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