]> git.proxmox.com Git - mirror_ovs.git/blob - ofproto/ofproto.c
ofp-actions: Fix variable length meta-flow OXMs.
[mirror_ovs.git] / ofproto / ofproto.c
1 /*
2 * Copyright (c) 2009-2017 Nicira, Inc.
3 * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 #include <config.h>
19 #include <errno.h>
20 #include <inttypes.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24
25 #include "bitmap.h"
26 #include "bundles.h"
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "connectivity.h"
30 #include "connmgr.h"
31 #include "coverage.h"
32 #include "dp-packet.h"
33 #include "hash.h"
34 #include "openvswitch/hmap.h"
35 #include "netdev.h"
36 #include "nx-match.h"
37 #include "ofproto.h"
38 #include "ofproto-provider.h"
39 #include "openflow/nicira-ext.h"
40 #include "openflow/openflow.h"
41 #include "openvswitch/dynamic-string.h"
42 #include "openvswitch/meta-flow.h"
43 #include "openvswitch/ofp-actions.h"
44 #include "openvswitch/ofp-errors.h"
45 #include "openvswitch/ofp-msgs.h"
46 #include "openvswitch/ofp-print.h"
47 #include "openvswitch/ofp-util.h"
48 #include "openvswitch/ofpbuf.h"
49 #include "openvswitch/vlog.h"
50 #include "ovs-rcu.h"
51 #include "packets.h"
52 #include "pinsched.h"
53 #include "poll-loop.h"
54 #include "random.h"
55 #include "seq.h"
56 #include "openvswitch/shash.h"
57 #include "simap.h"
58 #include "smap.h"
59 #include "sset.h"
60 #include "timeval.h"
61 #include "tun-metadata.h"
62 #include "unaligned.h"
63 #include "unixctl.h"
64 #include "util.h"
65
66 VLOG_DEFINE_THIS_MODULE(ofproto);
67
68 COVERAGE_DEFINE(ofproto_flush);
69 COVERAGE_DEFINE(ofproto_packet_out);
70 COVERAGE_DEFINE(ofproto_queue_req);
71 COVERAGE_DEFINE(ofproto_recv_openflow);
72 COVERAGE_DEFINE(ofproto_reinit_ports);
73 COVERAGE_DEFINE(ofproto_update_port);
74
75 /* Default fields to use for prefix tries in each flow table, unless something
76 * else is configured. */
77 const enum mf_field_id default_prefix_fields[2] =
78 { MFF_IPV4_DST, MFF_IPV4_SRC };
79
80 /* oftable. */
81 static void oftable_init(struct oftable *);
82 static void oftable_destroy(struct oftable *);
83
84 static void oftable_set_name(struct oftable *, const char *name);
85
86 static enum ofperr evict_rules_from_table(struct oftable *)
87 OVS_REQUIRES(ofproto_mutex);
88 static void oftable_configure_eviction(struct oftable *,
89 unsigned int eviction,
90 const struct mf_subfield *fields,
91 size_t n_fields)
92 OVS_REQUIRES(ofproto_mutex);
93
94 /* This is the only combination of OpenFlow eviction flags that OVS supports: a
95 * combination of OF1.4+ importance, the remaining lifetime of the flow, and
96 * fairness based on user-specified fields. */
97 #define OFPROTO_EVICTION_FLAGS \
98 (OFPTMPEF14_OTHER | OFPTMPEF14_IMPORTANCE | OFPTMPEF14_LIFETIME)
99
100 /* A set of rules within a single OpenFlow table (oftable) that have the same
101 * values for the oftable's eviction_fields. A rule to be evicted, when one is
102 * needed, is taken from the eviction group that contains the greatest number
103 * of rules.
104 *
105 * An oftable owns any number of eviction groups, each of which contains any
106 * number of rules.
107 *
108 * Membership in an eviction group is imprecise, based on the hash of the
109 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
110 * That is, if two rules have different eviction_fields, but those
111 * eviction_fields hash to the same value, then they will belong to the same
112 * eviction_group anyway.
113 *
114 * (When eviction is not enabled on an oftable, we don't track any eviction
115 * groups, to save time and space.) */
116 struct eviction_group {
117 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
118 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
119 struct heap rules; /* Contains "struct rule"s. */
120 };
121
122 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep)
123 OVS_REQUIRES(ofproto_mutex);
124 static uint64_t rule_eviction_priority(struct ofproto *ofproto, struct rule *)
125 OVS_REQUIRES(ofproto_mutex);
126 static void eviction_group_add_rule(struct rule *)
127 OVS_REQUIRES(ofproto_mutex);
128 static void eviction_group_remove_rule(struct rule *)
129 OVS_REQUIRES(ofproto_mutex);
130
131 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
132 const struct match *match, int priority,
133 ovs_version_t version,
134 ovs_be64 cookie, ovs_be64 cookie_mask,
135 ofp_port_t out_port, uint32_t out_group);
136 static void rule_criteria_require_rw(struct rule_criteria *,
137 bool can_write_readonly);
138 static void rule_criteria_destroy(struct rule_criteria *);
139
140 static enum ofperr collect_rules_loose(struct ofproto *,
141 const struct rule_criteria *,
142 struct rule_collection *);
143
144 struct learned_cookie {
145 union {
146 /* In struct ofproto's 'learned_cookies' hmap. */
147 struct hmap_node hmap_node OVS_GUARDED_BY(ofproto_mutex);
148
149 /* In 'dead_cookies' list when removed from hmap. */
150 struct ovs_list list_node;
151 } u;
152
153 /* Key. */
154 ovs_be64 cookie OVS_GUARDED_BY(ofproto_mutex);
155 uint8_t table_id OVS_GUARDED_BY(ofproto_mutex);
156
157 /* Number of references from "learn" actions.
158 *
159 * When this drops to 0, all of the flows in 'table_id' with the specified
160 * 'cookie' are deleted. */
161 int n OVS_GUARDED_BY(ofproto_mutex);
162 };
163
164 static const struct ofpact_learn *next_learn_with_delete(
165 const struct rule_actions *, const struct ofpact_learn *start);
166
167 static void learned_cookies_inc(struct ofproto *, const struct rule_actions *)
168 OVS_REQUIRES(ofproto_mutex);
169 static void learned_cookies_dec(struct ofproto *, const struct rule_actions *,
170 struct ovs_list *dead_cookies)
171 OVS_REQUIRES(ofproto_mutex);
172 static void learned_cookies_flush(struct ofproto *, struct ovs_list *dead_cookies)
173 OVS_REQUIRES(ofproto_mutex);
174
175 /* ofport. */
176 static void ofport_destroy__(struct ofport *) OVS_EXCLUDED(ofproto_mutex);
177 static void ofport_destroy(struct ofport *, bool del);
178 static bool ofport_is_mtu_overridden(const struct ofproto *,
179 const struct ofport *);
180
181 static int update_port(struct ofproto *, const char *devname);
182 static int init_ports(struct ofproto *);
183 static void reinit_ports(struct ofproto *);
184
185 static long long int ofport_get_usage(const struct ofproto *,
186 ofp_port_t ofp_port);
187 static void ofport_set_usage(struct ofproto *, ofp_port_t ofp_port,
188 long long int last_used);
189 static void ofport_remove_usage(struct ofproto *, ofp_port_t ofp_port);
190
191 /* Ofport usage.
192 *
193 * Keeps track of the currently used and recently used ofport values and is
194 * used to prevent immediate recycling of ofport values. */
195 struct ofport_usage {
196 struct hmap_node hmap_node; /* In struct ofproto's "ofport_usage" hmap. */
197 ofp_port_t ofp_port; /* OpenFlow port number. */
198 long long int last_used; /* Last time the 'ofp_port' was used. LLONG_MAX
199 represents in-use ofports. */
200 };
201
202 /* rule. */
203 static void ofproto_rule_send_removed(struct rule *)
204 OVS_EXCLUDED(ofproto_mutex);
205 static bool rule_is_readonly(const struct rule *);
206 static void ofproto_rule_insert__(struct ofproto *, struct rule *)
207 OVS_REQUIRES(ofproto_mutex);
208 static void ofproto_rule_remove__(struct ofproto *, struct rule *)
209 OVS_REQUIRES(ofproto_mutex);
210
211 /* The source of an OpenFlow request.
212 *
213 * A table modification request can be generated externally, via OpenFlow, or
214 * internally through a function call. This structure indicates the source of
215 * an OpenFlow-generated table modification. For an internal flow_mod, it
216 * isn't meaningful and thus supplied as NULL. */
217 struct openflow_mod_requester {
218 struct ofconn *ofconn; /* Connection on which flow_mod arrived. */
219 const struct ofp_header *request;
220 };
221
222 /* OpenFlow. */
223 static enum ofperr ofproto_rule_create(struct ofproto *, struct cls_rule *,
224 uint8_t table_id, ovs_be64 new_cookie,
225 uint16_t idle_timeout,
226 uint16_t hard_timeout,
227 enum ofputil_flow_mod_flags flags,
228 uint16_t importance,
229 const struct ofpact *ofpacts,
230 size_t ofpacts_len,
231 struct rule **new_rule)
232 OVS_NO_THREAD_SAFETY_ANALYSIS;
233
234 static void replace_rule_start(struct ofproto *, struct ofproto_flow_mod *,
235 struct rule *old_rule, struct rule *new_rule)
236 OVS_REQUIRES(ofproto_mutex);
237
238 static void replace_rule_revert(struct ofproto *, struct rule *old_rule,
239 struct rule *new_rule)
240 OVS_REQUIRES(ofproto_mutex);
241
242 static void replace_rule_finish(struct ofproto *, struct ofproto_flow_mod *,
243 const struct openflow_mod_requester *,
244 struct rule *old_rule, struct rule *new_rule,
245 struct ovs_list *dead_cookies)
246 OVS_REQUIRES(ofproto_mutex);
247 static void delete_flows__(struct rule_collection *,
248 enum ofp_flow_removed_reason,
249 const struct openflow_mod_requester *)
250 OVS_REQUIRES(ofproto_mutex);
251
252 static bool ofproto_group_exists(const struct ofproto *, uint32_t group_id);
253 static void handle_openflow(struct ofconn *, const struct ofpbuf *);
254 static enum ofperr ofproto_flow_mod_init(struct ofproto *,
255 struct ofproto_flow_mod *,
256 const struct ofputil_flow_mod *fm,
257 struct rule *)
258 OVS_EXCLUDED(ofproto_mutex);
259 static enum ofperr ofproto_flow_mod_start(struct ofproto *,
260 struct ofproto_flow_mod *)
261 OVS_REQUIRES(ofproto_mutex);
262 static void ofproto_flow_mod_revert(struct ofproto *,
263 struct ofproto_flow_mod *)
264 OVS_REQUIRES(ofproto_mutex);
265 static void ofproto_flow_mod_finish(struct ofproto *,
266 struct ofproto_flow_mod *,
267 const struct openflow_mod_requester *)
268 OVS_REQUIRES(ofproto_mutex);
269 static enum ofperr handle_flow_mod__(struct ofproto *,
270 const struct ofputil_flow_mod *,
271 const struct openflow_mod_requester *)
272 OVS_EXCLUDED(ofproto_mutex);
273 static void calc_duration(long long int start, long long int now,
274 uint32_t *sec, uint32_t *nsec);
275
276 /* ofproto. */
277 static uint64_t pick_datapath_id(const struct ofproto *);
278 static uint64_t pick_fallback_dpid(void);
279 static void ofproto_destroy__(struct ofproto *);
280 static void update_mtu(struct ofproto *, struct ofport *);
281 static void update_mtu_ofproto(struct ofproto *);
282 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
283 static void meter_insert_rule(struct rule *);
284
285 /* unixctl. */
286 static void ofproto_unixctl_init(void);
287
288 /* All registered ofproto classes, in probe order. */
289 static const struct ofproto_class **ofproto_classes;
290 static size_t n_ofproto_classes;
291 static size_t allocated_ofproto_classes;
292
293 /* Global lock that protects all flow table operations. */
294 struct ovs_mutex ofproto_mutex = OVS_MUTEX_INITIALIZER;
295
296 unsigned ofproto_flow_limit = OFPROTO_FLOW_LIMIT_DEFAULT;
297 unsigned ofproto_max_idle = OFPROTO_MAX_IDLE_DEFAULT;
298
299 size_t n_handlers, n_revalidators;
300 char *pmd_cpu_mask;
301
302 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
303 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
304
305 /* Initial mappings of port to OpenFlow number mappings. */
306 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
307
308 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
309
310 /* The default value of true waits for flow restore. */
311 static bool flow_restore_wait = true;
312
313 /* Must be called to initialize the ofproto library.
314 *
315 * The caller may pass in 'iface_hints', which contains an shash of
316 * "iface_hint" elements indexed by the interface's name. The provider
317 * may use these hints to describe the startup configuration in order to
318 * reinitialize its state. The caller owns the provided data, so a
319 * provider will make copies of anything required. An ofproto provider
320 * will remove any existing state that is not described by the hint, and
321 * may choose to remove it all. */
322 void
323 ofproto_init(const struct shash *iface_hints)
324 {
325 struct shash_node *node;
326 size_t i;
327
328 ofproto_class_register(&ofproto_dpif_class);
329
330 /* Make a local copy, since we don't own 'iface_hints' elements. */
331 SHASH_FOR_EACH(node, iface_hints) {
332 const struct iface_hint *orig_hint = node->data;
333 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
334 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
335
336 new_hint->br_name = xstrdup(orig_hint->br_name);
337 new_hint->br_type = xstrdup(br_type);
338 new_hint->ofp_port = orig_hint->ofp_port;
339
340 shash_add(&init_ofp_ports, node->name, new_hint);
341 }
342
343 for (i = 0; i < n_ofproto_classes; i++) {
344 ofproto_classes[i]->init(&init_ofp_ports);
345 }
346
347 ofproto_unixctl_init();
348 }
349
350 /* 'type' should be a normalized datapath type, as returned by
351 * ofproto_normalize_type(). Returns the corresponding ofproto_class
352 * structure, or a null pointer if there is none registered for 'type'. */
353 static const struct ofproto_class *
354 ofproto_class_find__(const char *type)
355 {
356 size_t i;
357
358 for (i = 0; i < n_ofproto_classes; i++) {
359 const struct ofproto_class *class = ofproto_classes[i];
360 struct sset types;
361 bool found;
362
363 sset_init(&types);
364 class->enumerate_types(&types);
365 found = sset_contains(&types, type);
366 sset_destroy(&types);
367
368 if (found) {
369 return class;
370 }
371 }
372 VLOG_WARN("unknown datapath type %s", type);
373 return NULL;
374 }
375
376 /* Registers a new ofproto class. After successful registration, new ofprotos
377 * of that type can be created using ofproto_create(). */
378 int
379 ofproto_class_register(const struct ofproto_class *new_class)
380 {
381 size_t i;
382
383 for (i = 0; i < n_ofproto_classes; i++) {
384 if (ofproto_classes[i] == new_class) {
385 return EEXIST;
386 }
387 }
388
389 if (n_ofproto_classes >= allocated_ofproto_classes) {
390 ofproto_classes = x2nrealloc(ofproto_classes,
391 &allocated_ofproto_classes,
392 sizeof *ofproto_classes);
393 }
394 ofproto_classes[n_ofproto_classes++] = new_class;
395 return 0;
396 }
397
398 /* Unregisters a datapath provider. 'type' must have been previously
399 * registered and not currently be in use by any ofprotos. After
400 * unregistration new datapaths of that type cannot be opened using
401 * ofproto_create(). */
402 int
403 ofproto_class_unregister(const struct ofproto_class *class)
404 {
405 size_t i;
406
407 for (i = 0; i < n_ofproto_classes; i++) {
408 if (ofproto_classes[i] == class) {
409 for (i++; i < n_ofproto_classes; i++) {
410 ofproto_classes[i - 1] = ofproto_classes[i];
411 }
412 n_ofproto_classes--;
413 return 0;
414 }
415 }
416 VLOG_WARN("attempted to unregister an ofproto class that is not "
417 "registered");
418 return EAFNOSUPPORT;
419 }
420
421 /* Clears 'types' and enumerates all registered ofproto types into it. The
422 * caller must first initialize the sset. */
423 void
424 ofproto_enumerate_types(struct sset *types)
425 {
426 size_t i;
427
428 sset_clear(types);
429 for (i = 0; i < n_ofproto_classes; i++) {
430 ofproto_classes[i]->enumerate_types(types);
431 }
432 }
433
434 /* Returns the fully spelled out name for the given ofproto 'type'.
435 *
436 * Normalized type string can be compared with strcmp(). Unnormalized type
437 * string might be the same even if they have different spellings. */
438 const char *
439 ofproto_normalize_type(const char *type)
440 {
441 return type && type[0] ? type : "system";
442 }
443
444 /* Clears 'names' and enumerates the names of all known created ofprotos with
445 * the given 'type'. The caller must first initialize the sset. Returns 0 if
446 * successful, otherwise a positive errno value.
447 *
448 * Some kinds of datapaths might not be practically enumerable. This is not
449 * considered an error. */
450 int
451 ofproto_enumerate_names(const char *type, struct sset *names)
452 {
453 const struct ofproto_class *class = ofproto_class_find__(type);
454 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
455 }
456
457 static void
458 ofproto_bump_tables_version(struct ofproto *ofproto)
459 {
460 ++ofproto->tables_version;
461 ofproto->ofproto_class->set_tables_version(ofproto,
462 ofproto->tables_version);
463 }
464
465 int
466 ofproto_create(const char *datapath_name, const char *datapath_type,
467 struct ofproto **ofprotop)
468 OVS_EXCLUDED(ofproto_mutex)
469 {
470 const struct ofproto_class *class;
471 struct ofproto *ofproto;
472 int error;
473 int i;
474
475 *ofprotop = NULL;
476
477 datapath_type = ofproto_normalize_type(datapath_type);
478 class = ofproto_class_find__(datapath_type);
479 if (!class) {
480 VLOG_WARN("could not create datapath %s of unknown type %s",
481 datapath_name, datapath_type);
482 return EAFNOSUPPORT;
483 }
484
485 ofproto = class->alloc();
486 if (!ofproto) {
487 VLOG_ERR("failed to allocate datapath %s of type %s",
488 datapath_name, datapath_type);
489 return ENOMEM;
490 }
491
492 /* Initialize. */
493 ovs_mutex_lock(&ofproto_mutex);
494 memset(ofproto, 0, sizeof *ofproto);
495 ofproto->ofproto_class = class;
496 ofproto->name = xstrdup(datapath_name);
497 ofproto->type = xstrdup(datapath_type);
498 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
499 hash_string(ofproto->name, 0));
500 ofproto->datapath_id = 0;
501 ofproto->forward_bpdu = false;
502 ofproto->fallback_dpid = pick_fallback_dpid();
503 ofproto->mfr_desc = NULL;
504 ofproto->hw_desc = NULL;
505 ofproto->sw_desc = NULL;
506 ofproto->serial_desc = NULL;
507 ofproto->dp_desc = NULL;
508 ofproto->frag_handling = OFPUTIL_FRAG_NORMAL;
509 hmap_init(&ofproto->ports);
510 hmap_init(&ofproto->ofport_usage);
511 shash_init(&ofproto->port_by_name);
512 simap_init(&ofproto->ofp_requests);
513 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
514 ofproto->eviction_group_timer = LLONG_MIN;
515 ofproto->tables = NULL;
516 ofproto->n_tables = 0;
517 ofproto->tables_version = OVS_VERSION_MIN;
518 hindex_init(&ofproto->cookies);
519 hmap_init(&ofproto->learned_cookies);
520 ovs_list_init(&ofproto->expirable);
521 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
522 ofproto->min_mtu = INT_MAX;
523 cmap_init(&ofproto->groups);
524 ovs_mutex_unlock(&ofproto_mutex);
525 ofproto->ogf.types = 0xf;
526 ofproto->ogf.capabilities = OFPGFC_CHAINING | OFPGFC_SELECT_LIVENESS |
527 OFPGFC_SELECT_WEIGHT;
528 for (i = 0; i < 4; i++) {
529 ofproto->ogf.max_groups[i] = OFPG_MAX;
530 ofproto->ogf.ofpacts[i] = (UINT64_C(1) << N_OFPACTS) - 1;
531 }
532 ovsrcu_set(&ofproto->metadata_tab, tun_metadata_alloc(NULL));
533
534 ovs_mutex_init(&ofproto->vl_mff_map.mutex);
535 cmap_init(&ofproto->vl_mff_map.cmap);
536
537 error = ofproto->ofproto_class->construct(ofproto);
538 if (error) {
539 VLOG_ERR("failed to open datapath %s: %s",
540 datapath_name, ovs_strerror(error));
541 ovs_mutex_lock(&ofproto_mutex);
542 connmgr_destroy(ofproto->connmgr);
543 ofproto->connmgr = NULL;
544 ovs_mutex_unlock(&ofproto_mutex);
545 ofproto_destroy__(ofproto);
546 return error;
547 }
548
549 /* Check that hidden tables, if any, are at the end. */
550 ovs_assert(ofproto->n_tables);
551 for (i = 0; i + 1 < ofproto->n_tables; i++) {
552 enum oftable_flags flags = ofproto->tables[i].flags;
553 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
554
555 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
556 }
557
558 ofproto->datapath_id = pick_datapath_id(ofproto);
559 init_ports(ofproto);
560
561 /* Initialize meters table. */
562 if (ofproto->ofproto_class->meter_get_features) {
563 ofproto->ofproto_class->meter_get_features(ofproto,
564 &ofproto->meter_features);
565 } else {
566 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
567 }
568 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
569 * sizeof(struct meter *));
570
571 /* Set the initial tables version. */
572 ofproto_bump_tables_version(ofproto);
573
574 *ofprotop = ofproto;
575 return 0;
576 }
577
578 /* Must be called (only) by an ofproto implementation in its constructor
579 * function. See the large comment on 'construct' in struct ofproto_class for
580 * details. */
581 void
582 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
583 {
584 struct oftable *table;
585
586 ovs_assert(!ofproto->n_tables);
587 ovs_assert(n_tables >= 1 && n_tables <= 255);
588
589 ofproto->n_tables = n_tables;
590 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
591 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
592 oftable_init(table);
593 }
594 }
595
596 /* To be optionally called (only) by an ofproto implementation in its
597 * constructor function. See the large comment on 'construct' in struct
598 * ofproto_class for details.
599 *
600 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
601 * will then ensure that actions passed into the ofproto implementation will
602 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
603 * function is not called, there will be no such restriction.
604 *
605 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
606 * the 'max_ports' restriction. */
607 void
608 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
609 {
610 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
611 ofproto->max_ports = max_ports;
612 }
613
614 uint64_t
615 ofproto_get_datapath_id(const struct ofproto *ofproto)
616 {
617 return ofproto->datapath_id;
618 }
619
620 void
621 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
622 {
623 uint64_t old_dpid = p->datapath_id;
624 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
625 if (p->datapath_id != old_dpid) {
626 /* Force all active connections to reconnect, since there is no way to
627 * notify a controller that the datapath ID has changed. */
628 ofproto_reconnect_controllers(p);
629 }
630 }
631
632 void
633 ofproto_set_controllers(struct ofproto *p,
634 const struct ofproto_controller *controllers,
635 size_t n_controllers, uint32_t allowed_versions)
636 {
637 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
638 allowed_versions);
639 }
640
641 void
642 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
643 {
644 connmgr_set_fail_mode(p->connmgr, fail_mode);
645 }
646
647 /* Drops the connections between 'ofproto' and all of its controllers, forcing
648 * them to reconnect. */
649 void
650 ofproto_reconnect_controllers(struct ofproto *ofproto)
651 {
652 connmgr_reconnect(ofproto->connmgr);
653 }
654
655 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
656 * in-band control should guarantee access, in the same way that in-band
657 * control guarantees access to OpenFlow controllers. */
658 void
659 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
660 const struct sockaddr_in *extras, size_t n)
661 {
662 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
663 }
664
665 /* Sets the OpenFlow queue used by flows set up by in-band control on
666 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
667 * flows will use the default queue. */
668 void
669 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
670 {
671 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
672 }
673
674 /* Sets the number of flows at which eviction from the kernel flow table
675 * will occur. */
676 void
677 ofproto_set_flow_limit(unsigned limit)
678 {
679 ofproto_flow_limit = limit;
680 }
681
682 /* Sets the maximum idle time for flows in the datapath before they are
683 * expired. */
684 void
685 ofproto_set_max_idle(unsigned max_idle)
686 {
687 ofproto_max_idle = max_idle;
688 }
689
690 /* If forward_bpdu is true, the NORMAL action will forward frames with
691 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
692 * the NORMAL action will drop these frames. */
693 void
694 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
695 {
696 bool old_val = ofproto->forward_bpdu;
697 ofproto->forward_bpdu = forward_bpdu;
698 if (old_val != ofproto->forward_bpdu) {
699 if (ofproto->ofproto_class->forward_bpdu_changed) {
700 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
701 }
702 }
703 }
704
705 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
706 * 'idle_time', in seconds, and the maximum number of MAC table entries to
707 * 'max_entries'. */
708 void
709 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
710 size_t max_entries)
711 {
712 if (ofproto->ofproto_class->set_mac_table_config) {
713 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
714 max_entries);
715 }
716 }
717
718 /* Multicast snooping configuration. */
719
720 /* Configures multicast snooping on 'ofproto' using the settings
721 * defined in 's'. If 's' is NULL, disables multicast snooping.
722 *
723 * Returns 0 if successful, otherwise a positive errno value. */
724 int
725 ofproto_set_mcast_snooping(struct ofproto *ofproto,
726 const struct ofproto_mcast_snooping_settings *s)
727 {
728 return (ofproto->ofproto_class->set_mcast_snooping
729 ? ofproto->ofproto_class->set_mcast_snooping(ofproto, s)
730 : EOPNOTSUPP);
731 }
732
733 /* Configures multicast snooping flood settings on 'ofp_port' of 'ofproto'.
734 *
735 * Returns 0 if successful, otherwise a positive errno value.*/
736 int
737 ofproto_port_set_mcast_snooping(struct ofproto *ofproto, void *aux,
738 const struct ofproto_mcast_snooping_port_settings *s)
739 {
740 return (ofproto->ofproto_class->set_mcast_snooping_port
741 ? ofproto->ofproto_class->set_mcast_snooping_port(ofproto, aux, s)
742 : EOPNOTSUPP);
743 }
744
745 void
746 ofproto_set_cpu_mask(const char *cmask)
747 {
748 free(pmd_cpu_mask);
749 pmd_cpu_mask = nullable_xstrdup(cmask);
750 }
751
752 void
753 ofproto_set_threads(int n_handlers_, int n_revalidators_)
754 {
755 int threads = MAX(count_cpu_cores(), 2);
756
757 n_revalidators = MAX(n_revalidators_, 0);
758 n_handlers = MAX(n_handlers_, 0);
759
760 if (!n_revalidators) {
761 n_revalidators = n_handlers
762 ? MAX(threads - (int) n_handlers, 1)
763 : threads / 4 + 1;
764 }
765
766 if (!n_handlers) {
767 n_handlers = MAX(threads - (int) n_revalidators, 1);
768 }
769 }
770
771 void
772 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
773 {
774 free(p->dp_desc);
775 p->dp_desc = nullable_xstrdup(dp_desc);
776 }
777
778 int
779 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
780 {
781 return connmgr_set_snoops(ofproto->connmgr, snoops);
782 }
783
784 int
785 ofproto_set_netflow(struct ofproto *ofproto,
786 const struct netflow_options *nf_options)
787 {
788 if (nf_options && sset_is_empty(&nf_options->collectors)) {
789 nf_options = NULL;
790 }
791
792 if (ofproto->ofproto_class->set_netflow) {
793 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
794 } else {
795 return nf_options ? EOPNOTSUPP : 0;
796 }
797 }
798
799 int
800 ofproto_set_sflow(struct ofproto *ofproto,
801 const struct ofproto_sflow_options *oso)
802 {
803 if (oso && sset_is_empty(&oso->targets)) {
804 oso = NULL;
805 }
806
807 if (ofproto->ofproto_class->set_sflow) {
808 return ofproto->ofproto_class->set_sflow(ofproto, oso);
809 } else {
810 return oso ? EOPNOTSUPP : 0;
811 }
812 }
813
814 int
815 ofproto_set_ipfix(struct ofproto *ofproto,
816 const struct ofproto_ipfix_bridge_exporter_options *bo,
817 const struct ofproto_ipfix_flow_exporter_options *fo,
818 size_t n_fo)
819 {
820 if (ofproto->ofproto_class->set_ipfix) {
821 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
822 } else {
823 return (bo || fo) ? EOPNOTSUPP : 0;
824 }
825 }
826
827 static int
828 ofproto_get_ipfix_stats(struct ofproto *ofproto,
829 bool bridge_ipfix,
830 struct ovs_list *replies)
831 {
832 int error;
833
834 if (ofproto->ofproto_class->get_ipfix_stats) {
835 error = ofproto->ofproto_class->get_ipfix_stats(ofproto,
836 bridge_ipfix,
837 replies);
838 } else {
839 error = EOPNOTSUPP;
840 }
841
842 return error;
843 }
844
845 static enum ofperr
846 handle_ipfix_bridge_stats_request(struct ofconn *ofconn,
847 const struct ofp_header *request)
848 {
849 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
850 struct ovs_list replies;
851 enum ofperr error;
852
853 ofpmp_init(&replies, request);
854 error = ofproto_get_ipfix_stats(ofproto, true, &replies);
855
856 if (!error) {
857 ofconn_send_replies(ofconn, &replies);
858 } else {
859 ofpbuf_list_delete(&replies);
860 }
861
862 return error;
863 }
864
865 static enum ofperr
866 handle_ipfix_flow_stats_request(struct ofconn *ofconn,
867 const struct ofp_header *request)
868 {
869 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
870 struct ovs_list replies;
871 enum ofperr error;
872
873 ofpmp_init(&replies, request);
874 error = ofproto_get_ipfix_stats(ofproto, false, &replies);
875
876 if (!error) {
877 ofconn_send_replies(ofconn, &replies);
878 } else {
879 ofpbuf_list_delete(&replies);
880 }
881
882 return error;
883 }
884
885 static enum ofperr
886 handle_nxt_ct_flush_zone(struct ofconn *ofconn, const struct ofp_header *oh)
887 {
888 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
889 const struct nx_zone_id *nzi = ofpmsg_body(oh);
890
891 if (!is_all_zeros(nzi->zero, sizeof nzi->zero)) {
892 return OFPERR_NXBRC_MUST_BE_ZERO;
893 }
894
895 uint16_t zone = ntohs(nzi->zone_id);
896 if (ofproto->ofproto_class->ct_flush) {
897 ofproto->ofproto_class->ct_flush(ofproto, &zone);
898 } else {
899 return EOPNOTSUPP;
900 }
901
902 return 0;
903 }
904
905 void
906 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
907 {
908 flow_restore_wait = flow_restore_wait_db;
909 }
910
911 bool
912 ofproto_get_flow_restore_wait(void)
913 {
914 return flow_restore_wait;
915 }
916
917 \f
918 /* Spanning Tree Protocol (STP) configuration. */
919
920 /* Configures STP on 'ofproto' using the settings defined in 's'. If
921 * 's' is NULL, disables STP.
922 *
923 * Returns 0 if successful, otherwise a positive errno value. */
924 int
925 ofproto_set_stp(struct ofproto *ofproto,
926 const struct ofproto_stp_settings *s)
927 {
928 return (ofproto->ofproto_class->set_stp
929 ? ofproto->ofproto_class->set_stp(ofproto, s)
930 : EOPNOTSUPP);
931 }
932
933 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
934 * 'enabled' member of 's' is false, then the other members are not
935 * meaningful.
936 *
937 * Returns 0 if successful, otherwise a positive errno value. */
938 int
939 ofproto_get_stp_status(struct ofproto *ofproto,
940 struct ofproto_stp_status *s)
941 {
942 return (ofproto->ofproto_class->get_stp_status
943 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
944 : EOPNOTSUPP);
945 }
946
947 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
948 * in 's'. The caller is responsible for assigning STP port numbers
949 * (using the 'port_num' member in the range of 1 through 255, inclusive)
950 * and ensuring there are no duplicates. If the 's' is NULL, then STP
951 * is disabled on the port.
952 *
953 * Returns 0 if successful, otherwise a positive errno value.*/
954 int
955 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
956 const struct ofproto_port_stp_settings *s)
957 {
958 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
959 if (!ofport) {
960 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu32,
961 ofproto->name, ofp_port);
962 return ENODEV;
963 }
964
965 return (ofproto->ofproto_class->set_stp_port
966 ? ofproto->ofproto_class->set_stp_port(ofport, s)
967 : EOPNOTSUPP);
968 }
969
970 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
971 * 's'. If the 'enabled' member in 's' is false, then the other members
972 * are not meaningful.
973 *
974 * Returns 0 if successful, otherwise a positive errno value.*/
975 int
976 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
977 struct ofproto_port_stp_status *s)
978 {
979 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
980 if (!ofport) {
981 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
982 "port %"PRIu32, ofproto->name, ofp_port);
983 return ENODEV;
984 }
985
986 return (ofproto->ofproto_class->get_stp_port_status
987 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
988 : EOPNOTSUPP);
989 }
990
991 /* Retrieves STP port statistics of 'ofp_port' on 'ofproto' and stores it in
992 * 's'. If the 'enabled' member in 's' is false, then the other members
993 * are not meaningful.
994 *
995 * Returns 0 if successful, otherwise a positive errno value.*/
996 int
997 ofproto_port_get_stp_stats(struct ofproto *ofproto, ofp_port_t ofp_port,
998 struct ofproto_port_stp_stats *s)
999 {
1000 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1001 if (!ofport) {
1002 VLOG_WARN_RL(&rl, "%s: cannot get STP stats on nonexistent "
1003 "port %"PRIu32, ofproto->name, ofp_port);
1004 return ENODEV;
1005 }
1006
1007 return (ofproto->ofproto_class->get_stp_port_stats
1008 ? ofproto->ofproto_class->get_stp_port_stats(ofport, s)
1009 : EOPNOTSUPP);
1010 }
1011
1012 /* Rapid Spanning Tree Protocol (RSTP) configuration. */
1013
1014 /* Configures RSTP on 'ofproto' using the settings defined in 's'. If
1015 * 's' is NULL, disables RSTP.
1016 *
1017 * Returns 0 if successful, otherwise a positive errno value. */
1018 int
1019 ofproto_set_rstp(struct ofproto *ofproto,
1020 const struct ofproto_rstp_settings *s)
1021 {
1022 if (!ofproto->ofproto_class->set_rstp) {
1023 return EOPNOTSUPP;
1024 }
1025 ofproto->ofproto_class->set_rstp(ofproto, s);
1026 return 0;
1027 }
1028
1029 /* Retrieves RSTP status of 'ofproto' and stores it in 's'. If the
1030 * 'enabled' member of 's' is false, then the other members are not
1031 * meaningful.
1032 *
1033 * Returns 0 if successful, otherwise a positive errno value. */
1034 int
1035 ofproto_get_rstp_status(struct ofproto *ofproto,
1036 struct ofproto_rstp_status *s)
1037 {
1038 if (!ofproto->ofproto_class->get_rstp_status) {
1039 return EOPNOTSUPP;
1040 }
1041 ofproto->ofproto_class->get_rstp_status(ofproto, s);
1042 return 0;
1043 }
1044
1045 /* Configures RSTP on 'ofp_port' of 'ofproto' using the settings defined
1046 * in 's'. The caller is responsible for assigning RSTP port numbers
1047 * (using the 'port_num' member in the range of 1 through 255, inclusive)
1048 * and ensuring there are no duplicates. If the 's' is NULL, then RSTP
1049 * is disabled on the port.
1050 *
1051 * Returns 0 if successful, otherwise a positive errno value.*/
1052 int
1053 ofproto_port_set_rstp(struct ofproto *ofproto, ofp_port_t ofp_port,
1054 const struct ofproto_port_rstp_settings *s)
1055 {
1056 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1057 if (!ofport) {
1058 VLOG_WARN("%s: cannot configure RSTP on nonexistent port %"PRIu32,
1059 ofproto->name, ofp_port);
1060 return ENODEV;
1061 }
1062
1063 if (!ofproto->ofproto_class->set_rstp_port) {
1064 return EOPNOTSUPP;
1065 }
1066 ofproto->ofproto_class->set_rstp_port(ofport, s);
1067 return 0;
1068 }
1069
1070 /* Retrieves RSTP port status of 'ofp_port' on 'ofproto' and stores it in
1071 * 's'. If the 'enabled' member in 's' is false, then the other members
1072 * are not meaningful.
1073 *
1074 * Returns 0 if successful, otherwise a positive errno value.*/
1075 int
1076 ofproto_port_get_rstp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
1077 struct ofproto_port_rstp_status *s)
1078 {
1079 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1080 if (!ofport) {
1081 VLOG_WARN_RL(&rl, "%s: cannot get RSTP status on nonexistent "
1082 "port %"PRIu32, ofproto->name, ofp_port);
1083 return ENODEV;
1084 }
1085
1086 if (!ofproto->ofproto_class->get_rstp_port_status) {
1087 return EOPNOTSUPP;
1088 }
1089 ofproto->ofproto_class->get_rstp_port_status(ofport, s);
1090 return 0;
1091 }
1092 \f
1093 /* Queue DSCP configuration. */
1094
1095 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
1096 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
1097 * to implement QoS. Instead, it is used to implement features which require
1098 * knowledge of what queues exist on a port, and some basic information about
1099 * them.
1100 *
1101 * Returns 0 if successful, otherwise a positive errno value. */
1102 int
1103 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
1104 const struct ofproto_port_queue *queues,
1105 size_t n_queues)
1106 {
1107 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1108
1109 if (!ofport) {
1110 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu32,
1111 ofproto->name, ofp_port);
1112 return ENODEV;
1113 }
1114
1115 return (ofproto->ofproto_class->set_queues
1116 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
1117 : EOPNOTSUPP);
1118 }
1119 \f
1120 /* LLDP configuration. */
1121 void
1122 ofproto_port_set_lldp(struct ofproto *ofproto,
1123 ofp_port_t ofp_port,
1124 const struct smap *cfg)
1125 {
1126 struct ofport *ofport;
1127 int error;
1128
1129 ofport = ofproto_get_port(ofproto, ofp_port);
1130 if (!ofport) {
1131 VLOG_WARN("%s: cannot configure LLDP on nonexistent port %"PRIu32,
1132 ofproto->name, ofp_port);
1133 return;
1134 }
1135 error = (ofproto->ofproto_class->set_lldp
1136 ? ofproto->ofproto_class->set_lldp(ofport, cfg)
1137 : EOPNOTSUPP);
1138 if (error) {
1139 VLOG_WARN("%s: lldp configuration on port %"PRIu32" (%s) failed (%s)",
1140 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1141 ovs_strerror(error));
1142 }
1143 }
1144
1145 int
1146 ofproto_set_aa(struct ofproto *ofproto, void *aux OVS_UNUSED,
1147 const struct aa_settings *s)
1148 {
1149 if (!ofproto->ofproto_class->set_aa) {
1150 return EOPNOTSUPP;
1151 }
1152 ofproto->ofproto_class->set_aa(ofproto, s);
1153 return 0;
1154 }
1155
1156 int
1157 ofproto_aa_mapping_register(struct ofproto *ofproto, void *aux,
1158 const struct aa_mapping_settings *s)
1159 {
1160 if (!ofproto->ofproto_class->aa_mapping_set) {
1161 return EOPNOTSUPP;
1162 }
1163 ofproto->ofproto_class->aa_mapping_set(ofproto, aux, s);
1164 return 0;
1165 }
1166
1167 int
1168 ofproto_aa_mapping_unregister(struct ofproto *ofproto, void *aux)
1169 {
1170 if (!ofproto->ofproto_class->aa_mapping_unset) {
1171 return EOPNOTSUPP;
1172 }
1173 ofproto->ofproto_class->aa_mapping_unset(ofproto, aux);
1174 return 0;
1175 }
1176
1177 int
1178 ofproto_aa_vlan_get_queued(struct ofproto *ofproto,
1179 struct ovs_list *list)
1180 {
1181 if (!ofproto->ofproto_class->aa_vlan_get_queued) {
1182 return EOPNOTSUPP;
1183 }
1184 ofproto->ofproto_class->aa_vlan_get_queued(ofproto, list);
1185 return 0;
1186 }
1187
1188 unsigned int
1189 ofproto_aa_vlan_get_queue_size(struct ofproto *ofproto)
1190 {
1191 if (!ofproto->ofproto_class->aa_vlan_get_queue_size) {
1192 return EOPNOTSUPP;
1193 }
1194 return ofproto->ofproto_class->aa_vlan_get_queue_size(ofproto);
1195 }
1196
1197 /* Connectivity Fault Management configuration. */
1198
1199 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
1200 void
1201 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
1202 {
1203 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1204 if (ofport && ofproto->ofproto_class->set_cfm) {
1205 ofproto->ofproto_class->set_cfm(ofport, NULL);
1206 }
1207 }
1208
1209 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
1210 * basic configuration from the configuration members in 'cfm', and the remote
1211 * maintenance point ID from remote_mpid. Ignores the statistics members of
1212 * 'cfm'.
1213 *
1214 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
1215 void
1216 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
1217 const struct cfm_settings *s)
1218 {
1219 struct ofport *ofport;
1220 int error;
1221
1222 ofport = ofproto_get_port(ofproto, ofp_port);
1223 if (!ofport) {
1224 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu32,
1225 ofproto->name, ofp_port);
1226 return;
1227 }
1228
1229 /* XXX: For configuration simplicity, we only support one remote_mpid
1230 * outside of the CFM module. It's not clear if this is the correct long
1231 * term solution or not. */
1232 error = (ofproto->ofproto_class->set_cfm
1233 ? ofproto->ofproto_class->set_cfm(ofport, s)
1234 : EOPNOTSUPP);
1235 if (error) {
1236 VLOG_WARN("%s: CFM configuration on port %"PRIu32" (%s) failed (%s)",
1237 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1238 ovs_strerror(error));
1239 }
1240 }
1241
1242 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
1243 * 'ofproto' does not have a port 'ofp_port'. */
1244 void
1245 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
1246 const struct smap *cfg)
1247 {
1248 struct ofport *ofport;
1249 int error;
1250
1251 ofport = ofproto_get_port(ofproto, ofp_port);
1252 if (!ofport) {
1253 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu32,
1254 ofproto->name, ofp_port);
1255 return;
1256 }
1257
1258 error = (ofproto->ofproto_class->set_bfd
1259 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
1260 : EOPNOTSUPP);
1261 if (error) {
1262 VLOG_WARN("%s: bfd configuration on port %"PRIu32" (%s) failed (%s)",
1263 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1264 ovs_strerror(error));
1265 }
1266 }
1267
1268 /* Checks the status change of BFD on 'ofport'.
1269 *
1270 * Returns true if 'ofproto_class' does not support 'bfd_status_changed'. */
1271 bool
1272 ofproto_port_bfd_status_changed(struct ofproto *ofproto, ofp_port_t ofp_port)
1273 {
1274 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1275 return (ofport && ofproto->ofproto_class->bfd_status_changed
1276 ? ofproto->ofproto_class->bfd_status_changed(ofport)
1277 : true);
1278 }
1279
1280 /* Populates 'status' with the status of BFD on 'ofport'. Returns 0 on
1281 * success. Returns a positive errno otherwise. Has no effect if 'ofp_port'
1282 * is not an OpenFlow port in 'ofproto'.
1283 *
1284 * The caller must provide and own '*status'. */
1285 int
1286 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
1287 struct smap *status)
1288 {
1289 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1290 return (ofport && ofproto->ofproto_class->get_bfd_status
1291 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
1292 : EOPNOTSUPP);
1293 }
1294
1295 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
1296 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
1297 * 0 if LACP partner information is not current (generally indicating a
1298 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
1299 int
1300 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
1301 {
1302 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1303 return (ofport && ofproto->ofproto_class->port_is_lacp_current
1304 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
1305 : -1);
1306 }
1307
1308 int
1309 ofproto_port_get_lacp_stats(const struct ofport *port, struct lacp_slave_stats *stats)
1310 {
1311 struct ofproto *ofproto = port->ofproto;
1312 int error;
1313
1314 if (ofproto->ofproto_class->port_get_lacp_stats) {
1315 error = ofproto->ofproto_class->port_get_lacp_stats(port, stats);
1316 } else {
1317 error = EOPNOTSUPP;
1318 }
1319
1320 return error;
1321 }
1322 \f
1323 /* Bundles. */
1324
1325 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
1326 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
1327 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
1328 * configuration plus, if there is more than one slave, a bonding
1329 * configuration.
1330 *
1331 * If 'aux' is already registered then this function updates its configuration
1332 * to 's'. Otherwise, this function registers a new bundle.
1333 *
1334 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
1335 * port. */
1336 int
1337 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
1338 const struct ofproto_bundle_settings *s)
1339 {
1340 return (ofproto->ofproto_class->bundle_set
1341 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1342 : EOPNOTSUPP);
1343 }
1344
1345 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1346 * If no such bundle has been registered, this has no effect. */
1347 int
1348 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1349 {
1350 return ofproto_bundle_register(ofproto, aux, NULL);
1351 }
1352
1353 \f
1354 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1355 * If 'aux' is already registered then this function updates its configuration
1356 * to 's'. Otherwise, this function registers a new mirror. */
1357 int
1358 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1359 const struct ofproto_mirror_settings *s)
1360 {
1361 return (ofproto->ofproto_class->mirror_set
1362 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1363 : EOPNOTSUPP);
1364 }
1365
1366 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1367 * If no mirror has been registered, this has no effect. */
1368 int
1369 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1370 {
1371 return ofproto_mirror_register(ofproto, aux, NULL);
1372 }
1373
1374 /* Retrieves statistics from mirror associated with client data pointer
1375 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1376 * 'bytes', respectively. If a particular counters is not supported,
1377 * the appropriate argument is set to UINT64_MAX.
1378 */
1379 int
1380 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1381 uint64_t *packets, uint64_t *bytes)
1382 {
1383 if (!ofproto->ofproto_class->mirror_get_stats) {
1384 *packets = *bytes = UINT64_MAX;
1385 return EOPNOTSUPP;
1386 }
1387
1388 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1389 packets, bytes);
1390 }
1391
1392 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1393 * which all packets are flooded, instead of using MAC learning. If
1394 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1395 *
1396 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1397 * port. */
1398 int
1399 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1400 {
1401 return (ofproto->ofproto_class->set_flood_vlans
1402 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1403 : EOPNOTSUPP);
1404 }
1405
1406 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1407 * output for a mirror. */
1408 bool
1409 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1410 {
1411 return (ofproto->ofproto_class->is_mirror_output_bundle
1412 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1413 : false);
1414 }
1415 \f
1416 /* Configuration of OpenFlow tables. */
1417
1418 /* Returns the number of OpenFlow tables in 'ofproto'. */
1419 int
1420 ofproto_get_n_tables(const struct ofproto *ofproto)
1421 {
1422 return ofproto->n_tables;
1423 }
1424
1425 /* Returns the number of Controller visible OpenFlow tables
1426 * in 'ofproto'. This number will exclude Hidden tables.
1427 * This funtion's return value should be less or equal to that of
1428 * ofproto_get_n_tables() . */
1429 uint8_t
1430 ofproto_get_n_visible_tables(const struct ofproto *ofproto)
1431 {
1432 uint8_t n = ofproto->n_tables;
1433
1434 /* Count only non-hidden tables in the number of tables. (Hidden tables,
1435 * if present, are always at the end.) */
1436 while(n && (ofproto->tables[n - 1].flags & OFTABLE_HIDDEN)) {
1437 n--;
1438 }
1439
1440 return n;
1441 }
1442
1443 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1444 * settings from 's'. 'table_id' must be in the range 0 through the number of
1445 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1446 *
1447 * For read-only tables, only the name may be configured. */
1448 void
1449 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1450 const struct ofproto_table_settings *s)
1451 {
1452 struct oftable *table;
1453
1454 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1455 table = &ofproto->tables[table_id];
1456
1457 oftable_set_name(table, s->name);
1458
1459 if (table->flags & OFTABLE_READONLY) {
1460 return;
1461 }
1462
1463 if (classifier_set_prefix_fields(&table->cls,
1464 s->prefix_fields, s->n_prefix_fields)) {
1465 /* XXX: Trigger revalidation. */
1466 }
1467
1468 ovs_mutex_lock(&ofproto_mutex);
1469 unsigned int new_eviction = (s->enable_eviction
1470 ? table->eviction | EVICTION_CLIENT
1471 : table->eviction & ~EVICTION_CLIENT);
1472 oftable_configure_eviction(table, new_eviction, s->groups, s->n_groups);
1473 table->max_flows = s->max_flows;
1474 evict_rules_from_table(table);
1475 ovs_mutex_unlock(&ofproto_mutex);
1476 }
1477 \f
1478 bool
1479 ofproto_has_snoops(const struct ofproto *ofproto)
1480 {
1481 return connmgr_has_snoops(ofproto->connmgr);
1482 }
1483
1484 void
1485 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1486 {
1487 connmgr_get_snoops(ofproto->connmgr, snoops);
1488 }
1489
1490 /* Deletes 'rule' from 'ofproto'.
1491 *
1492 * Within an ofproto implementation, this function allows an ofproto
1493 * implementation to destroy any rules that remain when its ->destruct()
1494 * function is called. This function is not suitable for use elsewhere in an
1495 * ofproto implementation.
1496 *
1497 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1498 * Cycle" in ofproto-provider.h. */
1499 void
1500 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1501 OVS_EXCLUDED(ofproto_mutex)
1502 {
1503 /* This skips the ofmonitor and flow-removed notifications because the
1504 * switch is being deleted and any OpenFlow channels have been or soon will
1505 * be killed. */
1506 ovs_mutex_lock(&ofproto_mutex);
1507
1508 if (rule->state == RULE_INSERTED) {
1509 /* Make sure there is no postponed removal of the rule. */
1510 ovs_assert(cls_rule_visible_in_version(&rule->cr, OVS_VERSION_MAX));
1511
1512 if (!classifier_remove(&rule->ofproto->tables[rule->table_id].cls,
1513 &rule->cr)) {
1514 OVS_NOT_REACHED();
1515 }
1516 ofproto_rule_remove__(rule->ofproto, rule);
1517 if (ofproto->ofproto_class->rule_delete) {
1518 ofproto->ofproto_class->rule_delete(rule);
1519 }
1520
1521 /* This may not be the last reference to the rule. */
1522 ofproto_rule_unref(rule);
1523 }
1524 ovs_mutex_unlock(&ofproto_mutex);
1525 }
1526
1527 static void
1528 ofproto_flush__(struct ofproto *ofproto)
1529 OVS_EXCLUDED(ofproto_mutex)
1530 {
1531 struct oftable *table;
1532
1533 /* This will flush all datapath flows. */
1534 if (ofproto->ofproto_class->flush) {
1535 ofproto->ofproto_class->flush(ofproto);
1536 }
1537
1538 /* XXX: There is a small race window here, where new datapath flows can be
1539 * created by upcall handlers based on the existing flow table. We can not
1540 * call ofproto class flush while holding 'ofproto_mutex' to prevent this,
1541 * as then we could deadlock on syncing with the handler threads waiting on
1542 * the same mutex. */
1543
1544 ovs_mutex_lock(&ofproto_mutex);
1545 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1546 struct rule_collection rules;
1547 struct rule *rule;
1548
1549 if (table->flags & OFTABLE_HIDDEN) {
1550 continue;
1551 }
1552
1553 rule_collection_init(&rules);
1554
1555 CLS_FOR_EACH (rule, cr, &table->cls) {
1556 rule_collection_add(&rules, rule);
1557 }
1558 delete_flows__(&rules, OFPRR_DELETE, NULL);
1559 }
1560 /* XXX: Concurrent handler threads may insert new learned flows based on
1561 * learn actions of the now deleted flows right after we release
1562 * 'ofproto_mutex'. */
1563 ovs_mutex_unlock(&ofproto_mutex);
1564 }
1565
1566 static void
1567 ofproto_destroy__(struct ofproto *ofproto)
1568 OVS_EXCLUDED(ofproto_mutex)
1569 {
1570 struct oftable *table;
1571
1572 cmap_destroy(&ofproto->groups);
1573
1574 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1575 tun_metadata_free(ovsrcu_get_protected(struct tun_table *,
1576 &ofproto->metadata_tab));
1577
1578 ovs_mutex_lock(&ofproto->vl_mff_map.mutex);
1579 mf_vl_mff_map_clear(&ofproto->vl_mff_map);
1580 ovs_mutex_unlock(&ofproto->vl_mff_map.mutex);
1581 cmap_destroy(&ofproto->vl_mff_map.cmap);
1582 ovs_mutex_destroy(&ofproto->vl_mff_map.mutex);
1583
1584 free(ofproto->name);
1585 free(ofproto->type);
1586 free(ofproto->mfr_desc);
1587 free(ofproto->hw_desc);
1588 free(ofproto->sw_desc);
1589 free(ofproto->serial_desc);
1590 free(ofproto->dp_desc);
1591 hmap_destroy(&ofproto->ports);
1592 hmap_destroy(&ofproto->ofport_usage);
1593 shash_destroy(&ofproto->port_by_name);
1594 simap_destroy(&ofproto->ofp_requests);
1595
1596 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1597 oftable_destroy(table);
1598 }
1599 free(ofproto->tables);
1600
1601 ovs_assert(hindex_is_empty(&ofproto->cookies));
1602 hindex_destroy(&ofproto->cookies);
1603
1604 ovs_assert(hmap_is_empty(&ofproto->learned_cookies));
1605 hmap_destroy(&ofproto->learned_cookies);
1606
1607 ofproto->ofproto_class->dealloc(ofproto);
1608 }
1609
1610 /* Destroying rules is doubly deferred, must have 'ofproto' around for them.
1611 * - 1st we defer the removal of the rules from the classifier
1612 * - 2nd we defer the actual destruction of the rules. */
1613 static void
1614 ofproto_destroy_defer__(struct ofproto *ofproto)
1615 OVS_EXCLUDED(ofproto_mutex)
1616 {
1617 ovsrcu_postpone(ofproto_destroy__, ofproto);
1618 }
1619
1620 void
1621 ofproto_destroy(struct ofproto *p, bool del)
1622 OVS_EXCLUDED(ofproto_mutex)
1623 {
1624 struct ofport *ofport, *next_ofport;
1625 struct ofport_usage *usage;
1626
1627 if (!p) {
1628 return;
1629 }
1630
1631 if (p->meters) {
1632 meter_delete(p, 1, p->meter_features.max_meters);
1633 p->meter_features.max_meters = 0;
1634 free(p->meters);
1635 p->meters = NULL;
1636 }
1637
1638 ofproto_flush__(p);
1639 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1640 ofport_destroy(ofport, del);
1641 }
1642
1643 HMAP_FOR_EACH_POP (usage, hmap_node, &p->ofport_usage) {
1644 free(usage);
1645 }
1646
1647 p->ofproto_class->destruct(p);
1648
1649 /* We should not postpone this because it involves deleting a listening
1650 * socket which we may want to reopen soon. 'connmgr' may be used by other
1651 * threads only if they take the ofproto_mutex and read a non-NULL
1652 * 'ofproto->connmgr'. */
1653 ovs_mutex_lock(&ofproto_mutex);
1654 connmgr_destroy(p->connmgr);
1655 p->connmgr = NULL;
1656 ovs_mutex_unlock(&ofproto_mutex);
1657
1658 /* Destroying rules is deferred, must have 'ofproto' around for them. */
1659 ovsrcu_postpone(ofproto_destroy_defer__, p);
1660 }
1661
1662 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1663 * kernel datapath, for example, this destroys the datapath in the kernel, and
1664 * with the netdev-based datapath, it tears down the data structures that
1665 * represent the datapath.
1666 *
1667 * The datapath should not be currently open as an ofproto. */
1668 int
1669 ofproto_delete(const char *name, const char *type)
1670 {
1671 const struct ofproto_class *class = ofproto_class_find__(type);
1672 return (!class ? EAFNOSUPPORT
1673 : !class->del ? EACCES
1674 : class->del(type, name));
1675 }
1676
1677 static void
1678 process_port_change(struct ofproto *ofproto, int error, char *devname)
1679 {
1680 if (error == ENOBUFS) {
1681 reinit_ports(ofproto);
1682 } else if (!error) {
1683 update_port(ofproto, devname);
1684 free(devname);
1685 }
1686 }
1687
1688 int
1689 ofproto_type_run(const char *datapath_type)
1690 {
1691 const struct ofproto_class *class;
1692 int error;
1693
1694 datapath_type = ofproto_normalize_type(datapath_type);
1695 class = ofproto_class_find__(datapath_type);
1696
1697 error = class->type_run ? class->type_run(datapath_type) : 0;
1698 if (error && error != EAGAIN) {
1699 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1700 datapath_type, ovs_strerror(error));
1701 }
1702 return error;
1703 }
1704
1705 void
1706 ofproto_type_wait(const char *datapath_type)
1707 {
1708 const struct ofproto_class *class;
1709
1710 datapath_type = ofproto_normalize_type(datapath_type);
1711 class = ofproto_class_find__(datapath_type);
1712
1713 if (class->type_wait) {
1714 class->type_wait(datapath_type);
1715 }
1716 }
1717
1718 int
1719 ofproto_run(struct ofproto *p)
1720 {
1721 int error;
1722 uint64_t new_seq;
1723
1724 error = p->ofproto_class->run(p);
1725 if (error && error != EAGAIN) {
1726 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1727 }
1728
1729 /* Restore the eviction group heap invariant occasionally. */
1730 if (p->eviction_group_timer < time_msec()) {
1731 size_t i;
1732
1733 p->eviction_group_timer = time_msec() + 1000;
1734
1735 for (i = 0; i < p->n_tables; i++) {
1736 struct oftable *table = &p->tables[i];
1737 struct eviction_group *evg;
1738 struct rule *rule;
1739
1740 if (!table->eviction) {
1741 continue;
1742 }
1743
1744 if (table->n_flows > 100000) {
1745 static struct vlog_rate_limit count_rl =
1746 VLOG_RATE_LIMIT_INIT(1, 1);
1747 VLOG_WARN_RL(&count_rl, "Table %"PRIuSIZE" has an excessive"
1748 " number of rules: %d", i, table->n_flows);
1749 }
1750
1751 ovs_mutex_lock(&ofproto_mutex);
1752 CLS_FOR_EACH (rule, cr, &table->cls) {
1753 if (rule->idle_timeout || rule->hard_timeout) {
1754 if (!rule->eviction_group) {
1755 eviction_group_add_rule(rule);
1756 } else {
1757 heap_raw_change(&rule->evg_node,
1758 rule_eviction_priority(p, rule));
1759 }
1760 }
1761 }
1762
1763 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1764 heap_rebuild(&evg->rules);
1765 }
1766 ovs_mutex_unlock(&ofproto_mutex);
1767 }
1768 }
1769
1770 if (p->ofproto_class->port_poll) {
1771 char *devname;
1772
1773 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1774 process_port_change(p, error, devname);
1775 }
1776 }
1777
1778 new_seq = seq_read(connectivity_seq_get());
1779 if (new_seq != p->change_seq) {
1780 struct sset devnames;
1781 const char *devname;
1782 struct ofport *ofport;
1783
1784 /* Update OpenFlow port status for any port whose netdev has changed.
1785 *
1786 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1787 * destroyed, so it's not safe to update ports directly from the
1788 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1789 * need this two-phase approach. */
1790 sset_init(&devnames);
1791 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1792 uint64_t port_change_seq;
1793
1794 port_change_seq = netdev_get_change_seq(ofport->netdev);
1795 if (ofport->change_seq != port_change_seq) {
1796 ofport->change_seq = port_change_seq;
1797 sset_add(&devnames, netdev_get_name(ofport->netdev));
1798 }
1799 }
1800 SSET_FOR_EACH (devname, &devnames) {
1801 update_port(p, devname);
1802 }
1803 sset_destroy(&devnames);
1804
1805 p->change_seq = new_seq;
1806 }
1807
1808 connmgr_run(p->connmgr, handle_openflow);
1809
1810 return error;
1811 }
1812
1813 void
1814 ofproto_wait(struct ofproto *p)
1815 {
1816 p->ofproto_class->wait(p);
1817 if (p->ofproto_class->port_poll_wait) {
1818 p->ofproto_class->port_poll_wait(p);
1819 }
1820 seq_wait(connectivity_seq_get(), p->change_seq);
1821 connmgr_wait(p->connmgr);
1822 }
1823
1824 bool
1825 ofproto_is_alive(const struct ofproto *p)
1826 {
1827 return connmgr_has_controllers(p->connmgr);
1828 }
1829
1830 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1831 * memory_report(). */
1832 void
1833 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1834 {
1835 const struct oftable *table;
1836 unsigned int n_rules;
1837
1838 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1839
1840 n_rules = 0;
1841 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1842 n_rules += table->n_flows;
1843 }
1844 simap_increase(usage, "rules", n_rules);
1845
1846 if (ofproto->ofproto_class->get_memory_usage) {
1847 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1848 }
1849
1850 connmgr_get_memory_usage(ofproto->connmgr, usage);
1851 }
1852
1853 void
1854 ofproto_type_get_memory_usage(const char *datapath_type, struct simap *usage)
1855 {
1856 const struct ofproto_class *class;
1857
1858 datapath_type = ofproto_normalize_type(datapath_type);
1859 class = ofproto_class_find__(datapath_type);
1860
1861 if (class && class->type_get_memory_usage) {
1862 class->type_get_memory_usage(datapath_type, usage);
1863 }
1864 }
1865
1866 void
1867 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1868 struct shash *info)
1869 {
1870 connmgr_get_controller_info(ofproto->connmgr, info);
1871 }
1872
1873 void
1874 ofproto_free_ofproto_controller_info(struct shash *info)
1875 {
1876 connmgr_free_controller_info(info);
1877 }
1878
1879 /* Makes a deep copy of 'old' into 'port'. */
1880 void
1881 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1882 {
1883 port->name = xstrdup(old->name);
1884 port->type = xstrdup(old->type);
1885 port->ofp_port = old->ofp_port;
1886 }
1887
1888 /* Frees memory allocated to members of 'ofproto_port'.
1889 *
1890 * Do not call this function on an ofproto_port obtained from
1891 * ofproto_port_dump_next(): that function retains ownership of the data in the
1892 * ofproto_port. */
1893 void
1894 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1895 {
1896 free(ofproto_port->name);
1897 free(ofproto_port->type);
1898 }
1899
1900 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1901 *
1902 * This function provides no status indication. An error status for the entire
1903 * dump operation is provided when it is completed by calling
1904 * ofproto_port_dump_done().
1905 */
1906 void
1907 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1908 const struct ofproto *ofproto)
1909 {
1910 dump->ofproto = ofproto;
1911 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1912 &dump->state);
1913 }
1914
1915 /* Attempts to retrieve another port from 'dump', which must have been created
1916 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1917 * 'port' and returns true. On failure, returns false.
1918 *
1919 * Failure might indicate an actual error or merely that the last port has been
1920 * dumped. An error status for the entire dump operation is provided when it
1921 * is completed by calling ofproto_port_dump_done().
1922 *
1923 * The ofproto owns the data stored in 'port'. It will remain valid until at
1924 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1925 * ofproto_port_dump_done(). */
1926 bool
1927 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1928 struct ofproto_port *port)
1929 {
1930 const struct ofproto *ofproto = dump->ofproto;
1931
1932 if (dump->error) {
1933 return false;
1934 }
1935
1936 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1937 port);
1938 if (dump->error) {
1939 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1940 return false;
1941 }
1942 return true;
1943 }
1944
1945 /* Completes port table dump operation 'dump', which must have been created
1946 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1947 * error-free, otherwise a positive errno value describing the problem. */
1948 int
1949 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1950 {
1951 const struct ofproto *ofproto = dump->ofproto;
1952 if (!dump->error) {
1953 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1954 dump->state);
1955 }
1956 return dump->error == EOF ? 0 : dump->error;
1957 }
1958
1959 /* Returns the type to pass to netdev_open() when a datapath of type
1960 * 'datapath_type' has a port of type 'port_type', for a few special
1961 * cases when a netdev type differs from a port type. For example, when
1962 * using the userspace datapath, a port of type "internal" needs to be
1963 * opened as "tap".
1964 *
1965 * Returns either 'type' itself or a string literal, which must not be
1966 * freed. */
1967 const char *
1968 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1969 {
1970 const struct ofproto_class *class;
1971
1972 datapath_type = ofproto_normalize_type(datapath_type);
1973 class = ofproto_class_find__(datapath_type);
1974 if (!class) {
1975 return port_type;
1976 }
1977
1978 return (class->port_open_type
1979 ? class->port_open_type(datapath_type, port_type)
1980 : port_type);
1981 }
1982
1983 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1984 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1985 * the port's OpenFlow port number.
1986 *
1987 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1988 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1989 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1990 * 'ofp_portp' is non-null). */
1991 int
1992 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1993 ofp_port_t *ofp_portp)
1994 {
1995 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1996 int error;
1997
1998 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1999 if (!error) {
2000 const char *netdev_name = netdev_get_name(netdev);
2001
2002 simap_put(&ofproto->ofp_requests, netdev_name,
2003 ofp_to_u16(ofp_port));
2004 error = update_port(ofproto, netdev_name);
2005 }
2006 if (ofp_portp) {
2007 *ofp_portp = OFPP_NONE;
2008 if (!error) {
2009 struct ofproto_port ofproto_port;
2010
2011 error = ofproto_port_query_by_name(ofproto,
2012 netdev_get_name(netdev),
2013 &ofproto_port);
2014 if (!error) {
2015 *ofp_portp = ofproto_port.ofp_port;
2016 ofproto_port_destroy(&ofproto_port);
2017 }
2018 }
2019 }
2020 return error;
2021 }
2022
2023 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
2024 * initializes '*port' appropriately; on failure, returns a positive errno
2025 * value.
2026 *
2027 * The caller owns the data in 'ofproto_port' and must free it with
2028 * ofproto_port_destroy() when it is no longer needed. */
2029 int
2030 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
2031 struct ofproto_port *port)
2032 {
2033 int error;
2034
2035 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
2036 if (error) {
2037 memset(port, 0, sizeof *port);
2038 }
2039 return error;
2040 }
2041
2042 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
2043 * Returns 0 if successful, otherwise a positive errno. */
2044 int
2045 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
2046 {
2047 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2048 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
2049 struct simap_node *ofp_request_node;
2050 int error;
2051
2052 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
2053 if (ofp_request_node) {
2054 simap_delete(&ofproto->ofp_requests, ofp_request_node);
2055 }
2056
2057 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
2058 if (!error && ofport) {
2059 /* 'name' is the netdev's name and update_port() is going to close the
2060 * netdev. Just in case update_port() refers to 'name' after it
2061 * destroys 'ofport', make a copy of it around the update_port()
2062 * call. */
2063 char *devname = xstrdup(name);
2064 update_port(ofproto, devname);
2065 free(devname);
2066 }
2067 return error;
2068 }
2069
2070 /* Refreshes datapath configuration of port number 'ofp_port' in 'ofproto'.
2071 *
2072 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
2073 void
2074 ofproto_port_set_config(struct ofproto *ofproto, ofp_port_t ofp_port,
2075 const struct smap *cfg)
2076 {
2077 struct ofport *ofport;
2078 int error;
2079
2080 ofport = ofproto_get_port(ofproto, ofp_port);
2081 if (!ofport) {
2082 VLOG_WARN("%s: cannot configure datapath on nonexistent port %"PRIu32,
2083 ofproto->name, ofp_port);
2084 return;
2085 }
2086
2087 error = (ofproto->ofproto_class->port_set_config
2088 ? ofproto->ofproto_class->port_set_config(ofport, cfg)
2089 : EOPNOTSUPP);
2090 if (error) {
2091 VLOG_WARN("%s: datapath configuration on port %"PRIu32
2092 " (%s) failed (%s)",
2093 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
2094 ovs_strerror(error));
2095 }
2096 }
2097
2098
2099 static void
2100 flow_mod_init(struct ofputil_flow_mod *fm,
2101 const struct match *match, int priority,
2102 const struct ofpact *ofpacts, size_t ofpacts_len,
2103 enum ofp_flow_mod_command command)
2104 {
2105 *fm = (struct ofputil_flow_mod) {
2106 .match = *match,
2107 .priority = priority,
2108 .table_id = 0,
2109 .command = command,
2110 .buffer_id = UINT32_MAX,
2111 .out_port = OFPP_ANY,
2112 .out_group = OFPG_ANY,
2113 .ofpacts = CONST_CAST(struct ofpact *, ofpacts),
2114 .ofpacts_len = ofpacts_len,
2115 };
2116 }
2117
2118 static int
2119 simple_flow_mod(struct ofproto *ofproto,
2120 const struct match *match, int priority,
2121 const struct ofpact *ofpacts, size_t ofpacts_len,
2122 enum ofp_flow_mod_command command)
2123 {
2124 struct ofputil_flow_mod fm;
2125
2126 flow_mod_init(&fm, match, priority, ofpacts, ofpacts_len, command);
2127
2128 return handle_flow_mod__(ofproto, &fm, NULL);
2129 }
2130
2131 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
2132 * performs the 'n_actions' actions in 'actions'. The new flow will not
2133 * timeout.
2134 *
2135 * If cls_rule->priority is in the range of priorities supported by OpenFlow
2136 * (0...65535, inclusive) then the flow will be visible to OpenFlow
2137 * controllers; otherwise, it will be hidden.
2138 *
2139 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
2140 *
2141 * This is a helper function for in-band control and fail-open. */
2142 void
2143 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
2144 int priority,
2145 const struct ofpact *ofpacts, size_t ofpacts_len)
2146 OVS_EXCLUDED(ofproto_mutex)
2147 {
2148 const struct rule *rule;
2149 bool must_add;
2150
2151 /* First do a cheap check whether the rule we're looking for already exists
2152 * with the actions that we want. If it does, then we're done. */
2153 rule = rule_from_cls_rule(classifier_find_match_exactly(
2154 &ofproto->tables[0].cls, match, priority,
2155 OVS_VERSION_MAX));
2156 if (rule) {
2157 const struct rule_actions *actions = rule_get_actions(rule);
2158 must_add = !ofpacts_equal(actions->ofpacts, actions->ofpacts_len,
2159 ofpacts, ofpacts_len);
2160 } else {
2161 must_add = true;
2162 }
2163
2164 /* If there's no such rule or the rule doesn't have the actions we want,
2165 * fall back to a executing a full flow mod. We can't optimize this at
2166 * all because we didn't take enough locks above to ensure that the flow
2167 * table didn't already change beneath us. */
2168 if (must_add) {
2169 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
2170 OFPFC_MODIFY_STRICT);
2171 }
2172 }
2173
2174 /* Executes the flow modification specified in 'fm'. Returns 0 on success, or
2175 * an OFPERR_* OpenFlow error code on failure.
2176 *
2177 * This is a helper function for in-band control and fail-open. */
2178 enum ofperr
2179 ofproto_flow_mod(struct ofproto *ofproto, const struct ofputil_flow_mod *fm)
2180 OVS_EXCLUDED(ofproto_mutex)
2181 {
2182 return handle_flow_mod__(ofproto, fm, NULL);
2183 }
2184
2185 /* Searches for a rule with matching criteria exactly equal to 'target' in
2186 * ofproto's table 0 and, if it finds one, deletes it.
2187 *
2188 * This is a helper function for in-band control and fail-open. */
2189 void
2190 ofproto_delete_flow(struct ofproto *ofproto,
2191 const struct match *target, int priority)
2192 OVS_REQUIRES(ofproto_mutex)
2193 {
2194 struct classifier *cls = &ofproto->tables[0].cls;
2195 struct rule *rule;
2196
2197 /* First do a cheap check whether the rule we're looking for has already
2198 * been deleted. If so, then we're done. */
2199 rule = rule_from_cls_rule(classifier_find_match_exactly(
2200 cls, target, priority, OVS_VERSION_MAX));
2201 if (!rule) {
2202 return;
2203 }
2204
2205 struct rule_collection rules;
2206
2207 rule_collection_init(&rules);
2208 rule_collection_add(&rules, rule);
2209 delete_flows__(&rules, OFPRR_DELETE, NULL);
2210 rule_collection_destroy(&rules);
2211 }
2212
2213 /* Delete all of the flows from all of ofproto's flow tables, then reintroduce
2214 * the flows required by in-band control and fail-open. */
2215 void
2216 ofproto_flush_flows(struct ofproto *ofproto)
2217 {
2218 COVERAGE_INC(ofproto_flush);
2219 ofproto_flush__(ofproto);
2220 connmgr_flushed(ofproto->connmgr);
2221 }
2222 \f
2223 static void
2224 reinit_ports(struct ofproto *p)
2225 {
2226 struct ofproto_port_dump dump;
2227 struct sset devnames;
2228 struct ofport *ofport;
2229 struct ofproto_port ofproto_port;
2230 const char *devname;
2231
2232 COVERAGE_INC(ofproto_reinit_ports);
2233
2234 sset_init(&devnames);
2235 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2236 sset_add(&devnames, netdev_get_name(ofport->netdev));
2237 }
2238 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2239 sset_add(&devnames, ofproto_port.name);
2240 }
2241
2242 SSET_FOR_EACH (devname, &devnames) {
2243 update_port(p, devname);
2244 }
2245 sset_destroy(&devnames);
2246 }
2247
2248 static ofp_port_t
2249 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
2250 {
2251 uint16_t port_idx;
2252
2253 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
2254 port_idx = port_idx ? port_idx : UINT16_MAX;
2255
2256 if (port_idx >= ofproto->max_ports
2257 || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
2258 uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
2259 long long int last_used_at, lru = LLONG_MAX;
2260
2261 /* Search for a free OpenFlow port number. We try not to
2262 * immediately reuse them to prevent problems due to old
2263 * flows.
2264 *
2265 * We limit the automatically assigned port numbers to the lower half
2266 * of the port range, to reserve the upper half for assignment by
2267 * controllers. */
2268 for (;;) {
2269 if (++ofproto->alloc_port_no >= MIN(ofproto->max_ports, 32768)) {
2270 ofproto->alloc_port_no = 1;
2271 }
2272 last_used_at = ofport_get_usage(ofproto,
2273 u16_to_ofp(ofproto->alloc_port_no));
2274 if (!last_used_at) {
2275 port_idx = ofproto->alloc_port_no;
2276 break;
2277 } else if ( last_used_at < time_msec() - 60*60*1000) {
2278 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
2279 * more than an hour ago, consider it usable. */
2280 ofport_remove_usage(ofproto,
2281 u16_to_ofp(ofproto->alloc_port_no));
2282 port_idx = ofproto->alloc_port_no;
2283 break;
2284 } else if (last_used_at < lru) {
2285 lru = last_used_at;
2286 lru_ofport = ofproto->alloc_port_no;
2287 }
2288
2289 if (ofproto->alloc_port_no == end_port_no) {
2290 if (lru_ofport) {
2291 port_idx = lru_ofport;
2292 break;
2293 }
2294 return OFPP_NONE;
2295 }
2296 }
2297 }
2298 ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
2299 return u16_to_ofp(port_idx);
2300 }
2301
2302 static void
2303 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2304 {
2305 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2306 ofport_set_usage(ofproto, ofp_port, time_msec());
2307 }
2308 }
2309
2310 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2311 * pointer if the netdev cannot be opened. On success, also fills in
2312 * '*pp'. */
2313 static struct netdev *
2314 ofport_open(struct ofproto *ofproto,
2315 struct ofproto_port *ofproto_port,
2316 struct ofputil_phy_port *pp)
2317 {
2318 enum netdev_flags flags;
2319 struct netdev *netdev;
2320 int error;
2321
2322 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2323 if (error) {
2324 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu32") because netdev %s "
2325 "cannot be opened (%s)",
2326 ofproto->name,
2327 ofproto_port->name, ofproto_port->ofp_port,
2328 ofproto_port->name, ovs_strerror(error));
2329 return NULL;
2330 }
2331
2332 if (ofproto_port->ofp_port == OFPP_NONE) {
2333 if (!strcmp(ofproto->name, ofproto_port->name)) {
2334 ofproto_port->ofp_port = OFPP_LOCAL;
2335 } else {
2336 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2337 ofproto_port->name);
2338 }
2339 }
2340 pp->port_no = ofproto_port->ofp_port;
2341 netdev_get_etheraddr(netdev, &pp->hw_addr);
2342 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2343 netdev_get_flags(netdev, &flags);
2344 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2345 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2346 netdev_get_features(netdev, &pp->curr, &pp->advertised,
2347 &pp->supported, &pp->peer);
2348 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2349 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2350
2351 return netdev;
2352 }
2353
2354 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
2355 * port number, and 'config' bits other than OFPUTIL_PC_PORT_DOWN are
2356 * disregarded. */
2357 static bool
2358 ofport_equal(const struct ofputil_phy_port *a,
2359 const struct ofputil_phy_port *b)
2360 {
2361 return (eth_addr_equals(a->hw_addr, b->hw_addr)
2362 && a->state == b->state
2363 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2364 && a->curr == b->curr
2365 && a->advertised == b->advertised
2366 && a->supported == b->supported
2367 && a->peer == b->peer
2368 && a->curr_speed == b->curr_speed
2369 && a->max_speed == b->max_speed);
2370 }
2371
2372 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2373 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2374 * one with the same name or port number). */
2375 static int
2376 ofport_install(struct ofproto *p,
2377 struct netdev *netdev, const struct ofputil_phy_port *pp)
2378 {
2379 const char *netdev_name = netdev_get_name(netdev);
2380 struct ofport *ofport;
2381 int error;
2382
2383 /* Create ofport. */
2384 ofport = p->ofproto_class->port_alloc();
2385 if (!ofport) {
2386 error = ENOMEM;
2387 goto error;
2388 }
2389 ofport->ofproto = p;
2390 ofport->netdev = netdev;
2391 ofport->change_seq = netdev_get_change_seq(netdev);
2392 ofport->pp = *pp;
2393 ofport->ofp_port = pp->port_no;
2394 ofport->created = time_msec();
2395
2396 /* Add port to 'p'. */
2397 hmap_insert(&p->ports, &ofport->hmap_node,
2398 hash_ofp_port(ofport->ofp_port));
2399 shash_add(&p->port_by_name, netdev_name, ofport);
2400
2401 update_mtu(p, ofport);
2402
2403 /* Let the ofproto_class initialize its private data. */
2404 error = p->ofproto_class->port_construct(ofport);
2405 if (error) {
2406 goto error;
2407 }
2408 connmgr_send_port_status(p->connmgr, NULL, pp, OFPPR_ADD);
2409 return 0;
2410
2411 error:
2412 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2413 p->name, netdev_name, ovs_strerror(error));
2414 if (ofport) {
2415 ofport_destroy__(ofport);
2416 } else {
2417 netdev_close(netdev);
2418 }
2419 return error;
2420 }
2421
2422 /* Removes 'ofport' from 'p' and destroys it. */
2423 static void
2424 ofport_remove(struct ofport *ofport)
2425 {
2426 struct ofproto *p = ofport->ofproto;
2427 bool is_mtu_overridden = ofport_is_mtu_overridden(p, ofport);
2428
2429 connmgr_send_port_status(ofport->ofproto->connmgr, NULL, &ofport->pp,
2430 OFPPR_DELETE);
2431 ofport_destroy(ofport, true);
2432 if (!is_mtu_overridden) {
2433 update_mtu_ofproto(p);
2434 }
2435 }
2436
2437 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2438 * destroys it. */
2439 static void
2440 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2441 {
2442 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2443 if (port) {
2444 ofport_remove(port);
2445 }
2446 }
2447
2448 /* Updates 'port' with new 'pp' description.
2449 *
2450 * Does not handle a name or port number change. The caller must implement
2451 * such a change as a delete followed by an add. */
2452 static void
2453 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2454 {
2455 port->pp.hw_addr = pp->hw_addr;
2456 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2457 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2458 port->pp.state = ((port->pp.state & ~OFPUTIL_PS_LINK_DOWN)
2459 | (pp->state & OFPUTIL_PS_LINK_DOWN));
2460 port->pp.curr = pp->curr;
2461 port->pp.advertised = pp->advertised;
2462 port->pp.supported = pp->supported;
2463 port->pp.peer = pp->peer;
2464 port->pp.curr_speed = pp->curr_speed;
2465 port->pp.max_speed = pp->max_speed;
2466
2467 connmgr_send_port_status(port->ofproto->connmgr, NULL,
2468 &port->pp, OFPPR_MODIFY);
2469 }
2470
2471 /* Update OpenFlow 'state' in 'port' and notify controller. */
2472 void
2473 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2474 {
2475 if (port->pp.state != state) {
2476 port->pp.state = state;
2477 connmgr_send_port_status(port->ofproto->connmgr, NULL,
2478 &port->pp, OFPPR_MODIFY);
2479 }
2480 }
2481
2482 void
2483 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2484 {
2485 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2486 if (port) {
2487 if (port->ofproto->ofproto_class->set_stp_port) {
2488 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2489 }
2490 if (port->ofproto->ofproto_class->set_rstp_port) {
2491 port->ofproto->ofproto_class->set_rstp_port(port, NULL);
2492 }
2493 if (port->ofproto->ofproto_class->set_cfm) {
2494 port->ofproto->ofproto_class->set_cfm(port, NULL);
2495 }
2496 if (port->ofproto->ofproto_class->bundle_remove) {
2497 port->ofproto->ofproto_class->bundle_remove(port);
2498 }
2499 }
2500 }
2501
2502 static void
2503 ofport_destroy__(struct ofport *port)
2504 {
2505 struct ofproto *ofproto = port->ofproto;
2506 const char *name = netdev_get_name(port->netdev);
2507
2508 hmap_remove(&ofproto->ports, &port->hmap_node);
2509 shash_delete(&ofproto->port_by_name,
2510 shash_find(&ofproto->port_by_name, name));
2511
2512 netdev_close(port->netdev);
2513 ofproto->ofproto_class->port_dealloc(port);
2514 }
2515
2516 static void
2517 ofport_destroy(struct ofport *port, bool del)
2518 {
2519 if (port) {
2520 dealloc_ofp_port(port->ofproto, port->ofp_port);
2521 port->ofproto->ofproto_class->port_destruct(port, del);
2522 ofport_destroy__(port);
2523 }
2524 }
2525
2526 struct ofport *
2527 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2528 {
2529 struct ofport *port;
2530
2531 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2532 &ofproto->ports) {
2533 if (port->ofp_port == ofp_port) {
2534 return port;
2535 }
2536 }
2537 return NULL;
2538 }
2539
2540 static long long int
2541 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2542 {
2543 struct ofport_usage *usage;
2544
2545 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2546 &ofproto->ofport_usage) {
2547 if (usage->ofp_port == ofp_port) {
2548 return usage->last_used;
2549 }
2550 }
2551 return 0;
2552 }
2553
2554 static void
2555 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2556 long long int last_used)
2557 {
2558 struct ofport_usage *usage;
2559 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2560 &ofproto->ofport_usage) {
2561 if (usage->ofp_port == ofp_port) {
2562 usage->last_used = last_used;
2563 return;
2564 }
2565 }
2566 ovs_assert(last_used == LLONG_MAX);
2567
2568 usage = xmalloc(sizeof *usage);
2569 usage->ofp_port = ofp_port;
2570 usage->last_used = last_used;
2571 hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2572 hash_ofp_port(ofp_port));
2573 }
2574
2575 static void
2576 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2577 {
2578 struct ofport_usage *usage;
2579 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2580 &ofproto->ofport_usage) {
2581 if (usage->ofp_port == ofp_port) {
2582 hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2583 free(usage);
2584 break;
2585 }
2586 }
2587 }
2588
2589 int
2590 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2591 {
2592 struct ofproto *ofproto = port->ofproto;
2593 int error;
2594
2595 if (ofproto->ofproto_class->port_get_stats) {
2596 error = ofproto->ofproto_class->port_get_stats(port, stats);
2597 } else {
2598 error = EOPNOTSUPP;
2599 }
2600
2601 return error;
2602 }
2603
2604 static int
2605 update_port(struct ofproto *ofproto, const char *name)
2606 {
2607 struct ofproto_port ofproto_port;
2608 struct ofputil_phy_port pp;
2609 struct netdev *netdev;
2610 struct ofport *port;
2611 int error = 0;
2612
2613 COVERAGE_INC(ofproto_update_port);
2614
2615 /* Fetch 'name''s location and properties from the datapath. */
2616 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2617 ? ofport_open(ofproto, &ofproto_port, &pp)
2618 : NULL);
2619
2620 if (netdev) {
2621 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2622 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2623 struct netdev *old_netdev = port->netdev;
2624
2625 /* 'name' hasn't changed location. Any properties changed? */
2626 if (!ofport_equal(&port->pp, &pp)) {
2627 ofport_modified(port, &pp);
2628 }
2629
2630 update_mtu(ofproto, port);
2631
2632 /* Install the newly opened netdev in case it has changed.
2633 * Don't close the old netdev yet in case port_modified has to
2634 * remove a retained reference to it.*/
2635 port->netdev = netdev;
2636 port->change_seq = netdev_get_change_seq(netdev);
2637
2638 if (port->ofproto->ofproto_class->port_modified) {
2639 port->ofproto->ofproto_class->port_modified(port);
2640 }
2641
2642 netdev_close(old_netdev);
2643 } else {
2644 /* If 'port' is nonnull then its name differs from 'name' and thus
2645 * we should delete it. If we think there's a port named 'name'
2646 * then its port number must be wrong now so delete it too. */
2647 if (port) {
2648 ofport_remove(port);
2649 }
2650 ofport_remove_with_name(ofproto, name);
2651 error = ofport_install(ofproto, netdev, &pp);
2652 }
2653 } else {
2654 /* Any port named 'name' is gone now. */
2655 ofport_remove_with_name(ofproto, name);
2656 }
2657 ofproto_port_destroy(&ofproto_port);
2658
2659 return error;
2660 }
2661
2662 static int
2663 init_ports(struct ofproto *p)
2664 {
2665 struct ofproto_port_dump dump;
2666 struct ofproto_port ofproto_port;
2667 struct shash_node *node, *next;
2668
2669 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2670 const char *name = ofproto_port.name;
2671
2672 if (shash_find(&p->port_by_name, name)) {
2673 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2674 p->name, name);
2675 } else {
2676 struct ofputil_phy_port pp;
2677 struct netdev *netdev;
2678
2679 /* Check if an OpenFlow port number had been requested. */
2680 node = shash_find(&init_ofp_ports, name);
2681 if (node) {
2682 const struct iface_hint *iface_hint = node->data;
2683 simap_put(&p->ofp_requests, name,
2684 ofp_to_u16(iface_hint->ofp_port));
2685 }
2686
2687 netdev = ofport_open(p, &ofproto_port, &pp);
2688 if (netdev) {
2689 ofport_install(p, netdev, &pp);
2690 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2691 p->alloc_port_no = MAX(p->alloc_port_no,
2692 ofp_to_u16(ofproto_port.ofp_port));
2693 }
2694 }
2695 }
2696 }
2697
2698 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2699 struct iface_hint *iface_hint = node->data;
2700
2701 if (!strcmp(iface_hint->br_name, p->name)) {
2702 free(iface_hint->br_name);
2703 free(iface_hint->br_type);
2704 free(iface_hint);
2705 shash_delete(&init_ofp_ports, node);
2706 }
2707 }
2708
2709 return 0;
2710 }
2711
2712 static bool
2713 ofport_is_internal(const struct ofproto *p, const struct ofport *port)
2714 {
2715 return !strcmp(netdev_get_type(port->netdev),
2716 ofproto_port_open_type(p->type, "internal"));
2717 }
2718
2719 /* If 'port' is internal and if the user didn't explicitly specify an mtu
2720 * through the database, we have to override it. */
2721 static bool
2722 ofport_is_mtu_overridden(const struct ofproto *p, const struct ofport *port)
2723 {
2724 return ofport_is_internal(p, port)
2725 && !netdev_mtu_is_user_config(port->netdev);
2726 }
2727
2728 /* Find the minimum MTU of all non-overridden devices attached to 'p'.
2729 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2730 static int
2731 find_min_mtu(struct ofproto *p)
2732 {
2733 struct ofport *ofport;
2734 int mtu = 0;
2735
2736 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2737 struct netdev *netdev = ofport->netdev;
2738 int dev_mtu;
2739
2740 /* Skip any overridden port, since that's what we're trying to set. */
2741 if (ofport_is_mtu_overridden(p, ofport)) {
2742 continue;
2743 }
2744
2745 if (netdev_get_mtu(netdev, &dev_mtu)) {
2746 continue;
2747 }
2748 if (!mtu || dev_mtu < mtu) {
2749 mtu = dev_mtu;
2750 }
2751 }
2752
2753 return mtu ? mtu: ETH_PAYLOAD_MAX;
2754 }
2755
2756 /* Update MTU of all overridden devices on 'p' to the minimum of the
2757 * non-overridden ports in event of 'port' added or changed. */
2758 static void
2759 update_mtu(struct ofproto *p, struct ofport *port)
2760 {
2761 struct netdev *netdev = port->netdev;
2762 int dev_mtu;
2763
2764 if (netdev_get_mtu(netdev, &dev_mtu)) {
2765 port->mtu = 0;
2766 return;
2767 }
2768 if (ofport_is_mtu_overridden(p, port)) {
2769 if (dev_mtu > p->min_mtu) {
2770 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2771 dev_mtu = p->min_mtu;
2772 }
2773 }
2774 port->mtu = dev_mtu;
2775 return;
2776 }
2777
2778 port->mtu = dev_mtu;
2779 /* For non-overridden port find new min mtu. */
2780
2781 update_mtu_ofproto(p);
2782 }
2783
2784 static void
2785 update_mtu_ofproto(struct ofproto *p)
2786 {
2787 struct ofport *ofport;
2788 int old_min = p->min_mtu;
2789
2790 p->min_mtu = find_min_mtu(p);
2791 if (p->min_mtu == old_min) {
2792 return;
2793 }
2794
2795 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2796 struct netdev *netdev = ofport->netdev;
2797
2798 if (ofport_is_mtu_overridden(p, ofport)) {
2799 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2800 ofport->mtu = p->min_mtu;
2801 }
2802 }
2803 }
2804 }
2805 \f
2806 static void
2807 ofproto_rule_destroy__(struct rule *rule)
2808 OVS_NO_THREAD_SAFETY_ANALYSIS
2809 {
2810 cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2811 rule_actions_destroy(rule_get_actions(rule));
2812 ovs_mutex_destroy(&rule->mutex);
2813 rule->ofproto->ofproto_class->rule_dealloc(rule);
2814 }
2815
2816 static void
2817 rule_destroy_cb(struct rule *rule)
2818 OVS_NO_THREAD_SAFETY_ANALYSIS
2819 {
2820 /* Send rule removed if needed. */
2821 if (rule->flags & OFPUTIL_FF_SEND_FLOW_REM
2822 && rule->removed_reason != OVS_OFPRR_NONE
2823 && !rule_is_hidden(rule)) {
2824 ofproto_rule_send_removed(rule);
2825 }
2826 rule->ofproto->ofproto_class->rule_destruct(rule);
2827 ofproto_rule_destroy__(rule);
2828 }
2829
2830 void
2831 ofproto_rule_ref(struct rule *rule)
2832 {
2833 if (rule) {
2834 ovs_refcount_ref(&rule->ref_count);
2835 }
2836 }
2837
2838 bool
2839 ofproto_rule_try_ref(struct rule *rule)
2840 {
2841 if (rule) {
2842 return ovs_refcount_try_ref_rcu(&rule->ref_count);
2843 }
2844 return false;
2845 }
2846
2847 /* Decrements 'rule''s ref_count and schedules 'rule' to be destroyed if the
2848 * ref_count reaches 0.
2849 *
2850 * Use of RCU allows short term use (between RCU quiescent periods) without
2851 * keeping a reference. A reference must be taken if the rule needs to
2852 * stay around accross the RCU quiescent periods. */
2853 void
2854 ofproto_rule_unref(struct rule *rule)
2855 {
2856 if (rule && ovs_refcount_unref_relaxed(&rule->ref_count) == 1) {
2857 ovs_assert(rule->state != RULE_INSERTED);
2858 ovsrcu_postpone(rule_destroy_cb, rule);
2859 }
2860 }
2861
2862 static void
2863 remove_rule_rcu__(struct rule *rule)
2864 OVS_REQUIRES(ofproto_mutex)
2865 {
2866 struct ofproto *ofproto = rule->ofproto;
2867 struct oftable *table = &ofproto->tables[rule->table_id];
2868
2869 ovs_assert(!cls_rule_visible_in_version(&rule->cr, OVS_VERSION_MAX));
2870 if (!classifier_remove(&table->cls, &rule->cr)) {
2871 OVS_NOT_REACHED();
2872 }
2873 if (ofproto->ofproto_class->rule_delete) {
2874 ofproto->ofproto_class->rule_delete(rule);
2875 }
2876 ofproto_rule_unref(rule);
2877 }
2878
2879 static void
2880 remove_rule_rcu(struct rule *rule)
2881 OVS_EXCLUDED(ofproto_mutex)
2882 {
2883 ovs_mutex_lock(&ofproto_mutex);
2884 remove_rule_rcu__(rule);
2885 ovs_mutex_unlock(&ofproto_mutex);
2886 }
2887
2888 /* Removes and deletes rules from a NULL-terminated array of rule pointers. */
2889 static void
2890 remove_rules_rcu(struct rule **rules)
2891 OVS_EXCLUDED(ofproto_mutex)
2892 {
2893 struct rule **orig_rules = rules;
2894
2895 if (*rules) {
2896 struct ofproto *ofproto = rules[0]->ofproto;
2897 unsigned long tables[BITMAP_N_LONGS(256)];
2898 struct rule *rule;
2899 size_t table_id;
2900
2901 memset(tables, 0, sizeof tables);
2902
2903 ovs_mutex_lock(&ofproto_mutex);
2904 while ((rule = *rules++)) {
2905 /* Defer once for each new table. This defers the subtable cleanup
2906 * until later, so that when removing large number of flows the
2907 * operation is faster. */
2908 if (!bitmap_is_set(tables, rule->table_id)) {
2909 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
2910
2911 bitmap_set1(tables, rule->table_id);
2912 classifier_defer(cls);
2913 }
2914 remove_rule_rcu__(rule);
2915 }
2916
2917 BITMAP_FOR_EACH_1(table_id, 256, tables) {
2918 struct classifier *cls = &ofproto->tables[table_id].cls;
2919
2920 classifier_publish(cls);
2921 }
2922 ovs_mutex_unlock(&ofproto_mutex);
2923 }
2924
2925 free(orig_rules);
2926 }
2927
2928 void
2929 ofproto_group_ref(struct ofgroup *group)
2930 {
2931 if (group) {
2932 ovs_refcount_ref(&group->ref_count);
2933 }
2934 }
2935
2936 bool
2937 ofproto_group_try_ref(struct ofgroup *group)
2938 {
2939 if (group) {
2940 return ovs_refcount_try_ref_rcu(&group->ref_count);
2941 }
2942 return false;
2943 }
2944
2945 static void
2946 group_destroy_cb(struct ofgroup *group)
2947 {
2948 group->ofproto->ofproto_class->group_destruct(group);
2949 ofputil_group_properties_destroy(CONST_CAST(struct ofputil_group_props *,
2950 &group->props));
2951 ofputil_bucket_list_destroy(CONST_CAST(struct ovs_list *,
2952 &group->buckets));
2953 group->ofproto->ofproto_class->group_dealloc(group);
2954 }
2955
2956 void
2957 ofproto_group_unref(struct ofgroup *group)
2958 OVS_NO_THREAD_SAFETY_ANALYSIS
2959 {
2960 if (group && ovs_refcount_unref_relaxed(&group->ref_count) == 1) {
2961 ovs_assert(rule_collection_n(&group->rules) == 0);
2962 ovsrcu_postpone(group_destroy_cb, group);
2963 }
2964 }
2965
2966 static void
2967 remove_group_rcu__(struct ofgroup *group)
2968 OVS_REQUIRES(ofproto_mutex)
2969 {
2970 struct ofproto *ofproto = group->ofproto;
2971
2972 ovs_assert(!versions_visible_in_version(&group->versions, OVS_VERSION_MAX));
2973
2974 cmap_remove(&ofproto->groups, &group->cmap_node,
2975 hash_int(group->group_id, 0));
2976 ofproto_group_unref(group);
2977 }
2978
2979 static void
2980 remove_group_rcu(struct ofgroup *group)
2981 OVS_EXCLUDED(ofproto_mutex)
2982 {
2983 ovs_mutex_lock(&ofproto_mutex);
2984 remove_group_rcu__(group);
2985 ovs_mutex_unlock(&ofproto_mutex);
2986 }
2987
2988 /* Removes and deletes groups from a NULL-terminated array of group
2989 * pointers. */
2990 static void
2991 remove_groups_rcu(struct ofgroup **groups)
2992 OVS_EXCLUDED(ofproto_mutex)
2993 {
2994 ovs_mutex_lock(&ofproto_mutex);
2995 for (struct ofgroup **g = groups; *g; g++) {
2996 remove_group_rcu__(*g);
2997 }
2998 ovs_mutex_unlock(&ofproto_mutex);
2999 free(groups);
3000 }
3001
3002 static uint32_t get_provider_meter_id(const struct ofproto *,
3003 uint32_t of_meter_id);
3004
3005 /* Creates and returns a new 'struct rule_actions', whose actions are a copy
3006 * of from the 'ofpacts_len' bytes of 'ofpacts'. */
3007 const struct rule_actions *
3008 rule_actions_create(const struct ofpact *ofpacts, size_t ofpacts_len)
3009 {
3010 struct rule_actions *actions;
3011
3012 actions = xmalloc(sizeof *actions + ofpacts_len);
3013 actions->ofpacts_len = ofpacts_len;
3014 memcpy(actions->ofpacts, ofpacts, ofpacts_len);
3015 actions->has_meter = ofpacts_get_meter(ofpacts, ofpacts_len) != 0;
3016 actions->has_groups =
3017 (ofpact_find_type_flattened(ofpacts, OFPACT_GROUP,
3018 ofpact_end(ofpacts, ofpacts_len))
3019 != NULL);
3020 actions->has_learn_with_delete = (next_learn_with_delete(actions, NULL)
3021 != NULL);
3022
3023 return actions;
3024 }
3025
3026 /* Free the actions after the RCU quiescent period is reached. */
3027 void
3028 rule_actions_destroy(const struct rule_actions *actions)
3029 {
3030 if (actions) {
3031 ovsrcu_postpone(free, CONST_CAST(struct rule_actions *, actions));
3032 }
3033 }
3034
3035 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
3036 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
3037 bool
3038 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
3039 OVS_REQUIRES(ofproto_mutex)
3040 {
3041 if (port == OFPP_ANY) {
3042 return true;
3043 } else {
3044 const struct rule_actions *actions = rule_get_actions(rule);
3045 return ofpacts_output_to_port(actions->ofpacts,
3046 actions->ofpacts_len, port);
3047 }
3048 }
3049
3050 /* Returns true if 'rule' has group and equals group_id. */
3051 static bool
3052 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
3053 OVS_REQUIRES(ofproto_mutex)
3054 {
3055 if (group_id == OFPG_ANY) {
3056 return true;
3057 } else {
3058 const struct rule_actions *actions = rule_get_actions(rule);
3059 return ofpacts_output_to_group(actions->ofpacts,
3060 actions->ofpacts_len, group_id);
3061 }
3062 }
3063
3064 static bool
3065 rule_is_readonly(const struct rule *rule)
3066 {
3067 const struct oftable *table = &rule->ofproto->tables[rule->table_id];
3068 return (table->flags & OFTABLE_READONLY) != 0;
3069 }
3070 \f
3071 static uint32_t
3072 hash_learned_cookie(ovs_be64 cookie_, uint8_t table_id)
3073 {
3074 uint64_t cookie = (OVS_FORCE uint64_t) cookie_;
3075 return hash_3words(cookie, cookie >> 32, table_id);
3076 }
3077
3078 static void
3079 learned_cookies_update_one__(struct ofproto *ofproto,
3080 const struct ofpact_learn *learn,
3081 int delta, struct ovs_list *dead_cookies)
3082 OVS_REQUIRES(ofproto_mutex)
3083 {
3084 uint32_t hash = hash_learned_cookie(learn->cookie, learn->table_id);
3085 struct learned_cookie *c;
3086
3087 HMAP_FOR_EACH_WITH_HASH (c, u.hmap_node, hash, &ofproto->learned_cookies) {
3088 if (c->cookie == learn->cookie && c->table_id == learn->table_id) {
3089 c->n += delta;
3090 ovs_assert(c->n >= 0);
3091
3092 if (!c->n) {
3093 hmap_remove(&ofproto->learned_cookies, &c->u.hmap_node);
3094 ovs_list_push_back(dead_cookies, &c->u.list_node);
3095 }
3096
3097 return;
3098 }
3099 }
3100
3101 ovs_assert(delta > 0);
3102 c = xmalloc(sizeof *c);
3103 hmap_insert(&ofproto->learned_cookies, &c->u.hmap_node, hash);
3104 c->cookie = learn->cookie;
3105 c->table_id = learn->table_id;
3106 c->n = delta;
3107 }
3108
3109 static const struct ofpact_learn *
3110 next_learn_with_delete(const struct rule_actions *actions,
3111 const struct ofpact_learn *start)
3112 {
3113 const struct ofpact *pos;
3114
3115 for (pos = start ? ofpact_next(&start->ofpact) : actions->ofpacts;
3116 pos < ofpact_end(actions->ofpacts, actions->ofpacts_len);
3117 pos = ofpact_next(pos)) {
3118 if (pos->type == OFPACT_LEARN) {
3119 const struct ofpact_learn *learn = ofpact_get_LEARN(pos);
3120 if (learn->flags & NX_LEARN_F_DELETE_LEARNED) {
3121 return learn;
3122 }
3123 }
3124 }
3125
3126 return NULL;
3127 }
3128
3129 static void
3130 learned_cookies_update__(struct ofproto *ofproto,
3131 const struct rule_actions *actions,
3132 int delta, struct ovs_list *dead_cookies)
3133 OVS_REQUIRES(ofproto_mutex)
3134 {
3135 if (actions->has_learn_with_delete) {
3136 const struct ofpact_learn *learn;
3137
3138 for (learn = next_learn_with_delete(actions, NULL); learn;
3139 learn = next_learn_with_delete(actions, learn)) {
3140 learned_cookies_update_one__(ofproto, learn, delta, dead_cookies);
3141 }
3142 }
3143 }
3144
3145 static void
3146 learned_cookies_inc(struct ofproto *ofproto,
3147 const struct rule_actions *actions)
3148 OVS_REQUIRES(ofproto_mutex)
3149 {
3150 learned_cookies_update__(ofproto, actions, +1, NULL);
3151 }
3152
3153 static void
3154 learned_cookies_dec(struct ofproto *ofproto,
3155 const struct rule_actions *actions,
3156 struct ovs_list *dead_cookies)
3157 OVS_REQUIRES(ofproto_mutex)
3158 {
3159 learned_cookies_update__(ofproto, actions, -1, dead_cookies);
3160 }
3161
3162 static void
3163 learned_cookies_flush(struct ofproto *ofproto, struct ovs_list *dead_cookies)
3164 OVS_REQUIRES(ofproto_mutex)
3165 {
3166 struct learned_cookie *c;
3167
3168 LIST_FOR_EACH_POP (c, u.list_node, dead_cookies) {
3169 struct rule_criteria criteria;
3170 struct rule_collection rules;
3171 struct match match;
3172
3173 match_init_catchall(&match);
3174 rule_criteria_init(&criteria, c->table_id, &match, 0, OVS_VERSION_MAX,
3175 c->cookie, OVS_BE64_MAX, OFPP_ANY, OFPG_ANY);
3176 rule_criteria_require_rw(&criteria, false);
3177 collect_rules_loose(ofproto, &criteria, &rules);
3178 rule_criteria_destroy(&criteria);
3179 delete_flows__(&rules, OFPRR_DELETE, NULL);
3180
3181 free(c);
3182 }
3183 }
3184 \f
3185 static enum ofperr
3186 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
3187 {
3188 ofconn_send_reply(ofconn, make_echo_reply(oh));
3189 return 0;
3190 }
3191
3192 static void
3193 query_tables(struct ofproto *ofproto,
3194 struct ofputil_table_features **featuresp,
3195 struct ofputil_table_stats **statsp)
3196 {
3197 struct mf_bitmap rw_fields = oxm_writable_fields();
3198 struct mf_bitmap match = oxm_matchable_fields();
3199 struct mf_bitmap mask = oxm_maskable_fields();
3200
3201 struct ofputil_table_features *features;
3202 struct ofputil_table_stats *stats;
3203 int i;
3204
3205 features = *featuresp = xcalloc(ofproto->n_tables, sizeof *features);
3206 for (i = 0; i < ofproto->n_tables; i++) {
3207 struct ofputil_table_features *f = &features[i];
3208
3209 f->table_id = i;
3210 sprintf(f->name, "table%d", i);
3211 f->metadata_match = OVS_BE64_MAX;
3212 f->metadata_write = OVS_BE64_MAX;
3213 atomic_read_relaxed(&ofproto->tables[i].miss_config, &f->miss_config);
3214 f->max_entries = 1000000;
3215
3216 bool more_tables = false;
3217 for (int j = i + 1; j < ofproto->n_tables; j++) {
3218 if (!(ofproto->tables[j].flags & OFTABLE_HIDDEN)) {
3219 bitmap_set1(f->nonmiss.next, j);
3220 more_tables = true;
3221 }
3222 }
3223 f->nonmiss.instructions = (1u << N_OVS_INSTRUCTIONS) - 1;
3224 if (!more_tables) {
3225 f->nonmiss.instructions &= ~(1u << OVSINST_OFPIT11_GOTO_TABLE);
3226 }
3227 f->nonmiss.write.ofpacts = (UINT64_C(1) << N_OFPACTS) - 1;
3228 f->nonmiss.write.set_fields = rw_fields;
3229 f->nonmiss.apply = f->nonmiss.write;
3230 f->miss = f->nonmiss;
3231
3232 f->match = match;
3233 f->mask = mask;
3234 f->wildcard = match;
3235 }
3236
3237 if (statsp) {
3238 stats = *statsp = xcalloc(ofproto->n_tables, sizeof *stats);
3239 for (i = 0; i < ofproto->n_tables; i++) {
3240 struct ofputil_table_stats *s = &stats[i];
3241
3242 s->table_id = i;
3243 s->active_count = ofproto->tables[i].n_flows;
3244 if (i == 0) {
3245 s->active_count -= connmgr_count_hidden_rules(
3246 ofproto->connmgr);
3247 }
3248 }
3249 } else {
3250 stats = NULL;
3251 }
3252
3253 ofproto->ofproto_class->query_tables(ofproto, features, stats);
3254
3255 for (i = 0; i < ofproto->n_tables; i++) {
3256 const struct oftable *table = &ofproto->tables[i];
3257 struct ofputil_table_features *f = &features[i];
3258
3259 if (table->name) {
3260 ovs_strzcpy(f->name, table->name, sizeof f->name);
3261 }
3262
3263 if (table->max_flows < f->max_entries) {
3264 f->max_entries = table->max_flows;
3265 }
3266 }
3267 }
3268
3269 static void
3270 query_switch_features(struct ofproto *ofproto,
3271 bool *arp_match_ip, uint64_t *ofpacts)
3272 {
3273 struct ofputil_table_features *features, *f;
3274
3275 *arp_match_ip = false;
3276 *ofpacts = 0;
3277
3278 query_tables(ofproto, &features, NULL);
3279 for (f = features; f < &features[ofproto->n_tables]; f++) {
3280 *ofpacts |= f->nonmiss.apply.ofpacts | f->miss.apply.ofpacts;
3281 if (bitmap_is_set(f->match.bm, MFF_ARP_SPA) ||
3282 bitmap_is_set(f->match.bm, MFF_ARP_TPA)) {
3283 *arp_match_ip = true;
3284 }
3285 }
3286 free(features);
3287
3288 /* Sanity check. */
3289 ovs_assert(*ofpacts & (UINT64_C(1) << OFPACT_OUTPUT));
3290 }
3291
3292 static enum ofperr
3293 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
3294 {
3295 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3296 struct ofputil_switch_features features;
3297 struct ofport *port;
3298 bool arp_match_ip;
3299 struct ofpbuf *b;
3300
3301 query_switch_features(ofproto, &arp_match_ip, &features.ofpacts);
3302
3303 features.datapath_id = ofproto->datapath_id;
3304 features.n_buffers = 0;
3305 features.n_tables = ofproto_get_n_visible_tables(ofproto);
3306 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
3307 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS |
3308 OFPUTIL_C_GROUP_STATS | OFPUTIL_C_BUNDLES);
3309 if (arp_match_ip) {
3310 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
3311 }
3312 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
3313 features.auxiliary_id = 0;
3314 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
3315 oh->xid);
3316 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3317 ofputil_put_switch_features_port(&port->pp, b);
3318 }
3319
3320 ofconn_send_reply(ofconn, b);
3321 return 0;
3322 }
3323
3324 static enum ofperr
3325 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
3326 {
3327 struct ofputil_switch_config config;
3328 config.frag = ofconn_get_ofproto(ofconn)->frag_handling;
3329 config.invalid_ttl_to_controller
3330 = ofconn_get_invalid_ttl_to_controller(ofconn);
3331 config.miss_send_len = ofconn_get_miss_send_len(ofconn);
3332
3333 ofconn_send_reply(ofconn, ofputil_encode_get_config_reply(oh, &config));
3334
3335 return 0;
3336 }
3337
3338 static enum ofperr
3339 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
3340 {
3341 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3342 struct ofputil_switch_config config;
3343 enum ofperr error;
3344
3345 error = ofputil_decode_set_config(oh, &config);
3346 if (error) {
3347 return error;
3348 }
3349
3350 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
3351 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
3352 enum ofputil_frag_handling cur = ofproto->frag_handling;
3353 enum ofputil_frag_handling next = config.frag;
3354
3355 if (cur != next) {
3356 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
3357 ofproto->frag_handling = next;
3358 } else {
3359 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
3360 ofproto->name,
3361 ofputil_frag_handling_to_string(next));
3362 }
3363 }
3364 }
3365
3366 if (config.invalid_ttl_to_controller >= 0) {
3367 ofconn_set_invalid_ttl_to_controller(ofconn,
3368 config.invalid_ttl_to_controller);
3369 }
3370
3371 ofconn_set_miss_send_len(ofconn, config.miss_send_len);
3372
3373 return 0;
3374 }
3375
3376 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
3377 * error message code for the caller to propagate upward. Otherwise, returns
3378 * 0.
3379 *
3380 * The log message mentions 'msg_type'. */
3381 static enum ofperr
3382 reject_slave_controller(struct ofconn *ofconn)
3383 {
3384 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
3385 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
3386 return OFPERR_OFPBRC_IS_SLAVE;
3387 } else {
3388 return 0;
3389 }
3390 }
3391
3392 /* Checks that the 'ofpacts_len' bytes of action in 'ofpacts' are appropriate
3393 * for 'ofproto':
3394 *
3395 * - If they use a meter, then 'ofproto' has that meter configured.
3396 *
3397 * - If they use any groups, then 'ofproto' has that group configured.
3398 *
3399 * Returns 0 if successful, otherwise an OpenFlow error. Caller must hold
3400 * 'ofproto_mutex' for the result to be valid also after this function
3401 * returns. */
3402 enum ofperr
3403 ofproto_check_ofpacts(struct ofproto *ofproto,
3404 const struct ofpact ofpacts[], size_t ofpacts_len)
3405 OVS_REQUIRES(ofproto_mutex)
3406 {
3407 uint32_t mid;
3408
3409 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
3410 if (mid && get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
3411 return OFPERR_OFPMMFC_INVALID_METER;
3412 }
3413
3414 const struct ofpact_group *a;
3415 OFPACT_FOR_EACH_TYPE_FLATTENED (a, GROUP, ofpacts, ofpacts_len) {
3416 if (!ofproto_group_exists(ofproto, a->group_id)) {
3417 return OFPERR_OFPBAC_BAD_OUT_GROUP;
3418 }
3419 }
3420
3421 return 0;
3422 }
3423
3424 void
3425 ofproto_packet_out_uninit(struct ofproto_packet_out *opo)
3426 {
3427 dp_packet_delete(opo->packet);
3428 opo->packet = NULL;
3429 free(opo->flow);
3430 opo->flow = NULL;
3431 free(opo->ofpacts);
3432 opo->ofpacts = NULL;
3433 opo->ofpacts_len = 0;
3434 ovs_assert(!opo->aux);
3435 }
3436
3437 /* Takes ownership of po->ofpacts, which must have been malloc'ed. */
3438 static enum ofperr
3439 ofproto_packet_out_init(struct ofproto *ofproto,
3440 struct ofconn *ofconn,
3441 struct ofproto_packet_out *opo,
3442 const struct ofputil_packet_out *po)
3443 {
3444 enum ofperr error;
3445
3446 if (ofp_to_u16(po->in_port) >= ofproto->max_ports
3447 && ofp_to_u16(po->in_port) < ofp_to_u16(OFPP_MAX)) {
3448 return OFPERR_OFPBRC_BAD_PORT;
3449 }
3450
3451 /* Get payload. */
3452 if (po->buffer_id != UINT32_MAX) {
3453 return OFPERR_OFPBRC_BUFFER_UNKNOWN;
3454 }
3455
3456 /* Ensure that the L3 header is 32-bit aligned. */
3457 opo->packet = dp_packet_clone_data_with_headroom(po->packet,
3458 po->packet_len, 2);
3459 /* Store struct flow. */
3460 opo->flow = xmalloc(sizeof *opo->flow);
3461 flow_extract(opo->packet, opo->flow);
3462 opo->flow->in_port.ofp_port = po->in_port;
3463
3464 /* Check actions like for flow mods. We pass a 'table_id' of 0 to
3465 * ofproto_check_consistency(), which isn't strictly correct because these
3466 * actions aren't in any table. This is OK as 'table_id' is only used to
3467 * check instructions (e.g., goto-table), which can't appear on the action
3468 * list of a packet-out. */
3469 error = ofpacts_check_consistency(po->ofpacts, po->ofpacts_len,
3470 opo->flow,
3471 u16_to_ofp(ofproto->max_ports), 0,
3472 ofproto->n_tables,
3473 ofconn_get_protocol(ofconn));
3474 if (error) {
3475 dp_packet_delete(opo->packet);
3476 free(opo->flow);
3477 return error;
3478 }
3479
3480 opo->ofpacts = po->ofpacts;
3481 opo->ofpacts_len = po->ofpacts_len;
3482
3483 opo->aux = NULL;
3484 return 0;
3485 }
3486
3487 static enum ofperr
3488 ofproto_packet_out_start(struct ofproto *ofproto,
3489 struct ofproto_packet_out *opo)
3490 OVS_REQUIRES(ofproto_mutex)
3491 {
3492 enum ofperr error;
3493
3494 error = ofproto_check_ofpacts(ofproto, opo->ofpacts, opo->ofpacts_len);
3495 if (error) {
3496 return error;
3497 }
3498
3499 return ofproto->ofproto_class->packet_xlate(ofproto, opo);
3500 }
3501
3502 static void
3503 ofproto_packet_out_revert(struct ofproto *ofproto,
3504 struct ofproto_packet_out *opo)
3505 OVS_REQUIRES(ofproto_mutex)
3506 {
3507 ofproto->ofproto_class->packet_xlate_revert(ofproto, opo);
3508 }
3509
3510 static void
3511 ofproto_packet_out_finish(struct ofproto *ofproto,
3512 struct ofproto_packet_out *opo)
3513 OVS_REQUIRES(ofproto_mutex)
3514 {
3515 ofproto->ofproto_class->packet_execute(ofproto, opo);
3516 }
3517
3518 static enum ofperr
3519 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
3520 OVS_EXCLUDED(ofproto_mutex)
3521 {
3522 struct ofproto *p = ofconn_get_ofproto(ofconn);
3523 struct ofputil_packet_out po;
3524 struct ofproto_packet_out opo;
3525 uint64_t ofpacts_stub[1024 / 8];
3526 struct ofpbuf ofpacts;
3527 enum ofperr error;
3528
3529 COVERAGE_INC(ofproto_packet_out);
3530
3531 error = reject_slave_controller(ofconn);
3532 if (error) {
3533 return error;
3534 }
3535
3536 /* Decode message. */
3537 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3538 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
3539 if (error) {
3540 ofpbuf_uninit(&ofpacts);
3541 return error;
3542 }
3543
3544 po.ofpacts = ofpbuf_steal_data(&ofpacts); /* Move to heap. */
3545 error = ofproto_packet_out_init(p, ofconn, &opo, &po);
3546 if (error) {
3547 free(po.ofpacts);
3548 return error;
3549 }
3550
3551 ovs_mutex_lock(&ofproto_mutex);
3552 opo.version = p->tables_version;
3553 error = ofproto_packet_out_start(p, &opo);
3554 if (!error) {
3555 ofproto_packet_out_finish(p, &opo);
3556 }
3557 ovs_mutex_unlock(&ofproto_mutex);
3558
3559 ofproto_packet_out_uninit(&opo);
3560 return error;
3561 }
3562
3563 static enum ofperr
3564 handle_nxt_resume(struct ofconn *ofconn, const struct ofp_header *oh)
3565 {
3566 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3567 struct ofputil_packet_in_private pin;
3568 enum ofperr error;
3569
3570 error = ofputil_decode_packet_in_private(oh, false,
3571 ofproto_get_tun_tab(ofproto), &pin,
3572 NULL, NULL);
3573 if (error) {
3574 return error;
3575 }
3576
3577 error = (ofproto->ofproto_class->nxt_resume
3578 ? ofproto->ofproto_class->nxt_resume(ofproto, &pin)
3579 : OFPERR_NXR_NOT_SUPPORTED);
3580
3581 ofputil_packet_in_private_destroy(&pin);
3582
3583 return error;
3584 }
3585
3586 static void
3587 update_port_config(struct ofconn *ofconn, struct ofport *port,
3588 enum ofputil_port_config config,
3589 enum ofputil_port_config mask)
3590 {
3591 enum ofputil_port_config toggle = (config ^ port->pp.config) & mask;
3592
3593 if (toggle & OFPUTIL_PC_PORT_DOWN
3594 && (config & OFPUTIL_PC_PORT_DOWN
3595 ? netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL)
3596 : netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL))) {
3597 /* We tried to bring the port up or down, but it failed, so don't
3598 * update the "down" bit. */
3599 toggle &= ~OFPUTIL_PC_PORT_DOWN;
3600 }
3601
3602 if (toggle) {
3603 enum ofputil_port_config old_config = port->pp.config;
3604 port->pp.config ^= toggle;
3605 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
3606 connmgr_send_port_status(port->ofproto->connmgr, ofconn, &port->pp,
3607 OFPPR_MODIFY);
3608 }
3609 }
3610
3611 static enum ofperr
3612 port_mod_start(struct ofconn *ofconn, struct ofputil_port_mod *pm,
3613 struct ofport **port)
3614 {
3615 struct ofproto *p = ofconn_get_ofproto(ofconn);
3616
3617 *port = ofproto_get_port(p, pm->port_no);
3618 if (!*port) {
3619 return OFPERR_OFPPMFC_BAD_PORT;
3620 }
3621 if (!eth_addr_equals((*port)->pp.hw_addr, pm->hw_addr)) {
3622 return OFPERR_OFPPMFC_BAD_HW_ADDR;
3623 }
3624 return 0;
3625 }
3626
3627 static void
3628 port_mod_finish(struct ofconn *ofconn, struct ofputil_port_mod *pm,
3629 struct ofport *port)
3630 {
3631 update_port_config(ofconn, port, pm->config, pm->mask);
3632 if (pm->advertise) {
3633 netdev_set_advertisements(port->netdev, pm->advertise);
3634 }
3635 }
3636
3637 static enum ofperr
3638 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3639 {
3640 struct ofputil_port_mod pm;
3641 struct ofport *port;
3642 enum ofperr error;
3643
3644 error = reject_slave_controller(ofconn);
3645 if (error) {
3646 return error;
3647 }
3648
3649 error = ofputil_decode_port_mod(oh, &pm, false);
3650 if (error) {
3651 return error;
3652 }
3653
3654 error = port_mod_start(ofconn, &pm, &port);
3655 if (!error) {
3656 port_mod_finish(ofconn, &pm, port);
3657 }
3658 return error;
3659 }
3660
3661 static enum ofperr
3662 handle_desc_stats_request(struct ofconn *ofconn,
3663 const struct ofp_header *request)
3664 {
3665 static const char *default_mfr_desc = "Nicira, Inc.";
3666 static const char *default_hw_desc = "Open vSwitch";
3667 static const char *default_sw_desc = VERSION;
3668 static const char *default_serial_desc = "None";
3669 static const char *default_dp_desc = "None";
3670
3671 struct ofproto *p = ofconn_get_ofproto(ofconn);
3672 struct ofp_desc_stats *ods;
3673 struct ofpbuf *msg;
3674
3675 msg = ofpraw_alloc_stats_reply(request, 0);
3676 ods = ofpbuf_put_zeros(msg, sizeof *ods);
3677 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
3678 sizeof ods->mfr_desc);
3679 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
3680 sizeof ods->hw_desc);
3681 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
3682 sizeof ods->sw_desc);
3683 ovs_strlcpy(ods->serial_num,
3684 p->serial_desc ? p->serial_desc : default_serial_desc,
3685 sizeof ods->serial_num);
3686 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
3687 sizeof ods->dp_desc);
3688 ofconn_send_reply(ofconn, msg);
3689
3690 return 0;
3691 }
3692
3693 static enum ofperr
3694 handle_table_stats_request(struct ofconn *ofconn,
3695 const struct ofp_header *request)
3696 {
3697 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3698 struct ofputil_table_features *features;
3699 struct ofputil_table_stats *stats;
3700 struct ofpbuf *reply;
3701 size_t i;
3702
3703 query_tables(ofproto, &features, &stats);
3704
3705 reply = ofputil_encode_table_stats_reply(request);
3706 for (i = 0; i < ofproto->n_tables; i++) {
3707 if (!(ofproto->tables[i].flags & OFTABLE_HIDDEN)) {
3708 ofputil_append_table_stats_reply(reply, &stats[i], &features[i]);
3709 }
3710 }
3711 ofconn_send_reply(ofconn, reply);
3712
3713 free(features);
3714 free(stats);
3715
3716 return 0;
3717 }
3718
3719 static enum ofperr
3720 handle_table_features_request(struct ofconn *ofconn,
3721 const struct ofp_header *request)
3722 {
3723 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3724 struct ofpbuf msg = ofpbuf_const_initializer(request,
3725 ntohs(request->length));
3726 ofpraw_pull_assert(&msg);
3727 if (msg.size || ofpmp_more(request)) {
3728 return OFPERR_OFPTFFC_EPERM;
3729 }
3730
3731 struct ofputil_table_features *features;
3732 query_tables(ofproto, &features, NULL);
3733
3734 struct ovs_list replies;
3735 ofpmp_init(&replies, request);
3736 for (size_t i = 0; i < ofproto->n_tables; i++) {
3737 if (!(ofproto->tables[i].flags & OFTABLE_HIDDEN)) {
3738 ofputil_append_table_features_reply(&features[i], &replies);
3739 }
3740 }
3741 ofconn_send_replies(ofconn, &replies);
3742
3743 free(features);
3744
3745 return 0;
3746 }
3747
3748 /* Returns the vacancy of 'oftable', a number that ranges from 0 (if the table
3749 * is full) to 100 (if the table is empty).
3750 *
3751 * A table without a limit on flows is considered to be empty. */
3752 static uint8_t
3753 oftable_vacancy(const struct oftable *t)
3754 {
3755 return (!t->max_flows ? 100
3756 : t->n_flows >= t->max_flows ? 0
3757 : (t->max_flows - t->n_flows) * 100.0 / t->max_flows);
3758 }
3759
3760 static void
3761 query_table_desc__(struct ofputil_table_desc *td,
3762 struct ofproto *ofproto, uint8_t table_id)
3763 {
3764 const struct oftable *t = &ofproto->tables[table_id];
3765
3766 td->table_id = table_id;
3767 td->eviction = (t->eviction & EVICTION_OPENFLOW
3768 ? OFPUTIL_TABLE_EVICTION_ON
3769 : OFPUTIL_TABLE_EVICTION_OFF);
3770 td->eviction_flags = OFPROTO_EVICTION_FLAGS;
3771 td->vacancy = (t->vacancy_event
3772 ? OFPUTIL_TABLE_VACANCY_ON
3773 : OFPUTIL_TABLE_VACANCY_OFF);
3774 td->table_vacancy.vacancy_down = t->vacancy_down;
3775 td->table_vacancy.vacancy_up = t->vacancy_up;
3776 td->table_vacancy.vacancy = oftable_vacancy(t);
3777 }
3778
3779 /* This function queries the database for dumping table-desc. */
3780 static void
3781 query_tables_desc(struct ofproto *ofproto, struct ofputil_table_desc **descp)
3782 {
3783 struct ofputil_table_desc *table_desc;
3784 size_t i;
3785
3786 table_desc = *descp = xcalloc(ofproto->n_tables, sizeof *table_desc);
3787 for (i = 0; i < ofproto->n_tables; i++) {
3788 struct ofputil_table_desc *td = &table_desc[i];
3789 query_table_desc__(td, ofproto, i);
3790 }
3791 }
3792
3793 /* Function to handle dump-table-desc request. */
3794 static enum ofperr
3795 handle_table_desc_request(struct ofconn *ofconn,
3796 const struct ofp_header *request)
3797 {
3798 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3799 struct ofputil_table_desc *table_desc;
3800 struct ovs_list replies;
3801 size_t i;
3802
3803 query_tables_desc(ofproto, &table_desc);
3804 ofpmp_init(&replies, request);
3805 for (i = 0; i < ofproto->n_tables; i++) {
3806 if (!(ofproto->tables[i].flags & OFTABLE_HIDDEN)) {
3807 ofputil_append_table_desc_reply(&table_desc[i], &replies,
3808 request->version);
3809 }
3810 }
3811 ofconn_send_replies(ofconn, &replies);
3812 free(table_desc);
3813 return 0;
3814 }
3815
3816 /* This function determines and sends the vacancy event, based on the value
3817 * of current vacancy and threshold vacancy. If the current vacancy is less
3818 * than or equal to vacancy_down, vacancy up events must be enabled, and when
3819 * the current vacancy is greater or equal to vacancy_up, vacancy down events
3820 * must be enabled. */
3821 static void
3822 send_table_status(struct ofproto *ofproto, uint8_t table_id)
3823 {
3824 struct oftable *t = &ofproto->tables[table_id];
3825 if (!t->vacancy_event) {
3826 return;
3827 }
3828
3829 uint8_t vacancy = oftable_vacancy(t);
3830 enum ofp14_table_reason event;
3831 if (vacancy < t->vacancy_down) {
3832 event = OFPTR_VACANCY_DOWN;
3833 } else if (vacancy > t->vacancy_up) {
3834 event = OFPTR_VACANCY_UP;
3835 } else {
3836 return;
3837 }
3838
3839 if (event == t->vacancy_event) {
3840 struct ofputil_table_desc td;
3841 query_table_desc__(&td, ofproto, table_id);
3842 connmgr_send_table_status(ofproto->connmgr, &td, event);
3843
3844 t->vacancy_event = (event == OFPTR_VACANCY_DOWN
3845 ? OFPTR_VACANCY_UP
3846 : OFPTR_VACANCY_DOWN);
3847 }
3848 }
3849
3850 static void
3851 append_port_stat(struct ofport *port, struct ovs_list *replies)
3852 {
3853 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3854
3855 calc_duration(port->created, time_msec(),
3856 &ops.duration_sec, &ops.duration_nsec);
3857
3858 /* Intentionally ignore return value, since errors will set
3859 * 'stats' to all-1s, which is correct for OpenFlow, and
3860 * netdev_get_stats() will log errors. */
3861 ofproto_port_get_stats(port, &ops.stats);
3862
3863 ofputil_append_port_stat(replies, &ops);
3864 }
3865
3866 static void
3867 handle_port_request(struct ofconn *ofconn,
3868 const struct ofp_header *request, ofp_port_t port_no,
3869 void (*cb)(struct ofport *, struct ovs_list *replies))
3870 {
3871 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3872 struct ofport *port;
3873 struct ovs_list replies;
3874
3875 ofpmp_init(&replies, request);
3876 if (port_no != OFPP_ANY) {
3877 port = ofproto_get_port(ofproto, port_no);
3878 if (port) {
3879 cb(port, &replies);
3880 }
3881 } else {
3882 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3883 cb(port, &replies);
3884 }
3885 }
3886
3887 ofconn_send_replies(ofconn, &replies);
3888 }
3889
3890 static enum ofperr
3891 handle_port_stats_request(struct ofconn *ofconn,
3892 const struct ofp_header *request)
3893 {
3894 ofp_port_t port_no;
3895 enum ofperr error;
3896
3897 error = ofputil_decode_port_stats_request(request, &port_no);
3898 if (!error) {
3899 handle_port_request(ofconn, request, port_no, append_port_stat);
3900 }
3901 return error;
3902 }
3903
3904 static void
3905 append_port_desc(struct ofport *port, struct ovs_list *replies)
3906 {
3907 ofputil_append_port_desc_stats_reply(&port->pp, replies);
3908 }
3909
3910 static enum ofperr
3911 handle_port_desc_stats_request(struct ofconn *ofconn,
3912 const struct ofp_header *request)
3913 {
3914 ofp_port_t port_no;
3915 enum ofperr error;
3916
3917 error = ofputil_decode_port_desc_stats_request(request, &port_no);
3918 if (!error) {
3919 handle_port_request(ofconn, request, port_no, append_port_desc);
3920 }
3921 return error;
3922 }
3923
3924 static uint32_t
3925 hash_cookie(ovs_be64 cookie)
3926 {
3927 return hash_uint64((OVS_FORCE uint64_t)cookie);
3928 }
3929
3930 static void
3931 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3932 OVS_REQUIRES(ofproto_mutex)
3933 {
3934 hindex_insert(&ofproto->cookies, &rule->cookie_node,
3935 hash_cookie(rule->flow_cookie));
3936 }
3937
3938 static void
3939 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3940 OVS_REQUIRES(ofproto_mutex)
3941 {
3942 hindex_remove(&ofproto->cookies, &rule->cookie_node);
3943 }
3944
3945 static void
3946 calc_duration(long long int start, long long int now,
3947 uint32_t *sec, uint32_t *nsec)
3948 {
3949 long long int msecs = now - start;
3950 *sec = msecs / 1000;
3951 *nsec = (msecs % 1000) * (1000 * 1000);
3952 }
3953
3954 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
3955 * true if 'table_id' is OK, false otherwise. */
3956 static bool
3957 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3958 {
3959 return table_id == OFPTT_ALL || table_id < ofproto->n_tables;
3960 }
3961
3962 static struct oftable *
3963 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3964 {
3965 struct oftable *table;
3966
3967 for (table = &ofproto->tables[table_id];
3968 table < &ofproto->tables[ofproto->n_tables];
3969 table++) {
3970 if (!(table->flags & OFTABLE_HIDDEN)) {
3971 return table;
3972 }
3973 }
3974
3975 return NULL;
3976 }
3977
3978 static struct oftable *
3979 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3980 {
3981 if (table_id == 0xff) {
3982 return next_visible_table(ofproto, 0);
3983 } else if (table_id < ofproto->n_tables) {
3984 return &ofproto->tables[table_id];
3985 } else {
3986 return NULL;
3987 }
3988 }
3989
3990 static struct oftable *
3991 next_matching_table(const struct ofproto *ofproto,
3992 const struct oftable *table, uint8_t table_id)
3993 {
3994 return (table_id == 0xff
3995 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3996 : NULL);
3997 }
3998
3999 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
4000 *
4001 * - If TABLE_ID is 0xff, this iterates over every classifier table in
4002 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
4003 *
4004 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
4005 * only once, for that table. (This can be used to access tables marked
4006 * OFTABLE_HIDDEN.)
4007 *
4008 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
4009 * entered at all. (Perhaps you should have validated TABLE_ID with
4010 * check_table_id().)
4011 *
4012 * All parameters are evaluated multiple times.
4013 */
4014 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
4015 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
4016 (TABLE) != NULL; \
4017 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
4018
4019 /* Initializes 'criteria' in a straightforward way based on the other
4020 * parameters.
4021 *
4022 * By default, the criteria include flows that are read-only, on the assumption
4023 * that the collected flows won't be modified. Call rule_criteria_require_rw()
4024 * if flows will be modified.
4025 *
4026 * For "loose" matching, the 'priority' parameter is unimportant and may be
4027 * supplied as 0. */
4028 static void
4029 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
4030 const struct match *match, int priority,
4031 ovs_version_t version, ovs_be64 cookie,
4032 ovs_be64 cookie_mask, ofp_port_t out_port,
4033 uint32_t out_group)
4034 {
4035 criteria->table_id = table_id;
4036 cls_rule_init(&criteria->cr, match, priority);
4037 criteria->version = version;
4038 criteria->cookie = cookie;
4039 criteria->cookie_mask = cookie_mask;
4040 criteria->out_port = out_port;
4041 criteria->out_group = out_group;
4042
4043 /* We ordinarily want to skip hidden rules, but there has to be a way for
4044 * code internal to OVS to modify and delete them, so if the criteria
4045 * specify a priority that can only be for a hidden flow, then allow hidden
4046 * rules to be selected. (This doesn't allow OpenFlow clients to meddle
4047 * with hidden flows because OpenFlow uses only a 16-bit field to specify
4048 * priority.) */
4049 criteria->include_hidden = priority > UINT16_MAX;
4050
4051 /* We assume that the criteria are being used to collect flows for reading
4052 * but not modification. Thus, we should collect read-only flows. */
4053 criteria->include_readonly = true;
4054 }
4055
4056 /* By default, criteria initialized by rule_criteria_init() will match flows
4057 * that are read-only, on the assumption that the collected flows won't be
4058 * modified. Call this function to match only flows that are be modifiable.
4059 *
4060 * Specify 'can_write_readonly' as false in ordinary circumstances, true if the
4061 * caller has special privileges that allow it to modify even "read-only"
4062 * flows. */
4063 static void
4064 rule_criteria_require_rw(struct rule_criteria *criteria,
4065 bool can_write_readonly)
4066 {
4067 criteria->include_readonly = can_write_readonly;
4068 }
4069
4070 static void
4071 rule_criteria_destroy(struct rule_criteria *criteria)
4072 {
4073 cls_rule_destroy(&criteria->cr);
4074 criteria->version = OVS_VERSION_NOT_REMOVED; /* Mark as destroyed. */
4075 }
4076
4077 /* Schedules postponed removal of rules, destroys 'rules'. */
4078 static void
4079 remove_rules_postponed(struct rule_collection *rules)
4080 OVS_REQUIRES(ofproto_mutex)
4081 {
4082 if (rule_collection_n(rules) > 0) {
4083 if (rule_collection_n(rules) == 1) {
4084 ovsrcu_postpone(remove_rule_rcu, rule_collection_rules(rules)[0]);
4085 rule_collection_init(rules);
4086 } else {
4087 ovsrcu_postpone(remove_rules_rcu, rule_collection_detach(rules));
4088 }
4089 }
4090 }
4091
4092 /* Schedules postponed removal of groups, destroys 'groups'. */
4093 static void
4094 remove_groups_postponed(struct group_collection *groups)
4095 OVS_REQUIRES(ofproto_mutex)
4096 {
4097 if (group_collection_n(groups) > 0) {
4098 if (group_collection_n(groups) == 1) {
4099 ovsrcu_postpone(remove_group_rcu,
4100 group_collection_groups(groups)[0]);
4101 group_collection_init(groups);
4102 } else {
4103 ovsrcu_postpone(remove_groups_rcu,
4104 group_collection_detach(groups));
4105 }
4106 }
4107 }
4108
4109 /* Checks whether 'rule' matches 'c' and, if so, adds it to 'rules'. This
4110 * function verifies most of the criteria in 'c' itself, but the caller must
4111 * check 'c->cr' itself.
4112 *
4113 * Rules that have already been marked for removal are not collected.
4114 *
4115 * Increments '*n_readonly' if 'rule' wasn't added because it's read-only (and
4116 * 'c' only includes modifiable rules). */
4117 static void
4118 collect_rule(struct rule *rule, const struct rule_criteria *c,
4119 struct rule_collection *rules, size_t *n_readonly)
4120 OVS_REQUIRES(ofproto_mutex)
4121 {
4122 if ((c->table_id == rule->table_id || c->table_id == 0xff)
4123 && ofproto_rule_has_out_port(rule, c->out_port)
4124 && ofproto_rule_has_out_group(rule, c->out_group)
4125 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)
4126 && (!rule_is_hidden(rule) || c->include_hidden)
4127 && cls_rule_visible_in_version(&rule->cr, c->version)) {
4128 /* Rule matches all the criteria... */
4129 if (!rule_is_readonly(rule) || c->include_readonly) {
4130 /* ...add it. */
4131 rule_collection_add(rules, rule);
4132 } else {
4133 /* ...except it's read-only. */
4134 ++*n_readonly;
4135 }
4136 }
4137 }
4138
4139 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
4140 * on classifiers rules are done in the "loose" way required for OpenFlow
4141 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
4142 * 'rules'.
4143 *
4144 * Returns 0 on success, otherwise an OpenFlow error code. */
4145 static enum ofperr
4146 collect_rules_loose(struct ofproto *ofproto,
4147 const struct rule_criteria *criteria,
4148 struct rule_collection *rules)
4149 OVS_REQUIRES(ofproto_mutex)
4150 {
4151 struct oftable *table;
4152 enum ofperr error = 0;
4153 size_t n_readonly = 0;
4154
4155 rule_collection_init(rules);
4156
4157 if (!check_table_id(ofproto, criteria->table_id)) {
4158 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4159 goto exit;
4160 }
4161
4162 if (criteria->cookie_mask == OVS_BE64_MAX) {
4163 struct rule *rule;
4164
4165 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
4166 hash_cookie(criteria->cookie),
4167 &ofproto->cookies) {
4168 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
4169 collect_rule(rule, criteria, rules, &n_readonly);
4170 }
4171 }
4172 } else {
4173 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
4174 struct rule *rule;
4175
4176 CLS_FOR_EACH_TARGET (rule, cr, &table->cls, &criteria->cr,
4177 criteria->version) {
4178 collect_rule(rule, criteria, rules, &n_readonly);
4179 }
4180 }
4181 }
4182
4183 exit:
4184 if (!error && !rule_collection_n(rules) && n_readonly) {
4185 /* We didn't find any rules to modify. We did find some read-only
4186 * rules that we're not allowed to modify, so report that. */
4187 error = OFPERR_OFPBRC_EPERM;
4188 }
4189 if (error) {
4190 rule_collection_destroy(rules);
4191 }
4192 return error;
4193 }
4194
4195 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
4196 * on classifiers rules are done in the "strict" way required for OpenFlow
4197 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
4198 * rules on list 'rules'.
4199 *
4200 * Returns 0 on success, otherwise an OpenFlow error code. */
4201 static enum ofperr
4202 collect_rules_strict(struct ofproto *ofproto,
4203 const struct rule_criteria *criteria,
4204 struct rule_collection *rules)
4205 OVS_REQUIRES(ofproto_mutex)
4206 {
4207 struct oftable *table;
4208 size_t n_readonly = 0;
4209 enum ofperr error = 0;
4210
4211 rule_collection_init(rules);
4212
4213 if (!check_table_id(ofproto, criteria->table_id)) {
4214 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4215 goto exit;
4216 }
4217
4218 if (criteria->cookie_mask == OVS_BE64_MAX) {
4219 struct rule *rule;
4220
4221 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
4222 hash_cookie(criteria->cookie),
4223 &ofproto->cookies) {
4224 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
4225 collect_rule(rule, criteria, rules, &n_readonly);
4226 }
4227 }
4228 } else {
4229 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
4230 struct rule *rule;
4231
4232 rule = rule_from_cls_rule(classifier_find_rule_exactly(
4233 &table->cls, &criteria->cr,
4234 criteria->version));
4235 if (rule) {
4236 collect_rule(rule, criteria, rules, &n_readonly);
4237 }
4238 }
4239 }
4240
4241 exit:
4242 if (!error && !rule_collection_n(rules) && n_readonly) {
4243 /* We didn't find any rules to modify. We did find some read-only
4244 * rules that we're not allowed to modify, so report that. */
4245 error = OFPERR_OFPBRC_EPERM;
4246 }
4247 if (error) {
4248 rule_collection_destroy(rules);
4249 }
4250 return error;
4251 }
4252
4253 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
4254 * forced into the range of a uint16_t. */
4255 static int
4256 age_secs(long long int age_ms)
4257 {
4258 return (age_ms < 0 ? 0
4259 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
4260 : (unsigned int) age_ms / 1000);
4261 }
4262
4263 static enum ofperr
4264 handle_flow_stats_request(struct ofconn *ofconn,
4265 const struct ofp_header *request)
4266 OVS_EXCLUDED(ofproto_mutex)
4267 {
4268 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4269 struct ofputil_flow_stats_request fsr;
4270 struct rule_criteria criteria;
4271 struct rule_collection rules;
4272 struct ovs_list replies;
4273 enum ofperr error;
4274
4275 error = ofputil_decode_flow_stats_request(&fsr, request,
4276 ofproto_get_tun_tab(ofproto));
4277 if (error) {
4278 return error;
4279 }
4280
4281 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, OVS_VERSION_MAX,
4282 fsr.cookie, fsr.cookie_mask, fsr.out_port,
4283 fsr.out_group);
4284
4285 ovs_mutex_lock(&ofproto_mutex);
4286 error = collect_rules_loose(ofproto, &criteria, &rules);
4287 rule_criteria_destroy(&criteria);
4288 if (!error) {
4289 rule_collection_ref(&rules);
4290 }
4291 ovs_mutex_unlock(&ofproto_mutex);
4292
4293 if (error) {
4294 return error;
4295 }
4296
4297 ofpmp_init(&replies, request);
4298 struct rule *rule;
4299 RULE_COLLECTION_FOR_EACH (rule, &rules) {
4300 long long int now = time_msec();
4301 struct ofputil_flow_stats fs;
4302 long long int created, used, modified;
4303 const struct rule_actions *actions;
4304 enum ofputil_flow_mod_flags flags;
4305
4306 ovs_mutex_lock(&rule->mutex);
4307 fs.cookie = rule->flow_cookie;
4308 fs.idle_timeout = rule->idle_timeout;
4309 fs.hard_timeout = rule->hard_timeout;
4310 fs.importance = rule->importance;
4311 created = rule->created;
4312 modified = rule->modified;
4313 actions = rule_get_actions(rule);
4314 flags = rule->flags;
4315 ovs_mutex_unlock(&rule->mutex);
4316
4317 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
4318 &fs.byte_count, &used);
4319
4320 minimatch_expand(&rule->cr.match, &fs.match);
4321 fs.table_id = rule->table_id;
4322 calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
4323 fs.priority = rule->cr.priority;
4324 fs.idle_age = age_secs(now - used);
4325 fs.hard_age = age_secs(now - modified);
4326 fs.ofpacts = actions->ofpacts;
4327 fs.ofpacts_len = actions->ofpacts_len;
4328
4329 fs.flags = flags;
4330 ofputil_append_flow_stats_reply(&fs, &replies,
4331 ofproto_get_tun_tab(ofproto));
4332 }
4333
4334 rule_collection_unref(&rules);
4335 rule_collection_destroy(&rules);
4336
4337 ofconn_send_replies(ofconn, &replies);
4338
4339 return 0;
4340 }
4341
4342 static void
4343 flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
4344 {
4345 uint64_t packet_count, byte_count;
4346 const struct rule_actions *actions;
4347 long long int created, used;
4348
4349 rule->ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
4350 &byte_count, &used);
4351
4352 ovs_mutex_lock(&rule->mutex);
4353 actions = rule_get_actions(rule);
4354 created = rule->created;
4355 ovs_mutex_unlock(&rule->mutex);
4356
4357 if (rule->table_id != 0) {
4358 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
4359 }
4360 ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
4361 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
4362 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
4363 cls_rule_format(&rule->cr, ofproto_get_tun_tab(ofproto), results);
4364 ds_put_char(results, ',');
4365
4366 ds_put_cstr(results, "actions=");
4367 ofpacts_format(actions->ofpacts, actions->ofpacts_len, results);
4368
4369 ds_put_cstr(results, "\n");
4370 }
4371
4372 /* Adds a pretty-printed description of all flows to 'results', including
4373 * hidden flows (e.g., set up by in-band control). */
4374 void
4375 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
4376 {
4377 struct oftable *table;
4378
4379 OFPROTO_FOR_EACH_TABLE (table, p) {
4380 struct rule *rule;
4381
4382 CLS_FOR_EACH (rule, cr, &table->cls) {
4383 flow_stats_ds(p, rule, results);
4384 }
4385 }
4386 }
4387
4388 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
4389 * '*engine_type' and '*engine_id', respectively. */
4390 void
4391 ofproto_get_netflow_ids(const struct ofproto *ofproto,
4392 uint8_t *engine_type, uint8_t *engine_id)
4393 {
4394 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
4395 }
4396
4397 /* Checks the status change of CFM on 'ofport'.
4398 *
4399 * Returns true if 'ofproto_class' does not support 'cfm_status_changed'. */
4400 bool
4401 ofproto_port_cfm_status_changed(struct ofproto *ofproto, ofp_port_t ofp_port)
4402 {
4403 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
4404 return (ofport && ofproto->ofproto_class->cfm_status_changed
4405 ? ofproto->ofproto_class->cfm_status_changed(ofport)
4406 : true);
4407 }
4408
4409 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'.
4410 * Returns 0 if the port's CFM status was successfully stored into
4411 * '*status'. Returns positive errno if the port did not have CFM
4412 * configured.
4413 *
4414 * The caller must provide and own '*status', and must free 'status->rmps'.
4415 * '*status' is indeterminate if the return value is non-zero. */
4416 int
4417 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
4418 struct cfm_status *status)
4419 {
4420 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
4421 return (ofport && ofproto->ofproto_class->get_cfm_status
4422 ? ofproto->ofproto_class->get_cfm_status(ofport, status)
4423 : EOPNOTSUPP);
4424 }
4425
4426 static enum ofperr
4427 handle_aggregate_stats_request(struct ofconn *ofconn,
4428 const struct ofp_header *oh)
4429 OVS_EXCLUDED(ofproto_mutex)
4430 {
4431 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4432 struct ofputil_flow_stats_request request;
4433 struct ofputil_aggregate_stats stats;
4434 bool unknown_packets, unknown_bytes;
4435 struct rule_criteria criteria;
4436 struct rule_collection rules;
4437 struct ofpbuf *reply;
4438 enum ofperr error;
4439
4440 error = ofputil_decode_flow_stats_request(&request, oh,
4441 ofproto_get_tun_tab(ofproto));
4442 if (error) {
4443 return error;
4444 }
4445
4446 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
4447 OVS_VERSION_MAX, request.cookie, request.cookie_mask,
4448 request.out_port, request.out_group);
4449
4450 ovs_mutex_lock(&ofproto_mutex);
4451 error = collect_rules_loose(ofproto, &criteria, &rules);
4452 rule_criteria_destroy(&criteria);
4453 if (!error) {
4454 rule_collection_ref(&rules);
4455 }
4456 ovs_mutex_unlock(&ofproto_mutex);
4457
4458 if (error) {
4459 return error;
4460 }
4461
4462 memset(&stats, 0, sizeof stats);
4463 unknown_packets = unknown_bytes = false;
4464
4465 struct rule *rule;
4466 RULE_COLLECTION_FOR_EACH (rule, &rules) {
4467 uint64_t packet_count;
4468 uint64_t byte_count;
4469 long long int used;
4470
4471 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
4472 &byte_count, &used);
4473
4474 if (packet_count == UINT64_MAX) {
4475 unknown_packets = true;
4476 } else {
4477 stats.packet_count += packet_count;
4478 }
4479
4480 if (byte_count == UINT64_MAX) {
4481 unknown_bytes = true;
4482 } else {
4483 stats.byte_count += byte_count;
4484 }
4485
4486 stats.flow_count++;
4487 }
4488 if (unknown_packets) {
4489 stats.packet_count = UINT64_MAX;
4490 }
4491 if (unknown_bytes) {
4492 stats.byte_count = UINT64_MAX;
4493 }
4494
4495 rule_collection_unref(&rules);
4496 rule_collection_destroy(&rules);
4497
4498 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
4499 ofconn_send_reply(ofconn, reply);
4500
4501 return 0;
4502 }
4503
4504 struct queue_stats_cbdata {
4505 struct ofport *ofport;
4506 struct ovs_list replies;
4507 long long int now;
4508 };
4509
4510 static void
4511 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
4512 const struct netdev_queue_stats *stats)
4513 {
4514 struct ofputil_queue_stats oqs;
4515
4516 oqs.port_no = cbdata->ofport->pp.port_no;
4517 oqs.queue_id = queue_id;
4518 oqs.tx_bytes = stats->tx_bytes;
4519 oqs.tx_packets = stats->tx_packets;
4520 oqs.tx_errors = stats->tx_errors;
4521 if (stats->created != LLONG_MIN) {
4522 calc_duration(stats->created, cbdata->now,
4523 &oqs.duration_sec, &oqs.duration_nsec);
4524 } else {
4525 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
4526 }
4527 ofputil_append_queue_stat(&cbdata->replies, &oqs);
4528 }
4529
4530 static void
4531 handle_queue_stats_dump_cb(uint32_t queue_id,
4532 struct netdev_queue_stats *stats,
4533 void *cbdata_)
4534 {
4535 struct queue_stats_cbdata *cbdata = cbdata_;
4536
4537 put_queue_stats(cbdata, queue_id, stats);
4538 }
4539
4540 static enum ofperr
4541 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
4542 struct queue_stats_cbdata *cbdata)
4543 {
4544 cbdata->ofport = port;
4545 if (queue_id == OFPQ_ALL) {
4546 netdev_dump_queue_stats(port->netdev,
4547 handle_queue_stats_dump_cb, cbdata);
4548 } else {
4549 struct netdev_queue_stats stats;
4550
4551 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
4552 put_queue_stats(cbdata, queue_id, &stats);
4553 } else {
4554 return OFPERR_OFPQOFC_BAD_QUEUE;
4555 }
4556 }
4557 return 0;
4558 }
4559
4560 static enum ofperr
4561 handle_queue_stats_request(struct ofconn *ofconn,
4562 const struct ofp_header *rq)
4563 {
4564 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4565 struct queue_stats_cbdata cbdata;
4566 struct ofport *port;
4567 enum ofperr error;
4568 struct ofputil_queue_stats_request oqsr;
4569
4570 COVERAGE_INC(ofproto_queue_req);
4571
4572 ofpmp_init(&cbdata.replies, rq);
4573 cbdata.now = time_msec();
4574
4575 error = ofputil_decode_queue_stats_request(rq, &oqsr);
4576 if (error) {
4577 return error;
4578 }
4579
4580 if (oqsr.port_no == OFPP_ANY) {
4581 error = OFPERR_OFPQOFC_BAD_QUEUE;
4582 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
4583 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
4584 error = 0;
4585 }
4586 }
4587 } else {
4588 port = ofproto_get_port(ofproto, oqsr.port_no);
4589 error = (port
4590 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
4591 : OFPERR_OFPQOFC_BAD_PORT);
4592 }
4593 if (!error) {
4594 ofconn_send_replies(ofconn, &cbdata.replies);
4595 } else {
4596 ofpbuf_list_delete(&cbdata.replies);
4597 }
4598
4599 return error;
4600 }
4601
4602 static enum ofperr
4603 evict_rules_from_table(struct oftable *table)
4604 OVS_REQUIRES(ofproto_mutex)
4605 {
4606 enum ofperr error = 0;
4607 struct rule_collection rules;
4608 unsigned int count = table->n_flows;
4609 unsigned int max_flows = table->max_flows;
4610
4611 rule_collection_init(&rules);
4612
4613 while (count-- > max_flows) {
4614 struct rule *rule;
4615
4616 if (!choose_rule_to_evict(table, &rule)) {
4617 error = OFPERR_OFPFMFC_TABLE_FULL;
4618 break;
4619 } else {
4620 eviction_group_remove_rule(rule);
4621 rule_collection_add(&rules, rule);
4622 }
4623 }
4624 delete_flows__(&rules, OFPRR_EVICTION, NULL);
4625
4626 return error;
4627 }
4628
4629 static void
4630 get_conjunctions(const struct ofputil_flow_mod *fm,
4631 struct cls_conjunction **conjsp, size_t *n_conjsp)
4632 {
4633 struct cls_conjunction *conjs = NULL;
4634 int n_conjs = 0;
4635
4636 const struct ofpact *ofpact;
4637 OFPACT_FOR_EACH (ofpact, fm->ofpacts, fm->ofpacts_len) {
4638 if (ofpact->type == OFPACT_CONJUNCTION) {
4639 n_conjs++;
4640 } else if (ofpact->type != OFPACT_NOTE) {
4641 /* "conjunction" may appear with "note" actions but not with any
4642 * other type of actions. */
4643 ovs_assert(!n_conjs);
4644 break;
4645 }
4646 }
4647 if (n_conjs) {
4648 int i = 0;
4649
4650 conjs = xzalloc(n_conjs * sizeof *conjs);
4651 OFPACT_FOR_EACH (ofpact, fm->ofpacts, fm->ofpacts_len) {
4652 if (ofpact->type == OFPACT_CONJUNCTION) {
4653 struct ofpact_conjunction *oc = ofpact_get_CONJUNCTION(ofpact);
4654 conjs[i].clause = oc->clause;
4655 conjs[i].n_clauses = oc->n_clauses;
4656 conjs[i].id = oc->id;
4657 i++;
4658 }
4659 }
4660 }
4661
4662 *conjsp = conjs;
4663 *n_conjsp = n_conjs;
4664 }
4665
4666 /* add_flow_init(), add_flow_start(), add_flow_revert(), and add_flow_finish()
4667 * implement OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
4668 * in which no matching flow already exists in the flow table.
4669 *
4670 * add_flow_init() creates a new flow according to 'fm' and stores it to 'ofm'
4671 * for later reference. If the flow replaces other flow, it will be updated to
4672 * match modify semantics later by add_flow_start() (by calling
4673 * replace_rule_start()).
4674 *
4675 * Returns 0 on success, or an OpenFlow error code on failure.
4676 *
4677 * On successful return the caller must complete the operation by calling
4678 * add_flow_start(), and if that succeeds, then either add_flow_finish(), or
4679 * add_flow_revert() if the operation needs to be reverted due to a later
4680 * failure.
4681 */
4682 static enum ofperr
4683 add_flow_init(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
4684 const struct ofputil_flow_mod *fm)
4685 OVS_EXCLUDED(ofproto_mutex)
4686 {
4687 struct oftable *table;
4688 struct cls_rule cr;
4689 uint8_t table_id;
4690 enum ofperr error;
4691
4692 if (!check_table_id(ofproto, fm->table_id)) {
4693 return OFPERR_OFPBRC_BAD_TABLE_ID;
4694 }
4695
4696 /* Pick table. */
4697 if (fm->table_id == 0xff) {
4698 if (ofproto->ofproto_class->rule_choose_table) {
4699 error = ofproto->ofproto_class->rule_choose_table(ofproto,
4700 &fm->match,
4701 &table_id);
4702 if (error) {
4703 return error;
4704 }
4705 ovs_assert(table_id < ofproto->n_tables);
4706 } else {
4707 table_id = 0;
4708 }
4709 } else if (fm->table_id < ofproto->n_tables) {
4710 table_id = fm->table_id;
4711 } else {
4712 return OFPERR_OFPBRC_BAD_TABLE_ID;
4713 }
4714
4715 table = &ofproto->tables[table_id];
4716 if (table->flags & OFTABLE_READONLY
4717 && !(fm->flags & OFPUTIL_FF_NO_READONLY)) {
4718 return OFPERR_OFPBRC_EPERM;
4719 }
4720
4721 if (!(fm->flags & OFPUTIL_FF_HIDDEN_FIELDS)
4722 && !match_has_default_hidden_fields(&fm->match)) {
4723 VLOG_WARN_RL(&rl, "%s: (add_flow) only internal flows can set "
4724 "non-default values to hidden fields", ofproto->name);
4725 return OFPERR_OFPBRC_EPERM;
4726 }
4727
4728 if (!ofm->temp_rule) {
4729 cls_rule_init(&cr, &fm->match, fm->priority);
4730
4731 /* Allocate new rule. Destroys 'cr'. */
4732 error = ofproto_rule_create(ofproto, &cr, table - ofproto->tables,
4733 fm->new_cookie, fm->idle_timeout,
4734 fm->hard_timeout, fm->flags,
4735 fm->importance, fm->ofpacts,
4736 fm->ofpacts_len, &ofm->temp_rule);
4737 if (error) {
4738 return error;
4739 }
4740
4741 get_conjunctions(fm, &ofm->conjs, &ofm->n_conjs);
4742 }
4743 return 0;
4744 }
4745
4746 /* ofm->temp_rule is consumed only in the successful case. */
4747 static enum ofperr
4748 add_flow_start(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
4749 OVS_REQUIRES(ofproto_mutex)
4750 {
4751 struct rule *old_rule = NULL;
4752 struct rule *new_rule = ofm->temp_rule;
4753 const struct rule_actions *actions = rule_get_actions(new_rule);
4754 struct oftable *table = &ofproto->tables[new_rule->table_id];
4755 enum ofperr error;
4756
4757 /* Must check actions while holding ofproto_mutex to avoid a race. */
4758 error = ofproto_check_ofpacts(ofproto, actions->ofpacts,
4759 actions->ofpacts_len);
4760 if (error) {
4761 return error;
4762 }
4763
4764 /* Check for the existence of an identical rule.
4765 * This will not return rules earlier marked for removal. */
4766 old_rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
4767 &new_rule->cr,
4768 ofm->version));
4769 if (!old_rule) {
4770 /* Check for overlap, if requested. */
4771 if (new_rule->flags & OFPUTIL_FF_CHECK_OVERLAP
4772 && classifier_rule_overlaps(&table->cls, &new_rule->cr,
4773 ofm->version)) {
4774 return OFPERR_OFPFMFC_OVERLAP;
4775 }
4776
4777 /* If necessary, evict an existing rule to clear out space. */
4778 if (table->n_flows >= table->max_flows) {
4779 if (!choose_rule_to_evict(table, &old_rule)) {
4780 return OFPERR_OFPFMFC_TABLE_FULL;
4781 }
4782 eviction_group_remove_rule(old_rule);
4783 /* Marks 'old_rule' as an evicted rule rather than replaced rule.
4784 */
4785 old_rule->removed_reason = OFPRR_EVICTION;
4786 }
4787 } else {
4788 ofm->modify_cookie = true;
4789 }
4790
4791 if (old_rule) {
4792 rule_collection_add(&ofm->old_rules, old_rule);
4793 }
4794 /* Take ownership of the temp_rule. */
4795 rule_collection_add(&ofm->new_rules, new_rule);
4796 ofm->temp_rule = NULL;
4797
4798 replace_rule_start(ofproto, ofm, old_rule, new_rule);
4799 return 0;
4800 }
4801
4802 /* Revert the effects of add_flow_start(). */
4803 static void
4804 add_flow_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
4805 OVS_REQUIRES(ofproto_mutex)
4806 {
4807 struct rule *old_rule = rule_collection_n(&ofm->old_rules)
4808 ? rule_collection_rules(&ofm->old_rules)[0] : NULL;
4809 struct rule *new_rule = rule_collection_rules(&ofm->new_rules)[0];
4810
4811 replace_rule_revert(ofproto, old_rule, new_rule);
4812 }
4813
4814 /* To be called after version bump. */
4815 static void
4816 add_flow_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
4817 const struct openflow_mod_requester *req)
4818 OVS_REQUIRES(ofproto_mutex)
4819 {
4820 struct rule *old_rule = rule_collection_n(&ofm->old_rules)
4821 ? rule_collection_rules(&ofm->old_rules)[0] : NULL;
4822 struct rule *new_rule = rule_collection_rules(&ofm->new_rules)[0];
4823 struct ovs_list dead_cookies = OVS_LIST_INITIALIZER(&dead_cookies);
4824
4825 replace_rule_finish(ofproto, ofm, req, old_rule, new_rule, &dead_cookies);
4826 learned_cookies_flush(ofproto, &dead_cookies);
4827
4828 if (old_rule) {
4829 ovsrcu_postpone(remove_rule_rcu, old_rule);
4830 } else {
4831 ofmonitor_report(ofproto->connmgr, new_rule, NXFME_ADDED, 0,
4832 req ? req->ofconn : NULL,
4833 req ? req->request->xid : 0, NULL);
4834
4835 /* Send Vacancy Events for OF1.4+. */
4836 send_table_status(ofproto, new_rule->table_id);
4837 }
4838 }
4839 \f
4840 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4841
4842 /* Create a new rule. Note that the rule is NOT inserted into a any data
4843 * structures yet. Takes ownership of 'cr'. Only assigns '*new_rule' if
4844 * successful. */
4845 static enum ofperr
4846 ofproto_rule_create(struct ofproto *ofproto, struct cls_rule *cr,
4847 uint8_t table_id, ovs_be64 new_cookie,
4848 uint16_t idle_timeout, uint16_t hard_timeout,
4849 enum ofputil_flow_mod_flags flags, uint16_t importance,
4850 const struct ofpact *ofpacts, size_t ofpacts_len,
4851 struct rule **new_rule)
4852 OVS_NO_THREAD_SAFETY_ANALYSIS
4853 {
4854 struct rule *rule;
4855 enum ofperr error;
4856
4857 /* Allocate new rule. */
4858 rule = ofproto->ofproto_class->rule_alloc();
4859 if (!rule) {
4860 cls_rule_destroy(cr);
4861 VLOG_WARN_RL(&rl, "%s: failed to allocate a rule.", ofproto->name);
4862 return OFPERR_OFPFMFC_UNKNOWN;
4863 }
4864
4865 /* Initialize base state. */
4866 *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
4867 cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), cr);
4868 ovs_refcount_init(&rule->ref_count);
4869
4870 ovs_mutex_init(&rule->mutex);
4871 ovs_mutex_lock(&rule->mutex);
4872 *CONST_CAST(ovs_be64 *, &rule->flow_cookie) = new_cookie;
4873 rule->created = rule->modified = time_msec();
4874 rule->idle_timeout = idle_timeout;
4875 rule->hard_timeout = hard_timeout;
4876 *CONST_CAST(uint16_t *, &rule->importance) = importance;
4877 rule->removed_reason = OVS_OFPRR_NONE;
4878
4879 *CONST_CAST(uint8_t *, &rule->table_id) = table_id;
4880 rule->flags = flags & OFPUTIL_FF_STATE;
4881
4882 *CONST_CAST(const struct rule_actions **, &rule->actions)
4883 = rule_actions_create(ofpacts, ofpacts_len);
4884
4885 ovs_list_init(&rule->meter_list_node);
4886 rule->eviction_group = NULL;
4887 rule->monitor_flags = 0;
4888 rule->add_seqno = 0;
4889 rule->modify_seqno = 0;
4890 ovs_list_init(&rule->expirable);
4891 ovs_mutex_unlock(&rule->mutex);
4892
4893 /* Construct rule, initializing derived state. */
4894 error = ofproto->ofproto_class->rule_construct(rule);
4895 if (error) {
4896 ofproto_rule_destroy__(rule);
4897 return error;
4898 }
4899
4900 rule->state = RULE_INITIALIZED;
4901
4902 *new_rule = rule;
4903 return 0;
4904 }
4905
4906 /* Initialize 'ofm' for a learn action. If the rule already existed, reference
4907 * to that rule is taken, otherwise a new rule is created. 'ofm' keeps the
4908 * rule reference in both. This does not take the global 'ofproto_mutex'. */
4909 enum ofperr
4910 ofproto_flow_mod_init_for_learn(struct ofproto *ofproto,
4911 const struct ofputil_flow_mod *fm,
4912 struct ofproto_flow_mod *ofm)
4913 OVS_EXCLUDED(ofproto_mutex)
4914 {
4915 enum ofperr error;
4916
4917 /* Reject flow mods that do not look like they were generated by a learn
4918 * action. */
4919 if (fm->command != OFPFC_MODIFY_STRICT || fm->table_id == OFPTT_ALL
4920 || fm->flags & OFPUTIL_FF_RESET_COUNTS
4921 || fm->buffer_id != UINT32_MAX) {
4922 return OFPERR_OFPFMFC_UNKNOWN;
4923 }
4924
4925 /* Check if the rule already exists, and we can get a reference to it. */
4926 struct oftable *table = &ofproto->tables[fm->table_id];
4927 struct rule *rule;
4928
4929 rule = rule_from_cls_rule(classifier_find_match_exactly(
4930 &table->cls, &fm->match, fm->priority,
4931 OVS_VERSION_MAX));
4932 if (rule) {
4933 /* Check if the rule's attributes match as well. */
4934 const struct rule_actions *actions;
4935
4936 ovs_mutex_lock(&rule->mutex);
4937 actions = rule_get_actions(rule);
4938 if (rule->idle_timeout == fm->idle_timeout
4939 && rule->hard_timeout == fm->hard_timeout
4940 && rule->importance == fm->importance
4941 && rule->flags == (fm->flags & OFPUTIL_FF_STATE)
4942 && (!fm->modify_cookie || (fm->new_cookie == rule->flow_cookie))
4943 && ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4944 actions->ofpacts, actions->ofpacts_len)) {
4945 /* Rule already exists and need not change, except for the modified
4946 * timestamp. Get a reference to the existing rule. */
4947 ovs_mutex_unlock(&rule->mutex);
4948 if (!ofproto_rule_try_ref(rule)) {
4949 rule = NULL; /* Pretend it did not exist. */
4950 }
4951 } else {
4952 ovs_mutex_unlock(&rule->mutex);
4953 rule = NULL;
4954 }
4955 }
4956
4957 /* Initialize ofproto_flow_mod for future use. */
4958 error = ofproto_flow_mod_init(ofproto, ofm, fm, rule);
4959 if (error) {
4960 ofproto_rule_unref(rule);
4961 return error;
4962 }
4963 return 0;
4964 }
4965
4966 enum ofperr
4967 ofproto_flow_mod_learn_refresh(struct ofproto_flow_mod *ofm)
4968 {
4969 enum ofperr error = 0;
4970
4971 /* ofm->temp_rule is our reference to the learned rule. We have a
4972 * reference to an existing rule, if it already was in the classifier,
4973 * otherwise we may have a fresh rule that we need to insert. */
4974 struct rule *rule = ofm->temp_rule;
4975 if (!rule) {
4976 return OFPERR_OFPFMFC_UNKNOWN;
4977 }
4978
4979 /* Create a new rule if the current one has been removed from the
4980 * classifier. We need to do this since RCU does not allow a current rule
4981 * to be reinserted before all threads have quiesced.
4982 *
4983 * It is possible that the rule is removed asynchronously, e.g., right
4984 * after we have read the 'rule->state' below. In this case the next time
4985 * this function is executed the rule will be reinstated. */
4986 if (rule->state == RULE_REMOVED) {
4987 struct cls_rule cr;
4988
4989 cls_rule_clone(&cr, &rule->cr);
4990 ovs_mutex_lock(&rule->mutex);
4991 error = ofproto_rule_create(rule->ofproto, &cr, rule->table_id,
4992 rule->flow_cookie,
4993 rule->idle_timeout,
4994 rule->hard_timeout, rule->flags,
4995 rule->importance,
4996 rule->actions->ofpacts,
4997 rule->actions->ofpacts_len,
4998 &ofm->temp_rule);
4999 ovs_mutex_unlock(&rule->mutex);
5000 if (!error) {
5001 ofproto_rule_unref(rule); /* Release old reference. */
5002 }
5003 } else {
5004 /* Refresh the existing rule. */
5005 ovs_mutex_lock(&rule->mutex);
5006 rule->modified = time_msec();
5007 ovs_mutex_unlock(&rule->mutex);
5008 }
5009 return error;
5010 }
5011
5012 enum ofperr
5013 ofproto_flow_mod_learn_start(struct ofproto_flow_mod *ofm)
5014 OVS_REQUIRES(ofproto_mutex)
5015 {
5016 struct rule *rule = ofm->temp_rule;
5017
5018 /* ofproto_flow_mod_start() consumes the reference, so we
5019 * take a new one. */
5020 ofproto_rule_ref(rule);
5021 enum ofperr error = ofproto_flow_mod_start(rule->ofproto, ofm);
5022 ofm->temp_rule = rule;
5023
5024 return error;
5025 }
5026
5027 void
5028 ofproto_flow_mod_learn_revert(struct ofproto_flow_mod *ofm)
5029 OVS_REQUIRES(ofproto_mutex)
5030 {
5031 struct rule *rule = rule_collection_rules(&ofm->new_rules)[0];
5032 ofproto_flow_mod_revert(rule->ofproto, ofm);
5033 }
5034
5035 void
5036 ofproto_flow_mod_learn_finish(struct ofproto_flow_mod *ofm,
5037 struct ofproto *orig_ofproto)
5038 OVS_REQUIRES(ofproto_mutex)
5039 {
5040 struct rule *rule = rule_collection_rules(&ofm->new_rules)[0];
5041
5042 /* If learning on a different bridge, must bump its version
5043 * number and flush connmgr afterwards. */
5044 if (rule->ofproto != orig_ofproto) {
5045 ofproto_bump_tables_version(rule->ofproto);
5046 }
5047 ofproto_flow_mod_finish(rule->ofproto, ofm, NULL);
5048 if (rule->ofproto != orig_ofproto) {
5049 ofmonitor_flush(rule->ofproto->connmgr);
5050 }
5051 }
5052
5053 /* Refresh 'ofm->temp_rule', for which the caller holds a reference, if already
5054 * in the classifier, insert it otherwise. If the rule has already been
5055 * removed from the classifier, a new rule is created using 'ofm->temp_rule' as
5056 * a template and the reference to the old 'ofm->temp_rule' is freed. If
5057 * 'keep_ref' is true, then a reference to the current rule is held, otherwise
5058 * it is released and 'ofm->temp_rule' is set to NULL.
5059 *
5060 * Caller needs to be the exclusive owner of 'ofm' as it is being manipulated
5061 * during the call. */
5062 enum ofperr
5063 ofproto_flow_mod_learn(struct ofproto_flow_mod *ofm, bool keep_ref)
5064 OVS_EXCLUDED(ofproto_mutex)
5065 {
5066 enum ofperr error = ofproto_flow_mod_learn_refresh(ofm);
5067 struct rule *rule = ofm->temp_rule;
5068
5069 /* Do we need to insert the rule? */
5070 if (!error && rule->state == RULE_INITIALIZED) {
5071 ovs_mutex_lock(&ofproto_mutex);
5072 ofm->version = rule->ofproto->tables_version + 1;
5073 error = ofproto_flow_mod_learn_start(ofm);
5074 if (!error) {
5075 ofproto_flow_mod_learn_finish(ofm, NULL);
5076 }
5077 ovs_mutex_unlock(&ofproto_mutex);
5078 }
5079
5080 if (!keep_ref) {
5081 ofproto_rule_unref(rule);
5082 ofm->temp_rule = NULL;
5083 }
5084 return error;
5085 }
5086
5087 static void
5088 replace_rule_start(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5089 struct rule *old_rule, struct rule *new_rule)
5090 {
5091 struct oftable *table = &ofproto->tables[new_rule->table_id];
5092
5093 /* 'old_rule' may be either an evicted rule or replaced rule. */
5094 if (old_rule) {
5095 /* Copy values from old rule for modify semantics. */
5096 if (old_rule->removed_reason != OFPRR_EVICTION) {
5097 bool change_cookie = (ofm->modify_cookie
5098 && new_rule->flow_cookie != OVS_BE64_MAX
5099 && new_rule->flow_cookie != old_rule->flow_cookie);
5100
5101 ovs_mutex_lock(&new_rule->mutex);
5102 ovs_mutex_lock(&old_rule->mutex);
5103 if (ofm->command != OFPFC_ADD) {
5104 new_rule->idle_timeout = old_rule->idle_timeout;
5105 new_rule->hard_timeout = old_rule->hard_timeout;
5106 *CONST_CAST(uint16_t *, &new_rule->importance) = old_rule->importance;
5107 new_rule->flags = old_rule->flags;
5108 new_rule->created = old_rule->created;
5109 }
5110 if (!change_cookie) {
5111 *CONST_CAST(ovs_be64 *, &new_rule->flow_cookie)
5112 = old_rule->flow_cookie;
5113 }
5114 ovs_mutex_unlock(&old_rule->mutex);
5115 ovs_mutex_unlock(&new_rule->mutex);
5116 }
5117
5118 /* Mark the old rule for removal in the next version. */
5119 cls_rule_make_invisible_in_version(&old_rule->cr, ofm->version);
5120
5121 /* Remove the old rule from data structures. */
5122 ofproto_rule_remove__(ofproto, old_rule);
5123 } else {
5124 table->n_flows++;
5125 }
5126 /* Insert flow to ofproto data structures, so that later flow_mods may
5127 * relate to it. This is reversible, in case later errors require this to
5128 * be reverted. */
5129 ofproto_rule_insert__(ofproto, new_rule);
5130 /* Make the new rule visible for classifier lookups only from the next
5131 * version. */
5132 classifier_insert(&table->cls, &new_rule->cr, ofm->version, ofm->conjs,
5133 ofm->n_conjs);
5134 }
5135
5136 static void
5137 replace_rule_revert(struct ofproto *ofproto,
5138 struct rule *old_rule, struct rule *new_rule)
5139 {
5140 struct oftable *table = &ofproto->tables[new_rule->table_id];
5141
5142 if (old_rule) {
5143 if (old_rule->removed_reason == OFPRR_EVICTION) {
5144 /* Revert the eviction. */
5145 eviction_group_add_rule(old_rule);
5146 }
5147
5148 /* Restore the old rule to data structures. */
5149 ofproto_rule_insert__(ofproto, old_rule);
5150
5151 /* Restore the original visibility of the old rule. */
5152 cls_rule_restore_visibility(&old_rule->cr);
5153 } else {
5154 /* Restore table's rule count. */
5155 table->n_flows--;
5156 }
5157
5158 /* Remove the new rule immediately. It was never visible to lookups. */
5159 if (!classifier_remove(&table->cls, &new_rule->cr)) {
5160 OVS_NOT_REACHED();
5161 }
5162 ofproto_rule_remove__(ofproto, new_rule);
5163 ofproto_rule_unref(new_rule);
5164 }
5165
5166 /* Adds the 'new_rule', replacing the 'old_rule'. */
5167 static void
5168 replace_rule_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5169 const struct openflow_mod_requester *req,
5170 struct rule *old_rule, struct rule *new_rule,
5171 struct ovs_list *dead_cookies)
5172 OVS_REQUIRES(ofproto_mutex)
5173 {
5174 struct rule *replaced_rule;
5175
5176 replaced_rule = (old_rule && old_rule->removed_reason != OFPRR_EVICTION)
5177 ? old_rule : NULL;
5178
5179 /* Insert the new flow to the ofproto provider. A non-NULL 'replaced_rule'
5180 * is a duplicate rule the 'new_rule' is replacing. The provider should
5181 * link the packet and byte counts from the old rule to the new one if
5182 * 'modify_keep_counts' is 'true'. The 'replaced_rule' will be deleted
5183 * right after this call. */
5184 ofproto->ofproto_class->rule_insert(new_rule, replaced_rule,
5185 ofm->modify_keep_counts);
5186 learned_cookies_inc(ofproto, rule_get_actions(new_rule));
5187
5188 if (old_rule) {
5189 const struct rule_actions *old_actions = rule_get_actions(old_rule);
5190 const struct rule_actions *new_actions = rule_get_actions(new_rule);
5191
5192 learned_cookies_dec(ofproto, old_actions, dead_cookies);
5193
5194 if (replaced_rule) {
5195 enum nx_flow_update_event event = ofm->command == OFPFC_ADD
5196 ? NXFME_ADDED : NXFME_MODIFIED;
5197
5198 bool changed_cookie = (new_rule->flow_cookie
5199 != old_rule->flow_cookie);
5200
5201 bool changed_actions = !ofpacts_equal(new_actions->ofpacts,
5202 new_actions->ofpacts_len,
5203 old_actions->ofpacts,
5204 old_actions->ofpacts_len);
5205
5206 if (event != NXFME_MODIFIED || changed_actions
5207 || changed_cookie) {
5208 ofmonitor_report(ofproto->connmgr, new_rule, event, 0,
5209 req ? req->ofconn : NULL,
5210 req ? req->request->xid : 0,
5211 changed_actions ? old_actions : NULL);
5212 }
5213 } else {
5214 /* XXX: This is slight duplication with delete_flows_finish__() */
5215 ofmonitor_report(ofproto->connmgr, old_rule, NXFME_DELETED,
5216 OFPRR_EVICTION,
5217 req ? req->ofconn : NULL,
5218 req ? req->request->xid : 0, NULL);
5219 }
5220 }
5221 }
5222
5223 /* ofm->temp_rule is consumed only in the successful case. */
5224 static enum ofperr
5225 modify_flows_start__(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5226 OVS_REQUIRES(ofproto_mutex)
5227 {
5228 struct rule_collection *old_rules = &ofm->old_rules;
5229 struct rule_collection *new_rules = &ofm->new_rules;
5230 enum ofperr error;
5231
5232 if (rule_collection_n(old_rules) > 0) {
5233 /* Create a new 'modified' rule for each old rule. */
5234 struct rule *old_rule, *new_rule;
5235 const struct rule_actions *actions = rule_get_actions(ofm->temp_rule);
5236
5237 /* Must check actions while holding ofproto_mutex to avoid a race. */
5238 error = ofproto_check_ofpacts(ofproto, actions->ofpacts,
5239 actions->ofpacts_len);
5240 if (error) {
5241 return error;
5242 }
5243
5244 /* Use the temp rule as the first new rule, and as the template for
5245 * the rest. */
5246 struct rule *temp = ofm->temp_rule;
5247 ofm->temp_rule = NULL; /* We consume the template. */
5248
5249 bool first = true;
5250 RULE_COLLECTION_FOR_EACH (old_rule, old_rules) {
5251 if (first) {
5252 /* The template rule's match is possibly a loose one, so it
5253 * must be replaced with the old rule's match so that the new
5254 * rule actually replaces the old one. */
5255 cls_rule_destroy(CONST_CAST(struct cls_rule *, &temp->cr));
5256 cls_rule_clone(CONST_CAST(struct cls_rule *, &temp->cr),
5257 &old_rule->cr);
5258 *CONST_CAST(uint8_t *, &temp->table_id) = old_rule->table_id;
5259 rule_collection_add(new_rules, temp);
5260 first = false;
5261 } else {
5262 struct cls_rule cr;
5263 cls_rule_clone(&cr, &old_rule->cr);
5264 error = ofproto_rule_create(ofproto, &cr, old_rule->table_id,
5265 temp->flow_cookie,
5266 temp->idle_timeout,
5267 temp->hard_timeout, temp->flags,
5268 temp->importance,
5269 temp->actions->ofpacts,
5270 temp->actions->ofpacts_len,
5271 &new_rule);
5272 if (!error) {
5273 rule_collection_add(new_rules, new_rule);
5274 } else {
5275 /* Return the template rule in place in the error case. */
5276 ofm->temp_rule = temp;
5277 rule_collection_rules(new_rules)[0] = NULL;
5278
5279 rule_collection_unref(new_rules);
5280 rule_collection_destroy(new_rules);
5281 return error;
5282 }
5283 }
5284 }
5285 ovs_assert(rule_collection_n(new_rules)
5286 == rule_collection_n(old_rules));
5287
5288 RULE_COLLECTIONS_FOR_EACH (old_rule, new_rule, old_rules, new_rules) {
5289 replace_rule_start(ofproto, ofm, old_rule, new_rule);
5290 }
5291 } else if (ofm->modify_may_add_flow) {
5292 /* No match, add a new flow, consumes 'temp'. */
5293 error = add_flow_start(ofproto, ofm);
5294 } else {
5295 /* No flow to modify and may not add a flow. */
5296 ofproto_rule_unref(ofm->temp_rule);
5297 ofm->temp_rule = NULL; /* We consume the template. */
5298 error = 0;
5299 }
5300
5301 return error;
5302 }
5303
5304 static enum ofperr
5305 modify_flows_init_loose(struct ofproto *ofproto,
5306 struct ofproto_flow_mod *ofm,
5307 const struct ofputil_flow_mod *fm)
5308 OVS_EXCLUDED(ofproto_mutex)
5309 {
5310 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, 0,
5311 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask, OFPP_ANY,
5312 OFPG_ANY);
5313 rule_criteria_require_rw(&ofm->criteria,
5314 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5315 /* Must create a new flow in advance for the case that no matches are
5316 * found. Also used for template for multiple modified flows. */
5317 add_flow_init(ofproto, ofm, fm);
5318
5319 return 0;
5320 }
5321
5322 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
5323 * failure. */
5324 static enum ofperr
5325 modify_flows_start_loose(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5326 OVS_REQUIRES(ofproto_mutex)
5327 {
5328 struct rule_collection *old_rules = &ofm->old_rules;
5329 enum ofperr error;
5330
5331 error = collect_rules_loose(ofproto, &ofm->criteria, old_rules);
5332
5333 if (!error) {
5334 error = modify_flows_start__(ofproto, ofm);
5335 }
5336
5337 if (error) {
5338 rule_collection_destroy(old_rules);
5339 }
5340
5341 return error;
5342 }
5343
5344 static void
5345 modify_flows_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5346 OVS_REQUIRES(ofproto_mutex)
5347 {
5348 struct rule_collection *old_rules = &ofm->old_rules;
5349 struct rule_collection *new_rules = &ofm->new_rules;
5350
5351 /* Old rules were not changed yet, only need to revert new rules. */
5352 if (rule_collection_n(old_rules) > 0) {
5353 struct rule *old_rule, *new_rule;
5354 RULE_COLLECTIONS_FOR_EACH (old_rule, new_rule, old_rules, new_rules) {
5355 replace_rule_revert(ofproto, old_rule, new_rule);
5356 }
5357 rule_collection_destroy(new_rules);
5358 rule_collection_destroy(old_rules);
5359 }
5360 }
5361
5362 static void
5363 modify_flows_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5364 const struct openflow_mod_requester *req)
5365 OVS_REQUIRES(ofproto_mutex)
5366 {
5367 struct rule_collection *old_rules = &ofm->old_rules;
5368 struct rule_collection *new_rules = &ofm->new_rules;
5369
5370 if (rule_collection_n(old_rules) == 0
5371 && rule_collection_n(new_rules) == 1) {
5372 add_flow_finish(ofproto, ofm, req);
5373 } else if (rule_collection_n(old_rules) > 0) {
5374 struct ovs_list dead_cookies = OVS_LIST_INITIALIZER(&dead_cookies);
5375
5376 ovs_assert(rule_collection_n(new_rules)
5377 == rule_collection_n(old_rules));
5378
5379 struct rule *old_rule, *new_rule;
5380 RULE_COLLECTIONS_FOR_EACH (old_rule, new_rule, old_rules, new_rules) {
5381 replace_rule_finish(ofproto, ofm, req, old_rule, new_rule,
5382 &dead_cookies);
5383 }
5384 learned_cookies_flush(ofproto, &dead_cookies);
5385 remove_rules_postponed(old_rules);
5386 }
5387 }
5388
5389 static enum ofperr
5390 modify_flow_init_strict(struct ofproto *ofproto OVS_UNUSED,
5391 struct ofproto_flow_mod *ofm,
5392 const struct ofputil_flow_mod *fm)
5393 OVS_EXCLUDED(ofproto_mutex)
5394 {
5395 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, fm->priority,
5396 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask, OFPP_ANY,
5397 OFPG_ANY);
5398 rule_criteria_require_rw(&ofm->criteria,
5399 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5400 /* Must create a new flow in advance for the case that no matches are
5401 * found. Also used for template for multiple modified flows. */
5402 add_flow_init(ofproto, ofm, fm);
5403
5404 return 0;
5405 }
5406
5407 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
5408 * code on failure. */
5409 static enum ofperr
5410 modify_flow_start_strict(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5411 OVS_REQUIRES(ofproto_mutex)
5412 {
5413 struct rule_collection *old_rules = &ofm->old_rules;
5414 enum ofperr error;
5415
5416 error = collect_rules_strict(ofproto, &ofm->criteria, old_rules);
5417
5418 if (!error) {
5419 /* collect_rules_strict() can return max 1 rule. */
5420 error = modify_flows_start__(ofproto, ofm);
5421 }
5422
5423 return error;
5424 }
5425 \f
5426 /* OFPFC_DELETE implementation. */
5427
5428 static void
5429 delete_flows_start__(struct ofproto *ofproto, ovs_version_t version,
5430 const struct rule_collection *rules)
5431 OVS_REQUIRES(ofproto_mutex)
5432 {
5433 struct rule *rule;
5434
5435 RULE_COLLECTION_FOR_EACH (rule, rules) {
5436 struct oftable *table = &ofproto->tables[rule->table_id];
5437
5438 table->n_flows--;
5439 cls_rule_make_invisible_in_version(&rule->cr, version);
5440
5441 /* Remove rule from ofproto data structures. */
5442 ofproto_rule_remove__(ofproto, rule);
5443 }
5444 }
5445
5446 static void
5447 delete_flows_revert__(struct ofproto *ofproto,
5448 const struct rule_collection *rules)
5449 OVS_REQUIRES(ofproto_mutex)
5450 {
5451 struct rule *rule;
5452
5453 RULE_COLLECTION_FOR_EACH (rule, rules) {
5454 struct oftable *table = &ofproto->tables[rule->table_id];
5455
5456 /* Add rule back to ofproto data structures. */
5457 ofproto_rule_insert__(ofproto, rule);
5458
5459 /* Restore table's rule count. */
5460 table->n_flows++;
5461
5462 /* Restore the original visibility of the rule. */
5463 cls_rule_restore_visibility(&rule->cr);
5464 }
5465 }
5466
5467 static void
5468 delete_flows_finish__(struct ofproto *ofproto,
5469 struct rule_collection *rules,
5470 enum ofp_flow_removed_reason reason,
5471 const struct openflow_mod_requester *req)
5472 OVS_REQUIRES(ofproto_mutex)
5473 {
5474 if (rule_collection_n(rules)) {
5475 struct ovs_list dead_cookies = OVS_LIST_INITIALIZER(&dead_cookies);
5476 struct rule *rule;
5477
5478 RULE_COLLECTION_FOR_EACH (rule, rules) {
5479 /* This value will be used to send the flow removed message right
5480 * before the rule is actually destroyed. */
5481 rule->removed_reason = reason;
5482
5483 ofmonitor_report(ofproto->connmgr, rule, NXFME_DELETED, reason,
5484 req ? req->ofconn : NULL,
5485 req ? req->request->xid : 0, NULL);
5486
5487 /* Send Vacancy Event for OF1.4+. */
5488 send_table_status(ofproto, rule->table_id);
5489
5490 learned_cookies_dec(ofproto, rule_get_actions(rule),
5491 &dead_cookies);
5492 }
5493 remove_rules_postponed(rules);
5494
5495 learned_cookies_flush(ofproto, &dead_cookies);
5496 }
5497 }
5498
5499 /* Deletes the rules listed in 'rules'.
5500 * The deleted rules will become invisible to the lookups in the next version.
5501 * Destroys 'rules'. */
5502 static void
5503 delete_flows__(struct rule_collection *rules,
5504 enum ofp_flow_removed_reason reason,
5505 const struct openflow_mod_requester *req)
5506 OVS_REQUIRES(ofproto_mutex)
5507 {
5508 if (rule_collection_n(rules)) {
5509 struct ofproto *ofproto = rule_collection_rules(rules)[0]->ofproto;
5510
5511 delete_flows_start__(ofproto, ofproto->tables_version + 1, rules);
5512 ofproto_bump_tables_version(ofproto);
5513 delete_flows_finish__(ofproto, rules, reason, req);
5514 ofmonitor_flush(ofproto->connmgr);
5515 }
5516 }
5517
5518 static enum ofperr
5519 delete_flows_init_loose(struct ofproto *ofproto OVS_UNUSED,
5520 struct ofproto_flow_mod *ofm,
5521 const struct ofputil_flow_mod *fm)
5522 OVS_EXCLUDED(ofproto_mutex)
5523 {
5524 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, 0,
5525 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask,
5526 fm->out_port, fm->out_group);
5527 rule_criteria_require_rw(&ofm->criteria,
5528 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5529 return 0;
5530 }
5531
5532 /* Implements OFPFC_DELETE. */
5533 static enum ofperr
5534 delete_flows_start_loose(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5535 OVS_REQUIRES(ofproto_mutex)
5536 {
5537 struct rule_collection *rules = &ofm->old_rules;
5538 enum ofperr error;
5539
5540 error = collect_rules_loose(ofproto, &ofm->criteria, rules);
5541
5542 if (!error) {
5543 delete_flows_start__(ofproto, ofm->version, rules);
5544 }
5545
5546 return error;
5547 }
5548
5549 static void
5550 delete_flows_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5551 OVS_REQUIRES(ofproto_mutex)
5552 {
5553 delete_flows_revert__(ofproto, &ofm->old_rules);
5554 }
5555
5556 static void
5557 delete_flows_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5558 const struct openflow_mod_requester *req)
5559 OVS_REQUIRES(ofproto_mutex)
5560 {
5561 delete_flows_finish__(ofproto, &ofm->old_rules, OFPRR_DELETE, req);
5562 }
5563
5564 static enum ofperr
5565 delete_flows_init_strict(struct ofproto *ofproto OVS_UNUSED,
5566 struct ofproto_flow_mod *ofm,
5567 const struct ofputil_flow_mod *fm)
5568 OVS_EXCLUDED(ofproto_mutex)
5569 {
5570 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, fm->priority,
5571 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask,
5572 fm->out_port, fm->out_group);
5573 rule_criteria_require_rw(&ofm->criteria,
5574 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5575 return 0;
5576 }
5577
5578 /* Implements OFPFC_DELETE_STRICT. */
5579 static enum ofperr
5580 delete_flow_start_strict(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5581 OVS_REQUIRES(ofproto_mutex)
5582 {
5583 struct rule_collection *rules = &ofm->old_rules;
5584 enum ofperr error;
5585
5586 error = collect_rules_strict(ofproto, &ofm->criteria, rules);
5587
5588 if (!error) {
5589 delete_flows_start__(ofproto, ofm->version, rules);
5590 }
5591
5592 return error;
5593 }
5594
5595 /* This may only be called by rule_destroy_cb()! */
5596 static void
5597 ofproto_rule_send_removed(struct rule *rule)
5598 OVS_EXCLUDED(ofproto_mutex)
5599 {
5600 struct ofputil_flow_removed fr;
5601 long long int used;
5602
5603 minimatch_expand(&rule->cr.match, &fr.match);
5604 fr.priority = rule->cr.priority;
5605
5606 /* Synchronize with connmgr_destroy() calls to prevent connmgr disappearing
5607 * while we use it. */
5608 ovs_mutex_lock(&ofproto_mutex);
5609 struct connmgr *connmgr = rule->ofproto->connmgr;
5610 if (!connmgr) {
5611 ovs_mutex_unlock(&ofproto_mutex);
5612 return;
5613 }
5614
5615 fr.cookie = rule->flow_cookie;
5616 fr.reason = rule->removed_reason;
5617 fr.table_id = rule->table_id;
5618 calc_duration(rule->created, time_msec(),
5619 &fr.duration_sec, &fr.duration_nsec);
5620 ovs_mutex_lock(&rule->mutex);
5621 fr.idle_timeout = rule->idle_timeout;
5622 fr.hard_timeout = rule->hard_timeout;
5623 ovs_mutex_unlock(&rule->mutex);
5624 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
5625 &fr.byte_count, &used);
5626 connmgr_send_flow_removed(connmgr, &fr);
5627 ovs_mutex_unlock(&ofproto_mutex);
5628 }
5629
5630 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
5631 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
5632 * ofproto.
5633 *
5634 * ofproto implementation ->run() functions should use this function to expire
5635 * OpenFlow flows. */
5636 void
5637 ofproto_rule_expire(struct rule *rule, uint8_t reason)
5638 OVS_REQUIRES(ofproto_mutex)
5639 {
5640 struct rule_collection rules;
5641
5642 rule_collection_init(&rules);
5643 rule_collection_add(&rules, rule);
5644 delete_flows__(&rules, reason, NULL);
5645 }
5646
5647 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
5648 * means "infinite". */
5649 static void
5650 reduce_timeout(uint16_t max, uint16_t *timeout)
5651 {
5652 if (max && (!*timeout || *timeout > max)) {
5653 *timeout = max;
5654 }
5655 }
5656
5657 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
5658 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
5659 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
5660 *
5661 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
5662 void
5663 ofproto_rule_reduce_timeouts__(struct rule *rule,
5664 uint16_t idle_timeout, uint16_t hard_timeout)
5665 OVS_REQUIRES(ofproto_mutex)
5666 OVS_EXCLUDED(rule->mutex)
5667 {
5668 if (!idle_timeout && !hard_timeout) {
5669 return;
5670 }
5671
5672 if (ovs_list_is_empty(&rule->expirable)) {
5673 ovs_list_insert(&rule->ofproto->expirable, &rule->expirable);
5674 }
5675
5676 ovs_mutex_lock(&rule->mutex);
5677 reduce_timeout(idle_timeout, &rule->idle_timeout);
5678 reduce_timeout(hard_timeout, &rule->hard_timeout);
5679 ovs_mutex_unlock(&rule->mutex);
5680 }
5681
5682 void
5683 ofproto_rule_reduce_timeouts(struct rule *rule,
5684 uint16_t idle_timeout, uint16_t hard_timeout)
5685 OVS_EXCLUDED(ofproto_mutex, rule->mutex)
5686 {
5687 if (!idle_timeout && !hard_timeout) {
5688 return;
5689 }
5690
5691 ovs_mutex_lock(&ofproto_mutex);
5692 if (ovs_list_is_empty(&rule->expirable)) {
5693 ovs_list_insert(&rule->ofproto->expirable, &rule->expirable);
5694 }
5695 ovs_mutex_unlock(&ofproto_mutex);
5696
5697 ovs_mutex_lock(&rule->mutex);
5698 reduce_timeout(idle_timeout, &rule->idle_timeout);
5699 reduce_timeout(hard_timeout, &rule->hard_timeout);
5700 ovs_mutex_unlock(&rule->mutex);
5701 }
5702 \f
5703 static enum ofperr
5704 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5705 OVS_EXCLUDED(ofproto_mutex)
5706 {
5707 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5708 struct ofputil_flow_mod fm;
5709 uint64_t ofpacts_stub[1024 / 8];
5710 struct ofpbuf ofpacts;
5711 enum ofperr error;
5712
5713 error = reject_slave_controller(ofconn);
5714 if (error) {
5715 return error;
5716 }
5717
5718 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
5719 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
5720 ofproto_get_tun_tab(ofproto),
5721 &ofproto->vl_mff_map, &ofpacts,
5722 u16_to_ofp(ofproto->max_ports),
5723 ofproto->n_tables);
5724 if (!error) {
5725 struct openflow_mod_requester req = { ofconn, oh };
5726 error = handle_flow_mod__(ofproto, &fm, &req);
5727 }
5728
5729 ofpbuf_uninit(&ofpacts);
5730 return error;
5731 }
5732
5733 static enum ofperr
5734 handle_flow_mod__(struct ofproto *ofproto, const struct ofputil_flow_mod *fm,
5735 const struct openflow_mod_requester *req)
5736 OVS_EXCLUDED(ofproto_mutex)
5737 {
5738 struct ofproto_flow_mod ofm;
5739 enum ofperr error;
5740
5741 error = ofproto_flow_mod_init(ofproto, &ofm, fm, NULL);
5742 if (error) {
5743 return error;
5744 }
5745
5746 ovs_mutex_lock(&ofproto_mutex);
5747 ofm.version = ofproto->tables_version + 1;
5748 error = ofproto_flow_mod_start(ofproto, &ofm);
5749 if (!error) {
5750 ofproto_bump_tables_version(ofproto);
5751 ofproto_flow_mod_finish(ofproto, &ofm, req);
5752 ofmonitor_flush(ofproto->connmgr);
5753 }
5754 ovs_mutex_unlock(&ofproto_mutex);
5755
5756 return error;
5757 }
5758
5759 static enum ofperr
5760 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
5761 {
5762 struct ofputil_role_request request;
5763 struct ofputil_role_request reply;
5764 struct ofpbuf *buf;
5765 enum ofperr error;
5766
5767 error = ofputil_decode_role_message(oh, &request);
5768 if (error) {
5769 return error;
5770 }
5771
5772 if (request.role != OFPCR12_ROLE_NOCHANGE) {
5773 if (request.role != OFPCR12_ROLE_EQUAL
5774 && request.have_generation_id
5775 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
5776 return OFPERR_OFPRRFC_STALE;
5777 }
5778
5779 ofconn_set_role(ofconn, request.role);
5780 }
5781
5782 reply.role = ofconn_get_role(ofconn);
5783 reply.have_generation_id = ofconn_get_master_election_id(
5784 ofconn, &reply.generation_id);
5785 buf = ofputil_encode_role_reply(oh, &reply);
5786 ofconn_send_reply(ofconn, buf);
5787
5788 return 0;
5789 }
5790
5791 static enum ofperr
5792 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
5793 const struct ofp_header *oh)
5794 {
5795 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
5796 enum ofputil_protocol cur, next;
5797
5798 cur = ofconn_get_protocol(ofconn);
5799 next = ofputil_protocol_set_tid(cur, msg->set != 0);
5800 ofconn_set_protocol(ofconn, next);
5801
5802 return 0;
5803 }
5804
5805 static enum ofperr
5806 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
5807 {
5808 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
5809 enum ofputil_protocol cur, next;
5810 enum ofputil_protocol next_base;
5811
5812 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
5813 if (!next_base) {
5814 return OFPERR_OFPBRC_EPERM;
5815 }
5816
5817 cur = ofconn_get_protocol(ofconn);
5818 next = ofputil_protocol_set_base(cur, next_base);
5819 ofconn_set_protocol(ofconn, next);
5820
5821 return 0;
5822 }
5823
5824 static enum ofperr
5825 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
5826 const struct ofp_header *oh)
5827 {
5828 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
5829 uint32_t format;
5830
5831 format = ntohl(msg->format);
5832 if (!ofputil_packet_in_format_is_valid(format)) {
5833 return OFPERR_OFPBRC_EPERM;
5834 }
5835
5836 ofconn_set_packet_in_format(ofconn, format);
5837 return 0;
5838 }
5839
5840 static enum ofperr
5841 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
5842 {
5843 struct ofputil_async_cfg basis = ofconn_get_async_config(ofconn);
5844 struct ofputil_async_cfg ac;
5845 enum ofperr error;
5846
5847 error = ofputil_decode_set_async_config(oh, false, &basis, &ac);
5848 if (error) {
5849 return error;
5850 }
5851
5852 ofconn_set_async_config(ofconn, &ac);
5853 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
5854 !ofconn_get_miss_send_len(ofconn)) {
5855 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
5856 }
5857
5858 return 0;
5859 }
5860
5861 static enum ofperr
5862 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
5863 {
5864 struct ofputil_async_cfg ac = ofconn_get_async_config(ofconn);
5865 ofconn_send_reply(ofconn, ofputil_encode_get_async_reply(oh, &ac));
5866
5867 return 0;
5868 }
5869
5870 static enum ofperr
5871 handle_nxt_set_controller_id(struct ofconn *ofconn,
5872 const struct ofp_header *oh)
5873 {
5874 const struct nx_controller_id *nci = ofpmsg_body(oh);
5875
5876 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
5877 return OFPERR_NXBRC_MUST_BE_ZERO;
5878 }
5879
5880 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
5881 return 0;
5882 }
5883
5884 static enum ofperr
5885 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
5886 {
5887 struct ofpbuf *buf;
5888
5889 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
5890 ? OFPRAW_OFPT10_BARRIER_REPLY
5891 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
5892 ofconn_send_reply(ofconn, buf);
5893 return 0;
5894 }
5895
5896 static void
5897 ofproto_compose_flow_refresh_update(const struct rule *rule,
5898 enum nx_flow_monitor_flags flags,
5899 struct ovs_list *msgs,
5900 const struct tun_table *tun_table)
5901 OVS_REQUIRES(ofproto_mutex)
5902 {
5903 const struct rule_actions *actions;
5904 struct ofputil_flow_update fu;
5905
5906 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
5907 ? NXFME_ADDED : NXFME_MODIFIED);
5908 fu.reason = 0;
5909 ovs_mutex_lock(&rule->mutex);
5910 fu.idle_timeout = rule->idle_timeout;
5911 fu.hard_timeout = rule->hard_timeout;
5912 ovs_mutex_unlock(&rule->mutex);
5913 fu.table_id = rule->table_id;
5914 fu.cookie = rule->flow_cookie;
5915 minimatch_expand(&rule->cr.match, &fu.match);
5916 fu.priority = rule->cr.priority;
5917
5918 actions = flags & NXFMF_ACTIONS ? rule_get_actions(rule) : NULL;
5919 fu.ofpacts = actions ? actions->ofpacts : NULL;
5920 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
5921
5922 if (ovs_list_is_empty(msgs)) {
5923 ofputil_start_flow_update(msgs);
5924 }
5925 ofputil_append_flow_update(&fu, msgs, tun_table);
5926 }
5927
5928 void
5929 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
5930 struct ovs_list *msgs)
5931 OVS_REQUIRES(ofproto_mutex)
5932 {
5933 struct rule *rule;
5934
5935 RULE_COLLECTION_FOR_EACH (rule, rules) {
5936 enum nx_flow_monitor_flags flags = rule->monitor_flags;
5937 rule->monitor_flags = 0;
5938
5939 ofproto_compose_flow_refresh_update(rule, flags, msgs,
5940 ofproto_get_tun_tab(rule->ofproto));
5941 }
5942 }
5943
5944 static void
5945 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
5946 struct rule *rule, uint64_t seqno,
5947 struct rule_collection *rules)
5948 OVS_REQUIRES(ofproto_mutex)
5949 {
5950 enum nx_flow_monitor_flags update;
5951
5952 if (rule_is_hidden(rule)) {
5953 return;
5954 }
5955
5956 if (!ofproto_rule_has_out_port(rule, m->out_port)) {
5957 return;
5958 }
5959
5960 if (seqno) {
5961 if (rule->add_seqno > seqno) {
5962 update = NXFMF_ADD | NXFMF_MODIFY;
5963 } else if (rule->modify_seqno > seqno) {
5964 update = NXFMF_MODIFY;
5965 } else {
5966 return;
5967 }
5968
5969 if (!(m->flags & update)) {
5970 return;
5971 }
5972 } else {
5973 update = NXFMF_INITIAL;
5974 }
5975
5976 if (!rule->monitor_flags) {
5977 rule_collection_add(rules, rule);
5978 }
5979 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
5980 }
5981
5982 static void
5983 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
5984 uint64_t seqno,
5985 struct rule_collection *rules)
5986 OVS_REQUIRES(ofproto_mutex)
5987 {
5988 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
5989 const struct oftable *table;
5990 struct cls_rule target;
5991
5992 cls_rule_init_from_minimatch(&target, &m->match, 0);
5993 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
5994 struct rule *rule;
5995
5996 CLS_FOR_EACH_TARGET (rule, cr, &table->cls, &target, OVS_VERSION_MAX) {
5997 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
5998 }
5999 }
6000 cls_rule_destroy(&target);
6001 }
6002
6003 static void
6004 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
6005 struct rule_collection *rules)
6006 OVS_REQUIRES(ofproto_mutex)
6007 {
6008 if (m->flags & NXFMF_INITIAL) {
6009 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
6010 }
6011 }
6012
6013 void
6014 ofmonitor_collect_resume_rules(struct ofmonitor *m,
6015 uint64_t seqno, struct rule_collection *rules)
6016 OVS_REQUIRES(ofproto_mutex)
6017 {
6018 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
6019 }
6020
6021 static enum ofperr
6022 flow_monitor_delete(struct ofconn *ofconn, uint32_t id)
6023 OVS_REQUIRES(ofproto_mutex)
6024 {
6025 struct ofmonitor *m;
6026 enum ofperr error;
6027
6028 m = ofmonitor_lookup(ofconn, id);
6029 if (m) {
6030 ofmonitor_destroy(m);
6031 error = 0;
6032 } else {
6033 error = OFPERR_OFPMOFC_UNKNOWN_MONITOR;
6034 }
6035
6036 return error;
6037 }
6038
6039 static enum ofperr
6040 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
6041 OVS_EXCLUDED(ofproto_mutex)
6042 {
6043 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6044
6045 struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
6046
6047 struct ofmonitor **monitors = NULL;
6048 size_t allocated_monitors = 0;
6049 size_t n_monitors = 0;
6050
6051 enum ofperr error;
6052
6053 ovs_mutex_lock(&ofproto_mutex);
6054 for (;;) {
6055 struct ofputil_flow_monitor_request request;
6056 struct ofmonitor *m;
6057 int retval;
6058
6059 retval = ofputil_decode_flow_monitor_request(&request, &b);
6060 if (retval == EOF) {
6061 break;
6062 } else if (retval) {
6063 error = retval;
6064 goto error;
6065 }
6066
6067 if (request.table_id != 0xff
6068 && request.table_id >= ofproto->n_tables) {
6069 error = OFPERR_OFPBRC_BAD_TABLE_ID;
6070 goto error;
6071 }
6072
6073 error = ofmonitor_create(&request, ofconn, &m);
6074 if (error) {
6075 goto error;
6076 }
6077
6078 if (n_monitors >= allocated_monitors) {
6079 monitors = x2nrealloc(monitors, &allocated_monitors,
6080 sizeof *monitors);
6081 }
6082 monitors[n_monitors++] = m;
6083 }
6084
6085 struct rule_collection rules;
6086 rule_collection_init(&rules);
6087 for (size_t i = 0; i < n_monitors; i++) {
6088 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
6089 }
6090
6091 struct ovs_list replies;
6092 ofpmp_init(&replies, oh);
6093 ofmonitor_compose_refresh_updates(&rules, &replies);
6094 ovs_mutex_unlock(&ofproto_mutex);
6095
6096 rule_collection_destroy(&rules);
6097
6098 ofconn_send_replies(ofconn, &replies);
6099 free(monitors);
6100
6101 return 0;
6102
6103 error:
6104 for (size_t i = 0; i < n_monitors; i++) {
6105 ofmonitor_destroy(monitors[i]);
6106 }
6107 free(monitors);
6108 ovs_mutex_unlock(&ofproto_mutex);
6109
6110 return error;
6111 }
6112
6113 static enum ofperr
6114 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
6115 OVS_EXCLUDED(ofproto_mutex)
6116 {
6117 enum ofperr error;
6118 uint32_t id;
6119
6120 id = ofputil_decode_flow_monitor_cancel(oh);
6121
6122 ovs_mutex_lock(&ofproto_mutex);
6123 error = flow_monitor_delete(ofconn, id);
6124 ovs_mutex_unlock(&ofproto_mutex);
6125
6126 return error;
6127 }
6128
6129 /* Meters implementation.
6130 *
6131 * Meter table entry, indexed by the OpenFlow meter_id.
6132 * 'created' is used to compute the duration for meter stats.
6133 * 'list rules' is needed so that we can delete the dependent rules when the
6134 * meter table entry is deleted.
6135 * 'provider_meter_id' is for the provider's private use.
6136 */
6137 struct meter {
6138 long long int created; /* Time created. */
6139 struct ovs_list rules; /* List of "struct rule_dpif"s. */
6140 ofproto_meter_id provider_meter_id;
6141 uint16_t flags; /* Meter flags. */
6142 uint16_t n_bands; /* Number of meter bands. */
6143 struct ofputil_meter_band *bands;
6144 };
6145
6146 /*
6147 * This is used in instruction validation at flow set-up time,
6148 * as flows may not use non-existing meters.
6149 * Return value of UINT32_MAX signifies an invalid meter.
6150 */
6151 static uint32_t
6152 get_provider_meter_id(const struct ofproto *ofproto, uint32_t of_meter_id)
6153 {
6154 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
6155 const struct meter *meter = ofproto->meters[of_meter_id];
6156 if (meter) {
6157 return meter->provider_meter_id.uint32;
6158 }
6159 }
6160 return UINT32_MAX;
6161 }
6162
6163 /* Finds the meter invoked by 'rule''s actions and adds 'rule' to the meter's
6164 * list of rules. */
6165 static void
6166 meter_insert_rule(struct rule *rule)
6167 {
6168 const struct rule_actions *a = rule_get_actions(rule);
6169 uint32_t meter_id = ofpacts_get_meter(a->ofpacts, a->ofpacts_len);
6170 struct meter *meter = rule->ofproto->meters[meter_id];
6171
6172 ovs_list_insert(&meter->rules, &rule->meter_list_node);
6173 }
6174
6175 static void
6176 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
6177 {
6178 free(meter->bands);
6179
6180 meter->flags = config->flags;
6181 meter->n_bands = config->n_bands;
6182 meter->bands = xmemdup(config->bands,
6183 config->n_bands * sizeof *meter->bands);
6184 }
6185
6186 static struct meter *
6187 meter_create(const struct ofputil_meter_config *config,
6188 ofproto_meter_id provider_meter_id)
6189 {
6190 struct meter *meter;
6191
6192 meter = xzalloc(sizeof *meter);
6193 meter->provider_meter_id = provider_meter_id;
6194 meter->created = time_msec();
6195 ovs_list_init(&meter->rules);
6196
6197 meter_update(meter, config);
6198
6199 return meter;
6200 }
6201
6202 static void
6203 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
6204 OVS_REQUIRES(ofproto_mutex)
6205 {
6206 for (uint32_t mid = first; mid <= last; ++mid) {
6207 struct meter *meter = ofproto->meters[mid];
6208 if (meter) {
6209 /* First delete the rules that use this meter. */
6210 if (!ovs_list_is_empty(&meter->rules)) {
6211 struct rule_collection rules;
6212 struct rule *rule;
6213
6214 rule_collection_init(&rules);
6215
6216 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
6217 rule_collection_add(&rules, rule);
6218 }
6219 delete_flows__(&rules, OFPRR_METER_DELETE, NULL);
6220 }
6221
6222 ofproto->meters[mid] = NULL;
6223 ofproto->ofproto_class->meter_del(ofproto,
6224 meter->provider_meter_id);
6225 free(meter->bands);
6226 free(meter);
6227 }
6228 }
6229 }
6230
6231 static enum ofperr
6232 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
6233 {
6234 ofproto_meter_id provider_meter_id = { UINT32_MAX };
6235 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
6236 enum ofperr error;
6237
6238 if (*meterp) {
6239 return OFPERR_OFPMMFC_METER_EXISTS;
6240 }
6241
6242 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
6243 &mm->meter);
6244 if (!error) {
6245 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
6246 *meterp = meter_create(&mm->meter, provider_meter_id);
6247 }
6248 return error;
6249 }
6250
6251 static enum ofperr
6252 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
6253 {
6254 struct meter *meter = ofproto->meters[mm->meter.meter_id];
6255 enum ofperr error;
6256 uint32_t provider_meter_id;
6257
6258 if (!meter) {
6259 return OFPERR_OFPMMFC_UNKNOWN_METER;
6260 }
6261
6262 provider_meter_id = meter->provider_meter_id.uint32;
6263 error = ofproto->ofproto_class->meter_set(ofproto,
6264 &meter->provider_meter_id,
6265 &mm->meter);
6266 ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
6267 if (!error) {
6268 meter_update(meter, &mm->meter);
6269 }
6270 return error;
6271 }
6272
6273 static enum ofperr
6274 handle_delete_meter(struct ofconn *ofconn, struct ofputil_meter_mod *mm)
6275 OVS_EXCLUDED(ofproto_mutex)
6276 {
6277 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6278 uint32_t meter_id = mm->meter.meter_id;
6279 enum ofperr error = 0;
6280 uint32_t first, last;
6281
6282 if (meter_id == OFPM13_ALL) {
6283 first = 1;
6284 last = ofproto->meter_features.max_meters;
6285 } else {
6286 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
6287 return 0;
6288 }
6289 first = last = meter_id;
6290 }
6291
6292 /* Delete the meters. */
6293 ovs_mutex_lock(&ofproto_mutex);
6294 meter_delete(ofproto, first, last);
6295 ovs_mutex_unlock(&ofproto_mutex);
6296
6297 return error;
6298 }
6299
6300 static enum ofperr
6301 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
6302 {
6303 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6304 struct ofputil_meter_mod mm;
6305 uint64_t bands_stub[256 / 8];
6306 struct ofpbuf bands;
6307 uint32_t meter_id;
6308 enum ofperr error;
6309
6310 error = reject_slave_controller(ofconn);
6311 if (error) {
6312 return error;
6313 }
6314
6315 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
6316
6317 error = ofputil_decode_meter_mod(oh, &mm, &bands);
6318 if (error) {
6319 goto exit_free_bands;
6320 }
6321
6322 meter_id = mm.meter.meter_id;
6323
6324 if (mm.command != OFPMC13_DELETE) {
6325 /* Fails also when meters are not implemented by the provider. */
6326 if (meter_id == 0 || meter_id > OFPM13_MAX) {
6327 error = OFPERR_OFPMMFC_INVALID_METER;
6328 goto exit_free_bands;
6329 } else if (meter_id > ofproto->meter_features.max_meters) {
6330 error = OFPERR_OFPMMFC_OUT_OF_METERS;
6331 goto exit_free_bands;
6332 }
6333 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
6334 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
6335 goto exit_free_bands;
6336 }
6337 }
6338
6339 switch (mm.command) {
6340 case OFPMC13_ADD:
6341 error = handle_add_meter(ofproto, &mm);
6342 break;
6343
6344 case OFPMC13_MODIFY:
6345 error = handle_modify_meter(ofproto, &mm);
6346 break;
6347
6348 case OFPMC13_DELETE:
6349 error = handle_delete_meter(ofconn, &mm);
6350 break;
6351
6352 default:
6353 error = OFPERR_OFPMMFC_BAD_COMMAND;
6354 break;
6355 }
6356
6357 if (!error) {
6358 struct ofputil_requestforward rf;
6359 rf.xid = oh->xid;
6360 rf.reason = OFPRFR_METER_MOD;
6361 rf.meter_mod = &mm;
6362 connmgr_send_requestforward(ofproto->connmgr, ofconn, &rf);
6363 }
6364
6365 exit_free_bands:
6366 ofpbuf_uninit(&bands);
6367 return error;
6368 }
6369
6370 static enum ofperr
6371 handle_meter_features_request(struct ofconn *ofconn,
6372 const struct ofp_header *request)
6373 {
6374 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6375 struct ofputil_meter_features features;
6376 struct ofpbuf *b;
6377
6378 if (ofproto->ofproto_class->meter_get_features) {
6379 ofproto->ofproto_class->meter_get_features(ofproto, &features);
6380 } else {
6381 memset(&features, 0, sizeof features);
6382 }
6383 b = ofputil_encode_meter_features_reply(&features, request);
6384
6385 ofconn_send_reply(ofconn, b);
6386 return 0;
6387 }
6388
6389 static enum ofperr
6390 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
6391 enum ofptype type)
6392 {
6393 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6394 struct ovs_list replies;
6395 uint64_t bands_stub[256 / 8];
6396 struct ofpbuf bands;
6397 uint32_t meter_id, first, last;
6398
6399 ofputil_decode_meter_request(request, &meter_id);
6400
6401 if (meter_id == OFPM13_ALL) {
6402 first = 1;
6403 last = ofproto->meter_features.max_meters;
6404 } else {
6405 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
6406 !ofproto->meters[meter_id]) {
6407 return OFPERR_OFPMMFC_UNKNOWN_METER;
6408 }
6409 first = last = meter_id;
6410 }
6411
6412 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
6413 ofpmp_init(&replies, request);
6414
6415 for (meter_id = first; meter_id <= last; ++meter_id) {
6416 struct meter *meter = ofproto->meters[meter_id];
6417 if (!meter) {
6418 continue; /* Skip non-existing meters. */
6419 }
6420 if (type == OFPTYPE_METER_STATS_REQUEST) {
6421 struct ofputil_meter_stats stats;
6422
6423 stats.meter_id = meter_id;
6424
6425 /* Provider sets the packet and byte counts, we do the rest. */
6426 stats.flow_count = ovs_list_size(&meter->rules);
6427 calc_duration(meter->created, time_msec(),
6428 &stats.duration_sec, &stats.duration_nsec);
6429 stats.n_bands = meter->n_bands;
6430 ofpbuf_clear(&bands);
6431 stats.bands
6432 = ofpbuf_put_uninit(&bands,
6433 meter->n_bands * sizeof *stats.bands);
6434
6435 if (!ofproto->ofproto_class->meter_get(ofproto,
6436 meter->provider_meter_id,
6437 &stats)) {
6438 ofputil_append_meter_stats(&replies, &stats);
6439 }
6440 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
6441 struct ofputil_meter_config config;
6442
6443 config.meter_id = meter_id;
6444 config.flags = meter->flags;
6445 config.n_bands = meter->n_bands;
6446 config.bands = meter->bands;
6447 ofputil_append_meter_config(&replies, &config);
6448 }
6449 }
6450
6451 ofconn_send_replies(ofconn, &replies);
6452 ofpbuf_uninit(&bands);
6453 return 0;
6454 }
6455
6456 /* Returned group is RCU protected. */
6457 static struct ofgroup *
6458 ofproto_group_lookup__(const struct ofproto *ofproto, uint32_t group_id,
6459 ovs_version_t version)
6460 {
6461 struct ofgroup *group;
6462
6463 CMAP_FOR_EACH_WITH_HASH (group, cmap_node, hash_int(group_id, 0),
6464 &ofproto->groups) {
6465 if (group->group_id == group_id
6466 && versions_visible_in_version(&group->versions, version)) {
6467 return group;
6468 }
6469 }
6470
6471 return NULL;
6472 }
6473
6474 /* If the group exists, this function increments the groups's reference count.
6475 *
6476 * Make sure to call ofproto_group_unref() after no longer needing to maintain
6477 * a reference to the group. */
6478 struct ofgroup *
6479 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
6480 ovs_version_t version, bool take_ref)
6481 {
6482 struct ofgroup *group;
6483
6484 group = ofproto_group_lookup__(ofproto, group_id, version);
6485 if (group && take_ref) {
6486 /* Not holding a lock, so it is possible that another thread releases
6487 * the last reference just before we manage to get one. */
6488 return ofproto_group_try_ref(group) ? group : NULL;
6489 }
6490 return group;
6491 }
6492
6493 /* Caller should hold 'ofproto_mutex' if it is important that the
6494 * group is not removed by someone else. */
6495 static bool
6496 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
6497 {
6498 return ofproto_group_lookup__(ofproto, group_id, OVS_VERSION_MAX) != NULL;
6499 }
6500
6501 static void
6502 group_add_rule(struct ofgroup *group, struct rule *rule)
6503 {
6504 rule_collection_add(&group->rules, rule);
6505 }
6506
6507 static void
6508 group_remove_rule(struct ofgroup *group, struct rule *rule)
6509 {
6510 rule_collection_remove(&group->rules, rule);
6511 }
6512
6513 static void
6514 append_group_stats(struct ofgroup *group, struct ovs_list *replies)
6515 OVS_REQUIRES(ofproto_mutex)
6516 {
6517 struct ofputil_group_stats ogs;
6518 const struct ofproto *ofproto = group->ofproto;
6519 long long int now = time_msec();
6520 int error;
6521
6522 ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
6523
6524 /* Provider sets the packet and byte counts, we do the rest. */
6525 ogs.ref_count = rule_collection_n(&group->rules);
6526 ogs.n_buckets = group->n_buckets;
6527
6528 error = (ofproto->ofproto_class->group_get_stats
6529 ? ofproto->ofproto_class->group_get_stats(group, &ogs)
6530 : EOPNOTSUPP);
6531 if (error) {
6532 ogs.packet_count = UINT64_MAX;
6533 ogs.byte_count = UINT64_MAX;
6534 memset(ogs.bucket_stats, 0xff,
6535 ogs.n_buckets * sizeof *ogs.bucket_stats);
6536 }
6537
6538 ogs.group_id = group->group_id;
6539 calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
6540
6541 ofputil_append_group_stats(replies, &ogs);
6542
6543 free(ogs.bucket_stats);
6544 }
6545
6546 static void
6547 handle_group_request(struct ofconn *ofconn,
6548 const struct ofp_header *request, uint32_t group_id,
6549 void (*cb)(struct ofgroup *, struct ovs_list *replies))
6550 OVS_EXCLUDED(ofproto_mutex)
6551 {
6552 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6553 struct ofgroup *group;
6554 struct ovs_list replies;
6555
6556 ofpmp_init(&replies, request);
6557 /* Must exclude modifications to guarantee iterating groups. */
6558 ovs_mutex_lock(&ofproto_mutex);
6559 if (group_id == OFPG_ALL) {
6560 CMAP_FOR_EACH (group, cmap_node, &ofproto->groups) {
6561 cb(group, &replies);
6562 }
6563 } else {
6564 group = ofproto_group_lookup__(ofproto, group_id, OVS_VERSION_MAX);
6565 if (group) {
6566 cb(group, &replies);
6567 }
6568 }
6569 ovs_mutex_unlock(&ofproto_mutex);
6570 ofconn_send_replies(ofconn, &replies);
6571 }
6572
6573 static enum ofperr
6574 handle_group_stats_request(struct ofconn *ofconn,
6575 const struct ofp_header *request)
6576 {
6577 uint32_t group_id;
6578 enum ofperr error;
6579
6580 error = ofputil_decode_group_stats_request(request, &group_id);
6581 if (error) {
6582 return error;
6583 }
6584
6585 handle_group_request(ofconn, request, group_id, append_group_stats);
6586 return 0;
6587 }
6588
6589 static void
6590 append_group_desc(struct ofgroup *group, struct ovs_list *replies)
6591 {
6592 struct ofputil_group_desc gds;
6593
6594 gds.group_id = group->group_id;
6595 gds.type = group->type;
6596 gds.props = group->props;
6597
6598 ofputil_append_group_desc_reply(&gds, &group->buckets, replies);
6599 }
6600
6601 static enum ofperr
6602 handle_group_desc_stats_request(struct ofconn *ofconn,
6603 const struct ofp_header *request)
6604 {
6605 handle_group_request(ofconn, request,
6606 ofputil_decode_group_desc_request(request),
6607 append_group_desc);
6608 return 0;
6609 }
6610
6611 static enum ofperr
6612 handle_group_features_stats_request(struct ofconn *ofconn,
6613 const struct ofp_header *request)
6614 {
6615 struct ofproto *p = ofconn_get_ofproto(ofconn);
6616 struct ofpbuf *msg;
6617
6618 msg = ofputil_encode_group_features_reply(&p->ogf, request);
6619 if (msg) {
6620 ofconn_send_reply(ofconn, msg);
6621 }
6622
6623 return 0;
6624 }
6625
6626 static void
6627 put_queue_get_config_reply(struct ofport *port, uint32_t queue,
6628 struct ovs_list *replies)
6629 {
6630 struct ofputil_queue_config qc;
6631
6632 /* None of the existing queues have compatible properties, so we hard-code
6633 * omitting min_rate and max_rate. */
6634 qc.port = port->ofp_port;
6635 qc.queue = queue;
6636 qc.min_rate = UINT16_MAX;
6637 qc.max_rate = UINT16_MAX;
6638 ofputil_append_queue_get_config_reply(&qc, replies);
6639 }
6640
6641 static int
6642 handle_queue_get_config_request_for_port(struct ofport *port, uint32_t queue,
6643 struct ovs_list *replies)
6644 {
6645 struct smap details = SMAP_INITIALIZER(&details);
6646 if (queue != OFPQ_ALL) {
6647 int error = netdev_get_queue(port->netdev, queue, &details);
6648 switch (error) {
6649 case 0:
6650 put_queue_get_config_reply(port, queue, replies);
6651 break;
6652 case EOPNOTSUPP:
6653 case EINVAL:
6654 return OFPERR_OFPQOFC_BAD_QUEUE;
6655 default:
6656 return OFPERR_NXQOFC_QUEUE_ERROR;
6657 }
6658 } else {
6659 struct netdev_queue_dump queue_dump;
6660 uint32_t queue_id;
6661
6662 NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &queue_dump,
6663 port->netdev) {
6664 put_queue_get_config_reply(port, queue_id, replies);
6665 }
6666 }
6667 smap_destroy(&details);
6668 return 0;
6669 }
6670
6671 static enum ofperr
6672 handle_queue_get_config_request(struct ofconn *ofconn,
6673 const struct ofp_header *oh)
6674 {
6675 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6676 struct ovs_list replies;
6677 struct ofport *port;
6678 ofp_port_t req_port;
6679 uint32_t req_queue;
6680 enum ofperr error;
6681
6682 error = ofputil_decode_queue_get_config_request(oh, &req_port, &req_queue);
6683 if (error) {
6684 return error;
6685 }
6686
6687 ofputil_start_queue_get_config_reply(oh, &replies);
6688 if (req_port == OFPP_ANY) {
6689 error = OFPERR_OFPQOFC_BAD_QUEUE;
6690 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
6691 if (!handle_queue_get_config_request_for_port(port, req_queue,
6692 &replies)) {
6693 error = 0;
6694 }
6695 }
6696 } else {
6697 port = ofproto_get_port(ofproto, req_port);
6698 error = (port
6699 ? handle_queue_get_config_request_for_port(port, req_queue,
6700 &replies)
6701 : OFPERR_OFPQOFC_BAD_PORT);
6702 }
6703 if (!error) {
6704 ofconn_send_replies(ofconn, &replies);
6705 } else {
6706 ofpbuf_list_delete(&replies);
6707 }
6708
6709 return error;
6710 }
6711
6712 static enum ofperr
6713 init_group(struct ofproto *ofproto, const struct ofputil_group_mod *gm,
6714 ovs_version_t version, struct ofgroup **ofgroup)
6715 {
6716 enum ofperr error;
6717 const long long int now = time_msec();
6718
6719 if (gm->group_id > OFPG_MAX) {
6720 return OFPERR_OFPGMFC_INVALID_GROUP;
6721 }
6722 if (gm->type > OFPGT11_FF) {
6723 return OFPERR_OFPGMFC_BAD_TYPE;
6724 }
6725
6726 *ofgroup = ofproto->ofproto_class->group_alloc();
6727 if (!*ofgroup) {
6728 VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
6729 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
6730 }
6731
6732 *CONST_CAST(struct ofproto **, &(*ofgroup)->ofproto) = ofproto;
6733 *CONST_CAST(uint32_t *, &((*ofgroup)->group_id)) = gm->group_id;
6734 *CONST_CAST(enum ofp11_group_type *, &(*ofgroup)->type) = gm->type;
6735 *CONST_CAST(long long int *, &((*ofgroup)->created)) = now;
6736 *CONST_CAST(long long int *, &((*ofgroup)->modified)) = now;
6737 ovs_refcount_init(&(*ofgroup)->ref_count);
6738 (*ofgroup)->being_deleted = false;
6739
6740 ovs_list_init(CONST_CAST(struct ovs_list *, &(*ofgroup)->buckets));
6741 ofputil_bucket_clone_list(CONST_CAST(struct ovs_list *,
6742 &(*ofgroup)->buckets),
6743 &gm->buckets, NULL);
6744
6745 *CONST_CAST(uint32_t *, &(*ofgroup)->n_buckets) =
6746 ovs_list_size(&(*ofgroup)->buckets);
6747
6748 ofputil_group_properties_copy(CONST_CAST(struct ofputil_group_props *,
6749 &(*ofgroup)->props),
6750 &gm->props);
6751 rule_collection_init(&(*ofgroup)->rules);
6752
6753 /* Make group visible from 'version'. */
6754 (*ofgroup)->versions = VERSIONS_INITIALIZER(version,
6755 OVS_VERSION_NOT_REMOVED);
6756
6757 /* Construct called BEFORE any locks are held. */
6758 error = ofproto->ofproto_class->group_construct(*ofgroup);
6759 if (error) {
6760 ofputil_group_properties_destroy(CONST_CAST(struct ofputil_group_props *,
6761 &(*ofgroup)->props));
6762 ofputil_bucket_list_destroy(CONST_CAST(struct ovs_list *,
6763 &(*ofgroup)->buckets));
6764 ofproto->ofproto_class->group_dealloc(*ofgroup);
6765 }
6766 return error;
6767 }
6768
6769 /* Implements the OFPGC11_ADD operation specified by 'gm', adding a group to
6770 * 'ofproto''s group table. Returns 0 on success or an OpenFlow error code on
6771 * failure. */
6772 static enum ofperr
6773 add_group_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
6774 OVS_REQUIRES(ofproto_mutex)
6775 {
6776 enum ofperr error;
6777
6778 if (ofproto_group_exists(ofproto, ogm->gm.group_id)) {
6779 return OFPERR_OFPGMFC_GROUP_EXISTS;
6780 }
6781
6782 if (ofproto->n_groups[ogm->gm.type]
6783 >= ofproto->ogf.max_groups[ogm->gm.type]) {
6784 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
6785 }
6786
6787 /* Allocate new group and initialize it. */
6788 error = init_group(ofproto, &ogm->gm, ogm->version, &ogm->new_group);
6789 if (!error) {
6790 /* Insert new group. */
6791 cmap_insert(&ofproto->groups, &ogm->new_group->cmap_node,
6792 hash_int(ogm->new_group->group_id, 0));
6793 ofproto->n_groups[ogm->new_group->type]++;
6794 }
6795 return error;
6796 }
6797
6798 /* Adds all of the buckets from 'ofgroup' to 'new_ofgroup'. The buckets
6799 * already in 'new_ofgroup' will be placed just after the (copy of the) bucket
6800 * in 'ofgroup' with bucket ID 'command_bucket_id'. Special
6801 * 'command_bucket_id' values OFPG15_BUCKET_FIRST and OFPG15_BUCKET_LAST are
6802 * also honored. */
6803 static enum ofperr
6804 copy_buckets_for_insert_bucket(const struct ofgroup *ofgroup,
6805 struct ofgroup *new_ofgroup,
6806 uint32_t command_bucket_id)
6807 {
6808 struct ofputil_bucket *last = NULL;
6809
6810 if (command_bucket_id <= OFPG15_BUCKET_MAX) {
6811 /* Check here to ensure that a bucket corresponding to
6812 * command_bucket_id exists in the old bucket list.
6813 *
6814 * The subsequent search of below of new_ofgroup covers
6815 * both buckets in the old bucket list and buckets added
6816 * by the insert buckets group mod message this function processes. */
6817 if (!ofputil_bucket_find(&ofgroup->buckets, command_bucket_id)) {
6818 return OFPERR_OFPGMFC_UNKNOWN_BUCKET;
6819 }
6820
6821 if (!ovs_list_is_empty(&new_ofgroup->buckets)) {
6822 last = ofputil_bucket_list_back(&new_ofgroup->buckets);
6823 }
6824 }
6825
6826 ofputil_bucket_clone_list(CONST_CAST(struct ovs_list *,
6827 &new_ofgroup->buckets),
6828 &ofgroup->buckets, NULL);
6829
6830 if (ofputil_bucket_check_duplicate_id(&new_ofgroup->buckets)) {
6831 VLOG_INFO_RL(&rl, "Duplicate bucket id");
6832 return OFPERR_OFPGMFC_BUCKET_EXISTS;
6833 }
6834
6835 /* Rearrange list according to command_bucket_id */
6836 if (command_bucket_id == OFPG15_BUCKET_LAST) {
6837 if (!ovs_list_is_empty(&ofgroup->buckets)) {
6838 struct ofputil_bucket *new_first;
6839 const struct ofputil_bucket *first;
6840
6841 first = ofputil_bucket_list_front(&ofgroup->buckets);
6842 new_first = ofputil_bucket_find(&new_ofgroup->buckets,
6843 first->bucket_id);
6844
6845 ovs_list_splice(new_ofgroup->buckets.next, &new_first->list_node,
6846 CONST_CAST(struct ovs_list *,
6847 &new_ofgroup->buckets));
6848 }
6849 } else if (command_bucket_id <= OFPG15_BUCKET_MAX && last) {
6850 struct ofputil_bucket *after;
6851
6852 /* Presence of bucket is checked above so after should never be NULL */
6853 after = ofputil_bucket_find(&new_ofgroup->buckets, command_bucket_id);
6854
6855 ovs_list_splice(after->list_node.next, new_ofgroup->buckets.next,
6856 last->list_node.next);
6857 }
6858
6859 return 0;
6860 }
6861
6862 /* Appends all of the a copy of all the buckets from 'ofgroup' to 'new_ofgroup'
6863 * with the exception of the bucket whose bucket id is 'command_bucket_id'.
6864 * Special 'command_bucket_id' values OFPG15_BUCKET_FIRST, OFPG15_BUCKET_LAST
6865 * and OFPG15_BUCKET_ALL are also honored. */
6866 static enum ofperr
6867 copy_buckets_for_remove_bucket(const struct ofgroup *ofgroup,
6868 struct ofgroup *new_ofgroup,
6869 uint32_t command_bucket_id)
6870 {
6871 const struct ofputil_bucket *skip = NULL;
6872
6873 if (command_bucket_id == OFPG15_BUCKET_ALL) {
6874 return 0;
6875 }
6876
6877 if (command_bucket_id == OFPG15_BUCKET_FIRST) {
6878 if (!ovs_list_is_empty(&ofgroup->buckets)) {
6879 skip = ofputil_bucket_list_front(&ofgroup->buckets);
6880 }
6881 } else if (command_bucket_id == OFPG15_BUCKET_LAST) {
6882 if (!ovs_list_is_empty(&ofgroup->buckets)) {
6883 skip = ofputil_bucket_list_back(&ofgroup->buckets);
6884 }
6885 } else {
6886 skip = ofputil_bucket_find(&ofgroup->buckets, command_bucket_id);
6887 if (!skip) {
6888 return OFPERR_OFPGMFC_UNKNOWN_BUCKET;
6889 }
6890 }
6891
6892 ofputil_bucket_clone_list(CONST_CAST(struct ovs_list *,
6893 &new_ofgroup->buckets),
6894 &ofgroup->buckets, skip);
6895
6896 return 0;
6897 }
6898
6899 /* Implements OFPGC11_MODIFY, OFPGC15_INSERT_BUCKET and
6900 * OFPGC15_REMOVE_BUCKET. Returns 0 on success or an OpenFlow error code
6901 * on failure.
6902 *
6903 * Note that the group is re-created and then replaces the old group in
6904 * ofproto's ofgroup hash map. Thus, the group is never altered while users of
6905 * the xlate module hold a pointer to the group. */
6906 static enum ofperr
6907 modify_group_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
6908 OVS_REQUIRES(ofproto_mutex)
6909 {
6910 struct ofgroup *old_group; /* Modified group. */
6911 struct ofgroup *new_group;
6912 enum ofperr error;
6913
6914 old_group = ofproto_group_lookup__(ofproto, ogm->gm.group_id,
6915 OVS_VERSION_MAX);
6916 if (!old_group) {
6917 return OFPERR_OFPGMFC_UNKNOWN_GROUP;
6918 }
6919
6920 if (old_group->type != ogm->gm.type
6921 && (ofproto->n_groups[ogm->gm.type]
6922 >= ofproto->ogf.max_groups[ogm->gm.type])) {
6923 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
6924 }
6925
6926 error = init_group(ofproto, &ogm->gm, ogm->version, &ogm->new_group);
6927 if (error) {
6928 return error;
6929 }
6930 new_group = ogm->new_group;
6931
6932 /* Manipulate bucket list for bucket commands */
6933 if (ogm->gm.command == OFPGC15_INSERT_BUCKET) {
6934 error = copy_buckets_for_insert_bucket(old_group, new_group,
6935 ogm->gm.command_bucket_id);
6936 } else if (ogm->gm.command == OFPGC15_REMOVE_BUCKET) {
6937 error = copy_buckets_for_remove_bucket(old_group, new_group,
6938 ogm->gm.command_bucket_id);
6939 }
6940 if (error) {
6941 goto out;
6942 }
6943
6944 /* The group creation time does not change during modification. */
6945 *CONST_CAST(long long int *, &(new_group->created)) = old_group->created;
6946 *CONST_CAST(long long int *, &(new_group->modified)) = time_msec();
6947
6948 group_collection_add(&ogm->old_groups, old_group);
6949
6950 /* Mark the old group for deletion. */
6951 versions_set_remove_version(&old_group->versions, ogm->version);
6952 /* Insert replacement group. */
6953 cmap_insert(&ofproto->groups, &new_group->cmap_node,
6954 hash_int(new_group->group_id, 0));
6955 /* Transfer rules. */
6956 rule_collection_move(&new_group->rules, &old_group->rules);
6957
6958 if (old_group->type != new_group->type) {
6959 ofproto->n_groups[old_group->type]--;
6960 ofproto->n_groups[new_group->type]++;
6961 }
6962 return 0;
6963
6964 out:
6965 ofproto_group_unref(new_group);
6966 return error;
6967 }
6968
6969 /* Implements the OFPGC11_ADD_OR_MOD command which creates the group when it does not
6970 * exist yet and modifies it otherwise */
6971 static enum ofperr
6972 add_or_modify_group_start(struct ofproto *ofproto,
6973 struct ofproto_group_mod *ogm)
6974 OVS_REQUIRES(ofproto_mutex)
6975 {
6976 enum ofperr error;
6977
6978 if (!ofproto_group_exists(ofproto, ogm->gm.group_id)) {
6979 error = add_group_start(ofproto, ogm);
6980 } else {
6981 error = modify_group_start(ofproto, ogm);
6982 }
6983
6984 return error;
6985 }
6986
6987 static void
6988 delete_group_start(struct ofproto *ofproto, ovs_version_t version,
6989 struct group_collection *groups, struct ofgroup *group)
6990 OVS_REQUIRES(ofproto_mutex)
6991 {
6992 /* Makes flow deletion code leave the rule pointers in 'group->rules'
6993 * intact, so that we can later refer to the rules deleted due to the group
6994 * deletion. Rule pointers will be removed from all other groups, if any,
6995 * so we will never try to delete the same rule twice. */
6996 group->being_deleted = true;
6997
6998 /* Mark all the referring groups for deletion. */
6999 delete_flows_start__(ofproto, version, &group->rules);
7000 group_collection_add(groups, group);
7001 versions_set_remove_version(&group->versions, version);
7002 ofproto->n_groups[group->type]--;
7003 }
7004
7005 static void
7006 delete_group_finish(struct ofproto *ofproto, struct ofgroup *group)
7007 OVS_REQUIRES(ofproto_mutex)
7008 {
7009 /* Finish deletion of all flow entries containing this group in a group
7010 * action. */
7011 delete_flows_finish__(ofproto, &group->rules, OFPRR_GROUP_DELETE, NULL);
7012
7013 /* Group removal is postponed by the caller. */
7014 }
7015
7016 /* Implements OFPGC11_DELETE. */
7017 static void
7018 delete_groups_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
7019 OVS_REQUIRES(ofproto_mutex)
7020 {
7021 struct ofgroup *group;
7022
7023 if (ogm->gm.group_id == OFPG_ALL) {
7024 CMAP_FOR_EACH (group, cmap_node, &ofproto->groups) {
7025 if (versions_visible_in_version(&group->versions, ogm->version)) {
7026 delete_group_start(ofproto, ogm->version, &ogm->old_groups,
7027 group);
7028 }
7029 }
7030 } else {
7031 group = ofproto_group_lookup__(ofproto, ogm->gm.group_id, ogm->version);
7032 if (group) {
7033 delete_group_start(ofproto, ogm->version, &ogm->old_groups, group);
7034 }
7035 }
7036 }
7037
7038 static enum ofperr
7039 ofproto_group_mod_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
7040 OVS_REQUIRES(ofproto_mutex)
7041 {
7042 enum ofperr error;
7043
7044 ogm->new_group = NULL;
7045 group_collection_init(&ogm->old_groups);
7046
7047 switch (ogm->gm.command) {
7048 case OFPGC11_ADD:
7049 error = add_group_start(ofproto, ogm);
7050 break;
7051
7052 case OFPGC11_MODIFY:
7053 error = modify_group_start(ofproto, ogm);
7054 break;
7055
7056 case OFPGC11_ADD_OR_MOD:
7057 error = add_or_modify_group_start(ofproto, ogm);
7058 break;
7059
7060 case OFPGC11_DELETE:
7061 delete_groups_start(ofproto, ogm);
7062 error = 0;
7063 break;
7064
7065 case OFPGC15_INSERT_BUCKET:
7066 error = modify_group_start(ofproto, ogm);
7067 break;
7068
7069 case OFPGC15_REMOVE_BUCKET:
7070 error = modify_group_start(ofproto, ogm);
7071 break;
7072
7073 default:
7074 if (ogm->gm.command > OFPGC11_DELETE) {
7075 VLOG_INFO_RL(&rl, "%s: Invalid group_mod command type %d",
7076 ofproto->name, ogm->gm.command);
7077 }
7078 error = OFPERR_OFPGMFC_BAD_COMMAND;
7079 break;
7080 }
7081 return error;
7082 }
7083
7084 static void
7085 ofproto_group_mod_revert(struct ofproto *ofproto,
7086 struct ofproto_group_mod *ogm)
7087 OVS_REQUIRES(ofproto_mutex)
7088 {
7089 struct ofgroup *new_group = ogm->new_group;
7090 struct ofgroup *old_group;
7091
7092 /* Restore replaced or deleted groups. */
7093 GROUP_COLLECTION_FOR_EACH (old_group, &ogm->old_groups) {
7094 ofproto->n_groups[old_group->type]++;
7095 if (new_group) {
7096 ovs_assert(group_collection_n(&ogm->old_groups) == 1);
7097 /* Transfer rules back. */
7098 rule_collection_move(&old_group->rules, &new_group->rules);
7099 } else {
7100 old_group->being_deleted = false;
7101 /* Revert rule deletion. */
7102 delete_flows_revert__(ofproto, &old_group->rules);
7103 }
7104 /* Restore visibility. */
7105 versions_set_remove_version(&old_group->versions,
7106 OVS_VERSION_NOT_REMOVED);
7107 }
7108 if (new_group) {
7109 /* Remove the new group immediately. It was never visible to
7110 * lookups. */
7111 cmap_remove(&ofproto->groups, &new_group->cmap_node,
7112 hash_int(new_group->group_id, 0));
7113 ofproto->n_groups[new_group->type]--;
7114 ofproto_group_unref(new_group);
7115 }
7116 }
7117
7118 static void
7119 ofproto_group_mod_finish(struct ofproto *ofproto,
7120 struct ofproto_group_mod *ogm,
7121 const struct openflow_mod_requester *req)
7122 OVS_REQUIRES(ofproto_mutex)
7123 {
7124 struct ofgroup *new_group = ogm->new_group;
7125 struct ofgroup *old_group;
7126
7127 if (new_group && group_collection_n(&ogm->old_groups) &&
7128 ofproto->ofproto_class->group_modify) {
7129 /* Modify a group. */
7130 ovs_assert(group_collection_n(&ogm->old_groups) == 1);
7131
7132 /* XXX: OK to lose old group's stats? */
7133 ofproto->ofproto_class->group_modify(new_group);
7134 }
7135
7136 /* Delete old groups. */
7137 GROUP_COLLECTION_FOR_EACH(old_group, &ogm->old_groups) {
7138 delete_group_finish(ofproto, old_group);
7139 }
7140 remove_groups_postponed(&ogm->old_groups);
7141
7142 if (req) {
7143 struct ofputil_requestforward rf;
7144 rf.xid = req->request->xid;
7145 rf.reason = OFPRFR_GROUP_MOD;
7146 rf.group_mod = &ogm->gm;
7147 connmgr_send_requestforward(ofproto->connmgr, req->ofconn, &rf);
7148 }
7149 }
7150
7151 /* Delete all groups from 'ofproto'.
7152 *
7153 * This is intended for use within an ofproto provider's 'destruct'
7154 * function. */
7155 void
7156 ofproto_group_delete_all(struct ofproto *ofproto)
7157 OVS_EXCLUDED(ofproto_mutex)
7158 {
7159 struct ofproto_group_mod ogm;
7160
7161 ogm.gm.command = OFPGC11_DELETE;
7162 ogm.gm.group_id = OFPG_ALL;
7163
7164 ovs_mutex_lock(&ofproto_mutex);
7165 ogm.version = ofproto->tables_version + 1;
7166 ofproto_group_mod_start(ofproto, &ogm);
7167 ofproto_bump_tables_version(ofproto);
7168 ofproto_group_mod_finish(ofproto, &ogm, NULL);
7169 ovs_mutex_unlock(&ofproto_mutex);
7170 }
7171
7172 static enum ofperr
7173 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
7174 OVS_EXCLUDED(ofproto_mutex)
7175 {
7176 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7177 struct ofproto_group_mod ogm;
7178 enum ofperr error;
7179
7180 error = reject_slave_controller(ofconn);
7181 if (error) {
7182 return error;
7183 }
7184
7185 error = ofputil_decode_group_mod(oh, &ogm.gm);
7186 if (error) {
7187 return error;
7188 }
7189
7190 ovs_mutex_lock(&ofproto_mutex);
7191 ogm.version = ofproto->tables_version + 1;
7192 error = ofproto_group_mod_start(ofproto, &ogm);
7193 if (!error) {
7194 struct openflow_mod_requester req = { ofconn, oh };
7195
7196 ofproto_bump_tables_version(ofproto);
7197 ofproto_group_mod_finish(ofproto, &ogm, &req);
7198 ofmonitor_flush(ofproto->connmgr);
7199 }
7200 ovs_mutex_unlock(&ofproto_mutex);
7201
7202 ofputil_uninit_group_mod(&ogm.gm);
7203
7204 return error;
7205 }
7206
7207 enum ofputil_table_miss
7208 ofproto_table_get_miss_config(const struct ofproto *ofproto, uint8_t table_id)
7209 {
7210 enum ofputil_table_miss miss;
7211
7212 atomic_read_relaxed(&ofproto->tables[table_id].miss_config, &miss);
7213 return miss;
7214 }
7215
7216 static void
7217 table_mod__(struct oftable *oftable,
7218 const struct ofputil_table_mod *tm)
7219 {
7220 if (tm->miss == OFPUTIL_TABLE_MISS_DEFAULT) {
7221 /* This is how an OFPT_TABLE_MOD decodes if it doesn't specify any
7222 * table-miss configuration (because the protocol used doesn't have
7223 * such a concept), so there's nothing to do. */
7224 } else {
7225 atomic_store_relaxed(&oftable->miss_config, tm->miss);
7226 }
7227
7228 unsigned int new_eviction = oftable->eviction;
7229 if (tm->eviction == OFPUTIL_TABLE_EVICTION_ON) {
7230 new_eviction |= EVICTION_OPENFLOW;
7231 } else if (tm->eviction == OFPUTIL_TABLE_EVICTION_OFF) {
7232 new_eviction &= ~EVICTION_OPENFLOW;
7233 }
7234
7235 if (new_eviction != oftable->eviction) {
7236 ovs_mutex_lock(&ofproto_mutex);
7237 oftable_configure_eviction(oftable, new_eviction,
7238 oftable->eviction_fields,
7239 oftable->n_eviction_fields);
7240 ovs_mutex_unlock(&ofproto_mutex);
7241 }
7242
7243 if (tm->vacancy != OFPUTIL_TABLE_VACANCY_DEFAULT) {
7244 ovs_mutex_lock(&ofproto_mutex);
7245 oftable->vacancy_down = tm->table_vacancy.vacancy_down;
7246 oftable->vacancy_up = tm->table_vacancy.vacancy_up;
7247 if (tm->vacancy == OFPUTIL_TABLE_VACANCY_OFF) {
7248 oftable->vacancy_event = 0;
7249 } else if (!oftable->vacancy_event) {
7250 uint8_t vacancy = oftable_vacancy(oftable);
7251 oftable->vacancy_event = (vacancy < oftable->vacancy_up
7252 ? OFPTR_VACANCY_UP
7253 : OFPTR_VACANCY_DOWN);
7254 }
7255 ovs_mutex_unlock(&ofproto_mutex);
7256 }
7257 }
7258
7259 static enum ofperr
7260 table_mod(struct ofproto *ofproto, const struct ofputil_table_mod *tm)
7261 {
7262 if (!check_table_id(ofproto, tm->table_id)) {
7263 return OFPERR_OFPTMFC_BAD_TABLE;
7264 }
7265
7266 /* Don't allow the eviction flags to be changed (except to the only fixed
7267 * value that OVS supports). OF1.4 says this is normal: "The
7268 * OFPTMPT_EVICTION property usually cannot be modified using a
7269 * OFP_TABLE_MOD request, because the eviction mechanism is switch
7270 * defined". */
7271 if (tm->eviction_flags != UINT32_MAX
7272 && tm->eviction_flags != OFPROTO_EVICTION_FLAGS) {
7273 return OFPERR_OFPTMFC_BAD_CONFIG;
7274 }
7275
7276 if (tm->table_id == OFPTT_ALL) {
7277 struct oftable *oftable;
7278 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
7279 if (!(oftable->flags & (OFTABLE_HIDDEN | OFTABLE_READONLY))) {
7280 table_mod__(oftable, tm);
7281 }
7282 }
7283 } else {
7284 struct oftable *oftable = &ofproto->tables[tm->table_id];
7285 if (oftable->flags & OFTABLE_READONLY) {
7286 return OFPERR_OFPTMFC_EPERM;
7287 }
7288 table_mod__(oftable, tm);
7289 }
7290
7291 return 0;
7292 }
7293
7294 static enum ofperr
7295 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
7296 {
7297 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7298 struct ofputil_table_mod tm;
7299 enum ofperr error;
7300
7301 error = reject_slave_controller(ofconn);
7302 if (error) {
7303 return error;
7304 }
7305
7306 error = ofputil_decode_table_mod(oh, &tm);
7307 if (error) {
7308 return error;
7309 }
7310
7311 return table_mod(ofproto, &tm);
7312 }
7313
7314 /* Free resources that may be allocated by ofproto_flow_mod_init(). */
7315 void
7316 ofproto_flow_mod_uninit(struct ofproto_flow_mod *ofm)
7317 {
7318 if (ofm->temp_rule) {
7319 ofproto_rule_unref(ofm->temp_rule);
7320 ofm->temp_rule = NULL;
7321 }
7322 if (ofm->criteria.version != OVS_VERSION_NOT_REMOVED) {
7323 rule_criteria_destroy(&ofm->criteria);
7324 }
7325 if (ofm->conjs) {
7326 free(ofm->conjs);
7327 ofm->conjs = NULL;
7328 ofm->n_conjs = 0;
7329 }
7330 }
7331
7332 static enum ofperr
7333 ofproto_flow_mod_init(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
7334 const struct ofputil_flow_mod *fm, struct rule *rule)
7335 OVS_EXCLUDED(ofproto_mutex)
7336 {
7337 enum ofperr error;
7338
7339 /* Forward flow mod fields we need later. */
7340 ofm->command = fm->command;
7341 ofm->modify_cookie = fm->modify_cookie;
7342
7343 ofm->modify_may_add_flow = (fm->new_cookie != OVS_BE64_MAX
7344 && fm->cookie_mask == htonll(0));
7345 /* Old flags must be kept when modifying a flow, but we still must
7346 * honor the reset counts flag if present in the flow mod. */
7347 ofm->modify_keep_counts = !(fm->flags & OFPUTIL_FF_RESET_COUNTS);
7348
7349 /* Initialize state needed by ofproto_flow_mod_uninit(). */
7350 ofm->temp_rule = rule;
7351 ofm->criteria.version = OVS_VERSION_NOT_REMOVED;
7352 ofm->conjs = NULL;
7353 ofm->n_conjs = 0;
7354
7355 bool check_buffer_id = false;
7356
7357 switch (ofm->command) {
7358 case OFPFC_ADD:
7359 check_buffer_id = true;
7360 error = add_flow_init(ofproto, ofm, fm);
7361 break;
7362 case OFPFC_MODIFY:
7363 check_buffer_id = true;
7364 error = modify_flows_init_loose(ofproto, ofm, fm);
7365 break;
7366 case OFPFC_MODIFY_STRICT:
7367 check_buffer_id = true;
7368 error = modify_flow_init_strict(ofproto, ofm, fm);
7369 break;
7370 case OFPFC_DELETE:
7371 error = delete_flows_init_loose(ofproto, ofm, fm);
7372 break;
7373 case OFPFC_DELETE_STRICT:
7374 error = delete_flows_init_strict(ofproto, ofm, fm);
7375 break;
7376 default:
7377 error = OFPERR_OFPFMFC_BAD_COMMAND;
7378 break;
7379 }
7380 if (!error && check_buffer_id && fm->buffer_id != UINT32_MAX) {
7381 error = OFPERR_OFPBRC_BUFFER_UNKNOWN;
7382 }
7383
7384 if (error) {
7385 ofproto_flow_mod_uninit(ofm);
7386 }
7387 return error;
7388 }
7389
7390 static enum ofperr
7391 ofproto_flow_mod_start(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
7392 OVS_REQUIRES(ofproto_mutex)
7393 {
7394 enum ofperr error;
7395
7396 rule_collection_init(&ofm->old_rules);
7397 rule_collection_init(&ofm->new_rules);
7398
7399 switch (ofm->command) {
7400 case OFPFC_ADD:
7401 error = add_flow_start(ofproto, ofm);
7402 break;
7403 case OFPFC_MODIFY:
7404 error = modify_flows_start_loose(ofproto, ofm);
7405 break;
7406 case OFPFC_MODIFY_STRICT:
7407 error = modify_flow_start_strict(ofproto, ofm);
7408 break;
7409 case OFPFC_DELETE:
7410 error = delete_flows_start_loose(ofproto, ofm);
7411 break;
7412 case OFPFC_DELETE_STRICT:
7413 error = delete_flow_start_strict(ofproto, ofm);
7414 break;
7415 default:
7416 OVS_NOT_REACHED();
7417 }
7418 /* Release resources not needed after start. */
7419 ofproto_flow_mod_uninit(ofm);
7420
7421 if (error) {
7422 rule_collection_destroy(&ofm->old_rules);
7423 rule_collection_destroy(&ofm->new_rules);
7424 }
7425 return error;
7426 }
7427
7428 static void
7429 ofproto_flow_mod_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
7430 OVS_REQUIRES(ofproto_mutex)
7431 {
7432 switch (ofm->command) {
7433 case OFPFC_ADD:
7434 add_flow_revert(ofproto, ofm);
7435 break;
7436
7437 case OFPFC_MODIFY:
7438 case OFPFC_MODIFY_STRICT:
7439 modify_flows_revert(ofproto, ofm);
7440 break;
7441
7442 case OFPFC_DELETE:
7443 case OFPFC_DELETE_STRICT:
7444 delete_flows_revert(ofproto, ofm);
7445 break;
7446
7447 default:
7448 break;
7449 }
7450
7451 rule_collection_destroy(&ofm->old_rules);
7452 rule_collection_destroy(&ofm->new_rules);
7453 }
7454
7455 static void
7456 ofproto_flow_mod_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
7457 const struct openflow_mod_requester *req)
7458 OVS_REQUIRES(ofproto_mutex)
7459 {
7460 switch (ofm->command) {
7461 case OFPFC_ADD:
7462 add_flow_finish(ofproto, ofm, req);
7463 break;
7464
7465 case OFPFC_MODIFY:
7466 case OFPFC_MODIFY_STRICT:
7467 modify_flows_finish(ofproto, ofm, req);
7468 break;
7469
7470 case OFPFC_DELETE:
7471 case OFPFC_DELETE_STRICT:
7472 delete_flows_finish(ofproto, ofm, req);
7473 break;
7474
7475 default:
7476 break;
7477 }
7478
7479 rule_collection_destroy(&ofm->old_rules);
7480 rule_collection_destroy(&ofm->new_rules);
7481
7482 if (req) {
7483 ofconn_report_flow_mod(req->ofconn, ofm->command);
7484 }
7485 }
7486
7487 /* Commit phases (all while locking ofproto_mutex):
7488 *
7489 * 1. Begin: Gather resources and make changes visible in the next version.
7490 * - Mark affected rules for removal in the next version.
7491 * - Create new replacement rules, make visible in the next
7492 * version.
7493 * - Do not send any events or notifications.
7494 *
7495 * 2. Revert: Fail if any errors are found. After this point no errors are
7496 * possible. No visible changes were made, so rollback is minimal (remove
7497 * added invisible rules, restore visibility of rules marked for removal).
7498 *
7499 * 3. Finish: Make the changes visible for lookups. Insert replacement rules to
7500 * the ofproto provider. Remove replaced and deleted rules from ofproto data
7501 * structures, and Schedule postponed removal of deleted rules from the
7502 * classifier. Send notifications, buffered packets, etc.
7503 */
7504 static enum ofperr
7505 do_bundle_commit(struct ofconn *ofconn, uint32_t id, uint16_t flags)
7506 {
7507 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7508 ovs_version_t version = ofproto->tables_version + 1;
7509 struct ofp_bundle *bundle;
7510 struct ofp_bundle_entry *be;
7511 enum ofperr error;
7512
7513 bundle = ofconn_get_bundle(ofconn, id);
7514
7515 if (!bundle) {
7516 return OFPERR_OFPBFC_BAD_ID;
7517 }
7518 if (bundle->flags != flags) {
7519 error = OFPERR_OFPBFC_BAD_FLAGS;
7520 } else {
7521 bool prev_is_port_mod = false;
7522
7523 error = 0;
7524 ovs_mutex_lock(&ofproto_mutex);
7525
7526 /* 1. Begin. */
7527 LIST_FOR_EACH (be, node, &bundle->msg_list) {
7528 if (be->type == OFPTYPE_PORT_MOD) {
7529 /* Our port mods are not atomic. */
7530 if (flags & OFPBF_ATOMIC) {
7531 error = OFPERR_OFPBFC_MSG_FAILED;
7532 } else {
7533 prev_is_port_mod = true;
7534 error = port_mod_start(ofconn, &be->opm.pm, &be->opm.port);
7535 }
7536 } else {
7537 /* Flow & group mods between port mods are applied as a single
7538 * version, but the versions are published only after we know
7539 * the commit is successful. */
7540 if (prev_is_port_mod) {
7541 prev_is_port_mod = false;
7542 ++version;
7543 }
7544 if (be->type == OFPTYPE_FLOW_MOD) {
7545 /* Store the version in which the changes should take
7546 * effect. */
7547 be->ofm.version = version;
7548 error = ofproto_flow_mod_start(ofproto, &be->ofm);
7549 } else if (be->type == OFPTYPE_GROUP_MOD) {
7550 /* Store the version in which the changes should take
7551 * effect. */
7552 be->ogm.version = version;
7553 error = ofproto_group_mod_start(ofproto, &be->ogm);
7554 } else if (be->type == OFPTYPE_PACKET_OUT) {
7555 be->opo.version = version;
7556 error = ofproto_packet_out_start(ofproto, &be->opo);
7557 } else {
7558 OVS_NOT_REACHED();
7559 }
7560 }
7561 if (error) {
7562 break;
7563 }
7564 }
7565
7566 if (error) {
7567 /* Send error referring to the original message. */
7568 if (error) {
7569 ofconn_send_error(ofconn, &be->ofp_msg, error);
7570 error = OFPERR_OFPBFC_MSG_FAILED;
7571 }
7572
7573 /* 2. Revert. Undo all the changes made above. */
7574 LIST_FOR_EACH_REVERSE_CONTINUE(be, node, &bundle->msg_list) {
7575 if (be->type == OFPTYPE_FLOW_MOD) {
7576 ofproto_flow_mod_revert(ofproto, &be->ofm);
7577 } else if (be->type == OFPTYPE_GROUP_MOD) {
7578 ofproto_group_mod_revert(ofproto, &be->ogm);
7579 } else if (be->type == OFPTYPE_PACKET_OUT) {
7580 ofproto_packet_out_revert(ofproto, &be->opo);
7581 }
7582 /* Nothing needs to be reverted for a port mod. */
7583 }
7584 } else {
7585 /* 4. Finish. */
7586 LIST_FOR_EACH (be, node, &bundle->msg_list) {
7587 if (be->type == OFPTYPE_PORT_MOD) {
7588 /* Perform the actual port mod. This is not atomic, i.e.,
7589 * the effects will be immediately seen by upcall
7590 * processing regardless of the lookup version. It should
7591 * be noted that port configuration changes can originate
7592 * also from OVSDB changes asynchronously to all upcall
7593 * processing. */
7594 port_mod_finish(ofconn, &be->opm.pm, be->opm.port);
7595 } else {
7596 version =
7597 (be->type == OFPTYPE_FLOW_MOD) ? be->ofm.version :
7598 (be->type == OFPTYPE_GROUP_MOD) ? be->ogm.version :
7599 (be->type == OFPTYPE_PACKET_OUT) ? be->opo.version :
7600 version;
7601
7602 /* Bump the lookup version to the one of the current
7603 * message. This makes all the changes in the bundle at
7604 * this version visible to lookups at once. */
7605 if (ofproto->tables_version < version) {
7606 ofproto->tables_version = version;
7607 ofproto->ofproto_class->set_tables_version(
7608 ofproto, ofproto->tables_version);
7609 }
7610
7611 struct openflow_mod_requester req = { ofconn,
7612 &be->ofp_msg };
7613
7614 if (be->type == OFPTYPE_FLOW_MOD) {
7615 ofproto_flow_mod_finish(ofproto, &be->ofm, &req);
7616 } else if (be->type == OFPTYPE_GROUP_MOD) {
7617 ofproto_group_mod_finish(ofproto, &be->ogm, &req);
7618 } else if (be->type == OFPTYPE_PACKET_OUT) {
7619 ofproto_packet_out_finish(ofproto, &be->opo);
7620 }
7621 }
7622 }
7623 }
7624
7625 ofmonitor_flush(ofproto->connmgr);
7626 ovs_mutex_unlock(&ofproto_mutex);
7627 }
7628
7629 /* The bundle is discarded regardless the outcome. */
7630 ofp_bundle_remove__(ofconn, bundle);
7631 return error;
7632 }
7633
7634 static enum ofperr
7635 handle_bundle_control(struct ofconn *ofconn, const struct ofp_header *oh)
7636 {
7637 struct ofputil_bundle_ctrl_msg bctrl;
7638 struct ofputil_bundle_ctrl_msg reply;
7639 struct ofpbuf *buf;
7640 enum ofperr error;
7641
7642 error = reject_slave_controller(ofconn);
7643 if (error) {
7644 return error;
7645 }
7646
7647 error = ofputil_decode_bundle_ctrl(oh, &bctrl);
7648 if (error) {
7649 return error;
7650 }
7651 reply.flags = 0;
7652 reply.bundle_id = bctrl.bundle_id;
7653
7654 switch (bctrl.type) {
7655 case OFPBCT_OPEN_REQUEST:
7656 error = ofp_bundle_open(ofconn, bctrl.bundle_id, bctrl.flags, oh);
7657 reply.type = OFPBCT_OPEN_REPLY;
7658 break;
7659 case OFPBCT_CLOSE_REQUEST:
7660 error = ofp_bundle_close(ofconn, bctrl.bundle_id, bctrl.flags);
7661 reply.type = OFPBCT_CLOSE_REPLY;
7662 break;
7663 case OFPBCT_COMMIT_REQUEST:
7664 error = do_bundle_commit(ofconn, bctrl.bundle_id, bctrl.flags);
7665 reply.type = OFPBCT_COMMIT_REPLY;
7666 break;
7667 case OFPBCT_DISCARD_REQUEST:
7668 error = ofp_bundle_discard(ofconn, bctrl.bundle_id);
7669 reply.type = OFPBCT_DISCARD_REPLY;
7670 break;
7671
7672 case OFPBCT_OPEN_REPLY:
7673 case OFPBCT_CLOSE_REPLY:
7674 case OFPBCT_COMMIT_REPLY:
7675 case OFPBCT_DISCARD_REPLY:
7676 return OFPERR_OFPBFC_BAD_TYPE;
7677 break;
7678 }
7679
7680 if (!error) {
7681 buf = ofputil_encode_bundle_ctrl_reply(oh, &reply);
7682 ofconn_send_reply(ofconn, buf);
7683 }
7684 return error;
7685 }
7686
7687 static enum ofperr
7688 handle_bundle_add(struct ofconn *ofconn, const struct ofp_header *oh)
7689 OVS_EXCLUDED(ofproto_mutex)
7690 {
7691 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7692 enum ofperr error;
7693 struct ofputil_bundle_add_msg badd;
7694 struct ofp_bundle_entry *bmsg;
7695 enum ofptype type;
7696
7697 error = reject_slave_controller(ofconn);
7698 if (error) {
7699 return error;
7700 }
7701
7702 error = ofputil_decode_bundle_add(oh, &badd, &type);
7703 if (error) {
7704 return error;
7705 }
7706
7707 bmsg = ofp_bundle_entry_alloc(type, badd.msg);
7708
7709 struct ofpbuf ofpacts;
7710 uint64_t ofpacts_stub[1024 / 8];
7711 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
7712
7713 if (type == OFPTYPE_PORT_MOD) {
7714 error = ofputil_decode_port_mod(badd.msg, &bmsg->opm.pm, false);
7715 } else if (type == OFPTYPE_FLOW_MOD) {
7716 struct ofputil_flow_mod fm;
7717
7718 error = ofputil_decode_flow_mod(&fm, badd.msg,
7719 ofconn_get_protocol(ofconn),
7720 ofproto_get_tun_tab(ofproto),
7721 &ofproto->vl_mff_map, &ofpacts,
7722 u16_to_ofp(ofproto->max_ports),
7723 ofproto->n_tables);
7724 if (!error) {
7725 error = ofproto_flow_mod_init(ofproto, &bmsg->ofm, &fm, NULL);
7726 }
7727 } else if (type == OFPTYPE_GROUP_MOD) {
7728 error = ofputil_decode_group_mod(badd.msg, &bmsg->ogm.gm);
7729 } else if (type == OFPTYPE_PACKET_OUT) {
7730 struct ofputil_packet_out po;
7731
7732 COVERAGE_INC(ofproto_packet_out);
7733
7734 /* Decode message. */
7735 error = ofputil_decode_packet_out(&po, badd.msg, &ofpacts);
7736 if (!error) {
7737 po.ofpacts = ofpbuf_steal_data(&ofpacts); /* Move to heap. */
7738 error = ofproto_packet_out_init(ofproto, ofconn, &bmsg->opo, &po);
7739 }
7740 } else {
7741 OVS_NOT_REACHED();
7742 }
7743
7744 ofpbuf_uninit(&ofpacts);
7745
7746 if (!error) {
7747 error = ofp_bundle_add_message(ofconn, badd.bundle_id, badd.flags,
7748 bmsg, oh);
7749 }
7750
7751 if (error) {
7752 ofp_bundle_entry_free(bmsg);
7753 }
7754
7755 return error;
7756 }
7757
7758 static enum ofperr
7759 handle_tlv_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
7760 {
7761 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7762 struct tun_table *old_tab, *new_tab;
7763 struct ofputil_tlv_table_mod ttm;
7764 enum ofperr error;
7765
7766 error = reject_slave_controller(ofconn);
7767 if (error) {
7768 return error;
7769 }
7770
7771 error = ofputil_decode_tlv_table_mod(oh, &ttm);
7772 if (error) {
7773 return error;
7774 }
7775
7776 old_tab = ovsrcu_get_protected(struct tun_table *, &ofproto->metadata_tab);
7777 error = tun_metadata_table_mod(&ttm, old_tab, &new_tab);
7778 if (!error) {
7779 ovsrcu_set(&ofproto->metadata_tab, new_tab);
7780 tun_metadata_postpone_free(old_tab);
7781
7782 ovs_mutex_lock(&ofproto->vl_mff_map.mutex);
7783 error = mf_vl_mff_map_mod_from_tun_metadata(&ofproto->vl_mff_map,
7784 &ttm);
7785 ovs_mutex_unlock(&ofproto->vl_mff_map.mutex);
7786 }
7787
7788 ofputil_uninit_tlv_table(&ttm.mappings);
7789 return error;
7790 }
7791
7792 static enum ofperr
7793 handle_tlv_table_request(struct ofconn *ofconn, const struct ofp_header *oh)
7794 {
7795 const struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7796 struct ofputil_tlv_table_reply ttr;
7797 struct ofpbuf *b;
7798
7799 tun_metadata_table_request(ofproto_get_tun_tab(ofproto), &ttr);
7800
7801 b = ofputil_encode_tlv_table_reply(oh, &ttr);
7802 ofputil_uninit_tlv_table(&ttr.mappings);
7803
7804 ofconn_send_reply(ofconn, b);
7805 return 0;
7806 }
7807
7808 static enum ofperr
7809 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
7810 OVS_EXCLUDED(ofproto_mutex)
7811 {
7812 const struct ofp_header *oh = msg->data;
7813 enum ofptype type;
7814 enum ofperr error;
7815
7816 error = ofptype_decode(&type, oh);
7817 if (error) {
7818 return error;
7819 }
7820 if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
7821 && ofpmp_more(oh)) {
7822 /* We have no buffer implementation for multipart requests.
7823 * Report overflow for requests which consists of multiple
7824 * messages. */
7825 return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
7826 }
7827
7828 switch (type) {
7829 /* OpenFlow requests. */
7830 case OFPTYPE_ECHO_REQUEST:
7831 return handle_echo_request(ofconn, oh);
7832
7833 case OFPTYPE_FEATURES_REQUEST:
7834 return handle_features_request(ofconn, oh);
7835
7836 case OFPTYPE_GET_CONFIG_REQUEST:
7837 return handle_get_config_request(ofconn, oh);
7838
7839 case OFPTYPE_SET_CONFIG:
7840 return handle_set_config(ofconn, oh);
7841
7842 case OFPTYPE_PACKET_OUT:
7843 return handle_packet_out(ofconn, oh);
7844
7845 case OFPTYPE_PORT_MOD:
7846 return handle_port_mod(ofconn, oh);
7847
7848 case OFPTYPE_FLOW_MOD:
7849 return handle_flow_mod(ofconn, oh);
7850
7851 case OFPTYPE_GROUP_MOD:
7852 return handle_group_mod(ofconn, oh);
7853
7854 case OFPTYPE_TABLE_MOD:
7855 return handle_table_mod(ofconn, oh);
7856
7857 case OFPTYPE_METER_MOD:
7858 return handle_meter_mod(ofconn, oh);
7859
7860 case OFPTYPE_BARRIER_REQUEST:
7861 return handle_barrier_request(ofconn, oh);
7862
7863 case OFPTYPE_ROLE_REQUEST:
7864 return handle_role_request(ofconn, oh);
7865
7866 /* OpenFlow replies. */
7867 case OFPTYPE_ECHO_REPLY:
7868 return 0;
7869
7870 /* Nicira extension requests. */
7871 case OFPTYPE_FLOW_MOD_TABLE_ID:
7872 return handle_nxt_flow_mod_table_id(ofconn, oh);
7873
7874 case OFPTYPE_SET_FLOW_FORMAT:
7875 return handle_nxt_set_flow_format(ofconn, oh);
7876
7877 case OFPTYPE_SET_PACKET_IN_FORMAT:
7878 return handle_nxt_set_packet_in_format(ofconn, oh);
7879
7880 case OFPTYPE_SET_CONTROLLER_ID:
7881 return handle_nxt_set_controller_id(ofconn, oh);
7882
7883 case OFPTYPE_FLOW_AGE:
7884 /* Nothing to do. */
7885 return 0;
7886
7887 case OFPTYPE_FLOW_MONITOR_CANCEL:
7888 return handle_flow_monitor_cancel(ofconn, oh);
7889
7890 case OFPTYPE_SET_ASYNC_CONFIG:
7891 return handle_nxt_set_async_config(ofconn, oh);
7892
7893 case OFPTYPE_GET_ASYNC_REQUEST:
7894 return handle_nxt_get_async_request(ofconn, oh);
7895
7896 case OFPTYPE_NXT_RESUME:
7897 return handle_nxt_resume(ofconn, oh);
7898
7899 /* Statistics requests. */
7900 case OFPTYPE_DESC_STATS_REQUEST:
7901 return handle_desc_stats_request(ofconn, oh);
7902
7903 case OFPTYPE_FLOW_STATS_REQUEST:
7904 return handle_flow_stats_request(ofconn, oh);
7905
7906 case OFPTYPE_AGGREGATE_STATS_REQUEST:
7907 return handle_aggregate_stats_request(ofconn, oh);
7908
7909 case OFPTYPE_TABLE_STATS_REQUEST:
7910 return handle_table_stats_request(ofconn, oh);
7911
7912 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
7913 return handle_table_features_request(ofconn, oh);
7914
7915 case OFPTYPE_TABLE_DESC_REQUEST:
7916 return handle_table_desc_request(ofconn, oh);
7917
7918 case OFPTYPE_PORT_STATS_REQUEST:
7919 return handle_port_stats_request(ofconn, oh);
7920
7921 case OFPTYPE_QUEUE_STATS_REQUEST:
7922 return handle_queue_stats_request(ofconn, oh);
7923
7924 case OFPTYPE_PORT_DESC_STATS_REQUEST:
7925 return handle_port_desc_stats_request(ofconn, oh);
7926
7927 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
7928 return handle_flow_monitor_request(ofconn, oh);
7929
7930 case OFPTYPE_METER_STATS_REQUEST:
7931 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
7932 return handle_meter_request(ofconn, oh, type);
7933
7934 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
7935 return handle_meter_features_request(ofconn, oh);
7936
7937 case OFPTYPE_GROUP_STATS_REQUEST:
7938 return handle_group_stats_request(ofconn, oh);
7939
7940 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
7941 return handle_group_desc_stats_request(ofconn, oh);
7942
7943 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
7944 return handle_group_features_stats_request(ofconn, oh);
7945
7946 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
7947 return handle_queue_get_config_request(ofconn, oh);
7948
7949 case OFPTYPE_BUNDLE_CONTROL:
7950 return handle_bundle_control(ofconn, oh);
7951
7952 case OFPTYPE_BUNDLE_ADD_MESSAGE:
7953 return handle_bundle_add(ofconn, oh);
7954
7955 case OFPTYPE_NXT_TLV_TABLE_MOD:
7956 return handle_tlv_table_mod(ofconn, oh);
7957
7958 case OFPTYPE_NXT_TLV_TABLE_REQUEST:
7959 return handle_tlv_table_request(ofconn, oh);
7960
7961 case OFPTYPE_IPFIX_BRIDGE_STATS_REQUEST:
7962 return handle_ipfix_bridge_stats_request(ofconn, oh);
7963
7964 case OFPTYPE_IPFIX_FLOW_STATS_REQUEST:
7965 return handle_ipfix_flow_stats_request(ofconn, oh);
7966
7967 case OFPTYPE_CT_FLUSH_ZONE:
7968 return handle_nxt_ct_flush_zone(ofconn, oh);
7969
7970 case OFPTYPE_HELLO:
7971 case OFPTYPE_ERROR:
7972 case OFPTYPE_FEATURES_REPLY:
7973 case OFPTYPE_GET_CONFIG_REPLY:
7974 case OFPTYPE_PACKET_IN:
7975 case OFPTYPE_FLOW_REMOVED:
7976 case OFPTYPE_PORT_STATUS:
7977 case OFPTYPE_BARRIER_REPLY:
7978 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
7979 case OFPTYPE_DESC_STATS_REPLY:
7980 case OFPTYPE_FLOW_STATS_REPLY:
7981 case OFPTYPE_QUEUE_STATS_REPLY:
7982 case OFPTYPE_PORT_STATS_REPLY:
7983 case OFPTYPE_TABLE_STATS_REPLY:
7984 case OFPTYPE_AGGREGATE_STATS_REPLY:
7985 case OFPTYPE_PORT_DESC_STATS_REPLY:
7986 case OFPTYPE_ROLE_REPLY:
7987 case OFPTYPE_FLOW_MONITOR_PAUSED:
7988 case OFPTYPE_FLOW_MONITOR_RESUMED:
7989 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
7990 case OFPTYPE_GET_ASYNC_REPLY:
7991 case OFPTYPE_GROUP_STATS_REPLY:
7992 case OFPTYPE_GROUP_DESC_STATS_REPLY:
7993 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
7994 case OFPTYPE_METER_STATS_REPLY:
7995 case OFPTYPE_METER_CONFIG_STATS_REPLY:
7996 case OFPTYPE_METER_FEATURES_STATS_REPLY:
7997 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
7998 case OFPTYPE_TABLE_DESC_REPLY:
7999 case OFPTYPE_ROLE_STATUS:
8000 case OFPTYPE_REQUESTFORWARD:
8001 case OFPTYPE_TABLE_STATUS:
8002 case OFPTYPE_NXT_TLV_TABLE_REPLY:
8003 case OFPTYPE_IPFIX_BRIDGE_STATS_REPLY:
8004 case OFPTYPE_IPFIX_FLOW_STATS_REPLY:
8005 default:
8006 if (ofpmsg_is_stat_request(oh)) {
8007 return OFPERR_OFPBRC_BAD_STAT;
8008 } else {
8009 return OFPERR_OFPBRC_BAD_TYPE;
8010 }
8011 }
8012 }
8013
8014 static void
8015 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
8016 OVS_EXCLUDED(ofproto_mutex)
8017 {
8018 enum ofperr error = handle_openflow__(ofconn, ofp_msg);
8019
8020 if (error) {
8021 ofconn_send_error(ofconn, ofp_msg->data, error);
8022 }
8023 COVERAGE_INC(ofproto_recv_openflow);
8024 }
8025 \f
8026 static uint64_t
8027 pick_datapath_id(const struct ofproto *ofproto)
8028 {
8029 const struct ofport *port;
8030
8031 port = ofproto_get_port(ofproto, OFPP_LOCAL);
8032 if (port) {
8033 struct eth_addr ea;
8034 int error;
8035
8036 error = netdev_get_etheraddr(port->netdev, &ea);
8037 if (!error) {
8038 return eth_addr_to_uint64(ea);
8039 }
8040 VLOG_WARN("%s: could not get MAC address for %s (%s)",
8041 ofproto->name, netdev_get_name(port->netdev),
8042 ovs_strerror(error));
8043 }
8044 return ofproto->fallback_dpid;
8045 }
8046
8047 static uint64_t
8048 pick_fallback_dpid(void)
8049 {
8050 struct eth_addr ea;
8051 eth_addr_nicira_random(&ea);
8052 return eth_addr_to_uint64(ea);
8053 }
8054 \f
8055 /* Table overflow policy. */
8056
8057 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
8058 * to NULL if the table is not configured to evict rules or if the table
8059 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
8060 * or with no timeouts are not evictable.) */
8061 static bool
8062 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
8063 OVS_REQUIRES(ofproto_mutex)
8064 {
8065 struct eviction_group *evg;
8066
8067 *rulep = NULL;
8068 if (!table->eviction) {
8069 return false;
8070 }
8071
8072 /* In the common case, the outer and inner loops here will each be entered
8073 * exactly once:
8074 *
8075 * - The inner loop normally "return"s in its first iteration. If the
8076 * eviction group has any evictable rules, then it always returns in
8077 * some iteration.
8078 *
8079 * - The outer loop only iterates more than once if the largest eviction
8080 * group has no evictable rules.
8081 *
8082 * - The outer loop can exit only if table's 'max_flows' is all filled up
8083 * by unevictable rules. */
8084 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
8085 struct rule *rule;
8086
8087 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
8088 *rulep = rule;
8089 return true;
8090 }
8091 }
8092
8093 return false;
8094 }
8095 \f
8096 /* Eviction groups. */
8097
8098 /* Returns the priority to use for an eviction_group that contains 'n_rules'
8099 * rules. The priority contains low-order random bits to ensure that eviction
8100 * groups with the same number of rules are prioritized randomly. */
8101 static uint32_t
8102 eviction_group_priority(size_t n_rules)
8103 {
8104 uint16_t size = MIN(UINT16_MAX, n_rules);
8105 return (size << 16) | random_uint16();
8106 }
8107
8108 /* Updates 'evg', an eviction_group within 'table', following a change that
8109 * adds or removes rules in 'evg'. */
8110 static void
8111 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
8112 OVS_REQUIRES(ofproto_mutex)
8113 {
8114 heap_change(&table->eviction_groups_by_size, &evg->size_node,
8115 eviction_group_priority(heap_count(&evg->rules)));
8116 }
8117
8118 /* Destroys 'evg', an eviction_group within 'table':
8119 *
8120 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
8121 * rules themselves, just removes them from the eviction group.)
8122 *
8123 * - Removes 'evg' from 'table'.
8124 *
8125 * - Frees 'evg'. */
8126 static void
8127 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
8128 OVS_REQUIRES(ofproto_mutex)
8129 {
8130 while (!heap_is_empty(&evg->rules)) {
8131 struct rule *rule;
8132
8133 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
8134 rule->eviction_group = NULL;
8135 }
8136 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
8137 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
8138 heap_destroy(&evg->rules);
8139 free(evg);
8140 }
8141
8142 /* Removes 'rule' from its eviction group, if any. */
8143 static void
8144 eviction_group_remove_rule(struct rule *rule)
8145 OVS_REQUIRES(ofproto_mutex)
8146 {
8147 if (rule->eviction_group) {
8148 struct oftable *table = &rule->ofproto->tables[rule->table_id];
8149 struct eviction_group *evg = rule->eviction_group;
8150
8151 rule->eviction_group = NULL;
8152 heap_remove(&evg->rules, &rule->evg_node);
8153 if (heap_is_empty(&evg->rules)) {
8154 eviction_group_destroy(table, evg);
8155 } else {
8156 eviction_group_resized(table, evg);
8157 }
8158 }
8159 }
8160
8161 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
8162 * returns the hash value. */
8163 static uint32_t
8164 eviction_group_hash_rule(struct rule *rule)
8165 OVS_REQUIRES(ofproto_mutex)
8166 {
8167 struct oftable *table = &rule->ofproto->tables[rule->table_id];
8168 const struct mf_subfield *sf;
8169 struct flow flow;
8170 uint32_t hash;
8171
8172 hash = table->eviction_group_id_basis;
8173 miniflow_expand(rule->cr.match.flow, &flow);
8174 for (sf = table->eviction_fields;
8175 sf < &table->eviction_fields[table->n_eviction_fields];
8176 sf++)
8177 {
8178 if (mf_are_prereqs_ok(sf->field, &flow, NULL)) {
8179 union mf_value value;
8180
8181 mf_get_value(sf->field, &flow, &value);
8182 if (sf->ofs) {
8183 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
8184 }
8185 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
8186 unsigned int start = sf->ofs + sf->n_bits;
8187 bitwise_zero(&value, sf->field->n_bytes, start,
8188 sf->field->n_bytes * 8 - start);
8189 }
8190 hash = hash_bytes(&value, sf->field->n_bytes, hash);
8191 } else {
8192 hash = hash_int(hash, 0);
8193 }
8194 }
8195
8196 return hash;
8197 }
8198
8199 /* Returns an eviction group within 'table' with the given 'id', creating one
8200 * if necessary. */
8201 static struct eviction_group *
8202 eviction_group_find(struct oftable *table, uint32_t id)
8203 OVS_REQUIRES(ofproto_mutex)
8204 {
8205 struct eviction_group *evg;
8206
8207 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
8208 return evg;
8209 }
8210
8211 evg = xmalloc(sizeof *evg);
8212 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
8213 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
8214 eviction_group_priority(0));
8215 heap_init(&evg->rules);
8216
8217 return evg;
8218 }
8219
8220 /* Returns an eviction priority for 'rule'. The return value should be
8221 * interpreted so that higher priorities make a rule a more attractive
8222 * candidate for eviction. */
8223 static uint64_t
8224 rule_eviction_priority(struct ofproto *ofproto, struct rule *rule)
8225 OVS_REQUIRES(ofproto_mutex)
8226 {
8227 /* Calculate absolute time when this flow will expire. If it will never
8228 * expire, then return 0 to make it unevictable. */
8229 long long int expiration = LLONG_MAX;
8230 if (rule->hard_timeout) {
8231 /* 'modified' needs protection even when we hold 'ofproto_mutex'. */
8232 ovs_mutex_lock(&rule->mutex);
8233 long long int modified = rule->modified;
8234 ovs_mutex_unlock(&rule->mutex);
8235
8236 expiration = modified + rule->hard_timeout * 1000;
8237 }
8238 if (rule->idle_timeout) {
8239 uint64_t packets, bytes;
8240 long long int used;
8241 long long int idle_expiration;
8242
8243 ofproto->ofproto_class->rule_get_stats(rule, &packets, &bytes, &used);
8244 idle_expiration = used + rule->idle_timeout * 1000;
8245 expiration = MIN(expiration, idle_expiration);
8246 }
8247 if (expiration == LLONG_MAX) {
8248 return 0;
8249 }
8250
8251 /* Calculate the time of expiration as a number of (approximate) seconds
8252 * after program startup.
8253 *
8254 * This should work OK for program runs that last UINT32_MAX seconds or
8255 * less. Therefore, please restart OVS at least once every 136 years. */
8256 uint32_t expiration_ofs = (expiration >> 10) - (time_boot_msec() >> 10);
8257
8258 /* Combine expiration time with OpenFlow "importance" to form a single
8259 * priority value. We want flows with relatively low "importance" to be
8260 * evicted before even considering expiration time, so put "importance" in
8261 * the most significant bits and expiration time in the least significant
8262 * bits.
8263 *
8264 * Small 'priority' should be evicted before those with large 'priority'.
8265 * The caller expects the opposite convention (a large return value being
8266 * more attractive for eviction) so we invert it before returning. */
8267 uint64_t priority = ((uint64_t) rule->importance << 32) + expiration_ofs;
8268 return UINT64_MAX - priority;
8269 }
8270
8271 /* Adds 'rule' to an appropriate eviction group for its oftable's
8272 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
8273 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
8274 * own).
8275 *
8276 * The caller must ensure that 'rule' is not already in an eviction group. */
8277 static void
8278 eviction_group_add_rule(struct rule *rule)
8279 OVS_REQUIRES(ofproto_mutex)
8280 {
8281 struct ofproto *ofproto = rule->ofproto;
8282 struct oftable *table = &ofproto->tables[rule->table_id];
8283 bool has_timeout;
8284
8285 /* Timeouts may be modified only when holding 'ofproto_mutex'. We have it
8286 * so no additional protection is needed. */
8287 has_timeout = rule->hard_timeout || rule->idle_timeout;
8288
8289 if (table->eviction && has_timeout) {
8290 struct eviction_group *evg;
8291
8292 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
8293
8294 rule->eviction_group = evg;
8295 heap_insert(&evg->rules, &rule->evg_node,
8296 rule_eviction_priority(ofproto, rule));
8297 eviction_group_resized(table, evg);
8298 }
8299 }
8300 \f
8301 /* oftables. */
8302
8303 /* Initializes 'table'. */
8304 static void
8305 oftable_init(struct oftable *table)
8306 {
8307 memset(table, 0, sizeof *table);
8308 classifier_init(&table->cls, flow_segment_u64s);
8309 table->max_flows = UINT_MAX;
8310 table->n_flows = 0;
8311 hmap_init(&table->eviction_groups_by_id);
8312 heap_init(&table->eviction_groups_by_size);
8313 atomic_init(&table->miss_config, OFPUTIL_TABLE_MISS_DEFAULT);
8314
8315 classifier_set_prefix_fields(&table->cls, default_prefix_fields,
8316 ARRAY_SIZE(default_prefix_fields));
8317
8318 atomic_init(&table->n_matched, 0);
8319 atomic_init(&table->n_missed, 0);
8320 }
8321
8322 /* Destroys 'table', including its classifier and eviction groups.
8323 *
8324 * The caller is responsible for freeing 'table' itself. */
8325 static void
8326 oftable_destroy(struct oftable *table)
8327 {
8328 ovs_assert(classifier_is_empty(&table->cls));
8329
8330 ovs_mutex_lock(&ofproto_mutex);
8331 oftable_configure_eviction(table, 0, NULL, 0);
8332 ovs_mutex_unlock(&ofproto_mutex);
8333
8334 hmap_destroy(&table->eviction_groups_by_id);
8335 heap_destroy(&table->eviction_groups_by_size);
8336 classifier_destroy(&table->cls);
8337 free(table->name);
8338 }
8339
8340 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
8341 * string, then 'table' will use its default name.
8342 *
8343 * This only affects the name exposed for a table exposed through the OpenFlow
8344 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
8345 static void
8346 oftable_set_name(struct oftable *table, const char *name)
8347 {
8348 if (name && name[0]) {
8349 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
8350 if (!table->name || strncmp(name, table->name, len)) {
8351 free(table->name);
8352 table->name = xmemdup0(name, len);
8353 }
8354 } else {
8355 free(table->name);
8356 table->name = NULL;
8357 }
8358 }
8359
8360 /* oftables support a choice of two policies when adding a rule would cause the
8361 * number of flows in the table to exceed the configured maximum number: either
8362 * they can refuse to add the new flow or they can evict some existing flow.
8363 * This function configures the latter policy on 'table', with fairness based
8364 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
8365 * 'n_fields' as 0 disables fairness.) */
8366 static void
8367 oftable_configure_eviction(struct oftable *table, unsigned int eviction,
8368 const struct mf_subfield *fields, size_t n_fields)
8369 OVS_REQUIRES(ofproto_mutex)
8370 {
8371 struct rule *rule;
8372
8373 if ((table->eviction != 0) == (eviction != 0)
8374 && n_fields == table->n_eviction_fields
8375 && (!n_fields
8376 || !memcmp(fields, table->eviction_fields,
8377 n_fields * sizeof *fields))) {
8378 /* The set of eviction fields did not change. If 'eviction' changed,
8379 * it remains nonzero, so that we can just update table->eviction
8380 * without fussing with the eviction groups. */
8381 table->eviction = eviction;
8382 return;
8383 }
8384
8385 /* Destroy existing eviction groups, then destroy and recreate data
8386 * structures to recover memory. */
8387 struct eviction_group *evg, *next;
8388 HMAP_FOR_EACH_SAFE (evg, next, id_node, &table->eviction_groups_by_id) {
8389 eviction_group_destroy(table, evg);
8390 }
8391 hmap_destroy(&table->eviction_groups_by_id);
8392 hmap_init(&table->eviction_groups_by_id);
8393 heap_destroy(&table->eviction_groups_by_size);
8394 heap_init(&table->eviction_groups_by_size);
8395
8396 /* Replace eviction groups by the new ones, if there is a change. Free the
8397 * old fields only after allocating the new ones, because 'fields ==
8398 * table->eviction_fields' is possible. */
8399 struct mf_subfield *old_fields = table->eviction_fields;
8400 table->n_eviction_fields = n_fields;
8401 table->eviction_fields = (fields
8402 ? xmemdup(fields, n_fields * sizeof *fields)
8403 : NULL);
8404 free(old_fields);
8405
8406 /* Add the new eviction groups, if enabled. */
8407 table->eviction = eviction;
8408 if (table->eviction) {
8409 table->eviction_group_id_basis = random_uint32();
8410 CLS_FOR_EACH (rule, cr, &table->cls) {
8411 eviction_group_add_rule(rule);
8412 }
8413 }
8414 }
8415
8416 /* Inserts 'rule' from the ofproto data structures BEFORE caller has inserted
8417 * it to the classifier. */
8418 static void
8419 ofproto_rule_insert__(struct ofproto *ofproto, struct rule *rule)
8420 OVS_REQUIRES(ofproto_mutex)
8421 {
8422 const struct rule_actions *actions = rule_get_actions(rule);
8423
8424 /* A rule may not be reinserted. */
8425 ovs_assert(rule->state == RULE_INITIALIZED);
8426
8427 if (rule->hard_timeout || rule->idle_timeout) {
8428 ovs_list_insert(&ofproto->expirable, &rule->expirable);
8429 }
8430 cookies_insert(ofproto, rule);
8431 eviction_group_add_rule(rule);
8432 if (actions->has_meter) {
8433 meter_insert_rule(rule);
8434 }
8435 if (actions->has_groups) {
8436 const struct ofpact_group *a;
8437 OFPACT_FOR_EACH_TYPE_FLATTENED (a, GROUP, actions->ofpacts,
8438 actions->ofpacts_len) {
8439 struct ofgroup *group;
8440
8441 group = ofproto_group_lookup(ofproto, a->group_id, OVS_VERSION_MAX,
8442 false);
8443 ovs_assert(group != NULL);
8444 group_add_rule(group, rule);
8445 }
8446 }
8447
8448 rule->state = RULE_INSERTED;
8449 }
8450
8451 /* Removes 'rule' from the ofproto data structures. Caller may have deferred
8452 * the removal from the classifier. */
8453 static void
8454 ofproto_rule_remove__(struct ofproto *ofproto, struct rule *rule)
8455 OVS_REQUIRES(ofproto_mutex)
8456 {
8457 ovs_assert(rule->state == RULE_INSERTED);
8458
8459 cookies_remove(ofproto, rule);
8460
8461 eviction_group_remove_rule(rule);
8462 if (!ovs_list_is_empty(&rule->expirable)) {
8463 ovs_list_remove(&rule->expirable);
8464 }
8465 if (!ovs_list_is_empty(&rule->meter_list_node)) {
8466 ovs_list_remove(&rule->meter_list_node);
8467 ovs_list_init(&rule->meter_list_node);
8468 }
8469
8470 /* Remove the rule from any groups, except from the group that is being
8471 * deleted, if any. */
8472 const struct rule_actions *actions = rule_get_actions(rule);
8473
8474 if (actions->has_groups) {
8475 const struct ofpact_group *a;
8476
8477 OFPACT_FOR_EACH_TYPE_FLATTENED(a, GROUP, actions->ofpacts,
8478 actions->ofpacts_len) {
8479 struct ofgroup *group;
8480
8481 group = ofproto_group_lookup(ofproto, a->group_id, OVS_VERSION_MAX,
8482 false);
8483 ovs_assert(group);
8484
8485 /* Leave the rule for the group that is being deleted, if any,
8486 * as we still need the list of rules for clean-up. */
8487 if (!group->being_deleted) {
8488 group_remove_rule(group, rule);
8489 }
8490 }
8491 }
8492
8493 rule->state = RULE_REMOVED;
8494 }
8495 \f
8496 /* unixctl commands. */
8497
8498 struct ofproto *
8499 ofproto_lookup(const char *name)
8500 {
8501 struct ofproto *ofproto;
8502
8503 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
8504 &all_ofprotos) {
8505 if (!strcmp(ofproto->name, name)) {
8506 return ofproto;
8507 }
8508 }
8509 return NULL;
8510 }
8511
8512 static void
8513 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
8514 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
8515 {
8516 struct ofproto *ofproto;
8517 struct ds results;
8518
8519 ds_init(&results);
8520 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
8521 ds_put_format(&results, "%s\n", ofproto->name);
8522 }
8523 unixctl_command_reply(conn, ds_cstr(&results));
8524 ds_destroy(&results);
8525 }
8526
8527 static void
8528 ofproto_unixctl_init(void)
8529 {
8530 static bool registered;
8531 if (registered) {
8532 return;
8533 }
8534 registered = true;
8535
8536 unixctl_command_register("ofproto/list", "", 0, 0,
8537 ofproto_unixctl_list, NULL);
8538 }