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