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