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