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_flush);
61 COVERAGE_DEFINE(ofproto_packet_out);
62 COVERAGE_DEFINE(ofproto_queue_req);
63 COVERAGE_DEFINE(ofproto_recv_openflow);
64 COVERAGE_DEFINE(ofproto_reinit_ports);
65 COVERAGE_DEFINE(ofproto_update_port);
68 S_OPENFLOW, /* Processing OpenFlow commands. */
69 S_EVICT, /* Evicting flows from over-limit tables. */
70 S_FLUSH, /* Deleting all flow table rules. */
73 enum ofoperation_type {
80 /* A single OpenFlow request can execute any number of operations. The
81 * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
82 * ofconn to which an error reply should be sent if necessary.
84 * ofproto initiates some operations internally. These operations are still
85 * assigned to groups but will not have an associated ofconn. */
87 struct ofproto *ofproto; /* Owning ofproto. */
88 struct list ofproto_node; /* In ofproto's "pending" list. */
89 struct list ops; /* List of "struct ofoperation"s. */
90 int n_running; /* Number of ops still pending. */
92 /* Data needed to send OpenFlow reply on failure or to send a buffered
95 * If list_is_empty(ofconn_node) then this ofopgroup never had an
96 * associated ofconn or its ofconn's connection dropped after it initiated
97 * the operation. In the latter case 'ofconn' is a wild pointer that
98 * refers to freed memory, so the 'ofconn' member must be used only if
99 * !list_is_empty(ofconn_node).
101 struct list ofconn_node; /* In ofconn's list of pending opgroups. */
102 struct ofconn *ofconn; /* ofconn for reply (but see note above). */
103 struct ofp_header *request; /* Original request (truncated at 64 bytes). */
104 uint32_t buffer_id; /* Buffer id from original request. */
107 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
108 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
109 const struct ofp_header *,
111 static void ofopgroup_submit(struct ofopgroup *);
112 static void ofopgroup_complete(struct ofopgroup *);
114 /* A single flow table operation. */
116 struct ofopgroup *group; /* Owning group. */
117 struct list group_node; /* In ofopgroup's "ops" list. */
118 struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
119 struct rule *rule; /* Rule being operated upon. */
120 enum ofoperation_type type; /* Type of operation. */
122 /* OFOPERATION_MODIFY, OFOPERATION_REPLACE: The old actions, if the actions
124 struct rule_actions *actions;
126 /* OFOPERATION_DELETE. */
127 enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
129 ovs_be64 flow_cookie; /* Rule's old flow cookie. */
130 uint16_t idle_timeout; /* Rule's old idle timeout. */
131 uint16_t hard_timeout; /* Rule's old hard timeout. */
132 enum ofputil_flow_mod_flags flags; /* Rule's old flags. */
133 enum ofperr error; /* 0 if no error. */
136 static struct ofoperation *ofoperation_create(struct ofopgroup *,
138 enum ofoperation_type,
139 enum ofp_flow_removed_reason);
140 static void ofoperation_destroy(struct ofoperation *);
143 static void oftable_init(struct oftable *);
144 static void oftable_destroy(struct oftable *);
146 static void oftable_set_name(struct oftable *, const char *name);
148 static void oftable_disable_eviction(struct oftable *);
149 static void oftable_enable_eviction(struct oftable *,
150 const struct mf_subfield *fields,
153 static void oftable_remove_rule(struct rule *rule) OVS_REQUIRES(ofproto_mutex);
154 static void oftable_remove_rule__(struct ofproto *, struct rule *)
155 OVS_REQUIRES(ofproto_mutex);
156 static void oftable_insert_rule(struct rule *);
158 /* A set of rules within a single OpenFlow table (oftable) that have the same
159 * values for the oftable's eviction_fields. A rule to be evicted, when one is
160 * needed, is taken from the eviction group that contains the greatest number
163 * An oftable owns any number of eviction groups, each of which contains any
166 * Membership in an eviction group is imprecise, based on the hash of the
167 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
168 * That is, if two rules have different eviction_fields, but those
169 * eviction_fields hash to the same value, then they will belong to the same
170 * eviction_group anyway.
172 * (When eviction is not enabled on an oftable, we don't track any eviction
173 * groups, to save time and space.) */
174 struct eviction_group {
175 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
176 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
177 struct heap rules; /* Contains "struct rule"s. */
180 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep);
181 static void ofproto_evict(struct ofproto *) OVS_EXCLUDED(ofproto_mutex);
182 static uint32_t rule_eviction_priority(struct rule *);
183 static void eviction_group_add_rule(struct rule *);
184 static void eviction_group_remove_rule(struct rule *);
186 /* Criteria that flow_mod and other operations use for selecting rules on
187 * which to operate. */
188 struct rule_criteria {
189 /* An OpenFlow table or 255 for all tables. */
192 /* OpenFlow matching criteria. Interpreted different in "loose" way by
193 * collect_rules_loose() and "strict" way by collect_rules_strict(), as
194 * defined in the OpenFlow spec. */
197 /* Matching criteria for the OpenFlow cookie. Consider a bit B in a rule's
198 * cookie and the corresponding bits C in 'cookie' and M in 'cookie_mask'.
199 * The rule will not be selected if M is 1 and B != C. */
201 ovs_be64 cookie_mask;
203 /* Selection based on actions within a rule:
205 * If out_port != OFPP_ANY, selects only rules that output to out_port.
206 * If out_group != OFPG_ALL, select only rules that output to out_group. */
211 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
212 const struct match *match,
213 unsigned int priority,
214 ovs_be64 cookie, ovs_be64 cookie_mask,
215 ofp_port_t out_port, uint32_t out_group);
216 static void rule_criteria_destroy(struct rule_criteria *);
218 /* A packet that needs to be passed to rule_execute().
220 * (We can't do this immediately from ofopgroup_complete() because that holds
221 * ofproto_mutex, which rule_execute() needs released.) */
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 *) OVS_EXCLUDED(ofproto_mutex);
230 static void destroy_rule_executes(struct ofproto *);
233 static void ofport_destroy__(struct ofport *) OVS_EXCLUDED(ofproto_mutex);
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 *);
240 static long long int ofport_get_usage(const struct ofproto *,
241 ofp_port_t ofp_port);
242 static void ofport_set_usage(struct ofproto *, ofp_port_t ofp_port,
243 long long int last_used);
244 static void ofport_remove_usage(struct ofproto *, ofp_port_t ofp_port);
248 * Keeps track of the currently used and recently used ofport values and is
249 * used to prevent immediate recycling of ofport values. */
250 struct ofport_usage {
251 struct hmap_node hmap_node; /* In struct ofproto's "ofport_usage" hmap. */
252 ofp_port_t ofp_port; /* OpenFlow port number. */
253 long long int last_used; /* Last time the 'ofp_port' was used. LLONG_MAX
254 represents in-use ofports. */
258 static void ofproto_rule_destroy__(struct rule *);
259 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
260 static bool rule_is_modifiable(const struct rule *);
263 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
264 struct ofputil_flow_mod *,
265 const struct ofp_header *);
266 static enum ofperr modify_flows__(struct ofproto *, struct ofconn *,
267 struct ofputil_flow_mod *,
268 const struct ofp_header *,
269 const struct rule_collection *);
270 static void delete_flow__(struct rule *rule, struct ofopgroup *,
271 enum ofp_flow_removed_reason)
272 OVS_REQUIRES(ofproto_mutex);
273 static enum ofperr add_group(struct ofproto *, struct ofputil_group_mod *);
274 static bool handle_openflow(struct ofconn *, const struct ofpbuf *);
275 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
276 struct ofputil_flow_mod *,
277 const struct ofp_header *)
278 OVS_EXCLUDED(ofproto_mutex);
279 static void calc_duration(long long int start, long long int now,
280 uint32_t *sec, uint32_t *nsec);
283 static uint64_t pick_datapath_id(const struct ofproto *);
284 static uint64_t pick_fallback_dpid(void);
285 static void ofproto_destroy__(struct ofproto *);
286 static void update_mtu(struct ofproto *, struct ofport *);
287 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
290 static void ofproto_unixctl_init(void);
292 /* All registered ofproto classes, in probe order. */
293 static const struct ofproto_class **ofproto_classes;
294 static size_t n_ofproto_classes;
295 static size_t allocated_ofproto_classes;
297 /* Global lock that protects all flow table operations. */
298 struct ovs_mutex ofproto_mutex = OVS_MUTEX_INITIALIZER;
300 unsigned flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT;
301 unsigned n_handler_threads;
302 enum ofproto_flow_miss_model flow_miss_model = OFPROTO_HANDLE_MISS_AUTO;
304 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
305 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
307 /* Initial mappings of port to OpenFlow number mappings. */
308 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
310 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
312 /* The default value of true waits for flow restore. */
313 static bool flow_restore_wait = true;
315 /* Must be called to initialize the ofproto library.
317 * The caller may pass in 'iface_hints', which contains an shash of
318 * "iface_hint" elements indexed by the interface's name. The provider
319 * may use these hints to describe the startup configuration in order to
320 * reinitialize its state. The caller owns the provided data, so a
321 * provider will make copies of anything required. An ofproto provider
322 * will remove any existing state that is not described by the hint, and
323 * may choose to remove it all. */
325 ofproto_init(const struct shash *iface_hints)
327 struct shash_node *node;
330 ofproto_class_register(&ofproto_dpif_class);
332 /* Make a local copy, since we don't own 'iface_hints' elements. */
333 SHASH_FOR_EACH(node, iface_hints) {
334 const struct iface_hint *orig_hint = node->data;
335 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
336 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
338 new_hint->br_name = xstrdup(orig_hint->br_name);
339 new_hint->br_type = xstrdup(br_type);
340 new_hint->ofp_port = orig_hint->ofp_port;
342 shash_add(&init_ofp_ports, node->name, new_hint);
345 for (i = 0; i < n_ofproto_classes; i++) {
346 ofproto_classes[i]->init(&init_ofp_ports);
350 /* 'type' should be a normalized datapath type, as returned by
351 * ofproto_normalize_type(). Returns the corresponding ofproto_class
352 * structure, or a null pointer if there is none registered for 'type'. */
353 static const struct ofproto_class *
354 ofproto_class_find__(const char *type)
358 for (i = 0; i < n_ofproto_classes; i++) {
359 const struct ofproto_class *class = ofproto_classes[i];
364 class->enumerate_types(&types);
365 found = sset_contains(&types, type);
366 sset_destroy(&types);
372 VLOG_WARN("unknown datapath type %s", type);
376 /* Registers a new ofproto class. After successful registration, new ofprotos
377 * of that type can be created using ofproto_create(). */
379 ofproto_class_register(const struct ofproto_class *new_class)
383 for (i = 0; i < n_ofproto_classes; i++) {
384 if (ofproto_classes[i] == new_class) {
389 if (n_ofproto_classes >= allocated_ofproto_classes) {
390 ofproto_classes = x2nrealloc(ofproto_classes,
391 &allocated_ofproto_classes,
392 sizeof *ofproto_classes);
394 ofproto_classes[n_ofproto_classes++] = new_class;
398 /* Unregisters a datapath provider. 'type' must have been previously
399 * registered and not currently be in use by any ofprotos. After
400 * unregistration new datapaths of that type cannot be opened using
401 * ofproto_create(). */
403 ofproto_class_unregister(const struct ofproto_class *class)
407 for (i = 0; i < n_ofproto_classes; i++) {
408 if (ofproto_classes[i] == class) {
409 for (i++; i < n_ofproto_classes; i++) {
410 ofproto_classes[i - 1] = ofproto_classes[i];
416 VLOG_WARN("attempted to unregister an ofproto class that is not "
421 /* Clears 'types' and enumerates all registered ofproto types into it. The
422 * caller must first initialize the sset. */
424 ofproto_enumerate_types(struct sset *types)
428 for (i = 0; i < n_ofproto_classes; i++) {
429 ofproto_classes[i]->enumerate_types(types);
433 /* Returns the fully spelled out name for the given ofproto 'type'.
435 * Normalized type string can be compared with strcmp(). Unnormalized type
436 * string might be the same even if they have different spellings. */
438 ofproto_normalize_type(const char *type)
440 return type && type[0] ? type : "system";
443 /* Clears 'names' and enumerates the names of all known created ofprotos with
444 * the given 'type'. The caller must first initialize the sset. Returns 0 if
445 * successful, otherwise a positive errno value.
447 * Some kinds of datapaths might not be practically enumerable. This is not
448 * considered an error. */
450 ofproto_enumerate_names(const char *type, struct sset *names)
452 const struct ofproto_class *class = ofproto_class_find__(type);
453 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
457 ofproto_create(const char *datapath_name, const char *datapath_type,
458 struct ofproto **ofprotop)
460 const struct ofproto_class *class;
461 struct ofproto *ofproto;
467 ofproto_unixctl_init();
469 datapath_type = ofproto_normalize_type(datapath_type);
470 class = ofproto_class_find__(datapath_type);
472 VLOG_WARN("could not create datapath %s of unknown type %s",
473 datapath_name, datapath_type);
477 ofproto = class->alloc();
479 VLOG_ERR("failed to allocate datapath %s of type %s",
480 datapath_name, datapath_type);
485 ovs_mutex_lock(&ofproto_mutex);
486 memset(ofproto, 0, sizeof *ofproto);
487 ofproto->ofproto_class = class;
488 ofproto->name = xstrdup(datapath_name);
489 ofproto->type = xstrdup(datapath_type);
490 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
491 hash_string(ofproto->name, 0));
492 ofproto->datapath_id = 0;
493 ofproto->forward_bpdu = false;
494 ofproto->fallback_dpid = pick_fallback_dpid();
495 ofproto->mfr_desc = NULL;
496 ofproto->hw_desc = NULL;
497 ofproto->sw_desc = NULL;
498 ofproto->serial_desc = NULL;
499 ofproto->dp_desc = NULL;
500 ofproto->frag_handling = OFPC_FRAG_NORMAL;
501 hmap_init(&ofproto->ports);
502 hmap_init(&ofproto->ofport_usage);
503 shash_init(&ofproto->port_by_name);
504 simap_init(&ofproto->ofp_requests);
505 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
506 ofproto->eviction_group_timer = LLONG_MIN;
507 ofproto->tables = NULL;
508 ofproto->n_tables = 0;
509 hindex_init(&ofproto->cookies);
510 list_init(&ofproto->expirable);
511 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
512 ofproto->state = S_OPENFLOW;
513 list_init(&ofproto->pending);
514 ofproto->n_pending = 0;
515 hmap_init(&ofproto->deletions);
516 guarded_list_init(&ofproto->rule_executes);
517 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
518 ofproto->first_op = ofproto->last_op = LLONG_MIN;
519 ofproto->next_op_report = LLONG_MAX;
520 ofproto->op_backoff = LLONG_MIN;
521 ofproto->vlan_bitmap = NULL;
522 ofproto->vlans_changed = false;
523 ofproto->min_mtu = INT_MAX;
524 ovs_rwlock_init(&ofproto->groups_rwlock);
525 hmap_init(&ofproto->groups);
526 ovs_mutex_unlock(&ofproto_mutex);
528 error = ofproto->ofproto_class->construct(ofproto);
530 VLOG_ERR("failed to open datapath %s: %s",
531 datapath_name, ovs_strerror(error));
532 ofproto_destroy__(ofproto);
536 /* Check that hidden tables, if any, are at the end. */
537 ovs_assert(ofproto->n_tables);
538 for (i = 0; i + 1 < ofproto->n_tables; i++) {
539 enum oftable_flags flags = ofproto->tables[i].flags;
540 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
542 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
545 ofproto->datapath_id = pick_datapath_id(ofproto);
548 /* Initialize meters table. */
549 if (ofproto->ofproto_class->meter_get_features) {
550 ofproto->ofproto_class->meter_get_features(ofproto,
551 &ofproto->meter_features);
553 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
555 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
556 * sizeof(struct meter *));
562 /* Must be called (only) by an ofproto implementation in its constructor
563 * function. See the large comment on 'construct' in struct ofproto_class for
566 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
568 struct oftable *table;
570 ovs_assert(!ofproto->n_tables);
571 ovs_assert(n_tables >= 1 && n_tables <= 255);
573 ofproto->n_tables = n_tables;
574 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
575 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
580 /* To be optionally called (only) by an ofproto implementation in its
581 * constructor function. See the large comment on 'construct' in struct
582 * ofproto_class for details.
584 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
585 * will then ensure that actions passed into the ofproto implementation will
586 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
587 * function is not called, there will be no such restriction.
589 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
590 * the 'max_ports' restriction. */
592 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
594 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
595 ofproto->max_ports = max_ports;
599 ofproto_get_datapath_id(const struct ofproto *ofproto)
601 return ofproto->datapath_id;
605 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
607 uint64_t old_dpid = p->datapath_id;
608 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
609 if (p->datapath_id != old_dpid) {
610 /* Force all active connections to reconnect, since there is no way to
611 * notify a controller that the datapath ID has changed. */
612 ofproto_reconnect_controllers(p);
617 ofproto_set_controllers(struct ofproto *p,
618 const struct ofproto_controller *controllers,
619 size_t n_controllers, uint32_t allowed_versions)
621 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
626 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
628 connmgr_set_fail_mode(p->connmgr, fail_mode);
631 /* Drops the connections between 'ofproto' and all of its controllers, forcing
632 * them to reconnect. */
634 ofproto_reconnect_controllers(struct ofproto *ofproto)
636 connmgr_reconnect(ofproto->connmgr);
639 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
640 * in-band control should guarantee access, in the same way that in-band
641 * control guarantees access to OpenFlow controllers. */
643 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
644 const struct sockaddr_in *extras, size_t n)
646 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
649 /* Sets the OpenFlow queue used by flows set up by in-band control on
650 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
651 * flows will use the default queue. */
653 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
655 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
658 /* Sets the number of flows at which eviction from the kernel flow table
661 ofproto_set_flow_eviction_threshold(unsigned threshold)
663 flow_eviction_threshold = MAX(OFPROTO_FLOW_EVICTION_THRESHOLD_MIN,
667 /* Sets the path for handling flow misses. */
669 ofproto_set_flow_miss_model(unsigned model)
671 flow_miss_model = model;
674 /* If forward_bpdu is true, the NORMAL action will forward frames with
675 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
676 * the NORMAL action will drop these frames. */
678 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
680 bool old_val = ofproto->forward_bpdu;
681 ofproto->forward_bpdu = forward_bpdu;
682 if (old_val != ofproto->forward_bpdu) {
683 if (ofproto->ofproto_class->forward_bpdu_changed) {
684 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
689 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
690 * 'idle_time', in seconds, and the maximum number of MAC table entries to
693 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
696 if (ofproto->ofproto_class->set_mac_table_config) {
697 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
702 /* Sets number of upcall handler threads. The default is
703 * (number of online cores - 2). */
705 ofproto_set_n_handler_threads(unsigned limit)
708 n_handler_threads = limit;
710 int n_proc = sysconf(_SC_NPROCESSORS_ONLN);
711 n_handler_threads = n_proc > 2 ? n_proc - 2 : 1;
716 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
719 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
723 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
725 return connmgr_set_snoops(ofproto->connmgr, snoops);
729 ofproto_set_netflow(struct ofproto *ofproto,
730 const struct netflow_options *nf_options)
732 if (nf_options && sset_is_empty(&nf_options->collectors)) {
736 if (ofproto->ofproto_class->set_netflow) {
737 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
739 return nf_options ? EOPNOTSUPP : 0;
744 ofproto_set_sflow(struct ofproto *ofproto,
745 const struct ofproto_sflow_options *oso)
747 if (oso && sset_is_empty(&oso->targets)) {
751 if (ofproto->ofproto_class->set_sflow) {
752 return ofproto->ofproto_class->set_sflow(ofproto, oso);
754 return oso ? EOPNOTSUPP : 0;
759 ofproto_set_ipfix(struct ofproto *ofproto,
760 const struct ofproto_ipfix_bridge_exporter_options *bo,
761 const struct ofproto_ipfix_flow_exporter_options *fo,
764 if (ofproto->ofproto_class->set_ipfix) {
765 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
767 return (bo || fo) ? EOPNOTSUPP : 0;
772 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
774 flow_restore_wait = flow_restore_wait_db;
778 ofproto_get_flow_restore_wait(void)
780 return flow_restore_wait;
784 /* Spanning Tree Protocol (STP) configuration. */
786 /* Configures STP on 'ofproto' using the settings defined in 's'. If
787 * 's' is NULL, disables STP.
789 * Returns 0 if successful, otherwise a positive errno value. */
791 ofproto_set_stp(struct ofproto *ofproto,
792 const struct ofproto_stp_settings *s)
794 return (ofproto->ofproto_class->set_stp
795 ? ofproto->ofproto_class->set_stp(ofproto, s)
799 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
800 * 'enabled' member of 's' is false, then the other members are not
803 * Returns 0 if successful, otherwise a positive errno value. */
805 ofproto_get_stp_status(struct ofproto *ofproto,
806 struct ofproto_stp_status *s)
808 return (ofproto->ofproto_class->get_stp_status
809 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
813 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
814 * in 's'. The caller is responsible for assigning STP port numbers
815 * (using the 'port_num' member in the range of 1 through 255, inclusive)
816 * and ensuring there are no duplicates. If the 's' is NULL, then STP
817 * is disabled on the port.
819 * Returns 0 if successful, otherwise a positive errno value.*/
821 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
822 const struct ofproto_port_stp_settings *s)
824 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
826 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
827 ofproto->name, ofp_port);
831 return (ofproto->ofproto_class->set_stp_port
832 ? ofproto->ofproto_class->set_stp_port(ofport, s)
836 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
837 * 's'. If the 'enabled' member in 's' is false, then the other members
838 * are not meaningful.
840 * Returns 0 if successful, otherwise a positive errno value.*/
842 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
843 struct ofproto_port_stp_status *s)
845 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
847 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
848 "port %"PRIu16, ofproto->name, ofp_port);
852 return (ofproto->ofproto_class->get_stp_port_status
853 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
857 /* Queue DSCP configuration. */
859 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
860 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
861 * to implement QoS. Instead, it is used to implement features which require
862 * knowledge of what queues exist on a port, and some basic information about
865 * Returns 0 if successful, otherwise a positive errno value. */
867 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
868 const struct ofproto_port_queue *queues,
871 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
874 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
875 ofproto->name, ofp_port);
879 return (ofproto->ofproto_class->set_queues
880 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
884 /* Connectivity Fault Management configuration. */
886 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
888 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
890 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
891 if (ofport && ofproto->ofproto_class->set_cfm) {
892 ofproto->ofproto_class->set_cfm(ofport, NULL);
896 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
897 * basic configuration from the configuration members in 'cfm', and the remote
898 * maintenance point ID from remote_mpid. Ignores the statistics members of
901 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
903 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
904 const struct cfm_settings *s)
906 struct ofport *ofport;
909 ofport = ofproto_get_port(ofproto, ofp_port);
911 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
912 ofproto->name, ofp_port);
916 /* XXX: For configuration simplicity, we only support one remote_mpid
917 * outside of the CFM module. It's not clear if this is the correct long
918 * term solution or not. */
919 error = (ofproto->ofproto_class->set_cfm
920 ? ofproto->ofproto_class->set_cfm(ofport, s)
923 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
924 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
925 ovs_strerror(error));
929 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
930 * 'ofproto' does not have a port 'ofp_port'. */
932 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
933 const struct smap *cfg)
935 struct ofport *ofport;
938 ofport = ofproto_get_port(ofproto, ofp_port);
940 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
941 ofproto->name, ofp_port);
945 error = (ofproto->ofproto_class->set_bfd
946 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
949 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
950 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
951 ovs_strerror(error));
955 /* Populates 'status' with key value pairs indicating the status of the BFD
956 * session on 'ofp_port'. This information is intended to be populated in the
957 * OVS database. Has no effect if 'ofp_port' is not na OpenFlow port in
960 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
963 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
964 return (ofport && ofproto->ofproto_class->get_bfd_status
965 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
969 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
970 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
971 * 0 if LACP partner information is not current (generally indicating a
972 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
974 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
976 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
977 return (ofport && ofproto->ofproto_class->port_is_lacp_current
978 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
984 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
985 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
986 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
987 * configuration plus, if there is more than one slave, a bonding
990 * If 'aux' is already registered then this function updates its configuration
991 * to 's'. Otherwise, this function registers a new bundle.
993 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
996 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
997 const struct ofproto_bundle_settings *s)
999 return (ofproto->ofproto_class->bundle_set
1000 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1004 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1005 * If no such bundle has been registered, this has no effect. */
1007 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1009 return ofproto_bundle_register(ofproto, aux, NULL);
1013 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1014 * If 'aux' is already registered then this function updates its configuration
1015 * to 's'. Otherwise, this function registers a new mirror. */
1017 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1018 const struct ofproto_mirror_settings *s)
1020 return (ofproto->ofproto_class->mirror_set
1021 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1025 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1026 * If no mirror has been registered, this has no effect. */
1028 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1030 return ofproto_mirror_register(ofproto, aux, NULL);
1033 /* Retrieves statistics from mirror associated with client data pointer
1034 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1035 * 'bytes', respectively. If a particular counters is not supported,
1036 * the appropriate argument is set to UINT64_MAX. */
1038 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1039 uint64_t *packets, uint64_t *bytes)
1041 if (!ofproto->ofproto_class->mirror_get_stats) {
1042 *packets = *bytes = UINT64_MAX;
1046 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1050 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1051 * which all packets are flooded, instead of using MAC learning. If
1052 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1054 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1057 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1059 return (ofproto->ofproto_class->set_flood_vlans
1060 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1064 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1065 * output for a mirror. */
1067 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1069 return (ofproto->ofproto_class->is_mirror_output_bundle
1070 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1074 /* Configuration of OpenFlow tables. */
1076 /* Returns the number of OpenFlow tables in 'ofproto'. */
1078 ofproto_get_n_tables(const struct ofproto *ofproto)
1080 return ofproto->n_tables;
1083 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1084 * settings from 's'. 'table_id' must be in the range 0 through the number of
1085 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1087 * For read-only tables, only the name may be configured. */
1089 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1090 const struct ofproto_table_settings *s)
1092 struct oftable *table;
1094 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1095 table = &ofproto->tables[table_id];
1097 oftable_set_name(table, s->name);
1099 if (table->flags & OFTABLE_READONLY) {
1104 oftable_enable_eviction(table, s->groups, s->n_groups);
1106 oftable_disable_eviction(table);
1109 table->max_flows = s->max_flows;
1110 ovs_rwlock_rdlock(&table->cls.rwlock);
1111 if (classifier_count(&table->cls) > table->max_flows
1112 && table->eviction_fields) {
1113 /* 'table' contains more flows than allowed. We might not be able to
1114 * evict them right away because of the asynchronous nature of flow
1115 * table changes. Schedule eviction for later. */
1116 switch (ofproto->state) {
1118 ofproto->state = S_EVICT;
1122 /* We're already deleting flows, nothing more to do. */
1126 ovs_rwlock_unlock(&table->cls.rwlock);
1130 ofproto_has_snoops(const struct ofproto *ofproto)
1132 return connmgr_has_snoops(ofproto->connmgr);
1136 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1138 connmgr_get_snoops(ofproto->connmgr, snoops);
1142 ofproto_rule_delete__(struct ofproto *ofproto, struct rule *rule,
1144 OVS_REQUIRES(ofproto_mutex)
1146 struct ofopgroup *group;
1148 ovs_assert(!rule->pending);
1150 group = ofopgroup_create_unattached(ofproto);
1151 delete_flow__(rule, group, reason);
1152 ofopgroup_submit(group);
1155 /* Deletes 'rule' from 'cls' within 'ofproto'.
1157 * Within an ofproto implementation, this function allows an ofproto
1158 * implementation to destroy any rules that remain when its ->destruct()
1159 * function is called. This function is not suitable for use elsewhere in an
1160 * ofproto implementation.
1162 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1163 * Cycle" in ofproto-provider.h. */
1165 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1166 OVS_EXCLUDED(ofproto_mutex)
1168 struct ofopgroup *group;
1170 ovs_mutex_lock(&ofproto_mutex);
1171 ovs_assert(!rule->pending);
1173 group = ofopgroup_create_unattached(ofproto);
1174 ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1175 oftable_remove_rule__(ofproto, rule);
1176 ofproto->ofproto_class->rule_delete(rule);
1177 ofopgroup_submit(group);
1179 ovs_mutex_unlock(&ofproto_mutex);
1183 ofproto_flush__(struct ofproto *ofproto)
1184 OVS_EXCLUDED(ofproto_mutex)
1186 struct oftable *table;
1188 if (ofproto->ofproto_class->flush) {
1189 ofproto->ofproto_class->flush(ofproto);
1192 ovs_mutex_lock(&ofproto_mutex);
1193 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1194 struct rule *rule, *next_rule;
1195 struct cls_cursor cursor;
1197 if (table->flags & OFTABLE_HIDDEN) {
1201 ovs_rwlock_rdlock(&table->cls.rwlock);
1202 cls_cursor_init(&cursor, &table->cls, NULL);
1203 ovs_rwlock_unlock(&table->cls.rwlock);
1204 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1205 if (!rule->pending) {
1206 ofproto_rule_delete__(ofproto, rule, OFPRR_DELETE);
1210 ovs_mutex_unlock(&ofproto_mutex);
1213 static void delete_group(struct ofproto *ofproto, uint32_t group_id);
1216 ofproto_destroy__(struct ofproto *ofproto)
1217 OVS_EXCLUDED(ofproto_mutex)
1219 struct oftable *table;
1221 ovs_assert(list_is_empty(&ofproto->pending));
1223 destroy_rule_executes(ofproto);
1224 guarded_list_destroy(&ofproto->rule_executes);
1226 delete_group(ofproto, OFPG_ALL);
1227 ovs_rwlock_destroy(&ofproto->groups_rwlock);
1228 hmap_destroy(&ofproto->groups);
1230 connmgr_destroy(ofproto->connmgr);
1232 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1233 free(ofproto->name);
1234 free(ofproto->type);
1235 free(ofproto->mfr_desc);
1236 free(ofproto->hw_desc);
1237 free(ofproto->sw_desc);
1238 free(ofproto->serial_desc);
1239 free(ofproto->dp_desc);
1240 hmap_destroy(&ofproto->ports);
1241 hmap_destroy(&ofproto->ofport_usage);
1242 shash_destroy(&ofproto->port_by_name);
1243 simap_destroy(&ofproto->ofp_requests);
1245 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1246 oftable_destroy(table);
1248 free(ofproto->tables);
1250 hmap_destroy(&ofproto->deletions);
1252 free(ofproto->vlan_bitmap);
1254 ofproto->ofproto_class->dealloc(ofproto);
1258 ofproto_destroy(struct ofproto *p)
1259 OVS_EXCLUDED(ofproto_mutex)
1261 struct ofport *ofport, *next_ofport;
1262 struct ofport_usage *usage, *next_usage;
1269 meter_delete(p, 1, p->meter_features.max_meters);
1270 p->meter_features.max_meters = 0;
1276 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1277 ofport_destroy(ofport);
1280 HMAP_FOR_EACH_SAFE (usage, next_usage, hmap_node, &p->ofport_usage) {
1281 hmap_remove(&p->ofport_usage, &usage->hmap_node);
1285 p->ofproto_class->destruct(p);
1286 ofproto_destroy__(p);
1289 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1290 * kernel datapath, for example, this destroys the datapath in the kernel, and
1291 * with the netdev-based datapath, it tears down the data structures that
1292 * represent the datapath.
1294 * The datapath should not be currently open as an ofproto. */
1296 ofproto_delete(const char *name, const char *type)
1298 const struct ofproto_class *class = ofproto_class_find__(type);
1299 return (!class ? EAFNOSUPPORT
1300 : !class->del ? EACCES
1301 : class->del(type, name));
1305 process_port_change(struct ofproto *ofproto, int error, char *devname)
1307 if (error == ENOBUFS) {
1308 reinit_ports(ofproto);
1309 } else if (!error) {
1310 update_port(ofproto, devname);
1316 ofproto_type_run(const char *datapath_type)
1318 const struct ofproto_class *class;
1321 datapath_type = ofproto_normalize_type(datapath_type);
1322 class = ofproto_class_find__(datapath_type);
1324 error = class->type_run ? class->type_run(datapath_type) : 0;
1325 if (error && error != EAGAIN) {
1326 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1327 datapath_type, ovs_strerror(error));
1333 ofproto_type_run_fast(const char *datapath_type)
1335 const struct ofproto_class *class;
1338 datapath_type = ofproto_normalize_type(datapath_type);
1339 class = ofproto_class_find__(datapath_type);
1341 error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1342 if (error && error != EAGAIN) {
1343 VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1344 datapath_type, ovs_strerror(error));
1350 ofproto_type_wait(const char *datapath_type)
1352 const struct ofproto_class *class;
1354 datapath_type = ofproto_normalize_type(datapath_type);
1355 class = ofproto_class_find__(datapath_type);
1357 if (class->type_wait) {
1358 class->type_wait(datapath_type);
1363 any_pending_ops(const struct ofproto *p)
1364 OVS_EXCLUDED(ofproto_mutex)
1368 ovs_mutex_lock(&ofproto_mutex);
1369 b = !list_is_empty(&p->pending);
1370 ovs_mutex_unlock(&ofproto_mutex);
1376 ofproto_run(struct ofproto *p)
1378 struct sset changed_netdevs;
1379 const char *changed_netdev;
1380 struct ofport *ofport;
1383 error = p->ofproto_class->run(p);
1384 if (error && error != EAGAIN) {
1385 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1388 run_rule_executes(p);
1390 /* Restore the eviction group heap invariant occasionally. */
1391 if (p->eviction_group_timer < time_msec()) {
1394 p->eviction_group_timer = time_msec() + 1000;
1396 for (i = 0; i < p->n_tables; i++) {
1397 struct oftable *table = &p->tables[i];
1398 struct eviction_group *evg;
1399 struct cls_cursor cursor;
1402 if (!table->eviction_fields) {
1406 ovs_mutex_lock(&ofproto_mutex);
1407 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1408 heap_rebuild(&evg->rules);
1411 ovs_rwlock_rdlock(&table->cls.rwlock);
1412 cls_cursor_init(&cursor, &table->cls, NULL);
1413 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1414 if (!rule->eviction_group
1415 && (rule->idle_timeout || rule->hard_timeout)) {
1416 eviction_group_add_rule(rule);
1419 ovs_rwlock_unlock(&table->cls.rwlock);
1420 ovs_mutex_unlock(&ofproto_mutex);
1424 if (p->ofproto_class->port_poll) {
1427 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1428 process_port_change(p, error, devname);
1432 /* Update OpenFlow port status for any port whose netdev has changed.
1434 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1435 * destroyed, so it's not safe to update ports directly from the
1436 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1437 * need this two-phase approach. */
1438 sset_init(&changed_netdevs);
1439 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1440 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1441 if (ofport->change_seq != change_seq) {
1442 ofport->change_seq = change_seq;
1443 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1446 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1447 update_port(p, changed_netdev);
1449 sset_destroy(&changed_netdevs);
1453 connmgr_run(p->connmgr, handle_openflow);
1457 connmgr_run(p->connmgr, NULL);
1459 if (!any_pending_ops(p)) {
1460 p->state = S_OPENFLOW;
1465 connmgr_run(p->connmgr, NULL);
1467 if (!any_pending_ops(p)) {
1468 connmgr_flushed(p->connmgr);
1469 p->state = S_OPENFLOW;
1477 if (time_msec() >= p->next_op_report) {
1478 long long int ago = (time_msec() - p->first_op) / 1000;
1479 long long int interval = (p->last_op - p->first_op) / 1000;
1483 ds_put_format(&s, "%d flow_mods ",
1484 p->n_add + p->n_delete + p->n_modify);
1485 if (interval == ago) {
1486 ds_put_format(&s, "in the last %lld s", ago);
1487 } else if (interval) {
1488 ds_put_format(&s, "in the %lld s starting %lld s ago",
1491 ds_put_format(&s, "%lld s ago", ago);
1494 ds_put_cstr(&s, " (");
1496 ds_put_format(&s, "%d adds, ", p->n_add);
1499 ds_put_format(&s, "%d deletes, ", p->n_delete);
1502 ds_put_format(&s, "%d modifications, ", p->n_modify);
1505 ds_put_char(&s, ')');
1507 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1510 p->n_add = p->n_delete = p->n_modify = 0;
1511 p->next_op_report = LLONG_MAX;
1517 /* Performs periodic activity required by 'ofproto' that needs to be done
1518 * with the least possible latency.
1520 * It makes sense to call this function a couple of times per poll loop, to
1521 * provide a significant performance boost on some benchmarks with the
1522 * ofproto-dpif implementation. */
1524 ofproto_run_fast(struct ofproto *p)
1528 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1529 if (error && error != EAGAIN) {
1530 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1531 p->name, ovs_strerror(error));
1537 ofproto_wait(struct ofproto *p)
1539 struct ofport *ofport;
1541 p->ofproto_class->wait(p);
1542 if (p->ofproto_class->port_poll_wait) {
1543 p->ofproto_class->port_poll_wait(p);
1546 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1547 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1548 poll_immediate_wake();
1554 connmgr_wait(p->connmgr, true);
1559 connmgr_wait(p->connmgr, false);
1560 if (!any_pending_ops(p)) {
1561 poll_immediate_wake();
1568 ofproto_is_alive(const struct ofproto *p)
1570 return connmgr_has_controllers(p->connmgr);
1573 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1574 * memory_report(). */
1576 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1578 const struct oftable *table;
1579 unsigned int n_rules;
1581 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1583 ovs_mutex_lock(&ofproto_mutex);
1584 simap_increase(usage, "ops",
1585 ofproto->n_pending + hmap_count(&ofproto->deletions));
1586 ovs_mutex_unlock(&ofproto_mutex);
1589 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1590 ovs_rwlock_rdlock(&table->cls.rwlock);
1591 n_rules += classifier_count(&table->cls);
1592 ovs_rwlock_unlock(&table->cls.rwlock);
1594 simap_increase(usage, "rules", n_rules);
1596 if (ofproto->ofproto_class->get_memory_usage) {
1597 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1600 connmgr_get_memory_usage(ofproto->connmgr, usage);
1604 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1607 connmgr_get_controller_info(ofproto->connmgr, info);
1611 ofproto_free_ofproto_controller_info(struct shash *info)
1613 connmgr_free_controller_info(info);
1616 /* Makes a deep copy of 'old' into 'port'. */
1618 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1620 port->name = xstrdup(old->name);
1621 port->type = xstrdup(old->type);
1622 port->ofp_port = old->ofp_port;
1625 /* Frees memory allocated to members of 'ofproto_port'.
1627 * Do not call this function on an ofproto_port obtained from
1628 * ofproto_port_dump_next(): that function retains ownership of the data in the
1631 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1633 free(ofproto_port->name);
1634 free(ofproto_port->type);
1637 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1639 * This function provides no status indication. An error status for the entire
1640 * dump operation is provided when it is completed by calling
1641 * ofproto_port_dump_done().
1644 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1645 const struct ofproto *ofproto)
1647 dump->ofproto = ofproto;
1648 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1652 /* Attempts to retrieve another port from 'dump', which must have been created
1653 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1654 * 'port' and returns true. On failure, returns false.
1656 * Failure might indicate an actual error or merely that the last port has been
1657 * dumped. An error status for the entire dump operation is provided when it
1658 * is completed by calling ofproto_port_dump_done().
1660 * The ofproto owns the data stored in 'port'. It will remain valid until at
1661 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1662 * ofproto_port_dump_done(). */
1664 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1665 struct ofproto_port *port)
1667 const struct ofproto *ofproto = dump->ofproto;
1673 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1676 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1682 /* Completes port table dump operation 'dump', which must have been created
1683 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1684 * error-free, otherwise a positive errno value describing the problem. */
1686 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1688 const struct ofproto *ofproto = dump->ofproto;
1690 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1693 return dump->error == EOF ? 0 : dump->error;
1696 /* Returns the type to pass to netdev_open() when a datapath of type
1697 * 'datapath_type' has a port of type 'port_type', for a few special
1698 * cases when a netdev type differs from a port type. For example, when
1699 * using the userspace datapath, a port of type "internal" needs to be
1702 * Returns either 'type' itself or a string literal, which must not be
1705 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1707 const struct ofproto_class *class;
1709 datapath_type = ofproto_normalize_type(datapath_type);
1710 class = ofproto_class_find__(datapath_type);
1715 return (class->port_open_type
1716 ? class->port_open_type(datapath_type, port_type)
1720 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1721 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1722 * the port's OpenFlow port number.
1724 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1725 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1726 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1727 * 'ofp_portp' is non-null). */
1729 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1730 ofp_port_t *ofp_portp)
1732 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1735 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1737 const char *netdev_name = netdev_get_name(netdev);
1739 simap_put(&ofproto->ofp_requests, netdev_name,
1740 ofp_to_u16(ofp_port));
1741 update_port(ofproto, netdev_name);
1744 struct ofproto_port ofproto_port;
1746 ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1748 *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1749 ofproto_port_destroy(&ofproto_port);
1754 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1755 * initializes '*port' appropriately; on failure, returns a positive errno
1758 * The caller owns the data in 'ofproto_port' and must free it with
1759 * ofproto_port_destroy() when it is no longer needed. */
1761 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1762 struct ofproto_port *port)
1766 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1768 memset(port, 0, sizeof *port);
1773 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1774 * Returns 0 if successful, otherwise a positive errno. */
1776 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1778 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1779 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1780 struct simap_node *ofp_request_node;
1783 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1784 if (ofp_request_node) {
1785 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1788 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1789 if (!error && ofport) {
1790 /* 'name' is the netdev's name and update_port() is going to close the
1791 * netdev. Just in case update_port() refers to 'name' after it
1792 * destroys 'ofport', make a copy of it around the update_port()
1794 char *devname = xstrdup(name);
1795 update_port(ofproto, devname);
1802 simple_flow_mod(struct ofproto *ofproto,
1803 const struct match *match, unsigned int priority,
1804 const struct ofpact *ofpacts, size_t ofpacts_len,
1805 enum ofp_flow_mod_command command)
1807 struct ofputil_flow_mod fm;
1809 memset(&fm, 0, sizeof fm);
1811 fm.priority = priority;
1814 fm.modify_cookie = false;
1816 fm.command = command;
1817 fm.idle_timeout = 0;
1818 fm.hard_timeout = 0;
1819 fm.buffer_id = UINT32_MAX;
1820 fm.out_port = OFPP_ANY;
1821 fm.out_group = OFPG_ANY;
1823 fm.ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1824 fm.ofpacts_len = ofpacts_len;
1826 return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1829 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1830 * performs the 'n_actions' actions in 'actions'. The new flow will not
1833 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1834 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1835 * controllers; otherwise, it will be hidden.
1837 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1839 * This is a helper function for in-band control and fail-open. */
1841 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1842 unsigned int priority,
1843 const struct ofpact *ofpacts, size_t ofpacts_len)
1844 OVS_EXCLUDED(ofproto_mutex)
1846 const struct rule *rule;
1849 /* First do a cheap check whether the rule we're looking for already exists
1850 * with the actions that we want. If it does, then we're done. */
1851 ovs_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1852 rule = rule_from_cls_rule(classifier_find_match_exactly(
1853 &ofproto->tables[0].cls, match, priority));
1855 ovs_mutex_lock(&rule->mutex);
1856 must_add = !ofpacts_equal(rule->actions->ofpacts,
1857 rule->actions->ofpacts_len,
1858 ofpacts, ofpacts_len);
1859 ovs_mutex_unlock(&rule->mutex);
1863 ovs_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1865 /* If there's no such rule or the rule doesn't have the actions we want,
1866 * fall back to a executing a full flow mod. We can't optimize this at
1867 * all because we didn't take enough locks above to ensure that the flow
1868 * table didn't already change beneath us. */
1870 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1871 OFPFC_MODIFY_STRICT);
1875 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1876 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1877 * operation cannot be initiated now but may be retried later.
1879 * This is a helper function for in-band control and fail-open and the "learn"
1882 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1883 OVS_EXCLUDED(ofproto_mutex)
1885 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1888 /* Searches for a rule with matching criteria exactly equal to 'target' in
1889 * ofproto's table 0 and, if it finds one, deletes it.
1891 * This is a helper function for in-band control and fail-open. */
1893 ofproto_delete_flow(struct ofproto *ofproto,
1894 const struct match *target, unsigned int priority)
1895 OVS_EXCLUDED(ofproto_mutex)
1897 struct classifier *cls = &ofproto->tables[0].cls;
1900 /* First do a cheap check whether the rule we're looking for has already
1901 * been deleted. If so, then we're done. */
1902 ovs_rwlock_rdlock(&cls->rwlock);
1903 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1905 ovs_rwlock_unlock(&cls->rwlock);
1910 /* Fall back to a executing a full flow mod. We can't optimize this at all
1911 * because we didn't take enough locks above to ensure that the flow table
1912 * didn't already change beneath us. */
1913 return simple_flow_mod(ofproto, target, priority, NULL, 0,
1914 OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
1917 /* Starts the process of deleting all of the flows from all of ofproto's flow
1918 * tables and then reintroducing the flows required by in-band control and
1919 * fail-open. The process will complete in a later call to ofproto_run(). */
1921 ofproto_flush_flows(struct ofproto *ofproto)
1923 COVERAGE_INC(ofproto_flush);
1924 ofproto->state = S_FLUSH;
1928 reinit_ports(struct ofproto *p)
1930 struct ofproto_port_dump dump;
1931 struct sset devnames;
1932 struct ofport *ofport;
1933 struct ofproto_port ofproto_port;
1934 const char *devname;
1936 COVERAGE_INC(ofproto_reinit_ports);
1938 sset_init(&devnames);
1939 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1940 sset_add(&devnames, netdev_get_name(ofport->netdev));
1942 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1943 sset_add(&devnames, ofproto_port.name);
1946 SSET_FOR_EACH (devname, &devnames) {
1947 update_port(p, devname);
1949 sset_destroy(&devnames);
1953 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1957 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1958 port_idx = port_idx ? port_idx : UINT16_MAX;
1960 if (port_idx >= ofproto->max_ports
1961 || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
1962 uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
1963 long long int last_used_at, lru = LLONG_MAX;
1965 /* Search for a free OpenFlow port number. We try not to
1966 * immediately reuse them to prevent problems due to old
1969 if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1970 ofproto->alloc_port_no = 1;
1972 last_used_at = ofport_get_usage(ofproto,
1973 u16_to_ofp(ofproto->alloc_port_no));
1974 if (!last_used_at) {
1975 port_idx = ofproto->alloc_port_no;
1977 } else if ( last_used_at < time_msec() - 60*60*1000) {
1978 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
1979 * more than an hour ago, consider it usable. */
1980 ofport_remove_usage(ofproto,
1981 u16_to_ofp(ofproto->alloc_port_no));
1982 port_idx = ofproto->alloc_port_no;
1984 } else if (last_used_at < lru) {
1986 lru_ofport = ofproto->alloc_port_no;
1989 if (ofproto->alloc_port_no == end_port_no) {
1991 port_idx = lru_ofport;
1998 ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
1999 return u16_to_ofp(port_idx);
2003 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2005 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2006 ofport_set_usage(ofproto, ofp_port, time_msec());
2010 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2011 * pointer if the netdev cannot be opened. On success, also fills in
2013 static struct netdev *
2014 ofport_open(struct ofproto *ofproto,
2015 struct ofproto_port *ofproto_port,
2016 struct ofputil_phy_port *pp)
2018 enum netdev_flags flags;
2019 struct netdev *netdev;
2022 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2024 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
2025 "cannot be opened (%s)",
2027 ofproto_port->name, ofproto_port->ofp_port,
2028 ofproto_port->name, ovs_strerror(error));
2032 if (ofproto_port->ofp_port == OFPP_NONE) {
2033 if (!strcmp(ofproto->name, ofproto_port->name)) {
2034 ofproto_port->ofp_port = OFPP_LOCAL;
2036 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2037 ofproto_port->name);
2040 pp->port_no = ofproto_port->ofp_port;
2041 netdev_get_etheraddr(netdev, pp->hw_addr);
2042 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2043 netdev_get_flags(netdev, &flags);
2044 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2045 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2046 netdev_get_features(netdev, &pp->curr, &pp->advertised,
2047 &pp->supported, &pp->peer);
2048 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2049 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2054 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
2055 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
2058 ofport_equal(const struct ofputil_phy_port *a,
2059 const struct ofputil_phy_port *b)
2061 return (eth_addr_equals(a->hw_addr, b->hw_addr)
2062 && a->state == b->state
2063 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2064 && a->curr == b->curr
2065 && a->advertised == b->advertised
2066 && a->supported == b->supported
2067 && a->peer == b->peer
2068 && a->curr_speed == b->curr_speed
2069 && a->max_speed == b->max_speed);
2072 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2073 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2074 * one with the same name or port number). */
2076 ofport_install(struct ofproto *p,
2077 struct netdev *netdev, const struct ofputil_phy_port *pp)
2079 const char *netdev_name = netdev_get_name(netdev);
2080 struct ofport *ofport;
2083 /* Create ofport. */
2084 ofport = p->ofproto_class->port_alloc();
2089 ofport->ofproto = p;
2090 ofport->netdev = netdev;
2091 ofport->change_seq = netdev_change_seq(netdev);
2093 ofport->ofp_port = pp->port_no;
2094 ofport->created = time_msec();
2096 /* Add port to 'p'. */
2097 hmap_insert(&p->ports, &ofport->hmap_node,
2098 hash_ofp_port(ofport->ofp_port));
2099 shash_add(&p->port_by_name, netdev_name, ofport);
2101 update_mtu(p, ofport);
2103 /* Let the ofproto_class initialize its private data. */
2104 error = p->ofproto_class->port_construct(ofport);
2108 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
2112 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2113 p->name, netdev_name, ovs_strerror(error));
2115 ofport_destroy__(ofport);
2117 netdev_close(netdev);
2121 /* Removes 'ofport' from 'p' and destroys it. */
2123 ofport_remove(struct ofport *ofport)
2125 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
2127 ofport_destroy(ofport);
2130 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2133 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2135 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2137 ofport_remove(port);
2141 /* Updates 'port' with new 'pp' description.
2143 * Does not handle a name or port number change. The caller must implement
2144 * such a change as a delete followed by an add. */
2146 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2148 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2149 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2150 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2151 port->pp.state = pp->state;
2152 port->pp.curr = pp->curr;
2153 port->pp.advertised = pp->advertised;
2154 port->pp.supported = pp->supported;
2155 port->pp.peer = pp->peer;
2156 port->pp.curr_speed = pp->curr_speed;
2157 port->pp.max_speed = pp->max_speed;
2159 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
2162 /* Update OpenFlow 'state' in 'port' and notify controller. */
2164 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2166 if (port->pp.state != state) {
2167 port->pp.state = state;
2168 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
2174 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2176 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2178 if (port->ofproto->ofproto_class->set_realdev) {
2179 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2181 if (port->ofproto->ofproto_class->set_stp_port) {
2182 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2184 if (port->ofproto->ofproto_class->set_cfm) {
2185 port->ofproto->ofproto_class->set_cfm(port, NULL);
2187 if (port->ofproto->ofproto_class->bundle_remove) {
2188 port->ofproto->ofproto_class->bundle_remove(port);
2194 ofport_destroy__(struct ofport *port)
2196 struct ofproto *ofproto = port->ofproto;
2197 const char *name = netdev_get_name(port->netdev);
2199 hmap_remove(&ofproto->ports, &port->hmap_node);
2200 shash_delete(&ofproto->port_by_name,
2201 shash_find(&ofproto->port_by_name, name));
2203 netdev_close(port->netdev);
2204 ofproto->ofproto_class->port_dealloc(port);
2208 ofport_destroy(struct ofport *port)
2211 dealloc_ofp_port(port->ofproto, port->ofp_port);
2212 port->ofproto->ofproto_class->port_destruct(port);
2213 ofport_destroy__(port);
2218 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2220 struct ofport *port;
2222 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2224 if (port->ofp_port == ofp_port) {
2231 static long long int
2232 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2234 struct ofport_usage *usage;
2236 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2237 &ofproto->ofport_usage) {
2238 if (usage->ofp_port == ofp_port) {
2239 return usage->last_used;
2246 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2247 long long int last_used)
2249 struct ofport_usage *usage;
2250 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2251 &ofproto->ofport_usage) {
2252 if (usage->ofp_port == ofp_port) {
2253 usage->last_used = last_used;
2257 ovs_assert(last_used == LLONG_MAX);
2259 usage = xmalloc(sizeof *usage);
2260 usage->ofp_port = ofp_port;
2261 usage->last_used = last_used;
2262 hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2263 hash_ofp_port(ofp_port));
2267 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2269 struct ofport_usage *usage;
2270 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2271 &ofproto->ofport_usage) {
2272 if (usage->ofp_port == ofp_port) {
2273 hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2281 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2283 struct ofproto *ofproto = port->ofproto;
2286 if (ofproto->ofproto_class->port_get_stats) {
2287 error = ofproto->ofproto_class->port_get_stats(port, stats);
2296 update_port(struct ofproto *ofproto, const char *name)
2298 struct ofproto_port ofproto_port;
2299 struct ofputil_phy_port pp;
2300 struct netdev *netdev;
2301 struct ofport *port;
2303 COVERAGE_INC(ofproto_update_port);
2305 /* Fetch 'name''s location and properties from the datapath. */
2306 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2307 ? ofport_open(ofproto, &ofproto_port, &pp)
2311 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2312 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2313 struct netdev *old_netdev = port->netdev;
2315 /* 'name' hasn't changed location. Any properties changed? */
2316 if (!ofport_equal(&port->pp, &pp)) {
2317 ofport_modified(port, &pp);
2320 update_mtu(ofproto, port);
2322 /* Install the newly opened netdev in case it has changed.
2323 * Don't close the old netdev yet in case port_modified has to
2324 * remove a retained reference to it.*/
2325 port->netdev = netdev;
2326 port->change_seq = netdev_change_seq(netdev);
2328 if (port->ofproto->ofproto_class->port_modified) {
2329 port->ofproto->ofproto_class->port_modified(port);
2332 netdev_close(old_netdev);
2334 /* If 'port' is nonnull then its name differs from 'name' and thus
2335 * we should delete it. If we think there's a port named 'name'
2336 * then its port number must be wrong now so delete it too. */
2338 ofport_remove(port);
2340 ofport_remove_with_name(ofproto, name);
2341 ofport_install(ofproto, netdev, &pp);
2344 /* Any port named 'name' is gone now. */
2345 ofport_remove_with_name(ofproto, name);
2347 ofproto_port_destroy(&ofproto_port);
2351 init_ports(struct ofproto *p)
2353 struct ofproto_port_dump dump;
2354 struct ofproto_port ofproto_port;
2355 struct shash_node *node, *next;
2357 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2358 const char *name = ofproto_port.name;
2360 if (shash_find(&p->port_by_name, name)) {
2361 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2364 struct ofputil_phy_port pp;
2365 struct netdev *netdev;
2367 /* Check if an OpenFlow port number had been requested. */
2368 node = shash_find(&init_ofp_ports, name);
2370 const struct iface_hint *iface_hint = node->data;
2371 simap_put(&p->ofp_requests, name,
2372 ofp_to_u16(iface_hint->ofp_port));
2375 netdev = ofport_open(p, &ofproto_port, &pp);
2377 ofport_install(p, netdev, &pp);
2378 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2379 p->alloc_port_no = MAX(p->alloc_port_no,
2380 ofp_to_u16(ofproto_port.ofp_port));
2386 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2387 struct iface_hint *iface_hint = node->data;
2389 if (!strcmp(iface_hint->br_name, p->name)) {
2390 free(iface_hint->br_name);
2391 free(iface_hint->br_type);
2393 shash_delete(&init_ofp_ports, node);
2400 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2401 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2403 find_min_mtu(struct ofproto *p)
2405 struct ofport *ofport;
2408 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2409 struct netdev *netdev = ofport->netdev;
2412 /* Skip any internal ports, since that's what we're trying to
2414 if (!strcmp(netdev_get_type(netdev), "internal")) {
2418 if (netdev_get_mtu(netdev, &dev_mtu)) {
2421 if (!mtu || dev_mtu < mtu) {
2426 return mtu ? mtu: ETH_PAYLOAD_MAX;
2429 /* Update MTU of all datapath devices on 'p' to the minimum of the
2430 * non-datapath ports in event of 'port' added or changed. */
2432 update_mtu(struct ofproto *p, struct ofport *port)
2434 struct ofport *ofport;
2435 struct netdev *netdev = port->netdev;
2436 int dev_mtu, old_min;
2438 if (netdev_get_mtu(netdev, &dev_mtu)) {
2442 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2443 if (dev_mtu > p->min_mtu) {
2444 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2445 dev_mtu = p->min_mtu;
2448 port->mtu = dev_mtu;
2452 /* For non-internal port find new min mtu. */
2453 old_min = p->min_mtu;
2454 port->mtu = dev_mtu;
2455 p->min_mtu = find_min_mtu(p);
2456 if (p->min_mtu == old_min) {
2460 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2461 struct netdev *netdev = ofport->netdev;
2463 if (!strcmp(netdev_get_type(netdev), "internal")) {
2464 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2465 ofport->mtu = p->min_mtu;
2472 ofproto_rule_ref(struct rule *rule)
2477 atomic_add(&rule->ref_count, 1, &orig);
2478 ovs_assert(orig != 0);
2483 ofproto_rule_unref(struct rule *rule)
2488 atomic_sub(&rule->ref_count, 1, &orig);
2490 rule->ofproto->ofproto_class->rule_destruct(rule);
2491 ofproto_rule_destroy__(rule);
2493 ovs_assert(orig != 0);
2498 struct rule_actions *
2499 rule_get_actions(const struct rule *rule)
2500 OVS_EXCLUDED(rule->mutex)
2502 struct rule_actions *actions;
2504 ovs_mutex_lock(&rule->mutex);
2505 actions = rule_get_actions__(rule);
2506 ovs_mutex_unlock(&rule->mutex);
2511 struct rule_actions *
2512 rule_get_actions__(const struct rule *rule)
2513 OVS_REQUIRES(rule->mutex)
2515 rule_actions_ref(rule->actions);
2516 return rule->actions;
2520 ofproto_rule_destroy__(struct rule *rule)
2521 OVS_NO_THREAD_SAFETY_ANALYSIS
2523 cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2524 rule_actions_unref(rule->actions);
2525 ovs_mutex_destroy(&rule->mutex);
2526 rule->ofproto->ofproto_class->rule_dealloc(rule);
2529 static uint32_t get_provider_meter_id(const struct ofproto *,
2530 uint32_t of_meter_id);
2532 /* Creates and returns a new 'struct rule_actions', with a ref_count of 1,
2533 * whose actions are a copy of from the 'ofpacts_len' bytes of 'ofpacts'. */
2534 struct rule_actions *
2535 rule_actions_create(const struct ofproto *ofproto,
2536 const struct ofpact *ofpacts, size_t ofpacts_len)
2538 struct rule_actions *actions;
2540 actions = xmalloc(sizeof *actions);
2541 atomic_init(&actions->ref_count, 1);
2542 actions->ofpacts = xmemdup(ofpacts, ofpacts_len);
2543 actions->ofpacts_len = ofpacts_len;
2544 actions->provider_meter_id
2545 = get_provider_meter_id(ofproto,
2546 ofpacts_get_meter(ofpacts, ofpacts_len));
2551 /* Increments 'actions''s ref_count. */
2553 rule_actions_ref(struct rule_actions *actions)
2558 atomic_add(&actions->ref_count, 1, &orig);
2559 ovs_assert(orig != 0);
2563 /* Decrements 'actions''s ref_count and frees 'actions' if the ref_count
2566 rule_actions_unref(struct rule_actions *actions)
2571 atomic_sub(&actions->ref_count, 1, &orig);
2573 free(actions->ofpacts);
2576 ovs_assert(orig != 0);
2581 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2582 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2584 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2585 OVS_REQUIRES(ofproto_mutex)
2587 return (port == OFPP_ANY
2588 || ofpacts_output_to_port(rule->actions->ofpacts,
2589 rule->actions->ofpacts_len, port));
2592 /* Returns true if 'rule' has group and equals group_id. */
2594 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
2595 OVS_REQUIRES(ofproto_mutex)
2597 return (group_id == OFPG11_ANY
2598 || ofpacts_output_to_group(rule->actions->ofpacts,
2599 rule->actions->ofpacts_len, group_id));
2602 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2603 * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2605 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2606 OVS_REQUIRES(ofproto_mutex)
2608 if (ofproto_rule_has_out_port(op->rule, out_port)) {
2613 case OFOPERATION_ADD:
2614 case OFOPERATION_DELETE:
2617 case OFOPERATION_MODIFY:
2618 case OFOPERATION_REPLACE:
2619 return ofpacts_output_to_port(op->actions->ofpacts,
2620 op->actions->ofpacts_len, out_port);
2627 rule_execute_destroy(struct rule_execute *e)
2629 ofproto_rule_unref(e->rule);
2630 list_remove(&e->list_node);
2634 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2635 * by passing them to the ofproto provider. */
2637 run_rule_executes(struct ofproto *ofproto)
2638 OVS_EXCLUDED(ofproto_mutex)
2640 struct rule_execute *e, *next;
2641 struct list executes;
2643 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2644 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2645 union flow_in_port in_port_;
2648 in_port_.ofp_port = e->in_port;
2649 flow_extract(e->packet, 0, 0, NULL, &in_port_, &flow);
2650 ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2652 rule_execute_destroy(e);
2656 /* Destroys and discards all "rule_execute" operations queued up in
2657 * ofproto->rule_executes. */
2659 destroy_rule_executes(struct ofproto *ofproto)
2661 struct rule_execute *e, *next;
2662 struct list executes;
2664 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2665 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2666 ofpbuf_delete(e->packet);
2667 rule_execute_destroy(e);
2671 /* Returns true if 'rule' should be hidden from the controller.
2673 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2674 * (e.g. by in-band control) and are intentionally hidden from the
2677 ofproto_rule_is_hidden(const struct rule *rule)
2679 return rule->cr.priority > UINT16_MAX;
2682 static enum oftable_flags
2683 rule_get_flags(const struct rule *rule)
2685 return rule->ofproto->tables[rule->table_id].flags;
2689 rule_is_modifiable(const struct rule *rule)
2691 return !(rule_get_flags(rule) & OFTABLE_READONLY);
2695 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2697 ofconn_send_reply(ofconn, make_echo_reply(oh));
2702 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2704 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2705 struct ofputil_switch_features features;
2706 struct ofport *port;
2712 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2714 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2716 /* Count only non-hidden tables in the number of tables. (Hidden tables,
2717 * if present, are always at the end.) */
2718 n_tables = ofproto->n_tables;
2719 for (i = 0; i < ofproto->n_tables; i++) {
2720 if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2726 features.datapath_id = ofproto->datapath_id;
2727 features.n_buffers = pktbuf_capacity();
2728 features.n_tables = n_tables;
2729 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2730 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2732 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2734 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2735 features.auxiliary_id = 0;
2736 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2738 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2739 ofputil_put_switch_features_port(&port->pp, b);
2742 ofconn_send_reply(ofconn, b);
2747 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2749 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2750 struct ofp_switch_config *osc;
2751 enum ofp_config_flags flags;
2755 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2756 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2757 flags = ofproto->frag_handling;
2758 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2759 if (oh->version < OFP13_VERSION
2760 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2761 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2763 osc->flags = htons(flags);
2764 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2765 ofconn_send_reply(ofconn, buf);
2771 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2773 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2774 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2775 uint16_t flags = ntohs(osc->flags);
2777 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2778 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2779 enum ofp_config_flags cur = ofproto->frag_handling;
2780 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2782 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2784 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2785 ofproto->frag_handling = next;
2787 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2789 ofputil_frag_handling_to_string(next));
2793 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2794 ofconn_set_invalid_ttl_to_controller(ofconn,
2795 (oh->version < OFP13_VERSION
2796 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2798 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2803 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2804 * error message code for the caller to propagate upward. Otherwise, returns
2807 * The log message mentions 'msg_type'. */
2809 reject_slave_controller(struct ofconn *ofconn)
2811 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2812 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2813 return OFPERR_OFPBRC_EPERM;
2819 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are appropriate
2820 * for a packet with the prerequisites satisfied by 'flow' in table 'table_id'.
2821 * 'flow' may be temporarily modified, but is restored at return.
2824 ofproto_check_ofpacts(struct ofproto *ofproto,
2825 const struct ofpact ofpacts[], size_t ofpacts_len,
2826 struct flow *flow, uint8_t table_id,
2827 bool enforce_consistency)
2832 error = ofpacts_check(ofpacts, ofpacts_len, flow,
2833 u16_to_ofp(ofproto->max_ports), table_id,
2834 enforce_consistency);
2839 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2840 if (mid && get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2841 return OFPERR_OFPMMFC_INVALID_METER;
2847 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2849 struct ofproto *p = ofconn_get_ofproto(ofconn);
2850 struct ofputil_packet_out po;
2851 struct ofpbuf *payload;
2852 uint64_t ofpacts_stub[1024 / 8];
2853 struct ofpbuf ofpacts;
2855 union flow_in_port in_port_;
2858 COVERAGE_INC(ofproto_packet_out);
2860 error = reject_slave_controller(ofconn);
2865 /* Decode message. */
2866 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2867 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2869 goto exit_free_ofpacts;
2871 if (ofp_to_u16(po.in_port) >= p->max_ports
2872 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2873 error = OFPERR_OFPBRC_BAD_PORT;
2874 goto exit_free_ofpacts;
2879 if (po.buffer_id != UINT32_MAX) {
2880 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2881 if (error || !payload) {
2882 goto exit_free_ofpacts;
2885 /* Ensure that the L3 header is 32-bit aligned. */
2886 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2889 /* Verify actions against packet, then send packet if successful. */
2890 in_port_.ofp_port = po.in_port;
2891 flow_extract(payload, 0, 0, NULL, &in_port_, &flow);
2892 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len, &flow, 0,
2893 oh->version > OFP10_VERSION);
2895 error = p->ofproto_class->packet_out(p, payload, &flow,
2896 po.ofpacts, po.ofpacts_len);
2898 ofpbuf_delete(payload);
2901 ofpbuf_uninit(&ofpacts);
2907 update_port_config(struct ofport *port,
2908 enum ofputil_port_config config,
2909 enum ofputil_port_config mask)
2911 enum ofputil_port_config old_config = port->pp.config;
2912 enum ofputil_port_config toggle;
2914 toggle = (config ^ port->pp.config) & mask;
2915 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2916 if (config & OFPUTIL_PC_PORT_DOWN) {
2917 netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2919 netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2921 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2924 port->pp.config ^= toggle;
2925 if (port->pp.config != old_config) {
2926 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2931 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2933 struct ofproto *p = ofconn_get_ofproto(ofconn);
2934 struct ofputil_port_mod pm;
2935 struct ofport *port;
2938 error = reject_slave_controller(ofconn);
2943 error = ofputil_decode_port_mod(oh, &pm);
2948 port = ofproto_get_port(p, pm.port_no);
2950 return OFPERR_OFPPMFC_BAD_PORT;
2951 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2952 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2954 update_port_config(port, pm.config, pm.mask);
2956 netdev_set_advertisements(port->netdev, pm.advertise);
2963 handle_desc_stats_request(struct ofconn *ofconn,
2964 const struct ofp_header *request)
2966 static const char *default_mfr_desc = "Nicira, Inc.";
2967 static const char *default_hw_desc = "Open vSwitch";
2968 static const char *default_sw_desc = VERSION;
2969 static const char *default_serial_desc = "None";
2970 static const char *default_dp_desc = "None";
2972 struct ofproto *p = ofconn_get_ofproto(ofconn);
2973 struct ofp_desc_stats *ods;
2976 msg = ofpraw_alloc_stats_reply(request, 0);
2977 ods = ofpbuf_put_zeros(msg, sizeof *ods);
2978 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
2979 sizeof ods->mfr_desc);
2980 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
2981 sizeof ods->hw_desc);
2982 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
2983 sizeof ods->sw_desc);
2984 ovs_strlcpy(ods->serial_num,
2985 p->serial_desc ? p->serial_desc : default_serial_desc,
2986 sizeof ods->serial_num);
2987 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
2988 sizeof ods->dp_desc);
2989 ofconn_send_reply(ofconn, msg);
2995 handle_table_stats_request(struct ofconn *ofconn,
2996 const struct ofp_header *request)
2998 struct ofproto *p = ofconn_get_ofproto(ofconn);
2999 struct ofp12_table_stats *ots;
3004 /* Set up default values.
3006 * ofp12_table_stats is used as a generic structure as
3007 * it is able to hold all the fields for ofp10_table_stats
3008 * and ofp11_table_stats (and of course itself).
3010 ots = xcalloc(p->n_tables, sizeof *ots);
3011 for (i = 0; i < p->n_tables; i++) {
3012 ots[i].table_id = i;
3013 sprintf(ots[i].name, "table%zu", i);
3014 ots[i].match = htonll(OFPXMT13_MASK);
3015 ots[i].wildcards = htonll(OFPXMT13_MASK);
3016 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
3017 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
3018 ots[i].write_setfields = htonll(OFPXMT13_MASK);
3019 ots[i].apply_setfields = htonll(OFPXMT13_MASK);
3020 ots[i].metadata_match = OVS_BE64_MAX;
3021 ots[i].metadata_write = OVS_BE64_MAX;
3022 ots[i].instructions = htonl(OFPIT11_ALL);
3023 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
3024 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
3025 ovs_rwlock_rdlock(&p->tables[i].cls.rwlock);
3026 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
3027 ovs_rwlock_unlock(&p->tables[i].cls.rwlock);
3030 p->ofproto_class->get_tables(p, ots);
3032 /* Post-process the tables, dropping hidden tables. */
3033 n_tables = p->n_tables;
3034 for (i = 0; i < p->n_tables; i++) {
3035 const struct oftable *table = &p->tables[i];
3037 if (table->flags & OFTABLE_HIDDEN) {
3043 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
3046 if (table->max_flows < ntohl(ots[i].max_entries)) {
3047 ots[i].max_entries = htonl(table->max_flows);
3051 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
3052 ofconn_send_reply(ofconn, msg);
3060 append_port_stat(struct ofport *port, struct list *replies)
3062 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3064 calc_duration(port->created, time_msec(),
3065 &ops.duration_sec, &ops.duration_nsec);
3067 /* Intentionally ignore return value, since errors will set
3068 * 'stats' to all-1s, which is correct for OpenFlow, and
3069 * netdev_get_stats() will log errors. */
3070 ofproto_port_get_stats(port, &ops.stats);
3072 ofputil_append_port_stat(replies, &ops);
3076 handle_port_stats_request(struct ofconn *ofconn,
3077 const struct ofp_header *request)
3079 struct ofproto *p = ofconn_get_ofproto(ofconn);
3080 struct ofport *port;
3081 struct list replies;
3085 error = ofputil_decode_port_stats_request(request, &port_no);
3090 ofpmp_init(&replies, request);
3091 if (port_no != OFPP_ANY) {
3092 port = ofproto_get_port(p, port_no);
3094 append_port_stat(port, &replies);
3097 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3098 append_port_stat(port, &replies);
3102 ofconn_send_replies(ofconn, &replies);
3107 handle_port_desc_stats_request(struct ofconn *ofconn,
3108 const struct ofp_header *request)
3110 struct ofproto *p = ofconn_get_ofproto(ofconn);
3111 enum ofp_version version;
3112 struct ofport *port;
3113 struct list replies;
3115 ofpmp_init(&replies, request);
3117 version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
3118 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3119 ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
3122 ofconn_send_replies(ofconn, &replies);
3127 hash_cookie(ovs_be64 cookie)
3129 return hash_2words((OVS_FORCE uint64_t)cookie >> 32,
3130 (OVS_FORCE uint64_t)cookie);
3134 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3135 OVS_REQUIRES(ofproto_mutex)
3137 hindex_insert(&ofproto->cookies, &rule->cookie_node,
3138 hash_cookie(rule->flow_cookie));
3142 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3143 OVS_REQUIRES(ofproto_mutex)
3145 hindex_remove(&ofproto->cookies, &rule->cookie_node);
3149 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
3150 ovs_be64 new_cookie)
3151 OVS_REQUIRES(ofproto_mutex)
3153 if (new_cookie != rule->flow_cookie) {
3154 cookies_remove(ofproto, rule);
3156 ovs_mutex_lock(&rule->mutex);
3157 rule->flow_cookie = new_cookie;
3158 ovs_mutex_unlock(&rule->mutex);
3160 cookies_insert(ofproto, rule);
3165 calc_duration(long long int start, long long int now,
3166 uint32_t *sec, uint32_t *nsec)
3168 long long int msecs = now - start;
3169 *sec = msecs / 1000;
3170 *nsec = (msecs % 1000) * (1000 * 1000);
3173 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
3174 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
3176 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3178 return (table_id == 0xff || table_id < ofproto->n_tables
3180 : OFPERR_OFPBRC_BAD_TABLE_ID);
3184 static struct oftable *
3185 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3187 struct oftable *table;
3189 for (table = &ofproto->tables[table_id];
3190 table < &ofproto->tables[ofproto->n_tables];
3192 if (!(table->flags & OFTABLE_HIDDEN)) {
3200 static struct oftable *
3201 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3203 if (table_id == 0xff) {
3204 return next_visible_table(ofproto, 0);
3205 } else if (table_id < ofproto->n_tables) {
3206 return &ofproto->tables[table_id];
3212 static struct oftable *
3213 next_matching_table(const struct ofproto *ofproto,
3214 const struct oftable *table, uint8_t table_id)
3216 return (table_id == 0xff
3217 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3221 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3223 * - If TABLE_ID is 0xff, this iterates over every classifier table in
3224 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3226 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3227 * only once, for that table. (This can be used to access tables marked
3230 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3231 * entered at all. (Perhaps you should have validated TABLE_ID with
3232 * check_table_id().)
3234 * All parameters are evaluated multiple times.
3236 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
3237 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
3239 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3241 /* Initializes 'criteria' in a straightforward way based on the other
3244 * For "loose" matching, the 'priority' parameter is unimportant and may be
3247 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3248 const struct match *match, unsigned int priority,
3249 ovs_be64 cookie, ovs_be64 cookie_mask,
3250 ofp_port_t out_port, uint32_t out_group)
3252 criteria->table_id = table_id;
3253 cls_rule_init(&criteria->cr, match, priority);
3254 criteria->cookie = cookie;
3255 criteria->cookie_mask = cookie_mask;
3256 criteria->out_port = out_port;
3257 criteria->out_group = out_group;
3261 rule_criteria_destroy(struct rule_criteria *criteria)
3263 cls_rule_destroy(&criteria->cr);
3267 rule_collection_init(struct rule_collection *rules)
3269 rules->rules = rules->stub;
3271 rules->capacity = ARRAY_SIZE(rules->stub);
3275 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3277 if (rules->n >= rules->capacity) {
3278 size_t old_size, new_size;
3280 old_size = rules->capacity * sizeof *rules->rules;
3281 rules->capacity *= 2;
3282 new_size = rules->capacity * sizeof *rules->rules;
3284 if (rules->rules == rules->stub) {
3285 rules->rules = xmalloc(new_size);
3286 memcpy(rules->rules, rules->stub, old_size);
3288 rules->rules = xrealloc(rules->rules, new_size);
3292 rules->rules[rules->n++] = rule;
3296 rule_collection_ref(struct rule_collection *rules)
3297 OVS_REQUIRES(ofproto_mutex)
3301 for (i = 0; i < rules->n; i++) {
3302 ofproto_rule_ref(rules->rules[i]);
3307 rule_collection_unref(struct rule_collection *rules)
3311 for (i = 0; i < rules->n; i++) {
3312 ofproto_rule_unref(rules->rules[i]);
3317 rule_collection_destroy(struct rule_collection *rules)
3319 if (rules->rules != rules->stub) {
3325 collect_rule(struct rule *rule, const struct rule_criteria *c,
3326 struct rule_collection *rules)
3327 OVS_REQUIRES(ofproto_mutex)
3329 /* We ordinarily want to skip hidden rules, but there has to be a way for
3330 * code internal to OVS to modify and delete them, so if the criteria
3331 * specify a priority that can only be for a hidden flow, then allow hidden
3332 * rules to be selected. (This doesn't allow OpenFlow clients to meddle
3333 * with hidden flows because OpenFlow uses only a 16-bit field to specify
3335 if (ofproto_rule_is_hidden(rule) && c->cr.priority <= UINT16_MAX) {
3337 } else if (rule->pending) {
3338 return OFPROTO_POSTPONE;
3340 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3341 && ofproto_rule_has_out_port(rule, c->out_port)
3342 && ofproto_rule_has_out_group(rule, c->out_group)
3343 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3344 rule_collection_add(rules, rule);
3350 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3351 * on classifiers rules are done in the "loose" way required for OpenFlow
3352 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3355 * Hidden rules are always omitted.
3357 * Returns 0 on success, otherwise an OpenFlow error code. */
3359 collect_rules_loose(struct ofproto *ofproto,
3360 const struct rule_criteria *criteria,
3361 struct rule_collection *rules)
3362 OVS_REQUIRES(ofproto_mutex)
3364 struct oftable *table;
3367 rule_collection_init(rules);
3369 error = check_table_id(ofproto, criteria->table_id);
3374 if (criteria->cookie_mask == OVS_BE64_MAX) {
3377 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3378 hash_cookie(criteria->cookie),
3379 &ofproto->cookies) {
3380 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3381 error = collect_rule(rule, criteria, rules);
3388 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3389 struct cls_cursor cursor;
3392 ovs_rwlock_rdlock(&table->cls.rwlock);
3393 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3394 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3395 error = collect_rule(rule, criteria, rules);
3400 ovs_rwlock_unlock(&table->cls.rwlock);
3406 rule_collection_destroy(rules);
3411 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3412 * on classifiers rules are done in the "strict" way required for OpenFlow
3413 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3414 * rules on list 'rules'.
3416 * Hidden rules are always omitted.
3418 * Returns 0 on success, otherwise an OpenFlow error code. */
3420 collect_rules_strict(struct ofproto *ofproto,
3421 const struct rule_criteria *criteria,
3422 struct rule_collection *rules)
3423 OVS_REQUIRES(ofproto_mutex)
3425 struct oftable *table;
3428 rule_collection_init(rules);
3430 error = check_table_id(ofproto, criteria->table_id);
3435 if (criteria->cookie_mask == OVS_BE64_MAX) {
3438 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3439 hash_cookie(criteria->cookie),
3440 &ofproto->cookies) {
3441 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3442 error = collect_rule(rule, criteria, rules);
3449 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3452 ovs_rwlock_rdlock(&table->cls.rwlock);
3453 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3454 &table->cls, &criteria->cr));
3455 ovs_rwlock_unlock(&table->cls.rwlock);
3457 error = collect_rule(rule, criteria, rules);
3467 rule_collection_destroy(rules);
3472 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3473 * forced into the range of a uint16_t. */
3475 age_secs(long long int age_ms)
3477 return (age_ms < 0 ? 0
3478 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3479 : (unsigned int) age_ms / 1000);
3483 handle_flow_stats_request(struct ofconn *ofconn,
3484 const struct ofp_header *request)
3485 OVS_EXCLUDED(ofproto_mutex)
3487 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3488 struct ofputil_flow_stats_request fsr;
3489 struct rule_criteria criteria;
3490 struct rule_collection rules;
3491 struct list replies;
3495 error = ofputil_decode_flow_stats_request(&fsr, request);
3500 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3501 fsr.cookie_mask, fsr.out_port, fsr.out_group);
3503 ovs_mutex_lock(&ofproto_mutex);
3504 error = collect_rules_loose(ofproto, &criteria, &rules);
3505 rule_criteria_destroy(&criteria);
3507 rule_collection_ref(&rules);
3509 ovs_mutex_unlock(&ofproto_mutex);
3515 ofpmp_init(&replies, request);
3516 for (i = 0; i < rules.n; i++) {
3517 struct rule *rule = rules.rules[i];
3518 long long int now = time_msec();
3519 struct ofputil_flow_stats fs;
3520 long long int created, used, modified;
3521 struct rule_actions *actions;
3522 enum ofputil_flow_mod_flags flags;
3524 ovs_mutex_lock(&rule->mutex);
3525 fs.cookie = rule->flow_cookie;
3526 fs.idle_timeout = rule->idle_timeout;
3527 fs.hard_timeout = rule->hard_timeout;
3528 created = rule->created;
3530 modified = rule->modified;
3531 actions = rule_get_actions__(rule);
3532 flags = rule->flags;
3533 ovs_mutex_unlock(&rule->mutex);
3535 minimatch_expand(&rule->cr.match, &fs.match);
3536 fs.table_id = rule->table_id;
3537 calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
3538 fs.priority = rule->cr.priority;
3539 fs.idle_age = age_secs(now - used);
3540 fs.hard_age = age_secs(now - modified);
3541 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3543 fs.ofpacts = actions->ofpacts;
3544 fs.ofpacts_len = actions->ofpacts_len;
3547 ofputil_append_flow_stats_reply(&fs, &replies);
3549 rule_actions_unref(actions);
3552 rule_collection_unref(&rules);
3553 rule_collection_destroy(&rules);
3555 ofconn_send_replies(ofconn, &replies);
3561 flow_stats_ds(struct rule *rule, struct ds *results)
3563 uint64_t packet_count, byte_count;
3564 struct rule_actions *actions;
3565 long long int created;
3567 rule->ofproto->ofproto_class->rule_get_stats(rule,
3568 &packet_count, &byte_count);
3570 ovs_mutex_lock(&rule->mutex);
3571 actions = rule_get_actions__(rule);
3572 created = rule->created;
3573 ovs_mutex_unlock(&rule->mutex);
3575 if (rule->table_id != 0) {
3576 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3578 ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
3579 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3580 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3581 cls_rule_format(&rule->cr, results);
3582 ds_put_char(results, ',');
3584 ds_put_cstr(results, "actions=");
3585 ofpacts_format(actions->ofpacts, actions->ofpacts_len, results);
3587 ds_put_cstr(results, "\n");
3589 rule_actions_unref(actions);
3592 /* Adds a pretty-printed description of all flows to 'results', including
3593 * hidden flows (e.g., set up by in-band control). */
3595 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3597 struct oftable *table;
3599 OFPROTO_FOR_EACH_TABLE (table, p) {
3600 struct cls_cursor cursor;
3603 ovs_rwlock_rdlock(&table->cls.rwlock);
3604 cls_cursor_init(&cursor, &table->cls, NULL);
3605 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3606 flow_stats_ds(rule, results);
3608 ovs_rwlock_unlock(&table->cls.rwlock);
3612 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3613 * '*engine_type' and '*engine_id', respectively. */
3615 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3616 uint8_t *engine_type, uint8_t *engine_id)
3618 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3621 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3622 * true if the port's CFM status was successfully stored into '*status'.
3623 * Returns false if the port did not have CFM configured, in which case
3624 * '*status' is indeterminate.
3626 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3628 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3629 struct ofproto_cfm_status *status)
3631 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3633 && ofproto->ofproto_class->get_cfm_status
3634 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3638 handle_aggregate_stats_request(struct ofconn *ofconn,
3639 const struct ofp_header *oh)
3640 OVS_EXCLUDED(ofproto_mutex)
3642 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3643 struct ofputil_flow_stats_request request;
3644 struct ofputil_aggregate_stats stats;
3645 bool unknown_packets, unknown_bytes;
3646 struct rule_criteria criteria;
3647 struct rule_collection rules;
3648 struct ofpbuf *reply;
3652 error = ofputil_decode_flow_stats_request(&request, oh);
3657 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3658 request.cookie, request.cookie_mask,
3659 request.out_port, request.out_group);
3661 ovs_mutex_lock(&ofproto_mutex);
3662 error = collect_rules_loose(ofproto, &criteria, &rules);
3663 rule_criteria_destroy(&criteria);
3665 rule_collection_ref(&rules);
3667 ovs_mutex_unlock(&ofproto_mutex);
3673 memset(&stats, 0, sizeof stats);
3674 unknown_packets = unknown_bytes = false;
3675 for (i = 0; i < rules.n; i++) {
3676 struct rule *rule = rules.rules[i];
3677 uint64_t packet_count;
3678 uint64_t byte_count;
3680 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3683 if (packet_count == UINT64_MAX) {
3684 unknown_packets = true;
3686 stats.packet_count += packet_count;
3689 if (byte_count == UINT64_MAX) {
3690 unknown_bytes = true;
3692 stats.byte_count += byte_count;
3697 if (unknown_packets) {
3698 stats.packet_count = UINT64_MAX;
3700 if (unknown_bytes) {
3701 stats.byte_count = UINT64_MAX;
3704 rule_collection_unref(&rules);
3705 rule_collection_destroy(&rules);
3707 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3708 ofconn_send_reply(ofconn, reply);
3713 struct queue_stats_cbdata {
3714 struct ofport *ofport;
3715 struct list replies;
3720 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3721 const struct netdev_queue_stats *stats)
3723 struct ofputil_queue_stats oqs;
3725 oqs.port_no = cbdata->ofport->pp.port_no;
3726 oqs.queue_id = queue_id;
3727 oqs.tx_bytes = stats->tx_bytes;
3728 oqs.tx_packets = stats->tx_packets;
3729 oqs.tx_errors = stats->tx_errors;
3730 if (stats->created != LLONG_MIN) {
3731 calc_duration(stats->created, cbdata->now,
3732 &oqs.duration_sec, &oqs.duration_nsec);
3734 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3736 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3740 handle_queue_stats_dump_cb(uint32_t queue_id,
3741 struct netdev_queue_stats *stats,
3744 struct queue_stats_cbdata *cbdata = cbdata_;
3746 put_queue_stats(cbdata, queue_id, stats);
3750 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3751 struct queue_stats_cbdata *cbdata)
3753 cbdata->ofport = port;
3754 if (queue_id == OFPQ_ALL) {
3755 netdev_dump_queue_stats(port->netdev,
3756 handle_queue_stats_dump_cb, cbdata);
3758 struct netdev_queue_stats stats;
3760 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3761 put_queue_stats(cbdata, queue_id, &stats);
3763 return OFPERR_OFPQOFC_BAD_QUEUE;
3770 handle_queue_stats_request(struct ofconn *ofconn,
3771 const struct ofp_header *rq)
3773 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3774 struct queue_stats_cbdata cbdata;
3775 struct ofport *port;
3777 struct ofputil_queue_stats_request oqsr;
3779 COVERAGE_INC(ofproto_queue_req);
3781 ofpmp_init(&cbdata.replies, rq);
3782 cbdata.now = time_msec();
3784 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3789 if (oqsr.port_no == OFPP_ANY) {
3790 error = OFPERR_OFPQOFC_BAD_QUEUE;
3791 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3792 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3797 port = ofproto_get_port(ofproto, oqsr.port_no);
3799 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3800 : OFPERR_OFPQOFC_BAD_PORT);
3803 ofconn_send_replies(ofconn, &cbdata.replies);
3805 ofpbuf_list_delete(&cbdata.replies);
3812 is_flow_deletion_pending(const struct ofproto *ofproto,
3813 const struct cls_rule *cls_rule,
3815 OVS_REQUIRES(ofproto_mutex)
3817 if (!hmap_is_empty(&ofproto->deletions)) {
3818 struct ofoperation *op;
3820 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3821 cls_rule_hash(cls_rule, table_id),
3822 &ofproto->deletions) {
3823 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3833 should_evict_a_rule(struct oftable *table, unsigned int extra_space)
3834 OVS_REQUIRES(ofproto_mutex)
3835 OVS_NO_THREAD_SAFETY_ANALYSIS
3837 return classifier_count(&table->cls) + extra_space > table->max_flows;
3841 evict_rules_from_table(struct ofproto *ofproto, struct oftable *table,
3842 unsigned int extra_space)
3843 OVS_REQUIRES(ofproto_mutex)
3845 while (should_evict_a_rule(table, extra_space)) {
3848 if (!choose_rule_to_evict(table, &rule)) {
3849 return OFPERR_OFPFMFC_TABLE_FULL;
3850 } else if (rule->pending) {
3851 return OFPROTO_POSTPONE;
3853 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
3854 delete_flow__(rule, group, OFPRR_EVICTION);
3855 ofopgroup_submit(group);
3862 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3863 * in which no matching flow already exists in the flow table.
3865 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3866 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3867 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3868 * initiated now but may be retried later.
3870 * The caller retains ownership of 'fm->ofpacts'.
3872 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3875 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3876 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3877 OVS_REQUIRES(ofproto_mutex)
3879 struct oftable *table;
3880 struct ofopgroup *group;
3886 error = check_table_id(ofproto, fm->table_id);
3892 if (fm->table_id == 0xff) {
3893 if (ofproto->ofproto_class->rule_choose_table) {
3894 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3900 ovs_assert(table_id < ofproto->n_tables);
3904 } else if (fm->table_id < ofproto->n_tables) {
3905 table_id = fm->table_id;
3907 return OFPERR_OFPBRC_BAD_TABLE_ID;
3910 table = &ofproto->tables[table_id];
3912 if (table->flags & OFTABLE_READONLY) {
3913 return OFPERR_OFPBRC_EPERM;
3916 cls_rule_init(&cr, &fm->match, fm->priority);
3918 /* Transform "add" into "modify" if there's an existing identical flow. */
3919 ovs_rwlock_rdlock(&table->cls.rwlock);
3920 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3921 ovs_rwlock_unlock(&table->cls.rwlock);
3923 cls_rule_destroy(&cr);
3924 if (!rule_is_modifiable(rule)) {
3925 return OFPERR_OFPBRC_EPERM;
3926 } else if (rule->pending) {
3927 return OFPROTO_POSTPONE;
3929 struct rule_collection rules;
3931 rule_collection_init(&rules);
3932 rule_collection_add(&rules, rule);
3933 fm->modify_cookie = true;
3934 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3935 rule_collection_destroy(&rules);
3941 /* Verify actions. */
3942 error = ofproto_check_ofpacts(ofproto, fm->ofpacts, fm->ofpacts_len,
3943 &fm->match.flow, table_id,
3944 request && request->version > OFP10_VERSION);
3946 cls_rule_destroy(&cr);
3950 /* Serialize against pending deletion. */
3951 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3952 cls_rule_destroy(&cr);
3953 return OFPROTO_POSTPONE;
3956 /* Check for overlap, if requested. */
3957 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3960 ovs_rwlock_rdlock(&table->cls.rwlock);
3961 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3962 ovs_rwlock_unlock(&table->cls.rwlock);
3965 cls_rule_destroy(&cr);
3966 return OFPERR_OFPFMFC_OVERLAP;
3970 /* If necessary, evict an existing rule to clear out space. */
3971 error = evict_rules_from_table(ofproto, table, 1);
3973 cls_rule_destroy(&cr);
3977 /* Allocate new rule. */
3978 rule = ofproto->ofproto_class->rule_alloc();
3980 cls_rule_destroy(&cr);
3981 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3982 ofproto->name, ovs_strerror(error));
3986 /* Initialize base state. */
3987 *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
3988 cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), &cr);
3989 atomic_init(&rule->ref_count, 1);
3990 rule->pending = NULL;
3991 rule->flow_cookie = fm->new_cookie;
3992 rule->created = rule->modified = rule->used = time_msec();
3994 ovs_mutex_init(&rule->mutex);
3995 ovs_mutex_lock(&rule->mutex);
3996 rule->idle_timeout = fm->idle_timeout;
3997 rule->hard_timeout = fm->hard_timeout;
3998 ovs_mutex_unlock(&rule->mutex);
4000 *CONST_CAST(uint8_t *, &rule->table_id) = table - ofproto->tables;
4001 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4002 rule->actions = rule_actions_create(ofproto, fm->ofpacts, fm->ofpacts_len);
4003 list_init(&rule->meter_list_node);
4004 rule->eviction_group = NULL;
4005 list_init(&rule->expirable);
4006 rule->monitor_flags = 0;
4007 rule->add_seqno = 0;
4008 rule->modify_seqno = 0;
4010 /* Construct rule, initializing derived state. */
4011 error = ofproto->ofproto_class->rule_construct(rule);
4013 ofproto_rule_destroy__(rule);
4018 oftable_insert_rule(rule);
4020 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4021 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
4022 ofproto->ofproto_class->rule_insert(rule);
4023 ofopgroup_submit(group);
4028 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4030 /* Modifies the rules listed in 'rules', changing their actions to match those
4033 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4036 * Returns 0 on success, otherwise an OpenFlow error code. */
4038 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4039 struct ofputil_flow_mod *fm, const struct ofp_header *request,
4040 const struct rule_collection *rules)
4041 OVS_REQUIRES(ofproto_mutex)
4043 enum ofoperation_type type;
4044 struct ofopgroup *group;
4048 /* Verify actions before we start to modify any rules, to avoid partial
4049 * flow table modifications. */
4050 for (i = 0; i < rules->n; i++) {
4051 struct rule *rule = rules->rules[i];
4053 error = ofpacts_check(fm->ofpacts, fm->ofpacts_len, &fm->match.flow,
4054 u16_to_ofp(ofproto->max_ports), rule->table_id,
4055 request && request->version > OFP10_VERSION);
4061 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
4062 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4063 error = OFPERR_OFPBRC_EPERM;
4064 for (i = 0; i < rules->n; i++) {
4065 struct rule *rule = rules->rules[i];
4066 struct ofoperation *op;
4067 bool actions_changed;
4068 bool reset_counters;
4070 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
4072 if (rule_is_modifiable(rule)) {
4073 /* At least one rule is modifiable, don't report EPERM error. */
4079 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4080 rule->actions->ofpacts,
4081 rule->actions->ofpacts_len);
4083 op = ofoperation_create(group, rule, type, 0);
4085 if (fm->modify_cookie && fm->new_cookie != OVS_BE64_MAX) {
4086 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
4088 if (type == OFOPERATION_REPLACE) {
4089 ovs_mutex_lock(&rule->mutex);
4090 rule->idle_timeout = fm->idle_timeout;
4091 rule->hard_timeout = fm->hard_timeout;
4092 ovs_mutex_unlock(&rule->mutex);
4094 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4095 if (fm->idle_timeout || fm->hard_timeout) {
4096 if (!rule->eviction_group) {
4097 eviction_group_add_rule(rule);
4100 eviction_group_remove_rule(rule);
4104 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
4105 if (actions_changed || reset_counters) {
4106 struct rule_actions *new_actions;
4108 op->actions = rule->actions;
4109 new_actions = rule_actions_create(ofproto,
4110 fm->ofpacts, fm->ofpacts_len);
4112 ovs_mutex_lock(&rule->mutex);
4113 rule->actions = new_actions;
4114 ovs_mutex_unlock(&rule->mutex);
4116 rule->ofproto->ofproto_class->rule_modify_actions(rule,
4119 ofoperation_complete(op, 0);
4122 ofopgroup_submit(group);
4128 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
4129 struct ofputil_flow_mod *fm, const struct ofp_header *request)
4130 OVS_REQUIRES(ofproto_mutex)
4132 if (fm->cookie_mask != htonll(0) || fm->new_cookie == OVS_BE64_MAX) {
4135 return add_flow(ofproto, ofconn, fm, request);
4138 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
4141 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4144 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4145 struct ofputil_flow_mod *fm,
4146 const struct ofp_header *request)
4147 OVS_REQUIRES(ofproto_mutex)
4149 struct rule_criteria criteria;
4150 struct rule_collection rules;
4153 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4154 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4155 error = collect_rules_loose(ofproto, &criteria, &rules);
4156 rule_criteria_destroy(&criteria);
4159 error = (rules.n > 0
4160 ? modify_flows__(ofproto, ofconn, fm, request, &rules)
4161 : modify_flows_add(ofproto, ofconn, fm, request));
4164 rule_collection_destroy(&rules);
4169 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4172 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4175 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4176 struct ofputil_flow_mod *fm,
4177 const struct ofp_header *request)
4178 OVS_REQUIRES(ofproto_mutex)
4180 struct rule_criteria criteria;
4181 struct rule_collection rules;
4184 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4185 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4186 error = collect_rules_strict(ofproto, &criteria, &rules);
4187 rule_criteria_destroy(&criteria);
4191 error = modify_flows_add(ofproto, ofconn, fm, request);
4192 } else if (rules.n == 1) {
4193 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
4197 rule_collection_destroy(&rules);
4202 /* OFPFC_DELETE implementation. */
4205 delete_flow__(struct rule *rule, struct ofopgroup *group,
4206 enum ofp_flow_removed_reason reason)
4207 OVS_REQUIRES(ofproto_mutex)
4209 struct ofproto *ofproto = rule->ofproto;
4211 ofproto_rule_send_removed(rule, reason);
4213 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
4214 oftable_remove_rule(rule);
4215 ofproto->ofproto_class->rule_delete(rule);
4218 /* Deletes the rules listed in 'rules'.
4220 * Returns 0 on success, otherwise an OpenFlow error code. */
4222 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4223 const struct ofp_header *request,
4224 const struct rule_collection *rules,
4225 enum ofp_flow_removed_reason reason)
4226 OVS_REQUIRES(ofproto_mutex)
4228 struct ofopgroup *group;
4231 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
4232 for (i = 0; i < rules->n; i++) {
4233 delete_flow__(rules->rules[i], group, reason);
4235 ofopgroup_submit(group);
4240 /* Implements OFPFC_DELETE. */
4242 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4243 const struct ofputil_flow_mod *fm,
4244 const struct ofp_header *request)
4245 OVS_REQUIRES(ofproto_mutex)
4247 struct rule_criteria criteria;
4248 struct rule_collection rules;
4251 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4252 fm->cookie, fm->cookie_mask,
4253 fm->out_port, fm->out_group);
4254 error = collect_rules_loose(ofproto, &criteria, &rules);
4255 rule_criteria_destroy(&criteria);
4257 if (!error && rules.n > 0) {
4258 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4260 rule_collection_destroy(&rules);
4265 /* Implements OFPFC_DELETE_STRICT. */
4267 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4268 const struct ofputil_flow_mod *fm,
4269 const struct ofp_header *request)
4270 OVS_REQUIRES(ofproto_mutex)
4272 struct rule_criteria criteria;
4273 struct rule_collection rules;
4276 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4277 fm->cookie, fm->cookie_mask,
4278 fm->out_port, fm->out_group);
4279 error = collect_rules_strict(ofproto, &criteria, &rules);
4280 rule_criteria_destroy(&criteria);
4282 if (!error && rules.n > 0) {
4283 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4285 rule_collection_destroy(&rules);
4291 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4292 OVS_REQUIRES(ofproto_mutex)
4294 struct ofputil_flow_removed fr;
4296 if (ofproto_rule_is_hidden(rule) ||
4297 !(rule->flags & OFPUTIL_FF_SEND_FLOW_REM)) {
4301 minimatch_expand(&rule->cr.match, &fr.match);
4302 fr.priority = rule->cr.priority;
4303 fr.cookie = rule->flow_cookie;
4305 fr.table_id = rule->table_id;
4306 calc_duration(rule->created, time_msec(),
4307 &fr.duration_sec, &fr.duration_nsec);
4308 ovs_mutex_lock(&rule->mutex);
4309 fr.idle_timeout = rule->idle_timeout;
4310 fr.hard_timeout = rule->hard_timeout;
4311 ovs_mutex_unlock(&rule->mutex);
4312 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4315 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4318 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4319 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4322 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4325 * ofproto implementation ->run() functions should use this function to expire
4326 * OpenFlow flows. */
4328 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4329 OVS_REQUIRES(ofproto_mutex)
4331 struct ofproto *ofproto = rule->ofproto;
4333 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT
4334 || reason == OFPRR_DELETE || reason == OFPRR_GROUP_DELETE);
4336 ofproto_rule_delete__(ofproto, rule, reason);
4339 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
4340 * means "infinite". */
4342 reduce_timeout(uint16_t max, uint16_t *timeout)
4344 if (max && (!*timeout || *timeout > max)) {
4349 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4350 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4351 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
4353 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4355 ofproto_rule_reduce_timeouts(struct rule *rule,
4356 uint16_t idle_timeout, uint16_t hard_timeout)
4357 OVS_EXCLUDED(ofproto_mutex, rule->mutex)
4359 if (!idle_timeout && !hard_timeout) {
4363 ovs_mutex_lock(&ofproto_mutex);
4364 if (list_is_empty(&rule->expirable)) {
4365 list_insert(&rule->ofproto->expirable, &rule->expirable);
4367 ovs_mutex_unlock(&ofproto_mutex);
4369 ovs_mutex_lock(&rule->mutex);
4370 reduce_timeout(idle_timeout, &rule->idle_timeout);
4371 reduce_timeout(hard_timeout, &rule->hard_timeout);
4372 ovs_mutex_unlock(&rule->mutex);
4376 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4377 OVS_EXCLUDED(ofproto_mutex)
4379 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4380 struct ofputil_flow_mod fm;
4381 uint64_t ofpacts_stub[1024 / 8];
4382 struct ofpbuf ofpacts;
4386 error = reject_slave_controller(ofconn);
4391 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4392 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4395 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4398 goto exit_free_ofpacts;
4401 /* Record the operation for logging a summary report. */
4402 switch (fm.command) {
4408 case OFPFC_MODIFY_STRICT:
4409 ofproto->n_modify++;
4413 case OFPFC_DELETE_STRICT:
4414 ofproto->n_delete++;
4419 if (ofproto->next_op_report == LLONG_MAX) {
4420 ofproto->first_op = now;
4421 ofproto->next_op_report = MAX(now + 10 * 1000,
4422 ofproto->op_backoff);
4423 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4425 ofproto->last_op = now;
4428 ofpbuf_uninit(&ofpacts);
4434 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4435 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4436 OVS_EXCLUDED(ofproto_mutex)
4440 ovs_mutex_lock(&ofproto_mutex);
4441 if (ofproto->n_pending < 50) {
4442 switch (fm->command) {
4444 error = add_flow(ofproto, ofconn, fm, oh);
4448 error = modify_flows_loose(ofproto, ofconn, fm, oh);
4451 case OFPFC_MODIFY_STRICT:
4452 error = modify_flow_strict(ofproto, ofconn, fm, oh);
4456 error = delete_flows_loose(ofproto, ofconn, fm, oh);
4459 case OFPFC_DELETE_STRICT:
4460 error = delete_flow_strict(ofproto, ofconn, fm, oh);
4464 if (fm->command > 0xff) {
4465 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4466 "flow_mod_table_id extension is not enabled",
4469 error = OFPERR_OFPFMFC_BAD_COMMAND;
4473 ovs_assert(!list_is_empty(&ofproto->pending));
4474 error = OFPROTO_POSTPONE;
4476 ovs_mutex_unlock(&ofproto_mutex);
4478 run_rule_executes(ofproto);
4483 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4485 struct ofputil_role_request request;
4486 struct ofputil_role_request reply;
4490 error = ofputil_decode_role_message(oh, &request);
4495 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4496 if (ofconn_get_role(ofconn) != request.role
4497 && ofconn_has_pending_opgroups(ofconn)) {
4498 return OFPROTO_POSTPONE;
4501 if (request.have_generation_id
4502 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4503 return OFPERR_OFPRRFC_STALE;
4506 ofconn_set_role(ofconn, request.role);
4509 reply.role = ofconn_get_role(ofconn);
4510 reply.have_generation_id = ofconn_get_master_election_id(
4511 ofconn, &reply.generation_id);
4512 buf = ofputil_encode_role_reply(oh, &reply);
4513 ofconn_send_reply(ofconn, buf);
4519 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4520 const struct ofp_header *oh)
4522 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4523 enum ofputil_protocol cur, next;
4525 cur = ofconn_get_protocol(ofconn);
4526 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4527 ofconn_set_protocol(ofconn, next);
4533 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4535 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4536 enum ofputil_protocol cur, next;
4537 enum ofputil_protocol next_base;
4539 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4541 return OFPERR_OFPBRC_EPERM;
4544 cur = ofconn_get_protocol(ofconn);
4545 next = ofputil_protocol_set_base(cur, next_base);
4546 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4547 /* Avoid sending async messages in surprising protocol. */
4548 return OFPROTO_POSTPONE;
4551 ofconn_set_protocol(ofconn, next);
4556 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4557 const struct ofp_header *oh)
4559 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4562 format = ntohl(msg->format);
4563 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4564 return OFPERR_OFPBRC_EPERM;
4567 if (format != ofconn_get_packet_in_format(ofconn)
4568 && ofconn_has_pending_opgroups(ofconn)) {
4569 /* Avoid sending async message in surprsing packet in format. */
4570 return OFPROTO_POSTPONE;
4573 ofconn_set_packet_in_format(ofconn, format);
4578 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4580 const struct nx_async_config *msg = ofpmsg_body(oh);
4581 uint32_t master[OAM_N_TYPES];
4582 uint32_t slave[OAM_N_TYPES];
4584 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4585 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4586 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4588 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4589 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4590 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4592 ofconn_set_async_config(ofconn, master, slave);
4593 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4594 !ofconn_get_miss_send_len(ofconn)) {
4595 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4602 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
4605 uint32_t master[OAM_N_TYPES];
4606 uint32_t slave[OAM_N_TYPES];
4607 struct nx_async_config *msg;
4609 ofconn_get_async_config(ofconn, master, slave);
4610 buf = ofpraw_alloc_reply(OFPRAW_OFPT13_GET_ASYNC_REPLY, oh, 0);
4611 msg = ofpbuf_put_zeros(buf, sizeof *msg);
4613 msg->packet_in_mask[0] = htonl(master[OAM_PACKET_IN]);
4614 msg->port_status_mask[0] = htonl(master[OAM_PORT_STATUS]);
4615 msg->flow_removed_mask[0] = htonl(master[OAM_FLOW_REMOVED]);
4617 msg->packet_in_mask[1] = htonl(slave[OAM_PACKET_IN]);
4618 msg->port_status_mask[1] = htonl(slave[OAM_PORT_STATUS]);
4619 msg->flow_removed_mask[1] = htonl(slave[OAM_FLOW_REMOVED]);
4621 ofconn_send_reply(ofconn, buf);
4627 handle_nxt_set_controller_id(struct ofconn *ofconn,
4628 const struct ofp_header *oh)
4630 const struct nx_controller_id *nci = ofpmsg_body(oh);
4632 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4633 return OFPERR_NXBRC_MUST_BE_ZERO;
4636 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4641 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4645 if (ofconn_has_pending_opgroups(ofconn)) {
4646 return OFPROTO_POSTPONE;
4649 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4650 ? OFPRAW_OFPT10_BARRIER_REPLY
4651 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4652 ofconn_send_reply(ofconn, buf);
4657 ofproto_compose_flow_refresh_update(const struct rule *rule,
4658 enum nx_flow_monitor_flags flags,
4660 OVS_REQUIRES(ofproto_mutex)
4662 struct ofoperation *op = rule->pending;
4663 const struct rule_actions *actions;
4664 struct ofputil_flow_update fu;
4667 if (op && op->type == OFOPERATION_ADD) {
4668 /* We'll report the final flow when the operation completes. Reporting
4669 * it now would cause a duplicate report later. */
4673 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4674 ? NXFME_ADDED : NXFME_MODIFIED);
4676 ovs_mutex_lock(&rule->mutex);
4677 fu.idle_timeout = rule->idle_timeout;
4678 fu.hard_timeout = rule->hard_timeout;
4679 ovs_mutex_unlock(&rule->mutex);
4680 fu.table_id = rule->table_id;
4681 fu.cookie = rule->flow_cookie;
4682 minimatch_expand(&rule->cr.match, &match);
4684 fu.priority = rule->cr.priority;
4686 if (!(flags & NXFMF_ACTIONS)) {
4689 actions = rule->actions;
4691 /* An operation is in progress. Use the previous version of the flow's
4692 * actions, so that when the operation commits we report the change. */
4694 case OFOPERATION_ADD:
4697 case OFOPERATION_MODIFY:
4698 case OFOPERATION_REPLACE:
4699 actions = op->actions ? op->actions : rule->actions;
4702 case OFOPERATION_DELETE:
4703 actions = rule->actions;
4710 fu.ofpacts = actions ? actions->ofpacts : NULL;
4711 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4713 if (list_is_empty(msgs)) {
4714 ofputil_start_flow_update(msgs);
4716 ofputil_append_flow_update(&fu, msgs);
4720 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4722 OVS_REQUIRES(ofproto_mutex)
4726 for (i = 0; i < rules->n; i++) {
4727 struct rule *rule = rules->rules[i];
4728 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4729 rule->monitor_flags = 0;
4731 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4736 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4737 struct rule *rule, uint64_t seqno,
4738 struct rule_collection *rules)
4739 OVS_REQUIRES(ofproto_mutex)
4741 enum nx_flow_monitor_flags update;
4743 if (ofproto_rule_is_hidden(rule)) {
4748 ? ofoperation_has_out_port(rule->pending, m->out_port)
4749 : ofproto_rule_has_out_port(rule, m->out_port))) {
4754 if (rule->add_seqno > seqno) {
4755 update = NXFMF_ADD | NXFMF_MODIFY;
4756 } else if (rule->modify_seqno > seqno) {
4757 update = NXFMF_MODIFY;
4762 if (!(m->flags & update)) {
4766 update = NXFMF_INITIAL;
4769 if (!rule->monitor_flags) {
4770 rule_collection_add(rules, rule);
4772 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4776 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4778 struct rule_collection *rules)
4779 OVS_REQUIRES(ofproto_mutex)
4781 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4782 const struct ofoperation *op;
4783 const struct oftable *table;
4784 struct cls_rule target;
4786 cls_rule_init_from_minimatch(&target, &m->match, 0);
4787 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4788 struct cls_cursor cursor;
4791 ovs_rwlock_rdlock(&table->cls.rwlock);
4792 cls_cursor_init(&cursor, &table->cls, &target);
4793 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4794 ovs_assert(!rule->pending); /* XXX */
4795 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4797 ovs_rwlock_unlock(&table->cls.rwlock);
4800 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4801 struct rule *rule = op->rule;
4803 if (((m->table_id == 0xff
4804 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4805 : m->table_id == rule->table_id))
4806 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4807 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4810 cls_rule_destroy(&target);
4814 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4815 struct rule_collection *rules)
4816 OVS_REQUIRES(ofproto_mutex)
4818 if (m->flags & NXFMF_INITIAL) {
4819 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4824 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4825 uint64_t seqno, struct rule_collection *rules)
4826 OVS_REQUIRES(ofproto_mutex)
4828 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4832 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4833 OVS_EXCLUDED(ofproto_mutex)
4835 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4836 struct ofmonitor **monitors;
4837 size_t n_monitors, allocated_monitors;
4838 struct rule_collection rules;
4839 struct list replies;
4845 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4847 n_monitors = allocated_monitors = 0;
4849 ovs_mutex_lock(&ofproto_mutex);
4851 struct ofputil_flow_monitor_request request;
4852 struct ofmonitor *m;
4855 retval = ofputil_decode_flow_monitor_request(&request, &b);
4856 if (retval == EOF) {
4858 } else if (retval) {
4863 if (request.table_id != 0xff
4864 && request.table_id >= ofproto->n_tables) {
4865 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4869 error = ofmonitor_create(&request, ofconn, &m);
4874 if (n_monitors >= allocated_monitors) {
4875 monitors = x2nrealloc(monitors, &allocated_monitors,
4878 monitors[n_monitors++] = m;
4881 rule_collection_init(&rules);
4882 for (i = 0; i < n_monitors; i++) {
4883 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4886 ofpmp_init(&replies, oh);
4887 ofmonitor_compose_refresh_updates(&rules, &replies);
4888 ovs_mutex_unlock(&ofproto_mutex);
4890 rule_collection_destroy(&rules);
4892 ofconn_send_replies(ofconn, &replies);
4898 for (i = 0; i < n_monitors; i++) {
4899 ofmonitor_destroy(monitors[i]);
4902 ovs_mutex_unlock(&ofproto_mutex);
4908 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4909 OVS_EXCLUDED(ofproto_mutex)
4911 struct ofmonitor *m;
4915 id = ofputil_decode_flow_monitor_cancel(oh);
4917 ovs_mutex_lock(&ofproto_mutex);
4918 m = ofmonitor_lookup(ofconn, id);
4920 ofmonitor_destroy(m);
4923 error = OFPERR_NXBRC_FM_BAD_ID;
4925 ovs_mutex_unlock(&ofproto_mutex);
4930 /* Meters implementation.
4932 * Meter table entry, indexed by the OpenFlow meter_id.
4933 * These are always dynamically allocated to allocate enough space for
4935 * 'created' is used to compute the duration for meter stats.
4936 * 'list rules' is needed so that we can delete the dependent rules when the
4937 * meter table entry is deleted.
4938 * 'provider_meter_id' is for the provider's private use.
4941 long long int created; /* Time created. */
4942 struct list rules; /* List of "struct rule_dpif"s. */
4943 ofproto_meter_id provider_meter_id;
4944 uint16_t flags; /* Meter flags. */
4945 uint16_t n_bands; /* Number of meter bands. */
4946 struct ofputil_meter_band *bands;
4950 * This is used in instruction validation at flow set-up time,
4951 * as flows may not use non-existing meters.
4952 * Return value of UINT32_MAX signifies an invalid meter.
4955 get_provider_meter_id(const struct ofproto *ofproto, uint32_t of_meter_id)
4957 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4958 const struct meter *meter = ofproto->meters[of_meter_id];
4960 return meter->provider_meter_id.uint32;
4967 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4971 meter->flags = config->flags;
4972 meter->n_bands = config->n_bands;
4973 meter->bands = xmemdup(config->bands,
4974 config->n_bands * sizeof *meter->bands);
4977 static struct meter *
4978 meter_create(const struct ofputil_meter_config *config,
4979 ofproto_meter_id provider_meter_id)
4981 struct meter *meter;
4983 meter = xzalloc(sizeof *meter);
4984 meter->provider_meter_id = provider_meter_id;
4985 meter->created = time_msec();
4986 list_init(&meter->rules);
4988 meter_update(meter, config);
4994 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
4995 OVS_REQUIRES(ofproto_mutex)
4998 for (mid = first; mid <= last; ++mid) {
4999 struct meter *meter = ofproto->meters[mid];
5001 ofproto->meters[mid] = NULL;
5002 ofproto->ofproto_class->meter_del(ofproto,
5003 meter->provider_meter_id);
5011 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5013 ofproto_meter_id provider_meter_id = { UINT32_MAX };
5014 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
5018 return OFPERR_OFPMMFC_METER_EXISTS;
5021 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
5024 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
5025 *meterp = meter_create(&mm->meter, provider_meter_id);
5031 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5033 struct meter *meter = ofproto->meters[mm->meter.meter_id];
5035 uint32_t provider_meter_id;
5038 return OFPERR_OFPMMFC_UNKNOWN_METER;
5041 provider_meter_id = meter->provider_meter_id.uint32;
5042 error = ofproto->ofproto_class->meter_set(ofproto,
5043 &meter->provider_meter_id,
5045 ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
5047 meter_update(meter, &mm->meter);
5053 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
5054 struct ofputil_meter_mod *mm)
5055 OVS_EXCLUDED(ofproto_mutex)
5057 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5058 uint32_t meter_id = mm->meter.meter_id;
5059 struct rule_collection rules;
5060 enum ofperr error = 0;
5061 uint32_t first, last;
5063 if (meter_id == OFPM13_ALL) {
5065 last = ofproto->meter_features.max_meters;
5067 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
5070 first = last = meter_id;
5073 /* First delete the rules that use this meter. If any of those rules are
5074 * currently being modified, postpone the whole operation until later. */
5075 rule_collection_init(&rules);
5076 ovs_mutex_lock(&ofproto_mutex);
5077 for (meter_id = first; meter_id <= last; ++meter_id) {
5078 struct meter *meter = ofproto->meters[meter_id];
5079 if (meter && !list_is_empty(&meter->rules)) {
5082 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
5083 if (rule->pending) {
5084 error = OFPROTO_POSTPONE;
5087 rule_collection_add(&rules, rule);
5092 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
5095 /* Delete the meters. */
5096 meter_delete(ofproto, first, last);
5099 ovs_mutex_unlock(&ofproto_mutex);
5100 rule_collection_destroy(&rules);
5106 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5108 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5109 struct ofputil_meter_mod mm;
5110 uint64_t bands_stub[256 / 8];
5111 struct ofpbuf bands;
5115 error = reject_slave_controller(ofconn);
5120 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5122 error = ofputil_decode_meter_mod(oh, &mm, &bands);
5124 goto exit_free_bands;
5127 meter_id = mm.meter.meter_id;
5129 if (mm.command != OFPMC13_DELETE) {
5130 /* Fails also when meters are not implemented by the provider. */
5131 if (meter_id == 0 || meter_id > OFPM13_MAX) {
5132 error = OFPERR_OFPMMFC_INVALID_METER;
5133 goto exit_free_bands;
5134 } else if (meter_id > ofproto->meter_features.max_meters) {
5135 error = OFPERR_OFPMMFC_OUT_OF_METERS;
5136 goto exit_free_bands;
5138 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
5139 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
5140 goto exit_free_bands;
5144 switch (mm.command) {
5146 error = handle_add_meter(ofproto, &mm);
5149 case OFPMC13_MODIFY:
5150 error = handle_modify_meter(ofproto, &mm);
5153 case OFPMC13_DELETE:
5154 error = handle_delete_meter(ofconn, oh, &mm);
5158 error = OFPERR_OFPMMFC_BAD_COMMAND;
5163 ofpbuf_uninit(&bands);
5168 handle_meter_features_request(struct ofconn *ofconn,
5169 const struct ofp_header *request)
5171 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5172 struct ofputil_meter_features features;
5175 if (ofproto->ofproto_class->meter_get_features) {
5176 ofproto->ofproto_class->meter_get_features(ofproto, &features);
5178 memset(&features, 0, sizeof features);
5180 b = ofputil_encode_meter_features_reply(&features, request);
5182 ofconn_send_reply(ofconn, b);
5187 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
5190 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5191 struct list replies;
5192 uint64_t bands_stub[256 / 8];
5193 struct ofpbuf bands;
5194 uint32_t meter_id, first, last;
5196 ofputil_decode_meter_request(request, &meter_id);
5198 if (meter_id == OFPM13_ALL) {
5200 last = ofproto->meter_features.max_meters;
5202 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
5203 !ofproto->meters[meter_id]) {
5204 return OFPERR_OFPMMFC_UNKNOWN_METER;
5206 first = last = meter_id;
5209 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5210 ofpmp_init(&replies, request);
5212 for (meter_id = first; meter_id <= last; ++meter_id) {
5213 struct meter *meter = ofproto->meters[meter_id];
5215 continue; /* Skip non-existing meters. */
5217 if (type == OFPTYPE_METER_STATS_REQUEST) {
5218 struct ofputil_meter_stats stats;
5220 stats.meter_id = meter_id;
5222 /* Provider sets the packet and byte counts, we do the rest. */
5223 stats.flow_count = list_size(&meter->rules);
5224 calc_duration(meter->created, time_msec(),
5225 &stats.duration_sec, &stats.duration_nsec);
5226 stats.n_bands = meter->n_bands;
5227 ofpbuf_clear(&bands);
5229 = ofpbuf_put_uninit(&bands,
5230 meter->n_bands * sizeof *stats.bands);
5232 if (!ofproto->ofproto_class->meter_get(ofproto,
5233 meter->provider_meter_id,
5235 ofputil_append_meter_stats(&replies, &stats);
5237 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
5238 struct ofputil_meter_config config;
5240 config.meter_id = meter_id;
5241 config.flags = meter->flags;
5242 config.n_bands = meter->n_bands;
5243 config.bands = meter->bands;
5244 ofputil_append_meter_config(&replies, &config);
5248 ofconn_send_replies(ofconn, &replies);
5249 ofpbuf_uninit(&bands);
5254 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
5255 struct ofgroup **group)
5256 OVS_TRY_RDLOCK(true, (*group)->rwlock)
5258 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5259 HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5260 hash_int(group_id, 0), &ofproto->groups) {
5261 if ((*group)->group_id == group_id) {
5262 ovs_rwlock_rdlock(&(*group)->rwlock);
5263 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5267 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5272 ofproto_group_release(struct ofgroup *group)
5273 OVS_RELEASES(group->rwlock)
5275 ovs_rwlock_unlock(&group->rwlock);
5279 ofproto_group_write_lookup(const struct ofproto *ofproto, uint32_t group_id,
5280 struct ofgroup **group)
5281 OVS_TRY_WRLOCK(true, ofproto->groups_rwlock)
5282 OVS_TRY_WRLOCK(true, (*group)->rwlock)
5284 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5285 HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5286 hash_int(group_id, 0), &ofproto->groups) {
5287 if ((*group)->group_id == group_id) {
5288 ovs_rwlock_wrlock(&(*group)->rwlock);
5292 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5297 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
5298 OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5300 struct ofgroup *grp;
5302 HMAP_FOR_EACH_IN_BUCKET (grp, hmap_node,
5303 hash_int(group_id, 0), &ofproto->groups) {
5304 if (grp->group_id == group_id) {
5312 append_group_stats(struct ofgroup *group, struct list *replies)
5313 OVS_REQ_RDLOCK(group->rwlock)
5315 struct ofputil_group_stats ogs;
5316 struct ofproto *ofproto = group->ofproto;
5317 long long int now = time_msec();
5320 ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
5322 error = (ofproto->ofproto_class->group_get_stats
5323 ? ofproto->ofproto_class->group_get_stats(group, &ogs)
5326 ogs.ref_count = UINT32_MAX;
5327 ogs.packet_count = UINT64_MAX;
5328 ogs.byte_count = UINT64_MAX;
5329 ogs.n_buckets = group->n_buckets;
5330 memset(ogs.bucket_stats, 0xff,
5331 ogs.n_buckets * sizeof *ogs.bucket_stats);
5334 ogs.group_id = group->group_id;
5335 calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
5337 ofputil_append_group_stats(replies, &ogs);
5339 free(ogs.bucket_stats);
5343 handle_group_stats_request(struct ofconn *ofconn,
5344 const struct ofp_header *request)
5346 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5347 struct list replies;
5349 struct ofgroup *group;
5352 error = ofputil_decode_group_stats_request(request, &group_id);
5357 ofpmp_init(&replies, request);
5359 if (group_id == OFPG_ALL) {
5360 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5361 HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5362 ovs_rwlock_rdlock(&group->rwlock);
5363 append_group_stats(group, &replies);
5364 ovs_rwlock_unlock(&group->rwlock);
5366 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5368 if (ofproto_group_lookup(ofproto, group_id, &group)) {
5369 append_group_stats(group, &replies);
5370 ofproto_group_release(group);
5374 ofconn_send_replies(ofconn, &replies);
5380 handle_group_desc_stats_request(struct ofconn *ofconn,
5381 const struct ofp_header *request)
5383 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5384 struct list replies;
5385 struct ofputil_group_desc gds;
5386 struct ofgroup *group;
5388 ofpmp_init(&replies, request);
5390 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5391 HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5392 gds.group_id = group->group_id;
5393 gds.type = group->type;
5394 ofputil_append_group_desc_reply(&gds, &group->buckets, &replies);
5396 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5398 ofconn_send_replies(ofconn, &replies);
5404 handle_group_features_stats_request(struct ofconn *ofconn,
5405 const struct ofp_header *request)
5407 struct ofproto *p = ofconn_get_ofproto(ofconn);
5410 msg = ofputil_encode_group_features_reply(&p->ogf, request);
5412 ofconn_send_reply(ofconn, msg);
5418 /* Implements OFPGC11_ADD
5419 * in which no matching flow already exists in the flow table.
5421 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
5422 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
5423 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
5424 * initiated now but may be retried later.
5426 * Upon successful return, takes ownership of 'fm->ofpacts'. On failure,
5427 * ownership remains with the caller.
5429 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
5432 add_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5434 struct ofgroup *ofgroup;
5437 if (gm->group_id > OFPG_MAX) {
5438 return OFPERR_OFPGMFC_INVALID_GROUP;
5440 if (gm->type > OFPGT11_FF) {
5441 return OFPERR_OFPGMFC_BAD_TYPE;
5444 /* Allocate new group and initialize it. */
5445 ofgroup = ofproto->ofproto_class->group_alloc();
5447 VLOG_WARN_RL(&rl, "%s: failed to create group", ofproto->name);
5448 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5451 ovs_rwlock_init(&ofgroup->rwlock);
5452 ofgroup->ofproto = ofproto;
5453 ofgroup->group_id = gm->group_id;
5454 ofgroup->type = gm->type;
5455 ofgroup->created = ofgroup->modified = time_msec();
5457 list_move(&ofgroup->buckets, &gm->buckets);
5458 ofgroup->n_buckets = list_size(&ofgroup->buckets);
5460 /* Construct called BEFORE any locks are held. */
5461 error = ofproto->ofproto_class->group_construct(ofgroup);
5466 /* We wrlock as late as possible to minimize the time we jam any other
5467 * threads: No visible state changes before acquiring the lock. */
5468 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5470 if (ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5471 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5475 if (ofproto_group_exists(ofproto, gm->group_id)) {
5476 error = OFPERR_OFPGMFC_GROUP_EXISTS;
5481 /* Insert new group. */
5482 hmap_insert(&ofproto->groups, &ofgroup->hmap_node,
5483 hash_int(ofgroup->group_id, 0));
5484 ofproto->n_groups[ofgroup->type]++;
5486 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5491 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5492 ofproto->ofproto_class->group_destruct(ofgroup);
5494 ofputil_bucket_list_destroy(&ofgroup->buckets);
5495 ofproto->ofproto_class->group_dealloc(ofgroup);
5500 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
5503 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
5506 modify_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5508 struct ofgroup *ofgroup;
5509 struct ofgroup *victim;
5512 if (gm->group_id > OFPG_MAX) {
5513 return OFPERR_OFPGMFC_INVALID_GROUP;
5516 if (gm->type > OFPGT11_FF) {
5517 return OFPERR_OFPGMFC_BAD_TYPE;
5520 victim = ofproto->ofproto_class->group_alloc();
5522 VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
5523 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5526 if (!ofproto_group_write_lookup(ofproto, gm->group_id, &ofgroup)) {
5527 error = OFPERR_OFPGMFC_UNKNOWN_GROUP;
5530 /* Both group's and its container's write locks held now.
5531 * Also, n_groups[] is protected by ofproto->groups_rwlock. */
5532 if (ofgroup->type != gm->type
5533 && ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5534 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5539 list_move(&victim->buckets, &ofgroup->buckets);
5541 ofgroup->type = gm->type;
5542 list_move(&ofgroup->buckets, &gm->buckets);
5543 ofgroup->n_buckets = list_size(&ofgroup->buckets);
5545 error = ofproto->ofproto_class->group_modify(ofgroup, victim);
5547 ofputil_bucket_list_destroy(&victim->buckets);
5548 ofproto->n_groups[victim->type]--;
5549 ofproto->n_groups[ofgroup->type]++;
5550 ofgroup->modified = time_msec();
5552 ofputil_bucket_list_destroy(&ofgroup->buckets);
5555 list_move(&ofgroup->buckets, &victim->buckets);
5559 ovs_rwlock_unlock(&ofgroup->rwlock);
5560 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5562 ofproto->ofproto_class->group_dealloc(victim);
5567 delete_group__(struct ofproto *ofproto, struct ofgroup *ofgroup)
5568 OVS_RELEASES(ofproto->groups_rwlock)
5570 /* Must wait until existing readers are done,
5571 * while holding the container's write lock at the same time. */
5572 ovs_rwlock_wrlock(&ofgroup->rwlock);
5573 hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5574 /* No-one can find this group any more. */
5575 ofproto->n_groups[ofgroup->type]--;
5576 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5578 ofproto->ofproto_class->group_destruct(ofgroup);
5579 ofputil_bucket_list_destroy(&ofgroup->buckets);
5580 ovs_rwlock_unlock(&ofgroup->rwlock);
5581 ovs_rwlock_destroy(&ofgroup->rwlock);
5582 ofproto->ofproto_class->group_dealloc(ofgroup);
5585 /* Implements OFPGC_DELETE. */
5587 delete_group(struct ofproto *ofproto, uint32_t group_id)
5589 struct ofgroup *ofgroup;
5591 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5592 if (group_id == OFPG_ALL) {
5594 struct hmap_node *node = hmap_first(&ofproto->groups);
5598 ofgroup = CONTAINER_OF(node, struct ofgroup, hmap_node);
5599 delete_group__(ofproto, ofgroup);
5600 /* Lock for each node separately, so that we will not jam the
5601 * other threads for too long time. */
5602 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5605 HMAP_FOR_EACH_IN_BUCKET (ofgroup, hmap_node,
5606 hash_int(group_id, 0), &ofproto->groups) {
5607 if (ofgroup->group_id == group_id) {
5608 delete_group__(ofproto, ofgroup);
5613 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5617 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5619 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5620 struct ofputil_group_mod gm;
5623 error = reject_slave_controller(ofconn);
5628 error = ofputil_decode_group_mod(oh, &gm);
5633 switch (gm.command) {
5635 return add_group(ofproto, &gm);
5637 case OFPGC11_MODIFY:
5638 return modify_group(ofproto, &gm);
5640 case OFPGC11_DELETE:
5641 delete_group(ofproto, gm.group_id);
5645 if (gm.command > OFPGC11_DELETE) {
5646 VLOG_WARN_RL(&rl, "%s: Invalid group_mod command type %d",
5647 ofproto->name, gm.command);
5649 return OFPERR_OFPGMFC_BAD_COMMAND;
5654 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5656 struct ofputil_table_mod tm;
5659 error = reject_slave_controller(ofconn);
5664 error = ofputil_decode_table_mod(oh, &tm);
5669 /* XXX Actual table mod support is not implemented yet. */
5674 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
5675 OVS_EXCLUDED(ofproto_mutex)
5677 const struct ofp_header *oh = msg->data;
5681 error = ofptype_decode(&type, oh);
5685 if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
5686 && ofpmp_more(oh)) {
5687 /* We have no buffer implementation for multipart requests.
5688 * Report overflow for requests which consists of multiple
5690 return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
5694 /* OpenFlow requests. */
5695 case OFPTYPE_ECHO_REQUEST:
5696 return handle_echo_request(ofconn, oh);
5698 case OFPTYPE_FEATURES_REQUEST:
5699 return handle_features_request(ofconn, oh);
5701 case OFPTYPE_GET_CONFIG_REQUEST:
5702 return handle_get_config_request(ofconn, oh);
5704 case OFPTYPE_SET_CONFIG:
5705 return handle_set_config(ofconn, oh);
5707 case OFPTYPE_PACKET_OUT:
5708 return handle_packet_out(ofconn, oh);
5710 case OFPTYPE_PORT_MOD:
5711 return handle_port_mod(ofconn, oh);
5713 case OFPTYPE_FLOW_MOD:
5714 return handle_flow_mod(ofconn, oh);
5716 case OFPTYPE_GROUP_MOD:
5717 return handle_group_mod(ofconn, oh);
5719 case OFPTYPE_TABLE_MOD:
5720 return handle_table_mod(ofconn, oh);
5722 case OFPTYPE_METER_MOD:
5723 return handle_meter_mod(ofconn, oh);
5725 case OFPTYPE_BARRIER_REQUEST:
5726 return handle_barrier_request(ofconn, oh);
5728 case OFPTYPE_ROLE_REQUEST:
5729 return handle_role_request(ofconn, oh);
5731 /* OpenFlow replies. */
5732 case OFPTYPE_ECHO_REPLY:
5735 /* Nicira extension requests. */
5736 case OFPTYPE_FLOW_MOD_TABLE_ID:
5737 return handle_nxt_flow_mod_table_id(ofconn, oh);
5739 case OFPTYPE_SET_FLOW_FORMAT:
5740 return handle_nxt_set_flow_format(ofconn, oh);
5742 case OFPTYPE_SET_PACKET_IN_FORMAT:
5743 return handle_nxt_set_packet_in_format(ofconn, oh);
5745 case OFPTYPE_SET_CONTROLLER_ID:
5746 return handle_nxt_set_controller_id(ofconn, oh);
5748 case OFPTYPE_FLOW_AGE:
5749 /* Nothing to do. */
5752 case OFPTYPE_FLOW_MONITOR_CANCEL:
5753 return handle_flow_monitor_cancel(ofconn, oh);
5755 case OFPTYPE_SET_ASYNC_CONFIG:
5756 return handle_nxt_set_async_config(ofconn, oh);
5758 case OFPTYPE_GET_ASYNC_REQUEST:
5759 return handle_nxt_get_async_request(ofconn, oh);
5761 /* Statistics requests. */
5762 case OFPTYPE_DESC_STATS_REQUEST:
5763 return handle_desc_stats_request(ofconn, oh);
5765 case OFPTYPE_FLOW_STATS_REQUEST:
5766 return handle_flow_stats_request(ofconn, oh);
5768 case OFPTYPE_AGGREGATE_STATS_REQUEST:
5769 return handle_aggregate_stats_request(ofconn, oh);
5771 case OFPTYPE_TABLE_STATS_REQUEST:
5772 return handle_table_stats_request(ofconn, oh);
5774 case OFPTYPE_PORT_STATS_REQUEST:
5775 return handle_port_stats_request(ofconn, oh);
5777 case OFPTYPE_QUEUE_STATS_REQUEST:
5778 return handle_queue_stats_request(ofconn, oh);
5780 case OFPTYPE_PORT_DESC_STATS_REQUEST:
5781 return handle_port_desc_stats_request(ofconn, oh);
5783 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
5784 return handle_flow_monitor_request(ofconn, oh);
5786 case OFPTYPE_METER_STATS_REQUEST:
5787 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
5788 return handle_meter_request(ofconn, oh, type);
5790 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
5791 return handle_meter_features_request(ofconn, oh);
5793 case OFPTYPE_GROUP_STATS_REQUEST:
5794 return handle_group_stats_request(ofconn, oh);
5796 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
5797 return handle_group_desc_stats_request(ofconn, oh);
5799 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
5800 return handle_group_features_stats_request(ofconn, oh);
5802 /* FIXME: Change the following once they are implemented: */
5803 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
5804 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
5809 case OFPTYPE_FEATURES_REPLY:
5810 case OFPTYPE_GET_CONFIG_REPLY:
5811 case OFPTYPE_PACKET_IN:
5812 case OFPTYPE_FLOW_REMOVED:
5813 case OFPTYPE_PORT_STATUS:
5814 case OFPTYPE_BARRIER_REPLY:
5815 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
5816 case OFPTYPE_DESC_STATS_REPLY:
5817 case OFPTYPE_FLOW_STATS_REPLY:
5818 case OFPTYPE_QUEUE_STATS_REPLY:
5819 case OFPTYPE_PORT_STATS_REPLY:
5820 case OFPTYPE_TABLE_STATS_REPLY:
5821 case OFPTYPE_AGGREGATE_STATS_REPLY:
5822 case OFPTYPE_PORT_DESC_STATS_REPLY:
5823 case OFPTYPE_ROLE_REPLY:
5824 case OFPTYPE_FLOW_MONITOR_PAUSED:
5825 case OFPTYPE_FLOW_MONITOR_RESUMED:
5826 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
5827 case OFPTYPE_GET_ASYNC_REPLY:
5828 case OFPTYPE_GROUP_STATS_REPLY:
5829 case OFPTYPE_GROUP_DESC_STATS_REPLY:
5830 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
5831 case OFPTYPE_METER_STATS_REPLY:
5832 case OFPTYPE_METER_CONFIG_STATS_REPLY:
5833 case OFPTYPE_METER_FEATURES_STATS_REPLY:
5834 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
5836 if (ofpmsg_is_stat_request(oh)) {
5837 return OFPERR_OFPBRC_BAD_STAT;
5839 return OFPERR_OFPBRC_BAD_TYPE;
5845 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
5846 OVS_EXCLUDED(ofproto_mutex)
5848 int error = handle_openflow__(ofconn, ofp_msg);
5849 if (error && error != OFPROTO_POSTPONE) {
5850 ofconn_send_error(ofconn, ofp_msg->data, error);
5852 COVERAGE_INC(ofproto_recv_openflow);
5853 return error != OFPROTO_POSTPONE;
5856 /* Asynchronous operations. */
5858 /* Creates and returns a new ofopgroup that is not associated with any
5859 * OpenFlow connection.
5861 * The caller should add operations to the returned group with
5862 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5863 static struct ofopgroup *
5864 ofopgroup_create_unattached(struct ofproto *ofproto)
5865 OVS_REQUIRES(ofproto_mutex)
5867 struct ofopgroup *group = xzalloc(sizeof *group);
5868 group->ofproto = ofproto;
5869 list_init(&group->ofproto_node);
5870 list_init(&group->ops);
5871 list_init(&group->ofconn_node);
5875 /* Creates and returns a new ofopgroup for 'ofproto'.
5877 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
5878 * connection. The 'request' and 'buffer_id' arguments are ignored.
5880 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
5881 * If the ofopgroup eventually fails, then the error reply will include
5882 * 'request'. If the ofopgroup eventually succeeds, then the packet with
5883 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
5885 * The caller should add operations to the returned group with
5886 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5887 static struct ofopgroup *
5888 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
5889 const struct ofp_header *request, uint32_t buffer_id)
5890 OVS_REQUIRES(ofproto_mutex)
5892 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
5894 size_t request_len = ntohs(request->length);
5896 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
5898 ofconn_add_opgroup(ofconn, &group->ofconn_node);
5899 group->ofconn = ofconn;
5900 group->request = xmemdup(request, MIN(request_len, 64));
5901 group->buffer_id = buffer_id;
5906 /* Submits 'group' for processing.
5908 * If 'group' contains no operations (e.g. none were ever added, or all of the
5909 * ones that were added completed synchronously), then it is destroyed
5910 * immediately. Otherwise it is added to the ofproto's list of pending
5913 ofopgroup_submit(struct ofopgroup *group)
5914 OVS_REQUIRES(ofproto_mutex)
5916 if (!group->n_running) {
5917 ofopgroup_complete(group);
5919 list_push_back(&group->ofproto->pending, &group->ofproto_node);
5920 group->ofproto->n_pending++;
5925 ofopgroup_complete(struct ofopgroup *group)
5926 OVS_REQUIRES(ofproto_mutex)
5928 struct ofproto *ofproto = group->ofproto;
5930 struct ofconn *abbrev_ofconn;
5931 ovs_be32 abbrev_xid;
5933 struct ofoperation *op, *next_op;
5936 ovs_assert(!group->n_running);
5939 LIST_FOR_EACH (op, group_node, &group->ops) {
5946 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
5947 LIST_FOR_EACH (op, group_node, &group->ops) {
5948 if (op->type != OFOPERATION_DELETE) {
5949 struct ofpbuf *packet;
5952 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
5955 struct rule_execute *re;
5959 ofproto_rule_ref(op->rule);
5961 re = xmalloc(sizeof *re);
5962 re->rule = op->rule;
5963 re->in_port = in_port;
5964 re->packet = packet;
5966 if (!guarded_list_push_back(&ofproto->rule_executes,
5967 &re->list_node, 1024)) {
5968 ofproto_rule_unref(op->rule);
5969 ofpbuf_delete(re->packet);
5978 if (!error && !list_is_empty(&group->ofconn_node)) {
5979 abbrev_ofconn = group->ofconn;
5980 abbrev_xid = group->request->xid;
5982 abbrev_ofconn = NULL;
5983 abbrev_xid = htonl(0);
5985 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
5986 struct rule *rule = op->rule;
5988 /* We generally want to report the change to active OpenFlow flow
5989 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
5991 - The operation failed.
5993 - The affected rule is not visible to controllers.
5995 - The operation's only effect was to update rule->modified. */
5997 || ofproto_rule_is_hidden(rule)
5998 || (op->type == OFOPERATION_MODIFY
6000 && rule->flow_cookie == op->flow_cookie))) {
6001 /* Check that we can just cast from ofoperation_type to
6002 * nx_flow_update_event. */
6003 enum nx_flow_update_event event_type;
6006 case OFOPERATION_ADD:
6007 case OFOPERATION_REPLACE:
6008 event_type = NXFME_ADDED;
6011 case OFOPERATION_DELETE:
6012 event_type = NXFME_DELETED;
6015 case OFOPERATION_MODIFY:
6016 event_type = NXFME_MODIFIED;
6023 ofmonitor_report(ofproto->connmgr, rule, event_type,
6024 op->reason, abbrev_ofconn, abbrev_xid);
6027 rule->pending = NULL;
6030 case OFOPERATION_ADD:
6034 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
6035 if (vid_mask == VLAN_VID_MASK) {
6036 if (ofproto->vlan_bitmap) {
6037 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
6038 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
6039 bitmap_set1(ofproto->vlan_bitmap, vid);
6040 ofproto->vlans_changed = true;
6043 ofproto->vlans_changed = true;
6047 oftable_remove_rule(rule);
6048 ofproto_rule_unref(rule);
6052 case OFOPERATION_DELETE:
6053 ovs_assert(!op->error);
6054 ofproto_rule_unref(rule);
6058 case OFOPERATION_MODIFY:
6059 case OFOPERATION_REPLACE:
6061 long long int now = time_msec();
6063 rule->modified = now;
6064 if (op->type == OFOPERATION_REPLACE) {
6065 rule->created = rule->used = now;
6068 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
6069 ovs_mutex_lock(&rule->mutex);
6070 rule->idle_timeout = op->idle_timeout;
6071 rule->hard_timeout = op->hard_timeout;
6072 ovs_mutex_unlock(&rule->mutex);
6074 struct rule_actions *old_actions;
6076 ovs_mutex_lock(&rule->mutex);
6077 old_actions = rule->actions;
6078 rule->actions = op->actions;
6079 ovs_mutex_unlock(&rule->mutex);
6082 rule_actions_unref(old_actions);
6084 rule->flags = op->flags;
6092 ofoperation_destroy(op);
6095 ofmonitor_flush(ofproto->connmgr);
6097 if (!list_is_empty(&group->ofproto_node)) {
6098 ovs_assert(ofproto->n_pending > 0);
6099 ofproto->n_pending--;
6100 list_remove(&group->ofproto_node);
6102 if (!list_is_empty(&group->ofconn_node)) {
6103 list_remove(&group->ofconn_node);
6105 ofconn_send_error(group->ofconn, group->request, error);
6107 connmgr_retry(ofproto->connmgr);
6109 free(group->request);
6113 /* Initiates a new operation on 'rule', of the specified 'type', within
6114 * 'group'. Prior to calling, 'rule' must not have any pending operation.
6116 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
6117 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
6119 * Returns the newly created ofoperation (which is also available as
6120 * rule->pending). */
6121 static struct ofoperation *
6122 ofoperation_create(struct ofopgroup *group, struct rule *rule,
6123 enum ofoperation_type type,
6124 enum ofp_flow_removed_reason reason)
6125 OVS_REQUIRES(ofproto_mutex)
6127 struct ofproto *ofproto = group->ofproto;
6128 struct ofoperation *op;
6130 ovs_assert(!rule->pending);
6132 op = rule->pending = xzalloc(sizeof *op);
6134 list_push_back(&group->ops, &op->group_node);
6137 op->reason = reason;
6138 op->flow_cookie = rule->flow_cookie;
6139 ovs_mutex_lock(&rule->mutex);
6140 op->idle_timeout = rule->idle_timeout;
6141 op->hard_timeout = rule->hard_timeout;
6142 ovs_mutex_unlock(&rule->mutex);
6143 op->flags = rule->flags;
6147 if (type == OFOPERATION_DELETE) {
6148 hmap_insert(&ofproto->deletions, &op->hmap_node,
6149 cls_rule_hash(&rule->cr, rule->table_id));
6156 ofoperation_destroy(struct ofoperation *op)
6157 OVS_REQUIRES(ofproto_mutex)
6159 struct ofopgroup *group = op->group;
6162 op->rule->pending = NULL;
6164 if (op->type == OFOPERATION_DELETE) {
6165 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
6167 list_remove(&op->group_node);
6168 rule_actions_unref(op->actions);
6172 /* Indicates that 'op' completed with status 'error', which is either 0 to
6173 * indicate success or an OpenFlow error code on failure.
6175 * If 'error' is 0, indicating success, the operation will be committed
6176 * permanently to the flow table.
6178 * If 'error' is nonzero, then generally the operation will be rolled back:
6180 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
6181 * restores the original rule. The caller must have uninitialized any
6182 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
6183 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
6184 * and 7 for the new rule, calling its ->rule_dealloc() function.
6186 * - If 'op' is a "modify flow" operation, ofproto restores the original
6189 * - 'op' must not be a "delete flow" operation. Removing a rule is not
6190 * allowed to fail. It must always succeed.
6192 * Please see the large comment in ofproto/ofproto-provider.h titled
6193 * "Asynchronous Operation Support" for more information. */
6195 ofoperation_complete(struct ofoperation *op, enum ofperr error)
6197 struct ofopgroup *group = op->group;
6199 ovs_assert(group->n_running > 0);
6200 ovs_assert(!error || op->type != OFOPERATION_DELETE);
6203 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
6204 /* This function can be called from ->rule_construct(), in which case
6205 * ofproto_mutex is held, or it can be called from ->run(), in which
6206 * case ofproto_mutex is not held. But only in the latter case can we
6207 * arrive here, so we can safely take ofproto_mutex now. */
6208 ovs_mutex_lock(&ofproto_mutex);
6209 ovs_assert(op->rule->pending == op);
6210 ofopgroup_complete(group);
6211 ovs_mutex_unlock(&ofproto_mutex);
6216 pick_datapath_id(const struct ofproto *ofproto)
6218 const struct ofport *port;
6220 port = ofproto_get_port(ofproto, OFPP_LOCAL);
6222 uint8_t ea[ETH_ADDR_LEN];
6225 error = netdev_get_etheraddr(port->netdev, ea);
6227 return eth_addr_to_uint64(ea);
6229 VLOG_WARN("%s: could not get MAC address for %s (%s)",
6230 ofproto->name, netdev_get_name(port->netdev),
6231 ovs_strerror(error));
6233 return ofproto->fallback_dpid;
6237 pick_fallback_dpid(void)
6239 uint8_t ea[ETH_ADDR_LEN];
6240 eth_addr_nicira_random(ea);
6241 return eth_addr_to_uint64(ea);
6244 /* Table overflow policy. */
6246 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
6247 * to NULL if the table is not configured to evict rules or if the table
6248 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
6249 * or with no timeouts are not evictable.) */
6251 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
6252 OVS_REQUIRES(ofproto_mutex)
6254 struct eviction_group *evg;
6257 if (!table->eviction_fields) {
6261 /* In the common case, the outer and inner loops here will each be entered
6264 * - The inner loop normally "return"s in its first iteration. If the
6265 * eviction group has any evictable rules, then it always returns in
6268 * - The outer loop only iterates more than once if the largest eviction
6269 * group has no evictable rules.
6271 * - The outer loop can exit only if table's 'max_flows' is all filled up
6272 * by unevictable rules. */
6273 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
6276 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
6285 /* Searches 'ofproto' for tables that have more flows than their configured
6286 * maximum and that have flow eviction enabled, and evicts as many flows as
6287 * necessary and currently feasible from them.
6289 * This triggers only when an OpenFlow table has N flows in it and then the
6290 * client configures a maximum number of flows less than N. */
6292 ofproto_evict(struct ofproto *ofproto)
6294 struct oftable *table;
6296 ovs_mutex_lock(&ofproto_mutex);
6297 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
6298 evict_rules_from_table(ofproto, table, 0);
6300 ovs_mutex_unlock(&ofproto_mutex);
6303 /* Eviction groups. */
6305 /* Returns the priority to use for an eviction_group that contains 'n_rules'
6306 * rules. The priority contains low-order random bits to ensure that eviction
6307 * groups with the same number of rules are prioritized randomly. */
6309 eviction_group_priority(size_t n_rules)
6311 uint16_t size = MIN(UINT16_MAX, n_rules);
6312 return (size << 16) | random_uint16();
6315 /* Updates 'evg', an eviction_group within 'table', following a change that
6316 * adds or removes rules in 'evg'. */
6318 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
6319 OVS_REQUIRES(ofproto_mutex)
6321 heap_change(&table->eviction_groups_by_size, &evg->size_node,
6322 eviction_group_priority(heap_count(&evg->rules)));
6325 /* Destroys 'evg', an eviction_group within 'table':
6327 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
6328 * rules themselves, just removes them from the eviction group.)
6330 * - Removes 'evg' from 'table'.
6334 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
6335 OVS_REQUIRES(ofproto_mutex)
6337 while (!heap_is_empty(&evg->rules)) {
6340 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
6341 rule->eviction_group = NULL;
6343 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
6344 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
6345 heap_destroy(&evg->rules);
6349 /* Removes 'rule' from its eviction group, if any. */
6351 eviction_group_remove_rule(struct rule *rule)
6352 OVS_REQUIRES(ofproto_mutex)
6354 if (rule->eviction_group) {
6355 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6356 struct eviction_group *evg = rule->eviction_group;
6358 rule->eviction_group = NULL;
6359 heap_remove(&evg->rules, &rule->evg_node);
6360 if (heap_is_empty(&evg->rules)) {
6361 eviction_group_destroy(table, evg);
6363 eviction_group_resized(table, evg);
6368 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
6369 * returns the hash value. */
6371 eviction_group_hash_rule(struct rule *rule)
6372 OVS_REQUIRES(ofproto_mutex)
6374 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6375 const struct mf_subfield *sf;
6379 hash = table->eviction_group_id_basis;
6380 miniflow_expand(&rule->cr.match.flow, &flow);
6381 for (sf = table->eviction_fields;
6382 sf < &table->eviction_fields[table->n_eviction_fields];
6385 if (mf_are_prereqs_ok(sf->field, &flow)) {
6386 union mf_value value;
6388 mf_get_value(sf->field, &flow, &value);
6390 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
6392 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
6393 unsigned int start = sf->ofs + sf->n_bits;
6394 bitwise_zero(&value, sf->field->n_bytes, start,
6395 sf->field->n_bytes * 8 - start);
6397 hash = hash_bytes(&value, sf->field->n_bytes, hash);
6399 hash = hash_int(hash, 0);
6406 /* Returns an eviction group within 'table' with the given 'id', creating one
6408 static struct eviction_group *
6409 eviction_group_find(struct oftable *table, uint32_t id)
6410 OVS_REQUIRES(ofproto_mutex)
6412 struct eviction_group *evg;
6414 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
6418 evg = xmalloc(sizeof *evg);
6419 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
6420 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
6421 eviction_group_priority(0));
6422 heap_init(&evg->rules);
6427 /* Returns an eviction priority for 'rule'. The return value should be
6428 * interpreted so that higher priorities make a rule more attractive candidates
6431 rule_eviction_priority(struct rule *rule)
6432 OVS_REQUIRES(ofproto_mutex)
6434 long long int hard_expiration;
6435 long long int idle_expiration;
6436 long long int expiration;
6437 uint32_t expiration_offset;
6439 /* Calculate time of expiration. */
6440 ovs_mutex_lock(&rule->mutex);
6441 hard_expiration = (rule->hard_timeout
6442 ? rule->modified + rule->hard_timeout * 1000
6444 idle_expiration = (rule->idle_timeout
6445 ? rule->used + rule->idle_timeout * 1000
6447 expiration = MIN(hard_expiration, idle_expiration);
6448 ovs_mutex_unlock(&rule->mutex);
6449 if (expiration == LLONG_MAX) {
6453 /* Calculate the time of expiration as a number of (approximate) seconds
6454 * after program startup.
6456 * This should work OK for program runs that last UINT32_MAX seconds or
6457 * less. Therefore, please restart OVS at least once every 136 years. */
6458 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
6460 /* Invert the expiration offset because we're using a max-heap. */
6461 return UINT32_MAX - expiration_offset;
6464 /* Adds 'rule' to an appropriate eviction group for its oftable's
6465 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
6466 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
6469 * The caller must ensure that 'rule' is not already in an eviction group. */
6471 eviction_group_add_rule(struct rule *rule)
6472 OVS_REQUIRES(ofproto_mutex)
6474 struct ofproto *ofproto = rule->ofproto;
6475 struct oftable *table = &ofproto->tables[rule->table_id];
6478 ovs_mutex_lock(&rule->mutex);
6479 has_timeout = rule->hard_timeout || rule->idle_timeout;
6480 ovs_mutex_unlock(&rule->mutex);
6482 if (table->eviction_fields && has_timeout) {
6483 struct eviction_group *evg;
6485 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
6487 rule->eviction_group = evg;
6488 heap_insert(&evg->rules, &rule->evg_node,
6489 rule_eviction_priority(rule));
6490 eviction_group_resized(table, evg);
6496 /* Initializes 'table'. */
6498 oftable_init(struct oftable *table)
6500 memset(table, 0, sizeof *table);
6501 classifier_init(&table->cls);
6502 table->max_flows = UINT_MAX;
6505 /* Destroys 'table', including its classifier and eviction groups.
6507 * The caller is responsible for freeing 'table' itself. */
6509 oftable_destroy(struct oftable *table)
6511 ovs_rwlock_rdlock(&table->cls.rwlock);
6512 ovs_assert(classifier_is_empty(&table->cls));
6513 ovs_rwlock_unlock(&table->cls.rwlock);
6514 oftable_disable_eviction(table);
6515 classifier_destroy(&table->cls);
6519 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
6520 * string, then 'table' will use its default name.
6522 * This only affects the name exposed for a table exposed through the OpenFlow
6523 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
6525 oftable_set_name(struct oftable *table, const char *name)
6527 if (name && name[0]) {
6528 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
6529 if (!table->name || strncmp(name, table->name, len)) {
6531 table->name = xmemdup0(name, len);
6539 /* oftables support a choice of two policies when adding a rule would cause the
6540 * number of flows in the table to exceed the configured maximum number: either
6541 * they can refuse to add the new flow or they can evict some existing flow.
6542 * This function configures the former policy on 'table'. */
6544 oftable_disable_eviction(struct oftable *table)
6545 OVS_REQUIRES(ofproto_mutex)
6547 if (table->eviction_fields) {
6548 struct eviction_group *evg, *next;
6550 HMAP_FOR_EACH_SAFE (evg, next, id_node,
6551 &table->eviction_groups_by_id) {
6552 eviction_group_destroy(table, evg);
6554 hmap_destroy(&table->eviction_groups_by_id);
6555 heap_destroy(&table->eviction_groups_by_size);
6557 free(table->eviction_fields);
6558 table->eviction_fields = NULL;
6559 table->n_eviction_fields = 0;
6563 /* oftables support a choice of two policies when adding a rule would cause the
6564 * number of flows in the table to exceed the configured maximum number: either
6565 * they can refuse to add the new flow or they can evict some existing flow.
6566 * This function configures the latter policy on 'table', with fairness based
6567 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
6568 * 'n_fields' as 0 disables fairness.) */
6570 oftable_enable_eviction(struct oftable *table,
6571 const struct mf_subfield *fields, size_t n_fields)
6572 OVS_REQUIRES(ofproto_mutex)
6574 struct cls_cursor cursor;
6577 if (table->eviction_fields
6578 && n_fields == table->n_eviction_fields
6580 || !memcmp(fields, table->eviction_fields,
6581 n_fields * sizeof *fields))) {
6586 oftable_disable_eviction(table);
6588 table->n_eviction_fields = n_fields;
6589 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
6591 table->eviction_group_id_basis = random_uint32();
6592 hmap_init(&table->eviction_groups_by_id);
6593 heap_init(&table->eviction_groups_by_size);
6595 ovs_rwlock_rdlock(&table->cls.rwlock);
6596 cls_cursor_init(&cursor, &table->cls, NULL);
6597 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6598 eviction_group_add_rule(rule);
6600 ovs_rwlock_unlock(&table->cls.rwlock);
6603 /* Removes 'rule' from the oftable that contains it. */
6605 oftable_remove_rule__(struct ofproto *ofproto, struct rule *rule)
6606 OVS_REQUIRES(ofproto_mutex)
6608 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
6610 ovs_rwlock_wrlock(&cls->rwlock);
6611 classifier_remove(cls, CONST_CAST(struct cls_rule *, &rule->cr));
6612 ovs_rwlock_unlock(&cls->rwlock);
6614 cookies_remove(ofproto, rule);
6616 eviction_group_remove_rule(rule);
6617 if (!list_is_empty(&rule->expirable)) {
6618 list_remove(&rule->expirable);
6620 if (!list_is_empty(&rule->meter_list_node)) {
6621 list_remove(&rule->meter_list_node);
6622 list_init(&rule->meter_list_node);
6627 oftable_remove_rule(struct rule *rule)
6628 OVS_REQUIRES(ofproto_mutex)
6630 oftable_remove_rule__(rule->ofproto, rule);
6633 /* Inserts 'rule' into its oftable, which must not already contain any rule for
6634 * the same cls_rule. */
6636 oftable_insert_rule(struct rule *rule)
6637 OVS_REQUIRES(ofproto_mutex)
6639 struct ofproto *ofproto = rule->ofproto;
6640 struct oftable *table = &ofproto->tables[rule->table_id];
6643 ovs_mutex_lock(&rule->mutex);
6644 may_expire = rule->hard_timeout || rule->idle_timeout;
6645 ovs_mutex_unlock(&rule->mutex);
6648 list_insert(&ofproto->expirable, &rule->expirable);
6651 cookies_insert(ofproto, rule);
6653 if (rule->actions->provider_meter_id != UINT32_MAX) {
6654 uint32_t meter_id = ofpacts_get_meter(rule->actions->ofpacts,
6655 rule->actions->ofpacts_len);
6656 struct meter *meter = ofproto->meters[meter_id];
6657 list_insert(&meter->rules, &rule->meter_list_node);
6659 ovs_rwlock_wrlock(&table->cls.rwlock);
6660 classifier_insert(&table->cls, CONST_CAST(struct cls_rule *, &rule->cr));
6661 ovs_rwlock_unlock(&table->cls.rwlock);
6662 eviction_group_add_rule(rule);
6665 /* unixctl commands. */
6668 ofproto_lookup(const char *name)
6670 struct ofproto *ofproto;
6672 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
6674 if (!strcmp(ofproto->name, name)) {
6682 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
6683 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6685 struct ofproto *ofproto;
6689 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
6690 ds_put_format(&results, "%s\n", ofproto->name);
6692 unixctl_command_reply(conn, ds_cstr(&results));
6693 ds_destroy(&results);
6697 ofproto_unixctl_init(void)
6699 static bool registered;
6705 unixctl_command_register("ofproto/list", "", 0, 0,
6706 ofproto_unixctl_list, NULL);
6709 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6711 * This is deprecated. It is only for compatibility with broken device drivers
6712 * in old versions of Linux that do not properly support VLANs when VLAN
6713 * devices are not used. When broken device drivers are no longer in
6714 * widespread use, we will delete these interfaces. */
6716 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
6717 * (exactly) by an OpenFlow rule in 'ofproto'. */
6719 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
6721 const struct oftable *oftable;
6723 free(ofproto->vlan_bitmap);
6724 ofproto->vlan_bitmap = bitmap_allocate(4096);
6725 ofproto->vlans_changed = false;
6727 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
6728 const struct cls_table *table;
6730 ovs_rwlock_rdlock(&oftable->cls.rwlock);
6731 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
6732 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
6733 const struct cls_rule *rule;
6735 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
6736 uint16_t vid = miniflow_get_vid(&rule->match.flow);
6737 bitmap_set1(vlan_bitmap, vid);
6738 bitmap_set1(ofproto->vlan_bitmap, vid);
6742 ovs_rwlock_unlock(&oftable->cls.rwlock);
6746 /* Returns true if new VLANs have come into use by the flow table since the
6747 * last call to ofproto_get_vlan_usage().
6749 * We don't track when old VLANs stop being used. */
6751 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
6753 return ofproto->vlans_changed;
6756 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
6757 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
6758 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
6759 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
6760 * then the VLAN device is un-enslaved. */
6762 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
6763 ofp_port_t realdev_ofp_port, int vid)
6765 struct ofport *ofport;
6768 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
6770 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
6772 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
6773 ofproto->name, vlandev_ofp_port);
6777 if (!ofproto->ofproto_class->set_realdev) {
6778 if (!vlandev_ofp_port) {
6781 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
6785 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
6787 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
6788 ofproto->name, vlandev_ofp_port,
6789 netdev_get_name(ofport->netdev), ovs_strerror(error));