2 * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3 * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
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:
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
26 #include "byte-order.h"
27 #include "classifier.h"
28 #include "connectivity.h"
31 #include "dynamic-string.h"
34 #include "meta-flow.h"
37 #include "ofp-actions.h"
38 #include "ofp-errors.h"
40 #include "ofp-print.h"
43 #include "ofproto-provider.h"
44 #include "openflow/nicira-ext.h"
45 #include "openflow/openflow.h"
50 #include "poll-loop.h"
58 #include "unaligned.h"
63 VLOG_DEFINE_THIS_MODULE(ofproto);
65 COVERAGE_DEFINE(ofproto_flush);
66 COVERAGE_DEFINE(ofproto_packet_out);
67 COVERAGE_DEFINE(ofproto_queue_req);
68 COVERAGE_DEFINE(ofproto_recv_openflow);
69 COVERAGE_DEFINE(ofproto_reinit_ports);
70 COVERAGE_DEFINE(ofproto_update_port);
72 /* Default fields to use for prefix tries in each flow table, unless something
73 * else is configured. */
74 const enum mf_field_id default_prefix_fields[2] =
75 { MFF_IPV4_DST, MFF_IPV4_SRC };
78 static void oftable_init(struct oftable *);
79 static void oftable_destroy(struct oftable *);
81 static void oftable_set_name(struct oftable *, const char *name);
83 static enum ofperr evict_rules_from_table(struct oftable *,
84 unsigned int extra_space)
85 OVS_REQUIRES(ofproto_mutex);
86 static void oftable_disable_eviction(struct oftable *);
87 static void oftable_enable_eviction(struct oftable *,
88 const struct mf_subfield *fields,
91 static void oftable_remove_rule(struct rule *rule) OVS_REQUIRES(ofproto_mutex);
92 static void oftable_remove_rule__(struct ofproto *, struct rule *)
93 OVS_REQUIRES(ofproto_mutex);
95 /* A set of rules within a single OpenFlow table (oftable) that have the same
96 * values for the oftable's eviction_fields. A rule to be evicted, when one is
97 * needed, is taken from the eviction group that contains the greatest number
100 * An oftable owns any number of eviction groups, each of which contains any
103 * Membership in an eviction group is imprecise, based on the hash of the
104 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
105 * That is, if two rules have different eviction_fields, but those
106 * eviction_fields hash to the same value, then they will belong to the same
107 * eviction_group anyway.
109 * (When eviction is not enabled on an oftable, we don't track any eviction
110 * groups, to save time and space.) */
111 struct eviction_group {
112 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
113 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
114 struct heap rules; /* Contains "struct rule"s. */
117 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep)
118 OVS_REQUIRES(ofproto_mutex);
119 static uint32_t rule_eviction_priority(struct ofproto *ofproto, struct rule *)
120 OVS_REQUIRES(ofproto_mutex);;
121 static void eviction_group_add_rule(struct rule *)
122 OVS_REQUIRES(ofproto_mutex);
123 static void eviction_group_remove_rule(struct rule *)
124 OVS_REQUIRES(ofproto_mutex);
126 /* Criteria that flow_mod and other operations use for selecting rules on
127 * which to operate. */
128 struct rule_criteria {
129 /* An OpenFlow table or 255 for all tables. */
132 /* OpenFlow matching criteria. Interpreted different in "loose" way by
133 * collect_rules_loose() and "strict" way by collect_rules_strict(), as
134 * defined in the OpenFlow spec. */
137 /* Matching criteria for the OpenFlow cookie. Consider a bit B in a rule's
138 * cookie and the corresponding bits C in 'cookie' and M in 'cookie_mask'.
139 * The rule will not be selected if M is 1 and B != C. */
141 ovs_be64 cookie_mask;
143 /* Selection based on actions within a rule:
145 * If out_port != OFPP_ANY, selects only rules that output to out_port.
146 * If out_group != OFPG_ALL, select only rules that output to out_group. */
150 /* If true, collects only rules that are modifiable. */
152 bool include_readonly;
155 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
156 const struct match *match,
157 unsigned int priority,
158 ovs_be64 cookie, ovs_be64 cookie_mask,
159 ofp_port_t out_port, uint32_t out_group);
160 static void rule_criteria_require_rw(struct rule_criteria *,
161 bool can_write_readonly);
162 static void rule_criteria_destroy(struct rule_criteria *);
164 static enum ofperr collect_rules_loose(struct ofproto *,
165 const struct rule_criteria *,
166 struct rule_collection *);
168 /* A packet that needs to be passed to rule_execute().
170 * (We can't do this immediately from ofopgroup_complete() because that holds
171 * ofproto_mutex, which rule_execute() needs released.) */
172 struct rule_execute {
173 struct list list_node; /* In struct ofproto's "rule_executes" list. */
174 struct rule *rule; /* Owns a reference to the rule. */
176 struct ofpbuf *packet; /* Owns the packet. */
179 static void run_rule_executes(struct ofproto *) OVS_EXCLUDED(ofproto_mutex);
180 static void destroy_rule_executes(struct ofproto *);
182 struct learned_cookie {
184 /* In struct ofproto's 'learned_cookies' hmap. */
185 struct hmap_node hmap_node OVS_GUARDED_BY(ofproto_mutex);
187 /* In 'dead_cookies' list when removed from hmap. */
188 struct list list_node;
192 ovs_be64 cookie OVS_GUARDED_BY(ofproto_mutex);
193 uint8_t table_id OVS_GUARDED_BY(ofproto_mutex);
195 /* Number of references from "learn" actions.
197 * When this drops to 0, all of the flows in 'table_id' with the specified
198 * 'cookie' are deleted. */
199 int n OVS_GUARDED_BY(ofproto_mutex);
202 static const struct ofpact_learn *next_learn_with_delete(
203 const struct rule_actions *, const struct ofpact_learn *start);
205 static void learned_cookies_inc(struct ofproto *, const struct rule_actions *)
206 OVS_REQUIRES(ofproto_mutex);
207 static void learned_cookies_dec(struct ofproto *, const struct rule_actions *,
208 struct list *dead_cookies)
209 OVS_REQUIRES(ofproto_mutex);
210 static void learned_cookies_flush(struct ofproto *, struct list *dead_cookies)
211 OVS_REQUIRES(ofproto_mutex);
214 static void ofport_destroy__(struct ofport *) OVS_EXCLUDED(ofproto_mutex);
215 static void ofport_destroy(struct ofport *);
217 static void update_port(struct ofproto *, const char *devname);
218 static int init_ports(struct ofproto *);
219 static void reinit_ports(struct ofproto *);
221 static long long int ofport_get_usage(const struct ofproto *,
222 ofp_port_t ofp_port);
223 static void ofport_set_usage(struct ofproto *, ofp_port_t ofp_port,
224 long long int last_used);
225 static void ofport_remove_usage(struct ofproto *, ofp_port_t ofp_port);
229 * Keeps track of the currently used and recently used ofport values and is
230 * used to prevent immediate recycling of ofport values. */
231 struct ofport_usage {
232 struct hmap_node hmap_node; /* In struct ofproto's "ofport_usage" hmap. */
233 ofp_port_t ofp_port; /* OpenFlow port number. */
234 long long int last_used; /* Last time the 'ofp_port' was used. LLONG_MAX
235 represents in-use ofports. */
239 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
240 static bool rule_is_readonly(const struct rule *);
242 /* The source of a flow_mod request, in the code that processes flow_mods.
244 * A flow table modification request can be generated externally, via OpenFlow,
245 * or internally through a function call. This structure indicates the source
246 * of an OpenFlow-generated flow_mod. For an internal flow_mod, it isn't
247 * meaningful and thus supplied as NULL. */
248 struct flow_mod_requester {
249 struct ofconn *ofconn; /* Connection on which flow_mod arrived. */
250 ovs_be32 xid; /* OpenFlow xid of flow_mod request. */
254 static enum ofperr add_flow(struct ofproto *, struct ofputil_flow_mod *,
255 const struct flow_mod_requester *);
257 static enum ofperr modify_flows__(struct ofproto *, struct ofputil_flow_mod *,
258 const struct rule_collection *,
259 const struct flow_mod_requester *);
260 static void delete_flows__(const struct rule_collection *,
261 enum ofp_flow_removed_reason,
262 const struct flow_mod_requester *)
263 OVS_REQUIRES(ofproto_mutex);
265 static enum ofperr send_buffered_packet(struct ofconn *, uint32_t buffer_id,
267 OVS_REQUIRES(ofproto_mutex);
269 static bool ofproto_group_exists__(const struct ofproto *ofproto,
271 OVS_REQ_RDLOCK(ofproto->groups_rwlock);
272 static bool ofproto_group_exists(const struct ofproto *ofproto,
274 OVS_EXCLUDED(ofproto->groups_rwlock);
275 static enum ofperr add_group(struct ofproto *, struct ofputil_group_mod *);
276 static void handle_openflow(struct ofconn *, const struct ofpbuf *);
277 static enum ofperr handle_flow_mod__(struct ofproto *,
278 struct ofputil_flow_mod *,
279 const struct flow_mod_requester *)
280 OVS_EXCLUDED(ofproto_mutex);
281 static void calc_duration(long long int start, long long int now,
282 uint32_t *sec, uint32_t *nsec);
285 static uint64_t pick_datapath_id(const struct ofproto *);
286 static uint64_t pick_fallback_dpid(void);
287 static void ofproto_destroy__(struct ofproto *);
288 static void update_mtu(struct ofproto *, struct ofport *);
289 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
290 static void meter_insert_rule(struct rule *);
293 static void ofproto_unixctl_init(void);
295 /* All registered ofproto classes, in probe order. */
296 static const struct ofproto_class **ofproto_classes;
297 static size_t n_ofproto_classes;
298 static size_t allocated_ofproto_classes;
300 /* Global lock that protects all flow table operations. */
301 struct ovs_mutex ofproto_mutex = OVS_MUTEX_INITIALIZER;
303 unsigned ofproto_flow_limit = OFPROTO_FLOW_LIMIT_DEFAULT;
304 unsigned ofproto_max_idle = OFPROTO_MAX_IDLE_DEFAULT;
306 size_t n_handlers, n_revalidators;
308 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
309 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
311 /* Initial mappings of port to OpenFlow number mappings. */
312 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
314 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
316 /* The default value of true waits for flow restore. */
317 static bool flow_restore_wait = true;
319 /* Must be called to initialize the ofproto library.
321 * The caller may pass in 'iface_hints', which contains an shash of
322 * "iface_hint" elements indexed by the interface's name. The provider
323 * may use these hints to describe the startup configuration in order to
324 * reinitialize its state. The caller owns the provided data, so a
325 * provider will make copies of anything required. An ofproto provider
326 * will remove any existing state that is not described by the hint, and
327 * may choose to remove it all. */
329 ofproto_init(const struct shash *iface_hints)
331 struct shash_node *node;
334 ofproto_class_register(&ofproto_dpif_class);
336 /* Make a local copy, since we don't own 'iface_hints' elements. */
337 SHASH_FOR_EACH(node, iface_hints) {
338 const struct iface_hint *orig_hint = node->data;
339 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
340 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
342 new_hint->br_name = xstrdup(orig_hint->br_name);
343 new_hint->br_type = xstrdup(br_type);
344 new_hint->ofp_port = orig_hint->ofp_port;
346 shash_add(&init_ofp_ports, node->name, new_hint);
349 for (i = 0; i < n_ofproto_classes; i++) {
350 ofproto_classes[i]->init(&init_ofp_ports);
354 /* 'type' should be a normalized datapath type, as returned by
355 * ofproto_normalize_type(). Returns the corresponding ofproto_class
356 * structure, or a null pointer if there is none registered for 'type'. */
357 static const struct ofproto_class *
358 ofproto_class_find__(const char *type)
362 for (i = 0; i < n_ofproto_classes; i++) {
363 const struct ofproto_class *class = ofproto_classes[i];
368 class->enumerate_types(&types);
369 found = sset_contains(&types, type);
370 sset_destroy(&types);
376 VLOG_WARN("unknown datapath type %s", type);
380 /* Registers a new ofproto class. After successful registration, new ofprotos
381 * of that type can be created using ofproto_create(). */
383 ofproto_class_register(const struct ofproto_class *new_class)
387 for (i = 0; i < n_ofproto_classes; i++) {
388 if (ofproto_classes[i] == new_class) {
393 if (n_ofproto_classes >= allocated_ofproto_classes) {
394 ofproto_classes = x2nrealloc(ofproto_classes,
395 &allocated_ofproto_classes,
396 sizeof *ofproto_classes);
398 ofproto_classes[n_ofproto_classes++] = new_class;
402 /* Unregisters a datapath provider. 'type' must have been previously
403 * registered and not currently be in use by any ofprotos. After
404 * unregistration new datapaths of that type cannot be opened using
405 * ofproto_create(). */
407 ofproto_class_unregister(const struct ofproto_class *class)
411 for (i = 0; i < n_ofproto_classes; i++) {
412 if (ofproto_classes[i] == class) {
413 for (i++; i < n_ofproto_classes; i++) {
414 ofproto_classes[i - 1] = ofproto_classes[i];
420 VLOG_WARN("attempted to unregister an ofproto class that is not "
425 /* Clears 'types' and enumerates all registered ofproto types into it. The
426 * caller must first initialize the sset. */
428 ofproto_enumerate_types(struct sset *types)
433 for (i = 0; i < n_ofproto_classes; i++) {
434 ofproto_classes[i]->enumerate_types(types);
438 /* Returns the fully spelled out name for the given ofproto 'type'.
440 * Normalized type string can be compared with strcmp(). Unnormalized type
441 * string might be the same even if they have different spellings. */
443 ofproto_normalize_type(const char *type)
445 return type && type[0] ? type : "system";
448 /* Clears 'names' and enumerates the names of all known created ofprotos with
449 * the given 'type'. The caller must first initialize the sset. Returns 0 if
450 * successful, otherwise a positive errno value.
452 * Some kinds of datapaths might not be practically enumerable. This is not
453 * considered an error. */
455 ofproto_enumerate_names(const char *type, struct sset *names)
457 const struct ofproto_class *class = ofproto_class_find__(type);
458 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
462 ofproto_create(const char *datapath_name, const char *datapath_type,
463 struct ofproto **ofprotop)
465 const struct ofproto_class *class;
466 struct ofproto *ofproto;
472 ofproto_unixctl_init();
474 datapath_type = ofproto_normalize_type(datapath_type);
475 class = ofproto_class_find__(datapath_type);
477 VLOG_WARN("could not create datapath %s of unknown type %s",
478 datapath_name, datapath_type);
482 ofproto = class->alloc();
484 VLOG_ERR("failed to allocate datapath %s of type %s",
485 datapath_name, datapath_type);
490 ovs_mutex_lock(&ofproto_mutex);
491 memset(ofproto, 0, sizeof *ofproto);
492 ofproto->ofproto_class = class;
493 ofproto->name = xstrdup(datapath_name);
494 ofproto->type = xstrdup(datapath_type);
495 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
496 hash_string(ofproto->name, 0));
497 ofproto->datapath_id = 0;
498 ofproto->forward_bpdu = false;
499 ofproto->fallback_dpid = pick_fallback_dpid();
500 ofproto->mfr_desc = NULL;
501 ofproto->hw_desc = NULL;
502 ofproto->sw_desc = NULL;
503 ofproto->serial_desc = NULL;
504 ofproto->dp_desc = NULL;
505 ofproto->frag_handling = OFPC_FRAG_NORMAL;
506 hmap_init(&ofproto->ports);
507 hmap_init(&ofproto->ofport_usage);
508 shash_init(&ofproto->port_by_name);
509 simap_init(&ofproto->ofp_requests);
510 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
511 ofproto->eviction_group_timer = LLONG_MIN;
512 ofproto->tables = NULL;
513 ofproto->n_tables = 0;
514 hindex_init(&ofproto->cookies);
515 hmap_init(&ofproto->learned_cookies);
516 list_init(&ofproto->expirable);
517 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
518 guarded_list_init(&ofproto->rule_executes);
519 ofproto->vlan_bitmap = NULL;
520 ofproto->vlans_changed = false;
521 ofproto->min_mtu = INT_MAX;
522 ovs_rwlock_init(&ofproto->groups_rwlock);
523 hmap_init(&ofproto->groups);
524 ovs_mutex_unlock(&ofproto_mutex);
525 ofproto->ogf.capabilities = OFPGFC_CHAINING | OFPGFC_SELECT_LIVENESS |
526 OFPGFC_SELECT_WEIGHT;
527 ofproto->ogf.max_groups[OFPGT11_ALL] = OFPG_MAX;
528 ofproto->ogf.max_groups[OFPGT11_SELECT] = OFPG_MAX;
529 ofproto->ogf.max_groups[OFPGT11_INDIRECT] = OFPG_MAX;
530 ofproto->ogf.max_groups[OFPGT11_FF] = OFPG_MAX;
531 ofproto->ogf.actions[0] =
532 (1 << OFPAT11_OUTPUT) |
533 (1 << OFPAT11_COPY_TTL_OUT) |
534 (1 << OFPAT11_COPY_TTL_IN) |
535 (1 << OFPAT11_SET_MPLS_TTL) |
536 (1 << OFPAT11_DEC_MPLS_TTL) |
537 (1 << OFPAT11_PUSH_VLAN) |
538 (1 << OFPAT11_POP_VLAN) |
539 (1 << OFPAT11_PUSH_MPLS) |
540 (1 << OFPAT11_POP_MPLS) |
541 (1 << OFPAT11_SET_QUEUE) |
542 (1 << OFPAT11_GROUP) |
543 (1 << OFPAT11_SET_NW_TTL) |
544 (1 << OFPAT11_DEC_NW_TTL) |
545 (1 << OFPAT12_SET_FIELD);
547 * (1 << OFPAT13_PUSH_PBB) |
548 * (1 << OFPAT13_POP_PBB) */
550 error = ofproto->ofproto_class->construct(ofproto);
552 VLOG_ERR("failed to open datapath %s: %s",
553 datapath_name, ovs_strerror(error));
554 ofproto_destroy__(ofproto);
558 /* Check that hidden tables, if any, are at the end. */
559 ovs_assert(ofproto->n_tables);
560 for (i = 0; i + 1 < ofproto->n_tables; i++) {
561 enum oftable_flags flags = ofproto->tables[i].flags;
562 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
564 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
567 ofproto->datapath_id = pick_datapath_id(ofproto);
570 /* Initialize meters table. */
571 if (ofproto->ofproto_class->meter_get_features) {
572 ofproto->ofproto_class->meter_get_features(ofproto,
573 &ofproto->meter_features);
575 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
577 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
578 * sizeof(struct meter *));
584 /* Must be called (only) by an ofproto implementation in its constructor
585 * function. See the large comment on 'construct' in struct ofproto_class for
588 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
590 struct oftable *table;
592 ovs_assert(!ofproto->n_tables);
593 ovs_assert(n_tables >= 1 && n_tables <= 255);
595 ofproto->n_tables = n_tables;
596 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
597 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
602 /* To be optionally called (only) by an ofproto implementation in its
603 * constructor function. See the large comment on 'construct' in struct
604 * ofproto_class for details.
606 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
607 * will then ensure that actions passed into the ofproto implementation will
608 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
609 * function is not called, there will be no such restriction.
611 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
612 * the 'max_ports' restriction. */
614 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
616 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
617 ofproto->max_ports = max_ports;
621 ofproto_get_datapath_id(const struct ofproto *ofproto)
623 return ofproto->datapath_id;
627 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
629 uint64_t old_dpid = p->datapath_id;
630 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
631 if (p->datapath_id != old_dpid) {
632 /* Force all active connections to reconnect, since there is no way to
633 * notify a controller that the datapath ID has changed. */
634 ofproto_reconnect_controllers(p);
639 ofproto_set_controllers(struct ofproto *p,
640 const struct ofproto_controller *controllers,
641 size_t n_controllers, uint32_t allowed_versions)
643 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
648 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
650 connmgr_set_fail_mode(p->connmgr, fail_mode);
653 /* Drops the connections between 'ofproto' and all of its controllers, forcing
654 * them to reconnect. */
656 ofproto_reconnect_controllers(struct ofproto *ofproto)
658 connmgr_reconnect(ofproto->connmgr);
661 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
662 * in-band control should guarantee access, in the same way that in-band
663 * control guarantees access to OpenFlow controllers. */
665 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
666 const struct sockaddr_in *extras, size_t n)
668 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
671 /* Sets the OpenFlow queue used by flows set up by in-band control on
672 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
673 * flows will use the default queue. */
675 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
677 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
680 /* Sets the number of flows at which eviction from the kernel flow table
683 ofproto_set_flow_limit(unsigned limit)
685 ofproto_flow_limit = limit;
688 /* Sets the maximum idle time for flows in the datapath before they are
691 ofproto_set_max_idle(unsigned max_idle)
693 ofproto_max_idle = max_idle;
696 /* If forward_bpdu is true, the NORMAL action will forward frames with
697 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
698 * the NORMAL action will drop these frames. */
700 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
702 bool old_val = ofproto->forward_bpdu;
703 ofproto->forward_bpdu = forward_bpdu;
704 if (old_val != ofproto->forward_bpdu) {
705 if (ofproto->ofproto_class->forward_bpdu_changed) {
706 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
711 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
712 * 'idle_time', in seconds, and the maximum number of MAC table entries to
715 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
718 if (ofproto->ofproto_class->set_mac_table_config) {
719 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
725 ofproto_set_threads(int n_handlers_, int n_revalidators_)
727 int threads = MAX(count_cpu_cores(), 2);
729 n_revalidators = MAX(n_revalidators_, 0);
730 n_handlers = MAX(n_handlers_, 0);
732 if (!n_revalidators) {
733 n_revalidators = n_handlers
734 ? MAX(threads - (int) n_handlers, 1)
739 n_handlers = MAX(threads - (int) n_revalidators, 1);
744 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
747 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
751 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
753 return connmgr_set_snoops(ofproto->connmgr, snoops);
757 ofproto_set_netflow(struct ofproto *ofproto,
758 const struct netflow_options *nf_options)
760 if (nf_options && sset_is_empty(&nf_options->collectors)) {
764 if (ofproto->ofproto_class->set_netflow) {
765 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
767 return nf_options ? EOPNOTSUPP : 0;
772 ofproto_set_sflow(struct ofproto *ofproto,
773 const struct ofproto_sflow_options *oso)
775 if (oso && sset_is_empty(&oso->targets)) {
779 if (ofproto->ofproto_class->set_sflow) {
780 return ofproto->ofproto_class->set_sflow(ofproto, oso);
782 return oso ? EOPNOTSUPP : 0;
787 ofproto_set_ipfix(struct ofproto *ofproto,
788 const struct ofproto_ipfix_bridge_exporter_options *bo,
789 const struct ofproto_ipfix_flow_exporter_options *fo,
792 if (ofproto->ofproto_class->set_ipfix) {
793 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
795 return (bo || fo) ? EOPNOTSUPP : 0;
800 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
802 flow_restore_wait = flow_restore_wait_db;
806 ofproto_get_flow_restore_wait(void)
808 return flow_restore_wait;
812 /* Spanning Tree Protocol (STP) configuration. */
814 /* Configures STP on 'ofproto' using the settings defined in 's'. If
815 * 's' is NULL, disables STP.
817 * Returns 0 if successful, otherwise a positive errno value. */
819 ofproto_set_stp(struct ofproto *ofproto,
820 const struct ofproto_stp_settings *s)
822 return (ofproto->ofproto_class->set_stp
823 ? ofproto->ofproto_class->set_stp(ofproto, s)
827 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
828 * 'enabled' member of 's' is false, then the other members are not
831 * Returns 0 if successful, otherwise a positive errno value. */
833 ofproto_get_stp_status(struct ofproto *ofproto,
834 struct ofproto_stp_status *s)
836 return (ofproto->ofproto_class->get_stp_status
837 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
841 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
842 * in 's'. The caller is responsible for assigning STP port numbers
843 * (using the 'port_num' member in the range of 1 through 255, inclusive)
844 * and ensuring there are no duplicates. If the 's' is NULL, then STP
845 * is disabled on the port.
847 * Returns 0 if successful, otherwise a positive errno value.*/
849 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
850 const struct ofproto_port_stp_settings *s)
852 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
854 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
855 ofproto->name, ofp_port);
859 return (ofproto->ofproto_class->set_stp_port
860 ? ofproto->ofproto_class->set_stp_port(ofport, s)
864 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
865 * 's'. If the 'enabled' member in 's' is false, then the other members
866 * are not meaningful.
868 * Returns 0 if successful, otherwise a positive errno value.*/
870 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
871 struct ofproto_port_stp_status *s)
873 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
875 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
876 "port %"PRIu16, ofproto->name, ofp_port);
880 return (ofproto->ofproto_class->get_stp_port_status
881 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
885 /* Retrieves STP port statistics of 'ofp_port' on 'ofproto' and stores it in
886 * 's'. If the 'enabled' member in 's' is false, then the other members
887 * are not meaningful.
889 * Returns 0 if successful, otherwise a positive errno value.*/
891 ofproto_port_get_stp_stats(struct ofproto *ofproto, ofp_port_t ofp_port,
892 struct ofproto_port_stp_stats *s)
894 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
896 VLOG_WARN_RL(&rl, "%s: cannot get STP stats on nonexistent "
897 "port %"PRIu16, ofproto->name, ofp_port);
901 return (ofproto->ofproto_class->get_stp_port_stats
902 ? ofproto->ofproto_class->get_stp_port_stats(ofport, s)
906 /* Queue DSCP configuration. */
908 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
909 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
910 * to implement QoS. Instead, it is used to implement features which require
911 * knowledge of what queues exist on a port, and some basic information about
914 * Returns 0 if successful, otherwise a positive errno value. */
916 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
917 const struct ofproto_port_queue *queues,
920 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
923 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
924 ofproto->name, ofp_port);
928 return (ofproto->ofproto_class->set_queues
929 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
933 /* Connectivity Fault Management configuration. */
935 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
937 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
939 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
940 if (ofport && ofproto->ofproto_class->set_cfm) {
941 ofproto->ofproto_class->set_cfm(ofport, NULL);
945 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
946 * basic configuration from the configuration members in 'cfm', and the remote
947 * maintenance point ID from remote_mpid. Ignores the statistics members of
950 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
952 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
953 const struct cfm_settings *s)
955 struct ofport *ofport;
958 ofport = ofproto_get_port(ofproto, ofp_port);
960 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
961 ofproto->name, ofp_port);
965 /* XXX: For configuration simplicity, we only support one remote_mpid
966 * outside of the CFM module. It's not clear if this is the correct long
967 * term solution or not. */
968 error = (ofproto->ofproto_class->set_cfm
969 ? ofproto->ofproto_class->set_cfm(ofport, s)
972 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
973 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
974 ovs_strerror(error));
978 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
979 * 'ofproto' does not have a port 'ofp_port'. */
981 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
982 const struct smap *cfg)
984 struct ofport *ofport;
987 ofport = ofproto_get_port(ofproto, ofp_port);
989 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
990 ofproto->name, ofp_port);
994 error = (ofproto->ofproto_class->set_bfd
995 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
998 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
999 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1000 ovs_strerror(error));
1004 /* Checks the status change of BFD on 'ofport'.
1006 * Returns true if 'ofproto_class' does not support 'bfd_status_changed'. */
1008 ofproto_port_bfd_status_changed(struct ofproto *ofproto, ofp_port_t ofp_port)
1010 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1011 return (ofport && ofproto->ofproto_class->bfd_status_changed
1012 ? ofproto->ofproto_class->bfd_status_changed(ofport)
1016 /* Populates 'status' with the status of BFD on 'ofport'. Returns 0 on
1017 * success. Returns a positive errno otherwise. Has no effect if 'ofp_port'
1018 * is not an OpenFlow port in 'ofproto'.
1020 * The caller must provide and own '*status'. */
1022 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
1023 struct smap *status)
1025 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1026 return (ofport && ofproto->ofproto_class->get_bfd_status
1027 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
1031 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
1032 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
1033 * 0 if LACP partner information is not current (generally indicating a
1034 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
1036 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
1038 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1039 return (ofport && ofproto->ofproto_class->port_is_lacp_current
1040 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
1046 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
1047 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
1048 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
1049 * configuration plus, if there is more than one slave, a bonding
1052 * If 'aux' is already registered then this function updates its configuration
1053 * to 's'. Otherwise, this function registers a new bundle.
1055 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
1058 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
1059 const struct ofproto_bundle_settings *s)
1061 return (ofproto->ofproto_class->bundle_set
1062 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1066 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1067 * If no such bundle has been registered, this has no effect. */
1069 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1071 return ofproto_bundle_register(ofproto, aux, NULL);
1075 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1076 * If 'aux' is already registered then this function updates its configuration
1077 * to 's'. Otherwise, this function registers a new mirror. */
1079 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1080 const struct ofproto_mirror_settings *s)
1082 return (ofproto->ofproto_class->mirror_set
1083 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1087 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1088 * If no mirror has been registered, this has no effect. */
1090 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1092 return ofproto_mirror_register(ofproto, aux, NULL);
1095 /* Retrieves statistics from mirror associated with client data pointer
1096 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1097 * 'bytes', respectively. If a particular counters is not supported,
1098 * the appropriate argument is set to UINT64_MAX. */
1100 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1101 uint64_t *packets, uint64_t *bytes)
1103 if (!ofproto->ofproto_class->mirror_get_stats) {
1104 *packets = *bytes = UINT64_MAX;
1108 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1112 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1113 * which all packets are flooded, instead of using MAC learning. If
1114 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1116 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1119 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1121 return (ofproto->ofproto_class->set_flood_vlans
1122 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1126 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1127 * output for a mirror. */
1129 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1131 return (ofproto->ofproto_class->is_mirror_output_bundle
1132 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1136 /* Configuration of OpenFlow tables. */
1138 /* Returns the number of OpenFlow tables in 'ofproto'. */
1140 ofproto_get_n_tables(const struct ofproto *ofproto)
1142 return ofproto->n_tables;
1145 /* Returns the number of Controller visible OpenFlow tables
1146 * in 'ofproto'. This number will exclude Hidden tables.
1147 * This funtion's return value should be less or equal to that of
1148 * ofproto_get_n_tables() . */
1150 ofproto_get_n_visible_tables(const struct ofproto *ofproto)
1152 uint8_t n = ofproto->n_tables;
1154 /* Count only non-hidden tables in the number of tables. (Hidden tables,
1155 * if present, are always at the end.) */
1156 while(n && (ofproto->tables[n - 1].flags & OFTABLE_HIDDEN)) {
1163 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1164 * settings from 's'. 'table_id' must be in the range 0 through the number of
1165 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1167 * For read-only tables, only the name may be configured. */
1169 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1170 const struct ofproto_table_settings *s)
1172 struct oftable *table;
1174 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1175 table = &ofproto->tables[table_id];
1177 oftable_set_name(table, s->name);
1179 if (table->flags & OFTABLE_READONLY) {
1184 oftable_enable_eviction(table, s->groups, s->n_groups);
1186 oftable_disable_eviction(table);
1189 table->max_flows = s->max_flows;
1190 fat_rwlock_wrlock(&table->cls.rwlock);
1191 classifier_set_prefix_fields(&table->cls,
1192 s->prefix_fields, s->n_prefix_fields);
1193 fat_rwlock_unlock(&table->cls.rwlock);
1195 ovs_mutex_lock(&ofproto_mutex);
1196 evict_rules_from_table(table, 0);
1197 ovs_mutex_unlock(&ofproto_mutex);
1201 ofproto_has_snoops(const struct ofproto *ofproto)
1203 return connmgr_has_snoops(ofproto->connmgr);
1207 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1209 connmgr_get_snoops(ofproto->connmgr, snoops);
1213 ofproto_rule_delete__(struct rule *rule, uint8_t reason)
1214 OVS_REQUIRES(ofproto_mutex)
1216 struct rule_collection rules;
1218 rules.rules = rules.stub;
1220 rules.stub[0] = rule;
1221 delete_flows__(&rules, reason, NULL);
1224 /* Deletes 'rule' from 'ofproto'.
1226 * Within an ofproto implementation, this function allows an ofproto
1227 * implementation to destroy any rules that remain when its ->destruct()
1228 * function is called. This function is not suitable for use elsewhere in an
1229 * ofproto implementation.
1231 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1232 * Cycle" in ofproto-provider.h. */
1234 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1235 OVS_EXCLUDED(ofproto_mutex)
1237 /* This skips the ofmonitor and flow-removed notifications because the
1238 * switch is being deleted and any OpenFlow channels have been or soon will
1240 ovs_mutex_lock(&ofproto_mutex);
1241 oftable_remove_rule__(ofproto, rule);
1242 ofproto->ofproto_class->rule_delete(rule);
1243 ovs_mutex_unlock(&ofproto_mutex);
1247 ofproto_flush__(struct ofproto *ofproto)
1248 OVS_EXCLUDED(ofproto_mutex)
1250 struct oftable *table;
1252 if (ofproto->ofproto_class->flush) {
1253 ofproto->ofproto_class->flush(ofproto);
1256 ovs_mutex_lock(&ofproto_mutex);
1257 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1258 struct rule *rule, *next_rule;
1259 struct cls_cursor cursor;
1261 if (table->flags & OFTABLE_HIDDEN) {
1265 fat_rwlock_rdlock(&table->cls.rwlock);
1266 cls_cursor_init(&cursor, &table->cls, NULL);
1267 fat_rwlock_unlock(&table->cls.rwlock);
1268 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1269 ofproto_rule_delete__(rule, OFPRR_DELETE);
1272 ovs_mutex_unlock(&ofproto_mutex);
1275 static void delete_group(struct ofproto *ofproto, uint32_t group_id);
1278 ofproto_destroy__(struct ofproto *ofproto)
1279 OVS_EXCLUDED(ofproto_mutex)
1281 struct oftable *table;
1283 destroy_rule_executes(ofproto);
1284 delete_group(ofproto, OFPG_ALL);
1286 guarded_list_destroy(&ofproto->rule_executes);
1287 ovs_rwlock_destroy(&ofproto->groups_rwlock);
1288 hmap_destroy(&ofproto->groups);
1290 connmgr_destroy(ofproto->connmgr);
1292 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1293 free(ofproto->name);
1294 free(ofproto->type);
1295 free(ofproto->mfr_desc);
1296 free(ofproto->hw_desc);
1297 free(ofproto->sw_desc);
1298 free(ofproto->serial_desc);
1299 free(ofproto->dp_desc);
1300 hmap_destroy(&ofproto->ports);
1301 hmap_destroy(&ofproto->ofport_usage);
1302 shash_destroy(&ofproto->port_by_name);
1303 simap_destroy(&ofproto->ofp_requests);
1305 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1306 oftable_destroy(table);
1308 free(ofproto->tables);
1310 ovs_assert(hindex_is_empty(&ofproto->cookies));
1311 hindex_destroy(&ofproto->cookies);
1313 ovs_assert(hmap_is_empty(&ofproto->learned_cookies));
1314 hmap_destroy(&ofproto->learned_cookies);
1316 free(ofproto->vlan_bitmap);
1318 ofproto->ofproto_class->dealloc(ofproto);
1322 ofproto_destroy(struct ofproto *p)
1323 OVS_EXCLUDED(ofproto_mutex)
1325 struct ofport *ofport, *next_ofport;
1326 struct ofport_usage *usage, *next_usage;
1333 meter_delete(p, 1, p->meter_features.max_meters);
1334 p->meter_features.max_meters = 0;
1340 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1341 ofport_destroy(ofport);
1344 HMAP_FOR_EACH_SAFE (usage, next_usage, hmap_node, &p->ofport_usage) {
1345 hmap_remove(&p->ofport_usage, &usage->hmap_node);
1349 p->ofproto_class->destruct(p);
1350 /* Destroying rules is deferred, must have 'ofproto' around for them. */
1351 ovsrcu_postpone(ofproto_destroy__, p);
1354 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1355 * kernel datapath, for example, this destroys the datapath in the kernel, and
1356 * with the netdev-based datapath, it tears down the data structures that
1357 * represent the datapath.
1359 * The datapath should not be currently open as an ofproto. */
1361 ofproto_delete(const char *name, const char *type)
1363 const struct ofproto_class *class = ofproto_class_find__(type);
1364 return (!class ? EAFNOSUPPORT
1365 : !class->del ? EACCES
1366 : class->del(type, name));
1370 process_port_change(struct ofproto *ofproto, int error, char *devname)
1372 if (error == ENOBUFS) {
1373 reinit_ports(ofproto);
1374 } else if (!error) {
1375 update_port(ofproto, devname);
1381 ofproto_type_run(const char *datapath_type)
1383 const struct ofproto_class *class;
1386 datapath_type = ofproto_normalize_type(datapath_type);
1387 class = ofproto_class_find__(datapath_type);
1389 error = class->type_run ? class->type_run(datapath_type) : 0;
1390 if (error && error != EAGAIN) {
1391 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1392 datapath_type, ovs_strerror(error));
1398 ofproto_type_wait(const char *datapath_type)
1400 const struct ofproto_class *class;
1402 datapath_type = ofproto_normalize_type(datapath_type);
1403 class = ofproto_class_find__(datapath_type);
1405 if (class->type_wait) {
1406 class->type_wait(datapath_type);
1411 ofproto_run(struct ofproto *p)
1416 error = p->ofproto_class->run(p);
1417 if (error && error != EAGAIN) {
1418 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1421 run_rule_executes(p);
1423 /* Restore the eviction group heap invariant occasionally. */
1424 if (p->eviction_group_timer < time_msec()) {
1427 p->eviction_group_timer = time_msec() + 1000;
1429 for (i = 0; i < p->n_tables; i++) {
1430 struct oftable *table = &p->tables[i];
1431 struct eviction_group *evg;
1432 struct cls_cursor cursor;
1435 if (!table->eviction_fields) {
1439 ovs_mutex_lock(&ofproto_mutex);
1440 fat_rwlock_rdlock(&table->cls.rwlock);
1441 cls_cursor_init(&cursor, &table->cls, NULL);
1442 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1443 if (rule->idle_timeout || rule->hard_timeout) {
1444 if (!rule->eviction_group) {
1445 eviction_group_add_rule(rule);
1447 heap_raw_change(&rule->evg_node,
1448 rule_eviction_priority(p, rule));
1452 fat_rwlock_unlock(&table->cls.rwlock);
1454 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1455 heap_rebuild(&evg->rules);
1457 ovs_mutex_unlock(&ofproto_mutex);
1461 if (p->ofproto_class->port_poll) {
1464 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1465 process_port_change(p, error, devname);
1469 new_seq = seq_read(connectivity_seq_get());
1470 if (new_seq != p->change_seq) {
1471 struct sset devnames;
1472 const char *devname;
1473 struct ofport *ofport;
1475 /* Update OpenFlow port status for any port whose netdev has changed.
1477 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1478 * destroyed, so it's not safe to update ports directly from the
1479 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1480 * need this two-phase approach. */
1481 sset_init(&devnames);
1482 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1483 uint64_t port_change_seq;
1485 port_change_seq = netdev_get_change_seq(ofport->netdev);
1486 if (ofport->change_seq != port_change_seq) {
1487 ofport->change_seq = port_change_seq;
1488 sset_add(&devnames, netdev_get_name(ofport->netdev));
1491 SSET_FOR_EACH (devname, &devnames) {
1492 update_port(p, devname);
1494 sset_destroy(&devnames);
1496 p->change_seq = new_seq;
1499 connmgr_run(p->connmgr, handle_openflow);
1505 ofproto_wait(struct ofproto *p)
1507 p->ofproto_class->wait(p);
1508 if (p->ofproto_class->port_poll_wait) {
1509 p->ofproto_class->port_poll_wait(p);
1511 seq_wait(connectivity_seq_get(), p->change_seq);
1512 connmgr_wait(p->connmgr);
1516 ofproto_is_alive(const struct ofproto *p)
1518 return connmgr_has_controllers(p->connmgr);
1521 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1522 * memory_report(). */
1524 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1526 const struct oftable *table;
1527 unsigned int n_rules;
1529 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1532 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1533 fat_rwlock_rdlock(&table->cls.rwlock);
1534 n_rules += classifier_count(&table->cls);
1535 fat_rwlock_unlock(&table->cls.rwlock);
1537 simap_increase(usage, "rules", n_rules);
1539 if (ofproto->ofproto_class->get_memory_usage) {
1540 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1543 connmgr_get_memory_usage(ofproto->connmgr, usage);
1547 ofproto_type_get_memory_usage(const char *datapath_type, struct simap *usage)
1549 const struct ofproto_class *class;
1551 datapath_type = ofproto_normalize_type(datapath_type);
1552 class = ofproto_class_find__(datapath_type);
1554 if (class && class->type_get_memory_usage) {
1555 class->type_get_memory_usage(datapath_type, usage);
1560 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1563 connmgr_get_controller_info(ofproto->connmgr, info);
1567 ofproto_free_ofproto_controller_info(struct shash *info)
1569 connmgr_free_controller_info(info);
1572 /* Makes a deep copy of 'old' into 'port'. */
1574 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1576 port->name = xstrdup(old->name);
1577 port->type = xstrdup(old->type);
1578 port->ofp_port = old->ofp_port;
1581 /* Frees memory allocated to members of 'ofproto_port'.
1583 * Do not call this function on an ofproto_port obtained from
1584 * ofproto_port_dump_next(): that function retains ownership of the data in the
1587 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1589 free(ofproto_port->name);
1590 free(ofproto_port->type);
1593 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1595 * This function provides no status indication. An error status for the entire
1596 * dump operation is provided when it is completed by calling
1597 * ofproto_port_dump_done().
1600 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1601 const struct ofproto *ofproto)
1603 dump->ofproto = ofproto;
1604 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1608 /* Attempts to retrieve another port from 'dump', which must have been created
1609 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1610 * 'port' and returns true. On failure, returns false.
1612 * Failure might indicate an actual error or merely that the last port has been
1613 * dumped. An error status for the entire dump operation is provided when it
1614 * is completed by calling ofproto_port_dump_done().
1616 * The ofproto owns the data stored in 'port'. It will remain valid until at
1617 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1618 * ofproto_port_dump_done(). */
1620 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1621 struct ofproto_port *port)
1623 const struct ofproto *ofproto = dump->ofproto;
1629 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1632 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1638 /* Completes port table dump operation 'dump', which must have been created
1639 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1640 * error-free, otherwise a positive errno value describing the problem. */
1642 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1644 const struct ofproto *ofproto = dump->ofproto;
1646 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1649 return dump->error == EOF ? 0 : dump->error;
1652 /* Returns the type to pass to netdev_open() when a datapath of type
1653 * 'datapath_type' has a port of type 'port_type', for a few special
1654 * cases when a netdev type differs from a port type. For example, when
1655 * using the userspace datapath, a port of type "internal" needs to be
1658 * Returns either 'type' itself or a string literal, which must not be
1661 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1663 const struct ofproto_class *class;
1665 datapath_type = ofproto_normalize_type(datapath_type);
1666 class = ofproto_class_find__(datapath_type);
1671 return (class->port_open_type
1672 ? class->port_open_type(datapath_type, port_type)
1676 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1677 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1678 * the port's OpenFlow port number.
1680 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1681 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1682 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1683 * 'ofp_portp' is non-null). */
1685 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1686 ofp_port_t *ofp_portp)
1688 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1691 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1693 const char *netdev_name = netdev_get_name(netdev);
1695 simap_put(&ofproto->ofp_requests, netdev_name,
1696 ofp_to_u16(ofp_port));
1697 update_port(ofproto, netdev_name);
1700 *ofp_portp = OFPP_NONE;
1702 struct ofproto_port ofproto_port;
1704 error = ofproto_port_query_by_name(ofproto,
1705 netdev_get_name(netdev),
1708 *ofp_portp = ofproto_port.ofp_port;
1709 ofproto_port_destroy(&ofproto_port);
1716 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1717 * initializes '*port' appropriately; on failure, returns a positive errno
1720 * The caller owns the data in 'ofproto_port' and must free it with
1721 * ofproto_port_destroy() when it is no longer needed. */
1723 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1724 struct ofproto_port *port)
1728 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1730 memset(port, 0, sizeof *port);
1735 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1736 * Returns 0 if successful, otherwise a positive errno. */
1738 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1740 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1741 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1742 struct simap_node *ofp_request_node;
1745 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1746 if (ofp_request_node) {
1747 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1750 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1751 if (!error && ofport) {
1752 /* 'name' is the netdev's name and update_port() is going to close the
1753 * netdev. Just in case update_port() refers to 'name' after it
1754 * destroys 'ofport', make a copy of it around the update_port()
1756 char *devname = xstrdup(name);
1757 update_port(ofproto, devname);
1764 flow_mod_init(struct ofputil_flow_mod *fm,
1765 const struct match *match, unsigned int priority,
1766 const struct ofpact *ofpacts, size_t ofpacts_len,
1767 enum ofp_flow_mod_command command)
1769 memset(fm, 0, sizeof *fm);
1771 fm->priority = priority;
1774 fm->modify_cookie = false;
1776 fm->command = command;
1777 fm->idle_timeout = 0;
1778 fm->hard_timeout = 0;
1779 fm->buffer_id = UINT32_MAX;
1780 fm->out_port = OFPP_ANY;
1781 fm->out_group = OFPG_ANY;
1783 fm->ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1784 fm->ofpacts_len = ofpacts_len;
1785 fm->delete_reason = OFPRR_DELETE;
1789 simple_flow_mod(struct ofproto *ofproto,
1790 const struct match *match, unsigned int priority,
1791 const struct ofpact *ofpacts, size_t ofpacts_len,
1792 enum ofp_flow_mod_command command)
1794 struct ofputil_flow_mod fm;
1796 flow_mod_init(&fm, match, priority, ofpacts, ofpacts_len, command);
1798 return handle_flow_mod__(ofproto, &fm, NULL);
1801 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1802 * performs the 'n_actions' actions in 'actions'. The new flow will not
1805 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1806 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1807 * controllers; otherwise, it will be hidden.
1809 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1811 * This is a helper function for in-band control and fail-open. */
1813 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1814 unsigned int priority,
1815 const struct ofpact *ofpacts, size_t ofpacts_len)
1816 OVS_EXCLUDED(ofproto_mutex)
1818 const struct rule *rule;
1821 /* First do a cheap check whether the rule we're looking for already exists
1822 * with the actions that we want. If it does, then we're done. */
1823 fat_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1824 rule = rule_from_cls_rule(classifier_find_match_exactly(
1825 &ofproto->tables[0].cls, match, priority));
1827 const struct rule_actions *actions = rule_get_actions(rule);
1828 must_add = !ofpacts_equal(actions->ofpacts, actions->ofpacts_len,
1829 ofpacts, ofpacts_len);
1833 fat_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1835 /* If there's no such rule or the rule doesn't have the actions we want,
1836 * fall back to a executing a full flow mod. We can't optimize this at
1837 * all because we didn't take enough locks above to ensure that the flow
1838 * table didn't already change beneath us. */
1840 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1841 OFPFC_MODIFY_STRICT);
1845 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1846 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1847 * operation cannot be initiated now but may be retried later.
1849 * This is a helper function for in-band control and fail-open and the "learn"
1852 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1853 OVS_EXCLUDED(ofproto_mutex)
1855 /* Optimize for the most common case of a repeated learn action.
1856 * If an identical flow already exists we only need to update its
1857 * 'modified' time. */
1858 if (fm->command == OFPFC_MODIFY_STRICT && fm->table_id != OFPTT_ALL
1859 && !(fm->flags & OFPUTIL_FF_RESET_COUNTS)) {
1860 struct oftable *table = &ofproto->tables[fm->table_id];
1864 fat_rwlock_rdlock(&table->cls.rwlock);
1865 rule = rule_from_cls_rule(classifier_find_match_exactly(&table->cls,
1869 /* Reading many of the rule fields and writing on 'modified'
1870 * requires the rule->mutex. Also, rule->actions may change
1871 * if rule->mutex is not held. */
1872 const struct rule_actions *actions;
1874 ovs_mutex_lock(&rule->mutex);
1875 actions = rule_get_actions(rule);
1876 if (rule->idle_timeout == fm->idle_timeout
1877 && rule->hard_timeout == fm->hard_timeout
1878 && rule->flags == (fm->flags & OFPUTIL_FF_STATE)
1879 && (!fm->modify_cookie || (fm->new_cookie == rule->flow_cookie))
1880 && ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
1881 actions->ofpacts, actions->ofpacts_len)) {
1882 /* Rule already exists and need not change, only update the
1883 modified timestamp. */
1884 rule->modified = time_msec();
1887 ovs_mutex_unlock(&rule->mutex);
1889 fat_rwlock_unlock(&table->cls.rwlock);
1896 return handle_flow_mod__(ofproto, fm, NULL);
1899 /* Searches for a rule with matching criteria exactly equal to 'target' in
1900 * ofproto's table 0 and, if it finds one, deletes it.
1902 * This is a helper function for in-band control and fail-open. */
1904 ofproto_delete_flow(struct ofproto *ofproto,
1905 const struct match *target, unsigned int priority)
1906 OVS_EXCLUDED(ofproto_mutex)
1908 struct classifier *cls = &ofproto->tables[0].cls;
1911 /* First do a cheap check whether the rule we're looking for has already
1912 * been deleted. If so, then we're done. */
1913 fat_rwlock_rdlock(&cls->rwlock);
1914 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1916 fat_rwlock_unlock(&cls->rwlock);
1921 /* Execute a flow mod. We can't optimize this at all because we didn't
1922 * take enough locks above to ensure that the flow table didn't already
1923 * change beneath us. */
1924 simple_flow_mod(ofproto, target, priority, NULL, 0, OFPFC_DELETE_STRICT);
1927 /* Delete all of the flows from all of ofproto's flow tables, then reintroduce
1928 * the flows required by in-band control and fail-open. */
1930 ofproto_flush_flows(struct ofproto *ofproto)
1932 COVERAGE_INC(ofproto_flush);
1933 ofproto_flush__(ofproto);
1934 connmgr_flushed(ofproto->connmgr);
1938 reinit_ports(struct ofproto *p)
1940 struct ofproto_port_dump dump;
1941 struct sset devnames;
1942 struct ofport *ofport;
1943 struct ofproto_port ofproto_port;
1944 const char *devname;
1946 COVERAGE_INC(ofproto_reinit_ports);
1948 sset_init(&devnames);
1949 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1950 sset_add(&devnames, netdev_get_name(ofport->netdev));
1952 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1953 sset_add(&devnames, ofproto_port.name);
1956 SSET_FOR_EACH (devname, &devnames) {
1957 update_port(p, devname);
1959 sset_destroy(&devnames);
1963 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1967 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1968 port_idx = port_idx ? port_idx : UINT16_MAX;
1970 if (port_idx >= ofproto->max_ports
1971 || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
1972 uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
1973 long long int last_used_at, lru = LLONG_MAX;
1975 /* Search for a free OpenFlow port number. We try not to
1976 * immediately reuse them to prevent problems due to old
1979 * We limit the automatically assigned port numbers to the lower half
1980 * of the port range, to reserve the upper half for assignment by
1983 if (++ofproto->alloc_port_no >= MIN(ofproto->max_ports, 32768)) {
1984 ofproto->alloc_port_no = 1;
1986 last_used_at = ofport_get_usage(ofproto,
1987 u16_to_ofp(ofproto->alloc_port_no));
1988 if (!last_used_at) {
1989 port_idx = ofproto->alloc_port_no;
1991 } else if ( last_used_at < time_msec() - 60*60*1000) {
1992 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
1993 * more than an hour ago, consider it usable. */
1994 ofport_remove_usage(ofproto,
1995 u16_to_ofp(ofproto->alloc_port_no));
1996 port_idx = ofproto->alloc_port_no;
1998 } else if (last_used_at < lru) {
2000 lru_ofport = ofproto->alloc_port_no;
2003 if (ofproto->alloc_port_no == end_port_no) {
2005 port_idx = lru_ofport;
2012 ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
2013 return u16_to_ofp(port_idx);
2017 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2019 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2020 ofport_set_usage(ofproto, ofp_port, time_msec());
2024 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2025 * pointer if the netdev cannot be opened. On success, also fills in
2027 static struct netdev *
2028 ofport_open(struct ofproto *ofproto,
2029 struct ofproto_port *ofproto_port,
2030 struct ofputil_phy_port *pp)
2032 enum netdev_flags flags;
2033 struct netdev *netdev;
2036 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2038 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
2039 "cannot be opened (%s)",
2041 ofproto_port->name, ofproto_port->ofp_port,
2042 ofproto_port->name, ovs_strerror(error));
2046 if (ofproto_port->ofp_port == OFPP_NONE) {
2047 if (!strcmp(ofproto->name, ofproto_port->name)) {
2048 ofproto_port->ofp_port = OFPP_LOCAL;
2050 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2051 ofproto_port->name);
2054 pp->port_no = ofproto_port->ofp_port;
2055 netdev_get_etheraddr(netdev, pp->hw_addr);
2056 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2057 netdev_get_flags(netdev, &flags);
2058 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2059 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2060 netdev_get_features(netdev, &pp->curr, &pp->advertised,
2061 &pp->supported, &pp->peer);
2062 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2063 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2068 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
2069 * port number, and 'config' bits other than OFPUTIL_PC_PORT_DOWN are
2072 ofport_equal(const struct ofputil_phy_port *a,
2073 const struct ofputil_phy_port *b)
2075 return (eth_addr_equals(a->hw_addr, b->hw_addr)
2076 && a->state == b->state
2077 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2078 && a->curr == b->curr
2079 && a->advertised == b->advertised
2080 && a->supported == b->supported
2081 && a->peer == b->peer
2082 && a->curr_speed == b->curr_speed
2083 && a->max_speed == b->max_speed);
2086 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2087 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2088 * one with the same name or port number). */
2090 ofport_install(struct ofproto *p,
2091 struct netdev *netdev, const struct ofputil_phy_port *pp)
2093 const char *netdev_name = netdev_get_name(netdev);
2094 struct ofport *ofport;
2097 /* Create ofport. */
2098 ofport = p->ofproto_class->port_alloc();
2103 ofport->ofproto = p;
2104 ofport->netdev = netdev;
2105 ofport->change_seq = netdev_get_change_seq(netdev);
2107 ofport->ofp_port = pp->port_no;
2108 ofport->created = time_msec();
2110 /* Add port to 'p'. */
2111 hmap_insert(&p->ports, &ofport->hmap_node,
2112 hash_ofp_port(ofport->ofp_port));
2113 shash_add(&p->port_by_name, netdev_name, ofport);
2115 update_mtu(p, ofport);
2117 /* Let the ofproto_class initialize its private data. */
2118 error = p->ofproto_class->port_construct(ofport);
2122 connmgr_send_port_status(p->connmgr, NULL, pp, OFPPR_ADD);
2126 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2127 p->name, netdev_name, ovs_strerror(error));
2129 ofport_destroy__(ofport);
2131 netdev_close(netdev);
2135 /* Removes 'ofport' from 'p' and destroys it. */
2137 ofport_remove(struct ofport *ofport)
2139 connmgr_send_port_status(ofport->ofproto->connmgr, NULL, &ofport->pp,
2141 ofport_destroy(ofport);
2144 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2147 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2149 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2151 ofport_remove(port);
2155 /* Updates 'port' with new 'pp' description.
2157 * Does not handle a name or port number change. The caller must implement
2158 * such a change as a delete followed by an add. */
2160 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2162 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2163 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2164 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2165 port->pp.state = ((port->pp.state & ~OFPUTIL_PS_LINK_DOWN)
2166 | (pp->state & OFPUTIL_PS_LINK_DOWN));
2167 port->pp.curr = pp->curr;
2168 port->pp.advertised = pp->advertised;
2169 port->pp.supported = pp->supported;
2170 port->pp.peer = pp->peer;
2171 port->pp.curr_speed = pp->curr_speed;
2172 port->pp.max_speed = pp->max_speed;
2174 connmgr_send_port_status(port->ofproto->connmgr, NULL,
2175 &port->pp, OFPPR_MODIFY);
2178 /* Update OpenFlow 'state' in 'port' and notify controller. */
2180 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2182 if (port->pp.state != state) {
2183 port->pp.state = state;
2184 connmgr_send_port_status(port->ofproto->connmgr, NULL,
2185 &port->pp, OFPPR_MODIFY);
2190 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2192 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2194 if (port->ofproto->ofproto_class->set_realdev) {
2195 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2197 if (port->ofproto->ofproto_class->set_stp_port) {
2198 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2200 if (port->ofproto->ofproto_class->set_cfm) {
2201 port->ofproto->ofproto_class->set_cfm(port, NULL);
2203 if (port->ofproto->ofproto_class->bundle_remove) {
2204 port->ofproto->ofproto_class->bundle_remove(port);
2210 ofport_destroy__(struct ofport *port)
2212 struct ofproto *ofproto = port->ofproto;
2213 const char *name = netdev_get_name(port->netdev);
2215 hmap_remove(&ofproto->ports, &port->hmap_node);
2216 shash_delete(&ofproto->port_by_name,
2217 shash_find(&ofproto->port_by_name, name));
2219 netdev_close(port->netdev);
2220 ofproto->ofproto_class->port_dealloc(port);
2224 ofport_destroy(struct ofport *port)
2227 dealloc_ofp_port(port->ofproto, port->ofp_port);
2228 port->ofproto->ofproto_class->port_destruct(port);
2229 ofport_destroy__(port);
2234 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2236 struct ofport *port;
2238 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2240 if (port->ofp_port == ofp_port) {
2247 static long long int
2248 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2250 struct ofport_usage *usage;
2252 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2253 &ofproto->ofport_usage) {
2254 if (usage->ofp_port == ofp_port) {
2255 return usage->last_used;
2262 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2263 long long int last_used)
2265 struct ofport_usage *usage;
2266 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2267 &ofproto->ofport_usage) {
2268 if (usage->ofp_port == ofp_port) {
2269 usage->last_used = last_used;
2273 ovs_assert(last_used == LLONG_MAX);
2275 usage = xmalloc(sizeof *usage);
2276 usage->ofp_port = ofp_port;
2277 usage->last_used = last_used;
2278 hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2279 hash_ofp_port(ofp_port));
2283 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2285 struct ofport_usage *usage;
2286 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2287 &ofproto->ofport_usage) {
2288 if (usage->ofp_port == ofp_port) {
2289 hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2297 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2299 struct ofproto *ofproto = port->ofproto;
2302 if (ofproto->ofproto_class->port_get_stats) {
2303 error = ofproto->ofproto_class->port_get_stats(port, stats);
2312 update_port(struct ofproto *ofproto, const char *name)
2314 struct ofproto_port ofproto_port;
2315 struct ofputil_phy_port pp;
2316 struct netdev *netdev;
2317 struct ofport *port;
2319 COVERAGE_INC(ofproto_update_port);
2321 /* Fetch 'name''s location and properties from the datapath. */
2322 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2323 ? ofport_open(ofproto, &ofproto_port, &pp)
2327 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2328 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2329 struct netdev *old_netdev = port->netdev;
2331 /* 'name' hasn't changed location. Any properties changed? */
2332 if (!ofport_equal(&port->pp, &pp)) {
2333 ofport_modified(port, &pp);
2336 update_mtu(ofproto, port);
2338 /* Install the newly opened netdev in case it has changed.
2339 * Don't close the old netdev yet in case port_modified has to
2340 * remove a retained reference to it.*/
2341 port->netdev = netdev;
2342 port->change_seq = netdev_get_change_seq(netdev);
2344 if (port->ofproto->ofproto_class->port_modified) {
2345 port->ofproto->ofproto_class->port_modified(port);
2348 netdev_close(old_netdev);
2350 /* If 'port' is nonnull then its name differs from 'name' and thus
2351 * we should delete it. If we think there's a port named 'name'
2352 * then its port number must be wrong now so delete it too. */
2354 ofport_remove(port);
2356 ofport_remove_with_name(ofproto, name);
2357 ofport_install(ofproto, netdev, &pp);
2360 /* Any port named 'name' is gone now. */
2361 ofport_remove_with_name(ofproto, name);
2363 ofproto_port_destroy(&ofproto_port);
2367 init_ports(struct ofproto *p)
2369 struct ofproto_port_dump dump;
2370 struct ofproto_port ofproto_port;
2371 struct shash_node *node, *next;
2373 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2374 const char *name = ofproto_port.name;
2376 if (shash_find(&p->port_by_name, name)) {
2377 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2380 struct ofputil_phy_port pp;
2381 struct netdev *netdev;
2383 /* Check if an OpenFlow port number had been requested. */
2384 node = shash_find(&init_ofp_ports, name);
2386 const struct iface_hint *iface_hint = node->data;
2387 simap_put(&p->ofp_requests, name,
2388 ofp_to_u16(iface_hint->ofp_port));
2391 netdev = ofport_open(p, &ofproto_port, &pp);
2393 ofport_install(p, netdev, &pp);
2394 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2395 p->alloc_port_no = MAX(p->alloc_port_no,
2396 ofp_to_u16(ofproto_port.ofp_port));
2402 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2403 struct iface_hint *iface_hint = node->data;
2405 if (!strcmp(iface_hint->br_name, p->name)) {
2406 free(iface_hint->br_name);
2407 free(iface_hint->br_type);
2409 shash_delete(&init_ofp_ports, node);
2416 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2417 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2419 find_min_mtu(struct ofproto *p)
2421 struct ofport *ofport;
2424 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2425 struct netdev *netdev = ofport->netdev;
2428 /* Skip any internal ports, since that's what we're trying to
2430 if (!strcmp(netdev_get_type(netdev), "internal")) {
2434 if (netdev_get_mtu(netdev, &dev_mtu)) {
2437 if (!mtu || dev_mtu < mtu) {
2442 return mtu ? mtu: ETH_PAYLOAD_MAX;
2445 /* Update MTU of all datapath devices on 'p' to the minimum of the
2446 * non-datapath ports in event of 'port' added or changed. */
2448 update_mtu(struct ofproto *p, struct ofport *port)
2450 struct ofport *ofport;
2451 struct netdev *netdev = port->netdev;
2452 int dev_mtu, old_min;
2454 if (netdev_get_mtu(netdev, &dev_mtu)) {
2458 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2459 if (dev_mtu > p->min_mtu) {
2460 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2461 dev_mtu = p->min_mtu;
2464 port->mtu = dev_mtu;
2468 /* For non-internal port find new min mtu. */
2469 old_min = p->min_mtu;
2470 port->mtu = dev_mtu;
2471 p->min_mtu = find_min_mtu(p);
2472 if (p->min_mtu == old_min) {
2476 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2477 struct netdev *netdev = ofport->netdev;
2479 if (!strcmp(netdev_get_type(netdev), "internal")) {
2480 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2481 ofport->mtu = p->min_mtu;
2488 ofproto_rule_destroy__(struct rule *rule)
2489 OVS_NO_THREAD_SAFETY_ANALYSIS
2491 cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2492 rule_actions_destroy(rule_get_actions(rule));
2493 ovs_mutex_destroy(&rule->mutex);
2494 rule->ofproto->ofproto_class->rule_dealloc(rule);
2498 rule_destroy_cb(struct rule *rule)
2500 rule->ofproto->ofproto_class->rule_destruct(rule);
2501 ofproto_rule_destroy__(rule);
2505 ofproto_rule_ref(struct rule *rule)
2508 ovs_refcount_ref(&rule->ref_count);
2512 /* Decrements 'rule''s ref_count and schedules 'rule' to be destroyed if the
2513 * ref_count reaches 0.
2515 * Use of RCU allows short term use (between RCU quiescent periods) without
2516 * keeping a reference. A reference must be taken if the rule needs to
2517 * stay around accross the RCU quiescent periods. */
2519 ofproto_rule_unref(struct rule *rule)
2521 if (rule && ovs_refcount_unref(&rule->ref_count) == 1) {
2522 ovsrcu_postpone(rule_destroy_cb, rule);
2527 ofproto_group_ref(struct ofgroup *group)
2530 ovs_refcount_ref(&group->ref_count);
2535 ofproto_group_unref(struct ofgroup *group)
2537 if (group && ovs_refcount_unref(&group->ref_count) == 1) {
2538 group->ofproto->ofproto_class->group_destruct(group);
2539 ofputil_bucket_list_destroy(&group->buckets);
2540 group->ofproto->ofproto_class->group_dealloc(group);
2544 static uint32_t get_provider_meter_id(const struct ofproto *,
2545 uint32_t of_meter_id);
2547 /* Creates and returns a new 'struct rule_actions', whose actions are a copy
2548 * of from the 'ofpacts_len' bytes of 'ofpacts'. */
2549 const struct rule_actions *
2550 rule_actions_create(const struct ofpact *ofpacts, size_t ofpacts_len)
2552 struct rule_actions *actions;
2554 actions = xmalloc(sizeof *actions + ofpacts_len);
2555 actions->ofpacts_len = ofpacts_len;
2556 actions->has_meter = ofpacts_get_meter(ofpacts, ofpacts_len) != 0;
2557 memcpy(actions->ofpacts, ofpacts, ofpacts_len);
2559 actions->has_learn_with_delete = (next_learn_with_delete(actions, NULL)
2565 /* Free the actions after the RCU quiescent period is reached. */
2567 rule_actions_destroy(const struct rule_actions *actions)
2570 ovsrcu_postpone(free, CONST_CAST(struct rule_actions *, actions));
2574 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2575 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2577 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2578 OVS_REQUIRES(ofproto_mutex)
2580 if (port == OFPP_ANY) {
2583 const struct rule_actions *actions = rule_get_actions(rule);
2584 return ofpacts_output_to_port(actions->ofpacts,
2585 actions->ofpacts_len, port);
2589 /* Returns true if 'rule' has group and equals group_id. */
2591 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
2592 OVS_REQUIRES(ofproto_mutex)
2594 if (group_id == OFPG_ANY) {
2597 const struct rule_actions *actions = rule_get_actions(rule);
2598 return ofpacts_output_to_group(actions->ofpacts,
2599 actions->ofpacts_len, group_id);
2604 rule_execute_destroy(struct rule_execute *e)
2606 ofproto_rule_unref(e->rule);
2607 list_remove(&e->list_node);
2611 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2612 * by passing them to the ofproto provider. */
2614 run_rule_executes(struct ofproto *ofproto)
2615 OVS_EXCLUDED(ofproto_mutex)
2617 struct rule_execute *e, *next;
2618 struct list executes;
2620 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2621 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2624 flow_extract(e->packet, NULL, &flow);
2625 flow.in_port.ofp_port = e->in_port;
2626 ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2628 rule_execute_destroy(e);
2632 /* Destroys and discards all "rule_execute" operations queued up in
2633 * ofproto->rule_executes. */
2635 destroy_rule_executes(struct ofproto *ofproto)
2637 struct rule_execute *e, *next;
2638 struct list executes;
2640 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2641 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2642 ofpbuf_delete(e->packet);
2643 rule_execute_destroy(e);
2648 rule_is_readonly(const struct rule *rule)
2650 const struct oftable *table = &rule->ofproto->tables[rule->table_id];
2651 return (table->flags & OFTABLE_READONLY) != 0;
2655 hash_learned_cookie(ovs_be64 cookie_, uint8_t table_id)
2657 uint64_t cookie = (OVS_FORCE uint64_t) cookie_;
2658 return hash_3words(cookie, cookie >> 32, table_id);
2662 learned_cookies_update_one__(struct ofproto *ofproto,
2663 const struct ofpact_learn *learn,
2664 int delta, struct list *dead_cookies)
2665 OVS_REQUIRES(ofproto_mutex)
2667 uint32_t hash = hash_learned_cookie(learn->cookie, learn->table_id);
2668 struct learned_cookie *c;
2670 HMAP_FOR_EACH_WITH_HASH (c, u.hmap_node, hash, &ofproto->learned_cookies) {
2671 if (c->cookie == learn->cookie && c->table_id == learn->table_id) {
2673 ovs_assert(c->n >= 0);
2676 hmap_remove(&ofproto->learned_cookies, &c->u.hmap_node);
2677 list_push_back(dead_cookies, &c->u.list_node);
2684 ovs_assert(delta > 0);
2685 c = xmalloc(sizeof *c);
2686 hmap_insert(&ofproto->learned_cookies, &c->u.hmap_node, hash);
2687 c->cookie = learn->cookie;
2688 c->table_id = learn->table_id;
2692 static const struct ofpact_learn *
2693 next_learn_with_delete(const struct rule_actions *actions,
2694 const struct ofpact_learn *start)
2696 const struct ofpact *pos;
2698 for (pos = start ? ofpact_next(&start->ofpact) : actions->ofpacts;
2699 pos < ofpact_end(actions->ofpacts, actions->ofpacts_len);
2700 pos = ofpact_next(pos)) {
2701 if (pos->type == OFPACT_LEARN) {
2702 const struct ofpact_learn *learn = ofpact_get_LEARN(pos);
2703 if (learn->flags & NX_LEARN_F_DELETE_LEARNED) {
2713 learned_cookies_update__(struct ofproto *ofproto,
2714 const struct rule_actions *actions,
2715 int delta, struct list *dead_cookies)
2716 OVS_REQUIRES(ofproto_mutex)
2718 if (actions->has_learn_with_delete) {
2719 const struct ofpact_learn *learn;
2721 for (learn = next_learn_with_delete(actions, NULL); learn;
2722 learn = next_learn_with_delete(actions, learn)) {
2723 learned_cookies_update_one__(ofproto, learn, delta, dead_cookies);
2729 learned_cookies_inc(struct ofproto *ofproto,
2730 const struct rule_actions *actions)
2731 OVS_REQUIRES(ofproto_mutex)
2733 learned_cookies_update__(ofproto, actions, +1, NULL);
2737 learned_cookies_dec(struct ofproto *ofproto,
2738 const struct rule_actions *actions,
2739 struct list *dead_cookies)
2740 OVS_REQUIRES(ofproto_mutex)
2742 learned_cookies_update__(ofproto, actions, -1, dead_cookies);
2746 learned_cookies_flush(struct ofproto *ofproto, struct list *dead_cookies)
2747 OVS_REQUIRES(ofproto_mutex)
2749 struct learned_cookie *c, *next;
2751 LIST_FOR_EACH_SAFE (c, next, u.list_node, dead_cookies) {
2752 struct rule_criteria criteria;
2753 struct rule_collection rules;
2756 match_init_catchall(&match);
2757 rule_criteria_init(&criteria, c->table_id, &match, 0,
2758 c->cookie, OVS_BE64_MAX, OFPP_ANY, OFPG_ANY);
2759 rule_criteria_require_rw(&criteria, false);
2760 collect_rules_loose(ofproto, &criteria, &rules);
2761 delete_flows__(&rules, OFPRR_DELETE, NULL);
2762 rule_criteria_destroy(&criteria);
2763 rule_collection_destroy(&rules);
2765 list_remove(&c->u.list_node);
2771 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2773 ofconn_send_reply(ofconn, make_echo_reply(oh));
2778 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2780 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2781 struct ofputil_switch_features features;
2782 struct ofport *port;
2786 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2788 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2790 features.datapath_id = ofproto->datapath_id;
2791 features.n_buffers = pktbuf_capacity();
2792 features.n_tables = ofproto_get_n_visible_tables(ofproto);
2793 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2794 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2796 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2798 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2799 features.auxiliary_id = 0;
2800 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2802 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2803 ofputil_put_switch_features_port(&port->pp, b);
2806 ofconn_send_reply(ofconn, b);
2811 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2813 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2814 struct ofp_switch_config *osc;
2815 enum ofp_config_flags flags;
2819 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2820 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2821 flags = ofproto->frag_handling;
2822 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2823 if (oh->version < OFP13_VERSION
2824 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2825 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2827 osc->flags = htons(flags);
2828 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2829 ofconn_send_reply(ofconn, buf);
2835 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2837 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2838 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2839 uint16_t flags = ntohs(osc->flags);
2841 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2842 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2843 enum ofp_config_flags cur = ofproto->frag_handling;
2844 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2846 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2848 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2849 ofproto->frag_handling = next;
2851 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2853 ofputil_frag_handling_to_string(next));
2857 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2858 ofconn_set_invalid_ttl_to_controller(ofconn,
2859 (oh->version < OFP13_VERSION
2860 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2862 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2867 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2868 * error message code for the caller to propagate upward. Otherwise, returns
2871 * The log message mentions 'msg_type'. */
2873 reject_slave_controller(struct ofconn *ofconn)
2875 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2876 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2877 return OFPERR_OFPBRC_EPERM;
2883 /* Checks that the 'ofpacts_len' bytes of action in 'ofpacts' are appropriate
2886 * - If they use a meter, then 'ofproto' has that meter configured.
2888 * - If they use any groups, then 'ofproto' has that group configured.
2890 * Returns 0 if successful, otherwise an OpenFlow error. */
2892 ofproto_check_ofpacts(struct ofproto *ofproto,
2893 const struct ofpact ofpacts[], size_t ofpacts_len)
2895 const struct ofpact *a;
2898 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2899 if (mid && get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2900 return OFPERR_OFPMMFC_INVALID_METER;
2903 OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
2904 if (a->type == OFPACT_GROUP
2905 && !ofproto_group_exists(ofproto, ofpact_get_GROUP(a)->group_id)) {
2906 return OFPERR_OFPBAC_BAD_OUT_GROUP;
2914 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2916 struct ofproto *p = ofconn_get_ofproto(ofconn);
2917 struct ofputil_packet_out po;
2918 struct ofpbuf *payload;
2919 uint64_t ofpacts_stub[1024 / 8];
2920 struct ofpbuf ofpacts;
2924 COVERAGE_INC(ofproto_packet_out);
2926 error = reject_slave_controller(ofconn);
2931 /* Decode message. */
2932 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2933 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2935 goto exit_free_ofpacts;
2937 if (ofp_to_u16(po.in_port) >= p->max_ports
2938 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2939 error = OFPERR_OFPBRC_BAD_PORT;
2940 goto exit_free_ofpacts;
2944 if (po.buffer_id != UINT32_MAX) {
2945 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2946 if (error || !payload) {
2947 goto exit_free_ofpacts;
2950 /* Ensure that the L3 header is 32-bit aligned. */
2951 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2954 /* Verify actions against packet, then send packet if successful. */
2955 flow_extract(payload, NULL, &flow);
2956 flow.in_port.ofp_port = po.in_port;
2957 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len);
2959 error = p->ofproto_class->packet_out(p, payload, &flow,
2960 po.ofpacts, po.ofpacts_len);
2962 ofpbuf_delete(payload);
2965 ofpbuf_uninit(&ofpacts);
2971 update_port_config(struct ofconn *ofconn, struct ofport *port,
2972 enum ofputil_port_config config,
2973 enum ofputil_port_config mask)
2975 enum ofputil_port_config toggle = (config ^ port->pp.config) & mask;
2977 if (toggle & OFPUTIL_PC_PORT_DOWN
2978 && (config & OFPUTIL_PC_PORT_DOWN
2979 ? netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL)
2980 : netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL))) {
2981 /* We tried to bring the port up or down, but it failed, so don't
2982 * update the "down" bit. */
2983 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2987 enum ofputil_port_config old_config = port->pp.config;
2988 port->pp.config ^= toggle;
2989 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2990 connmgr_send_port_status(port->ofproto->connmgr, ofconn, &port->pp,
2996 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2998 struct ofproto *p = ofconn_get_ofproto(ofconn);
2999 struct ofputil_port_mod pm;
3000 struct ofport *port;
3003 error = reject_slave_controller(ofconn);
3008 error = ofputil_decode_port_mod(oh, &pm, false);
3013 port = ofproto_get_port(p, pm.port_no);
3015 return OFPERR_OFPPMFC_BAD_PORT;
3016 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
3017 return OFPERR_OFPPMFC_BAD_HW_ADDR;
3019 update_port_config(ofconn, port, pm.config, pm.mask);
3021 netdev_set_advertisements(port->netdev, pm.advertise);
3028 handle_desc_stats_request(struct ofconn *ofconn,
3029 const struct ofp_header *request)
3031 static const char *default_mfr_desc = "Nicira, Inc.";
3032 static const char *default_hw_desc = "Open vSwitch";
3033 static const char *default_sw_desc = VERSION;
3034 static const char *default_serial_desc = "None";
3035 static const char *default_dp_desc = "None";
3037 struct ofproto *p = ofconn_get_ofproto(ofconn);
3038 struct ofp_desc_stats *ods;
3041 msg = ofpraw_alloc_stats_reply(request, 0);
3042 ods = ofpbuf_put_zeros(msg, sizeof *ods);
3043 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
3044 sizeof ods->mfr_desc);
3045 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
3046 sizeof ods->hw_desc);
3047 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
3048 sizeof ods->sw_desc);
3049 ovs_strlcpy(ods->serial_num,
3050 p->serial_desc ? p->serial_desc : default_serial_desc,
3051 sizeof ods->serial_num);
3052 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
3053 sizeof ods->dp_desc);
3054 ofconn_send_reply(ofconn, msg);
3060 handle_table_stats_request(struct ofconn *ofconn,
3061 const struct ofp_header *request)
3063 struct ofproto *p = ofconn_get_ofproto(ofconn);
3064 struct ofp12_table_stats *ots;
3069 /* Set up default values.
3071 * ofp12_table_stats is used as a generic structure as
3072 * it is able to hold all the fields for ofp10_table_stats
3073 * and ofp11_table_stats (and of course itself).
3075 ots = xcalloc(p->n_tables, sizeof *ots);
3076 for (i = 0; i < p->n_tables; i++) {
3077 ots[i].table_id = i;
3078 sprintf(ots[i].name, "table%"PRIuSIZE, i);
3079 ots[i].match = htonll(OFPXMT13_MASK);
3080 ots[i].wildcards = htonll(OFPXMT13_MASK);
3081 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
3082 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
3083 ots[i].write_setfields = htonll(OFPXMT13_MASK);
3084 ots[i].apply_setfields = htonll(OFPXMT13_MASK);
3085 ots[i].metadata_match = OVS_BE64_MAX;
3086 ots[i].metadata_write = OVS_BE64_MAX;
3087 ots[i].instructions = htonl(OFPIT11_ALL);
3088 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
3089 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
3090 fat_rwlock_rdlock(&p->tables[i].cls.rwlock);
3091 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
3092 fat_rwlock_unlock(&p->tables[i].cls.rwlock);
3095 p->ofproto_class->get_tables(p, ots);
3097 /* Post-process the tables, dropping hidden tables. */
3098 n_tables = p->n_tables;
3099 for (i = 0; i < p->n_tables; i++) {
3100 const struct oftable *table = &p->tables[i];
3102 if (table->flags & OFTABLE_HIDDEN) {
3108 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
3111 if (table->max_flows < ntohl(ots[i].max_entries)) {
3112 ots[i].max_entries = htonl(table->max_flows);
3116 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
3117 ofconn_send_reply(ofconn, msg);
3125 append_port_stat(struct ofport *port, struct list *replies)
3127 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3129 calc_duration(port->created, time_msec(),
3130 &ops.duration_sec, &ops.duration_nsec);
3132 /* Intentionally ignore return value, since errors will set
3133 * 'stats' to all-1s, which is correct for OpenFlow, and
3134 * netdev_get_stats() will log errors. */
3135 ofproto_port_get_stats(port, &ops.stats);
3137 ofputil_append_port_stat(replies, &ops);
3141 handle_port_request(struct ofconn *ofconn,
3142 const struct ofp_header *request, ofp_port_t port_no,
3143 void (*cb)(struct ofport *, struct list *replies))
3145 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3146 struct ofport *port;
3147 struct list replies;
3149 ofpmp_init(&replies, request);
3150 if (port_no != OFPP_ANY) {
3151 port = ofproto_get_port(ofproto, port_no);
3156 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3161 ofconn_send_replies(ofconn, &replies);
3165 handle_port_stats_request(struct ofconn *ofconn,
3166 const struct ofp_header *request)
3171 error = ofputil_decode_port_stats_request(request, &port_no);
3173 handle_port_request(ofconn, request, port_no, append_port_stat);
3179 append_port_desc(struct ofport *port, struct list *replies)
3181 ofputil_append_port_desc_stats_reply(&port->pp, replies);
3185 handle_port_desc_stats_request(struct ofconn *ofconn,
3186 const struct ofp_header *request)
3191 error = ofputil_decode_port_desc_stats_request(request, &port_no);
3193 handle_port_request(ofconn, request, port_no, append_port_desc);
3199 hash_cookie(ovs_be64 cookie)
3201 return hash_uint64((OVS_FORCE uint64_t)cookie);
3205 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3206 OVS_REQUIRES(ofproto_mutex)
3208 hindex_insert(&ofproto->cookies, &rule->cookie_node,
3209 hash_cookie(rule->flow_cookie));
3213 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3214 OVS_REQUIRES(ofproto_mutex)
3216 hindex_remove(&ofproto->cookies, &rule->cookie_node);
3220 calc_duration(long long int start, long long int now,
3221 uint32_t *sec, uint32_t *nsec)
3223 long long int msecs = now - start;
3224 *sec = msecs / 1000;
3225 *nsec = (msecs % 1000) * (1000 * 1000);
3228 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
3229 * true if 'table_id' is OK, false otherwise. */
3231 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3233 return table_id == OFPTT_ALL || table_id < ofproto->n_tables;
3236 static struct oftable *
3237 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3239 struct oftable *table;
3241 for (table = &ofproto->tables[table_id];
3242 table < &ofproto->tables[ofproto->n_tables];
3244 if (!(table->flags & OFTABLE_HIDDEN)) {
3252 static struct oftable *
3253 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3255 if (table_id == 0xff) {
3256 return next_visible_table(ofproto, 0);
3257 } else if (table_id < ofproto->n_tables) {
3258 return &ofproto->tables[table_id];
3264 static struct oftable *
3265 next_matching_table(const struct ofproto *ofproto,
3266 const struct oftable *table, uint8_t table_id)
3268 return (table_id == 0xff
3269 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3273 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3275 * - If TABLE_ID is 0xff, this iterates over every classifier table in
3276 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3278 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3279 * only once, for that table. (This can be used to access tables marked
3282 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3283 * entered at all. (Perhaps you should have validated TABLE_ID with
3284 * check_table_id().)
3286 * All parameters are evaluated multiple times.
3288 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
3289 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
3291 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3293 /* Initializes 'criteria' in a straightforward way based on the other
3296 * By default, the criteria include flows that are read-only, on the assumption
3297 * that the collected flows won't be modified. Call rule_criteria_require_rw()
3298 * if flows will be modified.
3300 * For "loose" matching, the 'priority' parameter is unimportant and may be
3303 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3304 const struct match *match, unsigned int priority,
3305 ovs_be64 cookie, ovs_be64 cookie_mask,
3306 ofp_port_t out_port, uint32_t out_group)
3308 criteria->table_id = table_id;
3309 cls_rule_init(&criteria->cr, match, priority);
3310 criteria->cookie = cookie;
3311 criteria->cookie_mask = cookie_mask;
3312 criteria->out_port = out_port;
3313 criteria->out_group = out_group;
3315 /* We ordinarily want to skip hidden rules, but there has to be a way for
3316 * code internal to OVS to modify and delete them, so if the criteria
3317 * specify a priority that can only be for a hidden flow, then allow hidden
3318 * rules to be selected. (This doesn't allow OpenFlow clients to meddle
3319 * with hidden flows because OpenFlow uses only a 16-bit field to specify
3321 criteria->include_hidden = priority > UINT16_MAX;
3323 /* We assume that the criteria are being used to collect flows for reading
3324 * but not modification. Thus, we should collect read-only flows. */
3325 criteria->include_readonly = true;
3328 /* By default, criteria initialized by rule_criteria_init() will match flows
3329 * that are read-only, on the assumption that the collected flows won't be
3330 * modified. Call this function to match only flows that are be modifiable.
3332 * Specify 'can_write_readonly' as false in ordinary circumstances, true if the
3333 * caller has special privileges that allow it to modify even "read-only"
3336 rule_criteria_require_rw(struct rule_criteria *criteria,
3337 bool can_write_readonly)
3339 criteria->include_readonly = can_write_readonly;
3343 rule_criteria_destroy(struct rule_criteria *criteria)
3345 cls_rule_destroy(&criteria->cr);
3349 rule_collection_init(struct rule_collection *rules)
3351 rules->rules = rules->stub;
3353 rules->capacity = ARRAY_SIZE(rules->stub);
3357 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3359 if (rules->n >= rules->capacity) {
3360 size_t old_size, new_size;
3362 old_size = rules->capacity * sizeof *rules->rules;
3363 rules->capacity *= 2;
3364 new_size = rules->capacity * sizeof *rules->rules;
3366 if (rules->rules == rules->stub) {
3367 rules->rules = xmalloc(new_size);
3368 memcpy(rules->rules, rules->stub, old_size);
3370 rules->rules = xrealloc(rules->rules, new_size);
3374 rules->rules[rules->n++] = rule;
3378 rule_collection_ref(struct rule_collection *rules)
3379 OVS_REQUIRES(ofproto_mutex)
3383 for (i = 0; i < rules->n; i++) {
3384 ofproto_rule_ref(rules->rules[i]);
3389 rule_collection_unref(struct rule_collection *rules)
3393 for (i = 0; i < rules->n; i++) {
3394 ofproto_rule_unref(rules->rules[i]);
3399 rule_collection_destroy(struct rule_collection *rules)
3401 if (rules->rules != rules->stub) {
3406 /* Checks whether 'rule' matches 'c' and, if so, adds it to 'rules'. This
3407 * function verifies most of the criteria in 'c' itself, but the caller must
3408 * check 'c->cr' itself.
3410 * Increments '*n_readonly' if 'rule' wasn't added because it's read-only (and
3411 * 'c' only includes modifiable rules). */
3413 collect_rule(struct rule *rule, const struct rule_criteria *c,
3414 struct rule_collection *rules, size_t *n_readonly)
3415 OVS_REQUIRES(ofproto_mutex)
3417 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3418 && ofproto_rule_has_out_port(rule, c->out_port)
3419 && ofproto_rule_has_out_group(rule, c->out_group)
3420 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)
3421 && (!rule_is_hidden(rule) || c->include_hidden)) {
3422 /* Rule matches all the criteria... */
3423 if (!rule_is_readonly(rule) || c->include_readonly) {
3425 rule_collection_add(rules, rule);
3427 /* ...except it's read-only. */
3433 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3434 * on classifiers rules are done in the "loose" way required for OpenFlow
3435 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3438 * Returns 0 on success, otherwise an OpenFlow error code. */
3440 collect_rules_loose(struct ofproto *ofproto,
3441 const struct rule_criteria *criteria,
3442 struct rule_collection *rules)
3443 OVS_REQUIRES(ofproto_mutex)
3445 struct oftable *table;
3446 enum ofperr error = 0;
3447 size_t n_readonly = 0;
3449 rule_collection_init(rules);
3451 if (!check_table_id(ofproto, criteria->table_id)) {
3452 error = OFPERR_OFPBRC_BAD_TABLE_ID;
3456 if (criteria->cookie_mask == OVS_BE64_MAX) {
3459 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3460 hash_cookie(criteria->cookie),
3461 &ofproto->cookies) {
3462 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3463 collect_rule(rule, criteria, rules, &n_readonly);
3467 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3468 struct cls_cursor cursor;
3471 fat_rwlock_rdlock(&table->cls.rwlock);
3472 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3473 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3474 collect_rule(rule, criteria, rules, &n_readonly);
3476 fat_rwlock_unlock(&table->cls.rwlock);
3481 if (!error && !rules->n && n_readonly) {
3482 /* We didn't find any rules to modify. We did find some read-only
3483 * rules that we're not allowed to modify, so report that. */
3484 error = OFPERR_OFPBRC_EPERM;
3487 rule_collection_destroy(rules);
3492 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3493 * on classifiers rules are done in the "strict" way required for OpenFlow
3494 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3495 * rules on list 'rules'.
3497 * Returns 0 on success, otherwise an OpenFlow error code. */
3499 collect_rules_strict(struct ofproto *ofproto,
3500 const struct rule_criteria *criteria,
3501 struct rule_collection *rules)
3502 OVS_REQUIRES(ofproto_mutex)
3504 struct oftable *table;
3505 size_t n_readonly = 0;
3508 rule_collection_init(rules);
3510 if (!check_table_id(ofproto, criteria->table_id)) {
3511 error = OFPERR_OFPBRC_BAD_TABLE_ID;
3515 if (criteria->cookie_mask == OVS_BE64_MAX) {
3518 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3519 hash_cookie(criteria->cookie),
3520 &ofproto->cookies) {
3521 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3522 collect_rule(rule, criteria, rules, &n_readonly);
3526 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3529 fat_rwlock_rdlock(&table->cls.rwlock);
3530 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3531 &table->cls, &criteria->cr));
3532 fat_rwlock_unlock(&table->cls.rwlock);
3534 collect_rule(rule, criteria, rules, &n_readonly);
3540 if (!error && !rules->n && n_readonly) {
3541 /* We didn't find any rules to modify. We did find some read-only
3542 * rules that we're not allowed to modify, so report that. */
3543 error = OFPERR_OFPBRC_EPERM;
3546 rule_collection_destroy(rules);
3551 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3552 * forced into the range of a uint16_t. */
3554 age_secs(long long int age_ms)
3556 return (age_ms < 0 ? 0
3557 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3558 : (unsigned int) age_ms / 1000);
3562 handle_flow_stats_request(struct ofconn *ofconn,
3563 const struct ofp_header *request)
3564 OVS_EXCLUDED(ofproto_mutex)
3566 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3567 struct ofputil_flow_stats_request fsr;
3568 struct rule_criteria criteria;
3569 struct rule_collection rules;
3570 struct list replies;
3574 error = ofputil_decode_flow_stats_request(&fsr, request);
3579 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3580 fsr.cookie_mask, fsr.out_port, fsr.out_group);
3582 ovs_mutex_lock(&ofproto_mutex);
3583 error = collect_rules_loose(ofproto, &criteria, &rules);
3584 rule_criteria_destroy(&criteria);
3586 rule_collection_ref(&rules);
3588 ovs_mutex_unlock(&ofproto_mutex);
3594 ofpmp_init(&replies, request);
3595 for (i = 0; i < rules.n; i++) {
3596 struct rule *rule = rules.rules[i];
3597 long long int now = time_msec();
3598 struct ofputil_flow_stats fs;
3599 long long int created, used, modified;
3600 const struct rule_actions *actions;
3601 enum ofputil_flow_mod_flags flags;
3603 ovs_mutex_lock(&rule->mutex);
3604 fs.cookie = rule->flow_cookie;
3605 fs.idle_timeout = rule->idle_timeout;
3606 fs.hard_timeout = rule->hard_timeout;
3607 created = rule->created;
3608 modified = rule->modified;
3609 actions = rule_get_actions(rule);
3610 flags = rule->flags;
3611 ovs_mutex_unlock(&rule->mutex);
3613 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3614 &fs.byte_count, &used);
3616 minimatch_expand(&rule->cr.match, &fs.match);
3617 fs.table_id = rule->table_id;
3618 calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
3619 fs.priority = rule->cr.priority;
3620 fs.idle_age = age_secs(now - used);
3621 fs.hard_age = age_secs(now - modified);
3622 fs.ofpacts = actions->ofpacts;
3623 fs.ofpacts_len = actions->ofpacts_len;
3626 ofputil_append_flow_stats_reply(&fs, &replies);
3629 rule_collection_unref(&rules);
3630 rule_collection_destroy(&rules);
3632 ofconn_send_replies(ofconn, &replies);
3638 flow_stats_ds(struct rule *rule, struct ds *results)
3640 uint64_t packet_count, byte_count;
3641 const struct rule_actions *actions;
3642 long long int created, used;
3644 rule->ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3645 &byte_count, &used);
3647 ovs_mutex_lock(&rule->mutex);
3648 actions = rule_get_actions(rule);
3649 created = rule->created;
3650 ovs_mutex_unlock(&rule->mutex);
3652 if (rule->table_id != 0) {
3653 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3655 ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
3656 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3657 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3658 cls_rule_format(&rule->cr, results);
3659 ds_put_char(results, ',');
3661 ds_put_cstr(results, "actions=");
3662 ofpacts_format(actions->ofpacts, actions->ofpacts_len, results);
3664 ds_put_cstr(results, "\n");
3667 /* Adds a pretty-printed description of all flows to 'results', including
3668 * hidden flows (e.g., set up by in-band control). */
3670 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3672 struct oftable *table;
3674 OFPROTO_FOR_EACH_TABLE (table, p) {
3675 struct cls_cursor cursor;
3678 fat_rwlock_rdlock(&table->cls.rwlock);
3679 cls_cursor_init(&cursor, &table->cls, NULL);
3680 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3681 flow_stats_ds(rule, results);
3683 fat_rwlock_unlock(&table->cls.rwlock);
3687 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3688 * '*engine_type' and '*engine_id', respectively. */
3690 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3691 uint8_t *engine_type, uint8_t *engine_id)
3693 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3696 /* Checks the status change of CFM on 'ofport'.
3698 * Returns true if 'ofproto_class' does not support 'cfm_status_changed'. */
3700 ofproto_port_cfm_status_changed(struct ofproto *ofproto, ofp_port_t ofp_port)
3702 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3703 return (ofport && ofproto->ofproto_class->cfm_status_changed
3704 ? ofproto->ofproto_class->cfm_status_changed(ofport)
3708 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'.
3709 * Returns 0 if the port's CFM status was successfully stored into
3710 * '*status'. Returns positive errno if the port did not have CFM
3713 * The caller must provide and own '*status', and must free 'status->rmps'.
3714 * '*status' is indeterminate if the return value is non-zero. */
3716 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3717 struct cfm_status *status)
3719 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3720 return (ofport && ofproto->ofproto_class->get_cfm_status
3721 ? ofproto->ofproto_class->get_cfm_status(ofport, status)
3726 handle_aggregate_stats_request(struct ofconn *ofconn,
3727 const struct ofp_header *oh)
3728 OVS_EXCLUDED(ofproto_mutex)
3730 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3731 struct ofputil_flow_stats_request request;
3732 struct ofputil_aggregate_stats stats;
3733 bool unknown_packets, unknown_bytes;
3734 struct rule_criteria criteria;
3735 struct rule_collection rules;
3736 struct ofpbuf *reply;
3740 error = ofputil_decode_flow_stats_request(&request, oh);
3745 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3746 request.cookie, request.cookie_mask,
3747 request.out_port, request.out_group);
3749 ovs_mutex_lock(&ofproto_mutex);
3750 error = collect_rules_loose(ofproto, &criteria, &rules);
3751 rule_criteria_destroy(&criteria);
3753 rule_collection_ref(&rules);
3755 ovs_mutex_unlock(&ofproto_mutex);
3761 memset(&stats, 0, sizeof stats);
3762 unknown_packets = unknown_bytes = false;
3763 for (i = 0; i < rules.n; i++) {
3764 struct rule *rule = rules.rules[i];
3765 uint64_t packet_count;
3766 uint64_t byte_count;
3769 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3770 &byte_count, &used);
3772 if (packet_count == UINT64_MAX) {
3773 unknown_packets = true;
3775 stats.packet_count += packet_count;
3778 if (byte_count == UINT64_MAX) {
3779 unknown_bytes = true;
3781 stats.byte_count += byte_count;
3786 if (unknown_packets) {
3787 stats.packet_count = UINT64_MAX;
3789 if (unknown_bytes) {
3790 stats.byte_count = UINT64_MAX;
3793 rule_collection_unref(&rules);
3794 rule_collection_destroy(&rules);
3796 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3797 ofconn_send_reply(ofconn, reply);
3802 struct queue_stats_cbdata {
3803 struct ofport *ofport;
3804 struct list replies;
3809 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3810 const struct netdev_queue_stats *stats)
3812 struct ofputil_queue_stats oqs;
3814 oqs.port_no = cbdata->ofport->pp.port_no;
3815 oqs.queue_id = queue_id;
3816 oqs.tx_bytes = stats->tx_bytes;
3817 oqs.tx_packets = stats->tx_packets;
3818 oqs.tx_errors = stats->tx_errors;
3819 if (stats->created != LLONG_MIN) {
3820 calc_duration(stats->created, cbdata->now,
3821 &oqs.duration_sec, &oqs.duration_nsec);
3823 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3825 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3829 handle_queue_stats_dump_cb(uint32_t queue_id,
3830 struct netdev_queue_stats *stats,
3833 struct queue_stats_cbdata *cbdata = cbdata_;
3835 put_queue_stats(cbdata, queue_id, stats);
3839 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3840 struct queue_stats_cbdata *cbdata)
3842 cbdata->ofport = port;
3843 if (queue_id == OFPQ_ALL) {
3844 netdev_dump_queue_stats(port->netdev,
3845 handle_queue_stats_dump_cb, cbdata);
3847 struct netdev_queue_stats stats;
3849 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3850 put_queue_stats(cbdata, queue_id, &stats);
3852 return OFPERR_OFPQOFC_BAD_QUEUE;
3859 handle_queue_stats_request(struct ofconn *ofconn,
3860 const struct ofp_header *rq)
3862 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3863 struct queue_stats_cbdata cbdata;
3864 struct ofport *port;
3866 struct ofputil_queue_stats_request oqsr;
3868 COVERAGE_INC(ofproto_queue_req);
3870 ofpmp_init(&cbdata.replies, rq);
3871 cbdata.now = time_msec();
3873 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3878 if (oqsr.port_no == OFPP_ANY) {
3879 error = OFPERR_OFPQOFC_BAD_QUEUE;
3880 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3881 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3886 port = ofproto_get_port(ofproto, oqsr.port_no);
3888 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3889 : OFPERR_OFPQOFC_BAD_PORT);
3892 ofconn_send_replies(ofconn, &cbdata.replies);
3894 ofpbuf_list_delete(&cbdata.replies);
3901 should_evict_a_rule(struct oftable *table, unsigned int extra_space)
3902 OVS_REQUIRES(ofproto_mutex)
3903 OVS_NO_THREAD_SAFETY_ANALYSIS
3905 return classifier_count(&table->cls) + extra_space > table->max_flows;
3909 evict_rules_from_table(struct oftable *table, unsigned int extra_space)
3910 OVS_REQUIRES(ofproto_mutex)
3912 while (should_evict_a_rule(table, extra_space)) {
3915 if (!choose_rule_to_evict(table, &rule)) {
3916 return OFPERR_OFPFMFC_TABLE_FULL;
3918 ofproto_rule_delete__(rule, OFPRR_EVICTION);
3925 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3926 * in which no matching flow already exists in the flow table.
3928 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3929 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3930 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3931 * initiated now but may be retried later.
3933 * The caller retains ownership of 'fm->ofpacts'.
3935 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3938 add_flow(struct ofproto *ofproto, struct ofputil_flow_mod *fm,
3939 const struct flow_mod_requester *req)
3940 OVS_REQUIRES(ofproto_mutex)
3942 const struct rule_actions *actions;
3943 struct oftable *table;
3949 if (!check_table_id(ofproto, fm->table_id)) {
3950 error = OFPERR_OFPBRC_BAD_TABLE_ID;
3955 if (fm->table_id == 0xff) {
3956 if (ofproto->ofproto_class->rule_choose_table) {
3957 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3963 ovs_assert(table_id < ofproto->n_tables);
3967 } else if (fm->table_id < ofproto->n_tables) {
3968 table_id = fm->table_id;
3970 return OFPERR_OFPBRC_BAD_TABLE_ID;
3973 table = &ofproto->tables[table_id];
3974 if (table->flags & OFTABLE_READONLY
3975 && !(fm->flags & OFPUTIL_FF_NO_READONLY)) {
3976 return OFPERR_OFPBRC_EPERM;
3979 if (!(fm->flags & OFPUTIL_FF_HIDDEN_FIELDS)) {
3980 if (!match_has_default_hidden_fields(&fm->match)) {
3981 VLOG_WARN_RL(&rl, "%s: (add_flow) only internal flows can set "
3982 "non-default values to hidden fields", ofproto->name);
3983 return OFPERR_OFPBRC_EPERM;
3987 cls_rule_init(&cr, &fm->match, fm->priority);
3989 /* Transform "add" into "modify" if there's an existing identical flow. */
3990 fat_rwlock_rdlock(&table->cls.rwlock);
3991 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3992 fat_rwlock_unlock(&table->cls.rwlock);
3994 struct rule_collection rules;
3996 cls_rule_destroy(&cr);
3998 rule_collection_init(&rules);
3999 rule_collection_add(&rules, rule);
4000 fm->modify_cookie = true;
4001 error = modify_flows__(ofproto, fm, &rules, req);
4002 rule_collection_destroy(&rules);
4007 /* Check for overlap, if requested. */
4008 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
4011 fat_rwlock_rdlock(&table->cls.rwlock);
4012 overlaps = classifier_rule_overlaps(&table->cls, &cr);
4013 fat_rwlock_unlock(&table->cls.rwlock);
4016 cls_rule_destroy(&cr);
4017 return OFPERR_OFPFMFC_OVERLAP;
4021 /* If necessary, evict an existing rule to clear out space. */
4022 error = evict_rules_from_table(table, 1);
4024 cls_rule_destroy(&cr);
4028 /* Allocate new rule. */
4029 rule = ofproto->ofproto_class->rule_alloc();
4031 cls_rule_destroy(&cr);
4032 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
4033 ofproto->name, ovs_strerror(error));
4037 /* Initialize base state. */
4038 *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
4039 cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), &cr);
4040 ovs_refcount_init(&rule->ref_count);
4041 rule->flow_cookie = fm->new_cookie;
4042 rule->created = rule->modified = time_msec();
4044 ovs_mutex_init(&rule->mutex);
4045 ovs_mutex_lock(&rule->mutex);
4046 rule->idle_timeout = fm->idle_timeout;
4047 rule->hard_timeout = fm->hard_timeout;
4048 ovs_mutex_unlock(&rule->mutex);
4050 *CONST_CAST(uint8_t *, &rule->table_id) = table - ofproto->tables;
4051 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4052 actions = rule_actions_create(fm->ofpacts, fm->ofpacts_len);
4053 ovsrcu_set(&rule->actions, actions);
4054 list_init(&rule->meter_list_node);
4055 rule->eviction_group = NULL;
4056 list_init(&rule->expirable);
4057 rule->monitor_flags = 0;
4058 rule->add_seqno = 0;
4059 rule->modify_seqno = 0;
4061 /* Construct rule, initializing derived state. */
4062 error = ofproto->ofproto_class->rule_construct(rule);
4064 ofproto_rule_destroy__(rule);
4068 if (fm->hard_timeout || fm->idle_timeout) {
4069 list_insert(&ofproto->expirable, &rule->expirable);
4071 cookies_insert(ofproto, rule);
4072 eviction_group_add_rule(rule);
4073 if (actions->has_meter) {
4074 meter_insert_rule(rule);
4077 fat_rwlock_wrlock(&table->cls.rwlock);
4078 classifier_insert(&table->cls, CONST_CAST(struct cls_rule *, &rule->cr));
4079 fat_rwlock_unlock(&table->cls.rwlock);
4081 error = ofproto->ofproto_class->rule_insert(rule);
4083 oftable_remove_rule(rule);
4084 ofproto_rule_unref(rule);
4087 learned_cookies_inc(ofproto, actions);
4089 if (minimask_get_vid_mask(&rule->cr.match.mask) == VLAN_VID_MASK) {
4090 if (ofproto->vlan_bitmap) {
4091 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
4092 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
4093 bitmap_set1(ofproto->vlan_bitmap, vid);
4094 ofproto->vlans_changed = true;
4097 ofproto->vlans_changed = true;
4101 ofmonitor_report(ofproto->connmgr, rule, NXFME_ADDED, 0,
4102 req ? req->ofconn : NULL, req ? req->xid : 0, NULL);
4104 return req ? send_buffered_packet(req->ofconn, fm->buffer_id, rule) : 0;
4107 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4109 /* Modifies the rules listed in 'rules', changing their actions to match those
4112 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4115 * Returns 0 on success, otherwise an OpenFlow error code. */
4117 modify_flows__(struct ofproto *ofproto, struct ofputil_flow_mod *fm,
4118 const struct rule_collection *rules,
4119 const struct flow_mod_requester *req)
4120 OVS_REQUIRES(ofproto_mutex)
4122 struct list dead_cookies = LIST_INITIALIZER(&dead_cookies);
4123 enum nx_flow_update_event event;
4126 if (ofproto->ofproto_class->rule_premodify_actions) {
4127 for (i = 0; i < rules->n; i++) {
4128 struct rule *rule = rules->rules[i];
4131 error = ofproto->ofproto_class->rule_premodify_actions(
4132 rule, fm->ofpacts, fm->ofpacts_len);
4139 event = fm->command == OFPFC_ADD ? NXFME_ADDED : NXFME_MODIFIED;
4140 for (i = 0; i < rules->n; i++) {
4141 struct rule *rule = rules->rules[i];
4143 /* 'fm' says that */
4144 bool change_cookie = (fm->modify_cookie
4145 && fm->new_cookie != OVS_BE64_MAX
4146 && fm->new_cookie != rule->flow_cookie);
4148 const struct rule_actions *actions = rule_get_actions(rule);
4149 bool change_actions = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4151 actions->ofpacts_len);
4153 bool reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
4155 long long int now = time_msec();
4157 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
4159 if (change_cookie) {
4160 cookies_remove(ofproto, rule);
4163 ovs_mutex_lock(&rule->mutex);
4164 if (fm->command == OFPFC_ADD) {
4165 rule->idle_timeout = fm->idle_timeout;
4166 rule->hard_timeout = fm->hard_timeout;
4167 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4168 rule->created = now;
4170 if (change_cookie) {
4171 rule->flow_cookie = fm->new_cookie;
4173 rule->modified = now;
4174 ovs_mutex_unlock(&rule->mutex);
4176 if (change_cookie) {
4177 cookies_insert(ofproto, rule);
4179 if (fm->command == OFPFC_ADD) {
4180 if (fm->idle_timeout || fm->hard_timeout) {
4181 if (!rule->eviction_group) {
4182 eviction_group_add_rule(rule);
4185 eviction_group_remove_rule(rule);
4189 if (change_actions) {
4190 ovsrcu_set(&rule->actions, rule_actions_create(fm->ofpacts,
4194 if (change_actions || reset_counters) {
4195 ofproto->ofproto_class->rule_modify_actions(rule, reset_counters);
4198 if (event != NXFME_MODIFIED || change_actions || change_cookie) {
4199 ofmonitor_report(ofproto->connmgr, rule, event, 0,
4200 req ? req->ofconn : NULL, req ? req->xid : 0,
4201 change_actions ? actions : NULL);
4204 if (change_actions) {
4205 learned_cookies_inc(ofproto, rule_get_actions(rule));
4206 learned_cookies_dec(ofproto, actions, &dead_cookies);
4207 rule_actions_destroy(actions);
4210 learned_cookies_flush(ofproto, &dead_cookies);
4212 if (fm->buffer_id != UINT32_MAX && req) {
4213 return send_buffered_packet(req->ofconn, fm->buffer_id,
4221 modify_flows_add(struct ofproto *ofproto, struct ofputil_flow_mod *fm,
4222 const struct flow_mod_requester *req)
4223 OVS_REQUIRES(ofproto_mutex)
4225 if (fm->cookie_mask != htonll(0) || fm->new_cookie == OVS_BE64_MAX) {
4228 return add_flow(ofproto, fm, req);
4231 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
4234 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4237 modify_flows_loose(struct ofproto *ofproto, struct ofputil_flow_mod *fm,
4238 const struct flow_mod_requester *req)
4239 OVS_REQUIRES(ofproto_mutex)
4241 struct rule_criteria criteria;
4242 struct rule_collection rules;
4245 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4246 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4247 rule_criteria_require_rw(&criteria,
4248 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
4249 error = collect_rules_loose(ofproto, &criteria, &rules);
4250 rule_criteria_destroy(&criteria);
4253 error = (rules.n > 0
4254 ? modify_flows__(ofproto, fm, &rules, req)
4255 : modify_flows_add(ofproto, fm, req));
4258 rule_collection_destroy(&rules);
4263 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4264 * code on failure. */
4266 modify_flow_strict(struct ofproto *ofproto, struct ofputil_flow_mod *fm,
4267 const struct flow_mod_requester *req)
4268 OVS_REQUIRES(ofproto_mutex)
4270 struct rule_criteria criteria;
4271 struct rule_collection rules;
4274 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4275 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4276 rule_criteria_require_rw(&criteria,
4277 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
4278 error = collect_rules_strict(ofproto, &criteria, &rules);
4279 rule_criteria_destroy(&criteria);
4283 error = modify_flows_add(ofproto, fm, req);
4284 } else if (rules.n == 1) {
4285 error = modify_flows__(ofproto, fm, &rules, req);
4289 rule_collection_destroy(&rules);
4294 /* OFPFC_DELETE implementation. */
4296 /* Deletes the rules listed in 'rules'. */
4298 delete_flows__(const struct rule_collection *rules,
4299 enum ofp_flow_removed_reason reason,
4300 const struct flow_mod_requester *req)
4301 OVS_REQUIRES(ofproto_mutex)
4304 struct list dead_cookies = LIST_INITIALIZER(&dead_cookies);
4305 struct ofproto *ofproto = rules->rules[0]->ofproto;
4308 for (i = 0; i < rules->n; i++) {
4309 struct rule *rule = rules->rules[i];
4310 const struct rule_actions *actions = rule_get_actions(rule);
4312 ofproto_rule_send_removed(rule, reason);
4314 ofmonitor_report(ofproto->connmgr, rule, NXFME_DELETED, reason,
4315 req ? req->ofconn : NULL, req ? req->xid : 0,
4317 oftable_remove_rule(rule);
4318 ofproto->ofproto_class->rule_delete(rule);
4320 learned_cookies_dec(ofproto, actions, &dead_cookies);
4322 learned_cookies_flush(ofproto, &dead_cookies);
4323 ofmonitor_flush(ofproto->connmgr);
4327 /* Implements OFPFC_DELETE. */
4329 delete_flows_loose(struct ofproto *ofproto,
4330 const struct ofputil_flow_mod *fm,
4331 const struct flow_mod_requester *req)
4332 OVS_REQUIRES(ofproto_mutex)
4334 struct rule_criteria criteria;
4335 struct rule_collection rules;
4338 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4339 fm->cookie, fm->cookie_mask,
4340 fm->out_port, fm->out_group);
4341 rule_criteria_require_rw(&criteria,
4342 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
4343 error = collect_rules_loose(ofproto, &criteria, &rules);
4344 rule_criteria_destroy(&criteria);
4346 if (!error && rules.n > 0) {
4347 delete_flows__(&rules, fm->delete_reason, req);
4349 rule_collection_destroy(&rules);
4354 /* Implements OFPFC_DELETE_STRICT. */
4356 delete_flow_strict(struct ofproto *ofproto, const struct ofputil_flow_mod *fm,
4357 const struct flow_mod_requester *req)
4358 OVS_REQUIRES(ofproto_mutex)
4360 struct rule_criteria criteria;
4361 struct rule_collection rules;
4364 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4365 fm->cookie, fm->cookie_mask,
4366 fm->out_port, fm->out_group);
4367 rule_criteria_require_rw(&criteria,
4368 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
4369 error = collect_rules_strict(ofproto, &criteria, &rules);
4370 rule_criteria_destroy(&criteria);
4372 if (!error && rules.n > 0) {
4373 delete_flows__(&rules, fm->delete_reason, req);
4375 rule_collection_destroy(&rules);
4381 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4382 OVS_REQUIRES(ofproto_mutex)
4384 struct ofputil_flow_removed fr;
4387 if (rule_is_hidden(rule) ||
4388 !(rule->flags & OFPUTIL_FF_SEND_FLOW_REM)) {
4392 minimatch_expand(&rule->cr.match, &fr.match);
4393 fr.priority = rule->cr.priority;
4394 fr.cookie = rule->flow_cookie;
4396 fr.table_id = rule->table_id;
4397 calc_duration(rule->created, time_msec(),
4398 &fr.duration_sec, &fr.duration_nsec);
4399 ovs_mutex_lock(&rule->mutex);
4400 fr.idle_timeout = rule->idle_timeout;
4401 fr.hard_timeout = rule->hard_timeout;
4402 ovs_mutex_unlock(&rule->mutex);
4403 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4404 &fr.byte_count, &used);
4406 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4409 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4410 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4413 * ofproto implementation ->run() functions should use this function to expire
4414 * OpenFlow flows. */
4416 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4417 OVS_REQUIRES(ofproto_mutex)
4419 ofproto_rule_delete__(rule, reason);
4422 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
4423 * means "infinite". */
4425 reduce_timeout(uint16_t max, uint16_t *timeout)
4427 if (max && (!*timeout || *timeout > max)) {
4432 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4433 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4434 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
4436 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4438 ofproto_rule_reduce_timeouts(struct rule *rule,
4439 uint16_t idle_timeout, uint16_t hard_timeout)
4440 OVS_EXCLUDED(ofproto_mutex, rule->mutex)
4442 if (!idle_timeout && !hard_timeout) {
4446 ovs_mutex_lock(&ofproto_mutex);
4447 if (list_is_empty(&rule->expirable)) {
4448 list_insert(&rule->ofproto->expirable, &rule->expirable);
4450 ovs_mutex_unlock(&ofproto_mutex);
4452 ovs_mutex_lock(&rule->mutex);
4453 reduce_timeout(idle_timeout, &rule->idle_timeout);
4454 reduce_timeout(hard_timeout, &rule->hard_timeout);
4455 ovs_mutex_unlock(&rule->mutex);
4459 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4460 OVS_EXCLUDED(ofproto_mutex)
4462 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4463 struct ofputil_flow_mod fm;
4464 uint64_t ofpacts_stub[1024 / 8];
4465 struct ofpbuf ofpacts;
4468 error = reject_slave_controller(ofconn);
4473 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4474 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4476 u16_to_ofp(ofproto->max_ports),
4479 error = ofproto_check_ofpacts(ofproto, fm.ofpacts, fm.ofpacts_len);
4482 struct flow_mod_requester req;
4484 req.ofconn = ofconn;
4486 error = handle_flow_mod__(ofproto, &fm, &req);
4489 goto exit_free_ofpacts;
4492 ofconn_report_flow_mod(ofconn, fm.command);
4495 ofpbuf_uninit(&ofpacts);
4501 handle_flow_mod__(struct ofproto *ofproto, struct ofputil_flow_mod *fm,
4502 const struct flow_mod_requester *req)
4503 OVS_EXCLUDED(ofproto_mutex)
4507 ovs_mutex_lock(&ofproto_mutex);
4508 switch (fm->command) {
4510 error = add_flow(ofproto, fm, req);
4514 error = modify_flows_loose(ofproto, fm, req);
4517 case OFPFC_MODIFY_STRICT:
4518 error = modify_flow_strict(ofproto, fm, req);
4522 error = delete_flows_loose(ofproto, fm, req);
4525 case OFPFC_DELETE_STRICT:
4526 error = delete_flow_strict(ofproto, fm, req);
4530 if (fm->command > 0xff) {
4531 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4532 "flow_mod_table_id extension is not enabled",
4535 error = OFPERR_OFPFMFC_BAD_COMMAND;
4538 ofmonitor_flush(ofproto->connmgr);
4539 ovs_mutex_unlock(&ofproto_mutex);
4541 run_rule_executes(ofproto);
4546 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4548 struct ofputil_role_request request;
4549 struct ofputil_role_request reply;
4553 error = ofputil_decode_role_message(oh, &request);
4558 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4559 if (request.have_generation_id
4560 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4561 return OFPERR_OFPRRFC_STALE;
4564 ofconn_set_role(ofconn, request.role);
4567 reply.role = ofconn_get_role(ofconn);
4568 reply.have_generation_id = ofconn_get_master_election_id(
4569 ofconn, &reply.generation_id);
4570 buf = ofputil_encode_role_reply(oh, &reply);
4571 ofconn_send_reply(ofconn, buf);
4577 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4578 const struct ofp_header *oh)
4580 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4581 enum ofputil_protocol cur, next;
4583 cur = ofconn_get_protocol(ofconn);
4584 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4585 ofconn_set_protocol(ofconn, next);
4591 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4593 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4594 enum ofputil_protocol cur, next;
4595 enum ofputil_protocol next_base;
4597 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4599 return OFPERR_OFPBRC_EPERM;
4602 cur = ofconn_get_protocol(ofconn);
4603 next = ofputil_protocol_set_base(cur, next_base);
4604 ofconn_set_protocol(ofconn, next);
4610 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4611 const struct ofp_header *oh)
4613 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4616 format = ntohl(msg->format);
4617 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4618 return OFPERR_OFPBRC_EPERM;
4621 ofconn_set_packet_in_format(ofconn, format);
4626 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4628 const struct nx_async_config *msg = ofpmsg_body(oh);
4629 uint32_t master[OAM_N_TYPES];
4630 uint32_t slave[OAM_N_TYPES];
4632 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4633 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4634 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4636 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4637 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4638 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4640 ofconn_set_async_config(ofconn, master, slave);
4641 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4642 !ofconn_get_miss_send_len(ofconn)) {
4643 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4650 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
4653 uint32_t master[OAM_N_TYPES];
4654 uint32_t slave[OAM_N_TYPES];
4655 struct nx_async_config *msg;
4657 ofconn_get_async_config(ofconn, master, slave);
4658 buf = ofpraw_alloc_reply(OFPRAW_OFPT13_GET_ASYNC_REPLY, oh, 0);
4659 msg = ofpbuf_put_zeros(buf, sizeof *msg);
4661 msg->packet_in_mask[0] = htonl(master[OAM_PACKET_IN]);
4662 msg->port_status_mask[0] = htonl(master[OAM_PORT_STATUS]);
4663 msg->flow_removed_mask[0] = htonl(master[OAM_FLOW_REMOVED]);
4665 msg->packet_in_mask[1] = htonl(slave[OAM_PACKET_IN]);
4666 msg->port_status_mask[1] = htonl(slave[OAM_PORT_STATUS]);
4667 msg->flow_removed_mask[1] = htonl(slave[OAM_FLOW_REMOVED]);
4669 ofconn_send_reply(ofconn, buf);
4675 handle_nxt_set_controller_id(struct ofconn *ofconn,
4676 const struct ofp_header *oh)
4678 const struct nx_controller_id *nci = ofpmsg_body(oh);
4680 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4681 return OFPERR_NXBRC_MUST_BE_ZERO;
4684 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4689 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4693 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4694 ? OFPRAW_OFPT10_BARRIER_REPLY
4695 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4696 ofconn_send_reply(ofconn, buf);
4701 ofproto_compose_flow_refresh_update(const struct rule *rule,
4702 enum nx_flow_monitor_flags flags,
4704 OVS_REQUIRES(ofproto_mutex)
4706 const struct rule_actions *actions;
4707 struct ofputil_flow_update fu;
4710 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4711 ? NXFME_ADDED : NXFME_MODIFIED);
4713 ovs_mutex_lock(&rule->mutex);
4714 fu.idle_timeout = rule->idle_timeout;
4715 fu.hard_timeout = rule->hard_timeout;
4716 ovs_mutex_unlock(&rule->mutex);
4717 fu.table_id = rule->table_id;
4718 fu.cookie = rule->flow_cookie;
4719 minimatch_expand(&rule->cr.match, &match);
4721 fu.priority = rule->cr.priority;
4723 actions = flags & NXFMF_ACTIONS ? rule_get_actions(rule) : NULL;
4724 fu.ofpacts = actions ? actions->ofpacts : NULL;
4725 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4727 if (list_is_empty(msgs)) {
4728 ofputil_start_flow_update(msgs);
4730 ofputil_append_flow_update(&fu, msgs);
4734 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4736 OVS_REQUIRES(ofproto_mutex)
4740 for (i = 0; i < rules->n; i++) {
4741 struct rule *rule = rules->rules[i];
4742 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4743 rule->monitor_flags = 0;
4745 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4750 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4751 struct rule *rule, uint64_t seqno,
4752 struct rule_collection *rules)
4753 OVS_REQUIRES(ofproto_mutex)
4755 enum nx_flow_monitor_flags update;
4757 if (rule_is_hidden(rule)) {
4761 if (!ofproto_rule_has_out_port(rule, m->out_port)) {
4766 if (rule->add_seqno > seqno) {
4767 update = NXFMF_ADD | NXFMF_MODIFY;
4768 } else if (rule->modify_seqno > seqno) {
4769 update = NXFMF_MODIFY;
4774 if (!(m->flags & update)) {
4778 update = NXFMF_INITIAL;
4781 if (!rule->monitor_flags) {
4782 rule_collection_add(rules, rule);
4784 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4788 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4790 struct rule_collection *rules)
4791 OVS_REQUIRES(ofproto_mutex)
4793 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4794 const struct oftable *table;
4795 struct cls_rule target;
4797 cls_rule_init_from_minimatch(&target, &m->match, 0);
4798 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4799 struct cls_cursor cursor;
4802 fat_rwlock_rdlock(&table->cls.rwlock);
4803 cls_cursor_init(&cursor, &table->cls, &target);
4804 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4805 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4807 fat_rwlock_unlock(&table->cls.rwlock);
4809 cls_rule_destroy(&target);
4813 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4814 struct rule_collection *rules)
4815 OVS_REQUIRES(ofproto_mutex)
4817 if (m->flags & NXFMF_INITIAL) {
4818 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4823 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4824 uint64_t seqno, struct rule_collection *rules)
4825 OVS_REQUIRES(ofproto_mutex)
4827 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4831 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4832 OVS_EXCLUDED(ofproto_mutex)
4834 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4835 struct ofmonitor **monitors;
4836 size_t n_monitors, allocated_monitors;
4837 struct rule_collection rules;
4838 struct list replies;
4844 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4846 n_monitors = allocated_monitors = 0;
4848 ovs_mutex_lock(&ofproto_mutex);
4850 struct ofputil_flow_monitor_request request;
4851 struct ofmonitor *m;
4854 retval = ofputil_decode_flow_monitor_request(&request, &b);
4855 if (retval == EOF) {
4857 } else if (retval) {
4862 if (request.table_id != 0xff
4863 && request.table_id >= ofproto->n_tables) {
4864 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4868 error = ofmonitor_create(&request, ofconn, &m);
4873 if (n_monitors >= allocated_monitors) {
4874 monitors = x2nrealloc(monitors, &allocated_monitors,
4877 monitors[n_monitors++] = m;
4880 rule_collection_init(&rules);
4881 for (i = 0; i < n_monitors; i++) {
4882 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4885 ofpmp_init(&replies, oh);
4886 ofmonitor_compose_refresh_updates(&rules, &replies);
4887 ovs_mutex_unlock(&ofproto_mutex);
4889 rule_collection_destroy(&rules);
4891 ofconn_send_replies(ofconn, &replies);
4897 for (i = 0; i < n_monitors; i++) {
4898 ofmonitor_destroy(monitors[i]);
4901 ovs_mutex_unlock(&ofproto_mutex);
4907 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4908 OVS_EXCLUDED(ofproto_mutex)
4910 struct ofmonitor *m;
4914 id = ofputil_decode_flow_monitor_cancel(oh);
4916 ovs_mutex_lock(&ofproto_mutex);
4917 m = ofmonitor_lookup(ofconn, id);
4919 ofmonitor_destroy(m);
4922 error = OFPERR_OFPMOFC_UNKNOWN_MONITOR;
4924 ovs_mutex_unlock(&ofproto_mutex);
4929 /* Meters implementation.
4931 * Meter table entry, indexed by the OpenFlow meter_id.
4932 * 'created' is used to compute the duration for meter stats.
4933 * 'list rules' is needed so that we can delete the dependent rules when the
4934 * meter table entry is deleted.
4935 * 'provider_meter_id' is for the provider's private use.
4938 long long int created; /* Time created. */
4939 struct list rules; /* List of "struct rule_dpif"s. */
4940 ofproto_meter_id provider_meter_id;
4941 uint16_t flags; /* Meter flags. */
4942 uint16_t n_bands; /* Number of meter bands. */
4943 struct ofputil_meter_band *bands;
4947 * This is used in instruction validation at flow set-up time,
4948 * as flows may not use non-existing meters.
4949 * Return value of UINT32_MAX signifies an invalid meter.
4952 get_provider_meter_id(const struct ofproto *ofproto, uint32_t of_meter_id)
4954 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4955 const struct meter *meter = ofproto->meters[of_meter_id];
4957 return meter->provider_meter_id.uint32;
4963 /* Finds the meter invoked by 'rule''s actions and adds 'rule' to the meter's
4966 meter_insert_rule(struct rule *rule)
4968 const struct rule_actions *a = rule_get_actions(rule);
4969 uint32_t meter_id = ofpacts_get_meter(a->ofpacts, a->ofpacts_len);
4970 struct meter *meter = rule->ofproto->meters[meter_id];
4972 list_insert(&meter->rules, &rule->meter_list_node);
4976 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4980 meter->flags = config->flags;
4981 meter->n_bands = config->n_bands;
4982 meter->bands = xmemdup(config->bands,
4983 config->n_bands * sizeof *meter->bands);
4986 static struct meter *
4987 meter_create(const struct ofputil_meter_config *config,
4988 ofproto_meter_id provider_meter_id)
4990 struct meter *meter;
4992 meter = xzalloc(sizeof *meter);
4993 meter->provider_meter_id = provider_meter_id;
4994 meter->created = time_msec();
4995 list_init(&meter->rules);
4997 meter_update(meter, config);
5003 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
5004 OVS_REQUIRES(ofproto_mutex)
5007 for (mid = first; mid <= last; ++mid) {
5008 struct meter *meter = ofproto->meters[mid];
5010 ofproto->meters[mid] = NULL;
5011 ofproto->ofproto_class->meter_del(ofproto,
5012 meter->provider_meter_id);
5020 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5022 ofproto_meter_id provider_meter_id = { UINT32_MAX };
5023 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
5027 return OFPERR_OFPMMFC_METER_EXISTS;
5030 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
5033 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
5034 *meterp = meter_create(&mm->meter, provider_meter_id);
5040 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5042 struct meter *meter = ofproto->meters[mm->meter.meter_id];
5044 uint32_t provider_meter_id;
5047 return OFPERR_OFPMMFC_UNKNOWN_METER;
5050 provider_meter_id = meter->provider_meter_id.uint32;
5051 error = ofproto->ofproto_class->meter_set(ofproto,
5052 &meter->provider_meter_id,
5054 ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
5056 meter_update(meter, &mm->meter);
5062 handle_delete_meter(struct ofconn *ofconn, struct ofputil_meter_mod *mm)
5063 OVS_EXCLUDED(ofproto_mutex)
5065 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5066 uint32_t meter_id = mm->meter.meter_id;
5067 struct rule_collection rules;
5068 enum ofperr error = 0;
5069 uint32_t first, last;
5071 if (meter_id == OFPM13_ALL) {
5073 last = ofproto->meter_features.max_meters;
5075 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
5078 first = last = meter_id;
5081 /* First delete the rules that use this meter. If any of those rules are
5082 * currently being modified, postpone the whole operation until later. */
5083 rule_collection_init(&rules);
5084 ovs_mutex_lock(&ofproto_mutex);
5085 for (meter_id = first; meter_id <= last; ++meter_id) {
5086 struct meter *meter = ofproto->meters[meter_id];
5087 if (meter && !list_is_empty(&meter->rules)) {
5090 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
5091 rule_collection_add(&rules, rule);
5096 delete_flows__(&rules, OFPRR_METER_DELETE, NULL);
5099 /* Delete the meters. */
5100 meter_delete(ofproto, first, last);
5102 ovs_mutex_unlock(&ofproto_mutex);
5103 rule_collection_destroy(&rules);
5109 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5111 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5112 struct ofputil_meter_mod mm;
5113 uint64_t bands_stub[256 / 8];
5114 struct ofpbuf bands;
5118 error = reject_slave_controller(ofconn);
5123 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5125 error = ofputil_decode_meter_mod(oh, &mm, &bands);
5127 goto exit_free_bands;
5130 meter_id = mm.meter.meter_id;
5132 if (mm.command != OFPMC13_DELETE) {
5133 /* Fails also when meters are not implemented by the provider. */
5134 if (meter_id == 0 || meter_id > OFPM13_MAX) {
5135 error = OFPERR_OFPMMFC_INVALID_METER;
5136 goto exit_free_bands;
5137 } else if (meter_id > ofproto->meter_features.max_meters) {
5138 error = OFPERR_OFPMMFC_OUT_OF_METERS;
5139 goto exit_free_bands;
5141 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
5142 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
5143 goto exit_free_bands;
5147 switch (mm.command) {
5149 error = handle_add_meter(ofproto, &mm);
5152 case OFPMC13_MODIFY:
5153 error = handle_modify_meter(ofproto, &mm);
5156 case OFPMC13_DELETE:
5157 error = handle_delete_meter(ofconn, &mm);
5161 error = OFPERR_OFPMMFC_BAD_COMMAND;
5166 ofpbuf_uninit(&bands);
5171 handle_meter_features_request(struct ofconn *ofconn,
5172 const struct ofp_header *request)
5174 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5175 struct ofputil_meter_features features;
5178 if (ofproto->ofproto_class->meter_get_features) {
5179 ofproto->ofproto_class->meter_get_features(ofproto, &features);
5181 memset(&features, 0, sizeof features);
5183 b = ofputil_encode_meter_features_reply(&features, request);
5185 ofconn_send_reply(ofconn, b);
5190 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
5193 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5194 struct list replies;
5195 uint64_t bands_stub[256 / 8];
5196 struct ofpbuf bands;
5197 uint32_t meter_id, first, last;
5199 ofputil_decode_meter_request(request, &meter_id);
5201 if (meter_id == OFPM13_ALL) {
5203 last = ofproto->meter_features.max_meters;
5205 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
5206 !ofproto->meters[meter_id]) {
5207 return OFPERR_OFPMMFC_UNKNOWN_METER;
5209 first = last = meter_id;
5212 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5213 ofpmp_init(&replies, request);
5215 for (meter_id = first; meter_id <= last; ++meter_id) {
5216 struct meter *meter = ofproto->meters[meter_id];
5218 continue; /* Skip non-existing meters. */
5220 if (type == OFPTYPE_METER_STATS_REQUEST) {
5221 struct ofputil_meter_stats stats;
5223 stats.meter_id = meter_id;
5225 /* Provider sets the packet and byte counts, we do the rest. */
5226 stats.flow_count = list_size(&meter->rules);
5227 calc_duration(meter->created, time_msec(),
5228 &stats.duration_sec, &stats.duration_nsec);
5229 stats.n_bands = meter->n_bands;
5230 ofpbuf_clear(&bands);
5232 = ofpbuf_put_uninit(&bands,
5233 meter->n_bands * sizeof *stats.bands);
5235 if (!ofproto->ofproto_class->meter_get(ofproto,
5236 meter->provider_meter_id,
5238 ofputil_append_meter_stats(&replies, &stats);
5240 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
5241 struct ofputil_meter_config config;
5243 config.meter_id = meter_id;
5244 config.flags = meter->flags;
5245 config.n_bands = meter->n_bands;
5246 config.bands = meter->bands;
5247 ofputil_append_meter_config(&replies, &config);
5251 ofconn_send_replies(ofconn, &replies);
5252 ofpbuf_uninit(&bands);
5257 ofproto_group_lookup__(const struct ofproto *ofproto, uint32_t group_id,
5258 struct ofgroup **group)
5259 OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5261 HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5262 hash_int(group_id, 0), &ofproto->groups) {
5263 if ((*group)->group_id == group_id) {
5271 /* If the group exists, this function increments the groups's reference count.
5273 * Make sure to call ofproto_group_unref() after no longer needing to maintain
5274 * a reference to the group. */
5276 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
5277 struct ofgroup **group)
5281 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5282 found = ofproto_group_lookup__(ofproto, group_id, group);
5284 ofproto_group_ref(*group);
5286 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5291 ofproto_group_exists__(const struct ofproto *ofproto, uint32_t group_id)
5292 OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5294 struct ofgroup *grp;
5296 HMAP_FOR_EACH_IN_BUCKET (grp, hmap_node,
5297 hash_int(group_id, 0), &ofproto->groups) {
5298 if (grp->group_id == group_id) {
5306 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
5307 OVS_EXCLUDED(ofproto->groups_rwlock)
5311 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5312 exists = ofproto_group_exists__(ofproto, group_id);
5313 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5319 group_get_ref_count(struct ofgroup *group)
5320 OVS_EXCLUDED(ofproto_mutex)
5322 struct ofproto *ofproto = CONST_CAST(struct ofproto *, group->ofproto);
5323 struct rule_criteria criteria;
5324 struct rule_collection rules;
5329 match_init_catchall(&match);
5330 rule_criteria_init(&criteria, 0xff, &match, 0, htonll(0), htonll(0),
5331 OFPP_ANY, group->group_id);
5332 ovs_mutex_lock(&ofproto_mutex);
5333 error = collect_rules_loose(ofproto, &criteria, &rules);
5334 ovs_mutex_unlock(&ofproto_mutex);
5335 rule_criteria_destroy(&criteria);
5337 count = !error && rules.n < UINT32_MAX ? rules.n : UINT32_MAX;
5339 rule_collection_destroy(&rules);
5344 append_group_stats(struct ofgroup *group, struct list *replies)
5346 struct ofputil_group_stats ogs;
5347 const struct ofproto *ofproto = group->ofproto;
5348 long long int now = time_msec();
5351 ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
5353 /* Provider sets the packet and byte counts, we do the rest. */
5354 ogs.ref_count = group_get_ref_count(group);
5355 ogs.n_buckets = group->n_buckets;
5357 error = (ofproto->ofproto_class->group_get_stats
5358 ? ofproto->ofproto_class->group_get_stats(group, &ogs)
5361 ogs.packet_count = UINT64_MAX;
5362 ogs.byte_count = UINT64_MAX;
5363 memset(ogs.bucket_stats, 0xff,
5364 ogs.n_buckets * sizeof *ogs.bucket_stats);
5367 ogs.group_id = group->group_id;
5368 calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
5370 ofputil_append_group_stats(replies, &ogs);
5372 free(ogs.bucket_stats);
5376 handle_group_request(struct ofconn *ofconn,
5377 const struct ofp_header *request, uint32_t group_id,
5378 void (*cb)(struct ofgroup *, struct list *replies))
5380 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5381 struct ofgroup *group;
5382 struct list replies;
5384 ofpmp_init(&replies, request);
5385 if (group_id == OFPG_ALL) {
5386 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5387 HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5388 cb(group, &replies);
5390 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5392 if (ofproto_group_lookup(ofproto, group_id, &group)) {
5393 cb(group, &replies);
5394 ofproto_group_unref(group);
5397 ofconn_send_replies(ofconn, &replies);
5401 handle_group_stats_request(struct ofconn *ofconn,
5402 const struct ofp_header *request)
5407 error = ofputil_decode_group_stats_request(request, &group_id);
5412 handle_group_request(ofconn, request, group_id, append_group_stats);
5417 append_group_desc(struct ofgroup *group, struct list *replies)
5419 struct ofputil_group_desc gds;
5421 gds.group_id = group->group_id;
5422 gds.type = group->type;
5423 ofputil_append_group_desc_reply(&gds, &group->buckets, replies);
5427 handle_group_desc_stats_request(struct ofconn *ofconn,
5428 const struct ofp_header *request)
5430 handle_group_request(ofconn, request,
5431 ofputil_decode_group_desc_request(request),
5437 handle_group_features_stats_request(struct ofconn *ofconn,
5438 const struct ofp_header *request)
5440 struct ofproto *p = ofconn_get_ofproto(ofconn);
5443 msg = ofputil_encode_group_features_reply(&p->ogf, request);
5445 ofconn_send_reply(ofconn, msg);
5452 handle_queue_get_config_request(struct ofconn *ofconn,
5453 const struct ofp_header *oh)
5455 struct ofproto *p = ofconn_get_ofproto(ofconn);
5456 struct netdev_queue_dump queue_dump;
5457 struct ofport *ofport;
5458 unsigned int queue_id;
5459 struct ofpbuf *reply;
5460 struct smap details;
5464 error = ofputil_decode_queue_get_config_request(oh, &request);
5469 ofport = ofproto_get_port(p, request);
5471 return OFPERR_OFPQOFC_BAD_PORT;
5474 reply = ofputil_encode_queue_get_config_reply(oh);
5476 smap_init(&details);
5477 NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &queue_dump, ofport->netdev) {
5478 struct ofputil_queue_config queue;
5480 /* None of the existing queues have compatible properties, so we
5481 * hard-code omitting min_rate and max_rate. */
5482 queue.queue_id = queue_id;
5483 queue.min_rate = UINT16_MAX;
5484 queue.max_rate = UINT16_MAX;
5485 ofputil_append_queue_get_config_reply(reply, &queue);
5487 smap_destroy(&details);
5489 ofconn_send_reply(ofconn, reply);
5495 init_group(struct ofproto *ofproto, struct ofputil_group_mod *gm,
5496 struct ofgroup **ofgroup)
5499 const long long int now = time_msec();
5501 if (gm->group_id > OFPG_MAX) {
5502 return OFPERR_OFPGMFC_INVALID_GROUP;
5504 if (gm->type > OFPGT11_FF) {
5505 return OFPERR_OFPGMFC_BAD_TYPE;
5508 *ofgroup = ofproto->ofproto_class->group_alloc();
5510 VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
5511 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5514 (*ofgroup)->ofproto = ofproto;
5515 *CONST_CAST(uint32_t *, &((*ofgroup)->group_id)) = gm->group_id;
5516 *CONST_CAST(enum ofp11_group_type *, &(*ofgroup)->type) = gm->type;
5517 *CONST_CAST(long long int *, &((*ofgroup)->created)) = now;
5518 *CONST_CAST(long long int *, &((*ofgroup)->modified)) = now;
5519 ovs_refcount_init(&(*ofgroup)->ref_count);
5521 list_move(&(*ofgroup)->buckets, &gm->buckets);
5522 *CONST_CAST(uint32_t *, &(*ofgroup)->n_buckets) =
5523 list_size(&(*ofgroup)->buckets);
5525 /* Construct called BEFORE any locks are held. */
5526 error = ofproto->ofproto_class->group_construct(*ofgroup);
5528 ofputil_bucket_list_destroy(&(*ofgroup)->buckets);
5529 ofproto->ofproto_class->group_dealloc(*ofgroup);
5534 /* Implements the OFPGC11_ADD operation specified by 'gm', adding a group to
5535 * 'ofproto''s group table. Returns 0 on success or an OpenFlow error code on
5538 add_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5540 struct ofgroup *ofgroup;
5543 /* Allocate new group and initialize it. */
5544 error = init_group(ofproto, gm, &ofgroup);
5549 /* We wrlock as late as possible to minimize the time we jam any other
5550 * threads: No visible state changes before acquiring the lock. */
5551 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5553 if (ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5554 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5558 if (ofproto_group_exists__(ofproto, gm->group_id)) {
5559 error = OFPERR_OFPGMFC_GROUP_EXISTS;
5564 /* Insert new group. */
5565 hmap_insert(&ofproto->groups, &ofgroup->hmap_node,
5566 hash_int(ofgroup->group_id, 0));
5567 ofproto->n_groups[ofgroup->type]++;
5569 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5574 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5575 ofproto->ofproto_class->group_destruct(ofgroup);
5576 ofputil_bucket_list_destroy(&ofgroup->buckets);
5577 ofproto->ofproto_class->group_dealloc(ofgroup);
5582 /* Implements OFPGC11_MODIFY. Returns 0 on success or an OpenFlow error code
5585 * Note that the group is re-created and then replaces the old group in
5586 * ofproto's ofgroup hash map. Thus, the group is never altered while users of
5587 * the xlate module hold a pointer to the group. */
5589 modify_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5591 struct ofgroup *ofgroup, *new_ofgroup, *retiring;
5594 error = init_group(ofproto, gm, &new_ofgroup);
5599 retiring = new_ofgroup;
5601 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5602 if (!ofproto_group_lookup__(ofproto, gm->group_id, &ofgroup)) {
5603 error = OFPERR_OFPGMFC_UNKNOWN_GROUP;
5607 /* Ofproto's group write lock is held now. */
5608 if (ofgroup->type != gm->type
5609 && ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5610 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5614 /* The group creation time does not change during modification. */
5615 *CONST_CAST(long long int *, &(new_ofgroup->created)) = ofgroup->created;
5616 *CONST_CAST(long long int *, &(new_ofgroup->modified)) = time_msec();
5618 error = ofproto->ofproto_class->group_modify(new_ofgroup);
5624 /* Replace ofgroup in ofproto's groups hash map with new_ofgroup. */
5625 hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5626 hmap_insert(&ofproto->groups, &new_ofgroup->hmap_node,
5627 hash_int(new_ofgroup->group_id, 0));
5628 if (ofgroup->type != new_ofgroup->type) {
5629 ofproto->n_groups[ofgroup->type]--;
5630 ofproto->n_groups[new_ofgroup->type]++;
5634 ofproto_group_unref(retiring);
5635 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5640 delete_group__(struct ofproto *ofproto, struct ofgroup *ofgroup)
5641 OVS_RELEASES(ofproto->groups_rwlock)
5644 struct ofputil_flow_mod fm;
5646 /* Delete all flow entries containing this group in a group action */
5647 match_init_catchall(&match);
5648 flow_mod_init(&fm, &match, 0, NULL, 0, OFPFC_DELETE);
5649 fm.delete_reason = OFPRR_GROUP_DELETE;
5650 fm.out_group = ofgroup->group_id;
5651 handle_flow_mod__(ofproto, &fm, NULL);
5653 hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5654 /* No-one can find this group any more. */
5655 ofproto->n_groups[ofgroup->type]--;
5656 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5657 ofproto_group_unref(ofgroup);
5660 /* Implements OFPGC11_DELETE. */
5662 delete_group(struct ofproto *ofproto, uint32_t group_id)
5664 struct ofgroup *ofgroup;
5666 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5667 if (group_id == OFPG_ALL) {
5669 struct hmap_node *node = hmap_first(&ofproto->groups);
5673 ofgroup = CONTAINER_OF(node, struct ofgroup, hmap_node);
5674 delete_group__(ofproto, ofgroup);
5675 /* Lock for each node separately, so that we will not jam the
5676 * other threads for too long time. */
5677 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5680 HMAP_FOR_EACH_IN_BUCKET (ofgroup, hmap_node,
5681 hash_int(group_id, 0), &ofproto->groups) {
5682 if (ofgroup->group_id == group_id) {
5683 delete_group__(ofproto, ofgroup);
5688 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5692 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5694 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5695 struct ofputil_group_mod gm;
5698 error = reject_slave_controller(ofconn);
5703 error = ofputil_decode_group_mod(oh, &gm);
5708 switch (gm.command) {
5710 return add_group(ofproto, &gm);
5712 case OFPGC11_MODIFY:
5713 return modify_group(ofproto, &gm);
5715 case OFPGC11_DELETE:
5716 delete_group(ofproto, gm.group_id);
5720 if (gm.command > OFPGC11_DELETE) {
5721 VLOG_WARN_RL(&rl, "%s: Invalid group_mod command type %d",
5722 ofproto->name, gm.command);
5724 return OFPERR_OFPGMFC_BAD_COMMAND;
5728 enum ofproto_table_config
5729 ofproto_table_get_config(const struct ofproto *ofproto, uint8_t table_id)
5732 atomic_read(&ofproto->tables[table_id].config, &value);
5733 return (enum ofproto_table_config)value;
5737 table_mod(struct ofproto *ofproto, const struct ofputil_table_mod *tm)
5739 /* Only accept currently supported configurations */
5740 if (tm->config & ~OFPTC11_TABLE_MISS_MASK) {
5741 return OFPERR_OFPTMFC_BAD_CONFIG;
5744 if (tm->table_id == OFPTT_ALL) {
5746 for (i = 0; i < ofproto->n_tables; i++) {
5747 atomic_store(&ofproto->tables[i].config,
5748 (unsigned int)tm->config);
5750 } else if (!check_table_id(ofproto, tm->table_id)) {
5751 return OFPERR_OFPTMFC_BAD_TABLE;
5753 atomic_store(&ofproto->tables[tm->table_id].config,
5754 (unsigned int)tm->config);
5761 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5763 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5764 struct ofputil_table_mod tm;
5767 error = reject_slave_controller(ofconn);
5772 error = ofputil_decode_table_mod(oh, &tm);
5777 return table_mod(ofproto, &tm);
5781 handle_bundle_control(struct ofconn *ofconn, const struct ofp_header *oh)
5784 struct ofputil_bundle_ctrl_msg bctrl;
5786 struct ofputil_bundle_ctrl_msg reply;
5788 error = ofputil_decode_bundle_ctrl(oh, &bctrl);
5793 reply.bundle_id = bctrl.bundle_id;
5795 switch (bctrl.type) {
5796 case OFPBCT_OPEN_REQUEST:
5797 error = ofp_bundle_open(ofconn, bctrl.bundle_id, bctrl.flags);
5798 reply.type = OFPBCT_OPEN_REPLY;
5800 case OFPBCT_CLOSE_REQUEST:
5801 error = ofp_bundle_close(ofconn, bctrl.bundle_id, bctrl.flags);
5802 reply.type = OFPBCT_CLOSE_REPLY;;
5804 case OFPBCT_COMMIT_REQUEST:
5805 error = ofp_bundle_commit(ofconn, bctrl.bundle_id, bctrl.flags);
5806 reply.type = OFPBCT_COMMIT_REPLY;
5808 case OFPBCT_DISCARD_REQUEST:
5809 error = ofp_bundle_discard(ofconn, bctrl.bundle_id);
5810 reply.type = OFPBCT_DISCARD_REPLY;
5813 case OFPBCT_OPEN_REPLY:
5814 case OFPBCT_CLOSE_REPLY:
5815 case OFPBCT_COMMIT_REPLY:
5816 case OFPBCT_DISCARD_REPLY:
5817 return OFPERR_OFPBFC_BAD_TYPE;
5822 buf = ofputil_encode_bundle_ctrl_reply(oh, &reply);
5823 ofconn_send_reply(ofconn, buf);
5830 handle_bundle_add(struct ofconn *ofconn, const struct ofp_header *oh)
5833 struct ofputil_bundle_add_msg badd;
5835 error = ofputil_decode_bundle_add(oh, &badd);
5840 return ofp_bundle_add_message(ofconn, &badd);
5844 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
5845 OVS_EXCLUDED(ofproto_mutex)
5847 const struct ofp_header *oh = ofpbuf_data(msg);
5851 error = ofptype_decode(&type, oh);
5855 if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
5856 && ofpmp_more(oh)) {
5857 /* We have no buffer implementation for multipart requests.
5858 * Report overflow for requests which consists of multiple
5860 return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
5864 /* OpenFlow requests. */
5865 case OFPTYPE_ECHO_REQUEST:
5866 return handle_echo_request(ofconn, oh);
5868 case OFPTYPE_FEATURES_REQUEST:
5869 return handle_features_request(ofconn, oh);
5871 case OFPTYPE_GET_CONFIG_REQUEST:
5872 return handle_get_config_request(ofconn, oh);
5874 case OFPTYPE_SET_CONFIG:
5875 return handle_set_config(ofconn, oh);
5877 case OFPTYPE_PACKET_OUT:
5878 return handle_packet_out(ofconn, oh);
5880 case OFPTYPE_PORT_MOD:
5881 return handle_port_mod(ofconn, oh);
5883 case OFPTYPE_FLOW_MOD:
5884 return handle_flow_mod(ofconn, oh);
5886 case OFPTYPE_GROUP_MOD:
5887 return handle_group_mod(ofconn, oh);
5889 case OFPTYPE_TABLE_MOD:
5890 return handle_table_mod(ofconn, oh);
5892 case OFPTYPE_METER_MOD:
5893 return handle_meter_mod(ofconn, oh);
5895 case OFPTYPE_BARRIER_REQUEST:
5896 return handle_barrier_request(ofconn, oh);
5898 case OFPTYPE_ROLE_REQUEST:
5899 return handle_role_request(ofconn, oh);
5901 /* OpenFlow replies. */
5902 case OFPTYPE_ECHO_REPLY:
5905 /* Nicira extension requests. */
5906 case OFPTYPE_FLOW_MOD_TABLE_ID:
5907 return handle_nxt_flow_mod_table_id(ofconn, oh);
5909 case OFPTYPE_SET_FLOW_FORMAT:
5910 return handle_nxt_set_flow_format(ofconn, oh);
5912 case OFPTYPE_SET_PACKET_IN_FORMAT:
5913 return handle_nxt_set_packet_in_format(ofconn, oh);
5915 case OFPTYPE_SET_CONTROLLER_ID:
5916 return handle_nxt_set_controller_id(ofconn, oh);
5918 case OFPTYPE_FLOW_AGE:
5919 /* Nothing to do. */
5922 case OFPTYPE_FLOW_MONITOR_CANCEL:
5923 return handle_flow_monitor_cancel(ofconn, oh);
5925 case OFPTYPE_SET_ASYNC_CONFIG:
5926 return handle_nxt_set_async_config(ofconn, oh);
5928 case OFPTYPE_GET_ASYNC_REQUEST:
5929 return handle_nxt_get_async_request(ofconn, oh);
5931 /* Statistics requests. */
5932 case OFPTYPE_DESC_STATS_REQUEST:
5933 return handle_desc_stats_request(ofconn, oh);
5935 case OFPTYPE_FLOW_STATS_REQUEST:
5936 return handle_flow_stats_request(ofconn, oh);
5938 case OFPTYPE_AGGREGATE_STATS_REQUEST:
5939 return handle_aggregate_stats_request(ofconn, oh);
5941 case OFPTYPE_TABLE_STATS_REQUEST:
5942 return handle_table_stats_request(ofconn, oh);
5944 case OFPTYPE_PORT_STATS_REQUEST:
5945 return handle_port_stats_request(ofconn, oh);
5947 case OFPTYPE_QUEUE_STATS_REQUEST:
5948 return handle_queue_stats_request(ofconn, oh);
5950 case OFPTYPE_PORT_DESC_STATS_REQUEST:
5951 return handle_port_desc_stats_request(ofconn, oh);
5953 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
5954 return handle_flow_monitor_request(ofconn, oh);
5956 case OFPTYPE_METER_STATS_REQUEST:
5957 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
5958 return handle_meter_request(ofconn, oh, type);
5960 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
5961 return handle_meter_features_request(ofconn, oh);
5963 case OFPTYPE_GROUP_STATS_REQUEST:
5964 return handle_group_stats_request(ofconn, oh);
5966 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
5967 return handle_group_desc_stats_request(ofconn, oh);
5969 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
5970 return handle_group_features_stats_request(ofconn, oh);
5972 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
5973 return handle_queue_get_config_request(ofconn, oh);
5975 case OFPTYPE_BUNDLE_CONTROL:
5976 return handle_bundle_control(ofconn, oh);
5978 case OFPTYPE_BUNDLE_ADD_MESSAGE:
5979 return handle_bundle_add(ofconn, oh);
5983 case OFPTYPE_FEATURES_REPLY:
5984 case OFPTYPE_GET_CONFIG_REPLY:
5985 case OFPTYPE_PACKET_IN:
5986 case OFPTYPE_FLOW_REMOVED:
5987 case OFPTYPE_PORT_STATUS:
5988 case OFPTYPE_BARRIER_REPLY:
5989 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
5990 case OFPTYPE_DESC_STATS_REPLY:
5991 case OFPTYPE_FLOW_STATS_REPLY:
5992 case OFPTYPE_QUEUE_STATS_REPLY:
5993 case OFPTYPE_PORT_STATS_REPLY:
5994 case OFPTYPE_TABLE_STATS_REPLY:
5995 case OFPTYPE_AGGREGATE_STATS_REPLY:
5996 case OFPTYPE_PORT_DESC_STATS_REPLY:
5997 case OFPTYPE_ROLE_REPLY:
5998 case OFPTYPE_FLOW_MONITOR_PAUSED:
5999 case OFPTYPE_FLOW_MONITOR_RESUMED:
6000 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
6001 case OFPTYPE_GET_ASYNC_REPLY:
6002 case OFPTYPE_GROUP_STATS_REPLY:
6003 case OFPTYPE_GROUP_DESC_STATS_REPLY:
6004 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
6005 case OFPTYPE_METER_STATS_REPLY:
6006 case OFPTYPE_METER_CONFIG_STATS_REPLY:
6007 case OFPTYPE_METER_FEATURES_STATS_REPLY:
6008 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
6009 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
6010 case OFPTYPE_ROLE_STATUS:
6012 if (ofpmsg_is_stat_request(oh)) {
6013 return OFPERR_OFPBRC_BAD_STAT;
6015 return OFPERR_OFPBRC_BAD_TYPE;
6021 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
6022 OVS_EXCLUDED(ofproto_mutex)
6024 int error = handle_openflow__(ofconn, ofp_msg);
6026 ofconn_send_error(ofconn, ofpbuf_data(ofp_msg), error);
6028 COVERAGE_INC(ofproto_recv_openflow);
6031 /* Asynchronous operations. */
6034 send_buffered_packet(struct ofconn *ofconn, uint32_t buffer_id,
6036 OVS_REQUIRES(ofproto_mutex)
6038 enum ofperr error = 0;
6039 if (ofconn && buffer_id != UINT32_MAX) {
6040 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6041 struct ofpbuf *packet;
6044 error = ofconn_pktbuf_retrieve(ofconn, buffer_id, &packet, &in_port);
6046 struct rule_execute *re;
6048 ofproto_rule_ref(rule);
6050 re = xmalloc(sizeof *re);
6052 re->in_port = in_port;
6053 re->packet = packet;
6055 if (!guarded_list_push_back(&ofproto->rule_executes,
6056 &re->list_node, 1024)) {
6057 ofproto_rule_unref(rule);
6058 ofpbuf_delete(re->packet);
6067 pick_datapath_id(const struct ofproto *ofproto)
6069 const struct ofport *port;
6071 port = ofproto_get_port(ofproto, OFPP_LOCAL);
6073 uint8_t ea[ETH_ADDR_LEN];
6076 error = netdev_get_etheraddr(port->netdev, ea);
6078 return eth_addr_to_uint64(ea);
6080 VLOG_WARN("%s: could not get MAC address for %s (%s)",
6081 ofproto->name, netdev_get_name(port->netdev),
6082 ovs_strerror(error));
6084 return ofproto->fallback_dpid;
6088 pick_fallback_dpid(void)
6090 uint8_t ea[ETH_ADDR_LEN];
6091 eth_addr_nicira_random(ea);
6092 return eth_addr_to_uint64(ea);
6095 /* Table overflow policy. */
6097 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
6098 * to NULL if the table is not configured to evict rules or if the table
6099 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
6100 * or with no timeouts are not evictable.) */
6102 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
6103 OVS_REQUIRES(ofproto_mutex)
6105 struct eviction_group *evg;
6108 if (!table->eviction_fields) {
6112 /* In the common case, the outer and inner loops here will each be entered
6115 * - The inner loop normally "return"s in its first iteration. If the
6116 * eviction group has any evictable rules, then it always returns in
6119 * - The outer loop only iterates more than once if the largest eviction
6120 * group has no evictable rules.
6122 * - The outer loop can exit only if table's 'max_flows' is all filled up
6123 * by unevictable rules. */
6124 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
6127 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
6136 /* Eviction groups. */
6138 /* Returns the priority to use for an eviction_group that contains 'n_rules'
6139 * rules. The priority contains low-order random bits to ensure that eviction
6140 * groups with the same number of rules are prioritized randomly. */
6142 eviction_group_priority(size_t n_rules)
6144 uint16_t size = MIN(UINT16_MAX, n_rules);
6145 return (size << 16) | random_uint16();
6148 /* Updates 'evg', an eviction_group within 'table', following a change that
6149 * adds or removes rules in 'evg'. */
6151 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
6152 OVS_REQUIRES(ofproto_mutex)
6154 heap_change(&table->eviction_groups_by_size, &evg->size_node,
6155 eviction_group_priority(heap_count(&evg->rules)));
6158 /* Destroys 'evg', an eviction_group within 'table':
6160 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
6161 * rules themselves, just removes them from the eviction group.)
6163 * - Removes 'evg' from 'table'.
6167 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
6168 OVS_REQUIRES(ofproto_mutex)
6170 while (!heap_is_empty(&evg->rules)) {
6173 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
6174 rule->eviction_group = NULL;
6176 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
6177 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
6178 heap_destroy(&evg->rules);
6182 /* Removes 'rule' from its eviction group, if any. */
6184 eviction_group_remove_rule(struct rule *rule)
6185 OVS_REQUIRES(ofproto_mutex)
6187 if (rule->eviction_group) {
6188 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6189 struct eviction_group *evg = rule->eviction_group;
6191 rule->eviction_group = NULL;
6192 heap_remove(&evg->rules, &rule->evg_node);
6193 if (heap_is_empty(&evg->rules)) {
6194 eviction_group_destroy(table, evg);
6196 eviction_group_resized(table, evg);
6201 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
6202 * returns the hash value. */
6204 eviction_group_hash_rule(struct rule *rule)
6205 OVS_REQUIRES(ofproto_mutex)
6207 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6208 const struct mf_subfield *sf;
6212 hash = table->eviction_group_id_basis;
6213 miniflow_expand(&rule->cr.match.flow, &flow);
6214 for (sf = table->eviction_fields;
6215 sf < &table->eviction_fields[table->n_eviction_fields];
6218 if (mf_are_prereqs_ok(sf->field, &flow)) {
6219 union mf_value value;
6221 mf_get_value(sf->field, &flow, &value);
6223 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
6225 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
6226 unsigned int start = sf->ofs + sf->n_bits;
6227 bitwise_zero(&value, sf->field->n_bytes, start,
6228 sf->field->n_bytes * 8 - start);
6230 hash = hash_bytes(&value, sf->field->n_bytes, hash);
6232 hash = hash_int(hash, 0);
6239 /* Returns an eviction group within 'table' with the given 'id', creating one
6241 static struct eviction_group *
6242 eviction_group_find(struct oftable *table, uint32_t id)
6243 OVS_REQUIRES(ofproto_mutex)
6245 struct eviction_group *evg;
6247 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
6251 evg = xmalloc(sizeof *evg);
6252 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
6253 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
6254 eviction_group_priority(0));
6255 heap_init(&evg->rules);
6260 /* Returns an eviction priority for 'rule'. The return value should be
6261 * interpreted so that higher priorities make a rule more attractive candidates
6263 * Called only if have a timeout. */
6265 rule_eviction_priority(struct ofproto *ofproto, struct rule *rule)
6266 OVS_REQUIRES(ofproto_mutex)
6268 long long int expiration = LLONG_MAX;
6269 long long int modified;
6270 uint32_t expiration_offset;
6272 /* 'modified' needs protection even when we hold 'ofproto_mutex'. */
6273 ovs_mutex_lock(&rule->mutex);
6274 modified = rule->modified;
6275 ovs_mutex_unlock(&rule->mutex);
6277 if (rule->hard_timeout) {
6278 expiration = modified + rule->hard_timeout * 1000;
6280 if (rule->idle_timeout) {
6281 uint64_t packets, bytes;
6283 long long int idle_expiration;
6285 ofproto->ofproto_class->rule_get_stats(rule, &packets, &bytes, &used);
6286 idle_expiration = used + rule->idle_timeout * 1000;
6287 expiration = MIN(expiration, idle_expiration);
6290 if (expiration == LLONG_MAX) {
6294 /* Calculate the time of expiration as a number of (approximate) seconds
6295 * after program startup.
6297 * This should work OK for program runs that last UINT32_MAX seconds or
6298 * less. Therefore, please restart OVS at least once every 136 years. */
6299 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
6301 /* Invert the expiration offset because we're using a max-heap. */
6302 return UINT32_MAX - expiration_offset;
6305 /* Adds 'rule' to an appropriate eviction group for its oftable's
6306 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
6307 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
6310 * The caller must ensure that 'rule' is not already in an eviction group. */
6312 eviction_group_add_rule(struct rule *rule)
6313 OVS_REQUIRES(ofproto_mutex)
6315 struct ofproto *ofproto = rule->ofproto;
6316 struct oftable *table = &ofproto->tables[rule->table_id];
6319 /* Timeouts may be modified only when holding 'ofproto_mutex'. We have it
6320 * so no additional protection is needed. */
6321 has_timeout = rule->hard_timeout || rule->idle_timeout;
6323 if (table->eviction_fields && has_timeout) {
6324 struct eviction_group *evg;
6326 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
6328 rule->eviction_group = evg;
6329 heap_insert(&evg->rules, &rule->evg_node,
6330 rule_eviction_priority(ofproto, rule));
6331 eviction_group_resized(table, evg);
6337 /* Initializes 'table'. */
6339 oftable_init(struct oftable *table)
6341 memset(table, 0, sizeof *table);
6342 classifier_init(&table->cls, flow_segment_u32s);
6343 table->max_flows = UINT_MAX;
6344 atomic_init(&table->config, (unsigned int)OFPROTO_TABLE_MISS_DEFAULT);
6346 fat_rwlock_wrlock(&table->cls.rwlock);
6347 classifier_set_prefix_fields(&table->cls, default_prefix_fields,
6348 ARRAY_SIZE(default_prefix_fields));
6349 fat_rwlock_unlock(&table->cls.rwlock);
6351 atomic_init(&table->n_matched, 0);
6352 atomic_init(&table->n_missed, 0);
6355 /* Destroys 'table', including its classifier and eviction groups.
6357 * The caller is responsible for freeing 'table' itself. */
6359 oftable_destroy(struct oftable *table)
6361 fat_rwlock_rdlock(&table->cls.rwlock);
6362 ovs_assert(classifier_is_empty(&table->cls));
6363 fat_rwlock_unlock(&table->cls.rwlock);
6364 oftable_disable_eviction(table);
6365 classifier_destroy(&table->cls);
6369 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
6370 * string, then 'table' will use its default name.
6372 * This only affects the name exposed for a table exposed through the OpenFlow
6373 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
6375 oftable_set_name(struct oftable *table, const char *name)
6377 if (name && name[0]) {
6378 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
6379 if (!table->name || strncmp(name, table->name, len)) {
6381 table->name = xmemdup0(name, len);
6389 /* oftables support a choice of two policies when adding a rule would cause the
6390 * number of flows in the table to exceed the configured maximum number: either
6391 * they can refuse to add the new flow or they can evict some existing flow.
6392 * This function configures the former policy on 'table'. */
6394 oftable_disable_eviction(struct oftable *table)
6395 OVS_REQUIRES(ofproto_mutex)
6397 if (table->eviction_fields) {
6398 struct eviction_group *evg, *next;
6400 HMAP_FOR_EACH_SAFE (evg, next, id_node,
6401 &table->eviction_groups_by_id) {
6402 eviction_group_destroy(table, evg);
6404 hmap_destroy(&table->eviction_groups_by_id);
6405 heap_destroy(&table->eviction_groups_by_size);
6407 free(table->eviction_fields);
6408 table->eviction_fields = NULL;
6409 table->n_eviction_fields = 0;
6413 /* oftables support a choice of two policies when adding a rule would cause the
6414 * number of flows in the table to exceed the configured maximum number: either
6415 * they can refuse to add the new flow or they can evict some existing flow.
6416 * This function configures the latter policy on 'table', with fairness based
6417 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
6418 * 'n_fields' as 0 disables fairness.) */
6420 oftable_enable_eviction(struct oftable *table,
6421 const struct mf_subfield *fields, size_t n_fields)
6422 OVS_REQUIRES(ofproto_mutex)
6424 struct cls_cursor cursor;
6427 if (table->eviction_fields
6428 && n_fields == table->n_eviction_fields
6430 || !memcmp(fields, table->eviction_fields,
6431 n_fields * sizeof *fields))) {
6436 oftable_disable_eviction(table);
6438 table->n_eviction_fields = n_fields;
6439 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
6441 table->eviction_group_id_basis = random_uint32();
6442 hmap_init(&table->eviction_groups_by_id);
6443 heap_init(&table->eviction_groups_by_size);
6445 fat_rwlock_rdlock(&table->cls.rwlock);
6446 cls_cursor_init(&cursor, &table->cls, NULL);
6447 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6448 eviction_group_add_rule(rule);
6450 fat_rwlock_unlock(&table->cls.rwlock);
6453 /* Removes 'rule' from the oftable that contains it. */
6455 oftable_remove_rule__(struct ofproto *ofproto, struct rule *rule)
6456 OVS_REQUIRES(ofproto_mutex)
6458 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
6460 fat_rwlock_wrlock(&cls->rwlock);
6461 classifier_remove(cls, CONST_CAST(struct cls_rule *, &rule->cr));
6462 fat_rwlock_unlock(&cls->rwlock);
6464 cookies_remove(ofproto, rule);
6466 eviction_group_remove_rule(rule);
6467 if (!list_is_empty(&rule->expirable)) {
6468 list_remove(&rule->expirable);
6470 if (!list_is_empty(&rule->meter_list_node)) {
6471 list_remove(&rule->meter_list_node);
6472 list_init(&rule->meter_list_node);
6477 oftable_remove_rule(struct rule *rule)
6478 OVS_REQUIRES(ofproto_mutex)
6480 oftable_remove_rule__(rule->ofproto, rule);
6483 /* unixctl commands. */
6486 ofproto_lookup(const char *name)
6488 struct ofproto *ofproto;
6490 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
6492 if (!strcmp(ofproto->name, name)) {
6500 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
6501 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6503 struct ofproto *ofproto;
6507 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
6508 ds_put_format(&results, "%s\n", ofproto->name);
6510 unixctl_command_reply(conn, ds_cstr(&results));
6511 ds_destroy(&results);
6515 ofproto_unixctl_init(void)
6517 static bool registered;
6523 unixctl_command_register("ofproto/list", "", 0, 0,
6524 ofproto_unixctl_list, NULL);
6527 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6529 * This is deprecated. It is only for compatibility with broken device drivers
6530 * in old versions of Linux that do not properly support VLANs when VLAN
6531 * devices are not used. When broken device drivers are no longer in
6532 * widespread use, we will delete these interfaces. */
6534 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
6535 * (exactly) by an OpenFlow rule in 'ofproto'. */
6537 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
6540 struct cls_rule target;
6541 const struct oftable *oftable;
6543 match_init_catchall(&match);
6544 match_set_vlan_vid_masked(&match, htons(VLAN_CFI), htons(VLAN_CFI));
6545 cls_rule_init(&target, &match, 0);
6547 free(ofproto->vlan_bitmap);
6548 ofproto->vlan_bitmap = bitmap_allocate(4096);
6549 ofproto->vlans_changed = false;
6551 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
6552 struct cls_cursor cursor;
6555 fat_rwlock_rdlock(&oftable->cls.rwlock);
6556 cls_cursor_init(&cursor, &oftable->cls, &target);
6557 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6558 if (minimask_get_vid_mask(&rule->cr.match.mask) == VLAN_VID_MASK) {
6559 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
6561 bitmap_set1(vlan_bitmap, vid);
6562 bitmap_set1(ofproto->vlan_bitmap, vid);
6565 fat_rwlock_unlock(&oftable->cls.rwlock);
6568 cls_rule_destroy(&target);
6571 /* Returns true if new VLANs have come into use by the flow table since the
6572 * last call to ofproto_get_vlan_usage().
6574 * We don't track when old VLANs stop being used. */
6576 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
6578 return ofproto->vlans_changed;
6581 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
6582 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
6583 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
6584 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
6585 * then the VLAN device is un-enslaved. */
6587 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
6588 ofp_port_t realdev_ofp_port, int vid)
6590 struct ofport *ofport;
6593 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
6595 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
6597 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
6598 ofproto->name, vlandev_ofp_port);
6602 if (!ofproto->ofproto_class->set_realdev) {
6603 if (!vlandev_ofp_port) {
6606 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
6610 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
6612 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
6613 ofproto->name, vlandev_ofp_port,
6614 netdev_get_name(ofport->netdev), ovs_strerror(error));