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