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 unsigned flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT;
279 unsigned n_handler_threads;
280 enum ofproto_flow_miss_model flow_miss_model = OFPROTO_HANDLE_MISS_AUTO;
282 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
283 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
285 /* Initial mappings of port to OpenFlow number mappings. */
286 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
288 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
290 /* The default value of true waits for flow restore. */
291 static bool flow_restore_wait = true;
293 /* Must be called to initialize the ofproto library.
295 * The caller may pass in 'iface_hints', which contains an shash of
296 * "iface_hint" elements indexed by the interface's name. The provider
297 * may use these hints to describe the startup configuration in order to
298 * reinitialize its state. The caller owns the provided data, so a
299 * provider will make copies of anything required. An ofproto provider
300 * will remove any existing state that is not described by the hint, and
301 * may choose to remove it all. */
303 ofproto_init(const struct shash *iface_hints)
305 struct shash_node *node;
308 ofproto_class_register(&ofproto_dpif_class);
310 /* Make a local copy, since we don't own 'iface_hints' elements. */
311 SHASH_FOR_EACH(node, iface_hints) {
312 const struct iface_hint *orig_hint = node->data;
313 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
314 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
316 new_hint->br_name = xstrdup(orig_hint->br_name);
317 new_hint->br_type = xstrdup(br_type);
318 new_hint->ofp_port = orig_hint->ofp_port;
320 shash_add(&init_ofp_ports, node->name, new_hint);
323 for (i = 0; i < n_ofproto_classes; i++) {
324 ofproto_classes[i]->init(&init_ofp_ports);
328 /* 'type' should be a normalized datapath type, as returned by
329 * ofproto_normalize_type(). Returns the corresponding ofproto_class
330 * structure, or a null pointer if there is none registered for 'type'. */
331 static const struct ofproto_class *
332 ofproto_class_find__(const char *type)
336 for (i = 0; i < n_ofproto_classes; i++) {
337 const struct ofproto_class *class = ofproto_classes[i];
342 class->enumerate_types(&types);
343 found = sset_contains(&types, type);
344 sset_destroy(&types);
350 VLOG_WARN("unknown datapath type %s", type);
354 /* Registers a new ofproto class. After successful registration, new ofprotos
355 * of that type can be created using ofproto_create(). */
357 ofproto_class_register(const struct ofproto_class *new_class)
361 for (i = 0; i < n_ofproto_classes; i++) {
362 if (ofproto_classes[i] == new_class) {
367 if (n_ofproto_classes >= allocated_ofproto_classes) {
368 ofproto_classes = x2nrealloc(ofproto_classes,
369 &allocated_ofproto_classes,
370 sizeof *ofproto_classes);
372 ofproto_classes[n_ofproto_classes++] = new_class;
376 /* Unregisters a datapath provider. 'type' must have been previously
377 * registered and not currently be in use by any ofprotos. After
378 * unregistration new datapaths of that type cannot be opened using
379 * ofproto_create(). */
381 ofproto_class_unregister(const struct ofproto_class *class)
385 for (i = 0; i < n_ofproto_classes; i++) {
386 if (ofproto_classes[i] == class) {
387 for (i++; i < n_ofproto_classes; i++) {
388 ofproto_classes[i - 1] = ofproto_classes[i];
394 VLOG_WARN("attempted to unregister an ofproto class that is not "
399 /* Clears 'types' and enumerates all registered ofproto types into it. The
400 * caller must first initialize the sset. */
402 ofproto_enumerate_types(struct sset *types)
406 for (i = 0; i < n_ofproto_classes; i++) {
407 ofproto_classes[i]->enumerate_types(types);
411 /* Returns the fully spelled out name for the given ofproto 'type'.
413 * Normalized type string can be compared with strcmp(). Unnormalized type
414 * string might be the same even if they have different spellings. */
416 ofproto_normalize_type(const char *type)
418 return type && type[0] ? type : "system";
421 /* Clears 'names' and enumerates the names of all known created ofprotos with
422 * the given 'type'. The caller must first initialize the sset. Returns 0 if
423 * successful, otherwise a positive errno value.
425 * Some kinds of datapaths might not be practically enumerable. This is not
426 * considered an error. */
428 ofproto_enumerate_names(const char *type, struct sset *names)
430 const struct ofproto_class *class = ofproto_class_find__(type);
431 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
435 ofproto_create(const char *datapath_name, const char *datapath_type,
436 struct ofproto **ofprotop)
438 const struct ofproto_class *class;
439 struct ofproto *ofproto;
445 ofproto_unixctl_init();
447 datapath_type = ofproto_normalize_type(datapath_type);
448 class = ofproto_class_find__(datapath_type);
450 VLOG_WARN("could not create datapath %s of unknown type %s",
451 datapath_name, datapath_type);
455 ofproto = class->alloc();
457 VLOG_ERR("failed to allocate datapath %s of type %s",
458 datapath_name, datapath_type);
463 memset(ofproto, 0, sizeof *ofproto);
464 ofproto->ofproto_class = class;
465 ofproto->name = xstrdup(datapath_name);
466 ofproto->type = xstrdup(datapath_type);
467 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
468 hash_string(ofproto->name, 0));
469 ofproto->datapath_id = 0;
470 ofproto->forward_bpdu = false;
471 ofproto->fallback_dpid = pick_fallback_dpid();
472 ofproto->mfr_desc = NULL;
473 ofproto->hw_desc = NULL;
474 ofproto->sw_desc = NULL;
475 ofproto->serial_desc = NULL;
476 ofproto->dp_desc = NULL;
477 ofproto->frag_handling = OFPC_FRAG_NORMAL;
478 hmap_init(&ofproto->ports);
479 shash_init(&ofproto->port_by_name);
480 simap_init(&ofproto->ofp_requests);
481 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
482 ofproto->eviction_group_timer = LLONG_MIN;
483 ofproto->tables = NULL;
484 ofproto->n_tables = 0;
485 hindex_init(&ofproto->cookies);
486 list_init(&ofproto->expirable);
487 ovs_mutex_init_recursive(&ofproto->expirable_mutex);
488 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
489 ofproto->state = S_OPENFLOW;
490 list_init(&ofproto->pending);
491 ofproto->n_pending = 0;
492 hmap_init(&ofproto->deletions);
493 guarded_list_init(&ofproto->rule_executes);
494 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
495 ofproto->first_op = ofproto->last_op = LLONG_MIN;
496 ofproto->next_op_report = LLONG_MAX;
497 ofproto->op_backoff = LLONG_MIN;
498 ofproto->vlan_bitmap = NULL;
499 ofproto->vlans_changed = false;
500 ofproto->min_mtu = INT_MAX;
502 error = ofproto->ofproto_class->construct(ofproto);
504 VLOG_ERR("failed to open datapath %s: %s",
505 datapath_name, ovs_strerror(error));
506 ofproto_destroy__(ofproto);
510 /* The "max_ports" member should have been set by ->construct(ofproto).
511 * Port 0 is not a valid OpenFlow port, so mark that as unavailable. */
512 ofproto->ofp_port_ids = bitmap_allocate(ofproto->max_ports);
513 bitmap_set1(ofproto->ofp_port_ids, 0);
515 /* Check that hidden tables, if any, are at the end. */
516 ovs_assert(ofproto->n_tables);
517 for (i = 0; i + 1 < ofproto->n_tables; i++) {
518 enum oftable_flags flags = ofproto->tables[i].flags;
519 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
521 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
524 ofproto->datapath_id = pick_datapath_id(ofproto);
527 /* Initialize meters table. */
528 if (ofproto->ofproto_class->meter_get_features) {
529 ofproto->ofproto_class->meter_get_features(ofproto,
530 &ofproto->meter_features);
532 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
534 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
535 * sizeof(struct meter *));
541 /* Must be called (only) by an ofproto implementation in its constructor
542 * function. See the large comment on 'construct' in struct ofproto_class for
545 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
547 struct oftable *table;
549 ovs_assert(!ofproto->n_tables);
550 ovs_assert(n_tables >= 1 && n_tables <= 255);
552 ofproto->n_tables = n_tables;
553 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
554 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
559 /* To be optionally called (only) by an ofproto implementation in its
560 * constructor function. See the large comment on 'construct' in struct
561 * ofproto_class for details.
563 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
564 * will then ensure that actions passed into the ofproto implementation will
565 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
566 * function is not called, there will be no such restriction.
568 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
569 * the 'max_ports' restriction. */
571 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
573 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
574 ofproto->max_ports = max_ports;
578 ofproto_get_datapath_id(const struct ofproto *ofproto)
580 return ofproto->datapath_id;
584 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
586 uint64_t old_dpid = p->datapath_id;
587 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
588 if (p->datapath_id != old_dpid) {
589 /* Force all active connections to reconnect, since there is no way to
590 * notify a controller that the datapath ID has changed. */
591 ofproto_reconnect_controllers(p);
596 ofproto_set_controllers(struct ofproto *p,
597 const struct ofproto_controller *controllers,
598 size_t n_controllers, uint32_t allowed_versions)
600 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
605 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
607 connmgr_set_fail_mode(p->connmgr, fail_mode);
610 /* Drops the connections between 'ofproto' and all of its controllers, forcing
611 * them to reconnect. */
613 ofproto_reconnect_controllers(struct ofproto *ofproto)
615 connmgr_reconnect(ofproto->connmgr);
618 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
619 * in-band control should guarantee access, in the same way that in-band
620 * control guarantees access to OpenFlow controllers. */
622 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
623 const struct sockaddr_in *extras, size_t n)
625 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
628 /* Sets the OpenFlow queue used by flows set up by in-band control on
629 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
630 * flows will use the default queue. */
632 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
634 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
637 /* Sets the number of flows at which eviction from the kernel flow table
640 ofproto_set_flow_eviction_threshold(unsigned threshold)
642 flow_eviction_threshold = MAX(OFPROTO_FLOW_EVICTION_THRESHOLD_MIN,
646 /* Sets the path for handling flow misses. */
648 ofproto_set_flow_miss_model(unsigned model)
650 flow_miss_model = model;
653 /* If forward_bpdu is true, the NORMAL action will forward frames with
654 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
655 * the NORMAL action will drop these frames. */
657 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
659 bool old_val = ofproto->forward_bpdu;
660 ofproto->forward_bpdu = forward_bpdu;
661 if (old_val != ofproto->forward_bpdu) {
662 if (ofproto->ofproto_class->forward_bpdu_changed) {
663 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
668 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
669 * 'idle_time', in seconds, and the maximum number of MAC table entries to
672 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
675 if (ofproto->ofproto_class->set_mac_table_config) {
676 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
681 /* Sets number of upcall handler threads. The default is
682 * (number of online cores - 2). */
684 ofproto_set_n_handler_threads(unsigned limit)
687 n_handler_threads = limit;
689 int n_proc = sysconf(_SC_NPROCESSORS_ONLN);
690 n_handler_threads = n_proc > 2 ? n_proc - 2 : 1;
695 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
698 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
702 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
704 return connmgr_set_snoops(ofproto->connmgr, snoops);
708 ofproto_set_netflow(struct ofproto *ofproto,
709 const struct netflow_options *nf_options)
711 if (nf_options && sset_is_empty(&nf_options->collectors)) {
715 if (ofproto->ofproto_class->set_netflow) {
716 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
718 return nf_options ? EOPNOTSUPP : 0;
723 ofproto_set_sflow(struct ofproto *ofproto,
724 const struct ofproto_sflow_options *oso)
726 if (oso && sset_is_empty(&oso->targets)) {
730 if (ofproto->ofproto_class->set_sflow) {
731 return ofproto->ofproto_class->set_sflow(ofproto, oso);
733 return oso ? EOPNOTSUPP : 0;
738 ofproto_set_ipfix(struct ofproto *ofproto,
739 const struct ofproto_ipfix_bridge_exporter_options *bo,
740 const struct ofproto_ipfix_flow_exporter_options *fo,
743 if (ofproto->ofproto_class->set_ipfix) {
744 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
746 return (bo || fo) ? EOPNOTSUPP : 0;
751 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
753 flow_restore_wait = flow_restore_wait_db;
757 ofproto_get_flow_restore_wait(void)
759 return flow_restore_wait;
763 /* Spanning Tree Protocol (STP) configuration. */
765 /* Configures STP on 'ofproto' using the settings defined in 's'. If
766 * 's' is NULL, disables STP.
768 * Returns 0 if successful, otherwise a positive errno value. */
770 ofproto_set_stp(struct ofproto *ofproto,
771 const struct ofproto_stp_settings *s)
773 return (ofproto->ofproto_class->set_stp
774 ? ofproto->ofproto_class->set_stp(ofproto, s)
778 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
779 * 'enabled' member of 's' is false, then the other members are not
782 * Returns 0 if successful, otherwise a positive errno value. */
784 ofproto_get_stp_status(struct ofproto *ofproto,
785 struct ofproto_stp_status *s)
787 return (ofproto->ofproto_class->get_stp_status
788 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
792 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
793 * in 's'. The caller is responsible for assigning STP port numbers
794 * (using the 'port_num' member in the range of 1 through 255, inclusive)
795 * and ensuring there are no duplicates. If the 's' is NULL, then STP
796 * is disabled on the port.
798 * Returns 0 if successful, otherwise a positive errno value.*/
800 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
801 const struct ofproto_port_stp_settings *s)
803 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
805 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
806 ofproto->name, ofp_port);
810 return (ofproto->ofproto_class->set_stp_port
811 ? ofproto->ofproto_class->set_stp_port(ofport, s)
815 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
816 * 's'. If the 'enabled' member in 's' is false, then the other members
817 * are not meaningful.
819 * Returns 0 if successful, otherwise a positive errno value.*/
821 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
822 struct ofproto_port_stp_status *s)
824 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
826 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
827 "port %"PRIu16, ofproto->name, ofp_port);
831 return (ofproto->ofproto_class->get_stp_port_status
832 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
836 /* Queue DSCP configuration. */
838 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
839 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
840 * to implement QoS. Instead, it is used to implement features which require
841 * knowledge of what queues exist on a port, and some basic information about
844 * Returns 0 if successful, otherwise a positive errno value. */
846 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
847 const struct ofproto_port_queue *queues,
850 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
853 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
854 ofproto->name, ofp_port);
858 return (ofproto->ofproto_class->set_queues
859 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
863 /* Connectivity Fault Management configuration. */
865 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
867 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
869 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
870 if (ofport && ofproto->ofproto_class->set_cfm) {
871 ofproto->ofproto_class->set_cfm(ofport, NULL);
875 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
876 * basic configuration from the configuration members in 'cfm', and the remote
877 * maintenance point ID from remote_mpid. Ignores the statistics members of
880 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
882 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
883 const struct cfm_settings *s)
885 struct ofport *ofport;
888 ofport = ofproto_get_port(ofproto, ofp_port);
890 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
891 ofproto->name, ofp_port);
895 /* XXX: For configuration simplicity, we only support one remote_mpid
896 * outside of the CFM module. It's not clear if this is the correct long
897 * term solution or not. */
898 error = (ofproto->ofproto_class->set_cfm
899 ? ofproto->ofproto_class->set_cfm(ofport, s)
902 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
903 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
904 ovs_strerror(error));
908 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
909 * 'ofproto' does not have a port 'ofp_port'. */
911 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
912 const struct smap *cfg)
914 struct ofport *ofport;
917 ofport = ofproto_get_port(ofproto, ofp_port);
919 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
920 ofproto->name, ofp_port);
924 error = (ofproto->ofproto_class->set_bfd
925 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
928 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
929 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
930 ovs_strerror(error));
934 /* Populates 'status' with key value pairs indicating the status of the BFD
935 * session on 'ofp_port'. This information is intended to be populated in the
936 * OVS database. Has no effect if 'ofp_port' is not na OpenFlow port in
939 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
942 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
943 return (ofport && ofproto->ofproto_class->get_bfd_status
944 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
948 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
949 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
950 * 0 if LACP partner information is not current (generally indicating a
951 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
953 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
955 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
956 return (ofport && ofproto->ofproto_class->port_is_lacp_current
957 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
963 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
964 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
965 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
966 * configuration plus, if there is more than one slave, a bonding
969 * If 'aux' is already registered then this function updates its configuration
970 * to 's'. Otherwise, this function registers a new bundle.
972 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
975 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
976 const struct ofproto_bundle_settings *s)
978 return (ofproto->ofproto_class->bundle_set
979 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
983 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
984 * If no such bundle has been registered, this has no effect. */
986 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
988 return ofproto_bundle_register(ofproto, aux, NULL);
992 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
993 * If 'aux' is already registered then this function updates its configuration
994 * to 's'. Otherwise, this function registers a new mirror. */
996 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
997 const struct ofproto_mirror_settings *s)
999 return (ofproto->ofproto_class->mirror_set
1000 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1004 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1005 * If no mirror has been registered, this has no effect. */
1007 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1009 return ofproto_mirror_register(ofproto, aux, NULL);
1012 /* Retrieves statistics from mirror associated with client data pointer
1013 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1014 * 'bytes', respectively. If a particular counters is not supported,
1015 * the appropriate argument is set to UINT64_MAX. */
1017 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1018 uint64_t *packets, uint64_t *bytes)
1020 if (!ofproto->ofproto_class->mirror_get_stats) {
1021 *packets = *bytes = UINT64_MAX;
1025 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1029 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1030 * which all packets are flooded, instead of using MAC learning. If
1031 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1033 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1036 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1038 return (ofproto->ofproto_class->set_flood_vlans
1039 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1043 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1044 * output for a mirror. */
1046 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1048 return (ofproto->ofproto_class->is_mirror_output_bundle
1049 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1053 /* Configuration of OpenFlow tables. */
1055 /* Returns the number of OpenFlow tables in 'ofproto'. */
1057 ofproto_get_n_tables(const struct ofproto *ofproto)
1059 return ofproto->n_tables;
1062 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1063 * settings from 's'. 'table_id' must be in the range 0 through the number of
1064 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1066 * For read-only tables, only the name may be configured. */
1068 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1069 const struct ofproto_table_settings *s)
1071 struct oftable *table;
1073 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1074 table = &ofproto->tables[table_id];
1076 oftable_set_name(table, s->name);
1078 if (table->flags & OFTABLE_READONLY) {
1083 oftable_enable_eviction(table, s->groups, s->n_groups);
1085 oftable_disable_eviction(table);
1088 table->max_flows = s->max_flows;
1089 ovs_rwlock_rdlock(&table->cls.rwlock);
1090 if (classifier_count(&table->cls) > table->max_flows
1091 && table->eviction_fields) {
1092 /* 'table' contains more flows than allowed. We might not be able to
1093 * evict them right away because of the asynchronous nature of flow
1094 * table changes. Schedule eviction for later. */
1095 switch (ofproto->state) {
1097 ofproto->state = S_EVICT;
1101 /* We're already deleting flows, nothing more to do. */
1105 ovs_rwlock_unlock(&table->cls.rwlock);
1109 ofproto_has_snoops(const struct ofproto *ofproto)
1111 return connmgr_has_snoops(ofproto->connmgr);
1115 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1117 connmgr_get_snoops(ofproto->connmgr, snoops);
1120 /* Deletes 'rule' from 'cls' within 'ofproto'.
1122 * Within an ofproto implementation, this function allows an ofproto
1123 * implementation to destroy any rules that remain when its ->destruct()
1124 * function is called. This function is not suitable for use elsewhere in an
1125 * ofproto implementation.
1127 * This function is also used internally in ofproto.c.
1129 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1130 * Cycle" in ofproto-provider.h.
1132 * The 'cls' argument is redundant (it is &ofproto->tables[rule->table_id].cls)
1133 * but it allows Clang to do better checking. */
1135 ofproto_rule_delete(struct ofproto *ofproto, struct classifier *cls,
1137 OVS_REQ_WRLOCK(cls->rwlock)
1139 struct ofopgroup *group;
1141 ovs_assert(!rule->pending);
1142 ovs_assert(cls == &ofproto->tables[rule->table_id].cls);
1144 group = ofopgroup_create_unattached(ofproto);
1145 ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1146 ovs_rwlock_wrlock(&rule->rwlock);
1147 oftable_remove_rule__(ofproto, cls, rule);
1148 ofproto->ofproto_class->rule_delete(rule);
1149 ofopgroup_submit(group);
1153 ofproto_flush__(struct ofproto *ofproto)
1155 struct oftable *table;
1157 if (ofproto->ofproto_class->flush) {
1158 ofproto->ofproto_class->flush(ofproto);
1161 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1162 struct rule *rule, *next_rule;
1163 struct cls_cursor cursor;
1165 if (table->flags & OFTABLE_HIDDEN) {
1169 ovs_rwlock_wrlock(&table->cls.rwlock);
1170 cls_cursor_init(&cursor, &table->cls, NULL);
1171 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1172 if (!rule->pending) {
1173 ofproto_rule_delete(ofproto, &table->cls, rule);
1176 ovs_rwlock_unlock(&table->cls.rwlock);
1181 ofproto_destroy__(struct ofproto *ofproto)
1183 struct oftable *table;
1185 ovs_assert(list_is_empty(&ofproto->pending));
1186 ovs_assert(!ofproto->n_pending);
1188 destroy_rule_executes(ofproto);
1189 guarded_list_destroy(&ofproto->rule_executes);
1191 connmgr_destroy(ofproto->connmgr);
1193 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1194 free(ofproto->name);
1195 free(ofproto->type);
1196 free(ofproto->mfr_desc);
1197 free(ofproto->hw_desc);
1198 free(ofproto->sw_desc);
1199 free(ofproto->serial_desc);
1200 free(ofproto->dp_desc);
1201 hmap_destroy(&ofproto->ports);
1202 shash_destroy(&ofproto->port_by_name);
1203 bitmap_free(ofproto->ofp_port_ids);
1204 simap_destroy(&ofproto->ofp_requests);
1206 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1207 oftable_destroy(table);
1209 free(ofproto->tables);
1211 hmap_destroy(&ofproto->deletions);
1213 free(ofproto->vlan_bitmap);
1215 ovs_mutex_destroy(&ofproto->expirable_mutex);
1216 ofproto->ofproto_class->dealloc(ofproto);
1220 ofproto_destroy(struct ofproto *p)
1222 struct ofport *ofport, *next_ofport;
1229 meter_delete(p, 1, p->meter_features.max_meters);
1230 p->meter_features.max_meters = 0;
1236 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1237 ofport_destroy(ofport);
1240 p->ofproto_class->destruct(p);
1241 ofproto_destroy__(p);
1244 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1245 * kernel datapath, for example, this destroys the datapath in the kernel, and
1246 * with the netdev-based datapath, it tears down the data structures that
1247 * represent the datapath.
1249 * The datapath should not be currently open as an ofproto. */
1251 ofproto_delete(const char *name, const char *type)
1253 const struct ofproto_class *class = ofproto_class_find__(type);
1254 return (!class ? EAFNOSUPPORT
1255 : !class->del ? EACCES
1256 : class->del(type, name));
1260 process_port_change(struct ofproto *ofproto, int error, char *devname)
1262 if (error == ENOBUFS) {
1263 reinit_ports(ofproto);
1264 } else if (!error) {
1265 update_port(ofproto, devname);
1271 ofproto_type_run(const char *datapath_type)
1273 const struct ofproto_class *class;
1276 datapath_type = ofproto_normalize_type(datapath_type);
1277 class = ofproto_class_find__(datapath_type);
1279 error = class->type_run ? class->type_run(datapath_type) : 0;
1280 if (error && error != EAGAIN) {
1281 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1282 datapath_type, ovs_strerror(error));
1288 ofproto_type_run_fast(const char *datapath_type)
1290 const struct ofproto_class *class;
1293 datapath_type = ofproto_normalize_type(datapath_type);
1294 class = ofproto_class_find__(datapath_type);
1296 error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1297 if (error && error != EAGAIN) {
1298 VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1299 datapath_type, ovs_strerror(error));
1305 ofproto_type_wait(const char *datapath_type)
1307 const struct ofproto_class *class;
1309 datapath_type = ofproto_normalize_type(datapath_type);
1310 class = ofproto_class_find__(datapath_type);
1312 if (class->type_wait) {
1313 class->type_wait(datapath_type);
1318 ofproto_run(struct ofproto *p)
1320 struct sset changed_netdevs;
1321 const char *changed_netdev;
1322 struct ofport *ofport;
1325 error = p->ofproto_class->run(p);
1326 if (error && error != EAGAIN) {
1327 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1330 run_rule_executes(p);
1332 /* Restore the eviction group heap invariant occasionally. */
1333 if (p->eviction_group_timer < time_msec()) {
1336 p->eviction_group_timer = time_msec() + 1000;
1338 for (i = 0; i < p->n_tables; i++) {
1339 struct oftable *table = &p->tables[i];
1340 struct eviction_group *evg;
1341 struct cls_cursor cursor;
1344 if (!table->eviction_fields) {
1348 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1349 heap_rebuild(&evg->rules);
1352 ovs_rwlock_rdlock(&table->cls.rwlock);
1353 cls_cursor_init(&cursor, &table->cls, NULL);
1354 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1355 if (!rule->eviction_group
1356 && (rule->idle_timeout || rule->hard_timeout)) {
1357 eviction_group_add_rule(rule);
1360 ovs_rwlock_unlock(&table->cls.rwlock);
1364 if (p->ofproto_class->port_poll) {
1367 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1368 process_port_change(p, error, devname);
1372 /* Update OpenFlow port status for any port whose netdev has changed.
1374 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1375 * destroyed, so it's not safe to update ports directly from the
1376 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1377 * need this two-phase approach. */
1378 sset_init(&changed_netdevs);
1379 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1380 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1381 if (ofport->change_seq != change_seq) {
1382 ofport->change_seq = change_seq;
1383 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1386 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1387 update_port(p, changed_netdev);
1389 sset_destroy(&changed_netdevs);
1393 connmgr_run(p->connmgr, handle_openflow);
1397 connmgr_run(p->connmgr, NULL);
1399 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1400 p->state = S_OPENFLOW;
1405 connmgr_run(p->connmgr, NULL);
1407 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1408 connmgr_flushed(p->connmgr);
1409 p->state = S_OPENFLOW;
1417 if (time_msec() >= p->next_op_report) {
1418 long long int ago = (time_msec() - p->first_op) / 1000;
1419 long long int interval = (p->last_op - p->first_op) / 1000;
1423 ds_put_format(&s, "%d flow_mods ",
1424 p->n_add + p->n_delete + p->n_modify);
1425 if (interval == ago) {
1426 ds_put_format(&s, "in the last %lld s", ago);
1427 } else if (interval) {
1428 ds_put_format(&s, "in the %lld s starting %lld s ago",
1431 ds_put_format(&s, "%lld s ago", ago);
1434 ds_put_cstr(&s, " (");
1436 ds_put_format(&s, "%d adds, ", p->n_add);
1439 ds_put_format(&s, "%d deletes, ", p->n_delete);
1442 ds_put_format(&s, "%d modifications, ", p->n_modify);
1445 ds_put_char(&s, ')');
1447 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1450 p->n_add = p->n_delete = p->n_modify = 0;
1451 p->next_op_report = LLONG_MAX;
1457 /* Performs periodic activity required by 'ofproto' that needs to be done
1458 * with the least possible latency.
1460 * It makes sense to call this function a couple of times per poll loop, to
1461 * provide a significant performance boost on some benchmarks with the
1462 * ofproto-dpif implementation. */
1464 ofproto_run_fast(struct ofproto *p)
1468 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1469 if (error && error != EAGAIN) {
1470 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1471 p->name, ovs_strerror(error));
1477 ofproto_wait(struct ofproto *p)
1479 struct ofport *ofport;
1481 p->ofproto_class->wait(p);
1482 if (p->ofproto_class->port_poll_wait) {
1483 p->ofproto_class->port_poll_wait(p);
1486 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1487 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1488 poll_immediate_wake();
1494 connmgr_wait(p->connmgr, true);
1499 connmgr_wait(p->connmgr, false);
1500 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1501 poll_immediate_wake();
1508 ofproto_is_alive(const struct ofproto *p)
1510 return connmgr_has_controllers(p->connmgr);
1513 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1514 * memory_report(). */
1516 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1518 const struct oftable *table;
1519 unsigned int n_rules;
1521 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1522 simap_increase(usage, "ops",
1523 ofproto->n_pending + hmap_count(&ofproto->deletions));
1526 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1527 ovs_rwlock_rdlock(&table->cls.rwlock);
1528 n_rules += classifier_count(&table->cls);
1529 ovs_rwlock_unlock(&table->cls.rwlock);
1531 simap_increase(usage, "rules", n_rules);
1533 if (ofproto->ofproto_class->get_memory_usage) {
1534 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1537 connmgr_get_memory_usage(ofproto->connmgr, usage);
1541 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1544 connmgr_get_controller_info(ofproto->connmgr, info);
1548 ofproto_free_ofproto_controller_info(struct shash *info)
1550 connmgr_free_controller_info(info);
1553 /* Makes a deep copy of 'old' into 'port'. */
1555 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1557 port->name = xstrdup(old->name);
1558 port->type = xstrdup(old->type);
1559 port->ofp_port = old->ofp_port;
1562 /* Frees memory allocated to members of 'ofproto_port'.
1564 * Do not call this function on an ofproto_port obtained from
1565 * ofproto_port_dump_next(): that function retains ownership of the data in the
1568 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1570 free(ofproto_port->name);
1571 free(ofproto_port->type);
1574 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1576 * This function provides no status indication. An error status for the entire
1577 * dump operation is provided when it is completed by calling
1578 * ofproto_port_dump_done().
1581 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1582 const struct ofproto *ofproto)
1584 dump->ofproto = ofproto;
1585 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1589 /* Attempts to retrieve another port from 'dump', which must have been created
1590 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1591 * 'port' and returns true. On failure, returns false.
1593 * Failure might indicate an actual error or merely that the last port has been
1594 * dumped. An error status for the entire dump operation is provided when it
1595 * is completed by calling ofproto_port_dump_done().
1597 * The ofproto owns the data stored in 'port'. It will remain valid until at
1598 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1599 * ofproto_port_dump_done(). */
1601 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1602 struct ofproto_port *port)
1604 const struct ofproto *ofproto = dump->ofproto;
1610 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1613 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1619 /* Completes port table dump operation 'dump', which must have been created
1620 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1621 * error-free, otherwise a positive errno value describing the problem. */
1623 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1625 const struct ofproto *ofproto = dump->ofproto;
1627 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1630 return dump->error == EOF ? 0 : dump->error;
1633 /* Returns the type to pass to netdev_open() when a datapath of type
1634 * 'datapath_type' has a port of type 'port_type', for a few special
1635 * cases when a netdev type differs from a port type. For example, when
1636 * using the userspace datapath, a port of type "internal" needs to be
1639 * Returns either 'type' itself or a string literal, which must not be
1642 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1644 const struct ofproto_class *class;
1646 datapath_type = ofproto_normalize_type(datapath_type);
1647 class = ofproto_class_find__(datapath_type);
1652 return (class->port_open_type
1653 ? class->port_open_type(datapath_type, port_type)
1657 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1658 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1659 * the port's OpenFlow port number.
1661 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1662 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1663 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1664 * 'ofp_portp' is non-null). */
1666 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1667 ofp_port_t *ofp_portp)
1669 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1672 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1674 const char *netdev_name = netdev_get_name(netdev);
1676 simap_put(&ofproto->ofp_requests, netdev_name,
1677 ofp_to_u16(ofp_port));
1678 update_port(ofproto, netdev_name);
1681 struct ofproto_port ofproto_port;
1683 ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1685 *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1686 ofproto_port_destroy(&ofproto_port);
1691 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1692 * initializes '*port' appropriately; on failure, returns a positive errno
1695 * The caller owns the data in 'ofproto_port' and must free it with
1696 * ofproto_port_destroy() when it is no longer needed. */
1698 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1699 struct ofproto_port *port)
1703 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1705 memset(port, 0, sizeof *port);
1710 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1711 * Returns 0 if successful, otherwise a positive errno. */
1713 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1715 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1716 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1717 struct simap_node *ofp_request_node;
1720 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1721 if (ofp_request_node) {
1722 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1725 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1726 if (!error && ofport) {
1727 /* 'name' is the netdev's name and update_port() is going to close the
1728 * netdev. Just in case update_port() refers to 'name' after it
1729 * destroys 'ofport', make a copy of it around the update_port()
1731 char *devname = xstrdup(name);
1732 update_port(ofproto, devname);
1739 simple_flow_mod(struct ofproto *ofproto,
1740 const struct match *match, unsigned int priority,
1741 const struct ofpact *ofpacts, size_t ofpacts_len,
1742 enum ofp_flow_mod_command command)
1744 struct ofputil_flow_mod fm;
1746 memset(&fm, 0, sizeof fm);
1748 fm.priority = priority;
1751 fm.modify_cookie = false;
1753 fm.command = command;
1754 fm.idle_timeout = 0;
1755 fm.hard_timeout = 0;
1756 fm.buffer_id = UINT32_MAX;
1757 fm.out_port = OFPP_ANY;
1759 fm.ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1760 fm.ofpacts_len = ofpacts_len;
1761 return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1764 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1765 * performs the 'n_actions' actions in 'actions'. The new flow will not
1768 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1769 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1770 * controllers; otherwise, it will be hidden.
1772 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1774 * This is a helper function for in-band control and fail-open. */
1776 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1777 unsigned int priority,
1778 const struct ofpact *ofpacts, size_t ofpacts_len)
1780 const struct rule *rule;
1783 /* First do a cheap check whether the rule we're looking for already exists
1784 * with the actions that we want. If it does, then we're done. */
1785 ovs_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1786 rule = rule_from_cls_rule(classifier_find_match_exactly(
1787 &ofproto->tables[0].cls, match, priority));
1789 ovs_rwlock_rdlock(&rule->rwlock);
1790 must_add = !ofpacts_equal(rule->actions->ofpacts,
1791 rule->actions->ofpacts_len,
1792 ofpacts, ofpacts_len);
1793 ovs_rwlock_unlock(&rule->rwlock);
1797 ovs_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1799 /* If there's no such rule or the rule doesn't have the actions we want,
1800 * fall back to a executing a full flow mod. We can't optimize this at
1801 * all because we didn't take enough locks above to ensure that the flow
1802 * table didn't already change beneath us. */
1804 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1805 OFPFC_MODIFY_STRICT);
1809 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1810 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1811 * operation cannot be initiated now but may be retried later.
1813 * This is a helper function for in-band control and fail-open. */
1815 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1817 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1820 /* Searches for a rule with matching criteria exactly equal to 'target' in
1821 * ofproto's table 0 and, if it finds one, deletes it.
1823 * This is a helper function for in-band control and fail-open. */
1825 ofproto_delete_flow(struct ofproto *ofproto,
1826 const struct match *target, unsigned int priority)
1828 struct classifier *cls = &ofproto->tables[0].cls;
1831 /* First do a cheap check whether the rule we're looking for has already
1832 * been deleted. If so, then we're done. */
1833 ovs_rwlock_rdlock(&cls->rwlock);
1834 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1836 ovs_rwlock_unlock(&cls->rwlock);
1841 /* Fall back to a executing a full flow mod. We can't optimize this at all
1842 * because we didn't take enough locks above to ensure that the flow table
1843 * didn't already change beneath us. */
1844 return simple_flow_mod(ofproto, target, priority, NULL, 0,
1845 OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
1848 /* Starts the process of deleting all of the flows from all of ofproto's flow
1849 * tables and then reintroducing the flows required by in-band control and
1850 * fail-open. The process will complete in a later call to ofproto_run(). */
1852 ofproto_flush_flows(struct ofproto *ofproto)
1854 COVERAGE_INC(ofproto_flush);
1855 ofproto->state = S_FLUSH;
1859 reinit_ports(struct ofproto *p)
1861 struct ofproto_port_dump dump;
1862 struct sset devnames;
1863 struct ofport *ofport;
1864 struct ofproto_port ofproto_port;
1865 const char *devname;
1867 COVERAGE_INC(ofproto_reinit_ports);
1869 sset_init(&devnames);
1870 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1871 sset_add(&devnames, netdev_get_name(ofport->netdev));
1873 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1874 sset_add(&devnames, ofproto_port.name);
1877 SSET_FOR_EACH (devname, &devnames) {
1878 update_port(p, devname);
1880 sset_destroy(&devnames);
1884 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1888 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1889 port_idx = port_idx ? port_idx : UINT16_MAX;
1891 if (port_idx >= ofproto->max_ports
1892 || bitmap_is_set(ofproto->ofp_port_ids, port_idx)) {
1893 uint16_t end_port_no = ofproto->alloc_port_no;
1895 /* Search for a free OpenFlow port number. We try not to
1896 * immediately reuse them to prevent problems due to old
1899 if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1900 ofproto->alloc_port_no = 0;
1902 if (!bitmap_is_set(ofproto->ofp_port_ids,
1903 ofproto->alloc_port_no)) {
1904 port_idx = ofproto->alloc_port_no;
1907 if (ofproto->alloc_port_no == end_port_no) {
1912 bitmap_set1(ofproto->ofp_port_ids, port_idx);
1913 return u16_to_ofp(port_idx);
1917 dealloc_ofp_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
1919 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
1920 bitmap_set0(ofproto->ofp_port_ids, ofp_to_u16(ofp_port));
1924 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1925 * pointer if the netdev cannot be opened. On success, also fills in
1927 static struct netdev *
1928 ofport_open(struct ofproto *ofproto,
1929 struct ofproto_port *ofproto_port,
1930 struct ofputil_phy_port *pp)
1932 enum netdev_flags flags;
1933 struct netdev *netdev;
1936 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1938 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1939 "cannot be opened (%s)",
1941 ofproto_port->name, ofproto_port->ofp_port,
1942 ofproto_port->name, ovs_strerror(error));
1946 if (ofproto_port->ofp_port == OFPP_NONE) {
1947 if (!strcmp(ofproto->name, ofproto_port->name)) {
1948 ofproto_port->ofp_port = OFPP_LOCAL;
1950 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
1951 ofproto_port->name);
1954 pp->port_no = ofproto_port->ofp_port;
1955 netdev_get_etheraddr(netdev, pp->hw_addr);
1956 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1957 netdev_get_flags(netdev, &flags);
1958 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1959 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1960 netdev_get_features(netdev, &pp->curr, &pp->advertised,
1961 &pp->supported, &pp->peer);
1962 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
1963 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
1968 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
1969 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1972 ofport_equal(const struct ofputil_phy_port *a,
1973 const struct ofputil_phy_port *b)
1975 return (eth_addr_equals(a->hw_addr, b->hw_addr)
1976 && a->state == b->state
1977 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1978 && a->curr == b->curr
1979 && a->advertised == b->advertised
1980 && a->supported == b->supported
1981 && a->peer == b->peer
1982 && a->curr_speed == b->curr_speed
1983 && a->max_speed == b->max_speed);
1986 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1987 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1988 * one with the same name or port number). */
1990 ofport_install(struct ofproto *p,
1991 struct netdev *netdev, const struct ofputil_phy_port *pp)
1993 const char *netdev_name = netdev_get_name(netdev);
1994 struct ofport *ofport;
1997 /* Create ofport. */
1998 ofport = p->ofproto_class->port_alloc();
2003 ofport->ofproto = p;
2004 ofport->netdev = netdev;
2005 ofport->change_seq = netdev_change_seq(netdev);
2007 ofport->ofp_port = pp->port_no;
2008 ofport->created = time_msec();
2010 /* Add port to 'p'. */
2011 hmap_insert(&p->ports, &ofport->hmap_node,
2012 hash_ofp_port(ofport->ofp_port));
2013 shash_add(&p->port_by_name, netdev_name, ofport);
2015 update_mtu(p, ofport);
2017 /* Let the ofproto_class initialize its private data. */
2018 error = p->ofproto_class->port_construct(ofport);
2022 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
2026 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2027 p->name, netdev_name, ovs_strerror(error));
2029 ofport_destroy__(ofport);
2031 netdev_close(netdev);
2035 /* Removes 'ofport' from 'p' and destroys it. */
2037 ofport_remove(struct ofport *ofport)
2039 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
2041 ofport_destroy(ofport);
2044 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2047 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2049 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2051 ofport_remove(port);
2055 /* Updates 'port' with new 'pp' description.
2057 * Does not handle a name or port number change. The caller must implement
2058 * such a change as a delete followed by an add. */
2060 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2062 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2063 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2064 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2065 port->pp.state = pp->state;
2066 port->pp.curr = pp->curr;
2067 port->pp.advertised = pp->advertised;
2068 port->pp.supported = pp->supported;
2069 port->pp.peer = pp->peer;
2070 port->pp.curr_speed = pp->curr_speed;
2071 port->pp.max_speed = pp->max_speed;
2073 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
2076 /* Update OpenFlow 'state' in 'port' and notify controller. */
2078 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2080 if (port->pp.state != state) {
2081 port->pp.state = state;
2082 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
2088 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2090 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2092 if (port->ofproto->ofproto_class->set_realdev) {
2093 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2095 if (port->ofproto->ofproto_class->set_stp_port) {
2096 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2098 if (port->ofproto->ofproto_class->set_cfm) {
2099 port->ofproto->ofproto_class->set_cfm(port, NULL);
2101 if (port->ofproto->ofproto_class->bundle_remove) {
2102 port->ofproto->ofproto_class->bundle_remove(port);
2108 ofport_destroy__(struct ofport *port)
2110 struct ofproto *ofproto = port->ofproto;
2111 const char *name = netdev_get_name(port->netdev);
2113 hmap_remove(&ofproto->ports, &port->hmap_node);
2114 shash_delete(&ofproto->port_by_name,
2115 shash_find(&ofproto->port_by_name, name));
2117 netdev_close(port->netdev);
2118 ofproto->ofproto_class->port_dealloc(port);
2122 ofport_destroy(struct ofport *port)
2125 dealloc_ofp_port(port->ofproto, port->ofp_port);
2126 port->ofproto->ofproto_class->port_destruct(port);
2127 ofport_destroy__(port);
2132 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2134 struct ofport *port;
2136 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2138 if (port->ofp_port == ofp_port) {
2146 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2148 struct ofproto *ofproto = port->ofproto;
2151 if (ofproto->ofproto_class->port_get_stats) {
2152 error = ofproto->ofproto_class->port_get_stats(port, stats);
2161 update_port(struct ofproto *ofproto, const char *name)
2163 struct ofproto_port ofproto_port;
2164 struct ofputil_phy_port pp;
2165 struct netdev *netdev;
2166 struct ofport *port;
2168 COVERAGE_INC(ofproto_update_port);
2170 /* Fetch 'name''s location and properties from the datapath. */
2171 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2172 ? ofport_open(ofproto, &ofproto_port, &pp)
2176 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2177 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2178 struct netdev *old_netdev = port->netdev;
2180 /* 'name' hasn't changed location. Any properties changed? */
2181 if (!ofport_equal(&port->pp, &pp)) {
2182 ofport_modified(port, &pp);
2185 update_mtu(ofproto, port);
2187 /* Install the newly opened netdev in case it has changed.
2188 * Don't close the old netdev yet in case port_modified has to
2189 * remove a retained reference to it.*/
2190 port->netdev = netdev;
2191 port->change_seq = netdev_change_seq(netdev);
2193 if (port->ofproto->ofproto_class->port_modified) {
2194 port->ofproto->ofproto_class->port_modified(port);
2197 netdev_close(old_netdev);
2199 /* If 'port' is nonnull then its name differs from 'name' and thus
2200 * we should delete it. If we think there's a port named 'name'
2201 * then its port number must be wrong now so delete it too. */
2203 ofport_remove(port);
2205 ofport_remove_with_name(ofproto, name);
2206 ofport_install(ofproto, netdev, &pp);
2209 /* Any port named 'name' is gone now. */
2210 ofport_remove_with_name(ofproto, name);
2212 ofproto_port_destroy(&ofproto_port);
2216 init_ports(struct ofproto *p)
2218 struct ofproto_port_dump dump;
2219 struct ofproto_port ofproto_port;
2220 struct shash_node *node, *next;
2222 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2223 const char *name = ofproto_port.name;
2225 if (shash_find(&p->port_by_name, name)) {
2226 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2229 struct ofputil_phy_port pp;
2230 struct netdev *netdev;
2232 /* Check if an OpenFlow port number had been requested. */
2233 node = shash_find(&init_ofp_ports, name);
2235 const struct iface_hint *iface_hint = node->data;
2236 simap_put(&p->ofp_requests, name,
2237 ofp_to_u16(iface_hint->ofp_port));
2240 netdev = ofport_open(p, &ofproto_port, &pp);
2242 ofport_install(p, netdev, &pp);
2243 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2244 p->alloc_port_no = MAX(p->alloc_port_no,
2245 ofp_to_u16(ofproto_port.ofp_port));
2251 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2252 struct iface_hint *iface_hint = node->data;
2254 if (!strcmp(iface_hint->br_name, p->name)) {
2255 free(iface_hint->br_name);
2256 free(iface_hint->br_type);
2258 shash_delete(&init_ofp_ports, node);
2265 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2266 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2268 find_min_mtu(struct ofproto *p)
2270 struct ofport *ofport;
2273 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2274 struct netdev *netdev = ofport->netdev;
2277 /* Skip any internal ports, since that's what we're trying to
2279 if (!strcmp(netdev_get_type(netdev), "internal")) {
2283 if (netdev_get_mtu(netdev, &dev_mtu)) {
2286 if (!mtu || dev_mtu < mtu) {
2291 return mtu ? mtu: ETH_PAYLOAD_MAX;
2294 /* Update MTU of all datapath devices on 'p' to the minimum of the
2295 * non-datapath ports in event of 'port' added or changed. */
2297 update_mtu(struct ofproto *p, struct ofport *port)
2299 struct ofport *ofport;
2300 struct netdev *netdev = port->netdev;
2301 int dev_mtu, old_min;
2303 if (netdev_get_mtu(netdev, &dev_mtu)) {
2307 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2308 if (dev_mtu > p->min_mtu) {
2309 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2310 dev_mtu = p->min_mtu;
2313 port->mtu = dev_mtu;
2317 /* For non-internal port find new min mtu. */
2318 old_min = p->min_mtu;
2319 port->mtu = dev_mtu;
2320 p->min_mtu = find_min_mtu(p);
2321 if (p->min_mtu == old_min) {
2325 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2326 struct netdev *netdev = ofport->netdev;
2328 if (!strcmp(netdev_get_type(netdev), "internal")) {
2329 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2330 ofport->mtu = p->min_mtu;
2337 ofproto_rule_ref(struct rule *rule)
2342 atomic_add(&rule->ref_count, 1, &orig);
2343 ovs_assert(orig != 0);
2348 ofproto_rule_unref(struct rule *rule)
2353 atomic_sub(&rule->ref_count, 1, &orig);
2355 rule->ofproto->ofproto_class->rule_destruct(rule);
2356 ofproto_rule_destroy__(rule);
2358 ovs_assert(orig != 0);
2364 ofproto_rule_destroy__(struct rule *rule)
2366 cls_rule_destroy(&rule->cr);
2367 rule_actions_unref(rule->actions);
2368 ovs_mutex_destroy(&rule->timeout_mutex);
2369 ovs_rwlock_destroy(&rule->rwlock);
2370 rule->ofproto->ofproto_class->rule_dealloc(rule);
2373 /* Creates and returns a new 'struct rule_actions', with a ref_count of 1,
2374 * whose actions are a copy of from the 'ofpacts_len' bytes of 'ofpacts'. */
2375 struct rule_actions *
2376 rule_actions_create(const struct ofpact *ofpacts, size_t ofpacts_len)
2378 struct rule_actions *actions;
2380 actions = xmalloc(sizeof *actions);
2381 atomic_init(&actions->ref_count, 1);
2382 actions->ofpacts = xmemdup(ofpacts, ofpacts_len);
2383 actions->ofpacts_len = ofpacts_len;
2384 actions->meter_id = ofpacts_get_meter(ofpacts, ofpacts_len);
2388 /* Increments 'actions''s ref_count. */
2390 rule_actions_ref(struct rule_actions *actions)
2395 atomic_add(&actions->ref_count, 1, &orig);
2396 ovs_assert(orig != 0);
2400 /* Decrements 'actions''s ref_count and frees 'actions' if the ref_count
2403 rule_actions_unref(struct rule_actions *actions)
2408 atomic_sub(&actions->ref_count, 1, &orig);
2412 ovs_assert(orig != 0);
2417 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2418 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2420 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2422 return (port == OFPP_ANY
2423 || ofpacts_output_to_port(rule->actions->ofpacts,
2424 rule->actions->ofpacts_len, port));
2427 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2428 * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2430 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2432 if (ofproto_rule_has_out_port(op->rule, out_port)) {
2437 case OFOPERATION_ADD:
2438 case OFOPERATION_DELETE:
2441 case OFOPERATION_MODIFY:
2442 case OFOPERATION_REPLACE:
2443 return ofpacts_output_to_port(op->actions->ofpacts,
2444 op->actions->ofpacts_len, out_port);
2451 rule_execute_destroy(struct rule_execute *e)
2453 ofproto_rule_unref(e->rule);
2454 list_remove(&e->list_node);
2458 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2459 * by passing them to the ofproto provider. */
2461 run_rule_executes(struct ofproto *ofproto)
2463 struct rule_execute *e, *next;
2464 struct list executes;
2466 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2467 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2468 union flow_in_port in_port_;
2471 in_port_.ofp_port = e->in_port;
2472 flow_extract(e->packet, 0, 0, NULL, &in_port_, &flow);
2473 ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2475 rule_execute_destroy(e);
2479 /* Destroys and discards all "rule_execute" operations queued up in
2480 * ofproto->rule_executes. */
2482 destroy_rule_executes(struct ofproto *ofproto)
2484 struct rule_execute *e, *next;
2485 struct list executes;
2487 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2488 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2489 ofpbuf_delete(e->packet);
2490 rule_execute_destroy(e);
2494 /* Returns true if 'rule' should be hidden from the controller.
2496 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2497 * (e.g. by in-band control) and are intentionally hidden from the
2500 ofproto_rule_is_hidden(const struct rule *rule)
2502 return rule->cr.priority > UINT16_MAX;
2505 static enum oftable_flags
2506 rule_get_flags(const struct rule *rule)
2508 return rule->ofproto->tables[rule->table_id].flags;
2512 rule_is_modifiable(const struct rule *rule)
2514 return !(rule_get_flags(rule) & OFTABLE_READONLY);
2518 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2520 ofconn_send_reply(ofconn, make_echo_reply(oh));
2525 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2527 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2528 struct ofputil_switch_features features;
2529 struct ofport *port;
2535 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2537 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2539 /* Count only non-hidden tables in the number of tables. (Hidden tables,
2540 * if present, are always at the end.) */
2541 n_tables = ofproto->n_tables;
2542 for (i = 0; i < ofproto->n_tables; i++) {
2543 if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2549 features.datapath_id = ofproto->datapath_id;
2550 features.n_buffers = pktbuf_capacity();
2551 features.n_tables = n_tables;
2552 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2553 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2555 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2557 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2558 features.auxiliary_id = 0;
2559 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2561 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2562 ofputil_put_switch_features_port(&port->pp, b);
2565 ofconn_send_reply(ofconn, b);
2570 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2572 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2573 struct ofp_switch_config *osc;
2574 enum ofp_config_flags flags;
2578 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2579 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2580 flags = ofproto->frag_handling;
2581 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2582 if (oh->version < OFP13_VERSION
2583 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2584 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2586 osc->flags = htons(flags);
2587 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2588 ofconn_send_reply(ofconn, buf);
2594 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2596 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2597 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2598 uint16_t flags = ntohs(osc->flags);
2600 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2601 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2602 enum ofp_config_flags cur = ofproto->frag_handling;
2603 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2605 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2607 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2608 ofproto->frag_handling = next;
2610 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2612 ofputil_frag_handling_to_string(next));
2616 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2617 ofconn_set_invalid_ttl_to_controller(ofconn,
2618 (oh->version < OFP13_VERSION
2619 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2621 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2626 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2627 * error message code for the caller to propagate upward. Otherwise, returns
2630 * The log message mentions 'msg_type'. */
2632 reject_slave_controller(struct ofconn *ofconn)
2634 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2635 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2636 return OFPERR_OFPBRC_EPERM;
2642 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are appropriate
2643 * for a packet with the prerequisites satisfied by 'flow' in table 'table_id'.
2644 * 'flow' may be temporarily modified, but is restored at return.
2647 ofproto_check_ofpacts(struct ofproto *ofproto,
2648 const struct ofpact ofpacts[], size_t ofpacts_len,
2649 struct flow *flow, uint8_t table_id)
2654 error = ofpacts_check(ofpacts, ofpacts_len, flow,
2655 u16_to_ofp(ofproto->max_ports), table_id);
2660 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2661 if (mid && ofproto_get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2662 return OFPERR_OFPMMFC_INVALID_METER;
2668 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2670 struct ofproto *p = ofconn_get_ofproto(ofconn);
2671 struct ofputil_packet_out po;
2672 struct ofpbuf *payload;
2673 uint64_t ofpacts_stub[1024 / 8];
2674 struct ofpbuf ofpacts;
2676 union flow_in_port in_port_;
2679 COVERAGE_INC(ofproto_packet_out);
2681 error = reject_slave_controller(ofconn);
2686 /* Decode message. */
2687 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2688 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2690 goto exit_free_ofpacts;
2692 if (ofp_to_u16(po.in_port) >= p->max_ports
2693 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2694 error = OFPERR_OFPBRC_BAD_PORT;
2695 goto exit_free_ofpacts;
2700 if (po.buffer_id != UINT32_MAX) {
2701 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2702 if (error || !payload) {
2703 goto exit_free_ofpacts;
2706 /* Ensure that the L3 header is 32-bit aligned. */
2707 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2710 /* Verify actions against packet, then send packet if successful. */
2711 in_port_.ofp_port = po.in_port;
2712 flow_extract(payload, 0, 0, NULL, &in_port_, &flow);
2713 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len, &flow, 0);
2715 error = p->ofproto_class->packet_out(p, payload, &flow,
2716 po.ofpacts, po.ofpacts_len);
2718 ofpbuf_delete(payload);
2721 ofpbuf_uninit(&ofpacts);
2727 update_port_config(struct ofport *port,
2728 enum ofputil_port_config config,
2729 enum ofputil_port_config mask)
2731 enum ofputil_port_config old_config = port->pp.config;
2732 enum ofputil_port_config toggle;
2734 toggle = (config ^ port->pp.config) & mask;
2735 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2736 if (config & OFPUTIL_PC_PORT_DOWN) {
2737 netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2739 netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2741 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2744 port->pp.config ^= toggle;
2745 if (port->pp.config != old_config) {
2746 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2751 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2753 struct ofproto *p = ofconn_get_ofproto(ofconn);
2754 struct ofputil_port_mod pm;
2755 struct ofport *port;
2758 error = reject_slave_controller(ofconn);
2763 error = ofputil_decode_port_mod(oh, &pm);
2768 port = ofproto_get_port(p, pm.port_no);
2770 return OFPERR_OFPPMFC_BAD_PORT;
2771 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2772 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2774 update_port_config(port, pm.config, pm.mask);
2776 netdev_set_advertisements(port->netdev, pm.advertise);
2783 handle_desc_stats_request(struct ofconn *ofconn,
2784 const struct ofp_header *request)
2786 static const char *default_mfr_desc = "Nicira, Inc.";
2787 static const char *default_hw_desc = "Open vSwitch";
2788 static const char *default_sw_desc = VERSION;
2789 static const char *default_serial_desc = "None";
2790 static const char *default_dp_desc = "None";
2792 struct ofproto *p = ofconn_get_ofproto(ofconn);
2793 struct ofp_desc_stats *ods;
2796 msg = ofpraw_alloc_stats_reply(request, 0);
2797 ods = ofpbuf_put_zeros(msg, sizeof *ods);
2798 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
2799 sizeof ods->mfr_desc);
2800 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
2801 sizeof ods->hw_desc);
2802 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
2803 sizeof ods->sw_desc);
2804 ovs_strlcpy(ods->serial_num,
2805 p->serial_desc ? p->serial_desc : default_serial_desc,
2806 sizeof ods->serial_num);
2807 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
2808 sizeof ods->dp_desc);
2809 ofconn_send_reply(ofconn, msg);
2815 handle_table_stats_request(struct ofconn *ofconn,
2816 const struct ofp_header *request)
2818 struct ofproto *p = ofconn_get_ofproto(ofconn);
2819 struct ofp12_table_stats *ots;
2824 /* Set up default values.
2826 * ofp12_table_stats is used as a generic structure as
2827 * it is able to hold all the fields for ofp10_table_stats
2828 * and ofp11_table_stats (and of course itself).
2830 ots = xcalloc(p->n_tables, sizeof *ots);
2831 for (i = 0; i < p->n_tables; i++) {
2832 ots[i].table_id = i;
2833 sprintf(ots[i].name, "table%zu", i);
2834 ots[i].match = htonll(OFPXMT12_MASK);
2835 ots[i].wildcards = htonll(OFPXMT12_MASK);
2836 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
2837 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
2838 ots[i].write_setfields = htonll(OFPXMT12_MASK);
2839 ots[i].apply_setfields = htonll(OFPXMT12_MASK);
2840 ots[i].metadata_match = htonll(UINT64_MAX);
2841 ots[i].metadata_write = htonll(UINT64_MAX);
2842 ots[i].instructions = htonl(OFPIT11_ALL);
2843 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
2844 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2845 ovs_rwlock_rdlock(&p->tables[i].cls.rwlock);
2846 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2847 ovs_rwlock_unlock(&p->tables[i].cls.rwlock);
2850 p->ofproto_class->get_tables(p, ots);
2852 /* Post-process the tables, dropping hidden tables. */
2853 n_tables = p->n_tables;
2854 for (i = 0; i < p->n_tables; i++) {
2855 const struct oftable *table = &p->tables[i];
2857 if (table->flags & OFTABLE_HIDDEN) {
2863 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2866 if (table->max_flows < ntohl(ots[i].max_entries)) {
2867 ots[i].max_entries = htonl(table->max_flows);
2871 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
2872 ofconn_send_reply(ofconn, msg);
2880 append_port_stat(struct ofport *port, struct list *replies)
2882 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
2884 calc_duration(port->created, time_msec(),
2885 &ops.duration_sec, &ops.duration_nsec);
2887 /* Intentionally ignore return value, since errors will set
2888 * 'stats' to all-1s, which is correct for OpenFlow, and
2889 * netdev_get_stats() will log errors. */
2890 ofproto_port_get_stats(port, &ops.stats);
2892 ofputil_append_port_stat(replies, &ops);
2896 handle_port_stats_request(struct ofconn *ofconn,
2897 const struct ofp_header *request)
2899 struct ofproto *p = ofconn_get_ofproto(ofconn);
2900 struct ofport *port;
2901 struct list replies;
2905 error = ofputil_decode_port_stats_request(request, &port_no);
2910 ofpmp_init(&replies, request);
2911 if (port_no != OFPP_ANY) {
2912 port = ofproto_get_port(p, port_no);
2914 append_port_stat(port, &replies);
2917 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2918 append_port_stat(port, &replies);
2922 ofconn_send_replies(ofconn, &replies);
2927 handle_port_desc_stats_request(struct ofconn *ofconn,
2928 const struct ofp_header *request)
2930 struct ofproto *p = ofconn_get_ofproto(ofconn);
2931 enum ofp_version version;
2932 struct ofport *port;
2933 struct list replies;
2935 ofpmp_init(&replies, request);
2937 version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
2938 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2939 ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
2942 ofconn_send_replies(ofconn, &replies);
2947 hash_cookie(ovs_be64 cookie)
2949 return hash_2words((OVS_FORCE uint64_t)cookie >> 32,
2950 (OVS_FORCE uint64_t)cookie);
2954 cookies_insert(struct ofproto *ofproto, struct rule *rule)
2956 hindex_insert(&ofproto->cookies, &rule->cookie_node,
2957 hash_cookie(rule->flow_cookie));
2961 cookies_remove(struct ofproto *ofproto, struct rule *rule)
2963 hindex_remove(&ofproto->cookies, &rule->cookie_node);
2967 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
2968 ovs_be64 new_cookie)
2970 if (new_cookie != rule->flow_cookie) {
2971 cookies_remove(ofproto, rule);
2973 ovs_rwlock_wrlock(&rule->rwlock);
2974 rule->flow_cookie = new_cookie;
2975 ovs_rwlock_unlock(&rule->rwlock);
2977 cookies_insert(ofproto, rule);
2982 calc_duration(long long int start, long long int now,
2983 uint32_t *sec, uint32_t *nsec)
2985 long long int msecs = now - start;
2986 *sec = msecs / 1000;
2987 *nsec = (msecs % 1000) * (1000 * 1000);
2990 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
2991 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
2993 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2995 return (table_id == 0xff || table_id < ofproto->n_tables
2997 : OFPERR_OFPBRC_BAD_TABLE_ID);
3001 static struct oftable *
3002 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3004 struct oftable *table;
3006 for (table = &ofproto->tables[table_id];
3007 table < &ofproto->tables[ofproto->n_tables];
3009 if (!(table->flags & OFTABLE_HIDDEN)) {
3017 static struct oftable *
3018 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3020 if (table_id == 0xff) {
3021 return next_visible_table(ofproto, 0);
3022 } else if (table_id < ofproto->n_tables) {
3023 return &ofproto->tables[table_id];
3029 static struct oftable *
3030 next_matching_table(const struct ofproto *ofproto,
3031 const struct oftable *table, uint8_t table_id)
3033 return (table_id == 0xff
3034 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3038 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3040 * - If TABLE_ID is 0xff, this iterates over every classifier table in
3041 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3043 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3044 * only once, for that table. (This can be used to access tables marked
3047 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3048 * entered at all. (Perhaps you should have validated TABLE_ID with
3049 * check_table_id().)
3051 * All parameters are evaluated multiple times.
3053 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
3054 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
3056 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3058 /* Initializes 'criteria' in a straightforward way based on the other
3061 * For "loose" matching, the 'priority' parameter is unimportant and may be
3064 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3065 const struct match *match, unsigned int priority,
3066 ovs_be64 cookie, ovs_be64 cookie_mask,
3067 ofp_port_t out_port)
3069 criteria->table_id = table_id;
3070 cls_rule_init(&criteria->cr, match, priority);
3071 criteria->cookie = cookie;
3072 criteria->cookie_mask = cookie_mask;
3073 criteria->out_port = out_port;
3077 rule_criteria_destroy(struct rule_criteria *criteria)
3079 cls_rule_destroy(&criteria->cr);
3083 rule_collection_init(struct rule_collection *rules)
3085 rules->rules = rules->stub;
3087 rules->capacity = ARRAY_SIZE(rules->stub);
3091 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3093 if (rules->n >= rules->capacity) {
3094 size_t old_size, new_size;
3096 old_size = rules->capacity * sizeof *rules->rules;
3097 rules->capacity *= 2;
3098 new_size = rules->capacity * sizeof *rules->rules;
3100 if (rules->rules == rules->stub) {
3101 rules->rules = xmalloc(new_size);
3102 memcpy(rules->rules, rules->stub, old_size);
3104 rules->rules = xrealloc(rules->rules, new_size);
3108 rules->rules[rules->n++] = rule;
3112 rule_collection_destroy(struct rule_collection *rules)
3114 if (rules->rules != rules->stub) {
3120 collect_rule(struct rule *rule, const struct rule_criteria *c,
3121 struct rule_collection *rules)
3123 if (ofproto_rule_is_hidden(rule)) {
3125 } else if (rule->pending) {
3126 return OFPROTO_POSTPONE;
3128 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3129 && ofproto_rule_has_out_port(rule, c->out_port)
3130 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3131 rule_collection_add(rules, rule);
3137 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3138 * on classifiers rules are done in the "loose" way required for OpenFlow
3139 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3142 * Hidden rules are always omitted.
3144 * Returns 0 on success, otherwise an OpenFlow error code. */
3146 collect_rules_loose(struct ofproto *ofproto,
3147 const struct rule_criteria *criteria,
3148 struct rule_collection *rules)
3150 struct oftable *table;
3153 rule_collection_init(rules);
3155 error = check_table_id(ofproto, criteria->table_id);
3160 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3163 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3164 hash_cookie(criteria->cookie),
3165 &ofproto->cookies) {
3166 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3167 error = collect_rule(rule, criteria, rules);
3174 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3175 struct cls_cursor cursor;
3178 ovs_rwlock_rdlock(&table->cls.rwlock);
3179 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3180 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3181 error = collect_rule(rule, criteria, rules);
3186 ovs_rwlock_unlock(&table->cls.rwlock);
3192 rule_collection_destroy(rules);
3197 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3198 * on classifiers rules are done in the "strict" way required for OpenFlow
3199 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3200 * rules on list 'rules'.
3202 * Hidden rules are always omitted.
3204 * Returns 0 on success, otherwise an OpenFlow error code. */
3206 collect_rules_strict(struct ofproto *ofproto,
3207 const struct rule_criteria *criteria,
3208 struct rule_collection *rules)
3210 struct oftable *table;
3213 rule_collection_init(rules);
3215 error = check_table_id(ofproto, criteria->table_id);
3220 if (criteria->cookie_mask == htonll(UINT64_MAX)) {
3223 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3224 hash_cookie(criteria->cookie),
3225 &ofproto->cookies) {
3226 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3227 error = collect_rule(rule, criteria, rules);
3234 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3237 ovs_rwlock_rdlock(&table->cls.rwlock);
3238 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3239 &table->cls, &criteria->cr));
3240 ovs_rwlock_unlock(&table->cls.rwlock);
3242 error = collect_rule(rule, criteria, rules);
3252 rule_collection_destroy(rules);
3257 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3258 * forced into the range of a uint16_t. */
3260 age_secs(long long int age_ms)
3262 return (age_ms < 0 ? 0
3263 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3264 : (unsigned int) age_ms / 1000);
3268 handle_flow_stats_request(struct ofconn *ofconn,
3269 const struct ofp_header *request)
3271 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3272 struct ofputil_flow_stats_request fsr;
3273 struct rule_criteria criteria;
3274 struct rule_collection rules;
3275 struct list replies;
3279 error = ofputil_decode_flow_stats_request(&fsr, request);
3284 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3285 fsr.cookie_mask, fsr.out_port);
3286 error = collect_rules_loose(ofproto, &criteria, &rules);
3287 rule_criteria_destroy(&criteria);
3292 ofpmp_init(&replies, request);
3293 for (i = 0; i < rules.n; i++) {
3294 struct rule *rule = rules.rules[i];
3295 long long int now = time_msec();
3296 struct ofputil_flow_stats fs;
3298 minimatch_expand(&rule->cr.match, &fs.match);
3299 fs.priority = rule->cr.priority;
3300 fs.cookie = rule->flow_cookie;
3301 fs.table_id = rule->table_id;
3302 calc_duration(rule->created, now, &fs.duration_sec, &fs.duration_nsec);
3303 fs.idle_age = age_secs(now - rule->used);
3304 fs.hard_age = age_secs(now - rule->modified);
3305 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3307 fs.ofpacts = rule->actions->ofpacts;
3308 fs.ofpacts_len = rule->actions->ofpacts_len;
3310 ovs_mutex_lock(&rule->timeout_mutex);
3311 fs.idle_timeout = rule->idle_timeout;
3312 fs.hard_timeout = rule->hard_timeout;
3313 ovs_mutex_unlock(&rule->timeout_mutex);
3316 if (rule->send_flow_removed) {
3317 fs.flags |= OFPUTIL_FF_SEND_FLOW_REM;
3318 /* FIXME: Implement OFPUTIL_FF_NO_PKT_COUNTS and
3319 OFPUTIL_FF_NO_BYT_COUNTS. */
3321 ofputil_append_flow_stats_reply(&fs, &replies);
3323 rule_collection_destroy(&rules);
3325 ofconn_send_replies(ofconn, &replies);
3331 flow_stats_ds(struct rule *rule, struct ds *results)
3333 uint64_t packet_count, byte_count;
3335 rule->ofproto->ofproto_class->rule_get_stats(rule,
3336 &packet_count, &byte_count);
3338 if (rule->table_id != 0) {
3339 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3341 ds_put_format(results, "duration=%llds, ",
3342 (time_msec() - rule->created) / 1000);
3343 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3344 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3345 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3346 cls_rule_format(&rule->cr, results);
3347 ds_put_char(results, ',');
3348 ofpacts_format(rule->actions->ofpacts, rule->actions->ofpacts_len,
3350 ds_put_cstr(results, "\n");
3353 /* Adds a pretty-printed description of all flows to 'results', including
3354 * hidden flows (e.g., set up by in-band control). */
3356 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3358 struct oftable *table;
3360 OFPROTO_FOR_EACH_TABLE (table, p) {
3361 struct cls_cursor cursor;
3364 ovs_rwlock_rdlock(&table->cls.rwlock);
3365 cls_cursor_init(&cursor, &table->cls, NULL);
3366 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3367 flow_stats_ds(rule, results);
3369 ovs_rwlock_unlock(&table->cls.rwlock);
3373 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3374 * '*engine_type' and '*engine_id', respectively. */
3376 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3377 uint8_t *engine_type, uint8_t *engine_id)
3379 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3382 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3383 * true if the port's CFM status was successfully stored into '*status'.
3384 * Returns false if the port did not have CFM configured, in which case
3385 * '*status' is indeterminate.
3387 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3389 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3390 struct ofproto_cfm_status *status)
3392 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3394 && ofproto->ofproto_class->get_cfm_status
3395 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3399 handle_aggregate_stats_request(struct ofconn *ofconn,
3400 const struct ofp_header *oh)
3402 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3403 struct ofputil_flow_stats_request request;
3404 struct ofputil_aggregate_stats stats;
3405 bool unknown_packets, unknown_bytes;
3406 struct rule_criteria criteria;
3407 struct rule_collection rules;
3408 struct ofpbuf *reply;
3412 error = ofputil_decode_flow_stats_request(&request, oh);
3417 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3418 request.cookie, request.cookie_mask,
3420 error = collect_rules_loose(ofproto, &criteria, &rules);
3421 rule_criteria_destroy(&criteria);
3426 memset(&stats, 0, sizeof stats);
3427 unknown_packets = unknown_bytes = false;
3428 for (i = 0; i < rules.n; i++) {
3429 struct rule *rule = rules.rules[i];
3430 uint64_t packet_count;
3431 uint64_t byte_count;
3433 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3436 if (packet_count == UINT64_MAX) {
3437 unknown_packets = true;
3439 stats.packet_count += packet_count;
3442 if (byte_count == UINT64_MAX) {
3443 unknown_bytes = true;
3445 stats.byte_count += byte_count;
3450 if (unknown_packets) {
3451 stats.packet_count = UINT64_MAX;
3453 if (unknown_bytes) {
3454 stats.byte_count = UINT64_MAX;
3457 rule_collection_destroy(&rules);
3459 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3460 ofconn_send_reply(ofconn, reply);
3465 struct queue_stats_cbdata {
3466 struct ofport *ofport;
3467 struct list replies;
3472 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3473 const struct netdev_queue_stats *stats)
3475 struct ofputil_queue_stats oqs;
3477 oqs.port_no = cbdata->ofport->pp.port_no;
3478 oqs.queue_id = queue_id;
3479 oqs.tx_bytes = stats->tx_bytes;
3480 oqs.tx_packets = stats->tx_packets;
3481 oqs.tx_errors = stats->tx_errors;
3482 if (stats->created != LLONG_MIN) {
3483 calc_duration(stats->created, cbdata->now,
3484 &oqs.duration_sec, &oqs.duration_nsec);
3486 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3488 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3492 handle_queue_stats_dump_cb(uint32_t queue_id,
3493 struct netdev_queue_stats *stats,
3496 struct queue_stats_cbdata *cbdata = cbdata_;
3498 put_queue_stats(cbdata, queue_id, stats);
3502 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3503 struct queue_stats_cbdata *cbdata)
3505 cbdata->ofport = port;
3506 if (queue_id == OFPQ_ALL) {
3507 netdev_dump_queue_stats(port->netdev,
3508 handle_queue_stats_dump_cb, cbdata);
3510 struct netdev_queue_stats stats;
3512 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3513 put_queue_stats(cbdata, queue_id, &stats);
3515 return OFPERR_OFPQOFC_BAD_QUEUE;
3522 handle_queue_stats_request(struct ofconn *ofconn,
3523 const struct ofp_header *rq)
3525 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3526 struct queue_stats_cbdata cbdata;
3527 struct ofport *port;
3529 struct ofputil_queue_stats_request oqsr;
3531 COVERAGE_INC(ofproto_queue_req);
3533 ofpmp_init(&cbdata.replies, rq);
3534 cbdata.now = time_msec();
3536 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3541 if (oqsr.port_no == OFPP_ANY) {
3542 error = OFPERR_OFPQOFC_BAD_QUEUE;
3543 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3544 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3549 port = ofproto_get_port(ofproto, oqsr.port_no);
3551 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3552 : OFPERR_OFPQOFC_BAD_PORT);
3555 ofconn_send_replies(ofconn, &cbdata.replies);
3557 ofpbuf_list_delete(&cbdata.replies);
3564 is_flow_deletion_pending(const struct ofproto *ofproto,
3565 const struct cls_rule *cls_rule,
3568 if (!hmap_is_empty(&ofproto->deletions)) {
3569 struct ofoperation *op;
3571 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3572 cls_rule_hash(cls_rule, table_id),
3573 &ofproto->deletions) {
3574 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3584 evict_rule_from_table(struct ofproto *ofproto, struct oftable *table)
3589 ovs_rwlock_rdlock(&table->cls.rwlock);
3590 n_rules = classifier_count(&table->cls);
3591 ovs_rwlock_unlock(&table->cls.rwlock);
3593 if (n_rules < table->max_flows) {
3595 } else if (!choose_rule_to_evict(table, &rule)) {
3596 return OFPERR_OFPFMFC_TABLE_FULL;
3597 } else if (rule->pending) {
3598 ovs_rwlock_unlock(&rule->rwlock);
3599 return OFPROTO_POSTPONE;
3601 struct ofopgroup *group;
3603 group = ofopgroup_create_unattached(ofproto);
3604 delete_flow__(rule, group, OFPRR_EVICTION);
3605 ofopgroup_submit(group);
3611 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3612 * in which no matching flow already exists in the flow table.
3614 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3615 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3616 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3617 * initiated now but may be retried later.
3619 * The caller retains ownership of 'fm->ofpacts'.
3621 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3624 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3625 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3627 struct oftable *table;
3628 struct ofopgroup *group;
3634 error = check_table_id(ofproto, fm->table_id);
3640 if (fm->table_id == 0xff) {
3641 if (ofproto->ofproto_class->rule_choose_table) {
3642 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3648 ovs_assert(table_id < ofproto->n_tables);
3652 } else if (fm->table_id < ofproto->n_tables) {
3653 table_id = fm->table_id;
3655 return OFPERR_OFPBRC_BAD_TABLE_ID;
3658 table = &ofproto->tables[table_id];
3660 if (table->flags & OFTABLE_READONLY) {
3661 return OFPERR_OFPBRC_EPERM;
3664 cls_rule_init(&cr, &fm->match, fm->priority);
3666 /* Transform "add" into "modify" if there's an existing identical flow. */
3667 ovs_rwlock_rdlock(&table->cls.rwlock);
3668 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3669 ovs_rwlock_unlock(&table->cls.rwlock);
3671 cls_rule_destroy(&cr);
3672 if (!rule_is_modifiable(rule)) {
3673 return OFPERR_OFPBRC_EPERM;
3674 } else if (rule->pending) {
3675 return OFPROTO_POSTPONE;
3677 struct rule_collection rules;
3679 rule_collection_init(&rules);
3680 rule_collection_add(&rules, rule);
3681 fm->modify_cookie = true;
3682 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3683 rule_collection_destroy(&rules);
3689 /* Verify actions. */
3690 error = ofproto_check_ofpacts(ofproto, fm->ofpacts, fm->ofpacts_len,
3691 &fm->match.flow, table_id);
3693 cls_rule_destroy(&cr);
3697 /* Serialize against pending deletion. */
3698 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3699 cls_rule_destroy(&cr);
3700 return OFPROTO_POSTPONE;
3703 /* Check for overlap, if requested. */
3704 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3707 ovs_rwlock_rdlock(&table->cls.rwlock);
3708 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3709 ovs_rwlock_unlock(&table->cls.rwlock);
3712 cls_rule_destroy(&cr);
3713 return OFPERR_OFPFMFC_OVERLAP;
3717 /* If necessary, evict an existing rule to clear out space. */
3718 error = evict_rule_from_table(ofproto, table);
3720 cls_rule_destroy(&cr);
3724 /* Allocate new rule. */
3725 rule = ofproto->ofproto_class->rule_alloc();
3727 cls_rule_destroy(&cr);
3728 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3729 ofproto->name, ovs_strerror(error));
3733 /* Initialize base state. */
3734 rule->ofproto = ofproto;
3735 cls_rule_move(&rule->cr, &cr);
3736 atomic_init(&rule->ref_count, 1);
3737 rule->pending = NULL;
3738 rule->flow_cookie = fm->new_cookie;
3739 rule->created = rule->modified = rule->used = time_msec();
3741 ovs_mutex_init(&rule->timeout_mutex);
3742 ovs_mutex_lock(&rule->timeout_mutex);
3743 rule->idle_timeout = fm->idle_timeout;
3744 rule->hard_timeout = fm->hard_timeout;
3745 ovs_mutex_unlock(&rule->timeout_mutex);
3747 rule->table_id = table - ofproto->tables;
3748 rule->send_flow_removed = (fm->flags & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3749 rule->actions = rule_actions_create(fm->ofpacts, fm->ofpacts_len);
3750 list_init(&rule->meter_list_node);
3751 rule->eviction_group = NULL;
3752 list_init(&rule->expirable);
3753 rule->monitor_flags = 0;
3754 rule->add_seqno = 0;
3755 rule->modify_seqno = 0;
3756 ovs_rwlock_init(&rule->rwlock);
3758 /* Construct rule, initializing derived state. */
3759 error = ofproto->ofproto_class->rule_construct(rule);
3761 ofproto_rule_destroy__(rule);
3766 oftable_insert_rule(rule);
3768 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3769 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
3770 ofproto->ofproto_class->rule_insert(rule);
3771 ofopgroup_submit(group);
3776 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3778 /* Modifies the rules listed in 'rules', changing their actions to match those
3781 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3784 * Returns 0 on success, otherwise an OpenFlow error code. */
3786 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3787 struct ofputil_flow_mod *fm, const struct ofp_header *request,
3788 const struct rule_collection *rules)
3790 enum ofoperation_type type;
3791 struct ofopgroup *group;
3795 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
3796 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3797 error = OFPERR_OFPBRC_EPERM;
3798 for (i = 0; i < rules->n; i++) {
3799 struct rule *rule = rules->rules[i];
3800 struct ofoperation *op;
3801 bool actions_changed;
3802 bool reset_counters;
3804 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
3806 if (rule_is_modifiable(rule)) {
3807 /* At least one rule is modifiable, don't report EPERM error. */
3813 /* Verify actions. */
3814 error = ofpacts_check(fm->ofpacts, fm->ofpacts_len, &fm->match.flow,
3815 u16_to_ofp(ofproto->max_ports), rule->table_id);
3820 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
3821 rule->actions->ofpacts,
3822 rule->actions->ofpacts_len);
3824 op = ofoperation_create(group, rule, type, 0);
3826 if (fm->modify_cookie && fm->new_cookie != htonll(UINT64_MAX)) {
3827 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
3829 if (type == OFOPERATION_REPLACE) {
3830 ovs_mutex_lock(&rule->timeout_mutex);
3831 rule->idle_timeout = fm->idle_timeout;
3832 rule->hard_timeout = fm->hard_timeout;
3833 ovs_mutex_unlock(&rule->timeout_mutex);
3835 rule->send_flow_removed = (fm->flags
3836 & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3838 if (fm->idle_timeout || fm->hard_timeout) {
3839 if (!rule->eviction_group) {
3840 eviction_group_add_rule(rule);
3843 eviction_group_remove_rule(rule);
3847 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
3848 if (actions_changed || reset_counters) {
3849 struct rule_actions *new_actions;
3851 op->actions = rule->actions;
3852 new_actions = rule_actions_create(fm->ofpacts, fm->ofpacts_len);
3854 ovs_rwlock_wrlock(&rule->rwlock);
3855 rule->actions = new_actions;
3856 ovs_rwlock_unlock(&rule->rwlock);
3858 rule->ofproto->ofproto_class->rule_modify_actions(rule,
3861 ofoperation_complete(op, 0);
3864 ofopgroup_submit(group);
3870 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
3871 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3873 if (fm->cookie_mask != htonll(0) || fm->new_cookie == htonll(UINT64_MAX)) {
3876 return add_flow(ofproto, ofconn, fm, request);
3879 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
3882 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3885 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3886 struct ofputil_flow_mod *fm,
3887 const struct ofp_header *request)
3889 struct rule_criteria criteria;
3890 struct rule_collection rules;
3893 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
3894 fm->cookie, fm->cookie_mask, OFPP_ANY);
3895 error = collect_rules_loose(ofproto, &criteria, &rules);
3896 rule_criteria_destroy(&criteria);
3899 error = (rules.n > 0
3900 ? modify_flows__(ofproto, ofconn, fm, request, &rules)
3901 : modify_flows_add(ofproto, ofconn, fm, request));
3904 rule_collection_destroy(&rules);
3909 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
3912 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3915 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3916 struct ofputil_flow_mod *fm,
3917 const struct ofp_header *request)
3919 struct rule_criteria criteria;
3920 struct rule_collection rules;
3923 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
3924 fm->cookie, fm->cookie_mask, OFPP_ANY);
3925 error = collect_rules_strict(ofproto, &criteria, &rules);
3926 rule_criteria_destroy(&criteria);
3930 error = modify_flows_add(ofproto, ofconn, fm, request);
3931 } else if (rules.n == 1) {
3932 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3936 rule_collection_destroy(&rules);
3941 /* OFPFC_DELETE implementation. */
3944 delete_flow__(struct rule *rule, struct ofopgroup *group,
3945 enum ofp_flow_removed_reason reason)
3947 struct ofproto *ofproto = rule->ofproto;
3949 ofproto_rule_send_removed(rule, reason);
3951 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
3952 oftable_remove_rule(rule);
3953 ofproto->ofproto_class->rule_delete(rule);
3956 /* Deletes the rules listed in 'rules'.
3958 * Returns 0 on success, otherwise an OpenFlow error code. */
3960 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3961 const struct ofp_header *request,
3962 const struct rule_collection *rules,
3963 enum ofp_flow_removed_reason reason)
3965 struct ofopgroup *group;
3968 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3969 for (i = 0; i < rules->n; i++) {
3970 struct rule *rule = rules->rules[i];
3971 ovs_rwlock_wrlock(&rule->rwlock);
3972 delete_flow__(rule, group, reason);
3974 ofopgroup_submit(group);
3979 /* Implements OFPFC_DELETE. */
3981 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3982 const struct ofputil_flow_mod *fm,
3983 const struct ofp_header *request)
3985 struct rule_criteria criteria;
3986 struct rule_collection rules;
3989 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
3990 fm->cookie, fm->cookie_mask,
3992 error = collect_rules_loose(ofproto, &criteria, &rules);
3993 rule_criteria_destroy(&criteria);
3995 if (!error && rules.n > 0) {
3996 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
3998 rule_collection_destroy(&rules);
4003 /* Implements OFPFC_DELETE_STRICT. */
4005 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4006 const struct ofputil_flow_mod *fm,
4007 const struct ofp_header *request)
4009 struct rule_criteria criteria;
4010 struct rule_collection rules;
4013 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4014 fm->cookie, fm->cookie_mask, fm->out_port);
4015 error = collect_rules_strict(ofproto, &criteria, &rules);
4016 rule_criteria_destroy(&criteria);
4018 if (!error && rules.n > 0) {
4019 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4021 rule_collection_destroy(&rules);
4027 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4029 struct ofputil_flow_removed fr;
4031 if (ofproto_rule_is_hidden(rule) || !rule->send_flow_removed) {
4035 minimatch_expand(&rule->cr.match, &fr.match);
4036 fr.priority = rule->cr.priority;
4037 fr.cookie = rule->flow_cookie;
4039 fr.table_id = rule->table_id;
4040 calc_duration(rule->created, time_msec(),
4041 &fr.duration_sec, &fr.duration_nsec);
4042 ovs_mutex_lock(&rule->timeout_mutex);
4043 fr.idle_timeout = rule->idle_timeout;
4044 fr.hard_timeout = rule->hard_timeout;
4045 ovs_mutex_unlock(&rule->timeout_mutex);
4046 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4049 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4052 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4053 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4056 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4059 * ofproto implementation ->run() functions should use this function to expire
4060 * OpenFlow flows. */
4062 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4064 struct ofproto *ofproto = rule->ofproto;
4065 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
4067 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
4068 ofproto_rule_send_removed(rule, reason);
4070 ovs_rwlock_wrlock(&cls->rwlock);
4071 ofproto_rule_delete(ofproto, cls, rule);
4072 ovs_rwlock_unlock(&cls->rwlock);
4075 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
4076 * means "infinite". */
4078 reduce_timeout(uint16_t max, uint16_t *timeout)
4080 if (max && (!*timeout || *timeout > max)) {
4085 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4086 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4087 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
4089 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4091 ofproto_rule_reduce_timeouts(struct rule *rule,
4092 uint16_t idle_timeout, uint16_t hard_timeout)
4093 OVS_EXCLUDED(rule->ofproto->expirable_mutex, rule->timeout_mutex)
4095 if (!idle_timeout && !hard_timeout) {
4099 ovs_mutex_lock(&rule->ofproto->expirable_mutex);
4100 if (list_is_empty(&rule->expirable)) {
4101 list_insert(&rule->ofproto->expirable, &rule->expirable);
4103 ovs_mutex_unlock(&rule->ofproto->expirable_mutex);
4105 ovs_mutex_lock(&rule->timeout_mutex);
4106 reduce_timeout(idle_timeout, &rule->idle_timeout);
4107 reduce_timeout(hard_timeout, &rule->hard_timeout);
4108 ovs_mutex_unlock(&rule->timeout_mutex);
4112 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4114 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4115 struct ofputil_flow_mod fm;
4116 uint64_t ofpacts_stub[1024 / 8];
4117 struct ofpbuf ofpacts;
4121 error = reject_slave_controller(ofconn);
4126 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4127 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4130 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4133 goto exit_free_ofpacts;
4136 /* Record the operation for logging a summary report. */
4137 switch (fm.command) {
4143 case OFPFC_MODIFY_STRICT:
4144 ofproto->n_modify++;
4148 case OFPFC_DELETE_STRICT:
4149 ofproto->n_delete++;
4154 if (ofproto->next_op_report == LLONG_MAX) {
4155 ofproto->first_op = now;
4156 ofproto->next_op_report = MAX(now + 10 * 1000,
4157 ofproto->op_backoff);
4158 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4160 ofproto->last_op = now;
4163 ofpbuf_uninit(&ofpacts);
4169 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4170 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4174 if (ofproto->n_pending < 50) {
4175 switch (fm->command) {
4177 error = add_flow(ofproto, ofconn, fm, oh);
4181 error = modify_flows_loose(ofproto, ofconn, fm, oh);
4184 case OFPFC_MODIFY_STRICT:
4185 error = modify_flow_strict(ofproto, ofconn, fm, oh);
4189 error = delete_flows_loose(ofproto, ofconn, fm, oh);
4192 case OFPFC_DELETE_STRICT:
4193 error = delete_flow_strict(ofproto, ofconn, fm, oh);
4197 if (fm->command > 0xff) {
4198 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4199 "flow_mod_table_id extension is not enabled",
4202 error = OFPERR_OFPFMFC_BAD_COMMAND;
4206 ovs_assert(!list_is_empty(&ofproto->pending));
4207 error = OFPROTO_POSTPONE;
4210 run_rule_executes(ofproto);
4215 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4217 struct ofputil_role_request request;
4218 struct ofputil_role_request reply;
4222 error = ofputil_decode_role_message(oh, &request);
4227 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4228 if (ofconn_get_role(ofconn) != request.role
4229 && ofconn_has_pending_opgroups(ofconn)) {
4230 return OFPROTO_POSTPONE;
4233 if (request.have_generation_id
4234 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4235 return OFPERR_OFPRRFC_STALE;
4238 ofconn_set_role(ofconn, request.role);
4241 reply.role = ofconn_get_role(ofconn);
4242 reply.have_generation_id = ofconn_get_master_election_id(
4243 ofconn, &reply.generation_id);
4244 buf = ofputil_encode_role_reply(oh, &reply);
4245 ofconn_send_reply(ofconn, buf);
4251 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4252 const struct ofp_header *oh)
4254 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4255 enum ofputil_protocol cur, next;
4257 cur = ofconn_get_protocol(ofconn);
4258 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4259 ofconn_set_protocol(ofconn, next);
4265 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4267 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4268 enum ofputil_protocol cur, next;
4269 enum ofputil_protocol next_base;
4271 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4273 return OFPERR_OFPBRC_EPERM;
4276 cur = ofconn_get_protocol(ofconn);
4277 next = ofputil_protocol_set_base(cur, next_base);
4278 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4279 /* Avoid sending async messages in surprising protocol. */
4280 return OFPROTO_POSTPONE;
4283 ofconn_set_protocol(ofconn, next);
4288 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4289 const struct ofp_header *oh)
4291 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4294 format = ntohl(msg->format);
4295 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4296 return OFPERR_OFPBRC_EPERM;
4299 if (format != ofconn_get_packet_in_format(ofconn)
4300 && ofconn_has_pending_opgroups(ofconn)) {
4301 /* Avoid sending async message in surprsing packet in format. */
4302 return OFPROTO_POSTPONE;
4305 ofconn_set_packet_in_format(ofconn, format);
4310 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4312 const struct nx_async_config *msg = ofpmsg_body(oh);
4313 uint32_t master[OAM_N_TYPES];
4314 uint32_t slave[OAM_N_TYPES];
4316 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4317 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4318 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4320 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4321 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4322 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4324 ofconn_set_async_config(ofconn, master, slave);
4325 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4326 !ofconn_get_miss_send_len(ofconn)) {
4327 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4334 handle_nxt_set_controller_id(struct ofconn *ofconn,
4335 const struct ofp_header *oh)
4337 const struct nx_controller_id *nci = ofpmsg_body(oh);
4339 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4340 return OFPERR_NXBRC_MUST_BE_ZERO;
4343 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4348 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4352 if (ofconn_has_pending_opgroups(ofconn)) {
4353 return OFPROTO_POSTPONE;
4356 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4357 ? OFPRAW_OFPT10_BARRIER_REPLY
4358 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4359 ofconn_send_reply(ofconn, buf);
4364 ofproto_compose_flow_refresh_update(const struct rule *rule,
4365 enum nx_flow_monitor_flags flags,
4368 struct ofoperation *op = rule->pending;
4369 const struct rule_actions *actions;
4370 struct ofputil_flow_update fu;
4373 if (op && op->type == OFOPERATION_ADD) {
4374 /* We'll report the final flow when the operation completes. Reporting
4375 * it now would cause a duplicate report later. */
4379 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4380 ? NXFME_ADDED : NXFME_MODIFIED);
4382 ovs_mutex_lock(&rule->timeout_mutex);
4383 fu.idle_timeout = rule->idle_timeout;
4384 fu.hard_timeout = rule->hard_timeout;
4385 ovs_mutex_unlock(&rule->timeout_mutex);
4386 fu.table_id = rule->table_id;
4387 fu.cookie = rule->flow_cookie;
4388 minimatch_expand(&rule->cr.match, &match);
4390 fu.priority = rule->cr.priority;
4392 if (!(flags & NXFMF_ACTIONS)) {
4395 actions = rule->actions;
4397 /* An operation is in progress. Use the previous version of the flow's
4398 * actions, so that when the operation commits we report the change. */
4400 case OFOPERATION_ADD:
4403 case OFOPERATION_MODIFY:
4404 case OFOPERATION_REPLACE:
4405 actions = op->actions ? op->actions : rule->actions;
4408 case OFOPERATION_DELETE:
4409 actions = rule->actions;
4416 fu.ofpacts = actions ? actions->ofpacts : NULL;
4417 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4419 if (list_is_empty(msgs)) {
4420 ofputil_start_flow_update(msgs);
4422 ofputil_append_flow_update(&fu, msgs);
4426 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4431 for (i = 0; i < rules->n; i++) {
4432 struct rule *rule = rules->rules[i];
4433 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4434 rule->monitor_flags = 0;
4436 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4441 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4442 struct rule *rule, uint64_t seqno,
4443 struct rule_collection *rules)
4445 enum nx_flow_monitor_flags update;
4447 if (ofproto_rule_is_hidden(rule)) {
4452 ? ofoperation_has_out_port(rule->pending, m->out_port)
4453 : ofproto_rule_has_out_port(rule, m->out_port))) {
4458 if (rule->add_seqno > seqno) {
4459 update = NXFMF_ADD | NXFMF_MODIFY;
4460 } else if (rule->modify_seqno > seqno) {
4461 update = NXFMF_MODIFY;
4466 if (!(m->flags & update)) {
4470 update = NXFMF_INITIAL;
4473 if (!rule->monitor_flags) {
4474 rule_collection_add(rules, rule);
4476 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4480 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4482 struct rule_collection *rules)
4484 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4485 const struct ofoperation *op;
4486 const struct oftable *table;
4487 struct cls_rule target;
4489 cls_rule_init_from_minimatch(&target, &m->match, 0);
4490 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4491 struct cls_cursor cursor;
4494 ovs_rwlock_rdlock(&table->cls.rwlock);
4495 cls_cursor_init(&cursor, &table->cls, &target);
4496 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4497 ovs_assert(!rule->pending); /* XXX */
4498 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4500 ovs_rwlock_unlock(&table->cls.rwlock);
4503 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4504 struct rule *rule = op->rule;
4506 if (((m->table_id == 0xff
4507 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4508 : m->table_id == rule->table_id))
4509 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4510 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4513 cls_rule_destroy(&target);
4517 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4518 struct rule_collection *rules)
4520 if (m->flags & NXFMF_INITIAL) {
4521 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4526 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4527 uint64_t seqno, struct rule_collection *rules)
4529 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4533 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4535 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4536 struct ofmonitor **monitors;
4537 size_t n_monitors, allocated_monitors;
4538 struct rule_collection rules;
4539 struct list replies;
4545 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4547 n_monitors = allocated_monitors = 0;
4549 struct ofputil_flow_monitor_request request;
4550 struct ofmonitor *m;
4553 retval = ofputil_decode_flow_monitor_request(&request, &b);
4554 if (retval == EOF) {
4556 } else if (retval) {
4561 if (request.table_id != 0xff
4562 && request.table_id >= ofproto->n_tables) {
4563 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4567 error = ofmonitor_create(&request, ofconn, &m);
4572 if (n_monitors >= allocated_monitors) {
4573 monitors = x2nrealloc(monitors, &allocated_monitors,
4576 monitors[n_monitors++] = m;
4579 rule_collection_init(&rules);
4580 for (i = 0; i < n_monitors; i++) {
4581 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4584 ofpmp_init(&replies, oh);
4585 ofmonitor_compose_refresh_updates(&rules, &replies);
4586 rule_collection_destroy(&rules);
4588 ofconn_send_replies(ofconn, &replies);
4595 for (i = 0; i < n_monitors; i++) {
4596 ofmonitor_destroy(monitors[i]);
4603 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4605 struct ofmonitor *m;
4608 id = ofputil_decode_flow_monitor_cancel(oh);
4609 m = ofmonitor_lookup(ofconn, id);
4611 return OFPERR_NXBRC_FM_BAD_ID;
4614 ofmonitor_destroy(m);
4618 /* Meters implementation.
4620 * Meter table entry, indexed by the OpenFlow meter_id.
4621 * These are always dynamically allocated to allocate enough space for
4623 * 'created' is used to compute the duration for meter stats.
4624 * 'list rules' is needed so that we can delete the dependent rules when the
4625 * meter table entry is deleted.
4626 * 'provider_meter_id' is for the provider's private use.
4629 long long int created; /* Time created. */
4630 struct list rules; /* List of "struct rule_dpif"s. */
4631 ofproto_meter_id provider_meter_id;
4632 uint16_t flags; /* Meter flags. */
4633 uint16_t n_bands; /* Number of meter bands. */
4634 struct ofputil_meter_band *bands;
4638 * This is used in instruction validation at flow set-up time,
4639 * as flows may not use non-existing meters.
4640 * This is also used by ofproto-providers to translate OpenFlow meter_ids
4641 * in METER instructions to the corresponding provider meter IDs.
4642 * Return value of UINT32_MAX signifies an invalid meter.
4645 ofproto_get_provider_meter_id(const struct ofproto * ofproto,
4646 uint32_t of_meter_id)
4648 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4649 const struct meter *meter = ofproto->meters[of_meter_id];
4651 return meter->provider_meter_id.uint32;
4658 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4662 meter->flags = config->flags;
4663 meter->n_bands = config->n_bands;
4664 meter->bands = xmemdup(config->bands,
4665 config->n_bands * sizeof *meter->bands);
4668 static struct meter *
4669 meter_create(const struct ofputil_meter_config *config,
4670 ofproto_meter_id provider_meter_id)
4672 struct meter *meter;
4674 meter = xzalloc(sizeof *meter);
4675 meter->provider_meter_id = provider_meter_id;
4676 meter->created = time_msec();
4677 list_init(&meter->rules);
4679 meter_update(meter, config);
4685 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
4688 for (mid = first; mid <= last; ++mid) {
4689 struct meter *meter = ofproto->meters[mid];
4691 ofproto->meters[mid] = NULL;
4692 ofproto->ofproto_class->meter_del(ofproto,
4693 meter->provider_meter_id);
4701 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4703 ofproto_meter_id provider_meter_id = { UINT32_MAX };
4704 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
4708 return OFPERR_OFPMMFC_METER_EXISTS;
4711 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
4714 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
4715 *meterp = meter_create(&mm->meter, provider_meter_id);
4721 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4723 struct meter *meter = ofproto->meters[mm->meter.meter_id];
4727 return OFPERR_OFPMMFC_UNKNOWN_METER;
4730 error = ofproto->ofproto_class->meter_set(ofproto,
4731 &meter->provider_meter_id,
4733 ovs_assert(meter->provider_meter_id.uint32 != UINT32_MAX);
4735 meter_update(meter, &mm->meter);
4741 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
4742 struct ofputil_meter_mod *mm)
4744 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4745 uint32_t meter_id = mm->meter.meter_id;
4746 struct rule_collection rules;
4747 enum ofperr error = 0;
4748 uint32_t first, last;
4750 if (meter_id == OFPM13_ALL) {
4752 last = ofproto->meter_features.max_meters;
4754 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
4757 first = last = meter_id;
4760 /* First delete the rules that use this meter. If any of those rules are
4761 * currently being modified, postpone the whole operation until later. */
4762 rule_collection_init(&rules);
4763 for (meter_id = first; meter_id <= last; ++meter_id) {
4764 struct meter *meter = ofproto->meters[meter_id];
4765 if (meter && !list_is_empty(&meter->rules)) {
4768 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
4769 if (rule->pending) {
4770 error = OFPROTO_POSTPONE;
4773 rule_collection_add(&rules, rule);
4778 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
4781 /* Delete the meters. */
4782 meter_delete(ofproto, first, last);
4785 rule_collection_destroy(&rules);
4791 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4793 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4794 struct ofputil_meter_mod mm;
4795 uint64_t bands_stub[256 / 8];
4796 struct ofpbuf bands;
4800 error = reject_slave_controller(ofconn);
4805 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4807 error = ofputil_decode_meter_mod(oh, &mm, &bands);
4809 goto exit_free_bands;
4812 meter_id = mm.meter.meter_id;
4814 if (mm.command != OFPMC13_DELETE) {
4815 /* Fails also when meters are not implemented by the provider. */
4816 if (meter_id == 0 || meter_id > OFPM13_MAX) {
4817 error = OFPERR_OFPMMFC_INVALID_METER;
4818 goto exit_free_bands;
4819 } else if (meter_id > ofproto->meter_features.max_meters) {
4820 error = OFPERR_OFPMMFC_OUT_OF_METERS;
4821 goto exit_free_bands;
4823 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
4824 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
4825 goto exit_free_bands;
4829 switch (mm.command) {
4831 error = handle_add_meter(ofproto, &mm);
4834 case OFPMC13_MODIFY:
4835 error = handle_modify_meter(ofproto, &mm);
4838 case OFPMC13_DELETE:
4839 error = handle_delete_meter(ofconn, oh, &mm);
4843 error = OFPERR_OFPMMFC_BAD_COMMAND;
4848 ofpbuf_uninit(&bands);
4853 handle_meter_features_request(struct ofconn *ofconn,
4854 const struct ofp_header *request)
4856 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4857 struct ofputil_meter_features features;
4860 if (ofproto->ofproto_class->meter_get_features) {
4861 ofproto->ofproto_class->meter_get_features(ofproto, &features);
4863 memset(&features, 0, sizeof features);
4865 b = ofputil_encode_meter_features_reply(&features, request);
4867 ofconn_send_reply(ofconn, b);
4872 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
4875 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4876 struct list replies;
4877 uint64_t bands_stub[256 / 8];
4878 struct ofpbuf bands;
4879 uint32_t meter_id, first, last;
4881 ofputil_decode_meter_request(request, &meter_id);
4883 if (meter_id == OFPM13_ALL) {
4885 last = ofproto->meter_features.max_meters;
4887 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
4888 !ofproto->meters[meter_id]) {
4889 return OFPERR_OFPMMFC_UNKNOWN_METER;
4891 first = last = meter_id;
4894 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4895 ofpmp_init(&replies, request);
4897 for (meter_id = first; meter_id <= last; ++meter_id) {
4898 struct meter *meter = ofproto->meters[meter_id];
4900 continue; /* Skip non-existing meters. */
4902 if (type == OFPTYPE_METER_STATS_REQUEST) {
4903 struct ofputil_meter_stats stats;
4905 stats.meter_id = meter_id;
4907 /* Provider sets the packet and byte counts, we do the rest. */
4908 stats.flow_count = list_size(&meter->rules);
4909 calc_duration(meter->created, time_msec(),
4910 &stats.duration_sec, &stats.duration_nsec);
4911 stats.n_bands = meter->n_bands;
4912 ofpbuf_clear(&bands);
4914 = ofpbuf_put_uninit(&bands,
4915 meter->n_bands * sizeof *stats.bands);
4917 if (!ofproto->ofproto_class->meter_get(ofproto,
4918 meter->provider_meter_id,
4920 ofputil_append_meter_stats(&replies, &stats);
4922 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
4923 struct ofputil_meter_config config;
4925 config.meter_id = meter_id;
4926 config.flags = meter->flags;
4927 config.n_bands = meter->n_bands;
4928 config.bands = meter->bands;
4929 ofputil_append_meter_config(&replies, &config);
4933 ofconn_send_replies(ofconn, &replies);
4934 ofpbuf_uninit(&bands);
4939 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4941 const struct ofp_header *oh = msg->data;
4945 error = ofptype_decode(&type, oh);
4951 /* OpenFlow requests. */
4952 case OFPTYPE_ECHO_REQUEST:
4953 return handle_echo_request(ofconn, oh);
4955 case OFPTYPE_FEATURES_REQUEST:
4956 return handle_features_request(ofconn, oh);
4958 case OFPTYPE_GET_CONFIG_REQUEST:
4959 return handle_get_config_request(ofconn, oh);
4961 case OFPTYPE_SET_CONFIG:
4962 return handle_set_config(ofconn, oh);
4964 case OFPTYPE_PACKET_OUT:
4965 return handle_packet_out(ofconn, oh);
4967 case OFPTYPE_PORT_MOD:
4968 return handle_port_mod(ofconn, oh);
4970 case OFPTYPE_FLOW_MOD:
4971 return handle_flow_mod(ofconn, oh);
4973 case OFPTYPE_METER_MOD:
4974 return handle_meter_mod(ofconn, oh);
4976 case OFPTYPE_BARRIER_REQUEST:
4977 return handle_barrier_request(ofconn, oh);
4979 case OFPTYPE_ROLE_REQUEST:
4980 return handle_role_request(ofconn, oh);
4982 /* OpenFlow replies. */
4983 case OFPTYPE_ECHO_REPLY:
4986 /* Nicira extension requests. */
4987 case OFPTYPE_FLOW_MOD_TABLE_ID:
4988 return handle_nxt_flow_mod_table_id(ofconn, oh);
4990 case OFPTYPE_SET_FLOW_FORMAT:
4991 return handle_nxt_set_flow_format(ofconn, oh);
4993 case OFPTYPE_SET_PACKET_IN_FORMAT:
4994 return handle_nxt_set_packet_in_format(ofconn, oh);
4996 case OFPTYPE_SET_CONTROLLER_ID:
4997 return handle_nxt_set_controller_id(ofconn, oh);
4999 case OFPTYPE_FLOW_AGE:
5000 /* Nothing to do. */
5003 case OFPTYPE_FLOW_MONITOR_CANCEL:
5004 return handle_flow_monitor_cancel(ofconn, oh);
5006 case OFPTYPE_SET_ASYNC_CONFIG:
5007 return handle_nxt_set_async_config(ofconn, oh);
5009 /* Statistics requests. */
5010 case OFPTYPE_DESC_STATS_REQUEST:
5011 return handle_desc_stats_request(ofconn, oh);
5013 case OFPTYPE_FLOW_STATS_REQUEST:
5014 return handle_flow_stats_request(ofconn, oh);
5016 case OFPTYPE_AGGREGATE_STATS_REQUEST:
5017 return handle_aggregate_stats_request(ofconn, oh);
5019 case OFPTYPE_TABLE_STATS_REQUEST:
5020 return handle_table_stats_request(ofconn, oh);
5022 case OFPTYPE_PORT_STATS_REQUEST:
5023 return handle_port_stats_request(ofconn, oh);
5025 case OFPTYPE_QUEUE_STATS_REQUEST:
5026 return handle_queue_stats_request(ofconn, oh);
5028 case OFPTYPE_PORT_DESC_STATS_REQUEST:
5029 return handle_port_desc_stats_request(ofconn, oh);
5031 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
5032 return handle_flow_monitor_request(ofconn, oh);
5034 case OFPTYPE_METER_STATS_REQUEST:
5035 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
5036 return handle_meter_request(ofconn, oh, type);
5038 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
5039 return handle_meter_features_request(ofconn, oh);
5041 /* FIXME: Change the following once they are implemented: */
5042 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
5043 case OFPTYPE_GET_ASYNC_REQUEST:
5044 case OFPTYPE_GROUP_STATS_REQUEST:
5045 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
5046 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
5047 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
5048 return OFPERR_OFPBRC_BAD_TYPE;
5052 case OFPTYPE_FEATURES_REPLY:
5053 case OFPTYPE_GET_CONFIG_REPLY:
5054 case OFPTYPE_PACKET_IN:
5055 case OFPTYPE_FLOW_REMOVED:
5056 case OFPTYPE_PORT_STATUS:
5057 case OFPTYPE_BARRIER_REPLY:
5058 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
5059 case OFPTYPE_DESC_STATS_REPLY:
5060 case OFPTYPE_FLOW_STATS_REPLY:
5061 case OFPTYPE_QUEUE_STATS_REPLY:
5062 case OFPTYPE_PORT_STATS_REPLY:
5063 case OFPTYPE_TABLE_STATS_REPLY:
5064 case OFPTYPE_AGGREGATE_STATS_REPLY:
5065 case OFPTYPE_PORT_DESC_STATS_REPLY:
5066 case OFPTYPE_ROLE_REPLY:
5067 case OFPTYPE_FLOW_MONITOR_PAUSED:
5068 case OFPTYPE_FLOW_MONITOR_RESUMED:
5069 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
5070 case OFPTYPE_GET_ASYNC_REPLY:
5071 case OFPTYPE_GROUP_STATS_REPLY:
5072 case OFPTYPE_GROUP_DESC_STATS_REPLY:
5073 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
5074 case OFPTYPE_METER_STATS_REPLY:
5075 case OFPTYPE_METER_CONFIG_STATS_REPLY:
5076 case OFPTYPE_METER_FEATURES_STATS_REPLY:
5077 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
5079 return OFPERR_OFPBRC_BAD_TYPE;
5084 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
5086 int error = handle_openflow__(ofconn, ofp_msg);
5087 if (error && error != OFPROTO_POSTPONE) {
5088 ofconn_send_error(ofconn, ofp_msg->data, error);
5090 COVERAGE_INC(ofproto_recv_openflow);
5091 return error != OFPROTO_POSTPONE;
5094 /* Asynchronous operations. */
5096 /* Creates and returns a new ofopgroup that is not associated with any
5097 * OpenFlow connection.
5099 * The caller should add operations to the returned group with
5100 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5101 static struct ofopgroup *
5102 ofopgroup_create_unattached(struct ofproto *ofproto)
5104 struct ofopgroup *group = xzalloc(sizeof *group);
5105 group->ofproto = ofproto;
5106 list_init(&group->ofproto_node);
5107 list_init(&group->ops);
5108 list_init(&group->ofconn_node);
5112 /* Creates and returns a new ofopgroup for 'ofproto'.
5114 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
5115 * connection. The 'request' and 'buffer_id' arguments are ignored.
5117 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
5118 * If the ofopgroup eventually fails, then the error reply will include
5119 * 'request'. If the ofopgroup eventually succeeds, then the packet with
5120 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
5122 * The caller should add operations to the returned group with
5123 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5124 static struct ofopgroup *
5125 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
5126 const struct ofp_header *request, uint32_t buffer_id)
5128 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
5130 size_t request_len = ntohs(request->length);
5132 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
5134 ofconn_add_opgroup(ofconn, &group->ofconn_node);
5135 group->ofconn = ofconn;
5136 group->request = xmemdup(request, MIN(request_len, 64));
5137 group->buffer_id = buffer_id;
5142 /* Submits 'group' for processing.
5144 * If 'group' contains no operations (e.g. none were ever added, or all of the
5145 * ones that were added completed synchronously), then it is destroyed
5146 * immediately. Otherwise it is added to the ofproto's list of pending
5149 ofopgroup_submit(struct ofopgroup *group)
5151 if (!group->n_running) {
5152 ofopgroup_complete(group);
5154 list_push_back(&group->ofproto->pending, &group->ofproto_node);
5155 group->ofproto->n_pending++;
5160 ofopgroup_complete(struct ofopgroup *group)
5162 struct ofproto *ofproto = group->ofproto;
5164 struct ofconn *abbrev_ofconn;
5165 ovs_be32 abbrev_xid;
5167 struct ofoperation *op, *next_op;
5170 ovs_assert(!group->n_running);
5173 LIST_FOR_EACH (op, group_node, &group->ops) {
5180 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
5181 LIST_FOR_EACH (op, group_node, &group->ops) {
5182 if (op->type != OFOPERATION_DELETE) {
5183 struct ofpbuf *packet;
5186 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
5189 struct rule_execute *re;
5193 ofproto_rule_ref(op->rule);
5195 re = xmalloc(sizeof *re);
5196 re->rule = op->rule;
5197 re->in_port = in_port;
5198 re->packet = packet;
5200 if (!guarded_list_push_back(&ofproto->rule_executes,
5201 &re->list_node, 1024)) {
5202 ofproto_rule_unref(op->rule);
5203 ofpbuf_delete(re->packet);
5212 if (!error && !list_is_empty(&group->ofconn_node)) {
5213 abbrev_ofconn = group->ofconn;
5214 abbrev_xid = group->request->xid;
5216 abbrev_ofconn = NULL;
5217 abbrev_xid = htonl(0);
5219 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
5220 struct rule *rule = op->rule;
5222 /* We generally want to report the change to active OpenFlow flow
5223 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
5225 - The operation failed.
5227 - The affected rule is not visible to controllers.
5229 - The operation's only effect was to update rule->modified. */
5231 || ofproto_rule_is_hidden(rule)
5232 || (op->type == OFOPERATION_MODIFY
5234 && rule->flow_cookie == op->flow_cookie))) {
5235 /* Check that we can just cast from ofoperation_type to
5236 * nx_flow_update_event. */
5237 enum nx_flow_update_event event_type;
5240 case OFOPERATION_ADD:
5241 case OFOPERATION_REPLACE:
5242 event_type = NXFME_ADDED;
5245 case OFOPERATION_DELETE:
5246 event_type = NXFME_DELETED;
5249 case OFOPERATION_MODIFY:
5250 event_type = NXFME_MODIFIED;
5257 ofmonitor_report(ofproto->connmgr, rule, event_type,
5258 op->reason, abbrev_ofconn, abbrev_xid);
5261 rule->pending = NULL;
5264 case OFOPERATION_ADD:
5268 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
5269 if (vid_mask == VLAN_VID_MASK) {
5270 if (ofproto->vlan_bitmap) {
5271 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
5272 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
5273 bitmap_set1(ofproto->vlan_bitmap, vid);
5274 ofproto->vlans_changed = true;
5277 ofproto->vlans_changed = true;
5281 ovs_rwlock_wrlock(&rule->rwlock);
5282 oftable_remove_rule(rule);
5283 ofproto_rule_unref(rule);
5287 case OFOPERATION_DELETE:
5288 ovs_assert(!op->error);
5289 ofproto_rule_unref(rule);
5293 case OFOPERATION_MODIFY:
5294 case OFOPERATION_REPLACE:
5296 long long int now = time_msec();
5298 rule->modified = now;
5299 if (op->type == OFOPERATION_REPLACE) {
5300 rule->created = rule->used = now;
5303 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
5304 ovs_mutex_lock(&rule->timeout_mutex);
5305 rule->idle_timeout = op->idle_timeout;
5306 rule->hard_timeout = op->hard_timeout;
5307 ovs_mutex_unlock(&rule->timeout_mutex);
5309 struct rule_actions *old_actions;
5311 ovs_rwlock_wrlock(&rule->rwlock);
5312 old_actions = rule->actions;
5313 rule->actions = op->actions;
5314 ovs_rwlock_unlock(&rule->rwlock);
5317 rule_actions_unref(old_actions);
5319 rule->send_flow_removed = op->send_flow_removed;
5327 ofoperation_destroy(op);
5330 ofmonitor_flush(ofproto->connmgr);
5332 if (!list_is_empty(&group->ofproto_node)) {
5333 ovs_assert(ofproto->n_pending > 0);
5334 ofproto->n_pending--;
5335 list_remove(&group->ofproto_node);
5337 if (!list_is_empty(&group->ofconn_node)) {
5338 list_remove(&group->ofconn_node);
5340 ofconn_send_error(group->ofconn, group->request, error);
5342 connmgr_retry(ofproto->connmgr);
5344 free(group->request);
5348 /* Initiates a new operation on 'rule', of the specified 'type', within
5349 * 'group'. Prior to calling, 'rule' must not have any pending operation.
5351 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
5352 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
5354 * Returns the newly created ofoperation (which is also available as
5355 * rule->pending). */
5356 static struct ofoperation *
5357 ofoperation_create(struct ofopgroup *group, struct rule *rule,
5358 enum ofoperation_type type,
5359 enum ofp_flow_removed_reason reason)
5361 struct ofproto *ofproto = group->ofproto;
5362 struct ofoperation *op;
5364 ovs_assert(!rule->pending);
5366 op = rule->pending = xzalloc(sizeof *op);
5368 list_push_back(&group->ops, &op->group_node);
5371 op->reason = reason;
5372 op->flow_cookie = rule->flow_cookie;
5373 ovs_mutex_lock(&rule->timeout_mutex);
5374 op->idle_timeout = rule->idle_timeout;
5375 op->hard_timeout = rule->hard_timeout;
5376 ovs_mutex_unlock(&rule->timeout_mutex);
5377 op->send_flow_removed = rule->send_flow_removed;
5381 if (type == OFOPERATION_DELETE) {
5382 hmap_insert(&ofproto->deletions, &op->hmap_node,
5383 cls_rule_hash(&rule->cr, rule->table_id));
5390 ofoperation_destroy(struct ofoperation *op)
5392 struct ofopgroup *group = op->group;
5395 op->rule->pending = NULL;
5397 if (op->type == OFOPERATION_DELETE) {
5398 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
5400 list_remove(&op->group_node);
5401 rule_actions_unref(op->actions);
5405 /* Indicates that 'op' completed with status 'error', which is either 0 to
5406 * indicate success or an OpenFlow error code on failure.
5408 * If 'error' is 0, indicating success, the operation will be committed
5409 * permanently to the flow table.
5411 * If 'error' is nonzero, then generally the operation will be rolled back:
5413 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
5414 * restores the original rule. The caller must have uninitialized any
5415 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
5416 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
5417 * and 7 for the new rule, calling its ->rule_dealloc() function.
5419 * - If 'op' is a "modify flow" operation, ofproto restores the original
5422 * - 'op' must not be a "delete flow" operation. Removing a rule is not
5423 * allowed to fail. It must always succeed.
5425 * Please see the large comment in ofproto/ofproto-provider.h titled
5426 * "Asynchronous Operation Support" for more information. */
5428 ofoperation_complete(struct ofoperation *op, enum ofperr error)
5430 struct ofopgroup *group = op->group;
5432 ovs_assert(op->rule->pending == op);
5433 ovs_assert(group->n_running > 0);
5434 ovs_assert(!error || op->type != OFOPERATION_DELETE);
5437 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
5438 ofopgroup_complete(group);
5443 pick_datapath_id(const struct ofproto *ofproto)
5445 const struct ofport *port;
5447 port = ofproto_get_port(ofproto, OFPP_LOCAL);
5449 uint8_t ea[ETH_ADDR_LEN];
5452 error = netdev_get_etheraddr(port->netdev, ea);
5454 return eth_addr_to_uint64(ea);
5456 VLOG_WARN("%s: could not get MAC address for %s (%s)",
5457 ofproto->name, netdev_get_name(port->netdev),
5458 ovs_strerror(error));
5460 return ofproto->fallback_dpid;
5464 pick_fallback_dpid(void)
5466 uint8_t ea[ETH_ADDR_LEN];
5467 eth_addr_nicira_random(ea);
5468 return eth_addr_to_uint64(ea);
5471 /* Table overflow policy. */
5473 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
5474 * to NULL if the table is not configured to evict rules or if the table
5475 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
5476 * or with no timeouts are not evictable.) */
5478 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
5480 struct eviction_group *evg;
5483 if (!table->eviction_fields) {
5487 /* In the common case, the outer and inner loops here will each be entered
5490 * - The inner loop normally "return"s in its first iteration. If the
5491 * eviction group has any evictable rules, then it always returns in
5494 * - The outer loop only iterates more than once if the largest eviction
5495 * group has no evictable rules.
5497 * - The outer loop can exit only if table's 'max_flows' is all filled up
5498 * by unevictable rules. */
5499 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
5502 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
5503 if (!ovs_rwlock_trywrlock(&rule->rwlock)) {
5513 /* Searches 'ofproto' for tables that have more flows than their configured
5514 * maximum and that have flow eviction enabled, and evicts as many flows as
5515 * necessary and currently feasible from them.
5517 * This triggers only when an OpenFlow table has N flows in it and then the
5518 * client configures a maximum number of flows less than N. */
5520 ofproto_evict(struct ofproto *ofproto)
5522 struct ofopgroup *group;
5523 struct oftable *table;
5525 group = ofopgroup_create_unattached(ofproto);
5526 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
5527 while (table->eviction_fields) {
5531 ovs_rwlock_rdlock(&table->cls.rwlock);
5532 n_rules = classifier_count(&table->cls);
5533 ovs_rwlock_unlock(&table->cls.rwlock);
5535 if (n_rules <= table->max_flows) {
5539 if (!choose_rule_to_evict(table, &rule)) {
5543 if (rule->pending) {
5544 ovs_rwlock_unlock(&rule->rwlock);
5548 ofoperation_create(group, rule,
5549 OFOPERATION_DELETE, OFPRR_EVICTION);
5550 oftable_remove_rule(rule);
5551 ofproto->ofproto_class->rule_delete(rule);
5554 ofopgroup_submit(group);
5557 /* Eviction groups. */
5559 /* Returns the priority to use for an eviction_group that contains 'n_rules'
5560 * rules. The priority contains low-order random bits to ensure that eviction
5561 * groups with the same number of rules are prioritized randomly. */
5563 eviction_group_priority(size_t n_rules)
5565 uint16_t size = MIN(UINT16_MAX, n_rules);
5566 return (size << 16) | random_uint16();
5569 /* Updates 'evg', an eviction_group within 'table', following a change that
5570 * adds or removes rules in 'evg'. */
5572 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
5574 heap_change(&table->eviction_groups_by_size, &evg->size_node,
5575 eviction_group_priority(heap_count(&evg->rules)));
5578 /* Destroys 'evg', an eviction_group within 'table':
5580 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
5581 * rules themselves, just removes them from the eviction group.)
5583 * - Removes 'evg' from 'table'.
5587 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
5589 while (!heap_is_empty(&evg->rules)) {
5592 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
5593 rule->eviction_group = NULL;
5595 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
5596 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
5597 heap_destroy(&evg->rules);
5601 /* Removes 'rule' from its eviction group, if any. */
5603 eviction_group_remove_rule(struct rule *rule)
5605 if (rule->eviction_group) {
5606 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5607 struct eviction_group *evg = rule->eviction_group;
5609 rule->eviction_group = NULL;
5610 heap_remove(&evg->rules, &rule->evg_node);
5611 if (heap_is_empty(&evg->rules)) {
5612 eviction_group_destroy(table, evg);
5614 eviction_group_resized(table, evg);
5619 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
5620 * returns the hash value. */
5622 eviction_group_hash_rule(struct rule *rule)
5624 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5625 const struct mf_subfield *sf;
5629 hash = table->eviction_group_id_basis;
5630 miniflow_expand(&rule->cr.match.flow, &flow);
5631 for (sf = table->eviction_fields;
5632 sf < &table->eviction_fields[table->n_eviction_fields];
5635 if (mf_are_prereqs_ok(sf->field, &flow)) {
5636 union mf_value value;
5638 mf_get_value(sf->field, &flow, &value);
5640 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
5642 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
5643 unsigned int start = sf->ofs + sf->n_bits;
5644 bitwise_zero(&value, sf->field->n_bytes, start,
5645 sf->field->n_bytes * 8 - start);
5647 hash = hash_bytes(&value, sf->field->n_bytes, hash);
5649 hash = hash_int(hash, 0);
5656 /* Returns an eviction group within 'table' with the given 'id', creating one
5658 static struct eviction_group *
5659 eviction_group_find(struct oftable *table, uint32_t id)
5661 struct eviction_group *evg;
5663 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
5667 evg = xmalloc(sizeof *evg);
5668 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
5669 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
5670 eviction_group_priority(0));
5671 heap_init(&evg->rules);
5676 /* Returns an eviction priority for 'rule'. The return value should be
5677 * interpreted so that higher priorities make a rule more attractive candidates
5680 rule_eviction_priority(struct rule *rule)
5682 long long int hard_expiration;
5683 long long int idle_expiration;
5684 long long int expiration;
5685 uint32_t expiration_offset;
5687 /* Calculate time of expiration. */
5688 ovs_mutex_lock(&rule->timeout_mutex);
5689 hard_expiration = (rule->hard_timeout
5690 ? rule->modified + rule->hard_timeout * 1000
5692 idle_expiration = (rule->idle_timeout
5693 ? rule->used + rule->idle_timeout * 1000
5695 expiration = MIN(hard_expiration, idle_expiration);
5696 ovs_mutex_unlock(&rule->timeout_mutex);
5697 if (expiration == LLONG_MAX) {
5701 /* Calculate the time of expiration as a number of (approximate) seconds
5702 * after program startup.
5704 * This should work OK for program runs that last UINT32_MAX seconds or
5705 * less. Therefore, please restart OVS at least once every 136 years. */
5706 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
5708 /* Invert the expiration offset because we're using a max-heap. */
5709 return UINT32_MAX - expiration_offset;
5712 /* Adds 'rule' to an appropriate eviction group for its oftable's
5713 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
5714 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
5717 * The caller must ensure that 'rule' is not already in an eviction group. */
5719 eviction_group_add_rule(struct rule *rule)
5721 struct ofproto *ofproto = rule->ofproto;
5722 struct oftable *table = &ofproto->tables[rule->table_id];
5725 ovs_mutex_lock(&rule->timeout_mutex);
5726 has_timeout = rule->hard_timeout || rule->idle_timeout;
5727 ovs_mutex_unlock(&rule->timeout_mutex);
5729 if (table->eviction_fields && has_timeout) {
5730 struct eviction_group *evg;
5732 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
5734 rule->eviction_group = evg;
5735 heap_insert(&evg->rules, &rule->evg_node,
5736 rule_eviction_priority(rule));
5737 eviction_group_resized(table, evg);
5743 /* Initializes 'table'. */
5745 oftable_init(struct oftable *table)
5747 memset(table, 0, sizeof *table);
5748 classifier_init(&table->cls);
5749 table->max_flows = UINT_MAX;
5752 /* Destroys 'table', including its classifier and eviction groups.
5754 * The caller is responsible for freeing 'table' itself. */
5756 oftable_destroy(struct oftable *table)
5758 ovs_rwlock_rdlock(&table->cls.rwlock);
5759 ovs_assert(classifier_is_empty(&table->cls));
5760 ovs_rwlock_unlock(&table->cls.rwlock);
5761 oftable_disable_eviction(table);
5762 classifier_destroy(&table->cls);
5766 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
5767 * string, then 'table' will use its default name.
5769 * This only affects the name exposed for a table exposed through the OpenFlow
5770 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
5772 oftable_set_name(struct oftable *table, const char *name)
5774 if (name && name[0]) {
5775 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
5776 if (!table->name || strncmp(name, table->name, len)) {
5778 table->name = xmemdup0(name, len);
5786 /* oftables support a choice of two policies when adding a rule would cause the
5787 * number of flows in the table to exceed the configured maximum number: either
5788 * they can refuse to add the new flow or they can evict some existing flow.
5789 * This function configures the former policy on 'table'. */
5791 oftable_disable_eviction(struct oftable *table)
5793 if (table->eviction_fields) {
5794 struct eviction_group *evg, *next;
5796 HMAP_FOR_EACH_SAFE (evg, next, id_node,
5797 &table->eviction_groups_by_id) {
5798 eviction_group_destroy(table, evg);
5800 hmap_destroy(&table->eviction_groups_by_id);
5801 heap_destroy(&table->eviction_groups_by_size);
5803 free(table->eviction_fields);
5804 table->eviction_fields = NULL;
5805 table->n_eviction_fields = 0;
5809 /* oftables support a choice of two policies when adding a rule would cause the
5810 * number of flows in the table to exceed the configured maximum number: either
5811 * they can refuse to add the new flow or they can evict some existing flow.
5812 * This function configures the latter policy on 'table', with fairness based
5813 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
5814 * 'n_fields' as 0 disables fairness.) */
5816 oftable_enable_eviction(struct oftable *table,
5817 const struct mf_subfield *fields, size_t n_fields)
5819 struct cls_cursor cursor;
5822 if (table->eviction_fields
5823 && n_fields == table->n_eviction_fields
5825 || !memcmp(fields, table->eviction_fields,
5826 n_fields * sizeof *fields))) {
5831 oftable_disable_eviction(table);
5833 table->n_eviction_fields = n_fields;
5834 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
5836 table->eviction_group_id_basis = random_uint32();
5837 hmap_init(&table->eviction_groups_by_id);
5838 heap_init(&table->eviction_groups_by_size);
5840 ovs_rwlock_rdlock(&table->cls.rwlock);
5841 cls_cursor_init(&cursor, &table->cls, NULL);
5842 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
5843 eviction_group_add_rule(rule);
5845 ovs_rwlock_unlock(&table->cls.rwlock);
5848 /* Removes 'rule' from the oftable that contains it. */
5850 oftable_remove_rule__(struct ofproto *ofproto, struct classifier *cls,
5852 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock)
5854 classifier_remove(cls, &rule->cr);
5855 cookies_remove(ofproto, rule);
5856 eviction_group_remove_rule(rule);
5857 ovs_mutex_lock(&ofproto->expirable_mutex);
5858 if (!list_is_empty(&rule->expirable)) {
5859 list_remove(&rule->expirable);
5861 ovs_mutex_unlock(&ofproto->expirable_mutex);
5862 if (!list_is_empty(&rule->meter_list_node)) {
5863 list_remove(&rule->meter_list_node);
5864 list_init(&rule->meter_list_node);
5866 ovs_rwlock_unlock(&rule->rwlock);
5870 oftable_remove_rule(struct rule *rule)
5872 struct ofproto *ofproto = rule->ofproto;
5873 struct oftable *table = &ofproto->tables[rule->table_id];
5875 ovs_rwlock_wrlock(&table->cls.rwlock);
5876 oftable_remove_rule__(ofproto, &table->cls, rule);
5877 ovs_rwlock_unlock(&table->cls.rwlock);
5880 /* Inserts 'rule' into its oftable, which must not already contain any rule for
5881 * the same cls_rule. */
5883 oftable_insert_rule(struct rule *rule)
5885 struct ofproto *ofproto = rule->ofproto;
5886 struct oftable *table = &ofproto->tables[rule->table_id];
5889 ovs_mutex_lock(&rule->timeout_mutex);
5890 may_expire = rule->hard_timeout || rule->idle_timeout;
5891 ovs_mutex_unlock(&rule->timeout_mutex);
5894 ovs_mutex_lock(&ofproto->expirable_mutex);
5895 list_insert(&ofproto->expirable, &rule->expirable);
5896 ovs_mutex_unlock(&ofproto->expirable_mutex);
5898 cookies_insert(ofproto, rule);
5900 if (rule->actions->meter_id) {
5901 struct meter *meter = ofproto->meters[rule->actions->meter_id];
5902 list_insert(&meter->rules, &rule->meter_list_node);
5904 ovs_rwlock_wrlock(&table->cls.rwlock);
5905 classifier_insert(&table->cls, &rule->cr);
5906 ovs_rwlock_unlock(&table->cls.rwlock);
5907 eviction_group_add_rule(rule);
5910 /* unixctl commands. */
5913 ofproto_lookup(const char *name)
5915 struct ofproto *ofproto;
5917 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
5919 if (!strcmp(ofproto->name, name)) {
5927 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
5928 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5930 struct ofproto *ofproto;
5934 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
5935 ds_put_format(&results, "%s\n", ofproto->name);
5937 unixctl_command_reply(conn, ds_cstr(&results));
5938 ds_destroy(&results);
5942 ofproto_unixctl_init(void)
5944 static bool registered;
5950 unixctl_command_register("ofproto/list", "", 0, 0,
5951 ofproto_unixctl_list, NULL);
5954 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5956 * This is deprecated. It is only for compatibility with broken device drivers
5957 * in old versions of Linux that do not properly support VLANs when VLAN
5958 * devices are not used. When broken device drivers are no longer in
5959 * widespread use, we will delete these interfaces. */
5961 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
5962 * (exactly) by an OpenFlow rule in 'ofproto'. */
5964 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
5966 const struct oftable *oftable;
5968 free(ofproto->vlan_bitmap);
5969 ofproto->vlan_bitmap = bitmap_allocate(4096);
5970 ofproto->vlans_changed = false;
5972 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
5973 const struct cls_table *table;
5975 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
5976 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
5977 const struct cls_rule *rule;
5979 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
5980 uint16_t vid = miniflow_get_vid(&rule->match.flow);
5981 bitmap_set1(vlan_bitmap, vid);
5982 bitmap_set1(ofproto->vlan_bitmap, vid);
5989 /* Returns true if new VLANs have come into use by the flow table since the
5990 * last call to ofproto_get_vlan_usage().
5992 * We don't track when old VLANs stop being used. */
5994 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
5996 return ofproto->vlans_changed;
5999 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
6000 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
6001 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
6002 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
6003 * then the VLAN device is un-enslaved. */
6005 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
6006 ofp_port_t realdev_ofp_port, int vid)
6008 struct ofport *ofport;
6011 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
6013 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
6015 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
6016 ofproto->name, vlandev_ofp_port);
6020 if (!ofproto->ofproto_class->set_realdev) {
6021 if (!vlandev_ofp_port) {
6024 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
6028 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
6030 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
6031 ofproto->name, vlandev_ofp_port,
6032 netdev_get_name(ofport->netdev), ovs_strerror(error));