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 rule_actions *actions;
129 /* OFOPERATION_DELETE. */
130 enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
132 ovs_be64 flow_cookie; /* Rule's old flow cookie. */
133 uint16_t idle_timeout; /* Rule's old idle timeout. */
134 uint16_t hard_timeout; /* Rule's old hard timeout. */
135 bool send_flow_removed; /* Rule's old 'send_flow_removed'. */
136 enum ofperr error; /* 0 if no error. */
139 static struct ofoperation *ofoperation_create(struct ofopgroup *,
141 enum ofoperation_type,
142 enum ofp_flow_removed_reason);
143 static void ofoperation_destroy(struct ofoperation *);
146 static void oftable_init(struct oftable *);
147 static void oftable_destroy(struct oftable *);
149 static void oftable_set_name(struct oftable *, const char *name);
151 static void oftable_disable_eviction(struct oftable *);
152 static void oftable_enable_eviction(struct oftable *,
153 const struct mf_subfield *fields,
156 static void oftable_remove_rule(struct rule *rule) OVS_RELEASES(rule->rwlock);
157 static void oftable_remove_rule__(struct ofproto *ofproto,
158 struct classifier *cls, struct rule *rule)
159 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock);
160 static void oftable_insert_rule(struct rule *);
162 /* A set of rules within a single OpenFlow table (oftable) that have the same
163 * values for the oftable's eviction_fields. A rule to be evicted, when one is
164 * needed, is taken from the eviction group that contains the greatest number
167 * An oftable owns any number of eviction groups, each of which contains any
170 * Membership in an eviction group is imprecise, based on the hash of the
171 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
172 * That is, if two rules have different eviction_fields, but those
173 * eviction_fields hash to the same value, then they will belong to the same
174 * eviction_group anyway.
176 * (When eviction is not enabled on an oftable, we don't track any eviction
177 * groups, to save time and space.) */
178 struct eviction_group {
179 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
180 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
181 struct heap rules; /* Contains "struct rule"s. */
184 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep)
185 OVS_TRY_WRLOCK(true, (*rulep)->rwlock);
186 static void ofproto_evict(struct ofproto *);
187 static uint32_t rule_eviction_priority(struct rule *);
188 static void eviction_group_add_rule(struct rule *);
189 static void eviction_group_remove_rule(struct rule *);
191 /* Criteria that flow_mod and other operations use for selecting rules on
192 * which to operate. */
193 struct rule_criteria {
194 /* An OpenFlow table or 255 for all tables. */
197 /* OpenFlow matching criteria. Interpreted different in "loose" way by
198 * collect_rules_loose() and "strict" way by collect_rules_strict(), as
199 * defined in the OpenFlow spec. */
202 /* Matching criteria for the OpenFlow cookie. Consider a bit B in a rule's
203 * cookie and the corresponding bits C in 'cookie' and M in 'cookie_mask'.
204 * The rule will not be selected if M is 1 and B != C. */
206 ovs_be64 cookie_mask;
208 /* Selection based on actions within a rule:
210 * If out_port != OFPP_ANY, selects only rules that output to out_port. */
214 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
215 const struct match *match,
216 unsigned int priority,
217 ovs_be64 cookie, ovs_be64 cookie_mask,
218 ofp_port_t out_port);
219 static void rule_criteria_destroy(struct rule_criteria *);
221 /* A packet that needs to be passed to rule_execute(). */
222 struct rule_execute {
223 struct list list_node; /* In struct ofproto's "rule_executes" list. */
224 struct rule *rule; /* Owns a reference to the rule. */
226 struct ofpbuf *packet; /* Owns the packet. */
229 static void run_rule_executes(struct ofproto *);
230 static void destroy_rule_executes(struct ofproto *);
233 static void ofport_destroy__(struct ofport *);
234 static void ofport_destroy(struct ofport *);
236 static void update_port(struct ofproto *, const char *devname);
237 static int init_ports(struct ofproto *);
238 static void reinit_ports(struct ofproto *);
241 static void ofproto_rule_destroy__(struct rule *);
242 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
243 static bool rule_is_modifiable(const struct rule *);
246 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
247 struct ofputil_flow_mod *,
248 const struct ofp_header *);
249 static enum ofperr modify_flows__(struct ofproto *, struct ofconn *,
250 struct ofputil_flow_mod *,
251 const struct ofp_header *,
252 const struct rule_collection *);
253 static void delete_flow__(struct rule *rule, struct ofopgroup *,
254 enum ofp_flow_removed_reason)
255 OVS_RELEASES(rule->rwlock);
256 static bool handle_openflow(struct ofconn *, const struct ofpbuf *);
257 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
258 struct ofputil_flow_mod *,
259 const struct ofp_header *);
260 static void calc_duration(long long int start, long long int now,
261 uint32_t *sec, uint32_t *nsec);
264 static uint64_t pick_datapath_id(const struct ofproto *);
265 static uint64_t pick_fallback_dpid(void);
266 static void ofproto_destroy__(struct ofproto *);
267 static void update_mtu(struct ofproto *, struct ofport *);
268 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
271 static void ofproto_unixctl_init(void);
273 /* All registered ofproto classes, in probe order. */
274 static const struct ofproto_class **ofproto_classes;
275 static size_t n_ofproto_classes;
276 static size_t allocated_ofproto_classes;
278 struct ovs_mutex ofproto_mutex;
280 unsigned flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT;
281 unsigned n_handler_threads;
282 enum ofproto_flow_miss_model flow_miss_model = OFPROTO_HANDLE_MISS_AUTO;
284 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
285 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
287 /* Initial mappings of port to OpenFlow number mappings. */
288 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
290 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
292 /* The default value of true waits for flow restore. */
293 static bool flow_restore_wait = true;
295 /* Must be called to initialize the ofproto library.
297 * The caller may pass in 'iface_hints', which contains an shash of
298 * "iface_hint" elements indexed by the interface's name. The provider
299 * may use these hints to describe the startup configuration in order to
300 * reinitialize its state. The caller owns the provided data, so a
301 * provider will make copies of anything required. An ofproto provider
302 * will remove any existing state that is not described by the hint, and
303 * may choose to remove it all. */
305 ofproto_init(const struct shash *iface_hints)
307 struct shash_node *node;
310 ovs_mutex_init_recursive(&ofproto_mutex);
312 ofproto_class_register(&ofproto_dpif_class);
314 /* Make a local copy, since we don't own 'iface_hints' elements. */
315 SHASH_FOR_EACH(node, iface_hints) {
316 const struct iface_hint *orig_hint = node->data;
317 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
318 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
320 new_hint->br_name = xstrdup(orig_hint->br_name);
321 new_hint->br_type = xstrdup(br_type);
322 new_hint->ofp_port = orig_hint->ofp_port;
324 shash_add(&init_ofp_ports, node->name, new_hint);
327 for (i = 0; i < n_ofproto_classes; i++) {
328 ofproto_classes[i]->init(&init_ofp_ports);
332 /* 'type' should be a normalized datapath type, as returned by
333 * ofproto_normalize_type(). Returns the corresponding ofproto_class
334 * structure, or a null pointer if there is none registered for 'type'. */
335 static const struct ofproto_class *
336 ofproto_class_find__(const char *type)
340 for (i = 0; i < n_ofproto_classes; i++) {
341 const struct ofproto_class *class = ofproto_classes[i];
346 class->enumerate_types(&types);
347 found = sset_contains(&types, type);
348 sset_destroy(&types);
354 VLOG_WARN("unknown datapath type %s", type);
358 /* Registers a new ofproto class. After successful registration, new ofprotos
359 * of that type can be created using ofproto_create(). */
361 ofproto_class_register(const struct ofproto_class *new_class)
365 for (i = 0; i < n_ofproto_classes; i++) {
366 if (ofproto_classes[i] == new_class) {
371 if (n_ofproto_classes >= allocated_ofproto_classes) {
372 ofproto_classes = x2nrealloc(ofproto_classes,
373 &allocated_ofproto_classes,
374 sizeof *ofproto_classes);
376 ofproto_classes[n_ofproto_classes++] = new_class;
380 /* Unregisters a datapath provider. 'type' must have been previously
381 * registered and not currently be in use by any ofprotos. After
382 * unregistration new datapaths of that type cannot be opened using
383 * ofproto_create(). */
385 ofproto_class_unregister(const struct ofproto_class *class)
389 for (i = 0; i < n_ofproto_classes; i++) {
390 if (ofproto_classes[i] == class) {
391 for (i++; i < n_ofproto_classes; i++) {
392 ofproto_classes[i - 1] = ofproto_classes[i];
398 VLOG_WARN("attempted to unregister an ofproto class that is not "
403 /* Clears 'types' and enumerates all registered ofproto types into it. The
404 * caller must first initialize the sset. */
406 ofproto_enumerate_types(struct sset *types)
410 for (i = 0; i < n_ofproto_classes; i++) {
411 ofproto_classes[i]->enumerate_types(types);
415 /* Returns the fully spelled out name for the given ofproto 'type'.
417 * Normalized type string can be compared with strcmp(). Unnormalized type
418 * string might be the same even if they have different spellings. */
420 ofproto_normalize_type(const char *type)
422 return type && type[0] ? type : "system";
425 /* Clears 'names' and enumerates the names of all known created ofprotos with
426 * the given 'type'. The caller must first initialize the sset. Returns 0 if
427 * successful, otherwise a positive errno value.
429 * Some kinds of datapaths might not be practically enumerable. This is not
430 * considered an error. */
432 ofproto_enumerate_names(const char *type, struct sset *names)
434 const struct ofproto_class *class = ofproto_class_find__(type);
435 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
439 ofproto_create(const char *datapath_name, const char *datapath_type,
440 struct ofproto **ofprotop)
442 const struct ofproto_class *class;
443 struct ofproto *ofproto;
449 ofproto_unixctl_init();
451 datapath_type = ofproto_normalize_type(datapath_type);
452 class = ofproto_class_find__(datapath_type);
454 VLOG_WARN("could not create datapath %s of unknown type %s",
455 datapath_name, datapath_type);
459 ofproto = class->alloc();
461 VLOG_ERR("failed to allocate datapath %s of type %s",
462 datapath_name, datapath_type);
467 ovs_mutex_lock(&ofproto_mutex);
468 memset(ofproto, 0, sizeof *ofproto);
469 ofproto->ofproto_class = class;
470 ofproto->name = xstrdup(datapath_name);
471 ofproto->type = xstrdup(datapath_type);
472 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
473 hash_string(ofproto->name, 0));
474 ofproto->datapath_id = 0;
475 ofproto->forward_bpdu = false;
476 ofproto->fallback_dpid = pick_fallback_dpid();
477 ofproto->mfr_desc = NULL;
478 ofproto->hw_desc = NULL;
479 ofproto->sw_desc = NULL;
480 ofproto->serial_desc = NULL;
481 ofproto->dp_desc = NULL;
482 ofproto->frag_handling = OFPC_FRAG_NORMAL;
483 hmap_init(&ofproto->ports);
484 shash_init(&ofproto->port_by_name);
485 simap_init(&ofproto->ofp_requests);
486 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
487 ofproto->eviction_group_timer = LLONG_MIN;
488 ofproto->tables = NULL;
489 ofproto->n_tables = 0;
490 hindex_init(&ofproto->cookies);
491 list_init(&ofproto->expirable);
492 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
493 ofproto->state = S_OPENFLOW;
494 list_init(&ofproto->pending);
495 ofproto->n_pending = 0;
496 hmap_init(&ofproto->deletions);
497 guarded_list_init(&ofproto->rule_executes);
498 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
499 ofproto->first_op = ofproto->last_op = LLONG_MIN;
500 ofproto->next_op_report = LLONG_MAX;
501 ofproto->op_backoff = LLONG_MIN;
502 ofproto->vlan_bitmap = NULL;
503 ofproto->vlans_changed = false;
504 ofproto->min_mtu = INT_MAX;
505 ovs_mutex_unlock(&ofproto_mutex);
507 error = ofproto->ofproto_class->construct(ofproto);
509 VLOG_ERR("failed to open datapath %s: %s",
510 datapath_name, ovs_strerror(error));
511 ofproto_destroy__(ofproto);
515 /* The "max_ports" member should have been set by ->construct(ofproto).
516 * Port 0 is not a valid OpenFlow port, so mark that as unavailable. */
517 ofproto->ofp_port_ids = bitmap_allocate(ofproto->max_ports);
518 bitmap_set1(ofproto->ofp_port_ids, 0);
520 /* Check that hidden tables, if any, are at the end. */
521 ovs_assert(ofproto->n_tables);
522 for (i = 0; i + 1 < ofproto->n_tables; i++) {
523 enum oftable_flags flags = ofproto->tables[i].flags;
524 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
526 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
529 ofproto->datapath_id = pick_datapath_id(ofproto);
532 /* Initialize meters table. */
533 if (ofproto->ofproto_class->meter_get_features) {
534 ofproto->ofproto_class->meter_get_features(ofproto,
535 &ofproto->meter_features);
537 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
539 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
540 * sizeof(struct meter *));
546 /* Must be called (only) by an ofproto implementation in its constructor
547 * function. See the large comment on 'construct' in struct ofproto_class for
550 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
552 struct oftable *table;
554 ovs_assert(!ofproto->n_tables);
555 ovs_assert(n_tables >= 1 && n_tables <= 255);
557 ofproto->n_tables = n_tables;
558 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
559 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
564 /* To be optionally called (only) by an ofproto implementation in its
565 * constructor function. See the large comment on 'construct' in struct
566 * ofproto_class for details.
568 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
569 * will then ensure that actions passed into the ofproto implementation will
570 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
571 * function is not called, there will be no such restriction.
573 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
574 * the 'max_ports' restriction. */
576 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
578 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
579 ofproto->max_ports = max_ports;
583 ofproto_get_datapath_id(const struct ofproto *ofproto)
585 return ofproto->datapath_id;
589 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
591 uint64_t old_dpid = p->datapath_id;
592 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
593 if (p->datapath_id != old_dpid) {
594 /* Force all active connections to reconnect, since there is no way to
595 * notify a controller that the datapath ID has changed. */
596 ofproto_reconnect_controllers(p);
601 ofproto_set_controllers(struct ofproto *p,
602 const struct ofproto_controller *controllers,
603 size_t n_controllers, uint32_t allowed_versions)
605 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
610 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
612 connmgr_set_fail_mode(p->connmgr, fail_mode);
615 /* Drops the connections between 'ofproto' and all of its controllers, forcing
616 * them to reconnect. */
618 ofproto_reconnect_controllers(struct ofproto *ofproto)
620 connmgr_reconnect(ofproto->connmgr);
623 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
624 * in-band control should guarantee access, in the same way that in-band
625 * control guarantees access to OpenFlow controllers. */
627 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
628 const struct sockaddr_in *extras, size_t n)
630 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
633 /* Sets the OpenFlow queue used by flows set up by in-band control on
634 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
635 * flows will use the default queue. */
637 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
639 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
642 /* Sets the number of flows at which eviction from the kernel flow table
645 ofproto_set_flow_eviction_threshold(unsigned threshold)
647 flow_eviction_threshold = MAX(OFPROTO_FLOW_EVICTION_THRESHOLD_MIN,
651 /* Sets the path for handling flow misses. */
653 ofproto_set_flow_miss_model(unsigned model)
655 flow_miss_model = model;
658 /* If forward_bpdu is true, the NORMAL action will forward frames with
659 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
660 * the NORMAL action will drop these frames. */
662 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
664 bool old_val = ofproto->forward_bpdu;
665 ofproto->forward_bpdu = forward_bpdu;
666 if (old_val != ofproto->forward_bpdu) {
667 if (ofproto->ofproto_class->forward_bpdu_changed) {
668 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
673 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
674 * 'idle_time', in seconds, and the maximum number of MAC table entries to
677 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
680 if (ofproto->ofproto_class->set_mac_table_config) {
681 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
686 /* Sets number of upcall handler threads. The default is
687 * (number of online cores - 2). */
689 ofproto_set_n_handler_threads(unsigned limit)
692 n_handler_threads = limit;
694 int n_proc = sysconf(_SC_NPROCESSORS_ONLN);
695 n_handler_threads = n_proc > 2 ? n_proc - 2 : 1;
700 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
703 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
707 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
709 return connmgr_set_snoops(ofproto->connmgr, snoops);
713 ofproto_set_netflow(struct ofproto *ofproto,
714 const struct netflow_options *nf_options)
716 if (nf_options && sset_is_empty(&nf_options->collectors)) {
720 if (ofproto->ofproto_class->set_netflow) {
721 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
723 return nf_options ? EOPNOTSUPP : 0;
728 ofproto_set_sflow(struct ofproto *ofproto,
729 const struct ofproto_sflow_options *oso)
731 if (oso && sset_is_empty(&oso->targets)) {
735 if (ofproto->ofproto_class->set_sflow) {
736 return ofproto->ofproto_class->set_sflow(ofproto, oso);
738 return oso ? EOPNOTSUPP : 0;
743 ofproto_set_ipfix(struct ofproto *ofproto,
744 const struct ofproto_ipfix_bridge_exporter_options *bo,
745 const struct ofproto_ipfix_flow_exporter_options *fo,
748 if (ofproto->ofproto_class->set_ipfix) {
749 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
751 return (bo || fo) ? EOPNOTSUPP : 0;
756 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
758 flow_restore_wait = flow_restore_wait_db;
762 ofproto_get_flow_restore_wait(void)
764 return flow_restore_wait;
768 /* Spanning Tree Protocol (STP) configuration. */
770 /* Configures STP on 'ofproto' using the settings defined in 's'. If
771 * 's' is NULL, disables STP.
773 * Returns 0 if successful, otherwise a positive errno value. */
775 ofproto_set_stp(struct ofproto *ofproto,
776 const struct ofproto_stp_settings *s)
778 return (ofproto->ofproto_class->set_stp
779 ? ofproto->ofproto_class->set_stp(ofproto, s)
783 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
784 * 'enabled' member of 's' is false, then the other members are not
787 * Returns 0 if successful, otherwise a positive errno value. */
789 ofproto_get_stp_status(struct ofproto *ofproto,
790 struct ofproto_stp_status *s)
792 return (ofproto->ofproto_class->get_stp_status
793 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
797 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
798 * in 's'. The caller is responsible for assigning STP port numbers
799 * (using the 'port_num' member in the range of 1 through 255, inclusive)
800 * and ensuring there are no duplicates. If the 's' is NULL, then STP
801 * is disabled on the port.
803 * Returns 0 if successful, otherwise a positive errno value.*/
805 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
806 const struct ofproto_port_stp_settings *s)
808 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
810 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
811 ofproto->name, ofp_port);
815 return (ofproto->ofproto_class->set_stp_port
816 ? ofproto->ofproto_class->set_stp_port(ofport, s)
820 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
821 * 's'. If the 'enabled' member in 's' is false, then the other members
822 * are not meaningful.
824 * Returns 0 if successful, otherwise a positive errno value.*/
826 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
827 struct ofproto_port_stp_status *s)
829 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
831 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
832 "port %"PRIu16, ofproto->name, ofp_port);
836 return (ofproto->ofproto_class->get_stp_port_status
837 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
841 /* Queue DSCP configuration. */
843 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
844 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
845 * to implement QoS. Instead, it is used to implement features which require
846 * knowledge of what queues exist on a port, and some basic information about
849 * Returns 0 if successful, otherwise a positive errno value. */
851 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
852 const struct ofproto_port_queue *queues,
855 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
858 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
859 ofproto->name, ofp_port);
863 return (ofproto->ofproto_class->set_queues
864 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
868 /* Connectivity Fault Management configuration. */
870 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
872 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
874 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
875 if (ofport && ofproto->ofproto_class->set_cfm) {
876 ofproto->ofproto_class->set_cfm(ofport, NULL);
880 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
881 * basic configuration from the configuration members in 'cfm', and the remote
882 * maintenance point ID from remote_mpid. Ignores the statistics members of
885 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
887 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
888 const struct cfm_settings *s)
890 struct ofport *ofport;
893 ofport = ofproto_get_port(ofproto, ofp_port);
895 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
896 ofproto->name, ofp_port);
900 /* XXX: For configuration simplicity, we only support one remote_mpid
901 * outside of the CFM module. It's not clear if this is the correct long
902 * term solution or not. */
903 error = (ofproto->ofproto_class->set_cfm
904 ? ofproto->ofproto_class->set_cfm(ofport, s)
907 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
908 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
909 ovs_strerror(error));
913 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
914 * 'ofproto' does not have a port 'ofp_port'. */
916 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
917 const struct smap *cfg)
919 struct ofport *ofport;
922 ofport = ofproto_get_port(ofproto, ofp_port);
924 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
925 ofproto->name, ofp_port);
929 error = (ofproto->ofproto_class->set_bfd
930 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
933 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
934 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
935 ovs_strerror(error));
939 /* Populates 'status' with key value pairs indicating the status of the BFD
940 * session on 'ofp_port'. This information is intended to be populated in the
941 * OVS database. Has no effect if 'ofp_port' is not na OpenFlow port in
944 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
947 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
948 return (ofport && ofproto->ofproto_class->get_bfd_status
949 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
953 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
954 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
955 * 0 if LACP partner information is not current (generally indicating a
956 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
958 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
960 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
961 return (ofport && ofproto->ofproto_class->port_is_lacp_current
962 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
968 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
969 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
970 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
971 * configuration plus, if there is more than one slave, a bonding
974 * If 'aux' is already registered then this function updates its configuration
975 * to 's'. Otherwise, this function registers a new bundle.
977 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
980 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
981 const struct ofproto_bundle_settings *s)
983 return (ofproto->ofproto_class->bundle_set
984 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
988 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
989 * If no such bundle has been registered, this has no effect. */
991 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
993 return ofproto_bundle_register(ofproto, aux, NULL);
997 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
998 * If 'aux' is already registered then this function updates its configuration
999 * to 's'. Otherwise, this function registers a new mirror. */
1001 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1002 const struct ofproto_mirror_settings *s)
1004 return (ofproto->ofproto_class->mirror_set
1005 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1009 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1010 * If no mirror has been registered, this has no effect. */
1012 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1014 return ofproto_mirror_register(ofproto, aux, NULL);
1017 /* Retrieves statistics from mirror associated with client data pointer
1018 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1019 * 'bytes', respectively. If a particular counters is not supported,
1020 * the appropriate argument is set to UINT64_MAX. */
1022 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1023 uint64_t *packets, uint64_t *bytes)
1025 if (!ofproto->ofproto_class->mirror_get_stats) {
1026 *packets = *bytes = UINT64_MAX;
1030 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1034 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1035 * which all packets are flooded, instead of using MAC learning. If
1036 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1038 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1041 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1043 return (ofproto->ofproto_class->set_flood_vlans
1044 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1048 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1049 * output for a mirror. */
1051 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1053 return (ofproto->ofproto_class->is_mirror_output_bundle
1054 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1058 /* Configuration of OpenFlow tables. */
1060 /* Returns the number of OpenFlow tables in 'ofproto'. */
1062 ofproto_get_n_tables(const struct ofproto *ofproto)
1064 return ofproto->n_tables;
1067 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1068 * settings from 's'. 'table_id' must be in the range 0 through the number of
1069 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1071 * For read-only tables, only the name may be configured. */
1073 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1074 const struct ofproto_table_settings *s)
1076 struct oftable *table;
1078 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1079 table = &ofproto->tables[table_id];
1081 oftable_set_name(table, s->name);
1083 if (table->flags & OFTABLE_READONLY) {
1088 oftable_enable_eviction(table, s->groups, s->n_groups);
1090 oftable_disable_eviction(table);
1093 table->max_flows = s->max_flows;
1094 ovs_rwlock_rdlock(&table->cls.rwlock);
1095 if (classifier_count(&table->cls) > table->max_flows
1096 && table->eviction_fields) {
1097 /* 'table' contains more flows than allowed. We might not be able to
1098 * evict them right away because of the asynchronous nature of flow
1099 * table changes. Schedule eviction for later. */
1100 switch (ofproto->state) {
1102 ofproto->state = S_EVICT;
1106 /* We're already deleting flows, nothing more to do. */
1110 ovs_rwlock_unlock(&table->cls.rwlock);
1114 ofproto_has_snoops(const struct ofproto *ofproto)
1116 return connmgr_has_snoops(ofproto->connmgr);
1120 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1122 connmgr_get_snoops(ofproto->connmgr, snoops);
1125 /* Deletes 'rule' from 'cls' within 'ofproto'.
1127 * Within an ofproto implementation, this function allows an ofproto
1128 * implementation to destroy any rules that remain when its ->destruct()
1129 * function is called. This function is not suitable for use elsewhere in an
1130 * ofproto implementation.
1132 * This function is also used internally in ofproto.c.
1134 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1135 * Cycle" in ofproto-provider.h.
1137 * The 'cls' argument is redundant (it is &ofproto->tables[rule->table_id].cls)
1138 * but it allows Clang to do better checking. */
1140 ofproto_rule_delete(struct ofproto *ofproto, struct classifier *cls,
1142 OVS_REQ_WRLOCK(cls->rwlock)
1144 struct ofopgroup *group;
1146 ovs_assert(!rule->pending);
1147 ovs_assert(cls == &ofproto->tables[rule->table_id].cls);
1149 group = ofopgroup_create_unattached(ofproto);
1150 ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1151 ovs_rwlock_wrlock(&rule->rwlock);
1152 oftable_remove_rule__(ofproto, cls, rule);
1153 ofproto->ofproto_class->rule_delete(rule);
1154 ofopgroup_submit(group);
1158 ofproto_flush__(struct ofproto *ofproto)
1160 struct oftable *table;
1162 if (ofproto->ofproto_class->flush) {
1163 ofproto->ofproto_class->flush(ofproto);
1166 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1167 struct rule *rule, *next_rule;
1168 struct cls_cursor cursor;
1170 if (table->flags & OFTABLE_HIDDEN) {
1174 ovs_rwlock_wrlock(&table->cls.rwlock);
1175 cls_cursor_init(&cursor, &table->cls, NULL);
1176 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1177 if (!rule->pending) {
1178 ofproto_rule_delete(ofproto, &table->cls, rule);
1181 ovs_rwlock_unlock(&table->cls.rwlock);
1186 ofproto_destroy__(struct ofproto *ofproto)
1188 struct oftable *table;
1190 ovs_assert(list_is_empty(&ofproto->pending));
1191 ovs_assert(!ofproto->n_pending);
1193 destroy_rule_executes(ofproto);
1194 guarded_list_destroy(&ofproto->rule_executes);
1196 connmgr_destroy(ofproto->connmgr);
1198 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1199 free(ofproto->name);
1200 free(ofproto->type);
1201 free(ofproto->mfr_desc);
1202 free(ofproto->hw_desc);
1203 free(ofproto->sw_desc);
1204 free(ofproto->serial_desc);
1205 free(ofproto->dp_desc);
1206 hmap_destroy(&ofproto->ports);
1207 shash_destroy(&ofproto->port_by_name);
1208 bitmap_free(ofproto->ofp_port_ids);
1209 simap_destroy(&ofproto->ofp_requests);
1211 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1212 oftable_destroy(table);
1214 free(ofproto->tables);
1216 hmap_destroy(&ofproto->deletions);
1218 free(ofproto->vlan_bitmap);
1220 ofproto->ofproto_class->dealloc(ofproto);
1224 ofproto_destroy(struct ofproto *p)
1226 struct ofport *ofport, *next_ofport;
1233 meter_delete(p, 1, p->meter_features.max_meters);
1234 p->meter_features.max_meters = 0;
1240 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1241 ofport_destroy(ofport);
1244 p->ofproto_class->destruct(p);
1245 ofproto_destroy__(p);
1248 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1249 * kernel datapath, for example, this destroys the datapath in the kernel, and
1250 * with the netdev-based datapath, it tears down the data structures that
1251 * represent the datapath.
1253 * The datapath should not be currently open as an ofproto. */
1255 ofproto_delete(const char *name, const char *type)
1257 const struct ofproto_class *class = ofproto_class_find__(type);
1258 return (!class ? EAFNOSUPPORT
1259 : !class->del ? EACCES
1260 : class->del(type, name));
1264 process_port_change(struct ofproto *ofproto, int error, char *devname)
1266 if (error == ENOBUFS) {
1267 reinit_ports(ofproto);
1268 } else if (!error) {
1269 update_port(ofproto, devname);
1275 ofproto_type_run(const char *datapath_type)
1277 const struct ofproto_class *class;
1280 datapath_type = ofproto_normalize_type(datapath_type);
1281 class = ofproto_class_find__(datapath_type);
1283 error = class->type_run ? class->type_run(datapath_type) : 0;
1284 if (error && error != EAGAIN) {
1285 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1286 datapath_type, ovs_strerror(error));
1292 ofproto_type_run_fast(const char *datapath_type)
1294 const struct ofproto_class *class;
1297 datapath_type = ofproto_normalize_type(datapath_type);
1298 class = ofproto_class_find__(datapath_type);
1300 error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1301 if (error && error != EAGAIN) {
1302 VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1303 datapath_type, ovs_strerror(error));
1309 ofproto_type_wait(const char *datapath_type)
1311 const struct ofproto_class *class;
1313 datapath_type = ofproto_normalize_type(datapath_type);
1314 class = ofproto_class_find__(datapath_type);
1316 if (class->type_wait) {
1317 class->type_wait(datapath_type);
1322 ofproto_run(struct ofproto *p)
1324 struct sset changed_netdevs;
1325 const char *changed_netdev;
1326 struct ofport *ofport;
1329 error = p->ofproto_class->run(p);
1330 if (error && error != EAGAIN) {
1331 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1334 run_rule_executes(p);
1336 /* Restore the eviction group heap invariant occasionally. */
1337 if (p->eviction_group_timer < time_msec()) {
1340 p->eviction_group_timer = time_msec() + 1000;
1342 for (i = 0; i < p->n_tables; i++) {
1343 struct oftable *table = &p->tables[i];
1344 struct eviction_group *evg;
1345 struct cls_cursor cursor;
1348 if (!table->eviction_fields) {
1352 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1353 heap_rebuild(&evg->rules);
1356 ovs_rwlock_rdlock(&table->cls.rwlock);
1357 cls_cursor_init(&cursor, &table->cls, NULL);
1358 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1359 if (!rule->eviction_group
1360 && (rule->idle_timeout || rule->hard_timeout)) {
1361 eviction_group_add_rule(rule);
1364 ovs_rwlock_unlock(&table->cls.rwlock);
1368 if (p->ofproto_class->port_poll) {
1371 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1372 process_port_change(p, error, devname);
1376 /* Update OpenFlow port status for any port whose netdev has changed.
1378 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1379 * destroyed, so it's not safe to update ports directly from the
1380 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1381 * need this two-phase approach. */
1382 sset_init(&changed_netdevs);
1383 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1384 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1385 if (ofport->change_seq != change_seq) {
1386 ofport->change_seq = change_seq;
1387 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1390 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1391 update_port(p, changed_netdev);
1393 sset_destroy(&changed_netdevs);
1397 connmgr_run(p->connmgr, handle_openflow);
1401 connmgr_run(p->connmgr, NULL);
1403 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1404 p->state = S_OPENFLOW;
1409 connmgr_run(p->connmgr, NULL);
1411 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1412 connmgr_flushed(p->connmgr);
1413 p->state = S_OPENFLOW;
1421 if (time_msec() >= p->next_op_report) {
1422 long long int ago = (time_msec() - p->first_op) / 1000;
1423 long long int interval = (p->last_op - p->first_op) / 1000;
1427 ds_put_format(&s, "%d flow_mods ",
1428 p->n_add + p->n_delete + p->n_modify);
1429 if (interval == ago) {
1430 ds_put_format(&s, "in the last %lld s", ago);
1431 } else if (interval) {
1432 ds_put_format(&s, "in the %lld s starting %lld s ago",
1435 ds_put_format(&s, "%lld s ago", ago);
1438 ds_put_cstr(&s, " (");
1440 ds_put_format(&s, "%d adds, ", p->n_add);
1443 ds_put_format(&s, "%d deletes, ", p->n_delete);
1446 ds_put_format(&s, "%d modifications, ", p->n_modify);
1449 ds_put_char(&s, ')');
1451 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1454 p->n_add = p->n_delete = p->n_modify = 0;
1455 p->next_op_report = LLONG_MAX;
1461 /* Performs periodic activity required by 'ofproto' that needs to be done
1462 * with the least possible latency.
1464 * It makes sense to call this function a couple of times per poll loop, to
1465 * provide a significant performance boost on some benchmarks with the
1466 * ofproto-dpif implementation. */
1468 ofproto_run_fast(struct ofproto *p)
1472 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1473 if (error && error != EAGAIN) {
1474 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1475 p->name, ovs_strerror(error));
1481 ofproto_wait(struct ofproto *p)
1483 struct ofport *ofport;
1485 p->ofproto_class->wait(p);
1486 if (p->ofproto_class->port_poll_wait) {
1487 p->ofproto_class->port_poll_wait(p);
1490 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1491 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1492 poll_immediate_wake();
1498 connmgr_wait(p->connmgr, true);
1503 connmgr_wait(p->connmgr, false);
1504 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1505 poll_immediate_wake();
1512 ofproto_is_alive(const struct ofproto *p)
1514 return connmgr_has_controllers(p->connmgr);
1517 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1518 * memory_report(). */
1520 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1522 const struct oftable *table;
1523 unsigned int n_rules;
1525 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1526 simap_increase(usage, "ops",
1527 ofproto->n_pending + hmap_count(&ofproto->deletions));
1530 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1531 ovs_rwlock_rdlock(&table->cls.rwlock);
1532 n_rules += classifier_count(&table->cls);
1533 ovs_rwlock_unlock(&table->cls.rwlock);
1535 simap_increase(usage, "rules", n_rules);
1537 if (ofproto->ofproto_class->get_memory_usage) {
1538 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1541 connmgr_get_memory_usage(ofproto->connmgr, usage);
1545 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1548 connmgr_get_controller_info(ofproto->connmgr, info);
1552 ofproto_free_ofproto_controller_info(struct shash *info)
1554 connmgr_free_controller_info(info);
1557 /* Makes a deep copy of 'old' into 'port'. */
1559 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1561 port->name = xstrdup(old->name);
1562 port->type = xstrdup(old->type);
1563 port->ofp_port = old->ofp_port;
1566 /* Frees memory allocated to members of 'ofproto_port'.
1568 * Do not call this function on an ofproto_port obtained from
1569 * ofproto_port_dump_next(): that function retains ownership of the data in the
1572 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1574 free(ofproto_port->name);
1575 free(ofproto_port->type);
1578 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1580 * This function provides no status indication. An error status for the entire
1581 * dump operation is provided when it is completed by calling
1582 * ofproto_port_dump_done().
1585 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1586 const struct ofproto *ofproto)
1588 dump->ofproto = ofproto;
1589 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1593 /* Attempts to retrieve another port from 'dump', which must have been created
1594 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1595 * 'port' and returns true. On failure, returns false.
1597 * Failure might indicate an actual error or merely that the last port has been
1598 * dumped. An error status for the entire dump operation is provided when it
1599 * is completed by calling ofproto_port_dump_done().
1601 * The ofproto owns the data stored in 'port'. It will remain valid until at
1602 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1603 * ofproto_port_dump_done(). */
1605 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1606 struct ofproto_port *port)
1608 const struct ofproto *ofproto = dump->ofproto;
1614 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1617 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1623 /* Completes port table dump operation 'dump', which must have been created
1624 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1625 * error-free, otherwise a positive errno value describing the problem. */
1627 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1629 const struct ofproto *ofproto = dump->ofproto;
1631 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1634 return dump->error == EOF ? 0 : dump->error;
1637 /* Returns the type to pass to netdev_open() when a datapath of type
1638 * 'datapath_type' has a port of type 'port_type', for a few special
1639 * cases when a netdev type differs from a port type. For example, when
1640 * using the userspace datapath, a port of type "internal" needs to be
1643 * Returns either 'type' itself or a string literal, which must not be
1646 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1648 const struct ofproto_class *class;
1650 datapath_type = ofproto_normalize_type(datapath_type);
1651 class = ofproto_class_find__(datapath_type);
1656 return (class->port_open_type
1657 ? class->port_open_type(datapath_type, port_type)
1661 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1662 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1663 * the port's OpenFlow port number.
1665 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1666 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1667 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1668 * 'ofp_portp' is non-null). */
1670 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1671 ofp_port_t *ofp_portp)
1673 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1676 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1678 const char *netdev_name = netdev_get_name(netdev);
1680 simap_put(&ofproto->ofp_requests, netdev_name,
1681 ofp_to_u16(ofp_port));
1682 update_port(ofproto, netdev_name);
1685 struct ofproto_port ofproto_port;
1687 ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1689 *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1690 ofproto_port_destroy(&ofproto_port);
1695 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1696 * initializes '*port' appropriately; on failure, returns a positive errno
1699 * The caller owns the data in 'ofproto_port' and must free it with
1700 * ofproto_port_destroy() when it is no longer needed. */
1702 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1703 struct ofproto_port *port)
1707 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1709 memset(port, 0, sizeof *port);
1714 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1715 * Returns 0 if successful, otherwise a positive errno. */
1717 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1719 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1720 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1721 struct simap_node *ofp_request_node;
1724 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1725 if (ofp_request_node) {
1726 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1729 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1730 if (!error && ofport) {
1731 /* 'name' is the netdev's name and update_port() is going to close the
1732 * netdev. Just in case update_port() refers to 'name' after it
1733 * destroys 'ofport', make a copy of it around the update_port()
1735 char *devname = xstrdup(name);
1736 update_port(ofproto, devname);
1743 simple_flow_mod(struct ofproto *ofproto,
1744 const struct match *match, unsigned int priority,
1745 const struct ofpact *ofpacts, size_t ofpacts_len,
1746 enum ofp_flow_mod_command command)
1748 struct ofputil_flow_mod fm;
1750 memset(&fm, 0, sizeof fm);
1752 fm.priority = priority;
1755 fm.modify_cookie = false;
1757 fm.command = command;
1758 fm.idle_timeout = 0;
1759 fm.hard_timeout = 0;
1760 fm.buffer_id = UINT32_MAX;
1761 fm.out_port = OFPP_ANY;
1763 fm.ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1764 fm.ofpacts_len = ofpacts_len;
1765 return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1768 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1769 * performs the 'n_actions' actions in 'actions'. The new flow will not
1772 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1773 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1774 * controllers; otherwise, it will be hidden.
1776 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1778 * This is a helper function for in-band control and fail-open. */
1780 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1781 unsigned int priority,
1782 const struct ofpact *ofpacts, size_t ofpacts_len)
1784 const struct rule *rule;
1787 /* First do a cheap check whether the rule we're looking for already exists
1788 * with the actions that we want. If it does, then we're done. */
1789 ovs_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1790 rule = rule_from_cls_rule(classifier_find_match_exactly(
1791 &ofproto->tables[0].cls, match, priority));
1793 ovs_rwlock_rdlock(&rule->rwlock);
1794 must_add = !ofpacts_equal(rule->actions->ofpacts,
1795 rule->actions->ofpacts_len,
1796 ofpacts, ofpacts_len);
1797 ovs_rwlock_unlock(&rule->rwlock);
1801 ovs_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1803 /* If there's no such rule or the rule doesn't have the actions we want,
1804 * fall back to a executing a full flow mod. We can't optimize this at
1805 * all because we didn't take enough locks above to ensure that the flow
1806 * table didn't already change beneath us. */
1808 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1809 OFPFC_MODIFY_STRICT);
1813 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1814 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1815 * operation cannot be initiated now but may be retried later.
1817 * This is a helper function for in-band control and fail-open. */
1819 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1821 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1824 /* Searches for a rule with matching criteria exactly equal to 'target' in
1825 * ofproto's table 0 and, if it finds one, deletes it.
1827 * This is a helper function for in-band control and fail-open. */
1829 ofproto_delete_flow(struct ofproto *ofproto,
1830 const struct match *target, unsigned int priority)
1832 struct classifier *cls = &ofproto->tables[0].cls;
1835 /* First do a cheap check whether the rule we're looking for has already
1836 * been deleted. If so, then we're done. */
1837 ovs_rwlock_rdlock(&cls->rwlock);
1838 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1840 ovs_rwlock_unlock(&cls->rwlock);
1845 /* Fall back to a executing a full flow mod. We can't optimize this at all
1846 * because we didn't take enough locks above to ensure that the flow table
1847 * didn't already change beneath us. */
1848 return simple_flow_mod(ofproto, target, priority, NULL, 0,
1849 OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
1852 /* Starts the process of deleting all of the flows from all of ofproto's flow
1853 * tables and then reintroducing the flows required by in-band control and
1854 * fail-open. The process will complete in a later call to ofproto_run(). */
1856 ofproto_flush_flows(struct ofproto *ofproto)
1858 COVERAGE_INC(ofproto_flush);
1859 ofproto->state = S_FLUSH;
1863 reinit_ports(struct ofproto *p)
1865 struct ofproto_port_dump dump;
1866 struct sset devnames;
1867 struct ofport *ofport;
1868 struct ofproto_port ofproto_port;
1869 const char *devname;
1871 COVERAGE_INC(ofproto_reinit_ports);
1873 sset_init(&devnames);
1874 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1875 sset_add(&devnames, netdev_get_name(ofport->netdev));
1877 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1878 sset_add(&devnames, ofproto_port.name);
1881 SSET_FOR_EACH (devname, &devnames) {
1882 update_port(p, devname);
1884 sset_destroy(&devnames);
1888 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1892 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1893 port_idx = port_idx ? port_idx : UINT16_MAX;
1895 if (port_idx >= ofproto->max_ports
1896 || bitmap_is_set(ofproto->ofp_port_ids, port_idx)) {
1897 uint16_t end_port_no = ofproto->alloc_port_no;
1899 /* Search for a free OpenFlow port number. We try not to
1900 * immediately reuse them to prevent problems due to old
1903 if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1904 ofproto->alloc_port_no = 0;
1906 if (!bitmap_is_set(ofproto->ofp_port_ids,
1907 ofproto->alloc_port_no)) {
1908 port_idx = ofproto->alloc_port_no;
1911 if (ofproto->alloc_port_no == end_port_no) {
1916 bitmap_set1(ofproto->ofp_port_ids, port_idx);
1917 return u16_to_ofp(port_idx);
1921 dealloc_ofp_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
1923 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
1924 bitmap_set0(ofproto->ofp_port_ids, ofp_to_u16(ofp_port));
1928 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1929 * pointer if the netdev cannot be opened. On success, also fills in
1931 static struct netdev *
1932 ofport_open(struct ofproto *ofproto,
1933 struct ofproto_port *ofproto_port,
1934 struct ofputil_phy_port *pp)
1936 enum netdev_flags flags;
1937 struct netdev *netdev;
1940 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1942 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1943 "cannot be opened (%s)",
1945 ofproto_port->name, ofproto_port->ofp_port,
1946 ofproto_port->name, ovs_strerror(error));
1950 if (ofproto_port->ofp_port == OFPP_NONE) {
1951 if (!strcmp(ofproto->name, ofproto_port->name)) {
1952 ofproto_port->ofp_port = OFPP_LOCAL;
1954 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
1955 ofproto_port->name);
1958 pp->port_no = ofproto_port->ofp_port;
1959 netdev_get_etheraddr(netdev, pp->hw_addr);
1960 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1961 netdev_get_flags(netdev, &flags);
1962 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1963 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1964 netdev_get_features(netdev, &pp->curr, &pp->advertised,
1965 &pp->supported, &pp->peer);
1966 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
1967 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
1972 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
1973 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1976 ofport_equal(const struct ofputil_phy_port *a,
1977 const struct ofputil_phy_port *b)
1979 return (eth_addr_equals(a->hw_addr, b->hw_addr)
1980 && a->state == b->state
1981 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1982 && a->curr == b->curr
1983 && a->advertised == b->advertised
1984 && a->supported == b->supported
1985 && a->peer == b->peer
1986 && a->curr_speed == b->curr_speed
1987 && a->max_speed == b->max_speed);
1990 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1991 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1992 * one with the same name or port number). */
1994 ofport_install(struct ofproto *p,
1995 struct netdev *netdev, const struct ofputil_phy_port *pp)
1997 const char *netdev_name = netdev_get_name(netdev);
1998 struct ofport *ofport;
2001 /* Create ofport. */
2002 ofport = p->ofproto_class->port_alloc();
2007 ofport->ofproto = p;
2008 ofport->netdev = netdev;
2009 ofport->change_seq = netdev_change_seq(netdev);
2011 ofport->ofp_port = pp->port_no;
2012 ofport->created = time_msec();
2014 /* Add port to 'p'. */
2015 hmap_insert(&p->ports, &ofport->hmap_node,
2016 hash_ofp_port(ofport->ofp_port));
2017 shash_add(&p->port_by_name, netdev_name, ofport);
2019 update_mtu(p, ofport);
2021 /* Let the ofproto_class initialize its private data. */
2022 error = p->ofproto_class->port_construct(ofport);
2026 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
2030 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2031 p->name, netdev_name, ovs_strerror(error));
2033 ofport_destroy__(ofport);
2035 netdev_close(netdev);
2039 /* Removes 'ofport' from 'p' and destroys it. */
2041 ofport_remove(struct ofport *ofport)
2043 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
2045 ofport_destroy(ofport);
2048 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2051 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2053 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2055 ofport_remove(port);
2059 /* Updates 'port' with new 'pp' description.
2061 * Does not handle a name or port number change. The caller must implement
2062 * such a change as a delete followed by an add. */
2064 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2066 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2067 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2068 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2069 port->pp.state = pp->state;
2070 port->pp.curr = pp->curr;
2071 port->pp.advertised = pp->advertised;
2072 port->pp.supported = pp->supported;
2073 port->pp.peer = pp->peer;
2074 port->pp.curr_speed = pp->curr_speed;
2075 port->pp.max_speed = pp->max_speed;
2077 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
2080 /* Update OpenFlow 'state' in 'port' and notify controller. */
2082 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2084 if (port->pp.state != state) {
2085 port->pp.state = state;
2086 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
2092 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2094 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2096 if (port->ofproto->ofproto_class->set_realdev) {
2097 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2099 if (port->ofproto->ofproto_class->set_stp_port) {
2100 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2102 if (port->ofproto->ofproto_class->set_cfm) {
2103 port->ofproto->ofproto_class->set_cfm(port, NULL);
2105 if (port->ofproto->ofproto_class->bundle_remove) {
2106 port->ofproto->ofproto_class->bundle_remove(port);
2112 ofport_destroy__(struct ofport *port)
2114 struct ofproto *ofproto = port->ofproto;
2115 const char *name = netdev_get_name(port->netdev);
2117 hmap_remove(&ofproto->ports, &port->hmap_node);
2118 shash_delete(&ofproto->port_by_name,
2119 shash_find(&ofproto->port_by_name, name));
2121 netdev_close(port->netdev);
2122 ofproto->ofproto_class->port_dealloc(port);
2126 ofport_destroy(struct ofport *port)
2129 dealloc_ofp_port(port->ofproto, port->ofp_port);
2130 port->ofproto->ofproto_class->port_destruct(port);
2131 ofport_destroy__(port);
2136 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2138 struct ofport *port;
2140 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2142 if (port->ofp_port == ofp_port) {
2150 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2152 struct ofproto *ofproto = port->ofproto;
2155 if (ofproto->ofproto_class->port_get_stats) {
2156 error = ofproto->ofproto_class->port_get_stats(port, stats);
2165 update_port(struct ofproto *ofproto, const char *name)
2167 struct ofproto_port ofproto_port;
2168 struct ofputil_phy_port pp;
2169 struct netdev *netdev;
2170 struct ofport *port;
2172 COVERAGE_INC(ofproto_update_port);
2174 /* Fetch 'name''s location and properties from the datapath. */
2175 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2176 ? ofport_open(ofproto, &ofproto_port, &pp)
2180 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2181 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2182 struct netdev *old_netdev = port->netdev;
2184 /* 'name' hasn't changed location. Any properties changed? */
2185 if (!ofport_equal(&port->pp, &pp)) {
2186 ofport_modified(port, &pp);
2189 update_mtu(ofproto, port);
2191 /* Install the newly opened netdev in case it has changed.
2192 * Don't close the old netdev yet in case port_modified has to
2193 * remove a retained reference to it.*/
2194 port->netdev = netdev;
2195 port->change_seq = netdev_change_seq(netdev);
2197 if (port->ofproto->ofproto_class->port_modified) {
2198 port->ofproto->ofproto_class->port_modified(port);
2201 netdev_close(old_netdev);
2203 /* If 'port' is nonnull then its name differs from 'name' and thus
2204 * we should delete it. If we think there's a port named 'name'
2205 * then its port number must be wrong now so delete it too. */
2207 ofport_remove(port);
2209 ofport_remove_with_name(ofproto, name);
2210 ofport_install(ofproto, netdev, &pp);
2213 /* Any port named 'name' is gone now. */
2214 ofport_remove_with_name(ofproto, name);
2216 ofproto_port_destroy(&ofproto_port);
2220 init_ports(struct ofproto *p)
2222 struct ofproto_port_dump dump;
2223 struct ofproto_port ofproto_port;
2224 struct shash_node *node, *next;
2226 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2227 const char *name = ofproto_port.name;
2229 if (shash_find(&p->port_by_name, name)) {
2230 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2233 struct ofputil_phy_port pp;
2234 struct netdev *netdev;
2236 /* Check if an OpenFlow port number had been requested. */
2237 node = shash_find(&init_ofp_ports, name);
2239 const struct iface_hint *iface_hint = node->data;
2240 simap_put(&p->ofp_requests, name,
2241 ofp_to_u16(iface_hint->ofp_port));
2244 netdev = ofport_open(p, &ofproto_port, &pp);
2246 ofport_install(p, netdev, &pp);
2247 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2248 p->alloc_port_no = MAX(p->alloc_port_no,
2249 ofp_to_u16(ofproto_port.ofp_port));
2255 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2256 struct iface_hint *iface_hint = node->data;
2258 if (!strcmp(iface_hint->br_name, p->name)) {
2259 free(iface_hint->br_name);
2260 free(iface_hint->br_type);
2262 shash_delete(&init_ofp_ports, node);
2269 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2270 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2272 find_min_mtu(struct ofproto *p)
2274 struct ofport *ofport;
2277 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2278 struct netdev *netdev = ofport->netdev;
2281 /* Skip any internal ports, since that's what we're trying to
2283 if (!strcmp(netdev_get_type(netdev), "internal")) {
2287 if (netdev_get_mtu(netdev, &dev_mtu)) {
2290 if (!mtu || dev_mtu < mtu) {
2295 return mtu ? mtu: ETH_PAYLOAD_MAX;
2298 /* Update MTU of all datapath devices on 'p' to the minimum of the
2299 * non-datapath ports in event of 'port' added or changed. */
2301 update_mtu(struct ofproto *p, struct ofport *port)
2303 struct ofport *ofport;
2304 struct netdev *netdev = port->netdev;
2305 int dev_mtu, old_min;
2307 if (netdev_get_mtu(netdev, &dev_mtu)) {
2311 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2312 if (dev_mtu > p->min_mtu) {
2313 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2314 dev_mtu = p->min_mtu;
2317 port->mtu = dev_mtu;
2321 /* For non-internal port find new min mtu. */
2322 old_min = p->min_mtu;
2323 port->mtu = dev_mtu;
2324 p->min_mtu = find_min_mtu(p);
2325 if (p->min_mtu == old_min) {
2329 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2330 struct netdev *netdev = ofport->netdev;
2332 if (!strcmp(netdev_get_type(netdev), "internal")) {
2333 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2334 ofport->mtu = p->min_mtu;
2341 ofproto_rule_ref(struct rule *rule)
2346 atomic_add(&rule->ref_count, 1, &orig);
2347 ovs_assert(orig != 0);
2352 ofproto_rule_unref(struct rule *rule)
2357 atomic_sub(&rule->ref_count, 1, &orig);
2359 rule->ofproto->ofproto_class->rule_destruct(rule);
2360 ofproto_rule_destroy__(rule);
2362 ovs_assert(orig != 0);
2368 ofproto_rule_destroy__(struct rule *rule)
2370 cls_rule_destroy(&rule->cr);
2371 rule_actions_unref(rule->actions);
2372 ovs_mutex_destroy(&rule->timeout_mutex);
2373 ovs_rwlock_destroy(&rule->rwlock);
2374 rule->ofproto->ofproto_class->rule_dealloc(rule);
2377 /* Creates and returns a new 'struct rule_actions', with a ref_count of 1,
2378 * whose actions are a copy of from the 'ofpacts_len' bytes of 'ofpacts'. */
2379 struct rule_actions *
2380 rule_actions_create(const struct ofpact *ofpacts, size_t ofpacts_len)
2382 struct rule_actions *actions;
2384 actions = xmalloc(sizeof *actions);
2385 atomic_init(&actions->ref_count, 1);
2386 actions->ofpacts = xmemdup(ofpacts, ofpacts_len);
2387 actions->ofpacts_len = ofpacts_len;
2388 actions->meter_id = ofpacts_get_meter(ofpacts, ofpacts_len);
2392 /* Increments 'actions''s ref_count. */
2394 rule_actions_ref(struct rule_actions *actions)
2399 atomic_add(&actions->ref_count, 1, &orig);
2400 ovs_assert(orig != 0);
2404 /* Decrements 'actions''s ref_count and frees 'actions' if the ref_count
2407 rule_actions_unref(struct rule_actions *actions)
2412 atomic_sub(&actions->ref_count, 1, &orig);
2416 ovs_assert(orig != 0);
2421 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2422 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2424 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2426 return (port == OFPP_ANY
2427 || ofpacts_output_to_port(rule->actions->ofpacts,
2428 rule->actions->ofpacts_len, port));
2431 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2432 * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2434 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2436 if (ofproto_rule_has_out_port(op->rule, out_port)) {
2441 case OFOPERATION_ADD:
2442 case OFOPERATION_DELETE:
2445 case OFOPERATION_MODIFY:
2446 case OFOPERATION_REPLACE:
2447 return ofpacts_output_to_port(op->actions->ofpacts,
2448 op->actions->ofpacts_len, out_port);
2455 rule_execute_destroy(struct rule_execute *e)
2457 ofproto_rule_unref(e->rule);
2458 list_remove(&e->list_node);
2462 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2463 * by passing them to the ofproto provider. */
2465 run_rule_executes(struct ofproto *ofproto)
2467 struct rule_execute *e, *next;
2468 struct list executes;
2470 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2471 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2472 union flow_in_port in_port_;
2475 in_port_.ofp_port = e->in_port;
2476 flow_extract(e->packet, 0, 0, NULL, &in_port_, &flow);
2477 ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2479 rule_execute_destroy(e);
2483 /* Destroys and discards all "rule_execute" operations queued up in
2484 * ofproto->rule_executes. */
2486 destroy_rule_executes(struct ofproto *ofproto)
2488 struct rule_execute *e, *next;
2489 struct list executes;
2491 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2492 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2493 ofpbuf_delete(e->packet);
2494 rule_execute_destroy(e);
2498 /* Returns true if 'rule' should be hidden from the controller.
2500 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2501 * (e.g. by in-band control) and are intentionally hidden from the
2504 ofproto_rule_is_hidden(const struct rule *rule)
2506 return rule->cr.priority > UINT16_MAX;
2509 static enum oftable_flags
2510 rule_get_flags(const struct rule *rule)
2512 return rule->ofproto->tables[rule->table_id].flags;
2516 rule_is_modifiable(const struct rule *rule)
2518 return !(rule_get_flags(rule) & OFTABLE_READONLY);
2522 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2524 ofconn_send_reply(ofconn, make_echo_reply(oh));
2529 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2531 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2532 struct ofputil_switch_features features;
2533 struct ofport *port;
2539 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2541 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2543 /* Count only non-hidden tables in the number of tables. (Hidden tables,
2544 * if present, are always at the end.) */
2545 n_tables = ofproto->n_tables;
2546 for (i = 0; i < ofproto->n_tables; i++) {
2547 if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2553 features.datapath_id = ofproto->datapath_id;
2554 features.n_buffers = pktbuf_capacity();
2555 features.n_tables = n_tables;
2556 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2557 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2559 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2561 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2562 features.auxiliary_id = 0;
2563 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2565 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2566 ofputil_put_switch_features_port(&port->pp, b);
2569 ofconn_send_reply(ofconn, b);
2574 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2576 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2577 struct ofp_switch_config *osc;
2578 enum ofp_config_flags flags;
2582 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2583 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2584 flags = ofproto->frag_handling;
2585 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2586 if (oh->version < OFP13_VERSION
2587 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2588 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2590 osc->flags = htons(flags);
2591 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2592 ofconn_send_reply(ofconn, buf);
2598 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2600 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2601 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2602 uint16_t flags = ntohs(osc->flags);
2604 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2605 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2606 enum ofp_config_flags cur = ofproto->frag_handling;
2607 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2609 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2611 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2612 ofproto->frag_handling = next;
2614 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2616 ofputil_frag_handling_to_string(next));
2620 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2621 ofconn_set_invalid_ttl_to_controller(ofconn,
2622 (oh->version < OFP13_VERSION
2623 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2625 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2630 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2631 * error message code for the caller to propagate upward. Otherwise, returns
2634 * The log message mentions 'msg_type'. */
2636 reject_slave_controller(struct ofconn *ofconn)
2638 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2639 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2640 return OFPERR_OFPBRC_EPERM;
2646 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are appropriate
2647 * for a packet with the prerequisites satisfied by 'flow' in table 'table_id'.
2648 * 'flow' may be temporarily modified, but is restored at return.
2651 ofproto_check_ofpacts(struct ofproto *ofproto,
2652 const struct ofpact ofpacts[], size_t ofpacts_len,
2653 struct flow *flow, uint8_t table_id)
2658 error = ofpacts_check(ofpacts, ofpacts_len, flow,
2659 u16_to_ofp(ofproto->max_ports), table_id);
2664 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2665 if (mid && ofproto_get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2666 return OFPERR_OFPMMFC_INVALID_METER;
2672 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2674 struct ofproto *p = ofconn_get_ofproto(ofconn);
2675 struct ofputil_packet_out po;
2676 struct ofpbuf *payload;
2677 uint64_t ofpacts_stub[1024 / 8];
2678 struct ofpbuf ofpacts;
2680 union flow_in_port in_port_;
2683 COVERAGE_INC(ofproto_packet_out);
2685 error = reject_slave_controller(ofconn);
2690 /* Decode message. */
2691 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2692 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2694 goto exit_free_ofpacts;
2696 if (ofp_to_u16(po.in_port) >= p->max_ports
2697 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2698 error = OFPERR_OFPBRC_BAD_PORT;
2699 goto exit_free_ofpacts;
2704 if (po.buffer_id != UINT32_MAX) {
2705 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2706 if (error || !payload) {
2707 goto exit_free_ofpacts;
2710 /* Ensure that the L3 header is 32-bit aligned. */
2711 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2714 /* Verify actions against packet, then send packet if successful. */
2715 in_port_.ofp_port = po.in_port;
2716 flow_extract(payload, 0, 0, NULL, &in_port_, &flow);
2717 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len, &flow, 0);
2719 error = p->ofproto_class->packet_out(p, payload, &flow,
2720 po.ofpacts, po.ofpacts_len);
2722 ofpbuf_delete(payload);
2725 ofpbuf_uninit(&ofpacts);
2731 update_port_config(struct ofport *port,
2732 enum ofputil_port_config config,
2733 enum ofputil_port_config mask)
2735 enum ofputil_port_config old_config = port->pp.config;
2736 enum ofputil_port_config toggle;
2738 toggle = (config ^ port->pp.config) & mask;
2739 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2740 if (config & OFPUTIL_PC_PORT_DOWN) {
2741 netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2743 netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2745 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2748 port->pp.config ^= toggle;
2749 if (port->pp.config != old_config) {
2750 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2755 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2757 struct ofproto *p = ofconn_get_ofproto(ofconn);
2758 struct ofputil_port_mod pm;
2759 struct ofport *port;
2762 error = reject_slave_controller(ofconn);
2767 error = ofputil_decode_port_mod(oh, &pm);
2772 port = ofproto_get_port(p, pm.port_no);
2774 return OFPERR_OFPPMFC_BAD_PORT;
2775 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2776 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2778 update_port_config(port, pm.config, pm.mask);
2780 netdev_set_advertisements(port->netdev, pm.advertise);
2787 handle_desc_stats_request(struct ofconn *ofconn,
2788 const struct ofp_header *request)
2790 static const char *default_mfr_desc = "Nicira, Inc.";
2791 static const char *default_hw_desc = "Open vSwitch";
2792 static const char *default_sw_desc = VERSION;
2793 static const char *default_serial_desc = "None";
2794 static const char *default_dp_desc = "None";
2796 struct ofproto *p = ofconn_get_ofproto(ofconn);
2797 struct ofp_desc_stats *ods;
2800 msg = ofpraw_alloc_stats_reply(request, 0);
2801 ods = ofpbuf_put_zeros(msg, sizeof *ods);
2802 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
2803 sizeof ods->mfr_desc);
2804 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
2805 sizeof ods->hw_desc);
2806 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
2807 sizeof ods->sw_desc);
2808 ovs_strlcpy(ods->serial_num,
2809 p->serial_desc ? p->serial_desc : default_serial_desc,
2810 sizeof ods->serial_num);
2811 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
2812 sizeof ods->dp_desc);
2813 ofconn_send_reply(ofconn, msg);
2819 handle_table_stats_request(struct ofconn *ofconn,
2820 const struct ofp_header *request)
2822 struct ofproto *p = ofconn_get_ofproto(ofconn);
2823 struct ofp12_table_stats *ots;
2828 /* Set up default values.
2830 * ofp12_table_stats is used as a generic structure as
2831 * it is able to hold all the fields for ofp10_table_stats
2832 * and ofp11_table_stats (and of course itself).
2834 ots = xcalloc(p->n_tables, sizeof *ots);
2835 for (i = 0; i < p->n_tables; i++) {
2836 ots[i].table_id = i;
2837 sprintf(ots[i].name, "table%zu", i);
2838 ots[i].match = htonll(OFPXMT12_MASK);
2839 ots[i].wildcards = htonll(OFPXMT12_MASK);
2840 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
2841 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
2842 ots[i].write_setfields = htonll(OFPXMT12_MASK);
2843 ots[i].apply_setfields = htonll(OFPXMT12_MASK);
2844 ots[i].metadata_match = htonll(UINT64_MAX);
2845 ots[i].metadata_write = htonll(UINT64_MAX);
2846 ots[i].instructions = htonl(OFPIT11_ALL);
2847 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
2848 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2849 ovs_rwlock_rdlock(&p->tables[i].cls.rwlock);
2850 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2851 ovs_rwlock_unlock(&p->tables[i].cls.rwlock);
2854 p->ofproto_class->get_tables(p, ots);
2856 /* Post-process the tables, dropping hidden tables. */
2857 n_tables = p->n_tables;
2858 for (i = 0; i < p->n_tables; i++) {
2859 const struct oftable *table = &p->tables[i];
2861 if (table->flags & OFTABLE_HIDDEN) {
2867 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2870 if (table->max_flows < ntohl(ots[i].max_entries)) {
2871 ots[i].max_entries = htonl(table->max_flows);
2875 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
2876 ofconn_send_reply(ofconn, msg);
2884 append_port_stat(struct ofport *port, struct list *replies)
2886 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
2888 calc_duration(port->created, time_msec(),
2889 &ops.duration_sec, &ops.duration_nsec);
2891 /* Intentionally ignore return value, since errors will set
2892 * 'stats' to all-1s, which is correct for OpenFlow, and
2893 * netdev_get_stats() will log errors. */
2894 ofproto_port_get_stats(port, &ops.stats);
2896 ofputil_append_port_stat(replies, &ops);
2900 handle_port_stats_request(struct ofconn *ofconn,
2901 const struct ofp_header *request)
2903 struct ofproto *p = ofconn_get_ofproto(ofconn);
2904 struct ofport *port;
2905 struct list replies;
2909 error = ofputil_decode_port_stats_request(request, &port_no);
2914 ofpmp_init(&replies, request);
2915 if (port_no != OFPP_ANY) {
2916 port = ofproto_get_port(p, port_no);
2918 append_port_stat(port, &replies);
2921 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2922 append_port_stat(port, &replies);
2926 ofconn_send_replies(ofconn, &replies);
2931 handle_port_desc_stats_request(struct ofconn *ofconn,
2932 const struct ofp_header *request)
2934 struct ofproto *p = ofconn_get_ofproto(ofconn);
2935 enum ofp_version version;
2936 struct ofport *port;
2937 struct list replies;
2939 ofpmp_init(&replies, request);
2941 version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
2942 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2943 ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
2946 ofconn_send_replies(ofconn, &replies);
2951 hash_cookie(ovs_be64 cookie)
2953 return hash_2words((OVS_FORCE uint64_t)cookie >> 32,
2954 (OVS_FORCE uint64_t)cookie);
2958 cookies_insert(struct ofproto *ofproto, struct rule *rule)
2959 OVS_REQUIRES(ofproto_mutex)
2961 hindex_insert(&ofproto->cookies, &rule->cookie_node,
2962 hash_cookie(rule->flow_cookie));
2966 cookies_remove(struct ofproto *ofproto, struct rule *rule)
2967 OVS_REQUIRES(ofproto_mutex)
2969 hindex_remove(&ofproto->cookies, &rule->cookie_node);
2973 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
2974 ovs_be64 new_cookie)
2976 if (new_cookie != rule->flow_cookie) {
2977 ovs_mutex_lock(&ofproto_mutex);
2978 cookies_remove(ofproto, rule);
2980 ovs_rwlock_wrlock(&rule->rwlock);
2981 rule->flow_cookie = new_cookie;
2982 ovs_rwlock_unlock(&rule->rwlock);
2984 cookies_insert(ofproto, rule);
2985 ovs_mutex_unlock(&ofproto_mutex);
2990 calc_duration(long long int start, long long int now,
2991 uint32_t *sec, uint32_t *nsec)
2993 long long int msecs = now - start;
2994 *sec = msecs / 1000;
2995 *nsec = (msecs % 1000) * (1000 * 1000);
2998 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
2999 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
3001 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3003 return (table_id == 0xff || table_id < ofproto->n_tables
3005 : OFPERR_OFPBRC_BAD_TABLE_ID);
3009 static struct oftable *
3010 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3012 struct oftable *table;
3014 for (table = &ofproto->tables[table_id];
3015 table < &ofproto->tables[ofproto->n_tables];
3017 if (!(table->flags & OFTABLE_HIDDEN)) {
3025 static struct oftable *
3026 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3028 if (table_id == 0xff) {
3029 return next_visible_table(ofproto, 0);
3030 } else if (table_id < ofproto->n_tables) {
3031 return &ofproto->tables[table_id];
3037 static struct oftable *
3038 next_matching_table(const struct ofproto *ofproto,
3039 const struct oftable *table, uint8_t table_id)
3041 return (table_id == 0xff
3042 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3046 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3048 * - If TABLE_ID is 0xff, this iterates over every classifier table in
3049 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3051 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3052 * only once, for that table. (This can be used to access tables marked
3055 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3056 * entered at all. (Perhaps you should have validated TABLE_ID with
3057 * check_table_id().)
3059 * All parameters are evaluated multiple times.
3061 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
3062 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
3064 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3066 /* Initializes 'criteria' in a straightforward way based on the other
3069 * For "loose" matching, the 'priority' parameter is unimportant and may be
3072 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3073 const struct match *match, unsigned int priority,
3074 ovs_be64 cookie, ovs_be64 cookie_mask,
3075 ofp_port_t out_port)
3077 criteria->table_id = table_id;
3078 cls_rule_init(&criteria->cr, match, priority);
3079 criteria->cookie = cookie;
3080 criteria->cookie_mask = cookie_mask;
3081 criteria->out_port = out_port;
3085 rule_criteria_destroy(struct rule_criteria *criteria)
3087 cls_rule_destroy(&criteria->cr);
3091 rule_collection_init(struct rule_collection *rules)
3093 rules->rules = rules->stub;
3095 rules->capacity = ARRAY_SIZE(rules->stub);
3099 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3101 if (rules->n >= rules->capacity) {
3102 size_t old_size, new_size;
3104 old_size = rules->capacity * sizeof *rules->rules;
3105 rules->capacity *= 2;
3106 new_size = rules->capacity * sizeof *rules->rules;
3108 if (rules->rules == rules->stub) {
3109 rules->rules = xmalloc(new_size);
3110 memcpy(rules->rules, rules->stub, old_size);
3112 rules->rules = xrealloc(rules->rules, new_size);
3116 rules->rules[rules->n++] = rule;
3120 rule_collection_destroy(struct rule_collection *rules)
3122 if (rules->rules != rules->stub) {
3128 collect_rule(struct rule *rule, const struct rule_criteria *c,
3129 struct rule_collection *rules)
3131 if (ofproto_rule_is_hidden(rule)) {
3133 } else if (rule->pending) {
3134 return OFPROTO_POSTPONE;
3136 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3137 && ofproto_rule_has_out_port(rule, c->out_port)
3138 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3139 rule_collection_add(rules, rule);
3145 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3146 * on classifiers rules are done in the "loose" way required for OpenFlow
3147 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3150 * Hidden rules are always omitted.
3152 * Returns 0 on success, otherwise an OpenFlow error code. */
3154 collect_rules_loose(struct ofproto *ofproto,
3155 const struct rule_criteria *criteria,
3156 struct rule_collection *rules)
3158 struct oftable *table;
3161 rule_collection_init(rules);
3163 error = check_table_id(ofproto, criteria->table_id);
3168 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3171 ovs_mutex_lock(&ofproto_mutex);
3172 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3173 hash_cookie(criteria->cookie),
3174 &ofproto->cookies) {
3175 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3176 error = collect_rule(rule, criteria, rules);
3182 ovs_mutex_unlock(&ofproto_mutex);
3184 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3185 struct cls_cursor cursor;
3188 ovs_rwlock_rdlock(&table->cls.rwlock);
3189 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3190 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3191 error = collect_rule(rule, criteria, rules);
3196 ovs_rwlock_unlock(&table->cls.rwlock);
3202 rule_collection_destroy(rules);
3207 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3208 * on classifiers rules are done in the "strict" way required for OpenFlow
3209 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3210 * rules on list 'rules'.
3212 * Hidden rules are always omitted.
3214 * Returns 0 on success, otherwise an OpenFlow error code. */
3216 collect_rules_strict(struct ofproto *ofproto,
3217 const struct rule_criteria *criteria,
3218 struct rule_collection *rules)
3220 struct oftable *table;
3223 rule_collection_init(rules);
3225 error = check_table_id(ofproto, criteria->table_id);
3230 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3233 ovs_mutex_lock(&ofproto_mutex);
3234 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3235 hash_cookie(criteria->cookie),
3236 &ofproto->cookies) {
3237 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3238 error = collect_rule(rule, criteria, rules);
3244 ovs_mutex_unlock(&ofproto_mutex);
3246 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3249 ovs_rwlock_rdlock(&table->cls.rwlock);
3250 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3251 &table->cls, &criteria->cr));
3252 ovs_rwlock_unlock(&table->cls.rwlock);
3254 error = collect_rule(rule, criteria, rules);
3264 rule_collection_destroy(rules);
3269 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3270 * forced into the range of a uint16_t. */
3272 age_secs(long long int age_ms)
3274 return (age_ms < 0 ? 0
3275 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3276 : (unsigned int) age_ms / 1000);
3280 handle_flow_stats_request(struct ofconn *ofconn,
3281 const struct ofp_header *request)
3283 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3284 struct ofputil_flow_stats_request fsr;
3285 struct rule_criteria criteria;
3286 struct rule_collection rules;
3287 struct list replies;
3291 error = ofputil_decode_flow_stats_request(&fsr, request);
3296 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3297 fsr.cookie_mask, fsr.out_port);
3298 error = collect_rules_loose(ofproto, &criteria, &rules);
3299 rule_criteria_destroy(&criteria);
3304 ofpmp_init(&replies, request);
3305 for (i = 0; i < rules.n; i++) {
3306 struct rule *rule = rules.rules[i];
3307 long long int now = time_msec();
3308 struct ofputil_flow_stats fs;
3310 minimatch_expand(&rule->cr.match, &fs.match);
3311 fs.priority = rule->cr.priority;
3312 fs.cookie = rule->flow_cookie;
3313 fs.table_id = rule->table_id;
3314 calc_duration(rule->created, now, &fs.duration_sec, &fs.duration_nsec);
3315 fs.idle_age = age_secs(now - rule->used);
3316 fs.hard_age = age_secs(now - rule->modified);
3317 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3319 fs.ofpacts = rule->actions->ofpacts;
3320 fs.ofpacts_len = rule->actions->ofpacts_len;
3322 ovs_mutex_lock(&rule->timeout_mutex);
3323 fs.idle_timeout = rule->idle_timeout;
3324 fs.hard_timeout = rule->hard_timeout;
3325 ovs_mutex_unlock(&rule->timeout_mutex);
3328 if (rule->send_flow_removed) {
3329 fs.flags |= OFPUTIL_FF_SEND_FLOW_REM;
3330 /* FIXME: Implement OFPUTIL_FF_NO_PKT_COUNTS and
3331 OFPUTIL_FF_NO_BYT_COUNTS. */
3333 ofputil_append_flow_stats_reply(&fs, &replies);
3335 rule_collection_destroy(&rules);
3337 ofconn_send_replies(ofconn, &replies);
3343 flow_stats_ds(struct rule *rule, struct ds *results)
3345 uint64_t packet_count, byte_count;
3347 rule->ofproto->ofproto_class->rule_get_stats(rule,
3348 &packet_count, &byte_count);
3350 if (rule->table_id != 0) {
3351 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3353 ds_put_format(results, "duration=%llds, ",
3354 (time_msec() - rule->created) / 1000);
3355 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3356 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3357 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3358 cls_rule_format(&rule->cr, results);
3359 ds_put_char(results, ',');
3360 ofpacts_format(rule->actions->ofpacts, rule->actions->ofpacts_len,
3362 ds_put_cstr(results, "\n");
3365 /* Adds a pretty-printed description of all flows to 'results', including
3366 * hidden flows (e.g., set up by in-band control). */
3368 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3370 struct oftable *table;
3372 OFPROTO_FOR_EACH_TABLE (table, p) {
3373 struct cls_cursor cursor;
3376 ovs_rwlock_rdlock(&table->cls.rwlock);
3377 cls_cursor_init(&cursor, &table->cls, NULL);
3378 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3379 flow_stats_ds(rule, results);
3381 ovs_rwlock_unlock(&table->cls.rwlock);
3385 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3386 * '*engine_type' and '*engine_id', respectively. */
3388 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3389 uint8_t *engine_type, uint8_t *engine_id)
3391 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3394 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3395 * true if the port's CFM status was successfully stored into '*status'.
3396 * Returns false if the port did not have CFM configured, in which case
3397 * '*status' is indeterminate.
3399 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3401 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3402 struct ofproto_cfm_status *status)
3404 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3406 && ofproto->ofproto_class->get_cfm_status
3407 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3411 handle_aggregate_stats_request(struct ofconn *ofconn,
3412 const struct ofp_header *oh)
3414 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3415 struct ofputil_flow_stats_request request;
3416 struct ofputil_aggregate_stats stats;
3417 bool unknown_packets, unknown_bytes;
3418 struct rule_criteria criteria;
3419 struct rule_collection rules;
3420 struct ofpbuf *reply;
3424 error = ofputil_decode_flow_stats_request(&request, oh);
3429 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3430 request.cookie, request.cookie_mask,
3432 error = collect_rules_loose(ofproto, &criteria, &rules);
3433 rule_criteria_destroy(&criteria);
3438 memset(&stats, 0, sizeof stats);
3439 unknown_packets = unknown_bytes = false;
3440 for (i = 0; i < rules.n; i++) {
3441 struct rule *rule = rules.rules[i];
3442 uint64_t packet_count;
3443 uint64_t byte_count;
3445 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3448 if (packet_count == UINT64_MAX) {
3449 unknown_packets = true;
3451 stats.packet_count += packet_count;
3454 if (byte_count == UINT64_MAX) {
3455 unknown_bytes = true;
3457 stats.byte_count += byte_count;
3462 if (unknown_packets) {
3463 stats.packet_count = UINT64_MAX;
3465 if (unknown_bytes) {
3466 stats.byte_count = UINT64_MAX;
3469 rule_collection_destroy(&rules);
3471 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3472 ofconn_send_reply(ofconn, reply);
3477 struct queue_stats_cbdata {
3478 struct ofport *ofport;
3479 struct list replies;
3484 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3485 const struct netdev_queue_stats *stats)
3487 struct ofputil_queue_stats oqs;
3489 oqs.port_no = cbdata->ofport->pp.port_no;
3490 oqs.queue_id = queue_id;
3491 oqs.tx_bytes = stats->tx_bytes;
3492 oqs.tx_packets = stats->tx_packets;
3493 oqs.tx_errors = stats->tx_errors;
3494 if (stats->created != LLONG_MIN) {
3495 calc_duration(stats->created, cbdata->now,
3496 &oqs.duration_sec, &oqs.duration_nsec);
3498 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3500 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3504 handle_queue_stats_dump_cb(uint32_t queue_id,
3505 struct netdev_queue_stats *stats,
3508 struct queue_stats_cbdata *cbdata = cbdata_;
3510 put_queue_stats(cbdata, queue_id, stats);
3514 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3515 struct queue_stats_cbdata *cbdata)
3517 cbdata->ofport = port;
3518 if (queue_id == OFPQ_ALL) {
3519 netdev_dump_queue_stats(port->netdev,
3520 handle_queue_stats_dump_cb, cbdata);
3522 struct netdev_queue_stats stats;
3524 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3525 put_queue_stats(cbdata, queue_id, &stats);
3527 return OFPERR_OFPQOFC_BAD_QUEUE;
3534 handle_queue_stats_request(struct ofconn *ofconn,
3535 const struct ofp_header *rq)
3537 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3538 struct queue_stats_cbdata cbdata;
3539 struct ofport *port;
3541 struct ofputil_queue_stats_request oqsr;
3543 COVERAGE_INC(ofproto_queue_req);
3545 ofpmp_init(&cbdata.replies, rq);
3546 cbdata.now = time_msec();
3548 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3553 if (oqsr.port_no == OFPP_ANY) {
3554 error = OFPERR_OFPQOFC_BAD_QUEUE;
3555 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3556 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3561 port = ofproto_get_port(ofproto, oqsr.port_no);
3563 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3564 : OFPERR_OFPQOFC_BAD_PORT);
3567 ofconn_send_replies(ofconn, &cbdata.replies);
3569 ofpbuf_list_delete(&cbdata.replies);
3576 is_flow_deletion_pending(const struct ofproto *ofproto,
3577 const struct cls_rule *cls_rule,
3580 if (!hmap_is_empty(&ofproto->deletions)) {
3581 struct ofoperation *op;
3583 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3584 cls_rule_hash(cls_rule, table_id),
3585 &ofproto->deletions) {
3586 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3596 evict_rule_from_table(struct ofproto *ofproto, struct oftable *table)
3601 ovs_rwlock_rdlock(&table->cls.rwlock);
3602 n_rules = classifier_count(&table->cls);
3603 ovs_rwlock_unlock(&table->cls.rwlock);
3605 if (n_rules < table->max_flows) {
3607 } else if (!choose_rule_to_evict(table, &rule)) {
3608 return OFPERR_OFPFMFC_TABLE_FULL;
3609 } else if (rule->pending) {
3610 ovs_rwlock_unlock(&rule->rwlock);
3611 return OFPROTO_POSTPONE;
3613 struct ofopgroup *group;
3615 group = ofopgroup_create_unattached(ofproto);
3616 delete_flow__(rule, group, OFPRR_EVICTION);
3617 ofopgroup_submit(group);
3623 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3624 * in which no matching flow already exists in the flow table.
3626 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3627 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3628 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3629 * initiated now but may be retried later.
3631 * The caller retains ownership of 'fm->ofpacts'.
3633 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3636 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3637 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3639 struct oftable *table;
3640 struct ofopgroup *group;
3646 error = check_table_id(ofproto, fm->table_id);
3652 if (fm->table_id == 0xff) {
3653 if (ofproto->ofproto_class->rule_choose_table) {
3654 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3660 ovs_assert(table_id < ofproto->n_tables);
3664 } else if (fm->table_id < ofproto->n_tables) {
3665 table_id = fm->table_id;
3667 return OFPERR_OFPBRC_BAD_TABLE_ID;
3670 table = &ofproto->tables[table_id];
3672 if (table->flags & OFTABLE_READONLY) {
3673 return OFPERR_OFPBRC_EPERM;
3676 cls_rule_init(&cr, &fm->match, fm->priority);
3678 /* Transform "add" into "modify" if there's an existing identical flow. */
3679 ovs_rwlock_rdlock(&table->cls.rwlock);
3680 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3681 ovs_rwlock_unlock(&table->cls.rwlock);
3683 cls_rule_destroy(&cr);
3684 if (!rule_is_modifiable(rule)) {
3685 return OFPERR_OFPBRC_EPERM;
3686 } else if (rule->pending) {
3687 return OFPROTO_POSTPONE;
3689 struct rule_collection rules;
3691 rule_collection_init(&rules);
3692 rule_collection_add(&rules, rule);
3693 fm->modify_cookie = true;
3694 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3695 rule_collection_destroy(&rules);
3701 /* Verify actions. */
3702 error = ofproto_check_ofpacts(ofproto, fm->ofpacts, fm->ofpacts_len,
3703 &fm->match.flow, table_id);
3705 cls_rule_destroy(&cr);
3709 /* Serialize against pending deletion. */
3710 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3711 cls_rule_destroy(&cr);
3712 return OFPROTO_POSTPONE;
3715 /* Check for overlap, if requested. */
3716 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3719 ovs_rwlock_rdlock(&table->cls.rwlock);
3720 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3721 ovs_rwlock_unlock(&table->cls.rwlock);
3724 cls_rule_destroy(&cr);
3725 return OFPERR_OFPFMFC_OVERLAP;
3729 /* If necessary, evict an existing rule to clear out space. */
3730 error = evict_rule_from_table(ofproto, table);
3732 cls_rule_destroy(&cr);
3736 /* Allocate new rule. */
3737 rule = ofproto->ofproto_class->rule_alloc();
3739 cls_rule_destroy(&cr);
3740 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3741 ofproto->name, ovs_strerror(error));
3745 /* Initialize base state. */
3746 rule->ofproto = ofproto;
3747 cls_rule_move(&rule->cr, &cr);
3748 atomic_init(&rule->ref_count, 1);
3749 rule->pending = NULL;
3750 rule->flow_cookie = fm->new_cookie;
3751 rule->created = rule->modified = rule->used = time_msec();
3753 ovs_mutex_init(&rule->timeout_mutex);
3754 ovs_mutex_lock(&rule->timeout_mutex);
3755 rule->idle_timeout = fm->idle_timeout;
3756 rule->hard_timeout = fm->hard_timeout;
3757 ovs_mutex_unlock(&rule->timeout_mutex);
3759 rule->table_id = table - ofproto->tables;
3760 rule->send_flow_removed = (fm->flags & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3761 rule->actions = rule_actions_create(fm->ofpacts, fm->ofpacts_len);
3762 list_init(&rule->meter_list_node);
3763 rule->eviction_group = NULL;
3764 list_init(&rule->expirable);
3765 rule->monitor_flags = 0;
3766 rule->add_seqno = 0;
3767 rule->modify_seqno = 0;
3768 ovs_rwlock_init(&rule->rwlock);
3770 /* Construct rule, initializing derived state. */
3771 error = ofproto->ofproto_class->rule_construct(rule);
3773 ofproto_rule_destroy__(rule);
3778 oftable_insert_rule(rule);
3780 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3781 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
3782 ofproto->ofproto_class->rule_insert(rule);
3783 ofopgroup_submit(group);
3788 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3790 /* Modifies the rules listed in 'rules', changing their actions to match those
3793 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3796 * Returns 0 on success, otherwise an OpenFlow error code. */
3798 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3799 struct ofputil_flow_mod *fm, const struct ofp_header *request,
3800 const struct rule_collection *rules)
3802 enum ofoperation_type type;
3803 struct ofopgroup *group;
3807 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
3808 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3809 error = OFPERR_OFPBRC_EPERM;
3810 for (i = 0; i < rules->n; i++) {
3811 struct rule *rule = rules->rules[i];
3812 struct ofoperation *op;
3813 bool actions_changed;
3814 bool reset_counters;
3816 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
3818 if (rule_is_modifiable(rule)) {
3819 /* At least one rule is modifiable, don't report EPERM error. */
3825 /* Verify actions. */
3826 error = ofpacts_check(fm->ofpacts, fm->ofpacts_len, &fm->match.flow,
3827 u16_to_ofp(ofproto->max_ports), rule->table_id);
3832 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
3833 rule->actions->ofpacts,
3834 rule->actions->ofpacts_len);
3836 op = ofoperation_create(group, rule, type, 0);
3838 if (fm->modify_cookie && fm->new_cookie != htonll(UINT64_MAX)) {
3839 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
3841 if (type == OFOPERATION_REPLACE) {
3842 ovs_mutex_lock(&rule->timeout_mutex);
3843 rule->idle_timeout = fm->idle_timeout;
3844 rule->hard_timeout = fm->hard_timeout;
3845 ovs_mutex_unlock(&rule->timeout_mutex);
3847 rule->send_flow_removed = (fm->flags
3848 & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3850 if (fm->idle_timeout || fm->hard_timeout) {
3851 if (!rule->eviction_group) {
3852 eviction_group_add_rule(rule);
3855 eviction_group_remove_rule(rule);
3859 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
3860 if (actions_changed || reset_counters) {
3861 struct rule_actions *new_actions;
3863 op->actions = rule->actions;
3864 new_actions = rule_actions_create(fm->ofpacts, fm->ofpacts_len);
3866 ovs_rwlock_wrlock(&rule->rwlock);
3867 rule->actions = new_actions;
3868 ovs_rwlock_unlock(&rule->rwlock);
3870 rule->ofproto->ofproto_class->rule_modify_actions(rule,
3873 ofoperation_complete(op, 0);
3876 ofopgroup_submit(group);
3882 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
3883 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3885 if (fm->cookie_mask != htonll(0) || fm->new_cookie == htonll(UINT64_MAX)) {
3888 return add_flow(ofproto, ofconn, fm, request);
3891 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
3894 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3897 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3898 struct ofputil_flow_mod *fm,
3899 const struct ofp_header *request)
3901 struct rule_criteria criteria;
3902 struct rule_collection rules;
3905 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
3906 fm->cookie, fm->cookie_mask, OFPP_ANY);
3907 error = collect_rules_loose(ofproto, &criteria, &rules);
3908 rule_criteria_destroy(&criteria);
3911 error = (rules.n > 0
3912 ? modify_flows__(ofproto, ofconn, fm, request, &rules)
3913 : modify_flows_add(ofproto, ofconn, fm, request));
3916 rule_collection_destroy(&rules);
3921 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
3924 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3927 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3928 struct ofputil_flow_mod *fm,
3929 const struct ofp_header *request)
3931 struct rule_criteria criteria;
3932 struct rule_collection rules;
3935 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
3936 fm->cookie, fm->cookie_mask, OFPP_ANY);
3937 error = collect_rules_strict(ofproto, &criteria, &rules);
3938 rule_criteria_destroy(&criteria);
3942 error = modify_flows_add(ofproto, ofconn, fm, request);
3943 } else if (rules.n == 1) {
3944 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3948 rule_collection_destroy(&rules);
3953 /* OFPFC_DELETE implementation. */
3956 delete_flow__(struct rule *rule, struct ofopgroup *group,
3957 enum ofp_flow_removed_reason reason)
3959 struct ofproto *ofproto = rule->ofproto;
3961 ofproto_rule_send_removed(rule, reason);
3963 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
3964 oftable_remove_rule(rule);
3965 ofproto->ofproto_class->rule_delete(rule);
3968 /* Deletes the rules listed in 'rules'.
3970 * Returns 0 on success, otherwise an OpenFlow error code. */
3972 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3973 const struct ofp_header *request,
3974 const struct rule_collection *rules,
3975 enum ofp_flow_removed_reason reason)
3977 struct ofopgroup *group;
3980 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3981 for (i = 0; i < rules->n; i++) {
3982 struct rule *rule = rules->rules[i];
3983 ovs_rwlock_wrlock(&rule->rwlock);
3984 delete_flow__(rule, group, reason);
3986 ofopgroup_submit(group);
3991 /* Implements OFPFC_DELETE. */
3993 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3994 const struct ofputil_flow_mod *fm,
3995 const struct ofp_header *request)
3997 struct rule_criteria criteria;
3998 struct rule_collection rules;
4001 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4002 fm->cookie, fm->cookie_mask,
4004 error = collect_rules_loose(ofproto, &criteria, &rules);
4005 rule_criteria_destroy(&criteria);
4007 if (!error && rules.n > 0) {
4008 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4010 rule_collection_destroy(&rules);
4015 /* Implements OFPFC_DELETE_STRICT. */
4017 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4018 const struct ofputil_flow_mod *fm,
4019 const struct ofp_header *request)
4021 struct rule_criteria criteria;
4022 struct rule_collection rules;
4025 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4026 fm->cookie, fm->cookie_mask, fm->out_port);
4027 error = collect_rules_strict(ofproto, &criteria, &rules);
4028 rule_criteria_destroy(&criteria);
4030 if (!error && rules.n > 0) {
4031 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4033 rule_collection_destroy(&rules);
4039 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4041 struct ofputil_flow_removed fr;
4043 if (ofproto_rule_is_hidden(rule) || !rule->send_flow_removed) {
4047 minimatch_expand(&rule->cr.match, &fr.match);
4048 fr.priority = rule->cr.priority;
4049 fr.cookie = rule->flow_cookie;
4051 fr.table_id = rule->table_id;
4052 calc_duration(rule->created, time_msec(),
4053 &fr.duration_sec, &fr.duration_nsec);
4054 ovs_mutex_lock(&rule->timeout_mutex);
4055 fr.idle_timeout = rule->idle_timeout;
4056 fr.hard_timeout = rule->hard_timeout;
4057 ovs_mutex_unlock(&rule->timeout_mutex);
4058 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4061 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4064 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4065 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4068 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4071 * ofproto implementation ->run() functions should use this function to expire
4072 * OpenFlow flows. */
4074 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4076 struct ofproto *ofproto = rule->ofproto;
4077 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
4079 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
4080 ofproto_rule_send_removed(rule, reason);
4082 ovs_rwlock_wrlock(&cls->rwlock);
4083 ofproto_rule_delete(ofproto, cls, rule);
4084 ovs_rwlock_unlock(&cls->rwlock);
4087 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
4088 * means "infinite". */
4090 reduce_timeout(uint16_t max, uint16_t *timeout)
4092 if (max && (!*timeout || *timeout > max)) {
4097 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4098 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4099 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
4101 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4103 ofproto_rule_reduce_timeouts(struct rule *rule,
4104 uint16_t idle_timeout, uint16_t hard_timeout)
4105 OVS_EXCLUDED(ofproto_mutex, rule->timeout_mutex)
4107 if (!idle_timeout && !hard_timeout) {
4111 ovs_mutex_lock(&ofproto_mutex);
4112 if (list_is_empty(&rule->expirable)) {
4113 list_insert(&rule->ofproto->expirable, &rule->expirable);
4115 ovs_mutex_unlock(&ofproto_mutex);
4117 ovs_mutex_lock(&rule->timeout_mutex);
4118 reduce_timeout(idle_timeout, &rule->idle_timeout);
4119 reduce_timeout(hard_timeout, &rule->hard_timeout);
4120 ovs_mutex_unlock(&rule->timeout_mutex);
4124 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4126 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4127 struct ofputil_flow_mod fm;
4128 uint64_t ofpacts_stub[1024 / 8];
4129 struct ofpbuf ofpacts;
4133 error = reject_slave_controller(ofconn);
4138 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4139 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4142 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4145 goto exit_free_ofpacts;
4148 /* Record the operation for logging a summary report. */
4149 switch (fm.command) {
4155 case OFPFC_MODIFY_STRICT:
4156 ofproto->n_modify++;
4160 case OFPFC_DELETE_STRICT:
4161 ofproto->n_delete++;
4166 if (ofproto->next_op_report == LLONG_MAX) {
4167 ofproto->first_op = now;
4168 ofproto->next_op_report = MAX(now + 10 * 1000,
4169 ofproto->op_backoff);
4170 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4172 ofproto->last_op = now;
4175 ofpbuf_uninit(&ofpacts);
4181 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4182 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4186 if (ofproto->n_pending < 50) {
4187 switch (fm->command) {
4189 error = add_flow(ofproto, ofconn, fm, oh);
4193 error = modify_flows_loose(ofproto, ofconn, fm, oh);
4196 case OFPFC_MODIFY_STRICT:
4197 error = modify_flow_strict(ofproto, ofconn, fm, oh);
4201 error = delete_flows_loose(ofproto, ofconn, fm, oh);
4204 case OFPFC_DELETE_STRICT:
4205 error = delete_flow_strict(ofproto, ofconn, fm, oh);
4209 if (fm->command > 0xff) {
4210 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4211 "flow_mod_table_id extension is not enabled",
4214 error = OFPERR_OFPFMFC_BAD_COMMAND;
4218 ovs_assert(!list_is_empty(&ofproto->pending));
4219 error = OFPROTO_POSTPONE;
4222 run_rule_executes(ofproto);
4227 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4229 struct ofputil_role_request request;
4230 struct ofputil_role_request reply;
4234 error = ofputil_decode_role_message(oh, &request);
4239 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4240 if (ofconn_get_role(ofconn) != request.role
4241 && ofconn_has_pending_opgroups(ofconn)) {
4242 return OFPROTO_POSTPONE;
4245 if (request.have_generation_id
4246 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4247 return OFPERR_OFPRRFC_STALE;
4250 ofconn_set_role(ofconn, request.role);
4253 reply.role = ofconn_get_role(ofconn);
4254 reply.have_generation_id = ofconn_get_master_election_id(
4255 ofconn, &reply.generation_id);
4256 buf = ofputil_encode_role_reply(oh, &reply);
4257 ofconn_send_reply(ofconn, buf);
4263 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4264 const struct ofp_header *oh)
4266 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4267 enum ofputil_protocol cur, next;
4269 cur = ofconn_get_protocol(ofconn);
4270 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4271 ofconn_set_protocol(ofconn, next);
4277 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4279 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4280 enum ofputil_protocol cur, next;
4281 enum ofputil_protocol next_base;
4283 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4285 return OFPERR_OFPBRC_EPERM;
4288 cur = ofconn_get_protocol(ofconn);
4289 next = ofputil_protocol_set_base(cur, next_base);
4290 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4291 /* Avoid sending async messages in surprising protocol. */
4292 return OFPROTO_POSTPONE;
4295 ofconn_set_protocol(ofconn, next);
4300 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4301 const struct ofp_header *oh)
4303 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4306 format = ntohl(msg->format);
4307 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4308 return OFPERR_OFPBRC_EPERM;
4311 if (format != ofconn_get_packet_in_format(ofconn)
4312 && ofconn_has_pending_opgroups(ofconn)) {
4313 /* Avoid sending async message in surprsing packet in format. */
4314 return OFPROTO_POSTPONE;
4317 ofconn_set_packet_in_format(ofconn, format);
4322 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4324 const struct nx_async_config *msg = ofpmsg_body(oh);
4325 uint32_t master[OAM_N_TYPES];
4326 uint32_t slave[OAM_N_TYPES];
4328 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4329 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4330 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4332 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4333 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4334 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4336 ofconn_set_async_config(ofconn, master, slave);
4337 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4338 !ofconn_get_miss_send_len(ofconn)) {
4339 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4346 handle_nxt_set_controller_id(struct ofconn *ofconn,
4347 const struct ofp_header *oh)
4349 const struct nx_controller_id *nci = ofpmsg_body(oh);
4351 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4352 return OFPERR_NXBRC_MUST_BE_ZERO;
4355 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4360 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4364 if (ofconn_has_pending_opgroups(ofconn)) {
4365 return OFPROTO_POSTPONE;
4368 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4369 ? OFPRAW_OFPT10_BARRIER_REPLY
4370 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4371 ofconn_send_reply(ofconn, buf);
4376 ofproto_compose_flow_refresh_update(const struct rule *rule,
4377 enum nx_flow_monitor_flags flags,
4380 struct ofoperation *op = rule->pending;
4381 const struct rule_actions *actions;
4382 struct ofputil_flow_update fu;
4385 if (op && op->type == OFOPERATION_ADD) {
4386 /* We'll report the final flow when the operation completes. Reporting
4387 * it now would cause a duplicate report later. */
4391 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4392 ? NXFME_ADDED : NXFME_MODIFIED);
4394 ovs_mutex_lock(&rule->timeout_mutex);
4395 fu.idle_timeout = rule->idle_timeout;
4396 fu.hard_timeout = rule->hard_timeout;
4397 ovs_mutex_unlock(&rule->timeout_mutex);
4398 fu.table_id = rule->table_id;
4399 fu.cookie = rule->flow_cookie;
4400 minimatch_expand(&rule->cr.match, &match);
4402 fu.priority = rule->cr.priority;
4404 if (!(flags & NXFMF_ACTIONS)) {
4407 actions = rule->actions;
4409 /* An operation is in progress. Use the previous version of the flow's
4410 * actions, so that when the operation commits we report the change. */
4412 case OFOPERATION_ADD:
4415 case OFOPERATION_MODIFY:
4416 case OFOPERATION_REPLACE:
4417 actions = op->actions ? op->actions : rule->actions;
4420 case OFOPERATION_DELETE:
4421 actions = rule->actions;
4428 fu.ofpacts = actions ? actions->ofpacts : NULL;
4429 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4431 if (list_is_empty(msgs)) {
4432 ofputil_start_flow_update(msgs);
4434 ofputil_append_flow_update(&fu, msgs);
4438 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4443 for (i = 0; i < rules->n; i++) {
4444 struct rule *rule = rules->rules[i];
4445 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4446 rule->monitor_flags = 0;
4448 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4453 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4454 struct rule *rule, uint64_t seqno,
4455 struct rule_collection *rules)
4457 enum nx_flow_monitor_flags update;
4459 if (ofproto_rule_is_hidden(rule)) {
4464 ? ofoperation_has_out_port(rule->pending, m->out_port)
4465 : ofproto_rule_has_out_port(rule, m->out_port))) {
4470 if (rule->add_seqno > seqno) {
4471 update = NXFMF_ADD | NXFMF_MODIFY;
4472 } else if (rule->modify_seqno > seqno) {
4473 update = NXFMF_MODIFY;
4478 if (!(m->flags & update)) {
4482 update = NXFMF_INITIAL;
4485 if (!rule->monitor_flags) {
4486 rule_collection_add(rules, rule);
4488 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4492 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4494 struct rule_collection *rules)
4496 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4497 const struct ofoperation *op;
4498 const struct oftable *table;
4499 struct cls_rule target;
4501 cls_rule_init_from_minimatch(&target, &m->match, 0);
4502 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4503 struct cls_cursor cursor;
4506 ovs_rwlock_rdlock(&table->cls.rwlock);
4507 cls_cursor_init(&cursor, &table->cls, &target);
4508 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4509 ovs_assert(!rule->pending); /* XXX */
4510 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4512 ovs_rwlock_unlock(&table->cls.rwlock);
4515 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4516 struct rule *rule = op->rule;
4518 if (((m->table_id == 0xff
4519 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4520 : m->table_id == rule->table_id))
4521 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4522 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4525 cls_rule_destroy(&target);
4529 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4530 struct rule_collection *rules)
4532 if (m->flags & NXFMF_INITIAL) {
4533 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4538 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4539 uint64_t seqno, struct rule_collection *rules)
4541 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4545 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4547 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4548 struct ofmonitor **monitors;
4549 size_t n_monitors, allocated_monitors;
4550 struct rule_collection rules;
4551 struct list replies;
4557 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4559 n_monitors = allocated_monitors = 0;
4561 struct ofputil_flow_monitor_request request;
4562 struct ofmonitor *m;
4565 retval = ofputil_decode_flow_monitor_request(&request, &b);
4566 if (retval == EOF) {
4568 } else if (retval) {
4573 if (request.table_id != 0xff
4574 && request.table_id >= ofproto->n_tables) {
4575 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4579 error = ofmonitor_create(&request, ofconn, &m);
4584 if (n_monitors >= allocated_monitors) {
4585 monitors = x2nrealloc(monitors, &allocated_monitors,
4588 monitors[n_monitors++] = m;
4591 rule_collection_init(&rules);
4592 for (i = 0; i < n_monitors; i++) {
4593 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4596 ofpmp_init(&replies, oh);
4597 ofmonitor_compose_refresh_updates(&rules, &replies);
4598 rule_collection_destroy(&rules);
4600 ofconn_send_replies(ofconn, &replies);
4607 for (i = 0; i < n_monitors; i++) {
4608 ofmonitor_destroy(monitors[i]);
4615 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4617 struct ofmonitor *m;
4620 id = ofputil_decode_flow_monitor_cancel(oh);
4621 m = ofmonitor_lookup(ofconn, id);
4623 return OFPERR_NXBRC_FM_BAD_ID;
4626 ofmonitor_destroy(m);
4630 /* Meters implementation.
4632 * Meter table entry, indexed by the OpenFlow meter_id.
4633 * These are always dynamically allocated to allocate enough space for
4635 * 'created' is used to compute the duration for meter stats.
4636 * 'list rules' is needed so that we can delete the dependent rules when the
4637 * meter table entry is deleted.
4638 * 'provider_meter_id' is for the provider's private use.
4641 long long int created; /* Time created. */
4642 struct list rules; /* List of "struct rule_dpif"s. */
4643 ofproto_meter_id provider_meter_id;
4644 uint16_t flags; /* Meter flags. */
4645 uint16_t n_bands; /* Number of meter bands. */
4646 struct ofputil_meter_band *bands;
4650 * This is used in instruction validation at flow set-up time,
4651 * as flows may not use non-existing meters.
4652 * This is also used by ofproto-providers to translate OpenFlow meter_ids
4653 * in METER instructions to the corresponding provider meter IDs.
4654 * Return value of UINT32_MAX signifies an invalid meter.
4657 ofproto_get_provider_meter_id(const struct ofproto * ofproto,
4658 uint32_t of_meter_id)
4660 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4661 const struct meter *meter = ofproto->meters[of_meter_id];
4663 return meter->provider_meter_id.uint32;
4670 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4674 meter->flags = config->flags;
4675 meter->n_bands = config->n_bands;
4676 meter->bands = xmemdup(config->bands,
4677 config->n_bands * sizeof *meter->bands);
4680 static struct meter *
4681 meter_create(const struct ofputil_meter_config *config,
4682 ofproto_meter_id provider_meter_id)
4684 struct meter *meter;
4686 meter = xzalloc(sizeof *meter);
4687 meter->provider_meter_id = provider_meter_id;
4688 meter->created = time_msec();
4689 list_init(&meter->rules);
4691 meter_update(meter, config);
4697 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
4700 for (mid = first; mid <= last; ++mid) {
4701 struct meter *meter = ofproto->meters[mid];
4703 ofproto->meters[mid] = NULL;
4704 ofproto->ofproto_class->meter_del(ofproto,
4705 meter->provider_meter_id);
4713 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4715 ofproto_meter_id provider_meter_id = { UINT32_MAX };
4716 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
4720 return OFPERR_OFPMMFC_METER_EXISTS;
4723 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
4726 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
4727 *meterp = meter_create(&mm->meter, provider_meter_id);
4733 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4735 struct meter *meter = ofproto->meters[mm->meter.meter_id];
4739 return OFPERR_OFPMMFC_UNKNOWN_METER;
4742 error = ofproto->ofproto_class->meter_set(ofproto,
4743 &meter->provider_meter_id,
4745 ovs_assert(meter->provider_meter_id.uint32 != UINT32_MAX);
4747 meter_update(meter, &mm->meter);
4753 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
4754 struct ofputil_meter_mod *mm)
4756 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4757 uint32_t meter_id = mm->meter.meter_id;
4758 struct rule_collection rules;
4759 enum ofperr error = 0;
4760 uint32_t first, last;
4762 if (meter_id == OFPM13_ALL) {
4764 last = ofproto->meter_features.max_meters;
4766 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
4769 first = last = meter_id;
4772 /* First delete the rules that use this meter. If any of those rules are
4773 * currently being modified, postpone the whole operation until later. */
4774 rule_collection_init(&rules);
4775 for (meter_id = first; meter_id <= last; ++meter_id) {
4776 struct meter *meter = ofproto->meters[meter_id];
4777 if (meter && !list_is_empty(&meter->rules)) {
4780 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
4781 if (rule->pending) {
4782 error = OFPROTO_POSTPONE;
4785 rule_collection_add(&rules, rule);
4790 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
4793 /* Delete the meters. */
4794 meter_delete(ofproto, first, last);
4797 rule_collection_destroy(&rules);
4803 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4805 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4806 struct ofputil_meter_mod mm;
4807 uint64_t bands_stub[256 / 8];
4808 struct ofpbuf bands;
4812 error = reject_slave_controller(ofconn);
4817 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4819 error = ofputil_decode_meter_mod(oh, &mm, &bands);
4821 goto exit_free_bands;
4824 meter_id = mm.meter.meter_id;
4826 if (mm.command != OFPMC13_DELETE) {
4827 /* Fails also when meters are not implemented by the provider. */
4828 if (meter_id == 0 || meter_id > OFPM13_MAX) {
4829 error = OFPERR_OFPMMFC_INVALID_METER;
4830 goto exit_free_bands;
4831 } else if (meter_id > ofproto->meter_features.max_meters) {
4832 error = OFPERR_OFPMMFC_OUT_OF_METERS;
4833 goto exit_free_bands;
4835 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
4836 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
4837 goto exit_free_bands;
4841 switch (mm.command) {
4843 error = handle_add_meter(ofproto, &mm);
4846 case OFPMC13_MODIFY:
4847 error = handle_modify_meter(ofproto, &mm);
4850 case OFPMC13_DELETE:
4851 error = handle_delete_meter(ofconn, oh, &mm);
4855 error = OFPERR_OFPMMFC_BAD_COMMAND;
4860 ofpbuf_uninit(&bands);
4865 handle_meter_features_request(struct ofconn *ofconn,
4866 const struct ofp_header *request)
4868 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4869 struct ofputil_meter_features features;
4872 if (ofproto->ofproto_class->meter_get_features) {
4873 ofproto->ofproto_class->meter_get_features(ofproto, &features);
4875 memset(&features, 0, sizeof features);
4877 b = ofputil_encode_meter_features_reply(&features, request);
4879 ofconn_send_reply(ofconn, b);
4884 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
4887 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4888 struct list replies;
4889 uint64_t bands_stub[256 / 8];
4890 struct ofpbuf bands;
4891 uint32_t meter_id, first, last;
4893 ofputil_decode_meter_request(request, &meter_id);
4895 if (meter_id == OFPM13_ALL) {
4897 last = ofproto->meter_features.max_meters;
4899 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
4900 !ofproto->meters[meter_id]) {
4901 return OFPERR_OFPMMFC_UNKNOWN_METER;
4903 first = last = meter_id;
4906 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4907 ofpmp_init(&replies, request);
4909 for (meter_id = first; meter_id <= last; ++meter_id) {
4910 struct meter *meter = ofproto->meters[meter_id];
4912 continue; /* Skip non-existing meters. */
4914 if (type == OFPTYPE_METER_STATS_REQUEST) {
4915 struct ofputil_meter_stats stats;
4917 stats.meter_id = meter_id;
4919 /* Provider sets the packet and byte counts, we do the rest. */
4920 stats.flow_count = list_size(&meter->rules);
4921 calc_duration(meter->created, time_msec(),
4922 &stats.duration_sec, &stats.duration_nsec);
4923 stats.n_bands = meter->n_bands;
4924 ofpbuf_clear(&bands);
4926 = ofpbuf_put_uninit(&bands,
4927 meter->n_bands * sizeof *stats.bands);
4929 if (!ofproto->ofproto_class->meter_get(ofproto,
4930 meter->provider_meter_id,
4932 ofputil_append_meter_stats(&replies, &stats);
4934 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
4935 struct ofputil_meter_config config;
4937 config.meter_id = meter_id;
4938 config.flags = meter->flags;
4939 config.n_bands = meter->n_bands;
4940 config.bands = meter->bands;
4941 ofputil_append_meter_config(&replies, &config);
4945 ofconn_send_replies(ofconn, &replies);
4946 ofpbuf_uninit(&bands);
4951 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4953 const struct ofp_header *oh = msg->data;
4957 error = ofptype_decode(&type, oh);
4963 /* OpenFlow requests. */
4964 case OFPTYPE_ECHO_REQUEST:
4965 return handle_echo_request(ofconn, oh);
4967 case OFPTYPE_FEATURES_REQUEST:
4968 return handle_features_request(ofconn, oh);
4970 case OFPTYPE_GET_CONFIG_REQUEST:
4971 return handle_get_config_request(ofconn, oh);
4973 case OFPTYPE_SET_CONFIG:
4974 return handle_set_config(ofconn, oh);
4976 case OFPTYPE_PACKET_OUT:
4977 return handle_packet_out(ofconn, oh);
4979 case OFPTYPE_PORT_MOD:
4980 return handle_port_mod(ofconn, oh);
4982 case OFPTYPE_FLOW_MOD:
4983 return handle_flow_mod(ofconn, oh);
4985 case OFPTYPE_METER_MOD:
4986 return handle_meter_mod(ofconn, oh);
4988 case OFPTYPE_BARRIER_REQUEST:
4989 return handle_barrier_request(ofconn, oh);
4991 case OFPTYPE_ROLE_REQUEST:
4992 return handle_role_request(ofconn, oh);
4994 /* OpenFlow replies. */
4995 case OFPTYPE_ECHO_REPLY:
4998 /* Nicira extension requests. */
4999 case OFPTYPE_FLOW_MOD_TABLE_ID:
5000 return handle_nxt_flow_mod_table_id(ofconn, oh);
5002 case OFPTYPE_SET_FLOW_FORMAT:
5003 return handle_nxt_set_flow_format(ofconn, oh);
5005 case OFPTYPE_SET_PACKET_IN_FORMAT:
5006 return handle_nxt_set_packet_in_format(ofconn, oh);
5008 case OFPTYPE_SET_CONTROLLER_ID:
5009 return handle_nxt_set_controller_id(ofconn, oh);
5011 case OFPTYPE_FLOW_AGE:
5012 /* Nothing to do. */
5015 case OFPTYPE_FLOW_MONITOR_CANCEL:
5016 return handle_flow_monitor_cancel(ofconn, oh);
5018 case OFPTYPE_SET_ASYNC_CONFIG:
5019 return handle_nxt_set_async_config(ofconn, oh);
5021 /* Statistics requests. */
5022 case OFPTYPE_DESC_STATS_REQUEST:
5023 return handle_desc_stats_request(ofconn, oh);
5025 case OFPTYPE_FLOW_STATS_REQUEST:
5026 return handle_flow_stats_request(ofconn, oh);
5028 case OFPTYPE_AGGREGATE_STATS_REQUEST:
5029 return handle_aggregate_stats_request(ofconn, oh);
5031 case OFPTYPE_TABLE_STATS_REQUEST:
5032 return handle_table_stats_request(ofconn, oh);
5034 case OFPTYPE_PORT_STATS_REQUEST:
5035 return handle_port_stats_request(ofconn, oh);
5037 case OFPTYPE_QUEUE_STATS_REQUEST:
5038 return handle_queue_stats_request(ofconn, oh);
5040 case OFPTYPE_PORT_DESC_STATS_REQUEST:
5041 return handle_port_desc_stats_request(ofconn, oh);
5043 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
5044 return handle_flow_monitor_request(ofconn, oh);
5046 case OFPTYPE_METER_STATS_REQUEST:
5047 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
5048 return handle_meter_request(ofconn, oh, type);
5050 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
5051 return handle_meter_features_request(ofconn, oh);
5053 /* FIXME: Change the following once they are implemented: */
5054 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
5055 case OFPTYPE_GET_ASYNC_REQUEST:
5056 case OFPTYPE_GROUP_STATS_REQUEST:
5057 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
5058 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
5059 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
5060 return OFPERR_OFPBRC_BAD_TYPE;
5064 case OFPTYPE_FEATURES_REPLY:
5065 case OFPTYPE_GET_CONFIG_REPLY:
5066 case OFPTYPE_PACKET_IN:
5067 case OFPTYPE_FLOW_REMOVED:
5068 case OFPTYPE_PORT_STATUS:
5069 case OFPTYPE_BARRIER_REPLY:
5070 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
5071 case OFPTYPE_DESC_STATS_REPLY:
5072 case OFPTYPE_FLOW_STATS_REPLY:
5073 case OFPTYPE_QUEUE_STATS_REPLY:
5074 case OFPTYPE_PORT_STATS_REPLY:
5075 case OFPTYPE_TABLE_STATS_REPLY:
5076 case OFPTYPE_AGGREGATE_STATS_REPLY:
5077 case OFPTYPE_PORT_DESC_STATS_REPLY:
5078 case OFPTYPE_ROLE_REPLY:
5079 case OFPTYPE_FLOW_MONITOR_PAUSED:
5080 case OFPTYPE_FLOW_MONITOR_RESUMED:
5081 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
5082 case OFPTYPE_GET_ASYNC_REPLY:
5083 case OFPTYPE_GROUP_STATS_REPLY:
5084 case OFPTYPE_GROUP_DESC_STATS_REPLY:
5085 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
5086 case OFPTYPE_METER_STATS_REPLY:
5087 case OFPTYPE_METER_CONFIG_STATS_REPLY:
5088 case OFPTYPE_METER_FEATURES_STATS_REPLY:
5089 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
5091 return OFPERR_OFPBRC_BAD_TYPE;
5096 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
5098 int error = handle_openflow__(ofconn, ofp_msg);
5099 if (error && error != OFPROTO_POSTPONE) {
5100 ofconn_send_error(ofconn, ofp_msg->data, error);
5102 COVERAGE_INC(ofproto_recv_openflow);
5103 return error != OFPROTO_POSTPONE;
5106 /* Asynchronous operations. */
5108 /* Creates and returns a new ofopgroup that is not associated with any
5109 * OpenFlow connection.
5111 * The caller should add operations to the returned group with
5112 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5113 static struct ofopgroup *
5114 ofopgroup_create_unattached(struct ofproto *ofproto)
5116 struct ofopgroup *group = xzalloc(sizeof *group);
5117 group->ofproto = ofproto;
5118 list_init(&group->ofproto_node);
5119 list_init(&group->ops);
5120 list_init(&group->ofconn_node);
5124 /* Creates and returns a new ofopgroup for 'ofproto'.
5126 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
5127 * connection. The 'request' and 'buffer_id' arguments are ignored.
5129 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
5130 * If the ofopgroup eventually fails, then the error reply will include
5131 * 'request'. If the ofopgroup eventually succeeds, then the packet with
5132 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
5134 * The caller should add operations to the returned group with
5135 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5136 static struct ofopgroup *
5137 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
5138 const struct ofp_header *request, uint32_t buffer_id)
5140 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
5142 size_t request_len = ntohs(request->length);
5144 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
5146 ofconn_add_opgroup(ofconn, &group->ofconn_node);
5147 group->ofconn = ofconn;
5148 group->request = xmemdup(request, MIN(request_len, 64));
5149 group->buffer_id = buffer_id;
5154 /* Submits 'group' for processing.
5156 * If 'group' contains no operations (e.g. none were ever added, or all of the
5157 * ones that were added completed synchronously), then it is destroyed
5158 * immediately. Otherwise it is added to the ofproto's list of pending
5161 ofopgroup_submit(struct ofopgroup *group)
5163 if (!group->n_running) {
5164 ofopgroup_complete(group);
5166 list_push_back(&group->ofproto->pending, &group->ofproto_node);
5167 group->ofproto->n_pending++;
5172 ofopgroup_complete(struct ofopgroup *group)
5174 struct ofproto *ofproto = group->ofproto;
5176 struct ofconn *abbrev_ofconn;
5177 ovs_be32 abbrev_xid;
5179 struct ofoperation *op, *next_op;
5182 ovs_assert(!group->n_running);
5185 LIST_FOR_EACH (op, group_node, &group->ops) {
5192 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
5193 LIST_FOR_EACH (op, group_node, &group->ops) {
5194 if (op->type != OFOPERATION_DELETE) {
5195 struct ofpbuf *packet;
5198 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
5201 struct rule_execute *re;
5205 ofproto_rule_ref(op->rule);
5207 re = xmalloc(sizeof *re);
5208 re->rule = op->rule;
5209 re->in_port = in_port;
5210 re->packet = packet;
5212 if (!guarded_list_push_back(&ofproto->rule_executes,
5213 &re->list_node, 1024)) {
5214 ofproto_rule_unref(op->rule);
5215 ofpbuf_delete(re->packet);
5224 if (!error && !list_is_empty(&group->ofconn_node)) {
5225 abbrev_ofconn = group->ofconn;
5226 abbrev_xid = group->request->xid;
5228 abbrev_ofconn = NULL;
5229 abbrev_xid = htonl(0);
5231 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
5232 struct rule *rule = op->rule;
5234 /* We generally want to report the change to active OpenFlow flow
5235 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
5237 - The operation failed.
5239 - The affected rule is not visible to controllers.
5241 - The operation's only effect was to update rule->modified. */
5243 || ofproto_rule_is_hidden(rule)
5244 || (op->type == OFOPERATION_MODIFY
5246 && rule->flow_cookie == op->flow_cookie))) {
5247 /* Check that we can just cast from ofoperation_type to
5248 * nx_flow_update_event. */
5249 enum nx_flow_update_event event_type;
5252 case OFOPERATION_ADD:
5253 case OFOPERATION_REPLACE:
5254 event_type = NXFME_ADDED;
5257 case OFOPERATION_DELETE:
5258 event_type = NXFME_DELETED;
5261 case OFOPERATION_MODIFY:
5262 event_type = NXFME_MODIFIED;
5269 ofmonitor_report(ofproto->connmgr, rule, event_type,
5270 op->reason, abbrev_ofconn, abbrev_xid);
5273 rule->pending = NULL;
5276 case OFOPERATION_ADD:
5280 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
5281 if (vid_mask == VLAN_VID_MASK) {
5282 if (ofproto->vlan_bitmap) {
5283 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
5284 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
5285 bitmap_set1(ofproto->vlan_bitmap, vid);
5286 ofproto->vlans_changed = true;
5289 ofproto->vlans_changed = true;
5293 ovs_rwlock_wrlock(&rule->rwlock);
5294 oftable_remove_rule(rule);
5295 ofproto_rule_unref(rule);
5299 case OFOPERATION_DELETE:
5300 ovs_assert(!op->error);
5301 ofproto_rule_unref(rule);
5305 case OFOPERATION_MODIFY:
5306 case OFOPERATION_REPLACE:
5308 long long int now = time_msec();
5310 rule->modified = now;
5311 if (op->type == OFOPERATION_REPLACE) {
5312 rule->created = rule->used = now;
5315 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
5316 ovs_mutex_lock(&rule->timeout_mutex);
5317 rule->idle_timeout = op->idle_timeout;
5318 rule->hard_timeout = op->hard_timeout;
5319 ovs_mutex_unlock(&rule->timeout_mutex);
5321 struct rule_actions *old_actions;
5323 ovs_rwlock_wrlock(&rule->rwlock);
5324 old_actions = rule->actions;
5325 rule->actions = op->actions;
5326 ovs_rwlock_unlock(&rule->rwlock);
5329 rule_actions_unref(old_actions);
5331 rule->send_flow_removed = op->send_flow_removed;
5339 ofoperation_destroy(op);
5342 ofmonitor_flush(ofproto->connmgr);
5344 if (!list_is_empty(&group->ofproto_node)) {
5345 ovs_assert(ofproto->n_pending > 0);
5346 ofproto->n_pending--;
5347 list_remove(&group->ofproto_node);
5349 if (!list_is_empty(&group->ofconn_node)) {
5350 list_remove(&group->ofconn_node);
5352 ofconn_send_error(group->ofconn, group->request, error);
5354 connmgr_retry(ofproto->connmgr);
5356 free(group->request);
5360 /* Initiates a new operation on 'rule', of the specified 'type', within
5361 * 'group'. Prior to calling, 'rule' must not have any pending operation.
5363 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
5364 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
5366 * Returns the newly created ofoperation (which is also available as
5367 * rule->pending). */
5368 static struct ofoperation *
5369 ofoperation_create(struct ofopgroup *group, struct rule *rule,
5370 enum ofoperation_type type,
5371 enum ofp_flow_removed_reason reason)
5373 struct ofproto *ofproto = group->ofproto;
5374 struct ofoperation *op;
5376 ovs_assert(!rule->pending);
5378 op = rule->pending = xzalloc(sizeof *op);
5380 list_push_back(&group->ops, &op->group_node);
5383 op->reason = reason;
5384 op->flow_cookie = rule->flow_cookie;
5385 ovs_mutex_lock(&rule->timeout_mutex);
5386 op->idle_timeout = rule->idle_timeout;
5387 op->hard_timeout = rule->hard_timeout;
5388 ovs_mutex_unlock(&rule->timeout_mutex);
5389 op->send_flow_removed = rule->send_flow_removed;
5393 if (type == OFOPERATION_DELETE) {
5394 hmap_insert(&ofproto->deletions, &op->hmap_node,
5395 cls_rule_hash(&rule->cr, rule->table_id));
5402 ofoperation_destroy(struct ofoperation *op)
5404 struct ofopgroup *group = op->group;
5407 op->rule->pending = NULL;
5409 if (op->type == OFOPERATION_DELETE) {
5410 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
5412 list_remove(&op->group_node);
5413 rule_actions_unref(op->actions);
5417 /* Indicates that 'op' completed with status 'error', which is either 0 to
5418 * indicate success or an OpenFlow error code on failure.
5420 * If 'error' is 0, indicating success, the operation will be committed
5421 * permanently to the flow table.
5423 * If 'error' is nonzero, then generally the operation will be rolled back:
5425 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
5426 * restores the original rule. The caller must have uninitialized any
5427 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
5428 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
5429 * and 7 for the new rule, calling its ->rule_dealloc() function.
5431 * - If 'op' is a "modify flow" operation, ofproto restores the original
5434 * - 'op' must not be a "delete flow" operation. Removing a rule is not
5435 * allowed to fail. It must always succeed.
5437 * Please see the large comment in ofproto/ofproto-provider.h titled
5438 * "Asynchronous Operation Support" for more information. */
5440 ofoperation_complete(struct ofoperation *op, enum ofperr error)
5442 struct ofopgroup *group = op->group;
5444 ovs_assert(op->rule->pending == op);
5445 ovs_assert(group->n_running > 0);
5446 ovs_assert(!error || op->type != OFOPERATION_DELETE);
5449 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
5450 ofopgroup_complete(group);
5455 pick_datapath_id(const struct ofproto *ofproto)
5457 const struct ofport *port;
5459 port = ofproto_get_port(ofproto, OFPP_LOCAL);
5461 uint8_t ea[ETH_ADDR_LEN];
5464 error = netdev_get_etheraddr(port->netdev, ea);
5466 return eth_addr_to_uint64(ea);
5468 VLOG_WARN("%s: could not get MAC address for %s (%s)",
5469 ofproto->name, netdev_get_name(port->netdev),
5470 ovs_strerror(error));
5472 return ofproto->fallback_dpid;
5476 pick_fallback_dpid(void)
5478 uint8_t ea[ETH_ADDR_LEN];
5479 eth_addr_nicira_random(ea);
5480 return eth_addr_to_uint64(ea);
5483 /* Table overflow policy. */
5485 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
5486 * to NULL if the table is not configured to evict rules or if the table
5487 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
5488 * or with no timeouts are not evictable.) */
5490 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
5492 struct eviction_group *evg;
5495 if (!table->eviction_fields) {
5499 /* In the common case, the outer and inner loops here will each be entered
5502 * - The inner loop normally "return"s in its first iteration. If the
5503 * eviction group has any evictable rules, then it always returns in
5506 * - The outer loop only iterates more than once if the largest eviction
5507 * group has no evictable rules.
5509 * - The outer loop can exit only if table's 'max_flows' is all filled up
5510 * by unevictable rules. */
5511 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
5514 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
5515 if (!ovs_rwlock_trywrlock(&rule->rwlock)) {
5525 /* Searches 'ofproto' for tables that have more flows than their configured
5526 * maximum and that have flow eviction enabled, and evicts as many flows as
5527 * necessary and currently feasible from them.
5529 * This triggers only when an OpenFlow table has N flows in it and then the
5530 * client configures a maximum number of flows less than N. */
5532 ofproto_evict(struct ofproto *ofproto)
5534 struct ofopgroup *group;
5535 struct oftable *table;
5537 group = ofopgroup_create_unattached(ofproto);
5538 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
5539 while (table->eviction_fields) {
5543 ovs_rwlock_rdlock(&table->cls.rwlock);
5544 n_rules = classifier_count(&table->cls);
5545 ovs_rwlock_unlock(&table->cls.rwlock);
5547 if (n_rules <= table->max_flows) {
5551 if (!choose_rule_to_evict(table, &rule)) {
5555 if (rule->pending) {
5556 ovs_rwlock_unlock(&rule->rwlock);
5560 ofoperation_create(group, rule,
5561 OFOPERATION_DELETE, OFPRR_EVICTION);
5562 oftable_remove_rule(rule);
5563 ofproto->ofproto_class->rule_delete(rule);
5566 ofopgroup_submit(group);
5569 /* Eviction groups. */
5571 /* Returns the priority to use for an eviction_group that contains 'n_rules'
5572 * rules. The priority contains low-order random bits to ensure that eviction
5573 * groups with the same number of rules are prioritized randomly. */
5575 eviction_group_priority(size_t n_rules)
5577 uint16_t size = MIN(UINT16_MAX, n_rules);
5578 return (size << 16) | random_uint16();
5581 /* Updates 'evg', an eviction_group within 'table', following a change that
5582 * adds or removes rules in 'evg'. */
5584 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
5586 heap_change(&table->eviction_groups_by_size, &evg->size_node,
5587 eviction_group_priority(heap_count(&evg->rules)));
5590 /* Destroys 'evg', an eviction_group within 'table':
5592 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
5593 * rules themselves, just removes them from the eviction group.)
5595 * - Removes 'evg' from 'table'.
5599 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
5601 while (!heap_is_empty(&evg->rules)) {
5604 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
5605 rule->eviction_group = NULL;
5607 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
5608 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
5609 heap_destroy(&evg->rules);
5613 /* Removes 'rule' from its eviction group, if any. */
5615 eviction_group_remove_rule(struct rule *rule)
5617 if (rule->eviction_group) {
5618 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5619 struct eviction_group *evg = rule->eviction_group;
5621 rule->eviction_group = NULL;
5622 heap_remove(&evg->rules, &rule->evg_node);
5623 if (heap_is_empty(&evg->rules)) {
5624 eviction_group_destroy(table, evg);
5626 eviction_group_resized(table, evg);
5631 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
5632 * returns the hash value. */
5634 eviction_group_hash_rule(struct rule *rule)
5636 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5637 const struct mf_subfield *sf;
5641 hash = table->eviction_group_id_basis;
5642 miniflow_expand(&rule->cr.match.flow, &flow);
5643 for (sf = table->eviction_fields;
5644 sf < &table->eviction_fields[table->n_eviction_fields];
5647 if (mf_are_prereqs_ok(sf->field, &flow)) {
5648 union mf_value value;
5650 mf_get_value(sf->field, &flow, &value);
5652 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
5654 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
5655 unsigned int start = sf->ofs + sf->n_bits;
5656 bitwise_zero(&value, sf->field->n_bytes, start,
5657 sf->field->n_bytes * 8 - start);
5659 hash = hash_bytes(&value, sf->field->n_bytes, hash);
5661 hash = hash_int(hash, 0);
5668 /* Returns an eviction group within 'table' with the given 'id', creating one
5670 static struct eviction_group *
5671 eviction_group_find(struct oftable *table, uint32_t id)
5673 struct eviction_group *evg;
5675 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
5679 evg = xmalloc(sizeof *evg);
5680 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
5681 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
5682 eviction_group_priority(0));
5683 heap_init(&evg->rules);
5688 /* Returns an eviction priority for 'rule'. The return value should be
5689 * interpreted so that higher priorities make a rule more attractive candidates
5692 rule_eviction_priority(struct rule *rule)
5694 long long int hard_expiration;
5695 long long int idle_expiration;
5696 long long int expiration;
5697 uint32_t expiration_offset;
5699 /* Calculate time of expiration. */
5700 ovs_mutex_lock(&rule->timeout_mutex);
5701 hard_expiration = (rule->hard_timeout
5702 ? rule->modified + rule->hard_timeout * 1000
5704 idle_expiration = (rule->idle_timeout
5705 ? rule->used + rule->idle_timeout * 1000
5707 expiration = MIN(hard_expiration, idle_expiration);
5708 ovs_mutex_unlock(&rule->timeout_mutex);
5709 if (expiration == LLONG_MAX) {
5713 /* Calculate the time of expiration as a number of (approximate) seconds
5714 * after program startup.
5716 * This should work OK for program runs that last UINT32_MAX seconds or
5717 * less. Therefore, please restart OVS at least once every 136 years. */
5718 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
5720 /* Invert the expiration offset because we're using a max-heap. */
5721 return UINT32_MAX - expiration_offset;
5724 /* Adds 'rule' to an appropriate eviction group for its oftable's
5725 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
5726 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
5729 * The caller must ensure that 'rule' is not already in an eviction group. */
5731 eviction_group_add_rule(struct rule *rule)
5733 struct ofproto *ofproto = rule->ofproto;
5734 struct oftable *table = &ofproto->tables[rule->table_id];
5737 ovs_mutex_lock(&rule->timeout_mutex);
5738 has_timeout = rule->hard_timeout || rule->idle_timeout;
5739 ovs_mutex_unlock(&rule->timeout_mutex);
5741 if (table->eviction_fields && has_timeout) {
5742 struct eviction_group *evg;
5744 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
5746 rule->eviction_group = evg;
5747 heap_insert(&evg->rules, &rule->evg_node,
5748 rule_eviction_priority(rule));
5749 eviction_group_resized(table, evg);
5755 /* Initializes 'table'. */
5757 oftable_init(struct oftable *table)
5759 memset(table, 0, sizeof *table);
5760 classifier_init(&table->cls);
5761 table->max_flows = UINT_MAX;
5764 /* Destroys 'table', including its classifier and eviction groups.
5766 * The caller is responsible for freeing 'table' itself. */
5768 oftable_destroy(struct oftable *table)
5770 ovs_rwlock_rdlock(&table->cls.rwlock);
5771 ovs_assert(classifier_is_empty(&table->cls));
5772 ovs_rwlock_unlock(&table->cls.rwlock);
5773 oftable_disable_eviction(table);
5774 classifier_destroy(&table->cls);
5778 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
5779 * string, then 'table' will use its default name.
5781 * This only affects the name exposed for a table exposed through the OpenFlow
5782 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
5784 oftable_set_name(struct oftable *table, const char *name)
5786 if (name && name[0]) {
5787 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
5788 if (!table->name || strncmp(name, table->name, len)) {
5790 table->name = xmemdup0(name, len);
5798 /* oftables support a choice of two policies when adding a rule would cause the
5799 * number of flows in the table to exceed the configured maximum number: either
5800 * they can refuse to add the new flow or they can evict some existing flow.
5801 * This function configures the former policy on 'table'. */
5803 oftable_disable_eviction(struct oftable *table)
5805 if (table->eviction_fields) {
5806 struct eviction_group *evg, *next;
5808 HMAP_FOR_EACH_SAFE (evg, next, id_node,
5809 &table->eviction_groups_by_id) {
5810 eviction_group_destroy(table, evg);
5812 hmap_destroy(&table->eviction_groups_by_id);
5813 heap_destroy(&table->eviction_groups_by_size);
5815 free(table->eviction_fields);
5816 table->eviction_fields = NULL;
5817 table->n_eviction_fields = 0;
5821 /* oftables support a choice of two policies when adding a rule would cause the
5822 * number of flows in the table to exceed the configured maximum number: either
5823 * they can refuse to add the new flow or they can evict some existing flow.
5824 * This function configures the latter policy on 'table', with fairness based
5825 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
5826 * 'n_fields' as 0 disables fairness.) */
5828 oftable_enable_eviction(struct oftable *table,
5829 const struct mf_subfield *fields, size_t n_fields)
5831 struct cls_cursor cursor;
5834 if (table->eviction_fields
5835 && n_fields == table->n_eviction_fields
5837 || !memcmp(fields, table->eviction_fields,
5838 n_fields * sizeof *fields))) {
5843 oftable_disable_eviction(table);
5845 table->n_eviction_fields = n_fields;
5846 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
5848 table->eviction_group_id_basis = random_uint32();
5849 hmap_init(&table->eviction_groups_by_id);
5850 heap_init(&table->eviction_groups_by_size);
5852 ovs_rwlock_rdlock(&table->cls.rwlock);
5853 cls_cursor_init(&cursor, &table->cls, NULL);
5854 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
5855 eviction_group_add_rule(rule);
5857 ovs_rwlock_unlock(&table->cls.rwlock);
5860 /* Removes 'rule' from the oftable that contains it. */
5862 oftable_remove_rule__(struct ofproto *ofproto, struct classifier *cls,
5864 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock)
5866 classifier_remove(cls, &rule->cr);
5868 ovs_mutex_lock(&ofproto_mutex);
5869 cookies_remove(ofproto, rule);
5870 ovs_mutex_unlock(&ofproto_mutex);
5872 eviction_group_remove_rule(rule);
5873 ovs_mutex_lock(&ofproto_mutex);
5874 if (!list_is_empty(&rule->expirable)) {
5875 list_remove(&rule->expirable);
5877 ovs_mutex_unlock(&ofproto_mutex);
5878 if (!list_is_empty(&rule->meter_list_node)) {
5879 list_remove(&rule->meter_list_node);
5880 list_init(&rule->meter_list_node);
5882 ovs_rwlock_unlock(&rule->rwlock);
5886 oftable_remove_rule(struct rule *rule)
5888 struct ofproto *ofproto = rule->ofproto;
5889 struct oftable *table = &ofproto->tables[rule->table_id];
5891 ovs_rwlock_wrlock(&table->cls.rwlock);
5892 oftable_remove_rule__(ofproto, &table->cls, rule);
5893 ovs_rwlock_unlock(&table->cls.rwlock);
5896 /* Inserts 'rule' into its oftable, which must not already contain any rule for
5897 * the same cls_rule. */
5899 oftable_insert_rule(struct rule *rule)
5901 struct ofproto *ofproto = rule->ofproto;
5902 struct oftable *table = &ofproto->tables[rule->table_id];
5905 ovs_mutex_lock(&rule->timeout_mutex);
5906 may_expire = rule->hard_timeout || rule->idle_timeout;
5907 ovs_mutex_unlock(&rule->timeout_mutex);
5910 ovs_mutex_lock(&ofproto_mutex);
5911 list_insert(&ofproto->expirable, &rule->expirable);
5912 ovs_mutex_unlock(&ofproto_mutex);
5915 ovs_mutex_lock(&ofproto_mutex);
5916 cookies_insert(ofproto, rule);
5917 ovs_mutex_unlock(&ofproto_mutex);
5919 if (rule->actions->meter_id) {
5920 struct meter *meter = ofproto->meters[rule->actions->meter_id];
5921 list_insert(&meter->rules, &rule->meter_list_node);
5923 ovs_rwlock_wrlock(&table->cls.rwlock);
5924 classifier_insert(&table->cls, &rule->cr);
5925 ovs_rwlock_unlock(&table->cls.rwlock);
5926 eviction_group_add_rule(rule);
5929 /* unixctl commands. */
5932 ofproto_lookup(const char *name)
5934 struct ofproto *ofproto;
5936 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
5938 if (!strcmp(ofproto->name, name)) {
5946 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
5947 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5949 struct ofproto *ofproto;
5953 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
5954 ds_put_format(&results, "%s\n", ofproto->name);
5956 unixctl_command_reply(conn, ds_cstr(&results));
5957 ds_destroy(&results);
5961 ofproto_unixctl_init(void)
5963 static bool registered;
5969 unixctl_command_register("ofproto/list", "", 0, 0,
5970 ofproto_unixctl_list, NULL);
5973 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5975 * This is deprecated. It is only for compatibility with broken device drivers
5976 * in old versions of Linux that do not properly support VLANs when VLAN
5977 * devices are not used. When broken device drivers are no longer in
5978 * widespread use, we will delete these interfaces. */
5980 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
5981 * (exactly) by an OpenFlow rule in 'ofproto'. */
5983 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
5985 const struct oftable *oftable;
5987 free(ofproto->vlan_bitmap);
5988 ofproto->vlan_bitmap = bitmap_allocate(4096);
5989 ofproto->vlans_changed = false;
5991 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
5992 const struct cls_table *table;
5994 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
5995 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
5996 const struct cls_rule *rule;
5998 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
5999 uint16_t vid = miniflow_get_vid(&rule->match.flow);
6000 bitmap_set1(vlan_bitmap, vid);
6001 bitmap_set1(ofproto->vlan_bitmap, vid);
6008 /* Returns true if new VLANs have come into use by the flow table since the
6009 * last call to ofproto_get_vlan_usage().
6011 * We don't track when old VLANs stop being used. */
6013 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
6015 return ofproto->vlans_changed;
6018 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
6019 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
6020 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
6021 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
6022 * then the VLAN device is un-enslaved. */
6024 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
6025 ofp_port_t realdev_ofp_port, int vid)
6027 struct ofport *ofport;
6030 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
6032 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
6034 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
6035 ofproto->name, vlandev_ofp_port);
6039 if (!ofproto->ofproto_class->set_realdev) {
6040 if (!vlandev_ofp_port) {
6043 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
6047 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
6049 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
6050 ofproto->name, vlandev_ofp_port,
6051 netdev_get_name(ofport->netdev), ovs_strerror(error));