]> git.proxmox.com Git - mirror_ovs.git/blame - lib/dpif-netdev.c
tests: Log commands being executed for async message control test.
[mirror_ovs.git] / lib / dpif-netdev.c
CommitLineData
72865317 1/*
4ea96698 2 * Copyright (c) 2009-2014, 2016-2018 Nicira, Inc.
72865317
BP
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#include <config.h>
db73f716 18#include "dpif-netdev.h"
f5ace7cd 19#include "dpif-netdev-private.h"
72865317 20
72865317
BP
21#include <ctype.h>
22#include <errno.h>
23#include <fcntl.h>
24#include <inttypes.h>
7f3adc00 25#include <net/if.h>
b2befd5b 26#include <sys/types.h>
7daedce4 27#include <netinet/in.h>
cdee00fd 28#include <stdint.h>
72865317
BP
29#include <stdlib.h>
30#include <string.h>
31#include <sys/ioctl.h>
7daedce4 32#include <sys/socket.h>
72865317 33#include <sys/stat.h>
72865317
BP
34#include <unistd.h>
35
9f861c91 36#include "bitmap.h"
59e6d833 37#include "cmap.h"
5cf3edb3 38#include "conntrack.h"
7daedce4 39#include "coverage.h"
4d4e68ed 40#include "ct-dpif.h"
72865317 41#include "csum.h"
e14deea0 42#include "dp-packet.h"
614c4892 43#include "dpif.h"
82a48ead 44#include "dpif-netdev-perf.h"
72865317 45#include "dpif-provider.h"
614c4892 46#include "dummy.h"
afae68b1 47#include "fat-rwlock.h"
72865317 48#include "flow.h"
762d146a 49#include "hmapx.h"
140dd699 50#include "id-pool.h"
4ea96698 51#include "ipf.h"
72865317 52#include "netdev.h"
b6cabb8f 53#include "netdev-offload.h"
79f36875 54#include "netdev-provider.h"
de281153 55#include "netdev-vport.h"
cdee00fd 56#include "netlink.h"
f094af7b 57#include "odp-execute.h"
72865317 58#include "odp-util.h"
25d436fb
BW
59#include "openvswitch/dynamic-string.h"
60#include "openvswitch/list.h"
61#include "openvswitch/match.h"
0d71302e 62#include "openvswitch/ofp-parse.h"
25d436fb 63#include "openvswitch/ofp-print.h"
64c96779 64#include "openvswitch/ofpbuf.h"
3eb67853 65#include "openvswitch/shash.h"
25d436fb 66#include "openvswitch/vlog.h"
5a034064 67#include "ovs-numa.h"
61e7deb1 68#include "ovs-rcu.h"
72865317 69#include "packets.h"
fd016ae3 70#include "openvswitch/poll-loop.h"
0de8783a 71#include "pvector.h"
26c6b6cd 72#include "random.h"
d33ed218 73#include "seq.h"
3eb67853 74#include "smap.h"
0cbfe35d 75#include "sset.h"
72865317 76#include "timeval.h"
53902038 77#include "tnl-neigh-cache.h"
7f9b8504 78#include "tnl-ports.h"
74cc3969 79#include "unixctl.h"
72865317 80#include "util.h"
241bad15 81#include "uuid.h"
7daedce4 82
d98e6007 83VLOG_DEFINE_THIS_MODULE(dpif_netdev);
72865317 84
5bf84282
NK
85/* Auto Load Balancing Defaults */
86#define ALB_ACCEPTABLE_IMPROVEMENT 25
87#define ALB_PMD_LOAD_THRESHOLD 95
88#define ALB_PMD_REBALANCE_POLL_INTERVAL 1 /* 1 Min */
89#define MIN_TO_MSEC 60000
90
8bb113da 91#define FLOW_DUMP_MAX_BATCH 50
adcf00ba 92/* Use per thread recirc_depth to prevent recirculation loop. */
3f9d3836 93#define MAX_RECIRC_DEPTH 6
adcf00ba 94DEFINE_STATIC_PER_THREAD_DATA(uint32_t, recirc_depth, 0)
e4cfed38 95
c71ea3c4
IM
96/* Use instant packet send by default. */
97#define DEFAULT_TX_FLUSH_INTERVAL 0
98
72865317 99/* Configuration parameters. */
72865317 100enum { MAX_FLOWS = 65536 }; /* Maximum number of flows in flow table. */
4b27db64
JR
101enum { MAX_METERS = 65536 }; /* Maximum number of meters. */
102enum { MAX_BANDS = 8 }; /* Maximum number of bands / meter. */
103enum { N_METER_LOCKS = 64 }; /* Maximum number of meters. */
72865317 104
8a4e3a85
BP
105/* Protects against changes to 'dp_netdevs'. */
106static struct ovs_mutex dp_netdev_mutex = OVS_MUTEX_INITIALIZER;
107
108/* Contains all 'struct dp_netdev's. */
109static struct shash dp_netdevs OVS_GUARDED_BY(dp_netdev_mutex)
110 = SHASH_INITIALIZER(&dp_netdevs);
111
623540e4 112static struct vlog_rate_limit upcall_rl = VLOG_RATE_LIMIT_INIT(600, 600);
6b31e073 113
5cf3edb3 114#define DP_NETDEV_CS_SUPPORTED_MASK (CS_NEW | CS_ESTABLISHED | CS_RELATED \
4cddb1f0
DB
115 | CS_INVALID | CS_REPLY_DIR | CS_TRACKED \
116 | CS_SRC_NAT | CS_DST_NAT)
5cf3edb3
DDP
117#define DP_NETDEV_CS_UNSUPPORTED_MASK (~(uint32_t)DP_NETDEV_CS_SUPPORTED_MASK)
118
2494ccd7 119static struct odp_support dp_netdev_support = {
f0fb825a 120 .max_vlan_headers = SIZE_MAX,
2494ccd7
JS
121 .max_mpls_depth = SIZE_MAX,
122 .recirc = true,
5cf3edb3
DDP
123 .ct_state = true,
124 .ct_zone = true,
125 .ct_mark = true,
126 .ct_label = true,
2575df07
JP
127 .ct_state_nat = true,
128 .ct_orig_tuple = true,
129 .ct_orig_tuple6 = true,
2494ccd7
JS
130};
131
60d8ccae
YW
132/* EMC cache and SMC cache compose the datapath flow cache (DFC)
133 *
134 * Exact match cache for frequently used flows
9bbf1c3d
DDP
135 *
136 * The cache uses a 32-bit hash of the packet (which can be the RSS hash) to
137 * search its entries for a miniflow that matches exactly the miniflow of the
0de8783a 138 * packet. It stores the 'dpcls_rule' (rule) that matches the miniflow.
9bbf1c3d
DDP
139 *
140 * A cache entry holds a reference to its 'dp_netdev_flow'.
141 *
142 * A miniflow with a given hash can be in one of EM_FLOW_HASH_SEGS different
143 * entries. The 32-bit hash is split into EM_FLOW_HASH_SEGS values (each of
144 * them is EM_FLOW_HASH_SHIFT bits wide and the remainder is thrown away). Each
145 * value is the index of a cache entry where the miniflow could be.
146 *
147 *
60d8ccae
YW
148 * Signature match cache (SMC)
149 *
150 * This cache stores a 16-bit signature for each flow without storing keys, and
151 * stores the corresponding 16-bit flow_table index to the 'dp_netdev_flow'.
152 * Each flow thus occupies 32bit which is much more memory efficient than EMC.
153 * SMC uses a set-associative design that each bucket contains
154 * SMC_ENTRY_PER_BUCKET number of entries.
155 * Since 16-bit flow_table index is used, if there are more than 2^16
156 * dp_netdev_flow, SMC will miss them that cannot be indexed by a 16-bit value.
157 *
158 *
9bbf1c3d
DDP
159 * Thread-safety
160 * =============
161 *
162 * Each pmd_thread has its own private exact match cache.
163 * If dp_netdev_input is not called from a pmd thread, a mutex is used.
164 */
165
fc82e877 166#define EM_FLOW_HASH_SHIFT 13
9bbf1c3d
DDP
167#define EM_FLOW_HASH_ENTRIES (1u << EM_FLOW_HASH_SHIFT)
168#define EM_FLOW_HASH_MASK (EM_FLOW_HASH_ENTRIES - 1)
169#define EM_FLOW_HASH_SEGS 2
170
60d8ccae
YW
171/* SMC uses a set-associative design. A bucket contains a set of entries that
172 * a flow item can occupy. For now, it uses one hash function rather than two
173 * as for the EMC design. */
174#define SMC_ENTRY_PER_BUCKET 4
175#define SMC_ENTRIES (1u << 20)
176#define SMC_BUCKET_CNT (SMC_ENTRIES / SMC_ENTRY_PER_BUCKET)
177#define SMC_MASK (SMC_BUCKET_CNT - 1)
178
4c30b246
CL
179/* Default EMC insert probability is 1 / DEFAULT_EM_FLOW_INSERT_INV_PROB */
180#define DEFAULT_EM_FLOW_INSERT_INV_PROB 100
181#define DEFAULT_EM_FLOW_INSERT_MIN (UINT32_MAX / \
182 DEFAULT_EM_FLOW_INSERT_INV_PROB)
183
9bbf1c3d 184struct emc_entry {
9bbf1c3d 185 struct dp_netdev_flow *flow;
0de8783a 186 struct netdev_flow_key key; /* key.hash used for emc hash value. */
9bbf1c3d
DDP
187};
188
189struct emc_cache {
190 struct emc_entry entries[EM_FLOW_HASH_ENTRIES];
67ad54cb 191 int sweep_idx; /* For emc_cache_slow_sweep(). */
9bbf1c3d
DDP
192};
193
60d8ccae
YW
194struct smc_bucket {
195 uint16_t sig[SMC_ENTRY_PER_BUCKET];
196 uint16_t flow_idx[SMC_ENTRY_PER_BUCKET];
197};
198
199/* Signature match cache, differentiate from EMC cache */
200struct smc_cache {
201 struct smc_bucket buckets[SMC_BUCKET_CNT];
202};
203
204struct dfc_cache {
205 struct emc_cache emc_cache;
206 struct smc_cache smc_cache;
207};
208
9bbf1c3d
DDP
209/* Iterate in the exact match cache through every entry that might contain a
210 * miniflow with hash 'HASH'. */
211#define EMC_FOR_EACH_POS_WITH_HASH(EMC, CURRENT_ENTRY, HASH) \
212 for (uint32_t i__ = 0, srch_hash__ = (HASH); \
213 (CURRENT_ENTRY) = &(EMC)->entries[srch_hash__ & EM_FLOW_HASH_MASK], \
214 i__ < EM_FLOW_HASH_SEGS; \
215 i__++, srch_hash__ >>= EM_FLOW_HASH_SHIFT)
0de8783a
JR
216\f
217/* Simple non-wildcarding single-priority classifier. */
218
05f9e707
IM
219/* Time in microseconds between successive optimizations of the dpcls
220 * subtable vector */
221#define DPCLS_OPTIMIZATION_INTERVAL 1000000LL
3453b4d6 222
05f9e707
IM
223/* Time in microseconds of the interval in which rxq processing cycles used
224 * in rxq to pmd assignments is measured and stored. */
225#define PMD_RXQ_INTERVAL_LEN 10000000LL
4809891b 226
c59e759f
KT
227/* Number of intervals for which cycles are stored
228 * and used during rxq to pmd assignment. */
229#define PMD_RXQ_INTERVAL_MAX 6
230
0de8783a 231struct dpcls {
3453b4d6
JS
232 struct cmap_node node; /* Within dp_netdev_pmd_thread.classifiers */
233 odp_port_t in_port;
0de8783a 234 struct cmap subtables_map;
da9cfca6 235 struct pvector subtables;
0de8783a 236};
9bbf1c3d 237
9b4f08cd
VDA
238/* Data structure to keep packet order till fastpath processing. */
239struct dp_packet_flow_map {
240 struct dp_packet *packet;
241 struct dp_netdev_flow *flow;
242 uint16_t tcp_flags;
243};
244
0de8783a
JR
245static void dpcls_init(struct dpcls *);
246static void dpcls_destroy(struct dpcls *);
3453b4d6 247static void dpcls_sort_subtable_vector(struct dpcls *);
0de8783a
JR
248static void dpcls_insert(struct dpcls *, struct dpcls_rule *,
249 const struct netdev_flow_key *mask);
250static void dpcls_remove(struct dpcls *, struct dpcls_rule *);
3453b4d6 251static bool dpcls_lookup(struct dpcls *cls,
60d8ccae 252 const struct netdev_flow_key *keys[],
3453b4d6
JS
253 struct dpcls_rule **rules, size_t cnt,
254 int *num_lookups_p);
92c7c870 255
4b27db64
JR
256/* Set of supported meter flags */
257#define DP_SUPPORTED_METER_FLAGS_MASK \
258 (OFPMF13_STATS | OFPMF13_PKTPS | OFPMF13_KBPS | OFPMF13_BURST)
259
260/* Set of supported meter band types */
261#define DP_SUPPORTED_METER_BAND_TYPES \
262 ( 1 << OFPMBT13_DROP )
263
264struct dp_meter_band {
265 struct ofputil_meter_band up; /* type, prec_level, pad, rate, burst_size */
266 uint32_t bucket; /* In 1/1000 packets (for PKTPS), or in bits (for KBPS) */
267 uint64_t packet_count;
268 uint64_t byte_count;
269};
270
271struct dp_meter {
272 uint16_t flags;
273 uint16_t n_bands;
274 uint32_t max_delta_t;
275 uint64_t used;
276 uint64_t packet_count;
277 uint64_t byte_count;
278 struct dp_meter_band bands[];
279};
280
5bf84282
NK
281struct pmd_auto_lb {
282 bool auto_lb_requested; /* Auto load balancing requested by user. */
283 bool is_enabled; /* Current status of Auto load balancing. */
284 uint64_t rebalance_intvl;
285 uint64_t rebalance_poll_timer;
286};
287
8a4e3a85
BP
288/* Datapath based on the network device interface from netdev.h.
289 *
290 *
291 * Thread-safety
292 * =============
293 *
294 * Some members, marked 'const', are immutable. Accessing other members
295 * requires synchronization, as noted in more detail below.
296 *
297 * Acquisition order is, from outermost to innermost:
298 *
299 * dp_netdev_mutex (global)
59e6d833 300 * port_mutex
d0cca6c3 301 * non_pmd_mutex
8a4e3a85 302 */
72865317 303struct dp_netdev {
8a4e3a85
BP
304 const struct dpif_class *const class;
305 const char *const name;
6b31e073 306 struct dpif *dpif;
6a8267c5
BP
307 struct ovs_refcount ref_cnt;
308 atomic_flag destroyed;
72865317 309
8a4e3a85
BP
310 /* Ports.
311 *
e9985d6a
DDP
312 * Any lookup into 'ports' or any access to the dp_netdev_ports found
313 * through 'ports' requires taking 'port_mutex'. */
59e6d833 314 struct ovs_mutex port_mutex;
e9985d6a 315 struct hmap ports;
d33ed218 316 struct seq *port_seq; /* Incremented whenever a port changes. */
6c3eee82 317
c71ea3c4
IM
318 /* The time that a packet can wait in output batch for sending. */
319 atomic_uint32_t tx_flush_interval;
320
4b27db64
JR
321 /* Meters. */
322 struct ovs_mutex meter_locks[N_METER_LOCKS];
323 struct dp_meter *meters[MAX_METERS]; /* Meter bands. */
4b27db64 324
65dcf3da
BB
325 /* Probability of EMC insertions is a factor of 'emc_insert_min'.*/
326 OVS_ALIGNED_VAR(CACHE_LINE_SIZE) atomic_uint32_t emc_insert_min;
79f36875
JS
327 /* Enable collection of PMD performance metrics. */
328 atomic_bool pmd_perf_metrics;
60d8ccae
YW
329 /* Enable the SMC cache from ovsdb config */
330 atomic_bool smc_enable_db;
65dcf3da 331
6b31e073
RW
332 /* Protects access to ofproto-dpif-upcall interface during revalidator
333 * thread synchronization. */
334 struct fat_rwlock upcall_rwlock;
623540e4
EJ
335 upcall_callback *upcall_cb; /* Callback function for executing upcalls. */
336 void *upcall_aux;
6b31e073 337
e4e74c3a
AW
338 /* Callback function for notifying the purging of dp flows (during
339 * reseting pmd deletion). */
340 dp_purge_callback *dp_purge_cb;
341 void *dp_purge_aux;
342
65f13b50
AW
343 /* Stores all 'struct dp_netdev_pmd_thread's. */
344 struct cmap poll_threads;
140dd699
IM
345 /* id pool for per thread static_tx_qid. */
346 struct id_pool *tx_qid_pool;
347 struct ovs_mutex tx_qid_pool_mutex;
e77c97b9
KT
348 /* Use measured cycles for rxq to pmd assignment. */
349 bool pmd_rxq_assign_cyc;
65f13b50
AW
350
351 /* Protects the access of the 'struct dp_netdev_pmd_thread'
352 * instance for non-pmd thread. */
353 struct ovs_mutex non_pmd_mutex;
354
355 /* Each pmd thread will store its pointer to
356 * 'struct dp_netdev_pmd_thread' in 'per_pmd_key'. */
357 ovsthread_key_t per_pmd_key;
f2eee189 358
a6a426d6
IM
359 struct seq *reconfigure_seq;
360 uint64_t last_reconfigure_seq;
361
a14b8947 362 /* Cpu mask for pin of pmd threads. */
f2eee189 363 char *pmd_cmask;
6e3c6fa4 364
a36de779 365 uint64_t last_tnl_conf_seq;
5cf3edb3 366
57593fd2 367 struct conntrack *conntrack;
5bf84282 368 struct pmd_auto_lb pmd_alb;
72865317
BP
369};
370
4b27db64
JR
371static void meter_lock(const struct dp_netdev *dp, uint32_t meter_id)
372 OVS_ACQUIRES(dp->meter_locks[meter_id % N_METER_LOCKS])
373{
374 ovs_mutex_lock(&dp->meter_locks[meter_id % N_METER_LOCKS]);
375}
376
377static void meter_unlock(const struct dp_netdev *dp, uint32_t meter_id)
378 OVS_RELEASES(dp->meter_locks[meter_id % N_METER_LOCKS])
379{
380 ovs_mutex_unlock(&dp->meter_locks[meter_id % N_METER_LOCKS]);
381}
382
383
8a4e3a85 384static struct dp_netdev_port *dp_netdev_lookup_port(const struct dp_netdev *dp,
e9985d6a
DDP
385 odp_port_t)
386 OVS_REQUIRES(dp->port_mutex);
ff073a71 387
c59e759f
KT
388enum rxq_cycles_counter_type {
389 RXQ_CYCLES_PROC_CURR, /* Cycles spent successfully polling and
390 processing packets during the current
391 interval. */
392 RXQ_CYCLES_PROC_HIST, /* Total cycles of all intervals that are used
393 during rxq to pmd assignment. */
394 RXQ_N_CYCLES
395};
396
02bb2824
YL
397enum {
398 DP_NETDEV_FLOW_OFFLOAD_OP_ADD,
399 DP_NETDEV_FLOW_OFFLOAD_OP_MOD,
400 DP_NETDEV_FLOW_OFFLOAD_OP_DEL,
401};
402
403struct dp_flow_offload_item {
404 struct dp_netdev_pmd_thread *pmd;
405 struct dp_netdev_flow *flow;
406 int op;
407 struct match match;
408 struct nlattr *actions;
409 size_t actions_len;
410
411 struct ovs_list node;
412};
413
414struct dp_flow_offload {
415 struct ovs_mutex mutex;
416 struct ovs_list list;
417 pthread_cond_t cond;
418};
419
420static struct dp_flow_offload dp_flow_offload = {
421 .mutex = OVS_MUTEX_INITIALIZER,
422 .list = OVS_LIST_INITIALIZER(&dp_flow_offload.list),
423};
424
425static struct ovsthread_once offload_thread_once
426 = OVSTHREAD_ONCE_INITIALIZER;
427
05f9e707 428#define XPS_TIMEOUT 500000LL /* In microseconds. */
324c8374 429
3eb67853
IM
430/* Contained by struct dp_netdev_port's 'rxqs' member. */
431struct dp_netdev_rxq {
947dc567
DDP
432 struct dp_netdev_port *port;
433 struct netdev_rxq *rx;
434 unsigned core_id; /* Core to which this queue should be
435 pinned. OVS_CORE_UNSPEC if the
436 queue doesn't need to be pinned to a
437 particular core. */
ee42dd70 438 unsigned intrvl_idx; /* Write index for 'cycles_intrvl'. */
47a45d86 439 struct dp_netdev_pmd_thread *pmd; /* pmd thread that polls this queue. */
79f36875 440 bool is_vhost; /* Is rxq of a vhost port. */
c59e759f
KT
441
442 /* Counters of cycles spent successfully polling and processing pkts. */
443 atomic_ullong cycles[RXQ_N_CYCLES];
444 /* We store PMD_RXQ_INTERVAL_MAX intervals of data for an rxq and then
445 sum them to yield the cycles used for an rxq. */
446 atomic_ullong cycles_intrvl[PMD_RXQ_INTERVAL_MAX];
3eb67853
IM
447};
448
72865317
BP
449/* A port in a netdev-based datapath. */
450struct dp_netdev_port {
35303d71 451 odp_port_t port_no;
ca62bb16
BB
452 bool dynamic_txqs; /* If true XPS will be used. */
453 bool need_reconfigure; /* True if we should reconfigure netdev. */
72865317 454 struct netdev *netdev;
e9985d6a 455 struct hmap_node node; /* Node in dp_netdev's 'ports'. */
4b609110 456 struct netdev_saved_flags *sf;
3eb67853 457 struct dp_netdev_rxq *rxqs;
85a4f238 458 unsigned n_rxq; /* Number of elements in 'rxqs' */
47a45d86 459 unsigned *txq_used; /* Number of threads that use each tx queue. */
324c8374 460 struct ovs_mutex txq_used_mutex;
2fbadeb6 461 bool emc_enabled; /* If true EMC will be used. */
0cbfe35d 462 char *type; /* Port type as requested by user. */
3eb67853 463 char *rxq_affinity_list; /* Requested affinity of rx queues. */
72865317
BP
464};
465
1c1e46ed
AW
466/* Contained by struct dp_netdev_flow's 'stats' member. */
467struct dp_netdev_flow_stats {
eb94da30
DDP
468 atomic_llong used; /* Last used time, in monotonic msecs. */
469 atomic_ullong packet_count; /* Number of packets matched. */
470 atomic_ullong byte_count; /* Number of bytes matched. */
471 atomic_uint16_t tcp_flags; /* Bitwise-OR of seen tcp_flags values. */
1c1e46ed
AW
472};
473
474/* A flow in 'dp_netdev_pmd_thread's 'flow_table'.
8a4e3a85
BP
475 *
476 *
477 * Thread-safety
478 * =============
479 *
480 * Except near the beginning or ending of its lifespan, rule 'rule' belongs to
1c1e46ed 481 * its pmd thread's classifier. The text below calls this classifier 'cls'.
8a4e3a85
BP
482 *
483 * Motivation
484 * ----------
485 *
486 * The thread safety rules described here for "struct dp_netdev_flow" are
487 * motivated by two goals:
488 *
489 * - Prevent threads that read members of "struct dp_netdev_flow" from
490 * reading bad data due to changes by some thread concurrently modifying
491 * those members.
492 *
493 * - Prevent two threads making changes to members of a given "struct
494 * dp_netdev_flow" from interfering with each other.
495 *
496 *
497 * Rules
498 * -----
499 *
ed79f89a
DDP
500 * A flow 'flow' may be accessed without a risk of being freed during an RCU
501 * grace period. Code that needs to hold onto a flow for a while
502 * should try incrementing 'flow->ref_cnt' with dp_netdev_flow_ref().
8a4e3a85
BP
503 *
504 * 'flow->ref_cnt' protects 'flow' from being freed. It doesn't protect the
ed79f89a
DDP
505 * flow from being deleted from 'cls' and it doesn't protect members of 'flow'
506 * from modification.
8a4e3a85
BP
507 *
508 * Some members, marked 'const', are immutable. Accessing other members
509 * requires synchronization, as noted in more detail below.
510 */
72865317 511struct dp_netdev_flow {
11e5cf1f 512 const struct flow flow; /* Unmasked flow that created this entry. */
8a4e3a85 513 /* Hash table index by unmasked flow. */
1c1e46ed
AW
514 const struct cmap_node node; /* In owning dp_netdev_pmd_thread's */
515 /* 'flow_table'. */
241bad15 516 const struct cmap_node mark_node; /* In owning flow_mark's mark_to_flow */
70e5ed6f 517 const ovs_u128 ufid; /* Unique flow identifier. */
241bad15 518 const ovs_u128 mega_ufid; /* Unique mega flow identifier. */
bd5131ba 519 const unsigned pmd_id; /* The 'core_id' of pmd thread owning this */
1c1e46ed 520 /* flow. */
72865317 521
ed79f89a
DDP
522 /* Number of references.
523 * The classifier owns one reference.
524 * Any thread trying to keep a rule from being freed should hold its own
525 * reference. */
526 struct ovs_refcount ref_cnt;
527
11e5cf1f 528 bool dead;
241bad15 529 uint32_t mark; /* Unique flow mark assigned to a flow */
11e5cf1f 530
1c1e46ed
AW
531 /* Statistics. */
532 struct dp_netdev_flow_stats stats;
8a4e3a85 533
45c626a3 534 /* Actions. */
61e7deb1 535 OVSRCU_TYPE(struct dp_netdev_actions *) actions;
0de8783a 536
11e5cf1f
DDP
537 /* While processing a group of input packets, the datapath uses the next
538 * member to store a pointer to the output batch for the flow. It is
539 * reset after the batch has been sent out (See dp_netdev_queue_batches(),
f7ce4811
PS
540 * packet_batch_per_flow_init() and packet_batch_per_flow_execute()). */
541 struct packet_batch_per_flow *batch;
11e5cf1f 542
0de8783a
JR
543 /* Packet classification. */
544 struct dpcls_rule cr; /* In owning dp_netdev's 'cls'. */
545 /* 'cr' must be the last member. */
72865317
BP
546};
547
ed79f89a 548static void dp_netdev_flow_unref(struct dp_netdev_flow *);
9bbf1c3d 549static bool dp_netdev_flow_ref(struct dp_netdev_flow *);
70e5ed6f 550static int dpif_netdev_flow_from_nlattrs(const struct nlattr *, uint32_t,
f0fb825a 551 struct flow *, bool);
8a4e3a85 552
a84cb64a
BP
553/* A set of datapath actions within a "struct dp_netdev_flow".
554 *
555 *
556 * Thread-safety
557 * =============
558 *
45c626a3 559 * A struct dp_netdev_actions 'actions' is protected with RCU. */
a84cb64a 560struct dp_netdev_actions {
a84cb64a
BP
561 /* These members are immutable: they do not change during the struct's
562 * lifetime. */
a84cb64a 563 unsigned int size; /* Size of 'actions', in bytes. */
9ff55ae2 564 struct nlattr actions[]; /* Sequence of OVS_ACTION_ATTR_* attributes. */
a84cb64a
BP
565};
566
567struct dp_netdev_actions *dp_netdev_actions_create(const struct nlattr *,
568 size_t);
61e7deb1
BP
569struct dp_netdev_actions *dp_netdev_flow_get_actions(
570 const struct dp_netdev_flow *);
571static void dp_netdev_actions_free(struct dp_netdev_actions *);
a84cb64a 572
947dc567 573struct polled_queue {
922b28d4 574 struct dp_netdev_rxq *rxq;
947dc567 575 odp_port_t port_no;
2fbadeb6 576 bool emc_enabled;
35c91567
DM
577 bool rxq_enabled;
578 uint64_t change_seq;
947dc567
DDP
579};
580
ae7ad0a1
IM
581/* Contained by struct dp_netdev_pmd_thread's 'poll_list' member. */
582struct rxq_poll {
947dc567
DDP
583 struct dp_netdev_rxq *rxq;
584 struct hmap_node node;
ae7ad0a1
IM
585};
586
57eebbb4
DDP
587/* Contained by struct dp_netdev_pmd_thread's 'send_port_cache',
588 * 'tnl_port_cache' or 'tx_ports'. */
d0cca6c3 589struct tx_port {
324c8374
IM
590 struct dp_netdev_port *port;
591 int qid;
592 long long last_used;
d0cca6c3 593 struct hmap_node node;
c71ea3c4 594 long long flush_time;
009e0033 595 struct dp_packet_batch output_pkts;
58ed6df0 596 struct dp_netdev_rxq *output_pkts_rxqs[NETDEV_MAX_BURST];
d0cca6c3
DDP
597};
598
b010be17
IM
599/* A set of properties for the current processing loop that is not directly
600 * associated with the pmd thread itself, but with the packets being
601 * processed or the short-term system configuration (for example, time).
602 * Contained by struct dp_netdev_pmd_thread's 'ctx' member. */
603struct dp_netdev_pmd_thread_ctx {
604 /* Latest measured time. See 'pmd_thread_ctx_time_update()'. */
605 long long now;
58ed6df0
IM
606 /* RX queue from which last packet was received. */
607 struct dp_netdev_rxq *last_rxq;
2fbadeb6
IM
608 /* EMC insertion probability context for the current processing cycle. */
609 uint32_t emc_insert_min;
d0cca6c3
DDP
610};
611
e4cfed38
PS
612/* PMD: Poll modes drivers. PMD accesses devices via polling to eliminate
613 * the performance overhead of interrupt processing. Therefore netdev can
614 * not implement rx-wait for these devices. dpif-netdev needs to poll
615 * these device to check for recv buffer. pmd-thread does polling for
1c1e46ed 616 * devices assigned to itself.
e4cfed38
PS
617 *
618 * DPDK used PMD for accessing NIC.
619 *
65f13b50
AW
620 * Note, instance with cpu core id NON_PMD_CORE_ID will be reserved for
621 * I/O of all non-pmd threads. There will be no actual thread created
622 * for the instance.
1c1e46ed 623 *
1859876c
BB
624 * Each struct has its own flow cache and classifier per managed ingress port.
625 * For packets received on ingress port, a look up is done on corresponding PMD
626 * thread's flow cache and in case of a miss, lookup is performed in the
627 * corresponding classifier of port. Packets are executed with the found
628 * actions in either case.
1c1e46ed 629 * */
65f13b50 630struct dp_netdev_pmd_thread {
d9d73f84
IM
631 struct dp_netdev *dp;
632 struct ovs_refcount ref_cnt; /* Every reference must be refcount'ed. */
633 struct cmap_node node; /* In 'dp->poll_threads'. */
634
65f13b50
AW
635 /* Per thread exact-match cache. Note, the instance for cpu core
636 * NON_PMD_CORE_ID can be accessed by multiple threads, and thusly
d0cca6c3
DDP
637 * need to be protected by 'non_pmd_mutex'. Every other instance
638 * will only be accessed by its own pmd thread. */
60d8ccae 639 OVS_ALIGNED_VAR(CACHE_LINE_SIZE) struct dfc_cache flow_cache;
1c1e46ed 640
3453b4d6 641 /* Flow-Table and classifiers
1c1e46ed
AW
642 *
643 * Writers of 'flow_table' must take the 'flow_mutex'. Corresponding
3453b4d6
JS
644 * changes to 'classifiers' must be made while still holding the
645 * 'flow_mutex'.
1c1e46ed
AW
646 */
647 struct ovs_mutex flow_mutex;
d9d73f84
IM
648 struct cmap flow_table OVS_GUARDED; /* Flow table. */
649
650 /* One classifier per in_port polled by the pmd */
651 struct cmap classifiers;
652 /* Periodically sort subtable vectors according to hit frequencies */
653 long long int next_optimization;
654 /* End of the next time interval for which processing cycles
655 are stored for each polled rxq. */
656 long long int rxq_next_cycle_store;
657
2a2c67b4
KT
658 /* Last interval timestamp. */
659 uint64_t intrvl_tsc_prev;
660 /* Last interval cycles. */
661 atomic_ullong intrvl_cycles;
662
b010be17
IM
663 /* Current context of the PMD thread. */
664 struct dp_netdev_pmd_thread_ctx ctx;
d9d73f84 665
d9d73f84
IM
666 struct seq *reload_seq;
667 uint64_t last_reload_seq;
ec61d470
IM
668
669 /* These are atomic variables used as a synchronization and configuration
670 * points for thread reload/exit.
671 *
672 * 'reload' atomic is the main one and it's used as a memory
673 * synchronization point for all other knobs and data.
674 *
675 * For a thread that requests PMD reload:
676 *
677 * * All changes that should be visible to the PMD thread must be made
678 * before setting the 'reload'. These changes could use any memory
679 * ordering model including 'relaxed'.
680 * * Setting the 'reload' atomic should occur in the same thread where
681 * all other PMD configuration options updated.
682 * * Setting the 'reload' atomic should be done with 'release' memory
683 * ordering model or stricter. This will guarantee that all previous
684 * changes (including non-atomic and 'relaxed') will be visible to
685 * the PMD thread.
686 * * To check that reload is done, thread should poll the 'reload' atomic
687 * to become 'false'. Polling should be done with 'acquire' memory
688 * ordering model or stricter. This ensures that PMD thread completed
689 * the reload process.
690 *
691 * For the PMD thread:
692 *
693 * * PMD thread should read 'reload' atomic with 'acquire' memory
694 * ordering model or stricter. This will guarantee that all changes
695 * made before setting the 'reload' in the requesting thread will be
696 * visible to the PMD thread.
697 * * All other configuration data could be read with any memory
698 * ordering model (including non-atomic and 'relaxed') but *only after*
699 * reading the 'reload' atomic set to 'true'.
700 * * When the PMD reload done, PMD should (optionally) set all the below
701 * knobs except the 'reload' to their default ('false') values and
702 * (mandatory), as the last step, set the 'reload' to 'false' using
703 * 'release' memory ordering model or stricter. This will inform the
704 * requesting thread that PMD has completed a reload cycle.
705 */
d9d73f84 706 atomic_bool reload; /* Do we need to reload ports? */
6d9fead1 707 atomic_bool wait_for_reload; /* Can we busy wait for the next reload? */
e2cafa86 708 atomic_bool reload_tx_qid; /* Do we need to reload static_tx_qid? */
299c8d61 709 atomic_bool exit; /* For terminating the pmd thread. */
ec61d470 710
d9d73f84
IM
711 pthread_t thread;
712 unsigned core_id; /* CPU core id of this pmd thread. */
713 int numa_id; /* numa node id of this pmd thread. */
714 bool isolated;
715
716 /* Queue id used by this pmd thread to send packets on all netdevs if
717 * XPS disabled for this netdev. All static_tx_qid's are unique and less
718 * than 'cmap_count(dp->poll_threads)'. */
719 uint32_t static_tx_qid;
720
c71ea3c4
IM
721 /* Number of filled output batches. */
722 int n_output_batches;
723
d9d73f84
IM
724 struct ovs_mutex port_mutex; /* Mutex for 'poll_list' and 'tx_ports'. */
725 /* List of rx queues to poll. */
726 struct hmap poll_list OVS_GUARDED;
727 /* Map of 'tx_port's used for transmission. Written by the main thread,
728 * read by the pmd thread. */
729 struct hmap tx_ports OVS_GUARDED;
730
731 /* These are thread-local copies of 'tx_ports'. One contains only tunnel
732 * ports (that support push_tunnel/pop_tunnel), the other contains ports
733 * with at least one txq (that support send). A port can be in both.
734 *
735 * There are two separate maps to make sure that we don't try to execute
736 * OUTPUT on a device which has 0 txqs or PUSH/POP on a non-tunnel device.
737 *
738 * The instances for cpu core NON_PMD_CORE_ID can be accessed by multiple
739 * threads, and thusly need to be protected by 'non_pmd_mutex'. Every
740 * other instance will only be accessed by its own pmd thread. */
741 struct hmap tnl_port_cache;
742 struct hmap send_port_cache;
743
82a48ead
JS
744 /* Keep track of detailed PMD performance statistics. */
745 struct pmd_perf_stats perf_stats;
d9d73f84 746
5bf84282
NK
747 /* Stats from previous iteration used by automatic pmd
748 * load balance logic. */
749 uint64_t prev_stats[PMD_N_STATS];
750 atomic_count pmd_overloaded;
751
d9d73f84
IM
752 /* Set to true if the pmd thread needs to be reloaded. */
753 bool need_reload;
6c3eee82
BP
754};
755
72865317
BP
756/* Interface to netdev-based datapath. */
757struct dpif_netdev {
758 struct dpif dpif;
759 struct dp_netdev *dp;
d33ed218 760 uint64_t last_port_seq;
72865317
BP
761};
762
8a4e3a85 763static int get_port_by_number(struct dp_netdev *dp, odp_port_t port_no,
e9985d6a
DDP
764 struct dp_netdev_port **portp)
765 OVS_REQUIRES(dp->port_mutex);
8a4e3a85 766static int get_port_by_name(struct dp_netdev *dp, const char *devname,
e9985d6a
DDP
767 struct dp_netdev_port **portp)
768 OVS_REQUIRES(dp->port_mutex);
8a4e3a85
BP
769static void dp_netdev_free(struct dp_netdev *)
770 OVS_REQUIRES(dp_netdev_mutex);
8a4e3a85
BP
771static int do_add_port(struct dp_netdev *dp, const char *devname,
772 const char *type, odp_port_t port_no)
59e6d833 773 OVS_REQUIRES(dp->port_mutex);
c40b890f 774static void do_del_port(struct dp_netdev *dp, struct dp_netdev_port *)
59e6d833 775 OVS_REQUIRES(dp->port_mutex);
614c4892
BP
776static int dpif_netdev_open(const struct dpif_class *, const char *name,
777 bool create, struct dpif **);
65f13b50 778static void dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
1895cc8d 779 struct dp_packet_batch *,
7d7ded7a
DB
780 bool should_steal,
781 const struct flow *flow,
4edb9ae9 782 const struct nlattr *actions,
b010be17 783 size_t actions_len);
65f13b50 784static void dp_netdev_input(struct dp_netdev_pmd_thread *,
1895cc8d 785 struct dp_packet_batch *, odp_port_t port_no);
a90ed026 786static void dp_netdev_recirculate(struct dp_netdev_pmd_thread *,
1895cc8d 787 struct dp_packet_batch *);
41ccaa24 788
6b31e073 789static void dp_netdev_disable_upcall(struct dp_netdev *);
ae7ad0a1 790static void dp_netdev_pmd_reload_done(struct dp_netdev_pmd_thread *pmd);
65f13b50 791static void dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd,
00873463
DDP
792 struct dp_netdev *dp, unsigned core_id,
793 int numa_id);
1c1e46ed 794static void dp_netdev_destroy_pmd(struct dp_netdev_pmd_thread *pmd);
e9985d6a
DDP
795static void dp_netdev_set_nonpmd(struct dp_netdev *dp)
796 OVS_REQUIRES(dp->port_mutex);
797
e32971b8 798static void *pmd_thread_main(void *);
b19befae 799static struct dp_netdev_pmd_thread *dp_netdev_get_pmd(struct dp_netdev *dp,
bd5131ba 800 unsigned core_id);
1c1e46ed
AW
801static struct dp_netdev_pmd_thread *
802dp_netdev_pmd_get_next(struct dp_netdev *dp, struct cmap_position *pos);
140dd699
IM
803static void dp_netdev_del_pmd(struct dp_netdev *dp,
804 struct dp_netdev_pmd_thread *pmd);
e32971b8 805static void dp_netdev_destroy_all_pmds(struct dp_netdev *dp, bool non_pmd);
d0cca6c3 806static void dp_netdev_pmd_clear_ports(struct dp_netdev_pmd_thread *pmd);
d0cca6c3 807static void dp_netdev_add_port_tx_to_pmd(struct dp_netdev_pmd_thread *pmd,
e32971b8
DDP
808 struct dp_netdev_port *port)
809 OVS_REQUIRES(pmd->port_mutex);
810static void dp_netdev_del_port_tx_from_pmd(struct dp_netdev_pmd_thread *pmd,
811 struct tx_port *tx)
812 OVS_REQUIRES(pmd->port_mutex);
d0cca6c3 813static void dp_netdev_add_rxq_to_pmd(struct dp_netdev_pmd_thread *pmd,
947dc567
DDP
814 struct dp_netdev_rxq *rxq)
815 OVS_REQUIRES(pmd->port_mutex);
e32971b8
DDP
816static void dp_netdev_del_rxq_from_pmd(struct dp_netdev_pmd_thread *pmd,
817 struct rxq_poll *poll)
818 OVS_REQUIRES(pmd->port_mutex);
c71ea3c4
IM
819static int
820dp_netdev_pmd_flush_output_packets(struct dp_netdev_pmd_thread *pmd,
821 bool force);
009e0033 822
e32971b8 823static void reconfigure_datapath(struct dp_netdev *dp)
3eb67853 824 OVS_REQUIRES(dp->port_mutex);
1c1e46ed
AW
825static bool dp_netdev_pmd_try_ref(struct dp_netdev_pmd_thread *pmd);
826static void dp_netdev_pmd_unref(struct dp_netdev_pmd_thread *pmd);
827static void dp_netdev_pmd_flow_flush(struct dp_netdev_pmd_thread *pmd);
d0cca6c3
DDP
828static void pmd_load_cached_ports(struct dp_netdev_pmd_thread *pmd)
829 OVS_REQUIRES(pmd->port_mutex);
3453b4d6 830static inline void
4809891b
KT
831dp_netdev_pmd_try_optimize(struct dp_netdev_pmd_thread *pmd,
832 struct polled_queue *poll_list, int poll_cnt);
833static void
834dp_netdev_rxq_set_cycles(struct dp_netdev_rxq *rx,
835 enum rxq_cycles_counter_type type,
836 unsigned long long cycles);
837static uint64_t
838dp_netdev_rxq_get_cycles(struct dp_netdev_rxq *rx,
839 enum rxq_cycles_counter_type type);
840static void
841dp_netdev_rxq_set_intrvl_cycles(struct dp_netdev_rxq *rx,
842 unsigned long long cycles);
655856ef
KT
843static uint64_t
844dp_netdev_rxq_get_intrvl_cycles(struct dp_netdev_rxq *rx, unsigned idx);
324c8374
IM
845static void
846dpif_netdev_xps_revalidate_pmd(const struct dp_netdev_pmd_thread *pmd,
b010be17 847 bool purge);
324c8374 848static int dpif_netdev_xps_get_tx_qid(const struct dp_netdev_pmd_thread *pmd,
b010be17 849 struct tx_port *tx);
324c8374 850
67ad54cb 851static inline bool emc_entry_alive(struct emc_entry *ce);
9bbf1c3d 852static void emc_clear_entry(struct emc_entry *ce);
60d8ccae 853static void smc_clear_entry(struct smc_bucket *b, int idx);
9bbf1c3d 854
cd995c73 855static void dp_netdev_request_reconfigure(struct dp_netdev *dp);
79f36875
JS
856static inline bool
857pmd_perf_metrics_enabled(const struct dp_netdev_pmd_thread *pmd);
02bb2824
YL
858static void queue_netdev_flow_del(struct dp_netdev_pmd_thread *pmd,
859 struct dp_netdev_flow *flow);
cd995c73 860
9bbf1c3d
DDP
861static void
862emc_cache_init(struct emc_cache *flow_cache)
863{
864 int i;
865
67ad54cb 866 flow_cache->sweep_idx = 0;
9bbf1c3d
DDP
867 for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
868 flow_cache->entries[i].flow = NULL;
0de8783a 869 flow_cache->entries[i].key.hash = 0;
09b0fa9c 870 flow_cache->entries[i].key.len = sizeof(struct miniflow);
5fcff47b 871 flowmap_init(&flow_cache->entries[i].key.mf.map);
9bbf1c3d
DDP
872 }
873}
874
60d8ccae
YW
875static void
876smc_cache_init(struct smc_cache *smc_cache)
877{
878 int i, j;
879 for (i = 0; i < SMC_BUCKET_CNT; i++) {
880 for (j = 0; j < SMC_ENTRY_PER_BUCKET; j++) {
881 smc_cache->buckets[i].flow_idx[j] = UINT16_MAX;
882 }
883 }
884}
885
886static void
887dfc_cache_init(struct dfc_cache *flow_cache)
888{
889 emc_cache_init(&flow_cache->emc_cache);
890 smc_cache_init(&flow_cache->smc_cache);
891}
892
9bbf1c3d
DDP
893static void
894emc_cache_uninit(struct emc_cache *flow_cache)
895{
896 int i;
897
898 for (i = 0; i < ARRAY_SIZE(flow_cache->entries); i++) {
899 emc_clear_entry(&flow_cache->entries[i]);
900 }
901}
902
60d8ccae
YW
903static void
904smc_cache_uninit(struct smc_cache *smc)
905{
906 int i, j;
907
908 for (i = 0; i < SMC_BUCKET_CNT; i++) {
909 for (j = 0; j < SMC_ENTRY_PER_BUCKET; j++) {
910 smc_clear_entry(&(smc->buckets[i]), j);
911 }
912 }
913}
914
915static void
916dfc_cache_uninit(struct dfc_cache *flow_cache)
917{
918 smc_cache_uninit(&flow_cache->smc_cache);
919 emc_cache_uninit(&flow_cache->emc_cache);
920}
921
67ad54cb
AW
922/* Check and clear dead flow references slowly (one entry at each
923 * invocation). */
924static void
925emc_cache_slow_sweep(struct emc_cache *flow_cache)
926{
927 struct emc_entry *entry = &flow_cache->entries[flow_cache->sweep_idx];
928
929 if (!emc_entry_alive(entry)) {
930 emc_clear_entry(entry);
931 }
932 flow_cache->sweep_idx = (flow_cache->sweep_idx + 1) & EM_FLOW_HASH_MASK;
933}
934
b010be17
IM
935/* Updates the time in PMD threads context and should be called in three cases:
936 *
937 * 1. PMD structure initialization:
938 * - dp_netdev_configure_pmd()
939 *
940 * 2. Before processing of the new packet batch:
941 * - dpif_netdev_execute()
009e0033 942 * - dp_netdev_process_rxq_port()
b010be17
IM
943 *
944 * 3. At least once per polling iteration in main polling threads if no
945 * packets received on current iteration:
946 * - dpif_netdev_run()
947 * - pmd_thread_main()
948 *
949 * 'pmd->ctx.now' should be used without update in all other cases if possible.
950 */
951static inline void
952pmd_thread_ctx_time_update(struct dp_netdev_pmd_thread *pmd)
953{
05f9e707 954 pmd->ctx.now = time_usec();
b010be17
IM
955}
956
c4ea7529
BP
957/* Returns true if 'dpif' is a netdev or dummy dpif, false otherwise. */
958bool
959dpif_is_netdev(const struct dpif *dpif)
960{
961 return dpif->dpif_class->open == dpif_netdev_open;
962}
963
72865317
BP
964static struct dpif_netdev *
965dpif_netdev_cast(const struct dpif *dpif)
966{
c4ea7529 967 ovs_assert(dpif_is_netdev(dpif));
72865317
BP
968 return CONTAINER_OF(dpif, struct dpif_netdev, dpif);
969}
970
971static struct dp_netdev *
972get_dp_netdev(const struct dpif *dpif)
973{
974 return dpif_netdev_cast(dpif)->dp;
975}
6553d06b
DDP
976\f
977enum pmd_info_type {
ce179f11
IM
978 PMD_INFO_SHOW_STATS, /* Show how cpu cycles are spent. */
979 PMD_INFO_CLEAR_STATS, /* Set the cycles count to 0. */
79f36875
JS
980 PMD_INFO_SHOW_RXQ, /* Show poll lists of pmd threads. */
981 PMD_INFO_PERF_SHOW, /* Show pmd performance details. */
6553d06b
DDP
982};
983
984static void
82a48ead 985format_pmd_thread(struct ds *reply, struct dp_netdev_pmd_thread *pmd)
6553d06b 986{
6553d06b
DDP
987 ds_put_cstr(reply, (pmd->core_id == NON_PMD_CORE_ID)
988 ? "main thread" : "pmd thread");
6553d06b
DDP
989 if (pmd->numa_id != OVS_NUMA_UNSPEC) {
990 ds_put_format(reply, " numa_id %d", pmd->numa_id);
991 }
d5c199ea 992 if (pmd->core_id != OVS_CORE_UNSPEC && pmd->core_id != NON_PMD_CORE_ID) {
bd5131ba 993 ds_put_format(reply, " core_id %u", pmd->core_id);
6553d06b
DDP
994 }
995 ds_put_cstr(reply, ":\n");
82a48ead
JS
996}
997
998static void
999pmd_info_show_stats(struct ds *reply,
1000 struct dp_netdev_pmd_thread *pmd)
1001{
1002 uint64_t stats[PMD_N_STATS];
1003 uint64_t total_cycles, total_packets;
1004 double passes_per_pkt = 0;
1005 double lookups_per_hit = 0;
1006 double packets_per_batch = 0;
1007
1008 pmd_perf_read_counters(&pmd->perf_stats, stats);
1009 total_cycles = stats[PMD_CYCLES_ITER_IDLE]
1010 + stats[PMD_CYCLES_ITER_BUSY];
1011 total_packets = stats[PMD_STAT_RECV];
1012
1013 format_pmd_thread(reply, pmd);
6553d06b 1014
82a48ead
JS
1015 if (total_packets > 0) {
1016 passes_per_pkt = (total_packets + stats[PMD_STAT_RECIRC])
1017 / (double) total_packets;
cc4891f3 1018 }
82a48ead
JS
1019 if (stats[PMD_STAT_MASKED_HIT] > 0) {
1020 lookups_per_hit = stats[PMD_STAT_MASKED_LOOKUP]
1021 / (double) stats[PMD_STAT_MASKED_HIT];
1022 }
1023 if (stats[PMD_STAT_SENT_BATCHES] > 0) {
1024 packets_per_batch = stats[PMD_STAT_SENT_PKTS]
1025 / (double) stats[PMD_STAT_SENT_BATCHES];
cc4891f3
IM
1026 }
1027
6553d06b 1028 ds_put_format(reply,
5a0e4aec
BP
1029 " packets received: %"PRIu64"\n"
1030 " packet recirculations: %"PRIu64"\n"
1031 " avg. datapath passes per packet: %.02f\n"
1032 " emc hits: %"PRIu64"\n"
60d8ccae 1033 " smc hits: %"PRIu64"\n"
5a0e4aec
BP
1034 " megaflow hits: %"PRIu64"\n"
1035 " avg. subtable lookups per megaflow hit: %.02f\n"
1036 " miss with success upcall: %"PRIu64"\n"
1037 " miss with failed upcall: %"PRIu64"\n"
1038 " avg. packets per output batch: %.02f\n",
82a48ead
JS
1039 total_packets, stats[PMD_STAT_RECIRC],
1040 passes_per_pkt, stats[PMD_STAT_EXACT_HIT],
60d8ccae 1041 stats[PMD_STAT_SMC_HIT],
82a48ead
JS
1042 stats[PMD_STAT_MASKED_HIT], lookups_per_hit,
1043 stats[PMD_STAT_MISS], stats[PMD_STAT_LOST],
cc4891f3 1044 packets_per_batch);
6553d06b
DDP
1045
1046 if (total_cycles == 0) {
1047 return;
1048 }
1049
1050 ds_put_format(reply,
5a0e4aec
BP
1051 " idle cycles: %"PRIu64" (%.02f%%)\n"
1052 " processing cycles: %"PRIu64" (%.02f%%)\n",
82a48ead
JS
1053 stats[PMD_CYCLES_ITER_IDLE],
1054 stats[PMD_CYCLES_ITER_IDLE] / (double) total_cycles * 100,
1055 stats[PMD_CYCLES_ITER_BUSY],
1056 stats[PMD_CYCLES_ITER_BUSY] / (double) total_cycles * 100);
6553d06b
DDP
1057
1058 if (total_packets == 0) {
1059 return;
1060 }
1061
1062 ds_put_format(reply,
5a0e4aec 1063 " avg cycles per packet: %.02f (%"PRIu64"/%"PRIu64")\n",
82a48ead 1064 total_cycles / (double) total_packets,
6553d06b
DDP
1065 total_cycles, total_packets);
1066
1067 ds_put_format(reply,
5a0e4aec 1068 " avg processing cycles per packet: "
82a48ead
JS
1069 "%.02f (%"PRIu64"/%"PRIu64")\n",
1070 stats[PMD_CYCLES_ITER_BUSY] / (double) total_packets,
1071 stats[PMD_CYCLES_ITER_BUSY], total_packets);
6553d06b
DDP
1072}
1073
79f36875
JS
1074static void
1075pmd_info_show_perf(struct ds *reply,
1076 struct dp_netdev_pmd_thread *pmd,
1077 struct pmd_perf_params *par)
1078{
1079 if (pmd->core_id != NON_PMD_CORE_ID) {
1080 char *time_str =
1081 xastrftime_msec("%H:%M:%S.###", time_wall_msec(), true);
1082 long long now = time_msec();
1083 double duration = (now - pmd->perf_stats.start_ms) / 1000.0;
1084
1085 ds_put_cstr(reply, "\n");
1086 ds_put_format(reply, "Time: %s\n", time_str);
1087 ds_put_format(reply, "Measurement duration: %.3f s\n", duration);
1088 ds_put_cstr(reply, "\n");
1089 format_pmd_thread(reply, pmd);
1090 ds_put_cstr(reply, "\n");
1091 pmd_perf_format_overall_stats(reply, &pmd->perf_stats, duration);
1092 if (pmd_perf_metrics_enabled(pmd)) {
1093 /* Prevent parallel clearing of perf metrics. */
1094 ovs_mutex_lock(&pmd->perf_stats.clear_mutex);
1095 if (par->histograms) {
1096 ds_put_cstr(reply, "\n");
1097 pmd_perf_format_histograms(reply, &pmd->perf_stats);
1098 }
1099 if (par->iter_hist_len > 0) {
1100 ds_put_cstr(reply, "\n");
1101 pmd_perf_format_iteration_history(reply, &pmd->perf_stats,
1102 par->iter_hist_len);
1103 }
1104 if (par->ms_hist_len > 0) {
1105 ds_put_cstr(reply, "\n");
1106 pmd_perf_format_ms_history(reply, &pmd->perf_stats,
1107 par->ms_hist_len);
1108 }
1109 ovs_mutex_unlock(&pmd->perf_stats.clear_mutex);
1110 }
1111 free(time_str);
1112 }
1113}
1114
947dc567
DDP
1115static int
1116compare_poll_list(const void *a_, const void *b_)
1117{
1118 const struct rxq_poll *a = a_;
1119 const struct rxq_poll *b = b_;
1120
1121 const char *namea = netdev_rxq_get_name(a->rxq->rx);
1122 const char *nameb = netdev_rxq_get_name(b->rxq->rx);
1123
1124 int cmp = strcmp(namea, nameb);
1125 if (!cmp) {
1126 return netdev_rxq_get_queue_id(a->rxq->rx)
1127 - netdev_rxq_get_queue_id(b->rxq->rx);
1128 } else {
1129 return cmp;
1130 }
1131}
1132
1133static void
1134sorted_poll_list(struct dp_netdev_pmd_thread *pmd, struct rxq_poll **list,
1135 size_t *n)
216abd28 1136 OVS_REQUIRES(pmd->port_mutex)
947dc567
DDP
1137{
1138 struct rxq_poll *ret, *poll;
1139 size_t i;
1140
1141 *n = hmap_count(&pmd->poll_list);
1142 if (!*n) {
1143 ret = NULL;
1144 } else {
1145 ret = xcalloc(*n, sizeof *ret);
1146 i = 0;
1147 HMAP_FOR_EACH (poll, node, &pmd->poll_list) {
1148 ret[i] = *poll;
1149 i++;
1150 }
1151 ovs_assert(i == *n);
1cc1b5f6 1152 qsort(ret, *n, sizeof *ret, compare_poll_list);
947dc567
DDP
1153 }
1154
947dc567
DDP
1155 *list = ret;
1156}
1157
ce179f11
IM
1158static void
1159pmd_info_show_rxq(struct ds *reply, struct dp_netdev_pmd_thread *pmd)
1160{
1161 if (pmd->core_id != NON_PMD_CORE_ID) {
947dc567 1162 struct rxq_poll *list;
2a2c67b4
KT
1163 size_t n_rxq;
1164 uint64_t total_cycles = 0;
ce179f11 1165
3eb67853 1166 ds_put_format(reply,
5a0e4aec 1167 "pmd thread numa_id %d core_id %u:\n isolated : %s\n",
3eb67853
IM
1168 pmd->numa_id, pmd->core_id, (pmd->isolated)
1169 ? "true" : "false");
ce179f11 1170
d0cca6c3 1171 ovs_mutex_lock(&pmd->port_mutex);
2a2c67b4 1172 sorted_poll_list(pmd, &list, &n_rxq);
ce179f11 1173
2a2c67b4
KT
1174 /* Get the total pmd cycles for an interval. */
1175 atomic_read_relaxed(&pmd->intrvl_cycles, &total_cycles);
1176 /* Estimate the cycles to cover all intervals. */
1177 total_cycles *= PMD_RXQ_INTERVAL_MAX;
1178
1179 for (int i = 0; i < n_rxq; i++) {
1180 struct dp_netdev_rxq *rxq = list[i].rxq;
1181 const char *name = netdev_rxq_get_name(rxq->rx);
1182 uint64_t proc_cycles = 0;
1183
1184 for (int j = 0; j < PMD_RXQ_INTERVAL_MAX; j++) {
1185 proc_cycles += dp_netdev_rxq_get_intrvl_cycles(rxq, j);
ce179f11 1186 }
5a0e4aec 1187 ds_put_format(reply, " port: %-16s queue-id: %2d", name,
947dc567 1188 netdev_rxq_get_queue_id(list[i].rxq->rx));
35c91567
DM
1189 ds_put_format(reply, " %s", netdev_rxq_enabled(list[i].rxq->rx)
1190 ? "(enabled) " : "(disabled)");
5a0e4aec 1191 ds_put_format(reply, " pmd usage: ");
2a2c67b4
KT
1192 if (total_cycles) {
1193 ds_put_format(reply, "%2"PRIu64"",
1194 proc_cycles * 100 / total_cycles);
1195 ds_put_cstr(reply, " %");
1196 } else {
1197 ds_put_format(reply, "%s", "NOT AVAIL");
1198 }
1199 ds_put_cstr(reply, "\n");
ce179f11 1200 }
d0cca6c3 1201 ovs_mutex_unlock(&pmd->port_mutex);
947dc567 1202 free(list);
ce179f11
IM
1203 }
1204}
1205
34d8e04b
EC
1206static int
1207compare_poll_thread_list(const void *a_, const void *b_)
1208{
1209 const struct dp_netdev_pmd_thread *a, *b;
1210
1211 a = *(struct dp_netdev_pmd_thread **)a_;
1212 b = *(struct dp_netdev_pmd_thread **)b_;
1213
1214 if (a->core_id < b->core_id) {
1215 return -1;
1216 }
1217 if (a->core_id > b->core_id) {
1218 return 1;
1219 }
1220 return 0;
1221}
1222
1223/* Create a sorted list of pmd's from the dp->poll_threads cmap. We can use
1224 * this list, as long as we do not go to quiescent state. */
1225static void
1226sorted_poll_thread_list(struct dp_netdev *dp,
1227 struct dp_netdev_pmd_thread ***list,
1228 size_t *n)
1229{
1230 struct dp_netdev_pmd_thread *pmd;
1231 struct dp_netdev_pmd_thread **pmd_list;
1232 size_t k = 0, n_pmds;
1233
1234 n_pmds = cmap_count(&dp->poll_threads);
1235 pmd_list = xcalloc(n_pmds, sizeof *pmd_list);
1236
1237 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
1238 if (k >= n_pmds) {
1239 break;
1240 }
1241 pmd_list[k++] = pmd;
1242 }
1243
1244 qsort(pmd_list, k, sizeof *pmd_list, compare_poll_thread_list);
1245
1246 *list = pmd_list;
1247 *n = k;
1248}
1249
cd995c73
KT
1250static void
1251dpif_netdev_pmd_rebalance(struct unixctl_conn *conn, int argc,
1252 const char *argv[], void *aux OVS_UNUSED)
1253{
1254 struct ds reply = DS_EMPTY_INITIALIZER;
1255 struct dp_netdev *dp = NULL;
1256
1257 ovs_mutex_lock(&dp_netdev_mutex);
1258
1259 if (argc == 2) {
1260 dp = shash_find_data(&dp_netdevs, argv[1]);
1261 } else if (shash_count(&dp_netdevs) == 1) {
1262 /* There's only one datapath */
1263 dp = shash_first(&dp_netdevs)->data;
1264 }
1265
1266 if (!dp) {
1267 ovs_mutex_unlock(&dp_netdev_mutex);
1268 unixctl_command_reply_error(conn,
1269 "please specify an existing datapath");
1270 return;
1271 }
1272
1273 dp_netdev_request_reconfigure(dp);
1274 ovs_mutex_unlock(&dp_netdev_mutex);
1275 ds_put_cstr(&reply, "pmd rxq rebalance requested.\n");
1276 unixctl_command_reply(conn, ds_cstr(&reply));
1277 ds_destroy(&reply);
1278}
1279
6553d06b
DDP
1280static void
1281dpif_netdev_pmd_info(struct unixctl_conn *conn, int argc, const char *argv[],
1282 void *aux)
1283{
1284 struct ds reply = DS_EMPTY_INITIALIZER;
34d8e04b 1285 struct dp_netdev_pmd_thread **pmd_list;
6553d06b
DDP
1286 struct dp_netdev *dp = NULL;
1287 enum pmd_info_type type = *(enum pmd_info_type *) aux;
82a48ead
JS
1288 unsigned int core_id;
1289 bool filter_on_pmd = false;
1290 size_t n;
6553d06b
DDP
1291
1292 ovs_mutex_lock(&dp_netdev_mutex);
1293
82a48ead 1294 while (argc > 1) {
79f36875 1295 if (!strcmp(argv[1], "-pmd") && argc > 2) {
82a48ead
JS
1296 if (str_to_uint(argv[2], 10, &core_id)) {
1297 filter_on_pmd = true;
1298 }
1299 argc -= 2;
1300 argv += 2;
1301 } else {
1302 dp = shash_find_data(&dp_netdevs, argv[1]);
1303 argc -= 1;
1304 argv += 1;
1305 }
6553d06b
DDP
1306 }
1307
1308 if (!dp) {
82a48ead
JS
1309 if (shash_count(&dp_netdevs) == 1) {
1310 /* There's only one datapath */
1311 dp = shash_first(&dp_netdevs)->data;
1312 } else {
1313 ovs_mutex_unlock(&dp_netdev_mutex);
1314 unixctl_command_reply_error(conn,
1315 "please specify an existing datapath");
1316 return;
1317 }
6553d06b
DDP
1318 }
1319
34d8e04b
EC
1320 sorted_poll_thread_list(dp, &pmd_list, &n);
1321 for (size_t i = 0; i < n; i++) {
1322 struct dp_netdev_pmd_thread *pmd = pmd_list[i];
1323 if (!pmd) {
1324 break;
1325 }
82a48ead
JS
1326 if (filter_on_pmd && pmd->core_id != core_id) {
1327 continue;
1328 }
ce179f11
IM
1329 if (type == PMD_INFO_SHOW_RXQ) {
1330 pmd_info_show_rxq(&reply, pmd);
82a48ead
JS
1331 } else if (type == PMD_INFO_CLEAR_STATS) {
1332 pmd_perf_stats_clear(&pmd->perf_stats);
1333 } else if (type == PMD_INFO_SHOW_STATS) {
1334 pmd_info_show_stats(&reply, pmd);
79f36875
JS
1335 } else if (type == PMD_INFO_PERF_SHOW) {
1336 pmd_info_show_perf(&reply, pmd, (struct pmd_perf_params *)aux);
6553d06b
DDP
1337 }
1338 }
34d8e04b 1339 free(pmd_list);
6553d06b
DDP
1340
1341 ovs_mutex_unlock(&dp_netdev_mutex);
1342
1343 unixctl_command_reply(conn, ds_cstr(&reply));
1344 ds_destroy(&reply);
1345}
79f36875
JS
1346
1347static void
1348pmd_perf_show_cmd(struct unixctl_conn *conn, int argc,
1349 const char *argv[],
1350 void *aux OVS_UNUSED)
1351{
1352 struct pmd_perf_params par;
1353 long int it_hist = 0, ms_hist = 0;
1354 par.histograms = true;
1355
1356 while (argc > 1) {
1357 if (!strcmp(argv[1], "-nh")) {
1358 par.histograms = false;
1359 argc -= 1;
1360 argv += 1;
1361 } else if (!strcmp(argv[1], "-it") && argc > 2) {
1362 it_hist = strtol(argv[2], NULL, 10);
1363 if (it_hist < 0) {
1364 it_hist = 0;
1365 } else if (it_hist > HISTORY_LEN) {
1366 it_hist = HISTORY_LEN;
1367 }
1368 argc -= 2;
1369 argv += 2;
1370 } else if (!strcmp(argv[1], "-ms") && argc > 2) {
1371 ms_hist = strtol(argv[2], NULL, 10);
1372 if (ms_hist < 0) {
1373 ms_hist = 0;
1374 } else if (ms_hist > HISTORY_LEN) {
1375 ms_hist = HISTORY_LEN;
1376 }
1377 argc -= 2;
1378 argv += 2;
1379 } else {
1380 break;
1381 }
1382 }
1383 par.iter_hist_len = it_hist;
1384 par.ms_hist_len = ms_hist;
1385 par.command_type = PMD_INFO_PERF_SHOW;
1386 dpif_netdev_pmd_info(conn, argc, argv, &par);
1387}
6553d06b
DDP
1388\f
1389static int
1390dpif_netdev_init(void)
1391{
1392 static enum pmd_info_type show_aux = PMD_INFO_SHOW_STATS,
ce179f11
IM
1393 clear_aux = PMD_INFO_CLEAR_STATS,
1394 poll_aux = PMD_INFO_SHOW_RXQ;
6553d06b 1395
82a48ead
JS
1396 unixctl_command_register("dpif-netdev/pmd-stats-show", "[-pmd core] [dp]",
1397 0, 3, dpif_netdev_pmd_info,
6553d06b 1398 (void *)&show_aux);
82a48ead
JS
1399 unixctl_command_register("dpif-netdev/pmd-stats-clear", "[-pmd core] [dp]",
1400 0, 3, dpif_netdev_pmd_info,
6553d06b 1401 (void *)&clear_aux);
82a48ead
JS
1402 unixctl_command_register("dpif-netdev/pmd-rxq-show", "[-pmd core] [dp]",
1403 0, 3, dpif_netdev_pmd_info,
ce179f11 1404 (void *)&poll_aux);
79f36875
JS
1405 unixctl_command_register("dpif-netdev/pmd-perf-show",
1406 "[-nh] [-it iter-history-len]"
1407 " [-ms ms-history-len]"
1408 " [-pmd core] [dp]",
1409 0, 8, pmd_perf_show_cmd,
1410 NULL);
cd995c73
KT
1411 unixctl_command_register("dpif-netdev/pmd-rxq-rebalance", "[dp]",
1412 0, 1, dpif_netdev_pmd_rebalance,
1413 NULL);
7178fefb
JS
1414 unixctl_command_register("dpif-netdev/pmd-perf-log-set",
1415 "on|off [-b before] [-a after] [-e|-ne] "
1416 "[-us usec] [-q qlen]",
1417 0, 10, pmd_perf_log_set_cmd,
1418 NULL);
6553d06b
DDP
1419 return 0;
1420}
72865317 1421
2197d7ab 1422static int
2240af25
DDP
1423dpif_netdev_enumerate(struct sset *all_dps,
1424 const struct dpif_class *dpif_class)
2197d7ab
GL
1425{
1426 struct shash_node *node;
1427
97be1538 1428 ovs_mutex_lock(&dp_netdev_mutex);
2197d7ab 1429 SHASH_FOR_EACH(node, &dp_netdevs) {
2240af25
DDP
1430 struct dp_netdev *dp = node->data;
1431 if (dpif_class != dp->class) {
1432 /* 'dp_netdevs' contains both "netdev" and "dummy" dpifs.
1433 * If the class doesn't match, skip this dpif. */
1434 continue;
1435 }
2197d7ab
GL
1436 sset_add(all_dps, node->name);
1437 }
97be1538 1438 ovs_mutex_unlock(&dp_netdev_mutex);
5279f8fd 1439
2197d7ab
GL
1440 return 0;
1441}
1442
add90f6f
EJ
1443static bool
1444dpif_netdev_class_is_dummy(const struct dpif_class *class)
1445{
1446 return class != &dpif_netdev_class;
1447}
1448
0aeaabc8
JP
1449static const char *
1450dpif_netdev_port_open_type(const struct dpif_class *class, const char *type)
1451{
1452 return strcmp(type, "internal") ? type
e98d0cb3 1453 : dpif_netdev_class_is_dummy(class) ? "dummy-internal"
0aeaabc8
JP
1454 : "tap";
1455}
1456
72865317
BP
1457static struct dpif *
1458create_dpif_netdev(struct dp_netdev *dp)
1459{
462278db 1460 uint16_t netflow_id = hash_string(dp->name, 0);
72865317 1461 struct dpif_netdev *dpif;
72865317 1462
6a8267c5 1463 ovs_refcount_ref(&dp->ref_cnt);
72865317 1464
72865317 1465 dpif = xmalloc(sizeof *dpif);
614c4892 1466 dpif_init(&dpif->dpif, dp->class, dp->name, netflow_id >> 8, netflow_id);
72865317 1467 dpif->dp = dp;
d33ed218 1468 dpif->last_port_seq = seq_read(dp->port_seq);
72865317
BP
1469
1470 return &dpif->dpif;
1471}
1472
4e022ec0
AW
1473/* Choose an unused, non-zero port number and return it on success.
1474 * Return ODPP_NONE on failure. */
1475static odp_port_t
e44768b7 1476choose_port(struct dp_netdev *dp, const char *name)
59e6d833 1477 OVS_REQUIRES(dp->port_mutex)
e44768b7 1478{
4e022ec0 1479 uint32_t port_no;
e44768b7
JP
1480
1481 if (dp->class != &dpif_netdev_class) {
1482 const char *p;
1483 int start_no = 0;
1484
1485 /* If the port name begins with "br", start the number search at
1486 * 100 to make writing tests easier. */
1487 if (!strncmp(name, "br", 2)) {
1488 start_no = 100;
1489 }
1490
1491 /* If the port name contains a number, try to assign that port number.
1492 * This can make writing unit tests easier because port numbers are
1493 * predictable. */
1494 for (p = name; *p != '\0'; p++) {
1495 if (isdigit((unsigned char) *p)) {
1496 port_no = start_no + strtol(p, NULL, 10);
ff073a71
BP
1497 if (port_no > 0 && port_no != odp_to_u32(ODPP_NONE)
1498 && !dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
4e022ec0 1499 return u32_to_odp(port_no);
e44768b7
JP
1500 }
1501 break;
1502 }
1503 }
1504 }
1505
ff073a71
BP
1506 for (port_no = 1; port_no <= UINT16_MAX; port_no++) {
1507 if (!dp_netdev_lookup_port(dp, u32_to_odp(port_no))) {
4e022ec0 1508 return u32_to_odp(port_no);
e44768b7
JP
1509 }
1510 }
1511
4e022ec0 1512 return ODPP_NONE;
e44768b7
JP
1513}
1514
72865317 1515static int
614c4892
BP
1516create_dp_netdev(const char *name, const struct dpif_class *class,
1517 struct dp_netdev **dpp)
8a4e3a85 1518 OVS_REQUIRES(dp_netdev_mutex)
72865317 1519{
1276e3db 1520 static struct ovsthread_once tsc_freq_check = OVSTHREAD_ONCE_INITIALIZER;
72865317
BP
1521 struct dp_netdev *dp;
1522 int error;
72865317 1523
1276e3db
IM
1524 /* Avoid estimating TSC frequency for dummy datapath to not slow down
1525 * unit tests. */
1526 if (!dpif_netdev_class_is_dummy(class)
1527 && ovsthread_once_start(&tsc_freq_check)) {
1528 pmd_perf_estimate_tsc_frequency();
1529 ovsthread_once_done(&tsc_freq_check);
1530 }
1531
462278db 1532 dp = xzalloc(sizeof *dp);
8a4e3a85
BP
1533 shash_add(&dp_netdevs, name, dp);
1534
1535 *CONST_CAST(const struct dpif_class **, &dp->class) = class;
1536 *CONST_CAST(const char **, &dp->name) = xstrdup(name);
6a8267c5 1537 ovs_refcount_init(&dp->ref_cnt);
1a65ba85 1538 atomic_flag_clear(&dp->destroyed);
8a4e3a85 1539
59e6d833 1540 ovs_mutex_init(&dp->port_mutex);
e9985d6a 1541 hmap_init(&dp->ports);
d33ed218 1542 dp->port_seq = seq_create();
6b31e073
RW
1543 fat_rwlock_init(&dp->upcall_rwlock);
1544
a6a426d6
IM
1545 dp->reconfigure_seq = seq_create();
1546 dp->last_reconfigure_seq = seq_read(dp->reconfigure_seq);
1547
4b27db64
JR
1548 for (int i = 0; i < N_METER_LOCKS; ++i) {
1549 ovs_mutex_init_adaptive(&dp->meter_locks[i]);
1550 }
1551
6b31e073
RW
1552 /* Disable upcalls by default. */
1553 dp_netdev_disable_upcall(dp);
623540e4 1554 dp->upcall_aux = NULL;
6b31e073 1555 dp->upcall_cb = NULL;
e44768b7 1556
57593fd2 1557 dp->conntrack = conntrack_init();
5cf3edb3 1558
4c30b246 1559 atomic_init(&dp->emc_insert_min, DEFAULT_EM_FLOW_INSERT_MIN);
c71ea3c4 1560 atomic_init(&dp->tx_flush_interval, DEFAULT_TX_FLUSH_INTERVAL);
4c30b246 1561
65f13b50 1562 cmap_init(&dp->poll_threads);
e77c97b9 1563 dp->pmd_rxq_assign_cyc = true;
140dd699
IM
1564
1565 ovs_mutex_init(&dp->tx_qid_pool_mutex);
1566 /* We need 1 Tx queue for each possible core + 1 for non-PMD threads. */
1567 dp->tx_qid_pool = id_pool_create(0, ovs_numa_get_n_cores() + 1);
1568
65f13b50
AW
1569 ovs_mutex_init_recursive(&dp->non_pmd_mutex);
1570 ovsthread_key_create(&dp->per_pmd_key, NULL);
1571
e9985d6a 1572 ovs_mutex_lock(&dp->port_mutex);
140dd699
IM
1573 /* non-PMD will be created before all other threads and will
1574 * allocate static_tx_qid = 0. */
f2eee189 1575 dp_netdev_set_nonpmd(dp);
65f13b50 1576
a3e8437a
TLSC
1577 error = do_add_port(dp, name, dpif_netdev_port_open_type(dp->class,
1578 "internal"),
1579 ODPP_LOCAL);
59e6d833 1580 ovs_mutex_unlock(&dp->port_mutex);
72865317
BP
1581 if (error) {
1582 dp_netdev_free(dp);
462278db 1583 return error;
72865317
BP
1584 }
1585
a36de779 1586 dp->last_tnl_conf_seq = seq_read(tnl_conf_seq);
462278db 1587 *dpp = dp;
72865317
BP
1588 return 0;
1589}
1590
a6a426d6
IM
1591static void
1592dp_netdev_request_reconfigure(struct dp_netdev *dp)
1593{
1594 seq_change(dp->reconfigure_seq);
1595}
1596
1597static bool
1598dp_netdev_is_reconf_required(struct dp_netdev *dp)
1599{
1600 return seq_read(dp->reconfigure_seq) != dp->last_reconfigure_seq;
1601}
1602
72865317 1603static int
614c4892 1604dpif_netdev_open(const struct dpif_class *class, const char *name,
4a387741 1605 bool create, struct dpif **dpifp)
72865317 1606{
462278db 1607 struct dp_netdev *dp;
5279f8fd 1608 int error;
462278db 1609
97be1538 1610 ovs_mutex_lock(&dp_netdev_mutex);
462278db
BP
1611 dp = shash_find_data(&dp_netdevs, name);
1612 if (!dp) {
5279f8fd 1613 error = create ? create_dp_netdev(name, class, &dp) : ENODEV;
72865317 1614 } else {
5279f8fd
BP
1615 error = (dp->class != class ? EINVAL
1616 : create ? EEXIST
1617 : 0);
1618 }
1619 if (!error) {
1620 *dpifp = create_dpif_netdev(dp);
6b31e073 1621 dp->dpif = *dpifp;
72865317 1622 }
97be1538 1623 ovs_mutex_unlock(&dp_netdev_mutex);
462278db 1624
5279f8fd 1625 return error;
72865317
BP
1626}
1627
88ace79b
DDP
1628static void
1629dp_netdev_destroy_upcall_lock(struct dp_netdev *dp)
1630 OVS_NO_THREAD_SAFETY_ANALYSIS
1631{
1632 /* Check that upcalls are disabled, i.e. that the rwlock is taken */
1633 ovs_assert(fat_rwlock_tryrdlock(&dp->upcall_rwlock));
1634
1635 /* Before freeing a lock we should release it */
1636 fat_rwlock_unlock(&dp->upcall_rwlock);
1637 fat_rwlock_destroy(&dp->upcall_rwlock);
1638}
1639
4b27db64
JR
1640static void
1641dp_delete_meter(struct dp_netdev *dp, uint32_t meter_id)
1642 OVS_REQUIRES(dp->meter_locks[meter_id % N_METER_LOCKS])
1643{
1644 if (dp->meters[meter_id]) {
1645 free(dp->meters[meter_id]);
1646 dp->meters[meter_id] = NULL;
1647 }
1648}
1649
8a4e3a85
BP
1650/* Requires dp_netdev_mutex so that we can't get a new reference to 'dp'
1651 * through the 'dp_netdevs' shash while freeing 'dp'. */
1ba530f4
BP
1652static void
1653dp_netdev_free(struct dp_netdev *dp)
8a4e3a85 1654 OVS_REQUIRES(dp_netdev_mutex)
1ba530f4 1655{
e9985d6a 1656 struct dp_netdev_port *port, *next;
4ad28026 1657
8a4e3a85
BP
1658 shash_find_and_delete(&dp_netdevs, dp->name);
1659
59e6d833 1660 ovs_mutex_lock(&dp->port_mutex);
e9985d6a 1661 HMAP_FOR_EACH_SAFE (port, next, node, &dp->ports) {
c40b890f 1662 do_del_port(dp, port);
1ba530f4 1663 }
59e6d833 1664 ovs_mutex_unlock(&dp->port_mutex);
4b27db64 1665
e32971b8 1666 dp_netdev_destroy_all_pmds(dp, true);
d916785c 1667 cmap_destroy(&dp->poll_threads);
51852a57 1668
140dd699
IM
1669 ovs_mutex_destroy(&dp->tx_qid_pool_mutex);
1670 id_pool_destroy(dp->tx_qid_pool);
1671
b9584f21
DDP
1672 ovs_mutex_destroy(&dp->non_pmd_mutex);
1673 ovsthread_key_delete(dp->per_pmd_key);
1674
57593fd2 1675 conntrack_destroy(dp->conntrack);
b9584f21
DDP
1676
1677
a6a426d6
IM
1678 seq_destroy(dp->reconfigure_seq);
1679
d33ed218 1680 seq_destroy(dp->port_seq);
e9985d6a 1681 hmap_destroy(&dp->ports);
3186ea46 1682 ovs_mutex_destroy(&dp->port_mutex);
88ace79b
DDP
1683
1684 /* Upcalls must be disabled at this point */
1685 dp_netdev_destroy_upcall_lock(dp);
9bbf1c3d 1686
4b27db64
JR
1687 int i;
1688
1689 for (i = 0; i < MAX_METERS; ++i) {
1690 meter_lock(dp, i);
1691 dp_delete_meter(dp, i);
1692 meter_unlock(dp, i);
1693 }
1694 for (i = 0; i < N_METER_LOCKS; ++i) {
1695 ovs_mutex_destroy(&dp->meter_locks[i]);
1696 }
1697
f2eee189 1698 free(dp->pmd_cmask);
8a4e3a85 1699 free(CONST_CAST(char *, dp->name));
72865317
BP
1700 free(dp);
1701}
1702
8a4e3a85
BP
1703static void
1704dp_netdev_unref(struct dp_netdev *dp)
1705{
1706 if (dp) {
1707 /* Take dp_netdev_mutex so that, if dp->ref_cnt falls to zero, we can't
1708 * get a new reference to 'dp' through the 'dp_netdevs' shash. */
1709 ovs_mutex_lock(&dp_netdev_mutex);
24f83812 1710 if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
8a4e3a85
BP
1711 dp_netdev_free(dp);
1712 }
1713 ovs_mutex_unlock(&dp_netdev_mutex);
1714 }
1715}
1716
72865317
BP
1717static void
1718dpif_netdev_close(struct dpif *dpif)
1719{
1720 struct dp_netdev *dp = get_dp_netdev(dpif);
5279f8fd 1721
8a4e3a85 1722 dp_netdev_unref(dp);
72865317
BP
1723 free(dpif);
1724}
1725
1726static int
7dab847a 1727dpif_netdev_destroy(struct dpif *dpif)
72865317
BP
1728{
1729 struct dp_netdev *dp = get_dp_netdev(dpif);
5279f8fd 1730
6a8267c5 1731 if (!atomic_flag_test_and_set(&dp->destroyed)) {
24f83812 1732 if (ovs_refcount_unref_relaxed(&dp->ref_cnt) == 1) {
6a8267c5
BP
1733 /* Can't happen: 'dpif' still owns a reference to 'dp'. */
1734 OVS_NOT_REACHED();
1735 }
1736 }
5279f8fd 1737
72865317
BP
1738 return 0;
1739}
1740
eb94da30
DDP
1741/* Add 'n' to the atomic variable 'var' non-atomically and using relaxed
1742 * load/store semantics. While the increment is not atomic, the load and
1743 * store operations are, making it impossible to read inconsistent values.
1744 *
1745 * This is used to update thread local stats counters. */
1746static void
1747non_atomic_ullong_add(atomic_ullong *var, unsigned long long n)
1748{
1749 unsigned long long tmp;
1750
1751 atomic_read_relaxed(var, &tmp);
1752 tmp += n;
1753 atomic_store_relaxed(var, tmp);
1754}
1755
72865317 1756static int
a8d9304d 1757dpif_netdev_get_stats(const struct dpif *dpif, struct dpif_dp_stats *stats)
72865317
BP
1758{
1759 struct dp_netdev *dp = get_dp_netdev(dpif);
1c1e46ed 1760 struct dp_netdev_pmd_thread *pmd;
82a48ead 1761 uint64_t pmd_stats[PMD_N_STATS];
8a4e3a85 1762
1c1e46ed
AW
1763 stats->n_flows = stats->n_hit = stats->n_missed = stats->n_lost = 0;
1764 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
1765 stats->n_flows += cmap_count(&pmd->flow_table);
82a48ead
JS
1766 pmd_perf_read_counters(&pmd->perf_stats, pmd_stats);
1767 stats->n_hit += pmd_stats[PMD_STAT_EXACT_HIT];
60d8ccae 1768 stats->n_hit += pmd_stats[PMD_STAT_SMC_HIT];
82a48ead
JS
1769 stats->n_hit += pmd_stats[PMD_STAT_MASKED_HIT];
1770 stats->n_missed += pmd_stats[PMD_STAT_MISS];
1771 stats->n_lost += pmd_stats[PMD_STAT_LOST];
51852a57 1772 }
1ce3fa06 1773 stats->n_masks = UINT32_MAX;
847108dc 1774 stats->n_mask_hit = UINT64_MAX;
5279f8fd 1775
72865317
BP
1776 return 0;
1777}
1778
e4cfed38 1779static void
65f13b50 1780dp_netdev_reload_pmd__(struct dp_netdev_pmd_thread *pmd)
e4cfed38 1781{
accf8626 1782 if (pmd->core_id == NON_PMD_CORE_ID) {
d0cca6c3
DDP
1783 ovs_mutex_lock(&pmd->dp->non_pmd_mutex);
1784 ovs_mutex_lock(&pmd->port_mutex);
1785 pmd_load_cached_ports(pmd);
1786 ovs_mutex_unlock(&pmd->port_mutex);
1787 ovs_mutex_unlock(&pmd->dp->non_pmd_mutex);
accf8626
AW
1788 return;
1789 }
1790
2788a1b1 1791 seq_change(pmd->reload_seq);
299c8d61 1792 atomic_store_explicit(&pmd->reload, true, memory_order_release);
65f13b50 1793}
e4cfed38 1794
59e6d833
BP
1795static uint32_t
1796hash_port_no(odp_port_t port_no)
1797{
1798 return hash_int(odp_to_u32(port_no), 0);
1799}
1800
72865317 1801static int
a3e8437a 1802port_create(const char *devname, const char *type,
b8d29252 1803 odp_port_t port_no, struct dp_netdev_port **portp)
72865317 1804{
4b609110 1805 struct netdev_saved_flags *sf;
72865317 1806 struct dp_netdev_port *port;
2499a8ce 1807 enum netdev_flags flags;
b8d29252 1808 struct netdev *netdev;
e32971b8 1809 int error;
72865317 1810
b8d29252 1811 *portp = NULL;
72865317
BP
1812
1813 /* Open and validate network device. */
a3e8437a 1814 error = netdev_open(devname, type, &netdev);
72865317 1815 if (error) {
b8d29252 1816 return error;
72865317 1817 }
72865317
BP
1818 /* XXX reject non-Ethernet devices */
1819
2499a8ce
AC
1820 netdev_get_flags(netdev, &flags);
1821 if (flags & NETDEV_LOOPBACK) {
1822 VLOG_ERR("%s: cannot add a loopback device", devname);
d17f4f08 1823 error = EINVAL;
b8d29252 1824 goto out;
2499a8ce
AC
1825 }
1826
e32971b8
DDP
1827 error = netdev_turn_flags_on(netdev, NETDEV_PROMISC, &sf);
1828 if (error) {
1829 VLOG_ERR("%s: cannot set promisc flag", devname);
1830 goto out;
324c8374
IM
1831 }
1832
e4cfed38 1833 port = xzalloc(sizeof *port);
35303d71 1834 port->port_no = port_no;
e4cfed38
PS
1835 port->netdev = netdev;
1836 port->type = xstrdup(type);
4b609110 1837 port->sf = sf;
2fbadeb6 1838 port->emc_enabled = true;
e32971b8
DDP
1839 port->need_reconfigure = true;
1840 ovs_mutex_init(&port->txq_used_mutex);
e4cfed38 1841
b8d29252 1842 *portp = port;
72865317
BP
1843
1844 return 0;
d17f4f08 1845
d17f4f08 1846out:
b8d29252 1847 netdev_close(netdev);
d17f4f08 1848 return error;
72865317
BP
1849}
1850
b8d29252
DDP
1851static int
1852do_add_port(struct dp_netdev *dp, const char *devname, const char *type,
1853 odp_port_t port_no)
1854 OVS_REQUIRES(dp->port_mutex)
1855{
1856 struct dp_netdev_port *port;
1857 int error;
1858
1859 /* Reject devices already in 'dp'. */
1860 if (!get_port_by_name(dp, devname, &port)) {
1861 return EEXIST;
1862 }
1863
a3e8437a 1864 error = port_create(devname, type, port_no, &port);
b8d29252
DDP
1865 if (error) {
1866 return error;
1867 }
1868
e9985d6a 1869 hmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
b8d29252
DDP
1870 seq_change(dp->port_seq);
1871
e32971b8
DDP
1872 reconfigure_datapath(dp);
1873
3f51ea18
IM
1874 /* Check that port was successfully configured. */
1875 return dp_netdev_lookup_port(dp, port_no) ? 0 : EINVAL;
b8d29252
DDP
1876}
1877
247527db
BP
1878static int
1879dpif_netdev_port_add(struct dpif *dpif, struct netdev *netdev,
4e022ec0 1880 odp_port_t *port_nop)
247527db
BP
1881{
1882 struct dp_netdev *dp = get_dp_netdev(dpif);
3aa30359
BP
1883 char namebuf[NETDEV_VPORT_NAME_BUFSIZE];
1884 const char *dpif_port;
4e022ec0 1885 odp_port_t port_no;
5279f8fd 1886 int error;
247527db 1887
59e6d833 1888 ovs_mutex_lock(&dp->port_mutex);
3aa30359 1889 dpif_port = netdev_vport_get_dpif_port(netdev, namebuf, sizeof namebuf);
4e022ec0 1890 if (*port_nop != ODPP_NONE) {
ff073a71
BP
1891 port_no = *port_nop;
1892 error = dp_netdev_lookup_port(dp, *port_nop) ? EBUSY : 0;
232dfa4a 1893 } else {
3aa30359 1894 port_no = choose_port(dp, dpif_port);
5279f8fd 1895 error = port_no == ODPP_NONE ? EFBIG : 0;
232dfa4a 1896 }
5279f8fd 1897 if (!error) {
247527db 1898 *port_nop = port_no;
5279f8fd 1899 error = do_add_port(dp, dpif_port, netdev_get_type(netdev), port_no);
247527db 1900 }
59e6d833 1901 ovs_mutex_unlock(&dp->port_mutex);
5279f8fd
BP
1902
1903 return error;
72865317
BP
1904}
1905
1906static int
4e022ec0 1907dpif_netdev_port_del(struct dpif *dpif, odp_port_t port_no)
72865317
BP
1908{
1909 struct dp_netdev *dp = get_dp_netdev(dpif);
5279f8fd
BP
1910 int error;
1911
59e6d833 1912 ovs_mutex_lock(&dp->port_mutex);
c40b890f
BP
1913 if (port_no == ODPP_LOCAL) {
1914 error = EINVAL;
1915 } else {
1916 struct dp_netdev_port *port;
1917
1918 error = get_port_by_number(dp, port_no, &port);
1919 if (!error) {
1920 do_del_port(dp, port);
1921 }
1922 }
59e6d833 1923 ovs_mutex_unlock(&dp->port_mutex);
5279f8fd
BP
1924
1925 return error;
72865317
BP
1926}
1927
1928static bool
4e022ec0 1929is_valid_port_number(odp_port_t port_no)
72865317 1930{
ff073a71
BP
1931 return port_no != ODPP_NONE;
1932}
1933
1934static struct dp_netdev_port *
1935dp_netdev_lookup_port(const struct dp_netdev *dp, odp_port_t port_no)
e9985d6a 1936 OVS_REQUIRES(dp->port_mutex)
ff073a71
BP
1937{
1938 struct dp_netdev_port *port;
1939
e9985d6a 1940 HMAP_FOR_EACH_WITH_HASH (port, node, hash_port_no(port_no), &dp->ports) {
35303d71 1941 if (port->port_no == port_no) {
ff073a71
BP
1942 return port;
1943 }
1944 }
1945 return NULL;
72865317
BP
1946}
1947
1948static int
1949get_port_by_number(struct dp_netdev *dp,
4e022ec0 1950 odp_port_t port_no, struct dp_netdev_port **portp)
e9985d6a 1951 OVS_REQUIRES(dp->port_mutex)
72865317
BP
1952{
1953 if (!is_valid_port_number(port_no)) {
1954 *portp = NULL;
1955 return EINVAL;
1956 } else {
ff073a71 1957 *portp = dp_netdev_lookup_port(dp, port_no);
0f6a066f 1958 return *portp ? 0 : ENODEV;
72865317
BP
1959 }
1960}
1961
b284085e 1962static void
62453dad 1963port_destroy(struct dp_netdev_port *port)
b284085e 1964{
62453dad
DDP
1965 if (!port) {
1966 return;
b284085e 1967 }
b284085e 1968
62453dad
DDP
1969 netdev_close(port->netdev);
1970 netdev_restore_flags(port->sf);
accf8626 1971
62453dad 1972 for (unsigned i = 0; i < port->n_rxq; i++) {
947dc567 1973 netdev_rxq_close(port->rxqs[i].rx);
b284085e 1974 }
324c8374 1975 ovs_mutex_destroy(&port->txq_used_mutex);
3eb67853 1976 free(port->rxq_affinity_list);
324c8374 1977 free(port->txq_used);
3eb67853 1978 free(port->rxqs);
62453dad
DDP
1979 free(port->type);
1980 free(port);
b284085e
PS
1981}
1982
72865317
BP
1983static int
1984get_port_by_name(struct dp_netdev *dp,
1985 const char *devname, struct dp_netdev_port **portp)
59e6d833 1986 OVS_REQUIRES(dp->port_mutex)
72865317
BP
1987{
1988 struct dp_netdev_port *port;
1989
e9985d6a 1990 HMAP_FOR_EACH (port, node, &dp->ports) {
3efb6063 1991 if (!strcmp(netdev_get_name(port->netdev), devname)) {
72865317
BP
1992 *portp = port;
1993 return 0;
1994 }
1995 }
0f6a066f
DDP
1996
1997 /* Callers of dpif_netdev_port_query_by_name() expect ENODEV for a non
1998 * existing port. */
1999 return ENODEV;
72865317
BP
2000}
2001
b9584f21 2002/* Returns 'true' if there is a port with pmd netdev. */
65f13b50 2003static bool
b9584f21 2004has_pmd_port(struct dp_netdev *dp)
e9985d6a 2005 OVS_REQUIRES(dp->port_mutex)
65f13b50
AW
2006{
2007 struct dp_netdev_port *port;
2008
e9985d6a 2009 HMAP_FOR_EACH (port, node, &dp->ports) {
5dd57e80 2010 if (netdev_is_pmd(port->netdev)) {
b9584f21 2011 return true;
65f13b50
AW
2012 }
2013 }
2014
2015 return false;
2016}
2017
c40b890f
BP
2018static void
2019do_del_port(struct dp_netdev *dp, struct dp_netdev_port *port)
59e6d833 2020 OVS_REQUIRES(dp->port_mutex)
72865317 2021{
e9985d6a 2022 hmap_remove(&dp->ports, &port->node);
d33ed218 2023 seq_change(dp->port_seq);
d0cca6c3 2024
e32971b8 2025 reconfigure_datapath(dp);
72865317 2026
62453dad 2027 port_destroy(port);
72865317
BP
2028}
2029
2030static void
4c738a8d
BP
2031answer_port_query(const struct dp_netdev_port *port,
2032 struct dpif_port *dpif_port)
72865317 2033{
3efb6063 2034 dpif_port->name = xstrdup(netdev_get_name(port->netdev));
0cbfe35d 2035 dpif_port->type = xstrdup(port->type);
35303d71 2036 dpif_port->port_no = port->port_no;
72865317
BP
2037}
2038
2039static int
4e022ec0 2040dpif_netdev_port_query_by_number(const struct dpif *dpif, odp_port_t port_no,
4c738a8d 2041 struct dpif_port *dpif_port)
72865317
BP
2042{
2043 struct dp_netdev *dp = get_dp_netdev(dpif);
2044 struct dp_netdev_port *port;
2045 int error;
2046
e9985d6a 2047 ovs_mutex_lock(&dp->port_mutex);
72865317 2048 error = get_port_by_number(dp, port_no, &port);
4afba28d 2049 if (!error && dpif_port) {
4c738a8d 2050 answer_port_query(port, dpif_port);
72865317 2051 }
e9985d6a 2052 ovs_mutex_unlock(&dp->port_mutex);
5279f8fd 2053
72865317
BP
2054 return error;
2055}
2056
2057static int
2058dpif_netdev_port_query_by_name(const struct dpif *dpif, const char *devname,
4c738a8d 2059 struct dpif_port *dpif_port)
72865317
BP
2060{
2061 struct dp_netdev *dp = get_dp_netdev(dpif);
2062 struct dp_netdev_port *port;
2063 int error;
2064
59e6d833 2065 ovs_mutex_lock(&dp->port_mutex);
72865317 2066 error = get_port_by_name(dp, devname, &port);
4afba28d 2067 if (!error && dpif_port) {
4c738a8d 2068 answer_port_query(port, dpif_port);
72865317 2069 }
59e6d833 2070 ovs_mutex_unlock(&dp->port_mutex);
5279f8fd 2071
72865317
BP
2072 return error;
2073}
2074
61e7deb1
BP
2075static void
2076dp_netdev_flow_free(struct dp_netdev_flow *flow)
2077{
61e7deb1 2078 dp_netdev_actions_free(dp_netdev_flow_get_actions(flow));
61e7deb1
BP
2079 free(flow);
2080}
2081
ed79f89a
DDP
2082static void dp_netdev_flow_unref(struct dp_netdev_flow *flow)
2083{
2084 if (ovs_refcount_unref_relaxed(&flow->ref_cnt) == 1) {
2085 ovsrcu_postpone(dp_netdev_flow_free, flow);
2086 }
2087}
2088
70e5ed6f
JS
2089static uint32_t
2090dp_netdev_flow_hash(const ovs_u128 *ufid)
2091{
2092 return ufid->u32[0];
2093}
2094
3453b4d6
JS
2095static inline struct dpcls *
2096dp_netdev_pmd_lookup_dpcls(struct dp_netdev_pmd_thread *pmd,
2097 odp_port_t in_port)
2098{
2099 struct dpcls *cls;
2100 uint32_t hash = hash_port_no(in_port);
2101 CMAP_FOR_EACH_WITH_HASH (cls, node, hash, &pmd->classifiers) {
2102 if (cls->in_port == in_port) {
2103 /* Port classifier exists already */
2104 return cls;
2105 }
2106 }
2107 return NULL;
2108}
2109
2110static inline struct dpcls *
2111dp_netdev_pmd_find_dpcls(struct dp_netdev_pmd_thread *pmd,
2112 odp_port_t in_port)
2113 OVS_REQUIRES(pmd->flow_mutex)
2114{
2115 struct dpcls *cls = dp_netdev_pmd_lookup_dpcls(pmd, in_port);
2116 uint32_t hash = hash_port_no(in_port);
2117
2118 if (!cls) {
2119 /* Create new classifier for in_port */
2120 cls = xmalloc(sizeof(*cls));
2121 dpcls_init(cls);
2122 cls->in_port = in_port;
2123 cmap_insert(&pmd->classifiers, &cls->node, hash);
2124 VLOG_DBG("Creating dpcls %p for in_port %d", cls, in_port);
2125 }
2126 return cls;
2127}
2128
241bad15
YL
2129#define MAX_FLOW_MARK (UINT32_MAX - 1)
2130#define INVALID_FLOW_MARK (UINT32_MAX)
2131
2132struct megaflow_to_mark_data {
2133 const struct cmap_node node;
2134 ovs_u128 mega_ufid;
2135 uint32_t mark;
2136};
2137
2138struct flow_mark {
2139 struct cmap megaflow_to_mark;
2140 struct cmap mark_to_flow;
2141 struct id_pool *pool;
241bad15
YL
2142};
2143
2144static struct flow_mark flow_mark = {
2145 .megaflow_to_mark = CMAP_INITIALIZER,
2146 .mark_to_flow = CMAP_INITIALIZER,
241bad15
YL
2147};
2148
2149static uint32_t
2150flow_mark_alloc(void)
2151{
2152 uint32_t mark;
2153
2154 if (!flow_mark.pool) {
2155 /* Haven't initiated yet, do it here */
2156 flow_mark.pool = id_pool_create(0, MAX_FLOW_MARK);
2157 }
2158
2159 if (id_pool_alloc_id(flow_mark.pool, &mark)) {
2160 return mark;
2161 }
2162
2163 return INVALID_FLOW_MARK;
2164}
2165
2166static void
2167flow_mark_free(uint32_t mark)
2168{
2169 id_pool_free_id(flow_mark.pool, mark);
2170}
2171
2172/* associate megaflow with a mark, which is a 1:1 mapping */
2173static void
2174megaflow_to_mark_associate(const ovs_u128 *mega_ufid, uint32_t mark)
2175{
2176 size_t hash = dp_netdev_flow_hash(mega_ufid);
2177 struct megaflow_to_mark_data *data = xzalloc(sizeof(*data));
2178
2179 data->mega_ufid = *mega_ufid;
2180 data->mark = mark;
2181
2182 cmap_insert(&flow_mark.megaflow_to_mark,
2183 CONST_CAST(struct cmap_node *, &data->node), hash);
2184}
2185
2186/* disassociate meagaflow with a mark */
2187static void
2188megaflow_to_mark_disassociate(const ovs_u128 *mega_ufid)
2189{
2190 size_t hash = dp_netdev_flow_hash(mega_ufid);
2191 struct megaflow_to_mark_data *data;
2192
2193 CMAP_FOR_EACH_WITH_HASH (data, node, hash, &flow_mark.megaflow_to_mark) {
2194 if (ovs_u128_equals(*mega_ufid, data->mega_ufid)) {
2195 cmap_remove(&flow_mark.megaflow_to_mark,
2196 CONST_CAST(struct cmap_node *, &data->node), hash);
5752eae4 2197 ovsrcu_postpone(free, data);
241bad15
YL
2198 return;
2199 }
2200 }
2201
2202 VLOG_WARN("Masked ufid "UUID_FMT" is not associated with a mark?\n",
2203 UUID_ARGS((struct uuid *)mega_ufid));
2204}
2205
2206static inline uint32_t
2207megaflow_to_mark_find(const ovs_u128 *mega_ufid)
2208{
2209 size_t hash = dp_netdev_flow_hash(mega_ufid);
2210 struct megaflow_to_mark_data *data;
2211
2212 CMAP_FOR_EACH_WITH_HASH (data, node, hash, &flow_mark.megaflow_to_mark) {
2213 if (ovs_u128_equals(*mega_ufid, data->mega_ufid)) {
2214 return data->mark;
2215 }
2216 }
2217
5d1765d3
IM
2218 VLOG_DBG("Mark id for ufid "UUID_FMT" was not found\n",
2219 UUID_ARGS((struct uuid *)mega_ufid));
241bad15
YL
2220 return INVALID_FLOW_MARK;
2221}
2222
2223/* associate mark with a flow, which is 1:N mapping */
2224static void
2225mark_to_flow_associate(const uint32_t mark, struct dp_netdev_flow *flow)
2226{
2227 dp_netdev_flow_ref(flow);
2228
2229 cmap_insert(&flow_mark.mark_to_flow,
2230 CONST_CAST(struct cmap_node *, &flow->mark_node),
2231 hash_int(mark, 0));
2232 flow->mark = mark;
2233
2234 VLOG_DBG("Associated dp_netdev flow %p with mark %u\n", flow, mark);
2235}
2236
2237static bool
2238flow_mark_has_no_ref(uint32_t mark)
2239{
2240 struct dp_netdev_flow *flow;
2241
2242 CMAP_FOR_EACH_WITH_HASH (flow, mark_node, hash_int(mark, 0),
2243 &flow_mark.mark_to_flow) {
2244 if (flow->mark == mark) {
2245 return false;
2246 }
2247 }
2248
2249 return true;
2250}
2251
2252static int
2253mark_to_flow_disassociate(struct dp_netdev_pmd_thread *pmd,
2254 struct dp_netdev_flow *flow)
2255{
2256 int ret = 0;
2257 uint32_t mark = flow->mark;
2258 struct cmap_node *mark_node = CONST_CAST(struct cmap_node *,
2259 &flow->mark_node);
2260
2261 cmap_remove(&flow_mark.mark_to_flow, mark_node, hash_int(mark, 0));
2262 flow->mark = INVALID_FLOW_MARK;
2263
2264 /*
2265 * no flow is referencing the mark any more? If so, let's
2266 * remove the flow from hardware and free the mark.
2267 */
2268 if (flow_mark_has_no_ref(mark)) {
30115809 2269 struct netdev *port;
241bad15
YL
2270 odp_port_t in_port = flow->flow.in_port.odp_port;
2271
1061dc7c 2272 port = netdev_ports_get(in_port, pmd->dp->class);
241bad15 2273 if (port) {
30115809
IM
2274 ret = netdev_flow_del(port, &flow->mega_ufid, NULL);
2275 netdev_close(port);
241bad15 2276 }
241bad15
YL
2277
2278 flow_mark_free(mark);
2279 VLOG_DBG("Freed flow mark %u\n", mark);
2280
2281 megaflow_to_mark_disassociate(&flow->mega_ufid);
2282 }
2283 dp_netdev_flow_unref(flow);
2284
2285 return ret;
2286}
2287
2288static void
2289flow_mark_flush(struct dp_netdev_pmd_thread *pmd)
2290{
2291 struct dp_netdev_flow *flow;
2292
2293 CMAP_FOR_EACH (flow, mark_node, &flow_mark.mark_to_flow) {
2294 if (flow->pmd_id == pmd->core_id) {
02bb2824 2295 queue_netdev_flow_del(pmd, flow);
241bad15
YL
2296 }
2297 }
2298}
2299
aab96ec4
YL
2300static struct dp_netdev_flow *
2301mark_to_flow_find(const struct dp_netdev_pmd_thread *pmd,
2302 const uint32_t mark)
2303{
2304 struct dp_netdev_flow *flow;
2305
2306 CMAP_FOR_EACH_WITH_HASH (flow, mark_node, hash_int(mark, 0),
2307 &flow_mark.mark_to_flow) {
2308 if (flow->mark == mark && flow->pmd_id == pmd->core_id &&
2309 flow->dead == false) {
2310 return flow;
2311 }
2312 }
2313
2314 return NULL;
2315}
2316
02bb2824
YL
2317static struct dp_flow_offload_item *
2318dp_netdev_alloc_flow_offload(struct dp_netdev_pmd_thread *pmd,
2319 struct dp_netdev_flow *flow,
2320 int op)
2321{
2322 struct dp_flow_offload_item *offload;
2323
2324 offload = xzalloc(sizeof(*offload));
2325 offload->pmd = pmd;
2326 offload->flow = flow;
2327 offload->op = op;
2328
2329 dp_netdev_flow_ref(flow);
2330 dp_netdev_pmd_try_ref(pmd);
2331
2332 return offload;
2333}
2334
2335static void
2336dp_netdev_free_flow_offload(struct dp_flow_offload_item *offload)
2337{
2338 dp_netdev_pmd_unref(offload->pmd);
2339 dp_netdev_flow_unref(offload->flow);
2340
2341 free(offload->actions);
2342 free(offload);
2343}
2344
2345static void
2346dp_netdev_append_flow_offload(struct dp_flow_offload_item *offload)
2347{
2348 ovs_mutex_lock(&dp_flow_offload.mutex);
2349 ovs_list_push_back(&dp_flow_offload.list, &offload->node);
2350 xpthread_cond_signal(&dp_flow_offload.cond);
2351 ovs_mutex_unlock(&dp_flow_offload.mutex);
2352}
2353
2354static int
2355dp_netdev_flow_offload_del(struct dp_flow_offload_item *offload)
2356{
2357 return mark_to_flow_disassociate(offload->pmd, offload->flow);
2358}
2359
2360/*
2361 * There are two flow offload operations here: addition and modification.
2362 *
2363 * For flow addition, this function does:
2364 * - allocate a new flow mark id
2365 * - perform hardware flow offload
2366 * - associate the flow mark with flow and mega flow
2367 *
2368 * For flow modification, both flow mark and the associations are still
2369 * valid, thus only item 2 needed.
2370 */
2371static int
2372dp_netdev_flow_offload_put(struct dp_flow_offload_item *offload)
2373{
02bb2824
YL
2374 struct dp_netdev_pmd_thread *pmd = offload->pmd;
2375 struct dp_netdev_flow *flow = offload->flow;
2376 odp_port_t in_port = flow->flow.in_port.odp_port;
2377 bool modification = offload->op == DP_NETDEV_FLOW_OFFLOAD_OP_MOD;
2378 struct offload_info info;
30115809 2379 struct netdev *port;
02bb2824
YL
2380 uint32_t mark;
2381 int ret;
2382
2383 if (flow->dead) {
2384 return -1;
2385 }
2386
2387 if (modification) {
2388 mark = flow->mark;
2389 ovs_assert(mark != INVALID_FLOW_MARK);
2390 } else {
2391 /*
2392 * If a mega flow has already been offloaded (from other PMD
2393 * instances), do not offload it again.
2394 */
2395 mark = megaflow_to_mark_find(&flow->mega_ufid);
2396 if (mark != INVALID_FLOW_MARK) {
2397 VLOG_DBG("Flow has already been offloaded with mark %u\n", mark);
2398 if (flow->mark != INVALID_FLOW_MARK) {
2399 ovs_assert(flow->mark == mark);
2400 } else {
2401 mark_to_flow_associate(mark, flow);
2402 }
2403 return 0;
2404 }
2405
2406 mark = flow_mark_alloc();
2407 if (mark == INVALID_FLOW_MARK) {
2408 VLOG_ERR("Failed to allocate flow mark!\n");
2409 }
2410 }
2411 info.flow_mark = mark;
2412
1061dc7c 2413 port = netdev_ports_get(in_port, pmd->dp->class);
30115809
IM
2414 if (!port || netdev_vport_is_vport_class(port->netdev_class)) {
2415 netdev_close(port);
0a5cba65 2416 goto err_free;
02bb2824 2417 }
30115809 2418 ret = netdev_flow_put(port, &offload->match,
02bb2824
YL
2419 CONST_CAST(struct nlattr *, offload->actions),
2420 offload->actions_len, &flow->mega_ufid, &info,
2421 NULL);
30115809 2422 netdev_close(port);
02bb2824
YL
2423
2424 if (ret) {
0a5cba65 2425 goto err_free;
02bb2824
YL
2426 }
2427
2428 if (!modification) {
2429 megaflow_to_mark_associate(&flow->mega_ufid, mark);
2430 mark_to_flow_associate(mark, flow);
2431 }
02bb2824 2432 return 0;
0a5cba65
IM
2433
2434err_free:
2435 if (!modification) {
2436 flow_mark_free(mark);
2437 } else {
2438 mark_to_flow_disassociate(pmd, flow);
2439 }
2440 return -1;
02bb2824
YL
2441}
2442
2443static void *
2444dp_netdev_flow_offload_main(void *data OVS_UNUSED)
2445{
2446 struct dp_flow_offload_item *offload;
2447 struct ovs_list *list;
2448 const char *op;
2449 int ret;
2450
2451 for (;;) {
2452 ovs_mutex_lock(&dp_flow_offload.mutex);
2453 if (ovs_list_is_empty(&dp_flow_offload.list)) {
2454 ovsrcu_quiesce_start();
2455 ovs_mutex_cond_wait(&dp_flow_offload.cond,
2456 &dp_flow_offload.mutex);
6c95dbf9 2457 ovsrcu_quiesce_end();
02bb2824
YL
2458 }
2459 list = ovs_list_pop_front(&dp_flow_offload.list);
2460 offload = CONTAINER_OF(list, struct dp_flow_offload_item, node);
2461 ovs_mutex_unlock(&dp_flow_offload.mutex);
2462
2463 switch (offload->op) {
2464 case DP_NETDEV_FLOW_OFFLOAD_OP_ADD:
2465 op = "add";
2466 ret = dp_netdev_flow_offload_put(offload);
2467 break;
2468 case DP_NETDEV_FLOW_OFFLOAD_OP_MOD:
2469 op = "modify";
2470 ret = dp_netdev_flow_offload_put(offload);
2471 break;
2472 case DP_NETDEV_FLOW_OFFLOAD_OP_DEL:
2473 op = "delete";
2474 ret = dp_netdev_flow_offload_del(offload);
2475 break;
2476 default:
2477 OVS_NOT_REACHED();
2478 }
2479
2480 VLOG_DBG("%s to %s netdev flow\n",
2481 ret == 0 ? "succeed" : "failed", op);
2482 dp_netdev_free_flow_offload(offload);
2483 }
2484
2485 return NULL;
2486}
2487
2488static void
2489queue_netdev_flow_del(struct dp_netdev_pmd_thread *pmd,
2490 struct dp_netdev_flow *flow)
2491{
2492 struct dp_flow_offload_item *offload;
2493
2494 if (ovsthread_once_start(&offload_thread_once)) {
2495 xpthread_cond_init(&dp_flow_offload.cond, NULL);
2496 ovs_thread_create("dp_netdev_flow_offload",
2497 dp_netdev_flow_offload_main, NULL);
2498 ovsthread_once_done(&offload_thread_once);
2499 }
2500
2501 offload = dp_netdev_alloc_flow_offload(pmd, flow,
2502 DP_NETDEV_FLOW_OFFLOAD_OP_DEL);
2503 dp_netdev_append_flow_offload(offload);
2504}
2505
2506static void
2507queue_netdev_flow_put(struct dp_netdev_pmd_thread *pmd,
2508 struct dp_netdev_flow *flow, struct match *match,
2509 const struct nlattr *actions, size_t actions_len)
2510{
2511 struct dp_flow_offload_item *offload;
2512 int op;
2513
2514 if (!netdev_is_flow_api_enabled()) {
2515 return;
2516 }
2517
2518 if (ovsthread_once_start(&offload_thread_once)) {
2519 xpthread_cond_init(&dp_flow_offload.cond, NULL);
2520 ovs_thread_create("dp_netdev_flow_offload",
2521 dp_netdev_flow_offload_main, NULL);
2522 ovsthread_once_done(&offload_thread_once);
2523 }
2524
2525 if (flow->mark != INVALID_FLOW_MARK) {
2526 op = DP_NETDEV_FLOW_OFFLOAD_OP_MOD;
2527 } else {
2528 op = DP_NETDEV_FLOW_OFFLOAD_OP_ADD;
2529 }
2530 offload = dp_netdev_alloc_flow_offload(pmd, flow, op);
2531 offload->match = *match;
2532 offload->actions = xmalloc(actions_len);
2533 memcpy(offload->actions, actions, actions_len);
2534 offload->actions_len = actions_len;
2535
2536 dp_netdev_append_flow_offload(offload);
2537}
2538
72865317 2539static void
1c1e46ed
AW
2540dp_netdev_pmd_remove_flow(struct dp_netdev_pmd_thread *pmd,
2541 struct dp_netdev_flow *flow)
2542 OVS_REQUIRES(pmd->flow_mutex)
72865317 2543{
9f361d6b 2544 struct cmap_node *node = CONST_CAST(struct cmap_node *, &flow->node);
3453b4d6
JS
2545 struct dpcls *cls;
2546 odp_port_t in_port = flow->flow.in_port.odp_port;
2c0ea78f 2547
3453b4d6
JS
2548 cls = dp_netdev_pmd_lookup_dpcls(pmd, in_port);
2549 ovs_assert(cls != NULL);
2550 dpcls_remove(cls, &flow->cr);
1c1e46ed 2551 cmap_remove(&pmd->flow_table, node, dp_netdev_flow_hash(&flow->ufid));
241bad15 2552 if (flow->mark != INVALID_FLOW_MARK) {
02bb2824 2553 queue_netdev_flow_del(pmd, flow);
241bad15 2554 }
9bbf1c3d 2555 flow->dead = true;
ed79f89a
DDP
2556
2557 dp_netdev_flow_unref(flow);
72865317
BP
2558}
2559
2560static void
1c1e46ed 2561dp_netdev_pmd_flow_flush(struct dp_netdev_pmd_thread *pmd)
72865317 2562{
78c8df12 2563 struct dp_netdev_flow *netdev_flow;
72865317 2564
1c1e46ed
AW
2565 ovs_mutex_lock(&pmd->flow_mutex);
2566 CMAP_FOR_EACH (netdev_flow, node, &pmd->flow_table) {
2567 dp_netdev_pmd_remove_flow(pmd, netdev_flow);
72865317 2568 }
1c1e46ed 2569 ovs_mutex_unlock(&pmd->flow_mutex);
72865317
BP
2570}
2571
2572static int
2573dpif_netdev_flow_flush(struct dpif *dpif)
2574{
2575 struct dp_netdev *dp = get_dp_netdev(dpif);
1c1e46ed
AW
2576 struct dp_netdev_pmd_thread *pmd;
2577
2578 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2579 dp_netdev_pmd_flow_flush(pmd);
2580 }
5279f8fd 2581
72865317
BP
2582 return 0;
2583}
2584
b0ec0f27 2585struct dp_netdev_port_state {
e9985d6a 2586 struct hmap_position position;
4c738a8d 2587 char *name;
b0ec0f27
BP
2588};
2589
2590static int
2591dpif_netdev_port_dump_start(const struct dpif *dpif OVS_UNUSED, void **statep)
2592{
2593 *statep = xzalloc(sizeof(struct dp_netdev_port_state));
2594 return 0;
2595}
2596
72865317 2597static int
b0ec0f27 2598dpif_netdev_port_dump_next(const struct dpif *dpif, void *state_,
4c738a8d 2599 struct dpif_port *dpif_port)
72865317 2600{
b0ec0f27 2601 struct dp_netdev_port_state *state = state_;
72865317 2602 struct dp_netdev *dp = get_dp_netdev(dpif);
e9985d6a 2603 struct hmap_node *node;
ff073a71 2604 int retval;
72865317 2605
e9985d6a
DDP
2606 ovs_mutex_lock(&dp->port_mutex);
2607 node = hmap_at_position(&dp->ports, &state->position);
ff073a71
BP
2608 if (node) {
2609 struct dp_netdev_port *port;
5279f8fd 2610
ff073a71
BP
2611 port = CONTAINER_OF(node, struct dp_netdev_port, node);
2612
2613 free(state->name);
2614 state->name = xstrdup(netdev_get_name(port->netdev));
2615 dpif_port->name = state->name;
2616 dpif_port->type = port->type;
35303d71 2617 dpif_port->port_no = port->port_no;
ff073a71
BP
2618
2619 retval = 0;
2620 } else {
2621 retval = EOF;
72865317 2622 }
e9985d6a 2623 ovs_mutex_unlock(&dp->port_mutex);
5279f8fd 2624
ff073a71 2625 return retval;
b0ec0f27
BP
2626}
2627
2628static int
4c738a8d 2629dpif_netdev_port_dump_done(const struct dpif *dpif OVS_UNUSED, void *state_)
b0ec0f27 2630{
4c738a8d
BP
2631 struct dp_netdev_port_state *state = state_;
2632 free(state->name);
b0ec0f27
BP
2633 free(state);
2634 return 0;
72865317
BP
2635}
2636
2637static int
67a4917b 2638dpif_netdev_port_poll(const struct dpif *dpif_, char **devnamep OVS_UNUSED)
72865317
BP
2639{
2640 struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
d33ed218 2641 uint64_t new_port_seq;
5279f8fd
BP
2642 int error;
2643
d33ed218
BP
2644 new_port_seq = seq_read(dpif->dp->port_seq);
2645 if (dpif->last_port_seq != new_port_seq) {
2646 dpif->last_port_seq = new_port_seq;
5279f8fd 2647 error = ENOBUFS;
72865317 2648 } else {
5279f8fd 2649 error = EAGAIN;
72865317 2650 }
5279f8fd
BP
2651
2652 return error;
72865317
BP
2653}
2654
2655static void
2656dpif_netdev_port_poll_wait(const struct dpif *dpif_)
2657{
2658 struct dpif_netdev *dpif = dpif_netdev_cast(dpif_);
5279f8fd 2659
d33ed218 2660 seq_wait(dpif->dp->port_seq, dpif->last_port_seq);
8a4e3a85
BP
2661}
2662
2663static struct dp_netdev_flow *
0de8783a 2664dp_netdev_flow_cast(const struct dpcls_rule *cr)
8a4e3a85
BP
2665{
2666 return cr ? CONTAINER_OF(cr, struct dp_netdev_flow, cr) : NULL;
72865317
BP
2667}
2668
9bbf1c3d
DDP
2669static bool dp_netdev_flow_ref(struct dp_netdev_flow *flow)
2670{
2671 return ovs_refcount_try_ref_rcu(&flow->ref_cnt);
2672}
2673
79df317f
DDP
2674/* netdev_flow_key utilities.
2675 *
2676 * netdev_flow_key is basically a miniflow. We use these functions
2677 * (netdev_flow_key_clone, netdev_flow_key_equal, ...) instead of the miniflow
2678 * functions (miniflow_clone_inline, miniflow_equal, ...), because:
2679 *
2680 * - Since we are dealing exclusively with miniflows created by
2681 * miniflow_extract(), if the map is different the miniflow is different.
2682 * Therefore we can be faster by comparing the map and the miniflow in a
2683 * single memcmp().
5fcff47b 2684 * - These functions can be inlined by the compiler. */
79df317f 2685
361d808d 2686/* Given the number of bits set in miniflow's maps, returns the size of the
caeb4906 2687 * 'netdev_flow_key.mf' */
361d808d
JR
2688static inline size_t
2689netdev_flow_key_size(size_t flow_u64s)
79df317f 2690{
361d808d 2691 return sizeof(struct miniflow) + MINIFLOW_VALUES_SIZE(flow_u64s);
79df317f
DDP
2692}
2693
79df317f
DDP
2694static inline bool
2695netdev_flow_key_equal(const struct netdev_flow_key *a,
0de8783a
JR
2696 const struct netdev_flow_key *b)
2697{
caeb4906
JR
2698 /* 'b->len' may be not set yet. */
2699 return a->hash == b->hash && !memcmp(&a->mf, &b->mf, a->len);
0de8783a
JR
2700}
2701
2702/* Used to compare 'netdev_flow_key' in the exact match cache to a miniflow.
d79a39fe 2703 * The maps are compared bitwise, so both 'key->mf' and 'mf' must have been
0de8783a
JR
2704 * generated by miniflow_extract. */
2705static inline bool
2706netdev_flow_key_equal_mf(const struct netdev_flow_key *key,
2707 const struct miniflow *mf)
79df317f 2708{
caeb4906 2709 return !memcmp(&key->mf, mf, key->len);
79df317f
DDP
2710}
2711
2712static inline void
2713netdev_flow_key_clone(struct netdev_flow_key *dst,
0de8783a
JR
2714 const struct netdev_flow_key *src)
2715{
caeb4906
JR
2716 memcpy(dst, src,
2717 offsetof(struct netdev_flow_key, mf) + src->len);
0de8783a
JR
2718}
2719
0de8783a
JR
2720/* Initialize a netdev_flow_key 'mask' from 'match'. */
2721static inline void
2722netdev_flow_mask_init(struct netdev_flow_key *mask,
2723 const struct match *match)
2724{
09b0fa9c 2725 uint64_t *dst = miniflow_values(&mask->mf);
5fcff47b 2726 struct flowmap fmap;
0de8783a 2727 uint32_t hash = 0;
5fcff47b 2728 size_t idx;
0de8783a
JR
2729
2730 /* Only check masks that make sense for the flow. */
5fcff47b
JR
2731 flow_wc_map(&match->flow, &fmap);
2732 flowmap_init(&mask->mf.map);
0de8783a 2733
5fcff47b
JR
2734 FLOWMAP_FOR_EACH_INDEX(idx, fmap) {
2735 uint64_t mask_u64 = flow_u64_value(&match->wc.masks, idx);
0de8783a 2736
5fcff47b
JR
2737 if (mask_u64) {
2738 flowmap_set(&mask->mf.map, idx, 1);
2739 *dst++ = mask_u64;
2740 hash = hash_add64(hash, mask_u64);
0de8783a 2741 }
0de8783a
JR
2742 }
2743
5fcff47b 2744 map_t map;
0de8783a 2745
5fcff47b
JR
2746 FLOWMAP_FOR_EACH_MAP (map, mask->mf.map) {
2747 hash = hash_add64(hash, map);
2748 }
0de8783a 2749
5fcff47b 2750 size_t n = dst - miniflow_get_values(&mask->mf);
0de8783a 2751
d70e8c28 2752 mask->hash = hash_finish(hash, n * 8);
0de8783a
JR
2753 mask->len = netdev_flow_key_size(n);
2754}
2755
361d808d 2756/* Initializes 'dst' as a copy of 'flow' masked with 'mask'. */
0de8783a
JR
2757static inline void
2758netdev_flow_key_init_masked(struct netdev_flow_key *dst,
2759 const struct flow *flow,
2760 const struct netdev_flow_key *mask)
79df317f 2761{
09b0fa9c
JR
2762 uint64_t *dst_u64 = miniflow_values(&dst->mf);
2763 const uint64_t *mask_u64 = miniflow_get_values(&mask->mf);
0de8783a 2764 uint32_t hash = 0;
d70e8c28 2765 uint64_t value;
0de8783a
JR
2766
2767 dst->len = mask->len;
361d808d 2768 dst->mf = mask->mf; /* Copy maps. */
0de8783a 2769
5fcff47b 2770 FLOW_FOR_EACH_IN_MAPS(value, flow, mask->mf.map) {
d70e8c28
JR
2771 *dst_u64 = value & *mask_u64++;
2772 hash = hash_add64(hash, *dst_u64++);
0de8783a 2773 }
09b0fa9c
JR
2774 dst->hash = hash_finish(hash,
2775 (dst_u64 - miniflow_get_values(&dst->mf)) * 8);
0de8783a
JR
2776}
2777
9bbf1c3d
DDP
2778static inline bool
2779emc_entry_alive(struct emc_entry *ce)
2780{
2781 return ce->flow && !ce->flow->dead;
2782}
2783
2784static void
2785emc_clear_entry(struct emc_entry *ce)
2786{
2787 if (ce->flow) {
2788 dp_netdev_flow_unref(ce->flow);
2789 ce->flow = NULL;
2790 }
2791}
2792
2793static inline void
2794emc_change_entry(struct emc_entry *ce, struct dp_netdev_flow *flow,
0de8783a 2795 const struct netdev_flow_key *key)
9bbf1c3d
DDP
2796{
2797 if (ce->flow != flow) {
2798 if (ce->flow) {
2799 dp_netdev_flow_unref(ce->flow);
2800 }
2801
2802 if (dp_netdev_flow_ref(flow)) {
2803 ce->flow = flow;
2804 } else {
2805 ce->flow = NULL;
2806 }
2807 }
0de8783a
JR
2808 if (key) {
2809 netdev_flow_key_clone(&ce->key, key);
9bbf1c3d
DDP
2810 }
2811}
2812
2813static inline void
0de8783a 2814emc_insert(struct emc_cache *cache, const struct netdev_flow_key *key,
9bbf1c3d
DDP
2815 struct dp_netdev_flow *flow)
2816{
2817 struct emc_entry *to_be_replaced = NULL;
2818 struct emc_entry *current_entry;
2819
0de8783a
JR
2820 EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, key->hash) {
2821 if (netdev_flow_key_equal(&current_entry->key, key)) {
9bbf1c3d 2822 /* We found the entry with the 'mf' miniflow */
0de8783a 2823 emc_change_entry(current_entry, flow, NULL);
9bbf1c3d
DDP
2824 return;
2825 }
2826
2827 /* Replacement policy: put the flow in an empty (not alive) entry, or
2828 * in the first entry where it can be */
2829 if (!to_be_replaced
2830 || (emc_entry_alive(to_be_replaced)
2831 && !emc_entry_alive(current_entry))
0de8783a 2832 || current_entry->key.hash < to_be_replaced->key.hash) {
9bbf1c3d
DDP
2833 to_be_replaced = current_entry;
2834 }
2835 }
2836 /* We didn't find the miniflow in the cache.
2837 * The 'to_be_replaced' entry is where the new flow will be stored */
2838
0de8783a 2839 emc_change_entry(to_be_replaced, flow, key);
9bbf1c3d
DDP
2840}
2841
4c30b246
CL
2842static inline void
2843emc_probabilistic_insert(struct dp_netdev_pmd_thread *pmd,
2844 const struct netdev_flow_key *key,
2845 struct dp_netdev_flow *flow)
2846{
2847 /* Insert an entry into the EMC based on probability value 'min'. By
2848 * default the value is UINT32_MAX / 100 which yields an insertion
2849 * probability of 1/100 ie. 1% */
2850
2fbadeb6 2851 uint32_t min = pmd->ctx.emc_insert_min;
4c30b246 2852
656238ee 2853 if (min && random_uint32() <= min) {
60d8ccae 2854 emc_insert(&(pmd->flow_cache).emc_cache, key, flow);
4c30b246
CL
2855 }
2856}
2857
9bbf1c3d 2858static inline struct dp_netdev_flow *
0de8783a 2859emc_lookup(struct emc_cache *cache, const struct netdev_flow_key *key)
9bbf1c3d
DDP
2860{
2861 struct emc_entry *current_entry;
2862
0de8783a
JR
2863 EMC_FOR_EACH_POS_WITH_HASH(cache, current_entry, key->hash) {
2864 if (current_entry->key.hash == key->hash
2865 && emc_entry_alive(current_entry)
2866 && netdev_flow_key_equal_mf(&current_entry->key, &key->mf)) {
9bbf1c3d 2867
0de8783a 2868 /* We found the entry with the 'key->mf' miniflow */
9bbf1c3d
DDP
2869 return current_entry->flow;
2870 }
2871 }
2872
2873 return NULL;
2874}
2875
60d8ccae
YW
2876static inline const struct cmap_node *
2877smc_entry_get(struct dp_netdev_pmd_thread *pmd, const uint32_t hash)
2878{
2879 struct smc_cache *cache = &(pmd->flow_cache).smc_cache;
2880 struct smc_bucket *bucket = &cache->buckets[hash & SMC_MASK];
2881 uint16_t sig = hash >> 16;
2882 uint16_t index = UINT16_MAX;
2883
2884 for (int i = 0; i < SMC_ENTRY_PER_BUCKET; i++) {
2885 if (bucket->sig[i] == sig) {
2886 index = bucket->flow_idx[i];
2887 break;
2888 }
2889 }
2890 if (index != UINT16_MAX) {
2891 return cmap_find_by_index(&pmd->flow_table, index);
2892 }
2893 return NULL;
2894}
2895
2896static void
2897smc_clear_entry(struct smc_bucket *b, int idx)
2898{
2899 b->flow_idx[idx] = UINT16_MAX;
2900}
2901
2902/* Insert the flow_table index into SMC. Insertion may fail when 1) SMC is
2903 * turned off, 2) the flow_table index is larger than uint16_t can handle.
2904 * If there is already an SMC entry having same signature, the index will be
2905 * updated. If there is no existing entry, but an empty entry is available,
2906 * the empty entry will be taken. If no empty entry or existing same signature,
2907 * a random entry from the hashed bucket will be picked. */
2908static inline void
2909smc_insert(struct dp_netdev_pmd_thread *pmd,
2910 const struct netdev_flow_key *key,
2911 uint32_t hash)
2912{
2913 struct smc_cache *smc_cache = &(pmd->flow_cache).smc_cache;
2914 struct smc_bucket *bucket = &smc_cache->buckets[key->hash & SMC_MASK];
2915 uint16_t index;
2916 uint32_t cmap_index;
2917 bool smc_enable_db;
2918 int i;
2919
2920 atomic_read_relaxed(&pmd->dp->smc_enable_db, &smc_enable_db);
2921 if (!smc_enable_db) {
2922 return;
2923 }
2924
2925 cmap_index = cmap_find_index(&pmd->flow_table, hash);
2926 index = (cmap_index >= UINT16_MAX) ? UINT16_MAX : (uint16_t)cmap_index;
2927
2928 /* If the index is larger than SMC can handle (uint16_t), we don't
2929 * insert */
2930 if (index == UINT16_MAX) {
2931 return;
2932 }
2933
2934 /* If an entry with same signature already exists, update the index */
2935 uint16_t sig = key->hash >> 16;
2936 for (i = 0; i < SMC_ENTRY_PER_BUCKET; i++) {
2937 if (bucket->sig[i] == sig) {
2938 bucket->flow_idx[i] = index;
2939 return;
2940 }
2941 }
2942 /* If there is an empty entry, occupy it. */
2943 for (i = 0; i < SMC_ENTRY_PER_BUCKET; i++) {
2944 if (bucket->flow_idx[i] == UINT16_MAX) {
2945 bucket->sig[i] = sig;
2946 bucket->flow_idx[i] = index;
2947 return;
2948 }
2949 }
2950 /* Otherwise, pick a random entry. */
2951 i = random_uint32() % SMC_ENTRY_PER_BUCKET;
2952 bucket->sig[i] = sig;
2953 bucket->flow_idx[i] = index;
2954}
2955
72865317 2956static struct dp_netdev_flow *
3453b4d6
JS
2957dp_netdev_pmd_lookup_flow(struct dp_netdev_pmd_thread *pmd,
2958 const struct netdev_flow_key *key,
2959 int *lookup_num_p)
2c0ea78f 2960{
3453b4d6 2961 struct dpcls *cls;
0de8783a 2962 struct dpcls_rule *rule;
f825fdd4
BP
2963 odp_port_t in_port = u32_to_odp(MINIFLOW_GET_U32(&key->mf,
2964 in_port.odp_port));
3453b4d6 2965 struct dp_netdev_flow *netdev_flow = NULL;
2c0ea78f 2966
3453b4d6
JS
2967 cls = dp_netdev_pmd_lookup_dpcls(pmd, in_port);
2968 if (OVS_LIKELY(cls)) {
60d8ccae 2969 dpcls_lookup(cls, &key, &rule, 1, lookup_num_p);
3453b4d6
JS
2970 netdev_flow = dp_netdev_flow_cast(rule);
2971 }
8a4e3a85 2972 return netdev_flow;
2c0ea78f
GS
2973}
2974
2975static struct dp_netdev_flow *
1c1e46ed
AW
2976dp_netdev_pmd_find_flow(const struct dp_netdev_pmd_thread *pmd,
2977 const ovs_u128 *ufidp, const struct nlattr *key,
2978 size_t key_len)
72865317 2979{
1763b4b8 2980 struct dp_netdev_flow *netdev_flow;
70e5ed6f
JS
2981 struct flow flow;
2982 ovs_u128 ufid;
2983
2984 /* If a UFID is not provided, determine one based on the key. */
2985 if (!ufidp && key && key_len
f0fb825a 2986 && !dpif_netdev_flow_from_nlattrs(key, key_len, &flow, false)) {
1c1e46ed 2987 dpif_flow_hash(pmd->dp->dpif, &flow, sizeof flow, &ufid);
70e5ed6f
JS
2988 ufidp = &ufid;
2989 }
72865317 2990
70e5ed6f
JS
2991 if (ufidp) {
2992 CMAP_FOR_EACH_WITH_HASH (netdev_flow, node, dp_netdev_flow_hash(ufidp),
1c1e46ed 2993 &pmd->flow_table) {
2ff8484b 2994 if (ovs_u128_equals(netdev_flow->ufid, *ufidp)) {
70e5ed6f
JS
2995 return netdev_flow;
2996 }
72865317
BP
2997 }
2998 }
8a4e3a85 2999
72865317
BP
3000 return NULL;
3001}
3002
3003static void
eb94da30 3004get_dpif_flow_stats(const struct dp_netdev_flow *netdev_flow_,
1763b4b8 3005 struct dpif_flow_stats *stats)
feebdea2 3006{
eb94da30
DDP
3007 struct dp_netdev_flow *netdev_flow;
3008 unsigned long long n;
3009 long long used;
3010 uint16_t flags;
3011
3012 netdev_flow = CONST_CAST(struct dp_netdev_flow *, netdev_flow_);
3013
3014 atomic_read_relaxed(&netdev_flow->stats.packet_count, &n);
3015 stats->n_packets = n;
3016 atomic_read_relaxed(&netdev_flow->stats.byte_count, &n);
3017 stats->n_bytes = n;
3018 atomic_read_relaxed(&netdev_flow->stats.used, &used);
3019 stats->used = used;
3020 atomic_read_relaxed(&netdev_flow->stats.tcp_flags, &flags);
3021 stats->tcp_flags = flags;
72865317
BP
3022}
3023
7af12bd7
JS
3024/* Converts to the dpif_flow format, using 'key_buf' and 'mask_buf' for
3025 * storing the netlink-formatted key/mask. 'key_buf' may be the same as
3026 * 'mask_buf'. Actions will be returned without copying, by relying on RCU to
3027 * protect them. */
6fe09f8c 3028static void
70e5ed6f 3029dp_netdev_flow_to_dpif_flow(const struct dp_netdev_flow *netdev_flow,
7af12bd7 3030 struct ofpbuf *key_buf, struct ofpbuf *mask_buf,
64bb477f 3031 struct dpif_flow *flow, bool terse)
6fe09f8c 3032{
64bb477f
JS
3033 if (terse) {
3034 memset(flow, 0, sizeof *flow);
3035 } else {
3036 struct flow_wildcards wc;
3037 struct dp_netdev_actions *actions;
3038 size_t offset;
5262eea1
JG
3039 struct odp_flow_key_parms odp_parms = {
3040 .flow = &netdev_flow->flow,
3041 .mask = &wc.masks,
2494ccd7 3042 .support = dp_netdev_support,
5262eea1 3043 };
64bb477f
JS
3044
3045 miniflow_expand(&netdev_flow->cr.mask->mf, &wc.masks);
f4b835bb
JR
3046 /* in_port is exact matched, but we have left it out from the mask for
3047 * optimnization reasons. Add in_port back to the mask. */
3048 wc.masks.in_port.odp_port = ODPP_NONE;
64bb477f
JS
3049
3050 /* Key */
6fd6ed71 3051 offset = key_buf->size;
64bb477f 3052 flow->key = ofpbuf_tail(key_buf);
5262eea1 3053 odp_flow_key_from_flow(&odp_parms, key_buf);
6fd6ed71 3054 flow->key_len = key_buf->size - offset;
64bb477f
JS
3055
3056 /* Mask */
6fd6ed71 3057 offset = mask_buf->size;
64bb477f 3058 flow->mask = ofpbuf_tail(mask_buf);
ec1f6f32 3059 odp_parms.key_buf = key_buf;
5262eea1 3060 odp_flow_key_from_mask(&odp_parms, mask_buf);
6fd6ed71 3061 flow->mask_len = mask_buf->size - offset;
64bb477f
JS
3062
3063 /* Actions */
3064 actions = dp_netdev_flow_get_actions(netdev_flow);
3065 flow->actions = actions->actions;
3066 flow->actions_len = actions->size;
3067 }
6fe09f8c 3068
70e5ed6f
JS
3069 flow->ufid = netdev_flow->ufid;
3070 flow->ufid_present = true;
1c1e46ed 3071 flow->pmd_id = netdev_flow->pmd_id;
6fe09f8c 3072 get_dpif_flow_stats(netdev_flow, &flow->stats);
0d6b401c
GT
3073
3074 flow->attrs.offloaded = false;
3075 flow->attrs.dp_layer = "ovs";
6fe09f8c
JS
3076}
3077
36956a7d 3078static int
8c301900
JR
3079dpif_netdev_mask_from_nlattrs(const struct nlattr *key, uint32_t key_len,
3080 const struct nlattr *mask_key,
3081 uint32_t mask_key_len, const struct flow *flow,
f0fb825a 3082 struct flow_wildcards *wc, bool probe)
8c301900 3083{
ca8d3442
DDP
3084 enum odp_key_fitness fitness;
3085
d40533fc 3086 fitness = odp_flow_key_to_mask(mask_key, mask_key_len, wc, flow, NULL);
ca8d3442 3087 if (fitness) {
f0fb825a
EG
3088 if (!probe) {
3089 /* This should not happen: it indicates that
3090 * odp_flow_key_from_mask() and odp_flow_key_to_mask()
3091 * disagree on the acceptable form of a mask. Log the problem
3092 * as an error, with enough details to enable debugging. */
3093 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3094
3095 if (!VLOG_DROP_ERR(&rl)) {
3096 struct ds s;
3097
3098 ds_init(&s);
3099 odp_flow_format(key, key_len, mask_key, mask_key_len, NULL, &s,
3100 true);
3101 VLOG_ERR("internal error parsing flow mask %s (%s)",
3102 ds_cstr(&s), odp_key_fitness_to_string(fitness));
3103 ds_destroy(&s);
3104 }
8c301900 3105 }
ca8d3442
DDP
3106
3107 return EINVAL;
8c301900
JR
3108 }
3109
3110 return 0;
3111}
3112
3113static int
3114dpif_netdev_flow_from_nlattrs(const struct nlattr *key, uint32_t key_len,
f0fb825a 3115 struct flow *flow, bool probe)
36956a7d 3116{
d40533fc 3117 if (odp_flow_key_to_flow(key, key_len, flow, NULL)) {
f0fb825a
EG
3118 if (!probe) {
3119 /* This should not happen: it indicates that
3120 * odp_flow_key_from_flow() and odp_flow_key_to_flow() disagree on
3121 * the acceptable form of a flow. Log the problem as an error,
3122 * with enough details to enable debugging. */
3123 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3124
3125 if (!VLOG_DROP_ERR(&rl)) {
3126 struct ds s;
3127
3128 ds_init(&s);
3129 odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
3130 VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
3131 ds_destroy(&s);
3132 }
36956a7d
BP
3133 }
3134
3135 return EINVAL;
3136 }
3137
5cf3edb3 3138 if (flow->ct_state & DP_NETDEV_CS_UNSUPPORTED_MASK) {
07659514
JS
3139 return EINVAL;
3140 }
3141
36956a7d
BP
3142 return 0;
3143}
3144
72865317 3145static int
6fe09f8c 3146dpif_netdev_flow_get(const struct dpif *dpif, const struct dpif_flow_get *get)
72865317
BP
3147{
3148 struct dp_netdev *dp = get_dp_netdev(dpif);
1763b4b8 3149 struct dp_netdev_flow *netdev_flow;
1c1e46ed 3150 struct dp_netdev_pmd_thread *pmd;
c673049c
IM
3151 struct hmapx to_find = HMAPX_INITIALIZER(&to_find);
3152 struct hmapx_node *node;
3153 int error = EINVAL;
3154
3155 if (get->pmd_id == PMD_ID_NULL) {
3156 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3157 if (dp_netdev_pmd_try_ref(pmd) && !hmapx_add(&to_find, pmd)) {
3158 dp_netdev_pmd_unref(pmd);
3159 }
3160 }
3161 } else {
3162 pmd = dp_netdev_get_pmd(dp, get->pmd_id);
3163 if (!pmd) {
3164 goto out;
3165 }
3166 hmapx_add(&to_find, pmd);
1c1e46ed
AW
3167 }
3168
c673049c
IM
3169 if (!hmapx_count(&to_find)) {
3170 goto out;
72865317 3171 }
1c1e46ed 3172
c673049c
IM
3173 HMAPX_FOR_EACH (node, &to_find) {
3174 pmd = (struct dp_netdev_pmd_thread *) node->data;
3175 netdev_flow = dp_netdev_pmd_find_flow(pmd, get->ufid, get->key,
3176 get->key_len);
3177 if (netdev_flow) {
3178 dp_netdev_flow_to_dpif_flow(netdev_flow, get->buffer, get->buffer,
3179 get->flow, false);
3180 error = 0;
3181 break;
3182 } else {
3183 error = ENOENT;
3184 }
3185 }
bc4a05c6 3186
c673049c
IM
3187 HMAPX_FOR_EACH (node, &to_find) {
3188 pmd = (struct dp_netdev_pmd_thread *) node->data;
3189 dp_netdev_pmd_unref(pmd);
3190 }
3191out:
3192 hmapx_destroy(&to_find);
5279f8fd 3193 return error;
72865317
BP
3194}
3195
241bad15
YL
3196static void
3197dp_netdev_get_mega_ufid(const struct match *match, ovs_u128 *mega_ufid)
3198{
3199 struct flow masked_flow;
3200 size_t i;
3201
3202 for (i = 0; i < sizeof(struct flow); i++) {
3203 ((uint8_t *)&masked_flow)[i] = ((uint8_t *)&match->flow)[i] &
3204 ((uint8_t *)&match->wc)[i];
3205 }
3206 dpif_flow_hash(NULL, &masked_flow, sizeof(struct flow), mega_ufid);
3207}
3208
0de8783a 3209static struct dp_netdev_flow *
1c1e46ed
AW
3210dp_netdev_flow_add(struct dp_netdev_pmd_thread *pmd,
3211 struct match *match, const ovs_u128 *ufid,
ae2ceebd 3212 const struct nlattr *actions, size_t actions_len)
1c1e46ed 3213 OVS_REQUIRES(pmd->flow_mutex)
72865317 3214{
0de8783a
JR
3215 struct dp_netdev_flow *flow;
3216 struct netdev_flow_key mask;
3453b4d6 3217 struct dpcls *cls;
f4b835bb
JR
3218
3219 /* Make sure in_port is exact matched before we read it. */
3220 ovs_assert(match->wc.masks.in_port.odp_port == ODPP_NONE);
3453b4d6 3221 odp_port_t in_port = match->flow.in_port.odp_port;
ed79f89a 3222
f4b835bb
JR
3223 /* As we select the dpcls based on the port number, each netdev flow
3224 * belonging to the same dpcls will have the same odp_port value.
3225 * For performance reasons we wildcard odp_port here in the mask. In the
3226 * typical case dp_hash is also wildcarded, and the resulting 8-byte
3227 * chunk {dp_hash, in_port} will be ignored by netdev_flow_mask_init() and
3228 * will not be part of the subtable mask.
3229 * This will speed up the hash computation during dpcls_lookup() because
3230 * there is one less call to hash_add64() in this case. */
3231 match->wc.masks.in_port.odp_port = 0;
0de8783a 3232 netdev_flow_mask_init(&mask, match);
f4b835bb
JR
3233 match->wc.masks.in_port.odp_port = ODPP_NONE;
3234
0de8783a 3235 /* Make sure wc does not have metadata. */
5fcff47b
JR
3236 ovs_assert(!FLOWMAP_HAS_FIELD(&mask.mf.map, metadata)
3237 && !FLOWMAP_HAS_FIELD(&mask.mf.map, regs));
679ba04c 3238
0de8783a 3239 /* Do not allocate extra space. */
caeb4906 3240 flow = xmalloc(sizeof *flow - sizeof flow->cr.flow.mf + mask.len);
1c1e46ed 3241 memset(&flow->stats, 0, sizeof flow->stats);
0de8783a 3242 flow->dead = false;
11e5cf1f 3243 flow->batch = NULL;
241bad15 3244 flow->mark = INVALID_FLOW_MARK;
bd5131ba 3245 *CONST_CAST(unsigned *, &flow->pmd_id) = pmd->core_id;
0de8783a 3246 *CONST_CAST(struct flow *, &flow->flow) = match->flow;
70e5ed6f 3247 *CONST_CAST(ovs_u128 *, &flow->ufid) = *ufid;
0de8783a 3248 ovs_refcount_init(&flow->ref_cnt);
0de8783a 3249 ovsrcu_set(&flow->actions, dp_netdev_actions_create(actions, actions_len));
2c0ea78f 3250
241bad15 3251 dp_netdev_get_mega_ufid(match, CONST_CAST(ovs_u128 *, &flow->mega_ufid));
0de8783a 3252 netdev_flow_key_init_masked(&flow->cr.flow, &match->flow, &mask);
3453b4d6 3253
f4b835bb 3254 /* Select dpcls for in_port. Relies on in_port to be exact match. */
3453b4d6
JS
3255 cls = dp_netdev_pmd_find_dpcls(pmd, in_port);
3256 dpcls_insert(cls, &flow->cr, &mask);
72865317 3257
4c75aaab
EJ
3258 cmap_insert(&pmd->flow_table, CONST_CAST(struct cmap_node *, &flow->node),
3259 dp_netdev_flow_hash(&flow->ufid));
3260
02bb2824 3261 queue_netdev_flow_put(pmd, flow, match, actions, actions_len);
241bad15 3262
beb75a40 3263 if (OVS_UNLIKELY(!VLOG_DROP_DBG((&upcall_rl)))) {
623540e4 3264 struct ds ds = DS_EMPTY_INITIALIZER;
9044f2c1
JG
3265 struct ofpbuf key_buf, mask_buf;
3266 struct odp_flow_key_parms odp_parms = {
3267 .flow = &match->flow,
3268 .mask = &match->wc.masks,
3269 .support = dp_netdev_support,
3270 };
3271
3272 ofpbuf_init(&key_buf, 0);
3273 ofpbuf_init(&mask_buf, 0);
623540e4 3274
9044f2c1
JG
3275 odp_flow_key_from_flow(&odp_parms, &key_buf);
3276 odp_parms.key_buf = &key_buf;
3277 odp_flow_key_from_mask(&odp_parms, &mask_buf);
0de8783a 3278
623540e4 3279 ds_put_cstr(&ds, "flow_add: ");
70e5ed6f
JS
3280 odp_format_ufid(ufid, &ds);
3281 ds_put_cstr(&ds, " ");
9044f2c1
JG
3282 odp_flow_format(key_buf.data, key_buf.size,
3283 mask_buf.data, mask_buf.size,
3284 NULL, &ds, false);
623540e4 3285 ds_put_cstr(&ds, ", actions:");
0722f341 3286 format_odp_actions(&ds, actions, actions_len, NULL);
623540e4 3287
beb75a40 3288 VLOG_DBG("%s", ds_cstr(&ds));
623540e4 3289
9044f2c1
JG
3290 ofpbuf_uninit(&key_buf);
3291 ofpbuf_uninit(&mask_buf);
beb75a40
JS
3292
3293 /* Add a printout of the actual match installed. */
3294 struct match m;
3295 ds_clear(&ds);
3296 ds_put_cstr(&ds, "flow match: ");
3297 miniflow_expand(&flow->cr.flow.mf, &m.flow);
3298 miniflow_expand(&flow->cr.mask->mf, &m.wc.masks);
b2f4b622 3299 memset(&m.tun_md, 0, sizeof m.tun_md);
beb75a40
JS
3300 match_format(&m, NULL, &ds, OFP_DEFAULT_PRIORITY);
3301
3302 VLOG_DBG("%s", ds_cstr(&ds));
3303
623540e4
EJ
3304 ds_destroy(&ds);
3305 }
3306
0de8783a 3307 return flow;
72865317
BP
3308}
3309
72865317 3310static int
f5d317a1
DDP
3311flow_put_on_pmd(struct dp_netdev_pmd_thread *pmd,
3312 struct netdev_flow_key *key,
3313 struct match *match,
3314 ovs_u128 *ufid,
3315 const struct dpif_flow_put *put,
3316 struct dpif_flow_stats *stats)
72865317 3317{
1763b4b8 3318 struct dp_netdev_flow *netdev_flow;
f5d317a1 3319 int error = 0;
72865317 3320
f5d317a1
DDP
3321 if (stats) {
3322 memset(stats, 0, sizeof *stats);
70e5ed6f
JS
3323 }
3324
1c1e46ed 3325 ovs_mutex_lock(&pmd->flow_mutex);
f5d317a1 3326 netdev_flow = dp_netdev_pmd_lookup_flow(pmd, key, NULL);
1763b4b8 3327 if (!netdev_flow) {
89625d1e 3328 if (put->flags & DPIF_FP_CREATE) {
1c1e46ed 3329 if (cmap_count(&pmd->flow_table) < MAX_FLOWS) {
f5d317a1 3330 dp_netdev_flow_add(pmd, match, ufid, put->actions,
70e5ed6f 3331 put->actions_len);
0de8783a 3332 error = 0;
72865317 3333 } else {
5279f8fd 3334 error = EFBIG;
72865317
BP
3335 }
3336 } else {
5279f8fd 3337 error = ENOENT;
72865317
BP
3338 }
3339 } else {
beb75a40 3340 if (put->flags & DPIF_FP_MODIFY) {
8a4e3a85
BP
3341 struct dp_netdev_actions *new_actions;
3342 struct dp_netdev_actions *old_actions;
3343
3344 new_actions = dp_netdev_actions_create(put->actions,
3345 put->actions_len);
3346
61e7deb1
BP
3347 old_actions = dp_netdev_flow_get_actions(netdev_flow);
3348 ovsrcu_set(&netdev_flow->actions, new_actions);
679ba04c 3349
02bb2824
YL
3350 queue_netdev_flow_put(pmd, netdev_flow, match,
3351 put->actions, put->actions_len);
241bad15 3352
f5d317a1
DDP
3353 if (stats) {
3354 get_dpif_flow_stats(netdev_flow, stats);
a84cb64a
BP
3355 }
3356 if (put->flags & DPIF_FP_ZERO_STATS) {
97447f55
DDP
3357 /* XXX: The userspace datapath uses thread local statistics
3358 * (for flows), which should be updated only by the owning
3359 * thread. Since we cannot write on stats memory here,
3360 * we choose not to support this flag. Please note:
3361 * - This feature is currently used only by dpctl commands with
3362 * option --clear.
3363 * - Should the need arise, this operation can be implemented
3364 * by keeping a base value (to be update here) for each
3365 * counter, and subtracting it before outputting the stats */
3366 error = EOPNOTSUPP;
72865317 3367 }
8a4e3a85 3368
61e7deb1 3369 ovsrcu_postpone(dp_netdev_actions_free, old_actions);
2c0ea78f 3370 } else if (put->flags & DPIF_FP_CREATE) {
5279f8fd 3371 error = EEXIST;
2c0ea78f
GS
3372 } else {
3373 /* Overlapping flow. */
3374 error = EINVAL;
72865317
BP
3375 }
3376 }
1c1e46ed 3377 ovs_mutex_unlock(&pmd->flow_mutex);
5279f8fd 3378 return error;
72865317
BP
3379}
3380
72865317 3381static int
f5d317a1 3382dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
72865317
BP
3383{
3384 struct dp_netdev *dp = get_dp_netdev(dpif);
beb75a40 3385 struct netdev_flow_key key, mask;
1c1e46ed 3386 struct dp_netdev_pmd_thread *pmd;
f5d317a1
DDP
3387 struct match match;
3388 ovs_u128 ufid;
3389 int error;
f0fb825a 3390 bool probe = put->flags & DPIF_FP_PROBE;
72865317 3391
f5d317a1
DDP
3392 if (put->stats) {
3393 memset(put->stats, 0, sizeof *put->stats);
3394 }
f0fb825a
EG
3395 error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &match.flow,
3396 probe);
f5d317a1
DDP
3397 if (error) {
3398 return error;
3399 }
3400 error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
3401 put->mask, put->mask_len,
f0fb825a 3402 &match.flow, &match.wc, probe);
f5d317a1
DDP
3403 if (error) {
3404 return error;
1c1e46ed
AW
3405 }
3406
f5d317a1
DDP
3407 if (put->ufid) {
3408 ufid = *put->ufid;
3409 } else {
3410 dpif_flow_hash(dpif, &match.flow, sizeof match.flow, &ufid);
3411 }
3412
35fe9efb
IM
3413 /* The Netlink encoding of datapath flow keys cannot express
3414 * wildcarding the presence of a VLAN tag. Instead, a missing VLAN
3415 * tag is interpreted as exact match on the fact that there is no
3416 * VLAN. Unless we refactor a lot of code that translates between
3417 * Netlink and struct flow representations, we have to do the same
3418 * here. This must be in sync with 'match' in handle_packet_upcall(). */
3419 if (!match.wc.masks.vlans[0].tci) {
3420 match.wc.masks.vlans[0].tci = htons(0xffff);
3421 }
3422
f5d317a1 3423 /* Must produce a netdev_flow_key for lookup.
beb75a40
JS
3424 * Use the same method as employed to create the key when adding
3425 * the flow to the dplcs to make sure they match. */
3426 netdev_flow_mask_init(&mask, &match);
3427 netdev_flow_key_init_masked(&key, &match.flow, &mask);
f5d317a1
DDP
3428
3429 if (put->pmd_id == PMD_ID_NULL) {
3430 if (cmap_count(&dp->poll_threads) == 0) {
3431 return EINVAL;
3432 }
3433 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3434 struct dpif_flow_stats pmd_stats;
3435 int pmd_error;
3436
3437 pmd_error = flow_put_on_pmd(pmd, &key, &match, &ufid, put,
3438 &pmd_stats);
3439 if (pmd_error) {
3440 error = pmd_error;
3441 } else if (put->stats) {
3442 put->stats->n_packets += pmd_stats.n_packets;
3443 put->stats->n_bytes += pmd_stats.n_bytes;
3444 put->stats->used = MAX(put->stats->used, pmd_stats.used);
3445 put->stats->tcp_flags |= pmd_stats.tcp_flags;
3446 }
3447 }
3448 } else {
3449 pmd = dp_netdev_get_pmd(dp, put->pmd_id);
3450 if (!pmd) {
3451 return EINVAL;
3452 }
3453 error = flow_put_on_pmd(pmd, &key, &match, &ufid, put, put->stats);
3454 dp_netdev_pmd_unref(pmd);
3455 }
3456
3457 return error;
3458}
3459
3460static int
3461flow_del_on_pmd(struct dp_netdev_pmd_thread *pmd,
3462 struct dpif_flow_stats *stats,
3463 const struct dpif_flow_del *del)
3464{
3465 struct dp_netdev_flow *netdev_flow;
3466 int error = 0;
3467
1c1e46ed
AW
3468 ovs_mutex_lock(&pmd->flow_mutex);
3469 netdev_flow = dp_netdev_pmd_find_flow(pmd, del->ufid, del->key,
3470 del->key_len);
1763b4b8 3471 if (netdev_flow) {
f5d317a1
DDP
3472 if (stats) {
3473 get_dpif_flow_stats(netdev_flow, stats);
feebdea2 3474 }
1c1e46ed 3475 dp_netdev_pmd_remove_flow(pmd, netdev_flow);
72865317 3476 } else {
5279f8fd 3477 error = ENOENT;
72865317 3478 }
1c1e46ed 3479 ovs_mutex_unlock(&pmd->flow_mutex);
f5d317a1
DDP
3480
3481 return error;
3482}
3483
3484static int
3485dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
3486{
3487 struct dp_netdev *dp = get_dp_netdev(dpif);
3488 struct dp_netdev_pmd_thread *pmd;
3489 int error = 0;
3490
3491 if (del->stats) {
3492 memset(del->stats, 0, sizeof *del->stats);
3493 }
3494
3495 if (del->pmd_id == PMD_ID_NULL) {
3496 if (cmap_count(&dp->poll_threads) == 0) {
3497 return EINVAL;
3498 }
3499 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3500 struct dpif_flow_stats pmd_stats;
3501 int pmd_error;
3502
3503 pmd_error = flow_del_on_pmd(pmd, &pmd_stats, del);
3504 if (pmd_error) {
3505 error = pmd_error;
3506 } else if (del->stats) {
3507 del->stats->n_packets += pmd_stats.n_packets;
3508 del->stats->n_bytes += pmd_stats.n_bytes;
3509 del->stats->used = MAX(del->stats->used, pmd_stats.used);
3510 del->stats->tcp_flags |= pmd_stats.tcp_flags;
3511 }
3512 }
3513 } else {
3514 pmd = dp_netdev_get_pmd(dp, del->pmd_id);
3515 if (!pmd) {
3516 return EINVAL;
3517 }
3518 error = flow_del_on_pmd(pmd, del->stats, del);
3519 dp_netdev_pmd_unref(pmd);
3520 }
3521
5279f8fd
BP
3522
3523 return error;
72865317
BP
3524}
3525
ac64794a
BP
3526struct dpif_netdev_flow_dump {
3527 struct dpif_flow_dump up;
1c1e46ed
AW
3528 struct cmap_position poll_thread_pos;
3529 struct cmap_position flow_pos;
3530 struct dp_netdev_pmd_thread *cur_pmd;
d2ad7ef1
JS
3531 int status;
3532 struct ovs_mutex mutex;
e723fd32
JS
3533};
3534
ac64794a
BP
3535static struct dpif_netdev_flow_dump *
3536dpif_netdev_flow_dump_cast(struct dpif_flow_dump *dump)
72865317 3537{
ac64794a 3538 return CONTAINER_OF(dump, struct dpif_netdev_flow_dump, up);
e723fd32
JS
3539}
3540
ac64794a 3541static struct dpif_flow_dump *
7e8b7199 3542dpif_netdev_flow_dump_create(const struct dpif *dpif_, bool terse,
a692410a 3543 struct dpif_flow_dump_types *types OVS_UNUSED)
e723fd32 3544{
ac64794a 3545 struct dpif_netdev_flow_dump *dump;
e723fd32 3546
1c1e46ed 3547 dump = xzalloc(sizeof *dump);
ac64794a 3548 dpif_flow_dump_init(&dump->up, dpif_);
64bb477f 3549 dump->up.terse = terse;
ac64794a
BP
3550 ovs_mutex_init(&dump->mutex);
3551
3552 return &dump->up;
e723fd32
JS
3553}
3554
3555static int
ac64794a 3556dpif_netdev_flow_dump_destroy(struct dpif_flow_dump *dump_)
e723fd32 3557{
ac64794a 3558 struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
e723fd32 3559
ac64794a
BP
3560 ovs_mutex_destroy(&dump->mutex);
3561 free(dump);
704a1e09
BP
3562 return 0;
3563}
3564
ac64794a
BP
3565struct dpif_netdev_flow_dump_thread {
3566 struct dpif_flow_dump_thread up;
3567 struct dpif_netdev_flow_dump *dump;
8bb113da
RW
3568 struct odputil_keybuf keybuf[FLOW_DUMP_MAX_BATCH];
3569 struct odputil_keybuf maskbuf[FLOW_DUMP_MAX_BATCH];
ac64794a
BP
3570};
3571
3572static struct dpif_netdev_flow_dump_thread *
3573dpif_netdev_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
3574{
3575 return CONTAINER_OF(thread, struct dpif_netdev_flow_dump_thread, up);
3576}
3577
3578static struct dpif_flow_dump_thread *
3579dpif_netdev_flow_dump_thread_create(struct dpif_flow_dump *dump_)
3580{
3581 struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
3582 struct dpif_netdev_flow_dump_thread *thread;
3583
3584 thread = xmalloc(sizeof *thread);
3585 dpif_flow_dump_thread_init(&thread->up, &dump->up);
3586 thread->dump = dump;
3587 return &thread->up;
3588}
3589
3590static void
3591dpif_netdev_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
3592{
3593 struct dpif_netdev_flow_dump_thread *thread
3594 = dpif_netdev_flow_dump_thread_cast(thread_);
3595
3596 free(thread);
3597}
3598
704a1e09 3599static int
ac64794a 3600dpif_netdev_flow_dump_next(struct dpif_flow_dump_thread *thread_,
8bb113da 3601 struct dpif_flow *flows, int max_flows)
ac64794a
BP
3602{
3603 struct dpif_netdev_flow_dump_thread *thread
3604 = dpif_netdev_flow_dump_thread_cast(thread_);
3605 struct dpif_netdev_flow_dump *dump = thread->dump;
8bb113da 3606 struct dp_netdev_flow *netdev_flows[FLOW_DUMP_MAX_BATCH];
8bb113da
RW
3607 int n_flows = 0;
3608 int i;
14608a15 3609
ac64794a 3610 ovs_mutex_lock(&dump->mutex);
8bb113da 3611 if (!dump->status) {
1c1e46ed
AW
3612 struct dpif_netdev *dpif = dpif_netdev_cast(thread->up.dpif);
3613 struct dp_netdev *dp = get_dp_netdev(&dpif->dpif);
3614 struct dp_netdev_pmd_thread *pmd = dump->cur_pmd;
3615 int flow_limit = MIN(max_flows, FLOW_DUMP_MAX_BATCH);
3616
3617 /* First call to dump_next(), extracts the first pmd thread.
3618 * If there is no pmd thread, returns immediately. */
3619 if (!pmd) {
3620 pmd = dp_netdev_pmd_get_next(dp, &dump->poll_thread_pos);
3621 if (!pmd) {
3622 ovs_mutex_unlock(&dump->mutex);
3623 return n_flows;
8bb113da 3624
8bb113da 3625 }
d2ad7ef1 3626 }
1c1e46ed
AW
3627
3628 do {
3629 for (n_flows = 0; n_flows < flow_limit; n_flows++) {
3630 struct cmap_node *node;
3631
3632 node = cmap_next_position(&pmd->flow_table, &dump->flow_pos);
3633 if (!node) {
3634 break;
3635 }
3636 netdev_flows[n_flows] = CONTAINER_OF(node,
3637 struct dp_netdev_flow,
3638 node);
3639 }
3640 /* When finishing dumping the current pmd thread, moves to
3641 * the next. */
3642 if (n_flows < flow_limit) {
3643 memset(&dump->flow_pos, 0, sizeof dump->flow_pos);
3644 dp_netdev_pmd_unref(pmd);
3645 pmd = dp_netdev_pmd_get_next(dp, &dump->poll_thread_pos);
3646 if (!pmd) {
3647 dump->status = EOF;
3648 break;
3649 }
3650 }
3651 /* Keeps the reference to next caller. */
3652 dump->cur_pmd = pmd;
3653
3654 /* If the current dump is empty, do not exit the loop, since the
3655 * remaining pmds could have flows to be dumped. Just dumps again
3656 * on the new 'pmd'. */
3657 } while (!n_flows);
8a4e3a85 3658 }
ac64794a 3659 ovs_mutex_unlock(&dump->mutex);
ac64794a 3660
8bb113da
RW
3661 for (i = 0; i < n_flows; i++) {
3662 struct odputil_keybuf *maskbuf = &thread->maskbuf[i];
3663 struct odputil_keybuf *keybuf = &thread->keybuf[i];
3664 struct dp_netdev_flow *netdev_flow = netdev_flows[i];
3665 struct dpif_flow *f = &flows[i];
7af12bd7 3666 struct ofpbuf key, mask;
8bb113da 3667
7af12bd7
JS
3668 ofpbuf_use_stack(&key, keybuf, sizeof *keybuf);
3669 ofpbuf_use_stack(&mask, maskbuf, sizeof *maskbuf);
64bb477f
JS
3670 dp_netdev_flow_to_dpif_flow(netdev_flow, &key, &mask, f,
3671 dump->up.terse);
8bb113da 3672 }
feebdea2 3673
8bb113da 3674 return n_flows;
72865317
BP
3675}
3676
3677static int
758c456d 3678dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
65f13b50 3679 OVS_NO_THREAD_SAFETY_ANALYSIS
72865317
BP
3680{
3681 struct dp_netdev *dp = get_dp_netdev(dpif);
65f13b50 3682 struct dp_netdev_pmd_thread *pmd;
1895cc8d 3683 struct dp_packet_batch pp;
72865317 3684
cf62fa4c
PS
3685 if (dp_packet_size(execute->packet) < ETH_HEADER_LEN ||
3686 dp_packet_size(execute->packet) > UINT16_MAX) {
72865317
BP
3687 return EINVAL;
3688 }
3689
65f13b50
AW
3690 /* Tries finding the 'pmd'. If NULL is returned, that means
3691 * the current thread is a non-pmd thread and should use
b19befae 3692 * dp_netdev_get_pmd(dp, NON_PMD_CORE_ID). */
65f13b50
AW
3693 pmd = ovsthread_getspecific(dp->per_pmd_key);
3694 if (!pmd) {
b19befae 3695 pmd = dp_netdev_get_pmd(dp, NON_PMD_CORE_ID);
546e57d4
DDP
3696 if (!pmd) {
3697 return EBUSY;
3698 }
65f13b50
AW
3699 }
3700
05267613
AZ
3701 if (execute->probe) {
3702 /* If this is part of a probe, Drop the packet, since executing
3703 * the action may actually cause spurious packets be sent into
3704 * the network. */
d1ce9c20
YS
3705 if (pmd->core_id == NON_PMD_CORE_ID) {
3706 dp_netdev_pmd_unref(pmd);
3707 }
05267613
AZ
3708 return 0;
3709 }
3710
65f13b50
AW
3711 /* If the current thread is non-pmd thread, acquires
3712 * the 'non_pmd_mutex'. */
3713 if (pmd->core_id == NON_PMD_CORE_ID) {
3714 ovs_mutex_lock(&dp->non_pmd_mutex);
3715 }
1c1e46ed 3716
2fbadeb6
IM
3717 /* Update current time in PMD context. We don't care about EMC insertion
3718 * probability, because we are on a slow path. */
b010be17
IM
3719 pmd_thread_ctx_time_update(pmd);
3720
36d8de17
DDP
3721 /* The action processing expects the RSS hash to be valid, because
3722 * it's always initialized at the beginning of datapath processing.
3723 * In this case, though, 'execute->packet' may not have gone through
3724 * the datapath at all, it may have been generated by the upper layer
3725 * (OpenFlow packet-out, BFD frame, ...). */
3726 if (!dp_packet_rss_valid(execute->packet)) {
3727 dp_packet_set_rss_hash(execute->packet,
3728 flow_hash_5tuple(execute->flow, 0));
3729 }
3730
72c84bc2 3731 dp_packet_batch_init_packet(&pp, execute->packet);
9f17f104 3732 pp.do_not_steal = true;
66e4ad8a 3733 dp_netdev_execute_actions(pmd, &pp, false, execute->flow,
b010be17 3734 execute->actions, execute->actions_len);
c71ea3c4 3735 dp_netdev_pmd_flush_output_packets(pmd, true);
36d8de17 3736
65f13b50
AW
3737 if (pmd->core_id == NON_PMD_CORE_ID) {
3738 ovs_mutex_unlock(&dp->non_pmd_mutex);
e9985d6a 3739 dp_netdev_pmd_unref(pmd);
65f13b50 3740 }
8a4e3a85 3741
758c456d 3742 return 0;
72865317
BP
3743}
3744
1a0c894a 3745static void
57924fc9
SB
3746dpif_netdev_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops,
3747 enum dpif_offload_type offload_type OVS_UNUSED)
1a0c894a
BP
3748{
3749 size_t i;
3750
3751 for (i = 0; i < n_ops; i++) {
3752 struct dpif_op *op = ops[i];
3753
3754 switch (op->type) {
3755 case DPIF_OP_FLOW_PUT:
fa37affa 3756 op->error = dpif_netdev_flow_put(dpif, &op->flow_put);
1a0c894a
BP
3757 break;
3758
3759 case DPIF_OP_FLOW_DEL:
fa37affa 3760 op->error = dpif_netdev_flow_del(dpif, &op->flow_del);
1a0c894a
BP
3761 break;
3762
3763 case DPIF_OP_EXECUTE:
fa37affa 3764 op->error = dpif_netdev_execute(dpif, &op->execute);
1a0c894a 3765 break;
6fe09f8c
JS
3766
3767 case DPIF_OP_FLOW_GET:
fa37affa 3768 op->error = dpif_netdev_flow_get(dpif, &op->flow_get);
6fe09f8c 3769 break;
1a0c894a
BP
3770 }
3771 }
3772}
3773
5bf84282
NK
3774/* Enable or Disable PMD auto load balancing. */
3775static void
3776set_pmd_auto_lb(struct dp_netdev *dp)
3777{
3778 unsigned int cnt = 0;
3779 struct dp_netdev_pmd_thread *pmd;
3780 struct pmd_auto_lb *pmd_alb = &dp->pmd_alb;
3781
3782 bool enable_alb = false;
3783 bool multi_rxq = false;
3784 bool pmd_rxq_assign_cyc = dp->pmd_rxq_assign_cyc;
3785
3786 /* Ensure that there is at least 2 non-isolated PMDs and
3787 * one of them is polling more than one rxq. */
3788 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3789 if (pmd->core_id == NON_PMD_CORE_ID || pmd->isolated) {
3790 continue;
3791 }
3792
3793 if (hmap_count(&pmd->poll_list) > 1) {
3794 multi_rxq = true;
3795 }
3796 if (cnt && multi_rxq) {
3797 enable_alb = true;
3798 break;
3799 }
3800 cnt++;
3801 }
3802
3803 /* Enable auto LB if it is requested and cycle based assignment is true. */
3804 enable_alb = enable_alb && pmd_rxq_assign_cyc &&
3805 pmd_alb->auto_lb_requested;
3806
3807 if (pmd_alb->is_enabled != enable_alb) {
3808 pmd_alb->is_enabled = enable_alb;
3809 if (pmd_alb->is_enabled) {
3810 VLOG_INFO("PMD auto load balance is enabled "
3811 "(with rebalance interval:%"PRIu64" msec)",
3812 pmd_alb->rebalance_intvl);
3813 } else {
3814 pmd_alb->rebalance_poll_timer = 0;
3815 VLOG_INFO("PMD auto load balance is disabled");
3816 }
3817 }
3818
3819}
3820
d4f6865c
DDP
3821/* Applies datapath configuration from the database. Some of the changes are
3822 * actually applied in dpif_netdev_run(). */
f2eee189 3823static int
d4f6865c 3824dpif_netdev_set_config(struct dpif *dpif, const struct smap *other_config)
f2eee189
AW
3825{
3826 struct dp_netdev *dp = get_dp_netdev(dpif);
d4f6865c 3827 const char *cmask = smap_get(other_config, "pmd-cpu-mask");
e77c97b9
KT
3828 const char *pmd_rxq_assign = smap_get_def(other_config, "pmd-rxq-assign",
3829 "cycles");
4c30b246
CL
3830 unsigned long long insert_prob =
3831 smap_get_ullong(other_config, "emc-insert-inv-prob",
3832 DEFAULT_EM_FLOW_INSERT_INV_PROB);
3833 uint32_t insert_min, cur_min;
c71ea3c4 3834 uint32_t tx_flush_interval, cur_tx_flush_interval;
5bf84282 3835 uint64_t rebalance_intvl;
c71ea3c4
IM
3836
3837 tx_flush_interval = smap_get_int(other_config, "tx-flush-interval",
3838 DEFAULT_TX_FLUSH_INTERVAL);
3839 atomic_read_relaxed(&dp->tx_flush_interval, &cur_tx_flush_interval);
3840 if (tx_flush_interval != cur_tx_flush_interval) {
3841 atomic_store_relaxed(&dp->tx_flush_interval, tx_flush_interval);
3842 VLOG_INFO("Flushing interval for tx queues set to %"PRIu32" us",
3843 tx_flush_interval);
3844 }
f2eee189 3845
a6a426d6
IM
3846 if (!nullable_string_is_equal(dp->pmd_cmask, cmask)) {
3847 free(dp->pmd_cmask);
3848 dp->pmd_cmask = nullable_xstrdup(cmask);
3849 dp_netdev_request_reconfigure(dp);
f2eee189
AW
3850 }
3851
4c30b246
CL
3852 atomic_read_relaxed(&dp->emc_insert_min, &cur_min);
3853 if (insert_prob <= UINT32_MAX) {
3854 insert_min = insert_prob == 0 ? 0 : UINT32_MAX / insert_prob;
3855 } else {
3856 insert_min = DEFAULT_EM_FLOW_INSERT_MIN;
3857 insert_prob = DEFAULT_EM_FLOW_INSERT_INV_PROB;
3858 }
3859
3860 if (insert_min != cur_min) {
3861 atomic_store_relaxed(&dp->emc_insert_min, insert_min);
3862 if (insert_min == 0) {
2fbadeb6 3863 VLOG_INFO("EMC insertion probability changed to zero");
4c30b246
CL
3864 } else {
3865 VLOG_INFO("EMC insertion probability changed to 1/%llu (~%.2f%%)",
3866 insert_prob, (100 / (float)insert_prob));
3867 }
3868 }
3869
79f36875
JS
3870 bool perf_enabled = smap_get_bool(other_config, "pmd-perf-metrics", false);
3871 bool cur_perf_enabled;
3872 atomic_read_relaxed(&dp->pmd_perf_metrics, &cur_perf_enabled);
3873 if (perf_enabled != cur_perf_enabled) {
3874 atomic_store_relaxed(&dp->pmd_perf_metrics, perf_enabled);
3875 if (perf_enabled) {
3876 VLOG_INFO("PMD performance metrics collection enabled");
3877 } else {
3878 VLOG_INFO("PMD performance metrics collection disabled");
3879 }
3880 }
3881
60d8ccae
YW
3882 bool smc_enable = smap_get_bool(other_config, "smc-enable", false);
3883 bool cur_smc;
3884 atomic_read_relaxed(&dp->smc_enable_db, &cur_smc);
3885 if (smc_enable != cur_smc) {
3886 atomic_store_relaxed(&dp->smc_enable_db, smc_enable);
3887 if (smc_enable) {
3888 VLOG_INFO("SMC cache is enabled");
3889 } else {
3890 VLOG_INFO("SMC cache is disabled");
3891 }
3892 }
e77c97b9
KT
3893
3894 bool pmd_rxq_assign_cyc = !strcmp(pmd_rxq_assign, "cycles");
3895 if (!pmd_rxq_assign_cyc && strcmp(pmd_rxq_assign, "roundrobin")) {
3896 VLOG_WARN("Unsupported Rxq to PMD assignment mode in pmd-rxq-assign. "
3897 "Defaulting to 'cycles'.");
3898 pmd_rxq_assign_cyc = true;
3899 pmd_rxq_assign = "cycles";
3900 }
3901 if (dp->pmd_rxq_assign_cyc != pmd_rxq_assign_cyc) {
3902 dp->pmd_rxq_assign_cyc = pmd_rxq_assign_cyc;
3903 VLOG_INFO("Rxq to PMD assignment mode changed to: \'%s\'.",
3904 pmd_rxq_assign);
3905 dp_netdev_request_reconfigure(dp);
3906 }
5bf84282
NK
3907
3908 struct pmd_auto_lb *pmd_alb = &dp->pmd_alb;
3909 pmd_alb->auto_lb_requested = smap_get_bool(other_config, "pmd-auto-lb",
3910 false);
3911
3912 rebalance_intvl = smap_get_int(other_config, "pmd-auto-lb-rebal-interval",
3913 ALB_PMD_REBALANCE_POLL_INTERVAL);
3914
3915 /* Input is in min, convert it to msec. */
3916 rebalance_intvl =
3917 rebalance_intvl ? rebalance_intvl * MIN_TO_MSEC : MIN_TO_MSEC;
3918
3919 if (pmd_alb->rebalance_intvl != rebalance_intvl) {
3920 pmd_alb->rebalance_intvl = rebalance_intvl;
3921 }
3922
3923 set_pmd_auto_lb(dp);
f2eee189
AW
3924 return 0;
3925}
3926
3eb67853
IM
3927/* Parses affinity list and returns result in 'core_ids'. */
3928static int
3929parse_affinity_list(const char *affinity_list, unsigned *core_ids, int n_rxq)
3930{
3931 unsigned i;
3932 char *list, *copy, *key, *value;
3933 int error = 0;
3934
3935 for (i = 0; i < n_rxq; i++) {
51c37a56 3936 core_ids[i] = OVS_CORE_UNSPEC;
3eb67853
IM
3937 }
3938
3939 if (!affinity_list) {
3940 return 0;
3941 }
3942
3943 list = copy = xstrdup(affinity_list);
3944
3945 while (ofputil_parse_key_value(&list, &key, &value)) {
3946 int rxq_id, core_id;
3947
3948 if (!str_to_int(key, 0, &rxq_id) || rxq_id < 0
3949 || !str_to_int(value, 0, &core_id) || core_id < 0) {
3950 error = EINVAL;
3951 break;
3952 }
3953
3954 if (rxq_id < n_rxq) {
3955 core_ids[rxq_id] = core_id;
3956 }
3957 }
3958
3959 free(copy);
3960 return error;
3961}
3962
3963/* Parses 'affinity_list' and applies configuration if it is valid. */
3964static int
3965dpif_netdev_port_set_rxq_affinity(struct dp_netdev_port *port,
3966 const char *affinity_list)
3967{
3968 unsigned *core_ids, i;
3969 int error = 0;
3970
3971 core_ids = xmalloc(port->n_rxq * sizeof *core_ids);
3972 if (parse_affinity_list(affinity_list, core_ids, port->n_rxq)) {
3973 error = EINVAL;
3974 goto exit;
3975 }
3976
3977 for (i = 0; i < port->n_rxq; i++) {
3978 port->rxqs[i].core_id = core_ids[i];
3979 }
3980
3981exit:
3982 free(core_ids);
3983 return error;
3984}
3985
2fbadeb6
IM
3986/* Returns 'true' if one of the 'port's RX queues exists in 'poll_list'
3987 * of given PMD thread. */
3988static bool
3989dpif_netdev_pmd_polls_port(struct dp_netdev_pmd_thread *pmd,
3990 struct dp_netdev_port *port)
3991 OVS_EXCLUDED(pmd->port_mutex)
3992{
3993 struct rxq_poll *poll;
3994 bool found = false;
3995
3996 ovs_mutex_lock(&pmd->port_mutex);
3997 HMAP_FOR_EACH (poll, node, &pmd->poll_list) {
3998 if (port == poll->rxq->port) {
3999 found = true;
4000 break;
4001 }
4002 }
4003 ovs_mutex_unlock(&pmd->port_mutex);
4004 return found;
4005}
4006
4007/* Updates port configuration from the database. The changes are actually
4008 * applied in dpif_netdev_run(). */
3eb67853
IM
4009static int
4010dpif_netdev_port_set_config(struct dpif *dpif, odp_port_t port_no,
4011 const struct smap *cfg)
4012{
4013 struct dp_netdev *dp = get_dp_netdev(dpif);
4014 struct dp_netdev_port *port;
4015 int error = 0;
4016 const char *affinity_list = smap_get(cfg, "pmd-rxq-affinity");
2fbadeb6 4017 bool emc_enabled = smap_get_bool(cfg, "emc-enable", true);
3eb67853
IM
4018
4019 ovs_mutex_lock(&dp->port_mutex);
4020 error = get_port_by_number(dp, port_no, &port);
2fbadeb6
IM
4021 if (error) {
4022 goto unlock;
4023 }
4024
4025 if (emc_enabled != port->emc_enabled) {
4026 struct dp_netdev_pmd_thread *pmd;
4027 struct ds ds = DS_EMPTY_INITIALIZER;
4028 uint32_t cur_min, insert_prob;
4029
4030 port->emc_enabled = emc_enabled;
4031 /* Mark for reload all the threads that polls this port and request
4032 * for reconfiguration for the actual reloading of threads. */
4033 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4034 if (dpif_netdev_pmd_polls_port(pmd, port)) {
4035 pmd->need_reload = true;
4036 }
4037 }
4038 dp_netdev_request_reconfigure(dp);
4039
4040 ds_put_format(&ds, "%s: EMC has been %s.",
4041 netdev_get_name(port->netdev),
4042 (emc_enabled) ? "enabled" : "disabled");
4043 if (emc_enabled) {
4044 ds_put_cstr(&ds, " Current insertion probability is ");
4045 atomic_read_relaxed(&dp->emc_insert_min, &cur_min);
4046 if (!cur_min) {
4047 ds_put_cstr(&ds, "zero.");
4048 } else {
4049 insert_prob = UINT32_MAX / cur_min;
4050 ds_put_format(&ds, "1/%"PRIu32" (~%.2f%%).",
4051 insert_prob, 100 / (float) insert_prob);
4052 }
4053 }
4054 VLOG_INFO("%s", ds_cstr(&ds));
4055 ds_destroy(&ds);
4056 }
4057
4058 /* Checking for RXq affinity changes. */
4059 if (!netdev_is_pmd(port->netdev)
3eb67853
IM
4060 || nullable_string_is_equal(affinity_list, port->rxq_affinity_list)) {
4061 goto unlock;
4062 }
4063
4064 error = dpif_netdev_port_set_rxq_affinity(port, affinity_list);
4065 if (error) {
4066 goto unlock;
4067 }
4068 free(port->rxq_affinity_list);
4069 port->rxq_affinity_list = nullable_xstrdup(affinity_list);
4070
4071 dp_netdev_request_reconfigure(dp);
4072unlock:
4073 ovs_mutex_unlock(&dp->port_mutex);
4074 return error;
4075}
4076
5bf93d67
EJ
4077static int
4078dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
4079 uint32_t queue_id, uint32_t *priority)
4080{
4081 *priority = queue_id;
4082 return 0;
4083}
4084
72865317 4085\f
9ff55ae2 4086/* Creates and returns a new 'struct dp_netdev_actions', whose actions are
1401f6de 4087 * a copy of the 'size' bytes of 'actions' input parameters. */
a84cb64a
BP
4088struct dp_netdev_actions *
4089dp_netdev_actions_create(const struct nlattr *actions, size_t size)
4090{
4091 struct dp_netdev_actions *netdev_actions;
4092
9ff55ae2
DDP
4093 netdev_actions = xmalloc(sizeof *netdev_actions + size);
4094 memcpy(netdev_actions->actions, actions, size);
a84cb64a
BP
4095 netdev_actions->size = size;
4096
4097 return netdev_actions;
4098}
4099
a84cb64a 4100struct dp_netdev_actions *
61e7deb1 4101dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
a84cb64a 4102{
61e7deb1 4103 return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
a84cb64a
BP
4104}
4105
61e7deb1
BP
4106static void
4107dp_netdev_actions_free(struct dp_netdev_actions *actions)
a84cb64a 4108{
61e7deb1 4109 free(actions);
a84cb64a
BP
4110}
4111\f
a19896ab
JS
4112static void
4113dp_netdev_rxq_set_cycles(struct dp_netdev_rxq *rx,
4114 enum rxq_cycles_counter_type type,
4115 unsigned long long cycles)
a2ac666d 4116{
a19896ab 4117 atomic_store_relaxed(&rx->cycles[type], cycles);
a2ac666d
CL
4118}
4119
4809891b 4120static void
a19896ab 4121dp_netdev_rxq_add_cycles(struct dp_netdev_rxq *rx,
4809891b
KT
4122 enum rxq_cycles_counter_type type,
4123 unsigned long long cycles)
4124{
a19896ab 4125 non_atomic_ullong_add(&rx->cycles[type], cycles);
4809891b
KT
4126}
4127
4128static uint64_t
4129dp_netdev_rxq_get_cycles(struct dp_netdev_rxq *rx,
4130 enum rxq_cycles_counter_type type)
4131{
4132 unsigned long long processing_cycles;
4133 atomic_read_relaxed(&rx->cycles[type], &processing_cycles);
4134 return processing_cycles;
4135}
4136
4137static void
4138dp_netdev_rxq_set_intrvl_cycles(struct dp_netdev_rxq *rx,
4139 unsigned long long cycles)
4140{
4ee87ad3
BP
4141 unsigned int idx = rx->intrvl_idx++ % PMD_RXQ_INTERVAL_MAX;
4142 atomic_store_relaxed(&rx->cycles_intrvl[idx], cycles);
4809891b
KT
4143}
4144
655856ef
KT
4145static uint64_t
4146dp_netdev_rxq_get_intrvl_cycles(struct dp_netdev_rxq *rx, unsigned idx)
4147{
4148 unsigned long long processing_cycles;
4149 atomic_read_relaxed(&rx->cycles_intrvl[idx], &processing_cycles);
4150 return processing_cycles;
4151}
4152
79f36875
JS
4153#if ATOMIC_ALWAYS_LOCK_FREE_8B
4154static inline bool
4155pmd_perf_metrics_enabled(const struct dp_netdev_pmd_thread *pmd)
4156{
4157 bool pmd_perf_enabled;
4158 atomic_read_relaxed(&pmd->dp->pmd_perf_metrics, &pmd_perf_enabled);
4159 return pmd_perf_enabled;
4160}
4161#else
4162/* If stores and reads of 64-bit integers are not atomic, the full PMD
4163 * performance metrics are not available as locked access to 64 bit
4164 * integers would be prohibitively expensive. */
4165static inline bool
4166pmd_perf_metrics_enabled(const struct dp_netdev_pmd_thread *pmd OVS_UNUSED)
4167{
4168 return false;
4169}
4170#endif
4171
c71ea3c4 4172static int
009e0033
IM
4173dp_netdev_pmd_flush_output_on_port(struct dp_netdev_pmd_thread *pmd,
4174 struct tx_port *p)
4175{
58ed6df0 4176 int i;
009e0033 4177 int tx_qid;
cc4891f3 4178 int output_cnt;
009e0033 4179 bool dynamic_txqs;
58ed6df0
IM
4180 struct cycle_timer timer;
4181 uint64_t cycles;
c71ea3c4 4182 uint32_t tx_flush_interval;
58ed6df0
IM
4183
4184 cycle_timer_start(&pmd->perf_stats, &timer);
009e0033
IM
4185
4186 dynamic_txqs = p->port->dynamic_txqs;
4187 if (dynamic_txqs) {
4188 tx_qid = dpif_netdev_xps_get_tx_qid(pmd, p);
4189 } else {
4190 tx_qid = pmd->static_tx_qid;
4191 }
4192
cc4891f3 4193 output_cnt = dp_packet_batch_size(&p->output_pkts);
58ed6df0 4194 ovs_assert(output_cnt > 0);
cc4891f3 4195
b30896c9 4196 netdev_send(p->port->netdev, tx_qid, &p->output_pkts, dynamic_txqs);
009e0033 4197 dp_packet_batch_init(&p->output_pkts);
cc4891f3 4198
c71ea3c4
IM
4199 /* Update time of the next flush. */
4200 atomic_read_relaxed(&pmd->dp->tx_flush_interval, &tx_flush_interval);
4201 p->flush_time = pmd->ctx.now + tx_flush_interval;
4202
4203 ovs_assert(pmd->n_output_batches > 0);
4204 pmd->n_output_batches--;
4205
82a48ead
JS
4206 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_SENT_PKTS, output_cnt);
4207 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_SENT_BATCHES, 1);
58ed6df0
IM
4208
4209 /* Distribute send cycles evenly among transmitted packets and assign to
4210 * their respective rx queues. */
4211 cycles = cycle_timer_stop(&pmd->perf_stats, &timer) / output_cnt;
4212 for (i = 0; i < output_cnt; i++) {
4213 if (p->output_pkts_rxqs[i]) {
4214 dp_netdev_rxq_add_cycles(p->output_pkts_rxqs[i],
4215 RXQ_CYCLES_PROC_CURR, cycles);
4216 }
4217 }
c71ea3c4
IM
4218
4219 return output_cnt;
009e0033
IM
4220}
4221
c71ea3c4
IM
4222static int
4223dp_netdev_pmd_flush_output_packets(struct dp_netdev_pmd_thread *pmd,
4224 bool force)
009e0033
IM
4225{
4226 struct tx_port *p;
c71ea3c4
IM
4227 int output_cnt = 0;
4228
4229 if (!pmd->n_output_batches) {
4230 return 0;
4231 }
009e0033
IM
4232
4233 HMAP_FOR_EACH (p, node, &pmd->send_port_cache) {
c71ea3c4
IM
4234 if (!dp_packet_batch_is_empty(&p->output_pkts)
4235 && (force || pmd->ctx.now >= p->flush_time)) {
4236 output_cnt += dp_netdev_pmd_flush_output_on_port(pmd, p);
009e0033
IM
4237 }
4238 }
c71ea3c4 4239 return output_cnt;
009e0033
IM
4240}
4241
a2ac666d 4242static int
65f13b50 4243dp_netdev_process_rxq_port(struct dp_netdev_pmd_thread *pmd,
a19896ab 4244 struct dp_netdev_rxq *rxq,
947dc567 4245 odp_port_t port_no)
e4cfed38 4246{
79f36875 4247 struct pmd_perf_stats *s = &pmd->perf_stats;
1895cc8d 4248 struct dp_packet_batch batch;
a19896ab 4249 struct cycle_timer timer;
1895cc8d 4250 int error;
79f36875
JS
4251 int batch_cnt = 0;
4252 int rem_qlen = 0, *qlen_p = NULL;
58ed6df0 4253 uint64_t cycles;
e4cfed38 4254
a19896ab
JS
4255 /* Measure duration for polling and processing rx burst. */
4256 cycle_timer_start(&pmd->perf_stats, &timer);
58ed6df0
IM
4257
4258 pmd->ctx.last_rxq = rxq;
1895cc8d 4259 dp_packet_batch_init(&batch);
58ed6df0 4260
79f36875
JS
4261 /* Fetch the rx queue length only for vhostuser ports. */
4262 if (pmd_perf_metrics_enabled(pmd) && rxq->is_vhost) {
4263 qlen_p = &rem_qlen;
4264 }
4265
4266 error = netdev_rxq_recv(rxq->rx, &batch, qlen_p);
e4cfed38 4267 if (!error) {
a19896ab 4268 /* At least one packet received. */
3c33f0ff 4269 *recirc_depth_get() = 0;
009e0033 4270 pmd_thread_ctx_time_update(pmd);
940ac2ce 4271 batch_cnt = dp_packet_batch_size(&batch);
79f36875
JS
4272 if (pmd_perf_metrics_enabled(pmd)) {
4273 /* Update batch histogram. */
4274 s->current.batches++;
4275 histogram_add_sample(&s->pkts_per_batch, batch_cnt);
4276 /* Update the maximum vhost rx queue fill level. */
4277 if (rxq->is_vhost && rem_qlen >= 0) {
4278 uint32_t qfill = batch_cnt + rem_qlen;
4279 if (qfill > s->current.max_vhost_qfill) {
4280 s->current.max_vhost_qfill = qfill;
4281 }
4282 }
4283 }
4284 /* Process packet batch. */
947dc567 4285 dp_netdev_input(pmd, &batch, port_no);
e4cfed38 4286
a19896ab 4287 /* Assign processing cycles to rx queue. */
58ed6df0 4288 cycles = cycle_timer_stop(&pmd->perf_stats, &timer);
a19896ab
JS
4289 dp_netdev_rxq_add_cycles(rxq, RXQ_CYCLES_PROC_CURR, cycles);
4290
79f36875 4291 dp_netdev_pmd_flush_output_packets(pmd, false);
a19896ab
JS
4292 } else {
4293 /* Discard cycles. */
4294 cycle_timer_stop(&pmd->perf_stats, &timer);
4295 if (error != EAGAIN && error != EOPNOTSUPP) {
4296 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4297
4298 VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
4299 netdev_rxq_get_name(rxq->rx), ovs_strerror(error));
4300 }
e4cfed38 4301 }
a2ac666d 4302
58ed6df0
IM
4303 pmd->ctx.last_rxq = NULL;
4304
79f36875 4305 return batch_cnt;
e4cfed38
PS
4306}
4307
e32971b8
DDP
4308static struct tx_port *
4309tx_port_lookup(const struct hmap *hmap, odp_port_t port_no)
4310{
4311 struct tx_port *tx;
4312
4313 HMAP_FOR_EACH_IN_BUCKET (tx, node, hash_port_no(port_no), hmap) {
4314 if (tx->port->port_no == port_no) {
4315 return tx;
4316 }
4317 }
4318
4319 return NULL;
4320}
4321
dc36593c
DDP
4322static int
4323port_reconfigure(struct dp_netdev_port *port)
4324{
4325 struct netdev *netdev = port->netdev;
dc36593c
DDP
4326 int i, err;
4327
dc36593c
DDP
4328 /* Closes the existing 'rxq's. */
4329 for (i = 0; i < port->n_rxq; i++) {
947dc567
DDP
4330 netdev_rxq_close(port->rxqs[i].rx);
4331 port->rxqs[i].rx = NULL;
dc36593c 4332 }
4809891b 4333 unsigned last_nrxq = port->n_rxq;
dc36593c
DDP
4334 port->n_rxq = 0;
4335
050c60bf 4336 /* Allows 'netdev' to apply the pending configuration changes. */
606f6650 4337 if (netdev_is_reconf_required(netdev) || port->need_reconfigure) {
e32971b8
DDP
4338 err = netdev_reconfigure(netdev);
4339 if (err && (err != EOPNOTSUPP)) {
4340 VLOG_ERR("Failed to set interface %s new configuration",
4341 netdev_get_name(netdev));
4342 return err;
4343 }
dc36593c 4344 }
050c60bf 4345 /* If the netdev_reconfigure() above succeeds, reopens the 'rxq's. */
3eb67853
IM
4346 port->rxqs = xrealloc(port->rxqs,
4347 sizeof *port->rxqs * netdev_n_rxq(netdev));
324c8374
IM
4348 /* Realloc 'used' counters for tx queues. */
4349 free(port->txq_used);
4350 port->txq_used = xcalloc(netdev_n_txq(netdev), sizeof *port->txq_used);
4351
dc36593c 4352 for (i = 0; i < netdev_n_rxq(netdev); i++) {
38259bd7
BP
4353 bool new_queue = i >= last_nrxq;
4354 if (new_queue) {
4355 memset(&port->rxqs[i], 0, sizeof port->rxqs[i]);
4356 }
4357
947dc567 4358 port->rxqs[i].port = port;
79f36875 4359 port->rxqs[i].is_vhost = !strncmp(port->type, "dpdkvhost", 9);
38259bd7 4360
947dc567 4361 err = netdev_rxq_open(netdev, &port->rxqs[i].rx, i);
dc36593c
DDP
4362 if (err) {
4363 return err;
4364 }
4365 port->n_rxq++;
4366 }
4367
3eb67853
IM
4368 /* Parse affinity list to apply configuration for new queues. */
4369 dpif_netdev_port_set_rxq_affinity(port, port->rxq_affinity_list);
4370
606f6650
EC
4371 /* If reconfiguration was successful mark it as such, so we can use it */
4372 port->need_reconfigure = false;
4373
dc36593c
DDP
4374 return 0;
4375}
4376
e32971b8
DDP
4377struct rr_numa_list {
4378 struct hmap numas; /* Contains 'struct rr_numa' */
4379};
4380
4381struct rr_numa {
4382 struct hmap_node node;
4383
4384 int numa_id;
4385
4386 /* Non isolated pmds on numa node 'numa_id' */
4387 struct dp_netdev_pmd_thread **pmds;
4388 int n_pmds;
4389
4390 int cur_index;
79da1e41 4391 bool idx_inc;
e32971b8
DDP
4392};
4393
4394static struct rr_numa *
4395rr_numa_list_lookup(struct rr_numa_list *rr, int numa_id)
4396{
4397 struct rr_numa *numa;
4398
4399 HMAP_FOR_EACH_WITH_HASH (numa, node, hash_int(numa_id, 0), &rr->numas) {
4400 if (numa->numa_id == numa_id) {
4401 return numa;
4402 }
4403 }
4404
4405 return NULL;
4406}
4407
c37813fd
BM
4408/* Returns the next node in numa list following 'numa' in round-robin fashion.
4409 * Returns first node if 'numa' is a null pointer or the last node in 'rr'.
4410 * Returns NULL if 'rr' numa list is empty. */
4411static struct rr_numa *
4412rr_numa_list_next(struct rr_numa_list *rr, const struct rr_numa *numa)
4413{
4414 struct hmap_node *node = NULL;
4415
4416 if (numa) {
4417 node = hmap_next(&rr->numas, &numa->node);
4418 }
4419 if (!node) {
4420 node = hmap_first(&rr->numas);
4421 }
4422
4423 return (node) ? CONTAINER_OF(node, struct rr_numa, node) : NULL;
4424}
4425
e32971b8
DDP
4426static void
4427rr_numa_list_populate(struct dp_netdev *dp, struct rr_numa_list *rr)
4428{
4429 struct dp_netdev_pmd_thread *pmd;
4430 struct rr_numa *numa;
4431
4432 hmap_init(&rr->numas);
4433
4434 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4435 if (pmd->core_id == NON_PMD_CORE_ID || pmd->isolated) {
4436 continue;
4437 }
4438
4439 numa = rr_numa_list_lookup(rr, pmd->numa_id);
4440 if (!numa) {
4441 numa = xzalloc(sizeof *numa);
4442 numa->numa_id = pmd->numa_id;
4443 hmap_insert(&rr->numas, &numa->node, hash_int(pmd->numa_id, 0));
4444 }
4445 numa->n_pmds++;
4446 numa->pmds = xrealloc(numa->pmds, numa->n_pmds * sizeof *numa->pmds);
4447 numa->pmds[numa->n_pmds - 1] = pmd;
79da1e41
KT
4448 /* At least one pmd so initialise curr_idx and idx_inc. */
4449 numa->cur_index = 0;
4450 numa->idx_inc = true;
e32971b8
DDP
4451 }
4452}
4453
e77c97b9
KT
4454/*
4455 * Returns the next pmd from the numa node.
4456 *
4457 * If 'updown' is 'true' it will alternate between selecting the next pmd in
4458 * either an up or down walk, switching between up/down when the first or last
4459 * core is reached. e.g. 1,2,3,3,2,1,1,2...
4460 *
4461 * If 'updown' is 'false' it will select the next pmd wrapping around when last
4462 * core reached. e.g. 1,2,3,1,2,3,1,2...
4463 */
e32971b8 4464static struct dp_netdev_pmd_thread *
e77c97b9 4465rr_numa_get_pmd(struct rr_numa *numa, bool updown)
e32971b8 4466{
79da1e41
KT
4467 int numa_idx = numa->cur_index;
4468
4469 if (numa->idx_inc == true) {
4470 /* Incrementing through list of pmds. */
4471 if (numa->cur_index == numa->n_pmds-1) {
4472 /* Reached the last pmd. */
e77c97b9
KT
4473 if (updown) {
4474 numa->idx_inc = false;
4475 } else {
4476 numa->cur_index = 0;
4477 }
79da1e41
KT
4478 } else {
4479 numa->cur_index++;
4480 }
4481 } else {
4482 /* Decrementing through list of pmds. */
4483 if (numa->cur_index == 0) {
4484 /* Reached the first pmd. */
4485 numa->idx_inc = true;
4486 } else {
4487 numa->cur_index--;
4488 }
4489 }
4490 return numa->pmds[numa_idx];
e32971b8
DDP
4491}
4492
4493static void
4494rr_numa_list_destroy(struct rr_numa_list *rr)
4495{
4496 struct rr_numa *numa;
4497
4498 HMAP_FOR_EACH_POP (numa, node, &rr->numas) {
4499 free(numa->pmds);
4500 free(numa);
4501 }
4502 hmap_destroy(&rr->numas);
4503}
4504
655856ef
KT
4505/* Sort Rx Queues by the processing cycles they are consuming. */
4506static int
cc131ac1 4507compare_rxq_cycles(const void *a, const void *b)
655856ef 4508{
28080276
KT
4509 struct dp_netdev_rxq *qa;
4510 struct dp_netdev_rxq *qb;
8368866e 4511 uint64_t cycles_qa, cycles_qb;
655856ef
KT
4512
4513 qa = *(struct dp_netdev_rxq **) a;
4514 qb = *(struct dp_netdev_rxq **) b;
4515
8368866e
KT
4516 cycles_qa = dp_netdev_rxq_get_cycles(qa, RXQ_CYCLES_PROC_HIST);
4517 cycles_qb = dp_netdev_rxq_get_cycles(qb, RXQ_CYCLES_PROC_HIST);
655856ef 4518
8368866e
KT
4519 if (cycles_qa != cycles_qb) {
4520 return (cycles_qa < cycles_qb) ? 1 : -1;
a130f1a8
KT
4521 } else {
4522 /* Cycles are the same so tiebreak on port/queue id.
4523 * Tiebreaking (as opposed to return 0) ensures consistent
4524 * sort results across multiple OS's. */
f0aa3801
BP
4525 uint32_t port_qa = odp_to_u32(qa->port->port_no);
4526 uint32_t port_qb = odp_to_u32(qb->port->port_no);
4527 if (port_qa != port_qb) {
4528 return port_qa > port_qb ? 1 : -1;
a130f1a8
KT
4529 } else {
4530 return netdev_rxq_get_queue_id(qa->rx)
4531 - netdev_rxq_get_queue_id(qb->rx);
4532 }
655856ef 4533 }
655856ef
KT
4534}
4535
e32971b8
DDP
4536/* Assign pmds to queues. If 'pinned' is true, assign pmds to pinned
4537 * queues and marks the pmds as isolated. Otherwise, assign non isolated
4538 * pmds to unpinned queues.
4539 *
4540 * The function doesn't touch the pmd threads, it just stores the assignment
4541 * in the 'pmd' member of each rxq. */
4542static void
4543rxq_scheduling(struct dp_netdev *dp, bool pinned) OVS_REQUIRES(dp->port_mutex)
4544{
4545 struct dp_netdev_port *port;
4546 struct rr_numa_list rr;
c37813fd 4547 struct rr_numa *non_local_numa = NULL;
655856ef 4548 struct dp_netdev_rxq ** rxqs = NULL;
97bf8f47 4549 int n_rxqs = 0;
655856ef
KT
4550 struct rr_numa *numa = NULL;
4551 int numa_id;
e77c97b9 4552 bool assign_cyc = dp->pmd_rxq_assign_cyc;
e32971b8
DDP
4553
4554 HMAP_FOR_EACH (port, node, &dp->ports) {
e32971b8
DDP
4555 if (!netdev_is_pmd(port->netdev)) {
4556 continue;
4557 }
4558
e32971b8
DDP
4559 for (int qid = 0; qid < port->n_rxq; qid++) {
4560 struct dp_netdev_rxq *q = &port->rxqs[qid];
4561
4562 if (pinned && q->core_id != OVS_CORE_UNSPEC) {
4563 struct dp_netdev_pmd_thread *pmd;
4564
4565 pmd = dp_netdev_get_pmd(dp, q->core_id);
4566 if (!pmd) {
4567 VLOG_WARN("There is no PMD thread on core %d. Queue "
4568 "%d on port \'%s\' will not be polled.",
4569 q->core_id, qid, netdev_get_name(port->netdev));
4570 } else {
4571 q->pmd = pmd;
4572 pmd->isolated = true;
433a3fa5
GM
4573 VLOG_INFO("Core %d on numa node %d assigned port \'%s\' "
4574 "rx queue %d.", pmd->core_id, pmd->numa_id,
4575 netdev_rxq_get_name(q->rx),
4576 netdev_rxq_get_queue_id(q->rx));
e32971b8
DDP
4577 dp_netdev_pmd_unref(pmd);
4578 }
4579 } else if (!pinned && q->core_id == OVS_CORE_UNSPEC) {
8368866e
KT
4580 uint64_t cycle_hist = 0;
4581
655856ef
KT
4582 if (n_rxqs == 0) {
4583 rxqs = xmalloc(sizeof *rxqs);
e32971b8 4584 } else {
655856ef 4585 rxqs = xrealloc(rxqs, sizeof *rxqs * (n_rxqs + 1));
e32971b8 4586 }
8368866e 4587
e77c97b9
KT
4588 if (assign_cyc) {
4589 /* Sum the queue intervals and store the cycle history. */
4590 for (unsigned i = 0; i < PMD_RXQ_INTERVAL_MAX; i++) {
4591 cycle_hist += dp_netdev_rxq_get_intrvl_cycles(q, i);
4592 }
4593 dp_netdev_rxq_set_cycles(q, RXQ_CYCLES_PROC_HIST,
4594 cycle_hist);
4595 }
655856ef
KT
4596 /* Store the queue. */
4597 rxqs[n_rxqs++] = q;
e32971b8
DDP
4598 }
4599 }
4600 }
4601
e77c97b9 4602 if (n_rxqs > 1 && assign_cyc) {
655856ef
KT
4603 /* Sort the queues in order of the processing cycles
4604 * they consumed during their last pmd interval. */
cc131ac1 4605 qsort(rxqs, n_rxqs, sizeof *rxqs, compare_rxq_cycles);
655856ef
KT
4606 }
4607
4608 rr_numa_list_populate(dp, &rr);
4609 /* Assign the sorted queues to pmds in round robin. */
97bf8f47 4610 for (int i = 0; i < n_rxqs; i++) {
655856ef
KT
4611 numa_id = netdev_get_numa_id(rxqs[i]->port->netdev);
4612 numa = rr_numa_list_lookup(&rr, numa_id);
4613 if (!numa) {
4614 /* There are no pmds on the queue's local NUMA node.
4615 Round robin on the NUMA nodes that do have pmds. */
4616 non_local_numa = rr_numa_list_next(&rr, non_local_numa);
4617 if (!non_local_numa) {
4618 VLOG_ERR("There is no available (non-isolated) pmd "
4619 "thread for port \'%s\' queue %d. This queue "
4620 "will not be polled. Is pmd-cpu-mask set to "
4621 "zero? Or are all PMDs isolated to other "
4622 "queues?", netdev_rxq_get_name(rxqs[i]->rx),
4623 netdev_rxq_get_queue_id(rxqs[i]->rx));
4624 continue;
4625 }
e77c97b9 4626 rxqs[i]->pmd = rr_numa_get_pmd(non_local_numa, assign_cyc);
655856ef
KT
4627 VLOG_WARN("There's no available (non-isolated) pmd thread "
4628 "on numa node %d. Queue %d on port \'%s\' will "
4629 "be assigned to the pmd on core %d "
4630 "(numa node %d). Expect reduced performance.",
4631 numa_id, netdev_rxq_get_queue_id(rxqs[i]->rx),
4632 netdev_rxq_get_name(rxqs[i]->rx),
4633 rxqs[i]->pmd->core_id, rxqs[i]->pmd->numa_id);
4634 } else {
e77c97b9
KT
4635 rxqs[i]->pmd = rr_numa_get_pmd(numa, assign_cyc);
4636 if (assign_cyc) {
4637 VLOG_INFO("Core %d on numa node %d assigned port \'%s\' "
4638 "rx queue %d "
4639 "(measured processing cycles %"PRIu64").",
4640 rxqs[i]->pmd->core_id, numa_id,
4641 netdev_rxq_get_name(rxqs[i]->rx),
4642 netdev_rxq_get_queue_id(rxqs[i]->rx),
4643 dp_netdev_rxq_get_cycles(rxqs[i],
4644 RXQ_CYCLES_PROC_HIST));
4645 } else {
4646 VLOG_INFO("Core %d on numa node %d assigned port \'%s\' "
4647 "rx queue %d.", rxqs[i]->pmd->core_id, numa_id,
4648 netdev_rxq_get_name(rxqs[i]->rx),
4649 netdev_rxq_get_queue_id(rxqs[i]->rx));
4650 }
655856ef
KT
4651 }
4652 }
4653
e32971b8 4654 rr_numa_list_destroy(&rr);
655856ef 4655 free(rxqs);
e32971b8
DDP
4656}
4657
140dd699
IM
4658static void
4659reload_affected_pmds(struct dp_netdev *dp)
4660{
4661 struct dp_netdev_pmd_thread *pmd;
4662
4663 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4664 if (pmd->need_reload) {
241bad15 4665 flow_mark_flush(pmd);
140dd699 4666 dp_netdev_reload_pmd__(pmd);
8f077b31
DM
4667 }
4668 }
4669
4670 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4671 if (pmd->need_reload) {
4672 if (pmd->core_id != NON_PMD_CORE_ID) {
4673 bool reload;
4674
4675 do {
4676 atomic_read_explicit(&pmd->reload, &reload,
4677 memory_order_acquire);
4678 } while (reload);
4679 }
140dd699
IM
4680 pmd->need_reload = false;
4681 }
4682 }
4683}
4684
6e3c6fa4
DDP
4685static void
4686reconfigure_pmd_threads(struct dp_netdev *dp)
4687 OVS_REQUIRES(dp->port_mutex)
4688{
e32971b8
DDP
4689 struct dp_netdev_pmd_thread *pmd;
4690 struct ovs_numa_dump *pmd_cores;
140dd699
IM
4691 struct ovs_numa_info_core *core;
4692 struct hmapx to_delete = HMAPX_INITIALIZER(&to_delete);
4693 struct hmapx_node *node;
e32971b8 4694 bool changed = false;
140dd699 4695 bool need_to_adjust_static_tx_qids = false;
e32971b8
DDP
4696
4697 /* The pmd threads should be started only if there's a pmd port in the
4698 * datapath. If the user didn't provide any "pmd-cpu-mask", we start
4699 * NR_PMD_THREADS per numa node. */
4700 if (!has_pmd_port(dp)) {
4701 pmd_cores = ovs_numa_dump_n_cores_per_numa(0);
4702 } else if (dp->pmd_cmask && dp->pmd_cmask[0]) {
4703 pmd_cores = ovs_numa_dump_cores_with_cmask(dp->pmd_cmask);
4704 } else {
4705 pmd_cores = ovs_numa_dump_n_cores_per_numa(NR_PMD_THREADS);
4706 }
4707
140dd699
IM
4708 /* We need to adjust 'static_tx_qid's only if we're reducing number of
4709 * PMD threads. Otherwise, new threads will allocate all the freed ids. */
4710 if (ovs_numa_dump_count(pmd_cores) < cmap_count(&dp->poll_threads) - 1) {
4711 /* Adjustment is required to keep 'static_tx_qid's sequential and
4712 * avoid possible issues, for example, imbalanced tx queue usage
4713 * and unnecessary locking caused by remapping on netdev level. */
4714 need_to_adjust_static_tx_qids = true;
4715 }
4716
4717 /* Check for unwanted pmd threads */
4718 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4719 if (pmd->core_id == NON_PMD_CORE_ID) {
4720 continue;
4721 }
4722 if (!ovs_numa_dump_contains_core(pmd_cores, pmd->numa_id,
4723 pmd->core_id)) {
4724 hmapx_add(&to_delete, pmd);
4725 } else if (need_to_adjust_static_tx_qids) {
e2cafa86 4726 atomic_store_relaxed(&pmd->reload_tx_qid, true);
140dd699 4727 pmd->need_reload = true;
e32971b8
DDP
4728 }
4729 }
4730
140dd699
IM
4731 HMAPX_FOR_EACH (node, &to_delete) {
4732 pmd = (struct dp_netdev_pmd_thread *) node->data;
4733 VLOG_INFO("PMD thread on numa_id: %d, core id: %2d destroyed.",
4734 pmd->numa_id, pmd->core_id);
4735 dp_netdev_del_pmd(dp, pmd);
4736 }
4737 changed = !hmapx_is_empty(&to_delete);
4738 hmapx_destroy(&to_delete);
e32971b8 4739
140dd699
IM
4740 if (need_to_adjust_static_tx_qids) {
4741 /* 'static_tx_qid's are not sequential now.
4742 * Reload remaining threads to fix this. */
4743 reload_affected_pmds(dp);
4744 }
e32971b8 4745
140dd699
IM
4746 /* Check for required new pmd threads */
4747 FOR_EACH_CORE_ON_DUMP(core, pmd_cores) {
4748 pmd = dp_netdev_get_pmd(dp, core->core_id);
4749 if (!pmd) {
8afbf2fa
IM
4750 struct ds name = DS_EMPTY_INITIALIZER;
4751
140dd699 4752 pmd = xzalloc(sizeof *pmd);
e32971b8 4753 dp_netdev_configure_pmd(pmd, dp, core->core_id, core->numa_id);
8afbf2fa
IM
4754
4755 ds_put_format(&name, "pmd-c%02d/id:", core->core_id);
4756 pmd->thread = ovs_thread_create(ds_cstr(&name),
4757 pmd_thread_main, pmd);
4758 ds_destroy(&name);
4759
140dd699
IM
4760 VLOG_INFO("PMD thread on numa_id: %d, core id: %2d created.",
4761 pmd->numa_id, pmd->core_id);
4762 changed = true;
4763 } else {
4764 dp_netdev_pmd_unref(pmd);
e32971b8 4765 }
140dd699
IM
4766 }
4767
4768 if (changed) {
4769 struct ovs_numa_info_numa *numa;
e32971b8
DDP
4770
4771 /* Log the number of pmd threads per numa node. */
4772 FOR_EACH_NUMA_ON_DUMP (numa, pmd_cores) {
140dd699 4773 VLOG_INFO("There are %"PRIuSIZE" pmd threads on numa node %d",
e32971b8
DDP
4774 numa->n_cores, numa->numa_id);
4775 }
4776 }
4777
4778 ovs_numa_dump_destroy(pmd_cores);
4779}
4780
e32971b8
DDP
4781static void
4782pmd_remove_stale_ports(struct dp_netdev *dp,
4783 struct dp_netdev_pmd_thread *pmd)
4784 OVS_EXCLUDED(pmd->port_mutex)
4785 OVS_REQUIRES(dp->port_mutex)
4786{
4787 struct rxq_poll *poll, *poll_next;
4788 struct tx_port *tx, *tx_next;
4789
4790 ovs_mutex_lock(&pmd->port_mutex);
4791 HMAP_FOR_EACH_SAFE (poll, poll_next, node, &pmd->poll_list) {
4792 struct dp_netdev_port *port = poll->rxq->port;
4793
4794 if (port->need_reconfigure
4795 || !hmap_contains(&dp->ports, &port->node)) {
4796 dp_netdev_del_rxq_from_pmd(pmd, poll);
4797 }
4798 }
4799 HMAP_FOR_EACH_SAFE (tx, tx_next, node, &pmd->tx_ports) {
4800 struct dp_netdev_port *port = tx->port;
4801
4802 if (port->need_reconfigure
4803 || !hmap_contains(&dp->ports, &port->node)) {
4804 dp_netdev_del_port_tx_from_pmd(pmd, tx);
4805 }
4806 }
4807 ovs_mutex_unlock(&pmd->port_mutex);
4808}
4809
4810/* Must be called each time a port is added/removed or the cmask changes.
4811 * This creates and destroys pmd threads, reconfigures ports, opens their
4812 * rxqs and assigns all rxqs/txqs to pmd threads. */
4813static void
4814reconfigure_datapath(struct dp_netdev *dp)
4815 OVS_REQUIRES(dp->port_mutex)
4816{
6d9fead1 4817 struct hmapx busy_threads = HMAPX_INITIALIZER(&busy_threads);
e32971b8
DDP
4818 struct dp_netdev_pmd_thread *pmd;
4819 struct dp_netdev_port *port;
4820 int wanted_txqs;
6e3c6fa4 4821
a6a426d6
IM
4822 dp->last_reconfigure_seq = seq_read(dp->reconfigure_seq);
4823
e32971b8
DDP
4824 /* Step 1: Adjust the pmd threads based on the datapath ports, the cores
4825 * on the system and the user configuration. */
4826 reconfigure_pmd_threads(dp);
6e3c6fa4 4827
e32971b8 4828 wanted_txqs = cmap_count(&dp->poll_threads);
324c8374 4829
e32971b8
DDP
4830 /* The number of pmd threads might have changed, or a port can be new:
4831 * adjust the txqs. */
4832 HMAP_FOR_EACH (port, node, &dp->ports) {
4833 netdev_set_tx_multiq(port->netdev, wanted_txqs);
324c8374
IM
4834 }
4835
e32971b8
DDP
4836 /* Step 2: Remove from the pmd threads ports that have been removed or
4837 * need reconfiguration. */
4838
4839 /* Check for all the ports that need reconfiguration. We cache this in
85a4f238
IM
4840 * 'port->need_reconfigure', because netdev_is_reconf_required() can
4841 * change at any time. */
e32971b8
DDP
4842 HMAP_FOR_EACH (port, node, &dp->ports) {
4843 if (netdev_is_reconf_required(port->netdev)) {
4844 port->need_reconfigure = true;
4845 }
4846 }
4847
4848 /* Remove from the pmd threads all the ports that have been deleted or
4849 * need reconfiguration. */
4850 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4851 pmd_remove_stale_ports(dp, pmd);
4852 }
4853
4854 /* Reload affected pmd threads. We must wait for the pmd threads before
4855 * reconfiguring the ports, because a port cannot be reconfigured while
4856 * it's being used. */
4857 reload_affected_pmds(dp);
4858
4859 /* Step 3: Reconfigure ports. */
4860
4861 /* We only reconfigure the ports that we determined above, because they're
4862 * not being used by any pmd thread at the moment. If a port fails to
4863 * reconfigure we remove it from the datapath. */
f582b6df
BP
4864 struct dp_netdev_port *next_port;
4865 HMAP_FOR_EACH_SAFE (port, next_port, node, &dp->ports) {
dc36593c 4866 int err;
6e3c6fa4 4867
e32971b8
DDP
4868 if (!port->need_reconfigure) {
4869 continue;
4870 }
4871
dc36593c
DDP
4872 err = port_reconfigure(port);
4873 if (err) {
4874 hmap_remove(&dp->ports, &port->node);
4875 seq_change(dp->port_seq);
4876 port_destroy(port);
324c8374 4877 } else {
e32971b8 4878 port->dynamic_txqs = netdev_n_txq(port->netdev) < wanted_txqs;
6e3c6fa4
DDP
4879 }
4880 }
e32971b8
DDP
4881
4882 /* Step 4: Compute new rxq scheduling. We don't touch the pmd threads
4883 * for now, we just update the 'pmd' pointer in each rxq to point to the
4884 * wanted thread according to the scheduling policy. */
4885
4886 /* Reset all the pmd threads to non isolated. */
4887 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4888 pmd->isolated = false;
4889 }
4890
4891 /* Reset all the queues to unassigned */
4892 HMAP_FOR_EACH (port, node, &dp->ports) {
4893 for (int i = 0; i < port->n_rxq; i++) {
4894 port->rxqs[i].pmd = NULL;
4895 }
4896 }
4897
4898 /* Add pinned queues and mark pmd threads isolated. */
4899 rxq_scheduling(dp, true);
4900
4901 /* Add non-pinned queues. */
4902 rxq_scheduling(dp, false);
4903
4904 /* Step 5: Remove queues not compliant with new scheduling. */
6d9fead1
DM
4905
4906 /* Count all the threads that will have at least one queue to poll. */
4907 HMAP_FOR_EACH (port, node, &dp->ports) {
4908 for (int qid = 0; qid < port->n_rxq; qid++) {
4909 struct dp_netdev_rxq *q = &port->rxqs[qid];
4910
4911 if (q->pmd) {
4912 hmapx_add(&busy_threads, q->pmd);
4913 }
4914 }
4915 }
4916
e32971b8
DDP
4917 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4918 struct rxq_poll *poll, *poll_next;
4919
4920 ovs_mutex_lock(&pmd->port_mutex);
4921 HMAP_FOR_EACH_SAFE (poll, poll_next, node, &pmd->poll_list) {
4922 if (poll->rxq->pmd != pmd) {
4923 dp_netdev_del_rxq_from_pmd(pmd, poll);
6d9fead1
DM
4924
4925 /* This pmd might sleep after this step if it has no rxq
4926 * remaining. Tell it to busy wait for new assignment if it
4927 * has at least one scheduled queue. */
4928 if (hmap_count(&pmd->poll_list) == 0 &&
4929 hmapx_contains(&busy_threads, pmd)) {
4930 atomic_store_relaxed(&pmd->wait_for_reload, true);
4931 }
e32971b8
DDP
4932 }
4933 }
4934 ovs_mutex_unlock(&pmd->port_mutex);
4935 }
4936
6d9fead1
DM
4937 hmapx_destroy(&busy_threads);
4938
e32971b8
DDP
4939 /* Reload affected pmd threads. We must wait for the pmd threads to remove
4940 * the old queues before readding them, otherwise a queue can be polled by
4941 * two threads at the same time. */
4942 reload_affected_pmds(dp);
4943
4944 /* Step 6: Add queues from scheduling, if they're not there already. */
4945 HMAP_FOR_EACH (port, node, &dp->ports) {
4946 if (!netdev_is_pmd(port->netdev)) {
4947 continue;
4948 }
4949
4950 for (int qid = 0; qid < port->n_rxq; qid++) {
4951 struct dp_netdev_rxq *q = &port->rxqs[qid];
4952
4953 if (q->pmd) {
4954 ovs_mutex_lock(&q->pmd->port_mutex);
4955 dp_netdev_add_rxq_to_pmd(q->pmd, q);
4956 ovs_mutex_unlock(&q->pmd->port_mutex);
4957 }
4958 }
4959 }
4960
4961 /* Add every port to the tx cache of every pmd thread, if it's not
4962 * there already and if this pmd has at least one rxq to poll. */
4963 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4964 ovs_mutex_lock(&pmd->port_mutex);
4965 if (hmap_count(&pmd->poll_list) || pmd->core_id == NON_PMD_CORE_ID) {
4966 HMAP_FOR_EACH (port, node, &dp->ports) {
4967 dp_netdev_add_port_tx_to_pmd(pmd, port);
4968 }
4969 }
4970 ovs_mutex_unlock(&pmd->port_mutex);
4971 }
4972
4973 /* Reload affected pmd threads. */
4974 reload_affected_pmds(dp);
5bf84282
NK
4975
4976 /* Check if PMD Auto LB is to be enabled */
4977 set_pmd_auto_lb(dp);
6e3c6fa4
DDP
4978}
4979
050c60bf
DDP
4980/* Returns true if one of the netdevs in 'dp' requires a reconfiguration */
4981static bool
4982ports_require_restart(const struct dp_netdev *dp)
4983 OVS_REQUIRES(dp->port_mutex)
4984{
4985 struct dp_netdev_port *port;
4986
4987 HMAP_FOR_EACH (port, node, &dp->ports) {
4988 if (netdev_is_reconf_required(port->netdev)) {
4989 return true;
4990 }
4991 }
4992
4993 return false;
4994}
4995
5bf84282
NK
4996/* Calculates variance in the values stored in array 'a'. 'n' is the number
4997 * of elements in array to be considered for calculating vairance.
4998 * Usage example: data array 'a' contains the processing load of each pmd and
4999 * 'n' is the number of PMDs. It returns the variance in processing load of
5000 * PMDs*/
5001static uint64_t
5002variance(uint64_t a[], int n)
5003{
5004 /* Compute mean (average of elements). */
5005 uint64_t sum = 0;
5006 uint64_t mean = 0;
5007 uint64_t sqDiff = 0;
5008
5009 if (!n) {
5010 return 0;
5011 }
5012
5013 for (int i = 0; i < n; i++) {
5014 sum += a[i];
5015 }
5016
5017 if (sum) {
5018 mean = sum / n;
5019
5020 /* Compute sum squared differences with mean. */
5021 for (int i = 0; i < n; i++) {
5022 sqDiff += (a[i] - mean)*(a[i] - mean);
5023 }
5024 }
5025 return (sqDiff ? (sqDiff / n) : 0);
5026}
5027
5028
5029/* Returns the variance in the PMDs usage as part of dry run of rxqs
5030 * assignment to PMDs. */
5031static bool
5032get_dry_run_variance(struct dp_netdev *dp, uint32_t *core_list,
5033 uint32_t num_pmds, uint64_t *predicted_variance)
5034 OVS_REQUIRES(dp->port_mutex)
5035{
5036 struct dp_netdev_port *port;
5037 struct dp_netdev_pmd_thread *pmd;
5038 struct dp_netdev_rxq **rxqs = NULL;
5039 struct rr_numa *numa = NULL;
5040 struct rr_numa_list rr;
5041 int n_rxqs = 0;
5042 bool ret = false;
5043 uint64_t *pmd_usage;
5044
5045 if (!predicted_variance) {
5046 return ret;
5047 }
5048
5049 pmd_usage = xcalloc(num_pmds, sizeof(uint64_t));
5050
5051 HMAP_FOR_EACH (port, node, &dp->ports) {
5052 if (!netdev_is_pmd(port->netdev)) {
5053 continue;
5054 }
5055
5056 for (int qid = 0; qid < port->n_rxq; qid++) {
5057 struct dp_netdev_rxq *q = &port->rxqs[qid];
5058 uint64_t cycle_hist = 0;
5059
5060 if (q->pmd->isolated) {
5061 continue;
5062 }
5063
5064 if (n_rxqs == 0) {
5065 rxqs = xmalloc(sizeof *rxqs);
5066 } else {
5067 rxqs = xrealloc(rxqs, sizeof *rxqs * (n_rxqs + 1));
5068 }
5069
5070 /* Sum the queue intervals and store the cycle history. */
5071 for (unsigned i = 0; i < PMD_RXQ_INTERVAL_MAX; i++) {
5072 cycle_hist += dp_netdev_rxq_get_intrvl_cycles(q, i);
5073 }
5074 dp_netdev_rxq_set_cycles(q, RXQ_CYCLES_PROC_HIST,
5075 cycle_hist);
5076 /* Store the queue. */
5077 rxqs[n_rxqs++] = q;
5078 }
5079 }
5080 if (n_rxqs > 1) {
5081 /* Sort the queues in order of the processing cycles
5082 * they consumed during their last pmd interval. */
5083 qsort(rxqs, n_rxqs, sizeof *rxqs, compare_rxq_cycles);
5084 }
5085 rr_numa_list_populate(dp, &rr);
5086
5087 for (int i = 0; i < n_rxqs; i++) {
5088 int numa_id = netdev_get_numa_id(rxqs[i]->port->netdev);
5089 numa = rr_numa_list_lookup(&rr, numa_id);
5090 if (!numa) {
5091 /* Abort if cross NUMA polling. */
5092 VLOG_DBG("PMD auto lb dry run."
5093 " Aborting due to cross-numa polling.");
5094 goto cleanup;
5095 }
5096
5097 pmd = rr_numa_get_pmd(numa, true);
5098 VLOG_DBG("PMD auto lb dry run. Predicted: Core %d on numa node %d "
5099 "to be assigned port \'%s\' rx queue %d "
5100 "(measured processing cycles %"PRIu64").",
5101 pmd->core_id, numa_id,
5102 netdev_rxq_get_name(rxqs[i]->rx),
5103 netdev_rxq_get_queue_id(rxqs[i]->rx),
5104 dp_netdev_rxq_get_cycles(rxqs[i], RXQ_CYCLES_PROC_HIST));
5105
5106 for (int id = 0; id < num_pmds; id++) {
5107 if (pmd->core_id == core_list[id]) {
5108 /* Add the processing cycles of rxq to pmd polling it. */
5109 pmd_usage[id] += dp_netdev_rxq_get_cycles(rxqs[i],
5110 RXQ_CYCLES_PROC_HIST);
5111 }
5112 }
5113 }
5114
5115 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
5116 uint64_t total_cycles = 0;
5117
5118 if ((pmd->core_id == NON_PMD_CORE_ID) || pmd->isolated) {
5119 continue;
5120 }
5121
5122 /* Get the total pmd cycles for an interval. */
5123 atomic_read_relaxed(&pmd->intrvl_cycles, &total_cycles);
5124 /* Estimate the cycles to cover all intervals. */
5125 total_cycles *= PMD_RXQ_INTERVAL_MAX;
5126 for (int id = 0; id < num_pmds; id++) {
5127 if (pmd->core_id == core_list[id]) {
5128 if (pmd_usage[id]) {
5129 pmd_usage[id] = (pmd_usage[id] * 100) / total_cycles;
5130 }
5131 VLOG_DBG("PMD auto lb dry run. Predicted: Core %d, "
5132 "usage %"PRIu64"", pmd->core_id, pmd_usage[id]);
5133 }
5134 }
5135 }
5136 *predicted_variance = variance(pmd_usage, num_pmds);
5137 ret = true;
5138
5139cleanup:
5140 rr_numa_list_destroy(&rr);
5141 free(rxqs);
5142 free(pmd_usage);
5143 return ret;
5144}
5145
5146/* Does the dry run of Rxq assignment to PMDs and returns true if it gives
5147 * better distribution of load on PMDs. */
5148static bool
5149pmd_rebalance_dry_run(struct dp_netdev *dp)
5150 OVS_REQUIRES(dp->port_mutex)
5151{
5152 struct dp_netdev_pmd_thread *pmd;
5153 uint64_t *curr_pmd_usage;
5154
5155 uint64_t curr_variance;
5156 uint64_t new_variance;
5157 uint64_t improvement = 0;
5158 uint32_t num_pmds;
5159 uint32_t *pmd_corelist;
eef85380 5160 struct rxq_poll *poll;
5bf84282
NK
5161 bool ret;
5162
5163 num_pmds = cmap_count(&dp->poll_threads);
5164
5165 if (num_pmds > 1) {
5166 curr_pmd_usage = xcalloc(num_pmds, sizeof(uint64_t));
5167 pmd_corelist = xcalloc(num_pmds, sizeof(uint32_t));
5168 } else {
5169 return false;
5170 }
5171
5172 num_pmds = 0;
5173 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
5174 uint64_t total_cycles = 0;
5175 uint64_t total_proc = 0;
5176
5177 if ((pmd->core_id == NON_PMD_CORE_ID) || pmd->isolated) {
5178 continue;
5179 }
5180
5181 /* Get the total pmd cycles for an interval. */
5182 atomic_read_relaxed(&pmd->intrvl_cycles, &total_cycles);
5183 /* Estimate the cycles to cover all intervals. */
5184 total_cycles *= PMD_RXQ_INTERVAL_MAX;
5185
eef85380
IM
5186 ovs_mutex_lock(&pmd->port_mutex);
5187 HMAP_FOR_EACH (poll, node, &pmd->poll_list) {
5bf84282 5188 for (unsigned i = 0; i < PMD_RXQ_INTERVAL_MAX; i++) {
eef85380 5189 total_proc += dp_netdev_rxq_get_intrvl_cycles(poll->rxq, i);
5bf84282 5190 }
5bf84282 5191 }
eef85380
IM
5192 ovs_mutex_unlock(&pmd->port_mutex);
5193
5bf84282
NK
5194 if (total_proc) {
5195 curr_pmd_usage[num_pmds] = (total_proc * 100) / total_cycles;
5196 }
5197
5198 VLOG_DBG("PMD auto lb dry run. Current: Core %d, usage %"PRIu64"",
5199 pmd->core_id, curr_pmd_usage[num_pmds]);
5200
5201 if (atomic_count_get(&pmd->pmd_overloaded)) {
5202 atomic_count_set(&pmd->pmd_overloaded, 0);
5203 }
5204
5205 pmd_corelist[num_pmds] = pmd->core_id;
5206 num_pmds++;
5207 }
5208
5209 curr_variance = variance(curr_pmd_usage, num_pmds);
5210 ret = get_dry_run_variance(dp, pmd_corelist, num_pmds, &new_variance);
5211
5212 if (ret) {
5213 VLOG_DBG("PMD auto lb dry run. Current PMD variance: %"PRIu64","
5214 " Predicted PMD variance: %"PRIu64"",
5215 curr_variance, new_variance);
5216
5217 if (new_variance < curr_variance) {
5218 improvement =
5219 ((curr_variance - new_variance) * 100) / curr_variance;
5220 }
5221 if (improvement < ALB_ACCEPTABLE_IMPROVEMENT) {
5222 ret = false;
5223 }
5224 }
5225
5226 free(curr_pmd_usage);
5227 free(pmd_corelist);
5228 return ret;
5229}
5230
5231
a36de779
PS
5232/* Return true if needs to revalidate datapath flows. */
5233static bool
e4cfed38
PS
5234dpif_netdev_run(struct dpif *dpif)
5235{
5236 struct dp_netdev_port *port;
5237 struct dp_netdev *dp = get_dp_netdev(dpif);
546e57d4 5238 struct dp_netdev_pmd_thread *non_pmd;
a36de779 5239 uint64_t new_tnl_seq;
c71ea3c4 5240 bool need_to_flush = true;
5bf84282
NK
5241 bool pmd_rebalance = false;
5242 long long int now = time_msec();
5243 struct dp_netdev_pmd_thread *pmd;
e4cfed38 5244
e9985d6a 5245 ovs_mutex_lock(&dp->port_mutex);
546e57d4
DDP
5246 non_pmd = dp_netdev_get_pmd(dp, NON_PMD_CORE_ID);
5247 if (non_pmd) {
5248 ovs_mutex_lock(&dp->non_pmd_mutex);
5249 HMAP_FOR_EACH (port, node, &dp->ports) {
5250 if (!netdev_is_pmd(port->netdev)) {
5251 int i;
55c955bd 5252
2fbadeb6
IM
5253 if (port->emc_enabled) {
5254 atomic_read_relaxed(&dp->emc_insert_min,
5255 &non_pmd->ctx.emc_insert_min);
5256 } else {
5257 non_pmd->ctx.emc_insert_min = 0;
5258 }
5259
546e57d4 5260 for (i = 0; i < port->n_rxq; i++) {
35c91567
DM
5261
5262 if (!netdev_rxq_enabled(port->rxqs[i].rx)) {
5263 continue;
5264 }
5265
c71ea3c4
IM
5266 if (dp_netdev_process_rxq_port(non_pmd,
5267 &port->rxqs[i],
5268 port->port_no)) {
5269 need_to_flush = false;
5270 }
546e57d4 5271 }
55c955bd 5272 }
e4cfed38 5273 }
c71ea3c4
IM
5274 if (need_to_flush) {
5275 /* We didn't receive anything in the process loop.
5276 * Check if we need to send something.
5277 * There was no time updates on current iteration. */
5278 pmd_thread_ctx_time_update(non_pmd);
5279 dp_netdev_pmd_flush_output_packets(non_pmd, false);
5280 }
5281
b010be17 5282 dpif_netdev_xps_revalidate_pmd(non_pmd, false);
546e57d4 5283 ovs_mutex_unlock(&dp->non_pmd_mutex);
6e3c6fa4 5284
546e57d4
DDP
5285 dp_netdev_pmd_unref(non_pmd);
5286 }
1c1e46ed 5287
5bf84282
NK
5288 struct pmd_auto_lb *pmd_alb = &dp->pmd_alb;
5289 if (pmd_alb->is_enabled) {
5290 if (!pmd_alb->rebalance_poll_timer) {
5291 pmd_alb->rebalance_poll_timer = now;
5292 } else if ((pmd_alb->rebalance_poll_timer +
5293 pmd_alb->rebalance_intvl) < now) {
5294 pmd_alb->rebalance_poll_timer = now;
5295 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
5296 if (atomic_count_get(&pmd->pmd_overloaded) >=
5297 PMD_RXQ_INTERVAL_MAX) {
5298 pmd_rebalance = true;
5299 break;
5300 }
5301 }
5302
5303 if (pmd_rebalance &&
5304 !dp_netdev_is_reconf_required(dp) &&
5305 !ports_require_restart(dp) &&
5306 pmd_rebalance_dry_run(dp)) {
5307 VLOG_INFO("PMD auto lb dry run."
5308 " requesting datapath reconfigure.");
5309 dp_netdev_request_reconfigure(dp);
5310 }
5311 }
5312 }
5313
a6a426d6 5314 if (dp_netdev_is_reconf_required(dp) || ports_require_restart(dp)) {
e32971b8 5315 reconfigure_datapath(dp);
6e3c6fa4
DDP
5316 }
5317 ovs_mutex_unlock(&dp->port_mutex);
5318
53902038 5319 tnl_neigh_cache_run();
7f9b8504 5320 tnl_port_map_run();
a36de779
PS
5321 new_tnl_seq = seq_read(tnl_conf_seq);
5322
5323 if (dp->last_tnl_conf_seq != new_tnl_seq) {
5324 dp->last_tnl_conf_seq = new_tnl_seq;
5325 return true;
5326 }
5327 return false;
e4cfed38
PS
5328}
5329
5330static void
5331dpif_netdev_wait(struct dpif *dpif)
5332{
5333 struct dp_netdev_port *port;
5334 struct dp_netdev *dp = get_dp_netdev(dpif);
5335
59e6d833 5336 ovs_mutex_lock(&dp_netdev_mutex);
e9985d6a
DDP
5337 ovs_mutex_lock(&dp->port_mutex);
5338 HMAP_FOR_EACH (port, node, &dp->ports) {
050c60bf 5339 netdev_wait_reconf_required(port->netdev);
55c955bd
PS
5340 if (!netdev_is_pmd(port->netdev)) {
5341 int i;
5342
490e82af 5343 for (i = 0; i < port->n_rxq; i++) {
947dc567 5344 netdev_rxq_wait(port->rxqs[i].rx);
55c955bd 5345 }
e4cfed38
PS
5346 }
5347 }
e9985d6a 5348 ovs_mutex_unlock(&dp->port_mutex);
59e6d833 5349 ovs_mutex_unlock(&dp_netdev_mutex);
a36de779 5350 seq_wait(tnl_conf_seq, dp->last_tnl_conf_seq);
e4cfed38
PS
5351}
5352
d0cca6c3
DDP
5353static void
5354pmd_free_cached_ports(struct dp_netdev_pmd_thread *pmd)
5355{
5356 struct tx_port *tx_port_cached;
5357
c71ea3c4
IM
5358 /* Flush all the queued packets. */
5359 dp_netdev_pmd_flush_output_packets(pmd, true);
324c8374 5360 /* Free all used tx queue ids. */
b010be17 5361 dpif_netdev_xps_revalidate_pmd(pmd, true);
324c8374 5362
57eebbb4
DDP
5363 HMAP_FOR_EACH_POP (tx_port_cached, node, &pmd->tnl_port_cache) {
5364 free(tx_port_cached);
5365 }
5366 HMAP_FOR_EACH_POP (tx_port_cached, node, &pmd->send_port_cache) {
d0cca6c3
DDP
5367 free(tx_port_cached);
5368 }
5369}
5370
5371/* Copies ports from 'pmd->tx_ports' (shared with the main thread) to
899363ed
BB
5372 * thread-local copies. Copy to 'pmd->tnl_port_cache' if it is a tunnel
5373 * device, otherwise to 'pmd->send_port_cache' if the port has at least
5374 * one txq. */
d0cca6c3
DDP
5375static void
5376pmd_load_cached_ports(struct dp_netdev_pmd_thread *pmd)
5377 OVS_REQUIRES(pmd->port_mutex)
5378{
5379 struct tx_port *tx_port, *tx_port_cached;
5380
5381 pmd_free_cached_ports(pmd);
57eebbb4
DDP
5382 hmap_shrink(&pmd->send_port_cache);
5383 hmap_shrink(&pmd->tnl_port_cache);
d0cca6c3
DDP
5384
5385 HMAP_FOR_EACH (tx_port, node, &pmd->tx_ports) {
57eebbb4
DDP
5386 if (netdev_has_tunnel_push_pop(tx_port->port->netdev)) {
5387 tx_port_cached = xmemdup(tx_port, sizeof *tx_port_cached);
5388 hmap_insert(&pmd->tnl_port_cache, &tx_port_cached->node,
5389 hash_port_no(tx_port_cached->port->port_no));
5390 }
5391
5392 if (netdev_n_txq(tx_port->port->netdev)) {
5393 tx_port_cached = xmemdup(tx_port, sizeof *tx_port_cached);
5394 hmap_insert(&pmd->send_port_cache, &tx_port_cached->node,
5395 hash_port_no(tx_port_cached->port->port_no));
5396 }
d0cca6c3
DDP
5397 }
5398}
5399
140dd699
IM
5400static void
5401pmd_alloc_static_tx_qid(struct dp_netdev_pmd_thread *pmd)
5402{
5403 ovs_mutex_lock(&pmd->dp->tx_qid_pool_mutex);
5404 if (!id_pool_alloc_id(pmd->dp->tx_qid_pool, &pmd->static_tx_qid)) {
5405 VLOG_ABORT("static_tx_qid allocation failed for PMD on core %2d"
5406 ", numa_id %d.", pmd->core_id, pmd->numa_id);
5407 }
5408 ovs_mutex_unlock(&pmd->dp->tx_qid_pool_mutex);
5409
5410 VLOG_DBG("static_tx_qid = %d allocated for PMD thread on core %2d"
5411 ", numa_id %d.", pmd->static_tx_qid, pmd->core_id, pmd->numa_id);
5412}
5413
5414static void
5415pmd_free_static_tx_qid(struct dp_netdev_pmd_thread *pmd)
5416{
5417 ovs_mutex_lock(&pmd->dp->tx_qid_pool_mutex);
5418 id_pool_free_id(pmd->dp->tx_qid_pool, pmd->static_tx_qid);
5419 ovs_mutex_unlock(&pmd->dp->tx_qid_pool_mutex);
5420}
5421
e4cfed38 5422static int
d0cca6c3 5423pmd_load_queues_and_ports(struct dp_netdev_pmd_thread *pmd,
947dc567 5424 struct polled_queue **ppoll_list)
e4cfed38 5425{
947dc567 5426 struct polled_queue *poll_list = *ppoll_list;
ae7ad0a1
IM
5427 struct rxq_poll *poll;
5428 int i;
e4cfed38 5429
d0cca6c3 5430 ovs_mutex_lock(&pmd->port_mutex);
947dc567
DDP
5431 poll_list = xrealloc(poll_list, hmap_count(&pmd->poll_list)
5432 * sizeof *poll_list);
a1fdee13 5433
ae7ad0a1 5434 i = 0;
947dc567 5435 HMAP_FOR_EACH (poll, node, &pmd->poll_list) {
922b28d4 5436 poll_list[i].rxq = poll->rxq;
947dc567 5437 poll_list[i].port_no = poll->rxq->port->port_no;
2fbadeb6 5438 poll_list[i].emc_enabled = poll->rxq->port->emc_enabled;
35c91567
DM
5439 poll_list[i].rxq_enabled = netdev_rxq_enabled(poll->rxq->rx);
5440 poll_list[i].change_seq =
5441 netdev_get_change_seq(poll->rxq->port->netdev);
947dc567 5442 i++;
e4cfed38 5443 }
d0cca6c3
DDP
5444
5445 pmd_load_cached_ports(pmd);
5446
5447 ovs_mutex_unlock(&pmd->port_mutex);
e4cfed38 5448
e4cfed38 5449 *ppoll_list = poll_list;
d42f9307 5450 return i;
e4cfed38
PS
5451}
5452
6c3eee82 5453static void *
e4cfed38 5454pmd_thread_main(void *f_)
6c3eee82 5455{
65f13b50 5456 struct dp_netdev_pmd_thread *pmd = f_;
82a48ead 5457 struct pmd_perf_stats *s = &pmd->perf_stats;
e4cfed38 5458 unsigned int lc = 0;
947dc567 5459 struct polled_queue *poll_list;
6d9fead1 5460 bool wait_for_reload = false;
e2cafa86 5461 bool reload_tx_qid;
d42f9307 5462 bool exiting;
6d9fead1 5463 bool reload;
e4cfed38
PS
5464 int poll_cnt;
5465 int i;
a2ac666d 5466 int process_packets = 0;
6c3eee82 5467
e4cfed38
PS
5468 poll_list = NULL;
5469
65f13b50
AW
5470 /* Stores the pmd thread's 'pmd' to 'per_pmd_key'. */
5471 ovsthread_setspecific(pmd->dp->per_pmd_key, pmd);
6930c7e0
DDP
5472 ovs_numa_thread_setaffinity_core(pmd->core_id);
5473 dpdk_set_lcore_id(pmd->core_id);
d0cca6c3 5474 poll_cnt = pmd_load_queues_and_ports(pmd, &poll_list);
60d8ccae 5475 dfc_cache_init(&pmd->flow_cache);
140dd699 5476 pmd_alloc_static_tx_qid(pmd);
ae7ad0a1 5477
e2cafa86 5478reload:
5bf84282
NK
5479 atomic_count_init(&pmd->pmd_overloaded, 0);
5480
7dd671f0
MK
5481 /* List port/core affinity */
5482 for (i = 0; i < poll_cnt; i++) {
ce179f11 5483 VLOG_DBG("Core %d processing port \'%s\' with queue-id %d\n",
922b28d4
KT
5484 pmd->core_id, netdev_rxq_get_name(poll_list[i].rxq->rx),
5485 netdev_rxq_get_queue_id(poll_list[i].rxq->rx));
4f5d13e2
KT
5486 /* Reset the rxq current cycles counter. */
5487 dp_netdev_rxq_set_cycles(poll_list[i].rxq, RXQ_CYCLES_PROC_CURR, 0);
7dd671f0
MK
5488 }
5489
2788a1b1 5490 if (!poll_cnt) {
6d9fead1
DM
5491 if (wait_for_reload) {
5492 /* Don't sleep, control thread will ask for a reload shortly. */
5493 do {
5494 atomic_read_explicit(&pmd->reload, &reload,
5495 memory_order_acquire);
5496 } while (!reload);
5497 } else {
5498 while (seq_read(pmd->reload_seq) == pmd->last_reload_seq) {
5499 seq_wait(pmd->reload_seq, pmd->last_reload_seq);
5500 poll_block();
5501 }
2788a1b1 5502 }
2788a1b1
DDP
5503 }
5504
2a2c67b4
KT
5505 pmd->intrvl_tsc_prev = 0;
5506 atomic_store_relaxed(&pmd->intrvl_cycles, 0);
a19896ab 5507 cycles_counter_update(s);
79f36875
JS
5508 /* Protect pmd stats from external clearing while polling. */
5509 ovs_mutex_lock(&pmd->perf_stats.stats_mutex);
e4cfed38 5510 for (;;) {
79f36875 5511 uint64_t rx_packets = 0, tx_packets = 0;
c71ea3c4 5512
a19896ab 5513 pmd_perf_start_iteration(s);
79f36875 5514
e4cfed38 5515 for (i = 0; i < poll_cnt; i++) {
2fbadeb6 5516
35c91567
DM
5517 if (!poll_list[i].rxq_enabled) {
5518 continue;
5519 }
5520
2fbadeb6
IM
5521 if (poll_list[i].emc_enabled) {
5522 atomic_read_relaxed(&pmd->dp->emc_insert_min,
5523 &pmd->ctx.emc_insert_min);
5524 } else {
5525 pmd->ctx.emc_insert_min = 0;
5526 }
5527
a2ac666d 5528 process_packets =
a19896ab 5529 dp_netdev_process_rxq_port(pmd, poll_list[i].rxq,
a2ac666d 5530 poll_list[i].port_no);
79f36875 5531 rx_packets += process_packets;
e4cfed38
PS
5532 }
5533
79f36875 5534 if (!rx_packets) {
c71ea3c4
IM
5535 /* We didn't receive anything in the process loop.
5536 * Check if we need to send something.
5537 * There was no time updates on current iteration. */
5538 pmd_thread_ctx_time_update(pmd);
79f36875 5539 tx_packets = dp_netdev_pmd_flush_output_packets(pmd, false);
c71ea3c4
IM
5540 }
5541
e4cfed38 5542 if (lc++ > 1024) {
e4cfed38 5543 lc = 0;
84067a4c 5544
fbe0962b 5545 coverage_try_clear();
4809891b 5546 dp_netdev_pmd_try_optimize(pmd, poll_list, poll_cnt);
9dede5cf 5547 if (!ovsrcu_try_quiesce()) {
60d8ccae 5548 emc_cache_slow_sweep(&((pmd->flow_cache).emc_cache));
9dede5cf 5549 }
84067a4c 5550
35c91567
DM
5551 for (i = 0; i < poll_cnt; i++) {
5552 uint64_t current_seq =
5553 netdev_get_change_seq(poll_list[i].rxq->port->netdev);
5554 if (poll_list[i].change_seq != current_seq) {
5555 poll_list[i].change_seq = current_seq;
5556 poll_list[i].rxq_enabled =
5557 netdev_rxq_enabled(poll_list[i].rxq->rx);
5558 }
5559 }
6c3eee82 5560 }
68a0625b
DM
5561
5562 atomic_read_explicit(&pmd->reload, &reload, memory_order_acquire);
5563 if (OVS_UNLIKELY(reload)) {
5564 break;
5565 }
5566
79f36875
JS
5567 pmd_perf_end_iteration(s, rx_packets, tx_packets,
5568 pmd_perf_metrics_enabled(pmd));
e4cfed38 5569 }
79f36875 5570 ovs_mutex_unlock(&pmd->perf_stats.stats_mutex);
6c3eee82 5571
d0cca6c3 5572 poll_cnt = pmd_load_queues_and_ports(pmd, &poll_list);
6d9fead1 5573 atomic_read_relaxed(&pmd->wait_for_reload, &wait_for_reload);
e2cafa86 5574 atomic_read_relaxed(&pmd->reload_tx_qid, &reload_tx_qid);
299c8d61 5575 atomic_read_relaxed(&pmd->exit, &exiting);
d42f9307
DDP
5576 /* Signal here to make sure the pmd finishes
5577 * reloading the updated configuration. */
5578 dp_netdev_pmd_reload_done(pmd);
5579
e2cafa86
DM
5580 if (reload_tx_qid) {
5581 pmd_free_static_tx_qid(pmd);
5582 pmd_alloc_static_tx_qid(pmd);
5583 }
9bbf1c3d 5584
d42f9307 5585 if (!exiting) {
e4cfed38
PS
5586 goto reload;
5587 }
6c3eee82 5588
e2cafa86 5589 pmd_free_static_tx_qid(pmd);
60d8ccae 5590 dfc_cache_uninit(&pmd->flow_cache);
e4cfed38 5591 free(poll_list);
d0cca6c3 5592 pmd_free_cached_ports(pmd);
6c3eee82
BP
5593 return NULL;
5594}
5595
6b31e073
RW
5596static void
5597dp_netdev_disable_upcall(struct dp_netdev *dp)
5598 OVS_ACQUIRES(dp->upcall_rwlock)
5599{
5600 fat_rwlock_wrlock(&dp->upcall_rwlock);
5601}
5602
5dddf960
JR
5603\f
5604/* Meters */
5605static void
5606dpif_netdev_meter_get_features(const struct dpif * dpif OVS_UNUSED,
5607 struct ofputil_meter_features *features)
5608{
4b27db64
JR
5609 features->max_meters = MAX_METERS;
5610 features->band_types = DP_SUPPORTED_METER_BAND_TYPES;
5611 features->capabilities = DP_SUPPORTED_METER_FLAGS_MASK;
5612 features->max_bands = MAX_BANDS;
5dddf960
JR
5613 features->max_color = 0;
5614}
5615
425a7b9e
JP
5616/* Applies the meter identified by 'meter_id' to 'packets_'. Packets
5617 * that exceed a band are dropped in-place. */
4b27db64
JR
5618static void
5619dp_netdev_run_meter(struct dp_netdev *dp, struct dp_packet_batch *packets_,
5620 uint32_t meter_id, long long int now)
5621{
5622 struct dp_meter *meter;
5623 struct dp_meter_band *band;
79c81260 5624 struct dp_packet *packet;
4b27db64
JR
5625 long long int long_delta_t; /* msec */
5626 uint32_t delta_t; /* msec */
79c81260 5627 const size_t cnt = dp_packet_batch_size(packets_);
4b27db64
JR
5628 uint32_t bytes, volume;
5629 int exceeded_band[NETDEV_MAX_BURST];
5630 uint32_t exceeded_rate[NETDEV_MAX_BURST];
5631 int exceeded_pkt = cnt; /* First packet that exceeded a band rate. */
5632
5633 if (meter_id >= MAX_METERS) {
5634 return;
5635 }
5636
5637 meter_lock(dp, meter_id);
5638 meter = dp->meters[meter_id];
5639 if (!meter) {
5640 goto out;
5641 }
5642
5643 /* Initialize as negative values. */
5644 memset(exceeded_band, 0xff, cnt * sizeof *exceeded_band);
5645 /* Initialize as zeroes. */
5646 memset(exceeded_rate, 0, cnt * sizeof *exceeded_rate);
5647
5648 /* All packets will hit the meter at the same time. */
42697ca7 5649 long_delta_t = now / 1000 - meter->used / 1000; /* msec */
4b27db64 5650
acc5df0e
IM
5651 if (long_delta_t < 0) {
5652 /* This condition means that we have several threads fighting for a
5653 meter lock, and the one who received the packets a bit later wins.
5654 Assuming that all racing threads received packets at the same time
5655 to avoid overflow. */
5656 long_delta_t = 0;
5657 }
5658
4b27db64
JR
5659 /* Make sure delta_t will not be too large, so that bucket will not
5660 * wrap around below. */
5661 delta_t = (long_delta_t > (long long int)meter->max_delta_t)
5662 ? meter->max_delta_t : (uint32_t)long_delta_t;
5663
5664 /* Update meter stats. */
5665 meter->used = now;
5666 meter->packet_count += cnt;
5667 bytes = 0;
e883448e 5668 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
79c81260 5669 bytes += dp_packet_size(packet);
4b27db64
JR
5670 }
5671 meter->byte_count += bytes;
5672
5673 /* Meters can operate in terms of packets per second or kilobits per
5674 * second. */
5675 if (meter->flags & OFPMF13_PKTPS) {
5676 /* Rate in packets/second, bucket 1/1000 packets. */
5677 /* msec * packets/sec = 1/1000 packets. */
5678 volume = cnt * 1000; /* Take 'cnt' packets from the bucket. */
5679 } else {
5680 /* Rate in kbps, bucket in bits. */
5681 /* msec * kbps = bits */
5682 volume = bytes * 8;
5683 }
5684
5685 /* Update all bands and find the one hit with the highest rate for each
5686 * packet (if any). */
5687 for (int m = 0; m < meter->n_bands; ++m) {
5688 band = &meter->bands[m];
5689
5690 /* Update band's bucket. */
5691 band->bucket += delta_t * band->up.rate;
5692 if (band->bucket > band->up.burst_size) {
5693 band->bucket = band->up.burst_size;
5694 }
5695
5696 /* Drain the bucket for all the packets, if possible. */
5697 if (band->bucket >= volume) {
5698 band->bucket -= volume;
5699 } else {
5700 int band_exceeded_pkt;
5701
5702 /* Band limit hit, must process packet-by-packet. */
5703 if (meter->flags & OFPMF13_PKTPS) {
5704 band_exceeded_pkt = band->bucket / 1000;
5705 band->bucket %= 1000; /* Remainder stays in bucket. */
5706
5707 /* Update the exceeding band for each exceeding packet.
5708 * (Only one band will be fired by a packet, and that
5709 * can be different for each packet.) */
e883448e 5710 for (int i = band_exceeded_pkt; i < cnt; i++) {
4b27db64
JR
5711 if (band->up.rate > exceeded_rate[i]) {
5712 exceeded_rate[i] = band->up.rate;
5713 exceeded_band[i] = m;
5714 }
5715 }
5716 } else {
5717 /* Packet sizes differ, must process one-by-one. */
5718 band_exceeded_pkt = cnt;
e883448e 5719 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
79c81260 5720 uint32_t bits = dp_packet_size(packet) * 8;
4b27db64
JR
5721
5722 if (band->bucket >= bits) {
5723 band->bucket -= bits;
5724 } else {
5725 if (i < band_exceeded_pkt) {
5726 band_exceeded_pkt = i;
5727 }
5728 /* Update the exceeding band for the exceeding packet.
5729 * (Only one band will be fired by a packet, and that
5730 * can be different for each packet.) */
5731 if (band->up.rate > exceeded_rate[i]) {
5732 exceeded_rate[i] = band->up.rate;
5733 exceeded_band[i] = m;
5734 }
5735 }
5736 }
5737 }
5738 /* Remember the first exceeding packet. */
5739 if (exceeded_pkt > band_exceeded_pkt) {
5740 exceeded_pkt = band_exceeded_pkt;
5741 }
5742 }
5743 }
5744
425a7b9e
JP
5745 /* Fire the highest rate band exceeded by each packet, and drop
5746 * packets if needed. */
4b27db64 5747 size_t j;
79c81260 5748 DP_PACKET_BATCH_REFILL_FOR_EACH (j, cnt, packet, packets_) {
4b27db64
JR
5749 if (exceeded_band[j] >= 0) {
5750 /* Meter drop packet. */
5751 band = &meter->bands[exceeded_band[j]];
5752 band->packet_count += 1;
5753 band->byte_count += dp_packet_size(packet);
5754
5755 dp_packet_delete(packet);
5756 } else {
5757 /* Meter accepts packet. */
5758 dp_packet_batch_refill(packets_, packet, j);
5759 }
5760 }
5761 out:
5762 meter_unlock(dp, meter_id);
5763}
5764
5765/* Meter set/get/del processing is still single-threaded. */
5dddf960 5766static int
8101f03f 5767dpif_netdev_meter_set(struct dpif *dpif, ofproto_meter_id meter_id,
4b27db64 5768 struct ofputil_meter_config *config)
5dddf960 5769{
4b27db64 5770 struct dp_netdev *dp = get_dp_netdev(dpif);
8101f03f 5771 uint32_t mid = meter_id.uint32;
4b27db64
JR
5772 struct dp_meter *meter;
5773 int i;
5774
4b27db64
JR
5775 if (mid >= MAX_METERS) {
5776 return EFBIG; /* Meter_id out of range. */
5777 }
5778
6508c845 5779 if (config->flags & ~DP_SUPPORTED_METER_FLAGS_MASK) {
4b27db64
JR
5780 return EBADF; /* Unsupported flags set */
5781 }
2029ce9a 5782
6508c845
JP
5783 if (config->n_bands > MAX_BANDS) {
5784 return EINVAL;
2029ce9a
AVA
5785 }
5786
4b27db64
JR
5787 for (i = 0; i < config->n_bands; ++i) {
5788 switch (config->bands[i].type) {
5789 case OFPMBT13_DROP:
5790 break;
5791 default:
5792 return ENODEV; /* Unsupported band type */
5793 }
5794 }
5795
5796 /* Allocate meter */
5797 meter = xzalloc(sizeof *meter
5798 + config->n_bands * sizeof(struct dp_meter_band));
4b27db64 5799
d0db81ea
JP
5800 meter->flags = config->flags;
5801 meter->n_bands = config->n_bands;
5802 meter->max_delta_t = 0;
5803 meter->used = time_usec();
4b27db64 5804
d0db81ea
JP
5805 /* set up bands */
5806 for (i = 0; i < config->n_bands; ++i) {
5807 uint32_t band_max_delta_t;
4b27db64 5808
d0db81ea
JP
5809 /* Set burst size to a workable value if none specified. */
5810 if (config->bands[i].burst_size == 0) {
5811 config->bands[i].burst_size = config->bands[i].rate;
5812 }
5813
5814 meter->bands[i].up = config->bands[i];
5815 /* Convert burst size to the bucket units: */
5816 /* pkts => 1/1000 packets, kilobits => bits. */
5817 meter->bands[i].up.burst_size *= 1000;
5818 /* Initialize bucket to empty. */
5819 meter->bands[i].bucket = 0;
5820
5821 /* Figure out max delta_t that is enough to fill any bucket. */
5822 band_max_delta_t
5823 = meter->bands[i].up.burst_size / meter->bands[i].up.rate;
5824 if (band_max_delta_t > meter->max_delta_t) {
5825 meter->max_delta_t = band_max_delta_t;
5826 }
4b27db64 5827 }
d0db81ea
JP
5828
5829 meter_lock(dp, mid);
5830 dp_delete_meter(dp, mid); /* Free existing meter, if any */
5831 dp->meters[mid] = meter;
5832 meter_unlock(dp, mid);
5833
5834 return 0;
5dddf960
JR
5835}
5836
5837static int
4b27db64
JR
5838dpif_netdev_meter_get(const struct dpif *dpif,
5839 ofproto_meter_id meter_id_,
5840 struct ofputil_meter_stats *stats, uint16_t n_bands)
5dddf960 5841{
4b27db64 5842 const struct dp_netdev *dp = get_dp_netdev(dpif);
4b27db64 5843 uint32_t meter_id = meter_id_.uint32;
866bc756 5844 int retval = 0;
4b27db64
JR
5845
5846 if (meter_id >= MAX_METERS) {
5847 return EFBIG;
5848 }
866bc756
JP
5849
5850 meter_lock(dp, meter_id);
5851 const struct dp_meter *meter = dp->meters[meter_id];
4b27db64 5852 if (!meter) {
866bc756
JP
5853 retval = ENOENT;
5854 goto done;
4b27db64
JR
5855 }
5856 if (stats) {
5857 int i = 0;
5858
4b27db64
JR
5859 stats->packet_in_count = meter->packet_count;
5860 stats->byte_in_count = meter->byte_count;
5861
5862 for (i = 0; i < n_bands && i < meter->n_bands; ++i) {
5863 stats->bands[i].packet_count = meter->bands[i].packet_count;
5864 stats->bands[i].byte_count = meter->bands[i].byte_count;
5865 }
4b27db64
JR
5866
5867 stats->n_bands = i;
5868 }
866bc756
JP
5869
5870done:
5871 meter_unlock(dp, meter_id);
5872 return retval;
5dddf960
JR
5873}
5874
5875static int
4b27db64
JR
5876dpif_netdev_meter_del(struct dpif *dpif,
5877 ofproto_meter_id meter_id_,
5878 struct ofputil_meter_stats *stats, uint16_t n_bands)
5dddf960 5879{
4b27db64
JR
5880 struct dp_netdev *dp = get_dp_netdev(dpif);
5881 int error;
5882
5883 error = dpif_netdev_meter_get(dpif, meter_id_, stats, n_bands);
5884 if (!error) {
5885 uint32_t meter_id = meter_id_.uint32;
5886
5887 meter_lock(dp, meter_id);
5888 dp_delete_meter(dp, meter_id);
5889 meter_unlock(dp, meter_id);
4b27db64
JR
5890 }
5891 return error;
5dddf960
JR
5892}
5893
5894\f
6b31e073
RW
5895static void
5896dpif_netdev_disable_upcall(struct dpif *dpif)
5897 OVS_NO_THREAD_SAFETY_ANALYSIS
5898{
5899 struct dp_netdev *dp = get_dp_netdev(dpif);
5900 dp_netdev_disable_upcall(dp);
5901}
5902
5903static void
5904dp_netdev_enable_upcall(struct dp_netdev *dp)
5905 OVS_RELEASES(dp->upcall_rwlock)
5906{
5907 fat_rwlock_unlock(&dp->upcall_rwlock);
5908}
5909
5910static void
5911dpif_netdev_enable_upcall(struct dpif *dpif)
5912 OVS_NO_THREAD_SAFETY_ANALYSIS
5913{
5914 struct dp_netdev *dp = get_dp_netdev(dpif);
5915 dp_netdev_enable_upcall(dp);
5916}
5917
ae7ad0a1 5918static void
accf8626
AW
5919dp_netdev_pmd_reload_done(struct dp_netdev_pmd_thread *pmd)
5920{
6d9fead1 5921 atomic_store_relaxed(&pmd->wait_for_reload, false);
e2cafa86 5922 atomic_store_relaxed(&pmd->reload_tx_qid, false);
2788a1b1 5923 pmd->last_reload_seq = seq_read(pmd->reload_seq);
8f077b31 5924 atomic_store_explicit(&pmd->reload, false, memory_order_release);
accf8626
AW
5925}
5926
1c1e46ed 5927/* Finds and refs the dp_netdev_pmd_thread on core 'core_id'. Returns
546e57d4
DDP
5928 * the pointer if succeeds, otherwise, NULL (it can return NULL even if
5929 * 'core_id' is NON_PMD_CORE_ID).
1c1e46ed
AW
5930 *
5931 * Caller must unrefs the returned reference. */
65f13b50 5932static struct dp_netdev_pmd_thread *
bd5131ba 5933dp_netdev_get_pmd(struct dp_netdev *dp, unsigned core_id)
65f13b50
AW
5934{
5935 struct dp_netdev_pmd_thread *pmd;
55847abe 5936 const struct cmap_node *pnode;
65f13b50 5937
b19befae 5938 pnode = cmap_find(&dp->poll_threads, hash_int(core_id, 0));
1c1e46ed
AW
5939 if (!pnode) {
5940 return NULL;
5941 }
65f13b50
AW
5942 pmd = CONTAINER_OF(pnode, struct dp_netdev_pmd_thread, node);
5943
1c1e46ed 5944 return dp_netdev_pmd_try_ref(pmd) ? pmd : NULL;
65f13b50
AW
5945}
5946
f2eee189
AW
5947/* Sets the 'struct dp_netdev_pmd_thread' for non-pmd threads. */
5948static void
5949dp_netdev_set_nonpmd(struct dp_netdev *dp)
e9985d6a 5950 OVS_REQUIRES(dp->port_mutex)
f2eee189
AW
5951{
5952 struct dp_netdev_pmd_thread *non_pmd;
5953
5954 non_pmd = xzalloc(sizeof *non_pmd);
00873463 5955 dp_netdev_configure_pmd(non_pmd, dp, NON_PMD_CORE_ID, OVS_NUMA_UNSPEC);
f2eee189
AW
5956}
5957
1c1e46ed
AW
5958/* Caller must have valid pointer to 'pmd'. */
5959static bool
5960dp_netdev_pmd_try_ref(struct dp_netdev_pmd_thread *pmd)
5961{
5962 return ovs_refcount_try_ref_rcu(&pmd->ref_cnt);
5963}
5964
5965static void
5966dp_netdev_pmd_unref(struct dp_netdev_pmd_thread *pmd)
5967{
5968 if (pmd && ovs_refcount_unref(&pmd->ref_cnt) == 1) {
5969 ovsrcu_postpone(dp_netdev_destroy_pmd, pmd);
5970 }
5971}
5972
5973/* Given cmap position 'pos', tries to ref the next node. If try_ref()
5974 * fails, keeps checking for next node until reaching the end of cmap.
5975 *
5976 * Caller must unrefs the returned reference. */
5977static struct dp_netdev_pmd_thread *
5978dp_netdev_pmd_get_next(struct dp_netdev *dp, struct cmap_position *pos)
5979{
5980 struct dp_netdev_pmd_thread *next;
5981
5982 do {
5983 struct cmap_node *node;
5984
5985 node = cmap_next_position(&dp->poll_threads, pos);
5986 next = node ? CONTAINER_OF(node, struct dp_netdev_pmd_thread, node)
5987 : NULL;
5988 } while (next && !dp_netdev_pmd_try_ref(next));
5989
5990 return next;
5991}
5992
65f13b50 5993/* Configures the 'pmd' based on the input argument. */
6c3eee82 5994static void
65f13b50 5995dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd, struct dp_netdev *dp,
00873463 5996 unsigned core_id, int numa_id)
65f13b50
AW
5997{
5998 pmd->dp = dp;
65f13b50
AW
5999 pmd->core_id = core_id;
6000 pmd->numa_id = numa_id;
e32971b8 6001 pmd->need_reload = false;
c71ea3c4 6002 pmd->n_output_batches = 0;
1c1e46ed
AW
6003
6004 ovs_refcount_init(&pmd->ref_cnt);
299c8d61 6005 atomic_init(&pmd->exit, false);
2788a1b1
DDP
6006 pmd->reload_seq = seq_create();
6007 pmd->last_reload_seq = seq_read(pmd->reload_seq);
14e3e12a 6008 atomic_init(&pmd->reload, false);
1c1e46ed 6009 ovs_mutex_init(&pmd->flow_mutex);
d0cca6c3 6010 ovs_mutex_init(&pmd->port_mutex);
1c1e46ed 6011 cmap_init(&pmd->flow_table);
3453b4d6 6012 cmap_init(&pmd->classifiers);
58ed6df0 6013 pmd->ctx.last_rxq = NULL;
b010be17
IM
6014 pmd_thread_ctx_time_update(pmd);
6015 pmd->next_optimization = pmd->ctx.now + DPCLS_OPTIMIZATION_INTERVAL;
6016 pmd->rxq_next_cycle_store = pmd->ctx.now + PMD_RXQ_INTERVAL_LEN;
947dc567 6017 hmap_init(&pmd->poll_list);
d0cca6c3 6018 hmap_init(&pmd->tx_ports);
57eebbb4
DDP
6019 hmap_init(&pmd->tnl_port_cache);
6020 hmap_init(&pmd->send_port_cache);
65f13b50
AW
6021 /* init the 'flow_cache' since there is no
6022 * actual thread created for NON_PMD_CORE_ID. */
6023 if (core_id == NON_PMD_CORE_ID) {
60d8ccae 6024 dfc_cache_init(&pmd->flow_cache);
140dd699 6025 pmd_alloc_static_tx_qid(pmd);
65f13b50 6026 }
82a48ead 6027 pmd_perf_stats_init(&pmd->perf_stats);
65f13b50
AW
6028 cmap_insert(&dp->poll_threads, CONST_CAST(struct cmap_node *, &pmd->node),
6029 hash_int(core_id, 0));
6030}
6031
1c1e46ed
AW
6032static void
6033dp_netdev_destroy_pmd(struct dp_netdev_pmd_thread *pmd)
6034{
3453b4d6
JS
6035 struct dpcls *cls;
6036
1c1e46ed 6037 dp_netdev_pmd_flow_flush(pmd);
57eebbb4
DDP
6038 hmap_destroy(&pmd->send_port_cache);
6039 hmap_destroy(&pmd->tnl_port_cache);
d0cca6c3 6040 hmap_destroy(&pmd->tx_ports);
947dc567 6041 hmap_destroy(&pmd->poll_list);
3453b4d6
JS
6042 /* All flows (including their dpcls_rules) have been deleted already */
6043 CMAP_FOR_EACH (cls, node, &pmd->classifiers) {
6044 dpcls_destroy(cls);
7c269972 6045 ovsrcu_postpone(free, cls);
3453b4d6
JS
6046 }
6047 cmap_destroy(&pmd->classifiers);
1c1e46ed
AW
6048 cmap_destroy(&pmd->flow_table);
6049 ovs_mutex_destroy(&pmd->flow_mutex);
2788a1b1 6050 seq_destroy(pmd->reload_seq);
d0cca6c3 6051 ovs_mutex_destroy(&pmd->port_mutex);
1c1e46ed
AW
6052 free(pmd);
6053}
6054
6055/* Stops the pmd thread, removes it from the 'dp->poll_threads',
6056 * and unrefs the struct. */
65f13b50 6057static void
e4e74c3a 6058dp_netdev_del_pmd(struct dp_netdev *dp, struct dp_netdev_pmd_thread *pmd)
6c3eee82 6059{
d0cca6c3
DDP
6060 /* NON_PMD_CORE_ID doesn't have a thread, so we don't have to synchronize,
6061 * but extra cleanup is necessary */
65f13b50 6062 if (pmd->core_id == NON_PMD_CORE_ID) {
febf4a7a 6063 ovs_mutex_lock(&dp->non_pmd_mutex);
60d8ccae 6064 dfc_cache_uninit(&pmd->flow_cache);
d0cca6c3 6065 pmd_free_cached_ports(pmd);
140dd699 6066 pmd_free_static_tx_qid(pmd);
febf4a7a 6067 ovs_mutex_unlock(&dp->non_pmd_mutex);
65f13b50 6068 } else {
299c8d61 6069 atomic_store_relaxed(&pmd->exit, true);
65f13b50 6070 dp_netdev_reload_pmd__(pmd);
65f13b50
AW
6071 xpthread_join(pmd->thread, NULL);
6072 }
ae7ad0a1 6073
d0cca6c3 6074 dp_netdev_pmd_clear_ports(pmd);
ae7ad0a1 6075
e4e74c3a
AW
6076 /* Purges the 'pmd''s flows after stopping the thread, but before
6077 * destroying the flows, so that the flow stats can be collected. */
6078 if (dp->dp_purge_cb) {
6079 dp->dp_purge_cb(dp->dp_purge_aux, pmd->core_id);
6080 }
65f13b50 6081 cmap_remove(&pmd->dp->poll_threads, &pmd->node, hash_int(pmd->core_id, 0));
1c1e46ed 6082 dp_netdev_pmd_unref(pmd);
65f13b50 6083}
6c3eee82 6084
e32971b8
DDP
6085/* Destroys all pmd threads. If 'non_pmd' is true it also destroys the non pmd
6086 * thread. */
65f13b50 6087static void
e32971b8 6088dp_netdev_destroy_all_pmds(struct dp_netdev *dp, bool non_pmd)
65f13b50
AW
6089{
6090 struct dp_netdev_pmd_thread *pmd;
d916785c
DDP
6091 struct dp_netdev_pmd_thread **pmd_list;
6092 size_t k = 0, n_pmds;
6093
e32971b8 6094 n_pmds = cmap_count(&dp->poll_threads);
d916785c 6095 pmd_list = xcalloc(n_pmds, sizeof *pmd_list);
65f13b50
AW
6096
6097 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
e32971b8 6098 if (!non_pmd && pmd->core_id == NON_PMD_CORE_ID) {
b9584f21
DDP
6099 continue;
6100 }
d916785c
DDP
6101 /* We cannot call dp_netdev_del_pmd(), since it alters
6102 * 'dp->poll_threads' (while we're iterating it) and it
6103 * might quiesce. */
6104 ovs_assert(k < n_pmds);
6105 pmd_list[k++] = pmd;
6c3eee82 6106 }
d916785c
DDP
6107
6108 for (size_t i = 0; i < k; i++) {
6109 dp_netdev_del_pmd(dp, pmd_list[i]);
6110 }
6111 free(pmd_list);
65f13b50 6112}
6c3eee82 6113
d0cca6c3
DDP
6114/* Deletes all rx queues from pmd->poll_list and all the ports from
6115 * pmd->tx_ports. */
cc245ce8 6116static void
d0cca6c3 6117dp_netdev_pmd_clear_ports(struct dp_netdev_pmd_thread *pmd)
cc245ce8
IM
6118{
6119 struct rxq_poll *poll;
d0cca6c3 6120 struct tx_port *port;
cc245ce8 6121
d0cca6c3 6122 ovs_mutex_lock(&pmd->port_mutex);
947dc567 6123 HMAP_FOR_EACH_POP (poll, node, &pmd->poll_list) {
cc245ce8
IM
6124 free(poll);
6125 }
d0cca6c3
DDP
6126 HMAP_FOR_EACH_POP (port, node, &pmd->tx_ports) {
6127 free(port);
6128 }
6129 ovs_mutex_unlock(&pmd->port_mutex);
cc245ce8
IM
6130}
6131
e32971b8 6132/* Adds rx queue to poll_list of PMD thread, if it's not there already. */
b68872d8 6133static void
e32971b8
DDP
6134dp_netdev_add_rxq_to_pmd(struct dp_netdev_pmd_thread *pmd,
6135 struct dp_netdev_rxq *rxq)
6136 OVS_REQUIRES(pmd->port_mutex)
b68872d8 6137{
e32971b8
DDP
6138 int qid = netdev_rxq_get_queue_id(rxq->rx);
6139 uint32_t hash = hash_2words(odp_to_u32(rxq->port->port_no), qid);
6140 struct rxq_poll *poll;
b68872d8 6141
e32971b8
DDP
6142 HMAP_FOR_EACH_WITH_HASH (poll, node, hash, &pmd->poll_list) {
6143 if (poll->rxq == rxq) {
6144 /* 'rxq' is already polled by this thread. Do nothing. */
6145 return;
d0cca6c3 6146 }
cc245ce8 6147 }
cc245ce8 6148
e32971b8
DDP
6149 poll = xmalloc(sizeof *poll);
6150 poll->rxq = rxq;
6151 hmap_insert(&pmd->poll_list, &poll->node, hash);
b68872d8 6152
e32971b8 6153 pmd->need_reload = true;
ae7ad0a1
IM
6154}
6155
e32971b8 6156/* Delete 'poll' from poll_list of PMD thread. */
ae7ad0a1 6157static void
e32971b8
DDP
6158dp_netdev_del_rxq_from_pmd(struct dp_netdev_pmd_thread *pmd,
6159 struct rxq_poll *poll)
d0cca6c3 6160 OVS_REQUIRES(pmd->port_mutex)
ae7ad0a1 6161{
e32971b8
DDP
6162 hmap_remove(&pmd->poll_list, &poll->node);
6163 free(poll);
ae7ad0a1 6164
e32971b8 6165 pmd->need_reload = true;
ae7ad0a1
IM
6166}
6167
d0cca6c3
DDP
6168/* Add 'port' to the tx port cache of 'pmd', which must be reloaded for the
6169 * changes to take effect. */
cc245ce8 6170static void
d0cca6c3
DDP
6171dp_netdev_add_port_tx_to_pmd(struct dp_netdev_pmd_thread *pmd,
6172 struct dp_netdev_port *port)
e32971b8 6173 OVS_REQUIRES(pmd->port_mutex)
d0cca6c3 6174{
57eebbb4
DDP
6175 struct tx_port *tx;
6176
e32971b8
DDP
6177 tx = tx_port_lookup(&pmd->tx_ports, port->port_no);
6178 if (tx) {
6179 /* 'port' is already on this thread tx cache. Do nothing. */
6180 return;
6181 }
6182
57eebbb4 6183 tx = xzalloc(sizeof *tx);
d0cca6c3 6184
324c8374
IM
6185 tx->port = port;
6186 tx->qid = -1;
c71ea3c4 6187 tx->flush_time = 0LL;
009e0033 6188 dp_packet_batch_init(&tx->output_pkts);
d0cca6c3 6189
324c8374 6190 hmap_insert(&pmd->tx_ports, &tx->node, hash_port_no(tx->port->port_no));
e32971b8 6191 pmd->need_reload = true;
d0cca6c3
DDP
6192}
6193
e32971b8
DDP
6194/* Del 'tx' from the tx port cache of 'pmd', which must be reloaded for the
6195 * changes to take effect. */
b9584f21 6196static void
e32971b8
DDP
6197dp_netdev_del_port_tx_from_pmd(struct dp_netdev_pmd_thread *pmd,
6198 struct tx_port *tx)
6199 OVS_REQUIRES(pmd->port_mutex)
b9584f21 6200{
e32971b8
DDP
6201 hmap_remove(&pmd->tx_ports, &tx->node);
6202 free(tx);
6203 pmd->need_reload = true;
6c3eee82
BP
6204}
6205\f
b5cbbcf6
AZ
6206static char *
6207dpif_netdev_get_datapath_version(void)
6208{
6209 return xstrdup("<built-in>");
6210}
6211
72865317 6212static void
1c1e46ed 6213dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow, int cnt, int size,
11bfdadd 6214 uint16_t tcp_flags, long long now)
72865317 6215{
eb94da30 6216 uint16_t flags;
72865317 6217
eb94da30
DDP
6218 atomic_store_relaxed(&netdev_flow->stats.used, now);
6219 non_atomic_ullong_add(&netdev_flow->stats.packet_count, cnt);
6220 non_atomic_ullong_add(&netdev_flow->stats.byte_count, size);
6221 atomic_read_relaxed(&netdev_flow->stats.tcp_flags, &flags);
6222 flags |= tcp_flags;
6223 atomic_store_relaxed(&netdev_flow->stats.tcp_flags, flags);
51852a57
BP
6224}
6225
623540e4 6226static int
e14deea0 6227dp_netdev_upcall(struct dp_netdev_pmd_thread *pmd, struct dp_packet *packet_,
7af12bd7 6228 struct flow *flow, struct flow_wildcards *wc, ovs_u128 *ufid,
623540e4
EJ
6229 enum dpif_upcall_type type, const struct nlattr *userdata,
6230 struct ofpbuf *actions, struct ofpbuf *put_actions)
6231{
1c1e46ed 6232 struct dp_netdev *dp = pmd->dp;
623540e4 6233
623540e4
EJ
6234 if (OVS_UNLIKELY(!dp->upcall_cb)) {
6235 return ENODEV;
6236 }
6237
6238 if (OVS_UNLIKELY(!VLOG_DROP_DBG(&upcall_rl))) {
6239 struct ds ds = DS_EMPTY_INITIALIZER;
623540e4 6240 char *packet_str;
cf62fa4c 6241 struct ofpbuf key;
5262eea1
JG
6242 struct odp_flow_key_parms odp_parms = {
6243 .flow = flow,
1dea1435 6244 .mask = wc ? &wc->masks : NULL,
2494ccd7 6245 .support = dp_netdev_support,
5262eea1 6246 };
623540e4
EJ
6247
6248 ofpbuf_init(&key, 0);
5262eea1 6249 odp_flow_key_from_flow(&odp_parms, &key);
2482b0b0 6250 packet_str = ofp_dp_packet_to_string(packet_);
623540e4 6251
6fd6ed71 6252 odp_flow_key_format(key.data, key.size, &ds);
623540e4
EJ
6253
6254 VLOG_DBG("%s: %s upcall:\n%s\n%s", dp->name,
6255 dpif_upcall_type_to_string(type), ds_cstr(&ds), packet_str);
6256
6257 ofpbuf_uninit(&key);
6258 free(packet_str);
6fd6ed71 6259
623540e4
EJ
6260 ds_destroy(&ds);
6261 }
6262
8d8ab6c2
JG
6263 return dp->upcall_cb(packet_, flow, ufid, pmd->core_id, type, userdata,
6264 actions, wc, put_actions, dp->upcall_aux);
623540e4
EJ
6265}
6266
bde94613
FA
6267static inline uint32_t
6268dpif_netdev_packet_get_rss_hash_orig_pkt(struct dp_packet *packet,
6269 const struct miniflow *mf)
6270{
6271 uint32_t hash;
6272
6273 if (OVS_LIKELY(dp_packet_rss_valid(packet))) {
6274 hash = dp_packet_get_rss_hash(packet);
6275 } else {
6276 hash = miniflow_hash_5tuple(mf, 0);
6277 dp_packet_set_rss_hash(packet, hash);
6278 }
6279
6280 return hash;
6281}
6282
9bbf1c3d 6283static inline uint32_t
048963aa
DDP
6284dpif_netdev_packet_get_rss_hash(struct dp_packet *packet,
6285 const struct miniflow *mf)
9bbf1c3d 6286{
048963aa 6287 uint32_t hash, recirc_depth;
9bbf1c3d 6288
f2f44f5d
DDP
6289 if (OVS_LIKELY(dp_packet_rss_valid(packet))) {
6290 hash = dp_packet_get_rss_hash(packet);
6291 } else {
9bbf1c3d 6292 hash = miniflow_hash_5tuple(mf, 0);
2bc1bbd2 6293 dp_packet_set_rss_hash(packet, hash);
9bbf1c3d 6294 }
048963aa
DDP
6295
6296 /* The RSS hash must account for the recirculation depth to avoid
6297 * collisions in the exact match cache */
6298 recirc_depth = *recirc_depth_get_unsafe();
6299 if (OVS_UNLIKELY(recirc_depth)) {
6300 hash = hash_finish(hash, recirc_depth);
048963aa 6301 }
9bbf1c3d
DDP
6302 return hash;
6303}
6304
f7ce4811 6305struct packet_batch_per_flow {
8cbf4f47
DDP
6306 unsigned int byte_count;
6307 uint16_t tcp_flags;
8cbf4f47
DDP
6308 struct dp_netdev_flow *flow;
6309
1895cc8d 6310 struct dp_packet_batch array;
8cbf4f47
DDP
6311};
6312
6313static inline void
f7ce4811
PS
6314packet_batch_per_flow_update(struct packet_batch_per_flow *batch,
6315 struct dp_packet *packet,
aab96ec4 6316 uint16_t tcp_flags)
8cbf4f47 6317{
cf62fa4c 6318 batch->byte_count += dp_packet_size(packet);
aab96ec4 6319 batch->tcp_flags |= tcp_flags;
940ac2ce 6320 dp_packet_batch_add(&batch->array, packet);
8cbf4f47
DDP
6321}
6322
6323static inline void
f7ce4811
PS
6324packet_batch_per_flow_init(struct packet_batch_per_flow *batch,
6325 struct dp_netdev_flow *flow)
8cbf4f47 6326{
11e5cf1f 6327 flow->batch = batch;
8cbf4f47 6328
11e5cf1f 6329 batch->flow = flow;
1895cc8d 6330 dp_packet_batch_init(&batch->array);
8cbf4f47
DDP
6331 batch->byte_count = 0;
6332 batch->tcp_flags = 0;
8cbf4f47
DDP
6333}
6334
6335static inline void
f7ce4811 6336packet_batch_per_flow_execute(struct packet_batch_per_flow *batch,
b010be17 6337 struct dp_netdev_pmd_thread *pmd)
8cbf4f47
DDP
6338{
6339 struct dp_netdev_actions *actions;
6340 struct dp_netdev_flow *flow = batch->flow;
6341
940ac2ce
PC
6342 dp_netdev_flow_used(flow, dp_packet_batch_size(&batch->array),
6343 batch->byte_count,
05f9e707 6344 batch->tcp_flags, pmd->ctx.now / 1000);
8cbf4f47
DDP
6345
6346 actions = dp_netdev_flow_get_actions(flow);
6347
66e4ad8a 6348 dp_netdev_execute_actions(pmd, &batch->array, true, &flow->flow,
b010be17 6349 actions->actions, actions->size);
8cbf4f47
DDP
6350}
6351
8aaa125d 6352static inline void
e14deea0 6353dp_netdev_queue_batches(struct dp_packet *pkt,
aab96ec4 6354 struct dp_netdev_flow *flow, uint16_t tcp_flags,
47a45d86
KT
6355 struct packet_batch_per_flow *batches,
6356 size_t *n_batches)
9bbf1c3d 6357{
f7ce4811 6358 struct packet_batch_per_flow *batch = flow->batch;
11e5cf1f 6359
f9fe365b
AZ
6360 if (OVS_UNLIKELY(!batch)) {
6361 batch = &batches[(*n_batches)++];
f7ce4811 6362 packet_batch_per_flow_init(batch, flow);
9bbf1c3d
DDP
6363 }
6364
aab96ec4 6365 packet_batch_per_flow_update(batch, pkt, tcp_flags);
9bbf1c3d
DDP
6366}
6367
9b4f08cd
VDA
6368static inline void
6369packet_enqueue_to_flow_map(struct dp_packet *packet,
6370 struct dp_netdev_flow *flow,
6371 uint16_t tcp_flags,
6372 struct dp_packet_flow_map *flow_map,
6373 size_t index)
6374{
6375 struct dp_packet_flow_map *map = &flow_map[index];
6376 map->flow = flow;
6377 map->packet = packet;
6378 map->tcp_flags = tcp_flags;
6379}
6380
60d8ccae
YW
6381/* SMC lookup function for a batch of packets.
6382 * By doing batching SMC lookup, we can use prefetch
6383 * to hide memory access latency.
6384 */
6385static inline void
6386smc_lookup_batch(struct dp_netdev_pmd_thread *pmd,
6387 struct netdev_flow_key *keys,
6388 struct netdev_flow_key **missed_keys,
6389 struct dp_packet_batch *packets_,
9b4f08cd
VDA
6390 const int cnt,
6391 struct dp_packet_flow_map *flow_map,
6392 uint8_t *index_map)
60d8ccae
YW
6393{
6394 int i;
6395 struct dp_packet *packet;
6396 size_t n_smc_hit = 0, n_missed = 0;
6397 struct dfc_cache *cache = &pmd->flow_cache;
6398 struct smc_cache *smc_cache = &cache->smc_cache;
6399 const struct cmap_node *flow_node;
9b4f08cd
VDA
6400 int recv_idx;
6401 uint16_t tcp_flags;
60d8ccae
YW
6402
6403 /* Prefetch buckets for all packets */
6404 for (i = 0; i < cnt; i++) {
6405 OVS_PREFETCH(&smc_cache->buckets[keys[i].hash & SMC_MASK]);
6406 }
6407
6408 DP_PACKET_BATCH_REFILL_FOR_EACH (i, cnt, packet, packets_) {
6409 struct dp_netdev_flow *flow = NULL;
6410 flow_node = smc_entry_get(pmd, keys[i].hash);
6411 bool hit = false;
9b4f08cd
VDA
6412 /* Get the original order of this packet in received batch. */
6413 recv_idx = index_map[i];
60d8ccae
YW
6414
6415 if (OVS_LIKELY(flow_node != NULL)) {
6416 CMAP_NODE_FOR_EACH (flow, node, flow_node) {
6417 /* Since we dont have per-port megaflow to check the port
6418 * number, we need to verify that the input ports match. */
6419 if (OVS_LIKELY(dpcls_rule_matches_key(&flow->cr, &keys[i]) &&
6420 flow->flow.in_port.odp_port == packet->md.in_port.odp_port)) {
9b4f08cd
VDA
6421 tcp_flags = miniflow_get_tcp_flags(&keys[i].mf);
6422
60d8ccae 6423 /* SMC hit and emc miss, we insert into EMC */
60d8ccae
YW
6424 keys[i].len =
6425 netdev_flow_key_size(miniflow_n_values(&keys[i].mf));
18e08953 6426 emc_probabilistic_insert(pmd, &keys[i], flow);
9b4f08cd
VDA
6427 /* Add these packets into the flow map in the same order
6428 * as received.
6429 */
6430 packet_enqueue_to_flow_map(packet, flow, tcp_flags,
6431 flow_map, recv_idx);
60d8ccae
YW
6432 n_smc_hit++;
6433 hit = true;
6434 break;
6435 }
6436 }
6437 if (hit) {
6438 continue;
6439 }
6440 }
6441
6442 /* SMC missed. Group missed packets together at
6443 * the beginning of the 'packets' array. */
6444 dp_packet_batch_refill(packets_, packet, i);
9b4f08cd
VDA
6445
6446 /* Preserve the order of packet for flow batching. */
6447 index_map[n_missed] = recv_idx;
6448
60d8ccae
YW
6449 /* Put missed keys to the pointer arrays return to the caller */
6450 missed_keys[n_missed++] = &keys[i];
6451 }
6452
6453 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_SMC_HIT, n_smc_hit);
6454}
6455
6456/* Try to process all ('cnt') the 'packets' using only the datapath flow cache
a90ed026 6457 * 'pmd->flow_cache'. If a flow is not found for a packet 'packets[i]', the
8aaa125d 6458 * miniflow is copied into 'keys' and the packet pointer is moved at the
60d8ccae
YW
6459 * beginning of the 'packets' array. The pointers of missed keys are put in the
6460 * missed_keys pointer array for future processing.
9bbf1c3d
DDP
6461 *
6462 * The function returns the number of packets that needs to be processed in the
6463 * 'packets' array (they have been moved to the beginning of the vector).
a90ed026 6464 *
02305520
FA
6465 * For performance reasons a caller may choose not to initialize the metadata
6466 * in 'packets_'. If 'md_is_valid' is false, the metadata in 'packets'
6467 * is not valid and must be initialized by this function using 'port_no'.
6468 * If 'md_is_valid' is true, the metadata is already valid and 'port_no'
6469 * will be ignored.
9bbf1c3d
DDP
6470 */
6471static inline size_t
60d8ccae 6472dfc_processing(struct dp_netdev_pmd_thread *pmd,
72c84bc2 6473 struct dp_packet_batch *packets_,
1895cc8d 6474 struct netdev_flow_key *keys,
60d8ccae 6475 struct netdev_flow_key **missed_keys,
f7ce4811 6476 struct packet_batch_per_flow batches[], size_t *n_batches,
9b4f08cd
VDA
6477 struct dp_packet_flow_map *flow_map,
6478 size_t *n_flows, uint8_t *index_map,
a90ed026 6479 bool md_is_valid, odp_port_t port_no)
72865317 6480{
b89c678b 6481 struct netdev_flow_key *key = &keys[0];
60d8ccae
YW
6482 size_t n_missed = 0, n_emc_hit = 0;
6483 struct dfc_cache *cache = &pmd->flow_cache;
72c84bc2 6484 struct dp_packet *packet;
45df9fef 6485 const size_t cnt = dp_packet_batch_size(packets_);
2fbadeb6 6486 uint32_t cur_min = pmd->ctx.emc_insert_min;
72c84bc2 6487 int i;
aab96ec4 6488 uint16_t tcp_flags;
60d8ccae 6489 bool smc_enable_db;
9b4f08cd
VDA
6490 size_t map_cnt = 0;
6491 bool batch_enable = true;
8cbf4f47 6492
60d8ccae 6493 atomic_read_relaxed(&pmd->dp->smc_enable_db, &smc_enable_db);
82a48ead
JS
6494 pmd_perf_update_counter(&pmd->perf_stats,
6495 md_is_valid ? PMD_STAT_RECIRC : PMD_STAT_RECV,
6496 cnt);
f79b1ddb 6497
45df9fef 6498 DP_PACKET_BATCH_REFILL_FOR_EACH (i, cnt, packet, packets_) {
9bbf1c3d 6499 struct dp_netdev_flow *flow;
aab96ec4 6500 uint32_t mark;
9bbf1c3d 6501
5a2fed48
AZ
6502 if (OVS_UNLIKELY(dp_packet_size(packet) < ETH_HEADER_LEN)) {
6503 dp_packet_delete(packet);
84d6d5eb
EJ
6504 continue;
6505 }
8cbf4f47 6506
45df9fef 6507 if (i != cnt - 1) {
72c84bc2 6508 struct dp_packet **packets = packets_->packets;
a90ed026 6509 /* Prefetch next packet data and metadata. */
72a5e2b8 6510 OVS_PREFETCH(dp_packet_data(packets[i+1]));
a90ed026 6511 pkt_metadata_prefetch_init(&packets[i+1]->md);
72a5e2b8
DDP
6512 }
6513
a90ed026
DDP
6514 if (!md_is_valid) {
6515 pkt_metadata_init(&packet->md, port_no);
6516 }
aab96ec4
YL
6517
6518 if ((*recirc_depth_get() == 0) &&
6519 dp_packet_has_flow_mark(packet, &mark)) {
6520 flow = mark_to_flow_find(pmd, mark);
9b4f08cd 6521 if (OVS_LIKELY(flow)) {
aab96ec4 6522 tcp_flags = parse_tcp_flags(packet);
9b4f08cd
VDA
6523 if (OVS_LIKELY(batch_enable)) {
6524 dp_netdev_queue_batches(packet, flow, tcp_flags, batches,
6525 n_batches);
6526 } else {
6527 /* Flow batching should be performed only after fast-path
6528 * processing is also completed for packets with emc miss
6529 * or else it will result in reordering of packets with
6530 * same datapath flows. */
6531 packet_enqueue_to_flow_map(packet, flow, tcp_flags,
6532 flow_map, map_cnt++);
6533 }
aab96ec4
YL
6534 continue;
6535 }
6536 }
6537
5a2fed48 6538 miniflow_extract(packet, &key->mf);
d262ac2c 6539 key->len = 0; /* Not computed yet. */
b137383e
IM
6540 key->hash =
6541 (md_is_valid == false)
6542 ? dpif_netdev_packet_get_rss_hash_orig_pkt(packet, &key->mf)
6543 : dpif_netdev_packet_get_rss_hash(packet, &key->mf);
6544
6545 /* If EMC is disabled skip emc_lookup */
6546 flow = (cur_min != 0) ? emc_lookup(&cache->emc_cache, key) : NULL;
8aaa125d 6547 if (OVS_LIKELY(flow)) {
aab96ec4 6548 tcp_flags = miniflow_get_tcp_flags(&key->mf);
60d8ccae 6549 n_emc_hit++;
9b4f08cd
VDA
6550 if (OVS_LIKELY(batch_enable)) {
6551 dp_netdev_queue_batches(packet, flow, tcp_flags, batches,
6552 n_batches);
6553 } else {
6554 /* Flow batching should be performed only after fast-path
6555 * processing is also completed for packets with emc miss
6556 * or else it will result in reordering of packets with
6557 * same datapath flows. */
6558 packet_enqueue_to_flow_map(packet, flow, tcp_flags,
6559 flow_map, map_cnt++);
6560 }
8aaa125d 6561 } else {
d1aa0b94 6562 /* Exact match cache missed. Group missed packets together at
72c84bc2
AZ
6563 * the beginning of the 'packets' array. */
6564 dp_packet_batch_refill(packets_, packet, i);
9b4f08cd
VDA
6565
6566 /* Preserve the order of packet for flow batching. */
6567 index_map[n_missed] = map_cnt;
6568 flow_map[map_cnt++].flow = NULL;
6569
400486f7 6570 /* 'key[n_missed]' contains the key of the current packet and it
60d8ccae
YW
6571 * will be passed to SMC lookup. The next key should be extracted
6572 * to 'keys[n_missed + 1]'.
6573 * We also maintain a pointer array to keys missed both SMC and EMC
6574 * which will be returned to the caller for future processing. */
6575 missed_keys[n_missed] = key;
400486f7 6576 key = &keys[++n_missed];
9b4f08cd
VDA
6577
6578 /* Skip batching for subsequent packets to avoid reordering. */
6579 batch_enable = false;
9bbf1c3d
DDP
6580 }
6581 }
9b4f08cd
VDA
6582 /* Count of packets which are not flow batched. */
6583 *n_flows = map_cnt;
9bbf1c3d 6584
60d8ccae
YW
6585 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_EXACT_HIT, n_emc_hit);
6586
6587 if (!smc_enable_db) {
6588 return dp_packet_batch_size(packets_);
6589 }
6590
6591 /* Packets miss EMC will do a batch lookup in SMC if enabled */
9b4f08cd
VDA
6592 smc_lookup_batch(pmd, keys, missed_keys, packets_,
6593 n_missed, flow_map, index_map);
4f150744 6594
72c84bc2 6595 return dp_packet_batch_size(packets_);
9bbf1c3d
DDP
6596}
6597
82a48ead 6598static inline int
47a45d86
KT
6599handle_packet_upcall(struct dp_netdev_pmd_thread *pmd,
6600 struct dp_packet *packet,
a260d966 6601 const struct netdev_flow_key *key,
82a48ead 6602 struct ofpbuf *actions, struct ofpbuf *put_actions)
a260d966
PS
6603{
6604 struct ofpbuf *add_actions;
6605 struct dp_packet_batch b;
6606 struct match match;
6607 ovs_u128 ufid;
6608 int error;
79f36875 6609 uint64_t cycles = cycles_counter_update(&pmd->perf_stats);
a260d966
PS
6610
6611 match.tun_md.valid = false;
6612 miniflow_expand(&key->mf, &match.flow);
c98eedf9 6613 memset(&match.wc, 0, sizeof match.wc);
a260d966
PS
6614
6615 ofpbuf_clear(actions);
6616 ofpbuf_clear(put_actions);
6617
6618 dpif_flow_hash(pmd->dp->dpif, &match.flow, sizeof match.flow, &ufid);
6619 error = dp_netdev_upcall(pmd, packet, &match.flow, &match.wc,
6620 &ufid, DPIF_UC_MISS, NULL, actions,
6621 put_actions);
6622 if (OVS_UNLIKELY(error && error != ENOSPC)) {
6623 dp_packet_delete(packet);
82a48ead 6624 return error;
a260d966
PS
6625 }
6626
6627 /* The Netlink encoding of datapath flow keys cannot express
6628 * wildcarding the presence of a VLAN tag. Instead, a missing VLAN
6629 * tag is interpreted as exact match on the fact that there is no
6630 * VLAN. Unless we refactor a lot of code that translates between
6631 * Netlink and struct flow representations, we have to do the same
35fe9efb 6632 * here. This must be in sync with 'match' in dpif_netdev_flow_put(). */
f0fb825a
EG
6633 if (!match.wc.masks.vlans[0].tci) {
6634 match.wc.masks.vlans[0].tci = htons(0xffff);
a260d966
PS
6635 }
6636
6637 /* We can't allow the packet batching in the next loop to execute
6638 * the actions. Otherwise, if there are any slow path actions,
6639 * we'll send the packet up twice. */
72c84bc2 6640 dp_packet_batch_init_packet(&b, packet);
66e4ad8a 6641 dp_netdev_execute_actions(pmd, &b, true, &match.flow,
b010be17 6642 actions->data, actions->size);
a260d966
PS
6643
6644 add_actions = put_actions->size ? put_actions : actions;
6645 if (OVS_LIKELY(error != ENOSPC)) {
6646 struct dp_netdev_flow *netdev_flow;
6647
6648 /* XXX: There's a race window where a flow covering this packet
6649 * could have already been installed since we last did the flow
6650 * lookup before upcall. This could be solved by moving the
6651 * mutex lock outside the loop, but that's an awful long time
af741ca3 6652 * to be locking revalidators out of making flow modifications. */
a260d966 6653 ovs_mutex_lock(&pmd->flow_mutex);
3453b4d6 6654 netdev_flow = dp_netdev_pmd_lookup_flow(pmd, key, NULL);
a260d966
PS
6655 if (OVS_LIKELY(!netdev_flow)) {
6656 netdev_flow = dp_netdev_flow_add(pmd, &match, &ufid,
6657 add_actions->data,
6658 add_actions->size);
6659 }
6660 ovs_mutex_unlock(&pmd->flow_mutex);
60d8ccae
YW
6661 uint32_t hash = dp_netdev_flow_hash(&netdev_flow->ufid);
6662 smc_insert(pmd, key, hash);
4c30b246 6663 emc_probabilistic_insert(pmd, key, netdev_flow);
a260d966 6664 }
79f36875
JS
6665 if (pmd_perf_metrics_enabled(pmd)) {
6666 /* Update upcall stats. */
6667 cycles = cycles_counter_update(&pmd->perf_stats) - cycles;
6668 struct pmd_perf_stats *s = &pmd->perf_stats;
6669 s->current.upcalls++;
6670 s->current.upcall_cycles += cycles;
6671 histogram_add_sample(&s->cycles_per_upcall, cycles);
6672 }
82a48ead 6673 return error;
a260d966
PS
6674}
6675
9bbf1c3d 6676static inline void
65f13b50 6677fast_path_processing(struct dp_netdev_pmd_thread *pmd,
1895cc8d 6678 struct dp_packet_batch *packets_,
60d8ccae 6679 struct netdev_flow_key **keys,
9b4f08cd
VDA
6680 struct dp_packet_flow_map *flow_map,
6681 uint8_t *index_map,
b010be17 6682 odp_port_t in_port)
9bbf1c3d 6683{
31c82130 6684 const size_t cnt = dp_packet_batch_size(packets_);
1a0d5831 6685#if !defined(__CHECKER__) && !defined(_WIN32)
9bbf1c3d
DDP
6686 const size_t PKT_ARRAY_SIZE = cnt;
6687#else
1a0d5831 6688 /* Sparse or MSVC doesn't like variable length array. */
cd159f1a 6689 enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
9bbf1c3d 6690#endif
31c82130 6691 struct dp_packet *packet;
3453b4d6 6692 struct dpcls *cls;
0de8783a 6693 struct dpcls_rule *rules[PKT_ARRAY_SIZE];
65f13b50 6694 struct dp_netdev *dp = pmd->dp;
82a48ead 6695 int upcall_ok_cnt = 0, upcall_fail_cnt = 0;
3453b4d6 6696 int lookup_cnt = 0, add_lookup_cnt;
9bbf1c3d
DDP
6697 bool any_miss;
6698
e883448e 6699 for (size_t i = 0; i < cnt; i++) {
0de8783a 6700 /* Key length is needed in all the cases, hash computed on demand. */
60d8ccae 6701 keys[i]->len = netdev_flow_key_size(miniflow_n_values(&keys[i]->mf));
9bbf1c3d 6702 }
3453b4d6
JS
6703 /* Get the classifier for the in_port */
6704 cls = dp_netdev_pmd_lookup_dpcls(pmd, in_port);
6705 if (OVS_LIKELY(cls)) {
60d8ccae
YW
6706 any_miss = !dpcls_lookup(cls, (const struct netdev_flow_key **)keys,
6707 rules, cnt, &lookup_cnt);
3453b4d6
JS
6708 } else {
6709 any_miss = true;
6710 memset(rules, 0, sizeof(rules));
6711 }
623540e4
EJ
6712 if (OVS_UNLIKELY(any_miss) && !fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
6713 uint64_t actions_stub[512 / 8], slow_stub[512 / 8];
6714 struct ofpbuf actions, put_actions;
623540e4
EJ
6715
6716 ofpbuf_use_stub(&actions, actions_stub, sizeof actions_stub);
6717 ofpbuf_use_stub(&put_actions, slow_stub, sizeof slow_stub);
6718
e883448e 6719 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
0de8783a 6720 struct dp_netdev_flow *netdev_flow;
623540e4 6721
0de8783a 6722 if (OVS_LIKELY(rules[i])) {
623540e4
EJ
6723 continue;
6724 }
6725
6726 /* It's possible that an earlier slow path execution installed
0de8783a 6727 * a rule covering this flow. In this case, it's a lot cheaper
623540e4 6728 * to catch it here than execute a miss. */
60d8ccae 6729 netdev_flow = dp_netdev_pmd_lookup_flow(pmd, keys[i],
3453b4d6 6730 &add_lookup_cnt);
623540e4 6731 if (netdev_flow) {
3453b4d6 6732 lookup_cnt += add_lookup_cnt;
0de8783a 6733 rules[i] = &netdev_flow->cr;
623540e4
EJ
6734 continue;
6735 }
6736
60d8ccae 6737 int error = handle_packet_upcall(pmd, packet, keys[i],
82a48ead
JS
6738 &actions, &put_actions);
6739
6740 if (OVS_UNLIKELY(error)) {
6741 upcall_fail_cnt++;
6742 } else {
6743 upcall_ok_cnt++;
6744 }
623540e4
EJ
6745 }
6746
6747 ofpbuf_uninit(&actions);
6748 ofpbuf_uninit(&put_actions);
6749 fat_rwlock_unlock(&dp->upcall_rwlock);
ac8c2081 6750 } else if (OVS_UNLIKELY(any_miss)) {
e883448e 6751 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
0de8783a 6752 if (OVS_UNLIKELY(!rules[i])) {
31c82130 6753 dp_packet_delete(packet);
82a48ead 6754 upcall_fail_cnt++;
ac8c2081
DDP
6755 }
6756 }
623540e4 6757 }
84d6d5eb 6758
e883448e 6759 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
84d6d5eb 6760 struct dp_netdev_flow *flow;
9b4f08cd
VDA
6761 /* Get the original order of this packet in received batch. */
6762 int recv_idx = index_map[i];
6763 uint16_t tcp_flags;
8cbf4f47 6764
0de8783a 6765 if (OVS_UNLIKELY(!rules[i])) {
84d6d5eb
EJ
6766 continue;
6767 }
6768
84d6d5eb 6769 flow = dp_netdev_flow_cast(rules[i]);
60d8ccae
YW
6770 uint32_t hash = dp_netdev_flow_hash(&flow->ufid);
6771 smc_insert(pmd, keys[i], hash);
0de8783a 6772
60d8ccae 6773 emc_probabilistic_insert(pmd, keys[i], flow);
9b4f08cd
VDA
6774 /* Add these packets into the flow map in the same order
6775 * as received.
6776 */
6777 tcp_flags = miniflow_get_tcp_flags(&keys[i]->mf);
6778 packet_enqueue_to_flow_map(packet, flow, tcp_flags,
6779 flow_map, recv_idx);
8cbf4f47
DDP
6780 }
6781
82a48ead
JS
6782 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_MASKED_HIT,
6783 cnt - upcall_ok_cnt - upcall_fail_cnt);
6784 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_MASKED_LOOKUP,
6785 lookup_cnt);
6786 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_MISS,
6787 upcall_ok_cnt);
6788 pmd_perf_update_counter(&pmd->perf_stats, PMD_STAT_LOST,
6789 upcall_fail_cnt);
72865317
BP
6790}
6791
a90ed026
DDP
6792/* Packets enter the datapath from a port (or from recirculation) here.
6793 *
02305520
FA
6794 * When 'md_is_valid' is true the metadata in 'packets' are already valid.
6795 * When false the metadata in 'packets' need to be initialized. */
adcf00ba 6796static void
a90ed026 6797dp_netdev_input__(struct dp_netdev_pmd_thread *pmd,
1895cc8d 6798 struct dp_packet_batch *packets,
a90ed026 6799 bool md_is_valid, odp_port_t port_no)
9bbf1c3d 6800{
1a0d5831 6801#if !defined(__CHECKER__) && !defined(_WIN32)
37eabc70 6802 const size_t PKT_ARRAY_SIZE = dp_packet_batch_size(packets);
9bbf1c3d 6803#else
1a0d5831 6804 /* Sparse or MSVC doesn't like variable length array. */
cd159f1a 6805 enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
9bbf1c3d 6806#endif
47a45d86
KT
6807 OVS_ALIGNED_VAR(CACHE_LINE_SIZE)
6808 struct netdev_flow_key keys[PKT_ARRAY_SIZE];
60d8ccae 6809 struct netdev_flow_key *missed_keys[PKT_ARRAY_SIZE];
f7ce4811 6810 struct packet_batch_per_flow batches[PKT_ARRAY_SIZE];
72c84bc2 6811 size_t n_batches;
9b4f08cd
VDA
6812 struct dp_packet_flow_map flow_map[PKT_ARRAY_SIZE];
6813 uint8_t index_map[PKT_ARRAY_SIZE];
6814 size_t n_flows, i;
6815
3453b4d6 6816 odp_port_t in_port;
9bbf1c3d 6817
8aaa125d 6818 n_batches = 0;
60d8ccae 6819 dfc_processing(pmd, packets, keys, missed_keys, batches, &n_batches,
9b4f08cd
VDA
6820 flow_map, &n_flows, index_map, md_is_valid, port_no);
6821
72c84bc2 6822 if (!dp_packet_batch_is_empty(packets)) {
3453b4d6
JS
6823 /* Get ingress port from first packet's metadata. */
6824 in_port = packets->packets[0]->md.in_port.odp_port;
60d8ccae 6825 fast_path_processing(pmd, packets, missed_keys,
9b4f08cd 6826 flow_map, index_map, in_port);
8aaa125d
DDP
6827 }
6828
9b4f08cd
VDA
6829 /* Batch rest of packets which are in flow map. */
6830 for (i = 0; i < n_flows; i++) {
6831 struct dp_packet_flow_map *map = &flow_map[i];
6832
6833 if (OVS_UNLIKELY(!map->flow)) {
6834 continue;
6835 }
6836 dp_netdev_queue_batches(map->packet, map->flow, map->tcp_flags,
6837 batches, &n_batches);
6838 }
6839
ad9f0581
BB
6840 /* All the flow batches need to be reset before any call to
6841 * packet_batch_per_flow_execute() as it could potentially trigger
6842 * recirculation. When a packet matching flow ‘j’ happens to be
6843 * recirculated, the nested call to dp_netdev_input__() could potentially
6844 * classify the packet as matching another flow - say 'k'. It could happen
6845 * that in the previous call to dp_netdev_input__() that same flow 'k' had
6846 * already its own batches[k] still waiting to be served. So if its
6847 * ‘batch’ member is not reset, the recirculated packet would be wrongly
6848 * appended to batches[k] of the 1st call to dp_netdev_input__(). */
603f2ce0
EJ
6849 for (i = 0; i < n_batches; i++) {
6850 batches[i].flow->batch = NULL;
6851 }
6852
8aaa125d 6853 for (i = 0; i < n_batches; i++) {
b010be17 6854 packet_batch_per_flow_execute(&batches[i], pmd);
9bbf1c3d
DDP
6855 }
6856}
6857
a90ed026
DDP
6858static void
6859dp_netdev_input(struct dp_netdev_pmd_thread *pmd,
1895cc8d 6860 struct dp_packet_batch *packets,
a90ed026
DDP
6861 odp_port_t port_no)
6862{
3453b4d6 6863 dp_netdev_input__(pmd, packets, false, port_no);
a90ed026
DDP
6864}
6865
6866static void
6867dp_netdev_recirculate(struct dp_netdev_pmd_thread *pmd,
1895cc8d 6868 struct dp_packet_batch *packets)
a90ed026 6869{
3453b4d6 6870 dp_netdev_input__(pmd, packets, true, 0);
a90ed026
DDP
6871}
6872
9080a111 6873struct dp_netdev_execute_aux {
65f13b50 6874 struct dp_netdev_pmd_thread *pmd;
66e4ad8a 6875 const struct flow *flow;
9080a111
JR
6876};
6877
e4e74c3a
AW
6878static void
6879dpif_netdev_register_dp_purge_cb(struct dpif *dpif, dp_purge_callback *cb,
6880 void *aux)
6881{
6882 struct dp_netdev *dp = get_dp_netdev(dpif);
6883 dp->dp_purge_aux = aux;
6884 dp->dp_purge_cb = cb;
6885}
6886
6b31e073 6887static void
623540e4
EJ
6888dpif_netdev_register_upcall_cb(struct dpif *dpif, upcall_callback *cb,
6889 void *aux)
6b31e073
RW
6890{
6891 struct dp_netdev *dp = get_dp_netdev(dpif);
623540e4 6892 dp->upcall_aux = aux;
6b31e073
RW
6893 dp->upcall_cb = cb;
6894}
6895
324c8374
IM
6896static void
6897dpif_netdev_xps_revalidate_pmd(const struct dp_netdev_pmd_thread *pmd,
b010be17 6898 bool purge)
324c8374
IM
6899{
6900 struct tx_port *tx;
6901 struct dp_netdev_port *port;
6902 long long interval;
6903
57eebbb4 6904 HMAP_FOR_EACH (tx, node, &pmd->send_port_cache) {
9f7a3035 6905 if (!tx->port->dynamic_txqs) {
324c8374
IM
6906 continue;
6907 }
b010be17 6908 interval = pmd->ctx.now - tx->last_used;
05f9e707 6909 if (tx->qid >= 0 && (purge || interval >= XPS_TIMEOUT)) {
324c8374
IM
6910 port = tx->port;
6911 ovs_mutex_lock(&port->txq_used_mutex);
6912 port->txq_used[tx->qid]--;
6913 ovs_mutex_unlock(&port->txq_used_mutex);
6914 tx->qid = -1;
6915 }
6916 }
6917}
6918
6919static int
6920dpif_netdev_xps_get_tx_qid(const struct dp_netdev_pmd_thread *pmd,
b010be17 6921 struct tx_port *tx)
324c8374
IM
6922{
6923 struct dp_netdev_port *port;
6924 long long interval;
6925 int i, min_cnt, min_qid;
6926
b010be17
IM
6927 interval = pmd->ctx.now - tx->last_used;
6928 tx->last_used = pmd->ctx.now;
324c8374 6929
05f9e707 6930 if (OVS_LIKELY(tx->qid >= 0 && interval < XPS_TIMEOUT)) {
324c8374
IM
6931 return tx->qid;
6932 }
6933
6934 port = tx->port;
6935
6936 ovs_mutex_lock(&port->txq_used_mutex);
6937 if (tx->qid >= 0) {
6938 port->txq_used[tx->qid]--;
6939 tx->qid = -1;
6940 }
6941
6942 min_cnt = -1;
6943 min_qid = 0;
6944 for (i = 0; i < netdev_n_txq(port->netdev); i++) {
6945 if (port->txq_used[i] < min_cnt || min_cnt == -1) {
6946 min_cnt = port->txq_used[i];
6947 min_qid = i;
6948 }
6949 }
6950
6951 port->txq_used[min_qid]++;
6952 tx->qid = min_qid;
6953
6954 ovs_mutex_unlock(&port->txq_used_mutex);
6955
b010be17 6956 dpif_netdev_xps_revalidate_pmd(pmd, false);
324c8374
IM
6957
6958 VLOG_DBG("Core %d: New TX queue ID %d for port \'%s\'.",
6959 pmd->core_id, tx->qid, netdev_get_name(tx->port->netdev));
6960 return min_qid;
6961}
6962
d0cca6c3 6963static struct tx_port *
57eebbb4
DDP
6964pmd_tnl_port_cache_lookup(const struct dp_netdev_pmd_thread *pmd,
6965 odp_port_t port_no)
6966{
6967 return tx_port_lookup(&pmd->tnl_port_cache, port_no);
6968}
6969
6970static struct tx_port *
6971pmd_send_port_cache_lookup(const struct dp_netdev_pmd_thread *pmd,
6972 odp_port_t port_no)
d0cca6c3 6973{
57eebbb4 6974 return tx_port_lookup(&pmd->send_port_cache, port_no);
d0cca6c3
DDP
6975}
6976
a36de779 6977static int
d0cca6c3 6978push_tnl_action(const struct dp_netdev_pmd_thread *pmd,
1895cc8d
PS
6979 const struct nlattr *attr,
6980 struct dp_packet_batch *batch)
a36de779 6981{
d0cca6c3 6982 struct tx_port *tun_port;
a36de779 6983 const struct ovs_action_push_tnl *data;
4c742796 6984 int err;
a36de779
PS
6985
6986 data = nl_attr_get(attr);
6987
81765c00 6988 tun_port = pmd_tnl_port_cache_lookup(pmd, data->tnl_port);
a36de779 6989 if (!tun_port) {
4c742796
PS
6990 err = -EINVAL;
6991 goto error;
a36de779 6992 }
324c8374 6993 err = netdev_push_header(tun_port->port->netdev, batch, data);
4c742796
PS
6994 if (!err) {
6995 return 0;
6996 }
6997error:
6998 dp_packet_delete_batch(batch, true);
6999 return err;
a36de779
PS
7000}
7001
66525ef3
PS
7002static void
7003dp_execute_userspace_action(struct dp_netdev_pmd_thread *pmd,
7d7ded7a 7004 struct dp_packet *packet, bool should_steal,
66525ef3
PS
7005 struct flow *flow, ovs_u128 *ufid,
7006 struct ofpbuf *actions,
b010be17 7007 const struct nlattr *userdata)
66525ef3
PS
7008{
7009 struct dp_packet_batch b;
7010 int error;
7011
7012 ofpbuf_clear(actions);
7013
7014 error = dp_netdev_upcall(pmd, packet, flow, NULL, ufid,
7015 DPIF_UC_ACTION, userdata, actions,
7016 NULL);
7017 if (!error || error == ENOSPC) {
72c84bc2 7018 dp_packet_batch_init_packet(&b, packet);
7d7ded7a 7019 dp_netdev_execute_actions(pmd, &b, should_steal, flow,
b010be17 7020 actions->data, actions->size);
7d7ded7a 7021 } else if (should_steal) {
66525ef3
PS
7022 dp_packet_delete(packet);
7023 }
7024}
7025
a36de779 7026static void
1895cc8d 7027dp_execute_cb(void *aux_, struct dp_packet_batch *packets_,
7d7ded7a 7028 const struct nlattr *a, bool should_steal)
4b27db64 7029 OVS_NO_THREAD_SAFETY_ANALYSIS
9080a111
JR
7030{
7031 struct dp_netdev_execute_aux *aux = aux_;
623540e4 7032 uint32_t *depth = recirc_depth_get();
28e2fa02
DDP
7033 struct dp_netdev_pmd_thread *pmd = aux->pmd;
7034 struct dp_netdev *dp = pmd->dp;
09f9da0b 7035 int type = nl_attr_type(a);
d0cca6c3 7036 struct tx_port *p;
9080a111 7037
09f9da0b
JR
7038 switch ((enum ovs_action_attr)type) {
7039 case OVS_ACTION_ATTR_OUTPUT:
57eebbb4 7040 p = pmd_send_port_cache_lookup(pmd, nl_attr_get_odp_port(a));
26a5075b 7041 if (OVS_LIKELY(p)) {
009e0033
IM
7042 struct dp_packet *packet;
7043 struct dp_packet_batch out;
347ba9bb 7044
7d7ded7a 7045 if (!should_steal) {
009e0033
IM
7046 dp_packet_batch_clone(&out, packets_);
7047 dp_packet_batch_reset_cutlen(packets_);
7048 packets_ = &out;
324c8374 7049 }
009e0033 7050 dp_packet_batch_apply_cutlen(packets_);
347ba9bb 7051
009e0033
IM
7052#ifdef DPDK_NETDEV
7053 if (OVS_UNLIKELY(!dp_packet_batch_is_empty(&p->output_pkts)
7054 && packets_->packets[0]->source
7055 != p->output_pkts.packets[0]->source)) {
7056 /* XXX: netdev-dpdk assumes that all packets in a single
7057 * output batch has the same source. Flush here to
7058 * avoid memory access issues. */
7059 dp_netdev_pmd_flush_output_on_port(pmd, p);
7060 }
7061#endif
c71ea3c4
IM
7062 if (dp_packet_batch_size(&p->output_pkts)
7063 + dp_packet_batch_size(packets_) > NETDEV_MAX_BURST) {
7064 /* Flush here to avoid overflow. */
009e0033
IM
7065 dp_netdev_pmd_flush_output_on_port(pmd, p);
7066 }
c71ea3c4
IM
7067
7068 if (dp_packet_batch_is_empty(&p->output_pkts)) {
7069 pmd->n_output_batches++;
7070 }
7071
e883448e 7072 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
58ed6df0
IM
7073 p->output_pkts_rxqs[dp_packet_batch_size(&p->output_pkts)] =
7074 pmd->ctx.last_rxq;
009e0033
IM
7075 dp_packet_batch_add(&p->output_pkts, packet);
7076 }
ac8c2081 7077 return;
8a4e3a85 7078 }
09f9da0b
JR
7079 break;
7080
a36de779 7081 case OVS_ACTION_ATTR_TUNNEL_PUSH:
47e1b3b6
IM
7082 if (should_steal) {
7083 /* We're requested to push tunnel header, but also we need to take
7084 * the ownership of these packets. Thus, we can avoid performing
7085 * the action, because the caller will not use the result anyway.
7086 * Just break to free the batch. */
7087 break;
a36de779 7088 }
47e1b3b6
IM
7089 dp_packet_batch_apply_cutlen(packets_);
7090 push_tnl_action(pmd, a, packets_);
7091 return;
a36de779
PS
7092
7093 case OVS_ACTION_ATTR_TUNNEL_POP:
7094 if (*depth < MAX_RECIRC_DEPTH) {
aaca4fe0 7095 struct dp_packet_batch *orig_packets_ = packets_;
8611f9a4 7096 odp_port_t portno = nl_attr_get_odp_port(a);
a36de779 7097
57eebbb4 7098 p = pmd_tnl_port_cache_lookup(pmd, portno);
a36de779 7099 if (p) {
1895cc8d 7100 struct dp_packet_batch tnl_pkt;
a36de779 7101
7d7ded7a 7102 if (!should_steal) {
aaca4fe0
WT
7103 dp_packet_batch_clone(&tnl_pkt, packets_);
7104 packets_ = &tnl_pkt;
7105 dp_packet_batch_reset_cutlen(orig_packets_);
a36de779
PS
7106 }
7107
aaca4fe0
WT
7108 dp_packet_batch_apply_cutlen(packets_);
7109
324c8374 7110 netdev_pop_header(p->port->netdev, packets_);
72c84bc2 7111 if (dp_packet_batch_is_empty(packets_)) {
1c8f98d9
PS
7112 return;
7113 }
9235b479 7114
72c84bc2 7115 struct dp_packet *packet;
e883448e 7116 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
72c84bc2 7117 packet->md.in_port.odp_port = portno;
a36de779 7118 }
9235b479
PS
7119
7120 (*depth)++;
7121 dp_netdev_recirculate(pmd, packets_);
7122 (*depth)--;
a36de779
PS
7123 return;
7124 }
7125 }
7126 break;
7127
623540e4
EJ
7128 case OVS_ACTION_ATTR_USERSPACE:
7129 if (!fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
aaca4fe0 7130 struct dp_packet_batch *orig_packets_ = packets_;
623540e4 7131 const struct nlattr *userdata;
aaca4fe0 7132 struct dp_packet_batch usr_pkt;
623540e4
EJ
7133 struct ofpbuf actions;
7134 struct flow flow;
7af12bd7 7135 ovs_u128 ufid;
aaca4fe0 7136 bool clone = false;
4fc65926 7137
623540e4
EJ
7138 userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
7139 ofpbuf_init(&actions, 0);
8cbf4f47 7140
aaca4fe0 7141 if (packets_->trunc) {
7d7ded7a 7142 if (!should_steal) {
aaca4fe0
WT
7143 dp_packet_batch_clone(&usr_pkt, packets_);
7144 packets_ = &usr_pkt;
aaca4fe0
WT
7145 clone = true;
7146 dp_packet_batch_reset_cutlen(orig_packets_);
7147 }
7148
7149 dp_packet_batch_apply_cutlen(packets_);
7150 }
7151
72c84bc2 7152 struct dp_packet *packet;
e883448e 7153 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
72c84bc2 7154 flow_extract(packet, &flow);
7af12bd7 7155 dpif_flow_hash(dp->dpif, &flow, sizeof flow, &ufid);
7d7ded7a 7156 dp_execute_userspace_action(pmd, packet, should_steal, &flow,
b010be17 7157 &ufid, &actions, userdata);
db73f716 7158 }
aaca4fe0
WT
7159
7160 if (clone) {
7161 dp_packet_delete_batch(packets_, true);
7162 }
7163
623540e4
EJ
7164 ofpbuf_uninit(&actions);
7165 fat_rwlock_unlock(&dp->upcall_rwlock);
6b31e073 7166
ac8c2081
DDP
7167 return;
7168 }
09f9da0b 7169 break;
572f732a 7170
adcf00ba
AZ
7171 case OVS_ACTION_ATTR_RECIRC:
7172 if (*depth < MAX_RECIRC_DEPTH) {
1895cc8d 7173 struct dp_packet_batch recirc_pkts;
572f732a 7174
7d7ded7a 7175 if (!should_steal) {
1895cc8d
PS
7176 dp_packet_batch_clone(&recirc_pkts, packets_);
7177 packets_ = &recirc_pkts;
28e2fa02 7178 }
8cbf4f47 7179
72c84bc2 7180 struct dp_packet *packet;
e883448e 7181 DP_PACKET_BATCH_FOR_EACH (i, packet, packets_) {
72c84bc2 7182 packet->md.recirc_id = nl_attr_get_u32(a);
8cbf4f47 7183 }
28e2fa02
DDP
7184
7185 (*depth)++;
1895cc8d 7186 dp_netdev_recirculate(pmd, packets_);
adcf00ba
AZ
7187 (*depth)--;
7188
ac8c2081 7189 return;
adcf00ba 7190 }
ac8c2081
DDP
7191
7192 VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
572f732a 7193 break;
572f732a 7194
5cf3edb3
DDP
7195 case OVS_ACTION_ATTR_CT: {
7196 const struct nlattr *b;
a76a37ef 7197 bool force = false;
5cf3edb3
DDP
7198 bool commit = false;
7199 unsigned int left;
7200 uint16_t zone = 0;
7201 const char *helper = NULL;
7202 const uint32_t *setmark = NULL;
7203 const struct ovs_key_ct_labels *setlabel = NULL;
4cddb1f0
DB
7204 struct nat_action_info_t nat_action_info;
7205 struct nat_action_info_t *nat_action_info_ref = NULL;
7206 bool nat_config = false;
5cf3edb3
DDP
7207
7208 NL_ATTR_FOR_EACH_UNSAFE (b, left, nl_attr_get(a),
7209 nl_attr_get_size(a)) {
7210 enum ovs_ct_attr sub_type = nl_attr_type(b);
7211
7212 switch(sub_type) {
b80e259f 7213 case OVS_CT_ATTR_FORCE_COMMIT:
a76a37ef
JR
7214 force = true;
7215 /* fall through. */
5cf3edb3
DDP
7216 case OVS_CT_ATTR_COMMIT:
7217 commit = true;
7218 break;
7219 case OVS_CT_ATTR_ZONE:
7220 zone = nl_attr_get_u16(b);
7221 break;
7222 case OVS_CT_ATTR_HELPER:
7223 helper = nl_attr_get_string(b);
7224 break;
7225 case OVS_CT_ATTR_MARK:
7226 setmark = nl_attr_get(b);
7227 break;
7228 case OVS_CT_ATTR_LABELS:
7229 setlabel = nl_attr_get(b);
7230 break;
8e83854c
JR
7231 case OVS_CT_ATTR_EVENTMASK:
7232 /* Silently ignored, as userspace datapath does not generate
7233 * netlink events. */
7234 break;
ebe62ec1
YHW
7235 case OVS_CT_ATTR_TIMEOUT:
7236 /* Userspace datapath does not support customized timeout
7237 * policy yet. */
7238 break;
4cddb1f0
DB
7239 case OVS_CT_ATTR_NAT: {
7240 const struct nlattr *b_nest;
7241 unsigned int left_nest;
7242 bool ip_min_specified = false;
7243 bool proto_num_min_specified = false;
7244 bool ip_max_specified = false;
7245 bool proto_num_max_specified = false;
7246 memset(&nat_action_info, 0, sizeof nat_action_info);
7247 nat_action_info_ref = &nat_action_info;
7248
7249 NL_NESTED_FOR_EACH_UNSAFE (b_nest, left_nest, b) {
7250 enum ovs_nat_attr sub_type_nest = nl_attr_type(b_nest);
7251
7252 switch (sub_type_nest) {
7253 case OVS_NAT_ATTR_SRC:
7254 case OVS_NAT_ATTR_DST:
7255 nat_config = true;
7256 nat_action_info.nat_action |=
7257 ((sub_type_nest == OVS_NAT_ATTR_SRC)
7258 ? NAT_ACTION_SRC : NAT_ACTION_DST);
7259 break;
7260 case OVS_NAT_ATTR_IP_MIN:
7261 memcpy(&nat_action_info.min_addr,
7262 nl_attr_get(b_nest),
7263 nl_attr_get_size(b_nest));
7264 ip_min_specified = true;
7265 break;
7266 case OVS_NAT_ATTR_IP_MAX:
7267 memcpy(&nat_action_info.max_addr,
7268 nl_attr_get(b_nest),
7269 nl_attr_get_size(b_nest));
7270 ip_max_specified = true;
7271 break;
7272 case OVS_NAT_ATTR_PROTO_MIN:
7273 nat_action_info.min_port =
7274 nl_attr_get_u16(b_nest);
7275 proto_num_min_specified = true;
7276 break;
7277 case OVS_NAT_ATTR_PROTO_MAX:
7278 nat_action_info.max_port =
7279 nl_attr_get_u16(b_nest);
7280 proto_num_max_specified = true;
7281 break;
7282 case OVS_NAT_ATTR_PERSISTENT:
7283 case OVS_NAT_ATTR_PROTO_HASH:
7284 case OVS_NAT_ATTR_PROTO_RANDOM:
7285 break;
7286 case OVS_NAT_ATTR_UNSPEC:
7287 case __OVS_NAT_ATTR_MAX:
7288 OVS_NOT_REACHED();
7289 }
7290 }
7291
7292 if (ip_min_specified && !ip_max_specified) {
7293 nat_action_info.max_addr = nat_action_info.min_addr;
7294 }
7295 if (proto_num_min_specified && !proto_num_max_specified) {
7296 nat_action_info.max_port = nat_action_info.min_port;
7297 }
7298 if (proto_num_min_specified || proto_num_max_specified) {
7299 if (nat_action_info.nat_action & NAT_ACTION_SRC) {
7300 nat_action_info.nat_action |= NAT_ACTION_SRC_PORT;
7301 } else if (nat_action_info.nat_action & NAT_ACTION_DST) {
7302 nat_action_info.nat_action |= NAT_ACTION_DST_PORT;
7303 }
7304 }
7305 break;
7306 }
5cf3edb3
DDP
7307 case OVS_CT_ATTR_UNSPEC:
7308 case __OVS_CT_ATTR_MAX:
7309 OVS_NOT_REACHED();
7310 }
7311 }
7312
4cddb1f0
DB
7313 /* We won't be able to function properly in this case, hence
7314 * complain loudly. */
7315 if (nat_config && !commit) {
7316 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
7317 VLOG_WARN_RL(&rl, "NAT specified without commit.");
7318 }
7319
57593fd2 7320 conntrack_execute(dp->conntrack, packets_, aux->flow->dl_type, force,
bd7d93f8 7321 commit, zone, setmark, setlabel, aux->flow->tp_src,
b010be17 7322 aux->flow->tp_dst, helper, nat_action_info_ref,
05f9e707 7323 pmd->ctx.now / 1000);
07659514 7324 break;
5cf3edb3 7325 }
07659514 7326
5dddf960 7327 case OVS_ACTION_ATTR_METER:
4b27db64 7328 dp_netdev_run_meter(pmd->dp, packets_, nl_attr_get_u32(a),
b010be17 7329 pmd->ctx.now);
4b27db64
JR
7330 break;
7331
09f9da0b
JR
7332 case OVS_ACTION_ATTR_PUSH_VLAN:
7333 case OVS_ACTION_ATTR_POP_VLAN:
7334 case OVS_ACTION_ATTR_PUSH_MPLS:
7335 case OVS_ACTION_ATTR_POP_MPLS:
7336 case OVS_ACTION_ATTR_SET:
6d670e7f 7337 case OVS_ACTION_ATTR_SET_MASKED:
09f9da0b 7338 case OVS_ACTION_ATTR_SAMPLE:
53e1d6f1 7339 case OVS_ACTION_ATTR_HASH:
09f9da0b 7340 case OVS_ACTION_ATTR_UNSPEC:
aaca4fe0 7341 case OVS_ACTION_ATTR_TRUNC:
6fcecb85
YY
7342 case OVS_ACTION_ATTR_PUSH_ETH:
7343 case OVS_ACTION_ATTR_POP_ETH:
535e3acf 7344 case OVS_ACTION_ATTR_CLONE:
f59cb331
YY
7345 case OVS_ACTION_ATTR_PUSH_NSH:
7346 case OVS_ACTION_ATTR_POP_NSH:
1fe178d2 7347 case OVS_ACTION_ATTR_CT_CLEAR:
5b34f8fc 7348 case OVS_ACTION_ATTR_CHECK_PKT_LEN:
09f9da0b
JR
7349 case __OVS_ACTION_ATTR_MAX:
7350 OVS_NOT_REACHED();
da546e07 7351 }
ac8c2081 7352
7d7ded7a 7353 dp_packet_delete_batch(packets_, should_steal);
98403001
BP
7354}
7355
4edb9ae9 7356static void
65f13b50 7357dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
1895cc8d 7358 struct dp_packet_batch *packets,
7d7ded7a 7359 bool should_steal, const struct flow *flow,
b010be17 7360 const struct nlattr *actions, size_t actions_len)
72865317 7361{
b010be17 7362 struct dp_netdev_execute_aux aux = { pmd, flow };
9080a111 7363
7d7ded7a 7364 odp_execute_actions(&aux, packets, should_steal, actions,
8cbf4f47 7365 actions_len, dp_execute_cb);
72865317
BP
7366}
7367
4d4e68ed
DDP
7368struct dp_netdev_ct_dump {
7369 struct ct_dpif_dump_state up;
7370 struct conntrack_dump dump;
7371 struct conntrack *ct;
7372 struct dp_netdev *dp;
7373};
7374
7375static int
7376dpif_netdev_ct_dump_start(struct dpif *dpif, struct ct_dpif_dump_state **dump_,
ded30c74 7377 const uint16_t *pzone, int *ptot_bkts)
4d4e68ed
DDP
7378{
7379 struct dp_netdev *dp = get_dp_netdev(dpif);
7380 struct dp_netdev_ct_dump *dump;
7381
7382 dump = xzalloc(sizeof *dump);
7383 dump->dp = dp;
57593fd2 7384 dump->ct = dp->conntrack;
4d4e68ed 7385
57593fd2 7386 conntrack_dump_start(dp->conntrack, &dump->dump, pzone, ptot_bkts);
4d4e68ed
DDP
7387
7388 *dump_ = &dump->up;
7389
7390 return 0;
7391}
7392
7393static int
7394dpif_netdev_ct_dump_next(struct dpif *dpif OVS_UNUSED,
7395 struct ct_dpif_dump_state *dump_,
7396 struct ct_dpif_entry *entry)
7397{
7398 struct dp_netdev_ct_dump *dump;
7399
7400 INIT_CONTAINER(dump, dump_, up);
7401
7402 return conntrack_dump_next(&dump->dump, entry);
7403}
7404
7405static int
7406dpif_netdev_ct_dump_done(struct dpif *dpif OVS_UNUSED,
7407 struct ct_dpif_dump_state *dump_)
7408{
7409 struct dp_netdev_ct_dump *dump;
7410 int err;
7411
7412 INIT_CONTAINER(dump, dump_, up);
7413
7414 err = conntrack_dump_done(&dump->dump);
7415
7416 free(dump);
7417
7418 return err;
7419}
7420
5d9cbb4c 7421static int
817a7657
YHW
7422dpif_netdev_ct_flush(struct dpif *dpif, const uint16_t *zone,
7423 const struct ct_dpif_tuple *tuple)
5d9cbb4c
DDP
7424{
7425 struct dp_netdev *dp = get_dp_netdev(dpif);
7426
817a7657 7427 if (tuple) {
57593fd2 7428 return conntrack_flush_tuple(dp->conntrack, tuple, zone ? *zone : 0);
817a7657 7429 }
57593fd2 7430 return conntrack_flush(dp->conntrack, zone);
5d9cbb4c
DDP
7431}
7432
c92339ad
DB
7433static int
7434dpif_netdev_ct_set_maxconns(struct dpif *dpif, uint32_t maxconns)
7435{
7436 struct dp_netdev *dp = get_dp_netdev(dpif);
7437
57593fd2 7438 return conntrack_set_maxconns(dp->conntrack, maxconns);
c92339ad
DB
7439}
7440
7441static int
7442dpif_netdev_ct_get_maxconns(struct dpif *dpif, uint32_t *maxconns)
7443{
7444 struct dp_netdev *dp = get_dp_netdev(dpif);
7445
57593fd2 7446 return conntrack_get_maxconns(dp->conntrack, maxconns);
c92339ad
DB
7447}
7448
875075b3
DB
7449static int
7450dpif_netdev_ct_get_nconns(struct dpif *dpif, uint32_t *nconns)
7451{
7452 struct dp_netdev *dp = get_dp_netdev(dpif);
7453
57593fd2 7454 return conntrack_get_nconns(dp->conntrack, nconns);
875075b3
DB
7455}
7456
64207120
DB
7457static int
7458dpif_netdev_ct_set_tcp_seq_chk(struct dpif *dpif, bool enabled)
7459{
7460 struct dp_netdev *dp = get_dp_netdev(dpif);
7461
7462 return conntrack_set_tcp_seq_chk(dp->conntrack, enabled);
7463}
7464
7465static int
7466dpif_netdev_ct_get_tcp_seq_chk(struct dpif *dpif, bool *enabled)
7467{
7468 struct dp_netdev *dp = get_dp_netdev(dpif);
7469 *enabled = conntrack_get_tcp_seq_chk(dp->conntrack);
7470 return 0;
7471}
7472
a7f33fdb
DB
7473static int
7474dpif_netdev_ct_set_limits(struct dpif *dpif OVS_UNUSED,
7475 const uint32_t *default_limits,
7476 const struct ovs_list *zone_limits)
7477{
7478 int err = 0;
7479 struct dp_netdev *dp = get_dp_netdev(dpif);
7480 if (default_limits) {
7481 err = zone_limit_update(dp->conntrack, DEFAULT_ZONE, *default_limits);
7482 if (err != 0) {
7483 return err;
7484 }
7485 }
7486
7487 struct ct_dpif_zone_limit *zone_limit;
7488 LIST_FOR_EACH (zone_limit, node, zone_limits) {
7489 err = zone_limit_update(dp->conntrack, zone_limit->zone,
7490 zone_limit->limit);
7491 if (err != 0) {
7492 break;
7493 }
7494 }
7495 return err;
7496}
7497
7498static int
7499dpif_netdev_ct_get_limits(struct dpif *dpif OVS_UNUSED,
7500 uint32_t *default_limit,
7501 const struct ovs_list *zone_limits_request,
7502 struct ovs_list *zone_limits_reply)
7503{
7504 struct dp_netdev *dp = get_dp_netdev(dpif);
7505 struct conntrack_zone_limit czl;
7506
7507 czl = zone_limit_get(dp->conntrack, DEFAULT_ZONE);
7508 if (czl.zone == DEFAULT_ZONE) {
7509 *default_limit = czl.limit;
7510 } else {
7511 return EINVAL;
7512 }
7513
7514 if (!ovs_list_is_empty(zone_limits_request)) {
7515 struct ct_dpif_zone_limit *zone_limit;
7516 LIST_FOR_EACH (zone_limit, node, zone_limits_request) {
7517 czl = zone_limit_get(dp->conntrack, zone_limit->zone);
7518 if (czl.zone == zone_limit->zone || czl.zone == DEFAULT_ZONE) {
7519 ct_dpif_push_zone_limit(zone_limits_reply, zone_limit->zone,
7520 czl.limit, czl.count);
7521 } else {
7522 return EINVAL;
7523 }
7524 }
7525 } else {
7526 for (int z = MIN_ZONE; z <= MAX_ZONE; z++) {
7527 czl = zone_limit_get(dp->conntrack, z);
7528 if (czl.zone == z) {
7529 ct_dpif_push_zone_limit(zone_limits_reply, z, czl.limit,
7530 czl.count);
7531 }
7532 }
7533 }
7534
7535 return 0;
7536}
7537
7538static int
7539dpif_netdev_ct_del_limits(struct dpif *dpif OVS_UNUSED,
7540 const struct ovs_list *zone_limits)
7541{
7542 int err = 0;
7543 struct dp_netdev *dp = get_dp_netdev(dpif);
7544 struct ct_dpif_zone_limit *zone_limit;
7545 LIST_FOR_EACH (zone_limit, node, zone_limits) {
7546 err = zone_limit_delete(dp->conntrack, zone_limit->zone);
7547 if (err != 0) {
7548 break;
7549 }
7550 }
7551
7552 return err;
7553}
7554
4ea96698
DB
7555static int
7556dpif_netdev_ipf_set_enabled(struct dpif *dpif, bool v6, bool enable)
7557{
7558 struct dp_netdev *dp = get_dp_netdev(dpif);
57593fd2 7559 return ipf_set_enabled(conntrack_ipf_ctx(dp->conntrack), v6, enable);
4ea96698
DB
7560}
7561
7562static int
7563dpif_netdev_ipf_set_min_frag(struct dpif *dpif, bool v6, uint32_t min_frag)
7564{
7565 struct dp_netdev *dp = get_dp_netdev(dpif);
57593fd2 7566 return ipf_set_min_frag(conntrack_ipf_ctx(dp->conntrack), v6, min_frag);
4ea96698
DB
7567}
7568
7569static int
7570dpif_netdev_ipf_set_max_nfrags(struct dpif *dpif, uint32_t max_frags)
7571{
7572 struct dp_netdev *dp = get_dp_netdev(dpif);
57593fd2 7573 return ipf_set_max_nfrags(conntrack_ipf_ctx(dp->conntrack), max_frags);
4ea96698
DB
7574}
7575
7576/* Adjust this function if 'dpif_ipf_status' and 'ipf_status' were to
7577 * diverge. */
7578static int
7579dpif_netdev_ipf_get_status(struct dpif *dpif,
7580 struct dpif_ipf_status *dpif_ipf_status)
7581{
7582 struct dp_netdev *dp = get_dp_netdev(dpif);
57593fd2 7583 ipf_get_status(conntrack_ipf_ctx(dp->conntrack),
4ea96698
DB
7584 (struct ipf_status *) dpif_ipf_status);
7585 return 0;
7586}
7587
7588static int
7589dpif_netdev_ipf_dump_start(struct dpif *dpif OVS_UNUSED,
7590 struct ipf_dump_ctx **ipf_dump_ctx)
7591{
7592 return ipf_dump_start(ipf_dump_ctx);
7593}
7594
7595static int
7596dpif_netdev_ipf_dump_next(struct dpif *dpif, void *ipf_dump_ctx, char **dump)
7597{
7598 struct dp_netdev *dp = get_dp_netdev(dpif);
57593fd2 7599 return ipf_dump_next(conntrack_ipf_ctx(dp->conntrack), ipf_dump_ctx,
4ea96698
DB
7600 dump);
7601}
7602
7603static int
7604dpif_netdev_ipf_dump_done(struct dpif *dpif OVS_UNUSED, void *ipf_dump_ctx)
7605{
7606 return ipf_dump_done(ipf_dump_ctx);
7607
7608}
7609
72865317 7610const struct dpif_class dpif_netdev_class = {
72865317 7611 "netdev",
f87c1357 7612 true, /* cleanup_required */
6553d06b 7613 dpif_netdev_init,
2197d7ab 7614 dpif_netdev_enumerate,
0aeaabc8 7615 dpif_netdev_port_open_type,
72865317
BP
7616 dpif_netdev_open,
7617 dpif_netdev_close,
7dab847a 7618 dpif_netdev_destroy,
e4cfed38
PS
7619 dpif_netdev_run,
7620 dpif_netdev_wait,
72865317 7621 dpif_netdev_get_stats,
72865317
BP
7622 dpif_netdev_port_add,
7623 dpif_netdev_port_del,
3eb67853 7624 dpif_netdev_port_set_config,
72865317
BP
7625 dpif_netdev_port_query_by_number,
7626 dpif_netdev_port_query_by_name,
98403001 7627 NULL, /* port_get_pid */
b0ec0f27
BP
7628 dpif_netdev_port_dump_start,
7629 dpif_netdev_port_dump_next,
7630 dpif_netdev_port_dump_done,
72865317
BP
7631 dpif_netdev_port_poll,
7632 dpif_netdev_port_poll_wait,
72865317 7633 dpif_netdev_flow_flush,
ac64794a
BP
7634 dpif_netdev_flow_dump_create,
7635 dpif_netdev_flow_dump_destroy,
7636 dpif_netdev_flow_dump_thread_create,
7637 dpif_netdev_flow_dump_thread_destroy,
704a1e09 7638 dpif_netdev_flow_dump_next,
1a0c894a 7639 dpif_netdev_operate,
6b31e073
RW
7640 NULL, /* recv_set */
7641 NULL, /* handlers_set */
d4f6865c 7642 dpif_netdev_set_config,
5bf93d67 7643 dpif_netdev_queue_to_priority,
6b31e073
RW
7644 NULL, /* recv */
7645 NULL, /* recv_wait */
7646 NULL, /* recv_purge */
e4e74c3a 7647 dpif_netdev_register_dp_purge_cb,
6b31e073
RW
7648 dpif_netdev_register_upcall_cb,
7649 dpif_netdev_enable_upcall,
7650 dpif_netdev_disable_upcall,
b5cbbcf6 7651 dpif_netdev_get_datapath_version,
4d4e68ed
DDP
7652 dpif_netdev_ct_dump_start,
7653 dpif_netdev_ct_dump_next,
7654 dpif_netdev_ct_dump_done,
5d9cbb4c 7655 dpif_netdev_ct_flush,
c92339ad
DB
7656 dpif_netdev_ct_set_maxconns,
7657 dpif_netdev_ct_get_maxconns,
875075b3 7658 dpif_netdev_ct_get_nconns,
64207120
DB
7659 dpif_netdev_ct_set_tcp_seq_chk,
7660 dpif_netdev_ct_get_tcp_seq_chk,
a7f33fdb
DB
7661 dpif_netdev_ct_set_limits,
7662 dpif_netdev_ct_get_limits,
7663 dpif_netdev_ct_del_limits,
1f161318
YHW
7664 NULL, /* ct_set_timeout_policy */
7665 NULL, /* ct_get_timeout_policy */
7666 NULL, /* ct_del_timeout_policy */
7667 NULL, /* ct_timeout_policy_dump_start */
7668 NULL, /* ct_timeout_policy_dump_next */
7669 NULL, /* ct_timeout_policy_dump_done */
187bb41f 7670 NULL, /* ct_get_timeout_policy_name */
4ea96698
DB
7671 dpif_netdev_ipf_set_enabled,
7672 dpif_netdev_ipf_set_min_frag,
7673 dpif_netdev_ipf_set_max_nfrags,
7674 dpif_netdev_ipf_get_status,
7675 dpif_netdev_ipf_dump_start,
7676 dpif_netdev_ipf_dump_next,
7677 dpif_netdev_ipf_dump_done,
5dddf960
JR
7678 dpif_netdev_meter_get_features,
7679 dpif_netdev_meter_set,
7680 dpif_netdev_meter_get,
7681 dpif_netdev_meter_del,
72865317 7682};
614c4892 7683
74cc3969
BP
7684static void
7685dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
7686 const char *argv[], void *aux OVS_UNUSED)
7687{
e9985d6a 7688 struct dp_netdev_port *port;
74cc3969 7689 struct dp_netdev *dp;
ff073a71 7690 odp_port_t port_no;
74cc3969 7691
8a4e3a85 7692 ovs_mutex_lock(&dp_netdev_mutex);
74cc3969
BP
7693 dp = shash_find_data(&dp_netdevs, argv[1]);
7694 if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
8a4e3a85 7695 ovs_mutex_unlock(&dp_netdev_mutex);
74cc3969
BP
7696 unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
7697 return;
7698 }
8a4e3a85
BP
7699 ovs_refcount_ref(&dp->ref_cnt);
7700 ovs_mutex_unlock(&dp_netdev_mutex);
74cc3969 7701
59e6d833 7702 ovs_mutex_lock(&dp->port_mutex);
e9985d6a 7703 if (get_port_by_name(dp, argv[2], &port)) {
74cc3969 7704 unixctl_command_reply_error(conn, "unknown port");
8a4e3a85 7705 goto exit;
74cc3969
BP
7706 }
7707
ff073a71
BP
7708 port_no = u32_to_odp(atoi(argv[3]));
7709 if (!port_no || port_no == ODPP_NONE) {
74cc3969 7710 unixctl_command_reply_error(conn, "bad port number");
8a4e3a85 7711 goto exit;
74cc3969 7712 }
ff073a71 7713 if (dp_netdev_lookup_port(dp, port_no)) {
74cc3969 7714 unixctl_command_reply_error(conn, "port number already in use");
8a4e3a85 7715 goto exit;
74cc3969 7716 }
59e6d833 7717
e9985d6a
DDP
7718 /* Remove port. */
7719 hmap_remove(&dp->ports, &port->node);
e32971b8 7720 reconfigure_datapath(dp);
59e6d833 7721
e9985d6a
DDP
7722 /* Reinsert with new port number. */
7723 port->port_no = port_no;
7724 hmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
e32971b8 7725 reconfigure_datapath(dp);
59e6d833 7726
d33ed218 7727 seq_change(dp->port_seq);
74cc3969 7728 unixctl_command_reply(conn, NULL);
8a4e3a85
BP
7729
7730exit:
59e6d833 7731 ovs_mutex_unlock(&dp->port_mutex);
8a4e3a85 7732 dp_netdev_unref(dp);
74cc3969
BP
7733}
7734
0cbfe35d
BP
7735static void
7736dpif_dummy_register__(const char *type)
7737{
7738 struct dpif_class *class;
7739
7740 class = xmalloc(sizeof *class);
7741 *class = dpif_netdev_class;
7742 class->type = xstrdup(type);
7743 dp_register_provider(class);
7744}
7745
8420c7ad
BP
7746static void
7747dpif_dummy_override(const char *type)
7748{
65d43fdc
YT
7749 int error;
7750
7751 /*
7752 * Ignore EAFNOSUPPORT to allow --enable-dummy=system with
7753 * a userland-only build. It's useful for testsuite.
7754 */
7755 error = dp_unregister_provider(type);
7756 if (error == 0 || error == EAFNOSUPPORT) {
8420c7ad
BP
7757 dpif_dummy_register__(type);
7758 }
7759}
7760
614c4892 7761void
8420c7ad 7762dpif_dummy_register(enum dummy_level level)
614c4892 7763{
8420c7ad 7764 if (level == DUMMY_OVERRIDE_ALL) {
0cbfe35d
BP
7765 struct sset types;
7766 const char *type;
7767
7768 sset_init(&types);
7769 dp_enumerate_types(&types);
7770 SSET_FOR_EACH (type, &types) {
8420c7ad 7771 dpif_dummy_override(type);
0cbfe35d
BP
7772 }
7773 sset_destroy(&types);
8420c7ad
BP
7774 } else if (level == DUMMY_OVERRIDE_SYSTEM) {
7775 dpif_dummy_override("system");
614c4892 7776 }
0cbfe35d
BP
7777
7778 dpif_dummy_register__("dummy");
74cc3969
BP
7779
7780 unixctl_command_register("dpif-dummy/change-port-number",
74467d5c 7781 "dp port new-number",
74cc3969 7782 3, 3, dpif_dummy_change_port_number, NULL);
614c4892 7783}
0de8783a
JR
7784\f
7785/* Datapath Classifier. */
7786
0fcf0776
ZF
7787static void
7788dpcls_subtable_destroy_cb(struct dpcls_subtable *subtable)
7789{
7790 cmap_destroy(&subtable->rules);
a0b36b39 7791 ovsrcu_postpone(free, subtable->mf_masks);
0fcf0776
ZF
7792 ovsrcu_postpone(free, subtable);
7793}
7794
0de8783a
JR
7795/* Initializes 'cls' as a classifier that initially contains no classification
7796 * rules. */
7797static void
7798dpcls_init(struct dpcls *cls)
7799{
7800 cmap_init(&cls->subtables_map);
da9cfca6 7801 pvector_init(&cls->subtables);
0de8783a
JR
7802}
7803
7804static void
7805dpcls_destroy_subtable(struct dpcls *cls, struct dpcls_subtable *subtable)
7806{
3453b4d6 7807 VLOG_DBG("Destroying subtable %p for in_port %d", subtable, cls->in_port);
da9cfca6 7808 pvector_remove(&cls->subtables, subtable);
0de8783a
JR
7809 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
7810 subtable->mask.hash);
0fcf0776 7811 ovsrcu_postpone(dpcls_subtable_destroy_cb, subtable);
0de8783a
JR
7812}
7813
7814/* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
7815 * caller's responsibility.
7816 * May only be called after all the readers have been terminated. */
7817static void
7818dpcls_destroy(struct dpcls *cls)
7819{
7820 if (cls) {
7821 struct dpcls_subtable *subtable;
7822
7823 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
361d808d 7824 ovs_assert(cmap_count(&subtable->rules) == 0);
0de8783a
JR
7825 dpcls_destroy_subtable(cls, subtable);
7826 }
7827 cmap_destroy(&cls->subtables_map);
da9cfca6 7828 pvector_destroy(&cls->subtables);
0de8783a
JR
7829 }
7830}
7831
7832static struct dpcls_subtable *
7833dpcls_create_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
7834{
7835 struct dpcls_subtable *subtable;
7836
7837 /* Need to add one. */
caeb4906
JR
7838 subtable = xmalloc(sizeof *subtable
7839 - sizeof subtable->mask.mf + mask->len);
0de8783a 7840 cmap_init(&subtable->rules);
3453b4d6 7841 subtable->hit_cnt = 0;
0de8783a 7842 netdev_flow_key_clone(&subtable->mask, mask);
aadede3d 7843
a0b36b39
HH
7844 /* The count of bits in the mask defines the space required for masks.
7845 * Then call gen_masks() to create the appropriate masks, avoiding the cost
7846 * of doing runtime calculations. */
7847 uint32_t unit0 = count_1bits(mask->mf.map.bits[0]);
7848 uint32_t unit1 = count_1bits(mask->mf.map.bits[1]);
7849 subtable->mf_bits_set_unit0 = unit0;
7850 subtable->mf_bits_set_unit1 = unit1;
7851 subtable->mf_masks = xmalloc(sizeof(uint64_t) * (unit0 + unit1));
7852 netdev_flow_key_gen_masks(mask, subtable->mf_masks, unit0, unit1);
7853
f54d8f00
HH
7854 /* Probe for a specialized generic lookup function. */
7855 subtable->lookup_func = dpcls_subtable_generic_probe(unit0, unit1);
7856
7857 /* If not set, assign generic lookup. Generic works for any miniflow. */
7858 if (!subtable->lookup_func) {
7859 subtable->lookup_func = dpcls_subtable_lookup_generic;
7860 }
aadede3d 7861
0de8783a 7862 cmap_insert(&cls->subtables_map, &subtable->cmap_node, mask->hash);
3453b4d6 7863 /* Add the new subtable at the end of the pvector (with no hits yet) */
da9cfca6 7864 pvector_insert(&cls->subtables, subtable, 0);
84dbfb2b 7865 VLOG_DBG("Creating %"PRIuSIZE". subtable %p for in_port %d",
3453b4d6 7866 cmap_count(&cls->subtables_map), subtable, cls->in_port);
da9cfca6 7867 pvector_publish(&cls->subtables);
0de8783a
JR
7868
7869 return subtable;
7870}
7871
7872static inline struct dpcls_subtable *
7873dpcls_find_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
7874{
7875 struct dpcls_subtable *subtable;
7876
7877 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, mask->hash,
7878 &cls->subtables_map) {
7879 if (netdev_flow_key_equal(&subtable->mask, mask)) {
7880 return subtable;
7881 }
7882 }
7883 return dpcls_create_subtable(cls, mask);
7884}
7885
3453b4d6
JS
7886
7887/* Periodically sort the dpcls subtable vectors according to hit counts */
7888static void
7889dpcls_sort_subtable_vector(struct dpcls *cls)
7890{
7891 struct pvector *pvec = &cls->subtables;
7892 struct dpcls_subtable *subtable;
7893
7894 PVECTOR_FOR_EACH (subtable, pvec) {
7895 pvector_change_priority(pvec, subtable, subtable->hit_cnt);
7896 subtable->hit_cnt = 0;
7897 }
7898 pvector_publish(pvec);
7899}
7900
7901static inline void
4809891b
KT
7902dp_netdev_pmd_try_optimize(struct dp_netdev_pmd_thread *pmd,
7903 struct polled_queue *poll_list, int poll_cnt)
3453b4d6
JS
7904{
7905 struct dpcls *cls;
5bf84282
NK
7906 uint64_t tot_idle = 0, tot_proc = 0;
7907 unsigned int pmd_load = 0;
3453b4d6 7908
b010be17 7909 if (pmd->ctx.now > pmd->rxq_next_cycle_store) {
2a2c67b4 7910 uint64_t curr_tsc;
5bf84282
NK
7911 struct pmd_auto_lb *pmd_alb = &pmd->dp->pmd_alb;
7912 if (pmd_alb->is_enabled && !pmd->isolated
7913 && (pmd->perf_stats.counters.n[PMD_CYCLES_ITER_IDLE] >=
7914 pmd->prev_stats[PMD_CYCLES_ITER_IDLE])
7915 && (pmd->perf_stats.counters.n[PMD_CYCLES_ITER_BUSY] >=
7916 pmd->prev_stats[PMD_CYCLES_ITER_BUSY]))
7917 {
7918 tot_idle = pmd->perf_stats.counters.n[PMD_CYCLES_ITER_IDLE] -
7919 pmd->prev_stats[PMD_CYCLES_ITER_IDLE];
7920 tot_proc = pmd->perf_stats.counters.n[PMD_CYCLES_ITER_BUSY] -
7921 pmd->prev_stats[PMD_CYCLES_ITER_BUSY];
7922
7923 if (tot_proc) {
7924 pmd_load = ((tot_proc * 100) / (tot_idle + tot_proc));
7925 }
7926
7927 if (pmd_load >= ALB_PMD_LOAD_THRESHOLD) {
7928 atomic_count_inc(&pmd->pmd_overloaded);
7929 } else {
7930 atomic_count_set(&pmd->pmd_overloaded, 0);
7931 }
7932 }
7933
7934 pmd->prev_stats[PMD_CYCLES_ITER_IDLE] =
7935 pmd->perf_stats.counters.n[PMD_CYCLES_ITER_IDLE];
7936 pmd->prev_stats[PMD_CYCLES_ITER_BUSY] =
7937 pmd->perf_stats.counters.n[PMD_CYCLES_ITER_BUSY];
7938
4809891b
KT
7939 /* Get the cycles that were used to process each queue and store. */
7940 for (unsigned i = 0; i < poll_cnt; i++) {
7941 uint64_t rxq_cyc_curr = dp_netdev_rxq_get_cycles(poll_list[i].rxq,
7942 RXQ_CYCLES_PROC_CURR);
7943 dp_netdev_rxq_set_intrvl_cycles(poll_list[i].rxq, rxq_cyc_curr);
7944 dp_netdev_rxq_set_cycles(poll_list[i].rxq, RXQ_CYCLES_PROC_CURR,
7945 0);
7946 }
2a2c67b4
KT
7947 curr_tsc = cycles_counter_update(&pmd->perf_stats);
7948 if (pmd->intrvl_tsc_prev) {
7949 /* There is a prev timestamp, store a new intrvl cycle count. */
7950 atomic_store_relaxed(&pmd->intrvl_cycles,
7951 curr_tsc - pmd->intrvl_tsc_prev);
7952 }
7953 pmd->intrvl_tsc_prev = curr_tsc;
4809891b 7954 /* Start new measuring interval */
b010be17 7955 pmd->rxq_next_cycle_store = pmd->ctx.now + PMD_RXQ_INTERVAL_LEN;
4809891b
KT
7956 }
7957
b010be17 7958 if (pmd->ctx.now > pmd->next_optimization) {
3453b4d6
JS
7959 /* Try to obtain the flow lock to block out revalidator threads.
7960 * If not possible, just try next time. */
7961 if (!ovs_mutex_trylock(&pmd->flow_mutex)) {
7962 /* Optimize each classifier */
7963 CMAP_FOR_EACH (cls, node, &pmd->classifiers) {
7964 dpcls_sort_subtable_vector(cls);
7965 }
7966 ovs_mutex_unlock(&pmd->flow_mutex);
7967 /* Start new measuring interval */
b010be17
IM
7968 pmd->next_optimization = pmd->ctx.now
7969 + DPCLS_OPTIMIZATION_INTERVAL;
3453b4d6
JS
7970 }
7971 }
7972}
7973
0de8783a
JR
7974/* Insert 'rule' into 'cls'. */
7975static void
7976dpcls_insert(struct dpcls *cls, struct dpcls_rule *rule,
7977 const struct netdev_flow_key *mask)
7978{
7979 struct dpcls_subtable *subtable = dpcls_find_subtable(cls, mask);
7980
3453b4d6 7981 /* Refer to subtable's mask, also for later removal. */
0de8783a
JR
7982 rule->mask = &subtable->mask;
7983 cmap_insert(&subtable->rules, &rule->cmap_node, rule->flow.hash);
7984}
7985
7986/* Removes 'rule' from 'cls', also destructing the 'rule'. */
7987static void
7988dpcls_remove(struct dpcls *cls, struct dpcls_rule *rule)
7989{
7990 struct dpcls_subtable *subtable;
7991
7992 ovs_assert(rule->mask);
7993
3453b4d6 7994 /* Get subtable from reference in rule->mask. */
0de8783a 7995 INIT_CONTAINER(subtable, rule->mask, mask);
0de8783a
JR
7996 if (cmap_remove(&subtable->rules, &rule->cmap_node, rule->flow.hash)
7997 == 0) {
3453b4d6 7998 /* Delete empty subtable. */
0de8783a 7999 dpcls_destroy_subtable(cls, subtable);
da9cfca6 8000 pvector_publish(&cls->subtables);
0de8783a
JR
8001 }
8002}
8003
a0b36b39
HH
8004/* Inner loop for mask generation of a unit, see netdev_flow_key_gen_masks. */
8005static inline void
8006netdev_flow_key_gen_mask_unit(uint64_t iter,
8007 const uint64_t count,
8008 uint64_t *mf_masks)
8009{
8010 int i;
8011 for (i = 0; i < count; i++) {
8012 uint64_t lowest_bit = (iter & -iter);
8013 iter &= ~lowest_bit;
8014 mf_masks[i] = (lowest_bit - 1);
8015 }
8016 /* Checks that count has covered all bits in the iter bitmap. */
8017 ovs_assert(iter == 0);
8018}
8019
8020/* Generate a mask for each block in the miniflow, based on the bits set. This
8021 * allows easily masking packets with the generated array here, without
8022 * calculations. This replaces runtime-calculating the masks.
8023 * @param key The table to generate the mf_masks for
8024 * @param mf_masks Pointer to a u64 array of at least *mf_bits* in size
8025 * @param mf_bits_total Number of bits set in the whole miniflow (both units)
8026 * @param mf_bits_unit0 Number of bits set in unit0 of the miniflow
8027 */
8028void
8029netdev_flow_key_gen_masks(const struct netdev_flow_key *tbl,
8030 uint64_t *mf_masks,
8031 const uint32_t mf_bits_u0,
8032 const uint32_t mf_bits_u1)
8033{
8034 uint64_t iter_u0 = tbl->mf.map.bits[0];
8035 uint64_t iter_u1 = tbl->mf.map.bits[1];
8036
8037 netdev_flow_key_gen_mask_unit(iter_u0, mf_bits_u0, &mf_masks[0]);
8038 netdev_flow_key_gen_mask_unit(iter_u1, mf_bits_u1, &mf_masks[mf_bits_u0]);
8039}
8040
361d808d
JR
8041/* Returns true if 'target' satisfies 'key' in 'mask', that is, if each 1-bit
8042 * in 'mask' the values in 'key' and 'target' are the same. */
f5ace7cd 8043bool
0de8783a
JR
8044dpcls_rule_matches_key(const struct dpcls_rule *rule,
8045 const struct netdev_flow_key *target)
8046{
09b0fa9c
JR
8047 const uint64_t *keyp = miniflow_get_values(&rule->flow.mf);
8048 const uint64_t *maskp = miniflow_get_values(&rule->mask->mf);
5fcff47b 8049 uint64_t value;
0de8783a 8050
5fcff47b
JR
8051 NETDEV_FLOW_KEY_FOR_EACH_IN_FLOWMAP(value, target, rule->flow.mf.map) {
8052 if (OVS_UNLIKELY((value & *maskp++) != *keyp++)) {
0de8783a
JR
8053 return false;
8054 }
8055 }
8056 return true;
8057}
8058
5b1c9c78
FA
8059/* For each miniflow in 'keys' performs a classifier lookup writing the result
8060 * into the corresponding slot in 'rules'. If a particular entry in 'keys' is
0de8783a
JR
8061 * NULL it is skipped.
8062 *
8063 * This function is optimized for use in the userspace datapath and therefore
8064 * does not implement a lot of features available in the standard
8065 * classifier_lookup() function. Specifically, it does not implement
8066 * priorities, instead returning any rule which matches the flow.
8067 *
5b1c9c78 8068 * Returns true if all miniflows found a corresponding rule. */
0de8783a 8069static bool
60d8ccae 8070dpcls_lookup(struct dpcls *cls, const struct netdev_flow_key *keys[],
3453b4d6
JS
8071 struct dpcls_rule **rules, const size_t cnt,
8072 int *num_lookups_p)
0de8783a 8073{
5b1c9c78 8074 /* The received 'cnt' miniflows are the search-keys that will be processed
63906f18
BB
8075 * to find a matching entry into the available subtables.
8076 * The number of bits in map_type is equal to NETDEV_MAX_BURST. */
aadede3d 8077#define MAP_BITS (sizeof(uint32_t) * CHAR_BIT)
63906f18 8078 BUILD_ASSERT_DECL(MAP_BITS >= NETDEV_MAX_BURST);
0de8783a 8079
0de8783a 8080 struct dpcls_subtable *subtable;
aadede3d 8081 uint32_t keys_map = TYPE_MAXIMUM(uint32_t); /* Set all bits. */
63906f18
BB
8082
8083 if (cnt != MAP_BITS) {
8084 keys_map >>= MAP_BITS - cnt; /* Clear extra bits. */
0de8783a
JR
8085 }
8086 memset(rules, 0, cnt * sizeof *rules);
8087
3453b4d6 8088 int lookups_match = 0, subtable_pos = 1;
aadede3d 8089 uint32_t found_map;
3453b4d6 8090
5b1c9c78
FA
8091 /* The Datapath classifier - aka dpcls - is composed of subtables.
8092 * Subtables are dynamically created as needed when new rules are inserted.
8093 * Each subtable collects rules with matches on a specific subset of packet
8094 * fields as defined by the subtable's mask. We proceed to process every
8095 * search-key against each subtable, but when a match is found for a
8096 * search-key, the search for that key can stop because the rules are
8097 * non-overlapping. */
da9cfca6 8098 PVECTOR_FOR_EACH (subtable, &cls->subtables) {
aadede3d
HH
8099 /* Call the subtable specific lookup function. */
8100 found_map = subtable->lookup_func(subtable, keys_map, keys, rules);
63906f18 8101
aadede3d
HH
8102 /* Count the number of subtables searched for this packet match. This
8103 * estimates the "spread" of subtables looked at per matched packet. */
8104 uint32_t pkts_matched = count_1bits(found_map);
8105 lookups_match += pkts_matched * subtable_pos;
63906f18 8106
aadede3d
HH
8107 /* Clear the found rules, and return early if all packets are found. */
8108 keys_map &= ~found_map;
63906f18 8109 if (!keys_map) {
3453b4d6
JS
8110 if (num_lookups_p) {
8111 *num_lookups_p = lookups_match;
8112 }
aadede3d 8113 return true;
0de8783a 8114 }
3453b4d6
JS
8115 subtable_pos++;
8116 }
aadede3d 8117
3453b4d6
JS
8118 if (num_lookups_p) {
8119 *num_lookups_p = lookups_match;
0de8783a 8120 }
aadede3d 8121 return false;
0de8783a 8122}