Coverage Report

Created: 2026-12-01 06:57

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openvswitch/lib/dpif-netdev-perf.h
Line
Count
Source
1
/*
2
 * Copyright (c) 2017 Ericsson AB.
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at:
7
 *
8
 *     http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
17
#ifndef DPIF_NETDEV_PERF_H
18
#define DPIF_NETDEV_PERF_H 1
19
20
#include <stdbool.h>
21
#include <stddef.h>
22
#include <stdint.h>
23
#include <string.h>
24
#include <time.h>
25
#include <math.h>
26
27
#ifdef DPDK_NETDEV
28
#include <rte_config.h>
29
#include <rte_cycles.h>
30
#endif
31
32
#include "openvswitch/vlog.h"
33
#include "ovs-atomic.h"
34
#include "timeval.h"
35
#include "unixctl.h"
36
#include "util.h"
37
38
#ifdef  __cplusplus
39
extern "C" {
40
#endif
41
42
/* This module encapsulates data structures and functions to maintain basic PMD
43
 * performance metrics such as packet counters, execution cycles as well as
44
 * histograms and time series recording for more detailed PMD metrics.
45
 *
46
 * It provides a clean API for dpif-netdev to initialize, update and read and
47
 * reset these metrics.
48
 *
49
 * The basic set of PMD counters is implemented as atomic_uint64_t variables
50
 * to guarantee correct read also in 32-bit systems.
51
 *
52
 * The detailed PMD performance metrics are only supported on 64-bit systems
53
 * with atomic 64-bit read and store semantics for plain uint64_t counters.
54
 */
55
56
/* Set of counter types maintained in pmd_perf_stats. */
57
58
enum pmd_stat_type {
59
    PMD_STAT_PHWOL_HIT,     /* Packets that had a partial HWOL hit (phwol),
60
                             * without any alternative actions. */
61
    PMD_STAT_PHWOL_ACT_HIT, /* Packets that had a partial HWOL hit with
62
                               alternative actions. */
63
    PMD_STAT_SIMPLE_HIT,    /* Packets that had a simple match hit. */
64
    PMD_STAT_EXACT_HIT,     /* Packets that had an exact match (emc). */
65
    PMD_STAT_SMC_HIT,       /* Packets that had a sig match hit (SMC). */
66
    PMD_STAT_MASKED_HIT,    /* Packets that matched in the flow table. */
67
    PMD_STAT_MISS,          /* Packets that did not match and upcall was ok. */
68
    PMD_STAT_LOST,          /* Packets that did not match and upcall failed. */
69
                            /* The above statistics account for the total
70
                             * number of packet passes through the datapath
71
                             * pipeline and should not be overlapping with each
72
                             * other. */
73
    PMD_STAT_MASKED_LOOKUP, /* Number of subtable lookups for flow table
74
                               hits. Each MASKED_HIT hit will have >= 1
75
                               MASKED_LOOKUP(s). */
76
    PMD_STAT_RECV,          /* Packets entering the datapath pipeline from an
77
                             * interface. */
78
    PMD_STAT_RECIRC,        /* Packets reentering the datapath pipeline due to
79
                             * recirculation. */
80
    PMD_STAT_SENT_PKTS,     /* Packets that have been sent. */
81
    PMD_STAT_SENT_BATCHES,  /* Number of batches sent. */
82
    PMD_CYCLES_ITER_IDLE,   /* Cycles spent in idle iterations. */
83
    PMD_CYCLES_ITER_BUSY,   /* Cycles spent in busy iterations. */
84
    PMD_CYCLES_UPCALL,      /* Cycles spent processing upcalls. */
85
    PMD_SLEEP_ITER,         /* Iterations where a sleep has taken place. */
86
    PMD_CYCLES_SLEEP,       /* Total cycles slept to save power. */
87
    PMD_N_STATS
88
};
89
90
/* Array of PMD counters indexed by enum pmd_stat_type.
91
 * The n[] array contains the actual counter values since initialization
92
 * of the PMD. Counters are atomically updated from the PMD but are
93
 * read and cleared also from other processes. To clear the counters at
94
 * PMD run-time, the current counter values are copied over to the zero[]
95
 * array. To read counters we subtract zero[] value from n[]. */
