2 * Copyright (c) 2009, 2010, 2011, 2012, 2013 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"
30 #include "dynamic-string.h"
33 #include "meta-flow.h"
36 #include "ofp-actions.h"
37 #include "ofp-errors.h"
39 #include "ofp-print.h"
42 #include "ofproto-provider.h"
43 #include "openflow/nicira-ext.h"
44 #include "openflow/openflow.h"
48 #include "poll-loop.h"
54 #include "unaligned.h"
58 VLOG_DEFINE_THIS_MODULE(ofproto);
60 COVERAGE_DEFINE(ofproto_error);
61 COVERAGE_DEFINE(ofproto_flush);
62 COVERAGE_DEFINE(ofproto_no_packet_in);
63 COVERAGE_DEFINE(ofproto_packet_out);
64 COVERAGE_DEFINE(ofproto_queue_req);
65 COVERAGE_DEFINE(ofproto_recv_openflow);
66 COVERAGE_DEFINE(ofproto_reinit_ports);
67 COVERAGE_DEFINE(ofproto_uninstallable);
68 COVERAGE_DEFINE(ofproto_update_port);
71 S_OPENFLOW, /* Processing OpenFlow commands. */
72 S_EVICT, /* Evicting flows from over-limit tables. */
73 S_FLUSH, /* Deleting all flow table rules. */
76 enum ofoperation_type {
83 /* A single OpenFlow request can execute any number of operations. The
84 * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
85 * ofconn to which an error reply should be sent if necessary.
87 * ofproto initiates some operations internally. These operations are still
88 * assigned to groups but will not have an associated ofconn. */
90 struct ofproto *ofproto; /* Owning ofproto. */
91 struct list ofproto_node; /* In ofproto's "pending" list. */
92 struct list ops; /* List of "struct ofoperation"s. */
93 int n_running; /* Number of ops still pending. */
95 /* Data needed to send OpenFlow reply on failure or to send a buffered
98 * If list_is_empty(ofconn_node) then this ofopgroup never had an
99 * associated ofconn or its ofconn's connection dropped after it initiated
100 * the operation. In the latter case 'ofconn' is a wild pointer that
101 * refers to freed memory, so the 'ofconn' member must be used only if
102 * !list_is_empty(ofconn_node).
104 struct list ofconn_node; /* In ofconn's list of pending opgroups. */
105 struct ofconn *ofconn; /* ofconn for reply (but see note above). */
106 struct ofp_header *request; /* Original request (truncated at 64 bytes). */
107 uint32_t buffer_id; /* Buffer id from original request. */
110 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
111 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
112 const struct ofp_header *,
114 static void ofopgroup_submit(struct ofopgroup *);
115 static void ofopgroup_complete(struct ofopgroup *);
117 /* A single flow table operation. */
119 struct ofopgroup *group; /* Owning group. */
120 struct list group_node; /* In ofopgroup's "ops" list. */
121 struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
122 struct rule *rule; /* Rule being operated upon. */
123 enum ofoperation_type type; /* Type of operation. */
125 /* OFOPERATION_MODIFY, OFOPERATION_REPLACE: The old actions, if the actions
127 struct ofpact *ofpacts;
131 /* OFOPERATION_DELETE. */
132 enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
134 ovs_be64 flow_cookie; /* Rule's old flow cookie. */
135 uint16_t idle_timeout; /* Rule's old idle timeout. */
136 uint16_t hard_timeout; /* Rule's old hard timeout. */
137 bool send_flow_removed; /* Rule's old 'send_flow_removed'. */
138 enum ofperr error; /* 0 if no error. */
141 static struct ofoperation *ofoperation_create(struct ofopgroup *,
143 enum ofoperation_type,
144 enum ofp_flow_removed_reason);
145 static void ofoperation_destroy(struct ofoperation *);
148 static void oftable_init(struct oftable *);
149 static void oftable_destroy(struct oftable *);
151 static void oftable_set_name(struct oftable *, const char *name);
153 static void oftable_disable_eviction(struct oftable *);
154 static void oftable_enable_eviction(struct oftable *,
155 const struct mf_subfield *fields,
158 static void oftable_remove_rule(struct rule *rule) OVS_RELEASES(rule->rwlock);
159 static void oftable_remove_rule__(struct ofproto *ofproto,
160 struct classifier *cls, struct rule *rule)
161 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock);
162 static void oftable_insert_rule(struct rule *);
164 /* A set of rules within a single OpenFlow table (oftable) that have the same
165 * values for the oftable's eviction_fields. A rule to be evicted, when one is
166 * needed, is taken from the eviction group that contains the greatest number
169 * An oftable owns any number of eviction groups, each of which contains any
172 * Membership in an eviction group is imprecise, based on the hash of the
173 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
174 * That is, if two rules have different eviction_fields, but those
175 * eviction_fields hash to the same value, then they will belong to the same
176 * eviction_group anyway.
178 * (When eviction is not enabled on an oftable, we don't track any eviction
179 * groups, to save time and space.) */
180 struct eviction_group {
181 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
182 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
183 struct heap rules; /* Contains "struct rule"s. */
186 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep)
187 OVS_TRY_WRLOCK(true, (*rulep)->rwlock);
188 static void ofproto_evict(struct ofproto *);
189 static uint32_t rule_eviction_priority(struct rule *);
190 static void eviction_group_add_rule(struct rule *);
191 static void eviction_group_remove_rule(struct rule *);
193 /* Criteria that flow_mod and other operations use for selecting rules on
194 * which to operate. */
195 struct rule_criteria {
196 /* An OpenFlow table or 255 for all tables. */
199 /* OpenFlow matching criteria. Interpreted different in "loose" way by
200 * collect_rules_loose() and "strict" way by collect_rules_strict(), as
201 * defined in the OpenFlow spec. */
204 /* Matching criteria for the OpenFlow cookie. Consider a bit B in a rule's
205 * cookie and the corresponding bits C in 'cookie' and M in 'cookie_mask'.
206 * The rule will not be selected if M is 1 and B != C. */
208 ovs_be64 cookie_mask;
210 /* Selection based on actions within a rule:
212 * If out_port != OFPP_ANY, selects only rules that output to out_port. */
216 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
217 const struct match *match,
218 unsigned int priority,
219 ovs_be64 cookie, ovs_be64 cookie_mask,
220 ofp_port_t out_port);
221 static void rule_criteria_destroy(struct rule_criteria *);
224 static void ofport_destroy__(struct ofport *);
225 static void ofport_destroy(struct ofport *);
227 static void update_port(struct ofproto *, const char *devname);
228 static int init_ports(struct ofproto *);
229 static void reinit_ports(struct ofproto *);
232 static void ofproto_rule_destroy(struct rule *);
233 static void ofproto_rule_destroy__(struct rule *);
234 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
235 static bool rule_is_modifiable(const struct rule *);
238 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
239 struct ofputil_flow_mod *,
240 const struct ofp_header *);
241 static enum ofperr modify_flows__(struct ofproto *, struct ofconn *,
242 struct ofputil_flow_mod *,
243 const struct ofp_header *,
244 const struct rule_collection *);
245 static void delete_flow__(struct rule *rule, struct ofopgroup *,
246 enum ofp_flow_removed_reason)
247 OVS_RELEASES(rule->rwlock);
248 static bool handle_openflow(struct ofconn *, const struct ofpbuf *);
249 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
250 struct ofputil_flow_mod *,
251 const struct ofp_header *);
252 static void calc_duration(long long int start, long long int now,
253 uint32_t *sec, uint32_t *nsec);
256 static uint64_t pick_datapath_id(const struct ofproto *);
257 static uint64_t pick_fallback_dpid(void);
258 static void ofproto_destroy__(struct ofproto *);
259 static void update_mtu(struct ofproto *, struct ofport *);
260 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
263 static void ofproto_unixctl_init(void);
265 /* All registered ofproto classes, in probe order. */
266 static const struct ofproto_class **ofproto_classes;
267 static size_t n_ofproto_classes;
268 static size_t allocated_ofproto_classes;
270 unsigned flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT;
271 unsigned n_handler_threads;
272 enum ofproto_flow_miss_model flow_miss_model = OFPROTO_HANDLE_MISS_AUTO;
274 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
275 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
277 /* Initial mappings of port to OpenFlow number mappings. */
278 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
280 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
282 /* The default value of true waits for flow restore. */
283 static bool flow_restore_wait = true;
285 /* Must be called to initialize the ofproto library.
287 * The caller may pass in 'iface_hints', which contains an shash of
288 * "iface_hint" elements indexed by the interface's name. The provider
289 * may use these hints to describe the startup configuration in order to
290 * reinitialize its state. The caller owns the provided data, so a
291 * provider will make copies of anything required. An ofproto provider
292 * will remove any existing state that is not described by the hint, and
293 * may choose to remove it all. */
295 ofproto_init(const struct shash *iface_hints)
297 struct shash_node *node;
300 ofproto_class_register(&ofproto_dpif_class);
302 /* Make a local copy, since we don't own 'iface_hints' elements. */
303 SHASH_FOR_EACH(node, iface_hints) {
304 const struct iface_hint *orig_hint = node->data;
305 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
306 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
308 new_hint->br_name = xstrdup(orig_hint->br_name);
309 new_hint->br_type = xstrdup(br_type);
310 new_hint->ofp_port = orig_hint->ofp_port;
312 shash_add(&init_ofp_ports, node->name, new_hint);
315 for (i = 0; i < n_ofproto_classes; i++) {
316 ofproto_classes[i]->init(&init_ofp_ports);
320 /* 'type' should be a normalized datapath type, as returned by
321 * ofproto_normalize_type(). Returns the corresponding ofproto_class
322 * structure, or a null pointer if there is none registered for 'type'. */
323 static const struct ofproto_class *
324 ofproto_class_find__(const char *type)
328 for (i = 0; i < n_ofproto_classes; i++) {
329 const struct ofproto_class *class = ofproto_classes[i];
334 class->enumerate_types(&types);
335 found = sset_contains(&types, type);
336 sset_destroy(&types);
342 VLOG_WARN("unknown datapath type %s", type);
346 /* Registers a new ofproto class. After successful registration, new ofprotos
347 * of that type can be created using ofproto_create(). */
349 ofproto_class_register(const struct ofproto_class *new_class)
353 for (i = 0; i < n_ofproto_classes; i++) {
354 if (ofproto_classes[i] == new_class) {
359 if (n_ofproto_classes >= allocated_ofproto_classes) {
360 ofproto_classes = x2nrealloc(ofproto_classes,
361 &allocated_ofproto_classes,
362 sizeof *ofproto_classes);
364 ofproto_classes[n_ofproto_classes++] = new_class;
368 /* Unregisters a datapath provider. 'type' must have been previously
369 * registered and not currently be in use by any ofprotos. After
370 * unregistration new datapaths of that type cannot be opened using
371 * ofproto_create(). */
373 ofproto_class_unregister(const struct ofproto_class *class)
377 for (i = 0; i < n_ofproto_classes; i++) {
378 if (ofproto_classes[i] == class) {
379 for (i++; i < n_ofproto_classes; i++) {
380 ofproto_classes[i - 1] = ofproto_classes[i];
386 VLOG_WARN("attempted to unregister an ofproto class that is not "
391 /* Clears 'types' and enumerates all registered ofproto types into it. The
392 * caller must first initialize the sset. */
394 ofproto_enumerate_types(struct sset *types)
398 for (i = 0; i < n_ofproto_classes; i++) {
399 ofproto_classes[i]->enumerate_types(types);
403 /* Returns the fully spelled out name for the given ofproto 'type'.
405 * Normalized type string can be compared with strcmp(). Unnormalized type
406 * string might be the same even if they have different spellings. */
408 ofproto_normalize_type(const char *type)
410 return type && type[0] ? type : "system";
413 /* Clears 'names' and enumerates the names of all known created ofprotos with
414 * the given 'type'. The caller must first initialize the sset. Returns 0 if
415 * successful, otherwise a positive errno value.
417 * Some kinds of datapaths might not be practically enumerable. This is not
418 * considered an error. */
420 ofproto_enumerate_names(const char *type, struct sset *names)
422 const struct ofproto_class *class = ofproto_class_find__(type);
423 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
427 ofproto_create(const char *datapath_name, const char *datapath_type,
428 struct ofproto **ofprotop)
430 const struct ofproto_class *class;
431 struct ofproto *ofproto;
437 ofproto_unixctl_init();
439 datapath_type = ofproto_normalize_type(datapath_type);
440 class = ofproto_class_find__(datapath_type);
442 VLOG_WARN("could not create datapath %s of unknown type %s",
443 datapath_name, datapath_type);
447 ofproto = class->alloc();
449 VLOG_ERR("failed to allocate datapath %s of type %s",
450 datapath_name, datapath_type);
455 memset(ofproto, 0, sizeof *ofproto);
456 ofproto->ofproto_class = class;
457 ofproto->name = xstrdup(datapath_name);
458 ofproto->type = xstrdup(datapath_type);
459 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
460 hash_string(ofproto->name, 0));
461 ofproto->datapath_id = 0;
462 ofproto->forward_bpdu = false;
463 ofproto->fallback_dpid = pick_fallback_dpid();
464 ofproto->mfr_desc = NULL;
465 ofproto->hw_desc = NULL;
466 ofproto->sw_desc = NULL;
467 ofproto->serial_desc = NULL;
468 ofproto->dp_desc = NULL;
469 ofproto->frag_handling = OFPC_FRAG_NORMAL;
470 hmap_init(&ofproto->ports);
471 shash_init(&ofproto->port_by_name);
472 simap_init(&ofproto->ofp_requests);
473 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
474 ofproto->eviction_group_timer = LLONG_MIN;
475 ofproto->tables = NULL;
476 ofproto->n_tables = 0;
477 hindex_init(&ofproto->cookies);
478 list_init(&ofproto->expirable);
479 ovs_mutex_init_recursive(&ofproto->expirable_mutex);
480 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
481 ofproto->state = S_OPENFLOW;
482 list_init(&ofproto->pending);
483 ofproto->n_pending = 0;
484 hmap_init(&ofproto->deletions);
485 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
486 ofproto->first_op = ofproto->last_op = LLONG_MIN;
487 ofproto->next_op_report = LLONG_MAX;
488 ofproto->op_backoff = LLONG_MIN;
489 ofproto->vlan_bitmap = NULL;
490 ofproto->vlans_changed = false;
491 ofproto->min_mtu = INT_MAX;
493 error = ofproto->ofproto_class->construct(ofproto);
495 VLOG_ERR("failed to open datapath %s: %s",
496 datapath_name, ovs_strerror(error));
497 ofproto_destroy__(ofproto);
501 /* The "max_ports" member should have been set by ->construct(ofproto).
502 * Port 0 is not a valid OpenFlow port, so mark that as unavailable. */
503 ofproto->ofp_port_ids = bitmap_allocate(ofproto->max_ports);
504 bitmap_set1(ofproto->ofp_port_ids, 0);
506 /* Check that hidden tables, if any, are at the end. */
507 ovs_assert(ofproto->n_tables);
508 for (i = 0; i + 1 < ofproto->n_tables; i++) {
509 enum oftable_flags flags = ofproto->tables[i].flags;
510 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
512 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
515 ofproto->datapath_id = pick_datapath_id(ofproto);
518 /* Initialize meters table. */
519 if (ofproto->ofproto_class->meter_get_features) {
520 ofproto->ofproto_class->meter_get_features(ofproto,
521 &ofproto->meter_features);
523 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
525 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
526 * sizeof(struct meter *));
532 /* Must be called (only) by an ofproto implementation in its constructor
533 * function. See the large comment on 'construct' in struct ofproto_class for
536 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
538 struct oftable *table;
540 ovs_assert(!ofproto->n_tables);
541 ovs_assert(n_tables >= 1 && n_tables <= 255);
543 ofproto->n_tables = n_tables;
544 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
545 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
550 /* To be optionally called (only) by an ofproto implementation in its
551 * constructor function. See the large comment on 'construct' in struct
552 * ofproto_class for details.
554 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
555 * will then ensure that actions passed into the ofproto implementation will
556 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
557 * function is not called, there will be no such restriction.
559 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
560 * the 'max_ports' restriction. */
562 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
564 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
565 ofproto->max_ports = max_ports;
569 ofproto_get_datapath_id(const struct ofproto *ofproto)
571 return ofproto->datapath_id;
575 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
577 uint64_t old_dpid = p->datapath_id;
578 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
579 if (p->datapath_id != old_dpid) {
580 /* Force all active connections to reconnect, since there is no way to
581 * notify a controller that the datapath ID has changed. */
582 ofproto_reconnect_controllers(p);
587 ofproto_set_controllers(struct ofproto *p,
588 const struct ofproto_controller *controllers,
589 size_t n_controllers, uint32_t allowed_versions)
591 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
596 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
598 connmgr_set_fail_mode(p->connmgr, fail_mode);
601 /* Drops the connections between 'ofproto' and all of its controllers, forcing
602 * them to reconnect. */
604 ofproto_reconnect_controllers(struct ofproto *ofproto)
606 connmgr_reconnect(ofproto->connmgr);
609 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
610 * in-band control should guarantee access, in the same way that in-band
611 * control guarantees access to OpenFlow controllers. */
613 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
614 const struct sockaddr_in *extras, size_t n)
616 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
619 /* Sets the OpenFlow queue used by flows set up by in-band control on
620 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
621 * flows will use the default queue. */
623 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
625 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
628 /* Sets the number of flows at which eviction from the kernel flow table
631 ofproto_set_flow_eviction_threshold(unsigned threshold)
633 flow_eviction_threshold = MAX(OFPROTO_FLOW_EVICTION_THRESHOLD_MIN,
637 /* Sets the path for handling flow misses. */
639 ofproto_set_flow_miss_model(unsigned model)
641 flow_miss_model = model;
644 /* If forward_bpdu is true, the NORMAL action will forward frames with
645 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
646 * the NORMAL action will drop these frames. */
648 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
650 bool old_val = ofproto->forward_bpdu;
651 ofproto->forward_bpdu = forward_bpdu;
652 if (old_val != ofproto->forward_bpdu) {
653 if (ofproto->ofproto_class->forward_bpdu_changed) {
654 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
659 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
660 * 'idle_time', in seconds, and the maximum number of MAC table entries to
663 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
666 if (ofproto->ofproto_class->set_mac_table_config) {
667 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
672 /* Sets number of upcall handler threads. The default is
673 * (number of online cores - 2). */
675 ofproto_set_n_handler_threads(unsigned limit)
678 n_handler_threads = limit;
680 int n_proc = sysconf(_SC_NPROCESSORS_ONLN);
681 n_handler_threads = n_proc > 2 ? n_proc - 2 : 1;
686 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
689 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
693 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
695 return connmgr_set_snoops(ofproto->connmgr, snoops);
699 ofproto_set_netflow(struct ofproto *ofproto,
700 const struct netflow_options *nf_options)
702 if (nf_options && sset_is_empty(&nf_options->collectors)) {
706 if (ofproto->ofproto_class->set_netflow) {
707 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
709 return nf_options ? EOPNOTSUPP : 0;
714 ofproto_set_sflow(struct ofproto *ofproto,
715 const struct ofproto_sflow_options *oso)
717 if (oso && sset_is_empty(&oso->targets)) {
721 if (ofproto->ofproto_class->set_sflow) {
722 return ofproto->ofproto_class->set_sflow(ofproto, oso);
724 return oso ? EOPNOTSUPP : 0;
729 ofproto_set_ipfix(struct ofproto *ofproto,
730 const struct ofproto_ipfix_bridge_exporter_options *bo,
731 const struct ofproto_ipfix_flow_exporter_options *fo,
734 if (ofproto->ofproto_class->set_ipfix) {
735 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
737 return (bo || fo) ? EOPNOTSUPP : 0;
742 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
744 flow_restore_wait = flow_restore_wait_db;
748 ofproto_get_flow_restore_wait(void)
750 return flow_restore_wait;
754 /* Spanning Tree Protocol (STP) configuration. */
756 /* Configures STP on 'ofproto' using the settings defined in 's'. If
757 * 's' is NULL, disables STP.
759 * Returns 0 if successful, otherwise a positive errno value. */
761 ofproto_set_stp(struct ofproto *ofproto,
762 const struct ofproto_stp_settings *s)
764 return (ofproto->ofproto_class->set_stp
765 ? ofproto->ofproto_class->set_stp(ofproto, s)
769 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
770 * 'enabled' member of 's' is false, then the other members are not
773 * Returns 0 if successful, otherwise a positive errno value. */
775 ofproto_get_stp_status(struct ofproto *ofproto,
776 struct ofproto_stp_status *s)
778 return (ofproto->ofproto_class->get_stp_status
779 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
783 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
784 * in 's'. The caller is responsible for assigning STP port numbers
785 * (using the 'port_num' member in the range of 1 through 255, inclusive)
786 * and ensuring there are no duplicates. If the 's' is NULL, then STP
787 * is disabled on the port.
789 * Returns 0 if successful, otherwise a positive errno value.*/
791 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
792 const struct ofproto_port_stp_settings *s)
794 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
796 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
797 ofproto->name, ofp_port);
801 return (ofproto->ofproto_class->set_stp_port
802 ? ofproto->ofproto_class->set_stp_port(ofport, s)
806 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
807 * 's'. If the 'enabled' member in 's' is false, then the other members
808 * are not meaningful.
810 * Returns 0 if successful, otherwise a positive errno value.*/
812 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
813 struct ofproto_port_stp_status *s)
815 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
817 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
818 "port %"PRIu16, ofproto->name, ofp_port);
822 return (ofproto->ofproto_class->get_stp_port_status
823 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
827 /* Queue DSCP configuration. */
829 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
830 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
831 * to implement QoS. Instead, it is used to implement features which require
832 * knowledge of what queues exist on a port, and some basic information about
835 * Returns 0 if successful, otherwise a positive errno value. */
837 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
838 const struct ofproto_port_queue *queues,
841 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
844 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
845 ofproto->name, ofp_port);
849 return (ofproto->ofproto_class->set_queues
850 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
854 /* Connectivity Fault Management configuration. */
856 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
858 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
860 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
861 if (ofport && ofproto->ofproto_class->set_cfm) {
862 ofproto->ofproto_class->set_cfm(ofport, NULL);
866 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
867 * basic configuration from the configuration members in 'cfm', and the remote
868 * maintenance point ID from remote_mpid. Ignores the statistics members of
871 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
873 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
874 const struct cfm_settings *s)
876 struct ofport *ofport;
879 ofport = ofproto_get_port(ofproto, ofp_port);
881 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
882 ofproto->name, ofp_port);
886 /* XXX: For configuration simplicity, we only support one remote_mpid
887 * outside of the CFM module. It's not clear if this is the correct long
888 * term solution or not. */
889 error = (ofproto->ofproto_class->set_cfm
890 ? ofproto->ofproto_class->set_cfm(ofport, s)
893 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
894 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
895 ovs_strerror(error));
899 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
900 * 'ofproto' does not have a port 'ofp_port'. */
902 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
903 const struct smap *cfg)
905 struct ofport *ofport;
908 ofport = ofproto_get_port(ofproto, ofp_port);
910 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
911 ofproto->name, ofp_port);
915 error = (ofproto->ofproto_class->set_bfd
916 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
919 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
920 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
921 ovs_strerror(error));
925 /* Populates 'status' with key value pairs indicating the status of the BFD
926 * session on 'ofp_port'. This information is intended to be populated in the
927 * OVS database. Has no effect if 'ofp_port' is not na OpenFlow port in
930 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
933 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
934 return (ofport && ofproto->ofproto_class->get_bfd_status
935 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
939 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
940 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
941 * 0 if LACP partner information is not current (generally indicating a
942 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
944 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
946 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
947 return (ofport && ofproto->ofproto_class->port_is_lacp_current
948 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
954 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
955 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
956 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
957 * configuration plus, if there is more than one slave, a bonding
960 * If 'aux' is already registered then this function updates its configuration
961 * to 's'. Otherwise, this function registers a new bundle.
963 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
966 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
967 const struct ofproto_bundle_settings *s)
969 return (ofproto->ofproto_class->bundle_set
970 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
974 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
975 * If no such bundle has been registered, this has no effect. */
977 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
979 return ofproto_bundle_register(ofproto, aux, NULL);
983 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
984 * If 'aux' is already registered then this function updates its configuration
985 * to 's'. Otherwise, this function registers a new mirror. */
987 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
988 const struct ofproto_mirror_settings *s)
990 return (ofproto->ofproto_class->mirror_set
991 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
995 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
996 * If no mirror has been registered, this has no effect. */
998 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1000 return ofproto_mirror_register(ofproto, aux, NULL);
1003 /* Retrieves statistics from mirror associated with client data pointer
1004 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1005 * 'bytes', respectively. If a particular counters is not supported,
1006 * the appropriate argument is set to UINT64_MAX. */
1008 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1009 uint64_t *packets, uint64_t *bytes)
1011 if (!ofproto->ofproto_class->mirror_get_stats) {
1012 *packets = *bytes = UINT64_MAX;
1016 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1020 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1021 * which all packets are flooded, instead of using MAC learning. If
1022 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1024 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1027 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1029 return (ofproto->ofproto_class->set_flood_vlans
1030 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1034 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1035 * output for a mirror. */
1037 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1039 return (ofproto->ofproto_class->is_mirror_output_bundle
1040 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1044 /* Configuration of OpenFlow tables. */
1046 /* Returns the number of OpenFlow tables in 'ofproto'. */
1048 ofproto_get_n_tables(const struct ofproto *ofproto)
1050 return ofproto->n_tables;
1053 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1054 * settings from 's'. 'table_id' must be in the range 0 through the number of
1055 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1057 * For read-only tables, only the name may be configured. */
1059 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1060 const struct ofproto_table_settings *s)
1062 struct oftable *table;
1064 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1065 table = &ofproto->tables[table_id];
1067 oftable_set_name(table, s->name);
1069 if (table->flags & OFTABLE_READONLY) {
1074 oftable_enable_eviction(table, s->groups, s->n_groups);
1076 oftable_disable_eviction(table);
1079 table->max_flows = s->max_flows;
1080 ovs_rwlock_rdlock(&table->cls.rwlock);
1081 if (classifier_count(&table->cls) > table->max_flows
1082 && table->eviction_fields) {
1083 /* 'table' contains more flows than allowed. We might not be able to
1084 * evict them right away because of the asynchronous nature of flow
1085 * table changes. Schedule eviction for later. */
1086 switch (ofproto->state) {
1088 ofproto->state = S_EVICT;
1092 /* We're already deleting flows, nothing more to do. */
1096 ovs_rwlock_unlock(&table->cls.rwlock);
1100 ofproto_has_snoops(const struct ofproto *ofproto)
1102 return connmgr_has_snoops(ofproto->connmgr);
1106 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1108 connmgr_get_snoops(ofproto->connmgr, snoops);
1111 /* Deletes 'rule' from 'cls' within 'ofproto'.
1113 * Within an ofproto implementation, this function allows an ofproto
1114 * implementation to destroy any rules that remain when its ->destruct()
1115 * function is called. This function is not suitable for use elsewhere in an
1116 * ofproto implementation.
1118 * This function is also used internally in ofproto.c.
1120 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1121 * Cycle" in ofproto-provider.h.
1123 * The 'cls' argument is redundant (it is &ofproto->tables[rule->table_id].cls)
1124 * but it allows Clang to do better checking. */
1126 ofproto_rule_delete(struct ofproto *ofproto, struct classifier *cls,
1128 OVS_REQ_WRLOCK(cls->rwlock)
1130 struct ofopgroup *group;
1132 ovs_assert(!rule->pending);
1133 ovs_assert(cls == &ofproto->tables[rule->table_id].cls);
1135 group = ofopgroup_create_unattached(ofproto);
1136 ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1137 ovs_rwlock_wrlock(&rule->rwlock);
1138 oftable_remove_rule__(ofproto, cls, rule);
1139 ofproto->ofproto_class->rule_delete(rule);
1140 ofopgroup_submit(group);
1144 ofproto_flush__(struct ofproto *ofproto)
1146 struct oftable *table;
1148 if (ofproto->ofproto_class->flush) {
1149 ofproto->ofproto_class->flush(ofproto);
1152 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1153 struct rule *rule, *next_rule;
1154 struct cls_cursor cursor;
1156 if (table->flags & OFTABLE_HIDDEN) {
1160 ovs_rwlock_wrlock(&table->cls.rwlock);
1161 cls_cursor_init(&cursor, &table->cls, NULL);
1162 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1163 if (!rule->pending) {
1164 ofproto_rule_delete(ofproto, &table->cls, rule);
1167 ovs_rwlock_unlock(&table->cls.rwlock);
1172 ofproto_destroy__(struct ofproto *ofproto)
1174 struct oftable *table;
1176 ovs_assert(list_is_empty(&ofproto->pending));
1177 ovs_assert(!ofproto->n_pending);
1179 connmgr_destroy(ofproto->connmgr);
1181 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1182 free(ofproto->name);
1183 free(ofproto->type);
1184 free(ofproto->mfr_desc);
1185 free(ofproto->hw_desc);
1186 free(ofproto->sw_desc);
1187 free(ofproto->serial_desc);
1188 free(ofproto->dp_desc);
1189 hmap_destroy(&ofproto->ports);
1190 shash_destroy(&ofproto->port_by_name);
1191 bitmap_free(ofproto->ofp_port_ids);
1192 simap_destroy(&ofproto->ofp_requests);
1194 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1195 oftable_destroy(table);
1197 free(ofproto->tables);
1199 hmap_destroy(&ofproto->deletions);
1201 free(ofproto->vlan_bitmap);
1203 ovs_mutex_destroy(&ofproto->expirable_mutex);
1204 ofproto->ofproto_class->dealloc(ofproto);
1208 ofproto_destroy(struct ofproto *p)
1210 struct ofport *ofport, *next_ofport;
1217 meter_delete(p, 1, p->meter_features.max_meters);
1218 p->meter_features.max_meters = 0;
1224 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1225 ofport_destroy(ofport);
1228 p->ofproto_class->destruct(p);
1229 ofproto_destroy__(p);
1232 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1233 * kernel datapath, for example, this destroys the datapath in the kernel, and
1234 * with the netdev-based datapath, it tears down the data structures that
1235 * represent the datapath.
1237 * The datapath should not be currently open as an ofproto. */
1239 ofproto_delete(const char *name, const char *type)
1241 const struct ofproto_class *class = ofproto_class_find__(type);
1242 return (!class ? EAFNOSUPPORT
1243 : !class->del ? EACCES
1244 : class->del(type, name));
1248 process_port_change(struct ofproto *ofproto, int error, char *devname)
1250 if (error == ENOBUFS) {
1251 reinit_ports(ofproto);
1252 } else if (!error) {
1253 update_port(ofproto, devname);
1259 ofproto_type_run(const char *datapath_type)
1261 const struct ofproto_class *class;
1264 datapath_type = ofproto_normalize_type(datapath_type);
1265 class = ofproto_class_find__(datapath_type);
1267 error = class->type_run ? class->type_run(datapath_type) : 0;
1268 if (error && error != EAGAIN) {
1269 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1270 datapath_type, ovs_strerror(error));
1276 ofproto_type_run_fast(const char *datapath_type)
1278 const struct ofproto_class *class;
1281 datapath_type = ofproto_normalize_type(datapath_type);
1282 class = ofproto_class_find__(datapath_type);
1284 error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1285 if (error && error != EAGAIN) {
1286 VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1287 datapath_type, ovs_strerror(error));
1293 ofproto_type_wait(const char *datapath_type)
1295 const struct ofproto_class *class;
1297 datapath_type = ofproto_normalize_type(datapath_type);
1298 class = ofproto_class_find__(datapath_type);
1300 if (class->type_wait) {
1301 class->type_wait(datapath_type);
1306 ofproto_run(struct ofproto *p)
1308 struct sset changed_netdevs;
1309 const char *changed_netdev;
1310 struct ofport *ofport;
1313 error = p->ofproto_class->run(p);
1314 if (error && error != EAGAIN) {
1315 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1318 /* Restore the eviction group heap invariant occasionally. */
1319 if (p->eviction_group_timer < time_msec()) {
1322 p->eviction_group_timer = time_msec() + 1000;
1324 for (i = 0; i < p->n_tables; i++) {
1325 struct oftable *table = &p->tables[i];
1326 struct eviction_group *evg;
1327 struct cls_cursor cursor;
1330 if (!table->eviction_fields) {
1334 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1335 heap_rebuild(&evg->rules);
1338 ovs_rwlock_rdlock(&table->cls.rwlock);
1339 cls_cursor_init(&cursor, &table->cls, NULL);
1340 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1341 if (!rule->eviction_group
1342 && (rule->idle_timeout || rule->hard_timeout)) {
1343 eviction_group_add_rule(rule);
1346 ovs_rwlock_unlock(&table->cls.rwlock);
1350 if (p->ofproto_class->port_poll) {
1353 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1354 process_port_change(p, error, devname);
1358 /* Update OpenFlow port status for any port whose netdev has changed.
1360 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1361 * destroyed, so it's not safe to update ports directly from the
1362 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1363 * need this two-phase approach. */
1364 sset_init(&changed_netdevs);
1365 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1366 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1367 if (ofport->change_seq != change_seq) {
1368 ofport->change_seq = change_seq;
1369 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1372 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1373 update_port(p, changed_netdev);
1375 sset_destroy(&changed_netdevs);
1379 connmgr_run(p->connmgr, handle_openflow);
1383 connmgr_run(p->connmgr, NULL);
1385 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1386 p->state = S_OPENFLOW;
1391 connmgr_run(p->connmgr, NULL);
1393 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1394 connmgr_flushed(p->connmgr);
1395 p->state = S_OPENFLOW;
1403 if (time_msec() >= p->next_op_report) {
1404 long long int ago = (time_msec() - p->first_op) / 1000;
1405 long long int interval = (p->last_op - p->first_op) / 1000;
1409 ds_put_format(&s, "%d flow_mods ",
1410 p->n_add + p->n_delete + p->n_modify);
1411 if (interval == ago) {
1412 ds_put_format(&s, "in the last %lld s", ago);
1413 } else if (interval) {
1414 ds_put_format(&s, "in the %lld s starting %lld s ago",
1417 ds_put_format(&s, "%lld s ago", ago);
1420 ds_put_cstr(&s, " (");
1422 ds_put_format(&s, "%d adds, ", p->n_add);
1425 ds_put_format(&s, "%d deletes, ", p->n_delete);
1428 ds_put_format(&s, "%d modifications, ", p->n_modify);
1431 ds_put_char(&s, ')');
1433 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1436 p->n_add = p->n_delete = p->n_modify = 0;
1437 p->next_op_report = LLONG_MAX;
1443 /* Performs periodic activity required by 'ofproto' that needs to be done
1444 * with the least possible latency.
1446 * It makes sense to call this function a couple of times per poll loop, to
1447 * provide a significant performance boost on some benchmarks with the
1448 * ofproto-dpif implementation. */
1450 ofproto_run_fast(struct ofproto *p)
1454 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1455 if (error && error != EAGAIN) {
1456 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1457 p->name, ovs_strerror(error));
1463 ofproto_wait(struct ofproto *p)
1465 struct ofport *ofport;
1467 p->ofproto_class->wait(p);
1468 if (p->ofproto_class->port_poll_wait) {
1469 p->ofproto_class->port_poll_wait(p);
1472 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1473 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1474 poll_immediate_wake();
1480 connmgr_wait(p->connmgr, true);
1485 connmgr_wait(p->connmgr, false);
1486 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1487 poll_immediate_wake();
1494 ofproto_is_alive(const struct ofproto *p)
1496 return connmgr_has_controllers(p->connmgr);
1499 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1500 * memory_report(). */
1502 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1504 const struct oftable *table;
1505 unsigned int n_rules;
1507 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1508 simap_increase(usage, "ops",
1509 ofproto->n_pending + hmap_count(&ofproto->deletions));
1512 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1513 ovs_rwlock_rdlock(&table->cls.rwlock);
1514 n_rules += classifier_count(&table->cls);
1515 ovs_rwlock_unlock(&table->cls.rwlock);
1517 simap_increase(usage, "rules", n_rules);
1519 if (ofproto->ofproto_class->get_memory_usage) {
1520 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1523 connmgr_get_memory_usage(ofproto->connmgr, usage);
1527 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1530 connmgr_get_controller_info(ofproto->connmgr, info);
1534 ofproto_free_ofproto_controller_info(struct shash *info)
1536 connmgr_free_controller_info(info);
1539 /* Makes a deep copy of 'old' into 'port'. */
1541 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1543 port->name = xstrdup(old->name);
1544 port->type = xstrdup(old->type);
1545 port->ofp_port = old->ofp_port;
1548 /* Frees memory allocated to members of 'ofproto_port'.
1550 * Do not call this function on an ofproto_port obtained from
1551 * ofproto_port_dump_next(): that function retains ownership of the data in the
1554 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1556 free(ofproto_port->name);
1557 free(ofproto_port->type);
1560 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1562 * This function provides no status indication. An error status for the entire
1563 * dump operation is provided when it is completed by calling
1564 * ofproto_port_dump_done().
1567 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1568 const struct ofproto *ofproto)
1570 dump->ofproto = ofproto;
1571 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1575 /* Attempts to retrieve another port from 'dump', which must have been created
1576 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1577 * 'port' and returns true. On failure, returns false.
1579 * Failure might indicate an actual error or merely that the last port has been
1580 * dumped. An error status for the entire dump operation is provided when it
1581 * is completed by calling ofproto_port_dump_done().
1583 * The ofproto owns the data stored in 'port'. It will remain valid until at
1584 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1585 * ofproto_port_dump_done(). */
1587 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1588 struct ofproto_port *port)
1590 const struct ofproto *ofproto = dump->ofproto;
1596 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1599 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1605 /* Completes port table dump operation 'dump', which must have been created
1606 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1607 * error-free, otherwise a positive errno value describing the problem. */
1609 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1611 const struct ofproto *ofproto = dump->ofproto;
1613 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1616 return dump->error == EOF ? 0 : dump->error;
1619 /* Returns the type to pass to netdev_open() when a datapath of type
1620 * 'datapath_type' has a port of type 'port_type', for a few special
1621 * cases when a netdev type differs from a port type. For example, when
1622 * using the userspace datapath, a port of type "internal" needs to be
1625 * Returns either 'type' itself or a string literal, which must not be
1628 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1630 const struct ofproto_class *class;
1632 datapath_type = ofproto_normalize_type(datapath_type);
1633 class = ofproto_class_find__(datapath_type);
1638 return (class->port_open_type
1639 ? class->port_open_type(datapath_type, port_type)
1643 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1644 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1645 * the port's OpenFlow port number.
1647 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1648 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1649 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1650 * 'ofp_portp' is non-null). */
1652 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1653 ofp_port_t *ofp_portp)
1655 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1658 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1660 const char *netdev_name = netdev_get_name(netdev);
1662 simap_put(&ofproto->ofp_requests, netdev_name,
1663 ofp_to_u16(ofp_port));
1664 update_port(ofproto, netdev_name);
1667 struct ofproto_port ofproto_port;
1669 ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1671 *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1672 ofproto_port_destroy(&ofproto_port);
1677 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1678 * initializes '*port' appropriately; on failure, returns a positive errno
1681 * The caller owns the data in 'ofproto_port' and must free it with
1682 * ofproto_port_destroy() when it is no longer needed. */
1684 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1685 struct ofproto_port *port)
1689 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1691 memset(port, 0, sizeof *port);
1696 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1697 * Returns 0 if successful, otherwise a positive errno. */
1699 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1701 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1702 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1703 struct simap_node *ofp_request_node;
1706 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1707 if (ofp_request_node) {
1708 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1711 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1712 if (!error && ofport) {
1713 /* 'name' is the netdev's name and update_port() is going to close the
1714 * netdev. Just in case update_port() refers to 'name' after it
1715 * destroys 'ofport', make a copy of it around the update_port()
1717 char *devname = xstrdup(name);
1718 update_port(ofproto, devname);
1725 simple_flow_mod(struct ofproto *ofproto,
1726 const struct match *match, unsigned int priority,
1727 const struct ofpact *ofpacts, size_t ofpacts_len,
1728 enum ofp_flow_mod_command command)
1730 struct ofputil_flow_mod fm;
1732 memset(&fm, 0, sizeof fm);
1734 fm.priority = priority;
1737 fm.modify_cookie = false;
1739 fm.command = command;
1740 fm.idle_timeout = 0;
1741 fm.hard_timeout = 0;
1742 fm.buffer_id = UINT32_MAX;
1743 fm.out_port = OFPP_ANY;
1745 fm.ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1746 fm.ofpacts_len = ofpacts_len;
1747 return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1750 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1751 * performs the 'n_actions' actions in 'actions'. The new flow will not
1754 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1755 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1756 * controllers; otherwise, it will be hidden.
1758 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1760 * This is a helper function for in-band control and fail-open. */
1762 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1763 unsigned int priority,
1764 const struct ofpact *ofpacts, size_t ofpacts_len)
1766 const struct rule *rule;
1768 /* First do a cheap check whether the rule we're looking for already exists
1769 * with the actions that we want. If it does, then we're done. */
1770 ovs_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1771 rule = rule_from_cls_rule(classifier_find_match_exactly(
1772 &ofproto->tables[0].cls, match, priority));
1773 ovs_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1775 /* If there's no such rule or the rule doesn't have the actions we want,
1776 * fall back to a executing a full flow mod. We can't optimize this at
1777 * all because we didn't take enough locks above to ensure that the flow
1778 * table didn't already change beneath us. */
1779 if (!rule || !ofpacts_equal(rule->ofpacts, rule->ofpacts_len,
1780 ofpacts, ofpacts_len)) {
1781 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1782 OFPFC_MODIFY_STRICT);
1786 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1787 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1788 * operation cannot be initiated now but may be retried later.
1790 * This is a helper function for in-band control and fail-open. */
1792 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1794 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1797 /* Searches for a rule with matching criteria exactly equal to 'target' in
1798 * ofproto's table 0 and, if it finds one, deletes it.
1800 * This is a helper function for in-band control and fail-open. */
1802 ofproto_delete_flow(struct ofproto *ofproto,
1803 const struct match *target, unsigned int priority)
1805 struct classifier *cls = &ofproto->tables[0].cls;
1808 /* First do a cheap check whether the rule we're looking for has already
1809 * been deleted. If so, then we're done. */
1810 ovs_rwlock_rdlock(&cls->rwlock);
1811 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1813 ovs_rwlock_unlock(&cls->rwlock);
1818 /* Fall back to a executing a full flow mod. We can't optimize this at all
1819 * because we didn't take enough locks above to ensure that the flow table
1820 * didn't already change beneath us. */
1821 return simple_flow_mod(ofproto, target, priority, NULL, 0,
1822 OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
1825 /* Starts the process of deleting all of the flows from all of ofproto's flow
1826 * tables and then reintroducing the flows required by in-band control and
1827 * fail-open. The process will complete in a later call to ofproto_run(). */
1829 ofproto_flush_flows(struct ofproto *ofproto)
1831 COVERAGE_INC(ofproto_flush);
1832 ofproto->state = S_FLUSH;
1836 reinit_ports(struct ofproto *p)
1838 struct ofproto_port_dump dump;
1839 struct sset devnames;
1840 struct ofport *ofport;
1841 struct ofproto_port ofproto_port;
1842 const char *devname;
1844 COVERAGE_INC(ofproto_reinit_ports);
1846 sset_init(&devnames);
1847 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1848 sset_add(&devnames, netdev_get_name(ofport->netdev));
1850 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1851 sset_add(&devnames, ofproto_port.name);
1854 SSET_FOR_EACH (devname, &devnames) {
1855 update_port(p, devname);
1857 sset_destroy(&devnames);
1861 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1865 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1866 port_idx = port_idx ? port_idx : UINT16_MAX;
1868 if (port_idx >= ofproto->max_ports
1869 || bitmap_is_set(ofproto->ofp_port_ids, port_idx)) {
1870 uint16_t end_port_no = ofproto->alloc_port_no;
1872 /* Search for a free OpenFlow port number. We try not to
1873 * immediately reuse them to prevent problems due to old
1876 if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1877 ofproto->alloc_port_no = 0;
1879 if (!bitmap_is_set(ofproto->ofp_port_ids,
1880 ofproto->alloc_port_no)) {
1881 port_idx = ofproto->alloc_port_no;
1884 if (ofproto->alloc_port_no == end_port_no) {
1889 bitmap_set1(ofproto->ofp_port_ids, port_idx);
1890 return u16_to_ofp(port_idx);
1894 dealloc_ofp_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
1896 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
1897 bitmap_set0(ofproto->ofp_port_ids, ofp_to_u16(ofp_port));
1901 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1902 * pointer if the netdev cannot be opened. On success, also fills in
1904 static struct netdev *
1905 ofport_open(struct ofproto *ofproto,
1906 struct ofproto_port *ofproto_port,
1907 struct ofputil_phy_port *pp)
1909 enum netdev_flags flags;
1910 struct netdev *netdev;
1913 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1915 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1916 "cannot be opened (%s)",
1918 ofproto_port->name, ofproto_port->ofp_port,
1919 ofproto_port->name, ovs_strerror(error));
1923 if (ofproto_port->ofp_port == OFPP_NONE) {
1924 if (!strcmp(ofproto->name, ofproto_port->name)) {
1925 ofproto_port->ofp_port = OFPP_LOCAL;
1927 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
1928 ofproto_port->name);
1931 pp->port_no = ofproto_port->ofp_port;
1932 netdev_get_etheraddr(netdev, pp->hw_addr);
1933 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1934 netdev_get_flags(netdev, &flags);
1935 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1936 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1937 netdev_get_features(netdev, &pp->curr, &pp->advertised,
1938 &pp->supported, &pp->peer);
1939 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
1940 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
1945 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
1946 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1949 ofport_equal(const struct ofputil_phy_port *a,
1950 const struct ofputil_phy_port *b)
1952 return (eth_addr_equals(a->hw_addr, b->hw_addr)
1953 && a->state == b->state
1954 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1955 && a->curr == b->curr
1956 && a->advertised == b->advertised
1957 && a->supported == b->supported
1958 && a->peer == b->peer
1959 && a->curr_speed == b->curr_speed
1960 && a->max_speed == b->max_speed);
1963 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1964 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1965 * one with the same name or port number). */
1967 ofport_install(struct ofproto *p,
1968 struct netdev *netdev, const struct ofputil_phy_port *pp)
1970 const char *netdev_name = netdev_get_name(netdev);
1971 struct ofport *ofport;
1974 /* Create ofport. */
1975 ofport = p->ofproto_class->port_alloc();
1980 ofport->ofproto = p;
1981 ofport->netdev = netdev;
1982 ofport->change_seq = netdev_change_seq(netdev);
1984 ofport->ofp_port = pp->port_no;
1985 ofport->created = time_msec();
1987 /* Add port to 'p'. */
1988 hmap_insert(&p->ports, &ofport->hmap_node,
1989 hash_ofp_port(ofport->ofp_port));
1990 shash_add(&p->port_by_name, netdev_name, ofport);
1992 update_mtu(p, ofport);
1994 /* Let the ofproto_class initialize its private data. */
1995 error = p->ofproto_class->port_construct(ofport);
1999 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
2003 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2004 p->name, netdev_name, ovs_strerror(error));
2006 ofport_destroy__(ofport);
2008 netdev_close(netdev);
2012 /* Removes 'ofport' from 'p' and destroys it. */
2014 ofport_remove(struct ofport *ofport)
2016 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
2018 ofport_destroy(ofport);
2021 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2024 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2026 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2028 ofport_remove(port);
2032 /* Updates 'port' with new 'pp' description.
2034 * Does not handle a name or port number change. The caller must implement
2035 * such a change as a delete followed by an add. */
2037 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2039 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2040 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2041 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2042 port->pp.state = pp->state;
2043 port->pp.curr = pp->curr;
2044 port->pp.advertised = pp->advertised;
2045 port->pp.supported = pp->supported;
2046 port->pp.peer = pp->peer;
2047 port->pp.curr_speed = pp->curr_speed;
2048 port->pp.max_speed = pp->max_speed;
2050 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
2053 /* Update OpenFlow 'state' in 'port' and notify controller. */
2055 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2057 if (port->pp.state != state) {
2058 port->pp.state = state;
2059 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
2065 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2067 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2069 if (port->ofproto->ofproto_class->set_realdev) {
2070 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2072 if (port->ofproto->ofproto_class->set_stp_port) {
2073 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2075 if (port->ofproto->ofproto_class->set_cfm) {
2076 port->ofproto->ofproto_class->set_cfm(port, NULL);
2078 if (port->ofproto->ofproto_class->bundle_remove) {
2079 port->ofproto->ofproto_class->bundle_remove(port);
2085 ofport_destroy__(struct ofport *port)
2087 struct ofproto *ofproto = port->ofproto;
2088 const char *name = netdev_get_name(port->netdev);
2090 hmap_remove(&ofproto->ports, &port->hmap_node);
2091 shash_delete(&ofproto->port_by_name,
2092 shash_find(&ofproto->port_by_name, name));
2094 netdev_close(port->netdev);
2095 ofproto->ofproto_class->port_dealloc(port);
2099 ofport_destroy(struct ofport *port)
2102 dealloc_ofp_port(port->ofproto, port->ofp_port);
2103 port->ofproto->ofproto_class->port_destruct(port);
2104 ofport_destroy__(port);
2109 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2111 struct ofport *port;
2113 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2115 if (port->ofp_port == ofp_port) {
2123 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2125 struct ofproto *ofproto = port->ofproto;
2128 if (ofproto->ofproto_class->port_get_stats) {
2129 error = ofproto->ofproto_class->port_get_stats(port, stats);
2138 update_port(struct ofproto *ofproto, const char *name)
2140 struct ofproto_port ofproto_port;
2141 struct ofputil_phy_port pp;
2142 struct netdev *netdev;
2143 struct ofport *port;
2145 COVERAGE_INC(ofproto_update_port);
2147 /* Fetch 'name''s location and properties from the datapath. */
2148 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2149 ? ofport_open(ofproto, &ofproto_port, &pp)
2153 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2154 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2155 struct netdev *old_netdev = port->netdev;
2157 /* 'name' hasn't changed location. Any properties changed? */
2158 if (!ofport_equal(&port->pp, &pp)) {
2159 ofport_modified(port, &pp);
2162 update_mtu(ofproto, port);
2164 /* Install the newly opened netdev in case it has changed.
2165 * Don't close the old netdev yet in case port_modified has to
2166 * remove a retained reference to it.*/
2167 port->netdev = netdev;
2168 port->change_seq = netdev_change_seq(netdev);
2170 if (port->ofproto->ofproto_class->port_modified) {
2171 port->ofproto->ofproto_class->port_modified(port);
2174 netdev_close(old_netdev);
2176 /* If 'port' is nonnull then its name differs from 'name' and thus
2177 * we should delete it. If we think there's a port named 'name'
2178 * then its port number must be wrong now so delete it too. */
2180 ofport_remove(port);
2182 ofport_remove_with_name(ofproto, name);
2183 ofport_install(ofproto, netdev, &pp);
2186 /* Any port named 'name' is gone now. */
2187 ofport_remove_with_name(ofproto, name);
2189 ofproto_port_destroy(&ofproto_port);
2193 init_ports(struct ofproto *p)
2195 struct ofproto_port_dump dump;
2196 struct ofproto_port ofproto_port;
2197 struct shash_node *node, *next;
2199 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2200 const char *name = ofproto_port.name;
2202 if (shash_find(&p->port_by_name, name)) {
2203 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2206 struct ofputil_phy_port pp;
2207 struct netdev *netdev;
2209 /* Check if an OpenFlow port number had been requested. */
2210 node = shash_find(&init_ofp_ports, name);
2212 const struct iface_hint *iface_hint = node->data;
2213 simap_put(&p->ofp_requests, name,
2214 ofp_to_u16(iface_hint->ofp_port));
2217 netdev = ofport_open(p, &ofproto_port, &pp);
2219 ofport_install(p, netdev, &pp);
2220 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2221 p->alloc_port_no = MAX(p->alloc_port_no,
2222 ofp_to_u16(ofproto_port.ofp_port));
2228 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2229 struct iface_hint *iface_hint = node->data;
2231 if (!strcmp(iface_hint->br_name, p->name)) {
2232 free(iface_hint->br_name);
2233 free(iface_hint->br_type);
2235 shash_delete(&init_ofp_ports, node);
2242 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2243 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2245 find_min_mtu(struct ofproto *p)
2247 struct ofport *ofport;
2250 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2251 struct netdev *netdev = ofport->netdev;
2254 /* Skip any internal ports, since that's what we're trying to
2256 if (!strcmp(netdev_get_type(netdev), "internal")) {
2260 if (netdev_get_mtu(netdev, &dev_mtu)) {
2263 if (!mtu || dev_mtu < mtu) {
2268 return mtu ? mtu: ETH_PAYLOAD_MAX;
2271 /* Update MTU of all datapath devices on 'p' to the minimum of the
2272 * non-datapath ports in event of 'port' added or changed. */
2274 update_mtu(struct ofproto *p, struct ofport *port)
2276 struct ofport *ofport;
2277 struct netdev *netdev = port->netdev;
2278 int dev_mtu, old_min;
2280 if (netdev_get_mtu(netdev, &dev_mtu)) {
2284 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2285 if (dev_mtu > p->min_mtu) {
2286 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2287 dev_mtu = p->min_mtu;
2290 port->mtu = dev_mtu;
2294 /* For non-internal port find new min mtu. */
2295 old_min = p->min_mtu;
2296 port->mtu = dev_mtu;
2297 p->min_mtu = find_min_mtu(p);
2298 if (p->min_mtu == old_min) {
2302 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2303 struct netdev *netdev = ofport->netdev;
2305 if (!strcmp(netdev_get_type(netdev), "internal")) {
2306 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2307 ofport->mtu = p->min_mtu;
2314 ofproto_rule_destroy(struct rule *rule)
2317 rule->ofproto->ofproto_class->rule_destruct(rule);
2318 ofproto_rule_destroy__(rule);
2323 ofproto_rule_destroy__(struct rule *rule)
2325 cls_rule_destroy(&rule->cr);
2326 free(rule->ofpacts);
2327 ovs_mutex_destroy(&rule->timeout_mutex);
2328 ovs_rwlock_destroy(&rule->rwlock);
2329 rule->ofproto->ofproto_class->rule_dealloc(rule);
2332 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2333 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2335 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2337 return (port == OFPP_ANY
2338 || ofpacts_output_to_port(rule->ofpacts, rule->ofpacts_len, port));
2341 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2342 * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2344 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2346 if (ofproto_rule_has_out_port(op->rule, out_port)) {
2351 case OFOPERATION_ADD:
2352 case OFOPERATION_DELETE:
2355 case OFOPERATION_MODIFY:
2356 case OFOPERATION_REPLACE:
2357 return ofpacts_output_to_port(op->ofpacts, op->ofpacts_len, out_port);
2363 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2364 * statistics appropriately.
2366 * 'packet' doesn't necessarily have to match 'rule'. 'rule' will be credited
2367 * with statistics for 'packet' either way.
2369 * Takes ownership of 'packet'. */
2371 rule_execute(struct rule *rule, ofp_port_t in_port, struct ofpbuf *packet)
2374 union flow_in_port in_port_;
2376 in_port_.ofp_port = in_port;
2377 flow_extract(packet, 0, 0, NULL, &in_port_, &flow);
2378 return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
2381 /* Returns true if 'rule' should be hidden from the controller.
2383 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2384 * (e.g. by in-band control) and are intentionally hidden from the
2387 ofproto_rule_is_hidden(const struct rule *rule)
2389 return rule->cr.priority > UINT16_MAX;
2392 static enum oftable_flags
2393 rule_get_flags(const struct rule *rule)
2395 return rule->ofproto->tables[rule->table_id].flags;
2399 rule_is_modifiable(const struct rule *rule)
2401 return !(rule_get_flags(rule) & OFTABLE_READONLY);
2405 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2407 ofconn_send_reply(ofconn, make_echo_reply(oh));
2412 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2414 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2415 struct ofputil_switch_features features;
2416 struct ofport *port;
2422 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2424 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2426 /* Count only non-hidden tables in the number of tables. (Hidden tables,
2427 * if present, are always at the end.) */
2428 n_tables = ofproto->n_tables;
2429 for (i = 0; i < ofproto->n_tables; i++) {
2430 if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2436 features.datapath_id = ofproto->datapath_id;
2437 features.n_buffers = pktbuf_capacity();
2438 features.n_tables = n_tables;
2439 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2440 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2442 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2444 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2445 features.auxiliary_id = 0;
2446 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2448 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2449 ofputil_put_switch_features_port(&port->pp, b);
2452 ofconn_send_reply(ofconn, b);
2457 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2459 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2460 struct ofp_switch_config *osc;
2461 enum ofp_config_flags flags;
2465 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2466 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2467 flags = ofproto->frag_handling;
2468 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2469 if (oh->version < OFP13_VERSION
2470 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2471 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2473 osc->flags = htons(flags);
2474 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2475 ofconn_send_reply(ofconn, buf);
2481 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2483 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2484 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2485 uint16_t flags = ntohs(osc->flags);
2487 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2488 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2489 enum ofp_config_flags cur = ofproto->frag_handling;
2490 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2492 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2494 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2495 ofproto->frag_handling = next;
2497 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2499 ofputil_frag_handling_to_string(next));
2503 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2504 ofconn_set_invalid_ttl_to_controller(ofconn,
2505 (oh->version < OFP13_VERSION
2506 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2508 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2513 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2514 * error message code for the caller to propagate upward. Otherwise, returns
2517 * The log message mentions 'msg_type'. */
2519 reject_slave_controller(struct ofconn *ofconn)
2521 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2522 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2523 return OFPERR_OFPBRC_EPERM;
2529 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are appropriate
2530 * for a packet with the prerequisites satisfied by 'flow' in table 'table_id'.
2531 * 'flow' may be temporarily modified, but is restored at return.
2534 ofproto_check_ofpacts(struct ofproto *ofproto,
2535 const struct ofpact ofpacts[], size_t ofpacts_len,
2536 struct flow *flow, uint8_t table_id)
2541 error = ofpacts_check(ofpacts, ofpacts_len, flow,
2542 u16_to_ofp(ofproto->max_ports), table_id);
2547 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2548 if (mid && ofproto_get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2549 return OFPERR_OFPMMFC_INVALID_METER;
2555 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2557 struct ofproto *p = ofconn_get_ofproto(ofconn);
2558 struct ofputil_packet_out po;
2559 struct ofpbuf *payload;
2560 uint64_t ofpacts_stub[1024 / 8];
2561 struct ofpbuf ofpacts;
2563 union flow_in_port in_port_;
2566 COVERAGE_INC(ofproto_packet_out);
2568 error = reject_slave_controller(ofconn);
2573 /* Decode message. */
2574 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2575 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2577 goto exit_free_ofpacts;
2579 if (ofp_to_u16(po.in_port) >= p->max_ports
2580 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2581 error = OFPERR_OFPBRC_BAD_PORT;
2582 goto exit_free_ofpacts;
2587 if (po.buffer_id != UINT32_MAX) {
2588 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2589 if (error || !payload) {
2590 goto exit_free_ofpacts;
2593 /* Ensure that the L3 header is 32-bit aligned. */
2594 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2597 /* Verify actions against packet, then send packet if successful. */
2598 in_port_.ofp_port = po.in_port;
2599 flow_extract(payload, 0, 0, NULL, &in_port_, &flow);
2600 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len, &flow, 0);
2602 error = p->ofproto_class->packet_out(p, payload, &flow,
2603 po.ofpacts, po.ofpacts_len);
2605 ofpbuf_delete(payload);
2608 ofpbuf_uninit(&ofpacts);
2614 update_port_config(struct ofport *port,
2615 enum ofputil_port_config config,
2616 enum ofputil_port_config mask)
2618 enum ofputil_port_config old_config = port->pp.config;
2619 enum ofputil_port_config toggle;
2621 toggle = (config ^ port->pp.config) & mask;
2622 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2623 if (config & OFPUTIL_PC_PORT_DOWN) {
2624 netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2626 netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2628 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2631 port->pp.config ^= toggle;
2632 if (port->pp.config != old_config) {
2633 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2638 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2640 struct ofproto *p = ofconn_get_ofproto(ofconn);
2641 struct ofputil_port_mod pm;
2642 struct ofport *port;
2645 error = reject_slave_controller(ofconn);
2650 error = ofputil_decode_port_mod(oh, &pm);
2655 port = ofproto_get_port(p, pm.port_no);
2657 return OFPERR_OFPPMFC_BAD_PORT;
2658 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2659 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2661 update_port_config(port, pm.config, pm.mask);
2663 netdev_set_advertisements(port->netdev, pm.advertise);
2670 handle_desc_stats_request(struct ofconn *ofconn,
2671 const struct ofp_header *request)
2673 static const char *default_mfr_desc = "Nicira, Inc.";
2674 static const char *default_hw_desc = "Open vSwitch";
2675 static const char *default_sw_desc = VERSION;
2676 static const char *default_serial_desc = "None";
2677 static const char *default_dp_desc = "None";
2679 struct ofproto *p = ofconn_get_ofproto(ofconn);
2680 struct ofp_desc_stats *ods;
2683 msg = ofpraw_alloc_stats_reply(request, 0);
2684 ods = ofpbuf_put_zeros(msg, sizeof *ods);
2685 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
2686 sizeof ods->mfr_desc);
2687 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
2688 sizeof ods->hw_desc);
2689 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
2690 sizeof ods->sw_desc);
2691 ovs_strlcpy(ods->serial_num,
2692 p->serial_desc ? p->serial_desc : default_serial_desc,
2693 sizeof ods->serial_num);
2694 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
2695 sizeof ods->dp_desc);
2696 ofconn_send_reply(ofconn, msg);
2702 handle_table_stats_request(struct ofconn *ofconn,
2703 const struct ofp_header *request)
2705 struct ofproto *p = ofconn_get_ofproto(ofconn);
2706 struct ofp12_table_stats *ots;
2711 /* Set up default values.
2713 * ofp12_table_stats is used as a generic structure as
2714 * it is able to hold all the fields for ofp10_table_stats
2715 * and ofp11_table_stats (and of course itself).
2717 ots = xcalloc(p->n_tables, sizeof *ots);
2718 for (i = 0; i < p->n_tables; i++) {
2719 ots[i].table_id = i;
2720 sprintf(ots[i].name, "table%zu", i);
2721 ots[i].match = htonll(OFPXMT12_MASK);
2722 ots[i].wildcards = htonll(OFPXMT12_MASK);
2723 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
2724 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
2725 ots[i].write_setfields = htonll(OFPXMT12_MASK);
2726 ots[i].apply_setfields = htonll(OFPXMT12_MASK);
2727 ots[i].metadata_match = htonll(UINT64_MAX);
2728 ots[i].metadata_write = htonll(UINT64_MAX);
2729 ots[i].instructions = htonl(OFPIT11_ALL);
2730 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
2731 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2732 ovs_rwlock_rdlock(&p->tables[i].cls.rwlock);
2733 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2734 ovs_rwlock_unlock(&p->tables[i].cls.rwlock);
2737 p->ofproto_class->get_tables(p, ots);
2739 /* Post-process the tables, dropping hidden tables. */
2740 n_tables = p->n_tables;
2741 for (i = 0; i < p->n_tables; i++) {
2742 const struct oftable *table = &p->tables[i];
2744 if (table->flags & OFTABLE_HIDDEN) {
2750 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2753 if (table->max_flows < ntohl(ots[i].max_entries)) {
2754 ots[i].max_entries = htonl(table->max_flows);
2758 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
2759 ofconn_send_reply(ofconn, msg);
2767 append_port_stat(struct ofport *port, struct list *replies)
2769 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
2771 calc_duration(port->created, time_msec(),
2772 &ops.duration_sec, &ops.duration_nsec);
2774 /* Intentionally ignore return value, since errors will set
2775 * 'stats' to all-1s, which is correct for OpenFlow, and
2776 * netdev_get_stats() will log errors. */
2777 ofproto_port_get_stats(port, &ops.stats);
2779 ofputil_append_port_stat(replies, &ops);
2783 handle_port_stats_request(struct ofconn *ofconn,
2784 const struct ofp_header *request)
2786 struct ofproto *p = ofconn_get_ofproto(ofconn);
2787 struct ofport *port;
2788 struct list replies;
2792 error = ofputil_decode_port_stats_request(request, &port_no);
2797 ofpmp_init(&replies, request);
2798 if (port_no != OFPP_ANY) {
2799 port = ofproto_get_port(p, port_no);
2801 append_port_stat(port, &replies);
2804 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2805 append_port_stat(port, &replies);
2809 ofconn_send_replies(ofconn, &replies);
2814 handle_port_desc_stats_request(struct ofconn *ofconn,
2815 const struct ofp_header *request)
2817 struct ofproto *p = ofconn_get_ofproto(ofconn);
2818 enum ofp_version version;
2819 struct ofport *port;
2820 struct list replies;
2822 ofpmp_init(&replies, request);
2824 version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
2825 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2826 ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
2829 ofconn_send_replies(ofconn, &replies);
2834 hash_cookie(ovs_be64 cookie)
2836 return hash_2words((OVS_FORCE uint64_t)cookie >> 32,
2837 (OVS_FORCE uint64_t)cookie);
2841 cookies_insert(struct ofproto *ofproto, struct rule *rule)
2843 hindex_insert(&ofproto->cookies, &rule->cookie_node,
2844 hash_cookie(rule->flow_cookie));
2848 cookies_remove(struct ofproto *ofproto, struct rule *rule)
2850 hindex_remove(&ofproto->cookies, &rule->cookie_node);
2854 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
2855 ovs_be64 new_cookie)
2857 if (new_cookie != rule->flow_cookie) {
2858 cookies_remove(ofproto, rule);
2860 ovs_rwlock_wrlock(&rule->rwlock);
2861 rule->flow_cookie = new_cookie;
2862 ovs_rwlock_unlock(&rule->rwlock);
2864 cookies_insert(ofproto, rule);
2869 calc_duration(long long int start, long long int now,
2870 uint32_t *sec, uint32_t *nsec)
2872 long long int msecs = now - start;
2873 *sec = msecs / 1000;
2874 *nsec = (msecs % 1000) * (1000 * 1000);
2877 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
2878 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
2880 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2882 return (table_id == 0xff || table_id < ofproto->n_tables
2884 : OFPERR_OFPBRC_BAD_TABLE_ID);
2888 static struct oftable *
2889 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
2891 struct oftable *table;
2893 for (table = &ofproto->tables[table_id];
2894 table < &ofproto->tables[ofproto->n_tables];
2896 if (!(table->flags & OFTABLE_HIDDEN)) {
2904 static struct oftable *
2905 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
2907 if (table_id == 0xff) {
2908 return next_visible_table(ofproto, 0);
2909 } else if (table_id < ofproto->n_tables) {
2910 return &ofproto->tables[table_id];
2916 static struct oftable *
2917 next_matching_table(const struct ofproto *ofproto,
2918 const struct oftable *table, uint8_t table_id)
2920 return (table_id == 0xff
2921 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
2925 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
2927 * - If TABLE_ID is 0xff, this iterates over every classifier table in
2928 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
2930 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
2931 * only once, for that table. (This can be used to access tables marked
2934 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
2935 * entered at all. (Perhaps you should have validated TABLE_ID with
2936 * check_table_id().)
2938 * All parameters are evaluated multiple times.
2940 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
2941 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
2943 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
2945 /* Initializes 'criteria' in a straightforward way based on the other
2948 * For "loose" matching, the 'priority' parameter is unimportant and may be
2951 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
2952 const struct match *match, unsigned int priority,
2953 ovs_be64 cookie, ovs_be64 cookie_mask,
2954 ofp_port_t out_port)
2956 criteria->table_id = table_id;
2957 cls_rule_init(&criteria->cr, match, priority);
2958 criteria->cookie = cookie;
2959 criteria->cookie_mask = cookie_mask;
2960 criteria->out_port = out_port;
2964 rule_criteria_destroy(struct rule_criteria *criteria)
2966 cls_rule_destroy(&criteria->cr);
2970 rule_collection_init(struct rule_collection *rules)
2972 rules->rules = rules->stub;
2974 rules->capacity = ARRAY_SIZE(rules->stub);
2978 rule_collection_add(struct rule_collection *rules, struct rule *rule)
2980 if (rules->n >= rules->capacity) {
2981 size_t old_size, new_size;
2983 old_size = rules->capacity * sizeof *rules->rules;
2984 rules->capacity *= 2;
2985 new_size = rules->capacity * sizeof *rules->rules;
2987 if (rules->rules == rules->stub) {
2988 rules->rules = xmalloc(new_size);
2989 memcpy(rules->rules, rules->stub, old_size);
2991 rules->rules = xrealloc(rules->rules, new_size);
2995 rules->rules[rules->n++] = rule;
2999 rule_collection_destroy(struct rule_collection *rules)
3001 if (rules->rules != rules->stub) {
3007 collect_rule(struct rule *rule, const struct rule_criteria *c,
3008 struct rule_collection *rules)
3010 if (ofproto_rule_is_hidden(rule)) {
3012 } else if (rule->pending) {
3013 return OFPROTO_POSTPONE;
3015 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3016 && ofproto_rule_has_out_port(rule, c->out_port)
3017 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3018 rule_collection_add(rules, rule);
3024 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3025 * on classifiers rules are done in the "loose" way required for OpenFlow
3026 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3029 * Hidden rules are always omitted.
3031 * Returns 0 on success, otherwise an OpenFlow error code. */
3033 collect_rules_loose(struct ofproto *ofproto,
3034 const struct rule_criteria *criteria,
3035 struct rule_collection *rules)
3037 struct oftable *table;
3040 rule_collection_init(rules);
3042 error = check_table_id(ofproto, criteria->table_id);
3047 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3050 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3051 hash_cookie(criteria->cookie),
3052 &ofproto->cookies) {
3053 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3054 error = collect_rule(rule, criteria, rules);
3061 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3062 struct cls_cursor cursor;
3065 ovs_rwlock_rdlock(&table->cls.rwlock);
3066 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3067 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3068 error = collect_rule(rule, criteria, rules);
3073 ovs_rwlock_unlock(&table->cls.rwlock);
3079 rule_collection_destroy(rules);
3084 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3085 * on classifiers rules are done in the "strict" way required for OpenFlow
3086 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3087 * rules on list 'rules'.
3089 * Hidden rules are always omitted.
3091 * Returns 0 on success, otherwise an OpenFlow error code. */
3093 collect_rules_strict(struct ofproto *ofproto,
3094 const struct rule_criteria *criteria,
3095 struct rule_collection *rules)
3097 struct oftable *table;
3100 rule_collection_init(rules);
3102 error = check_table_id(ofproto, criteria->table_id);
3107 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3110 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3111 hash_cookie(criteria->cookie),
3112 &ofproto->cookies) {
3113 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3114 error = collect_rule(rule, criteria, rules);
3121 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3124 ovs_rwlock_rdlock(&table->cls.rwlock);
3125 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3126 &table->cls, &criteria->cr));
3127 ovs_rwlock_unlock(&table->cls.rwlock);
3129 error = collect_rule(rule, criteria, rules);
3139 rule_collection_destroy(rules);
3144 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3145 * forced into the range of a uint16_t. */
3147 age_secs(long long int age_ms)
3149 return (age_ms < 0 ? 0
3150 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3151 : (unsigned int) age_ms / 1000);
3155 handle_flow_stats_request(struct ofconn *ofconn,
3156 const struct ofp_header *request)
3158 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3159 struct ofputil_flow_stats_request fsr;
3160 struct rule_criteria criteria;
3161 struct rule_collection rules;
3162 struct list replies;
3166 error = ofputil_decode_flow_stats_request(&fsr, request);
3171 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3172 fsr.cookie_mask, fsr.out_port);
3173 error = collect_rules_loose(ofproto, &criteria, &rules);
3174 rule_criteria_destroy(&criteria);
3179 ofpmp_init(&replies, request);
3180 for (i = 0; i < rules.n; i++) {
3181 struct rule *rule = rules.rules[i];
3182 long long int now = time_msec();
3183 struct ofputil_flow_stats fs;
3185 minimatch_expand(&rule->cr.match, &fs.match);
3186 fs.priority = rule->cr.priority;
3187 fs.cookie = rule->flow_cookie;
3188 fs.table_id = rule->table_id;
3189 calc_duration(rule->created, now, &fs.duration_sec, &fs.duration_nsec);
3190 fs.idle_age = age_secs(now - rule->used);
3191 fs.hard_age = age_secs(now - rule->modified);
3192 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3194 fs.ofpacts = rule->ofpacts;
3195 fs.ofpacts_len = rule->ofpacts_len;
3197 ovs_mutex_lock(&rule->timeout_mutex);
3198 fs.idle_timeout = rule->idle_timeout;
3199 fs.hard_timeout = rule->hard_timeout;
3200 ovs_mutex_unlock(&rule->timeout_mutex);
3203 if (rule->send_flow_removed) {
3204 fs.flags |= OFPUTIL_FF_SEND_FLOW_REM;
3205 /* FIXME: Implement OFPUTIL_FF_NO_PKT_COUNTS and
3206 OFPUTIL_FF_NO_BYT_COUNTS. */
3208 ofputil_append_flow_stats_reply(&fs, &replies);
3210 rule_collection_destroy(&rules);
3212 ofconn_send_replies(ofconn, &replies);
3218 flow_stats_ds(struct rule *rule, struct ds *results)
3220 uint64_t packet_count, byte_count;
3222 rule->ofproto->ofproto_class->rule_get_stats(rule,
3223 &packet_count, &byte_count);
3225 if (rule->table_id != 0) {
3226 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3228 ds_put_format(results, "duration=%llds, ",
3229 (time_msec() - rule->created) / 1000);
3230 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3231 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3232 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3233 cls_rule_format(&rule->cr, results);
3234 ds_put_char(results, ',');
3235 ofpacts_format(rule->ofpacts, rule->ofpacts_len, results);
3236 ds_put_cstr(results, "\n");
3239 /* Adds a pretty-printed description of all flows to 'results', including
3240 * hidden flows (e.g., set up by in-band control). */
3242 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3244 struct oftable *table;
3246 OFPROTO_FOR_EACH_TABLE (table, p) {
3247 struct cls_cursor cursor;
3250 ovs_rwlock_rdlock(&table->cls.rwlock);
3251 cls_cursor_init(&cursor, &table->cls, NULL);
3252 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3253 flow_stats_ds(rule, results);
3255 ovs_rwlock_unlock(&table->cls.rwlock);
3259 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3260 * '*engine_type' and '*engine_id', respectively. */
3262 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3263 uint8_t *engine_type, uint8_t *engine_id)
3265 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3268 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3269 * true if the port's CFM status was successfully stored into '*status'.
3270 * Returns false if the port did not have CFM configured, in which case
3271 * '*status' is indeterminate.
3273 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3275 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3276 struct ofproto_cfm_status *status)
3278 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3280 && ofproto->ofproto_class->get_cfm_status
3281 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3285 handle_aggregate_stats_request(struct ofconn *ofconn,
3286 const struct ofp_header *oh)
3288 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3289 struct ofputil_flow_stats_request request;
3290 struct ofputil_aggregate_stats stats;
3291 bool unknown_packets, unknown_bytes;
3292 struct rule_criteria criteria;
3293 struct rule_collection rules;
3294 struct ofpbuf *reply;
3298 error = ofputil_decode_flow_stats_request(&request, oh);
3303 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3304 request.cookie, request.cookie_mask,
3306 error = collect_rules_loose(ofproto, &criteria, &rules);
3307 rule_criteria_destroy(&criteria);
3312 memset(&stats, 0, sizeof stats);
3313 unknown_packets = unknown_bytes = false;
3314 for (i = 0; i < rules.n; i++) {
3315 struct rule *rule = rules.rules[i];
3316 uint64_t packet_count;
3317 uint64_t byte_count;
3319 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3322 if (packet_count == UINT64_MAX) {
3323 unknown_packets = true;
3325 stats.packet_count += packet_count;
3328 if (byte_count == UINT64_MAX) {
3329 unknown_bytes = true;
3331 stats.byte_count += byte_count;
3336 if (unknown_packets) {
3337 stats.packet_count = UINT64_MAX;
3339 if (unknown_bytes) {
3340 stats.byte_count = UINT64_MAX;
3343 rule_collection_destroy(&rules);
3345 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3346 ofconn_send_reply(ofconn, reply);
3351 struct queue_stats_cbdata {
3352 struct ofport *ofport;
3353 struct list replies;
3358 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3359 const struct netdev_queue_stats *stats)
3361 struct ofputil_queue_stats oqs;
3363 oqs.port_no = cbdata->ofport->pp.port_no;
3364 oqs.queue_id = queue_id;
3365 oqs.tx_bytes = stats->tx_bytes;
3366 oqs.tx_packets = stats->tx_packets;
3367 oqs.tx_errors = stats->tx_errors;
3368 if (stats->created != LLONG_MIN) {
3369 calc_duration(stats->created, cbdata->now,
3370 &oqs.duration_sec, &oqs.duration_nsec);
3372 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3374 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3378 handle_queue_stats_dump_cb(uint32_t queue_id,
3379 struct netdev_queue_stats *stats,
3382 struct queue_stats_cbdata *cbdata = cbdata_;
3384 put_queue_stats(cbdata, queue_id, stats);
3388 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3389 struct queue_stats_cbdata *cbdata)
3391 cbdata->ofport = port;
3392 if (queue_id == OFPQ_ALL) {
3393 netdev_dump_queue_stats(port->netdev,
3394 handle_queue_stats_dump_cb, cbdata);
3396 struct netdev_queue_stats stats;
3398 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3399 put_queue_stats(cbdata, queue_id, &stats);
3401 return OFPERR_OFPQOFC_BAD_QUEUE;
3408 handle_queue_stats_request(struct ofconn *ofconn,
3409 const struct ofp_header *rq)
3411 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3412 struct queue_stats_cbdata cbdata;
3413 struct ofport *port;
3415 struct ofputil_queue_stats_request oqsr;
3417 COVERAGE_INC(ofproto_queue_req);
3419 ofpmp_init(&cbdata.replies, rq);
3420 cbdata.now = time_msec();
3422 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3427 if (oqsr.port_no == OFPP_ANY) {
3428 error = OFPERR_OFPQOFC_BAD_QUEUE;
3429 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3430 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3435 port = ofproto_get_port(ofproto, oqsr.port_no);
3437 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3438 : OFPERR_OFPQOFC_BAD_PORT);
3441 ofconn_send_replies(ofconn, &cbdata.replies);
3443 ofpbuf_list_delete(&cbdata.replies);
3450 is_flow_deletion_pending(const struct ofproto *ofproto,
3451 const struct cls_rule *cls_rule,
3454 if (!hmap_is_empty(&ofproto->deletions)) {
3455 struct ofoperation *op;
3457 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3458 cls_rule_hash(cls_rule, table_id),
3459 &ofproto->deletions) {
3460 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3470 evict_rule_from_table(struct ofproto *ofproto, struct oftable *table)
3475 ovs_rwlock_rdlock(&table->cls.rwlock);
3476 n_rules = classifier_count(&table->cls);
3477 ovs_rwlock_unlock(&table->cls.rwlock);
3479 if (n_rules < table->max_flows) {
3481 } else if (!choose_rule_to_evict(table, &rule)) {
3482 return OFPERR_OFPFMFC_TABLE_FULL;
3483 } else if (rule->pending) {
3484 ovs_rwlock_unlock(&rule->rwlock);
3485 return OFPROTO_POSTPONE;
3487 struct ofopgroup *group;
3489 group = ofopgroup_create_unattached(ofproto);
3490 delete_flow__(rule, group, OFPRR_EVICTION);
3491 ofopgroup_submit(group);
3497 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3498 * in which no matching flow already exists in the flow table.
3500 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3501 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3502 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3503 * initiated now but may be retried later.
3505 * The caller retains ownership of 'fm->ofpacts'.
3507 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3510 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3511 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3513 struct oftable *table;
3514 struct ofopgroup *group;
3520 error = check_table_id(ofproto, fm->table_id);
3526 if (fm->table_id == 0xff) {
3527 if (ofproto->ofproto_class->rule_choose_table) {
3528 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3534 ovs_assert(table_id < ofproto->n_tables);
3538 } else if (fm->table_id < ofproto->n_tables) {
3539 table_id = fm->table_id;
3541 return OFPERR_OFPBRC_BAD_TABLE_ID;
3544 table = &ofproto->tables[table_id];
3546 if (table->flags & OFTABLE_READONLY) {
3547 return OFPERR_OFPBRC_EPERM;
3550 cls_rule_init(&cr, &fm->match, fm->priority);
3552 /* Transform "add" into "modify" if there's an existing identical flow. */
3553 ovs_rwlock_rdlock(&table->cls.rwlock);
3554 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3555 ovs_rwlock_unlock(&table->cls.rwlock);
3557 cls_rule_destroy(&cr);
3558 if (!rule_is_modifiable(rule)) {
3559 return OFPERR_OFPBRC_EPERM;
3560 } else if (rule->pending) {
3561 return OFPROTO_POSTPONE;
3563 struct rule_collection rules;
3565 rule_collection_init(&rules);
3566 rule_collection_add(&rules, rule);
3567 fm->modify_cookie = true;
3568 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3569 rule_collection_destroy(&rules);
3575 /* Verify actions. */
3576 error = ofproto_check_ofpacts(ofproto, fm->ofpacts, fm->ofpacts_len,
3577 &fm->match.flow, table_id);
3579 cls_rule_destroy(&cr);
3583 /* Serialize against pending deletion. */
3584 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3585 cls_rule_destroy(&cr);
3586 return OFPROTO_POSTPONE;
3589 /* Check for overlap, if requested. */
3590 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3593 ovs_rwlock_rdlock(&table->cls.rwlock);
3594 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3595 ovs_rwlock_unlock(&table->cls.rwlock);
3598 cls_rule_destroy(&cr);
3599 return OFPERR_OFPFMFC_OVERLAP;
3603 /* If necessary, evict an existing rule to clear out space. */
3604 error = evict_rule_from_table(ofproto, table);
3606 cls_rule_destroy(&cr);
3610 /* Allocate new rule. */
3611 rule = ofproto->ofproto_class->rule_alloc();
3613 cls_rule_destroy(&cr);
3614 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3615 ofproto->name, ovs_strerror(error));
3619 /* Initialize base state. */
3620 rule->ofproto = ofproto;
3621 cls_rule_move(&rule->cr, &cr);
3622 rule->pending = NULL;
3623 rule->flow_cookie = fm->new_cookie;
3624 rule->created = rule->modified = rule->used = time_msec();
3626 ovs_mutex_init(&rule->timeout_mutex);
3627 ovs_mutex_lock(&rule->timeout_mutex);
3628 rule->idle_timeout = fm->idle_timeout;
3629 rule->hard_timeout = fm->hard_timeout;
3630 ovs_mutex_unlock(&rule->timeout_mutex);
3632 rule->table_id = table - ofproto->tables;
3633 rule->send_flow_removed = (fm->flags & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3634 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3635 rule->ofpacts_len = fm->ofpacts_len;
3636 rule->meter_id = ofpacts_get_meter(rule->ofpacts, rule->ofpacts_len);
3637 list_init(&rule->meter_list_node);
3638 rule->eviction_group = NULL;
3639 list_init(&rule->expirable);
3640 rule->monitor_flags = 0;
3641 rule->add_seqno = 0;
3642 rule->modify_seqno = 0;
3643 ovs_rwlock_init(&rule->rwlock);
3645 /* Construct rule, initializing derived state. */
3646 error = ofproto->ofproto_class->rule_construct(rule);
3648 ofproto_rule_destroy__(rule);
3653 oftable_insert_rule(rule);
3655 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3656 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
3657 ofproto->ofproto_class->rule_insert(rule);
3658 ofopgroup_submit(group);
3663 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3665 /* Modifies the rules listed in 'rules', changing their actions to match those
3668 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3671 * Returns 0 on success, otherwise an OpenFlow error code. */
3673 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3674 struct ofputil_flow_mod *fm, const struct ofp_header *request,
3675 const struct rule_collection *rules)
3677 enum ofoperation_type type;
3678 struct ofopgroup *group;
3682 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
3683 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3684 error = OFPERR_OFPBRC_EPERM;
3685 for (i = 0; i < rules->n; i++) {
3686 struct rule *rule = rules->rules[i];
3687 struct ofoperation *op;
3688 bool actions_changed;
3689 bool reset_counters;
3691 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
3693 if (rule_is_modifiable(rule)) {
3694 /* At least one rule is modifiable, don't report EPERM error. */
3700 /* Verify actions. */
3701 error = ofpacts_check(fm->ofpacts, fm->ofpacts_len, &fm->match.flow,
3702 u16_to_ofp(ofproto->max_ports), rule->table_id);
3707 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
3708 rule->ofpacts, rule->ofpacts_len);
3710 op = ofoperation_create(group, rule, type, 0);
3712 if (fm->modify_cookie && fm->new_cookie != htonll(UINT64_MAX)) {
3713 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
3715 if (type == OFOPERATION_REPLACE) {
3716 ovs_mutex_lock(&rule->timeout_mutex);
3717 rule->idle_timeout = fm->idle_timeout;
3718 rule->hard_timeout = fm->hard_timeout;
3719 ovs_mutex_unlock(&rule->timeout_mutex);
3721 rule->send_flow_removed = (fm->flags
3722 & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3724 if (fm->idle_timeout || fm->hard_timeout) {
3725 if (!rule->eviction_group) {
3726 eviction_group_add_rule(rule);
3729 eviction_group_remove_rule(rule);
3733 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
3734 if (actions_changed || reset_counters) {
3735 op->ofpacts = rule->ofpacts;
3736 op->ofpacts_len = rule->ofpacts_len;
3737 op->meter_id = rule->meter_id;
3739 ovs_rwlock_wrlock(&rule->rwlock);
3740 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3741 rule->ofpacts_len = fm->ofpacts_len;
3742 ovs_rwlock_unlock(&rule->rwlock);
3744 rule->meter_id = ofpacts_get_meter(rule->ofpacts,
3746 rule->ofproto->ofproto_class->rule_modify_actions(rule,
3749 ofoperation_complete(op, 0);
3752 ofopgroup_submit(group);
3758 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
3759 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3761 if (fm->cookie_mask != htonll(0) || fm->new_cookie == htonll(UINT64_MAX)) {
3764 return add_flow(ofproto, ofconn, fm, request);
3767 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
3770 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3773 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3774 struct ofputil_flow_mod *fm,
3775 const struct ofp_header *request)
3777 struct rule_criteria criteria;
3778 struct rule_collection rules;
3781 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
3782 fm->cookie, fm->cookie_mask, OFPP_ANY);
3783 error = collect_rules_loose(ofproto, &criteria, &rules);
3784 rule_criteria_destroy(&criteria);
3787 error = (rules.n > 0
3788 ? modify_flows__(ofproto, ofconn, fm, request, &rules)
3789 : modify_flows_add(ofproto, ofconn, fm, request));
3792 rule_collection_destroy(&rules);
3797 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
3800 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3803 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3804 struct ofputil_flow_mod *fm,
3805 const struct ofp_header *request)
3807 struct rule_criteria criteria;
3808 struct rule_collection rules;
3811 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
3812 fm->cookie, fm->cookie_mask, OFPP_ANY);
3813 error = collect_rules_strict(ofproto, &criteria, &rules);
3814 rule_criteria_destroy(&criteria);
3818 error = modify_flows_add(ofproto, ofconn, fm, request);
3819 } else if (rules.n == 1) {
3820 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3824 rule_collection_destroy(&rules);
3829 /* OFPFC_DELETE implementation. */
3832 delete_flow__(struct rule *rule, struct ofopgroup *group,
3833 enum ofp_flow_removed_reason reason)
3835 struct ofproto *ofproto = rule->ofproto;
3837 ofproto_rule_send_removed(rule, reason);
3839 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
3840 oftable_remove_rule(rule);
3841 ofproto->ofproto_class->rule_delete(rule);
3844 /* Deletes the rules listed in 'rules'.
3846 * Returns 0 on success, otherwise an OpenFlow error code. */
3848 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3849 const struct ofp_header *request,
3850 const struct rule_collection *rules,
3851 enum ofp_flow_removed_reason reason)
3853 struct ofopgroup *group;
3856 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3857 for (i = 0; i < rules->n; i++) {
3858 struct rule *rule = rules->rules[i];
3859 ovs_rwlock_wrlock(&rule->rwlock);
3860 delete_flow__(rule, group, reason);
3862 ofopgroup_submit(group);
3867 /* Implements OFPFC_DELETE. */
3869 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3870 const struct ofputil_flow_mod *fm,
3871 const struct ofp_header *request)
3873 struct rule_criteria criteria;
3874 struct rule_collection rules;
3877 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
3878 fm->cookie, fm->cookie_mask,
3880 error = collect_rules_loose(ofproto, &criteria, &rules);
3881 rule_criteria_destroy(&criteria);
3883 if (!error && rules.n > 0) {
3884 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
3886 rule_collection_destroy(&rules);
3891 /* Implements OFPFC_DELETE_STRICT. */
3893 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3894 const struct ofputil_flow_mod *fm,
3895 const struct ofp_header *request)
3897 struct rule_criteria criteria;
3898 struct rule_collection rules;
3901 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
3902 fm->cookie, fm->cookie_mask, fm->out_port);
3903 error = collect_rules_strict(ofproto, &criteria, &rules);
3904 rule_criteria_destroy(&criteria);
3906 if (!error && rules.n > 0) {
3907 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
3909 rule_collection_destroy(&rules);
3915 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
3917 struct ofputil_flow_removed fr;
3919 if (ofproto_rule_is_hidden(rule) || !rule->send_flow_removed) {
3923 minimatch_expand(&rule->cr.match, &fr.match);
3924 fr.priority = rule->cr.priority;
3925 fr.cookie = rule->flow_cookie;
3927 fr.table_id = rule->table_id;
3928 calc_duration(rule->created, time_msec(),
3929 &fr.duration_sec, &fr.duration_nsec);
3930 ovs_mutex_lock(&rule->timeout_mutex);
3931 fr.idle_timeout = rule->idle_timeout;
3932 fr.hard_timeout = rule->hard_timeout;
3933 ovs_mutex_unlock(&rule->timeout_mutex);
3934 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
3937 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
3940 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
3941 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
3944 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
3947 * ofproto implementation ->run() functions should use this function to expire
3948 * OpenFlow flows. */
3950 ofproto_rule_expire(struct rule *rule, uint8_t reason)
3952 struct ofproto *ofproto = rule->ofproto;
3953 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
3955 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
3956 ofproto_rule_send_removed(rule, reason);
3958 ovs_rwlock_wrlock(&cls->rwlock);
3959 ofproto_rule_delete(ofproto, cls, rule);
3960 ovs_rwlock_unlock(&cls->rwlock);
3963 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
3964 * means "infinite". */
3966 reduce_timeout(uint16_t max, uint16_t *timeout)
3968 if (max && (!*timeout || *timeout > max)) {
3973 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
3974 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
3975 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
3977 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
3979 ofproto_rule_reduce_timeouts(struct rule *rule,
3980 uint16_t idle_timeout, uint16_t hard_timeout)
3981 OVS_EXCLUDED(rule->ofproto->expirable_mutex, rule->timeout_mutex)
3983 if (!idle_timeout && !hard_timeout) {
3987 ovs_mutex_lock(&rule->ofproto->expirable_mutex);
3988 if (list_is_empty(&rule->expirable)) {
3989 list_insert(&rule->ofproto->expirable, &rule->expirable);
3991 ovs_mutex_unlock(&rule->ofproto->expirable_mutex);
3993 ovs_mutex_lock(&rule->timeout_mutex);
3994 reduce_timeout(idle_timeout, &rule->idle_timeout);
3995 reduce_timeout(hard_timeout, &rule->hard_timeout);
3996 ovs_mutex_unlock(&rule->timeout_mutex);
4000 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4002 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4003 struct ofputil_flow_mod fm;
4004 uint64_t ofpacts_stub[1024 / 8];
4005 struct ofpbuf ofpacts;
4009 error = reject_slave_controller(ofconn);
4014 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4015 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4018 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4021 goto exit_free_ofpacts;
4024 /* Record the operation for logging a summary report. */
4025 switch (fm.command) {
4031 case OFPFC_MODIFY_STRICT:
4032 ofproto->n_modify++;
4036 case OFPFC_DELETE_STRICT:
4037 ofproto->n_delete++;
4042 if (ofproto->next_op_report == LLONG_MAX) {
4043 ofproto->first_op = now;
4044 ofproto->next_op_report = MAX(now + 10 * 1000,
4045 ofproto->op_backoff);
4046 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4048 ofproto->last_op = now;
4051 ofpbuf_uninit(&ofpacts);
4057 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4058 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4060 if (ofproto->n_pending >= 50) {
4061 ovs_assert(!list_is_empty(&ofproto->pending));
4062 return OFPROTO_POSTPONE;
4065 switch (fm->command) {
4067 return add_flow(ofproto, ofconn, fm, oh);
4070 return modify_flows_loose(ofproto, ofconn, fm, oh);
4072 case OFPFC_MODIFY_STRICT:
4073 return modify_flow_strict(ofproto, ofconn, fm, oh);
4076 return delete_flows_loose(ofproto, ofconn, fm, oh);
4078 case OFPFC_DELETE_STRICT:
4079 return delete_flow_strict(ofproto, ofconn, fm, oh);
4082 if (fm->command > 0xff) {
4083 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4084 "flow_mod_table_id extension is not enabled",
4087 return OFPERR_OFPFMFC_BAD_COMMAND;
4092 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4094 struct ofputil_role_request request;
4095 struct ofputil_role_request reply;
4099 error = ofputil_decode_role_message(oh, &request);
4104 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4105 if (ofconn_get_role(ofconn) != request.role
4106 && ofconn_has_pending_opgroups(ofconn)) {
4107 return OFPROTO_POSTPONE;
4110 if (request.have_generation_id
4111 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4112 return OFPERR_OFPRRFC_STALE;
4115 ofconn_set_role(ofconn, request.role);
4118 reply.role = ofconn_get_role(ofconn);
4119 reply.have_generation_id = ofconn_get_master_election_id(
4120 ofconn, &reply.generation_id);
4121 buf = ofputil_encode_role_reply(oh, &reply);
4122 ofconn_send_reply(ofconn, buf);
4128 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4129 const struct ofp_header *oh)
4131 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4132 enum ofputil_protocol cur, next;
4134 cur = ofconn_get_protocol(ofconn);
4135 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4136 ofconn_set_protocol(ofconn, next);
4142 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4144 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4145 enum ofputil_protocol cur, next;
4146 enum ofputil_protocol next_base;
4148 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4150 return OFPERR_OFPBRC_EPERM;
4153 cur = ofconn_get_protocol(ofconn);
4154 next = ofputil_protocol_set_base(cur, next_base);
4155 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4156 /* Avoid sending async messages in surprising protocol. */
4157 return OFPROTO_POSTPONE;
4160 ofconn_set_protocol(ofconn, next);
4165 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4166 const struct ofp_header *oh)
4168 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4171 format = ntohl(msg->format);
4172 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4173 return OFPERR_OFPBRC_EPERM;
4176 if (format != ofconn_get_packet_in_format(ofconn)
4177 && ofconn_has_pending_opgroups(ofconn)) {
4178 /* Avoid sending async message in surprsing packet in format. */
4179 return OFPROTO_POSTPONE;
4182 ofconn_set_packet_in_format(ofconn, format);
4187 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4189 const struct nx_async_config *msg = ofpmsg_body(oh);
4190 uint32_t master[OAM_N_TYPES];
4191 uint32_t slave[OAM_N_TYPES];
4193 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4194 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4195 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4197 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4198 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4199 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4201 ofconn_set_async_config(ofconn, master, slave);
4202 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4203 !ofconn_get_miss_send_len(ofconn)) {
4204 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4211 handle_nxt_set_controller_id(struct ofconn *ofconn,
4212 const struct ofp_header *oh)
4214 const struct nx_controller_id *nci = ofpmsg_body(oh);
4216 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4217 return OFPERR_NXBRC_MUST_BE_ZERO;
4220 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4225 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4229 if (ofconn_has_pending_opgroups(ofconn)) {
4230 return OFPROTO_POSTPONE;
4233 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4234 ? OFPRAW_OFPT10_BARRIER_REPLY
4235 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4236 ofconn_send_reply(ofconn, buf);
4241 ofproto_compose_flow_refresh_update(const struct rule *rule,
4242 enum nx_flow_monitor_flags flags,
4245 struct ofoperation *op = rule->pending;
4246 struct ofputil_flow_update fu;
4249 if (op && op->type == OFOPERATION_ADD) {
4250 /* We'll report the final flow when the operation completes. Reporting
4251 * it now would cause a duplicate report later. */
4255 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4256 ? NXFME_ADDED : NXFME_MODIFIED);
4258 ovs_mutex_lock(&rule->timeout_mutex);
4259 fu.idle_timeout = rule->idle_timeout;
4260 fu.hard_timeout = rule->hard_timeout;
4261 ovs_mutex_unlock(&rule->timeout_mutex);
4262 fu.table_id = rule->table_id;
4263 fu.cookie = rule->flow_cookie;
4264 minimatch_expand(&rule->cr.match, &match);
4266 fu.priority = rule->cr.priority;
4267 if (!(flags & NXFMF_ACTIONS)) {
4271 fu.ofpacts = rule->ofpacts;
4272 fu.ofpacts_len = rule->ofpacts_len;
4274 /* An operation is in progress. Use the previous version of the flow's
4275 * actions, so that when the operation commits we report the change. */
4277 case OFOPERATION_ADD:
4280 case OFOPERATION_MODIFY:
4281 case OFOPERATION_REPLACE:
4283 fu.ofpacts = op->ofpacts;
4284 fu.ofpacts_len = op->ofpacts_len;
4286 fu.ofpacts = rule->ofpacts;
4287 fu.ofpacts_len = rule->ofpacts_len;
4291 case OFOPERATION_DELETE:
4292 fu.ofpacts = rule->ofpacts;
4293 fu.ofpacts_len = rule->ofpacts_len;
4301 if (list_is_empty(msgs)) {
4302 ofputil_start_flow_update(msgs);
4304 ofputil_append_flow_update(&fu, msgs);
4308 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4313 for (i = 0; i < rules->n; i++) {
4314 struct rule *rule = rules->rules[i];
4315 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4316 rule->monitor_flags = 0;
4318 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4323 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4324 struct rule *rule, uint64_t seqno,
4325 struct rule_collection *rules)
4327 enum nx_flow_monitor_flags update;
4329 if (ofproto_rule_is_hidden(rule)) {
4334 ? ofoperation_has_out_port(rule->pending, m->out_port)
4335 : ofproto_rule_has_out_port(rule, m->out_port))) {
4340 if (rule->add_seqno > seqno) {
4341 update = NXFMF_ADD | NXFMF_MODIFY;
4342 } else if (rule->modify_seqno > seqno) {
4343 update = NXFMF_MODIFY;
4348 if (!(m->flags & update)) {
4352 update = NXFMF_INITIAL;
4355 if (!rule->monitor_flags) {
4356 rule_collection_add(rules, rule);
4358 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4362 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4364 struct rule_collection *rules)
4366 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4367 const struct ofoperation *op;
4368 const struct oftable *table;
4369 struct cls_rule target;
4371 cls_rule_init_from_minimatch(&target, &m->match, 0);
4372 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4373 struct cls_cursor cursor;
4376 ovs_rwlock_rdlock(&table->cls.rwlock);
4377 cls_cursor_init(&cursor, &table->cls, &target);
4378 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4379 ovs_assert(!rule->pending); /* XXX */
4380 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4382 ovs_rwlock_unlock(&table->cls.rwlock);
4385 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4386 struct rule *rule = op->rule;
4388 if (((m->table_id == 0xff
4389 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4390 : m->table_id == rule->table_id))
4391 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4392 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4395 cls_rule_destroy(&target);
4399 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4400 struct rule_collection *rules)
4402 if (m->flags & NXFMF_INITIAL) {
4403 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4408 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4409 uint64_t seqno, struct rule_collection *rules)
4411 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4415 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4417 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4418 struct ofmonitor **monitors;
4419 size_t n_monitors, allocated_monitors;
4420 struct rule_collection rules;
4421 struct list replies;
4427 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4429 n_monitors = allocated_monitors = 0;
4431 struct ofputil_flow_monitor_request request;
4432 struct ofmonitor *m;
4435 retval = ofputil_decode_flow_monitor_request(&request, &b);
4436 if (retval == EOF) {
4438 } else if (retval) {
4443 if (request.table_id != 0xff
4444 && request.table_id >= ofproto->n_tables) {
4445 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4449 error = ofmonitor_create(&request, ofconn, &m);
4454 if (n_monitors >= allocated_monitors) {
4455 monitors = x2nrealloc(monitors, &allocated_monitors,
4458 monitors[n_monitors++] = m;
4461 rule_collection_init(&rules);
4462 for (i = 0; i < n_monitors; i++) {
4463 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4466 ofpmp_init(&replies, oh);
4467 ofmonitor_compose_refresh_updates(&rules, &replies);
4468 rule_collection_destroy(&rules);
4470 ofconn_send_replies(ofconn, &replies);
4477 for (i = 0; i < n_monitors; i++) {
4478 ofmonitor_destroy(monitors[i]);
4485 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4487 struct ofmonitor *m;
4490 id = ofputil_decode_flow_monitor_cancel(oh);
4491 m = ofmonitor_lookup(ofconn, id);
4493 return OFPERR_NXBRC_FM_BAD_ID;
4496 ofmonitor_destroy(m);
4500 /* Meters implementation.
4502 * Meter table entry, indexed by the OpenFlow meter_id.
4503 * These are always dynamically allocated to allocate enough space for
4505 * 'created' is used to compute the duration for meter stats.
4506 * 'list rules' is needed so that we can delete the dependent rules when the
4507 * meter table entry is deleted.
4508 * 'provider_meter_id' is for the provider's private use.
4511 long long int created; /* Time created. */
4512 struct list rules; /* List of "struct rule_dpif"s. */
4513 ofproto_meter_id provider_meter_id;
4514 uint16_t flags; /* Meter flags. */
4515 uint16_t n_bands; /* Number of meter bands. */
4516 struct ofputil_meter_band *bands;
4520 * This is used in instruction validation at flow set-up time,
4521 * as flows may not use non-existing meters.
4522 * This is also used by ofproto-providers to translate OpenFlow meter_ids
4523 * in METER instructions to the corresponding provider meter IDs.
4524 * Return value of UINT32_MAX signifies an invalid meter.
4527 ofproto_get_provider_meter_id(const struct ofproto * ofproto,
4528 uint32_t of_meter_id)
4530 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4531 const struct meter *meter = ofproto->meters[of_meter_id];
4533 return meter->provider_meter_id.uint32;
4540 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4544 meter->flags = config->flags;
4545 meter->n_bands = config->n_bands;
4546 meter->bands = xmemdup(config->bands,
4547 config->n_bands * sizeof *meter->bands);
4550 static struct meter *
4551 meter_create(const struct ofputil_meter_config *config,
4552 ofproto_meter_id provider_meter_id)
4554 struct meter *meter;
4556 meter = xzalloc(sizeof *meter);
4557 meter->provider_meter_id = provider_meter_id;
4558 meter->created = time_msec();
4559 list_init(&meter->rules);
4561 meter_update(meter, config);
4567 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
4570 for (mid = first; mid <= last; ++mid) {
4571 struct meter *meter = ofproto->meters[mid];
4573 ofproto->meters[mid] = NULL;
4574 ofproto->ofproto_class->meter_del(ofproto,
4575 meter->provider_meter_id);
4583 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4585 ofproto_meter_id provider_meter_id = { UINT32_MAX };
4586 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
4590 return OFPERR_OFPMMFC_METER_EXISTS;
4593 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
4596 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
4597 *meterp = meter_create(&mm->meter, provider_meter_id);
4603 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4605 struct meter *meter = ofproto->meters[mm->meter.meter_id];
4609 return OFPERR_OFPMMFC_UNKNOWN_METER;
4612 error = ofproto->ofproto_class->meter_set(ofproto,
4613 &meter->provider_meter_id,
4615 ovs_assert(meter->provider_meter_id.uint32 != UINT32_MAX);
4617 meter_update(meter, &mm->meter);
4623 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
4624 struct ofputil_meter_mod *mm)
4626 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4627 uint32_t meter_id = mm->meter.meter_id;
4628 struct rule_collection rules;
4629 enum ofperr error = 0;
4630 uint32_t first, last;
4632 if (meter_id == OFPM13_ALL) {
4634 last = ofproto->meter_features.max_meters;
4636 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
4639 first = last = meter_id;
4642 /* First delete the rules that use this meter. If any of those rules are
4643 * currently being modified, postpone the whole operation until later. */
4644 rule_collection_init(&rules);
4645 for (meter_id = first; meter_id <= last; ++meter_id) {
4646 struct meter *meter = ofproto->meters[meter_id];
4647 if (meter && !list_is_empty(&meter->rules)) {
4650 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
4651 if (rule->pending) {
4652 error = OFPROTO_POSTPONE;
4655 rule_collection_add(&rules, rule);
4660 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
4663 /* Delete the meters. */
4664 meter_delete(ofproto, first, last);
4667 rule_collection_destroy(&rules);
4673 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4675 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4676 struct ofputil_meter_mod mm;
4677 uint64_t bands_stub[256 / 8];
4678 struct ofpbuf bands;
4682 error = reject_slave_controller(ofconn);
4687 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4689 error = ofputil_decode_meter_mod(oh, &mm, &bands);
4691 goto exit_free_bands;
4694 meter_id = mm.meter.meter_id;
4696 if (mm.command != OFPMC13_DELETE) {
4697 /* Fails also when meters are not implemented by the provider. */
4698 if (meter_id == 0 || meter_id > OFPM13_MAX) {
4699 error = OFPERR_OFPMMFC_INVALID_METER;
4700 goto exit_free_bands;
4701 } else if (meter_id > ofproto->meter_features.max_meters) {
4702 error = OFPERR_OFPMMFC_OUT_OF_METERS;
4703 goto exit_free_bands;
4705 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
4706 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
4707 goto exit_free_bands;
4711 switch (mm.command) {
4713 error = handle_add_meter(ofproto, &mm);
4716 case OFPMC13_MODIFY:
4717 error = handle_modify_meter(ofproto, &mm);
4720 case OFPMC13_DELETE:
4721 error = handle_delete_meter(ofconn, oh, &mm);
4725 error = OFPERR_OFPMMFC_BAD_COMMAND;
4730 ofpbuf_uninit(&bands);
4735 handle_meter_features_request(struct ofconn *ofconn,
4736 const struct ofp_header *request)
4738 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4739 struct ofputil_meter_features features;
4742 if (ofproto->ofproto_class->meter_get_features) {
4743 ofproto->ofproto_class->meter_get_features(ofproto, &features);
4745 memset(&features, 0, sizeof features);
4747 b = ofputil_encode_meter_features_reply(&features, request);
4749 ofconn_send_reply(ofconn, b);
4754 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
4757 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4758 struct list replies;
4759 uint64_t bands_stub[256 / 8];
4760 struct ofpbuf bands;
4761 uint32_t meter_id, first, last;
4763 ofputil_decode_meter_request(request, &meter_id);
4765 if (meter_id == OFPM13_ALL) {
4767 last = ofproto->meter_features.max_meters;
4769 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
4770 !ofproto->meters[meter_id]) {
4771 return OFPERR_OFPMMFC_UNKNOWN_METER;
4773 first = last = meter_id;
4776 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4777 ofpmp_init(&replies, request);
4779 for (meter_id = first; meter_id <= last; ++meter_id) {
4780 struct meter *meter = ofproto->meters[meter_id];
4782 continue; /* Skip non-existing meters. */
4784 if (type == OFPTYPE_METER_STATS_REQUEST) {
4785 struct ofputil_meter_stats stats;
4787 stats.meter_id = meter_id;
4789 /* Provider sets the packet and byte counts, we do the rest. */
4790 stats.flow_count = list_size(&meter->rules);
4791 calc_duration(meter->created, time_msec(),
4792 &stats.duration_sec, &stats.duration_nsec);
4793 stats.n_bands = meter->n_bands;
4794 ofpbuf_clear(&bands);
4796 = ofpbuf_put_uninit(&bands,
4797 meter->n_bands * sizeof *stats.bands);
4799 if (!ofproto->ofproto_class->meter_get(ofproto,
4800 meter->provider_meter_id,
4802 ofputil_append_meter_stats(&replies, &stats);
4804 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
4805 struct ofputil_meter_config config;
4807 config.meter_id = meter_id;
4808 config.flags = meter->flags;
4809 config.n_bands = meter->n_bands;
4810 config.bands = meter->bands;
4811 ofputil_append_meter_config(&replies, &config);
4815 ofconn_send_replies(ofconn, &replies);
4816 ofpbuf_uninit(&bands);
4821 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4823 const struct ofp_header *oh = msg->data;
4827 error = ofptype_decode(&type, oh);
4833 /* OpenFlow requests. */
4834 case OFPTYPE_ECHO_REQUEST:
4835 return handle_echo_request(ofconn, oh);
4837 case OFPTYPE_FEATURES_REQUEST:
4838 return handle_features_request(ofconn, oh);
4840 case OFPTYPE_GET_CONFIG_REQUEST:
4841 return handle_get_config_request(ofconn, oh);
4843 case OFPTYPE_SET_CONFIG:
4844 return handle_set_config(ofconn, oh);
4846 case OFPTYPE_PACKET_OUT:
4847 return handle_packet_out(ofconn, oh);
4849 case OFPTYPE_PORT_MOD:
4850 return handle_port_mod(ofconn, oh);
4852 case OFPTYPE_FLOW_MOD:
4853 return handle_flow_mod(ofconn, oh);
4855 case OFPTYPE_METER_MOD:
4856 return handle_meter_mod(ofconn, oh);
4858 case OFPTYPE_BARRIER_REQUEST:
4859 return handle_barrier_request(ofconn, oh);
4861 case OFPTYPE_ROLE_REQUEST:
4862 return handle_role_request(ofconn, oh);
4864 /* OpenFlow replies. */
4865 case OFPTYPE_ECHO_REPLY:
4868 /* Nicira extension requests. */
4869 case OFPTYPE_FLOW_MOD_TABLE_ID:
4870 return handle_nxt_flow_mod_table_id(ofconn, oh);
4872 case OFPTYPE_SET_FLOW_FORMAT:
4873 return handle_nxt_set_flow_format(ofconn, oh);
4875 case OFPTYPE_SET_PACKET_IN_FORMAT:
4876 return handle_nxt_set_packet_in_format(ofconn, oh);
4878 case OFPTYPE_SET_CONTROLLER_ID:
4879 return handle_nxt_set_controller_id(ofconn, oh);
4881 case OFPTYPE_FLOW_AGE:
4882 /* Nothing to do. */
4885 case OFPTYPE_FLOW_MONITOR_CANCEL:
4886 return handle_flow_monitor_cancel(ofconn, oh);
4888 case OFPTYPE_SET_ASYNC_CONFIG:
4889 return handle_nxt_set_async_config(ofconn, oh);
4891 /* Statistics requests. */
4892 case OFPTYPE_DESC_STATS_REQUEST:
4893 return handle_desc_stats_request(ofconn, oh);
4895 case OFPTYPE_FLOW_STATS_REQUEST:
4896 return handle_flow_stats_request(ofconn, oh);
4898 case OFPTYPE_AGGREGATE_STATS_REQUEST:
4899 return handle_aggregate_stats_request(ofconn, oh);
4901 case OFPTYPE_TABLE_STATS_REQUEST:
4902 return handle_table_stats_request(ofconn, oh);
4904 case OFPTYPE_PORT_STATS_REQUEST:
4905 return handle_port_stats_request(ofconn, oh);
4907 case OFPTYPE_QUEUE_STATS_REQUEST:
4908 return handle_queue_stats_request(ofconn, oh);
4910 case OFPTYPE_PORT_DESC_STATS_REQUEST:
4911 return handle_port_desc_stats_request(ofconn, oh);
4913 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
4914 return handle_flow_monitor_request(ofconn, oh);
4916 case OFPTYPE_METER_STATS_REQUEST:
4917 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
4918 return handle_meter_request(ofconn, oh, type);
4920 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
4921 return handle_meter_features_request(ofconn, oh);
4923 /* FIXME: Change the following once they are implemented: */
4924 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
4925 case OFPTYPE_GET_ASYNC_REQUEST:
4926 case OFPTYPE_GROUP_STATS_REQUEST:
4927 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
4928 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
4929 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
4930 return OFPERR_OFPBRC_BAD_TYPE;
4934 case OFPTYPE_FEATURES_REPLY:
4935 case OFPTYPE_GET_CONFIG_REPLY:
4936 case OFPTYPE_PACKET_IN:
4937 case OFPTYPE_FLOW_REMOVED:
4938 case OFPTYPE_PORT_STATUS:
4939 case OFPTYPE_BARRIER_REPLY:
4940 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
4941 case OFPTYPE_DESC_STATS_REPLY:
4942 case OFPTYPE_FLOW_STATS_REPLY:
4943 case OFPTYPE_QUEUE_STATS_REPLY:
4944 case OFPTYPE_PORT_STATS_REPLY:
4945 case OFPTYPE_TABLE_STATS_REPLY:
4946 case OFPTYPE_AGGREGATE_STATS_REPLY:
4947 case OFPTYPE_PORT_DESC_STATS_REPLY:
4948 case OFPTYPE_ROLE_REPLY:
4949 case OFPTYPE_FLOW_MONITOR_PAUSED:
4950 case OFPTYPE_FLOW_MONITOR_RESUMED:
4951 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
4952 case OFPTYPE_GET_ASYNC_REPLY:
4953 case OFPTYPE_GROUP_STATS_REPLY:
4954 case OFPTYPE_GROUP_DESC_STATS_REPLY:
4955 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
4956 case OFPTYPE_METER_STATS_REPLY:
4957 case OFPTYPE_METER_CONFIG_STATS_REPLY:
4958 case OFPTYPE_METER_FEATURES_STATS_REPLY:
4959 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
4961 return OFPERR_OFPBRC_BAD_TYPE;
4966 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
4968 int error = handle_openflow__(ofconn, ofp_msg);
4969 if (error && error != OFPROTO_POSTPONE) {
4970 ofconn_send_error(ofconn, ofp_msg->data, error);
4972 COVERAGE_INC(ofproto_recv_openflow);
4973 return error != OFPROTO_POSTPONE;
4976 /* Asynchronous operations. */
4978 /* Creates and returns a new ofopgroup that is not associated with any
4979 * OpenFlow connection.
4981 * The caller should add operations to the returned group with
4982 * ofoperation_create() and then submit it with ofopgroup_submit(). */
4983 static struct ofopgroup *
4984 ofopgroup_create_unattached(struct ofproto *ofproto)
4986 struct ofopgroup *group = xzalloc(sizeof *group);
4987 group->ofproto = ofproto;
4988 list_init(&group->ofproto_node);
4989 list_init(&group->ops);
4990 list_init(&group->ofconn_node);
4994 /* Creates and returns a new ofopgroup for 'ofproto'.
4996 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
4997 * connection. The 'request' and 'buffer_id' arguments are ignored.
4999 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
5000 * If the ofopgroup eventually fails, then the error reply will include
5001 * 'request'. If the ofopgroup eventually succeeds, then the packet with
5002 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
5004 * The caller should add operations to the returned group with
5005 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5006 static struct ofopgroup *
5007 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
5008 const struct ofp_header *request, uint32_t buffer_id)
5010 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
5012 size_t request_len = ntohs(request->length);
5014 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
5016 ofconn_add_opgroup(ofconn, &group->ofconn_node);
5017 group->ofconn = ofconn;
5018 group->request = xmemdup(request, MIN(request_len, 64));
5019 group->buffer_id = buffer_id;
5024 /* Submits 'group' for processing.
5026 * If 'group' contains no operations (e.g. none were ever added, or all of the
5027 * ones that were added completed synchronously), then it is destroyed
5028 * immediately. Otherwise it is added to the ofproto's list of pending
5031 ofopgroup_submit(struct ofopgroup *group)
5033 if (!group->n_running) {
5034 ofopgroup_complete(group);
5036 list_push_back(&group->ofproto->pending, &group->ofproto_node);
5037 group->ofproto->n_pending++;
5042 ofopgroup_complete(struct ofopgroup *group)
5044 struct ofproto *ofproto = group->ofproto;
5046 struct ofconn *abbrev_ofconn;
5047 ovs_be32 abbrev_xid;
5049 struct ofoperation *op, *next_op;
5052 ovs_assert(!group->n_running);
5055 LIST_FOR_EACH (op, group_node, &group->ops) {
5062 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
5063 LIST_FOR_EACH (op, group_node, &group->ops) {
5064 if (op->type != OFOPERATION_DELETE) {
5065 struct ofpbuf *packet;
5068 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
5072 error = rule_execute(op->rule, in_port, packet);
5079 if (!error && !list_is_empty(&group->ofconn_node)) {
5080 abbrev_ofconn = group->ofconn;
5081 abbrev_xid = group->request->xid;
5083 abbrev_ofconn = NULL;
5084 abbrev_xid = htonl(0);
5086 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
5087 struct rule *rule = op->rule;
5089 /* We generally want to report the change to active OpenFlow flow
5090 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
5092 - The operation failed.
5094 - The affected rule is not visible to controllers.
5096 - The operation's only effect was to update rule->modified. */
5098 || ofproto_rule_is_hidden(rule)
5099 || (op->type == OFOPERATION_MODIFY
5101 && rule->flow_cookie == op->flow_cookie))) {
5102 /* Check that we can just cast from ofoperation_type to
5103 * nx_flow_update_event. */
5104 enum nx_flow_update_event event_type;
5107 case OFOPERATION_ADD:
5108 case OFOPERATION_REPLACE:
5109 event_type = NXFME_ADDED;
5112 case OFOPERATION_DELETE:
5113 event_type = NXFME_DELETED;
5116 case OFOPERATION_MODIFY:
5117 event_type = NXFME_MODIFIED;
5124 ofmonitor_report(ofproto->connmgr, rule, event_type,
5125 op->reason, abbrev_ofconn, abbrev_xid);
5128 rule->pending = NULL;
5131 case OFOPERATION_ADD:
5135 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
5136 if (vid_mask == VLAN_VID_MASK) {
5137 if (ofproto->vlan_bitmap) {
5138 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
5139 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
5140 bitmap_set1(ofproto->vlan_bitmap, vid);
5141 ofproto->vlans_changed = true;
5144 ofproto->vlans_changed = true;
5148 ovs_rwlock_wrlock(&rule->rwlock);
5149 oftable_remove_rule(rule);
5150 ofproto_rule_destroy(rule);
5154 case OFOPERATION_DELETE:
5155 ovs_assert(!op->error);
5156 ofproto_rule_destroy(rule);
5160 case OFOPERATION_MODIFY:
5161 case OFOPERATION_REPLACE:
5163 long long int now = time_msec();
5165 rule->modified = now;
5166 if (op->type == OFOPERATION_REPLACE) {
5167 rule->created = rule->used = now;
5170 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
5171 ovs_mutex_lock(&rule->timeout_mutex);
5172 rule->idle_timeout = op->idle_timeout;
5173 rule->hard_timeout = op->hard_timeout;
5174 ovs_mutex_unlock(&rule->timeout_mutex);
5176 free(rule->ofpacts);
5178 ovs_rwlock_wrlock(&rule->rwlock);
5179 rule->ofpacts = op->ofpacts;
5180 rule->ofpacts_len = op->ofpacts_len;
5181 ovs_rwlock_unlock(&rule->rwlock);
5184 op->ofpacts_len = 0;
5186 rule->send_flow_removed = op->send_flow_removed;
5194 ofoperation_destroy(op);
5197 ofmonitor_flush(ofproto->connmgr);
5199 if (!list_is_empty(&group->ofproto_node)) {
5200 ovs_assert(ofproto->n_pending > 0);
5201 ofproto->n_pending--;
5202 list_remove(&group->ofproto_node);
5204 if (!list_is_empty(&group->ofconn_node)) {
5205 list_remove(&group->ofconn_node);
5207 ofconn_send_error(group->ofconn, group->request, error);
5209 connmgr_retry(ofproto->connmgr);
5211 free(group->request);
5215 /* Initiates a new operation on 'rule', of the specified 'type', within
5216 * 'group'. Prior to calling, 'rule' must not have any pending operation.
5218 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
5219 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
5221 * Returns the newly created ofoperation (which is also available as
5222 * rule->pending). */
5223 static struct ofoperation *
5224 ofoperation_create(struct ofopgroup *group, struct rule *rule,
5225 enum ofoperation_type type,
5226 enum ofp_flow_removed_reason reason)
5228 struct ofproto *ofproto = group->ofproto;
5229 struct ofoperation *op;
5231 ovs_assert(!rule->pending);
5233 op = rule->pending = xzalloc(sizeof *op);
5235 list_push_back(&group->ops, &op->group_node);
5238 op->reason = reason;
5239 op->flow_cookie = rule->flow_cookie;
5240 ovs_mutex_lock(&rule->timeout_mutex);
5241 op->idle_timeout = rule->idle_timeout;
5242 op->hard_timeout = rule->hard_timeout;
5243 ovs_mutex_unlock(&rule->timeout_mutex);
5244 op->send_flow_removed = rule->send_flow_removed;
5248 if (type == OFOPERATION_DELETE) {
5249 hmap_insert(&ofproto->deletions, &op->hmap_node,
5250 cls_rule_hash(&rule->cr, rule->table_id));
5257 ofoperation_destroy(struct ofoperation *op)
5259 struct ofopgroup *group = op->group;
5262 op->rule->pending = NULL;
5264 if (op->type == OFOPERATION_DELETE) {
5265 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
5267 list_remove(&op->group_node);
5272 /* Indicates that 'op' completed with status 'error', which is either 0 to
5273 * indicate success or an OpenFlow error code on failure.
5275 * If 'error' is 0, indicating success, the operation will be committed
5276 * permanently to the flow table.
5278 * If 'error' is nonzero, then generally the operation will be rolled back:
5280 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
5281 * restores the original rule. The caller must have uninitialized any
5282 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
5283 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
5284 * and 7 for the new rule, calling its ->rule_dealloc() function.
5286 * - If 'op' is a "modify flow" operation, ofproto restores the original
5289 * - 'op' must not be a "delete flow" operation. Removing a rule is not
5290 * allowed to fail. It must always succeed.
5292 * Please see the large comment in ofproto/ofproto-provider.h titled
5293 * "Asynchronous Operation Support" for more information. */
5295 ofoperation_complete(struct ofoperation *op, enum ofperr error)
5297 struct ofopgroup *group = op->group;
5299 ovs_assert(op->rule->pending == op);
5300 ovs_assert(group->n_running > 0);
5301 ovs_assert(!error || op->type != OFOPERATION_DELETE);
5304 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
5305 ofopgroup_complete(group);
5310 pick_datapath_id(const struct ofproto *ofproto)
5312 const struct ofport *port;
5314 port = ofproto_get_port(ofproto, OFPP_LOCAL);
5316 uint8_t ea[ETH_ADDR_LEN];
5319 error = netdev_get_etheraddr(port->netdev, ea);
5321 return eth_addr_to_uint64(ea);
5323 VLOG_WARN("%s: could not get MAC address for %s (%s)",
5324 ofproto->name, netdev_get_name(port->netdev),
5325 ovs_strerror(error));
5327 return ofproto->fallback_dpid;
5331 pick_fallback_dpid(void)
5333 uint8_t ea[ETH_ADDR_LEN];
5334 eth_addr_nicira_random(ea);
5335 return eth_addr_to_uint64(ea);
5338 /* Table overflow policy. */
5340 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
5341 * to NULL if the table is not configured to evict rules or if the table
5342 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
5343 * or with no timeouts are not evictable.) */
5345 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
5347 struct eviction_group *evg;
5350 if (!table->eviction_fields) {
5354 /* In the common case, the outer and inner loops here will each be entered
5357 * - The inner loop normally "return"s in its first iteration. If the
5358 * eviction group has any evictable rules, then it always returns in
5361 * - The outer loop only iterates more than once if the largest eviction
5362 * group has no evictable rules.
5364 * - The outer loop can exit only if table's 'max_flows' is all filled up
5365 * by unevictable rules. */
5366 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
5369 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
5370 if (!ovs_rwlock_trywrlock(&rule->rwlock)) {
5380 /* Searches 'ofproto' for tables that have more flows than their configured
5381 * maximum and that have flow eviction enabled, and evicts as many flows as
5382 * necessary and currently feasible from them.
5384 * This triggers only when an OpenFlow table has N flows in it and then the
5385 * client configures a maximum number of flows less than N. */
5387 ofproto_evict(struct ofproto *ofproto)
5389 struct ofopgroup *group;
5390 struct oftable *table;
5392 group = ofopgroup_create_unattached(ofproto);
5393 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
5394 while (table->eviction_fields) {
5398 ovs_rwlock_rdlock(&table->cls.rwlock);
5399 n_rules = classifier_count(&table->cls);
5400 ovs_rwlock_unlock(&table->cls.rwlock);
5402 if (n_rules <= table->max_flows) {
5406 if (!choose_rule_to_evict(table, &rule)) {
5410 if (rule->pending) {
5411 ovs_rwlock_unlock(&rule->rwlock);
5415 ofoperation_create(group, rule,
5416 OFOPERATION_DELETE, OFPRR_EVICTION);
5417 oftable_remove_rule(rule);
5418 ofproto->ofproto_class->rule_delete(rule);
5421 ofopgroup_submit(group);
5424 /* Eviction groups. */
5426 /* Returns the priority to use for an eviction_group that contains 'n_rules'
5427 * rules. The priority contains low-order random bits to ensure that eviction
5428 * groups with the same number of rules are prioritized randomly. */
5430 eviction_group_priority(size_t n_rules)
5432 uint16_t size = MIN(UINT16_MAX, n_rules);
5433 return (size << 16) | random_uint16();
5436 /* Updates 'evg', an eviction_group within 'table', following a change that
5437 * adds or removes rules in 'evg'. */
5439 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
5441 heap_change(&table->eviction_groups_by_size, &evg->size_node,
5442 eviction_group_priority(heap_count(&evg->rules)));
5445 /* Destroys 'evg', an eviction_group within 'table':
5447 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
5448 * rules themselves, just removes them from the eviction group.)
5450 * - Removes 'evg' from 'table'.
5454 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
5456 while (!heap_is_empty(&evg->rules)) {
5459 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
5460 rule->eviction_group = NULL;
5462 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
5463 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
5464 heap_destroy(&evg->rules);
5468 /* Removes 'rule' from its eviction group, if any. */
5470 eviction_group_remove_rule(struct rule *rule)
5472 if (rule->eviction_group) {
5473 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5474 struct eviction_group *evg = rule->eviction_group;
5476 rule->eviction_group = NULL;
5477 heap_remove(&evg->rules, &rule->evg_node);
5478 if (heap_is_empty(&evg->rules)) {
5479 eviction_group_destroy(table, evg);
5481 eviction_group_resized(table, evg);
5486 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
5487 * returns the hash value. */
5489 eviction_group_hash_rule(struct rule *rule)
5491 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5492 const struct mf_subfield *sf;
5496 hash = table->eviction_group_id_basis;
5497 miniflow_expand(&rule->cr.match.flow, &flow);
5498 for (sf = table->eviction_fields;
5499 sf < &table->eviction_fields[table->n_eviction_fields];
5502 if (mf_are_prereqs_ok(sf->field, &flow)) {
5503 union mf_value value;
5505 mf_get_value(sf->field, &flow, &value);
5507 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
5509 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
5510 unsigned int start = sf->ofs + sf->n_bits;
5511 bitwise_zero(&value, sf->field->n_bytes, start,
5512 sf->field->n_bytes * 8 - start);
5514 hash = hash_bytes(&value, sf->field->n_bytes, hash);
5516 hash = hash_int(hash, 0);
5523 /* Returns an eviction group within 'table' with the given 'id', creating one
5525 static struct eviction_group *
5526 eviction_group_find(struct oftable *table, uint32_t id)
5528 struct eviction_group *evg;
5530 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
5534 evg = xmalloc(sizeof *evg);
5535 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
5536 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
5537 eviction_group_priority(0));
5538 heap_init(&evg->rules);
5543 /* Returns an eviction priority for 'rule'. The return value should be
5544 * interpreted so that higher priorities make a rule more attractive candidates
5547 rule_eviction_priority(struct rule *rule)
5549 long long int hard_expiration;
5550 long long int idle_expiration;
5551 long long int expiration;
5552 uint32_t expiration_offset;
5554 /* Calculate time of expiration. */
5555 ovs_mutex_lock(&rule->timeout_mutex);
5556 hard_expiration = (rule->hard_timeout
5557 ? rule->modified + rule->hard_timeout * 1000
5559 idle_expiration = (rule->idle_timeout
5560 ? rule->used + rule->idle_timeout * 1000
5562 expiration = MIN(hard_expiration, idle_expiration);
5563 ovs_mutex_unlock(&rule->timeout_mutex);
5564 if (expiration == LLONG_MAX) {
5568 /* Calculate the time of expiration as a number of (approximate) seconds
5569 * after program startup.
5571 * This should work OK for program runs that last UINT32_MAX seconds or
5572 * less. Therefore, please restart OVS at least once every 136 years. */
5573 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
5575 /* Invert the expiration offset because we're using a max-heap. */
5576 return UINT32_MAX - expiration_offset;
5579 /* Adds 'rule' to an appropriate eviction group for its oftable's
5580 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
5581 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
5584 * The caller must ensure that 'rule' is not already in an eviction group. */
5586 eviction_group_add_rule(struct rule *rule)
5588 struct ofproto *ofproto = rule->ofproto;
5589 struct oftable *table = &ofproto->tables[rule->table_id];
5592 ovs_mutex_lock(&rule->timeout_mutex);
5593 has_timeout = rule->hard_timeout || rule->idle_timeout;
5594 ovs_mutex_unlock(&rule->timeout_mutex);
5596 if (table->eviction_fields && has_timeout) {
5597 struct eviction_group *evg;
5599 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
5601 rule->eviction_group = evg;
5602 heap_insert(&evg->rules, &rule->evg_node,
5603 rule_eviction_priority(rule));
5604 eviction_group_resized(table, evg);
5610 /* Initializes 'table'. */
5612 oftable_init(struct oftable *table)
5614 memset(table, 0, sizeof *table);
5615 classifier_init(&table->cls);
5616 table->max_flows = UINT_MAX;
5619 /* Destroys 'table', including its classifier and eviction groups.
5621 * The caller is responsible for freeing 'table' itself. */
5623 oftable_destroy(struct oftable *table)
5625 ovs_rwlock_rdlock(&table->cls.rwlock);
5626 ovs_assert(classifier_is_empty(&table->cls));
5627 ovs_rwlock_unlock(&table->cls.rwlock);
5628 oftable_disable_eviction(table);
5629 classifier_destroy(&table->cls);
5633 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
5634 * string, then 'table' will use its default name.
5636 * This only affects the name exposed for a table exposed through the OpenFlow
5637 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
5639 oftable_set_name(struct oftable *table, const char *name)
5641 if (name && name[0]) {
5642 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
5643 if (!table->name || strncmp(name, table->name, len)) {
5645 table->name = xmemdup0(name, len);
5653 /* oftables support a choice of two policies when adding a rule would cause the
5654 * number of flows in the table to exceed the configured maximum number: either
5655 * they can refuse to add the new flow or they can evict some existing flow.
5656 * This function configures the former policy on 'table'. */
5658 oftable_disable_eviction(struct oftable *table)
5660 if (table->eviction_fields) {
5661 struct eviction_group *evg, *next;
5663 HMAP_FOR_EACH_SAFE (evg, next, id_node,
5664 &table->eviction_groups_by_id) {
5665 eviction_group_destroy(table, evg);
5667 hmap_destroy(&table->eviction_groups_by_id);
5668 heap_destroy(&table->eviction_groups_by_size);
5670 free(table->eviction_fields);
5671 table->eviction_fields = NULL;
5672 table->n_eviction_fields = 0;
5676 /* oftables support a choice of two policies when adding a rule would cause the
5677 * number of flows in the table to exceed the configured maximum number: either
5678 * they can refuse to add the new flow or they can evict some existing flow.
5679 * This function configures the latter policy on 'table', with fairness based
5680 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
5681 * 'n_fields' as 0 disables fairness.) */
5683 oftable_enable_eviction(struct oftable *table,
5684 const struct mf_subfield *fields, size_t n_fields)
5686 struct cls_cursor cursor;
5689 if (table->eviction_fields
5690 && n_fields == table->n_eviction_fields
5692 || !memcmp(fields, table->eviction_fields,
5693 n_fields * sizeof *fields))) {
5698 oftable_disable_eviction(table);
5700 table->n_eviction_fields = n_fields;
5701 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
5703 table->eviction_group_id_basis = random_uint32();
5704 hmap_init(&table->eviction_groups_by_id);
5705 heap_init(&table->eviction_groups_by_size);
5707 ovs_rwlock_rdlock(&table->cls.rwlock);
5708 cls_cursor_init(&cursor, &table->cls, NULL);
5709 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
5710 eviction_group_add_rule(rule);
5712 ovs_rwlock_unlock(&table->cls.rwlock);
5715 /* Removes 'rule' from the oftable that contains it. */
5717 oftable_remove_rule__(struct ofproto *ofproto, struct classifier *cls,
5719 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock)
5721 classifier_remove(cls, &rule->cr);
5722 cookies_remove(ofproto, rule);
5723 eviction_group_remove_rule(rule);
5724 ovs_mutex_lock(&ofproto->expirable_mutex);
5725 if (!list_is_empty(&rule->expirable)) {
5726 list_remove(&rule->expirable);
5728 ovs_mutex_unlock(&ofproto->expirable_mutex);
5729 if (!list_is_empty(&rule->meter_list_node)) {
5730 list_remove(&rule->meter_list_node);
5731 list_init(&rule->meter_list_node);
5733 ovs_rwlock_unlock(&rule->rwlock);
5737 oftable_remove_rule(struct rule *rule)
5739 struct ofproto *ofproto = rule->ofproto;
5740 struct oftable *table = &ofproto->tables[rule->table_id];
5742 ovs_rwlock_wrlock(&table->cls.rwlock);
5743 oftable_remove_rule__(ofproto, &table->cls, rule);
5744 ovs_rwlock_unlock(&table->cls.rwlock);
5747 /* Inserts 'rule' into its oftable, which must not already contain any rule for
5748 * the same cls_rule. */
5750 oftable_insert_rule(struct rule *rule)
5752 struct ofproto *ofproto = rule->ofproto;
5753 struct oftable *table = &ofproto->tables[rule->table_id];
5756 ovs_mutex_lock(&rule->timeout_mutex);
5757 may_expire = rule->hard_timeout || rule->idle_timeout;
5758 ovs_mutex_unlock(&rule->timeout_mutex);
5761 ovs_mutex_lock(&ofproto->expirable_mutex);
5762 list_insert(&ofproto->expirable, &rule->expirable);
5763 ovs_mutex_unlock(&ofproto->expirable_mutex);
5765 cookies_insert(ofproto, rule);
5766 if (rule->meter_id) {
5767 struct meter *meter = ofproto->meters[rule->meter_id];
5768 list_insert(&meter->rules, &rule->meter_list_node);
5770 ovs_rwlock_wrlock(&table->cls.rwlock);
5771 classifier_insert(&table->cls, &rule->cr);
5772 ovs_rwlock_unlock(&table->cls.rwlock);
5773 eviction_group_add_rule(rule);
5776 /* unixctl commands. */
5779 ofproto_lookup(const char *name)
5781 struct ofproto *ofproto;
5783 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
5785 if (!strcmp(ofproto->name, name)) {
5793 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
5794 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5796 struct ofproto *ofproto;
5800 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
5801 ds_put_format(&results, "%s\n", ofproto->name);
5803 unixctl_command_reply(conn, ds_cstr(&results));
5804 ds_destroy(&results);
5808 ofproto_unixctl_init(void)
5810 static bool registered;
5816 unixctl_command_register("ofproto/list", "", 0, 0,
5817 ofproto_unixctl_list, NULL);
5820 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5822 * This is deprecated. It is only for compatibility with broken device drivers
5823 * in old versions of Linux that do not properly support VLANs when VLAN
5824 * devices are not used. When broken device drivers are no longer in
5825 * widespread use, we will delete these interfaces. */
5827 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
5828 * (exactly) by an OpenFlow rule in 'ofproto'. */
5830 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
5832 const struct oftable *oftable;
5834 free(ofproto->vlan_bitmap);
5835 ofproto->vlan_bitmap = bitmap_allocate(4096);
5836 ofproto->vlans_changed = false;
5838 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
5839 const struct cls_table *table;
5841 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
5842 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
5843 const struct cls_rule *rule;
5845 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
5846 uint16_t vid = miniflow_get_vid(&rule->match.flow);
5847 bitmap_set1(vlan_bitmap, vid);
5848 bitmap_set1(ofproto->vlan_bitmap, vid);
5855 /* Returns true if new VLANs have come into use by the flow table since the
5856 * last call to ofproto_get_vlan_usage().
5858 * We don't track when old VLANs stop being used. */
5860 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
5862 return ofproto->vlans_changed;
5865 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
5866 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
5867 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
5868 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
5869 * then the VLAN device is un-enslaved. */
5871 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
5872 ofp_port_t realdev_ofp_port, int vid)
5874 struct ofport *ofport;
5877 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
5879 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
5881 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
5882 ofproto->name, vlandev_ofp_port);
5886 if (!ofproto->ofproto_class->set_realdev) {
5887 if (!vlandev_ofp_port) {
5890 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
5894 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
5896 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
5897 ofproto->name, vlandev_ofp_port,
5898 netdev_get_name(ofport->netdev), ovs_strerror(error));