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