96
97
struct pmd_counters {
98
    atomic_uint64_t n[PMD_N_STATS];     /* Value since _init(). */
99
    uint64_t zero[PMD_N_STATS];         /* Value at last _clear().  */
100
};
101
102
/* Data structure to collect statistical distribution of an integer measurement
103
 * type in form of a histogram. The wall[] array contains the inclusive
104
 * upper boundaries of the bins, while the bin[] array contains the actual
105
 * counters per bin. The histogram walls are typically set automatically
106
 * using the functions provided below.*/
107
108
0
#define NUM_BINS 32             /* Number of histogram bins. */
109
110
struct histogram {
111
    uint32_t wall[NUM_BINS];
112
    uint64_t bin[NUM_BINS];
113
};
114
115
/* Data structure to record details PMD execution metrics per iteration for
116
 * a history period of up to HISTORY_LEN iterations in circular buffer.
117
 * Also used to record up to HISTORY_LEN millisecond averages/totals of these
118
 * metrics.*/
119
120
struct iter_stats {
121
    uint64_t timestamp;         /* Iteration no. or millisecond. */
122
    uint64_t cycles;            /* Number of TSC cycles spent in it. or ms. */
123
    uint64_t busy_cycles;       /* Cycles spent in busy iterations or ms. */
124
    uint32_t iterations;        /* Iterations in ms. */
125
    uint32_t pkts;              /* Packets processed in iteration or ms. */
126
    uint32_t upcalls;           /* Number of upcalls in iteration or ms. */
127
    uint32_t upcall_cycles;     /* Cycles spent in upcalls in it. or ms. */
128
    uint32_t batches;           /* Number of rx batches in iteration or ms. */
129
    uint32_t max_vhost_qfill;   /* Maximum fill level in iteration or ms. */
130
};
131
132
0
#define HISTORY_LEN 1000        /* Length of recorded history
133
                                   (iterations and ms). */
134
#define DEF_HIST_SHOW 20        /* Default number of history samples to
135
                                   display. */
136
137
struct history {
138
    size_t idx;                 /* Slot to which next call to history_store()
139
                                   will write. */
140
    struct iter_stats sample[HISTORY_LEN];
141
};
142
143
/* Container for all performance metrics of a PMD within the struct
144
 * dp_netdev_pmd_thread. The metrics must be updated from within the PMD
145
 * thread but can be read from any thread. The basic PMD counters in
146
 * struct pmd_counters can be read without protection against concurrent
147
 * clearing. The other metrics may only be safely read with the clear_mutex
148
 * held to protect against concurrent clearing. */
149
150
struct pmd_perf_stats {
151
    /* Prevents interference between PMD polling and stats clearing. */
152
    struct ovs_mutex stats_mutex;
153
    /* Set by CLI thread to order clearing of PMD stats. */
154
    volatile bool clear;
155
    /* Prevents stats retrieval while clearing is in progress. */
156
    struct ovs_mutex clear_mutex;
157
    /* Start of the current performance measurement period. */
158
    uint64_t start_ms;
159
    /* Counter for PMD iterations. */
160
    uint64_t iteration_cnt;
161
    /* Start of the current iteration. */
162
    uint64_t start_tsc;
163
    /* Latest TSC time stamp taken in PMD. */
164
    uint64_t last_tsc;
165
    /* Used to space certain checks in time. */
166
    uint64_t next_check_tsc;
167
    /* If non-NULL, outermost cycle timer currently running in PMD. */
168
    struct cycle_timer *cur_timer;
169
    /* Set of PMD counters with their zero offsets. */
170
    struct pmd_counters counters;
171
    /* Statistics of the current iteration. */
172
    struct iter_stats current;
173
    /* Totals for the current millisecond. */
174
    struct iter_stats totals;
175
    /* Histograms for the PMD metrics. */
176
    struct histogram cycles;
177
    struct histogram pkts;
178
    struct histogram cycles_per_pkt;
179
    struct histogram upcalls;
180
    struct histogram cycles_per_upcall;
181
    struct histogram pkts_per_batch;
182
    struct histogram max_vhost_qfill;
183
    /* Iteration history buffer. */
184
    struct history iterations;
185
    /* Millisecond history buffer. */
186
    struct history milliseconds;
187
    /* Suspicious iteration log. */
188
    uint32_t log_susp_it;
189
    /* Start of iteration range to log. */
190
    uint32_t log_begin_it;
191
    /* End of iteration range to log. */
192
    uint32_t log_end_it;
193
    /* Reason for logging suspicious iteration. */
194
    char *log_reason;
195
};
196
197
#ifdef __linux__
198
static inline uint64_t
199
rdtsc_syscall(struct pmd_perf_stats *s)
200
0
{
201
0
    struct timespec val;
202
0
    uint64_t v;
203
0
204
0
    if (clock_gettime(CLOCK_MONOTONIC_RAW, &val) != 0) {
205
0
       return s->last_tsc;
206
0
    }
207
0
208
0
    v  = val.tv_sec * UINT64_C(1000000000) + val.tv_nsec;
209
0
    return s->last_tsc = v;
210
0
}
Unexecuted instantiation: dpif-netdev.c:rdtsc_syscall
Unexecuted instantiation: dpif-netdev-dpcls.c:rdtsc_syscall
Unexecuted instantiation: dpif-netdev-perf.c:rdtsc_syscall
211
#endif
212
213
/* Support for accurate timing of PMD execution on TSC clock cycle level.
214
 * These functions are intended to be invoked in the context of pmd threads. */
