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