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