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