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