]> git.proxmox.com Git - mirror_ovs.git/blob - lib/dpif-netdev.c
dpif-netdev: Initialize 'tun_md' member of match.
[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 'rxqs' */
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 if (odp_flow_key_to_flow(key, key_len, flow)) {
2258 if (!probe) {
2259 /* This should not happen: it indicates that
2260 * odp_flow_key_from_flow() and odp_flow_key_to_flow() disagree on
2261 * the acceptable form of a flow. Log the problem as an error,
2262 * with enough details to enable debugging. */
2263 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2264
2265 if (!VLOG_DROP_ERR(&rl)) {
2266 struct ds s;
2267
2268 ds_init(&s);
2269 odp_flow_format(key, key_len, NULL, 0, NULL, &s, true);
2270 VLOG_ERR("internal error parsing flow key %s", ds_cstr(&s));
2271 ds_destroy(&s);
2272 }
2273 }
2274
2275 return EINVAL;
2276 }
2277
2278 if (flow->ct_state & DP_NETDEV_CS_UNSUPPORTED_MASK) {
2279 return EINVAL;
2280 }
2281
2282 return 0;
2283 }
2284
2285 static int
2286 dpif_netdev_flow_get(const struct dpif *dpif, const struct dpif_flow_get *get)
2287 {
2288 struct dp_netdev *dp = get_dp_netdev(dpif);
2289 struct dp_netdev_flow *netdev_flow;
2290 struct dp_netdev_pmd_thread *pmd;
2291 struct hmapx to_find = HMAPX_INITIALIZER(&to_find);
2292 struct hmapx_node *node;
2293 int error = EINVAL;
2294
2295 if (get->pmd_id == PMD_ID_NULL) {
2296 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2297 if (dp_netdev_pmd_try_ref(pmd) && !hmapx_add(&to_find, pmd)) {
2298 dp_netdev_pmd_unref(pmd);
2299 }
2300 }
2301 } else {
2302 pmd = dp_netdev_get_pmd(dp, get->pmd_id);
2303 if (!pmd) {
2304 goto out;
2305 }
2306 hmapx_add(&to_find, pmd);
2307 }
2308
2309 if (!hmapx_count(&to_find)) {
2310 goto out;
2311 }
2312
2313 HMAPX_FOR_EACH (node, &to_find) {
2314 pmd = (struct dp_netdev_pmd_thread *) node->data;
2315 netdev_flow = dp_netdev_pmd_find_flow(pmd, get->ufid, get->key,
2316 get->key_len);
2317 if (netdev_flow) {
2318 dp_netdev_flow_to_dpif_flow(netdev_flow, get->buffer, get->buffer,
2319 get->flow, false);
2320 error = 0;
2321 break;
2322 } else {
2323 error = ENOENT;
2324 }
2325 }
2326
2327 HMAPX_FOR_EACH (node, &to_find) {
2328 pmd = (struct dp_netdev_pmd_thread *) node->data;
2329 dp_netdev_pmd_unref(pmd);
2330 }
2331 out:
2332 hmapx_destroy(&to_find);
2333 return error;
2334 }
2335
2336 static struct dp_netdev_flow *
2337 dp_netdev_flow_add(struct dp_netdev_pmd_thread *pmd,
2338 struct match *match, const ovs_u128 *ufid,
2339 const struct nlattr *actions, size_t actions_len)
2340 OVS_REQUIRES(pmd->flow_mutex)
2341 {
2342 struct dp_netdev_flow *flow;
2343 struct netdev_flow_key mask;
2344 struct dpcls *cls;
2345
2346 /* Make sure in_port is exact matched before we read it. */
2347 ovs_assert(match->wc.masks.in_port.odp_port == ODPP_NONE);
2348 odp_port_t in_port = match->flow.in_port.odp_port;
2349
2350 /* As we select the dpcls based on the port number, each netdev flow
2351 * belonging to the same dpcls will have the same odp_port value.
2352 * For performance reasons we wildcard odp_port here in the mask. In the
2353 * typical case dp_hash is also wildcarded, and the resulting 8-byte
2354 * chunk {dp_hash, in_port} will be ignored by netdev_flow_mask_init() and
2355 * will not be part of the subtable mask.
2356 * This will speed up the hash computation during dpcls_lookup() because
2357 * there is one less call to hash_add64() in this case. */
2358 match->wc.masks.in_port.odp_port = 0;
2359 netdev_flow_mask_init(&mask, match);
2360 match->wc.masks.in_port.odp_port = ODPP_NONE;
2361
2362 /* Make sure wc does not have metadata. */
2363 ovs_assert(!FLOWMAP_HAS_FIELD(&mask.mf.map, metadata)
2364 && !FLOWMAP_HAS_FIELD(&mask.mf.map, regs));
2365
2366 /* Do not allocate extra space. */
2367 flow = xmalloc(sizeof *flow - sizeof flow->cr.flow.mf + mask.len);
2368 memset(&flow->stats, 0, sizeof flow->stats);
2369 flow->dead = false;
2370 flow->batch = NULL;
2371 *CONST_CAST(unsigned *, &flow->pmd_id) = pmd->core_id;
2372 *CONST_CAST(struct flow *, &flow->flow) = match->flow;
2373 *CONST_CAST(ovs_u128 *, &flow->ufid) = *ufid;
2374 ovs_refcount_init(&flow->ref_cnt);
2375 ovsrcu_set(&flow->actions, dp_netdev_actions_create(actions, actions_len));
2376
2377 netdev_flow_key_init_masked(&flow->cr.flow, &match->flow, &mask);
2378
2379 /* Select dpcls for in_port. Relies on in_port to be exact match. */
2380 cls = dp_netdev_pmd_find_dpcls(pmd, in_port);
2381 dpcls_insert(cls, &flow->cr, &mask);
2382
2383 cmap_insert(&pmd->flow_table, CONST_CAST(struct cmap_node *, &flow->node),
2384 dp_netdev_flow_hash(&flow->ufid));
2385
2386 if (OVS_UNLIKELY(!VLOG_DROP_DBG((&upcall_rl)))) {
2387 struct ds ds = DS_EMPTY_INITIALIZER;
2388 struct ofpbuf key_buf, mask_buf;
2389 struct odp_flow_key_parms odp_parms = {
2390 .flow = &match->flow,
2391 .mask = &match->wc.masks,
2392 .support = dp_netdev_support,
2393 };
2394
2395 ofpbuf_init(&key_buf, 0);
2396 ofpbuf_init(&mask_buf, 0);
2397
2398 odp_flow_key_from_flow(&odp_parms, &key_buf);
2399 odp_parms.key_buf = &key_buf;
2400 odp_flow_key_from_mask(&odp_parms, &mask_buf);
2401
2402 ds_put_cstr(&ds, "flow_add: ");
2403 odp_format_ufid(ufid, &ds);
2404 ds_put_cstr(&ds, " ");
2405 odp_flow_format(key_buf.data, key_buf.size,
2406 mask_buf.data, mask_buf.size,
2407 NULL, &ds, false);
2408 ds_put_cstr(&ds, ", actions:");
2409 format_odp_actions(&ds, actions, actions_len, NULL);
2410
2411 VLOG_DBG("%s", ds_cstr(&ds));
2412
2413 ofpbuf_uninit(&key_buf);
2414 ofpbuf_uninit(&mask_buf);
2415
2416 /* Add a printout of the actual match installed. */
2417 struct match m;
2418 ds_clear(&ds);
2419 ds_put_cstr(&ds, "flow match: ");
2420 miniflow_expand(&flow->cr.flow.mf, &m.flow);
2421 miniflow_expand(&flow->cr.mask->mf, &m.wc.masks);
2422 memset(&m.tun_md, 0, sizeof m.tun_md);
2423 match_format(&m, NULL, &ds, OFP_DEFAULT_PRIORITY);
2424
2425 VLOG_DBG("%s", ds_cstr(&ds));
2426
2427 ds_destroy(&ds);
2428 }
2429
2430 return flow;
2431 }
2432
2433 static int
2434 flow_put_on_pmd(struct dp_netdev_pmd_thread *pmd,
2435 struct netdev_flow_key *key,
2436 struct match *match,
2437 ovs_u128 *ufid,
2438 const struct dpif_flow_put *put,
2439 struct dpif_flow_stats *stats)
2440 {
2441 struct dp_netdev_flow *netdev_flow;
2442 int error = 0;
2443
2444 if (stats) {
2445 memset(stats, 0, sizeof *stats);
2446 }
2447
2448 ovs_mutex_lock(&pmd->flow_mutex);
2449 netdev_flow = dp_netdev_pmd_lookup_flow(pmd, key, NULL);
2450 if (!netdev_flow) {
2451 if (put->flags & DPIF_FP_CREATE) {
2452 if (cmap_count(&pmd->flow_table) < MAX_FLOWS) {
2453 dp_netdev_flow_add(pmd, match, ufid, put->actions,
2454 put->actions_len);
2455 error = 0;
2456 } else {
2457 error = EFBIG;
2458 }
2459 } else {
2460 error = ENOENT;
2461 }
2462 } else {
2463 if (put->flags & DPIF_FP_MODIFY) {
2464 struct dp_netdev_actions *new_actions;
2465 struct dp_netdev_actions *old_actions;
2466
2467 new_actions = dp_netdev_actions_create(put->actions,
2468 put->actions_len);
2469
2470 old_actions = dp_netdev_flow_get_actions(netdev_flow);
2471 ovsrcu_set(&netdev_flow->actions, new_actions);
2472
2473 if (stats) {
2474 get_dpif_flow_stats(netdev_flow, stats);
2475 }
2476 if (put->flags & DPIF_FP_ZERO_STATS) {
2477 /* XXX: The userspace datapath uses thread local statistics
2478 * (for flows), which should be updated only by the owning
2479 * thread. Since we cannot write on stats memory here,
2480 * we choose not to support this flag. Please note:
2481 * - This feature is currently used only by dpctl commands with
2482 * option --clear.
2483 * - Should the need arise, this operation can be implemented
2484 * by keeping a base value (to be update here) for each
2485 * counter, and subtracting it before outputting the stats */
2486 error = EOPNOTSUPP;
2487 }
2488
2489 ovsrcu_postpone(dp_netdev_actions_free, old_actions);
2490 } else if (put->flags & DPIF_FP_CREATE) {
2491 error = EEXIST;
2492 } else {
2493 /* Overlapping flow. */
2494 error = EINVAL;
2495 }
2496 }
2497 ovs_mutex_unlock(&pmd->flow_mutex);
2498 return error;
2499 }
2500
2501 static int
2502 dpif_netdev_flow_put(struct dpif *dpif, const struct dpif_flow_put *put)
2503 {
2504 struct dp_netdev *dp = get_dp_netdev(dpif);
2505 struct netdev_flow_key key, mask;
2506 struct dp_netdev_pmd_thread *pmd;
2507 struct match match;
2508 ovs_u128 ufid;
2509 int error;
2510 bool probe = put->flags & DPIF_FP_PROBE;
2511
2512 if (put->stats) {
2513 memset(put->stats, 0, sizeof *put->stats);
2514 }
2515 error = dpif_netdev_flow_from_nlattrs(put->key, put->key_len, &match.flow,
2516 probe);
2517 if (error) {
2518 return error;
2519 }
2520 error = dpif_netdev_mask_from_nlattrs(put->key, put->key_len,
2521 put->mask, put->mask_len,
2522 &match.flow, &match.wc, probe);
2523 if (error) {
2524 return error;
2525 }
2526
2527 if (put->ufid) {
2528 ufid = *put->ufid;
2529 } else {
2530 dpif_flow_hash(dpif, &match.flow, sizeof match.flow, &ufid);
2531 }
2532
2533 /* Must produce a netdev_flow_key for lookup.
2534 * Use the same method as employed to create the key when adding
2535 * the flow to the dplcs to make sure they match. */
2536 netdev_flow_mask_init(&mask, &match);
2537 netdev_flow_key_init_masked(&key, &match.flow, &mask);
2538
2539 if (put->pmd_id == PMD_ID_NULL) {
2540 if (cmap_count(&dp->poll_threads) == 0) {
2541 return EINVAL;
2542 }
2543 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2544 struct dpif_flow_stats pmd_stats;
2545 int pmd_error;
2546
2547 pmd_error = flow_put_on_pmd(pmd, &key, &match, &ufid, put,
2548 &pmd_stats);
2549 if (pmd_error) {
2550 error = pmd_error;
2551 } else if (put->stats) {
2552 put->stats->n_packets += pmd_stats.n_packets;
2553 put->stats->n_bytes += pmd_stats.n_bytes;
2554 put->stats->used = MAX(put->stats->used, pmd_stats.used);
2555 put->stats->tcp_flags |= pmd_stats.tcp_flags;
2556 }
2557 }
2558 } else {
2559 pmd = dp_netdev_get_pmd(dp, put->pmd_id);
2560 if (!pmd) {
2561 return EINVAL;
2562 }
2563 error = flow_put_on_pmd(pmd, &key, &match, &ufid, put, put->stats);
2564 dp_netdev_pmd_unref(pmd);
2565 }
2566
2567 return error;
2568 }
2569
2570 static int
2571 flow_del_on_pmd(struct dp_netdev_pmd_thread *pmd,
2572 struct dpif_flow_stats *stats,
2573 const struct dpif_flow_del *del)
2574 {
2575 struct dp_netdev_flow *netdev_flow;
2576 int error = 0;
2577
2578 ovs_mutex_lock(&pmd->flow_mutex);
2579 netdev_flow = dp_netdev_pmd_find_flow(pmd, del->ufid, del->key,
2580 del->key_len);
2581 if (netdev_flow) {
2582 if (stats) {
2583 get_dpif_flow_stats(netdev_flow, stats);
2584 }
2585 dp_netdev_pmd_remove_flow(pmd, netdev_flow);
2586 } else {
2587 error = ENOENT;
2588 }
2589 ovs_mutex_unlock(&pmd->flow_mutex);
2590
2591 return error;
2592 }
2593
2594 static int
2595 dpif_netdev_flow_del(struct dpif *dpif, const struct dpif_flow_del *del)
2596 {
2597 struct dp_netdev *dp = get_dp_netdev(dpif);
2598 struct dp_netdev_pmd_thread *pmd;
2599 int error = 0;
2600
2601 if (del->stats) {
2602 memset(del->stats, 0, sizeof *del->stats);
2603 }
2604
2605 if (del->pmd_id == PMD_ID_NULL) {
2606 if (cmap_count(&dp->poll_threads) == 0) {
2607 return EINVAL;
2608 }
2609 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
2610 struct dpif_flow_stats pmd_stats;
2611 int pmd_error;
2612
2613 pmd_error = flow_del_on_pmd(pmd, &pmd_stats, del);
2614 if (pmd_error) {
2615 error = pmd_error;
2616 } else if (del->stats) {
2617 del->stats->n_packets += pmd_stats.n_packets;
2618 del->stats->n_bytes += pmd_stats.n_bytes;
2619 del->stats->used = MAX(del->stats->used, pmd_stats.used);
2620 del->stats->tcp_flags |= pmd_stats.tcp_flags;
2621 }
2622 }
2623 } else {
2624 pmd = dp_netdev_get_pmd(dp, del->pmd_id);
2625 if (!pmd) {
2626 return EINVAL;
2627 }
2628 error = flow_del_on_pmd(pmd, del->stats, del);
2629 dp_netdev_pmd_unref(pmd);
2630 }
2631
2632
2633 return error;
2634 }
2635
2636 struct dpif_netdev_flow_dump {
2637 struct dpif_flow_dump up;
2638 struct cmap_position poll_thread_pos;
2639 struct cmap_position flow_pos;
2640 struct dp_netdev_pmd_thread *cur_pmd;
2641 int status;
2642 struct ovs_mutex mutex;
2643 };
2644
2645 static struct dpif_netdev_flow_dump *
2646 dpif_netdev_flow_dump_cast(struct dpif_flow_dump *dump)
2647 {
2648 return CONTAINER_OF(dump, struct dpif_netdev_flow_dump, up);
2649 }
2650
2651 static struct dpif_flow_dump *
2652 dpif_netdev_flow_dump_create(const struct dpif *dpif_, bool terse,
2653 char *type OVS_UNUSED)
2654 {
2655 struct dpif_netdev_flow_dump *dump;
2656
2657 dump = xzalloc(sizeof *dump);
2658 dpif_flow_dump_init(&dump->up, dpif_);
2659 dump->up.terse = terse;
2660 ovs_mutex_init(&dump->mutex);
2661
2662 return &dump->up;
2663 }
2664
2665 static int
2666 dpif_netdev_flow_dump_destroy(struct dpif_flow_dump *dump_)
2667 {
2668 struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
2669
2670 ovs_mutex_destroy(&dump->mutex);
2671 free(dump);
2672 return 0;
2673 }
2674
2675 struct dpif_netdev_flow_dump_thread {
2676 struct dpif_flow_dump_thread up;
2677 struct dpif_netdev_flow_dump *dump;
2678 struct odputil_keybuf keybuf[FLOW_DUMP_MAX_BATCH];
2679 struct odputil_keybuf maskbuf[FLOW_DUMP_MAX_BATCH];
2680 };
2681
2682 static struct dpif_netdev_flow_dump_thread *
2683 dpif_netdev_flow_dump_thread_cast(struct dpif_flow_dump_thread *thread)
2684 {
2685 return CONTAINER_OF(thread, struct dpif_netdev_flow_dump_thread, up);
2686 }
2687
2688 static struct dpif_flow_dump_thread *
2689 dpif_netdev_flow_dump_thread_create(struct dpif_flow_dump *dump_)
2690 {
2691 struct dpif_netdev_flow_dump *dump = dpif_netdev_flow_dump_cast(dump_);
2692 struct dpif_netdev_flow_dump_thread *thread;
2693
2694 thread = xmalloc(sizeof *thread);
2695 dpif_flow_dump_thread_init(&thread->up, &dump->up);
2696 thread->dump = dump;
2697 return &thread->up;
2698 }
2699
2700 static void
2701 dpif_netdev_flow_dump_thread_destroy(struct dpif_flow_dump_thread *thread_)
2702 {
2703 struct dpif_netdev_flow_dump_thread *thread
2704 = dpif_netdev_flow_dump_thread_cast(thread_);
2705
2706 free(thread);
2707 }
2708
2709 static int
2710 dpif_netdev_flow_dump_next(struct dpif_flow_dump_thread *thread_,
2711 struct dpif_flow *flows, int max_flows)
2712 {
2713 struct dpif_netdev_flow_dump_thread *thread
2714 = dpif_netdev_flow_dump_thread_cast(thread_);
2715 struct dpif_netdev_flow_dump *dump = thread->dump;
2716 struct dp_netdev_flow *netdev_flows[FLOW_DUMP_MAX_BATCH];
2717 int n_flows = 0;
2718 int i;
2719
2720 ovs_mutex_lock(&dump->mutex);
2721 if (!dump->status) {
2722 struct dpif_netdev *dpif = dpif_netdev_cast(thread->up.dpif);
2723 struct dp_netdev *dp = get_dp_netdev(&dpif->dpif);
2724 struct dp_netdev_pmd_thread *pmd = dump->cur_pmd;
2725 int flow_limit = MIN(max_flows, FLOW_DUMP_MAX_BATCH);
2726
2727 /* First call to dump_next(), extracts the first pmd thread.
2728 * If there is no pmd thread, returns immediately. */
2729 if (!pmd) {
2730 pmd = dp_netdev_pmd_get_next(dp, &dump->poll_thread_pos);
2731 if (!pmd) {
2732 ovs_mutex_unlock(&dump->mutex);
2733 return n_flows;
2734
2735 }
2736 }
2737
2738 do {
2739 for (n_flows = 0; n_flows < flow_limit; n_flows++) {
2740 struct cmap_node *node;
2741
2742 node = cmap_next_position(&pmd->flow_table, &dump->flow_pos);
2743 if (!node) {
2744 break;
2745 }
2746 netdev_flows[n_flows] = CONTAINER_OF(node,
2747 struct dp_netdev_flow,
2748 node);
2749 }
2750 /* When finishing dumping the current pmd thread, moves to
2751 * the next. */
2752 if (n_flows < flow_limit) {
2753 memset(&dump->flow_pos, 0, sizeof dump->flow_pos);
2754 dp_netdev_pmd_unref(pmd);
2755 pmd = dp_netdev_pmd_get_next(dp, &dump->poll_thread_pos);
2756 if (!pmd) {
2757 dump->status = EOF;
2758 break;
2759 }
2760 }
2761 /* Keeps the reference to next caller. */
2762 dump->cur_pmd = pmd;
2763
2764 /* If the current dump is empty, do not exit the loop, since the
2765 * remaining pmds could have flows to be dumped. Just dumps again
2766 * on the new 'pmd'. */
2767 } while (!n_flows);
2768 }
2769 ovs_mutex_unlock(&dump->mutex);
2770
2771 for (i = 0; i < n_flows; i++) {
2772 struct odputil_keybuf *maskbuf = &thread->maskbuf[i];
2773 struct odputil_keybuf *keybuf = &thread->keybuf[i];
2774 struct dp_netdev_flow *netdev_flow = netdev_flows[i];
2775 struct dpif_flow *f = &flows[i];
2776 struct ofpbuf key, mask;
2777
2778 ofpbuf_use_stack(&key, keybuf, sizeof *keybuf);
2779 ofpbuf_use_stack(&mask, maskbuf, sizeof *maskbuf);
2780 dp_netdev_flow_to_dpif_flow(netdev_flow, &key, &mask, f,
2781 dump->up.terse);
2782 }
2783
2784 return n_flows;
2785 }
2786
2787 static int
2788 dpif_netdev_execute(struct dpif *dpif, struct dpif_execute *execute)
2789 OVS_NO_THREAD_SAFETY_ANALYSIS
2790 {
2791 struct dp_netdev *dp = get_dp_netdev(dpif);
2792 struct dp_netdev_pmd_thread *pmd;
2793 struct dp_packet_batch pp;
2794
2795 if (dp_packet_size(execute->packet) < ETH_HEADER_LEN ||
2796 dp_packet_size(execute->packet) > UINT16_MAX) {
2797 return EINVAL;
2798 }
2799
2800 /* Tries finding the 'pmd'. If NULL is returned, that means
2801 * the current thread is a non-pmd thread and should use
2802 * dp_netdev_get_pmd(dp, NON_PMD_CORE_ID). */
2803 pmd = ovsthread_getspecific(dp->per_pmd_key);
2804 if (!pmd) {
2805 pmd = dp_netdev_get_pmd(dp, NON_PMD_CORE_ID);
2806 if (!pmd) {
2807 return EBUSY;
2808 }
2809 }
2810
2811 if (execute->probe) {
2812 /* If this is part of a probe, Drop the packet, since executing
2813 * the action may actually cause spurious packets be sent into
2814 * the network. */
2815 return 0;
2816 }
2817
2818 /* If the current thread is non-pmd thread, acquires
2819 * the 'non_pmd_mutex'. */
2820 if (pmd->core_id == NON_PMD_CORE_ID) {
2821 ovs_mutex_lock(&dp->non_pmd_mutex);
2822 }
2823
2824 /* The action processing expects the RSS hash to be valid, because
2825 * it's always initialized at the beginning of datapath processing.
2826 * In this case, though, 'execute->packet' may not have gone through
2827 * the datapath at all, it may have been generated by the upper layer
2828 * (OpenFlow packet-out, BFD frame, ...). */
2829 if (!dp_packet_rss_valid(execute->packet)) {
2830 dp_packet_set_rss_hash(execute->packet,
2831 flow_hash_5tuple(execute->flow, 0));
2832 }
2833
2834 dp_packet_batch_init_packet(&pp, execute->packet);
2835 dp_netdev_execute_actions(pmd, &pp, false, execute->flow,
2836 execute->actions, execute->actions_len,
2837 time_msec());
2838
2839 if (pmd->core_id == NON_PMD_CORE_ID) {
2840 ovs_mutex_unlock(&dp->non_pmd_mutex);
2841 dp_netdev_pmd_unref(pmd);
2842 }
2843
2844 return 0;
2845 }
2846
2847 static void
2848 dpif_netdev_operate(struct dpif *dpif, struct dpif_op **ops, size_t n_ops)
2849 {
2850 size_t i;
2851
2852 for (i = 0; i < n_ops; i++) {
2853 struct dpif_op *op = ops[i];
2854
2855 switch (op->type) {
2856 case DPIF_OP_FLOW_PUT:
2857 op->error = dpif_netdev_flow_put(dpif, &op->u.flow_put);
2858 break;
2859
2860 case DPIF_OP_FLOW_DEL:
2861 op->error = dpif_netdev_flow_del(dpif, &op->u.flow_del);
2862 break;
2863
2864 case DPIF_OP_EXECUTE:
2865 op->error = dpif_netdev_execute(dpif, &op->u.execute);
2866 break;
2867
2868 case DPIF_OP_FLOW_GET:
2869 op->error = dpif_netdev_flow_get(dpif, &op->u.flow_get);
2870 break;
2871 }
2872 }
2873 }
2874
2875 /* Applies datapath configuration from the database. Some of the changes are
2876 * actually applied in dpif_netdev_run(). */
2877 static int
2878 dpif_netdev_set_config(struct dpif *dpif, const struct smap *other_config)
2879 {
2880 struct dp_netdev *dp = get_dp_netdev(dpif);
2881 const char *cmask = smap_get(other_config, "pmd-cpu-mask");
2882 unsigned long long insert_prob =
2883 smap_get_ullong(other_config, "emc-insert-inv-prob",
2884 DEFAULT_EM_FLOW_INSERT_INV_PROB);
2885 uint32_t insert_min, cur_min;
2886
2887 if (!nullable_string_is_equal(dp->pmd_cmask, cmask)) {
2888 free(dp->pmd_cmask);
2889 dp->pmd_cmask = nullable_xstrdup(cmask);
2890 dp_netdev_request_reconfigure(dp);
2891 }
2892
2893 atomic_read_relaxed(&dp->emc_insert_min, &cur_min);
2894 if (insert_prob <= UINT32_MAX) {
2895 insert_min = insert_prob == 0 ? 0 : UINT32_MAX / insert_prob;
2896 } else {
2897 insert_min = DEFAULT_EM_FLOW_INSERT_MIN;
2898 insert_prob = DEFAULT_EM_FLOW_INSERT_INV_PROB;
2899 }
2900
2901 if (insert_min != cur_min) {
2902 atomic_store_relaxed(&dp->emc_insert_min, insert_min);
2903 if (insert_min == 0) {
2904 VLOG_INFO("EMC has been disabled");
2905 } else {
2906 VLOG_INFO("EMC insertion probability changed to 1/%llu (~%.2f%%)",
2907 insert_prob, (100 / (float)insert_prob));
2908 }
2909 }
2910
2911 return 0;
2912 }
2913
2914 /* Parses affinity list and returns result in 'core_ids'. */
2915 static int
2916 parse_affinity_list(const char *affinity_list, unsigned *core_ids, int n_rxq)
2917 {
2918 unsigned i;
2919 char *list, *copy, *key, *value;
2920 int error = 0;
2921
2922 for (i = 0; i < n_rxq; i++) {
2923 core_ids[i] = OVS_CORE_UNSPEC;
2924 }
2925
2926 if (!affinity_list) {
2927 return 0;
2928 }
2929
2930 list = copy = xstrdup(affinity_list);
2931
2932 while (ofputil_parse_key_value(&list, &key, &value)) {
2933 int rxq_id, core_id;
2934
2935 if (!str_to_int(key, 0, &rxq_id) || rxq_id < 0
2936 || !str_to_int(value, 0, &core_id) || core_id < 0) {
2937 error = EINVAL;
2938 break;
2939 }
2940
2941 if (rxq_id < n_rxq) {
2942 core_ids[rxq_id] = core_id;
2943 }
2944 }
2945
2946 free(copy);
2947 return error;
2948 }
2949
2950 /* Parses 'affinity_list' and applies configuration if it is valid. */
2951 static int
2952 dpif_netdev_port_set_rxq_affinity(struct dp_netdev_port *port,
2953 const char *affinity_list)
2954 {
2955 unsigned *core_ids, i;
2956 int error = 0;
2957
2958 core_ids = xmalloc(port->n_rxq * sizeof *core_ids);
2959 if (parse_affinity_list(affinity_list, core_ids, port->n_rxq)) {
2960 error = EINVAL;
2961 goto exit;
2962 }
2963
2964 for (i = 0; i < port->n_rxq; i++) {
2965 port->rxqs[i].core_id = core_ids[i];
2966 }
2967
2968 exit:
2969 free(core_ids);
2970 return error;
2971 }
2972
2973 /* Changes the affinity of port's rx queues. The changes are actually applied
2974 * in dpif_netdev_run(). */
2975 static int
2976 dpif_netdev_port_set_config(struct dpif *dpif, odp_port_t port_no,
2977 const struct smap *cfg)
2978 {
2979 struct dp_netdev *dp = get_dp_netdev(dpif);
2980 struct dp_netdev_port *port;
2981 int error = 0;
2982 const char *affinity_list = smap_get(cfg, "pmd-rxq-affinity");
2983
2984 ovs_mutex_lock(&dp->port_mutex);
2985 error = get_port_by_number(dp, port_no, &port);
2986 if (error || !netdev_is_pmd(port->netdev)
2987 || nullable_string_is_equal(affinity_list, port->rxq_affinity_list)) {
2988 goto unlock;
2989 }
2990
2991 error = dpif_netdev_port_set_rxq_affinity(port, affinity_list);
2992 if (error) {
2993 goto unlock;
2994 }
2995 free(port->rxq_affinity_list);
2996 port->rxq_affinity_list = nullable_xstrdup(affinity_list);
2997
2998 dp_netdev_request_reconfigure(dp);
2999 unlock:
3000 ovs_mutex_unlock(&dp->port_mutex);
3001 return error;
3002 }
3003
3004 static int
3005 dpif_netdev_queue_to_priority(const struct dpif *dpif OVS_UNUSED,
3006 uint32_t queue_id, uint32_t *priority)
3007 {
3008 *priority = queue_id;
3009 return 0;
3010 }
3011
3012 \f
3013 /* Creates and returns a new 'struct dp_netdev_actions', whose actions are
3014 * a copy of the 'size' bytes of 'actions' input parameters. */
3015 struct dp_netdev_actions *
3016 dp_netdev_actions_create(const struct nlattr *actions, size_t size)
3017 {
3018 struct dp_netdev_actions *netdev_actions;
3019
3020 netdev_actions = xmalloc(sizeof *netdev_actions + size);
3021 memcpy(netdev_actions->actions, actions, size);
3022 netdev_actions->size = size;
3023
3024 return netdev_actions;
3025 }
3026
3027 struct dp_netdev_actions *
3028 dp_netdev_flow_get_actions(const struct dp_netdev_flow *flow)
3029 {
3030 return ovsrcu_get(struct dp_netdev_actions *, &flow->actions);
3031 }
3032
3033 static void
3034 dp_netdev_actions_free(struct dp_netdev_actions *actions)
3035 {
3036 free(actions);
3037 }
3038 \f
3039 static inline unsigned long long
3040 cycles_counter(void)
3041 {
3042 #ifdef DPDK_NETDEV
3043 return rte_get_tsc_cycles();
3044 #else
3045 return 0;
3046 #endif
3047 }
3048
3049 /* Fake mutex to make sure that the calls to cycles_count_* are balanced */
3050 extern struct ovs_mutex cycles_counter_fake_mutex;
3051
3052 /* Start counting cycles. Must be followed by 'cycles_count_end()' */
3053 static inline void
3054 cycles_count_start(struct dp_netdev_pmd_thread *pmd)
3055 OVS_ACQUIRES(&cycles_counter_fake_mutex)
3056 OVS_NO_THREAD_SAFETY_ANALYSIS
3057 {
3058 pmd->last_cycles = cycles_counter();
3059 }
3060
3061 /* Stop counting cycles and add them to the counter 'type' */
3062 static inline void
3063 cycles_count_end(struct dp_netdev_pmd_thread *pmd,
3064 enum pmd_cycles_counter_type type)
3065 OVS_RELEASES(&cycles_counter_fake_mutex)
3066 OVS_NO_THREAD_SAFETY_ANALYSIS
3067 {
3068 unsigned long long interval = cycles_counter() - pmd->last_cycles;
3069
3070 non_atomic_ullong_add(&pmd->cycles.n[type], interval);
3071 }
3072
3073 /* Calculate the intermediate cycle result and add to the counter 'type' */
3074 static inline void
3075 cycles_count_intermediate(struct dp_netdev_pmd_thread *pmd,
3076 enum pmd_cycles_counter_type type)
3077 OVS_NO_THREAD_SAFETY_ANALYSIS
3078 {
3079 unsigned long long new_cycles = cycles_counter();
3080 unsigned long long interval = new_cycles - pmd->last_cycles;
3081 pmd->last_cycles = new_cycles;
3082
3083 non_atomic_ullong_add(&pmd->cycles.n[type], interval);
3084 }
3085
3086 static int
3087 dp_netdev_process_rxq_port(struct dp_netdev_pmd_thread *pmd,
3088 struct netdev_rxq *rx,
3089 odp_port_t port_no)
3090 {
3091 struct dp_packet_batch batch;
3092 int error;
3093 int batch_cnt = 0;
3094
3095 dp_packet_batch_init(&batch);
3096 error = netdev_rxq_recv(rx, &batch);
3097 if (!error) {
3098 *recirc_depth_get() = 0;
3099
3100 batch_cnt = batch.count;
3101 dp_netdev_input(pmd, &batch, port_no);
3102 } else if (error != EAGAIN && error != EOPNOTSUPP) {
3103 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3104
3105 VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
3106 netdev_rxq_get_name(rx), ovs_strerror(error));
3107 }
3108
3109 return batch_cnt;
3110 }
3111
3112 static struct tx_port *
3113 tx_port_lookup(const struct hmap *hmap, odp_port_t port_no)
3114 {
3115 struct tx_port *tx;
3116
3117 HMAP_FOR_EACH_IN_BUCKET (tx, node, hash_port_no(port_no), hmap) {
3118 if (tx->port->port_no == port_no) {
3119 return tx;
3120 }
3121 }
3122
3123 return NULL;
3124 }
3125
3126 static int
3127 port_reconfigure(struct dp_netdev_port *port)
3128 {
3129 struct netdev *netdev = port->netdev;
3130 int i, err;
3131
3132 port->need_reconfigure = false;
3133
3134 /* Closes the existing 'rxq's. */
3135 for (i = 0; i < port->n_rxq; i++) {
3136 netdev_rxq_close(port->rxqs[i].rx);
3137 port->rxqs[i].rx = NULL;
3138 }
3139 port->n_rxq = 0;
3140
3141 /* Allows 'netdev' to apply the pending configuration changes. */
3142 if (netdev_is_reconf_required(netdev)) {
3143 err = netdev_reconfigure(netdev);
3144 if (err && (err != EOPNOTSUPP)) {
3145 VLOG_ERR("Failed to set interface %s new configuration",
3146 netdev_get_name(netdev));
3147 return err;
3148 }
3149 }
3150 /* If the netdev_reconfigure() above succeeds, reopens the 'rxq's. */
3151 port->rxqs = xrealloc(port->rxqs,
3152 sizeof *port->rxqs * netdev_n_rxq(netdev));
3153 /* Realloc 'used' counters for tx queues. */
3154 free(port->txq_used);
3155 port->txq_used = xcalloc(netdev_n_txq(netdev), sizeof *port->txq_used);
3156
3157 for (i = 0; i < netdev_n_rxq(netdev); i++) {
3158 port->rxqs[i].port = port;
3159 err = netdev_rxq_open(netdev, &port->rxqs[i].rx, i);
3160 if (err) {
3161 return err;
3162 }
3163 port->n_rxq++;
3164 }
3165
3166 /* Parse affinity list to apply configuration for new queues. */
3167 dpif_netdev_port_set_rxq_affinity(port, port->rxq_affinity_list);
3168
3169 return 0;
3170 }
3171
3172 struct rr_numa_list {
3173 struct hmap numas; /* Contains 'struct rr_numa' */
3174 };
3175
3176 struct rr_numa {
3177 struct hmap_node node;
3178
3179 int numa_id;
3180
3181 /* Non isolated pmds on numa node 'numa_id' */
3182 struct dp_netdev_pmd_thread **pmds;
3183 int n_pmds;
3184
3185 int cur_index;
3186 };
3187
3188 static struct rr_numa *
3189 rr_numa_list_lookup(struct rr_numa_list *rr, int numa_id)
3190 {
3191 struct rr_numa *numa;
3192
3193 HMAP_FOR_EACH_WITH_HASH (numa, node, hash_int(numa_id, 0), &rr->numas) {
3194 if (numa->numa_id == numa_id) {
3195 return numa;
3196 }
3197 }
3198
3199 return NULL;
3200 }
3201
3202 static void
3203 rr_numa_list_populate(struct dp_netdev *dp, struct rr_numa_list *rr)
3204 {
3205 struct dp_netdev_pmd_thread *pmd;
3206 struct rr_numa *numa;
3207
3208 hmap_init(&rr->numas);
3209
3210 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3211 if (pmd->core_id == NON_PMD_CORE_ID || pmd->isolated) {
3212 continue;
3213 }
3214
3215 numa = rr_numa_list_lookup(rr, pmd->numa_id);
3216 if (!numa) {
3217 numa = xzalloc(sizeof *numa);
3218 numa->numa_id = pmd->numa_id;
3219 hmap_insert(&rr->numas, &numa->node, hash_int(pmd->numa_id, 0));
3220 }
3221 numa->n_pmds++;
3222 numa->pmds = xrealloc(numa->pmds, numa->n_pmds * sizeof *numa->pmds);
3223 numa->pmds[numa->n_pmds - 1] = pmd;
3224 }
3225 }
3226
3227 static struct dp_netdev_pmd_thread *
3228 rr_numa_get_pmd(struct rr_numa *numa)
3229 {
3230 return numa->pmds[numa->cur_index++ % numa->n_pmds];
3231 }
3232
3233 static void
3234 rr_numa_list_destroy(struct rr_numa_list *rr)
3235 {
3236 struct rr_numa *numa;
3237
3238 HMAP_FOR_EACH_POP (numa, node, &rr->numas) {
3239 free(numa->pmds);
3240 free(numa);
3241 }
3242 hmap_destroy(&rr->numas);
3243 }
3244
3245 /* Assign pmds to queues. If 'pinned' is true, assign pmds to pinned
3246 * queues and marks the pmds as isolated. Otherwise, assign non isolated
3247 * pmds to unpinned queues.
3248 *
3249 * The function doesn't touch the pmd threads, it just stores the assignment
3250 * in the 'pmd' member of each rxq. */
3251 static void
3252 rxq_scheduling(struct dp_netdev *dp, bool pinned) OVS_REQUIRES(dp->port_mutex)
3253 {
3254 struct dp_netdev_port *port;
3255 struct rr_numa_list rr;
3256
3257 rr_numa_list_populate(dp, &rr);
3258
3259 HMAP_FOR_EACH (port, node, &dp->ports) {
3260 struct rr_numa *numa;
3261 int numa_id;
3262
3263 if (!netdev_is_pmd(port->netdev)) {
3264 continue;
3265 }
3266
3267 numa_id = netdev_get_numa_id(port->netdev);
3268 numa = rr_numa_list_lookup(&rr, numa_id);
3269
3270 for (int qid = 0; qid < port->n_rxq; qid++) {
3271 struct dp_netdev_rxq *q = &port->rxqs[qid];
3272
3273 if (pinned && q->core_id != OVS_CORE_UNSPEC) {
3274 struct dp_netdev_pmd_thread *pmd;
3275
3276 pmd = dp_netdev_get_pmd(dp, q->core_id);
3277 if (!pmd) {
3278 VLOG_WARN("There is no PMD thread on core %d. Queue "
3279 "%d on port \'%s\' will not be polled.",
3280 q->core_id, qid, netdev_get_name(port->netdev));
3281 } else {
3282 q->pmd = pmd;
3283 pmd->isolated = true;
3284 dp_netdev_pmd_unref(pmd);
3285 }
3286 } else if (!pinned && q->core_id == OVS_CORE_UNSPEC) {
3287 if (!numa) {
3288 VLOG_WARN("There's no available (non isolated) pmd thread "
3289 "on numa node %d. Queue %d on port \'%s\' will "
3290 "not be polled.",
3291 numa_id, qid, netdev_get_name(port->netdev));
3292 } else {
3293 q->pmd = rr_numa_get_pmd(numa);
3294 }
3295 }
3296 }
3297 }
3298
3299 rr_numa_list_destroy(&rr);
3300 }
3301
3302 static void
3303 reconfigure_pmd_threads(struct dp_netdev *dp)
3304 OVS_REQUIRES(dp->port_mutex)
3305 {
3306 struct dp_netdev_pmd_thread *pmd;
3307 struct ovs_numa_dump *pmd_cores;
3308 bool changed = false;
3309
3310 /* The pmd threads should be started only if there's a pmd port in the
3311 * datapath. If the user didn't provide any "pmd-cpu-mask", we start
3312 * NR_PMD_THREADS per numa node. */
3313 if (!has_pmd_port(dp)) {
3314 pmd_cores = ovs_numa_dump_n_cores_per_numa(0);
3315 } else if (dp->pmd_cmask && dp->pmd_cmask[0]) {
3316 pmd_cores = ovs_numa_dump_cores_with_cmask(dp->pmd_cmask);
3317 } else {
3318 pmd_cores = ovs_numa_dump_n_cores_per_numa(NR_PMD_THREADS);
3319 }
3320
3321 /* Check for changed configuration */
3322 if (ovs_numa_dump_count(pmd_cores) != cmap_count(&dp->poll_threads) - 1) {
3323 changed = true;
3324 } else {
3325 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3326 if (pmd->core_id != NON_PMD_CORE_ID
3327 && !ovs_numa_dump_contains_core(pmd_cores,
3328 pmd->numa_id,
3329 pmd->core_id)) {
3330 changed = true;
3331 break;
3332 }
3333 }
3334 }
3335
3336 /* Destroy the old and recreate the new pmd threads. We don't perform an
3337 * incremental update because we would have to adjust 'static_tx_qid'. */
3338 if (changed) {
3339 struct ovs_numa_info_core *core;
3340 struct ovs_numa_info_numa *numa;
3341
3342 /* Do not destroy the non pmd thread. */
3343 dp_netdev_destroy_all_pmds(dp, false);
3344 FOR_EACH_CORE_ON_DUMP (core, pmd_cores) {
3345 struct dp_netdev_pmd_thread *pmd = xzalloc(sizeof *pmd);
3346
3347 dp_netdev_configure_pmd(pmd, dp, core->core_id, core->numa_id);
3348
3349 pmd->thread = ovs_thread_create("pmd", pmd_thread_main, pmd);
3350 }
3351
3352 /* Log the number of pmd threads per numa node. */
3353 FOR_EACH_NUMA_ON_DUMP (numa, pmd_cores) {
3354 VLOG_INFO("Created %"PRIuSIZE" pmd threads on numa node %d",
3355 numa->n_cores, numa->numa_id);
3356 }
3357 }
3358
3359 ovs_numa_dump_destroy(pmd_cores);
3360 }
3361
3362 static void
3363 reload_affected_pmds(struct dp_netdev *dp)
3364 {
3365 struct dp_netdev_pmd_thread *pmd;
3366
3367 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3368 if (pmd->need_reload) {
3369 dp_netdev_reload_pmd__(pmd);
3370 pmd->need_reload = false;
3371 }
3372 }
3373 }
3374
3375 static void
3376 pmd_remove_stale_ports(struct dp_netdev *dp,
3377 struct dp_netdev_pmd_thread *pmd)
3378 OVS_EXCLUDED(pmd->port_mutex)
3379 OVS_REQUIRES(dp->port_mutex)
3380 {
3381 struct rxq_poll *poll, *poll_next;
3382 struct tx_port *tx, *tx_next;
3383
3384 ovs_mutex_lock(&pmd->port_mutex);
3385 HMAP_FOR_EACH_SAFE (poll, poll_next, node, &pmd->poll_list) {
3386 struct dp_netdev_port *port = poll->rxq->port;
3387
3388 if (port->need_reconfigure
3389 || !hmap_contains(&dp->ports, &port->node)) {
3390 dp_netdev_del_rxq_from_pmd(pmd, poll);
3391 }
3392 }
3393 HMAP_FOR_EACH_SAFE (tx, tx_next, node, &pmd->tx_ports) {
3394 struct dp_netdev_port *port = tx->port;
3395
3396 if (port->need_reconfigure
3397 || !hmap_contains(&dp->ports, &port->node)) {
3398 dp_netdev_del_port_tx_from_pmd(pmd, tx);
3399 }
3400 }
3401 ovs_mutex_unlock(&pmd->port_mutex);
3402 }
3403
3404 /* Must be called each time a port is added/removed or the cmask changes.
3405 * This creates and destroys pmd threads, reconfigures ports, opens their
3406 * rxqs and assigns all rxqs/txqs to pmd threads. */
3407 static void
3408 reconfigure_datapath(struct dp_netdev *dp)
3409 OVS_REQUIRES(dp->port_mutex)
3410 {
3411 struct dp_netdev_pmd_thread *pmd;
3412 struct dp_netdev_port *port;
3413 int wanted_txqs;
3414
3415 dp->last_reconfigure_seq = seq_read(dp->reconfigure_seq);
3416
3417 /* Step 1: Adjust the pmd threads based on the datapath ports, the cores
3418 * on the system and the user configuration. */
3419 reconfigure_pmd_threads(dp);
3420
3421 wanted_txqs = cmap_count(&dp->poll_threads);
3422
3423 /* The number of pmd threads might have changed, or a port can be new:
3424 * adjust the txqs. */
3425 HMAP_FOR_EACH (port, node, &dp->ports) {
3426 netdev_set_tx_multiq(port->netdev, wanted_txqs);
3427 }
3428
3429 /* Step 2: Remove from the pmd threads ports that have been removed or
3430 * need reconfiguration. */
3431
3432 /* Check for all the ports that need reconfiguration. We cache this in
3433 * 'port->need_reconfigure', because netdev_is_reconf_required() can
3434 * change at any time. */
3435 HMAP_FOR_EACH (port, node, &dp->ports) {
3436 if (netdev_is_reconf_required(port->netdev)) {
3437 port->need_reconfigure = true;
3438 }
3439 }
3440
3441 /* Remove from the pmd threads all the ports that have been deleted or
3442 * need reconfiguration. */
3443 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3444 pmd_remove_stale_ports(dp, pmd);
3445 }
3446
3447 /* Reload affected pmd threads. We must wait for the pmd threads before
3448 * reconfiguring the ports, because a port cannot be reconfigured while
3449 * it's being used. */
3450 reload_affected_pmds(dp);
3451
3452 /* Step 3: Reconfigure ports. */
3453
3454 /* We only reconfigure the ports that we determined above, because they're
3455 * not being used by any pmd thread at the moment. If a port fails to
3456 * reconfigure we remove it from the datapath. */
3457 struct dp_netdev_port *next_port;
3458 HMAP_FOR_EACH_SAFE (port, next_port, node, &dp->ports) {
3459 int err;
3460
3461 if (!port->need_reconfigure) {
3462 continue;
3463 }
3464
3465 err = port_reconfigure(port);
3466 if (err) {
3467 hmap_remove(&dp->ports, &port->node);
3468 seq_change(dp->port_seq);
3469 port_destroy(port);
3470 } else {
3471 port->dynamic_txqs = netdev_n_txq(port->netdev) < wanted_txqs;
3472 }
3473 }
3474
3475 /* Step 4: Compute new rxq scheduling. We don't touch the pmd threads
3476 * for now, we just update the 'pmd' pointer in each rxq to point to the
3477 * wanted thread according to the scheduling policy. */
3478
3479 /* Reset all the pmd threads to non isolated. */
3480 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3481 pmd->isolated = false;
3482 }
3483
3484 /* Reset all the queues to unassigned */
3485 HMAP_FOR_EACH (port, node, &dp->ports) {
3486 for (int i = 0; i < port->n_rxq; i++) {
3487 port->rxqs[i].pmd = NULL;
3488 }
3489 }
3490
3491 /* Add pinned queues and mark pmd threads isolated. */
3492 rxq_scheduling(dp, true);
3493
3494 /* Add non-pinned queues. */
3495 rxq_scheduling(dp, false);
3496
3497 /* Step 5: Remove queues not compliant with new scheduling. */
3498 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3499 struct rxq_poll *poll, *poll_next;
3500
3501 ovs_mutex_lock(&pmd->port_mutex);
3502 HMAP_FOR_EACH_SAFE (poll, poll_next, node, &pmd->poll_list) {
3503 if (poll->rxq->pmd != pmd) {
3504 dp_netdev_del_rxq_from_pmd(pmd, poll);
3505 }
3506 }
3507 ovs_mutex_unlock(&pmd->port_mutex);
3508 }
3509
3510 /* Reload affected pmd threads. We must wait for the pmd threads to remove
3511 * the old queues before readding them, otherwise a queue can be polled by
3512 * two threads at the same time. */
3513 reload_affected_pmds(dp);
3514
3515 /* Step 6: Add queues from scheduling, if they're not there already. */
3516 HMAP_FOR_EACH (port, node, &dp->ports) {
3517 if (!netdev_is_pmd(port->netdev)) {
3518 continue;
3519 }
3520
3521 for (int qid = 0; qid < port->n_rxq; qid++) {
3522 struct dp_netdev_rxq *q = &port->rxqs[qid];
3523
3524 if (q->pmd) {
3525 ovs_mutex_lock(&q->pmd->port_mutex);
3526 dp_netdev_add_rxq_to_pmd(q->pmd, q);
3527 ovs_mutex_unlock(&q->pmd->port_mutex);
3528 }
3529 }
3530 }
3531
3532 /* Add every port to the tx cache of every pmd thread, if it's not
3533 * there already and if this pmd has at least one rxq to poll. */
3534 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
3535 ovs_mutex_lock(&pmd->port_mutex);
3536 if (hmap_count(&pmd->poll_list) || pmd->core_id == NON_PMD_CORE_ID) {
3537 HMAP_FOR_EACH (port, node, &dp->ports) {
3538 dp_netdev_add_port_tx_to_pmd(pmd, port);
3539 }
3540 }
3541 ovs_mutex_unlock(&pmd->port_mutex);
3542 }
3543
3544 /* Reload affected pmd threads. */
3545 reload_affected_pmds(dp);
3546 }
3547
3548 /* Returns true if one of the netdevs in 'dp' requires a reconfiguration */
3549 static bool
3550 ports_require_restart(const struct dp_netdev *dp)
3551 OVS_REQUIRES(dp->port_mutex)
3552 {
3553 struct dp_netdev_port *port;
3554
3555 HMAP_FOR_EACH (port, node, &dp->ports) {
3556 if (netdev_is_reconf_required(port->netdev)) {
3557 return true;
3558 }
3559 }
3560
3561 return false;
3562 }
3563
3564 /* Return true if needs to revalidate datapath flows. */
3565 static bool
3566 dpif_netdev_run(struct dpif *dpif)
3567 {
3568 struct dp_netdev_port *port;
3569 struct dp_netdev *dp = get_dp_netdev(dpif);
3570 struct dp_netdev_pmd_thread *non_pmd;
3571 uint64_t new_tnl_seq;
3572 int process_packets = 0;
3573
3574 ovs_mutex_lock(&dp->port_mutex);
3575 non_pmd = dp_netdev_get_pmd(dp, NON_PMD_CORE_ID);
3576 if (non_pmd) {
3577 ovs_mutex_lock(&dp->non_pmd_mutex);
3578 cycles_count_start(non_pmd);
3579 HMAP_FOR_EACH (port, node, &dp->ports) {
3580 if (!netdev_is_pmd(port->netdev)) {
3581 int i;
3582
3583 for (i = 0; i < port->n_rxq; i++) {
3584 process_packets =
3585 dp_netdev_process_rxq_port(non_pmd,
3586 port->rxqs[i].rx,
3587 port->port_no);
3588 cycles_count_intermediate(non_pmd, process_packets ?
3589 PMD_CYCLES_PROCESSING
3590 : PMD_CYCLES_IDLE);
3591 }
3592 }
3593 }
3594 cycles_count_end(non_pmd, PMD_CYCLES_IDLE);
3595 dpif_netdev_xps_revalidate_pmd(non_pmd, time_msec(), false);
3596 ovs_mutex_unlock(&dp->non_pmd_mutex);
3597
3598 dp_netdev_pmd_unref(non_pmd);
3599 }
3600
3601 if (dp_netdev_is_reconf_required(dp) || ports_require_restart(dp)) {
3602 reconfigure_datapath(dp);
3603 }
3604 ovs_mutex_unlock(&dp->port_mutex);
3605
3606 tnl_neigh_cache_run();
3607 tnl_port_map_run();
3608 new_tnl_seq = seq_read(tnl_conf_seq);
3609
3610 if (dp->last_tnl_conf_seq != new_tnl_seq) {
3611 dp->last_tnl_conf_seq = new_tnl_seq;
3612 return true;
3613 }
3614 return false;
3615 }
3616
3617 static void
3618 dpif_netdev_wait(struct dpif *dpif)
3619 {
3620 struct dp_netdev_port *port;
3621 struct dp_netdev *dp = get_dp_netdev(dpif);
3622
3623 ovs_mutex_lock(&dp_netdev_mutex);
3624 ovs_mutex_lock(&dp->port_mutex);
3625 HMAP_FOR_EACH (port, node, &dp->ports) {
3626 netdev_wait_reconf_required(port->netdev);
3627 if (!netdev_is_pmd(port->netdev)) {
3628 int i;
3629
3630 for (i = 0; i < port->n_rxq; i++) {
3631 netdev_rxq_wait(port->rxqs[i].rx);
3632 }
3633 }
3634 }
3635 ovs_mutex_unlock(&dp->port_mutex);
3636 ovs_mutex_unlock(&dp_netdev_mutex);
3637 seq_wait(tnl_conf_seq, dp->last_tnl_conf_seq);
3638 }
3639
3640 static void
3641 pmd_free_cached_ports(struct dp_netdev_pmd_thread *pmd)
3642 {
3643 struct tx_port *tx_port_cached;
3644
3645 /* Free all used tx queue ids. */
3646 dpif_netdev_xps_revalidate_pmd(pmd, 0, true);
3647
3648 HMAP_FOR_EACH_POP (tx_port_cached, node, &pmd->tnl_port_cache) {
3649 free(tx_port_cached);
3650 }
3651 HMAP_FOR_EACH_POP (tx_port_cached, node, &pmd->send_port_cache) {
3652 free(tx_port_cached);
3653 }
3654 }
3655
3656 /* Copies ports from 'pmd->tx_ports' (shared with the main thread) to
3657 * 'pmd->port_cache' (thread local) */
3658 static void
3659 pmd_load_cached_ports(struct dp_netdev_pmd_thread *pmd)
3660 OVS_REQUIRES(pmd->port_mutex)
3661 {
3662 struct tx_port *tx_port, *tx_port_cached;
3663
3664 pmd_free_cached_ports(pmd);
3665 hmap_shrink(&pmd->send_port_cache);
3666 hmap_shrink(&pmd->tnl_port_cache);
3667
3668 HMAP_FOR_EACH (tx_port, node, &pmd->tx_ports) {
3669 if (netdev_has_tunnel_push_pop(tx_port->port->netdev)) {
3670 tx_port_cached = xmemdup(tx_port, sizeof *tx_port_cached);
3671 hmap_insert(&pmd->tnl_port_cache, &tx_port_cached->node,
3672 hash_port_no(tx_port_cached->port->port_no));
3673 }
3674
3675 if (netdev_n_txq(tx_port->port->netdev)) {
3676 tx_port_cached = xmemdup(tx_port, sizeof *tx_port_cached);
3677 hmap_insert(&pmd->send_port_cache, &tx_port_cached->node,
3678 hash_port_no(tx_port_cached->port->port_no));
3679 }
3680 }
3681 }
3682
3683 static int
3684 pmd_load_queues_and_ports(struct dp_netdev_pmd_thread *pmd,
3685 struct polled_queue **ppoll_list)
3686 {
3687 struct polled_queue *poll_list = *ppoll_list;
3688 struct rxq_poll *poll;
3689 int i;
3690
3691 ovs_mutex_lock(&pmd->port_mutex);
3692 poll_list = xrealloc(poll_list, hmap_count(&pmd->poll_list)
3693 * sizeof *poll_list);
3694
3695 i = 0;
3696 HMAP_FOR_EACH (poll, node, &pmd->poll_list) {
3697 poll_list[i].rx = poll->rxq->rx;
3698 poll_list[i].port_no = poll->rxq->port->port_no;
3699 i++;
3700 }
3701
3702 pmd_load_cached_ports(pmd);
3703
3704 ovs_mutex_unlock(&pmd->port_mutex);
3705
3706 *ppoll_list = poll_list;
3707 return i;
3708 }
3709
3710 static void *
3711 pmd_thread_main(void *f_)
3712 {
3713 struct dp_netdev_pmd_thread *pmd = f_;
3714 unsigned int lc = 0;
3715 struct polled_queue *poll_list;
3716 bool exiting;
3717 int poll_cnt;
3718 int i;
3719 int process_packets = 0;
3720
3721 poll_list = NULL;
3722
3723 /* Stores the pmd thread's 'pmd' to 'per_pmd_key'. */
3724 ovsthread_setspecific(pmd->dp->per_pmd_key, pmd);
3725 ovs_numa_thread_setaffinity_core(pmd->core_id);
3726 dpdk_set_lcore_id(pmd->core_id);
3727 poll_cnt = pmd_load_queues_and_ports(pmd, &poll_list);
3728 reload:
3729 emc_cache_init(&pmd->flow_cache);
3730
3731 /* List port/core affinity */
3732 for (i = 0; i < poll_cnt; i++) {
3733 VLOG_DBG("Core %d processing port \'%s\' with queue-id %d\n",
3734 pmd->core_id, netdev_rxq_get_name(poll_list[i].rx),
3735 netdev_rxq_get_queue_id(poll_list[i].rx));
3736 }
3737
3738 if (!poll_cnt) {
3739 while (seq_read(pmd->reload_seq) == pmd->last_reload_seq) {
3740 seq_wait(pmd->reload_seq, pmd->last_reload_seq);
3741 poll_block();
3742 }
3743 lc = UINT_MAX;
3744 }
3745
3746 cycles_count_start(pmd);
3747 for (;;) {
3748 for (i = 0; i < poll_cnt; i++) {
3749 process_packets =
3750 dp_netdev_process_rxq_port(pmd, poll_list[i].rx,
3751 poll_list[i].port_no);
3752 cycles_count_intermediate(pmd,
3753 process_packets ? PMD_CYCLES_PROCESSING
3754 : PMD_CYCLES_IDLE);
3755 }
3756
3757 if (lc++ > 1024) {
3758 bool reload;
3759
3760 lc = 0;
3761
3762 coverage_try_clear();
3763 dp_netdev_pmd_try_optimize(pmd);
3764 if (!ovsrcu_try_quiesce()) {
3765 emc_cache_slow_sweep(&pmd->flow_cache);
3766 }
3767
3768 atomic_read_relaxed(&pmd->reload, &reload);
3769 if (reload) {
3770 break;
3771 }
3772 }
3773 }
3774
3775 cycles_count_end(pmd, PMD_CYCLES_IDLE);
3776
3777 poll_cnt = pmd_load_queues_and_ports(pmd, &poll_list);
3778 exiting = latch_is_set(&pmd->exit_latch);
3779 /* Signal here to make sure the pmd finishes
3780 * reloading the updated configuration. */
3781 dp_netdev_pmd_reload_done(pmd);
3782
3783 emc_cache_uninit(&pmd->flow_cache);
3784
3785 if (!exiting) {
3786 goto reload;
3787 }
3788
3789 free(poll_list);
3790 pmd_free_cached_ports(pmd);
3791 return NULL;
3792 }
3793
3794 static void
3795 dp_netdev_disable_upcall(struct dp_netdev *dp)
3796 OVS_ACQUIRES(dp->upcall_rwlock)
3797 {
3798 fat_rwlock_wrlock(&dp->upcall_rwlock);
3799 }
3800
3801 \f
3802 /* Meters */
3803 static void
3804 dpif_netdev_meter_get_features(const struct dpif * dpif OVS_UNUSED,
3805 struct ofputil_meter_features *features)
3806 {
3807 features->max_meters = MAX_METERS;
3808 features->band_types = DP_SUPPORTED_METER_BAND_TYPES;
3809 features->capabilities = DP_SUPPORTED_METER_FLAGS_MASK;
3810 features->max_bands = MAX_BANDS;
3811 features->max_color = 0;
3812 }
3813
3814 /* Returns false when packet needs to be dropped. */
3815 static void
3816 dp_netdev_run_meter(struct dp_netdev *dp, struct dp_packet_batch *packets_,
3817 uint32_t meter_id, long long int now)
3818 {
3819 struct dp_meter *meter;
3820 struct dp_meter_band *band;
3821 long long int long_delta_t; /* msec */
3822 uint32_t delta_t; /* msec */
3823 int i;
3824 int cnt = packets_->count;
3825 uint32_t bytes, volume;
3826 int exceeded_band[NETDEV_MAX_BURST];
3827 uint32_t exceeded_rate[NETDEV_MAX_BURST];
3828 int exceeded_pkt = cnt; /* First packet that exceeded a band rate. */
3829
3830 if (meter_id >= MAX_METERS) {
3831 return;
3832 }
3833
3834 meter_lock(dp, meter_id);
3835 meter = dp->meters[meter_id];
3836 if (!meter) {
3837 goto out;
3838 }
3839
3840 /* Initialize as negative values. */
3841 memset(exceeded_band, 0xff, cnt * sizeof *exceeded_band);
3842 /* Initialize as zeroes. */
3843 memset(exceeded_rate, 0, cnt * sizeof *exceeded_rate);
3844
3845 /* All packets will hit the meter at the same time. */
3846 long_delta_t = (now - meter->used); /* msec */
3847
3848 /* Make sure delta_t will not be too large, so that bucket will not
3849 * wrap around below. */
3850 delta_t = (long_delta_t > (long long int)meter->max_delta_t)
3851 ? meter->max_delta_t : (uint32_t)long_delta_t;
3852
3853 /* Update meter stats. */
3854 meter->used = now;
3855 meter->packet_count += cnt;
3856 bytes = 0;
3857 for (i = 0; i < cnt; i++) {
3858 bytes += dp_packet_size(packets_->packets[i]);
3859 }
3860 meter->byte_count += bytes;
3861
3862 /* Meters can operate in terms of packets per second or kilobits per
3863 * second. */
3864 if (meter->flags & OFPMF13_PKTPS) {
3865 /* Rate in packets/second, bucket 1/1000 packets. */
3866 /* msec * packets/sec = 1/1000 packets. */
3867 volume = cnt * 1000; /* Take 'cnt' packets from the bucket. */
3868 } else {
3869 /* Rate in kbps, bucket in bits. */
3870 /* msec * kbps = bits */
3871 volume = bytes * 8;
3872 }
3873
3874 /* Update all bands and find the one hit with the highest rate for each
3875 * packet (if any). */
3876 for (int m = 0; m < meter->n_bands; ++m) {
3877 band = &meter->bands[m];
3878
3879 /* Update band's bucket. */
3880 band->bucket += delta_t * band->up.rate;
3881 if (band->bucket > band->up.burst_size) {
3882 band->bucket = band->up.burst_size;
3883 }
3884
3885 /* Drain the bucket for all the packets, if possible. */
3886 if (band->bucket >= volume) {
3887 band->bucket -= volume;
3888 } else {
3889 int band_exceeded_pkt;
3890
3891 /* Band limit hit, must process packet-by-packet. */
3892 if (meter->flags & OFPMF13_PKTPS) {
3893 band_exceeded_pkt = band->bucket / 1000;
3894 band->bucket %= 1000; /* Remainder stays in bucket. */
3895
3896 /* Update the exceeding band for each exceeding packet.
3897 * (Only one band will be fired by a packet, and that
3898 * can be different for each packet.) */
3899 for (i = band_exceeded_pkt; i < cnt; i++) {
3900 if (band->up.rate > exceeded_rate[i]) {
3901 exceeded_rate[i] = band->up.rate;
3902 exceeded_band[i] = m;
3903 }
3904 }
3905 } else {
3906 /* Packet sizes differ, must process one-by-one. */
3907 band_exceeded_pkt = cnt;
3908 for (i = 0; i < cnt; i++) {
3909 uint32_t bits = dp_packet_size(packets_->packets[i]) * 8;
3910
3911 if (band->bucket >= bits) {
3912 band->bucket -= bits;
3913 } else {
3914 if (i < band_exceeded_pkt) {
3915 band_exceeded_pkt = i;
3916 }
3917 /* Update the exceeding band for the exceeding packet.
3918 * (Only one band will be fired by a packet, and that
3919 * can be different for each packet.) */
3920 if (band->up.rate > exceeded_rate[i]) {
3921 exceeded_rate[i] = band->up.rate;
3922 exceeded_band[i] = m;
3923 }
3924 }
3925 }
3926 }
3927 /* Remember the first exceeding packet. */
3928 if (exceeded_pkt > band_exceeded_pkt) {
3929 exceeded_pkt = band_exceeded_pkt;
3930 }
3931 }
3932 }
3933
3934 /* Fire the highest rate band exceeded by each packet.
3935 * Drop packets if needed, by swapping packet to the end that will be
3936 * ignored. */
3937 const size_t size = dp_packet_batch_size(packets_);
3938 struct dp_packet *packet;
3939 size_t j;
3940 DP_PACKET_BATCH_REFILL_FOR_EACH (j, size, packet, packets_) {
3941 if (exceeded_band[j] >= 0) {
3942 /* Meter drop packet. */
3943 band = &meter->bands[exceeded_band[j]];
3944 band->packet_count += 1;
3945 band->byte_count += dp_packet_size(packet);
3946
3947 dp_packet_delete(packet);
3948 } else {
3949 /* Meter accepts packet. */
3950 dp_packet_batch_refill(packets_, packet, j);
3951 }
3952 }
3953 out:
3954 meter_unlock(dp, meter_id);
3955 }
3956
3957 /* Meter set/get/del processing is still single-threaded. */
3958 static int
3959 dpif_netdev_meter_set(struct dpif *dpif, ofproto_meter_id *meter_id,
3960 struct ofputil_meter_config *config)
3961 {
3962 struct dp_netdev *dp = get_dp_netdev(dpif);
3963 uint32_t mid = meter_id->uint32;
3964 struct dp_meter *meter;
3965 int i;
3966
3967 if (mid >= MAX_METERS) {
3968 return EFBIG; /* Meter_id out of range. */
3969 }
3970
3971 if (config->flags & ~DP_SUPPORTED_METER_FLAGS_MASK ||
3972 !(config->flags & (OFPMF13_KBPS | OFPMF13_PKTPS))) {
3973 return EBADF; /* Unsupported flags set */
3974 }
3975 /* Validate bands */
3976 if (config->n_bands == 0 || config->n_bands > MAX_BANDS) {
3977 return EINVAL; /* Too many bands */
3978 }
3979 for (i = 0; i < config->n_bands; ++i) {
3980 switch (config->bands[i].type) {
3981 case OFPMBT13_DROP:
3982 break;
3983 default:
3984 return ENODEV; /* Unsupported band type */
3985 }
3986 }
3987
3988 /* Allocate meter */
3989 meter = xzalloc(sizeof *meter
3990 + config->n_bands * sizeof(struct dp_meter_band));
3991 if (meter) {
3992 meter->flags = config->flags;
3993 meter->n_bands = config->n_bands;
3994 meter->max_delta_t = 0;
3995 meter->used = time_msec();
3996
3997 /* set up bands */
3998 for (i = 0; i < config->n_bands; ++i) {
3999 uint32_t band_max_delta_t;
4000
4001 /* Set burst size to a workable value if none specified. */
4002 if (config->bands[i].burst_size == 0) {
4003 config->bands[i].burst_size = config->bands[i].rate;
4004 }
4005
4006 meter->bands[i].up = config->bands[i];
4007 /* Convert burst size to the bucket units: */
4008 /* pkts => 1/1000 packets, kilobits => bits. */
4009 meter->bands[i].up.burst_size *= 1000;
4010 /* Initialize bucket to empty. */
4011 meter->bands[i].bucket = 0;
4012
4013 /* Figure out max delta_t that is enough to fill any bucket. */
4014 band_max_delta_t
4015 = meter->bands[i].up.burst_size / meter->bands[i].up.rate;
4016 if (band_max_delta_t > meter->max_delta_t) {
4017 meter->max_delta_t = band_max_delta_t;
4018 }
4019 }
4020
4021 meter_lock(dp, mid);
4022 dp_delete_meter(dp, mid); /* Free existing meter, if any */
4023 dp->meters[mid] = meter;
4024 meter_unlock(dp, mid);
4025
4026 return 0;
4027 }
4028 return ENOMEM;
4029 }
4030
4031 static int
4032 dpif_netdev_meter_get(const struct dpif *dpif,
4033 ofproto_meter_id meter_id_,
4034 struct ofputil_meter_stats *stats, uint16_t n_bands)
4035 {
4036 const struct dp_netdev *dp = get_dp_netdev(dpif);
4037 const struct dp_meter *meter;
4038 uint32_t meter_id = meter_id_.uint32;
4039
4040 if (meter_id >= MAX_METERS) {
4041 return EFBIG;
4042 }
4043 meter = dp->meters[meter_id];
4044 if (!meter) {
4045 return ENOENT;
4046 }
4047 if (stats) {
4048 int i = 0;
4049
4050 meter_lock(dp, meter_id);
4051 stats->packet_in_count = meter->packet_count;
4052 stats->byte_in_count = meter->byte_count;
4053
4054 for (i = 0; i < n_bands && i < meter->n_bands; ++i) {
4055 stats->bands[i].packet_count = meter->bands[i].packet_count;
4056 stats->bands[i].byte_count = meter->bands[i].byte_count;
4057 }
4058 meter_unlock(dp, meter_id);
4059
4060 stats->n_bands = i;
4061 }
4062 return 0;
4063 }
4064
4065 static int
4066 dpif_netdev_meter_del(struct dpif *dpif,
4067 ofproto_meter_id meter_id_,
4068 struct ofputil_meter_stats *stats, uint16_t n_bands)
4069 {
4070 struct dp_netdev *dp = get_dp_netdev(dpif);
4071 int error;
4072
4073 error = dpif_netdev_meter_get(dpif, meter_id_, stats, n_bands);
4074 if (!error) {
4075 uint32_t meter_id = meter_id_.uint32;
4076
4077 meter_lock(dp, meter_id);
4078 dp_delete_meter(dp, meter_id);
4079 meter_unlock(dp, meter_id);
4080 }
4081 return error;
4082 }
4083
4084 \f
4085 static void
4086 dpif_netdev_disable_upcall(struct dpif *dpif)
4087 OVS_NO_THREAD_SAFETY_ANALYSIS
4088 {
4089 struct dp_netdev *dp = get_dp_netdev(dpif);
4090 dp_netdev_disable_upcall(dp);
4091 }
4092
4093 static void
4094 dp_netdev_enable_upcall(struct dp_netdev *dp)
4095 OVS_RELEASES(dp->upcall_rwlock)
4096 {
4097 fat_rwlock_unlock(&dp->upcall_rwlock);
4098 }
4099
4100 static void
4101 dpif_netdev_enable_upcall(struct dpif *dpif)
4102 OVS_NO_THREAD_SAFETY_ANALYSIS
4103 {
4104 struct dp_netdev *dp = get_dp_netdev(dpif);
4105 dp_netdev_enable_upcall(dp);
4106 }
4107
4108 static void
4109 dp_netdev_pmd_reload_done(struct dp_netdev_pmd_thread *pmd)
4110 {
4111 ovs_mutex_lock(&pmd->cond_mutex);
4112 atomic_store_relaxed(&pmd->reload, false);
4113 pmd->last_reload_seq = seq_read(pmd->reload_seq);
4114 xpthread_cond_signal(&pmd->cond);
4115 ovs_mutex_unlock(&pmd->cond_mutex);
4116 }
4117
4118 /* Finds and refs the dp_netdev_pmd_thread on core 'core_id'. Returns
4119 * the pointer if succeeds, otherwise, NULL (it can return NULL even if
4120 * 'core_id' is NON_PMD_CORE_ID).
4121 *
4122 * Caller must unrefs the returned reference. */
4123 static struct dp_netdev_pmd_thread *
4124 dp_netdev_get_pmd(struct dp_netdev *dp, unsigned core_id)
4125 {
4126 struct dp_netdev_pmd_thread *pmd;
4127 const struct cmap_node *pnode;
4128
4129 pnode = cmap_find(&dp->poll_threads, hash_int(core_id, 0));
4130 if (!pnode) {
4131 return NULL;
4132 }
4133 pmd = CONTAINER_OF(pnode, struct dp_netdev_pmd_thread, node);
4134
4135 return dp_netdev_pmd_try_ref(pmd) ? pmd : NULL;
4136 }
4137
4138 /* Sets the 'struct dp_netdev_pmd_thread' for non-pmd threads. */
4139 static void
4140 dp_netdev_set_nonpmd(struct dp_netdev *dp)
4141 OVS_REQUIRES(dp->port_mutex)
4142 {
4143 struct dp_netdev_pmd_thread *non_pmd;
4144
4145 non_pmd = xzalloc(sizeof *non_pmd);
4146 dp_netdev_configure_pmd(non_pmd, dp, NON_PMD_CORE_ID, OVS_NUMA_UNSPEC);
4147 }
4148
4149 /* Caller must have valid pointer to 'pmd'. */
4150 static bool
4151 dp_netdev_pmd_try_ref(struct dp_netdev_pmd_thread *pmd)
4152 {
4153 return ovs_refcount_try_ref_rcu(&pmd->ref_cnt);
4154 }
4155
4156 static void
4157 dp_netdev_pmd_unref(struct dp_netdev_pmd_thread *pmd)
4158 {
4159 if (pmd && ovs_refcount_unref(&pmd->ref_cnt) == 1) {
4160 ovsrcu_postpone(dp_netdev_destroy_pmd, pmd);
4161 }
4162 }
4163
4164 /* Given cmap position 'pos', tries to ref the next node. If try_ref()
4165 * fails, keeps checking for next node until reaching the end of cmap.
4166 *
4167 * Caller must unrefs the returned reference. */
4168 static struct dp_netdev_pmd_thread *
4169 dp_netdev_pmd_get_next(struct dp_netdev *dp, struct cmap_position *pos)
4170 {
4171 struct dp_netdev_pmd_thread *next;
4172
4173 do {
4174 struct cmap_node *node;
4175
4176 node = cmap_next_position(&dp->poll_threads, pos);
4177 next = node ? CONTAINER_OF(node, struct dp_netdev_pmd_thread, node)
4178 : NULL;
4179 } while (next && !dp_netdev_pmd_try_ref(next));
4180
4181 return next;
4182 }
4183
4184 /* Configures the 'pmd' based on the input argument. */
4185 static void
4186 dp_netdev_configure_pmd(struct dp_netdev_pmd_thread *pmd, struct dp_netdev *dp,
4187 unsigned core_id, int numa_id)
4188 {
4189 pmd->dp = dp;
4190 pmd->core_id = core_id;
4191 pmd->numa_id = numa_id;
4192 pmd->need_reload = false;
4193
4194 *CONST_CAST(int *, &pmd->static_tx_qid) = cmap_count(&dp->poll_threads);
4195
4196 ovs_refcount_init(&pmd->ref_cnt);
4197 latch_init(&pmd->exit_latch);
4198 pmd->reload_seq = seq_create();
4199 pmd->last_reload_seq = seq_read(pmd->reload_seq);
4200 atomic_init(&pmd->reload, false);
4201 xpthread_cond_init(&pmd->cond, NULL);
4202 ovs_mutex_init(&pmd->cond_mutex);
4203 ovs_mutex_init(&pmd->flow_mutex);
4204 ovs_mutex_init(&pmd->port_mutex);
4205 cmap_init(&pmd->flow_table);
4206 cmap_init(&pmd->classifiers);
4207 pmd->next_optimization = time_msec() + DPCLS_OPTIMIZATION_INTERVAL;
4208 hmap_init(&pmd->poll_list);
4209 hmap_init(&pmd->tx_ports);
4210 hmap_init(&pmd->tnl_port_cache);
4211 hmap_init(&pmd->send_port_cache);
4212 /* init the 'flow_cache' since there is no
4213 * actual thread created for NON_PMD_CORE_ID. */
4214 if (core_id == NON_PMD_CORE_ID) {
4215 emc_cache_init(&pmd->flow_cache);
4216 }
4217 cmap_insert(&dp->poll_threads, CONST_CAST(struct cmap_node *, &pmd->node),
4218 hash_int(core_id, 0));
4219 }
4220
4221 static void
4222 dp_netdev_destroy_pmd(struct dp_netdev_pmd_thread *pmd)
4223 {
4224 struct dpcls *cls;
4225
4226 dp_netdev_pmd_flow_flush(pmd);
4227 hmap_destroy(&pmd->send_port_cache);
4228 hmap_destroy(&pmd->tnl_port_cache);
4229 hmap_destroy(&pmd->tx_ports);
4230 hmap_destroy(&pmd->poll_list);
4231 /* All flows (including their dpcls_rules) have been deleted already */
4232 CMAP_FOR_EACH (cls, node, &pmd->classifiers) {
4233 dpcls_destroy(cls);
4234 ovsrcu_postpone(free, cls);
4235 }
4236 cmap_destroy(&pmd->classifiers);
4237 cmap_destroy(&pmd->flow_table);
4238 ovs_mutex_destroy(&pmd->flow_mutex);
4239 latch_destroy(&pmd->exit_latch);
4240 seq_destroy(pmd->reload_seq);
4241 xpthread_cond_destroy(&pmd->cond);
4242 ovs_mutex_destroy(&pmd->cond_mutex);
4243 ovs_mutex_destroy(&pmd->port_mutex);
4244 free(pmd);
4245 }
4246
4247 /* Stops the pmd thread, removes it from the 'dp->poll_threads',
4248 * and unrefs the struct. */
4249 static void
4250 dp_netdev_del_pmd(struct dp_netdev *dp, struct dp_netdev_pmd_thread *pmd)
4251 {
4252 /* NON_PMD_CORE_ID doesn't have a thread, so we don't have to synchronize,
4253 * but extra cleanup is necessary */
4254 if (pmd->core_id == NON_PMD_CORE_ID) {
4255 ovs_mutex_lock(&dp->non_pmd_mutex);
4256 emc_cache_uninit(&pmd->flow_cache);
4257 pmd_free_cached_ports(pmd);
4258 ovs_mutex_unlock(&dp->non_pmd_mutex);
4259 } else {
4260 latch_set(&pmd->exit_latch);
4261 dp_netdev_reload_pmd__(pmd);
4262 xpthread_join(pmd->thread, NULL);
4263 }
4264
4265 dp_netdev_pmd_clear_ports(pmd);
4266
4267 /* Purges the 'pmd''s flows after stopping the thread, but before
4268 * destroying the flows, so that the flow stats can be collected. */
4269 if (dp->dp_purge_cb) {
4270 dp->dp_purge_cb(dp->dp_purge_aux, pmd->core_id);
4271 }
4272 cmap_remove(&pmd->dp->poll_threads, &pmd->node, hash_int(pmd->core_id, 0));
4273 dp_netdev_pmd_unref(pmd);
4274 }
4275
4276 /* Destroys all pmd threads. If 'non_pmd' is true it also destroys the non pmd
4277 * thread. */
4278 static void
4279 dp_netdev_destroy_all_pmds(struct dp_netdev *dp, bool non_pmd)
4280 {
4281 struct dp_netdev_pmd_thread *pmd;
4282 struct dp_netdev_pmd_thread **pmd_list;
4283 size_t k = 0, n_pmds;
4284
4285 n_pmds = cmap_count(&dp->poll_threads);
4286 pmd_list = xcalloc(n_pmds, sizeof *pmd_list);
4287
4288 CMAP_FOR_EACH (pmd, node, &dp->poll_threads) {
4289 if (!non_pmd && pmd->core_id == NON_PMD_CORE_ID) {
4290 continue;
4291 }
4292 /* We cannot call dp_netdev_del_pmd(), since it alters
4293 * 'dp->poll_threads' (while we're iterating it) and it
4294 * might quiesce. */
4295 ovs_assert(k < n_pmds);
4296 pmd_list[k++] = pmd;
4297 }
4298
4299 for (size_t i = 0; i < k; i++) {
4300 dp_netdev_del_pmd(dp, pmd_list[i]);
4301 }
4302 free(pmd_list);
4303 }
4304
4305 /* Deletes all rx queues from pmd->poll_list and all the ports from
4306 * pmd->tx_ports. */
4307 static void
4308 dp_netdev_pmd_clear_ports(struct dp_netdev_pmd_thread *pmd)
4309 {
4310 struct rxq_poll *poll;
4311 struct tx_port *port;
4312
4313 ovs_mutex_lock(&pmd->port_mutex);
4314 HMAP_FOR_EACH_POP (poll, node, &pmd->poll_list) {
4315 free(poll);
4316 }
4317 HMAP_FOR_EACH_POP (port, node, &pmd->tx_ports) {
4318 free(port);
4319 }
4320 ovs_mutex_unlock(&pmd->port_mutex);
4321 }
4322
4323 /* Adds rx queue to poll_list of PMD thread, if it's not there already. */
4324 static void
4325 dp_netdev_add_rxq_to_pmd(struct dp_netdev_pmd_thread *pmd,
4326 struct dp_netdev_rxq *rxq)
4327 OVS_REQUIRES(pmd->port_mutex)
4328 {
4329 int qid = netdev_rxq_get_queue_id(rxq->rx);
4330 uint32_t hash = hash_2words(odp_to_u32(rxq->port->port_no), qid);
4331 struct rxq_poll *poll;
4332
4333 HMAP_FOR_EACH_WITH_HASH (poll, node, hash, &pmd->poll_list) {
4334 if (poll->rxq == rxq) {
4335 /* 'rxq' is already polled by this thread. Do nothing. */
4336 return;
4337 }
4338 }
4339
4340 poll = xmalloc(sizeof *poll);
4341 poll->rxq = rxq;
4342 hmap_insert(&pmd->poll_list, &poll->node, hash);
4343
4344 pmd->need_reload = true;
4345 }
4346
4347 /* Delete 'poll' from poll_list of PMD thread. */
4348 static void
4349 dp_netdev_del_rxq_from_pmd(struct dp_netdev_pmd_thread *pmd,
4350 struct rxq_poll *poll)
4351 OVS_REQUIRES(pmd->port_mutex)
4352 {
4353 hmap_remove(&pmd->poll_list, &poll->node);
4354 free(poll);
4355
4356 pmd->need_reload = true;
4357 }
4358
4359 /* Add 'port' to the tx port cache of 'pmd', which must be reloaded for the
4360 * changes to take effect. */
4361 static void
4362 dp_netdev_add_port_tx_to_pmd(struct dp_netdev_pmd_thread *pmd,
4363 struct dp_netdev_port *port)
4364 OVS_REQUIRES(pmd->port_mutex)
4365 {
4366 struct tx_port *tx;
4367
4368 tx = tx_port_lookup(&pmd->tx_ports, port->port_no);
4369 if (tx) {
4370 /* 'port' is already on this thread tx cache. Do nothing. */
4371 return;
4372 }
4373
4374 tx = xzalloc(sizeof *tx);
4375
4376 tx->port = port;
4377 tx->qid = -1;
4378
4379 hmap_insert(&pmd->tx_ports, &tx->node, hash_port_no(tx->port->port_no));
4380 pmd->need_reload = true;
4381 }
4382
4383 /* Del 'tx' from the tx port cache of 'pmd', which must be reloaded for the
4384 * changes to take effect. */
4385 static void
4386 dp_netdev_del_port_tx_from_pmd(struct dp_netdev_pmd_thread *pmd,
4387 struct tx_port *tx)
4388 OVS_REQUIRES(pmd->port_mutex)
4389 {
4390 hmap_remove(&pmd->tx_ports, &tx->node);
4391 free(tx);
4392 pmd->need_reload = true;
4393 }
4394 \f
4395 static char *
4396 dpif_netdev_get_datapath_version(void)
4397 {
4398 return xstrdup("<built-in>");
4399 }
4400
4401 static void
4402 dp_netdev_flow_used(struct dp_netdev_flow *netdev_flow, int cnt, int size,
4403 uint16_t tcp_flags, long long now)
4404 {
4405 uint16_t flags;
4406
4407 atomic_store_relaxed(&netdev_flow->stats.used, now);
4408 non_atomic_ullong_add(&netdev_flow->stats.packet_count, cnt);
4409 non_atomic_ullong_add(&netdev_flow->stats.byte_count, size);
4410 atomic_read_relaxed(&netdev_flow->stats.tcp_flags, &flags);
4411 flags |= tcp_flags;
4412 atomic_store_relaxed(&netdev_flow->stats.tcp_flags, flags);
4413 }
4414
4415 static void
4416 dp_netdev_count_packet(struct dp_netdev_pmd_thread *pmd,
4417 enum dp_stat_type type, int cnt)
4418 {
4419 non_atomic_ullong_add(&pmd->stats.n[type], cnt);
4420 }
4421
4422 static int
4423 dp_netdev_upcall(struct dp_netdev_pmd_thread *pmd, struct dp_packet *packet_,
4424 struct flow *flow, struct flow_wildcards *wc, ovs_u128 *ufid,
4425 enum dpif_upcall_type type, const struct nlattr *userdata,
4426 struct ofpbuf *actions, struct ofpbuf *put_actions)
4427 {
4428 struct dp_netdev *dp = pmd->dp;
4429
4430 if (OVS_UNLIKELY(!dp->upcall_cb)) {
4431 return ENODEV;
4432 }
4433
4434 if (OVS_UNLIKELY(!VLOG_DROP_DBG(&upcall_rl))) {
4435 struct ds ds = DS_EMPTY_INITIALIZER;
4436 char *packet_str;
4437 struct ofpbuf key;
4438 struct odp_flow_key_parms odp_parms = {
4439 .flow = flow,
4440 .mask = wc ? &wc->masks : NULL,
4441 .support = dp_netdev_support,
4442 };
4443
4444 ofpbuf_init(&key, 0);
4445 odp_flow_key_from_flow(&odp_parms, &key);
4446 packet_str = ofp_dp_packet_to_string(packet_);
4447
4448 odp_flow_key_format(key.data, key.size, &ds);
4449
4450 VLOG_DBG("%s: %s upcall:\n%s\n%s", dp->name,
4451 dpif_upcall_type_to_string(type), ds_cstr(&ds), packet_str);
4452
4453 ofpbuf_uninit(&key);
4454 free(packet_str);
4455
4456 ds_destroy(&ds);
4457 }
4458
4459 return dp->upcall_cb(packet_, flow, ufid, pmd->core_id, type, userdata,
4460 actions, wc, put_actions, dp->upcall_aux);
4461 }
4462
4463 static inline uint32_t
4464 dpif_netdev_packet_get_rss_hash(struct dp_packet *packet,
4465 const struct miniflow *mf)
4466 {
4467 uint32_t hash, recirc_depth;
4468
4469 if (OVS_LIKELY(dp_packet_rss_valid(packet))) {
4470 hash = dp_packet_get_rss_hash(packet);
4471 } else {
4472 hash = miniflow_hash_5tuple(mf, 0);
4473 dp_packet_set_rss_hash(packet, hash);
4474 }
4475
4476 /* The RSS hash must account for the recirculation depth to avoid
4477 * collisions in the exact match cache */
4478 recirc_depth = *recirc_depth_get_unsafe();
4479 if (OVS_UNLIKELY(recirc_depth)) {
4480 hash = hash_finish(hash, recirc_depth);
4481 dp_packet_set_rss_hash(packet, hash);
4482 }
4483 return hash;
4484 }
4485
4486 struct packet_batch_per_flow {
4487 unsigned int byte_count;
4488 uint16_t tcp_flags;
4489 struct dp_netdev_flow *flow;
4490
4491 struct dp_packet_batch array;
4492 };
4493
4494 static inline void
4495 packet_batch_per_flow_update(struct packet_batch_per_flow *batch,
4496 struct dp_packet *packet,
4497 const struct miniflow *mf)
4498 {
4499 batch->byte_count += dp_packet_size(packet);
4500 batch->tcp_flags |= miniflow_get_tcp_flags(mf);
4501 batch->array.packets[batch->array.count++] = packet;
4502 }
4503
4504 static inline void
4505 packet_batch_per_flow_init(struct packet_batch_per_flow *batch,
4506 struct dp_netdev_flow *flow)
4507 {
4508 flow->batch = batch;
4509
4510 batch->flow = flow;
4511 dp_packet_batch_init(&batch->array);
4512 batch->byte_count = 0;
4513 batch->tcp_flags = 0;
4514 }
4515
4516 static inline void
4517 packet_batch_per_flow_execute(struct packet_batch_per_flow *batch,
4518 struct dp_netdev_pmd_thread *pmd,
4519 long long now)
4520 {
4521 struct dp_netdev_actions *actions;
4522 struct dp_netdev_flow *flow = batch->flow;
4523
4524 dp_netdev_flow_used(flow, batch->array.count, batch->byte_count,
4525 batch->tcp_flags, now);
4526
4527 actions = dp_netdev_flow_get_actions(flow);
4528
4529 dp_netdev_execute_actions(pmd, &batch->array, true, &flow->flow,
4530 actions->actions, actions->size, now);
4531 }
4532
4533 static inline void
4534 dp_netdev_queue_batches(struct dp_packet *pkt,
4535 struct dp_netdev_flow *flow, const struct miniflow *mf,
4536 struct packet_batch_per_flow *batches,
4537 size_t *n_batches)
4538 {
4539 struct packet_batch_per_flow *batch = flow->batch;
4540
4541 if (OVS_UNLIKELY(!batch)) {
4542 batch = &batches[(*n_batches)++];
4543 packet_batch_per_flow_init(batch, flow);
4544 }
4545
4546 packet_batch_per_flow_update(batch, pkt, mf);
4547 }
4548
4549 /* Try to process all ('cnt') the 'packets' using only the exact match cache
4550 * 'pmd->flow_cache'. If a flow is not found for a packet 'packets[i]', the
4551 * miniflow is copied into 'keys' and the packet pointer is moved at the
4552 * beginning of the 'packets' array.
4553 *
4554 * The function returns the number of packets that needs to be processed in the
4555 * 'packets' array (they have been moved to the beginning of the vector).
4556 *
4557 * If 'md_is_valid' is false, the metadata in 'packets' is not valid and must
4558 * be initialized by this function using 'port_no'.
4559 */
4560 static inline size_t
4561 emc_processing(struct dp_netdev_pmd_thread *pmd,
4562 struct dp_packet_batch *packets_,
4563 struct netdev_flow_key *keys,
4564 struct packet_batch_per_flow batches[], size_t *n_batches,
4565 bool md_is_valid, odp_port_t port_no)
4566 {
4567 struct emc_cache *flow_cache = &pmd->flow_cache;
4568 struct netdev_flow_key *key = &keys[0];
4569 size_t n_missed = 0, n_dropped = 0;
4570 struct dp_packet *packet;
4571 const size_t size = dp_packet_batch_size(packets_);
4572 uint32_t cur_min;
4573 int i;
4574
4575 atomic_read_relaxed(&pmd->dp->emc_insert_min, &cur_min);
4576
4577 DP_PACKET_BATCH_REFILL_FOR_EACH (i, size, packet, packets_) {
4578 struct dp_netdev_flow *flow;
4579
4580 if (OVS_UNLIKELY(dp_packet_size(packet) < ETH_HEADER_LEN)) {
4581 dp_packet_delete(packet);
4582 n_dropped++;
4583 continue;
4584 }
4585
4586 if (i != size - 1) {
4587 struct dp_packet **packets = packets_->packets;
4588 /* Prefetch next packet data and metadata. */
4589 OVS_PREFETCH(dp_packet_data(packets[i+1]));
4590 pkt_metadata_prefetch_init(&packets[i+1]->md);
4591 }
4592
4593 if (!md_is_valid) {
4594 pkt_metadata_init(&packet->md, port_no);
4595 }
4596 miniflow_extract(packet, &key->mf);
4597 key->len = 0; /* Not computed yet. */
4598 key->hash = dpif_netdev_packet_get_rss_hash(packet, &key->mf);
4599
4600 /* If EMC is disabled skip emc_lookup */
4601 flow = (cur_min == 0) ? NULL: emc_lookup(flow_cache, key);
4602 if (OVS_LIKELY(flow)) {
4603 dp_netdev_queue_batches(packet, flow, &key->mf, batches,
4604 n_batches);
4605 } else {
4606 /* Exact match cache missed. Group missed packets together at
4607 * the beginning of the 'packets' array. */
4608 dp_packet_batch_refill(packets_, packet, i);
4609 /* 'key[n_missed]' contains the key of the current packet and it
4610 * must be returned to the caller. The next key should be extracted
4611 * to 'keys[n_missed + 1]'. */
4612 key = &keys[++n_missed];
4613 }
4614 }
4615
4616 dp_netdev_count_packet(pmd, DP_STAT_EXACT_HIT,
4617 size - n_dropped - n_missed);
4618
4619 return dp_packet_batch_size(packets_);
4620 }
4621
4622 static inline void
4623 handle_packet_upcall(struct dp_netdev_pmd_thread *pmd,
4624 struct dp_packet *packet,
4625 const struct netdev_flow_key *key,
4626 struct ofpbuf *actions, struct ofpbuf *put_actions,
4627 int *lost_cnt, long long now)
4628 {
4629 struct ofpbuf *add_actions;
4630 struct dp_packet_batch b;
4631 struct match match;
4632 ovs_u128 ufid;
4633 int error;
4634
4635 match.tun_md.valid = false;
4636 miniflow_expand(&key->mf, &match.flow);
4637
4638 ofpbuf_clear(actions);
4639 ofpbuf_clear(put_actions);
4640
4641 dpif_flow_hash(pmd->dp->dpif, &match.flow, sizeof match.flow, &ufid);
4642 error = dp_netdev_upcall(pmd, packet, &match.flow, &match.wc,
4643 &ufid, DPIF_UC_MISS, NULL, actions,
4644 put_actions);
4645 if (OVS_UNLIKELY(error && error != ENOSPC)) {
4646 dp_packet_delete(packet);
4647 (*lost_cnt)++;
4648 return;
4649 }
4650
4651 /* The Netlink encoding of datapath flow keys cannot express
4652 * wildcarding the presence of a VLAN tag. Instead, a missing VLAN
4653 * tag is interpreted as exact match on the fact that there is no
4654 * VLAN. Unless we refactor a lot of code that translates between
4655 * Netlink and struct flow representations, we have to do the same
4656 * here. */
4657 if (!match.wc.masks.vlans[0].tci) {
4658 match.wc.masks.vlans[0].tci = htons(0xffff);
4659 }
4660
4661 /* We can't allow the packet batching in the next loop to execute
4662 * the actions. Otherwise, if there are any slow path actions,
4663 * we'll send the packet up twice. */
4664 dp_packet_batch_init_packet(&b, packet);
4665 dp_netdev_execute_actions(pmd, &b, true, &match.flow,
4666 actions->data, actions->size, now);
4667
4668 add_actions = put_actions->size ? put_actions : actions;
4669 if (OVS_LIKELY(error != ENOSPC)) {
4670 struct dp_netdev_flow *netdev_flow;
4671
4672 /* XXX: There's a race window where a flow covering this packet
4673 * could have already been installed since we last did the flow
4674 * lookup before upcall. This could be solved by moving the
4675 * mutex lock outside the loop, but that's an awful long time
4676 * to be locking everyone out of making flow installs. If we
4677 * move to a per-core classifier, it would be reasonable. */
4678 ovs_mutex_lock(&pmd->flow_mutex);
4679 netdev_flow = dp_netdev_pmd_lookup_flow(pmd, key, NULL);
4680 if (OVS_LIKELY(!netdev_flow)) {
4681 netdev_flow = dp_netdev_flow_add(pmd, &match, &ufid,
4682 add_actions->data,
4683 add_actions->size);
4684 }
4685 ovs_mutex_unlock(&pmd->flow_mutex);
4686 emc_probabilistic_insert(pmd, key, netdev_flow);
4687 }
4688 }
4689
4690 static inline void
4691 fast_path_processing(struct dp_netdev_pmd_thread *pmd,
4692 struct dp_packet_batch *packets_,
4693 struct netdev_flow_key *keys,
4694 struct packet_batch_per_flow batches[], size_t *n_batches,
4695 odp_port_t in_port,
4696 long long now)
4697 {
4698 int cnt = packets_->count;
4699 #if !defined(__CHECKER__) && !defined(_WIN32)
4700 const size_t PKT_ARRAY_SIZE = cnt;
4701 #else
4702 /* Sparse or MSVC doesn't like variable length array. */
4703 enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
4704 #endif
4705 struct dp_packet **packets = packets_->packets;
4706 struct dpcls *cls;
4707 struct dpcls_rule *rules[PKT_ARRAY_SIZE];
4708 struct dp_netdev *dp = pmd->dp;
4709 int miss_cnt = 0, lost_cnt = 0;
4710 int lookup_cnt = 0, add_lookup_cnt;
4711 bool any_miss;
4712 size_t i;
4713
4714 for (i = 0; i < cnt; i++) {
4715 /* Key length is needed in all the cases, hash computed on demand. */
4716 keys[i].len = netdev_flow_key_size(miniflow_n_values(&keys[i].mf));
4717 }
4718 /* Get the classifier for the in_port */
4719 cls = dp_netdev_pmd_lookup_dpcls(pmd, in_port);
4720 if (OVS_LIKELY(cls)) {
4721 any_miss = !dpcls_lookup(cls, keys, rules, cnt, &lookup_cnt);
4722 } else {
4723 any_miss = true;
4724 memset(rules, 0, sizeof(rules));
4725 }
4726 if (OVS_UNLIKELY(any_miss) && !fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
4727 uint64_t actions_stub[512 / 8], slow_stub[512 / 8];
4728 struct ofpbuf actions, put_actions;
4729
4730 ofpbuf_use_stub(&actions, actions_stub, sizeof actions_stub);
4731 ofpbuf_use_stub(&put_actions, slow_stub, sizeof slow_stub);
4732
4733 for (i = 0; i < cnt; i++) {
4734 struct dp_netdev_flow *netdev_flow;
4735
4736 if (OVS_LIKELY(rules[i])) {
4737 continue;
4738 }
4739
4740 /* It's possible that an earlier slow path execution installed
4741 * a rule covering this flow. In this case, it's a lot cheaper
4742 * to catch it here than execute a miss. */
4743 netdev_flow = dp_netdev_pmd_lookup_flow(pmd, &keys[i],
4744 &add_lookup_cnt);
4745 if (netdev_flow) {
4746 lookup_cnt += add_lookup_cnt;
4747 rules[i] = &netdev_flow->cr;
4748 continue;
4749 }
4750
4751 miss_cnt++;
4752 handle_packet_upcall(pmd, packets[i], &keys[i], &actions,
4753 &put_actions, &lost_cnt, now);
4754 }
4755
4756 ofpbuf_uninit(&actions);
4757 ofpbuf_uninit(&put_actions);
4758 fat_rwlock_unlock(&dp->upcall_rwlock);
4759 } else if (OVS_UNLIKELY(any_miss)) {
4760 for (i = 0; i < cnt; i++) {
4761 if (OVS_UNLIKELY(!rules[i])) {
4762 dp_packet_delete(packets[i]);
4763 lost_cnt++;
4764 miss_cnt++;
4765 }
4766 }
4767 }
4768
4769 for (i = 0; i < cnt; i++) {
4770 struct dp_packet *packet = packets[i];
4771 struct dp_netdev_flow *flow;
4772
4773 if (OVS_UNLIKELY(!rules[i])) {
4774 continue;
4775 }
4776
4777 flow = dp_netdev_flow_cast(rules[i]);
4778
4779 emc_probabilistic_insert(pmd, &keys[i], flow);
4780 dp_netdev_queue_batches(packet, flow, &keys[i].mf, batches, n_batches);
4781 }
4782
4783 dp_netdev_count_packet(pmd, DP_STAT_MASKED_HIT, cnt - miss_cnt);
4784 dp_netdev_count_packet(pmd, DP_STAT_LOOKUP_HIT, lookup_cnt);
4785 dp_netdev_count_packet(pmd, DP_STAT_MISS, miss_cnt);
4786 dp_netdev_count_packet(pmd, DP_STAT_LOST, lost_cnt);
4787 }
4788
4789 /* Packets enter the datapath from a port (or from recirculation) here.
4790 *
4791 * For performance reasons a caller may choose not to initialize the metadata
4792 * in 'packets': in this case 'mdinit' is false and this function needs to
4793 * initialize it using 'port_no'. If the metadata in 'packets' is already
4794 * valid, 'md_is_valid' must be true and 'port_no' will be ignored. */
4795 static void
4796 dp_netdev_input__(struct dp_netdev_pmd_thread *pmd,
4797 struct dp_packet_batch *packets,
4798 bool md_is_valid, odp_port_t port_no)
4799 {
4800 int cnt = packets->count;
4801 #if !defined(__CHECKER__) && !defined(_WIN32)
4802 const size_t PKT_ARRAY_SIZE = cnt;
4803 #else
4804 /* Sparse or MSVC doesn't like variable length array. */
4805 enum { PKT_ARRAY_SIZE = NETDEV_MAX_BURST };
4806 #endif
4807 OVS_ALIGNED_VAR(CACHE_LINE_SIZE)
4808 struct netdev_flow_key keys[PKT_ARRAY_SIZE];
4809 struct packet_batch_per_flow batches[PKT_ARRAY_SIZE];
4810 long long now = time_msec();
4811 size_t n_batches;
4812 odp_port_t in_port;
4813
4814 n_batches = 0;
4815 emc_processing(pmd, packets, keys, batches, &n_batches,
4816 md_is_valid, port_no);
4817 if (!dp_packet_batch_is_empty(packets)) {
4818 /* Get ingress port from first packet's metadata. */
4819 in_port = packets->packets[0]->md.in_port.odp_port;
4820 fast_path_processing(pmd, packets, keys, batches, &n_batches,
4821 in_port, now);
4822 }
4823
4824 /* All the flow batches need to be reset before any call to
4825 * packet_batch_per_flow_execute() as it could potentially trigger
4826 * recirculation. When a packet matching flow ‘j’ happens to be
4827 * recirculated, the nested call to dp_netdev_input__() could potentially
4828 * classify the packet as matching another flow - say 'k'. It could happen
4829 * that in the previous call to dp_netdev_input__() that same flow 'k' had
4830 * already its own batches[k] still waiting to be served. So if its
4831 * ‘batch’ member is not reset, the recirculated packet would be wrongly
4832 * appended to batches[k] of the 1st call to dp_netdev_input__(). */
4833 size_t i;
4834 for (i = 0; i < n_batches; i++) {
4835 batches[i].flow->batch = NULL;
4836 }
4837
4838 for (i = 0; i < n_batches; i++) {
4839 packet_batch_per_flow_execute(&batches[i], pmd, now);
4840 }
4841 }
4842
4843 static void
4844 dp_netdev_input(struct dp_netdev_pmd_thread *pmd,
4845 struct dp_packet_batch *packets,
4846 odp_port_t port_no)
4847 {
4848 dp_netdev_input__(pmd, packets, false, port_no);
4849 }
4850
4851 static void
4852 dp_netdev_recirculate(struct dp_netdev_pmd_thread *pmd,
4853 struct dp_packet_batch *packets)
4854 {
4855 dp_netdev_input__(pmd, packets, true, 0);
4856 }
4857
4858 struct dp_netdev_execute_aux {
4859 struct dp_netdev_pmd_thread *pmd;
4860 long long now;
4861 const struct flow *flow;
4862 };
4863
4864 static void
4865 dpif_netdev_register_dp_purge_cb(struct dpif *dpif, dp_purge_callback *cb,
4866 void *aux)
4867 {
4868 struct dp_netdev *dp = get_dp_netdev(dpif);
4869 dp->dp_purge_aux = aux;
4870 dp->dp_purge_cb = cb;
4871 }
4872
4873 static void
4874 dpif_netdev_register_upcall_cb(struct dpif *dpif, upcall_callback *cb,
4875 void *aux)
4876 {
4877 struct dp_netdev *dp = get_dp_netdev(dpif);
4878 dp->upcall_aux = aux;
4879 dp->upcall_cb = cb;
4880 }
4881
4882 static void
4883 dpif_netdev_xps_revalidate_pmd(const struct dp_netdev_pmd_thread *pmd,
4884 long long now, bool purge)
4885 {
4886 struct tx_port *tx;
4887 struct dp_netdev_port *port;
4888 long long interval;
4889
4890 HMAP_FOR_EACH (tx, node, &pmd->send_port_cache) {
4891 if (!tx->port->dynamic_txqs) {
4892 continue;
4893 }
4894 interval = now - tx->last_used;
4895 if (tx->qid >= 0 && (purge || interval >= XPS_TIMEOUT_MS)) {
4896 port = tx->port;
4897 ovs_mutex_lock(&port->txq_used_mutex);
4898 port->txq_used[tx->qid]--;
4899 ovs_mutex_unlock(&port->txq_used_mutex);
4900 tx->qid = -1;
4901 }
4902 }
4903 }
4904
4905 static int
4906 dpif_netdev_xps_get_tx_qid(const struct dp_netdev_pmd_thread *pmd,
4907 struct tx_port *tx, long long now)
4908 {
4909 struct dp_netdev_port *port;
4910 long long interval;
4911 int i, min_cnt, min_qid;
4912
4913 if (OVS_UNLIKELY(!now)) {
4914 now = time_msec();
4915 }
4916
4917 interval = now - tx->last_used;
4918 tx->last_used = now;
4919
4920 if (OVS_LIKELY(tx->qid >= 0 && interval < XPS_TIMEOUT_MS)) {
4921 return tx->qid;
4922 }
4923
4924 port = tx->port;
4925
4926 ovs_mutex_lock(&port->txq_used_mutex);
4927 if (tx->qid >= 0) {
4928 port->txq_used[tx->qid]--;
4929 tx->qid = -1;
4930 }
4931
4932 min_cnt = -1;
4933 min_qid = 0;
4934 for (i = 0; i < netdev_n_txq(port->netdev); i++) {
4935 if (port->txq_used[i] < min_cnt || min_cnt == -1) {
4936 min_cnt = port->txq_used[i];
4937 min_qid = i;
4938 }
4939 }
4940
4941 port->txq_used[min_qid]++;
4942 tx->qid = min_qid;
4943
4944 ovs_mutex_unlock(&port->txq_used_mutex);
4945
4946 dpif_netdev_xps_revalidate_pmd(pmd, now, false);
4947
4948 VLOG_DBG("Core %d: New TX queue ID %d for port \'%s\'.",
4949 pmd->core_id, tx->qid, netdev_get_name(tx->port->netdev));
4950 return min_qid;
4951 }
4952
4953 static struct tx_port *
4954 pmd_tnl_port_cache_lookup(const struct dp_netdev_pmd_thread *pmd,
4955 odp_port_t port_no)
4956 {
4957 return tx_port_lookup(&pmd->tnl_port_cache, port_no);
4958 }
4959
4960 static struct tx_port *
4961 pmd_send_port_cache_lookup(const struct dp_netdev_pmd_thread *pmd,
4962 odp_port_t port_no)
4963 {
4964 return tx_port_lookup(&pmd->send_port_cache, port_no);
4965 }
4966
4967 static int
4968 push_tnl_action(const struct dp_netdev_pmd_thread *pmd,
4969 const struct nlattr *attr,
4970 struct dp_packet_batch *batch)
4971 {
4972 struct tx_port *tun_port;
4973 const struct ovs_action_push_tnl *data;
4974 int err;
4975
4976 data = nl_attr_get(attr);
4977
4978 tun_port = pmd_tnl_port_cache_lookup(pmd, data->tnl_port);
4979 if (!tun_port) {
4980 err = -EINVAL;
4981 goto error;
4982 }
4983 err = netdev_push_header(tun_port->port->netdev, batch, data);
4984 if (!err) {
4985 return 0;
4986 }
4987 error:
4988 dp_packet_delete_batch(batch, true);
4989 return err;
4990 }
4991
4992 static void
4993 dp_execute_userspace_action(struct dp_netdev_pmd_thread *pmd,
4994 struct dp_packet *packet, bool may_steal,
4995 struct flow *flow, ovs_u128 *ufid,
4996 struct ofpbuf *actions,
4997 const struct nlattr *userdata, long long now)
4998 {
4999 struct dp_packet_batch b;
5000 int error;
5001
5002 ofpbuf_clear(actions);
5003
5004 error = dp_netdev_upcall(pmd, packet, flow, NULL, ufid,
5005 DPIF_UC_ACTION, userdata, actions,
5006 NULL);
5007 if (!error || error == ENOSPC) {
5008 dp_packet_batch_init_packet(&b, packet);
5009 dp_netdev_execute_actions(pmd, &b, may_steal, flow,
5010 actions->data, actions->size, now);
5011 } else if (may_steal) {
5012 dp_packet_delete(packet);
5013 }
5014 }
5015
5016 static void
5017 dp_execute_cb(void *aux_, struct dp_packet_batch *packets_,
5018 const struct nlattr *a, bool may_steal)
5019 OVS_NO_THREAD_SAFETY_ANALYSIS
5020 {
5021 struct dp_netdev_execute_aux *aux = aux_;
5022 uint32_t *depth = recirc_depth_get();
5023 struct dp_netdev_pmd_thread *pmd = aux->pmd;
5024 struct dp_netdev *dp = pmd->dp;
5025 int type = nl_attr_type(a);
5026 long long now = aux->now;
5027 struct tx_port *p;
5028
5029 switch ((enum ovs_action_attr)type) {
5030 case OVS_ACTION_ATTR_OUTPUT:
5031 p = pmd_send_port_cache_lookup(pmd, nl_attr_get_odp_port(a));
5032 if (OVS_LIKELY(p)) {
5033 int tx_qid;
5034 bool dynamic_txqs;
5035
5036 dynamic_txqs = p->port->dynamic_txqs;
5037 if (dynamic_txqs) {
5038 tx_qid = dpif_netdev_xps_get_tx_qid(pmd, p, now);
5039 } else {
5040 tx_qid = pmd->static_tx_qid;
5041 }
5042
5043 netdev_send(p->port->netdev, tx_qid, packets_, may_steal,
5044 dynamic_txqs);
5045 return;
5046 }
5047 break;
5048
5049 case OVS_ACTION_ATTR_TUNNEL_PUSH:
5050 if (*depth < MAX_RECIRC_DEPTH) {
5051 struct dp_packet_batch tnl_pkt;
5052 struct dp_packet_batch *orig_packets_ = packets_;
5053 int err;
5054
5055 if (!may_steal) {
5056 dp_packet_batch_clone(&tnl_pkt, packets_);
5057 packets_ = &tnl_pkt;
5058 dp_packet_batch_reset_cutlen(orig_packets_);
5059 }
5060
5061 dp_packet_batch_apply_cutlen(packets_);
5062
5063 err = push_tnl_action(pmd, a, packets_);
5064 if (!err) {
5065 (*depth)++;
5066 dp_netdev_recirculate(pmd, packets_);
5067 (*depth)--;
5068 }
5069 return;
5070 }
5071 break;
5072
5073 case OVS_ACTION_ATTR_TUNNEL_POP:
5074 if (*depth < MAX_RECIRC_DEPTH) {
5075 struct dp_packet_batch *orig_packets_ = packets_;
5076 odp_port_t portno = nl_attr_get_odp_port(a);
5077
5078 p = pmd_tnl_port_cache_lookup(pmd, portno);
5079 if (p) {
5080 struct dp_packet_batch tnl_pkt;
5081
5082 if (!may_steal) {
5083 dp_packet_batch_clone(&tnl_pkt, packets_);
5084 packets_ = &tnl_pkt;
5085 dp_packet_batch_reset_cutlen(orig_packets_);
5086 }
5087
5088 dp_packet_batch_apply_cutlen(packets_);
5089
5090 netdev_pop_header(p->port->netdev, packets_);
5091 if (dp_packet_batch_is_empty(packets_)) {
5092 return;
5093 }
5094
5095 struct dp_packet *packet;
5096 DP_PACKET_BATCH_FOR_EACH (packet, packets_) {
5097 packet->md.in_port.odp_port = portno;
5098 }
5099
5100 (*depth)++;
5101 dp_netdev_recirculate(pmd, packets_);
5102 (*depth)--;
5103 return;
5104 }
5105 }
5106 break;
5107
5108 case OVS_ACTION_ATTR_USERSPACE:
5109 if (!fat_rwlock_tryrdlock(&dp->upcall_rwlock)) {
5110 struct dp_packet_batch *orig_packets_ = packets_;
5111 const struct nlattr *userdata;
5112 struct dp_packet_batch usr_pkt;
5113 struct ofpbuf actions;
5114 struct flow flow;
5115 ovs_u128 ufid;
5116 bool clone = false;
5117
5118 userdata = nl_attr_find_nested(a, OVS_USERSPACE_ATTR_USERDATA);
5119 ofpbuf_init(&actions, 0);
5120
5121 if (packets_->trunc) {
5122 if (!may_steal) {
5123 dp_packet_batch_clone(&usr_pkt, packets_);
5124 packets_ = &usr_pkt;
5125 clone = true;
5126 dp_packet_batch_reset_cutlen(orig_packets_);
5127 }
5128
5129 dp_packet_batch_apply_cutlen(packets_);
5130 }
5131
5132 struct dp_packet *packet;
5133 DP_PACKET_BATCH_FOR_EACH (packet, packets_) {
5134 flow_extract(packet, &flow);
5135 dpif_flow_hash(dp->dpif, &flow, sizeof flow, &ufid);
5136 dp_execute_userspace_action(pmd, packet, may_steal, &flow,
5137 &ufid, &actions, userdata, now);
5138 }
5139
5140 if (clone) {
5141 dp_packet_delete_batch(packets_, true);
5142 }
5143
5144 ofpbuf_uninit(&actions);
5145 fat_rwlock_unlock(&dp->upcall_rwlock);
5146
5147 return;
5148 }
5149 break;
5150
5151 case OVS_ACTION_ATTR_RECIRC:
5152 if (*depth < MAX_RECIRC_DEPTH) {
5153 struct dp_packet_batch recirc_pkts;
5154
5155 if (!may_steal) {
5156 dp_packet_batch_clone(&recirc_pkts, packets_);
5157 packets_ = &recirc_pkts;
5158 }
5159
5160 struct dp_packet *packet;
5161 DP_PACKET_BATCH_FOR_EACH (packet, packets_) {
5162 packet->md.recirc_id = nl_attr_get_u32(a);
5163 }
5164
5165 (*depth)++;
5166 dp_netdev_recirculate(pmd, packets_);
5167 (*depth)--;
5168
5169 return;
5170 }
5171
5172 VLOG_WARN("Packet dropped. Max recirculation depth exceeded.");
5173 break;
5174
5175 case OVS_ACTION_ATTR_CT: {
5176 const struct nlattr *b;
5177 bool force = false;
5178 bool commit = false;
5179 unsigned int left;
5180 uint16_t zone = 0;
5181 const char *helper = NULL;
5182 const uint32_t *setmark = NULL;
5183 const struct ovs_key_ct_labels *setlabel = NULL;
5184 struct nat_action_info_t nat_action_info;
5185 struct nat_action_info_t *nat_action_info_ref = NULL;
5186 bool nat_config = false;
5187
5188 NL_ATTR_FOR_EACH_UNSAFE (b, left, nl_attr_get(a),
5189 nl_attr_get_size(a)) {
5190 enum ovs_ct_attr sub_type = nl_attr_type(b);
5191
5192 switch(sub_type) {
5193 case OVS_CT_ATTR_FORCE_COMMIT:
5194 force = true;
5195 /* fall through. */
5196 case OVS_CT_ATTR_COMMIT:
5197 commit = true;
5198 break;
5199 case OVS_CT_ATTR_ZONE:
5200 zone = nl_attr_get_u16(b);
5201 break;
5202 case OVS_CT_ATTR_HELPER:
5203 helper = nl_attr_get_string(b);
5204 break;
5205 case OVS_CT_ATTR_MARK:
5206 setmark = nl_attr_get(b);
5207 break;
5208 case OVS_CT_ATTR_LABELS:
5209 setlabel = nl_attr_get(b);
5210 break;
5211 case OVS_CT_ATTR_EVENTMASK:
5212 /* Silently ignored, as userspace datapath does not generate
5213 * netlink events. */
5214 break;
5215 case OVS_CT_ATTR_NAT: {
5216 const struct nlattr *b_nest;
5217 unsigned int left_nest;
5218 bool ip_min_specified = false;
5219 bool proto_num_min_specified = false;
5220 bool ip_max_specified = false;
5221 bool proto_num_max_specified = false;
5222 memset(&nat_action_info, 0, sizeof nat_action_info);
5223 nat_action_info_ref = &nat_action_info;
5224
5225 NL_NESTED_FOR_EACH_UNSAFE (b_nest, left_nest, b) {
5226 enum ovs_nat_attr sub_type_nest = nl_attr_type(b_nest);
5227
5228 switch (sub_type_nest) {
5229 case OVS_NAT_ATTR_SRC:
5230 case OVS_NAT_ATTR_DST:
5231 nat_config = true;
5232 nat_action_info.nat_action |=
5233 ((sub_type_nest == OVS_NAT_ATTR_SRC)
5234 ? NAT_ACTION_SRC : NAT_ACTION_DST);
5235 break;
5236 case OVS_NAT_ATTR_IP_MIN:
5237 memcpy(&nat_action_info.min_addr,
5238 nl_attr_get(b_nest),
5239 nl_attr_get_size(b_nest));
5240 ip_min_specified = true;
5241 break;
5242 case OVS_NAT_ATTR_IP_MAX:
5243 memcpy(&nat_action_info.max_addr,
5244 nl_attr_get(b_nest),
5245 nl_attr_get_size(b_nest));
5246 ip_max_specified = true;
5247 break;
5248 case OVS_NAT_ATTR_PROTO_MIN:
5249 nat_action_info.min_port =
5250 nl_attr_get_u16(b_nest);
5251 proto_num_min_specified = true;
5252 break;
5253 case OVS_NAT_ATTR_PROTO_MAX:
5254 nat_action_info.max_port =
5255 nl_attr_get_u16(b_nest);
5256 proto_num_max_specified = true;
5257 break;
5258 case OVS_NAT_ATTR_PERSISTENT:
5259 case OVS_NAT_ATTR_PROTO_HASH:
5260 case OVS_NAT_ATTR_PROTO_RANDOM:
5261 break;
5262 case OVS_NAT_ATTR_UNSPEC:
5263 case __OVS_NAT_ATTR_MAX:
5264 OVS_NOT_REACHED();
5265 }
5266 }
5267
5268 if (ip_min_specified && !ip_max_specified) {
5269 nat_action_info.max_addr = nat_action_info.min_addr;
5270 }
5271 if (proto_num_min_specified && !proto_num_max_specified) {
5272 nat_action_info.max_port = nat_action_info.min_port;
5273 }
5274 if (proto_num_min_specified || proto_num_max_specified) {
5275 if (nat_action_info.nat_action & NAT_ACTION_SRC) {
5276 nat_action_info.nat_action |= NAT_ACTION_SRC_PORT;
5277 } else if (nat_action_info.nat_action & NAT_ACTION_DST) {
5278 nat_action_info.nat_action |= NAT_ACTION_DST_PORT;
5279 }
5280 }
5281 break;
5282 }
5283 case OVS_CT_ATTR_UNSPEC:
5284 case __OVS_CT_ATTR_MAX:
5285 OVS_NOT_REACHED();
5286 }
5287 }
5288
5289 /* We won't be able to function properly in this case, hence
5290 * complain loudly. */
5291 if (nat_config && !commit) {
5292 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 5);
5293 VLOG_WARN_RL(&rl, "NAT specified without commit.");
5294 }
5295
5296 conntrack_execute(&dp->conntrack, packets_, aux->flow->dl_type, force,
5297 commit, zone, setmark, setlabel, helper,
5298 nat_action_info_ref);
5299 break;
5300 }
5301
5302 case OVS_ACTION_ATTR_METER:
5303 dp_netdev_run_meter(pmd->dp, packets_, nl_attr_get_u32(a),
5304 time_msec());
5305 break;
5306
5307 case OVS_ACTION_ATTR_PUSH_VLAN:
5308 case OVS_ACTION_ATTR_POP_VLAN:
5309 case OVS_ACTION_ATTR_PUSH_MPLS:
5310 case OVS_ACTION_ATTR_POP_MPLS:
5311 case OVS_ACTION_ATTR_SET:
5312 case OVS_ACTION_ATTR_SET_MASKED:
5313 case OVS_ACTION_ATTR_SAMPLE:
5314 case OVS_ACTION_ATTR_HASH:
5315 case OVS_ACTION_ATTR_UNSPEC:
5316 case OVS_ACTION_ATTR_TRUNC:
5317 case OVS_ACTION_ATTR_PUSH_ETH:
5318 case OVS_ACTION_ATTR_POP_ETH:
5319 case OVS_ACTION_ATTR_CLONE:
5320 case __OVS_ACTION_ATTR_MAX:
5321 OVS_NOT_REACHED();
5322 }
5323
5324 dp_packet_delete_batch(packets_, may_steal);
5325 }
5326
5327 static void
5328 dp_netdev_execute_actions(struct dp_netdev_pmd_thread *pmd,
5329 struct dp_packet_batch *packets,
5330 bool may_steal, const struct flow *flow,
5331 const struct nlattr *actions, size_t actions_len,
5332 long long now)
5333 {
5334 struct dp_netdev_execute_aux aux = { pmd, now, flow };
5335
5336 odp_execute_actions(&aux, packets, may_steal, actions,
5337 actions_len, dp_execute_cb);
5338 }
5339
5340 struct dp_netdev_ct_dump {
5341 struct ct_dpif_dump_state up;
5342 struct conntrack_dump dump;
5343 struct conntrack *ct;
5344 struct dp_netdev *dp;
5345 };
5346
5347 static int
5348 dpif_netdev_ct_dump_start(struct dpif *dpif, struct ct_dpif_dump_state **dump_,
5349 const uint16_t *pzone)
5350 {
5351 struct dp_netdev *dp = get_dp_netdev(dpif);
5352 struct dp_netdev_ct_dump *dump;
5353
5354 dump = xzalloc(sizeof *dump);
5355 dump->dp = dp;
5356 dump->ct = &dp->conntrack;
5357
5358 conntrack_dump_start(&dp->conntrack, &dump->dump, pzone);
5359
5360 *dump_ = &dump->up;
5361
5362 return 0;
5363 }
5364
5365 static int
5366 dpif_netdev_ct_dump_next(struct dpif *dpif OVS_UNUSED,
5367 struct ct_dpif_dump_state *dump_,
5368 struct ct_dpif_entry *entry)
5369 {
5370 struct dp_netdev_ct_dump *dump;
5371
5372 INIT_CONTAINER(dump, dump_, up);
5373
5374 return conntrack_dump_next(&dump->dump, entry);
5375 }
5376
5377 static int
5378 dpif_netdev_ct_dump_done(struct dpif *dpif OVS_UNUSED,
5379 struct ct_dpif_dump_state *dump_)
5380 {
5381 struct dp_netdev_ct_dump *dump;
5382 int err;
5383
5384 INIT_CONTAINER(dump, dump_, up);
5385
5386 err = conntrack_dump_done(&dump->dump);
5387
5388 free(dump);
5389
5390 return err;
5391 }
5392
5393 static int
5394 dpif_netdev_ct_flush(struct dpif *dpif, const uint16_t *zone)
5395 {
5396 struct dp_netdev *dp = get_dp_netdev(dpif);
5397
5398 return conntrack_flush(&dp->conntrack, zone);
5399 }
5400
5401 const struct dpif_class dpif_netdev_class = {
5402 "netdev",
5403 dpif_netdev_init,
5404 dpif_netdev_enumerate,
5405 dpif_netdev_port_open_type,
5406 dpif_netdev_open,
5407 dpif_netdev_close,
5408 dpif_netdev_destroy,
5409 dpif_netdev_run,
5410 dpif_netdev_wait,
5411 dpif_netdev_get_stats,
5412 dpif_netdev_port_add,
5413 dpif_netdev_port_del,
5414 dpif_netdev_port_set_config,
5415 dpif_netdev_port_query_by_number,
5416 dpif_netdev_port_query_by_name,
5417 NULL, /* port_get_pid */
5418 dpif_netdev_port_dump_start,
5419 dpif_netdev_port_dump_next,
5420 dpif_netdev_port_dump_done,
5421 dpif_netdev_port_poll,
5422 dpif_netdev_port_poll_wait,
5423 dpif_netdev_flow_flush,
5424 dpif_netdev_flow_dump_create,
5425 dpif_netdev_flow_dump_destroy,
5426 dpif_netdev_flow_dump_thread_create,
5427 dpif_netdev_flow_dump_thread_destroy,
5428 dpif_netdev_flow_dump_next,
5429 dpif_netdev_operate,
5430 NULL, /* recv_set */
5431 NULL, /* handlers_set */
5432 dpif_netdev_set_config,
5433 dpif_netdev_queue_to_priority,
5434 NULL, /* recv */
5435 NULL, /* recv_wait */
5436 NULL, /* recv_purge */
5437 dpif_netdev_register_dp_purge_cb,
5438 dpif_netdev_register_upcall_cb,
5439 dpif_netdev_enable_upcall,
5440 dpif_netdev_disable_upcall,
5441 dpif_netdev_get_datapath_version,
5442 dpif_netdev_ct_dump_start,
5443 dpif_netdev_ct_dump_next,
5444 dpif_netdev_ct_dump_done,
5445 dpif_netdev_ct_flush,
5446 dpif_netdev_meter_get_features,
5447 dpif_netdev_meter_set,
5448 dpif_netdev_meter_get,
5449 dpif_netdev_meter_del,
5450 };
5451
5452 static void
5453 dpif_dummy_change_port_number(struct unixctl_conn *conn, int argc OVS_UNUSED,
5454 const char *argv[], void *aux OVS_UNUSED)
5455 {
5456 struct dp_netdev_port *port;
5457 struct dp_netdev *dp;
5458 odp_port_t port_no;
5459
5460 ovs_mutex_lock(&dp_netdev_mutex);
5461 dp = shash_find_data(&dp_netdevs, argv[1]);
5462 if (!dp || !dpif_netdev_class_is_dummy(dp->class)) {
5463 ovs_mutex_unlock(&dp_netdev_mutex);
5464 unixctl_command_reply_error(conn, "unknown datapath or not a dummy");
5465 return;
5466 }
5467 ovs_refcount_ref(&dp->ref_cnt);
5468 ovs_mutex_unlock(&dp_netdev_mutex);
5469
5470 ovs_mutex_lock(&dp->port_mutex);
5471 if (get_port_by_name(dp, argv[2], &port)) {
5472 unixctl_command_reply_error(conn, "unknown port");
5473 goto exit;
5474 }
5475
5476 port_no = u32_to_odp(atoi(argv[3]));
5477 if (!port_no || port_no == ODPP_NONE) {
5478 unixctl_command_reply_error(conn, "bad port number");
5479 goto exit;
5480 }
5481 if (dp_netdev_lookup_port(dp, port_no)) {
5482 unixctl_command_reply_error(conn, "port number already in use");
5483 goto exit;
5484 }
5485
5486 /* Remove port. */
5487 hmap_remove(&dp->ports, &port->node);
5488 reconfigure_datapath(dp);
5489
5490 /* Reinsert with new port number. */
5491 port->port_no = port_no;
5492 hmap_insert(&dp->ports, &port->node, hash_port_no(port_no));
5493 reconfigure_datapath(dp);
5494
5495 seq_change(dp->port_seq);
5496 unixctl_command_reply(conn, NULL);
5497
5498 exit:
5499 ovs_mutex_unlock(&dp->port_mutex);
5500 dp_netdev_unref(dp);
5501 }
5502
5503 static void
5504 dpif_dummy_register__(const char *type)
5505 {
5506 struct dpif_class *class;
5507
5508 class = xmalloc(sizeof *class);
5509 *class = dpif_netdev_class;
5510 class->type = xstrdup(type);
5511 dp_register_provider(class);
5512 }
5513
5514 static void
5515 dpif_dummy_override(const char *type)
5516 {
5517 int error;
5518
5519 /*
5520 * Ignore EAFNOSUPPORT to allow --enable-dummy=system with
5521 * a userland-only build. It's useful for testsuite.
5522 */
5523 error = dp_unregister_provider(type);
5524 if (error == 0 || error == EAFNOSUPPORT) {
5525 dpif_dummy_register__(type);
5526 }
5527 }
5528
5529 void
5530 dpif_dummy_register(enum dummy_level level)
5531 {
5532 if (level == DUMMY_OVERRIDE_ALL) {
5533 struct sset types;
5534 const char *type;
5535
5536 sset_init(&types);
5537 dp_enumerate_types(&types);
5538 SSET_FOR_EACH (type, &types) {
5539 dpif_dummy_override(type);
5540 }
5541 sset_destroy(&types);
5542 } else if (level == DUMMY_OVERRIDE_SYSTEM) {
5543 dpif_dummy_override("system");
5544 }
5545
5546 dpif_dummy_register__("dummy");
5547
5548 unixctl_command_register("dpif-dummy/change-port-number",
5549 "dp port new-number",
5550 3, 3, dpif_dummy_change_port_number, NULL);
5551 }
5552 \f
5553 /* Datapath Classifier. */
5554
5555 /* A set of rules that all have the same fields wildcarded. */
5556 struct dpcls_subtable {
5557 /* The fields are only used by writers. */
5558 struct cmap_node cmap_node OVS_GUARDED; /* Within dpcls 'subtables_map'. */
5559
5560 /* These fields are accessed by readers. */
5561 struct cmap rules; /* Contains "struct dpcls_rule"s. */
5562 uint32_t hit_cnt; /* Number of match hits in subtable in current
5563 optimization interval. */
5564 struct netdev_flow_key mask; /* Wildcards for fields (const). */
5565 /* 'mask' must be the last field, additional space is allocated here. */
5566 };
5567
5568 /* Initializes 'cls' as a classifier that initially contains no classification
5569 * rules. */
5570 static void
5571 dpcls_init(struct dpcls *cls)
5572 {
5573 cmap_init(&cls->subtables_map);
5574 pvector_init(&cls->subtables);
5575 }
5576
5577 static void
5578 dpcls_destroy_subtable(struct dpcls *cls, struct dpcls_subtable *subtable)
5579 {
5580 VLOG_DBG("Destroying subtable %p for in_port %d", subtable, cls->in_port);
5581 pvector_remove(&cls->subtables, subtable);
5582 cmap_remove(&cls->subtables_map, &subtable->cmap_node,
5583 subtable->mask.hash);
5584 cmap_destroy(&subtable->rules);
5585 ovsrcu_postpone(free, subtable);
5586 }
5587
5588 /* Destroys 'cls'. Rules within 'cls', if any, are not freed; this is the
5589 * caller's responsibility.
5590 * May only be called after all the readers have been terminated. */
5591 static void
5592 dpcls_destroy(struct dpcls *cls)
5593 {
5594 if (cls) {
5595 struct dpcls_subtable *subtable;
5596
5597 CMAP_FOR_EACH (subtable, cmap_node, &cls->subtables_map) {
5598 ovs_assert(cmap_count(&subtable->rules) == 0);
5599 dpcls_destroy_subtable(cls, subtable);
5600 }
5601 cmap_destroy(&cls->subtables_map);
5602 pvector_destroy(&cls->subtables);
5603 }
5604 }
5605
5606 static struct dpcls_subtable *
5607 dpcls_create_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
5608 {
5609 struct dpcls_subtable *subtable;
5610
5611 /* Need to add one. */
5612 subtable = xmalloc(sizeof *subtable
5613 - sizeof subtable->mask.mf + mask->len);
5614 cmap_init(&subtable->rules);
5615 subtable->hit_cnt = 0;
5616 netdev_flow_key_clone(&subtable->mask, mask);
5617 cmap_insert(&cls->subtables_map, &subtable->cmap_node, mask->hash);
5618 /* Add the new subtable at the end of the pvector (with no hits yet) */
5619 pvector_insert(&cls->subtables, subtable, 0);
5620 VLOG_DBG("Creating %"PRIuSIZE". subtable %p for in_port %d",
5621 cmap_count(&cls->subtables_map), subtable, cls->in_port);
5622 pvector_publish(&cls->subtables);
5623
5624 return subtable;
5625 }
5626
5627 static inline struct dpcls_subtable *
5628 dpcls_find_subtable(struct dpcls *cls, const struct netdev_flow_key *mask)
5629 {
5630 struct dpcls_subtable *subtable;
5631
5632 CMAP_FOR_EACH_WITH_HASH (subtable, cmap_node, mask->hash,
5633 &cls->subtables_map) {
5634 if (netdev_flow_key_equal(&subtable->mask, mask)) {
5635 return subtable;
5636 }
5637 }
5638 return dpcls_create_subtable(cls, mask);
5639 }
5640
5641
5642 /* Periodically sort the dpcls subtable vectors according to hit counts */
5643 static void
5644 dpcls_sort_subtable_vector(struct dpcls *cls)
5645 {
5646 struct pvector *pvec = &cls->subtables;
5647 struct dpcls_subtable *subtable;
5648
5649 PVECTOR_FOR_EACH (subtable, pvec) {
5650 pvector_change_priority(pvec, subtable, subtable->hit_cnt);
5651 subtable->hit_cnt = 0;
5652 }
5653 pvector_publish(pvec);
5654 }
5655
5656 static inline void
5657 dp_netdev_pmd_try_optimize(struct dp_netdev_pmd_thread *pmd)
5658 {
5659 struct dpcls *cls;
5660 long long int now = time_msec();
5661
5662 if (now > pmd->next_optimization) {
5663 /* Try to obtain the flow lock to block out revalidator threads.
5664 * If not possible, just try next time. */
5665 if (!ovs_mutex_trylock(&pmd->flow_mutex)) {
5666 /* Optimize each classifier */
5667 CMAP_FOR_EACH (cls, node, &pmd->classifiers) {
5668 dpcls_sort_subtable_vector(cls);
5669 }
5670 ovs_mutex_unlock(&pmd->flow_mutex);
5671 /* Start new measuring interval */
5672 pmd->next_optimization = now + DPCLS_OPTIMIZATION_INTERVAL;
5673 }
5674 }
5675 }
5676
5677 /* Insert 'rule' into 'cls'. */
5678 static void
5679 dpcls_insert(struct dpcls *cls, struct dpcls_rule *rule,
5680 const struct netdev_flow_key *mask)
5681 {
5682 struct dpcls_subtable *subtable = dpcls_find_subtable(cls, mask);
5683
5684 /* Refer to subtable's mask, also for later removal. */
5685 rule->mask = &subtable->mask;
5686 cmap_insert(&subtable->rules, &rule->cmap_node, rule->flow.hash);
5687 }
5688
5689 /* Removes 'rule' from 'cls', also destructing the 'rule'. */
5690 static void
5691 dpcls_remove(struct dpcls *cls, struct dpcls_rule *rule)
5692 {
5693 struct dpcls_subtable *subtable;
5694
5695 ovs_assert(rule->mask);
5696
5697 /* Get subtable from reference in rule->mask. */
5698 INIT_CONTAINER(subtable, rule->mask, mask);
5699 if (cmap_remove(&subtable->rules, &rule->cmap_node, rule->flow.hash)
5700 == 0) {
5701 /* Delete empty subtable. */
5702 dpcls_destroy_subtable(cls, subtable);
5703 pvector_publish(&cls->subtables);
5704 }
5705 }
5706
5707 /* Returns true if 'target' satisfies 'key' in 'mask', that is, if each 1-bit
5708 * in 'mask' the values in 'key' and 'target' are the same. */
5709 static inline bool
5710 dpcls_rule_matches_key(const struct dpcls_rule *rule,
5711 const struct netdev_flow_key *target)
5712 {
5713 const uint64_t *keyp = miniflow_get_values(&rule->flow.mf);
5714 const uint64_t *maskp = miniflow_get_values(&rule->mask->mf);
5715 uint64_t value;
5716
5717 NETDEV_FLOW_KEY_FOR_EACH_IN_FLOWMAP(value, target, rule->flow.mf.map) {
5718 if (OVS_UNLIKELY((value & *maskp++) != *keyp++)) {
5719 return false;
5720 }
5721 }
5722 return true;
5723 }
5724
5725 /* For each miniflow in 'keys' performs a classifier lookup writing the result
5726 * into the corresponding slot in 'rules'. If a particular entry in 'keys' is
5727 * NULL it is skipped.
5728 *
5729 * This function is optimized for use in the userspace datapath and therefore
5730 * does not implement a lot of features available in the standard
5731 * classifier_lookup() function. Specifically, it does not implement
5732 * priorities, instead returning any rule which matches the flow.
5733 *
5734 * Returns true if all miniflows found a corresponding rule. */
5735 static bool
5736 dpcls_lookup(struct dpcls *cls, const struct netdev_flow_key keys[],
5737 struct dpcls_rule **rules, const size_t cnt,
5738 int *num_lookups_p)
5739 {
5740 /* The received 'cnt' miniflows are the search-keys that will be processed
5741 * to find a matching entry into the available subtables.
5742 * The number of bits in map_type is equal to NETDEV_MAX_BURST. */
5743 typedef uint32_t map_type;
5744 #define MAP_BITS (sizeof(map_type) * CHAR_BIT)
5745 BUILD_ASSERT_DECL(MAP_BITS >= NETDEV_MAX_BURST);
5746
5747 struct dpcls_subtable *subtable;
5748
5749 map_type keys_map = TYPE_MAXIMUM(map_type); /* Set all bits. */
5750 map_type found_map;
5751 uint32_t hashes[MAP_BITS];
5752 const struct cmap_node *nodes[MAP_BITS];
5753
5754 if (cnt != MAP_BITS) {
5755 keys_map >>= MAP_BITS - cnt; /* Clear extra bits. */
5756 }
5757 memset(rules, 0, cnt * sizeof *rules);
5758
5759 int lookups_match = 0, subtable_pos = 1;
5760
5761 /* The Datapath classifier - aka dpcls - is composed of subtables.
5762 * Subtables are dynamically created as needed when new rules are inserted.
5763 * Each subtable collects rules with matches on a specific subset of packet
5764 * fields as defined by the subtable's mask. We proceed to process every
5765 * search-key against each subtable, but when a match is found for a
5766 * search-key, the search for that key can stop because the rules are
5767 * non-overlapping. */
5768 PVECTOR_FOR_EACH (subtable, &cls->subtables) {
5769 int i;
5770
5771 /* Compute hashes for the remaining keys. Each search-key is
5772 * masked with the subtable's mask to avoid hashing the wildcarded
5773 * bits. */
5774 ULLONG_FOR_EACH_1(i, keys_map) {
5775 hashes[i] = netdev_flow_key_hash_in_mask(&keys[i],
5776 &subtable->mask);
5777 }
5778 /* Lookup. */
5779 found_map = cmap_find_batch(&subtable->rules, keys_map, hashes, nodes);
5780 /* Check results. When the i-th bit of found_map is set, it means
5781 * that a set of nodes with a matching hash value was found for the
5782 * i-th search-key. Due to possible hash collisions we need to check
5783 * which of the found rules, if any, really matches our masked
5784 * search-key. */
5785 ULLONG_FOR_EACH_1(i, found_map) {
5786 struct dpcls_rule *rule;
5787
5788 CMAP_NODE_FOR_EACH (rule, cmap_node, nodes[i]) {
5789 if (OVS_LIKELY(dpcls_rule_matches_key(rule, &keys[i]))) {
5790 rules[i] = rule;
5791 /* Even at 20 Mpps the 32-bit hit_cnt cannot wrap
5792 * within one second optimization interval. */
5793 subtable->hit_cnt++;
5794 lookups_match += subtable_pos;
5795 goto next;
5796 }
5797 }
5798 /* None of the found rules was a match. Reset the i-th bit to
5799 * keep searching this key in the next subtable. */
5800 ULLONG_SET0(found_map, i); /* Did not match. */
5801 next:
5802 ; /* Keep Sparse happy. */
5803 }
5804 keys_map &= ~found_map; /* Clear the found rules. */
5805 if (!keys_map) {
5806 if (num_lookups_p) {
5807 *num_lookups_p = lookups_match;
5808 }
5809 return true; /* All found. */
5810 }
5811 subtable_pos++;
5812 }
5813 if (num_lookups_p) {
5814 *num_lookups_p = lookups_match;
5815 }
5816 return false; /* Some misses. */
5817 }