215
216
/* Read the TSC cycle register and cache it. Any function not requiring clock
217
 * cycle accuracy should read the cached value using cycles_counter_get() to
218
 * avoid the overhead of reading the TSC register. */
219
220
static inline uint64_t
221
cycles_counter_update(struct pmd_perf_stats *s)
222
0
{
223
#ifdef DPDK_NETDEV
224
    return s->last_tsc = rte_get_tsc_cycles();
225
#elif defined(__x86_64__)
226
    uint32_t h, l;
227
0
    asm volatile("rdtsc" : "=a" (l), "=d" (h));
228
229
0
    return s->last_tsc = ((uint64_t) h << 32) | l;
230
#elif defined(__aarch64__)
231
    asm volatile("mrs %0, cntvct_el0" : "=r" (s->last_tsc));
232
233
    return s->last_tsc;
234
#elif defined(__linux__)
235
    return rdtsc_syscall(s);
236
#else
237
    return s->last_tsc = 0;
238
#endif
239
0
}
Unexecuted instantiation: dpif-netdev.c:cycles_counter_update
Unexecuted instantiation: dpif-netdev-dpcls.c:cycles_counter_update
Unexecuted instantiation: dpif-netdev-perf.c:cycles_counter_update
240
241
static inline uint64_t
242
cycles_counter_get(struct pmd_perf_stats *s)
243
0
{
244
0
    return s->last_tsc;
245
0
}
Unexecuted instantiation: dpif-netdev.c:cycles_counter_get
Unexecuted instantiation: dpif-netdev-dpcls.c:cycles_counter_get
Unexecuted instantiation: dpif-netdev-perf.c:cycles_counter_get
246
247
void pmd_perf_estimate_tsc_frequency(void);
248
249
/* A nestable timer for measuring execution time in TSC cycles.
250
 *
251
 * Usage:
252
 * struct cycle_timer timer;
253
 *
254
 * cycle_timer_start(pmd, &timer);
255
 * <Timed execution>
256
 * uint64_t cycles = cycle_timer_stop(pmd, &timer);
257
 *
258
 * The caller must guarantee that a call to cycle_timer_start() is always
259
 * paired with a call to cycle_stimer_stop().
260
 *
261
 * Is is possible to have nested cycles timers within the timed code. The
262
 * execution time measured by the nested timers is excluded from the time
263
 * measured by the embracing timer.
264
 */
265
266
struct cycle_timer {
267
    uint64_t start;
268
    uint64_t suspended;
269
    struct cycle_timer *interrupted;
270
};
271
272
static inline void
273
cycle_timer_start(struct pmd_perf_stats *s,
274
                  struct cycle_timer *timer)
