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