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