275
0
{
276
0
    struct cycle_timer *cur_timer = s->cur_timer;
277
0
    uint64_t now = cycles_counter_update(s);
278
279
0
    if (cur_timer) {
280
0
        cur_timer->suspended = now;
281
0
    }
282
0
    timer->interrupted = cur_timer;
283
0
    timer->start = now;
284
0
    timer->suspended = 0;
285
0
    s->cur_timer = timer;
286
0
}
Unexecuted instantiation: dpif-netdev.c:cycle_timer_start
Unexecuted instantiation: dpif-netdev-dpcls.c:cycle_timer_start
Unexecuted instantiation: dpif-netdev-perf.c:cycle_timer_start
287
288
static inline uint64_t
289
cycle_timer_stop(struct pmd_perf_stats *s,
290
                 struct cycle_timer *timer)
291
0
{
292
    /* Assert that this is the current cycle timer. */
293
0
    ovs_assert(s->cur_timer == timer);
294
0
    uint64_t now = cycles_counter_update(s);
295
0
    struct cycle_timer *intr_timer = timer->interrupted;
296
297
0
    if (intr_timer) {
298
        /* Adjust the start offset by the suspended cycles. */
299
0
        intr_timer->start += now - intr_timer->suspended;
300
0
    }
301
    /* Restore suspended timer, if any. */
302
0
    s->cur_timer = intr_timer;
303
0
    return now - timer->start;
304
0
}
Unexecuted instantiation: dpif-netdev.c:cycle_timer_stop
Unexecuted instantiation: dpif-netdev-dpcls.c:cycle_timer_stop
Unexecuted instantiation: dpif-netdev-perf.c:cycle_timer_stop
305
306
/* Functions to initialize and reset the PMD performance metrics. */
307
308
void pmd_perf_stats_init(struct pmd_perf_stats *s);
309
void pmd_perf_stats_clear(struct pmd_perf_stats *s);
310
void pmd_perf_stats_clear_lock(struct pmd_perf_stats *s);
311
312
/* Functions to read and update PMD counters. */
313
314
void pmd_perf_read_counters(struct pmd_perf_stats *s,
315
                            uint64_t stats[PMD_N_STATS]);
316
317
/* PMD performance counters are updated lock-less. For real PMDs
318
 * they are only updated from the PMD thread itself. In the case of the
319
 * NON-PMD they might be updated from multiple threads, but we can live
320
 * with losing a rare update as 100% accuracy is not required.
321
 * However, as counters are read for display from outside the PMD thread
322
 * with e.g. pmd-perf-show, we make sure that the 64-bit read and store
323
 * operations are atomic also on 32-bit systems so that readers cannot
324
 * not read garbage. On 64-bit systems this incurs no overhead. */
325
326
static inline void
327
pmd_perf_update_counter(struct pmd_perf_stats *s,
328
                        enum pmd_stat_type counter, int delta)
329
0
{
330
0
    uint64_t tmp;
331
0
    atomic_read_relaxed(&s->counters.n[counter], &tmp);
332
0
    tmp += delta;
333
0
    atomic_store_relaxed(&s->counters.n[counter], tmp);
334
0
}
Unexecuted instantiation: dpif-netdev.c:pmd_perf_update_counter
Unexecuted instantiation: dpif-netdev-dpcls.c:pmd_perf_update_counter
Unexecuted instantiation: dpif-netdev-perf.c:pmd_perf_update_counter
335
336
/* Functions to manipulate a sample history. */
337
338
static inline void
339
histogram_add_sample(struct histogram *hist, uint32_t val)
340
0
{
341
    /* TODO: Can do better with binary search? */
342
0
    for (int i = 0; i < NUM_BINS-1; i++) {
343
0
        if (val <= hist->wall[i]) {
344
0
            hist->bin[i]++;
345
0
            return;
346
0
        }
347
0
    }
348
0
    hist->bin[NUM_BINS-1]++;
349
0
}
Unexecuted instantiation: dpif-netdev.c:histogram_add_sample
Unexecuted instantiation: dpif-netdev-dpcls.c:histogram_add_sample
Unexecuted instantiation: dpif-netdev-perf.c:histogram_add_sample
350
351
uint64_t histogram_samples(const struct histogram *hist);
352
353
/* This function is used to advance the given history index by positive
354
 * offset in the circular history buffer. */
