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)
2960 hindex_insert(&ofproto->cookies, &rule->cookie_node,
2961 hash_cookie(rule->flow_cookie));
2965 cookies_remove(struct ofproto *ofproto, struct rule *rule)
2967 hindex_remove(&ofproto->cookies, &rule->cookie_node);
2971 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
2972 ovs_be64 new_cookie)
2974 if (new_cookie != rule->flow_cookie) {
2975 cookies_remove(ofproto, rule);
2977 ovs_rwlock_wrlock(&rule->rwlock);
2978 rule->flow_cookie = new_cookie;
2979 ovs_rwlock_unlock(&rule->rwlock);
2981 cookies_insert(ofproto, rule);
2986 calc_duration(long long int start, long long int now,
2987 uint32_t *sec, uint32_t *nsec)
2989 long long int msecs = now - start;
2990 *sec = msecs / 1000;
2991 *nsec = (msecs % 1000) * (1000 * 1000);
2994 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
2995 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
2997 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2999 return (table_id == 0xff || table_id < ofproto->n_tables
3001 : OFPERR_OFPBRC_BAD_TABLE_ID);
3005 static struct oftable *
3006 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3008 struct oftable *table;
3010 for (table = &ofproto->tables[table_id];
3011 table < &ofproto->tables[ofproto->n_tables];
3013 if (!(table->flags & OFTABLE_HIDDEN)) {
3021 static struct oftable *
3022 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3024 if (table_id == 0xff) {
3025 return next_visible_table(ofproto, 0);
3026 } else if (table_id < ofproto->n_tables) {
3027 return &ofproto->tables[table_id];
3033 static struct oftable *
3034 next_matching_table(const struct ofproto *ofproto,
3035 const struct oftable *table, uint8_t table_id)
3037 return (table_id == 0xff
3038 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3042 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3044 * - If TABLE_ID is 0xff, this iterates over every classifier table in
3045 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3047 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3048 * only once, for that table. (This can be used to access tables marked
3051 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3052 * entered at all. (Perhaps you should have validated TABLE_ID with
3053 * check_table_id().)
3055 * All parameters are evaluated multiple times.
3057 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
3058 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
3060 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3062 /* Initializes 'criteria' in a straightforward way based on the other
3065 * For "loose" matching, the 'priority' parameter is unimportant and may be
3068 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3069 const struct match *match, unsigned int priority,
3070 ovs_be64 cookie, ovs_be64 cookie_mask,
3071 ofp_port_t out_port)
3073 criteria->table_id = table_id;
3074 cls_rule_init(&criteria->cr, match, priority);
3075 criteria->cookie = cookie;
3076 criteria->cookie_mask = cookie_mask;
3077 criteria->out_port = out_port;
3081 rule_criteria_destroy(struct rule_criteria *criteria)
3083 cls_rule_destroy(&criteria->cr);
3087 rule_collection_init(struct rule_collection *rules)
3089 rules->rules = rules->stub;
3091 rules->capacity = ARRAY_SIZE(rules->stub);
3095 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3097 if (rules->n >= rules->capacity) {
3098 size_t old_size, new_size;
3100 old_size = rules->capacity * sizeof *rules->rules;
3101 rules->capacity *= 2;
3102 new_size = rules->capacity * sizeof *rules->rules;
3104 if (rules->rules == rules->stub) {
3105 rules->rules = xmalloc(new_size);
3106 memcpy(rules->rules, rules->stub, old_size);
3108 rules->rules = xrealloc(rules->rules, new_size);
3112 rules->rules[rules->n++] = rule;
3116 rule_collection_destroy(struct rule_collection *rules)
3118 if (rules->rules != rules->stub) {
3124 collect_rule(struct rule *rule, const struct rule_criteria *c,
3125 struct rule_collection *rules)
3127 if (ofproto_rule_is_hidden(rule)) {
3129 } else if (rule->pending) {
3130 return OFPROTO_POSTPONE;
3132 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3133 && ofproto_rule_has_out_port(rule, c->out_port)
3134 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3135 rule_collection_add(rules, rule);
3141 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3142 * on classifiers rules are done in the "loose" way required for OpenFlow
3143 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3146 * Hidden rules are always omitted.
3148 * Returns 0 on success, otherwise an OpenFlow error code. */
3150 collect_rules_loose(struct ofproto *ofproto,
3151 const struct rule_criteria *criteria,
3152 struct rule_collection *rules)
3154 struct oftable *table;
3157 rule_collection_init(rules);
3159 error = check_table_id(ofproto, criteria->table_id);
3164 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3167 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3168 hash_cookie(criteria->cookie),
3169 &ofproto->cookies) {
3170 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3171 error = collect_rule(rule, criteria, rules);
3178 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3179 struct cls_cursor cursor;
3182 ovs_rwlock_rdlock(&table->cls.rwlock);
3183 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3184 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3185 error = collect_rule(rule, criteria, rules);
3190 ovs_rwlock_unlock(&table->cls.rwlock);
3196 rule_collection_destroy(rules);
3201 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3202 * on classifiers rules are done in the "strict" way required for OpenFlow
3203 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3204 * rules on list 'rules'.
3206 * Hidden rules are always omitted.
3208 * Returns 0 on success, otherwise an OpenFlow error code. */
3210 collect_rules_strict(struct ofproto *ofproto,
3211 const struct rule_criteria *criteria,
3212 struct rule_collection *rules)
3214 struct oftable *table;
3217 rule_collection_init(rules);
3219 error = check_table_id(ofproto, criteria->table_id);
3224 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3227 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3228 hash_cookie(criteria->cookie),
3229 &ofproto->cookies) {
3230 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3231 error = collect_rule(rule, criteria, rules);
3238 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3241 ovs_rwlock_rdlock(&table->cls.rwlock);
3242 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3243 &table->cls, &criteria->cr));
3244 ovs_rwlock_unlock(&table->cls.rwlock);
3246 error = collect_rule(rule, criteria, rules);
3256 rule_collection_destroy(rules);
3261 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3262 * forced into the range of a uint16_t. */
3264 age_secs(long long int age_ms)
3266 return (age_ms < 0 ? 0
3267 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3268 : (unsigned int) age_ms / 1000);
3272 handle_flow_stats_request(struct ofconn *ofconn,
3273 const struct ofp_header *request)
3275 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3276 struct ofputil_flow_stats_request fsr;
3277 struct rule_criteria criteria;
3278 struct rule_collection rules;
3279 struct list replies;
3283 error = ofputil_decode_flow_stats_request(&fsr, request);
3288 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3289 fsr.cookie_mask, fsr.out_port);
3290 error = collect_rules_loose(ofproto, &criteria, &rules);
3291 rule_criteria_destroy(&criteria);
3296 ofpmp_init(&replies, request);
3297 for (i = 0; i < rules.n; i++) {
3298 struct rule *rule = rules.rules[i];
3299 long long int now = time_msec();
3300 struct ofputil_flow_stats fs;
3302 minimatch_expand(&rule->cr.match, &fs.match);
3303 fs.priority = rule->cr.priority;
3304 fs.cookie = rule->flow_cookie;
3305 fs.table_id = rule->table_id;
3306 calc_duration(rule->created, now, &fs.duration_sec, &fs.duration_nsec);
3307 fs.idle_age = age_secs(now - rule->used);
3308 fs.hard_age = age_secs(now - rule->modified);
3309 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3311 fs.ofpacts = rule->actions->ofpacts;
3312 fs.ofpacts_len = rule->actions->ofpacts_len;
3314 ovs_mutex_lock(&rule->timeout_mutex);
3315 fs.idle_timeout = rule->idle_timeout;
3316 fs.hard_timeout = rule->hard_timeout;
3317 ovs_mutex_unlock(&rule->timeout_mutex);
3320 if (rule->send_flow_removed) {
3321 fs.flags |= OFPUTIL_FF_SEND_FLOW_REM;
3322 /* FIXME: Implement OFPUTIL_FF_NO_PKT_COUNTS and
3323 OFPUTIL_FF_NO_BYT_COUNTS. */
3325 ofputil_append_flow_stats_reply(&fs, &replies);
3327 rule_collection_destroy(&rules);
3329 ofconn_send_replies(ofconn, &replies);
3335 flow_stats_ds(struct rule *rule, struct ds *results)
3337 uint64_t packet_count, byte_count;
3339 rule->ofproto->ofproto_class->rule_get_stats(rule,
3340 &packet_count, &byte_count);
3342 if (rule->table_id != 0) {
3343 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3345 ds_put_format(results, "duration=%llds, ",
3346 (time_msec() - rule->created) / 1000);
3347 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3348 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3349 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3350 cls_rule_format(&rule->cr, results);
3351 ds_put_char(results, ',');
3352 ofpacts_format(rule->actions->ofpacts, rule->actions->ofpacts_len,
3354 ds_put_cstr(results, "\n");
3357 /* Adds a pretty-printed description of all flows to 'results', including
3358 * hidden flows (e.g., set up by in-band control). */
3360 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3362 struct oftable *table;
3364 OFPROTO_FOR_EACH_TABLE (table, p) {
3365 struct cls_cursor cursor;
3368 ovs_rwlock_rdlock(&table->cls.rwlock);
3369 cls_cursor_init(&cursor, &table->cls, NULL);
3370 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3371 flow_stats_ds(rule, results);
3373 ovs_rwlock_unlock(&table->cls.rwlock);
3377 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3378 * '*engine_type' and '*engine_id', respectively. */
3380 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3381 uint8_t *engine_type, uint8_t *engine_id)
3383 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3386 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3387 * true if the port's CFM status was successfully stored into '*status'.
3388 * Returns false if the port did not have CFM configured, in which case
3389 * '*status' is indeterminate.
3391 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3393 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3394 struct ofproto_cfm_status *status)
3396 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3398 && ofproto->ofproto_class->get_cfm_status
3399 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3403 handle_aggregate_stats_request(struct ofconn *ofconn,
3404 const struct ofp_header *oh)
3406 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3407 struct ofputil_flow_stats_request request;
3408 struct ofputil_aggregate_stats stats;
3409 bool unknown_packets, unknown_bytes;
3410 struct rule_criteria criteria;
3411 struct rule_collection rules;
3412 struct ofpbuf *reply;
3416 error = ofputil_decode_flow_stats_request(&request, oh);
3421 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3422 request.cookie, request.cookie_mask,
3424 error = collect_rules_loose(ofproto, &criteria, &rules);
3425 rule_criteria_destroy(&criteria);
3430 memset(&stats, 0, sizeof stats);
3431 unknown_packets = unknown_bytes = false;
3432 for (i = 0; i < rules.n; i++) {
3433 struct rule *rule = rules.rules[i];
3434 uint64_t packet_count;
3435 uint64_t byte_count;
3437 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3440 if (packet_count == UINT64_MAX) {
3441 unknown_packets = true;
3443 stats.packet_count += packet_count;
3446 if (byte_count == UINT64_MAX) {
3447 unknown_bytes = true;
3449 stats.byte_count += byte_count;
3454 if (unknown_packets) {
3455 stats.packet_count = UINT64_MAX;
3457 if (unknown_bytes) {
3458 stats.byte_count = UINT64_MAX;
3461 rule_collection_destroy(&rules);
3463 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3464 ofconn_send_reply(ofconn, reply);
3469 struct queue_stats_cbdata {
3470 struct ofport *ofport;
3471 struct list replies;
3476 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3477 const struct netdev_queue_stats *stats)
3479 struct ofputil_queue_stats oqs;
3481 oqs.port_no = cbdata->ofport->pp.port_no;
3482 oqs.queue_id = queue_id;
3483 oqs.tx_bytes = stats->tx_bytes;
3484 oqs.tx_packets = stats->tx_packets;
3485 oqs.tx_errors = stats->tx_errors;
3486 if (stats->created != LLONG_MIN) {
3487 calc_duration(stats->created, cbdata->now,
3488 &oqs.duration_sec, &oqs.duration_nsec);
3490 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3492 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3496 handle_queue_stats_dump_cb(uint32_t queue_id,
3497 struct netdev_queue_stats *stats,
3500 struct queue_stats_cbdata *cbdata = cbdata_;
3502 put_queue_stats(cbdata, queue_id, stats);
3506 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3507 struct queue_stats_cbdata *cbdata)
3509 cbdata->ofport = port;
3510 if (queue_id == OFPQ_ALL) {
3511 netdev_dump_queue_stats(port->netdev,
3512 handle_queue_stats_dump_cb, cbdata);
3514 struct netdev_queue_stats stats;
3516 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3517 put_queue_stats(cbdata, queue_id, &stats);
3519 return OFPERR_OFPQOFC_BAD_QUEUE;
3526 handle_queue_stats_request(struct ofconn *ofconn,
3527 const struct ofp_header *rq)
3529 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3530 struct queue_stats_cbdata cbdata;
3531 struct ofport *port;
3533 struct ofputil_queue_stats_request oqsr;
3535 COVERAGE_INC(ofproto_queue_req);
3537 ofpmp_init(&cbdata.replies, rq);
3538 cbdata.now = time_msec();
3540 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3545 if (oqsr.port_no == OFPP_ANY) {
3546 error = OFPERR_OFPQOFC_BAD_QUEUE;
3547 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3548 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3553 port = ofproto_get_port(ofproto, oqsr.port_no);
3555 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3556 : OFPERR_OFPQOFC_BAD_PORT);
3559 ofconn_send_replies(ofconn, &cbdata.replies);
3561 ofpbuf_list_delete(&cbdata.replies);
3568 is_flow_deletion_pending(const struct ofproto *ofproto,
3569 const struct cls_rule *cls_rule,
3572 if (!hmap_is_empty(&ofproto->deletions)) {
3573 struct ofoperation *op;
3575 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3576 cls_rule_hash(cls_rule, table_id),
3577 &ofproto->deletions) {
3578 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3588 evict_rule_from_table(struct ofproto *ofproto, struct oftable *table)
3593 ovs_rwlock_rdlock(&table->cls.rwlock);
3594 n_rules = classifier_count(&table->cls);
3595 ovs_rwlock_unlock(&table->cls.rwlock);
3597 if (n_rules < table->max_flows) {
3599 } else if (!choose_rule_to_evict(table, &rule)) {
3600 return OFPERR_OFPFMFC_TABLE_FULL;
3601 } else if (rule->pending) {
3602 ovs_rwlock_unlock(&rule->rwlock);
3603 return OFPROTO_POSTPONE;
3605 struct ofopgroup *group;
3607 group = ofopgroup_create_unattached(ofproto);
3608 delete_flow__(rule, group, OFPRR_EVICTION);
3609 ofopgroup_submit(group);
3615 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3616 * in which no matching flow already exists in the flow table.
3618 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3619 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3620 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3621 * initiated now but may be retried later.
3623 * The caller retains ownership of 'fm->ofpacts'.
3625 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3628 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3629 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3631 struct oftable *table;
3632 struct ofopgroup *group;
3638 error = check_table_id(ofproto, fm->table_id);
3644 if (fm->table_id == 0xff) {
3645 if (ofproto->ofproto_class->rule_choose_table) {
3646 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3652 ovs_assert(table_id < ofproto->n_tables);
3656 } else if (fm->table_id < ofproto->n_tables) {
3657 table_id = fm->table_id;
3659 return OFPERR_OFPBRC_BAD_TABLE_ID;
3662 table = &ofproto->tables[table_id];
3664 if (table->flags & OFTABLE_READONLY) {
3665 return OFPERR_OFPBRC_EPERM;
3668 cls_rule_init(&cr, &fm->match, fm->priority);
3670 /* Transform "add" into "modify" if there's an existing identical flow. */
3671 ovs_rwlock_rdlock(&table->cls.rwlock);
3672 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3673 ovs_rwlock_unlock(&table->cls.rwlock);
3675 cls_rule_destroy(&cr);
3676 if (!rule_is_modifiable(rule)) {
3677 return OFPERR_OFPBRC_EPERM;
3678 } else if (rule->pending) {
3679 return OFPROTO_POSTPONE;
3681 struct rule_collection rules;
3683 rule_collection_init(&rules);
3684 rule_collection_add(&rules, rule);
3685 fm->modify_cookie = true;
3686 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3687 rule_collection_destroy(&rules);
3693 /* Verify actions. */
3694 error = ofproto_check_ofpacts(ofproto, fm->ofpacts, fm->ofpacts_len,
3695 &fm->match.flow, table_id);
3697 cls_rule_destroy(&cr);
3701 /* Serialize against pending deletion. */
3702 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3703 cls_rule_destroy(&cr);
3704 return OFPROTO_POSTPONE;
3707 /* Check for overlap, if requested. */
3708 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3711 ovs_rwlock_rdlock(&table->cls.rwlock);
3712 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3713 ovs_rwlock_unlock(&table->cls.rwlock);
3716 cls_rule_destroy(&cr);
3717 return OFPERR_OFPFMFC_OVERLAP;
3721 /* If necessary, evict an existing rule to clear out space. */
3722 error = evict_rule_from_table(ofproto, table);
3724 cls_rule_destroy(&cr);
3728 /* Allocate new rule. */
3729 rule = ofproto->ofproto_class->rule_alloc();
3731 cls_rule_destroy(&cr);
3732 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3733 ofproto->name, ovs_strerror(error));
3737 /* Initialize base state. */
3738 rule->ofproto = ofproto;
3739 cls_rule_move(&rule->cr, &cr);
3740 atomic_init(&rule->ref_count, 1);
3741 rule->pending = NULL;
3742 rule->flow_cookie = fm->new_cookie;
3743 rule->created = rule->modified = rule->used = time_msec();
3745 ovs_mutex_init(&rule->timeout_mutex);
3746 ovs_mutex_lock(&rule->timeout_mutex);
3747 rule->idle_timeout = fm->idle_timeout;
3748 rule->hard_timeout = fm->hard_timeout;
3749 ovs_mutex_unlock(&rule->timeout_mutex);
3751 rule->table_id = table - ofproto->tables;
3752 rule->send_flow_removed = (fm->flags & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3753 rule->actions = rule_actions_create(fm->ofpacts, fm->ofpacts_len);
3754 list_init(&rule->meter_list_node);
3755 rule->eviction_group = NULL;
3756 list_init(&rule->expirable);
3757 rule->monitor_flags = 0;
3758 rule->add_seqno = 0;
3759 rule->modify_seqno = 0;
3760 ovs_rwlock_init(&rule->rwlock);
3762 /* Construct rule, initializing derived state. */
3763 error = ofproto->ofproto_class->rule_construct(rule);
3765 ofproto_rule_destroy__(rule);
3770 oftable_insert_rule(rule);
3772 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3773 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
3774 ofproto->ofproto_class->rule_insert(rule);
3775 ofopgroup_submit(group);
3780 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3782 /* Modifies the rules listed in 'rules', changing their actions to match those
3785 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3788 * Returns 0 on success, otherwise an OpenFlow error code. */
3790 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3791 struct ofputil_flow_mod *fm, const struct ofp_header *request,
3792 const struct rule_collection *rules)
3794 enum ofoperation_type type;
3795 struct ofopgroup *group;
3799 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
3800 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3801 error = OFPERR_OFPBRC_EPERM;
3802 for (i = 0; i < rules->n; i++) {
3803 struct rule *rule = rules->rules[i];
3804 struct ofoperation *op;
3805 bool actions_changed;
3806 bool reset_counters;
3808 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
3810 if (rule_is_modifiable(rule)) {
3811 /* At least one rule is modifiable, don't report EPERM error. */
3817 /* Verify actions. */
3818 error = ofpacts_check(fm->ofpacts, fm->ofpacts_len, &fm->match.flow,
3819 u16_to_ofp(ofproto->max_ports), rule->table_id);
3824 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
3825 rule->actions->ofpacts,
3826 rule->actions->ofpacts_len);
3828 op = ofoperation_create(group, rule, type, 0);
3830 if (fm->modify_cookie && fm->new_cookie != htonll(UINT64_MAX)) {
3831 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
3833 if (type == OFOPERATION_REPLACE) {
3834 ovs_mutex_lock(&rule->timeout_mutex);
3835 rule->idle_timeout = fm->idle_timeout;
3836 rule->hard_timeout = fm->hard_timeout;
3837 ovs_mutex_unlock(&rule->timeout_mutex);
3839 rule->send_flow_removed = (fm->flags
3840 & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3842 if (fm->idle_timeout || fm->hard_timeout) {
3843 if (!rule->eviction_group) {
3844 eviction_group_add_rule(rule);
3847 eviction_group_remove_rule(rule);
3851 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
3852 if (actions_changed || reset_counters) {
3853 struct rule_actions *new_actions;
3855 op->actions = rule->actions;
3856 new_actions = rule_actions_create(fm->ofpacts, fm->ofpacts_len);
3858 ovs_rwlock_wrlock(&rule->rwlock);
3859 rule->actions = new_actions;
3860 ovs_rwlock_unlock(&rule->rwlock);
3862 rule->ofproto->ofproto_class->rule_modify_actions(rule,
3865 ofoperation_complete(op, 0);
3868 ofopgroup_submit(group);
3874 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
3875 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3877 if (fm->cookie_mask != htonll(0) || fm->new_cookie == htonll(UINT64_MAX)) {
3880 return add_flow(ofproto, ofconn, fm, request);
3883 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
3886 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3889 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3890 struct ofputil_flow_mod *fm,
3891 const struct ofp_header *request)
3893 struct rule_criteria criteria;
3894 struct rule_collection rules;
3897 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
3898 fm->cookie, fm->cookie_mask, OFPP_ANY);
3899 error = collect_rules_loose(ofproto, &criteria, &rules);
3900 rule_criteria_destroy(&criteria);
3903 error = (rules.n > 0
3904 ? modify_flows__(ofproto, ofconn, fm, request, &rules)
3905 : modify_flows_add(ofproto, ofconn, fm, request));
3908 rule_collection_destroy(&rules);
3913 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
3916 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3919 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3920 struct ofputil_flow_mod *fm,
3921 const struct ofp_header *request)
3923 struct rule_criteria criteria;
3924 struct rule_collection rules;
3927 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
3928 fm->cookie, fm->cookie_mask, OFPP_ANY);
3929 error = collect_rules_strict(ofproto, &criteria, &rules);
3930 rule_criteria_destroy(&criteria);
3934 error = modify_flows_add(ofproto, ofconn, fm, request);
3935 } else if (rules.n == 1) {
3936 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3940 rule_collection_destroy(&rules);
3945 /* OFPFC_DELETE implementation. */
3948 delete_flow__(struct rule *rule, struct ofopgroup *group,
3949 enum ofp_flow_removed_reason reason)
3951 struct ofproto *ofproto = rule->ofproto;
3953 ofproto_rule_send_removed(rule, reason);
3955 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
3956 oftable_remove_rule(rule);
3957 ofproto->ofproto_class->rule_delete(rule);
3960 /* Deletes the rules listed in 'rules'.
3962 * Returns 0 on success, otherwise an OpenFlow error code. */
3964 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3965 const struct ofp_header *request,
3966 const struct rule_collection *rules,
3967 enum ofp_flow_removed_reason reason)
3969 struct ofopgroup *group;
3972 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3973 for (i = 0; i < rules->n; i++) {
3974 struct rule *rule = rules->rules[i];
3975 ovs_rwlock_wrlock(&rule->rwlock);
3976 delete_flow__(rule, group, reason);
3978 ofopgroup_submit(group);
3983 /* Implements OFPFC_DELETE. */
3985 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3986 const struct ofputil_flow_mod *fm,
3987 const struct ofp_header *request)
3989 struct rule_criteria criteria;
3990 struct rule_collection rules;
3993 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
3994 fm->cookie, fm->cookie_mask,
3996 error = collect_rules_loose(ofproto, &criteria, &rules);
3997 rule_criteria_destroy(&criteria);
3999 if (!error && rules.n > 0) {
4000 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4002 rule_collection_destroy(&rules);
4007 /* Implements OFPFC_DELETE_STRICT. */
4009 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4010 const struct ofputil_flow_mod *fm,
4011 const struct ofp_header *request)
4013 struct rule_criteria criteria;
4014 struct rule_collection rules;
4017 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4018 fm->cookie, fm->cookie_mask, fm->out_port);
4019 error = collect_rules_strict(ofproto, &criteria, &rules);
4020 rule_criteria_destroy(&criteria);
4022 if (!error && rules.n > 0) {
4023 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4025 rule_collection_destroy(&rules);
4031 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4033 struct ofputil_flow_removed fr;
4035 if (ofproto_rule_is_hidden(rule) || !rule->send_flow_removed) {
4039 minimatch_expand(&rule->cr.match, &fr.match);
4040 fr.priority = rule->cr.priority;
4041 fr.cookie = rule->flow_cookie;
4043 fr.table_id = rule->table_id;
4044 calc_duration(rule->created, time_msec(),
4045 &fr.duration_sec, &fr.duration_nsec);
4046 ovs_mutex_lock(&rule->timeout_mutex);
4047 fr.idle_timeout = rule->idle_timeout;
4048 fr.hard_timeout = rule->hard_timeout;
4049 ovs_mutex_unlock(&rule->timeout_mutex);
4050 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4053 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4056 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4057 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4060 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4063 * ofproto implementation ->run() functions should use this function to expire
4064 * OpenFlow flows. */
4066 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4068 struct ofproto *ofproto = rule->ofproto;
4069 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
4071 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
4072 ofproto_rule_send_removed(rule, reason);
4074 ovs_rwlock_wrlock(&cls->rwlock);
4075 ofproto_rule_delete(ofproto, cls, rule);
4076 ovs_rwlock_unlock(&cls->rwlock);
4079 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
4080 * means "infinite". */
4082 reduce_timeout(uint16_t max, uint16_t *timeout)
4084 if (max && (!*timeout || *timeout > max)) {
4089 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4090 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4091 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
4093 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4095 ofproto_rule_reduce_timeouts(struct rule *rule,
4096 uint16_t idle_timeout, uint16_t hard_timeout)
4097 OVS_EXCLUDED(ofproto_mutex, rule->timeout_mutex)
4099 if (!idle_timeout && !hard_timeout) {
4103 ovs_mutex_lock(&ofproto_mutex);
4104 if (list_is_empty(&rule->expirable)) {
4105 list_insert(&rule->ofproto->expirable, &rule->expirable);
4107 ovs_mutex_unlock(&ofproto_mutex);
4109 ovs_mutex_lock(&rule->timeout_mutex);
4110 reduce_timeout(idle_timeout, &rule->idle_timeout);
4111 reduce_timeout(hard_timeout, &rule->hard_timeout);
4112 ovs_mutex_unlock(&rule->timeout_mutex);
4116 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4118 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4119 struct ofputil_flow_mod fm;
4120 uint64_t ofpacts_stub[1024 / 8];
4121 struct ofpbuf ofpacts;
4125 error = reject_slave_controller(ofconn);
4130 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4131 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4134 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4137 goto exit_free_ofpacts;
4140 /* Record the operation for logging a summary report. */
4141 switch (fm.command) {
4147 case OFPFC_MODIFY_STRICT:
4148 ofproto->n_modify++;
4152 case OFPFC_DELETE_STRICT:
4153 ofproto->n_delete++;
4158 if (ofproto->next_op_report == LLONG_MAX) {
4159 ofproto->first_op = now;
4160 ofproto->next_op_report = MAX(now + 10 * 1000,
4161 ofproto->op_backoff);
4162 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4164 ofproto->last_op = now;
4167 ofpbuf_uninit(&ofpacts);
4173 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4174 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4178 if (ofproto->n_pending < 50) {
4179 switch (fm->command) {
4181 error = add_flow(ofproto, ofconn, fm, oh);
4185 error = modify_flows_loose(ofproto, ofconn, fm, oh);
4188 case OFPFC_MODIFY_STRICT:
4189 error = modify_flow_strict(ofproto, ofconn, fm, oh);
4193 error = delete_flows_loose(ofproto, ofconn, fm, oh);
4196 case OFPFC_DELETE_STRICT:
4197 error = delete_flow_strict(ofproto, ofconn, fm, oh);
4201 if (fm->command > 0xff) {
4202 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4203 "flow_mod_table_id extension is not enabled",
4206 error = OFPERR_OFPFMFC_BAD_COMMAND;
4210 ovs_assert(!list_is_empty(&ofproto->pending));
4211 error = OFPROTO_POSTPONE;
4214 run_rule_executes(ofproto);
4219 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4221 struct ofputil_role_request request;
4222 struct ofputil_role_request reply;
4226 error = ofputil_decode_role_message(oh, &request);
4231 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4232 if (ofconn_get_role(ofconn) != request.role
4233 && ofconn_has_pending_opgroups(ofconn)) {
4234 return OFPROTO_POSTPONE;
4237 if (request.have_generation_id
4238 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4239 return OFPERR_OFPRRFC_STALE;
4242 ofconn_set_role(ofconn, request.role);
4245 reply.role = ofconn_get_role(ofconn);
4246 reply.have_generation_id = ofconn_get_master_election_id(
4247 ofconn, &reply.generation_id);
4248 buf = ofputil_encode_role_reply(oh, &reply);
4249 ofconn_send_reply(ofconn, buf);
4255 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4256 const struct ofp_header *oh)
4258 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4259 enum ofputil_protocol cur, next;
4261 cur = ofconn_get_protocol(ofconn);
4262 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4263 ofconn_set_protocol(ofconn, next);
4269 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4271 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4272 enum ofputil_protocol cur, next;
4273 enum ofputil_protocol next_base;
4275 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4277 return OFPERR_OFPBRC_EPERM;
4280 cur = ofconn_get_protocol(ofconn);
4281 next = ofputil_protocol_set_base(cur, next_base);
4282 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4283 /* Avoid sending async messages in surprising protocol. */
4284 return OFPROTO_POSTPONE;
4287 ofconn_set_protocol(ofconn, next);
4292 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4293 const struct ofp_header *oh)
4295 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4298 format = ntohl(msg->format);
4299 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4300 return OFPERR_OFPBRC_EPERM;
4303 if (format != ofconn_get_packet_in_format(ofconn)
4304 && ofconn_has_pending_opgroups(ofconn)) {
4305 /* Avoid sending async message in surprsing packet in format. */
4306 return OFPROTO_POSTPONE;
4309 ofconn_set_packet_in_format(ofconn, format);
4314 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4316 const struct nx_async_config *msg = ofpmsg_body(oh);
4317 uint32_t master[OAM_N_TYPES];
4318 uint32_t slave[OAM_N_TYPES];
4320 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4321 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4322 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4324 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4325 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4326 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4328 ofconn_set_async_config(ofconn, master, slave);
4329 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4330 !ofconn_get_miss_send_len(ofconn)) {
4331 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4338 handle_nxt_set_controller_id(struct ofconn *ofconn,
4339 const struct ofp_header *oh)
4341 const struct nx_controller_id *nci = ofpmsg_body(oh);
4343 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4344 return OFPERR_NXBRC_MUST_BE_ZERO;
4347 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4352 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4356 if (ofconn_has_pending_opgroups(ofconn)) {
4357 return OFPROTO_POSTPONE;
4360 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4361 ? OFPRAW_OFPT10_BARRIER_REPLY
4362 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4363 ofconn_send_reply(ofconn, buf);
4368 ofproto_compose_flow_refresh_update(const struct rule *rule,
4369 enum nx_flow_monitor_flags flags,
4372 struct ofoperation *op = rule->pending;
4373 const struct rule_actions *actions;
4374 struct ofputil_flow_update fu;
4377 if (op && op->type == OFOPERATION_ADD) {
4378 /* We'll report the final flow when the operation completes. Reporting
4379 * it now would cause a duplicate report later. */
4383 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4384 ? NXFME_ADDED : NXFME_MODIFIED);
4386 ovs_mutex_lock(&rule->timeout_mutex);
4387 fu.idle_timeout = rule->idle_timeout;
4388 fu.hard_timeout = rule->hard_timeout;
4389 ovs_mutex_unlock(&rule->timeout_mutex);
4390 fu.table_id = rule->table_id;
4391 fu.cookie = rule->flow_cookie;
4392 minimatch_expand(&rule->cr.match, &match);
4394 fu.priority = rule->cr.priority;
4396 if (!(flags & NXFMF_ACTIONS)) {
4399 actions = rule->actions;
4401 /* An operation is in progress. Use the previous version of the flow's
4402 * actions, so that when the operation commits we report the change. */
4404 case OFOPERATION_ADD:
4407 case OFOPERATION_MODIFY:
4408 case OFOPERATION_REPLACE:
4409 actions = op->actions ? op->actions : rule->actions;
4412 case OFOPERATION_DELETE:
4413 actions = rule->actions;
4420 fu.ofpacts = actions ? actions->ofpacts : NULL;
4421 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4423 if (list_is_empty(msgs)) {
4424 ofputil_start_flow_update(msgs);
4426 ofputil_append_flow_update(&fu, msgs);
4430 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4435 for (i = 0; i < rules->n; i++) {
4436 struct rule *rule = rules->rules[i];
4437 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4438 rule->monitor_flags = 0;
4440 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4445 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4446 struct rule *rule, uint64_t seqno,
4447 struct rule_collection *rules)
4449 enum nx_flow_monitor_flags update;
4451 if (ofproto_rule_is_hidden(rule)) {
4456 ? ofoperation_has_out_port(rule->pending, m->out_port)
4457 : ofproto_rule_has_out_port(rule, m->out_port))) {
4462 if (rule->add_seqno > seqno) {
4463 update = NXFMF_ADD | NXFMF_MODIFY;
4464 } else if (rule->modify_seqno > seqno) {
4465 update = NXFMF_MODIFY;
4470 if (!(m->flags & update)) {
4474 update = NXFMF_INITIAL;
4477 if (!rule->monitor_flags) {
4478 rule_collection_add(rules, rule);
4480 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4484 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4486 struct rule_collection *rules)
4488 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4489 const struct ofoperation *op;
4490 const struct oftable *table;
4491 struct cls_rule target;
4493 cls_rule_init_from_minimatch(&target, &m->match, 0);
4494 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4495 struct cls_cursor cursor;
4498 ovs_rwlock_rdlock(&table->cls.rwlock);
4499 cls_cursor_init(&cursor, &table->cls, &target);
4500 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4501 ovs_assert(!rule->pending); /* XXX */
4502 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4504 ovs_rwlock_unlock(&table->cls.rwlock);
4507 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4508 struct rule *rule = op->rule;
4510 if (((m->table_id == 0xff
4511 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4512 : m->table_id == rule->table_id))
4513 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4514 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4517 cls_rule_destroy(&target);
4521 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4522 struct rule_collection *rules)
4524 if (m->flags & NXFMF_INITIAL) {
4525 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4530 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4531 uint64_t seqno, struct rule_collection *rules)
4533 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4537 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4539 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4540 struct ofmonitor **monitors;
4541 size_t n_monitors, allocated_monitors;
4542 struct rule_collection rules;
4543 struct list replies;
4549 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4551 n_monitors = allocated_monitors = 0;
4553 struct ofputil_flow_monitor_request request;
4554 struct ofmonitor *m;
4557 retval = ofputil_decode_flow_monitor_request(&request, &b);
4558 if (retval == EOF) {
4560 } else if (retval) {
4565 if (request.table_id != 0xff
4566 && request.table_id >= ofproto->n_tables) {
4567 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4571 error = ofmonitor_create(&request, ofconn, &m);
4576 if (n_monitors >= allocated_monitors) {
4577 monitors = x2nrealloc(monitors, &allocated_monitors,
4580 monitors[n_monitors++] = m;
4583 rule_collection_init(&rules);
4584 for (i = 0; i < n_monitors; i++) {
4585 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4588 ofpmp_init(&replies, oh);
4589 ofmonitor_compose_refresh_updates(&rules, &replies);
4590 rule_collection_destroy(&rules);
4592 ofconn_send_replies(ofconn, &replies);
4599 for (i = 0; i < n_monitors; i++) {
4600 ofmonitor_destroy(monitors[i]);
4607 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4609 struct ofmonitor *m;
4612 id = ofputil_decode_flow_monitor_cancel(oh);
4613 m = ofmonitor_lookup(ofconn, id);
4615 return OFPERR_NXBRC_FM_BAD_ID;
4618 ofmonitor_destroy(m);
4622 /* Meters implementation.
4624 * Meter table entry, indexed by the OpenFlow meter_id.
4625 * These are always dynamically allocated to allocate enough space for
4627 * 'created' is used to compute the duration for meter stats.
4628 * 'list rules' is needed so that we can delete the dependent rules when the
4629 * meter table entry is deleted.
4630 * 'provider_meter_id' is for the provider's private use.
4633 long long int created; /* Time created. */
4634 struct list rules; /* List of "struct rule_dpif"s. */
4635 ofproto_meter_id provider_meter_id;
4636 uint16_t flags; /* Meter flags. */
4637 uint16_t n_bands; /* Number of meter bands. */
4638 struct ofputil_meter_band *bands;
4642 * This is used in instruction validation at flow set-up time,
4643 * as flows may not use non-existing meters.
4644 * This is also used by ofproto-providers to translate OpenFlow meter_ids
4645 * in METER instructions to the corresponding provider meter IDs.
4646 * Return value of UINT32_MAX signifies an invalid meter.
4649 ofproto_get_provider_meter_id(const struct ofproto * ofproto,
4650 uint32_t of_meter_id)
4652 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4653 const struct meter *meter = ofproto->meters[of_meter_id];
4655 return meter->provider_meter_id.uint32;
4662 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4666 meter->flags = config->flags;
4667 meter->n_bands = config->n_bands;
4668 meter->bands = xmemdup(config->bands,
4669 config->n_bands * sizeof *meter->bands);
4672 static struct meter *
4673 meter_create(const struct ofputil_meter_config *config,
4674 ofproto_meter_id provider_meter_id)
4676 struct meter *meter;
4678 meter = xzalloc(sizeof *meter);
4679 meter->provider_meter_id = provider_meter_id;
4680 meter->created = time_msec();
4681 list_init(&meter->rules);
4683 meter_update(meter, config);
4689 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
4692 for (mid = first; mid <= last; ++mid) {
4693 struct meter *meter = ofproto->meters[mid];
4695 ofproto->meters[mid] = NULL;
4696 ofproto->ofproto_class->meter_del(ofproto,
4697 meter->provider_meter_id);
4705 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4707 ofproto_meter_id provider_meter_id = { UINT32_MAX };
4708 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
4712 return OFPERR_OFPMMFC_METER_EXISTS;
4715 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
4718 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
4719 *meterp = meter_create(&mm->meter, provider_meter_id);
4725 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4727 struct meter *meter = ofproto->meters[mm->meter.meter_id];
4731 return OFPERR_OFPMMFC_UNKNOWN_METER;
4734 error = ofproto->ofproto_class->meter_set(ofproto,
4735 &meter->provider_meter_id,
4737 ovs_assert(meter->provider_meter_id.uint32 != UINT32_MAX);
4739 meter_update(meter, &mm->meter);
4745 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
4746 struct ofputil_meter_mod *mm)
4748 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4749 uint32_t meter_id = mm->meter.meter_id;
4750 struct rule_collection rules;
4751 enum ofperr error = 0;
4752 uint32_t first, last;
4754 if (meter_id == OFPM13_ALL) {
4756 last = ofproto->meter_features.max_meters;
4758 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
4761 first = last = meter_id;
4764 /* First delete the rules that use this meter. If any of those rules are
4765 * currently being modified, postpone the whole operation until later. */
4766 rule_collection_init(&rules);
4767 for (meter_id = first; meter_id <= last; ++meter_id) {
4768 struct meter *meter = ofproto->meters[meter_id];
4769 if (meter && !list_is_empty(&meter->rules)) {
4772 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
4773 if (rule->pending) {
4774 error = OFPROTO_POSTPONE;
4777 rule_collection_add(&rules, rule);
4782 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
4785 /* Delete the meters. */
4786 meter_delete(ofproto, first, last);
4789 rule_collection_destroy(&rules);
4795 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4797 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4798 struct ofputil_meter_mod mm;
4799 uint64_t bands_stub[256 / 8];
4800 struct ofpbuf bands;
4804 error = reject_slave_controller(ofconn);
4809 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4811 error = ofputil_decode_meter_mod(oh, &mm, &bands);
4813 goto exit_free_bands;
4816 meter_id = mm.meter.meter_id;
4818 if (mm.command != OFPMC13_DELETE) {
4819 /* Fails also when meters are not implemented by the provider. */
4820 if (meter_id == 0 || meter_id > OFPM13_MAX) {
4821 error = OFPERR_OFPMMFC_INVALID_METER;
4822 goto exit_free_bands;
4823 } else if (meter_id > ofproto->meter_features.max_meters) {
4824 error = OFPERR_OFPMMFC_OUT_OF_METERS;
4825 goto exit_free_bands;
4827 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
4828 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
4829 goto exit_free_bands;
4833 switch (mm.command) {
4835 error = handle_add_meter(ofproto, &mm);
4838 case OFPMC13_MODIFY:
4839 error = handle_modify_meter(ofproto, &mm);
4842 case OFPMC13_DELETE:
4843 error = handle_delete_meter(ofconn, oh, &mm);
4847 error = OFPERR_OFPMMFC_BAD_COMMAND;
4852 ofpbuf_uninit(&bands);
4857 handle_meter_features_request(struct ofconn *ofconn,
4858 const struct ofp_header *request)
4860 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4861 struct ofputil_meter_features features;
4864 if (ofproto->ofproto_class->meter_get_features) {
4865 ofproto->ofproto_class->meter_get_features(ofproto, &features);
4867 memset(&features, 0, sizeof features);
4869 b = ofputil_encode_meter_features_reply(&features, request);
4871 ofconn_send_reply(ofconn, b);
4876 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
4879 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4880 struct list replies;
4881 uint64_t bands_stub[256 / 8];
4882 struct ofpbuf bands;
4883 uint32_t meter_id, first, last;
4885 ofputil_decode_meter_request(request, &meter_id);
4887 if (meter_id == OFPM13_ALL) {
4889 last = ofproto->meter_features.max_meters;
4891 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
4892 !ofproto->meters[meter_id]) {
4893 return OFPERR_OFPMMFC_UNKNOWN_METER;
4895 first = last = meter_id;
4898 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4899 ofpmp_init(&replies, request);
4901 for (meter_id = first; meter_id <= last; ++meter_id) {
4902 struct meter *meter = ofproto->meters[meter_id];
4904 continue; /* Skip non-existing meters. */
4906 if (type == OFPTYPE_METER_STATS_REQUEST) {
4907 struct ofputil_meter_stats stats;
4909 stats.meter_id = meter_id;
4911 /* Provider sets the packet and byte counts, we do the rest. */
4912 stats.flow_count = list_size(&meter->rules);
4913 calc_duration(meter->created, time_msec(),
4914 &stats.duration_sec, &stats.duration_nsec);
4915 stats.n_bands = meter->n_bands;
4916 ofpbuf_clear(&bands);
4918 = ofpbuf_put_uninit(&bands,
4919 meter->n_bands * sizeof *stats.bands);
4921 if (!ofproto->ofproto_class->meter_get(ofproto,
4922 meter->provider_meter_id,
4924 ofputil_append_meter_stats(&replies, &stats);
4926 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
4927 struct ofputil_meter_config config;
4929 config.meter_id = meter_id;
4930 config.flags = meter->flags;
4931 config.n_bands = meter->n_bands;
4932 config.bands = meter->bands;
4933 ofputil_append_meter_config(&replies, &config);
4937 ofconn_send_replies(ofconn, &replies);
4938 ofpbuf_uninit(&bands);
4943 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4945 const struct ofp_header *oh = msg->data;
4949 error = ofptype_decode(&type, oh);
4955 /* OpenFlow requests. */
4956 case OFPTYPE_ECHO_REQUEST:
4957 return handle_echo_request(ofconn, oh);
4959 case OFPTYPE_FEATURES_REQUEST:
4960 return handle_features_request(ofconn, oh);
4962 case OFPTYPE_GET_CONFIG_REQUEST:
4963 return handle_get_config_request(ofconn, oh);
4965 case OFPTYPE_SET_CONFIG:
4966 return handle_set_config(ofconn, oh);
4968 case OFPTYPE_PACKET_OUT:
4969 return handle_packet_out(ofconn, oh);
4971 case OFPTYPE_PORT_MOD:
4972 return handle_port_mod(ofconn, oh);
4974 case OFPTYPE_FLOW_MOD:
4975 return handle_flow_mod(ofconn, oh);
4977 case OFPTYPE_METER_MOD:
4978 return handle_meter_mod(ofconn, oh);
4980 case OFPTYPE_BARRIER_REQUEST:
4981 return handle_barrier_request(ofconn, oh);
4983 case OFPTYPE_ROLE_REQUEST:
4984 return handle_role_request(ofconn, oh);
4986 /* OpenFlow replies. */
4987 case OFPTYPE_ECHO_REPLY:
4990 /* Nicira extension requests. */
4991 case OFPTYPE_FLOW_MOD_TABLE_ID:
4992 return handle_nxt_flow_mod_table_id(ofconn, oh);
4994 case OFPTYPE_SET_FLOW_FORMAT:
4995 return handle_nxt_set_flow_format(ofconn, oh);
4997 case OFPTYPE_SET_PACKET_IN_FORMAT:
4998 return handle_nxt_set_packet_in_format(ofconn, oh);
5000 case OFPTYPE_SET_CONTROLLER_ID:
5001 return handle_nxt_set_controller_id(ofconn, oh);
5003 case OFPTYPE_FLOW_AGE:
5004 /* Nothing to do. */
5007 case OFPTYPE_FLOW_MONITOR_CANCEL:
5008 return handle_flow_monitor_cancel(ofconn, oh);
5010 case OFPTYPE_SET_ASYNC_CONFIG:
5011 return handle_nxt_set_async_config(ofconn, oh);
5013 /* Statistics requests. */
5014 case OFPTYPE_DESC_STATS_REQUEST:
5015 return handle_desc_stats_request(ofconn, oh);
5017 case OFPTYPE_FLOW_STATS_REQUEST:
5018 return handle_flow_stats_request(ofconn, oh);
5020 case OFPTYPE_AGGREGATE_STATS_REQUEST:
5021 return handle_aggregate_stats_request(ofconn, oh);
5023 case OFPTYPE_TABLE_STATS_REQUEST:
5024 return handle_table_stats_request(ofconn, oh);
5026 case OFPTYPE_PORT_STATS_REQUEST:
5027 return handle_port_stats_request(ofconn, oh);
5029 case OFPTYPE_QUEUE_STATS_REQUEST:
5030 return handle_queue_stats_request(ofconn, oh);
5032 case OFPTYPE_PORT_DESC_STATS_REQUEST:
5033 return handle_port_desc_stats_request(ofconn, oh);
5035 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
5036 return handle_flow_monitor_request(ofconn, oh);
5038 case OFPTYPE_METER_STATS_REQUEST:
5039 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
5040 return handle_meter_request(ofconn, oh, type);
5042 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
5043 return handle_meter_features_request(ofconn, oh);
5045 /* FIXME: Change the following once they are implemented: */
5046 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
5047 case OFPTYPE_GET_ASYNC_REQUEST:
5048 case OFPTYPE_GROUP_STATS_REQUEST:
5049 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
5050 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
5051 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
5052 return OFPERR_OFPBRC_BAD_TYPE;
5056 case OFPTYPE_FEATURES_REPLY:
5057 case OFPTYPE_GET_CONFIG_REPLY:
5058 case OFPTYPE_PACKET_IN:
5059 case OFPTYPE_FLOW_REMOVED:
5060 case OFPTYPE_PORT_STATUS:
5061 case OFPTYPE_BARRIER_REPLY:
5062 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
5063 case OFPTYPE_DESC_STATS_REPLY:
5064 case OFPTYPE_FLOW_STATS_REPLY:
5065 case OFPTYPE_QUEUE_STATS_REPLY:
5066 case OFPTYPE_PORT_STATS_REPLY:
5067 case OFPTYPE_TABLE_STATS_REPLY:
5068 case OFPTYPE_AGGREGATE_STATS_REPLY:
5069 case OFPTYPE_PORT_DESC_STATS_REPLY:
5070 case OFPTYPE_ROLE_REPLY:
5071 case OFPTYPE_FLOW_MONITOR_PAUSED:
5072 case OFPTYPE_FLOW_MONITOR_RESUMED:
5073 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
5074 case OFPTYPE_GET_ASYNC_REPLY:
5075 case OFPTYPE_GROUP_STATS_REPLY:
5076 case OFPTYPE_GROUP_DESC_STATS_REPLY:
5077 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
5078 case OFPTYPE_METER_STATS_REPLY:
5079 case OFPTYPE_METER_CONFIG_STATS_REPLY:
5080 case OFPTYPE_METER_FEATURES_STATS_REPLY:
5081 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
5083 return OFPERR_OFPBRC_BAD_TYPE;
5088 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
5090 int error = handle_openflow__(ofconn, ofp_msg);
5091 if (error && error != OFPROTO_POSTPONE) {
5092 ofconn_send_error(ofconn, ofp_msg->data, error);
5094 COVERAGE_INC(ofproto_recv_openflow);
5095 return error != OFPROTO_POSTPONE;
5098 /* Asynchronous operations. */
5100 /* Creates and returns a new ofopgroup that is not associated with any
5101 * OpenFlow connection.
5103 * The caller should add operations to the returned group with
5104 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5105 static struct ofopgroup *
5106 ofopgroup_create_unattached(struct ofproto *ofproto)
5108 struct ofopgroup *group = xzalloc(sizeof *group);
5109 group->ofproto = ofproto;
5110 list_init(&group->ofproto_node);
5111 list_init(&group->ops);
5112 list_init(&group->ofconn_node);
5116 /* Creates and returns a new ofopgroup for 'ofproto'.
5118 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
5119 * connection. The 'request' and 'buffer_id' arguments are ignored.
5121 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
5122 * If the ofopgroup eventually fails, then the error reply will include
5123 * 'request'. If the ofopgroup eventually succeeds, then the packet with
5124 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
5126 * The caller should add operations to the returned group with
5127 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5128 static struct ofopgroup *
5129 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
5130 const struct ofp_header *request, uint32_t buffer_id)
5132 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
5134 size_t request_len = ntohs(request->length);
5136 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
5138 ofconn_add_opgroup(ofconn, &group->ofconn_node);
5139 group->ofconn = ofconn;
5140 group->request = xmemdup(request, MIN(request_len, 64));
5141 group->buffer_id = buffer_id;
5146 /* Submits 'group' for processing.
5148 * If 'group' contains no operations (e.g. none were ever added, or all of the
5149 * ones that were added completed synchronously), then it is destroyed
5150 * immediately. Otherwise it is added to the ofproto's list of pending
5153 ofopgroup_submit(struct ofopgroup *group)
5155 if (!group->n_running) {
5156 ofopgroup_complete(group);
5158 list_push_back(&group->ofproto->pending, &group->ofproto_node);
5159 group->ofproto->n_pending++;
5164 ofopgroup_complete(struct ofopgroup *group)
5166 struct ofproto *ofproto = group->ofproto;
5168 struct ofconn *abbrev_ofconn;
5169 ovs_be32 abbrev_xid;
5171 struct ofoperation *op, *next_op;
5174 ovs_assert(!group->n_running);
5177 LIST_FOR_EACH (op, group_node, &group->ops) {
5184 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
5185 LIST_FOR_EACH (op, group_node, &group->ops) {
5186 if (op->type != OFOPERATION_DELETE) {
5187 struct ofpbuf *packet;
5190 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
5193 struct rule_execute *re;
5197 ofproto_rule_ref(op->rule);
5199 re = xmalloc(sizeof *re);
5200 re->rule = op->rule;
5201 re->in_port = in_port;
5202 re->packet = packet;
5204 if (!guarded_list_push_back(&ofproto->rule_executes,
5205 &re->list_node, 1024)) {
5206 ofproto_rule_unref(op->rule);
5207 ofpbuf_delete(re->packet);
5216 if (!error && !list_is_empty(&group->ofconn_node)) {
5217 abbrev_ofconn = group->ofconn;
5218 abbrev_xid = group->request->xid;
5220 abbrev_ofconn = NULL;
5221 abbrev_xid = htonl(0);
5223 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
5224 struct rule *rule = op->rule;
5226 /* We generally want to report the change to active OpenFlow flow
5227 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
5229 - The operation failed.
5231 - The affected rule is not visible to controllers.
5233 - The operation's only effect was to update rule->modified. */
5235 || ofproto_rule_is_hidden(rule)
5236 || (op->type == OFOPERATION_MODIFY
5238 && rule->flow_cookie == op->flow_cookie))) {
5239 /* Check that we can just cast from ofoperation_type to
5240 * nx_flow_update_event. */
5241 enum nx_flow_update_event event_type;
5244 case OFOPERATION_ADD:
5245 case OFOPERATION_REPLACE:
5246 event_type = NXFME_ADDED;
5249 case OFOPERATION_DELETE:
5250 event_type = NXFME_DELETED;
5253 case OFOPERATION_MODIFY:
5254 event_type = NXFME_MODIFIED;
5261 ofmonitor_report(ofproto->connmgr, rule, event_type,
5262 op->reason, abbrev_ofconn, abbrev_xid);
5265 rule->pending = NULL;
5268 case OFOPERATION_ADD:
5272 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
5273 if (vid_mask == VLAN_VID_MASK) {
5274 if (ofproto->vlan_bitmap) {
5275 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
5276 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
5277 bitmap_set1(ofproto->vlan_bitmap, vid);
5278 ofproto->vlans_changed = true;
5281 ofproto->vlans_changed = true;
5285 ovs_rwlock_wrlock(&rule->rwlock);
5286 oftable_remove_rule(rule);
5287 ofproto_rule_unref(rule);
5291 case OFOPERATION_DELETE:
5292 ovs_assert(!op->error);
5293 ofproto_rule_unref(rule);
5297 case OFOPERATION_MODIFY:
5298 case OFOPERATION_REPLACE:
5300 long long int now = time_msec();
5302 rule->modified = now;
5303 if (op->type == OFOPERATION_REPLACE) {
5304 rule->created = rule->used = now;
5307 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
5308 ovs_mutex_lock(&rule->timeout_mutex);
5309 rule->idle_timeout = op->idle_timeout;
5310 rule->hard_timeout = op->hard_timeout;
5311 ovs_mutex_unlock(&rule->timeout_mutex);
5313 struct rule_actions *old_actions;
5315 ovs_rwlock_wrlock(&rule->rwlock);
5316 old_actions = rule->actions;
5317 rule->actions = op->actions;
5318 ovs_rwlock_unlock(&rule->rwlock);
5321 rule_actions_unref(old_actions);
5323 rule->send_flow_removed = op->send_flow_removed;
5331 ofoperation_destroy(op);
5334 ofmonitor_flush(ofproto->connmgr);
5336 if (!list_is_empty(&group->ofproto_node)) {
5337 ovs_assert(ofproto->n_pending > 0);
5338 ofproto->n_pending--;
5339 list_remove(&group->ofproto_node);
5341 if (!list_is_empty(&group->ofconn_node)) {
5342 list_remove(&group->ofconn_node);
5344 ofconn_send_error(group->ofconn, group->request, error);
5346 connmgr_retry(ofproto->connmgr);
5348 free(group->request);
5352 /* Initiates a new operation on 'rule', of the specified 'type', within
5353 * 'group'. Prior to calling, 'rule' must not have any pending operation.
5355 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
5356 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
5358 * Returns the newly created ofoperation (which is also available as
5359 * rule->pending). */
5360 static struct ofoperation *
5361 ofoperation_create(struct ofopgroup *group, struct rule *rule,
5362 enum ofoperation_type type,
5363 enum ofp_flow_removed_reason reason)
5365 struct ofproto *ofproto = group->ofproto;
5366 struct ofoperation *op;
5368 ovs_assert(!rule->pending);
5370 op = rule->pending = xzalloc(sizeof *op);
5372 list_push_back(&group->ops, &op->group_node);
5375 op->reason = reason;
5376 op->flow_cookie = rule->flow_cookie;
5377 ovs_mutex_lock(&rule->timeout_mutex);
5378 op->idle_timeout = rule->idle_timeout;
5379 op->hard_timeout = rule->hard_timeout;
5380 ovs_mutex_unlock(&rule->timeout_mutex);
5381 op->send_flow_removed = rule->send_flow_removed;
5385 if (type == OFOPERATION_DELETE) {
5386 hmap_insert(&ofproto->deletions, &op->hmap_node,
5387 cls_rule_hash(&rule->cr, rule->table_id));
5394 ofoperation_destroy(struct ofoperation *op)
5396 struct ofopgroup *group = op->group;
5399 op->rule->pending = NULL;
5401 if (op->type == OFOPERATION_DELETE) {
5402 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
5404 list_remove(&op->group_node);
5405 rule_actions_unref(op->actions);
5409 /* Indicates that 'op' completed with status 'error', which is either 0 to
5410 * indicate success or an OpenFlow error code on failure.
5412 * If 'error' is 0, indicating success, the operation will be committed
5413 * permanently to the flow table.
5415 * If 'error' is nonzero, then generally the operation will be rolled back:
5417 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
5418 * restores the original rule. The caller must have uninitialized any
5419 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
5420 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
5421 * and 7 for the new rule, calling its ->rule_dealloc() function.
5423 * - If 'op' is a "modify flow" operation, ofproto restores the original
5426 * - 'op' must not be a "delete flow" operation. Removing a rule is not
5427 * allowed to fail. It must always succeed.
5429 * Please see the large comment in ofproto/ofproto-provider.h titled
5430 * "Asynchronous Operation Support" for more information. */
5432 ofoperation_complete(struct ofoperation *op, enum ofperr error)
5434 struct ofopgroup *group = op->group;
5436 ovs_assert(op->rule->pending == op);
5437 ovs_assert(group->n_running > 0);
5438 ovs_assert(!error || op->type != OFOPERATION_DELETE);
5441 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
5442 ofopgroup_complete(group);
5447 pick_datapath_id(const struct ofproto *ofproto)
5449 const struct ofport *port;
5451 port = ofproto_get_port(ofproto, OFPP_LOCAL);
5453 uint8_t ea[ETH_ADDR_LEN];
5456 error = netdev_get_etheraddr(port->netdev, ea);
5458 return eth_addr_to_uint64(ea);
5460 VLOG_WARN("%s: could not get MAC address for %s (%s)",
5461 ofproto->name, netdev_get_name(port->netdev),
5462 ovs_strerror(error));
5464 return ofproto->fallback_dpid;
5468 pick_fallback_dpid(void)
5470 uint8_t ea[ETH_ADDR_LEN];
5471 eth_addr_nicira_random(ea);
5472 return eth_addr_to_uint64(ea);
5475 /* Table overflow policy. */
5477 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
5478 * to NULL if the table is not configured to evict rules or if the table
5479 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
5480 * or with no timeouts are not evictable.) */
5482 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
5484 struct eviction_group *evg;
5487 if (!table->eviction_fields) {
5491 /* In the common case, the outer and inner loops here will each be entered
5494 * - The inner loop normally "return"s in its first iteration. If the
5495 * eviction group has any evictable rules, then it always returns in
5498 * - The outer loop only iterates more than once if the largest eviction
5499 * group has no evictable rules.
5501 * - The outer loop can exit only if table's 'max_flows' is all filled up
5502 * by unevictable rules. */
5503 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
5506 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
5507 if (!ovs_rwlock_trywrlock(&rule->rwlock)) {
5517 /* Searches 'ofproto' for tables that have more flows than their configured
5518 * maximum and that have flow eviction enabled, and evicts as many flows as
5519 * necessary and currently feasible from them.
5521 * This triggers only when an OpenFlow table has N flows in it and then the
5522 * client configures a maximum number of flows less than N. */
5524 ofproto_evict(struct ofproto *ofproto)
5526 struct ofopgroup *group;
5527 struct oftable *table;
5529 group = ofopgroup_create_unattached(ofproto);
5530 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
5531 while (table->eviction_fields) {
5535 ovs_rwlock_rdlock(&table->cls.rwlock);
5536 n_rules = classifier_count(&table->cls);
5537 ovs_rwlock_unlock(&table->cls.rwlock);
5539 if (n_rules <= table->max_flows) {
5543 if (!choose_rule_to_evict(table, &rule)) {
5547 if (rule->pending) {
5548 ovs_rwlock_unlock(&rule->rwlock);
5552 ofoperation_create(group, rule,
5553 OFOPERATION_DELETE, OFPRR_EVICTION);
5554 oftable_remove_rule(rule);
5555 ofproto->ofproto_class->rule_delete(rule);
5558 ofopgroup_submit(group);
5561 /* Eviction groups. */
5563 /* Returns the priority to use for an eviction_group that contains 'n_rules'
5564 * rules. The priority contains low-order random bits to ensure that eviction
5565 * groups with the same number of rules are prioritized randomly. */
5567 eviction_group_priority(size_t n_rules)
5569 uint16_t size = MIN(UINT16_MAX, n_rules);
5570 return (size << 16) | random_uint16();
5573 /* Updates 'evg', an eviction_group within 'table', following a change that
5574 * adds or removes rules in 'evg'. */
5576 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
5578 heap_change(&table->eviction_groups_by_size, &evg->size_node,
5579 eviction_group_priority(heap_count(&evg->rules)));
5582 /* Destroys 'evg', an eviction_group within 'table':
5584 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
5585 * rules themselves, just removes them from the eviction group.)
5587 * - Removes 'evg' from 'table'.
5591 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
5593 while (!heap_is_empty(&evg->rules)) {
5596 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
5597 rule->eviction_group = NULL;
5599 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
5600 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
5601 heap_destroy(&evg->rules);
5605 /* Removes 'rule' from its eviction group, if any. */
5607 eviction_group_remove_rule(struct rule *rule)
5609 if (rule->eviction_group) {
5610 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5611 struct eviction_group *evg = rule->eviction_group;
5613 rule->eviction_group = NULL;
5614 heap_remove(&evg->rules, &rule->evg_node);
5615 if (heap_is_empty(&evg->rules)) {
5616 eviction_group_destroy(table, evg);
5618 eviction_group_resized(table, evg);
5623 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
5624 * returns the hash value. */
5626 eviction_group_hash_rule(struct rule *rule)
5628 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5629 const struct mf_subfield *sf;
5633 hash = table->eviction_group_id_basis;
5634 miniflow_expand(&rule->cr.match.flow, &flow);
5635 for (sf = table->eviction_fields;
5636 sf < &table->eviction_fields[table->n_eviction_fields];
5639 if (mf_are_prereqs_ok(sf->field, &flow)) {
5640 union mf_value value;
5642 mf_get_value(sf->field, &flow, &value);
5644 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
5646 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
5647 unsigned int start = sf->ofs + sf->n_bits;
5648 bitwise_zero(&value, sf->field->n_bytes, start,
5649 sf->field->n_bytes * 8 - start);
5651 hash = hash_bytes(&value, sf->field->n_bytes, hash);
5653 hash = hash_int(hash, 0);
5660 /* Returns an eviction group within 'table' with the given 'id', creating one
5662 static struct eviction_group *
5663 eviction_group_find(struct oftable *table, uint32_t id)
5665 struct eviction_group *evg;
5667 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
5671 evg = xmalloc(sizeof *evg);
5672 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
5673 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
5674 eviction_group_priority(0));
5675 heap_init(&evg->rules);
5680 /* Returns an eviction priority for 'rule'. The return value should be
5681 * interpreted so that higher priorities make a rule more attractive candidates
5684 rule_eviction_priority(struct rule *rule)
5686 long long int hard_expiration;
5687 long long int idle_expiration;
5688 long long int expiration;
5689 uint32_t expiration_offset;
5691 /* Calculate time of expiration. */
5692 ovs_mutex_lock(&rule->timeout_mutex);
5693 hard_expiration = (rule->hard_timeout
5694 ? rule->modified + rule->hard_timeout * 1000
5696 idle_expiration = (rule->idle_timeout
5697 ? rule->used + rule->idle_timeout * 1000
5699 expiration = MIN(hard_expiration, idle_expiration);
5700 ovs_mutex_unlock(&rule->timeout_mutex);
5701 if (expiration == LLONG_MAX) {
5705 /* Calculate the time of expiration as a number of (approximate) seconds
5706 * after program startup.
5708 * This should work OK for program runs that last UINT32_MAX seconds or
5709 * less. Therefore, please restart OVS at least once every 136 years. */
5710 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
5712 /* Invert the expiration offset because we're using a max-heap. */
5713 return UINT32_MAX - expiration_offset;
5716 /* Adds 'rule' to an appropriate eviction group for its oftable's
5717 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
5718 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
5721 * The caller must ensure that 'rule' is not already in an eviction group. */
5723 eviction_group_add_rule(struct rule *rule)
5725 struct ofproto *ofproto = rule->ofproto;
5726 struct oftable *table = &ofproto->tables[rule->table_id];
5729 ovs_mutex_lock(&rule->timeout_mutex);
5730 has_timeout = rule->hard_timeout || rule->idle_timeout;
5731 ovs_mutex_unlock(&rule->timeout_mutex);
5733 if (table->eviction_fields && has_timeout) {
5734 struct eviction_group *evg;
5736 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
5738 rule->eviction_group = evg;
5739 heap_insert(&evg->rules, &rule->evg_node,
5740 rule_eviction_priority(rule));
5741 eviction_group_resized(table, evg);
5747 /* Initializes 'table'. */
5749 oftable_init(struct oftable *table)
5751 memset(table, 0, sizeof *table);
5752 classifier_init(&table->cls);
5753 table->max_flows = UINT_MAX;
5756 /* Destroys 'table', including its classifier and eviction groups.
5758 * The caller is responsible for freeing 'table' itself. */
5760 oftable_destroy(struct oftable *table)
5762 ovs_rwlock_rdlock(&table->cls.rwlock);
5763 ovs_assert(classifier_is_empty(&table->cls));
5764 ovs_rwlock_unlock(&table->cls.rwlock);
5765 oftable_disable_eviction(table);
5766 classifier_destroy(&table->cls);
5770 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
5771 * string, then 'table' will use its default name.
5773 * This only affects the name exposed for a table exposed through the OpenFlow
5774 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
5776 oftable_set_name(struct oftable *table, const char *name)
5778 if (name && name[0]) {
5779 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
5780 if (!table->name || strncmp(name, table->name, len)) {
5782 table->name = xmemdup0(name, len);
5790 /* oftables support a choice of two policies when adding a rule would cause the
5791 * number of flows in the table to exceed the configured maximum number: either
5792 * they can refuse to add the new flow or they can evict some existing flow.
5793 * This function configures the former policy on 'table'. */
5795 oftable_disable_eviction(struct oftable *table)
5797 if (table->eviction_fields) {
5798 struct eviction_group *evg, *next;
5800 HMAP_FOR_EACH_SAFE (evg, next, id_node,
5801 &table->eviction_groups_by_id) {
5802 eviction_group_destroy(table, evg);
5804 hmap_destroy(&table->eviction_groups_by_id);
5805 heap_destroy(&table->eviction_groups_by_size);
5807 free(table->eviction_fields);
5808 table->eviction_fields = NULL;
5809 table->n_eviction_fields = 0;
5813 /* oftables support a choice of two policies when adding a rule would cause the
5814 * number of flows in the table to exceed the configured maximum number: either
5815 * they can refuse to add the new flow or they can evict some existing flow.
5816 * This function configures the latter policy on 'table', with fairness based
5817 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
5818 * 'n_fields' as 0 disables fairness.) */
5820 oftable_enable_eviction(struct oftable *table,
5821 const struct mf_subfield *fields, size_t n_fields)
5823 struct cls_cursor cursor;
5826 if (table->eviction_fields
5827 && n_fields == table->n_eviction_fields
5829 || !memcmp(fields, table->eviction_fields,
5830 n_fields * sizeof *fields))) {
5835 oftable_disable_eviction(table);
5837 table->n_eviction_fields = n_fields;
5838 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
5840 table->eviction_group_id_basis = random_uint32();
5841 hmap_init(&table->eviction_groups_by_id);
5842 heap_init(&table->eviction_groups_by_size);
5844 ovs_rwlock_rdlock(&table->cls.rwlock);
5845 cls_cursor_init(&cursor, &table->cls, NULL);
5846 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
5847 eviction_group_add_rule(rule);
5849 ovs_rwlock_unlock(&table->cls.rwlock);
5852 /* Removes 'rule' from the oftable that contains it. */
5854 oftable_remove_rule__(struct ofproto *ofproto, struct classifier *cls,
5856 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock)
5858 classifier_remove(cls, &rule->cr);
5859 cookies_remove(ofproto, rule);
5860 eviction_group_remove_rule(rule);
5861 ovs_mutex_lock(&ofproto_mutex);
5862 if (!list_is_empty(&rule->expirable)) {
5863 list_remove(&rule->expirable);
5865 ovs_mutex_unlock(&ofproto_mutex);
5866 if (!list_is_empty(&rule->meter_list_node)) {
5867 list_remove(&rule->meter_list_node);
5868 list_init(&rule->meter_list_node);
5870 ovs_rwlock_unlock(&rule->rwlock);
5874 oftable_remove_rule(struct rule *rule)
5876 struct ofproto *ofproto = rule->ofproto;
5877 struct oftable *table = &ofproto->tables[rule->table_id];
5879 ovs_rwlock_wrlock(&table->cls.rwlock);
5880 oftable_remove_rule__(ofproto, &table->cls, rule);
5881 ovs_rwlock_unlock(&table->cls.rwlock);
5884 /* Inserts 'rule' into its oftable, which must not already contain any rule for
5885 * the same cls_rule. */
5887 oftable_insert_rule(struct rule *rule)
5889 struct ofproto *ofproto = rule->ofproto;
5890 struct oftable *table = &ofproto->tables[rule->table_id];
5893 ovs_mutex_lock(&rule->timeout_mutex);
5894 may_expire = rule->hard_timeout || rule->idle_timeout;
5895 ovs_mutex_unlock(&rule->timeout_mutex);
5898 ovs_mutex_lock(&ofproto_mutex);
5899 list_insert(&ofproto->expirable, &rule->expirable);
5900 ovs_mutex_unlock(&ofproto_mutex);
5902 cookies_insert(ofproto, rule);
5904 if (rule->actions->meter_id) {
5905 struct meter *meter = ofproto->meters[rule->actions->meter_id];
5906 list_insert(&meter->rules, &rule->meter_list_node);
5908 ovs_rwlock_wrlock(&table->cls.rwlock);
5909 classifier_insert(&table->cls, &rule->cr);
5910 ovs_rwlock_unlock(&table->cls.rwlock);
5911 eviction_group_add_rule(rule);
5914 /* unixctl commands. */
5917 ofproto_lookup(const char *name)
5919 struct ofproto *ofproto;
5921 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
5923 if (!strcmp(ofproto->name, name)) {
5931 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
5932 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5934 struct ofproto *ofproto;
5938 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
5939 ds_put_format(&results, "%s\n", ofproto->name);
5941 unixctl_command_reply(conn, ds_cstr(&results));
5942 ds_destroy(&results);
5946 ofproto_unixctl_init(void)
5948 static bool registered;
5954 unixctl_command_register("ofproto/list", "", 0, 0,
5955 ofproto_unixctl_list, NULL);
5958 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5960 * This is deprecated. It is only for compatibility with broken device drivers
5961 * in old versions of Linux that do not properly support VLANs when VLAN
5962 * devices are not used. When broken device drivers are no longer in
5963 * widespread use, we will delete these interfaces. */
5965 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
5966 * (exactly) by an OpenFlow rule in 'ofproto'. */
5968 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
5970 const struct oftable *oftable;
5972 free(ofproto->vlan_bitmap);
5973 ofproto->vlan_bitmap = bitmap_allocate(4096);
5974 ofproto->vlans_changed = false;
5976 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
5977 const struct cls_table *table;
5979 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
5980 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
5981 const struct cls_rule *rule;
5983 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
5984 uint16_t vid = miniflow_get_vid(&rule->match.flow);
5985 bitmap_set1(vlan_bitmap, vid);
5986 bitmap_set1(ofproto->vlan_bitmap, vid);
5993 /* Returns true if new VLANs have come into use by the flow table since the
5994 * last call to ofproto_get_vlan_usage().
5996 * We don't track when old VLANs stop being used. */
5998 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
6000 return ofproto->vlans_changed;
6003 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
6004 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
6005 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
6006 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
6007 * then the VLAN device is un-enslaved. */
6009 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
6010 ofp_port_t realdev_ofp_port, int vid)
6012 struct ofport *ofport;
6015 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
6017 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
6019 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
6020 ofproto->name, vlandev_ofp_port);
6024 if (!ofproto->ofproto_class->set_realdev) {
6025 if (!vlandev_ofp_port) {
6028 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
6032 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
6034 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
6035 ofproto->name, vlandev_ofp_port,
6036 netdev_get_name(ofport->netdev), ovs_strerror(error));