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