355
static inline uint32_t
356
history_add(uint32_t idx, uint32_t offset)
357
0
{
358
0
    return (idx + offset) % HISTORY_LEN;
359
0
}
Unexecuted instantiation: dpif-netdev.c:history_add
Unexecuted instantiation: dpif-netdev-dpcls.c:history_add
Unexecuted instantiation: dpif-netdev-perf.c:history_add
360
361
/* This function computes the difference between two indices into the
362
 * circular history buffer. The result is always positive in the range
363
 * 0 .. HISTORY_LEN-1 and specifies the number of steps to reach idx1
364
 * starting from idx2. It can also be used to retreat the history index
365
 * idx1 by idx2 steps. */
366
static inline uint32_t
367
history_sub(uint32_t idx1, uint32_t idx2)
368
0
{
369
0
    return (idx1 + HISTORY_LEN - idx2) % HISTORY_LEN;
370
0
}
Unexecuted instantiation: dpif-netdev.c:history_sub
Unexecuted instantiation: dpif-netdev-dpcls.c:history_sub
Unexecuted instantiation: dpif-netdev-perf.c:history_sub
371
372
static inline struct iter_stats *
373
history_current(struct history *h)
374
0
{
375
0
    return &h->sample[h->idx];
376
0
}
Unexecuted instantiation: dpif-netdev.c:history_current
Unexecuted instantiation: dpif-netdev-dpcls.c:history_current
Unexecuted instantiation: dpif-netdev-perf.c:history_current
377
378
static inline struct iter_stats *
379
history_next(struct history *h)
380
0
{
381
0
    size_t next_idx = history_add(h->idx, 1);
382
0
    struct iter_stats *next = &h->sample[next_idx];
383
384
0
    memset(next, 0, sizeof(*next));
385
0
    h->idx = next_idx;
386
0
    return next;
387
0
}
Unexecuted instantiation: dpif-netdev.c:history_next
Unexecuted instantiation: dpif-netdev-dpcls.c:history_next
Unexecuted instantiation: dpif-netdev-perf.c:history_next
388
389
static inline struct iter_stats *
390
history_store(struct history *h, struct iter_stats *is)
391
0
{
392
0
    if (is) {
393
0
        h->sample[h->idx] = *is;
394
0
    }
395
    /* Advance the history pointer */
396
0
    return history_next(h);
397
0
}
Unexecuted instantiation: dpif-netdev.c:history_store
Unexecuted instantiation: dpif-netdev-dpcls.c:history_store
Unexecuted instantiation: dpif-netdev-perf.c:history_store
398
399
/* Data and function related to logging of suspicious iterations. */
400
401
extern bool log_enabled;
402
extern bool log_extend;
403
extern uint32_t log_q_thr;
404
extern uint64_t iter_cycle_threshold;
405
406
void pmd_perf_set_log_susp_iteration(struct pmd_perf_stats *s, char *reason);
407
void pmd_perf_log_susp_iteration_neighborhood(struct pmd_perf_stats *s);
408
409
/* Functions recording PMD metrics per iteration. */
410
411
void
412
pmd_perf_start_iteration(struct pmd_perf_stats *s);
413
void
414
pmd_perf_end_iteration(struct pmd_perf_stats *s, int rx_packets,
415
                       int tx_packets, uint64_t sleep_cycles,
416
                       bool full_metrics);
417
418
/* Formatting the output of commands. */
419
420
struct pmd_perf_params {
421
    int command_type;
422
    bool histograms;
423
    size_t iter_hist_len;
424
    size_t ms_hist_len;
425
};
426
427
void pmd_perf_format_overall_stats(struct ds *str, struct pmd_perf_stats *s,
428
                                   double duration, bool format_iterations);
429
void pmd_perf_format_histograms(struct ds *str, struct pmd_perf_stats *s);
430
void pmd_perf_format_iteration_history(struct ds *str,
431
                                       struct pmd_perf_stats *s,
432
                                       int n_iter);
433
void pmd_perf_format_ms_history(struct ds *str, struct pmd_perf_stats *s,
434
                                int n_ms);
435
void pmd_perf_log_set_cmd(struct unixctl_conn *conn,
436
                          int argc, const char *argv[],
437
                          void *aux OVS_UNUSED);
438
439
#ifdef  __cplusplus
440
}
441
#endif
442
443
#endif /* DPIF_NETDEV_PERF_H */