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"
55 #include "unaligned.h"
59 VLOG_DEFINE_THIS_MODULE(ofproto);
61 COVERAGE_DEFINE(ofproto_flush);
62 COVERAGE_DEFINE(ofproto_packet_out);
63 COVERAGE_DEFINE(ofproto_queue_req);
64 COVERAGE_DEFINE(ofproto_recv_openflow);
65 COVERAGE_DEFINE(ofproto_reinit_ports);
66 COVERAGE_DEFINE(ofproto_update_port);
69 S_OPENFLOW, /* Processing OpenFlow commands. */
70 S_EVICT, /* Evicting flows from over-limit tables. */
71 S_FLUSH, /* Deleting all flow table rules. */
74 enum ofoperation_type {
81 /* A single OpenFlow request can execute any number of operations. The
82 * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
83 * ofconn to which an error reply should be sent if necessary.
85 * ofproto initiates some operations internally. These operations are still
86 * assigned to groups but will not have an associated ofconn. */
88 struct ofproto *ofproto; /* Owning ofproto. */
89 struct list ofproto_node; /* In ofproto's "pending" list. */
90 struct list ops; /* List of "struct ofoperation"s. */
91 int n_running; /* Number of ops still pending. */
93 /* Data needed to send OpenFlow reply on failure or to send a buffered
96 * If list_is_empty(ofconn_node) then this ofopgroup never had an
97 * associated ofconn or its ofconn's connection dropped after it initiated
98 * the operation. In the latter case 'ofconn' is a wild pointer that
99 * refers to freed memory, so the 'ofconn' member must be used only if
100 * !list_is_empty(ofconn_node).
102 struct list ofconn_node; /* In ofconn's list of pending opgroups. */
103 struct ofconn *ofconn; /* ofconn for reply (but see note above). */
104 struct ofp_header *request; /* Original request (truncated at 64 bytes). */
105 uint32_t buffer_id; /* Buffer id from original request. */
108 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
109 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
110 const struct ofp_header *,
112 static void ofopgroup_submit(struct ofopgroup *);
113 static void ofopgroup_complete(struct ofopgroup *);
115 /* A single flow table operation. */
117 struct ofopgroup *group; /* Owning group. */
118 struct list group_node; /* In ofopgroup's "ops" list. */
119 struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
120 struct rule *rule; /* Rule being operated upon. */
121 enum ofoperation_type type; /* Type of operation. */
123 /* OFOPERATION_MODIFY, OFOPERATION_REPLACE: The old actions, if the actions
125 struct rule_actions *actions;
127 /* OFOPERATION_DELETE. */
128 enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
130 ovs_be64 flow_cookie; /* Rule's old flow cookie. */
131 uint16_t idle_timeout; /* Rule's old idle timeout. */
132 uint16_t hard_timeout; /* Rule's old hard timeout. */
133 enum ofputil_flow_mod_flags flags; /* Rule's old flags. */
134 enum ofperr error; /* 0 if no error. */
137 static struct ofoperation *ofoperation_create(struct ofopgroup *,
139 enum ofoperation_type,
140 enum ofp_flow_removed_reason);
141 static void ofoperation_destroy(struct ofoperation *);
144 static void oftable_init(struct oftable *);
145 static void oftable_destroy(struct oftable *);
147 static void oftable_set_name(struct oftable *, const char *name);
149 static void oftable_disable_eviction(struct oftable *);
150 static void oftable_enable_eviction(struct oftable *,
151 const struct mf_subfield *fields,
154 static void oftable_remove_rule(struct rule *rule) OVS_REQUIRES(ofproto_mutex);
155 static void oftable_remove_rule__(struct ofproto *, struct rule *)
156 OVS_REQUIRES(ofproto_mutex);
157 static void oftable_insert_rule(struct rule *);
159 /* A set of rules within a single OpenFlow table (oftable) that have the same
160 * values for the oftable's eviction_fields. A rule to be evicted, when one is
161 * needed, is taken from the eviction group that contains the greatest number
164 * An oftable owns any number of eviction groups, each of which contains any
167 * Membership in an eviction group is imprecise, based on the hash of the
168 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
169 * That is, if two rules have different eviction_fields, but those
170 * eviction_fields hash to the same value, then they will belong to the same
171 * eviction_group anyway.
173 * (When eviction is not enabled on an oftable, we don't track any eviction
174 * groups, to save time and space.) */
175 struct eviction_group {
176 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
177 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
178 struct heap rules; /* Contains "struct rule"s. */
181 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep);
182 static void ofproto_evict(struct ofproto *) OVS_EXCLUDED(ofproto_mutex);
183 static uint32_t rule_eviction_priority(struct rule *);
184 static void eviction_group_add_rule(struct rule *);
185 static void eviction_group_remove_rule(struct rule *);
187 /* Criteria that flow_mod and other operations use for selecting rules on
188 * which to operate. */
189 struct rule_criteria {
190 /* An OpenFlow table or 255 for all tables. */
193 /* OpenFlow matching criteria. Interpreted different in "loose" way by
194 * collect_rules_loose() and "strict" way by collect_rules_strict(), as
195 * defined in the OpenFlow spec. */
198 /* Matching criteria for the OpenFlow cookie. Consider a bit B in a rule's
199 * cookie and the corresponding bits C in 'cookie' and M in 'cookie_mask'.
200 * The rule will not be selected if M is 1 and B != C. */
202 ovs_be64 cookie_mask;
204 /* Selection based on actions within a rule:
206 * If out_port != OFPP_ANY, selects only rules that output to out_port.
207 * If out_group != OFPG_ALL, select only rules that output to out_group. */
212 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
213 const struct match *match,
214 unsigned int priority,
215 ovs_be64 cookie, ovs_be64 cookie_mask,
216 ofp_port_t out_port, uint32_t out_group);
217 static void rule_criteria_destroy(struct rule_criteria *);
219 /* A packet that needs to be passed to rule_execute().
221 * (We can't do this immediately from ofopgroup_complete() because that holds
222 * ofproto_mutex, which rule_execute() needs released.) */
223 struct rule_execute {
224 struct list list_node; /* In struct ofproto's "rule_executes" list. */
225 struct rule *rule; /* Owns a reference to the rule. */
227 struct ofpbuf *packet; /* Owns the packet. */
230 static void run_rule_executes(struct ofproto *) OVS_EXCLUDED(ofproto_mutex);
231 static void destroy_rule_executes(struct ofproto *);
234 static void ofport_destroy__(struct ofport *) OVS_EXCLUDED(ofproto_mutex);
235 static void ofport_destroy(struct ofport *);
237 static void update_port(struct ofproto *, const char *devname);
238 static int init_ports(struct ofproto *);
239 static void reinit_ports(struct ofproto *);
241 static long long int ofport_get_usage(const struct ofproto *,
242 ofp_port_t ofp_port);
243 static void ofport_set_usage(struct ofproto *, ofp_port_t ofp_port,
244 long long int last_used);
245 static void ofport_remove_usage(struct ofproto *, ofp_port_t ofp_port);
249 * Keeps track of the currently used and recently used ofport values and is
250 * used to prevent immediate recycling of ofport values. */
251 struct ofport_usage {
252 struct hmap_node hmap_node; /* In struct ofproto's "ofport_usage" hmap. */
253 ofp_port_t ofp_port; /* OpenFlow port number. */
254 long long int last_used; /* Last time the 'ofp_port' was used. LLONG_MAX
255 represents in-use ofports. */
259 static void ofproto_rule_destroy__(struct rule *);
260 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
261 static bool rule_is_modifiable(const struct rule *);
264 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
265 struct ofputil_flow_mod *,
266 const struct ofp_header *);
267 static enum ofperr modify_flows__(struct ofproto *, struct ofconn *,
268 struct ofputil_flow_mod *,
269 const struct ofp_header *,
270 const struct rule_collection *);
271 static void delete_flow__(struct rule *rule, struct ofopgroup *,
272 enum ofp_flow_removed_reason)
273 OVS_REQUIRES(ofproto_mutex);
274 static bool ofproto_group_exists__(const struct ofproto *ofproto,
276 OVS_REQ_RDLOCK(ofproto->groups_rwlock);
277 static bool ofproto_group_exists(const struct ofproto *ofproto,
279 OVS_EXCLUDED(ofproto->groups_rwlock);
280 static enum ofperr add_group(struct ofproto *, struct ofputil_group_mod *);
281 static bool handle_openflow(struct ofconn *, const struct ofpbuf *);
282 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
283 struct ofputil_flow_mod *,
284 const struct ofp_header *)
285 OVS_EXCLUDED(ofproto_mutex);
286 static void calc_duration(long long int start, long long int now,
287 uint32_t *sec, uint32_t *nsec);
290 static uint64_t pick_datapath_id(const struct ofproto *);
291 static uint64_t pick_fallback_dpid(void);
292 static void ofproto_destroy__(struct ofproto *);
293 static void update_mtu(struct ofproto *, struct ofport *);
294 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
297 static void ofproto_unixctl_init(void);
299 /* All registered ofproto classes, in probe order. */
300 static const struct ofproto_class **ofproto_classes;
301 static size_t n_ofproto_classes;
302 static size_t allocated_ofproto_classes;
304 /* Global lock that protects all flow table operations. */
305 struct ovs_mutex ofproto_mutex = OVS_MUTEX_INITIALIZER;
307 unsigned flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT;
308 unsigned n_handler_threads;
309 enum ofproto_flow_miss_model flow_miss_model = OFPROTO_HANDLE_MISS_AUTO;
311 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
312 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
314 /* Initial mappings of port to OpenFlow number mappings. */
315 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
317 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
319 /* The default value of true waits for flow restore. */
320 static bool flow_restore_wait = true;
322 /* Must be called to initialize the ofproto library.
324 * The caller may pass in 'iface_hints', which contains an shash of
325 * "iface_hint" elements indexed by the interface's name. The provider
326 * may use these hints to describe the startup configuration in order to
327 * reinitialize its state. The caller owns the provided data, so a
328 * provider will make copies of anything required. An ofproto provider
329 * will remove any existing state that is not described by the hint, and
330 * may choose to remove it all. */
332 ofproto_init(const struct shash *iface_hints)
334 struct shash_node *node;
337 ofproto_class_register(&ofproto_dpif_class);
339 /* Make a local copy, since we don't own 'iface_hints' elements. */
340 SHASH_FOR_EACH(node, iface_hints) {
341 const struct iface_hint *orig_hint = node->data;
342 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
343 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
345 new_hint->br_name = xstrdup(orig_hint->br_name);
346 new_hint->br_type = xstrdup(br_type);
347 new_hint->ofp_port = orig_hint->ofp_port;
349 shash_add(&init_ofp_ports, node->name, new_hint);
352 for (i = 0; i < n_ofproto_classes; i++) {
353 ofproto_classes[i]->init(&init_ofp_ports);
357 /* 'type' should be a normalized datapath type, as returned by
358 * ofproto_normalize_type(). Returns the corresponding ofproto_class
359 * structure, or a null pointer if there is none registered for 'type'. */
360 static const struct ofproto_class *
361 ofproto_class_find__(const char *type)
365 for (i = 0; i < n_ofproto_classes; i++) {
366 const struct ofproto_class *class = ofproto_classes[i];
371 class->enumerate_types(&types);
372 found = sset_contains(&types, type);
373 sset_destroy(&types);
379 VLOG_WARN("unknown datapath type %s", type);
383 /* Registers a new ofproto class. After successful registration, new ofprotos
384 * of that type can be created using ofproto_create(). */
386 ofproto_class_register(const struct ofproto_class *new_class)
390 for (i = 0; i < n_ofproto_classes; i++) {
391 if (ofproto_classes[i] == new_class) {
396 if (n_ofproto_classes >= allocated_ofproto_classes) {
397 ofproto_classes = x2nrealloc(ofproto_classes,
398 &allocated_ofproto_classes,
399 sizeof *ofproto_classes);
401 ofproto_classes[n_ofproto_classes++] = new_class;
405 /* Unregisters a datapath provider. 'type' must have been previously
406 * registered and not currently be in use by any ofprotos. After
407 * unregistration new datapaths of that type cannot be opened using
408 * ofproto_create(). */
410 ofproto_class_unregister(const struct ofproto_class *class)
414 for (i = 0; i < n_ofproto_classes; i++) {
415 if (ofproto_classes[i] == class) {
416 for (i++; i < n_ofproto_classes; i++) {
417 ofproto_classes[i - 1] = ofproto_classes[i];
423 VLOG_WARN("attempted to unregister an ofproto class that is not "
428 /* Clears 'types' and enumerates all registered ofproto types into it. The
429 * caller must first initialize the sset. */
431 ofproto_enumerate_types(struct sset *types)
435 for (i = 0; i < n_ofproto_classes; i++) {
436 ofproto_classes[i]->enumerate_types(types);
440 /* Returns the fully spelled out name for the given ofproto 'type'.
442 * Normalized type string can be compared with strcmp(). Unnormalized type
443 * string might be the same even if they have different spellings. */
445 ofproto_normalize_type(const char *type)
447 return type && type[0] ? type : "system";
450 /* Clears 'names' and enumerates the names of all known created ofprotos with
451 * the given 'type'. The caller must first initialize the sset. Returns 0 if
452 * successful, otherwise a positive errno value.
454 * Some kinds of datapaths might not be practically enumerable. This is not
455 * considered an error. */
457 ofproto_enumerate_names(const char *type, struct sset *names)
459 const struct ofproto_class *class = ofproto_class_find__(type);
460 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
464 ofproto_create(const char *datapath_name, const char *datapath_type,
465 struct ofproto **ofprotop)
467 const struct ofproto_class *class;
468 struct ofproto *ofproto;
474 ofproto_unixctl_init();
476 datapath_type = ofproto_normalize_type(datapath_type);
477 class = ofproto_class_find__(datapath_type);
479 VLOG_WARN("could not create datapath %s of unknown type %s",
480 datapath_name, datapath_type);
484 ofproto = class->alloc();
486 VLOG_ERR("failed to allocate datapath %s of type %s",
487 datapath_name, datapath_type);
492 ovs_mutex_lock(&ofproto_mutex);
493 memset(ofproto, 0, sizeof *ofproto);
494 ofproto->ofproto_class = class;
495 ofproto->name = xstrdup(datapath_name);
496 ofproto->type = xstrdup(datapath_type);
497 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
498 hash_string(ofproto->name, 0));
499 ofproto->datapath_id = 0;
500 ofproto->forward_bpdu = false;
501 ofproto->fallback_dpid = pick_fallback_dpid();
502 ofproto->mfr_desc = NULL;
503 ofproto->hw_desc = NULL;
504 ofproto->sw_desc = NULL;
505 ofproto->serial_desc = NULL;
506 ofproto->dp_desc = NULL;
507 ofproto->frag_handling = OFPC_FRAG_NORMAL;
508 hmap_init(&ofproto->ports);
509 hmap_init(&ofproto->ofport_usage);
510 shash_init(&ofproto->port_by_name);
511 simap_init(&ofproto->ofp_requests);
512 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
513 ofproto->eviction_group_timer = LLONG_MIN;
514 ofproto->tables = NULL;
515 ofproto->n_tables = 0;
516 hindex_init(&ofproto->cookies);
517 list_init(&ofproto->expirable);
518 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
519 ofproto->state = S_OPENFLOW;
520 list_init(&ofproto->pending);
521 ofproto->n_pending = 0;
522 hmap_init(&ofproto->deletions);
523 guarded_list_init(&ofproto->rule_executes);
524 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
525 ofproto->first_op = ofproto->last_op = LLONG_MIN;
526 ofproto->next_op_report = LLONG_MAX;
527 ofproto->op_backoff = LLONG_MIN;
528 ofproto->vlan_bitmap = NULL;
529 ofproto->vlans_changed = false;
530 ofproto->min_mtu = INT_MAX;
531 ovs_rwlock_init(&ofproto->groups_rwlock);
532 hmap_init(&ofproto->groups);
533 ovs_mutex_unlock(&ofproto_mutex);
534 ofproto->ogf.capabilities = OFPGFC_CHAINING | OFPGFC_SELECT_LIVENESS |
535 OFPGFC_SELECT_WEIGHT;
536 ofproto->ogf.max_groups[OFPGT11_ALL] = OFPG_MAX;
537 ofproto->ogf.max_groups[OFPGT11_SELECT] = OFPG_MAX;
538 ofproto->ogf.max_groups[OFPGT11_INDIRECT] = OFPG_MAX;
539 ofproto->ogf.max_groups[OFPGT11_FF] = OFPG_MAX;
540 ofproto->ogf.actions[0] =
541 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) (1 << ENUM) |
542 #include "ofp-util.def"
545 error = ofproto->ofproto_class->construct(ofproto);
547 VLOG_ERR("failed to open datapath %s: %s",
548 datapath_name, ovs_strerror(error));
549 ofproto_destroy__(ofproto);
553 /* Check that hidden tables, if any, are at the end. */
554 ovs_assert(ofproto->n_tables);
555 for (i = 0; i + 1 < ofproto->n_tables; i++) {
556 enum oftable_flags flags = ofproto->tables[i].flags;
557 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
559 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
562 ofproto->datapath_id = pick_datapath_id(ofproto);
565 /* Initialize meters table. */
566 if (ofproto->ofproto_class->meter_get_features) {
567 ofproto->ofproto_class->meter_get_features(ofproto,
568 &ofproto->meter_features);
570 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
572 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
573 * sizeof(struct meter *));
579 /* Must be called (only) by an ofproto implementation in its constructor
580 * function. See the large comment on 'construct' in struct ofproto_class for
583 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
585 struct oftable *table;
587 ovs_assert(!ofproto->n_tables);
588 ovs_assert(n_tables >= 1 && n_tables <= 255);
590 ofproto->n_tables = n_tables;
591 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
592 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
597 /* To be optionally called (only) by an ofproto implementation in its
598 * constructor function. See the large comment on 'construct' in struct
599 * ofproto_class for details.
601 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
602 * will then ensure that actions passed into the ofproto implementation will
603 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
604 * function is not called, there will be no such restriction.
606 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
607 * the 'max_ports' restriction. */
609 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
611 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
612 ofproto->max_ports = max_ports;
616 ofproto_get_datapath_id(const struct ofproto *ofproto)
618 return ofproto->datapath_id;
622 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
624 uint64_t old_dpid = p->datapath_id;
625 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
626 if (p->datapath_id != old_dpid) {
627 /* Force all active connections to reconnect, since there is no way to
628 * notify a controller that the datapath ID has changed. */
629 ofproto_reconnect_controllers(p);
634 ofproto_set_controllers(struct ofproto *p,
635 const struct ofproto_controller *controllers,
636 size_t n_controllers, uint32_t allowed_versions)
638 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
643 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
645 connmgr_set_fail_mode(p->connmgr, fail_mode);
648 /* Drops the connections between 'ofproto' and all of its controllers, forcing
649 * them to reconnect. */
651 ofproto_reconnect_controllers(struct ofproto *ofproto)
653 connmgr_reconnect(ofproto->connmgr);
656 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
657 * in-band control should guarantee access, in the same way that in-band
658 * control guarantees access to OpenFlow controllers. */
660 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
661 const struct sockaddr_in *extras, size_t n)
663 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
666 /* Sets the OpenFlow queue used by flows set up by in-band control on
667 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
668 * flows will use the default queue. */
670 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
672 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
675 /* Sets the number of flows at which eviction from the kernel flow table
678 ofproto_set_flow_eviction_threshold(unsigned threshold)
680 flow_eviction_threshold = MAX(OFPROTO_FLOW_EVICTION_THRESHOLD_MIN,
684 /* Sets the path for handling flow misses. */
686 ofproto_set_flow_miss_model(unsigned model)
688 flow_miss_model = model;
691 /* If forward_bpdu is true, the NORMAL action will forward frames with
692 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
693 * the NORMAL action will drop these frames. */
695 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
697 bool old_val = ofproto->forward_bpdu;
698 ofproto->forward_bpdu = forward_bpdu;
699 if (old_val != ofproto->forward_bpdu) {
700 if (ofproto->ofproto_class->forward_bpdu_changed) {
701 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
706 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
707 * 'idle_time', in seconds, and the maximum number of MAC table entries to
710 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
713 if (ofproto->ofproto_class->set_mac_table_config) {
714 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
719 /* Sets number of upcall handler threads. The default is
720 * (number of online cores - 2). */
722 ofproto_set_n_handler_threads(unsigned limit)
725 n_handler_threads = limit;
727 int n_proc = sysconf(_SC_NPROCESSORS_ONLN);
728 n_handler_threads = n_proc > 2 ? n_proc - 2 : 1;
733 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
736 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
740 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
742 return connmgr_set_snoops(ofproto->connmgr, snoops);
746 ofproto_set_netflow(struct ofproto *ofproto,
747 const struct netflow_options *nf_options)
749 if (nf_options && sset_is_empty(&nf_options->collectors)) {
753 if (ofproto->ofproto_class->set_netflow) {
754 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
756 return nf_options ? EOPNOTSUPP : 0;
761 ofproto_set_sflow(struct ofproto *ofproto,
762 const struct ofproto_sflow_options *oso)
764 if (oso && sset_is_empty(&oso->targets)) {
768 if (ofproto->ofproto_class->set_sflow) {
769 return ofproto->ofproto_class->set_sflow(ofproto, oso);
771 return oso ? EOPNOTSUPP : 0;
776 ofproto_set_ipfix(struct ofproto *ofproto,
777 const struct ofproto_ipfix_bridge_exporter_options *bo,
778 const struct ofproto_ipfix_flow_exporter_options *fo,
781 if (ofproto->ofproto_class->set_ipfix) {
782 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
784 return (bo || fo) ? EOPNOTSUPP : 0;
789 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
791 flow_restore_wait = flow_restore_wait_db;
795 ofproto_get_flow_restore_wait(void)
797 return flow_restore_wait;
801 /* Spanning Tree Protocol (STP) configuration. */
803 /* Configures STP on 'ofproto' using the settings defined in 's'. If
804 * 's' is NULL, disables STP.
806 * Returns 0 if successful, otherwise a positive errno value. */
808 ofproto_set_stp(struct ofproto *ofproto,
809 const struct ofproto_stp_settings *s)
811 return (ofproto->ofproto_class->set_stp
812 ? ofproto->ofproto_class->set_stp(ofproto, s)
816 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
817 * 'enabled' member of 's' is false, then the other members are not
820 * Returns 0 if successful, otherwise a positive errno value. */
822 ofproto_get_stp_status(struct ofproto *ofproto,
823 struct ofproto_stp_status *s)
825 return (ofproto->ofproto_class->get_stp_status
826 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
830 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
831 * in 's'. The caller is responsible for assigning STP port numbers
832 * (using the 'port_num' member in the range of 1 through 255, inclusive)
833 * and ensuring there are no duplicates. If the 's' is NULL, then STP
834 * is disabled on the port.
836 * Returns 0 if successful, otherwise a positive errno value.*/
838 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
839 const struct ofproto_port_stp_settings *s)
841 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
843 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
844 ofproto->name, ofp_port);
848 return (ofproto->ofproto_class->set_stp_port
849 ? ofproto->ofproto_class->set_stp_port(ofport, s)
853 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
854 * 's'. If the 'enabled' member in 's' is false, then the other members
855 * are not meaningful.
857 * Returns 0 if successful, otherwise a positive errno value.*/
859 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
860 struct ofproto_port_stp_status *s)
862 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
864 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
865 "port %"PRIu16, ofproto->name, ofp_port);
869 return (ofproto->ofproto_class->get_stp_port_status
870 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
874 /* Queue DSCP configuration. */
876 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
877 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
878 * to implement QoS. Instead, it is used to implement features which require
879 * knowledge of what queues exist on a port, and some basic information about
882 * Returns 0 if successful, otherwise a positive errno value. */
884 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
885 const struct ofproto_port_queue *queues,
888 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
891 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
892 ofproto->name, ofp_port);
896 return (ofproto->ofproto_class->set_queues
897 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
901 /* Connectivity Fault Management configuration. */
903 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
905 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
907 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
908 if (ofport && ofproto->ofproto_class->set_cfm) {
909 ofproto->ofproto_class->set_cfm(ofport, NULL);
913 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
914 * basic configuration from the configuration members in 'cfm', and the remote
915 * maintenance point ID from remote_mpid. Ignores the statistics members of
918 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
920 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
921 const struct cfm_settings *s)
923 struct ofport *ofport;
926 ofport = ofproto_get_port(ofproto, ofp_port);
928 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
929 ofproto->name, ofp_port);
933 /* XXX: For configuration simplicity, we only support one remote_mpid
934 * outside of the CFM module. It's not clear if this is the correct long
935 * term solution or not. */
936 error = (ofproto->ofproto_class->set_cfm
937 ? ofproto->ofproto_class->set_cfm(ofport, s)
940 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
941 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
942 ovs_strerror(error));
946 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
947 * 'ofproto' does not have a port 'ofp_port'. */
949 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
950 const struct smap *cfg)
952 struct ofport *ofport;
955 ofport = ofproto_get_port(ofproto, ofp_port);
957 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
958 ofproto->name, ofp_port);
962 error = (ofproto->ofproto_class->set_bfd
963 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
966 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
967 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
968 ovs_strerror(error));
972 /* Populates 'status' with key value pairs indicating the status of the BFD
973 * session on 'ofp_port'. This information is intended to be populated in the
974 * OVS database. Has no effect if 'ofp_port' is not na OpenFlow port in
977 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
980 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
981 return (ofport && ofproto->ofproto_class->get_bfd_status
982 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
986 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
987 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
988 * 0 if LACP partner information is not current (generally indicating a
989 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
991 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
993 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
994 return (ofport && ofproto->ofproto_class->port_is_lacp_current
995 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
1001 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
1002 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
1003 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
1004 * configuration plus, if there is more than one slave, a bonding
1007 * If 'aux' is already registered then this function updates its configuration
1008 * to 's'. Otherwise, this function registers a new bundle.
1010 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
1013 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
1014 const struct ofproto_bundle_settings *s)
1016 return (ofproto->ofproto_class->bundle_set
1017 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1021 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1022 * If no such bundle has been registered, this has no effect. */
1024 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1026 return ofproto_bundle_register(ofproto, aux, NULL);
1030 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1031 * If 'aux' is already registered then this function updates its configuration
1032 * to 's'. Otherwise, this function registers a new mirror. */
1034 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1035 const struct ofproto_mirror_settings *s)
1037 return (ofproto->ofproto_class->mirror_set
1038 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1042 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1043 * If no mirror has been registered, this has no effect. */
1045 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1047 return ofproto_mirror_register(ofproto, aux, NULL);
1050 /* Retrieves statistics from mirror associated with client data pointer
1051 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1052 * 'bytes', respectively. If a particular counters is not supported,
1053 * the appropriate argument is set to UINT64_MAX. */
1055 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1056 uint64_t *packets, uint64_t *bytes)
1058 if (!ofproto->ofproto_class->mirror_get_stats) {
1059 *packets = *bytes = UINT64_MAX;
1063 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1067 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1068 * which all packets are flooded, instead of using MAC learning. If
1069 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1071 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1074 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1076 return (ofproto->ofproto_class->set_flood_vlans
1077 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1081 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1082 * output for a mirror. */
1084 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1086 return (ofproto->ofproto_class->is_mirror_output_bundle
1087 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1091 /* Configuration of OpenFlow tables. */
1093 /* Returns the number of OpenFlow tables in 'ofproto'. */
1095 ofproto_get_n_tables(const struct ofproto *ofproto)
1097 return ofproto->n_tables;
1100 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1101 * settings from 's'. 'table_id' must be in the range 0 through the number of
1102 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1104 * For read-only tables, only the name may be configured. */
1106 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1107 const struct ofproto_table_settings *s)
1109 struct oftable *table;
1111 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1112 table = &ofproto->tables[table_id];
1114 oftable_set_name(table, s->name);
1116 if (table->flags & OFTABLE_READONLY) {
1121 oftable_enable_eviction(table, s->groups, s->n_groups);
1123 oftable_disable_eviction(table);
1126 table->max_flows = s->max_flows;
1127 ovs_rwlock_rdlock(&table->cls.rwlock);
1128 if (classifier_count(&table->cls) > table->max_flows
1129 && table->eviction_fields) {
1130 /* 'table' contains more flows than allowed. We might not be able to
1131 * evict them right away because of the asynchronous nature of flow
1132 * table changes. Schedule eviction for later. */
1133 switch (ofproto->state) {
1135 ofproto->state = S_EVICT;
1139 /* We're already deleting flows, nothing more to do. */
1143 ovs_rwlock_unlock(&table->cls.rwlock);
1147 ofproto_has_snoops(const struct ofproto *ofproto)
1149 return connmgr_has_snoops(ofproto->connmgr);
1153 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1155 connmgr_get_snoops(ofproto->connmgr, snoops);
1159 ofproto_rule_delete__(struct ofproto *ofproto, struct rule *rule,
1161 OVS_REQUIRES(ofproto_mutex)
1163 struct ofopgroup *group;
1165 ovs_assert(!rule->pending);
1167 group = ofopgroup_create_unattached(ofproto);
1168 delete_flow__(rule, group, reason);
1169 ofopgroup_submit(group);
1172 /* Deletes 'rule' from 'cls' within 'ofproto'.
1174 * Within an ofproto implementation, this function allows an ofproto
1175 * implementation to destroy any rules that remain when its ->destruct()
1176 * function is called. This function is not suitable for use elsewhere in an
1177 * ofproto implementation.
1179 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1180 * Cycle" in ofproto-provider.h. */
1182 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1183 OVS_EXCLUDED(ofproto_mutex)
1185 struct ofopgroup *group;
1187 ovs_mutex_lock(&ofproto_mutex);
1188 ovs_assert(!rule->pending);
1190 group = ofopgroup_create_unattached(ofproto);
1191 ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1192 oftable_remove_rule__(ofproto, rule);
1193 ofproto->ofproto_class->rule_delete(rule);
1194 ofopgroup_submit(group);
1196 ovs_mutex_unlock(&ofproto_mutex);
1200 ofproto_flush__(struct ofproto *ofproto)
1201 OVS_EXCLUDED(ofproto_mutex)
1203 struct oftable *table;
1205 if (ofproto->ofproto_class->flush) {
1206 ofproto->ofproto_class->flush(ofproto);
1209 ovs_mutex_lock(&ofproto_mutex);
1210 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1211 struct rule *rule, *next_rule;
1212 struct cls_cursor cursor;
1214 if (table->flags & OFTABLE_HIDDEN) {
1218 ovs_rwlock_rdlock(&table->cls.rwlock);
1219 cls_cursor_init(&cursor, &table->cls, NULL);
1220 ovs_rwlock_unlock(&table->cls.rwlock);
1221 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1222 if (!rule->pending) {
1223 ofproto_rule_delete__(ofproto, rule, OFPRR_DELETE);
1227 ovs_mutex_unlock(&ofproto_mutex);
1230 static void delete_group(struct ofproto *ofproto, uint32_t group_id);
1233 ofproto_destroy__(struct ofproto *ofproto)
1234 OVS_EXCLUDED(ofproto_mutex)
1236 struct oftable *table;
1238 ovs_assert(list_is_empty(&ofproto->pending));
1240 destroy_rule_executes(ofproto);
1241 guarded_list_destroy(&ofproto->rule_executes);
1243 delete_group(ofproto, OFPG_ALL);
1244 ovs_rwlock_destroy(&ofproto->groups_rwlock);
1245 hmap_destroy(&ofproto->groups);
1247 connmgr_destroy(ofproto->connmgr);
1249 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1250 free(ofproto->name);
1251 free(ofproto->type);
1252 free(ofproto->mfr_desc);
1253 free(ofproto->hw_desc);
1254 free(ofproto->sw_desc);
1255 free(ofproto->serial_desc);
1256 free(ofproto->dp_desc);
1257 hmap_destroy(&ofproto->ports);
1258 hmap_destroy(&ofproto->ofport_usage);
1259 shash_destroy(&ofproto->port_by_name);
1260 simap_destroy(&ofproto->ofp_requests);
1262 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1263 oftable_destroy(table);
1265 free(ofproto->tables);
1267 hmap_destroy(&ofproto->deletions);
1269 free(ofproto->vlan_bitmap);
1271 ofproto->ofproto_class->dealloc(ofproto);
1275 ofproto_destroy(struct ofproto *p)
1276 OVS_EXCLUDED(ofproto_mutex)
1278 struct ofport *ofport, *next_ofport;
1279 struct ofport_usage *usage, *next_usage;
1286 meter_delete(p, 1, p->meter_features.max_meters);
1287 p->meter_features.max_meters = 0;
1293 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1294 ofport_destroy(ofport);
1297 HMAP_FOR_EACH_SAFE (usage, next_usage, hmap_node, &p->ofport_usage) {
1298 hmap_remove(&p->ofport_usage, &usage->hmap_node);
1302 p->ofproto_class->destruct(p);
1303 ofproto_destroy__(p);
1306 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1307 * kernel datapath, for example, this destroys the datapath in the kernel, and
1308 * with the netdev-based datapath, it tears down the data structures that
1309 * represent the datapath.
1311 * The datapath should not be currently open as an ofproto. */
1313 ofproto_delete(const char *name, const char *type)
1315 const struct ofproto_class *class = ofproto_class_find__(type);
1316 return (!class ? EAFNOSUPPORT
1317 : !class->del ? EACCES
1318 : class->del(type, name));
1322 process_port_change(struct ofproto *ofproto, int error, char *devname)
1324 if (error == ENOBUFS) {
1325 reinit_ports(ofproto);
1326 } else if (!error) {
1327 update_port(ofproto, devname);
1333 ofproto_type_run(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 ? class->type_run(datapath_type) : 0;
1342 if (error && error != EAGAIN) {
1343 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1344 datapath_type, ovs_strerror(error));
1350 ofproto_type_run_fast(const char *datapath_type)
1352 const struct ofproto_class *class;
1355 datapath_type = ofproto_normalize_type(datapath_type);
1356 class = ofproto_class_find__(datapath_type);
1358 error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1359 if (error && error != EAGAIN) {
1360 VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1361 datapath_type, ovs_strerror(error));
1367 ofproto_type_wait(const char *datapath_type)
1369 const struct ofproto_class *class;
1371 datapath_type = ofproto_normalize_type(datapath_type);
1372 class = ofproto_class_find__(datapath_type);
1374 if (class->type_wait) {
1375 class->type_wait(datapath_type);
1380 any_pending_ops(const struct ofproto *p)
1381 OVS_EXCLUDED(ofproto_mutex)
1385 ovs_mutex_lock(&ofproto_mutex);
1386 b = !list_is_empty(&p->pending);
1387 ovs_mutex_unlock(&ofproto_mutex);
1393 ofproto_run(struct ofproto *p)
1395 struct sset changed_netdevs;
1396 const char *changed_netdev;
1397 struct ofport *ofport;
1400 error = p->ofproto_class->run(p);
1401 if (error && error != EAGAIN) {
1402 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1405 run_rule_executes(p);
1407 /* Restore the eviction group heap invariant occasionally. */
1408 if (p->eviction_group_timer < time_msec()) {
1411 p->eviction_group_timer = time_msec() + 1000;
1413 for (i = 0; i < p->n_tables; i++) {
1414 struct oftable *table = &p->tables[i];
1415 struct eviction_group *evg;
1416 struct cls_cursor cursor;
1419 if (!table->eviction_fields) {
1423 ovs_mutex_lock(&ofproto_mutex);
1424 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1425 heap_rebuild(&evg->rules);
1428 ovs_rwlock_rdlock(&table->cls.rwlock);
1429 cls_cursor_init(&cursor, &table->cls, NULL);
1430 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1431 if (!rule->eviction_group
1432 && (rule->idle_timeout || rule->hard_timeout)) {
1433 eviction_group_add_rule(rule);
1436 ovs_rwlock_unlock(&table->cls.rwlock);
1437 ovs_mutex_unlock(&ofproto_mutex);
1441 if (p->ofproto_class->port_poll) {
1444 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1445 process_port_change(p, error, devname);
1449 /* Update OpenFlow port status for any port whose netdev has changed.
1451 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1452 * destroyed, so it's not safe to update ports directly from the
1453 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1454 * need this two-phase approach. */
1455 sset_init(&changed_netdevs);
1456 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1457 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1458 if (ofport->change_seq != change_seq) {
1459 ofport->change_seq = change_seq;
1460 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1463 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1464 update_port(p, changed_netdev);
1466 sset_destroy(&changed_netdevs);
1470 connmgr_run(p->connmgr, handle_openflow);
1474 connmgr_run(p->connmgr, NULL);
1476 if (!any_pending_ops(p)) {
1477 p->state = S_OPENFLOW;
1482 connmgr_run(p->connmgr, NULL);
1484 if (!any_pending_ops(p)) {
1485 connmgr_flushed(p->connmgr);
1486 p->state = S_OPENFLOW;
1494 if (time_msec() >= p->next_op_report) {
1495 long long int ago = (time_msec() - p->first_op) / 1000;
1496 long long int interval = (p->last_op - p->first_op) / 1000;
1500 ds_put_format(&s, "%d flow_mods ",
1501 p->n_add + p->n_delete + p->n_modify);
1502 if (interval == ago) {
1503 ds_put_format(&s, "in the last %lld s", ago);
1504 } else if (interval) {
1505 ds_put_format(&s, "in the %lld s starting %lld s ago",
1508 ds_put_format(&s, "%lld s ago", ago);
1511 ds_put_cstr(&s, " (");
1513 ds_put_format(&s, "%d adds, ", p->n_add);
1516 ds_put_format(&s, "%d deletes, ", p->n_delete);
1519 ds_put_format(&s, "%d modifications, ", p->n_modify);
1522 ds_put_char(&s, ')');
1524 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1527 p->n_add = p->n_delete = p->n_modify = 0;
1528 p->next_op_report = LLONG_MAX;
1534 /* Performs periodic activity required by 'ofproto' that needs to be done
1535 * with the least possible latency.
1537 * It makes sense to call this function a couple of times per poll loop, to
1538 * provide a significant performance boost on some benchmarks with the
1539 * ofproto-dpif implementation. */
1541 ofproto_run_fast(struct ofproto *p)
1545 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1546 if (error && error != EAGAIN) {
1547 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1548 p->name, ovs_strerror(error));
1554 ofproto_wait(struct ofproto *p)
1556 struct ofport *ofport;
1558 p->ofproto_class->wait(p);
1559 if (p->ofproto_class->port_poll_wait) {
1560 p->ofproto_class->port_poll_wait(p);
1563 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1564 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1565 poll_immediate_wake();
1571 connmgr_wait(p->connmgr, true);
1576 connmgr_wait(p->connmgr, false);
1577 if (!any_pending_ops(p)) {
1578 poll_immediate_wake();
1585 ofproto_is_alive(const struct ofproto *p)
1587 return connmgr_has_controllers(p->connmgr);
1590 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1591 * memory_report(). */
1593 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1595 const struct oftable *table;
1596 unsigned int n_rules;
1598 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1600 ovs_mutex_lock(&ofproto_mutex);
1601 simap_increase(usage, "ops",
1602 ofproto->n_pending + hmap_count(&ofproto->deletions));
1603 ovs_mutex_unlock(&ofproto_mutex);
1606 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1607 ovs_rwlock_rdlock(&table->cls.rwlock);
1608 n_rules += classifier_count(&table->cls);
1609 ovs_rwlock_unlock(&table->cls.rwlock);
1611 simap_increase(usage, "rules", n_rules);
1613 if (ofproto->ofproto_class->get_memory_usage) {
1614 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1617 connmgr_get_memory_usage(ofproto->connmgr, usage);
1621 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1624 connmgr_get_controller_info(ofproto->connmgr, info);
1628 ofproto_free_ofproto_controller_info(struct shash *info)
1630 connmgr_free_controller_info(info);
1633 /* Makes a deep copy of 'old' into 'port'. */
1635 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1637 port->name = xstrdup(old->name);
1638 port->type = xstrdup(old->type);
1639 port->ofp_port = old->ofp_port;
1642 /* Frees memory allocated to members of 'ofproto_port'.
1644 * Do not call this function on an ofproto_port obtained from
1645 * ofproto_port_dump_next(): that function retains ownership of the data in the
1648 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1650 free(ofproto_port->name);
1651 free(ofproto_port->type);
1654 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1656 * This function provides no status indication. An error status for the entire
1657 * dump operation is provided when it is completed by calling
1658 * ofproto_port_dump_done().
1661 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1662 const struct ofproto *ofproto)
1664 dump->ofproto = ofproto;
1665 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1669 /* Attempts to retrieve another port from 'dump', which must have been created
1670 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1671 * 'port' and returns true. On failure, returns false.
1673 * Failure might indicate an actual error or merely that the last port has been
1674 * dumped. An error status for the entire dump operation is provided when it
1675 * is completed by calling ofproto_port_dump_done().
1677 * The ofproto owns the data stored in 'port'. It will remain valid until at
1678 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1679 * ofproto_port_dump_done(). */
1681 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1682 struct ofproto_port *port)
1684 const struct ofproto *ofproto = dump->ofproto;
1690 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1693 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1699 /* Completes port table dump operation 'dump', which must have been created
1700 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1701 * error-free, otherwise a positive errno value describing the problem. */
1703 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1705 const struct ofproto *ofproto = dump->ofproto;
1707 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1710 return dump->error == EOF ? 0 : dump->error;
1713 /* Returns the type to pass to netdev_open() when a datapath of type
1714 * 'datapath_type' has a port of type 'port_type', for a few special
1715 * cases when a netdev type differs from a port type. For example, when
1716 * using the userspace datapath, a port of type "internal" needs to be
1719 * Returns either 'type' itself or a string literal, which must not be
1722 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1724 const struct ofproto_class *class;
1726 datapath_type = ofproto_normalize_type(datapath_type);
1727 class = ofproto_class_find__(datapath_type);
1732 return (class->port_open_type
1733 ? class->port_open_type(datapath_type, port_type)
1737 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1738 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1739 * the port's OpenFlow port number.
1741 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1742 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1743 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1744 * 'ofp_portp' is non-null). */
1746 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1747 ofp_port_t *ofp_portp)
1749 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1752 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1754 const char *netdev_name = netdev_get_name(netdev);
1756 simap_put(&ofproto->ofp_requests, netdev_name,
1757 ofp_to_u16(ofp_port));
1758 update_port(ofproto, netdev_name);
1761 struct ofproto_port ofproto_port;
1763 ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1765 *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1766 ofproto_port_destroy(&ofproto_port);
1771 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1772 * initializes '*port' appropriately; on failure, returns a positive errno
1775 * The caller owns the data in 'ofproto_port' and must free it with
1776 * ofproto_port_destroy() when it is no longer needed. */
1778 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1779 struct ofproto_port *port)
1783 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1785 memset(port, 0, sizeof *port);
1790 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1791 * Returns 0 if successful, otherwise a positive errno. */
1793 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1795 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1796 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1797 struct simap_node *ofp_request_node;
1800 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1801 if (ofp_request_node) {
1802 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1805 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1806 if (!error && ofport) {
1807 /* 'name' is the netdev's name and update_port() is going to close the
1808 * netdev. Just in case update_port() refers to 'name' after it
1809 * destroys 'ofport', make a copy of it around the update_port()
1811 char *devname = xstrdup(name);
1812 update_port(ofproto, devname);
1819 flow_mod_init(struct ofputil_flow_mod *fm,
1820 const struct match *match, unsigned int priority,
1821 const struct ofpact *ofpacts, size_t ofpacts_len,
1822 enum ofp_flow_mod_command command)
1824 memset(fm, 0, sizeof *fm);
1826 fm->priority = priority;
1829 fm->modify_cookie = false;
1831 fm->command = command;
1832 fm->idle_timeout = 0;
1833 fm->hard_timeout = 0;
1834 fm->buffer_id = UINT32_MAX;
1835 fm->out_port = OFPP_ANY;
1836 fm->out_group = OFPG_ANY;
1838 fm->ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1839 fm->ofpacts_len = ofpacts_len;
1843 simple_flow_mod(struct ofproto *ofproto,
1844 const struct match *match, unsigned int priority,
1845 const struct ofpact *ofpacts, size_t ofpacts_len,
1846 enum ofp_flow_mod_command command)
1848 struct ofputil_flow_mod fm;
1850 flow_mod_init(&fm, match, priority, ofpacts, ofpacts_len, command);
1852 return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1855 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1856 * performs the 'n_actions' actions in 'actions'. The new flow will not
1859 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1860 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1861 * controllers; otherwise, it will be hidden.
1863 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1865 * This is a helper function for in-band control and fail-open. */
1867 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1868 unsigned int priority,
1869 const struct ofpact *ofpacts, size_t ofpacts_len)
1870 OVS_EXCLUDED(ofproto_mutex)
1872 const struct rule *rule;
1875 /* First do a cheap check whether the rule we're looking for already exists
1876 * with the actions that we want. If it does, then we're done. */
1877 ovs_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1878 rule = rule_from_cls_rule(classifier_find_match_exactly(
1879 &ofproto->tables[0].cls, match, priority));
1881 ovs_mutex_lock(&rule->mutex);
1882 must_add = !ofpacts_equal(rule->actions->ofpacts,
1883 rule->actions->ofpacts_len,
1884 ofpacts, ofpacts_len);
1885 ovs_mutex_unlock(&rule->mutex);
1889 ovs_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1891 /* If there's no such rule or the rule doesn't have the actions we want,
1892 * fall back to a executing a full flow mod. We can't optimize this at
1893 * all because we didn't take enough locks above to ensure that the flow
1894 * table didn't already change beneath us. */
1896 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1897 OFPFC_MODIFY_STRICT);
1901 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1902 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1903 * operation cannot be initiated now but may be retried later.
1905 * This is a helper function for in-band control and fail-open and the "learn"
1908 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1909 OVS_EXCLUDED(ofproto_mutex)
1911 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1914 /* Searches for a rule with matching criteria exactly equal to 'target' in
1915 * ofproto's table 0 and, if it finds one, deletes it.
1917 * This is a helper function for in-band control and fail-open. */
1919 ofproto_delete_flow(struct ofproto *ofproto,
1920 const struct match *target, unsigned int priority)
1921 OVS_EXCLUDED(ofproto_mutex)
1923 struct classifier *cls = &ofproto->tables[0].cls;
1926 /* First do a cheap check whether the rule we're looking for has already
1927 * been deleted. If so, then we're done. */
1928 ovs_rwlock_rdlock(&cls->rwlock);
1929 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1931 ovs_rwlock_unlock(&cls->rwlock);
1936 /* Fall back to a executing a full flow mod. We can't optimize this at all
1937 * because we didn't take enough locks above to ensure that the flow table
1938 * didn't already change beneath us. */
1939 return simple_flow_mod(ofproto, target, priority, NULL, 0,
1940 OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
1943 /* Starts the process of deleting all of the flows from all of ofproto's flow
1944 * tables and then reintroducing the flows required by in-band control and
1945 * fail-open. The process will complete in a later call to ofproto_run(). */
1947 ofproto_flush_flows(struct ofproto *ofproto)
1949 COVERAGE_INC(ofproto_flush);
1950 ofproto->state = S_FLUSH;
1954 reinit_ports(struct ofproto *p)
1956 struct ofproto_port_dump dump;
1957 struct sset devnames;
1958 struct ofport *ofport;
1959 struct ofproto_port ofproto_port;
1960 const char *devname;
1962 COVERAGE_INC(ofproto_reinit_ports);
1964 sset_init(&devnames);
1965 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1966 sset_add(&devnames, netdev_get_name(ofport->netdev));
1968 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1969 sset_add(&devnames, ofproto_port.name);
1972 SSET_FOR_EACH (devname, &devnames) {
1973 update_port(p, devname);
1975 sset_destroy(&devnames);
1979 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1983 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1984 port_idx = port_idx ? port_idx : UINT16_MAX;
1986 if (port_idx >= ofproto->max_ports
1987 || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
1988 uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
1989 long long int last_used_at, lru = LLONG_MAX;
1991 /* Search for a free OpenFlow port number. We try not to
1992 * immediately reuse them to prevent problems due to old
1995 if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1996 ofproto->alloc_port_no = 1;
1998 last_used_at = ofport_get_usage(ofproto,
1999 u16_to_ofp(ofproto->alloc_port_no));
2000 if (!last_used_at) {
2001 port_idx = ofproto->alloc_port_no;
2003 } else if ( last_used_at < time_msec() - 60*60*1000) {
2004 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
2005 * more than an hour ago, consider it usable. */
2006 ofport_remove_usage(ofproto,
2007 u16_to_ofp(ofproto->alloc_port_no));
2008 port_idx = ofproto->alloc_port_no;
2010 } else if (last_used_at < lru) {
2012 lru_ofport = ofproto->alloc_port_no;
2015 if (ofproto->alloc_port_no == end_port_no) {
2017 port_idx = lru_ofport;
2024 ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
2025 return u16_to_ofp(port_idx);
2029 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2031 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2032 ofport_set_usage(ofproto, ofp_port, time_msec());
2036 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2037 * pointer if the netdev cannot be opened. On success, also fills in
2039 static struct netdev *
2040 ofport_open(struct ofproto *ofproto,
2041 struct ofproto_port *ofproto_port,
2042 struct ofputil_phy_port *pp)
2044 enum netdev_flags flags;
2045 struct netdev *netdev;
2048 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2050 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
2051 "cannot be opened (%s)",
2053 ofproto_port->name, ofproto_port->ofp_port,
2054 ofproto_port->name, ovs_strerror(error));
2058 if (ofproto_port->ofp_port == OFPP_NONE) {
2059 if (!strcmp(ofproto->name, ofproto_port->name)) {
2060 ofproto_port->ofp_port = OFPP_LOCAL;
2062 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2063 ofproto_port->name);
2066 pp->port_no = ofproto_port->ofp_port;
2067 netdev_get_etheraddr(netdev, pp->hw_addr);
2068 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2069 netdev_get_flags(netdev, &flags);
2070 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2071 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2072 netdev_get_features(netdev, &pp->curr, &pp->advertised,
2073 &pp->supported, &pp->peer);
2074 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2075 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2080 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
2081 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
2084 ofport_equal(const struct ofputil_phy_port *a,
2085 const struct ofputil_phy_port *b)
2087 return (eth_addr_equals(a->hw_addr, b->hw_addr)
2088 && a->state == b->state
2089 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2090 && a->curr == b->curr
2091 && a->advertised == b->advertised
2092 && a->supported == b->supported
2093 && a->peer == b->peer
2094 && a->curr_speed == b->curr_speed
2095 && a->max_speed == b->max_speed);
2098 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2099 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2100 * one with the same name or port number). */
2102 ofport_install(struct ofproto *p,
2103 struct netdev *netdev, const struct ofputil_phy_port *pp)
2105 const char *netdev_name = netdev_get_name(netdev);
2106 struct ofport *ofport;
2109 /* Create ofport. */
2110 ofport = p->ofproto_class->port_alloc();
2115 ofport->ofproto = p;
2116 ofport->netdev = netdev;
2117 ofport->change_seq = netdev_change_seq(netdev);
2119 ofport->ofp_port = pp->port_no;
2120 ofport->created = time_msec();
2122 /* Add port to 'p'. */
2123 hmap_insert(&p->ports, &ofport->hmap_node,
2124 hash_ofp_port(ofport->ofp_port));
2125 shash_add(&p->port_by_name, netdev_name, ofport);
2127 update_mtu(p, ofport);
2129 /* Let the ofproto_class initialize its private data. */
2130 error = p->ofproto_class->port_construct(ofport);
2134 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
2138 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2139 p->name, netdev_name, ovs_strerror(error));
2141 ofport_destroy__(ofport);
2143 netdev_close(netdev);
2147 /* Removes 'ofport' from 'p' and destroys it. */
2149 ofport_remove(struct ofport *ofport)
2151 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
2153 ofport_destroy(ofport);
2156 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2159 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2161 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2163 ofport_remove(port);
2167 /* Updates 'port' with new 'pp' description.
2169 * Does not handle a name or port number change. The caller must implement
2170 * such a change as a delete followed by an add. */
2172 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2174 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2175 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2176 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2177 port->pp.state = pp->state;
2178 port->pp.curr = pp->curr;
2179 port->pp.advertised = pp->advertised;
2180 port->pp.supported = pp->supported;
2181 port->pp.peer = pp->peer;
2182 port->pp.curr_speed = pp->curr_speed;
2183 port->pp.max_speed = pp->max_speed;
2185 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
2188 /* Update OpenFlow 'state' in 'port' and notify controller. */
2190 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2192 if (port->pp.state != state) {
2193 port->pp.state = state;
2194 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
2200 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2202 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2204 if (port->ofproto->ofproto_class->set_realdev) {
2205 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2207 if (port->ofproto->ofproto_class->set_stp_port) {
2208 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2210 if (port->ofproto->ofproto_class->set_cfm) {
2211 port->ofproto->ofproto_class->set_cfm(port, NULL);
2213 if (port->ofproto->ofproto_class->bundle_remove) {
2214 port->ofproto->ofproto_class->bundle_remove(port);
2220 ofport_destroy__(struct ofport *port)
2222 struct ofproto *ofproto = port->ofproto;
2223 const char *name = netdev_get_name(port->netdev);
2225 hmap_remove(&ofproto->ports, &port->hmap_node);
2226 shash_delete(&ofproto->port_by_name,
2227 shash_find(&ofproto->port_by_name, name));
2229 netdev_close(port->netdev);
2230 ofproto->ofproto_class->port_dealloc(port);
2234 ofport_destroy(struct ofport *port)
2237 dealloc_ofp_port(port->ofproto, port->ofp_port);
2238 port->ofproto->ofproto_class->port_destruct(port);
2239 ofport_destroy__(port);
2244 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2246 struct ofport *port;
2248 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2250 if (port->ofp_port == ofp_port) {
2257 static long long int
2258 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2260 struct ofport_usage *usage;
2262 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2263 &ofproto->ofport_usage) {
2264 if (usage->ofp_port == ofp_port) {
2265 return usage->last_used;
2272 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2273 long long int last_used)
2275 struct ofport_usage *usage;
2276 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2277 &ofproto->ofport_usage) {
2278 if (usage->ofp_port == ofp_port) {
2279 usage->last_used = last_used;
2283 ovs_assert(last_used == LLONG_MAX);
2285 usage = xmalloc(sizeof *usage);
2286 usage->ofp_port = ofp_port;
2287 usage->last_used = last_used;
2288 hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2289 hash_ofp_port(ofp_port));
2293 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2295 struct ofport_usage *usage;
2296 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2297 &ofproto->ofport_usage) {
2298 if (usage->ofp_port == ofp_port) {
2299 hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2307 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2309 struct ofproto *ofproto = port->ofproto;
2312 if (ofproto->ofproto_class->port_get_stats) {
2313 error = ofproto->ofproto_class->port_get_stats(port, stats);
2322 update_port(struct ofproto *ofproto, const char *name)
2324 struct ofproto_port ofproto_port;
2325 struct ofputil_phy_port pp;
2326 struct netdev *netdev;
2327 struct ofport *port;
2329 COVERAGE_INC(ofproto_update_port);
2331 /* Fetch 'name''s location and properties from the datapath. */
2332 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2333 ? ofport_open(ofproto, &ofproto_port, &pp)
2337 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2338 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2339 struct netdev *old_netdev = port->netdev;
2341 /* 'name' hasn't changed location. Any properties changed? */
2342 if (!ofport_equal(&port->pp, &pp)) {
2343 ofport_modified(port, &pp);
2346 update_mtu(ofproto, port);
2348 /* Install the newly opened netdev in case it has changed.
2349 * Don't close the old netdev yet in case port_modified has to
2350 * remove a retained reference to it.*/
2351 port->netdev = netdev;
2352 port->change_seq = netdev_change_seq(netdev);
2354 if (port->ofproto->ofproto_class->port_modified) {
2355 port->ofproto->ofproto_class->port_modified(port);
2358 netdev_close(old_netdev);
2360 /* If 'port' is nonnull then its name differs from 'name' and thus
2361 * we should delete it. If we think there's a port named 'name'
2362 * then its port number must be wrong now so delete it too. */
2364 ofport_remove(port);
2366 ofport_remove_with_name(ofproto, name);
2367 ofport_install(ofproto, netdev, &pp);
2370 /* Any port named 'name' is gone now. */
2371 ofport_remove_with_name(ofproto, name);
2373 ofproto_port_destroy(&ofproto_port);
2377 init_ports(struct ofproto *p)
2379 struct ofproto_port_dump dump;
2380 struct ofproto_port ofproto_port;
2381 struct shash_node *node, *next;
2383 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2384 const char *name = ofproto_port.name;
2386 if (shash_find(&p->port_by_name, name)) {
2387 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2390 struct ofputil_phy_port pp;
2391 struct netdev *netdev;
2393 /* Check if an OpenFlow port number had been requested. */
2394 node = shash_find(&init_ofp_ports, name);
2396 const struct iface_hint *iface_hint = node->data;
2397 simap_put(&p->ofp_requests, name,
2398 ofp_to_u16(iface_hint->ofp_port));
2401 netdev = ofport_open(p, &ofproto_port, &pp);
2403 ofport_install(p, netdev, &pp);
2404 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2405 p->alloc_port_no = MAX(p->alloc_port_no,
2406 ofp_to_u16(ofproto_port.ofp_port));
2412 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2413 struct iface_hint *iface_hint = node->data;
2415 if (!strcmp(iface_hint->br_name, p->name)) {
2416 free(iface_hint->br_name);
2417 free(iface_hint->br_type);
2419 shash_delete(&init_ofp_ports, node);
2426 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2427 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2429 find_min_mtu(struct ofproto *p)
2431 struct ofport *ofport;
2434 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2435 struct netdev *netdev = ofport->netdev;
2438 /* Skip any internal ports, since that's what we're trying to
2440 if (!strcmp(netdev_get_type(netdev), "internal")) {
2444 if (netdev_get_mtu(netdev, &dev_mtu)) {
2447 if (!mtu || dev_mtu < mtu) {
2452 return mtu ? mtu: ETH_PAYLOAD_MAX;
2455 /* Update MTU of all datapath devices on 'p' to the minimum of the
2456 * non-datapath ports in event of 'port' added or changed. */
2458 update_mtu(struct ofproto *p, struct ofport *port)
2460 struct ofport *ofport;
2461 struct netdev *netdev = port->netdev;
2462 int dev_mtu, old_min;
2464 if (netdev_get_mtu(netdev, &dev_mtu)) {
2468 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2469 if (dev_mtu > p->min_mtu) {
2470 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2471 dev_mtu = p->min_mtu;
2474 port->mtu = dev_mtu;
2478 /* For non-internal port find new min mtu. */
2479 old_min = p->min_mtu;
2480 port->mtu = dev_mtu;
2481 p->min_mtu = find_min_mtu(p);
2482 if (p->min_mtu == old_min) {
2486 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2487 struct netdev *netdev = ofport->netdev;
2489 if (!strcmp(netdev_get_type(netdev), "internal")) {
2490 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2491 ofport->mtu = p->min_mtu;
2498 ofproto_rule_ref(struct rule *rule)
2503 atomic_add(&rule->ref_count, 1, &orig);
2504 ovs_assert(orig != 0);
2509 ofproto_rule_unref(struct rule *rule)
2514 atomic_sub(&rule->ref_count, 1, &orig);
2516 rule->ofproto->ofproto_class->rule_destruct(rule);
2517 ofproto_rule_destroy__(rule);
2519 ovs_assert(orig != 0);
2524 struct rule_actions *
2525 rule_get_actions(const struct rule *rule)
2526 OVS_EXCLUDED(rule->mutex)
2528 struct rule_actions *actions;
2530 ovs_mutex_lock(&rule->mutex);
2531 actions = rule_get_actions__(rule);
2532 ovs_mutex_unlock(&rule->mutex);
2537 struct rule_actions *
2538 rule_get_actions__(const struct rule *rule)
2539 OVS_REQUIRES(rule->mutex)
2541 rule_actions_ref(rule->actions);
2542 return rule->actions;
2546 ofproto_rule_destroy__(struct rule *rule)
2547 OVS_NO_THREAD_SAFETY_ANALYSIS
2549 cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2550 rule_actions_unref(rule->actions);
2551 ovs_mutex_destroy(&rule->mutex);
2552 rule->ofproto->ofproto_class->rule_dealloc(rule);
2555 static uint32_t get_provider_meter_id(const struct ofproto *,
2556 uint32_t of_meter_id);
2558 /* Creates and returns a new 'struct rule_actions', with a ref_count of 1,
2559 * whose actions are a copy of from the 'ofpacts_len' bytes of 'ofpacts'. */
2560 struct rule_actions *
2561 rule_actions_create(const struct ofproto *ofproto,
2562 const struct ofpact *ofpacts, size_t ofpacts_len)
2564 struct rule_actions *actions;
2566 actions = xmalloc(sizeof *actions);
2567 atomic_init(&actions->ref_count, 1);
2568 actions->ofpacts = xmemdup(ofpacts, ofpacts_len);
2569 actions->ofpacts_len = ofpacts_len;
2570 actions->provider_meter_id
2571 = get_provider_meter_id(ofproto,
2572 ofpacts_get_meter(ofpacts, ofpacts_len));
2577 /* Increments 'actions''s ref_count. */
2579 rule_actions_ref(struct rule_actions *actions)
2584 atomic_add(&actions->ref_count, 1, &orig);
2585 ovs_assert(orig != 0);
2589 /* Decrements 'actions''s ref_count and frees 'actions' if the ref_count
2592 rule_actions_unref(struct rule_actions *actions)
2597 atomic_sub(&actions->ref_count, 1, &orig);
2599 free(actions->ofpacts);
2602 ovs_assert(orig != 0);
2607 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2608 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2610 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2611 OVS_REQUIRES(ofproto_mutex)
2613 return (port == OFPP_ANY
2614 || ofpacts_output_to_port(rule->actions->ofpacts,
2615 rule->actions->ofpacts_len, port));
2618 /* Returns true if 'rule' has group and equals group_id. */
2620 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
2621 OVS_REQUIRES(ofproto_mutex)
2623 return (group_id == OFPG11_ANY
2624 || ofpacts_output_to_group(rule->actions->ofpacts,
2625 rule->actions->ofpacts_len, group_id));
2628 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2629 * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2631 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2632 OVS_REQUIRES(ofproto_mutex)
2634 if (ofproto_rule_has_out_port(op->rule, out_port)) {
2639 case OFOPERATION_ADD:
2640 case OFOPERATION_DELETE:
2643 case OFOPERATION_MODIFY:
2644 case OFOPERATION_REPLACE:
2645 return ofpacts_output_to_port(op->actions->ofpacts,
2646 op->actions->ofpacts_len, out_port);
2653 rule_execute_destroy(struct rule_execute *e)
2655 ofproto_rule_unref(e->rule);
2656 list_remove(&e->list_node);
2660 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2661 * by passing them to the ofproto provider. */
2663 run_rule_executes(struct ofproto *ofproto)
2664 OVS_EXCLUDED(ofproto_mutex)
2666 struct rule_execute *e, *next;
2667 struct list executes;
2669 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2670 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2671 union flow_in_port in_port_;
2674 in_port_.ofp_port = e->in_port;
2675 flow_extract(e->packet, 0, 0, NULL, &in_port_, &flow);
2676 ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2678 rule_execute_destroy(e);
2682 /* Destroys and discards all "rule_execute" operations queued up in
2683 * ofproto->rule_executes. */
2685 destroy_rule_executes(struct ofproto *ofproto)
2687 struct rule_execute *e, *next;
2688 struct list executes;
2690 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2691 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2692 ofpbuf_delete(e->packet);
2693 rule_execute_destroy(e);
2697 /* Returns true if 'rule' should be hidden from the controller.
2699 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2700 * (e.g. by in-band control) and are intentionally hidden from the
2703 ofproto_rule_is_hidden(const struct rule *rule)
2705 return rule->cr.priority > UINT16_MAX;
2708 static enum oftable_flags
2709 rule_get_flags(const struct rule *rule)
2711 return rule->ofproto->tables[rule->table_id].flags;
2715 rule_is_modifiable(const struct rule *rule)
2717 return !(rule_get_flags(rule) & OFTABLE_READONLY);
2721 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2723 ofconn_send_reply(ofconn, make_echo_reply(oh));
2728 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2730 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2731 struct ofputil_switch_features features;
2732 struct ofport *port;
2738 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2740 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2742 /* Count only non-hidden tables in the number of tables. (Hidden tables,
2743 * if present, are always at the end.) */
2744 n_tables = ofproto->n_tables;
2745 for (i = 0; i < ofproto->n_tables; i++) {
2746 if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2752 features.datapath_id = ofproto->datapath_id;
2753 features.n_buffers = pktbuf_capacity();
2754 features.n_tables = n_tables;
2755 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2756 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2758 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2760 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2761 features.auxiliary_id = 0;
2762 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2764 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2765 ofputil_put_switch_features_port(&port->pp, b);
2768 ofconn_send_reply(ofconn, b);
2773 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2775 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2776 struct ofp_switch_config *osc;
2777 enum ofp_config_flags flags;
2781 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2782 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2783 flags = ofproto->frag_handling;
2784 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2785 if (oh->version < OFP13_VERSION
2786 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2787 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2789 osc->flags = htons(flags);
2790 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2791 ofconn_send_reply(ofconn, buf);
2797 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2799 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2800 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2801 uint16_t flags = ntohs(osc->flags);
2803 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2804 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2805 enum ofp_config_flags cur = ofproto->frag_handling;
2806 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2808 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2810 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2811 ofproto->frag_handling = next;
2813 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2815 ofputil_frag_handling_to_string(next));
2819 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2820 ofconn_set_invalid_ttl_to_controller(ofconn,
2821 (oh->version < OFP13_VERSION
2822 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2824 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2829 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2830 * error message code for the caller to propagate upward. Otherwise, returns
2833 * The log message mentions 'msg_type'. */
2835 reject_slave_controller(struct ofconn *ofconn)
2837 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2838 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2839 return OFPERR_OFPBRC_EPERM;
2845 /* Checks that the 'ofpacts_len' bytes of action in 'ofpacts' are appropriate
2848 * - If they use a meter, then 'ofproto' has that meter configured.
2850 * - If they use any groups, then 'ofproto' has that group configured.
2852 * Returns 0 if successful, otherwise an OpenFlow error. */
2854 ofproto_check_ofpacts(struct ofproto *ofproto,
2855 const struct ofpact ofpacts[], size_t ofpacts_len)
2857 const struct ofpact *a;
2860 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2861 if (mid && get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2862 return OFPERR_OFPMMFC_INVALID_METER;
2865 OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
2866 if (a->type == OFPACT_GROUP
2867 && !ofproto_group_exists(ofproto, ofpact_get_GROUP(a)->group_id)) {
2868 return OFPERR_OFPBAC_BAD_OUT_GROUP;
2876 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2878 struct ofproto *p = ofconn_get_ofproto(ofconn);
2879 struct ofputil_packet_out po;
2880 struct ofpbuf *payload;
2881 uint64_t ofpacts_stub[1024 / 8];
2882 struct ofpbuf ofpacts;
2884 union flow_in_port in_port_;
2887 COVERAGE_INC(ofproto_packet_out);
2889 error = reject_slave_controller(ofconn);
2894 /* Decode message. */
2895 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2896 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2898 goto exit_free_ofpacts;
2900 if (ofp_to_u16(po.in_port) >= p->max_ports
2901 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2902 error = OFPERR_OFPBRC_BAD_PORT;
2903 goto exit_free_ofpacts;
2907 if (po.buffer_id != UINT32_MAX) {
2908 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2909 if (error || !payload) {
2910 goto exit_free_ofpacts;
2913 /* Ensure that the L3 header is 32-bit aligned. */
2914 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2917 /* Verify actions against packet, then send packet if successful. */
2918 in_port_.ofp_port = po.in_port;
2919 flow_extract(payload, 0, 0, NULL, &in_port_, &flow);
2920 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len);
2922 error = p->ofproto_class->packet_out(p, payload, &flow,
2923 po.ofpacts, po.ofpacts_len);
2925 ofpbuf_delete(payload);
2928 ofpbuf_uninit(&ofpacts);
2934 update_port_config(struct ofport *port,
2935 enum ofputil_port_config config,
2936 enum ofputil_port_config mask)
2938 enum ofputil_port_config old_config = port->pp.config;
2939 enum ofputil_port_config toggle;
2941 toggle = (config ^ port->pp.config) & mask;
2942 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2943 if (config & OFPUTIL_PC_PORT_DOWN) {
2944 netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2946 netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2948 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2951 port->pp.config ^= toggle;
2952 if (port->pp.config != old_config) {
2953 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2958 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2960 struct ofproto *p = ofconn_get_ofproto(ofconn);
2961 struct ofputil_port_mod pm;
2962 struct ofport *port;
2965 error = reject_slave_controller(ofconn);
2970 error = ofputil_decode_port_mod(oh, &pm);
2975 port = ofproto_get_port(p, pm.port_no);
2977 return OFPERR_OFPPMFC_BAD_PORT;
2978 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2979 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2981 update_port_config(port, pm.config, pm.mask);
2983 netdev_set_advertisements(port->netdev, pm.advertise);
2990 handle_desc_stats_request(struct ofconn *ofconn,
2991 const struct ofp_header *request)
2993 static const char *default_mfr_desc = "Nicira, Inc.";
2994 static const char *default_hw_desc = "Open vSwitch";
2995 static const char *default_sw_desc = VERSION;
2996 static const char *default_serial_desc = "None";
2997 static const char *default_dp_desc = "None";
2999 struct ofproto *p = ofconn_get_ofproto(ofconn);
3000 struct ofp_desc_stats *ods;
3003 msg = ofpraw_alloc_stats_reply(request, 0);
3004 ods = ofpbuf_put_zeros(msg, sizeof *ods);
3005 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
3006 sizeof ods->mfr_desc);
3007 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
3008 sizeof ods->hw_desc);
3009 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
3010 sizeof ods->sw_desc);
3011 ovs_strlcpy(ods->serial_num,
3012 p->serial_desc ? p->serial_desc : default_serial_desc,
3013 sizeof ods->serial_num);
3014 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
3015 sizeof ods->dp_desc);
3016 ofconn_send_reply(ofconn, msg);
3022 handle_table_stats_request(struct ofconn *ofconn,
3023 const struct ofp_header *request)
3025 struct ofproto *p = ofconn_get_ofproto(ofconn);
3026 struct ofp12_table_stats *ots;
3031 /* Set up default values.
3033 * ofp12_table_stats is used as a generic structure as
3034 * it is able to hold all the fields for ofp10_table_stats
3035 * and ofp11_table_stats (and of course itself).
3037 ots = xcalloc(p->n_tables, sizeof *ots);
3038 for (i = 0; i < p->n_tables; i++) {
3039 ots[i].table_id = i;
3040 sprintf(ots[i].name, "table%zu", i);
3041 ots[i].match = htonll(OFPXMT13_MASK);
3042 ots[i].wildcards = htonll(OFPXMT13_MASK);
3043 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
3044 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
3045 ots[i].write_setfields = htonll(OFPXMT13_MASK);
3046 ots[i].apply_setfields = htonll(OFPXMT13_MASK);
3047 ots[i].metadata_match = OVS_BE64_MAX;
3048 ots[i].metadata_write = OVS_BE64_MAX;
3049 ots[i].instructions = htonl(OFPIT11_ALL);
3050 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
3051 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
3052 ovs_rwlock_rdlock(&p->tables[i].cls.rwlock);
3053 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
3054 ovs_rwlock_unlock(&p->tables[i].cls.rwlock);
3057 p->ofproto_class->get_tables(p, ots);
3059 /* Post-process the tables, dropping hidden tables. */
3060 n_tables = p->n_tables;
3061 for (i = 0; i < p->n_tables; i++) {
3062 const struct oftable *table = &p->tables[i];
3064 if (table->flags & OFTABLE_HIDDEN) {
3070 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
3073 if (table->max_flows < ntohl(ots[i].max_entries)) {
3074 ots[i].max_entries = htonl(table->max_flows);
3078 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
3079 ofconn_send_reply(ofconn, msg);
3087 append_port_stat(struct ofport *port, struct list *replies)
3089 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3091 calc_duration(port->created, time_msec(),
3092 &ops.duration_sec, &ops.duration_nsec);
3094 /* Intentionally ignore return value, since errors will set
3095 * 'stats' to all-1s, which is correct for OpenFlow, and
3096 * netdev_get_stats() will log errors. */
3097 ofproto_port_get_stats(port, &ops.stats);
3099 ofputil_append_port_stat(replies, &ops);
3103 handle_port_stats_request(struct ofconn *ofconn,
3104 const struct ofp_header *request)
3106 struct ofproto *p = ofconn_get_ofproto(ofconn);
3107 struct ofport *port;
3108 struct list replies;
3112 error = ofputil_decode_port_stats_request(request, &port_no);
3117 ofpmp_init(&replies, request);
3118 if (port_no != OFPP_ANY) {
3119 port = ofproto_get_port(p, port_no);
3121 append_port_stat(port, &replies);
3124 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3125 append_port_stat(port, &replies);
3129 ofconn_send_replies(ofconn, &replies);
3134 handle_port_desc_stats_request(struct ofconn *ofconn,
3135 const struct ofp_header *request)
3137 struct ofproto *p = ofconn_get_ofproto(ofconn);
3138 enum ofp_version version;
3139 struct ofport *port;
3140 struct list replies;
3142 ofpmp_init(&replies, request);
3144 version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
3145 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3146 ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
3149 ofconn_send_replies(ofconn, &replies);
3154 hash_cookie(ovs_be64 cookie)
3156 return hash_2words((OVS_FORCE uint64_t)cookie >> 32,
3157 (OVS_FORCE uint64_t)cookie);
3161 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3162 OVS_REQUIRES(ofproto_mutex)
3164 hindex_insert(&ofproto->cookies, &rule->cookie_node,
3165 hash_cookie(rule->flow_cookie));
3169 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3170 OVS_REQUIRES(ofproto_mutex)
3172 hindex_remove(&ofproto->cookies, &rule->cookie_node);
3176 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
3177 ovs_be64 new_cookie)
3178 OVS_REQUIRES(ofproto_mutex)
3180 if (new_cookie != rule->flow_cookie) {
3181 cookies_remove(ofproto, rule);
3183 ovs_mutex_lock(&rule->mutex);
3184 rule->flow_cookie = new_cookie;
3185 ovs_mutex_unlock(&rule->mutex);
3187 cookies_insert(ofproto, rule);
3192 calc_duration(long long int start, long long int now,
3193 uint32_t *sec, uint32_t *nsec)
3195 long long int msecs = now - start;
3196 *sec = msecs / 1000;
3197 *nsec = (msecs % 1000) * (1000 * 1000);
3200 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
3201 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
3203 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3205 return (table_id == 0xff || table_id < ofproto->n_tables
3207 : OFPERR_OFPBRC_BAD_TABLE_ID);
3211 static struct oftable *
3212 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3214 struct oftable *table;
3216 for (table = &ofproto->tables[table_id];
3217 table < &ofproto->tables[ofproto->n_tables];
3219 if (!(table->flags & OFTABLE_HIDDEN)) {
3227 static struct oftable *
3228 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3230 if (table_id == 0xff) {
3231 return next_visible_table(ofproto, 0);
3232 } else if (table_id < ofproto->n_tables) {
3233 return &ofproto->tables[table_id];
3239 static struct oftable *
3240 next_matching_table(const struct ofproto *ofproto,
3241 const struct oftable *table, uint8_t table_id)
3243 return (table_id == 0xff
3244 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3248 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3250 * - If TABLE_ID is 0xff, this iterates over every classifier table in
3251 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3253 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3254 * only once, for that table. (This can be used to access tables marked
3257 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3258 * entered at all. (Perhaps you should have validated TABLE_ID with
3259 * check_table_id().)
3261 * All parameters are evaluated multiple times.
3263 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
3264 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
3266 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3268 /* Initializes 'criteria' in a straightforward way based on the other
3271 * For "loose" matching, the 'priority' parameter is unimportant and may be
3274 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3275 const struct match *match, unsigned int priority,
3276 ovs_be64 cookie, ovs_be64 cookie_mask,
3277 ofp_port_t out_port, uint32_t out_group)
3279 criteria->table_id = table_id;
3280 cls_rule_init(&criteria->cr, match, priority);
3281 criteria->cookie = cookie;
3282 criteria->cookie_mask = cookie_mask;
3283 criteria->out_port = out_port;
3284 criteria->out_group = out_group;
3288 rule_criteria_destroy(struct rule_criteria *criteria)
3290 cls_rule_destroy(&criteria->cr);
3294 rule_collection_init(struct rule_collection *rules)
3296 rules->rules = rules->stub;
3298 rules->capacity = ARRAY_SIZE(rules->stub);
3302 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3304 if (rules->n >= rules->capacity) {
3305 size_t old_size, new_size;
3307 old_size = rules->capacity * sizeof *rules->rules;
3308 rules->capacity *= 2;
3309 new_size = rules->capacity * sizeof *rules->rules;
3311 if (rules->rules == rules->stub) {
3312 rules->rules = xmalloc(new_size);
3313 memcpy(rules->rules, rules->stub, old_size);
3315 rules->rules = xrealloc(rules->rules, new_size);
3319 rules->rules[rules->n++] = rule;
3323 rule_collection_ref(struct rule_collection *rules)
3324 OVS_REQUIRES(ofproto_mutex)
3328 for (i = 0; i < rules->n; i++) {
3329 ofproto_rule_ref(rules->rules[i]);
3334 rule_collection_unref(struct rule_collection *rules)
3338 for (i = 0; i < rules->n; i++) {
3339 ofproto_rule_unref(rules->rules[i]);
3344 rule_collection_destroy(struct rule_collection *rules)
3346 if (rules->rules != rules->stub) {
3352 collect_rule(struct rule *rule, const struct rule_criteria *c,
3353 struct rule_collection *rules)
3354 OVS_REQUIRES(ofproto_mutex)
3356 /* We ordinarily want to skip hidden rules, but there has to be a way for
3357 * code internal to OVS to modify and delete them, so if the criteria
3358 * specify a priority that can only be for a hidden flow, then allow hidden
3359 * rules to be selected. (This doesn't allow OpenFlow clients to meddle
3360 * with hidden flows because OpenFlow uses only a 16-bit field to specify
3362 if (ofproto_rule_is_hidden(rule) && c->cr.priority <= UINT16_MAX) {
3364 } else if (rule->pending) {
3365 return OFPROTO_POSTPONE;
3367 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3368 && ofproto_rule_has_out_port(rule, c->out_port)
3369 && ofproto_rule_has_out_group(rule, c->out_group)
3370 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3371 rule_collection_add(rules, rule);
3377 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3378 * on classifiers rules are done in the "loose" way required for OpenFlow
3379 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3382 * Hidden rules are always omitted.
3384 * Returns 0 on success, otherwise an OpenFlow error code. */
3386 collect_rules_loose(struct ofproto *ofproto,
3387 const struct rule_criteria *criteria,
3388 struct rule_collection *rules)
3389 OVS_REQUIRES(ofproto_mutex)
3391 struct oftable *table;
3394 rule_collection_init(rules);
3396 error = check_table_id(ofproto, criteria->table_id);
3401 if (criteria->cookie_mask == OVS_BE64_MAX) {
3404 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3405 hash_cookie(criteria->cookie),
3406 &ofproto->cookies) {
3407 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3408 error = collect_rule(rule, criteria, rules);
3415 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3416 struct cls_cursor cursor;
3419 ovs_rwlock_rdlock(&table->cls.rwlock);
3420 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3421 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3422 error = collect_rule(rule, criteria, rules);
3427 ovs_rwlock_unlock(&table->cls.rwlock);
3433 rule_collection_destroy(rules);
3438 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3439 * on classifiers rules are done in the "strict" way required for OpenFlow
3440 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3441 * rules on list 'rules'.
3443 * Hidden rules are always omitted.
3445 * Returns 0 on success, otherwise an OpenFlow error code. */
3447 collect_rules_strict(struct ofproto *ofproto,
3448 const struct rule_criteria *criteria,
3449 struct rule_collection *rules)
3450 OVS_REQUIRES(ofproto_mutex)
3452 struct oftable *table;
3455 rule_collection_init(rules);
3457 error = check_table_id(ofproto, criteria->table_id);
3462 if (criteria->cookie_mask == OVS_BE64_MAX) {
3465 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3466 hash_cookie(criteria->cookie),
3467 &ofproto->cookies) {
3468 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3469 error = collect_rule(rule, criteria, rules);
3476 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3479 ovs_rwlock_rdlock(&table->cls.rwlock);
3480 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3481 &table->cls, &criteria->cr));
3482 ovs_rwlock_unlock(&table->cls.rwlock);
3484 error = collect_rule(rule, criteria, rules);
3494 rule_collection_destroy(rules);
3499 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3500 * forced into the range of a uint16_t. */
3502 age_secs(long long int age_ms)
3504 return (age_ms < 0 ? 0
3505 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3506 : (unsigned int) age_ms / 1000);
3510 handle_flow_stats_request(struct ofconn *ofconn,
3511 const struct ofp_header *request)
3512 OVS_EXCLUDED(ofproto_mutex)
3514 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3515 struct ofputil_flow_stats_request fsr;
3516 struct rule_criteria criteria;
3517 struct rule_collection rules;
3518 struct list replies;
3522 error = ofputil_decode_flow_stats_request(&fsr, request);
3527 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3528 fsr.cookie_mask, fsr.out_port, fsr.out_group);
3530 ovs_mutex_lock(&ofproto_mutex);
3531 error = collect_rules_loose(ofproto, &criteria, &rules);
3532 rule_criteria_destroy(&criteria);
3534 rule_collection_ref(&rules);
3536 ovs_mutex_unlock(&ofproto_mutex);
3542 ofpmp_init(&replies, request);
3543 for (i = 0; i < rules.n; i++) {
3544 struct rule *rule = rules.rules[i];
3545 long long int now = time_msec();
3546 struct ofputil_flow_stats fs;
3547 long long int created, used, modified;
3548 struct rule_actions *actions;
3549 enum ofputil_flow_mod_flags flags;
3551 ovs_mutex_lock(&rule->mutex);
3552 fs.cookie = rule->flow_cookie;
3553 fs.idle_timeout = rule->idle_timeout;
3554 fs.hard_timeout = rule->hard_timeout;
3555 created = rule->created;
3557 modified = rule->modified;
3558 actions = rule_get_actions__(rule);
3559 flags = rule->flags;
3560 ovs_mutex_unlock(&rule->mutex);
3562 minimatch_expand(&rule->cr.match, &fs.match);
3563 fs.table_id = rule->table_id;
3564 calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
3565 fs.priority = rule->cr.priority;
3566 fs.idle_age = age_secs(now - used);
3567 fs.hard_age = age_secs(now - modified);
3568 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3570 fs.ofpacts = actions->ofpacts;
3571 fs.ofpacts_len = actions->ofpacts_len;
3574 ofputil_append_flow_stats_reply(&fs, &replies);
3576 rule_actions_unref(actions);
3579 rule_collection_unref(&rules);
3580 rule_collection_destroy(&rules);
3582 ofconn_send_replies(ofconn, &replies);
3588 flow_stats_ds(struct rule *rule, struct ds *results)
3590 uint64_t packet_count, byte_count;
3591 struct rule_actions *actions;
3592 long long int created;
3594 rule->ofproto->ofproto_class->rule_get_stats(rule,
3595 &packet_count, &byte_count);
3597 ovs_mutex_lock(&rule->mutex);
3598 actions = rule_get_actions__(rule);
3599 created = rule->created;
3600 ovs_mutex_unlock(&rule->mutex);
3602 if (rule->table_id != 0) {
3603 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3605 ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
3606 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3607 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3608 cls_rule_format(&rule->cr, results);
3609 ds_put_char(results, ',');
3611 ds_put_cstr(results, "actions=");
3612 ofpacts_format(actions->ofpacts, actions->ofpacts_len, results);
3614 ds_put_cstr(results, "\n");
3616 rule_actions_unref(actions);
3619 /* Adds a pretty-printed description of all flows to 'results', including
3620 * hidden flows (e.g., set up by in-band control). */
3622 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3624 struct oftable *table;
3626 OFPROTO_FOR_EACH_TABLE (table, p) {
3627 struct cls_cursor cursor;
3630 ovs_rwlock_rdlock(&table->cls.rwlock);
3631 cls_cursor_init(&cursor, &table->cls, NULL);
3632 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3633 flow_stats_ds(rule, results);
3635 ovs_rwlock_unlock(&table->cls.rwlock);
3639 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3640 * '*engine_type' and '*engine_id', respectively. */
3642 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3643 uint8_t *engine_type, uint8_t *engine_id)
3645 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3648 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3649 * true if the port's CFM status was successfully stored into '*status'.
3650 * Returns false if the port did not have CFM configured, in which case
3651 * '*status' is indeterminate.
3653 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3655 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3656 struct ofproto_cfm_status *status)
3658 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3660 && ofproto->ofproto_class->get_cfm_status
3661 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3665 handle_aggregate_stats_request(struct ofconn *ofconn,
3666 const struct ofp_header *oh)
3667 OVS_EXCLUDED(ofproto_mutex)
3669 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3670 struct ofputil_flow_stats_request request;
3671 struct ofputil_aggregate_stats stats;
3672 bool unknown_packets, unknown_bytes;
3673 struct rule_criteria criteria;
3674 struct rule_collection rules;
3675 struct ofpbuf *reply;
3679 error = ofputil_decode_flow_stats_request(&request, oh);
3684 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3685 request.cookie, request.cookie_mask,
3686 request.out_port, request.out_group);
3688 ovs_mutex_lock(&ofproto_mutex);
3689 error = collect_rules_loose(ofproto, &criteria, &rules);
3690 rule_criteria_destroy(&criteria);
3692 rule_collection_ref(&rules);
3694 ovs_mutex_unlock(&ofproto_mutex);
3700 memset(&stats, 0, sizeof stats);
3701 unknown_packets = unknown_bytes = false;
3702 for (i = 0; i < rules.n; i++) {
3703 struct rule *rule = rules.rules[i];
3704 uint64_t packet_count;
3705 uint64_t byte_count;
3707 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3710 if (packet_count == UINT64_MAX) {
3711 unknown_packets = true;
3713 stats.packet_count += packet_count;
3716 if (byte_count == UINT64_MAX) {
3717 unknown_bytes = true;
3719 stats.byte_count += byte_count;
3724 if (unknown_packets) {
3725 stats.packet_count = UINT64_MAX;
3727 if (unknown_bytes) {
3728 stats.byte_count = UINT64_MAX;
3731 rule_collection_unref(&rules);
3732 rule_collection_destroy(&rules);
3734 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3735 ofconn_send_reply(ofconn, reply);
3740 struct queue_stats_cbdata {
3741 struct ofport *ofport;
3742 struct list replies;
3747 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3748 const struct netdev_queue_stats *stats)
3750 struct ofputil_queue_stats oqs;
3752 oqs.port_no = cbdata->ofport->pp.port_no;
3753 oqs.queue_id = queue_id;
3754 oqs.tx_bytes = stats->tx_bytes;
3755 oqs.tx_packets = stats->tx_packets;
3756 oqs.tx_errors = stats->tx_errors;
3757 if (stats->created != LLONG_MIN) {
3758 calc_duration(stats->created, cbdata->now,
3759 &oqs.duration_sec, &oqs.duration_nsec);
3761 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3763 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3767 handle_queue_stats_dump_cb(uint32_t queue_id,
3768 struct netdev_queue_stats *stats,
3771 struct queue_stats_cbdata *cbdata = cbdata_;
3773 put_queue_stats(cbdata, queue_id, stats);
3777 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3778 struct queue_stats_cbdata *cbdata)
3780 cbdata->ofport = port;
3781 if (queue_id == OFPQ_ALL) {
3782 netdev_dump_queue_stats(port->netdev,
3783 handle_queue_stats_dump_cb, cbdata);
3785 struct netdev_queue_stats stats;
3787 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3788 put_queue_stats(cbdata, queue_id, &stats);
3790 return OFPERR_OFPQOFC_BAD_QUEUE;
3797 handle_queue_stats_request(struct ofconn *ofconn,
3798 const struct ofp_header *rq)
3800 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3801 struct queue_stats_cbdata cbdata;
3802 struct ofport *port;
3804 struct ofputil_queue_stats_request oqsr;
3806 COVERAGE_INC(ofproto_queue_req);
3808 ofpmp_init(&cbdata.replies, rq);
3809 cbdata.now = time_msec();
3811 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3816 if (oqsr.port_no == OFPP_ANY) {
3817 error = OFPERR_OFPQOFC_BAD_QUEUE;
3818 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3819 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3824 port = ofproto_get_port(ofproto, oqsr.port_no);
3826 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3827 : OFPERR_OFPQOFC_BAD_PORT);
3830 ofconn_send_replies(ofconn, &cbdata.replies);
3832 ofpbuf_list_delete(&cbdata.replies);
3839 is_flow_deletion_pending(const struct ofproto *ofproto,
3840 const struct cls_rule *cls_rule,
3842 OVS_REQUIRES(ofproto_mutex)
3844 if (!hmap_is_empty(&ofproto->deletions)) {
3845 struct ofoperation *op;
3847 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3848 cls_rule_hash(cls_rule, table_id),
3849 &ofproto->deletions) {
3850 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3860 should_evict_a_rule(struct oftable *table, unsigned int extra_space)
3861 OVS_REQUIRES(ofproto_mutex)
3862 OVS_NO_THREAD_SAFETY_ANALYSIS
3864 return classifier_count(&table->cls) + extra_space > table->max_flows;
3868 evict_rules_from_table(struct ofproto *ofproto, struct oftable *table,
3869 unsigned int extra_space)
3870 OVS_REQUIRES(ofproto_mutex)
3872 while (should_evict_a_rule(table, extra_space)) {
3875 if (!choose_rule_to_evict(table, &rule)) {
3876 return OFPERR_OFPFMFC_TABLE_FULL;
3877 } else if (rule->pending) {
3878 return OFPROTO_POSTPONE;
3880 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
3881 delete_flow__(rule, group, OFPRR_EVICTION);
3882 ofopgroup_submit(group);
3889 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3890 * in which no matching flow already exists in the flow table.
3892 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3893 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3894 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3895 * initiated now but may be retried later.
3897 * The caller retains ownership of 'fm->ofpacts'.
3899 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3902 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3903 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3904 OVS_REQUIRES(ofproto_mutex)
3906 struct oftable *table;
3907 struct ofopgroup *group;
3913 error = check_table_id(ofproto, fm->table_id);
3919 if (fm->table_id == 0xff) {
3920 if (ofproto->ofproto_class->rule_choose_table) {
3921 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3927 ovs_assert(table_id < ofproto->n_tables);
3931 } else if (fm->table_id < ofproto->n_tables) {
3932 table_id = fm->table_id;
3934 return OFPERR_OFPBRC_BAD_TABLE_ID;
3937 table = &ofproto->tables[table_id];
3939 if (table->flags & OFTABLE_READONLY) {
3940 return OFPERR_OFPBRC_EPERM;
3943 cls_rule_init(&cr, &fm->match, fm->priority);
3945 /* Transform "add" into "modify" if there's an existing identical flow. */
3946 ovs_rwlock_rdlock(&table->cls.rwlock);
3947 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3948 ovs_rwlock_unlock(&table->cls.rwlock);
3950 cls_rule_destroy(&cr);
3951 if (!rule_is_modifiable(rule)) {
3952 return OFPERR_OFPBRC_EPERM;
3953 } else if (rule->pending) {
3954 return OFPROTO_POSTPONE;
3956 struct rule_collection rules;
3958 rule_collection_init(&rules);
3959 rule_collection_add(&rules, rule);
3960 fm->modify_cookie = true;
3961 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3962 rule_collection_destroy(&rules);
3968 /* Serialize against pending deletion. */
3969 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3970 cls_rule_destroy(&cr);
3971 return OFPROTO_POSTPONE;
3974 /* Check for overlap, if requested. */
3975 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3978 ovs_rwlock_rdlock(&table->cls.rwlock);
3979 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3980 ovs_rwlock_unlock(&table->cls.rwlock);
3983 cls_rule_destroy(&cr);
3984 return OFPERR_OFPFMFC_OVERLAP;
3988 /* If necessary, evict an existing rule to clear out space. */
3989 error = evict_rules_from_table(ofproto, table, 1);
3991 cls_rule_destroy(&cr);
3995 /* Allocate new rule. */
3996 rule = ofproto->ofproto_class->rule_alloc();
3998 cls_rule_destroy(&cr);
3999 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
4000 ofproto->name, ovs_strerror(error));
4004 /* Initialize base state. */
4005 *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
4006 cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), &cr);
4007 atomic_init(&rule->ref_count, 1);
4008 rule->pending = NULL;
4009 rule->flow_cookie = fm->new_cookie;
4010 rule->created = rule->modified = rule->used = time_msec();
4012 ovs_mutex_init(&rule->mutex);
4013 ovs_mutex_lock(&rule->mutex);
4014 rule->idle_timeout = fm->idle_timeout;
4015 rule->hard_timeout = fm->hard_timeout;
4016 ovs_mutex_unlock(&rule->mutex);
4018 *CONST_CAST(uint8_t *, &rule->table_id) = table - ofproto->tables;
4019 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4020 rule->actions = rule_actions_create(ofproto, fm->ofpacts, fm->ofpacts_len);
4021 list_init(&rule->meter_list_node);
4022 rule->eviction_group = NULL;
4023 list_init(&rule->expirable);
4024 rule->monitor_flags = 0;
4025 rule->add_seqno = 0;
4026 rule->modify_seqno = 0;
4028 /* Construct rule, initializing derived state. */
4029 error = ofproto->ofproto_class->rule_construct(rule);
4031 ofproto_rule_destroy__(rule);
4036 oftable_insert_rule(rule);
4038 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4039 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
4040 ofproto->ofproto_class->rule_insert(rule);
4041 ofopgroup_submit(group);
4046 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4048 /* Modifies the rules listed in 'rules', changing their actions to match those
4051 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4054 * Returns 0 on success, otherwise an OpenFlow error code. */
4056 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4057 struct ofputil_flow_mod *fm, const struct ofp_header *request,
4058 const struct rule_collection *rules)
4059 OVS_REQUIRES(ofproto_mutex)
4061 enum ofoperation_type type;
4062 struct ofopgroup *group;
4066 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
4067 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4068 error = OFPERR_OFPBRC_EPERM;
4069 for (i = 0; i < rules->n; i++) {
4070 struct rule *rule = rules->rules[i];
4071 struct ofoperation *op;
4072 bool actions_changed;
4073 bool reset_counters;
4075 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
4077 if (rule_is_modifiable(rule)) {
4078 /* At least one rule is modifiable, don't report EPERM error. */
4084 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4085 rule->actions->ofpacts,
4086 rule->actions->ofpacts_len);
4088 op = ofoperation_create(group, rule, type, 0);
4090 if (fm->modify_cookie && fm->new_cookie != OVS_BE64_MAX) {
4091 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
4093 if (type == OFOPERATION_REPLACE) {
4094 ovs_mutex_lock(&rule->mutex);
4095 rule->idle_timeout = fm->idle_timeout;
4096 rule->hard_timeout = fm->hard_timeout;
4097 ovs_mutex_unlock(&rule->mutex);
4099 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4100 if (fm->idle_timeout || fm->hard_timeout) {
4101 if (!rule->eviction_group) {
4102 eviction_group_add_rule(rule);
4105 eviction_group_remove_rule(rule);
4109 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
4110 if (actions_changed || reset_counters) {
4111 struct rule_actions *new_actions;
4113 op->actions = rule->actions;
4114 new_actions = rule_actions_create(ofproto,
4115 fm->ofpacts, fm->ofpacts_len);
4117 ovs_mutex_lock(&rule->mutex);
4118 rule->actions = new_actions;
4119 ovs_mutex_unlock(&rule->mutex);
4121 rule->ofproto->ofproto_class->rule_modify_actions(rule,
4124 ofoperation_complete(op, 0);
4127 ofopgroup_submit(group);
4133 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
4134 struct ofputil_flow_mod *fm, const struct ofp_header *request)
4135 OVS_REQUIRES(ofproto_mutex)
4137 if (fm->cookie_mask != htonll(0) || fm->new_cookie == OVS_BE64_MAX) {
4140 return add_flow(ofproto, ofconn, fm, request);
4143 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
4146 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4149 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4150 struct ofputil_flow_mod *fm,
4151 const struct ofp_header *request)
4152 OVS_REQUIRES(ofproto_mutex)
4154 struct rule_criteria criteria;
4155 struct rule_collection rules;
4158 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4159 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4160 error = collect_rules_loose(ofproto, &criteria, &rules);
4161 rule_criteria_destroy(&criteria);
4164 error = (rules.n > 0
4165 ? modify_flows__(ofproto, ofconn, fm, request, &rules)
4166 : modify_flows_add(ofproto, ofconn, fm, request));
4169 rule_collection_destroy(&rules);
4174 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4177 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4180 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4181 struct ofputil_flow_mod *fm,
4182 const struct ofp_header *request)
4183 OVS_REQUIRES(ofproto_mutex)
4185 struct rule_criteria criteria;
4186 struct rule_collection rules;
4189 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4190 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4191 error = collect_rules_strict(ofproto, &criteria, &rules);
4192 rule_criteria_destroy(&criteria);
4196 error = modify_flows_add(ofproto, ofconn, fm, request);
4197 } else if (rules.n == 1) {
4198 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
4202 rule_collection_destroy(&rules);
4207 /* OFPFC_DELETE implementation. */
4210 delete_flow__(struct rule *rule, struct ofopgroup *group,
4211 enum ofp_flow_removed_reason reason)
4212 OVS_REQUIRES(ofproto_mutex)
4214 struct ofproto *ofproto = rule->ofproto;
4216 ofproto_rule_send_removed(rule, reason);
4218 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
4219 oftable_remove_rule(rule);
4220 ofproto->ofproto_class->rule_delete(rule);
4223 /* Deletes the rules listed in 'rules'.
4225 * Returns 0 on success, otherwise an OpenFlow error code. */
4227 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4228 const struct ofp_header *request,
4229 const struct rule_collection *rules,
4230 enum ofp_flow_removed_reason reason)
4231 OVS_REQUIRES(ofproto_mutex)
4233 struct ofopgroup *group;
4236 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
4237 for (i = 0; i < rules->n; i++) {
4238 delete_flow__(rules->rules[i], group, reason);
4240 ofopgroup_submit(group);
4245 /* Implements OFPFC_DELETE. */
4247 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4248 const struct ofputil_flow_mod *fm,
4249 const struct ofp_header *request)
4250 OVS_REQUIRES(ofproto_mutex)
4252 struct rule_criteria criteria;
4253 struct rule_collection rules;
4256 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4257 fm->cookie, fm->cookie_mask,
4258 fm->out_port, fm->out_group);
4259 error = collect_rules_loose(ofproto, &criteria, &rules);
4260 rule_criteria_destroy(&criteria);
4262 if (!error && rules.n > 0) {
4263 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4265 rule_collection_destroy(&rules);
4270 /* Implements OFPFC_DELETE_STRICT. */
4272 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4273 const struct ofputil_flow_mod *fm,
4274 const struct ofp_header *request)
4275 OVS_REQUIRES(ofproto_mutex)
4277 struct rule_criteria criteria;
4278 struct rule_collection rules;
4281 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4282 fm->cookie, fm->cookie_mask,
4283 fm->out_port, fm->out_group);
4284 error = collect_rules_strict(ofproto, &criteria, &rules);
4285 rule_criteria_destroy(&criteria);
4287 if (!error && rules.n > 0) {
4288 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4290 rule_collection_destroy(&rules);
4296 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4297 OVS_REQUIRES(ofproto_mutex)
4299 struct ofputil_flow_removed fr;
4301 if (ofproto_rule_is_hidden(rule) ||
4302 !(rule->flags & OFPUTIL_FF_SEND_FLOW_REM)) {
4306 minimatch_expand(&rule->cr.match, &fr.match);
4307 fr.priority = rule->cr.priority;
4308 fr.cookie = rule->flow_cookie;
4310 fr.table_id = rule->table_id;
4311 calc_duration(rule->created, time_msec(),
4312 &fr.duration_sec, &fr.duration_nsec);
4313 ovs_mutex_lock(&rule->mutex);
4314 fr.idle_timeout = rule->idle_timeout;
4315 fr.hard_timeout = rule->hard_timeout;
4316 ovs_mutex_unlock(&rule->mutex);
4317 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4320 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4323 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4324 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4327 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4330 * ofproto implementation ->run() functions should use this function to expire
4331 * OpenFlow flows. */
4333 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4334 OVS_REQUIRES(ofproto_mutex)
4336 struct ofproto *ofproto = rule->ofproto;
4338 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT
4339 || reason == OFPRR_DELETE || reason == OFPRR_GROUP_DELETE);
4341 ofproto_rule_delete__(ofproto, rule, reason);
4344 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
4345 * means "infinite". */
4347 reduce_timeout(uint16_t max, uint16_t *timeout)
4349 if (max && (!*timeout || *timeout > max)) {
4354 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4355 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4356 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
4358 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4360 ofproto_rule_reduce_timeouts(struct rule *rule,
4361 uint16_t idle_timeout, uint16_t hard_timeout)
4362 OVS_EXCLUDED(ofproto_mutex, rule->mutex)
4364 if (!idle_timeout && !hard_timeout) {
4368 ovs_mutex_lock(&ofproto_mutex);
4369 if (list_is_empty(&rule->expirable)) {
4370 list_insert(&rule->ofproto->expirable, &rule->expirable);
4372 ovs_mutex_unlock(&ofproto_mutex);
4374 ovs_mutex_lock(&rule->mutex);
4375 reduce_timeout(idle_timeout, &rule->idle_timeout);
4376 reduce_timeout(hard_timeout, &rule->hard_timeout);
4377 ovs_mutex_unlock(&rule->mutex);
4381 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4382 OVS_EXCLUDED(ofproto_mutex)
4384 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4385 struct ofputil_flow_mod fm;
4386 uint64_t ofpacts_stub[1024 / 8];
4387 struct ofpbuf ofpacts;
4391 error = reject_slave_controller(ofconn);
4396 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4397 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4399 u16_to_ofp(ofproto->max_ports),
4402 error = ofproto_check_ofpacts(ofproto, fm.ofpacts, fm.ofpacts_len);
4405 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4408 goto exit_free_ofpacts;
4411 /* Record the operation for logging a summary report. */
4412 switch (fm.command) {
4418 case OFPFC_MODIFY_STRICT:
4419 ofproto->n_modify++;
4423 case OFPFC_DELETE_STRICT:
4424 ofproto->n_delete++;
4429 if (ofproto->next_op_report == LLONG_MAX) {
4430 ofproto->first_op = now;
4431 ofproto->next_op_report = MAX(now + 10 * 1000,
4432 ofproto->op_backoff);
4433 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4435 ofproto->last_op = now;
4438 ofpbuf_uninit(&ofpacts);
4444 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4445 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4446 OVS_EXCLUDED(ofproto_mutex)
4450 ovs_mutex_lock(&ofproto_mutex);
4451 if (ofproto->n_pending < 50) {
4452 switch (fm->command) {
4454 error = add_flow(ofproto, ofconn, fm, oh);
4458 error = modify_flows_loose(ofproto, ofconn, fm, oh);
4461 case OFPFC_MODIFY_STRICT:
4462 error = modify_flow_strict(ofproto, ofconn, fm, oh);
4466 error = delete_flows_loose(ofproto, ofconn, fm, oh);
4469 case OFPFC_DELETE_STRICT:
4470 error = delete_flow_strict(ofproto, ofconn, fm, oh);
4474 if (fm->command > 0xff) {
4475 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4476 "flow_mod_table_id extension is not enabled",
4479 error = OFPERR_OFPFMFC_BAD_COMMAND;
4483 ovs_assert(!list_is_empty(&ofproto->pending));
4484 error = OFPROTO_POSTPONE;
4486 ovs_mutex_unlock(&ofproto_mutex);
4488 run_rule_executes(ofproto);
4493 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4495 struct ofputil_role_request request;
4496 struct ofputil_role_request reply;
4500 error = ofputil_decode_role_message(oh, &request);
4505 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4506 if (ofconn_get_role(ofconn) != request.role
4507 && ofconn_has_pending_opgroups(ofconn)) {
4508 return OFPROTO_POSTPONE;
4511 if (request.have_generation_id
4512 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4513 return OFPERR_OFPRRFC_STALE;
4516 ofconn_set_role(ofconn, request.role);
4519 reply.role = ofconn_get_role(ofconn);
4520 reply.have_generation_id = ofconn_get_master_election_id(
4521 ofconn, &reply.generation_id);
4522 buf = ofputil_encode_role_reply(oh, &reply);
4523 ofconn_send_reply(ofconn, buf);
4529 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4530 const struct ofp_header *oh)
4532 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4533 enum ofputil_protocol cur, next;
4535 cur = ofconn_get_protocol(ofconn);
4536 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4537 ofconn_set_protocol(ofconn, next);
4543 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4545 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4546 enum ofputil_protocol cur, next;
4547 enum ofputil_protocol next_base;
4549 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4551 return OFPERR_OFPBRC_EPERM;
4554 cur = ofconn_get_protocol(ofconn);
4555 next = ofputil_protocol_set_base(cur, next_base);
4556 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4557 /* Avoid sending async messages in surprising protocol. */
4558 return OFPROTO_POSTPONE;
4561 ofconn_set_protocol(ofconn, next);
4566 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4567 const struct ofp_header *oh)
4569 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4572 format = ntohl(msg->format);
4573 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4574 return OFPERR_OFPBRC_EPERM;
4577 if (format != ofconn_get_packet_in_format(ofconn)
4578 && ofconn_has_pending_opgroups(ofconn)) {
4579 /* Avoid sending async message in surprsing packet in format. */
4580 return OFPROTO_POSTPONE;
4583 ofconn_set_packet_in_format(ofconn, format);
4588 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4590 const struct nx_async_config *msg = ofpmsg_body(oh);
4591 uint32_t master[OAM_N_TYPES];
4592 uint32_t slave[OAM_N_TYPES];
4594 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4595 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4596 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4598 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4599 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4600 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4602 ofconn_set_async_config(ofconn, master, slave);
4603 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4604 !ofconn_get_miss_send_len(ofconn)) {
4605 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4612 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
4615 uint32_t master[OAM_N_TYPES];
4616 uint32_t slave[OAM_N_TYPES];
4617 struct nx_async_config *msg;
4619 ofconn_get_async_config(ofconn, master, slave);
4620 buf = ofpraw_alloc_reply(OFPRAW_OFPT13_GET_ASYNC_REPLY, oh, 0);
4621 msg = ofpbuf_put_zeros(buf, sizeof *msg);
4623 msg->packet_in_mask[0] = htonl(master[OAM_PACKET_IN]);
4624 msg->port_status_mask[0] = htonl(master[OAM_PORT_STATUS]);
4625 msg->flow_removed_mask[0] = htonl(master[OAM_FLOW_REMOVED]);
4627 msg->packet_in_mask[1] = htonl(slave[OAM_PACKET_IN]);
4628 msg->port_status_mask[1] = htonl(slave[OAM_PORT_STATUS]);
4629 msg->flow_removed_mask[1] = htonl(slave[OAM_FLOW_REMOVED]);
4631 ofconn_send_reply(ofconn, buf);
4637 handle_nxt_set_controller_id(struct ofconn *ofconn,
4638 const struct ofp_header *oh)
4640 const struct nx_controller_id *nci = ofpmsg_body(oh);
4642 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4643 return OFPERR_NXBRC_MUST_BE_ZERO;
4646 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4651 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4655 if (ofconn_has_pending_opgroups(ofconn)) {
4656 return OFPROTO_POSTPONE;
4659 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4660 ? OFPRAW_OFPT10_BARRIER_REPLY
4661 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4662 ofconn_send_reply(ofconn, buf);
4667 ofproto_compose_flow_refresh_update(const struct rule *rule,
4668 enum nx_flow_monitor_flags flags,
4670 OVS_REQUIRES(ofproto_mutex)
4672 struct ofoperation *op = rule->pending;
4673 const struct rule_actions *actions;
4674 struct ofputil_flow_update fu;
4677 if (op && op->type == OFOPERATION_ADD) {
4678 /* We'll report the final flow when the operation completes. Reporting
4679 * it now would cause a duplicate report later. */
4683 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4684 ? NXFME_ADDED : NXFME_MODIFIED);
4686 ovs_mutex_lock(&rule->mutex);
4687 fu.idle_timeout = rule->idle_timeout;
4688 fu.hard_timeout = rule->hard_timeout;
4689 ovs_mutex_unlock(&rule->mutex);
4690 fu.table_id = rule->table_id;
4691 fu.cookie = rule->flow_cookie;
4692 minimatch_expand(&rule->cr.match, &match);
4694 fu.priority = rule->cr.priority;
4696 if (!(flags & NXFMF_ACTIONS)) {
4699 actions = rule->actions;
4701 /* An operation is in progress. Use the previous version of the flow's
4702 * actions, so that when the operation commits we report the change. */
4704 case OFOPERATION_ADD:
4707 case OFOPERATION_MODIFY:
4708 case OFOPERATION_REPLACE:
4709 actions = op->actions ? op->actions : rule->actions;
4712 case OFOPERATION_DELETE:
4713 actions = rule->actions;
4720 fu.ofpacts = actions ? actions->ofpacts : NULL;
4721 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4723 if (list_is_empty(msgs)) {
4724 ofputil_start_flow_update(msgs);
4726 ofputil_append_flow_update(&fu, msgs);
4730 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4732 OVS_REQUIRES(ofproto_mutex)
4736 for (i = 0; i < rules->n; i++) {
4737 struct rule *rule = rules->rules[i];
4738 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4739 rule->monitor_flags = 0;
4741 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4746 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4747 struct rule *rule, uint64_t seqno,
4748 struct rule_collection *rules)
4749 OVS_REQUIRES(ofproto_mutex)
4751 enum nx_flow_monitor_flags update;
4753 if (ofproto_rule_is_hidden(rule)) {
4758 ? ofoperation_has_out_port(rule->pending, m->out_port)
4759 : ofproto_rule_has_out_port(rule, m->out_port))) {
4764 if (rule->add_seqno > seqno) {
4765 update = NXFMF_ADD | NXFMF_MODIFY;
4766 } else if (rule->modify_seqno > seqno) {
4767 update = NXFMF_MODIFY;
4772 if (!(m->flags & update)) {
4776 update = NXFMF_INITIAL;
4779 if (!rule->monitor_flags) {
4780 rule_collection_add(rules, rule);
4782 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4786 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4788 struct rule_collection *rules)
4789 OVS_REQUIRES(ofproto_mutex)
4791 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4792 const struct ofoperation *op;
4793 const struct oftable *table;
4794 struct cls_rule target;
4796 cls_rule_init_from_minimatch(&target, &m->match, 0);
4797 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4798 struct cls_cursor cursor;
4801 ovs_rwlock_rdlock(&table->cls.rwlock);
4802 cls_cursor_init(&cursor, &table->cls, &target);
4803 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4804 ovs_assert(!rule->pending); /* XXX */
4805 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4807 ovs_rwlock_unlock(&table->cls.rwlock);
4810 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4811 struct rule *rule = op->rule;
4813 if (((m->table_id == 0xff
4814 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4815 : m->table_id == rule->table_id))
4816 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4817 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4820 cls_rule_destroy(&target);
4824 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4825 struct rule_collection *rules)
4826 OVS_REQUIRES(ofproto_mutex)
4828 if (m->flags & NXFMF_INITIAL) {
4829 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4834 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4835 uint64_t seqno, struct rule_collection *rules)
4836 OVS_REQUIRES(ofproto_mutex)
4838 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4842 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4843 OVS_EXCLUDED(ofproto_mutex)
4845 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4846 struct ofmonitor **monitors;
4847 size_t n_monitors, allocated_monitors;
4848 struct rule_collection rules;
4849 struct list replies;
4855 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4857 n_monitors = allocated_monitors = 0;
4859 ovs_mutex_lock(&ofproto_mutex);
4861 struct ofputil_flow_monitor_request request;
4862 struct ofmonitor *m;
4865 retval = ofputil_decode_flow_monitor_request(&request, &b);
4866 if (retval == EOF) {
4868 } else if (retval) {
4873 if (request.table_id != 0xff
4874 && request.table_id >= ofproto->n_tables) {
4875 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4879 error = ofmonitor_create(&request, ofconn, &m);
4884 if (n_monitors >= allocated_monitors) {
4885 monitors = x2nrealloc(monitors, &allocated_monitors,
4888 monitors[n_monitors++] = m;
4891 rule_collection_init(&rules);
4892 for (i = 0; i < n_monitors; i++) {
4893 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4896 ofpmp_init(&replies, oh);
4897 ofmonitor_compose_refresh_updates(&rules, &replies);
4898 ovs_mutex_unlock(&ofproto_mutex);
4900 rule_collection_destroy(&rules);
4902 ofconn_send_replies(ofconn, &replies);
4908 for (i = 0; i < n_monitors; i++) {
4909 ofmonitor_destroy(monitors[i]);
4912 ovs_mutex_unlock(&ofproto_mutex);
4918 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4919 OVS_EXCLUDED(ofproto_mutex)
4921 struct ofmonitor *m;
4925 id = ofputil_decode_flow_monitor_cancel(oh);
4927 ovs_mutex_lock(&ofproto_mutex);
4928 m = ofmonitor_lookup(ofconn, id);
4930 ofmonitor_destroy(m);
4933 error = OFPERR_NXBRC_FM_BAD_ID;
4935 ovs_mutex_unlock(&ofproto_mutex);
4940 /* Meters implementation.
4942 * Meter table entry, indexed by the OpenFlow meter_id.
4943 * These are always dynamically allocated to allocate enough space for
4945 * 'created' is used to compute the duration for meter stats.
4946 * 'list rules' is needed so that we can delete the dependent rules when the
4947 * meter table entry is deleted.
4948 * 'provider_meter_id' is for the provider's private use.
4951 long long int created; /* Time created. */
4952 struct list rules; /* List of "struct rule_dpif"s. */
4953 ofproto_meter_id provider_meter_id;
4954 uint16_t flags; /* Meter flags. */
4955 uint16_t n_bands; /* Number of meter bands. */
4956 struct ofputil_meter_band *bands;
4960 * This is used in instruction validation at flow set-up time,
4961 * as flows may not use non-existing meters.
4962 * Return value of UINT32_MAX signifies an invalid meter.
4965 get_provider_meter_id(const struct ofproto *ofproto, uint32_t of_meter_id)
4967 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4968 const struct meter *meter = ofproto->meters[of_meter_id];
4970 return meter->provider_meter_id.uint32;
4977 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4981 meter->flags = config->flags;
4982 meter->n_bands = config->n_bands;
4983 meter->bands = xmemdup(config->bands,
4984 config->n_bands * sizeof *meter->bands);
4987 static struct meter *
4988 meter_create(const struct ofputil_meter_config *config,
4989 ofproto_meter_id provider_meter_id)
4991 struct meter *meter;
4993 meter = xzalloc(sizeof *meter);
4994 meter->provider_meter_id = provider_meter_id;
4995 meter->created = time_msec();
4996 list_init(&meter->rules);
4998 meter_update(meter, config);
5004 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
5005 OVS_REQUIRES(ofproto_mutex)
5008 for (mid = first; mid <= last; ++mid) {
5009 struct meter *meter = ofproto->meters[mid];
5011 ofproto->meters[mid] = NULL;
5012 ofproto->ofproto_class->meter_del(ofproto,
5013 meter->provider_meter_id);
5021 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5023 ofproto_meter_id provider_meter_id = { UINT32_MAX };
5024 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
5028 return OFPERR_OFPMMFC_METER_EXISTS;
5031 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
5034 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
5035 *meterp = meter_create(&mm->meter, provider_meter_id);
5041 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5043 struct meter *meter = ofproto->meters[mm->meter.meter_id];
5045 uint32_t provider_meter_id;
5048 return OFPERR_OFPMMFC_UNKNOWN_METER;
5051 provider_meter_id = meter->provider_meter_id.uint32;
5052 error = ofproto->ofproto_class->meter_set(ofproto,
5053 &meter->provider_meter_id,
5055 ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
5057 meter_update(meter, &mm->meter);
5063 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
5064 struct ofputil_meter_mod *mm)
5065 OVS_EXCLUDED(ofproto_mutex)
5067 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5068 uint32_t meter_id = mm->meter.meter_id;
5069 struct rule_collection rules;
5070 enum ofperr error = 0;
5071 uint32_t first, last;
5073 if (meter_id == OFPM13_ALL) {
5075 last = ofproto->meter_features.max_meters;
5077 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
5080 first = last = meter_id;
5083 /* First delete the rules that use this meter. If any of those rules are
5084 * currently being modified, postpone the whole operation until later. */
5085 rule_collection_init(&rules);
5086 ovs_mutex_lock(&ofproto_mutex);
5087 for (meter_id = first; meter_id <= last; ++meter_id) {
5088 struct meter *meter = ofproto->meters[meter_id];
5089 if (meter && !list_is_empty(&meter->rules)) {
5092 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
5093 if (rule->pending) {
5094 error = OFPROTO_POSTPONE;
5097 rule_collection_add(&rules, rule);
5102 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
5105 /* Delete the meters. */
5106 meter_delete(ofproto, first, last);
5109 ovs_mutex_unlock(&ofproto_mutex);
5110 rule_collection_destroy(&rules);
5116 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5118 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5119 struct ofputil_meter_mod mm;
5120 uint64_t bands_stub[256 / 8];
5121 struct ofpbuf bands;
5125 error = reject_slave_controller(ofconn);
5130 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5132 error = ofputil_decode_meter_mod(oh, &mm, &bands);
5134 goto exit_free_bands;
5137 meter_id = mm.meter.meter_id;
5139 if (mm.command != OFPMC13_DELETE) {
5140 /* Fails also when meters are not implemented by the provider. */
5141 if (meter_id == 0 || meter_id > OFPM13_MAX) {
5142 error = OFPERR_OFPMMFC_INVALID_METER;
5143 goto exit_free_bands;
5144 } else if (meter_id > ofproto->meter_features.max_meters) {
5145 error = OFPERR_OFPMMFC_OUT_OF_METERS;
5146 goto exit_free_bands;
5148 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
5149 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
5150 goto exit_free_bands;
5154 switch (mm.command) {
5156 error = handle_add_meter(ofproto, &mm);
5159 case OFPMC13_MODIFY:
5160 error = handle_modify_meter(ofproto, &mm);
5163 case OFPMC13_DELETE:
5164 error = handle_delete_meter(ofconn, oh, &mm);
5168 error = OFPERR_OFPMMFC_BAD_COMMAND;
5173 ofpbuf_uninit(&bands);
5178 handle_meter_features_request(struct ofconn *ofconn,
5179 const struct ofp_header *request)
5181 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5182 struct ofputil_meter_features features;
5185 if (ofproto->ofproto_class->meter_get_features) {
5186 ofproto->ofproto_class->meter_get_features(ofproto, &features);
5188 memset(&features, 0, sizeof features);
5190 b = ofputil_encode_meter_features_reply(&features, request);
5192 ofconn_send_reply(ofconn, b);
5197 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
5200 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5201 struct list replies;
5202 uint64_t bands_stub[256 / 8];
5203 struct ofpbuf bands;
5204 uint32_t meter_id, first, last;
5206 ofputil_decode_meter_request(request, &meter_id);
5208 if (meter_id == OFPM13_ALL) {
5210 last = ofproto->meter_features.max_meters;
5212 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
5213 !ofproto->meters[meter_id]) {
5214 return OFPERR_OFPMMFC_UNKNOWN_METER;
5216 first = last = meter_id;
5219 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5220 ofpmp_init(&replies, request);
5222 for (meter_id = first; meter_id <= last; ++meter_id) {
5223 struct meter *meter = ofproto->meters[meter_id];
5225 continue; /* Skip non-existing meters. */
5227 if (type == OFPTYPE_METER_STATS_REQUEST) {
5228 struct ofputil_meter_stats stats;
5230 stats.meter_id = meter_id;
5232 /* Provider sets the packet and byte counts, we do the rest. */
5233 stats.flow_count = list_size(&meter->rules);
5234 calc_duration(meter->created, time_msec(),
5235 &stats.duration_sec, &stats.duration_nsec);
5236 stats.n_bands = meter->n_bands;
5237 ofpbuf_clear(&bands);
5239 = ofpbuf_put_uninit(&bands,
5240 meter->n_bands * sizeof *stats.bands);
5242 if (!ofproto->ofproto_class->meter_get(ofproto,
5243 meter->provider_meter_id,
5245 ofputil_append_meter_stats(&replies, &stats);
5247 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
5248 struct ofputil_meter_config config;
5250 config.meter_id = meter_id;
5251 config.flags = meter->flags;
5252 config.n_bands = meter->n_bands;
5253 config.bands = meter->bands;
5254 ofputil_append_meter_config(&replies, &config);
5258 ofconn_send_replies(ofconn, &replies);
5259 ofpbuf_uninit(&bands);
5264 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
5265 struct ofgroup **group)
5266 OVS_TRY_RDLOCK(true, (*group)->rwlock)
5268 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5269 HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5270 hash_int(group_id, 0), &ofproto->groups) {
5271 if ((*group)->group_id == group_id) {
5272 ovs_rwlock_rdlock(&(*group)->rwlock);
5273 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5277 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5282 ofproto_group_release(struct ofgroup *group)
5283 OVS_RELEASES(group->rwlock)
5285 ovs_rwlock_unlock(&group->rwlock);
5289 ofproto_group_write_lookup(const struct ofproto *ofproto, uint32_t group_id,
5290 struct ofgroup **group)
5291 OVS_TRY_WRLOCK(true, ofproto->groups_rwlock)
5292 OVS_TRY_WRLOCK(true, (*group)->rwlock)
5294 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5295 HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5296 hash_int(group_id, 0), &ofproto->groups) {
5297 if ((*group)->group_id == group_id) {
5298 ovs_rwlock_wrlock(&(*group)->rwlock);
5302 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5307 ofproto_group_exists__(const struct ofproto *ofproto, uint32_t group_id)
5308 OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5310 struct ofgroup *grp;
5312 HMAP_FOR_EACH_IN_BUCKET (grp, hmap_node,
5313 hash_int(group_id, 0), &ofproto->groups) {
5314 if (grp->group_id == group_id) {
5322 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
5323 OVS_EXCLUDED(ofproto->groups_rwlock)
5327 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5328 exists = ofproto_group_exists__(ofproto, group_id);
5329 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5335 group_get_ref_count(struct ofgroup *group)
5336 OVS_EXCLUDED(ofproto_mutex)
5338 struct ofproto *ofproto = group->ofproto;
5339 struct rule_criteria criteria;
5340 struct rule_collection rules;
5345 match_init_catchall(&match);
5346 rule_criteria_init(&criteria, 0xff, &match, 0, htonll(0), htonll(0),
5347 OFPP_ANY, group->group_id);
5348 ovs_mutex_lock(&ofproto_mutex);
5349 error = collect_rules_loose(ofproto, &criteria, &rules);
5350 ovs_mutex_unlock(&ofproto_mutex);
5351 rule_criteria_destroy(&criteria);
5353 count = !error && rules.n < UINT32_MAX ? rules.n : UINT32_MAX;
5355 rule_collection_destroy(&rules);
5360 append_group_stats(struct ofgroup *group, struct list *replies)
5361 OVS_REQ_RDLOCK(group->rwlock)
5363 struct ofputil_group_stats ogs;
5364 struct ofproto *ofproto = group->ofproto;
5365 long long int now = time_msec();
5368 ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
5370 /* Provider sets the packet and byte counts, we do the rest. */
5371 ogs.ref_count = group_get_ref_count(group);
5372 ogs.n_buckets = group->n_buckets;
5374 error = (ofproto->ofproto_class->group_get_stats
5375 ? ofproto->ofproto_class->group_get_stats(group, &ogs)
5378 ogs.packet_count = UINT64_MAX;
5379 ogs.byte_count = UINT64_MAX;
5380 memset(ogs.bucket_stats, 0xff,
5381 ogs.n_buckets * sizeof *ogs.bucket_stats);
5384 ogs.group_id = group->group_id;
5385 calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
5387 ofputil_append_group_stats(replies, &ogs);
5389 free(ogs.bucket_stats);
5393 handle_group_stats_request(struct ofconn *ofconn,
5394 const struct ofp_header *request)
5396 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5397 struct list replies;
5399 struct ofgroup *group;
5402 error = ofputil_decode_group_stats_request(request, &group_id);
5407 ofpmp_init(&replies, request);
5409 if (group_id == OFPG_ALL) {
5410 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5411 HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5412 ovs_rwlock_rdlock(&group->rwlock);
5413 append_group_stats(group, &replies);
5414 ovs_rwlock_unlock(&group->rwlock);
5416 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5418 if (ofproto_group_lookup(ofproto, group_id, &group)) {
5419 append_group_stats(group, &replies);
5420 ofproto_group_release(group);
5424 ofconn_send_replies(ofconn, &replies);
5430 handle_group_desc_stats_request(struct ofconn *ofconn,
5431 const struct ofp_header *request)
5433 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5434 struct list replies;
5435 struct ofputil_group_desc gds;
5436 struct ofgroup *group;
5438 ofpmp_init(&replies, request);
5440 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5441 HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5442 gds.group_id = group->group_id;
5443 gds.type = group->type;
5444 ofputil_append_group_desc_reply(&gds, &group->buckets, &replies);
5446 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5448 ofconn_send_replies(ofconn, &replies);
5454 handle_group_features_stats_request(struct ofconn *ofconn,
5455 const struct ofp_header *request)
5457 struct ofproto *p = ofconn_get_ofproto(ofconn);
5460 msg = ofputil_encode_group_features_reply(&p->ogf, request);
5462 ofconn_send_reply(ofconn, msg);
5469 handle_queue_get_config_request(struct ofconn *ofconn,
5470 const struct ofp_header *oh)
5472 struct ofproto *p = ofconn_get_ofproto(ofconn);
5473 struct netdev_queue_dump queue_dump;
5474 struct ofport *ofport;
5475 unsigned int queue_id;
5476 struct ofpbuf *reply;
5477 struct smap details;
5481 error = ofputil_decode_queue_get_config_request(oh, &request);
5486 ofport = ofproto_get_port(p, request);
5488 return OFPERR_OFPQOFC_BAD_PORT;
5491 reply = ofputil_encode_queue_get_config_reply(oh);
5493 smap_init(&details);
5494 NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &queue_dump, ofport->netdev) {
5495 struct ofputil_queue_config queue;
5497 /* None of the existing queues have compatible properties, so we
5498 * hard-code omitting min_rate and max_rate. */
5499 queue.queue_id = queue_id;
5500 queue.min_rate = UINT16_MAX;
5501 queue.max_rate = UINT16_MAX;
5502 ofputil_append_queue_get_config_reply(reply, &queue);
5504 smap_destroy(&details);
5506 ofconn_send_reply(ofconn, reply);
5511 /* Implements OFPGC11_ADD
5512 * in which no matching flow already exists in the flow table.
5514 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
5515 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
5516 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
5517 * initiated now but may be retried later.
5519 * Upon successful return, takes ownership of 'fm->ofpacts'. On failure,
5520 * ownership remains with the caller.
5522 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
5525 add_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5527 struct ofgroup *ofgroup;
5530 if (gm->group_id > OFPG_MAX) {
5531 return OFPERR_OFPGMFC_INVALID_GROUP;
5533 if (gm->type > OFPGT11_FF) {
5534 return OFPERR_OFPGMFC_BAD_TYPE;
5537 /* Allocate new group and initialize it. */
5538 ofgroup = ofproto->ofproto_class->group_alloc();
5540 VLOG_WARN_RL(&rl, "%s: failed to create group", ofproto->name);
5541 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5544 ovs_rwlock_init(&ofgroup->rwlock);
5545 ofgroup->ofproto = ofproto;
5546 ofgroup->group_id = gm->group_id;
5547 ofgroup->type = gm->type;
5548 ofgroup->created = ofgroup->modified = time_msec();
5550 list_move(&ofgroup->buckets, &gm->buckets);
5551 ofgroup->n_buckets = list_size(&ofgroup->buckets);
5553 /* Construct called BEFORE any locks are held. */
5554 error = ofproto->ofproto_class->group_construct(ofgroup);
5559 /* We wrlock as late as possible to minimize the time we jam any other
5560 * threads: No visible state changes before acquiring the lock. */
5561 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5563 if (ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5564 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5568 if (ofproto_group_exists__(ofproto, gm->group_id)) {
5569 error = OFPERR_OFPGMFC_GROUP_EXISTS;
5574 /* Insert new group. */
5575 hmap_insert(&ofproto->groups, &ofgroup->hmap_node,
5576 hash_int(ofgroup->group_id, 0));
5577 ofproto->n_groups[ofgroup->type]++;
5579 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5584 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5585 ofproto->ofproto_class->group_destruct(ofgroup);
5587 ofputil_bucket_list_destroy(&ofgroup->buckets);
5588 ofproto->ofproto_class->group_dealloc(ofgroup);
5593 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
5596 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
5599 modify_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5601 struct ofgroup *ofgroup;
5602 struct ofgroup *victim;
5605 if (gm->group_id > OFPG_MAX) {
5606 return OFPERR_OFPGMFC_INVALID_GROUP;
5609 if (gm->type > OFPGT11_FF) {
5610 return OFPERR_OFPGMFC_BAD_TYPE;
5613 victim = ofproto->ofproto_class->group_alloc();
5615 VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
5616 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5619 if (!ofproto_group_write_lookup(ofproto, gm->group_id, &ofgroup)) {
5620 error = OFPERR_OFPGMFC_UNKNOWN_GROUP;
5623 /* Both group's and its container's write locks held now.
5624 * Also, n_groups[] is protected by ofproto->groups_rwlock. */
5625 if (ofgroup->type != gm->type
5626 && ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5627 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5632 list_move(&victim->buckets, &ofgroup->buckets);
5634 ofgroup->type = gm->type;
5635 list_move(&ofgroup->buckets, &gm->buckets);
5636 ofgroup->n_buckets = list_size(&ofgroup->buckets);
5638 error = ofproto->ofproto_class->group_modify(ofgroup, victim);
5640 ofputil_bucket_list_destroy(&victim->buckets);
5641 ofproto->n_groups[victim->type]--;
5642 ofproto->n_groups[ofgroup->type]++;
5643 ofgroup->modified = time_msec();
5645 ofputil_bucket_list_destroy(&ofgroup->buckets);
5648 list_move(&ofgroup->buckets, &victim->buckets);
5652 ovs_rwlock_unlock(&ofgroup->rwlock);
5653 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5655 ofproto->ofproto_class->group_dealloc(victim);
5660 delete_group__(struct ofproto *ofproto, struct ofgroup *ofgroup)
5661 OVS_RELEASES(ofproto->groups_rwlock)
5664 struct ofputil_flow_mod fm;
5666 /* Delete all flow entries containing this group in a group action */
5667 match_init_catchall(&match);
5668 flow_mod_init(&fm, &match, 0, NULL, 0, OFPFC_DELETE);
5669 fm.out_group = ofgroup->group_id;
5670 handle_flow_mod__(ofproto, NULL, &fm, NULL);
5672 /* Must wait until existing readers are done,
5673 * while holding the container's write lock at the same time. */
5674 ovs_rwlock_wrlock(&ofgroup->rwlock);
5675 hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5676 /* No-one can find this group any more. */
5677 ofproto->n_groups[ofgroup->type]--;
5678 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5680 ofproto->ofproto_class->group_destruct(ofgroup);
5681 ofputil_bucket_list_destroy(&ofgroup->buckets);
5682 ovs_rwlock_unlock(&ofgroup->rwlock);
5683 ovs_rwlock_destroy(&ofgroup->rwlock);
5684 ofproto->ofproto_class->group_dealloc(ofgroup);
5687 /* Implements OFPGC_DELETE. */
5689 delete_group(struct ofproto *ofproto, uint32_t group_id)
5691 struct ofgroup *ofgroup;
5693 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5694 if (group_id == OFPG_ALL) {
5696 struct hmap_node *node = hmap_first(&ofproto->groups);
5700 ofgroup = CONTAINER_OF(node, struct ofgroup, hmap_node);
5701 delete_group__(ofproto, ofgroup);
5702 /* Lock for each node separately, so that we will not jam the
5703 * other threads for too long time. */
5704 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5707 HMAP_FOR_EACH_IN_BUCKET (ofgroup, hmap_node,
5708 hash_int(group_id, 0), &ofproto->groups) {
5709 if (ofgroup->group_id == group_id) {
5710 delete_group__(ofproto, ofgroup);
5715 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5719 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5721 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5722 struct ofputil_group_mod gm;
5725 error = reject_slave_controller(ofconn);
5730 error = ofputil_decode_group_mod(oh, &gm);
5735 switch (gm.command) {
5737 return add_group(ofproto, &gm);
5739 case OFPGC11_MODIFY:
5740 return modify_group(ofproto, &gm);
5742 case OFPGC11_DELETE:
5743 delete_group(ofproto, gm.group_id);
5747 if (gm.command > OFPGC11_DELETE) {
5748 VLOG_WARN_RL(&rl, "%s: Invalid group_mod command type %d",
5749 ofproto->name, gm.command);
5751 return OFPERR_OFPGMFC_BAD_COMMAND;
5756 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5758 struct ofputil_table_mod tm;
5761 error = reject_slave_controller(ofconn);
5766 error = ofputil_decode_table_mod(oh, &tm);
5771 /* XXX Actual table mod support is not implemented yet. */
5776 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
5777 OVS_EXCLUDED(ofproto_mutex)
5779 const struct ofp_header *oh = msg->data;
5783 error = ofptype_decode(&type, oh);
5787 if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
5788 && ofpmp_more(oh)) {
5789 /* We have no buffer implementation for multipart requests.
5790 * Report overflow for requests which consists of multiple
5792 return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
5796 /* OpenFlow requests. */
5797 case OFPTYPE_ECHO_REQUEST:
5798 return handle_echo_request(ofconn, oh);
5800 case OFPTYPE_FEATURES_REQUEST:
5801 return handle_features_request(ofconn, oh);
5803 case OFPTYPE_GET_CONFIG_REQUEST:
5804 return handle_get_config_request(ofconn, oh);
5806 case OFPTYPE_SET_CONFIG:
5807 return handle_set_config(ofconn, oh);
5809 case OFPTYPE_PACKET_OUT:
5810 return handle_packet_out(ofconn, oh);
5812 case OFPTYPE_PORT_MOD:
5813 return handle_port_mod(ofconn, oh);
5815 case OFPTYPE_FLOW_MOD:
5816 return handle_flow_mod(ofconn, oh);
5818 case OFPTYPE_GROUP_MOD:
5819 return handle_group_mod(ofconn, oh);
5821 case OFPTYPE_TABLE_MOD:
5822 return handle_table_mod(ofconn, oh);
5824 case OFPTYPE_METER_MOD:
5825 return handle_meter_mod(ofconn, oh);
5827 case OFPTYPE_BARRIER_REQUEST:
5828 return handle_barrier_request(ofconn, oh);
5830 case OFPTYPE_ROLE_REQUEST:
5831 return handle_role_request(ofconn, oh);
5833 /* OpenFlow replies. */
5834 case OFPTYPE_ECHO_REPLY:
5837 /* Nicira extension requests. */
5838 case OFPTYPE_FLOW_MOD_TABLE_ID:
5839 return handle_nxt_flow_mod_table_id(ofconn, oh);
5841 case OFPTYPE_SET_FLOW_FORMAT:
5842 return handle_nxt_set_flow_format(ofconn, oh);
5844 case OFPTYPE_SET_PACKET_IN_FORMAT:
5845 return handle_nxt_set_packet_in_format(ofconn, oh);
5847 case OFPTYPE_SET_CONTROLLER_ID:
5848 return handle_nxt_set_controller_id(ofconn, oh);
5850 case OFPTYPE_FLOW_AGE:
5851 /* Nothing to do. */
5854 case OFPTYPE_FLOW_MONITOR_CANCEL:
5855 return handle_flow_monitor_cancel(ofconn, oh);
5857 case OFPTYPE_SET_ASYNC_CONFIG:
5858 return handle_nxt_set_async_config(ofconn, oh);
5860 case OFPTYPE_GET_ASYNC_REQUEST:
5861 return handle_nxt_get_async_request(ofconn, oh);
5863 /* Statistics requests. */
5864 case OFPTYPE_DESC_STATS_REQUEST:
5865 return handle_desc_stats_request(ofconn, oh);
5867 case OFPTYPE_FLOW_STATS_REQUEST:
5868 return handle_flow_stats_request(ofconn, oh);
5870 case OFPTYPE_AGGREGATE_STATS_REQUEST:
5871 return handle_aggregate_stats_request(ofconn, oh);
5873 case OFPTYPE_TABLE_STATS_REQUEST:
5874 return handle_table_stats_request(ofconn, oh);
5876 case OFPTYPE_PORT_STATS_REQUEST:
5877 return handle_port_stats_request(ofconn, oh);
5879 case OFPTYPE_QUEUE_STATS_REQUEST:
5880 return handle_queue_stats_request(ofconn, oh);
5882 case OFPTYPE_PORT_DESC_STATS_REQUEST:
5883 return handle_port_desc_stats_request(ofconn, oh);
5885 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
5886 return handle_flow_monitor_request(ofconn, oh);
5888 case OFPTYPE_METER_STATS_REQUEST:
5889 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
5890 return handle_meter_request(ofconn, oh, type);
5892 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
5893 return handle_meter_features_request(ofconn, oh);
5895 case OFPTYPE_GROUP_STATS_REQUEST:
5896 return handle_group_stats_request(ofconn, oh);
5898 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
5899 return handle_group_desc_stats_request(ofconn, oh);
5901 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
5902 return handle_group_features_stats_request(ofconn, oh);
5904 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
5905 return handle_queue_get_config_request(ofconn, oh);
5909 case OFPTYPE_FEATURES_REPLY:
5910 case OFPTYPE_GET_CONFIG_REPLY:
5911 case OFPTYPE_PACKET_IN:
5912 case OFPTYPE_FLOW_REMOVED:
5913 case OFPTYPE_PORT_STATUS:
5914 case OFPTYPE_BARRIER_REPLY:
5915 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
5916 case OFPTYPE_DESC_STATS_REPLY:
5917 case OFPTYPE_FLOW_STATS_REPLY:
5918 case OFPTYPE_QUEUE_STATS_REPLY:
5919 case OFPTYPE_PORT_STATS_REPLY:
5920 case OFPTYPE_TABLE_STATS_REPLY:
5921 case OFPTYPE_AGGREGATE_STATS_REPLY:
5922 case OFPTYPE_PORT_DESC_STATS_REPLY:
5923 case OFPTYPE_ROLE_REPLY:
5924 case OFPTYPE_FLOW_MONITOR_PAUSED:
5925 case OFPTYPE_FLOW_MONITOR_RESUMED:
5926 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
5927 case OFPTYPE_GET_ASYNC_REPLY:
5928 case OFPTYPE_GROUP_STATS_REPLY:
5929 case OFPTYPE_GROUP_DESC_STATS_REPLY:
5930 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
5931 case OFPTYPE_METER_STATS_REPLY:
5932 case OFPTYPE_METER_CONFIG_STATS_REPLY:
5933 case OFPTYPE_METER_FEATURES_STATS_REPLY:
5934 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
5935 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
5936 case OFPTYPE_ROLE_STATUS:
5938 if (ofpmsg_is_stat_request(oh)) {
5939 return OFPERR_OFPBRC_BAD_STAT;
5941 return OFPERR_OFPBRC_BAD_TYPE;
5947 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
5948 OVS_EXCLUDED(ofproto_mutex)
5950 int error = handle_openflow__(ofconn, ofp_msg);
5951 if (error && error != OFPROTO_POSTPONE) {
5952 ofconn_send_error(ofconn, ofp_msg->data, error);
5954 COVERAGE_INC(ofproto_recv_openflow);
5955 return error != OFPROTO_POSTPONE;
5958 /* Asynchronous operations. */
5960 /* Creates and returns a new ofopgroup that is not associated with any
5961 * OpenFlow connection.
5963 * The caller should add operations to the returned group with
5964 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5965 static struct ofopgroup *
5966 ofopgroup_create_unattached(struct ofproto *ofproto)
5967 OVS_REQUIRES(ofproto_mutex)
5969 struct ofopgroup *group = xzalloc(sizeof *group);
5970 group->ofproto = ofproto;
5971 list_init(&group->ofproto_node);
5972 list_init(&group->ops);
5973 list_init(&group->ofconn_node);
5977 /* Creates and returns a new ofopgroup for 'ofproto'.
5979 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
5980 * connection. The 'request' and 'buffer_id' arguments are ignored.
5982 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
5983 * If the ofopgroup eventually fails, then the error reply will include
5984 * 'request'. If the ofopgroup eventually succeeds, then the packet with
5985 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
5987 * The caller should add operations to the returned group with
5988 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5989 static struct ofopgroup *
5990 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
5991 const struct ofp_header *request, uint32_t buffer_id)
5992 OVS_REQUIRES(ofproto_mutex)
5994 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
5996 size_t request_len = ntohs(request->length);
5998 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
6000 ofconn_add_opgroup(ofconn, &group->ofconn_node);
6001 group->ofconn = ofconn;
6002 group->request = xmemdup(request, MIN(request_len, 64));
6003 group->buffer_id = buffer_id;
6008 /* Submits 'group' for processing.
6010 * If 'group' contains no operations (e.g. none were ever added, or all of the
6011 * ones that were added completed synchronously), then it is destroyed
6012 * immediately. Otherwise it is added to the ofproto's list of pending
6015 ofopgroup_submit(struct ofopgroup *group)
6016 OVS_REQUIRES(ofproto_mutex)
6018 if (!group->n_running) {
6019 ofopgroup_complete(group);
6021 list_push_back(&group->ofproto->pending, &group->ofproto_node);
6022 group->ofproto->n_pending++;
6027 ofopgroup_complete(struct ofopgroup *group)
6028 OVS_REQUIRES(ofproto_mutex)
6030 struct ofproto *ofproto = group->ofproto;
6032 struct ofconn *abbrev_ofconn;
6033 ovs_be32 abbrev_xid;
6035 struct ofoperation *op, *next_op;
6038 ovs_assert(!group->n_running);
6041 LIST_FOR_EACH (op, group_node, &group->ops) {
6048 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
6049 LIST_FOR_EACH (op, group_node, &group->ops) {
6050 if (op->type != OFOPERATION_DELETE) {
6051 struct ofpbuf *packet;
6054 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
6057 struct rule_execute *re;
6061 ofproto_rule_ref(op->rule);
6063 re = xmalloc(sizeof *re);
6064 re->rule = op->rule;
6065 re->in_port = in_port;
6066 re->packet = packet;
6068 if (!guarded_list_push_back(&ofproto->rule_executes,
6069 &re->list_node, 1024)) {
6070 ofproto_rule_unref(op->rule);
6071 ofpbuf_delete(re->packet);
6080 if (!error && !list_is_empty(&group->ofconn_node)) {
6081 abbrev_ofconn = group->ofconn;
6082 abbrev_xid = group->request->xid;
6084 abbrev_ofconn = NULL;
6085 abbrev_xid = htonl(0);
6087 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
6088 struct rule *rule = op->rule;
6090 /* We generally want to report the change to active OpenFlow flow
6091 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
6093 - The operation failed.
6095 - The affected rule is not visible to controllers.
6097 - The operation's only effect was to update rule->modified. */
6099 || ofproto_rule_is_hidden(rule)
6100 || (op->type == OFOPERATION_MODIFY
6102 && rule->flow_cookie == op->flow_cookie))) {
6103 /* Check that we can just cast from ofoperation_type to
6104 * nx_flow_update_event. */
6105 enum nx_flow_update_event event_type;
6108 case OFOPERATION_ADD:
6109 case OFOPERATION_REPLACE:
6110 event_type = NXFME_ADDED;
6113 case OFOPERATION_DELETE:
6114 event_type = NXFME_DELETED;
6117 case OFOPERATION_MODIFY:
6118 event_type = NXFME_MODIFIED;
6125 ofmonitor_report(ofproto->connmgr, rule, event_type,
6126 op->reason, abbrev_ofconn, abbrev_xid);
6129 rule->pending = NULL;
6132 case OFOPERATION_ADD:
6136 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
6137 if (vid_mask == VLAN_VID_MASK) {
6138 if (ofproto->vlan_bitmap) {
6139 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
6140 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
6141 bitmap_set1(ofproto->vlan_bitmap, vid);
6142 ofproto->vlans_changed = true;
6145 ofproto->vlans_changed = true;
6149 oftable_remove_rule(rule);
6150 ofproto_rule_unref(rule);
6154 case OFOPERATION_DELETE:
6155 ovs_assert(!op->error);
6156 ofproto_rule_unref(rule);
6160 case OFOPERATION_MODIFY:
6161 case OFOPERATION_REPLACE:
6163 long long int now = time_msec();
6165 rule->modified = now;
6166 if (op->type == OFOPERATION_REPLACE) {
6167 rule->created = rule->used = now;
6170 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
6171 ovs_mutex_lock(&rule->mutex);
6172 rule->idle_timeout = op->idle_timeout;
6173 rule->hard_timeout = op->hard_timeout;
6174 ovs_mutex_unlock(&rule->mutex);
6176 struct rule_actions *old_actions;
6178 ovs_mutex_lock(&rule->mutex);
6179 old_actions = rule->actions;
6180 rule->actions = op->actions;
6181 ovs_mutex_unlock(&rule->mutex);
6184 rule_actions_unref(old_actions);
6186 rule->flags = op->flags;
6194 ofoperation_destroy(op);
6197 ofmonitor_flush(ofproto->connmgr);
6199 if (!list_is_empty(&group->ofproto_node)) {
6200 ovs_assert(ofproto->n_pending > 0);
6201 ofproto->n_pending--;
6202 list_remove(&group->ofproto_node);
6204 if (!list_is_empty(&group->ofconn_node)) {
6205 list_remove(&group->ofconn_node);
6207 ofconn_send_error(group->ofconn, group->request, error);
6209 connmgr_retry(ofproto->connmgr);
6211 free(group->request);
6215 /* Initiates a new operation on 'rule', of the specified 'type', within
6216 * 'group'. Prior to calling, 'rule' must not have any pending operation.
6218 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
6219 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
6221 * Returns the newly created ofoperation (which is also available as
6222 * rule->pending). */
6223 static struct ofoperation *
6224 ofoperation_create(struct ofopgroup *group, struct rule *rule,
6225 enum ofoperation_type type,
6226 enum ofp_flow_removed_reason reason)
6227 OVS_REQUIRES(ofproto_mutex)
6229 struct ofproto *ofproto = group->ofproto;
6230 struct ofoperation *op;
6232 ovs_assert(!rule->pending);
6234 op = rule->pending = xzalloc(sizeof *op);
6236 list_push_back(&group->ops, &op->group_node);
6239 op->reason = reason;
6240 op->flow_cookie = rule->flow_cookie;
6241 ovs_mutex_lock(&rule->mutex);
6242 op->idle_timeout = rule->idle_timeout;
6243 op->hard_timeout = rule->hard_timeout;
6244 ovs_mutex_unlock(&rule->mutex);
6245 op->flags = rule->flags;
6249 if (type == OFOPERATION_DELETE) {
6250 hmap_insert(&ofproto->deletions, &op->hmap_node,
6251 cls_rule_hash(&rule->cr, rule->table_id));
6258 ofoperation_destroy(struct ofoperation *op)
6259 OVS_REQUIRES(ofproto_mutex)
6261 struct ofopgroup *group = op->group;
6264 op->rule->pending = NULL;
6266 if (op->type == OFOPERATION_DELETE) {
6267 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
6269 list_remove(&op->group_node);
6270 rule_actions_unref(op->actions);
6274 /* Indicates that 'op' completed with status 'error', which is either 0 to
6275 * indicate success or an OpenFlow error code on failure.
6277 * If 'error' is 0, indicating success, the operation will be committed
6278 * permanently to the flow table.
6280 * If 'error' is nonzero, then generally the operation will be rolled back:
6282 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
6283 * restores the original rule. The caller must have uninitialized any
6284 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
6285 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
6286 * and 7 for the new rule, calling its ->rule_dealloc() function.
6288 * - If 'op' is a "modify flow" operation, ofproto restores the original
6291 * - 'op' must not be a "delete flow" operation. Removing a rule is not
6292 * allowed to fail. It must always succeed.
6294 * Please see the large comment in ofproto/ofproto-provider.h titled
6295 * "Asynchronous Operation Support" for more information. */
6297 ofoperation_complete(struct ofoperation *op, enum ofperr error)
6299 struct ofopgroup *group = op->group;
6301 ovs_assert(group->n_running > 0);
6302 ovs_assert(!error || op->type != OFOPERATION_DELETE);
6305 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
6306 /* This function can be called from ->rule_construct(), in which case
6307 * ofproto_mutex is held, or it can be called from ->run(), in which
6308 * case ofproto_mutex is not held. But only in the latter case can we
6309 * arrive here, so we can safely take ofproto_mutex now. */
6310 ovs_mutex_lock(&ofproto_mutex);
6311 ovs_assert(op->rule->pending == op);
6312 ofopgroup_complete(group);
6313 ovs_mutex_unlock(&ofproto_mutex);
6318 pick_datapath_id(const struct ofproto *ofproto)
6320 const struct ofport *port;
6322 port = ofproto_get_port(ofproto, OFPP_LOCAL);
6324 uint8_t ea[ETH_ADDR_LEN];
6327 error = netdev_get_etheraddr(port->netdev, ea);
6329 return eth_addr_to_uint64(ea);
6331 VLOG_WARN("%s: could not get MAC address for %s (%s)",
6332 ofproto->name, netdev_get_name(port->netdev),
6333 ovs_strerror(error));
6335 return ofproto->fallback_dpid;
6339 pick_fallback_dpid(void)
6341 uint8_t ea[ETH_ADDR_LEN];
6342 eth_addr_nicira_random(ea);
6343 return eth_addr_to_uint64(ea);
6346 /* Table overflow policy. */
6348 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
6349 * to NULL if the table is not configured to evict rules or if the table
6350 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
6351 * or with no timeouts are not evictable.) */
6353 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
6354 OVS_REQUIRES(ofproto_mutex)
6356 struct eviction_group *evg;
6359 if (!table->eviction_fields) {
6363 /* In the common case, the outer and inner loops here will each be entered
6366 * - The inner loop normally "return"s in its first iteration. If the
6367 * eviction group has any evictable rules, then it always returns in
6370 * - The outer loop only iterates more than once if the largest eviction
6371 * group has no evictable rules.
6373 * - The outer loop can exit only if table's 'max_flows' is all filled up
6374 * by unevictable rules. */
6375 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
6378 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
6387 /* Searches 'ofproto' for tables that have more flows than their configured
6388 * maximum and that have flow eviction enabled, and evicts as many flows as
6389 * necessary and currently feasible from them.
6391 * This triggers only when an OpenFlow table has N flows in it and then the
6392 * client configures a maximum number of flows less than N. */
6394 ofproto_evict(struct ofproto *ofproto)
6396 struct oftable *table;
6398 ovs_mutex_lock(&ofproto_mutex);
6399 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
6400 evict_rules_from_table(ofproto, table, 0);
6402 ovs_mutex_unlock(&ofproto_mutex);
6405 /* Eviction groups. */
6407 /* Returns the priority to use for an eviction_group that contains 'n_rules'
6408 * rules. The priority contains low-order random bits to ensure that eviction
6409 * groups with the same number of rules are prioritized randomly. */
6411 eviction_group_priority(size_t n_rules)
6413 uint16_t size = MIN(UINT16_MAX, n_rules);
6414 return (size << 16) | random_uint16();
6417 /* Updates 'evg', an eviction_group within 'table', following a change that
6418 * adds or removes rules in 'evg'. */
6420 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
6421 OVS_REQUIRES(ofproto_mutex)
6423 heap_change(&table->eviction_groups_by_size, &evg->size_node,
6424 eviction_group_priority(heap_count(&evg->rules)));
6427 /* Destroys 'evg', an eviction_group within 'table':
6429 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
6430 * rules themselves, just removes them from the eviction group.)
6432 * - Removes 'evg' from 'table'.
6436 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
6437 OVS_REQUIRES(ofproto_mutex)
6439 while (!heap_is_empty(&evg->rules)) {
6442 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
6443 rule->eviction_group = NULL;
6445 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
6446 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
6447 heap_destroy(&evg->rules);
6451 /* Removes 'rule' from its eviction group, if any. */
6453 eviction_group_remove_rule(struct rule *rule)
6454 OVS_REQUIRES(ofproto_mutex)
6456 if (rule->eviction_group) {
6457 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6458 struct eviction_group *evg = rule->eviction_group;
6460 rule->eviction_group = NULL;
6461 heap_remove(&evg->rules, &rule->evg_node);
6462 if (heap_is_empty(&evg->rules)) {
6463 eviction_group_destroy(table, evg);
6465 eviction_group_resized(table, evg);
6470 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
6471 * returns the hash value. */
6473 eviction_group_hash_rule(struct rule *rule)
6474 OVS_REQUIRES(ofproto_mutex)
6476 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6477 const struct mf_subfield *sf;
6481 hash = table->eviction_group_id_basis;
6482 miniflow_expand(&rule->cr.match.flow, &flow);
6483 for (sf = table->eviction_fields;
6484 sf < &table->eviction_fields[table->n_eviction_fields];
6487 if (mf_are_prereqs_ok(sf->field, &flow)) {
6488 union mf_value value;
6490 mf_get_value(sf->field, &flow, &value);
6492 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
6494 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
6495 unsigned int start = sf->ofs + sf->n_bits;
6496 bitwise_zero(&value, sf->field->n_bytes, start,
6497 sf->field->n_bytes * 8 - start);
6499 hash = hash_bytes(&value, sf->field->n_bytes, hash);
6501 hash = hash_int(hash, 0);
6508 /* Returns an eviction group within 'table' with the given 'id', creating one
6510 static struct eviction_group *
6511 eviction_group_find(struct oftable *table, uint32_t id)
6512 OVS_REQUIRES(ofproto_mutex)
6514 struct eviction_group *evg;
6516 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
6520 evg = xmalloc(sizeof *evg);
6521 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
6522 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
6523 eviction_group_priority(0));
6524 heap_init(&evg->rules);
6529 /* Returns an eviction priority for 'rule'. The return value should be
6530 * interpreted so that higher priorities make a rule more attractive candidates
6533 rule_eviction_priority(struct rule *rule)
6534 OVS_REQUIRES(ofproto_mutex)
6536 long long int hard_expiration;
6537 long long int idle_expiration;
6538 long long int expiration;
6539 uint32_t expiration_offset;
6541 /* Calculate time of expiration. */
6542 ovs_mutex_lock(&rule->mutex);
6543 hard_expiration = (rule->hard_timeout
6544 ? rule->modified + rule->hard_timeout * 1000
6546 idle_expiration = (rule->idle_timeout
6547 ? rule->used + rule->idle_timeout * 1000
6549 expiration = MIN(hard_expiration, idle_expiration);
6550 ovs_mutex_unlock(&rule->mutex);
6551 if (expiration == LLONG_MAX) {
6555 /* Calculate the time of expiration as a number of (approximate) seconds
6556 * after program startup.
6558 * This should work OK for program runs that last UINT32_MAX seconds or
6559 * less. Therefore, please restart OVS at least once every 136 years. */
6560 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
6562 /* Invert the expiration offset because we're using a max-heap. */
6563 return UINT32_MAX - expiration_offset;
6566 /* Adds 'rule' to an appropriate eviction group for its oftable's
6567 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
6568 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
6571 * The caller must ensure that 'rule' is not already in an eviction group. */
6573 eviction_group_add_rule(struct rule *rule)
6574 OVS_REQUIRES(ofproto_mutex)
6576 struct ofproto *ofproto = rule->ofproto;
6577 struct oftable *table = &ofproto->tables[rule->table_id];
6580 ovs_mutex_lock(&rule->mutex);
6581 has_timeout = rule->hard_timeout || rule->idle_timeout;
6582 ovs_mutex_unlock(&rule->mutex);
6584 if (table->eviction_fields && has_timeout) {
6585 struct eviction_group *evg;
6587 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
6589 rule->eviction_group = evg;
6590 heap_insert(&evg->rules, &rule->evg_node,
6591 rule_eviction_priority(rule));
6592 eviction_group_resized(table, evg);
6598 /* Initializes 'table'. */
6600 oftable_init(struct oftable *table)
6602 memset(table, 0, sizeof *table);
6603 classifier_init(&table->cls);
6604 table->max_flows = UINT_MAX;
6607 /* Destroys 'table', including its classifier and eviction groups.
6609 * The caller is responsible for freeing 'table' itself. */
6611 oftable_destroy(struct oftable *table)
6613 ovs_rwlock_rdlock(&table->cls.rwlock);
6614 ovs_assert(classifier_is_empty(&table->cls));
6615 ovs_rwlock_unlock(&table->cls.rwlock);
6616 oftable_disable_eviction(table);
6617 classifier_destroy(&table->cls);
6621 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
6622 * string, then 'table' will use its default name.
6624 * This only affects the name exposed for a table exposed through the OpenFlow
6625 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
6627 oftable_set_name(struct oftable *table, const char *name)
6629 if (name && name[0]) {
6630 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
6631 if (!table->name || strncmp(name, table->name, len)) {
6633 table->name = xmemdup0(name, len);
6641 /* oftables support a choice of two policies when adding a rule would cause the
6642 * number of flows in the table to exceed the configured maximum number: either
6643 * they can refuse to add the new flow or they can evict some existing flow.
6644 * This function configures the former policy on 'table'. */
6646 oftable_disable_eviction(struct oftable *table)
6647 OVS_REQUIRES(ofproto_mutex)
6649 if (table->eviction_fields) {
6650 struct eviction_group *evg, *next;
6652 HMAP_FOR_EACH_SAFE (evg, next, id_node,
6653 &table->eviction_groups_by_id) {
6654 eviction_group_destroy(table, evg);
6656 hmap_destroy(&table->eviction_groups_by_id);
6657 heap_destroy(&table->eviction_groups_by_size);
6659 free(table->eviction_fields);
6660 table->eviction_fields = NULL;
6661 table->n_eviction_fields = 0;
6665 /* oftables support a choice of two policies when adding a rule would cause the
6666 * number of flows in the table to exceed the configured maximum number: either
6667 * they can refuse to add the new flow or they can evict some existing flow.
6668 * This function configures the latter policy on 'table', with fairness based
6669 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
6670 * 'n_fields' as 0 disables fairness.) */
6672 oftable_enable_eviction(struct oftable *table,
6673 const struct mf_subfield *fields, size_t n_fields)
6674 OVS_REQUIRES(ofproto_mutex)
6676 struct cls_cursor cursor;
6679 if (table->eviction_fields
6680 && n_fields == table->n_eviction_fields
6682 || !memcmp(fields, table->eviction_fields,
6683 n_fields * sizeof *fields))) {
6688 oftable_disable_eviction(table);
6690 table->n_eviction_fields = n_fields;
6691 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
6693 table->eviction_group_id_basis = random_uint32();
6694 hmap_init(&table->eviction_groups_by_id);
6695 heap_init(&table->eviction_groups_by_size);
6697 ovs_rwlock_rdlock(&table->cls.rwlock);
6698 cls_cursor_init(&cursor, &table->cls, NULL);
6699 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6700 eviction_group_add_rule(rule);
6702 ovs_rwlock_unlock(&table->cls.rwlock);
6705 /* Removes 'rule' from the oftable that contains it. */
6707 oftable_remove_rule__(struct ofproto *ofproto, struct rule *rule)
6708 OVS_REQUIRES(ofproto_mutex)
6710 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
6712 ovs_rwlock_wrlock(&cls->rwlock);
6713 classifier_remove(cls, CONST_CAST(struct cls_rule *, &rule->cr));
6714 ovs_rwlock_unlock(&cls->rwlock);
6716 cookies_remove(ofproto, rule);
6718 eviction_group_remove_rule(rule);
6719 if (!list_is_empty(&rule->expirable)) {
6720 list_remove(&rule->expirable);
6722 if (!list_is_empty(&rule->meter_list_node)) {
6723 list_remove(&rule->meter_list_node);
6724 list_init(&rule->meter_list_node);
6729 oftable_remove_rule(struct rule *rule)
6730 OVS_REQUIRES(ofproto_mutex)
6732 oftable_remove_rule__(rule->ofproto, rule);
6735 /* Inserts 'rule' into its oftable, which must not already contain any rule for
6736 * the same cls_rule. */
6738 oftable_insert_rule(struct rule *rule)
6739 OVS_REQUIRES(ofproto_mutex)
6741 struct ofproto *ofproto = rule->ofproto;
6742 struct oftable *table = &ofproto->tables[rule->table_id];
6745 ovs_mutex_lock(&rule->mutex);
6746 may_expire = rule->hard_timeout || rule->idle_timeout;
6747 ovs_mutex_unlock(&rule->mutex);
6750 list_insert(&ofproto->expirable, &rule->expirable);
6753 cookies_insert(ofproto, rule);
6755 if (rule->actions->provider_meter_id != UINT32_MAX) {
6756 uint32_t meter_id = ofpacts_get_meter(rule->actions->ofpacts,
6757 rule->actions->ofpacts_len);
6758 struct meter *meter = ofproto->meters[meter_id];
6759 list_insert(&meter->rules, &rule->meter_list_node);
6761 ovs_rwlock_wrlock(&table->cls.rwlock);
6762 classifier_insert(&table->cls, CONST_CAST(struct cls_rule *, &rule->cr));
6763 ovs_rwlock_unlock(&table->cls.rwlock);
6764 eviction_group_add_rule(rule);
6767 /* unixctl commands. */
6770 ofproto_lookup(const char *name)
6772 struct ofproto *ofproto;
6774 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
6776 if (!strcmp(ofproto->name, name)) {
6784 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
6785 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6787 struct ofproto *ofproto;
6791 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
6792 ds_put_format(&results, "%s\n", ofproto->name);
6794 unixctl_command_reply(conn, ds_cstr(&results));
6795 ds_destroy(&results);
6799 ofproto_unixctl_init(void)
6801 static bool registered;
6807 unixctl_command_register("ofproto/list", "", 0, 0,
6808 ofproto_unixctl_list, NULL);
6811 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6813 * This is deprecated. It is only for compatibility with broken device drivers
6814 * in old versions of Linux that do not properly support VLANs when VLAN
6815 * devices are not used. When broken device drivers are no longer in
6816 * widespread use, we will delete these interfaces. */
6818 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
6819 * (exactly) by an OpenFlow rule in 'ofproto'. */
6821 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
6823 const struct oftable *oftable;
6825 free(ofproto->vlan_bitmap);
6826 ofproto->vlan_bitmap = bitmap_allocate(4096);
6827 ofproto->vlans_changed = false;
6829 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
6830 const struct cls_subtable *table;
6832 ovs_rwlock_rdlock(&oftable->cls.rwlock);
6833 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.subtables) {
6834 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
6835 const struct cls_rule *rule;
6837 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
6838 uint16_t vid = miniflow_get_vid(&rule->match.flow);
6839 bitmap_set1(vlan_bitmap, vid);
6840 bitmap_set1(ofproto->vlan_bitmap, vid);
6844 ovs_rwlock_unlock(&oftable->cls.rwlock);
6848 /* Returns true if new VLANs have come into use by the flow table since the
6849 * last call to ofproto_get_vlan_usage().
6851 * We don't track when old VLANs stop being used. */
6853 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
6855 return ofproto->vlans_changed;
6858 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
6859 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
6860 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
6861 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
6862 * then the VLAN device is un-enslaved. */
6864 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
6865 ofp_port_t realdev_ofp_port, int vid)
6867 struct ofport *ofport;
6870 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
6872 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
6874 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
6875 ofproto->name, vlandev_ofp_port);
6879 if (!ofproto->ofproto_class->set_realdev) {
6880 if (!vlandev_ofp_port) {
6883 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
6887 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
6889 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
6890 ofproto->name, vlandev_ofp_port,
6891 netdev_get_name(ofport->netdev), ovs_strerror(error));