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.actions[0] =
535 #define OFPAT11_ACTION(ENUM, STRUCT, EXTENSIBLE, NAME) (1 << ENUM) |
536 #include "ofp-util.def"
539 error = ofproto->ofproto_class->construct(ofproto);
541 VLOG_ERR("failed to open datapath %s: %s",
542 datapath_name, ovs_strerror(error));
543 ofproto_destroy__(ofproto);
547 /* Check that hidden tables, if any, are at the end. */
548 ovs_assert(ofproto->n_tables);
549 for (i = 0; i + 1 < ofproto->n_tables; i++) {
550 enum oftable_flags flags = ofproto->tables[i].flags;
551 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
553 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
556 ofproto->datapath_id = pick_datapath_id(ofproto);
559 /* Initialize meters table. */
560 if (ofproto->ofproto_class->meter_get_features) {
561 ofproto->ofproto_class->meter_get_features(ofproto,
562 &ofproto->meter_features);
564 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
566 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
567 * sizeof(struct meter *));
573 /* Must be called (only) by an ofproto implementation in its constructor
574 * function. See the large comment on 'construct' in struct ofproto_class for
577 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
579 struct oftable *table;
581 ovs_assert(!ofproto->n_tables);
582 ovs_assert(n_tables >= 1 && n_tables <= 255);
584 ofproto->n_tables = n_tables;
585 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
586 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
591 /* To be optionally called (only) by an ofproto implementation in its
592 * constructor function. See the large comment on 'construct' in struct
593 * ofproto_class for details.
595 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
596 * will then ensure that actions passed into the ofproto implementation will
597 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
598 * function is not called, there will be no such restriction.
600 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
601 * the 'max_ports' restriction. */
603 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
605 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
606 ofproto->max_ports = max_ports;
610 ofproto_get_datapath_id(const struct ofproto *ofproto)
612 return ofproto->datapath_id;
616 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
618 uint64_t old_dpid = p->datapath_id;
619 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
620 if (p->datapath_id != old_dpid) {
621 /* Force all active connections to reconnect, since there is no way to
622 * notify a controller that the datapath ID has changed. */
623 ofproto_reconnect_controllers(p);
628 ofproto_set_controllers(struct ofproto *p,
629 const struct ofproto_controller *controllers,
630 size_t n_controllers, uint32_t allowed_versions)
632 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
637 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
639 connmgr_set_fail_mode(p->connmgr, fail_mode);
642 /* Drops the connections between 'ofproto' and all of its controllers, forcing
643 * them to reconnect. */
645 ofproto_reconnect_controllers(struct ofproto *ofproto)
647 connmgr_reconnect(ofproto->connmgr);
650 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
651 * in-band control should guarantee access, in the same way that in-band
652 * control guarantees access to OpenFlow controllers. */
654 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
655 const struct sockaddr_in *extras, size_t n)
657 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
660 /* Sets the OpenFlow queue used by flows set up by in-band control on
661 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
662 * flows will use the default queue. */
664 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
666 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
669 /* Sets the number of flows at which eviction from the kernel flow table
672 ofproto_set_flow_eviction_threshold(unsigned threshold)
674 flow_eviction_threshold = MAX(OFPROTO_FLOW_EVICTION_THRESHOLD_MIN,
678 /* Sets the path for handling flow misses. */
680 ofproto_set_flow_miss_model(unsigned model)
682 flow_miss_model = model;
685 /* If forward_bpdu is true, the NORMAL action will forward frames with
686 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
687 * the NORMAL action will drop these frames. */
689 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
691 bool old_val = ofproto->forward_bpdu;
692 ofproto->forward_bpdu = forward_bpdu;
693 if (old_val != ofproto->forward_bpdu) {
694 if (ofproto->ofproto_class->forward_bpdu_changed) {
695 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
700 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
701 * 'idle_time', in seconds, and the maximum number of MAC table entries to
704 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
707 if (ofproto->ofproto_class->set_mac_table_config) {
708 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
713 /* Sets number of upcall handler threads. The default is
714 * (number of online cores - 2). */
716 ofproto_set_n_handler_threads(unsigned limit)
719 n_handler_threads = limit;
721 int n_proc = sysconf(_SC_NPROCESSORS_ONLN);
722 n_handler_threads = n_proc > 2 ? n_proc - 2 : 1;
727 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
730 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
734 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
736 return connmgr_set_snoops(ofproto->connmgr, snoops);
740 ofproto_set_netflow(struct ofproto *ofproto,
741 const struct netflow_options *nf_options)
743 if (nf_options && sset_is_empty(&nf_options->collectors)) {
747 if (ofproto->ofproto_class->set_netflow) {
748 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
750 return nf_options ? EOPNOTSUPP : 0;
755 ofproto_set_sflow(struct ofproto *ofproto,
756 const struct ofproto_sflow_options *oso)
758 if (oso && sset_is_empty(&oso->targets)) {
762 if (ofproto->ofproto_class->set_sflow) {
763 return ofproto->ofproto_class->set_sflow(ofproto, oso);
765 return oso ? EOPNOTSUPP : 0;
770 ofproto_set_ipfix(struct ofproto *ofproto,
771 const struct ofproto_ipfix_bridge_exporter_options *bo,
772 const struct ofproto_ipfix_flow_exporter_options *fo,
775 if (ofproto->ofproto_class->set_ipfix) {
776 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
778 return (bo || fo) ? EOPNOTSUPP : 0;
783 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
785 flow_restore_wait = flow_restore_wait_db;
789 ofproto_get_flow_restore_wait(void)
791 return flow_restore_wait;
795 /* Spanning Tree Protocol (STP) configuration. */
797 /* Configures STP on 'ofproto' using the settings defined in 's'. If
798 * 's' is NULL, disables STP.
800 * Returns 0 if successful, otherwise a positive errno value. */
802 ofproto_set_stp(struct ofproto *ofproto,
803 const struct ofproto_stp_settings *s)
805 return (ofproto->ofproto_class->set_stp
806 ? ofproto->ofproto_class->set_stp(ofproto, s)
810 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
811 * 'enabled' member of 's' is false, then the other members are not
814 * Returns 0 if successful, otherwise a positive errno value. */
816 ofproto_get_stp_status(struct ofproto *ofproto,
817 struct ofproto_stp_status *s)
819 return (ofproto->ofproto_class->get_stp_status
820 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
824 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
825 * in 's'. The caller is responsible for assigning STP port numbers
826 * (using the 'port_num' member in the range of 1 through 255, inclusive)
827 * and ensuring there are no duplicates. If the 's' is NULL, then STP
828 * is disabled on the port.
830 * Returns 0 if successful, otherwise a positive errno value.*/
832 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
833 const struct ofproto_port_stp_settings *s)
835 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
837 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
838 ofproto->name, ofp_port);
842 return (ofproto->ofproto_class->set_stp_port
843 ? ofproto->ofproto_class->set_stp_port(ofport, s)
847 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
848 * 's'. If the 'enabled' member in 's' is false, then the other members
849 * are not meaningful.
851 * Returns 0 if successful, otherwise a positive errno value.*/
853 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
854 struct ofproto_port_stp_status *s)
856 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
858 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
859 "port %"PRIu16, ofproto->name, ofp_port);
863 return (ofproto->ofproto_class->get_stp_port_status
864 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
868 /* Queue DSCP configuration. */
870 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
871 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
872 * to implement QoS. Instead, it is used to implement features which require
873 * knowledge of what queues exist on a port, and some basic information about
876 * Returns 0 if successful, otherwise a positive errno value. */
878 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
879 const struct ofproto_port_queue *queues,
882 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
885 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
886 ofproto->name, ofp_port);
890 return (ofproto->ofproto_class->set_queues
891 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
895 /* Connectivity Fault Management configuration. */
897 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
899 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
901 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
902 if (ofport && ofproto->ofproto_class->set_cfm) {
903 ofproto->ofproto_class->set_cfm(ofport, NULL);
907 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
908 * basic configuration from the configuration members in 'cfm', and the remote
909 * maintenance point ID from remote_mpid. Ignores the statistics members of
912 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
914 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
915 const struct cfm_settings *s)
917 struct ofport *ofport;
920 ofport = ofproto_get_port(ofproto, ofp_port);
922 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
923 ofproto->name, ofp_port);
927 /* XXX: For configuration simplicity, we only support one remote_mpid
928 * outside of the CFM module. It's not clear if this is the correct long
929 * term solution or not. */
930 error = (ofproto->ofproto_class->set_cfm
931 ? ofproto->ofproto_class->set_cfm(ofport, s)
934 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
935 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
936 ovs_strerror(error));
940 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
941 * 'ofproto' does not have a port 'ofp_port'. */
943 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
944 const struct smap *cfg)
946 struct ofport *ofport;
949 ofport = ofproto_get_port(ofproto, ofp_port);
951 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
952 ofproto->name, ofp_port);
956 error = (ofproto->ofproto_class->set_bfd
957 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
960 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
961 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
962 ovs_strerror(error));
966 /* Populates 'status' with key value pairs indicating the status of the BFD
967 * session on 'ofp_port'. This information is intended to be populated in the
968 * OVS database. Has no effect if 'ofp_port' is not na OpenFlow port in
971 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
974 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
975 return (ofport && ofproto->ofproto_class->get_bfd_status
976 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
980 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
981 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
982 * 0 if LACP partner information is not current (generally indicating a
983 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
985 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
987 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
988 return (ofport && ofproto->ofproto_class->port_is_lacp_current
989 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
995 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
996 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
997 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
998 * configuration plus, if there is more than one slave, a bonding
1001 * If 'aux' is already registered then this function updates its configuration
1002 * to 's'. Otherwise, this function registers a new bundle.
1004 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
1007 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
1008 const struct ofproto_bundle_settings *s)
1010 return (ofproto->ofproto_class->bundle_set
1011 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1015 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1016 * If no such bundle has been registered, this has no effect. */
1018 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1020 return ofproto_bundle_register(ofproto, aux, NULL);
1024 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1025 * If 'aux' is already registered then this function updates its configuration
1026 * to 's'. Otherwise, this function registers a new mirror. */
1028 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1029 const struct ofproto_mirror_settings *s)
1031 return (ofproto->ofproto_class->mirror_set
1032 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1036 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1037 * If no mirror has been registered, this has no effect. */
1039 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1041 return ofproto_mirror_register(ofproto, aux, NULL);
1044 /* Retrieves statistics from mirror associated with client data pointer
1045 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1046 * 'bytes', respectively. If a particular counters is not supported,
1047 * the appropriate argument is set to UINT64_MAX. */
1049 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1050 uint64_t *packets, uint64_t *bytes)
1052 if (!ofproto->ofproto_class->mirror_get_stats) {
1053 *packets = *bytes = UINT64_MAX;
1057 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1061 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1062 * which all packets are flooded, instead of using MAC learning. If
1063 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1065 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1068 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1070 return (ofproto->ofproto_class->set_flood_vlans
1071 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1075 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1076 * output for a mirror. */
1078 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1080 return (ofproto->ofproto_class->is_mirror_output_bundle
1081 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1085 /* Configuration of OpenFlow tables. */
1087 /* Returns the number of OpenFlow tables in 'ofproto'. */
1089 ofproto_get_n_tables(const struct ofproto *ofproto)
1091 return ofproto->n_tables;
1094 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1095 * settings from 's'. 'table_id' must be in the range 0 through the number of
1096 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1098 * For read-only tables, only the name may be configured. */
1100 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1101 const struct ofproto_table_settings *s)
1103 struct oftable *table;
1105 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1106 table = &ofproto->tables[table_id];
1108 oftable_set_name(table, s->name);
1110 if (table->flags & OFTABLE_READONLY) {
1115 oftable_enable_eviction(table, s->groups, s->n_groups);
1117 oftable_disable_eviction(table);
1120 table->max_flows = s->max_flows;
1121 ovs_rwlock_rdlock(&table->cls.rwlock);
1122 if (classifier_count(&table->cls) > table->max_flows
1123 && table->eviction_fields) {
1124 /* 'table' contains more flows than allowed. We might not be able to
1125 * evict them right away because of the asynchronous nature of flow
1126 * table changes. Schedule eviction for later. */
1127 switch (ofproto->state) {
1129 ofproto->state = S_EVICT;
1133 /* We're already deleting flows, nothing more to do. */
1137 ovs_rwlock_unlock(&table->cls.rwlock);
1141 ofproto_has_snoops(const struct ofproto *ofproto)
1143 return connmgr_has_snoops(ofproto->connmgr);
1147 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1149 connmgr_get_snoops(ofproto->connmgr, snoops);
1153 ofproto_rule_delete__(struct ofproto *ofproto, struct rule *rule,
1155 OVS_REQUIRES(ofproto_mutex)
1157 struct ofopgroup *group;
1159 ovs_assert(!rule->pending);
1161 group = ofopgroup_create_unattached(ofproto);
1162 delete_flow__(rule, group, reason);
1163 ofopgroup_submit(group);
1166 /* Deletes 'rule' from 'cls' within 'ofproto'.
1168 * Within an ofproto implementation, this function allows an ofproto
1169 * implementation to destroy any rules that remain when its ->destruct()
1170 * function is called. This function is not suitable for use elsewhere in an
1171 * ofproto implementation.
1173 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1174 * Cycle" in ofproto-provider.h. */
1176 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1177 OVS_EXCLUDED(ofproto_mutex)
1179 struct ofopgroup *group;
1181 ovs_mutex_lock(&ofproto_mutex);
1182 ovs_assert(!rule->pending);
1184 group = ofopgroup_create_unattached(ofproto);
1185 ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1186 oftable_remove_rule__(ofproto, rule);
1187 ofproto->ofproto_class->rule_delete(rule);
1188 ofopgroup_submit(group);
1190 ovs_mutex_unlock(&ofproto_mutex);
1194 ofproto_flush__(struct ofproto *ofproto)
1195 OVS_EXCLUDED(ofproto_mutex)
1197 struct oftable *table;
1199 if (ofproto->ofproto_class->flush) {
1200 ofproto->ofproto_class->flush(ofproto);
1203 ovs_mutex_lock(&ofproto_mutex);
1204 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1205 struct rule *rule, *next_rule;
1206 struct cls_cursor cursor;
1208 if (table->flags & OFTABLE_HIDDEN) {
1212 ovs_rwlock_rdlock(&table->cls.rwlock);
1213 cls_cursor_init(&cursor, &table->cls, NULL);
1214 ovs_rwlock_unlock(&table->cls.rwlock);
1215 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1216 if (!rule->pending) {
1217 ofproto_rule_delete__(ofproto, rule, OFPRR_DELETE);
1221 ovs_mutex_unlock(&ofproto_mutex);
1224 static void delete_group(struct ofproto *ofproto, uint32_t group_id);
1227 ofproto_destroy__(struct ofproto *ofproto)
1228 OVS_EXCLUDED(ofproto_mutex)
1230 struct oftable *table;
1232 ovs_assert(list_is_empty(&ofproto->pending));
1234 destroy_rule_executes(ofproto);
1235 guarded_list_destroy(&ofproto->rule_executes);
1237 delete_group(ofproto, OFPG_ALL);
1238 ovs_rwlock_destroy(&ofproto->groups_rwlock);
1239 hmap_destroy(&ofproto->groups);
1241 connmgr_destroy(ofproto->connmgr);
1243 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1244 free(ofproto->name);
1245 free(ofproto->type);
1246 free(ofproto->mfr_desc);
1247 free(ofproto->hw_desc);
1248 free(ofproto->sw_desc);
1249 free(ofproto->serial_desc);
1250 free(ofproto->dp_desc);
1251 hmap_destroy(&ofproto->ports);
1252 hmap_destroy(&ofproto->ofport_usage);
1253 shash_destroy(&ofproto->port_by_name);
1254 simap_destroy(&ofproto->ofp_requests);
1256 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1257 oftable_destroy(table);
1259 free(ofproto->tables);
1261 hmap_destroy(&ofproto->deletions);
1263 free(ofproto->vlan_bitmap);
1265 ofproto->ofproto_class->dealloc(ofproto);
1269 ofproto_destroy(struct ofproto *p)
1270 OVS_EXCLUDED(ofproto_mutex)
1272 struct ofport *ofport, *next_ofport;
1273 struct ofport_usage *usage, *next_usage;
1280 meter_delete(p, 1, p->meter_features.max_meters);
1281 p->meter_features.max_meters = 0;
1287 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1288 ofport_destroy(ofport);
1291 HMAP_FOR_EACH_SAFE (usage, next_usage, hmap_node, &p->ofport_usage) {
1292 hmap_remove(&p->ofport_usage, &usage->hmap_node);
1296 p->ofproto_class->destruct(p);
1297 ofproto_destroy__(p);
1300 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1301 * kernel datapath, for example, this destroys the datapath in the kernel, and
1302 * with the netdev-based datapath, it tears down the data structures that
1303 * represent the datapath.
1305 * The datapath should not be currently open as an ofproto. */
1307 ofproto_delete(const char *name, const char *type)
1309 const struct ofproto_class *class = ofproto_class_find__(type);
1310 return (!class ? EAFNOSUPPORT
1311 : !class->del ? EACCES
1312 : class->del(type, name));
1316 process_port_change(struct ofproto *ofproto, int error, char *devname)
1318 if (error == ENOBUFS) {
1319 reinit_ports(ofproto);
1320 } else if (!error) {
1321 update_port(ofproto, devname);
1327 ofproto_type_run(const char *datapath_type)
1329 const struct ofproto_class *class;
1332 datapath_type = ofproto_normalize_type(datapath_type);
1333 class = ofproto_class_find__(datapath_type);
1335 error = class->type_run ? class->type_run(datapath_type) : 0;
1336 if (error && error != EAGAIN) {
1337 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1338 datapath_type, ovs_strerror(error));
1344 ofproto_type_run_fast(const char *datapath_type)
1346 const struct ofproto_class *class;
1349 datapath_type = ofproto_normalize_type(datapath_type);
1350 class = ofproto_class_find__(datapath_type);
1352 error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1353 if (error && error != EAGAIN) {
1354 VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1355 datapath_type, ovs_strerror(error));
1361 ofproto_type_wait(const char *datapath_type)
1363 const struct ofproto_class *class;
1365 datapath_type = ofproto_normalize_type(datapath_type);
1366 class = ofproto_class_find__(datapath_type);
1368 if (class->type_wait) {
1369 class->type_wait(datapath_type);
1374 any_pending_ops(const struct ofproto *p)
1375 OVS_EXCLUDED(ofproto_mutex)
1379 ovs_mutex_lock(&ofproto_mutex);
1380 b = !list_is_empty(&p->pending);
1381 ovs_mutex_unlock(&ofproto_mutex);
1387 ofproto_run(struct ofproto *p)
1389 struct sset changed_netdevs;
1390 const char *changed_netdev;
1391 struct ofport *ofport;
1394 error = p->ofproto_class->run(p);
1395 if (error && error != EAGAIN) {
1396 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1399 run_rule_executes(p);
1401 /* Restore the eviction group heap invariant occasionally. */
1402 if (p->eviction_group_timer < time_msec()) {
1405 p->eviction_group_timer = time_msec() + 1000;
1407 for (i = 0; i < p->n_tables; i++) {
1408 struct oftable *table = &p->tables[i];
1409 struct eviction_group *evg;
1410 struct cls_cursor cursor;
1413 if (!table->eviction_fields) {
1417 ovs_mutex_lock(&ofproto_mutex);
1418 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1419 heap_rebuild(&evg->rules);
1422 ovs_rwlock_rdlock(&table->cls.rwlock);
1423 cls_cursor_init(&cursor, &table->cls, NULL);
1424 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1425 if (!rule->eviction_group
1426 && (rule->idle_timeout || rule->hard_timeout)) {
1427 eviction_group_add_rule(rule);
1430 ovs_rwlock_unlock(&table->cls.rwlock);
1431 ovs_mutex_unlock(&ofproto_mutex);
1435 if (p->ofproto_class->port_poll) {
1438 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1439 process_port_change(p, error, devname);
1443 /* Update OpenFlow port status for any port whose netdev has changed.
1445 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1446 * destroyed, so it's not safe to update ports directly from the
1447 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1448 * need this two-phase approach. */
1449 sset_init(&changed_netdevs);
1450 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1451 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1452 if (ofport->change_seq != change_seq) {
1453 ofport->change_seq = change_seq;
1454 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1457 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1458 update_port(p, changed_netdev);
1460 sset_destroy(&changed_netdevs);
1464 connmgr_run(p->connmgr, handle_openflow);
1468 connmgr_run(p->connmgr, NULL);
1470 if (!any_pending_ops(p)) {
1471 p->state = S_OPENFLOW;
1476 connmgr_run(p->connmgr, NULL);
1478 if (!any_pending_ops(p)) {
1479 connmgr_flushed(p->connmgr);
1480 p->state = S_OPENFLOW;
1488 if (time_msec() >= p->next_op_report) {
1489 long long int ago = (time_msec() - p->first_op) / 1000;
1490 long long int interval = (p->last_op - p->first_op) / 1000;
1494 ds_put_format(&s, "%d flow_mods ",
1495 p->n_add + p->n_delete + p->n_modify);
1496 if (interval == ago) {
1497 ds_put_format(&s, "in the last %lld s", ago);
1498 } else if (interval) {
1499 ds_put_format(&s, "in the %lld s starting %lld s ago",
1502 ds_put_format(&s, "%lld s ago", ago);
1505 ds_put_cstr(&s, " (");
1507 ds_put_format(&s, "%d adds, ", p->n_add);
1510 ds_put_format(&s, "%d deletes, ", p->n_delete);
1513 ds_put_format(&s, "%d modifications, ", p->n_modify);
1516 ds_put_char(&s, ')');
1518 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1521 p->n_add = p->n_delete = p->n_modify = 0;
1522 p->next_op_report = LLONG_MAX;
1528 /* Performs periodic activity required by 'ofproto' that needs to be done
1529 * with the least possible latency.
1531 * It makes sense to call this function a couple of times per poll loop, to
1532 * provide a significant performance boost on some benchmarks with the
1533 * ofproto-dpif implementation. */
1535 ofproto_run_fast(struct ofproto *p)
1539 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1540 if (error && error != EAGAIN) {
1541 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1542 p->name, ovs_strerror(error));
1548 ofproto_wait(struct ofproto *p)
1550 struct ofport *ofport;
1552 p->ofproto_class->wait(p);
1553 if (p->ofproto_class->port_poll_wait) {
1554 p->ofproto_class->port_poll_wait(p);
1557 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1558 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1559 poll_immediate_wake();
1565 connmgr_wait(p->connmgr, true);
1570 connmgr_wait(p->connmgr, false);
1571 if (!any_pending_ops(p)) {
1572 poll_immediate_wake();
1579 ofproto_is_alive(const struct ofproto *p)
1581 return connmgr_has_controllers(p->connmgr);
1584 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1585 * memory_report(). */
1587 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1589 const struct oftable *table;
1590 unsigned int n_rules;
1592 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1594 ovs_mutex_lock(&ofproto_mutex);
1595 simap_increase(usage, "ops",
1596 ofproto->n_pending + hmap_count(&ofproto->deletions));
1597 ovs_mutex_unlock(&ofproto_mutex);
1600 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1601 ovs_rwlock_rdlock(&table->cls.rwlock);
1602 n_rules += classifier_count(&table->cls);
1603 ovs_rwlock_unlock(&table->cls.rwlock);
1605 simap_increase(usage, "rules", n_rules);
1607 if (ofproto->ofproto_class->get_memory_usage) {
1608 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1611 connmgr_get_memory_usage(ofproto->connmgr, usage);
1615 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1618 connmgr_get_controller_info(ofproto->connmgr, info);
1622 ofproto_free_ofproto_controller_info(struct shash *info)
1624 connmgr_free_controller_info(info);
1627 /* Makes a deep copy of 'old' into 'port'. */
1629 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1631 port->name = xstrdup(old->name);
1632 port->type = xstrdup(old->type);
1633 port->ofp_port = old->ofp_port;
1636 /* Frees memory allocated to members of 'ofproto_port'.
1638 * Do not call this function on an ofproto_port obtained from
1639 * ofproto_port_dump_next(): that function retains ownership of the data in the
1642 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1644 free(ofproto_port->name);
1645 free(ofproto_port->type);
1648 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1650 * This function provides no status indication. An error status for the entire
1651 * dump operation is provided when it is completed by calling
1652 * ofproto_port_dump_done().
1655 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1656 const struct ofproto *ofproto)
1658 dump->ofproto = ofproto;
1659 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1663 /* Attempts to retrieve another port from 'dump', which must have been created
1664 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1665 * 'port' and returns true. On failure, returns false.
1667 * Failure might indicate an actual error or merely that the last port has been
1668 * dumped. An error status for the entire dump operation is provided when it
1669 * is completed by calling ofproto_port_dump_done().
1671 * The ofproto owns the data stored in 'port'. It will remain valid until at
1672 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1673 * ofproto_port_dump_done(). */
1675 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1676 struct ofproto_port *port)
1678 const struct ofproto *ofproto = dump->ofproto;
1684 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1687 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1693 /* Completes port table dump operation 'dump', which must have been created
1694 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1695 * error-free, otherwise a positive errno value describing the problem. */
1697 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1699 const struct ofproto *ofproto = dump->ofproto;
1701 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1704 return dump->error == EOF ? 0 : dump->error;
1707 /* Returns the type to pass to netdev_open() when a datapath of type
1708 * 'datapath_type' has a port of type 'port_type', for a few special
1709 * cases when a netdev type differs from a port type. For example, when
1710 * using the userspace datapath, a port of type "internal" needs to be
1713 * Returns either 'type' itself or a string literal, which must not be
1716 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1718 const struct ofproto_class *class;
1720 datapath_type = ofproto_normalize_type(datapath_type);
1721 class = ofproto_class_find__(datapath_type);
1726 return (class->port_open_type
1727 ? class->port_open_type(datapath_type, port_type)
1731 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1732 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1733 * the port's OpenFlow port number.
1735 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1736 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1737 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1738 * 'ofp_portp' is non-null). */
1740 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1741 ofp_port_t *ofp_portp)
1743 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1746 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1748 const char *netdev_name = netdev_get_name(netdev);
1750 simap_put(&ofproto->ofp_requests, netdev_name,
1751 ofp_to_u16(ofp_port));
1752 update_port(ofproto, netdev_name);
1755 struct ofproto_port ofproto_port;
1757 ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1759 *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1760 ofproto_port_destroy(&ofproto_port);
1765 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1766 * initializes '*port' appropriately; on failure, returns a positive errno
1769 * The caller owns the data in 'ofproto_port' and must free it with
1770 * ofproto_port_destroy() when it is no longer needed. */
1772 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1773 struct ofproto_port *port)
1777 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1779 memset(port, 0, sizeof *port);
1784 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1785 * Returns 0 if successful, otherwise a positive errno. */
1787 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1789 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1790 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1791 struct simap_node *ofp_request_node;
1794 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1795 if (ofp_request_node) {
1796 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1799 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1800 if (!error && ofport) {
1801 /* 'name' is the netdev's name and update_port() is going to close the
1802 * netdev. Just in case update_port() refers to 'name' after it
1803 * destroys 'ofport', make a copy of it around the update_port()
1805 char *devname = xstrdup(name);
1806 update_port(ofproto, devname);
1813 flow_mod_init(struct ofputil_flow_mod *fm,
1814 const struct match *match, unsigned int priority,
1815 const struct ofpact *ofpacts, size_t ofpacts_len,
1816 enum ofp_flow_mod_command command)
1818 memset(fm, 0, sizeof *fm);
1820 fm->priority = priority;
1823 fm->modify_cookie = false;
1825 fm->command = command;
1826 fm->idle_timeout = 0;
1827 fm->hard_timeout = 0;
1828 fm->buffer_id = UINT32_MAX;
1829 fm->out_port = OFPP_ANY;
1830 fm->out_group = OFPG_ANY;
1832 fm->ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1833 fm->ofpacts_len = ofpacts_len;
1837 simple_flow_mod(struct ofproto *ofproto,
1838 const struct match *match, unsigned int priority,
1839 const struct ofpact *ofpacts, size_t ofpacts_len,
1840 enum ofp_flow_mod_command command)
1842 struct ofputil_flow_mod fm;
1844 flow_mod_init(&fm, match, priority, ofpacts, ofpacts_len, command);
1846 return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1849 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1850 * performs the 'n_actions' actions in 'actions'. The new flow will not
1853 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1854 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1855 * controllers; otherwise, it will be hidden.
1857 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1859 * This is a helper function for in-band control and fail-open. */
1861 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1862 unsigned int priority,
1863 const struct ofpact *ofpacts, size_t ofpacts_len)
1864 OVS_EXCLUDED(ofproto_mutex)
1866 const struct rule *rule;
1869 /* First do a cheap check whether the rule we're looking for already exists
1870 * with the actions that we want. If it does, then we're done. */
1871 ovs_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1872 rule = rule_from_cls_rule(classifier_find_match_exactly(
1873 &ofproto->tables[0].cls, match, priority));
1875 ovs_mutex_lock(&rule->mutex);
1876 must_add = !ofpacts_equal(rule->actions->ofpacts,
1877 rule->actions->ofpacts_len,
1878 ofpacts, ofpacts_len);
1879 ovs_mutex_unlock(&rule->mutex);
1883 ovs_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1885 /* If there's no such rule or the rule doesn't have the actions we want,
1886 * fall back to a executing a full flow mod. We can't optimize this at
1887 * all because we didn't take enough locks above to ensure that the flow
1888 * table didn't already change beneath us. */
1890 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1891 OFPFC_MODIFY_STRICT);
1895 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1896 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1897 * operation cannot be initiated now but may be retried later.
1899 * This is a helper function for in-band control and fail-open and the "learn"
1902 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1903 OVS_EXCLUDED(ofproto_mutex)
1905 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1908 /* Searches for a rule with matching criteria exactly equal to 'target' in
1909 * ofproto's table 0 and, if it finds one, deletes it.
1911 * This is a helper function for in-band control and fail-open. */
1913 ofproto_delete_flow(struct ofproto *ofproto,
1914 const struct match *target, unsigned int priority)
1915 OVS_EXCLUDED(ofproto_mutex)
1917 struct classifier *cls = &ofproto->tables[0].cls;
1920 /* First do a cheap check whether the rule we're looking for has already
1921 * been deleted. If so, then we're done. */
1922 ovs_rwlock_rdlock(&cls->rwlock);
1923 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1925 ovs_rwlock_unlock(&cls->rwlock);
1930 /* Fall back to a executing a full flow mod. We can't optimize this at all
1931 * because we didn't take enough locks above to ensure that the flow table
1932 * didn't already change beneath us. */
1933 return simple_flow_mod(ofproto, target, priority, NULL, 0,
1934 OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
1937 /* Starts the process of deleting all of the flows from all of ofproto's flow
1938 * tables and then reintroducing the flows required by in-band control and
1939 * fail-open. The process will complete in a later call to ofproto_run(). */
1941 ofproto_flush_flows(struct ofproto *ofproto)
1943 COVERAGE_INC(ofproto_flush);
1944 ofproto->state = S_FLUSH;
1948 reinit_ports(struct ofproto *p)
1950 struct ofproto_port_dump dump;
1951 struct sset devnames;
1952 struct ofport *ofport;
1953 struct ofproto_port ofproto_port;
1954 const char *devname;
1956 COVERAGE_INC(ofproto_reinit_ports);
1958 sset_init(&devnames);
1959 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1960 sset_add(&devnames, netdev_get_name(ofport->netdev));
1962 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1963 sset_add(&devnames, ofproto_port.name);
1966 SSET_FOR_EACH (devname, &devnames) {
1967 update_port(p, devname);
1969 sset_destroy(&devnames);
1973 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1977 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1978 port_idx = port_idx ? port_idx : UINT16_MAX;
1980 if (port_idx >= ofproto->max_ports
1981 || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
1982 uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
1983 long long int last_used_at, lru = LLONG_MAX;
1985 /* Search for a free OpenFlow port number. We try not to
1986 * immediately reuse them to prevent problems due to old
1989 if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1990 ofproto->alloc_port_no = 1;
1992 last_used_at = ofport_get_usage(ofproto,
1993 u16_to_ofp(ofproto->alloc_port_no));
1994 if (!last_used_at) {
1995 port_idx = ofproto->alloc_port_no;
1997 } else if ( last_used_at < time_msec() - 60*60*1000) {
1998 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
1999 * more than an hour ago, consider it usable. */
2000 ofport_remove_usage(ofproto,
2001 u16_to_ofp(ofproto->alloc_port_no));
2002 port_idx = ofproto->alloc_port_no;
2004 } else if (last_used_at < lru) {
2006 lru_ofport = ofproto->alloc_port_no;
2009 if (ofproto->alloc_port_no == end_port_no) {
2011 port_idx = lru_ofport;
2018 ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
2019 return u16_to_ofp(port_idx);
2023 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2025 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2026 ofport_set_usage(ofproto, ofp_port, time_msec());
2030 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2031 * pointer if the netdev cannot be opened. On success, also fills in
2033 static struct netdev *
2034 ofport_open(struct ofproto *ofproto,
2035 struct ofproto_port *ofproto_port,
2036 struct ofputil_phy_port *pp)
2038 enum netdev_flags flags;
2039 struct netdev *netdev;
2042 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2044 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
2045 "cannot be opened (%s)",
2047 ofproto_port->name, ofproto_port->ofp_port,
2048 ofproto_port->name, ovs_strerror(error));
2052 if (ofproto_port->ofp_port == OFPP_NONE) {
2053 if (!strcmp(ofproto->name, ofproto_port->name)) {
2054 ofproto_port->ofp_port = OFPP_LOCAL;
2056 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2057 ofproto_port->name);
2060 pp->port_no = ofproto_port->ofp_port;
2061 netdev_get_etheraddr(netdev, pp->hw_addr);
2062 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2063 netdev_get_flags(netdev, &flags);
2064 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2065 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2066 netdev_get_features(netdev, &pp->curr, &pp->advertised,
2067 &pp->supported, &pp->peer);
2068 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2069 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2074 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
2075 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
2078 ofport_equal(const struct ofputil_phy_port *a,
2079 const struct ofputil_phy_port *b)
2081 return (eth_addr_equals(a->hw_addr, b->hw_addr)
2082 && a->state == b->state
2083 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2084 && a->curr == b->curr
2085 && a->advertised == b->advertised
2086 && a->supported == b->supported
2087 && a->peer == b->peer
2088 && a->curr_speed == b->curr_speed
2089 && a->max_speed == b->max_speed);
2092 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2093 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2094 * one with the same name or port number). */
2096 ofport_install(struct ofproto *p,
2097 struct netdev *netdev, const struct ofputil_phy_port *pp)
2099 const char *netdev_name = netdev_get_name(netdev);
2100 struct ofport *ofport;
2103 /* Create ofport. */
2104 ofport = p->ofproto_class->port_alloc();
2109 ofport->ofproto = p;
2110 ofport->netdev = netdev;
2111 ofport->change_seq = netdev_change_seq(netdev);
2113 ofport->ofp_port = pp->port_no;
2114 ofport->created = time_msec();
2116 /* Add port to 'p'. */
2117 hmap_insert(&p->ports, &ofport->hmap_node,
2118 hash_ofp_port(ofport->ofp_port));
2119 shash_add(&p->port_by_name, netdev_name, ofport);
2121 update_mtu(p, ofport);
2123 /* Let the ofproto_class initialize its private data. */
2124 error = p->ofproto_class->port_construct(ofport);
2128 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
2132 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2133 p->name, netdev_name, ovs_strerror(error));
2135 ofport_destroy__(ofport);
2137 netdev_close(netdev);
2141 /* Removes 'ofport' from 'p' and destroys it. */
2143 ofport_remove(struct ofport *ofport)
2145 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
2147 ofport_destroy(ofport);
2150 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2153 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2155 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2157 ofport_remove(port);
2161 /* Updates 'port' with new 'pp' description.
2163 * Does not handle a name or port number change. The caller must implement
2164 * such a change as a delete followed by an add. */
2166 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2168 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2169 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2170 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2171 port->pp.state = pp->state;
2172 port->pp.curr = pp->curr;
2173 port->pp.advertised = pp->advertised;
2174 port->pp.supported = pp->supported;
2175 port->pp.peer = pp->peer;
2176 port->pp.curr_speed = pp->curr_speed;
2177 port->pp.max_speed = pp->max_speed;
2179 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
2182 /* Update OpenFlow 'state' in 'port' and notify controller. */
2184 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2186 if (port->pp.state != state) {
2187 port->pp.state = state;
2188 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
2194 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2196 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2198 if (port->ofproto->ofproto_class->set_realdev) {
2199 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2201 if (port->ofproto->ofproto_class->set_stp_port) {
2202 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2204 if (port->ofproto->ofproto_class->set_cfm) {
2205 port->ofproto->ofproto_class->set_cfm(port, NULL);
2207 if (port->ofproto->ofproto_class->bundle_remove) {
2208 port->ofproto->ofproto_class->bundle_remove(port);
2214 ofport_destroy__(struct ofport *port)
2216 struct ofproto *ofproto = port->ofproto;
2217 const char *name = netdev_get_name(port->netdev);
2219 hmap_remove(&ofproto->ports, &port->hmap_node);
2220 shash_delete(&ofproto->port_by_name,
2221 shash_find(&ofproto->port_by_name, name));
2223 netdev_close(port->netdev);
2224 ofproto->ofproto_class->port_dealloc(port);
2228 ofport_destroy(struct ofport *port)
2231 dealloc_ofp_port(port->ofproto, port->ofp_port);
2232 port->ofproto->ofproto_class->port_destruct(port);
2233 ofport_destroy__(port);
2238 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2240 struct ofport *port;
2242 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2244 if (port->ofp_port == ofp_port) {
2251 static long long int
2252 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2254 struct ofport_usage *usage;
2256 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2257 &ofproto->ofport_usage) {
2258 if (usage->ofp_port == ofp_port) {
2259 return usage->last_used;
2266 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2267 long long int last_used)
2269 struct ofport_usage *usage;
2270 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2271 &ofproto->ofport_usage) {
2272 if (usage->ofp_port == ofp_port) {
2273 usage->last_used = last_used;
2277 ovs_assert(last_used == LLONG_MAX);
2279 usage = xmalloc(sizeof *usage);
2280 usage->ofp_port = ofp_port;
2281 usage->last_used = last_used;
2282 hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2283 hash_ofp_port(ofp_port));
2287 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2289 struct ofport_usage *usage;
2290 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2291 &ofproto->ofport_usage) {
2292 if (usage->ofp_port == ofp_port) {
2293 hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2301 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2303 struct ofproto *ofproto = port->ofproto;
2306 if (ofproto->ofproto_class->port_get_stats) {
2307 error = ofproto->ofproto_class->port_get_stats(port, stats);
2316 update_port(struct ofproto *ofproto, const char *name)
2318 struct ofproto_port ofproto_port;
2319 struct ofputil_phy_port pp;
2320 struct netdev *netdev;
2321 struct ofport *port;
2323 COVERAGE_INC(ofproto_update_port);
2325 /* Fetch 'name''s location and properties from the datapath. */
2326 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2327 ? ofport_open(ofproto, &ofproto_port, &pp)
2331 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2332 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2333 struct netdev *old_netdev = port->netdev;
2335 /* 'name' hasn't changed location. Any properties changed? */
2336 if (!ofport_equal(&port->pp, &pp)) {
2337 ofport_modified(port, &pp);
2340 update_mtu(ofproto, port);
2342 /* Install the newly opened netdev in case it has changed.
2343 * Don't close the old netdev yet in case port_modified has to
2344 * remove a retained reference to it.*/
2345 port->netdev = netdev;
2346 port->change_seq = netdev_change_seq(netdev);
2348 if (port->ofproto->ofproto_class->port_modified) {
2349 port->ofproto->ofproto_class->port_modified(port);
2352 netdev_close(old_netdev);
2354 /* If 'port' is nonnull then its name differs from 'name' and thus
2355 * we should delete it. If we think there's a port named 'name'
2356 * then its port number must be wrong now so delete it too. */
2358 ofport_remove(port);
2360 ofport_remove_with_name(ofproto, name);
2361 ofport_install(ofproto, netdev, &pp);
2364 /* Any port named 'name' is gone now. */
2365 ofport_remove_with_name(ofproto, name);
2367 ofproto_port_destroy(&ofproto_port);
2371 init_ports(struct ofproto *p)
2373 struct ofproto_port_dump dump;
2374 struct ofproto_port ofproto_port;
2375 struct shash_node *node, *next;
2377 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2378 const char *name = ofproto_port.name;
2380 if (shash_find(&p->port_by_name, name)) {
2381 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2384 struct ofputil_phy_port pp;
2385 struct netdev *netdev;
2387 /* Check if an OpenFlow port number had been requested. */
2388 node = shash_find(&init_ofp_ports, name);
2390 const struct iface_hint *iface_hint = node->data;
2391 simap_put(&p->ofp_requests, name,
2392 ofp_to_u16(iface_hint->ofp_port));
2395 netdev = ofport_open(p, &ofproto_port, &pp);
2397 ofport_install(p, netdev, &pp);
2398 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2399 p->alloc_port_no = MAX(p->alloc_port_no,
2400 ofp_to_u16(ofproto_port.ofp_port));
2406 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2407 struct iface_hint *iface_hint = node->data;
2409 if (!strcmp(iface_hint->br_name, p->name)) {
2410 free(iface_hint->br_name);
2411 free(iface_hint->br_type);
2413 shash_delete(&init_ofp_ports, node);
2420 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2421 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2423 find_min_mtu(struct ofproto *p)
2425 struct ofport *ofport;
2428 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2429 struct netdev *netdev = ofport->netdev;
2432 /* Skip any internal ports, since that's what we're trying to
2434 if (!strcmp(netdev_get_type(netdev), "internal")) {
2438 if (netdev_get_mtu(netdev, &dev_mtu)) {
2441 if (!mtu || dev_mtu < mtu) {
2446 return mtu ? mtu: ETH_PAYLOAD_MAX;
2449 /* Update MTU of all datapath devices on 'p' to the minimum of the
2450 * non-datapath ports in event of 'port' added or changed. */
2452 update_mtu(struct ofproto *p, struct ofport *port)
2454 struct ofport *ofport;
2455 struct netdev *netdev = port->netdev;
2456 int dev_mtu, old_min;
2458 if (netdev_get_mtu(netdev, &dev_mtu)) {
2462 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2463 if (dev_mtu > p->min_mtu) {
2464 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2465 dev_mtu = p->min_mtu;
2468 port->mtu = dev_mtu;
2472 /* For non-internal port find new min mtu. */
2473 old_min = p->min_mtu;
2474 port->mtu = dev_mtu;
2475 p->min_mtu = find_min_mtu(p);
2476 if (p->min_mtu == old_min) {
2480 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2481 struct netdev *netdev = ofport->netdev;
2483 if (!strcmp(netdev_get_type(netdev), "internal")) {
2484 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2485 ofport->mtu = p->min_mtu;
2492 ofproto_rule_ref(struct rule *rule)
2497 atomic_add(&rule->ref_count, 1, &orig);
2498 ovs_assert(orig != 0);
2503 ofproto_rule_unref(struct rule *rule)
2508 atomic_sub(&rule->ref_count, 1, &orig);
2510 rule->ofproto->ofproto_class->rule_destruct(rule);
2511 ofproto_rule_destroy__(rule);
2513 ovs_assert(orig != 0);
2518 struct rule_actions *
2519 rule_get_actions(const struct rule *rule)
2520 OVS_EXCLUDED(rule->mutex)
2522 struct rule_actions *actions;
2524 ovs_mutex_lock(&rule->mutex);
2525 actions = rule_get_actions__(rule);
2526 ovs_mutex_unlock(&rule->mutex);
2531 struct rule_actions *
2532 rule_get_actions__(const struct rule *rule)
2533 OVS_REQUIRES(rule->mutex)
2535 rule_actions_ref(rule->actions);
2536 return rule->actions;
2540 ofproto_rule_destroy__(struct rule *rule)
2541 OVS_NO_THREAD_SAFETY_ANALYSIS
2543 cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2544 rule_actions_unref(rule->actions);
2545 ovs_mutex_destroy(&rule->mutex);
2546 rule->ofproto->ofproto_class->rule_dealloc(rule);
2549 static uint32_t get_provider_meter_id(const struct ofproto *,
2550 uint32_t of_meter_id);
2552 /* Creates and returns a new 'struct rule_actions', with a ref_count of 1,
2553 * whose actions are a copy of from the 'ofpacts_len' bytes of 'ofpacts'. */
2554 struct rule_actions *
2555 rule_actions_create(const struct ofproto *ofproto,
2556 const struct ofpact *ofpacts, size_t ofpacts_len)
2558 struct rule_actions *actions;
2560 actions = xmalloc(sizeof *actions);
2561 atomic_init(&actions->ref_count, 1);
2562 actions->ofpacts = xmemdup(ofpacts, ofpacts_len);
2563 actions->ofpacts_len = ofpacts_len;
2564 actions->provider_meter_id
2565 = get_provider_meter_id(ofproto,
2566 ofpacts_get_meter(ofpacts, ofpacts_len));
2571 /* Increments 'actions''s ref_count. */
2573 rule_actions_ref(struct rule_actions *actions)
2578 atomic_add(&actions->ref_count, 1, &orig);
2579 ovs_assert(orig != 0);
2583 /* Decrements 'actions''s ref_count and frees 'actions' if the ref_count
2586 rule_actions_unref(struct rule_actions *actions)
2591 atomic_sub(&actions->ref_count, 1, &orig);
2593 free(actions->ofpacts);
2596 ovs_assert(orig != 0);
2601 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2602 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2604 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2605 OVS_REQUIRES(ofproto_mutex)
2607 return (port == OFPP_ANY
2608 || ofpacts_output_to_port(rule->actions->ofpacts,
2609 rule->actions->ofpacts_len, port));
2612 /* Returns true if 'rule' has group and equals group_id. */
2614 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
2615 OVS_REQUIRES(ofproto_mutex)
2617 return (group_id == OFPG11_ANY
2618 || ofpacts_output_to_group(rule->actions->ofpacts,
2619 rule->actions->ofpacts_len, group_id));
2622 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2623 * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2625 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2626 OVS_REQUIRES(ofproto_mutex)
2628 if (ofproto_rule_has_out_port(op->rule, out_port)) {
2633 case OFOPERATION_ADD:
2634 case OFOPERATION_DELETE:
2637 case OFOPERATION_MODIFY:
2638 case OFOPERATION_REPLACE:
2639 return ofpacts_output_to_port(op->actions->ofpacts,
2640 op->actions->ofpacts_len, out_port);
2647 rule_execute_destroy(struct rule_execute *e)
2649 ofproto_rule_unref(e->rule);
2650 list_remove(&e->list_node);
2654 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2655 * by passing them to the ofproto provider. */
2657 run_rule_executes(struct ofproto *ofproto)
2658 OVS_EXCLUDED(ofproto_mutex)
2660 struct rule_execute *e, *next;
2661 struct list executes;
2663 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2664 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2665 union flow_in_port in_port_;
2668 in_port_.ofp_port = e->in_port;
2669 flow_extract(e->packet, 0, 0, NULL, &in_port_, &flow);
2670 ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2672 rule_execute_destroy(e);
2676 /* Destroys and discards all "rule_execute" operations queued up in
2677 * ofproto->rule_executes. */
2679 destroy_rule_executes(struct ofproto *ofproto)
2681 struct rule_execute *e, *next;
2682 struct list executes;
2684 guarded_list_pop_all(&ofproto->rule_executes, &executes);
2685 LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2686 ofpbuf_delete(e->packet);
2687 rule_execute_destroy(e);
2691 /* Returns true if 'rule' should be hidden from the controller.
2693 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2694 * (e.g. by in-band control) and are intentionally hidden from the
2697 ofproto_rule_is_hidden(const struct rule *rule)
2699 return rule->cr.priority > UINT16_MAX;
2702 static enum oftable_flags
2703 rule_get_flags(const struct rule *rule)
2705 return rule->ofproto->tables[rule->table_id].flags;
2709 rule_is_modifiable(const struct rule *rule)
2711 return !(rule_get_flags(rule) & OFTABLE_READONLY);
2715 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2717 ofconn_send_reply(ofconn, make_echo_reply(oh));
2722 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2724 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2725 struct ofputil_switch_features features;
2726 struct ofport *port;
2732 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2734 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2736 /* Count only non-hidden tables in the number of tables. (Hidden tables,
2737 * if present, are always at the end.) */
2738 n_tables = ofproto->n_tables;
2739 for (i = 0; i < ofproto->n_tables; i++) {
2740 if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2746 features.datapath_id = ofproto->datapath_id;
2747 features.n_buffers = pktbuf_capacity();
2748 features.n_tables = n_tables;
2749 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2750 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2752 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2754 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2755 features.auxiliary_id = 0;
2756 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2758 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2759 ofputil_put_switch_features_port(&port->pp, b);
2762 ofconn_send_reply(ofconn, b);
2767 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2769 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2770 struct ofp_switch_config *osc;
2771 enum ofp_config_flags flags;
2775 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2776 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2777 flags = ofproto->frag_handling;
2778 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2779 if (oh->version < OFP13_VERSION
2780 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2781 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2783 osc->flags = htons(flags);
2784 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2785 ofconn_send_reply(ofconn, buf);
2791 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2793 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2794 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2795 uint16_t flags = ntohs(osc->flags);
2797 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2798 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2799 enum ofp_config_flags cur = ofproto->frag_handling;
2800 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2802 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2804 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2805 ofproto->frag_handling = next;
2807 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2809 ofputil_frag_handling_to_string(next));
2813 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2814 ofconn_set_invalid_ttl_to_controller(ofconn,
2815 (oh->version < OFP13_VERSION
2816 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2818 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2823 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2824 * error message code for the caller to propagate upward. Otherwise, returns
2827 * The log message mentions 'msg_type'. */
2829 reject_slave_controller(struct ofconn *ofconn)
2831 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2832 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2833 return OFPERR_OFPBRC_EPERM;
2839 /* Checks that the 'ofpacts_len' bytes of action in 'ofpacts' are appropriate
2842 * - If they use a meter, then 'ofproto' has that meter configured.
2844 * - If they use any groups, then 'ofproto' has that group configured.
2846 * Returns 0 if successful, otherwise an OpenFlow error. */
2848 ofproto_check_ofpacts(struct ofproto *ofproto,
2849 const struct ofpact ofpacts[], size_t ofpacts_len)
2851 const struct ofpact *a;
2854 mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2855 if (mid && get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2856 return OFPERR_OFPMMFC_INVALID_METER;
2859 OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
2860 if (a->type == OFPACT_GROUP
2861 && !ofproto_group_exists(ofproto, ofpact_get_GROUP(a)->group_id)) {
2862 return OFPERR_OFPBAC_BAD_OUT_GROUP;
2870 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2872 struct ofproto *p = ofconn_get_ofproto(ofconn);
2873 struct ofputil_packet_out po;
2874 struct ofpbuf *payload;
2875 uint64_t ofpacts_stub[1024 / 8];
2876 struct ofpbuf ofpacts;
2878 union flow_in_port in_port_;
2881 COVERAGE_INC(ofproto_packet_out);
2883 error = reject_slave_controller(ofconn);
2888 /* Decode message. */
2889 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2890 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2892 goto exit_free_ofpacts;
2894 if (ofp_to_u16(po.in_port) >= p->max_ports
2895 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2896 error = OFPERR_OFPBRC_BAD_PORT;
2897 goto exit_free_ofpacts;
2902 if (po.buffer_id != UINT32_MAX) {
2903 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2904 if (error || !payload) {
2905 goto exit_free_ofpacts;
2908 /* Ensure that the L3 header is 32-bit aligned. */
2909 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2912 /* Verify actions against packet, then send packet if successful. */
2913 in_port_.ofp_port = po.in_port;
2914 flow_extract(payload, 0, 0, NULL, &in_port_, &flow);
2915 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len);
2917 error = p->ofproto_class->packet_out(p, payload, &flow,
2918 po.ofpacts, po.ofpacts_len);
2920 ofpbuf_delete(payload);
2923 ofpbuf_uninit(&ofpacts);
2929 update_port_config(struct ofport *port,
2930 enum ofputil_port_config config,
2931 enum ofputil_port_config mask)
2933 enum ofputil_port_config old_config = port->pp.config;
2934 enum ofputil_port_config toggle;
2936 toggle = (config ^ port->pp.config) & mask;
2937 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2938 if (config & OFPUTIL_PC_PORT_DOWN) {
2939 netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2941 netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2943 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2946 port->pp.config ^= toggle;
2947 if (port->pp.config != old_config) {
2948 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2953 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2955 struct ofproto *p = ofconn_get_ofproto(ofconn);
2956 struct ofputil_port_mod pm;
2957 struct ofport *port;
2960 error = reject_slave_controller(ofconn);
2965 error = ofputil_decode_port_mod(oh, &pm);
2970 port = ofproto_get_port(p, pm.port_no);
2972 return OFPERR_OFPPMFC_BAD_PORT;
2973 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2974 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2976 update_port_config(port, pm.config, pm.mask);
2978 netdev_set_advertisements(port->netdev, pm.advertise);
2985 handle_desc_stats_request(struct ofconn *ofconn,
2986 const struct ofp_header *request)
2988 static const char *default_mfr_desc = "Nicira, Inc.";
2989 static const char *default_hw_desc = "Open vSwitch";
2990 static const char *default_sw_desc = VERSION;
2991 static const char *default_serial_desc = "None";
2992 static const char *default_dp_desc = "None";
2994 struct ofproto *p = ofconn_get_ofproto(ofconn);
2995 struct ofp_desc_stats *ods;
2998 msg = ofpraw_alloc_stats_reply(request, 0);
2999 ods = ofpbuf_put_zeros(msg, sizeof *ods);
3000 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
3001 sizeof ods->mfr_desc);
3002 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
3003 sizeof ods->hw_desc);
3004 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
3005 sizeof ods->sw_desc);
3006 ovs_strlcpy(ods->serial_num,
3007 p->serial_desc ? p->serial_desc : default_serial_desc,
3008 sizeof ods->serial_num);
3009 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
3010 sizeof ods->dp_desc);
3011 ofconn_send_reply(ofconn, msg);
3017 handle_table_stats_request(struct ofconn *ofconn,
3018 const struct ofp_header *request)
3020 struct ofproto *p = ofconn_get_ofproto(ofconn);
3021 struct ofp12_table_stats *ots;
3026 /* Set up default values.
3028 * ofp12_table_stats is used as a generic structure as
3029 * it is able to hold all the fields for ofp10_table_stats
3030 * and ofp11_table_stats (and of course itself).
3032 ots = xcalloc(p->n_tables, sizeof *ots);
3033 for (i = 0; i < p->n_tables; i++) {
3034 ots[i].table_id = i;
3035 sprintf(ots[i].name, "table%zu", i);
3036 ots[i].match = htonll(OFPXMT13_MASK);
3037 ots[i].wildcards = htonll(OFPXMT13_MASK);
3038 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
3039 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
3040 ots[i].write_setfields = htonll(OFPXMT13_MASK);
3041 ots[i].apply_setfields = htonll(OFPXMT13_MASK);
3042 ots[i].metadata_match = OVS_BE64_MAX;
3043 ots[i].metadata_write = OVS_BE64_MAX;
3044 ots[i].instructions = htonl(OFPIT11_ALL);
3045 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
3046 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
3047 ovs_rwlock_rdlock(&p->tables[i].cls.rwlock);
3048 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
3049 ovs_rwlock_unlock(&p->tables[i].cls.rwlock);
3052 p->ofproto_class->get_tables(p, ots);
3054 /* Post-process the tables, dropping hidden tables. */
3055 n_tables = p->n_tables;
3056 for (i = 0; i < p->n_tables; i++) {
3057 const struct oftable *table = &p->tables[i];
3059 if (table->flags & OFTABLE_HIDDEN) {
3065 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
3068 if (table->max_flows < ntohl(ots[i].max_entries)) {
3069 ots[i].max_entries = htonl(table->max_flows);
3073 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
3074 ofconn_send_reply(ofconn, msg);
3082 append_port_stat(struct ofport *port, struct list *replies)
3084 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3086 calc_duration(port->created, time_msec(),
3087 &ops.duration_sec, &ops.duration_nsec);
3089 /* Intentionally ignore return value, since errors will set
3090 * 'stats' to all-1s, which is correct for OpenFlow, and
3091 * netdev_get_stats() will log errors. */
3092 ofproto_port_get_stats(port, &ops.stats);
3094 ofputil_append_port_stat(replies, &ops);
3098 handle_port_stats_request(struct ofconn *ofconn,
3099 const struct ofp_header *request)
3101 struct ofproto *p = ofconn_get_ofproto(ofconn);
3102 struct ofport *port;
3103 struct list replies;
3107 error = ofputil_decode_port_stats_request(request, &port_no);
3112 ofpmp_init(&replies, request);
3113 if (port_no != OFPP_ANY) {
3114 port = ofproto_get_port(p, port_no);
3116 append_port_stat(port, &replies);
3119 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3120 append_port_stat(port, &replies);
3124 ofconn_send_replies(ofconn, &replies);
3129 handle_port_desc_stats_request(struct ofconn *ofconn,
3130 const struct ofp_header *request)
3132 struct ofproto *p = ofconn_get_ofproto(ofconn);
3133 enum ofp_version version;
3134 struct ofport *port;
3135 struct list replies;
3137 ofpmp_init(&replies, request);
3139 version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
3140 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3141 ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
3144 ofconn_send_replies(ofconn, &replies);
3149 hash_cookie(ovs_be64 cookie)
3151 return hash_2words((OVS_FORCE uint64_t)cookie >> 32,
3152 (OVS_FORCE uint64_t)cookie);
3156 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3157 OVS_REQUIRES(ofproto_mutex)
3159 hindex_insert(&ofproto->cookies, &rule->cookie_node,
3160 hash_cookie(rule->flow_cookie));
3164 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3165 OVS_REQUIRES(ofproto_mutex)
3167 hindex_remove(&ofproto->cookies, &rule->cookie_node);
3171 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
3172 ovs_be64 new_cookie)
3173 OVS_REQUIRES(ofproto_mutex)
3175 if (new_cookie != rule->flow_cookie) {
3176 cookies_remove(ofproto, rule);
3178 ovs_mutex_lock(&rule->mutex);
3179 rule->flow_cookie = new_cookie;
3180 ovs_mutex_unlock(&rule->mutex);
3182 cookies_insert(ofproto, rule);
3187 calc_duration(long long int start, long long int now,
3188 uint32_t *sec, uint32_t *nsec)
3190 long long int msecs = now - start;
3191 *sec = msecs / 1000;
3192 *nsec = (msecs % 1000) * (1000 * 1000);
3195 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
3196 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
3198 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3200 return (table_id == 0xff || table_id < ofproto->n_tables
3202 : OFPERR_OFPBRC_BAD_TABLE_ID);
3206 static struct oftable *
3207 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3209 struct oftable *table;
3211 for (table = &ofproto->tables[table_id];
3212 table < &ofproto->tables[ofproto->n_tables];
3214 if (!(table->flags & OFTABLE_HIDDEN)) {
3222 static struct oftable *
3223 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3225 if (table_id == 0xff) {
3226 return next_visible_table(ofproto, 0);
3227 } else if (table_id < ofproto->n_tables) {
3228 return &ofproto->tables[table_id];
3234 static struct oftable *
3235 next_matching_table(const struct ofproto *ofproto,
3236 const struct oftable *table, uint8_t table_id)
3238 return (table_id == 0xff
3239 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3243 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3245 * - If TABLE_ID is 0xff, this iterates over every classifier table in
3246 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3248 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3249 * only once, for that table. (This can be used to access tables marked
3252 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3253 * entered at all. (Perhaps you should have validated TABLE_ID with
3254 * check_table_id().)
3256 * All parameters are evaluated multiple times.
3258 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
3259 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
3261 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3263 /* Initializes 'criteria' in a straightforward way based on the other
3266 * For "loose" matching, the 'priority' parameter is unimportant and may be
3269 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3270 const struct match *match, unsigned int priority,
3271 ovs_be64 cookie, ovs_be64 cookie_mask,
3272 ofp_port_t out_port, uint32_t out_group)
3274 criteria->table_id = table_id;
3275 cls_rule_init(&criteria->cr, match, priority);
3276 criteria->cookie = cookie;
3277 criteria->cookie_mask = cookie_mask;
3278 criteria->out_port = out_port;
3279 criteria->out_group = out_group;
3283 rule_criteria_destroy(struct rule_criteria *criteria)
3285 cls_rule_destroy(&criteria->cr);
3289 rule_collection_init(struct rule_collection *rules)
3291 rules->rules = rules->stub;
3293 rules->capacity = ARRAY_SIZE(rules->stub);
3297 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3299 if (rules->n >= rules->capacity) {
3300 size_t old_size, new_size;
3302 old_size = rules->capacity * sizeof *rules->rules;
3303 rules->capacity *= 2;
3304 new_size = rules->capacity * sizeof *rules->rules;
3306 if (rules->rules == rules->stub) {
3307 rules->rules = xmalloc(new_size);
3308 memcpy(rules->rules, rules->stub, old_size);
3310 rules->rules = xrealloc(rules->rules, new_size);
3314 rules->rules[rules->n++] = rule;
3318 rule_collection_ref(struct rule_collection *rules)
3319 OVS_REQUIRES(ofproto_mutex)
3323 for (i = 0; i < rules->n; i++) {
3324 ofproto_rule_ref(rules->rules[i]);
3329 rule_collection_unref(struct rule_collection *rules)
3333 for (i = 0; i < rules->n; i++) {
3334 ofproto_rule_unref(rules->rules[i]);
3339 rule_collection_destroy(struct rule_collection *rules)
3341 if (rules->rules != rules->stub) {
3347 collect_rule(struct rule *rule, const struct rule_criteria *c,
3348 struct rule_collection *rules)
3349 OVS_REQUIRES(ofproto_mutex)
3351 /* We ordinarily want to skip hidden rules, but there has to be a way for
3352 * code internal to OVS to modify and delete them, so if the criteria
3353 * specify a priority that can only be for a hidden flow, then allow hidden
3354 * rules to be selected. (This doesn't allow OpenFlow clients to meddle
3355 * with hidden flows because OpenFlow uses only a 16-bit field to specify
3357 if (ofproto_rule_is_hidden(rule) && c->cr.priority <= UINT16_MAX) {
3359 } else if (rule->pending) {
3360 return OFPROTO_POSTPONE;
3362 if ((c->table_id == rule->table_id || c->table_id == 0xff)
3363 && ofproto_rule_has_out_port(rule, c->out_port)
3364 && ofproto_rule_has_out_group(rule, c->out_group)
3365 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3366 rule_collection_add(rules, rule);
3372 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3373 * on classifiers rules are done in the "loose" way required for OpenFlow
3374 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
3377 * Hidden rules are always omitted.
3379 * Returns 0 on success, otherwise an OpenFlow error code. */
3381 collect_rules_loose(struct ofproto *ofproto,
3382 const struct rule_criteria *criteria,
3383 struct rule_collection *rules)
3384 OVS_REQUIRES(ofproto_mutex)
3386 struct oftable *table;
3389 rule_collection_init(rules);
3391 error = check_table_id(ofproto, criteria->table_id);
3396 if (criteria->cookie_mask == OVS_BE64_MAX) {
3399 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3400 hash_cookie(criteria->cookie),
3401 &ofproto->cookies) {
3402 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3403 error = collect_rule(rule, criteria, rules);
3410 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3411 struct cls_cursor cursor;
3414 ovs_rwlock_rdlock(&table->cls.rwlock);
3415 cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3416 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3417 error = collect_rule(rule, criteria, rules);
3422 ovs_rwlock_unlock(&table->cls.rwlock);
3428 rule_collection_destroy(rules);
3433 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
3434 * on classifiers rules are done in the "strict" way required for OpenFlow
3435 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
3436 * rules on list 'rules'.
3438 * Hidden rules are always omitted.
3440 * Returns 0 on success, otherwise an OpenFlow error code. */
3442 collect_rules_strict(struct ofproto *ofproto,
3443 const struct rule_criteria *criteria,
3444 struct rule_collection *rules)
3445 OVS_REQUIRES(ofproto_mutex)
3447 struct oftable *table;
3450 rule_collection_init(rules);
3452 error = check_table_id(ofproto, criteria->table_id);
3457 if (criteria->cookie_mask == OVS_BE64_MAX) {
3460 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3461 hash_cookie(criteria->cookie),
3462 &ofproto->cookies) {
3463 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3464 error = collect_rule(rule, criteria, rules);
3471 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3474 ovs_rwlock_rdlock(&table->cls.rwlock);
3475 rule = rule_from_cls_rule(classifier_find_rule_exactly(
3476 &table->cls, &criteria->cr));
3477 ovs_rwlock_unlock(&table->cls.rwlock);
3479 error = collect_rule(rule, criteria, rules);
3489 rule_collection_destroy(rules);
3494 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3495 * forced into the range of a uint16_t. */
3497 age_secs(long long int age_ms)
3499 return (age_ms < 0 ? 0
3500 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3501 : (unsigned int) age_ms / 1000);
3505 handle_flow_stats_request(struct ofconn *ofconn,
3506 const struct ofp_header *request)
3507 OVS_EXCLUDED(ofproto_mutex)
3509 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3510 struct ofputil_flow_stats_request fsr;
3511 struct rule_criteria criteria;
3512 struct rule_collection rules;
3513 struct list replies;
3517 error = ofputil_decode_flow_stats_request(&fsr, request);
3522 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3523 fsr.cookie_mask, fsr.out_port, fsr.out_group);
3525 ovs_mutex_lock(&ofproto_mutex);
3526 error = collect_rules_loose(ofproto, &criteria, &rules);
3527 rule_criteria_destroy(&criteria);
3529 rule_collection_ref(&rules);
3531 ovs_mutex_unlock(&ofproto_mutex);
3537 ofpmp_init(&replies, request);
3538 for (i = 0; i < rules.n; i++) {
3539 struct rule *rule = rules.rules[i];
3540 long long int now = time_msec();
3541 struct ofputil_flow_stats fs;
3542 long long int created, used, modified;
3543 struct rule_actions *actions;
3544 enum ofputil_flow_mod_flags flags;
3546 ovs_mutex_lock(&rule->mutex);
3547 fs.cookie = rule->flow_cookie;
3548 fs.idle_timeout = rule->idle_timeout;
3549 fs.hard_timeout = rule->hard_timeout;
3550 created = rule->created;
3552 modified = rule->modified;
3553 actions = rule_get_actions__(rule);
3554 flags = rule->flags;
3555 ovs_mutex_unlock(&rule->mutex);
3557 minimatch_expand(&rule->cr.match, &fs.match);
3558 fs.table_id = rule->table_id;
3559 calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
3560 fs.priority = rule->cr.priority;
3561 fs.idle_age = age_secs(now - used);
3562 fs.hard_age = age_secs(now - modified);
3563 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3565 fs.ofpacts = actions->ofpacts;
3566 fs.ofpacts_len = actions->ofpacts_len;
3569 ofputil_append_flow_stats_reply(&fs, &replies);
3571 rule_actions_unref(actions);
3574 rule_collection_unref(&rules);
3575 rule_collection_destroy(&rules);
3577 ofconn_send_replies(ofconn, &replies);
3583 flow_stats_ds(struct rule *rule, struct ds *results)
3585 uint64_t packet_count, byte_count;
3586 struct rule_actions *actions;
3587 long long int created;
3589 rule->ofproto->ofproto_class->rule_get_stats(rule,
3590 &packet_count, &byte_count);
3592 ovs_mutex_lock(&rule->mutex);
3593 actions = rule_get_actions__(rule);
3594 created = rule->created;
3595 ovs_mutex_unlock(&rule->mutex);
3597 if (rule->table_id != 0) {
3598 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3600 ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
3601 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3602 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3603 cls_rule_format(&rule->cr, results);
3604 ds_put_char(results, ',');
3606 ds_put_cstr(results, "actions=");
3607 ofpacts_format(actions->ofpacts, actions->ofpacts_len, results);
3609 ds_put_cstr(results, "\n");
3611 rule_actions_unref(actions);
3614 /* Adds a pretty-printed description of all flows to 'results', including
3615 * hidden flows (e.g., set up by in-band control). */
3617 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3619 struct oftable *table;
3621 OFPROTO_FOR_EACH_TABLE (table, p) {
3622 struct cls_cursor cursor;
3625 ovs_rwlock_rdlock(&table->cls.rwlock);
3626 cls_cursor_init(&cursor, &table->cls, NULL);
3627 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3628 flow_stats_ds(rule, results);
3630 ovs_rwlock_unlock(&table->cls.rwlock);
3634 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3635 * '*engine_type' and '*engine_id', respectively. */
3637 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3638 uint8_t *engine_type, uint8_t *engine_id)
3640 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3643 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3644 * true if the port's CFM status was successfully stored into '*status'.
3645 * Returns false if the port did not have CFM configured, in which case
3646 * '*status' is indeterminate.
3648 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3650 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3651 struct ofproto_cfm_status *status)
3653 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3655 && ofproto->ofproto_class->get_cfm_status
3656 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3660 handle_aggregate_stats_request(struct ofconn *ofconn,
3661 const struct ofp_header *oh)
3662 OVS_EXCLUDED(ofproto_mutex)
3664 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3665 struct ofputil_flow_stats_request request;
3666 struct ofputil_aggregate_stats stats;
3667 bool unknown_packets, unknown_bytes;
3668 struct rule_criteria criteria;
3669 struct rule_collection rules;
3670 struct ofpbuf *reply;
3674 error = ofputil_decode_flow_stats_request(&request, oh);
3679 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3680 request.cookie, request.cookie_mask,
3681 request.out_port, request.out_group);
3683 ovs_mutex_lock(&ofproto_mutex);
3684 error = collect_rules_loose(ofproto, &criteria, &rules);
3685 rule_criteria_destroy(&criteria);
3687 rule_collection_ref(&rules);
3689 ovs_mutex_unlock(&ofproto_mutex);
3695 memset(&stats, 0, sizeof stats);
3696 unknown_packets = unknown_bytes = false;
3697 for (i = 0; i < rules.n; i++) {
3698 struct rule *rule = rules.rules[i];
3699 uint64_t packet_count;
3700 uint64_t byte_count;
3702 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3705 if (packet_count == UINT64_MAX) {
3706 unknown_packets = true;
3708 stats.packet_count += packet_count;
3711 if (byte_count == UINT64_MAX) {
3712 unknown_bytes = true;
3714 stats.byte_count += byte_count;
3719 if (unknown_packets) {
3720 stats.packet_count = UINT64_MAX;
3722 if (unknown_bytes) {
3723 stats.byte_count = UINT64_MAX;
3726 rule_collection_unref(&rules);
3727 rule_collection_destroy(&rules);
3729 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3730 ofconn_send_reply(ofconn, reply);
3735 struct queue_stats_cbdata {
3736 struct ofport *ofport;
3737 struct list replies;
3742 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3743 const struct netdev_queue_stats *stats)
3745 struct ofputil_queue_stats oqs;
3747 oqs.port_no = cbdata->ofport->pp.port_no;
3748 oqs.queue_id = queue_id;
3749 oqs.tx_bytes = stats->tx_bytes;
3750 oqs.tx_packets = stats->tx_packets;
3751 oqs.tx_errors = stats->tx_errors;
3752 if (stats->created != LLONG_MIN) {
3753 calc_duration(stats->created, cbdata->now,
3754 &oqs.duration_sec, &oqs.duration_nsec);
3756 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3758 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3762 handle_queue_stats_dump_cb(uint32_t queue_id,
3763 struct netdev_queue_stats *stats,
3766 struct queue_stats_cbdata *cbdata = cbdata_;
3768 put_queue_stats(cbdata, queue_id, stats);
3772 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3773 struct queue_stats_cbdata *cbdata)
3775 cbdata->ofport = port;
3776 if (queue_id == OFPQ_ALL) {
3777 netdev_dump_queue_stats(port->netdev,
3778 handle_queue_stats_dump_cb, cbdata);
3780 struct netdev_queue_stats stats;
3782 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3783 put_queue_stats(cbdata, queue_id, &stats);
3785 return OFPERR_OFPQOFC_BAD_QUEUE;
3792 handle_queue_stats_request(struct ofconn *ofconn,
3793 const struct ofp_header *rq)
3795 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3796 struct queue_stats_cbdata cbdata;
3797 struct ofport *port;
3799 struct ofputil_queue_stats_request oqsr;
3801 COVERAGE_INC(ofproto_queue_req);
3803 ofpmp_init(&cbdata.replies, rq);
3804 cbdata.now = time_msec();
3806 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3811 if (oqsr.port_no == OFPP_ANY) {
3812 error = OFPERR_OFPQOFC_BAD_QUEUE;
3813 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3814 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3819 port = ofproto_get_port(ofproto, oqsr.port_no);
3821 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3822 : OFPERR_OFPQOFC_BAD_PORT);
3825 ofconn_send_replies(ofconn, &cbdata.replies);
3827 ofpbuf_list_delete(&cbdata.replies);
3834 is_flow_deletion_pending(const struct ofproto *ofproto,
3835 const struct cls_rule *cls_rule,
3837 OVS_REQUIRES(ofproto_mutex)
3839 if (!hmap_is_empty(&ofproto->deletions)) {
3840 struct ofoperation *op;
3842 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3843 cls_rule_hash(cls_rule, table_id),
3844 &ofproto->deletions) {
3845 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3855 should_evict_a_rule(struct oftable *table, unsigned int extra_space)
3856 OVS_REQUIRES(ofproto_mutex)
3857 OVS_NO_THREAD_SAFETY_ANALYSIS
3859 return classifier_count(&table->cls) + extra_space > table->max_flows;
3863 evict_rules_from_table(struct ofproto *ofproto, struct oftable *table,
3864 unsigned int extra_space)
3865 OVS_REQUIRES(ofproto_mutex)
3867 while (should_evict_a_rule(table, extra_space)) {
3870 if (!choose_rule_to_evict(table, &rule)) {
3871 return OFPERR_OFPFMFC_TABLE_FULL;
3872 } else if (rule->pending) {
3873 return OFPROTO_POSTPONE;
3875 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
3876 delete_flow__(rule, group, OFPRR_EVICTION);
3877 ofopgroup_submit(group);
3884 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3885 * in which no matching flow already exists in the flow table.
3887 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3888 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3889 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3890 * initiated now but may be retried later.
3892 * The caller retains ownership of 'fm->ofpacts'.
3894 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3897 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3898 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3899 OVS_REQUIRES(ofproto_mutex)
3901 struct oftable *table;
3902 struct ofopgroup *group;
3908 error = check_table_id(ofproto, fm->table_id);
3914 if (fm->table_id == 0xff) {
3915 if (ofproto->ofproto_class->rule_choose_table) {
3916 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3922 ovs_assert(table_id < ofproto->n_tables);
3926 } else if (fm->table_id < ofproto->n_tables) {
3927 table_id = fm->table_id;
3929 return OFPERR_OFPBRC_BAD_TABLE_ID;
3932 table = &ofproto->tables[table_id];
3934 if (table->flags & OFTABLE_READONLY) {
3935 return OFPERR_OFPBRC_EPERM;
3938 cls_rule_init(&cr, &fm->match, fm->priority);
3940 /* Transform "add" into "modify" if there's an existing identical flow. */
3941 ovs_rwlock_rdlock(&table->cls.rwlock);
3942 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3943 ovs_rwlock_unlock(&table->cls.rwlock);
3945 cls_rule_destroy(&cr);
3946 if (!rule_is_modifiable(rule)) {
3947 return OFPERR_OFPBRC_EPERM;
3948 } else if (rule->pending) {
3949 return OFPROTO_POSTPONE;
3951 struct rule_collection rules;
3953 rule_collection_init(&rules);
3954 rule_collection_add(&rules, rule);
3955 fm->modify_cookie = true;
3956 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
3957 rule_collection_destroy(&rules);
3963 /* Serialize against pending deletion. */
3964 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3965 cls_rule_destroy(&cr);
3966 return OFPROTO_POSTPONE;
3969 /* Check for overlap, if requested. */
3970 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3973 ovs_rwlock_rdlock(&table->cls.rwlock);
3974 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3975 ovs_rwlock_unlock(&table->cls.rwlock);
3978 cls_rule_destroy(&cr);
3979 return OFPERR_OFPFMFC_OVERLAP;
3983 /* If necessary, evict an existing rule to clear out space. */
3984 error = evict_rules_from_table(ofproto, table, 1);
3986 cls_rule_destroy(&cr);
3990 /* Allocate new rule. */
3991 rule = ofproto->ofproto_class->rule_alloc();
3993 cls_rule_destroy(&cr);
3994 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3995 ofproto->name, ovs_strerror(error));
3999 /* Initialize base state. */
4000 *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
4001 cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), &cr);
4002 atomic_init(&rule->ref_count, 1);
4003 rule->pending = NULL;
4004 rule->flow_cookie = fm->new_cookie;
4005 rule->created = rule->modified = rule->used = time_msec();
4007 ovs_mutex_init(&rule->mutex);
4008 ovs_mutex_lock(&rule->mutex);
4009 rule->idle_timeout = fm->idle_timeout;
4010 rule->hard_timeout = fm->hard_timeout;
4011 ovs_mutex_unlock(&rule->mutex);
4013 *CONST_CAST(uint8_t *, &rule->table_id) = table - ofproto->tables;
4014 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4015 rule->actions = rule_actions_create(ofproto, fm->ofpacts, fm->ofpacts_len);
4016 list_init(&rule->meter_list_node);
4017 rule->eviction_group = NULL;
4018 list_init(&rule->expirable);
4019 rule->monitor_flags = 0;
4020 rule->add_seqno = 0;
4021 rule->modify_seqno = 0;
4023 /* Construct rule, initializing derived state. */
4024 error = ofproto->ofproto_class->rule_construct(rule);
4026 ofproto_rule_destroy__(rule);
4031 oftable_insert_rule(rule);
4033 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4034 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
4035 ofproto->ofproto_class->rule_insert(rule);
4036 ofopgroup_submit(group);
4041 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4043 /* Modifies the rules listed in 'rules', changing their actions to match those
4046 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4049 * Returns 0 on success, otherwise an OpenFlow error code. */
4051 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4052 struct ofputil_flow_mod *fm, const struct ofp_header *request,
4053 const struct rule_collection *rules)
4054 OVS_REQUIRES(ofproto_mutex)
4056 enum ofoperation_type type;
4057 struct ofopgroup *group;
4061 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
4062 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4063 error = OFPERR_OFPBRC_EPERM;
4064 for (i = 0; i < rules->n; i++) {
4065 struct rule *rule = rules->rules[i];
4066 struct ofoperation *op;
4067 bool actions_changed;
4068 bool reset_counters;
4070 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
4072 if (rule_is_modifiable(rule)) {
4073 /* At least one rule is modifiable, don't report EPERM error. */
4079 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4080 rule->actions->ofpacts,
4081 rule->actions->ofpacts_len);
4083 op = ofoperation_create(group, rule, type, 0);
4085 if (fm->modify_cookie && fm->new_cookie != OVS_BE64_MAX) {
4086 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
4088 if (type == OFOPERATION_REPLACE) {
4089 ovs_mutex_lock(&rule->mutex);
4090 rule->idle_timeout = fm->idle_timeout;
4091 rule->hard_timeout = fm->hard_timeout;
4092 ovs_mutex_unlock(&rule->mutex);
4094 rule->flags = fm->flags & OFPUTIL_FF_STATE;
4095 if (fm->idle_timeout || fm->hard_timeout) {
4096 if (!rule->eviction_group) {
4097 eviction_group_add_rule(rule);
4100 eviction_group_remove_rule(rule);
4104 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
4105 if (actions_changed || reset_counters) {
4106 struct rule_actions *new_actions;
4108 op->actions = rule->actions;
4109 new_actions = rule_actions_create(ofproto,
4110 fm->ofpacts, fm->ofpacts_len);
4112 ovs_mutex_lock(&rule->mutex);
4113 rule->actions = new_actions;
4114 ovs_mutex_unlock(&rule->mutex);
4116 rule->ofproto->ofproto_class->rule_modify_actions(rule,
4119 ofoperation_complete(op, 0);
4122 ofopgroup_submit(group);
4128 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
4129 struct ofputil_flow_mod *fm, const struct ofp_header *request)
4130 OVS_REQUIRES(ofproto_mutex)
4132 if (fm->cookie_mask != htonll(0) || fm->new_cookie == OVS_BE64_MAX) {
4135 return add_flow(ofproto, ofconn, fm, request);
4138 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
4141 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4144 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4145 struct ofputil_flow_mod *fm,
4146 const struct ofp_header *request)
4147 OVS_REQUIRES(ofproto_mutex)
4149 struct rule_criteria criteria;
4150 struct rule_collection rules;
4153 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4154 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4155 error = collect_rules_loose(ofproto, &criteria, &rules);
4156 rule_criteria_destroy(&criteria);
4159 error = (rules.n > 0
4160 ? modify_flows__(ofproto, ofconn, fm, request, &rules)
4161 : modify_flows_add(ofproto, ofconn, fm, request));
4164 rule_collection_destroy(&rules);
4169 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4172 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4175 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4176 struct ofputil_flow_mod *fm,
4177 const struct ofp_header *request)
4178 OVS_REQUIRES(ofproto_mutex)
4180 struct rule_criteria criteria;
4181 struct rule_collection rules;
4184 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4185 fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4186 error = collect_rules_strict(ofproto, &criteria, &rules);
4187 rule_criteria_destroy(&criteria);
4191 error = modify_flows_add(ofproto, ofconn, fm, request);
4192 } else if (rules.n == 1) {
4193 error = modify_flows__(ofproto, ofconn, fm, request, &rules);
4197 rule_collection_destroy(&rules);
4202 /* OFPFC_DELETE implementation. */
4205 delete_flow__(struct rule *rule, struct ofopgroup *group,
4206 enum ofp_flow_removed_reason reason)
4207 OVS_REQUIRES(ofproto_mutex)
4209 struct ofproto *ofproto = rule->ofproto;
4211 ofproto_rule_send_removed(rule, reason);
4213 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
4214 oftable_remove_rule(rule);
4215 ofproto->ofproto_class->rule_delete(rule);
4218 /* Deletes the rules listed in 'rules'.
4220 * Returns 0 on success, otherwise an OpenFlow error code. */
4222 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4223 const struct ofp_header *request,
4224 const struct rule_collection *rules,
4225 enum ofp_flow_removed_reason reason)
4226 OVS_REQUIRES(ofproto_mutex)
4228 struct ofopgroup *group;
4231 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
4232 for (i = 0; i < rules->n; i++) {
4233 delete_flow__(rules->rules[i], group, reason);
4235 ofopgroup_submit(group);
4240 /* Implements OFPFC_DELETE. */
4242 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4243 const struct ofputil_flow_mod *fm,
4244 const struct ofp_header *request)
4245 OVS_REQUIRES(ofproto_mutex)
4247 struct rule_criteria criteria;
4248 struct rule_collection rules;
4251 rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4252 fm->cookie, fm->cookie_mask,
4253 fm->out_port, fm->out_group);
4254 error = collect_rules_loose(ofproto, &criteria, &rules);
4255 rule_criteria_destroy(&criteria);
4257 if (!error && rules.n > 0) {
4258 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4260 rule_collection_destroy(&rules);
4265 /* Implements OFPFC_DELETE_STRICT. */
4267 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4268 const struct ofputil_flow_mod *fm,
4269 const struct ofp_header *request)
4270 OVS_REQUIRES(ofproto_mutex)
4272 struct rule_criteria criteria;
4273 struct rule_collection rules;
4276 rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4277 fm->cookie, fm->cookie_mask,
4278 fm->out_port, fm->out_group);
4279 error = collect_rules_strict(ofproto, &criteria, &rules);
4280 rule_criteria_destroy(&criteria);
4282 if (!error && rules.n > 0) {
4283 error = delete_flows__(ofproto, ofconn, request, &rules, OFPRR_DELETE);
4285 rule_collection_destroy(&rules);
4291 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4292 OVS_REQUIRES(ofproto_mutex)
4294 struct ofputil_flow_removed fr;
4296 if (ofproto_rule_is_hidden(rule) ||
4297 !(rule->flags & OFPUTIL_FF_SEND_FLOW_REM)) {
4301 minimatch_expand(&rule->cr.match, &fr.match);
4302 fr.priority = rule->cr.priority;
4303 fr.cookie = rule->flow_cookie;
4305 fr.table_id = rule->table_id;
4306 calc_duration(rule->created, time_msec(),
4307 &fr.duration_sec, &fr.duration_nsec);
4308 ovs_mutex_lock(&rule->mutex);
4309 fr.idle_timeout = rule->idle_timeout;
4310 fr.hard_timeout = rule->hard_timeout;
4311 ovs_mutex_unlock(&rule->mutex);
4312 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4315 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4318 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4319 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4322 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4325 * ofproto implementation ->run() functions should use this function to expire
4326 * OpenFlow flows. */
4328 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4329 OVS_REQUIRES(ofproto_mutex)
4331 struct ofproto *ofproto = rule->ofproto;
4333 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT
4334 || reason == OFPRR_DELETE || reason == OFPRR_GROUP_DELETE);
4336 ofproto_rule_delete__(ofproto, rule, reason);
4339 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
4340 * means "infinite". */
4342 reduce_timeout(uint16_t max, uint16_t *timeout)
4344 if (max && (!*timeout || *timeout > max)) {
4349 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4350 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4351 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
4353 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4355 ofproto_rule_reduce_timeouts(struct rule *rule,
4356 uint16_t idle_timeout, uint16_t hard_timeout)
4357 OVS_EXCLUDED(ofproto_mutex, rule->mutex)
4359 if (!idle_timeout && !hard_timeout) {
4363 ovs_mutex_lock(&ofproto_mutex);
4364 if (list_is_empty(&rule->expirable)) {
4365 list_insert(&rule->ofproto->expirable, &rule->expirable);
4367 ovs_mutex_unlock(&ofproto_mutex);
4369 ovs_mutex_lock(&rule->mutex);
4370 reduce_timeout(idle_timeout, &rule->idle_timeout);
4371 reduce_timeout(hard_timeout, &rule->hard_timeout);
4372 ovs_mutex_unlock(&rule->mutex);
4376 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4377 OVS_EXCLUDED(ofproto_mutex)
4379 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4380 struct ofputil_flow_mod fm;
4381 uint64_t ofpacts_stub[1024 / 8];
4382 struct ofpbuf ofpacts;
4386 error = reject_slave_controller(ofconn);
4391 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4392 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4394 u16_to_ofp(ofproto->max_ports),
4397 error = ofproto_check_ofpacts(ofproto, fm.ofpacts, fm.ofpacts_len);
4400 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4403 goto exit_free_ofpacts;
4406 /* Record the operation for logging a summary report. */
4407 switch (fm.command) {
4413 case OFPFC_MODIFY_STRICT:
4414 ofproto->n_modify++;
4418 case OFPFC_DELETE_STRICT:
4419 ofproto->n_delete++;
4424 if (ofproto->next_op_report == LLONG_MAX) {
4425 ofproto->first_op = now;
4426 ofproto->next_op_report = MAX(now + 10 * 1000,
4427 ofproto->op_backoff);
4428 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
4430 ofproto->last_op = now;
4433 ofpbuf_uninit(&ofpacts);
4439 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4440 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4441 OVS_EXCLUDED(ofproto_mutex)
4445 ovs_mutex_lock(&ofproto_mutex);
4446 if (ofproto->n_pending < 50) {
4447 switch (fm->command) {
4449 error = add_flow(ofproto, ofconn, fm, oh);
4453 error = modify_flows_loose(ofproto, ofconn, fm, oh);
4456 case OFPFC_MODIFY_STRICT:
4457 error = modify_flow_strict(ofproto, ofconn, fm, oh);
4461 error = delete_flows_loose(ofproto, ofconn, fm, oh);
4464 case OFPFC_DELETE_STRICT:
4465 error = delete_flow_strict(ofproto, ofconn, fm, oh);
4469 if (fm->command > 0xff) {
4470 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4471 "flow_mod_table_id extension is not enabled",
4474 error = OFPERR_OFPFMFC_BAD_COMMAND;
4478 ovs_assert(!list_is_empty(&ofproto->pending));
4479 error = OFPROTO_POSTPONE;
4481 ovs_mutex_unlock(&ofproto_mutex);
4483 run_rule_executes(ofproto);
4488 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4490 struct ofputil_role_request request;
4491 struct ofputil_role_request reply;
4495 error = ofputil_decode_role_message(oh, &request);
4500 if (request.role != OFPCR12_ROLE_NOCHANGE) {
4501 if (ofconn_get_role(ofconn) != request.role
4502 && ofconn_has_pending_opgroups(ofconn)) {
4503 return OFPROTO_POSTPONE;
4506 if (request.have_generation_id
4507 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4508 return OFPERR_OFPRRFC_STALE;
4511 ofconn_set_role(ofconn, request.role);
4514 reply.role = ofconn_get_role(ofconn);
4515 reply.have_generation_id = ofconn_get_master_election_id(
4516 ofconn, &reply.generation_id);
4517 buf = ofputil_encode_role_reply(oh, &reply);
4518 ofconn_send_reply(ofconn, buf);
4524 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4525 const struct ofp_header *oh)
4527 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4528 enum ofputil_protocol cur, next;
4530 cur = ofconn_get_protocol(ofconn);
4531 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4532 ofconn_set_protocol(ofconn, next);
4538 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4540 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4541 enum ofputil_protocol cur, next;
4542 enum ofputil_protocol next_base;
4544 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4546 return OFPERR_OFPBRC_EPERM;
4549 cur = ofconn_get_protocol(ofconn);
4550 next = ofputil_protocol_set_base(cur, next_base);
4551 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4552 /* Avoid sending async messages in surprising protocol. */
4553 return OFPROTO_POSTPONE;
4556 ofconn_set_protocol(ofconn, next);
4561 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4562 const struct ofp_header *oh)
4564 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4567 format = ntohl(msg->format);
4568 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4569 return OFPERR_OFPBRC_EPERM;
4572 if (format != ofconn_get_packet_in_format(ofconn)
4573 && ofconn_has_pending_opgroups(ofconn)) {
4574 /* Avoid sending async message in surprsing packet in format. */
4575 return OFPROTO_POSTPONE;
4578 ofconn_set_packet_in_format(ofconn, format);
4583 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4585 const struct nx_async_config *msg = ofpmsg_body(oh);
4586 uint32_t master[OAM_N_TYPES];
4587 uint32_t slave[OAM_N_TYPES];
4589 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4590 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4591 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4593 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4594 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4595 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4597 ofconn_set_async_config(ofconn, master, slave);
4598 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4599 !ofconn_get_miss_send_len(ofconn)) {
4600 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4607 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
4610 uint32_t master[OAM_N_TYPES];
4611 uint32_t slave[OAM_N_TYPES];
4612 struct nx_async_config *msg;
4614 ofconn_get_async_config(ofconn, master, slave);
4615 buf = ofpraw_alloc_reply(OFPRAW_OFPT13_GET_ASYNC_REPLY, oh, 0);
4616 msg = ofpbuf_put_zeros(buf, sizeof *msg);
4618 msg->packet_in_mask[0] = htonl(master[OAM_PACKET_IN]);
4619 msg->port_status_mask[0] = htonl(master[OAM_PORT_STATUS]);
4620 msg->flow_removed_mask[0] = htonl(master[OAM_FLOW_REMOVED]);
4622 msg->packet_in_mask[1] = htonl(slave[OAM_PACKET_IN]);
4623 msg->port_status_mask[1] = htonl(slave[OAM_PORT_STATUS]);
4624 msg->flow_removed_mask[1] = htonl(slave[OAM_FLOW_REMOVED]);
4626 ofconn_send_reply(ofconn, buf);
4632 handle_nxt_set_controller_id(struct ofconn *ofconn,
4633 const struct ofp_header *oh)
4635 const struct nx_controller_id *nci = ofpmsg_body(oh);
4637 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4638 return OFPERR_NXBRC_MUST_BE_ZERO;
4641 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4646 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4650 if (ofconn_has_pending_opgroups(ofconn)) {
4651 return OFPROTO_POSTPONE;
4654 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4655 ? OFPRAW_OFPT10_BARRIER_REPLY
4656 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4657 ofconn_send_reply(ofconn, buf);
4662 ofproto_compose_flow_refresh_update(const struct rule *rule,
4663 enum nx_flow_monitor_flags flags,
4665 OVS_REQUIRES(ofproto_mutex)
4667 struct ofoperation *op = rule->pending;
4668 const struct rule_actions *actions;
4669 struct ofputil_flow_update fu;
4672 if (op && op->type == OFOPERATION_ADD) {
4673 /* We'll report the final flow when the operation completes. Reporting
4674 * it now would cause a duplicate report later. */
4678 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4679 ? NXFME_ADDED : NXFME_MODIFIED);
4681 ovs_mutex_lock(&rule->mutex);
4682 fu.idle_timeout = rule->idle_timeout;
4683 fu.hard_timeout = rule->hard_timeout;
4684 ovs_mutex_unlock(&rule->mutex);
4685 fu.table_id = rule->table_id;
4686 fu.cookie = rule->flow_cookie;
4687 minimatch_expand(&rule->cr.match, &match);
4689 fu.priority = rule->cr.priority;
4691 if (!(flags & NXFMF_ACTIONS)) {
4694 actions = rule->actions;
4696 /* An operation is in progress. Use the previous version of the flow's
4697 * actions, so that when the operation commits we report the change. */
4699 case OFOPERATION_ADD:
4702 case OFOPERATION_MODIFY:
4703 case OFOPERATION_REPLACE:
4704 actions = op->actions ? op->actions : rule->actions;
4707 case OFOPERATION_DELETE:
4708 actions = rule->actions;
4715 fu.ofpacts = actions ? actions->ofpacts : NULL;
4716 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4718 if (list_is_empty(msgs)) {
4719 ofputil_start_flow_update(msgs);
4721 ofputil_append_flow_update(&fu, msgs);
4725 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4727 OVS_REQUIRES(ofproto_mutex)
4731 for (i = 0; i < rules->n; i++) {
4732 struct rule *rule = rules->rules[i];
4733 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4734 rule->monitor_flags = 0;
4736 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4741 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4742 struct rule *rule, uint64_t seqno,
4743 struct rule_collection *rules)
4744 OVS_REQUIRES(ofproto_mutex)
4746 enum nx_flow_monitor_flags update;
4748 if (ofproto_rule_is_hidden(rule)) {
4753 ? ofoperation_has_out_port(rule->pending, m->out_port)
4754 : ofproto_rule_has_out_port(rule, m->out_port))) {
4759 if (rule->add_seqno > seqno) {
4760 update = NXFMF_ADD | NXFMF_MODIFY;
4761 } else if (rule->modify_seqno > seqno) {
4762 update = NXFMF_MODIFY;
4767 if (!(m->flags & update)) {
4771 update = NXFMF_INITIAL;
4774 if (!rule->monitor_flags) {
4775 rule_collection_add(rules, rule);
4777 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4781 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4783 struct rule_collection *rules)
4784 OVS_REQUIRES(ofproto_mutex)
4786 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4787 const struct ofoperation *op;
4788 const struct oftable *table;
4789 struct cls_rule target;
4791 cls_rule_init_from_minimatch(&target, &m->match, 0);
4792 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4793 struct cls_cursor cursor;
4796 ovs_rwlock_rdlock(&table->cls.rwlock);
4797 cls_cursor_init(&cursor, &table->cls, &target);
4798 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4799 ovs_assert(!rule->pending); /* XXX */
4800 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4802 ovs_rwlock_unlock(&table->cls.rwlock);
4805 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4806 struct rule *rule = op->rule;
4808 if (((m->table_id == 0xff
4809 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4810 : m->table_id == rule->table_id))
4811 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4812 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4815 cls_rule_destroy(&target);
4819 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4820 struct rule_collection *rules)
4821 OVS_REQUIRES(ofproto_mutex)
4823 if (m->flags & NXFMF_INITIAL) {
4824 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4829 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4830 uint64_t seqno, struct rule_collection *rules)
4831 OVS_REQUIRES(ofproto_mutex)
4833 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4837 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4838 OVS_EXCLUDED(ofproto_mutex)
4840 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4841 struct ofmonitor **monitors;
4842 size_t n_monitors, allocated_monitors;
4843 struct rule_collection rules;
4844 struct list replies;
4850 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4852 n_monitors = allocated_monitors = 0;
4854 ovs_mutex_lock(&ofproto_mutex);
4856 struct ofputil_flow_monitor_request request;
4857 struct ofmonitor *m;
4860 retval = ofputil_decode_flow_monitor_request(&request, &b);
4861 if (retval == EOF) {
4863 } else if (retval) {
4868 if (request.table_id != 0xff
4869 && request.table_id >= ofproto->n_tables) {
4870 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4874 error = ofmonitor_create(&request, ofconn, &m);
4879 if (n_monitors >= allocated_monitors) {
4880 monitors = x2nrealloc(monitors, &allocated_monitors,
4883 monitors[n_monitors++] = m;
4886 rule_collection_init(&rules);
4887 for (i = 0; i < n_monitors; i++) {
4888 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4891 ofpmp_init(&replies, oh);
4892 ofmonitor_compose_refresh_updates(&rules, &replies);
4893 ovs_mutex_unlock(&ofproto_mutex);
4895 rule_collection_destroy(&rules);
4897 ofconn_send_replies(ofconn, &replies);
4903 for (i = 0; i < n_monitors; i++) {
4904 ofmonitor_destroy(monitors[i]);
4907 ovs_mutex_unlock(&ofproto_mutex);
4913 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4914 OVS_EXCLUDED(ofproto_mutex)
4916 struct ofmonitor *m;
4920 id = ofputil_decode_flow_monitor_cancel(oh);
4922 ovs_mutex_lock(&ofproto_mutex);
4923 m = ofmonitor_lookup(ofconn, id);
4925 ofmonitor_destroy(m);
4928 error = OFPERR_NXBRC_FM_BAD_ID;
4930 ovs_mutex_unlock(&ofproto_mutex);
4935 /* Meters implementation.
4937 * Meter table entry, indexed by the OpenFlow meter_id.
4938 * These are always dynamically allocated to allocate enough space for
4940 * 'created' is used to compute the duration for meter stats.
4941 * 'list rules' is needed so that we can delete the dependent rules when the
4942 * meter table entry is deleted.
4943 * 'provider_meter_id' is for the provider's private use.
4946 long long int created; /* Time created. */
4947 struct list rules; /* List of "struct rule_dpif"s. */
4948 ofproto_meter_id provider_meter_id;
4949 uint16_t flags; /* Meter flags. */
4950 uint16_t n_bands; /* Number of meter bands. */
4951 struct ofputil_meter_band *bands;
4955 * This is used in instruction validation at flow set-up time,
4956 * as flows may not use non-existing meters.
4957 * Return value of UINT32_MAX signifies an invalid meter.
4960 get_provider_meter_id(const struct ofproto *ofproto, uint32_t of_meter_id)
4962 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4963 const struct meter *meter = ofproto->meters[of_meter_id];
4965 return meter->provider_meter_id.uint32;
4972 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4976 meter->flags = config->flags;
4977 meter->n_bands = config->n_bands;
4978 meter->bands = xmemdup(config->bands,
4979 config->n_bands * sizeof *meter->bands);
4982 static struct meter *
4983 meter_create(const struct ofputil_meter_config *config,
4984 ofproto_meter_id provider_meter_id)
4986 struct meter *meter;
4988 meter = xzalloc(sizeof *meter);
4989 meter->provider_meter_id = provider_meter_id;
4990 meter->created = time_msec();
4991 list_init(&meter->rules);
4993 meter_update(meter, config);
4999 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
5000 OVS_REQUIRES(ofproto_mutex)
5003 for (mid = first; mid <= last; ++mid) {
5004 struct meter *meter = ofproto->meters[mid];
5006 ofproto->meters[mid] = NULL;
5007 ofproto->ofproto_class->meter_del(ofproto,
5008 meter->provider_meter_id);
5016 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5018 ofproto_meter_id provider_meter_id = { UINT32_MAX };
5019 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
5023 return OFPERR_OFPMMFC_METER_EXISTS;
5026 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
5029 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
5030 *meterp = meter_create(&mm->meter, provider_meter_id);
5036 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5038 struct meter *meter = ofproto->meters[mm->meter.meter_id];
5040 uint32_t provider_meter_id;
5043 return OFPERR_OFPMMFC_UNKNOWN_METER;
5046 provider_meter_id = meter->provider_meter_id.uint32;
5047 error = ofproto->ofproto_class->meter_set(ofproto,
5048 &meter->provider_meter_id,
5050 ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
5052 meter_update(meter, &mm->meter);
5058 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
5059 struct ofputil_meter_mod *mm)
5060 OVS_EXCLUDED(ofproto_mutex)
5062 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5063 uint32_t meter_id = mm->meter.meter_id;
5064 struct rule_collection rules;
5065 enum ofperr error = 0;
5066 uint32_t first, last;
5068 if (meter_id == OFPM13_ALL) {
5070 last = ofproto->meter_features.max_meters;
5072 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
5075 first = last = meter_id;
5078 /* First delete the rules that use this meter. If any of those rules are
5079 * currently being modified, postpone the whole operation until later. */
5080 rule_collection_init(&rules);
5081 ovs_mutex_lock(&ofproto_mutex);
5082 for (meter_id = first; meter_id <= last; ++meter_id) {
5083 struct meter *meter = ofproto->meters[meter_id];
5084 if (meter && !list_is_empty(&meter->rules)) {
5087 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
5088 if (rule->pending) {
5089 error = OFPROTO_POSTPONE;
5092 rule_collection_add(&rules, rule);
5097 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
5100 /* Delete the meters. */
5101 meter_delete(ofproto, first, last);
5104 ovs_mutex_unlock(&ofproto_mutex);
5105 rule_collection_destroy(&rules);
5111 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5113 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5114 struct ofputil_meter_mod mm;
5115 uint64_t bands_stub[256 / 8];
5116 struct ofpbuf bands;
5120 error = reject_slave_controller(ofconn);
5125 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5127 error = ofputil_decode_meter_mod(oh, &mm, &bands);
5129 goto exit_free_bands;
5132 meter_id = mm.meter.meter_id;
5134 if (mm.command != OFPMC13_DELETE) {
5135 /* Fails also when meters are not implemented by the provider. */
5136 if (meter_id == 0 || meter_id > OFPM13_MAX) {
5137 error = OFPERR_OFPMMFC_INVALID_METER;
5138 goto exit_free_bands;
5139 } else if (meter_id > ofproto->meter_features.max_meters) {
5140 error = OFPERR_OFPMMFC_OUT_OF_METERS;
5141 goto exit_free_bands;
5143 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
5144 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
5145 goto exit_free_bands;
5149 switch (mm.command) {
5151 error = handle_add_meter(ofproto, &mm);
5154 case OFPMC13_MODIFY:
5155 error = handle_modify_meter(ofproto, &mm);
5158 case OFPMC13_DELETE:
5159 error = handle_delete_meter(ofconn, oh, &mm);
5163 error = OFPERR_OFPMMFC_BAD_COMMAND;
5168 ofpbuf_uninit(&bands);
5173 handle_meter_features_request(struct ofconn *ofconn,
5174 const struct ofp_header *request)
5176 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5177 struct ofputil_meter_features features;
5180 if (ofproto->ofproto_class->meter_get_features) {
5181 ofproto->ofproto_class->meter_get_features(ofproto, &features);
5183 memset(&features, 0, sizeof features);
5185 b = ofputil_encode_meter_features_reply(&features, request);
5187 ofconn_send_reply(ofconn, b);
5192 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
5195 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5196 struct list replies;
5197 uint64_t bands_stub[256 / 8];
5198 struct ofpbuf bands;
5199 uint32_t meter_id, first, last;
5201 ofputil_decode_meter_request(request, &meter_id);
5203 if (meter_id == OFPM13_ALL) {
5205 last = ofproto->meter_features.max_meters;
5207 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
5208 !ofproto->meters[meter_id]) {
5209 return OFPERR_OFPMMFC_UNKNOWN_METER;
5211 first = last = meter_id;
5214 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5215 ofpmp_init(&replies, request);
5217 for (meter_id = first; meter_id <= last; ++meter_id) {
5218 struct meter *meter = ofproto->meters[meter_id];
5220 continue; /* Skip non-existing meters. */
5222 if (type == OFPTYPE_METER_STATS_REQUEST) {
5223 struct ofputil_meter_stats stats;
5225 stats.meter_id = meter_id;
5227 /* Provider sets the packet and byte counts, we do the rest. */
5228 stats.flow_count = list_size(&meter->rules);
5229 calc_duration(meter->created, time_msec(),
5230 &stats.duration_sec, &stats.duration_nsec);
5231 stats.n_bands = meter->n_bands;
5232 ofpbuf_clear(&bands);
5234 = ofpbuf_put_uninit(&bands,
5235 meter->n_bands * sizeof *stats.bands);
5237 if (!ofproto->ofproto_class->meter_get(ofproto,
5238 meter->provider_meter_id,
5240 ofputil_append_meter_stats(&replies, &stats);
5242 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
5243 struct ofputil_meter_config config;
5245 config.meter_id = meter_id;
5246 config.flags = meter->flags;
5247 config.n_bands = meter->n_bands;
5248 config.bands = meter->bands;
5249 ofputil_append_meter_config(&replies, &config);
5253 ofconn_send_replies(ofconn, &replies);
5254 ofpbuf_uninit(&bands);
5259 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
5260 struct ofgroup **group)
5261 OVS_TRY_RDLOCK(true, (*group)->rwlock)
5263 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5264 HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5265 hash_int(group_id, 0), &ofproto->groups) {
5266 if ((*group)->group_id == group_id) {
5267 ovs_rwlock_rdlock(&(*group)->rwlock);
5268 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5272 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5277 ofproto_group_release(struct ofgroup *group)
5278 OVS_RELEASES(group->rwlock)
5280 ovs_rwlock_unlock(&group->rwlock);
5284 ofproto_group_write_lookup(const struct ofproto *ofproto, uint32_t group_id,
5285 struct ofgroup **group)
5286 OVS_TRY_WRLOCK(true, ofproto->groups_rwlock)
5287 OVS_TRY_WRLOCK(true, (*group)->rwlock)
5289 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5290 HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5291 hash_int(group_id, 0), &ofproto->groups) {
5292 if ((*group)->group_id == group_id) {
5293 ovs_rwlock_wrlock(&(*group)->rwlock);
5297 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5302 ofproto_group_exists__(const struct ofproto *ofproto, uint32_t group_id)
5303 OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5305 struct ofgroup *grp;
5307 HMAP_FOR_EACH_IN_BUCKET (grp, hmap_node,
5308 hash_int(group_id, 0), &ofproto->groups) {
5309 if (grp->group_id == group_id) {
5317 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
5318 OVS_EXCLUDED(ofproto->groups_rwlock)
5322 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5323 exists = ofproto_group_exists__(ofproto, group_id);
5324 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5330 group_get_ref_count(struct ofgroup *group)
5331 OVS_EXCLUDED(ofproto_mutex)
5333 struct ofproto *ofproto = group->ofproto;
5334 struct rule_criteria criteria;
5335 struct rule_collection rules;
5340 match_init_catchall(&match);
5341 rule_criteria_init(&criteria, 0xff, &match, 0, htonll(0), htonll(0),
5342 OFPP_ANY, group->group_id);
5343 ovs_mutex_lock(&ofproto_mutex);
5344 error = collect_rules_loose(ofproto, &criteria, &rules);
5345 ovs_mutex_unlock(&ofproto_mutex);
5346 rule_criteria_destroy(&criteria);
5348 count = !error && rules.n < UINT32_MAX ? rules.n : UINT32_MAX;
5350 rule_collection_destroy(&rules);
5355 append_group_stats(struct ofgroup *group, struct list *replies)
5356 OVS_REQ_RDLOCK(group->rwlock)
5358 struct ofputil_group_stats ogs;
5359 struct ofproto *ofproto = group->ofproto;
5360 long long int now = time_msec();
5363 ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
5365 /* Provider sets the packet and byte counts, we do the rest. */
5366 ogs.ref_count = group_get_ref_count(group);
5367 ogs.n_buckets = group->n_buckets;
5369 error = (ofproto->ofproto_class->group_get_stats
5370 ? ofproto->ofproto_class->group_get_stats(group, &ogs)
5373 ogs.packet_count = UINT64_MAX;
5374 ogs.byte_count = UINT64_MAX;
5375 memset(ogs.bucket_stats, 0xff,
5376 ogs.n_buckets * sizeof *ogs.bucket_stats);
5379 ogs.group_id = group->group_id;
5380 calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
5382 ofputil_append_group_stats(replies, &ogs);
5384 free(ogs.bucket_stats);
5388 handle_group_stats_request(struct ofconn *ofconn,
5389 const struct ofp_header *request)
5391 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5392 struct list replies;
5394 struct ofgroup *group;
5397 error = ofputil_decode_group_stats_request(request, &group_id);
5402 ofpmp_init(&replies, request);
5404 if (group_id == OFPG_ALL) {
5405 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5406 HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5407 ovs_rwlock_rdlock(&group->rwlock);
5408 append_group_stats(group, &replies);
5409 ovs_rwlock_unlock(&group->rwlock);
5411 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5413 if (ofproto_group_lookup(ofproto, group_id, &group)) {
5414 append_group_stats(group, &replies);
5415 ofproto_group_release(group);
5419 ofconn_send_replies(ofconn, &replies);
5425 handle_group_desc_stats_request(struct ofconn *ofconn,
5426 const struct ofp_header *request)
5428 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5429 struct list replies;
5430 struct ofputil_group_desc gds;
5431 struct ofgroup *group;
5433 ofpmp_init(&replies, request);
5435 ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5436 HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5437 gds.group_id = group->group_id;
5438 gds.type = group->type;
5439 ofputil_append_group_desc_reply(&gds, &group->buckets, &replies);
5441 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5443 ofconn_send_replies(ofconn, &replies);
5449 handle_group_features_stats_request(struct ofconn *ofconn,
5450 const struct ofp_header *request)
5452 struct ofproto *p = ofconn_get_ofproto(ofconn);
5455 msg = ofputil_encode_group_features_reply(&p->ogf, request);
5457 ofconn_send_reply(ofconn, msg);
5464 handle_queue_get_config_request(struct ofconn *ofconn,
5465 const struct ofp_header *oh)
5467 struct ofproto *p = ofconn_get_ofproto(ofconn);
5468 struct netdev_queue_dump queue_dump;
5469 struct ofport *ofport;
5470 unsigned int queue_id;
5471 struct ofpbuf *reply;
5472 struct smap details;
5476 error = ofputil_decode_queue_get_config_request(oh, &request);
5481 ofport = ofproto_get_port(p, request);
5483 return OFPERR_OFPQOFC_BAD_PORT;
5486 reply = ofputil_encode_queue_get_config_reply(oh);
5488 smap_init(&details);
5489 NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &queue_dump, ofport->netdev) {
5490 struct ofputil_queue_config queue;
5492 /* None of the existing queues have compatible properties, so we
5493 * hard-code omitting min_rate and max_rate. */
5494 queue.queue_id = queue_id;
5495 queue.min_rate = UINT16_MAX;
5496 queue.max_rate = UINT16_MAX;
5497 ofputil_append_queue_get_config_reply(reply, &queue);
5499 smap_destroy(&details);
5501 ofconn_send_reply(ofconn, reply);
5506 /* Implements OFPGC11_ADD
5507 * in which no matching flow already exists in the flow table.
5509 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
5510 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
5511 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
5512 * initiated now but may be retried later.
5514 * Upon successful return, takes ownership of 'fm->ofpacts'. On failure,
5515 * ownership remains with the caller.
5517 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
5520 add_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5522 struct ofgroup *ofgroup;
5525 if (gm->group_id > OFPG_MAX) {
5526 return OFPERR_OFPGMFC_INVALID_GROUP;
5528 if (gm->type > OFPGT11_FF) {
5529 return OFPERR_OFPGMFC_BAD_TYPE;
5532 /* Allocate new group and initialize it. */
5533 ofgroup = ofproto->ofproto_class->group_alloc();
5535 VLOG_WARN_RL(&rl, "%s: failed to create group", ofproto->name);
5536 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5539 ovs_rwlock_init(&ofgroup->rwlock);
5540 ofgroup->ofproto = ofproto;
5541 ofgroup->group_id = gm->group_id;
5542 ofgroup->type = gm->type;
5543 ofgroup->created = ofgroup->modified = time_msec();
5545 list_move(&ofgroup->buckets, &gm->buckets);
5546 ofgroup->n_buckets = list_size(&ofgroup->buckets);
5548 /* Construct called BEFORE any locks are held. */
5549 error = ofproto->ofproto_class->group_construct(ofgroup);
5554 /* We wrlock as late as possible to minimize the time we jam any other
5555 * threads: No visible state changes before acquiring the lock. */
5556 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5558 if (ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5559 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5563 if (ofproto_group_exists__(ofproto, gm->group_id)) {
5564 error = OFPERR_OFPGMFC_GROUP_EXISTS;
5569 /* Insert new group. */
5570 hmap_insert(&ofproto->groups, &ofgroup->hmap_node,
5571 hash_int(ofgroup->group_id, 0));
5572 ofproto->n_groups[ofgroup->type]++;
5574 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5579 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5580 ofproto->ofproto_class->group_destruct(ofgroup);
5582 ofputil_bucket_list_destroy(&ofgroup->buckets);
5583 ofproto->ofproto_class->group_dealloc(ofgroup);
5588 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
5591 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
5594 modify_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5596 struct ofgroup *ofgroup;
5597 struct ofgroup *victim;
5600 if (gm->group_id > OFPG_MAX) {
5601 return OFPERR_OFPGMFC_INVALID_GROUP;
5604 if (gm->type > OFPGT11_FF) {
5605 return OFPERR_OFPGMFC_BAD_TYPE;
5608 victim = ofproto->ofproto_class->group_alloc();
5610 VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
5611 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5614 if (!ofproto_group_write_lookup(ofproto, gm->group_id, &ofgroup)) {
5615 error = OFPERR_OFPGMFC_UNKNOWN_GROUP;
5618 /* Both group's and its container's write locks held now.
5619 * Also, n_groups[] is protected by ofproto->groups_rwlock. */
5620 if (ofgroup->type != gm->type
5621 && ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5622 error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5627 list_move(&victim->buckets, &ofgroup->buckets);
5629 ofgroup->type = gm->type;
5630 list_move(&ofgroup->buckets, &gm->buckets);
5631 ofgroup->n_buckets = list_size(&ofgroup->buckets);
5633 error = ofproto->ofproto_class->group_modify(ofgroup, victim);
5635 ofputil_bucket_list_destroy(&victim->buckets);
5636 ofproto->n_groups[victim->type]--;
5637 ofproto->n_groups[ofgroup->type]++;
5638 ofgroup->modified = time_msec();
5640 ofputil_bucket_list_destroy(&ofgroup->buckets);
5643 list_move(&ofgroup->buckets, &victim->buckets);
5647 ovs_rwlock_unlock(&ofgroup->rwlock);
5648 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5650 ofproto->ofproto_class->group_dealloc(victim);
5655 delete_group__(struct ofproto *ofproto, struct ofgroup *ofgroup)
5656 OVS_RELEASES(ofproto->groups_rwlock)
5659 struct ofputil_flow_mod fm;
5661 /* Delete all flow entries containing this group in a group action */
5662 match_init_catchall(&match);
5663 flow_mod_init(&fm, &match, 0, NULL, 0, OFPFC_DELETE);
5664 fm.out_group = ofgroup->group_id;
5665 handle_flow_mod__(ofproto, NULL, &fm, NULL);
5667 /* Must wait until existing readers are done,
5668 * while holding the container's write lock at the same time. */
5669 ovs_rwlock_wrlock(&ofgroup->rwlock);
5670 hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5671 /* No-one can find this group any more. */
5672 ofproto->n_groups[ofgroup->type]--;
5673 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5675 ofproto->ofproto_class->group_destruct(ofgroup);
5676 ofputil_bucket_list_destroy(&ofgroup->buckets);
5677 ovs_rwlock_unlock(&ofgroup->rwlock);
5678 ovs_rwlock_destroy(&ofgroup->rwlock);
5679 ofproto->ofproto_class->group_dealloc(ofgroup);
5682 /* Implements OFPGC_DELETE. */
5684 delete_group(struct ofproto *ofproto, uint32_t group_id)
5686 struct ofgroup *ofgroup;
5688 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5689 if (group_id == OFPG_ALL) {
5691 struct hmap_node *node = hmap_first(&ofproto->groups);
5695 ofgroup = CONTAINER_OF(node, struct ofgroup, hmap_node);
5696 delete_group__(ofproto, ofgroup);
5697 /* Lock for each node separately, so that we will not jam the
5698 * other threads for too long time. */
5699 ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5702 HMAP_FOR_EACH_IN_BUCKET (ofgroup, hmap_node,
5703 hash_int(group_id, 0), &ofproto->groups) {
5704 if (ofgroup->group_id == group_id) {
5705 delete_group__(ofproto, ofgroup);
5710 ovs_rwlock_unlock(&ofproto->groups_rwlock);
5714 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5716 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5717 struct ofputil_group_mod gm;
5720 error = reject_slave_controller(ofconn);
5725 error = ofputil_decode_group_mod(oh, &gm);
5730 switch (gm.command) {
5732 return add_group(ofproto, &gm);
5734 case OFPGC11_MODIFY:
5735 return modify_group(ofproto, &gm);
5737 case OFPGC11_DELETE:
5738 delete_group(ofproto, gm.group_id);
5742 if (gm.command > OFPGC11_DELETE) {
5743 VLOG_WARN_RL(&rl, "%s: Invalid group_mod command type %d",
5744 ofproto->name, gm.command);
5746 return OFPERR_OFPGMFC_BAD_COMMAND;
5751 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5753 struct ofputil_table_mod tm;
5756 error = reject_slave_controller(ofconn);
5761 error = ofputil_decode_table_mod(oh, &tm);
5766 /* XXX Actual table mod support is not implemented yet. */
5771 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
5772 OVS_EXCLUDED(ofproto_mutex)
5774 const struct ofp_header *oh = msg->data;
5778 error = ofptype_decode(&type, oh);
5782 if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
5783 && ofpmp_more(oh)) {
5784 /* We have no buffer implementation for multipart requests.
5785 * Report overflow for requests which consists of multiple
5787 return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
5791 /* OpenFlow requests. */
5792 case OFPTYPE_ECHO_REQUEST:
5793 return handle_echo_request(ofconn, oh);
5795 case OFPTYPE_FEATURES_REQUEST:
5796 return handle_features_request(ofconn, oh);
5798 case OFPTYPE_GET_CONFIG_REQUEST:
5799 return handle_get_config_request(ofconn, oh);
5801 case OFPTYPE_SET_CONFIG:
5802 return handle_set_config(ofconn, oh);
5804 case OFPTYPE_PACKET_OUT:
5805 return handle_packet_out(ofconn, oh);
5807 case OFPTYPE_PORT_MOD:
5808 return handle_port_mod(ofconn, oh);
5810 case OFPTYPE_FLOW_MOD:
5811 return handle_flow_mod(ofconn, oh);
5813 case OFPTYPE_GROUP_MOD:
5814 return handle_group_mod(ofconn, oh);
5816 case OFPTYPE_TABLE_MOD:
5817 return handle_table_mod(ofconn, oh);
5819 case OFPTYPE_METER_MOD:
5820 return handle_meter_mod(ofconn, oh);
5822 case OFPTYPE_BARRIER_REQUEST:
5823 return handle_barrier_request(ofconn, oh);
5825 case OFPTYPE_ROLE_REQUEST:
5826 return handle_role_request(ofconn, oh);
5828 /* OpenFlow replies. */
5829 case OFPTYPE_ECHO_REPLY:
5832 /* Nicira extension requests. */
5833 case OFPTYPE_FLOW_MOD_TABLE_ID:
5834 return handle_nxt_flow_mod_table_id(ofconn, oh);
5836 case OFPTYPE_SET_FLOW_FORMAT:
5837 return handle_nxt_set_flow_format(ofconn, oh);
5839 case OFPTYPE_SET_PACKET_IN_FORMAT:
5840 return handle_nxt_set_packet_in_format(ofconn, oh);
5842 case OFPTYPE_SET_CONTROLLER_ID:
5843 return handle_nxt_set_controller_id(ofconn, oh);
5845 case OFPTYPE_FLOW_AGE:
5846 /* Nothing to do. */
5849 case OFPTYPE_FLOW_MONITOR_CANCEL:
5850 return handle_flow_monitor_cancel(ofconn, oh);
5852 case OFPTYPE_SET_ASYNC_CONFIG:
5853 return handle_nxt_set_async_config(ofconn, oh);
5855 case OFPTYPE_GET_ASYNC_REQUEST:
5856 return handle_nxt_get_async_request(ofconn, oh);
5858 /* Statistics requests. */
5859 case OFPTYPE_DESC_STATS_REQUEST:
5860 return handle_desc_stats_request(ofconn, oh);
5862 case OFPTYPE_FLOW_STATS_REQUEST:
5863 return handle_flow_stats_request(ofconn, oh);
5865 case OFPTYPE_AGGREGATE_STATS_REQUEST:
5866 return handle_aggregate_stats_request(ofconn, oh);
5868 case OFPTYPE_TABLE_STATS_REQUEST:
5869 return handle_table_stats_request(ofconn, oh);
5871 case OFPTYPE_PORT_STATS_REQUEST:
5872 return handle_port_stats_request(ofconn, oh);
5874 case OFPTYPE_QUEUE_STATS_REQUEST:
5875 return handle_queue_stats_request(ofconn, oh);
5877 case OFPTYPE_PORT_DESC_STATS_REQUEST:
5878 return handle_port_desc_stats_request(ofconn, oh);
5880 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
5881 return handle_flow_monitor_request(ofconn, oh);
5883 case OFPTYPE_METER_STATS_REQUEST:
5884 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
5885 return handle_meter_request(ofconn, oh, type);
5887 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
5888 return handle_meter_features_request(ofconn, oh);
5890 case OFPTYPE_GROUP_STATS_REQUEST:
5891 return handle_group_stats_request(ofconn, oh);
5893 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
5894 return handle_group_desc_stats_request(ofconn, oh);
5896 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
5897 return handle_group_features_stats_request(ofconn, oh);
5899 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
5900 return handle_queue_get_config_request(ofconn, oh);
5904 case OFPTYPE_FEATURES_REPLY:
5905 case OFPTYPE_GET_CONFIG_REPLY:
5906 case OFPTYPE_PACKET_IN:
5907 case OFPTYPE_FLOW_REMOVED:
5908 case OFPTYPE_PORT_STATUS:
5909 case OFPTYPE_BARRIER_REPLY:
5910 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
5911 case OFPTYPE_DESC_STATS_REPLY:
5912 case OFPTYPE_FLOW_STATS_REPLY:
5913 case OFPTYPE_QUEUE_STATS_REPLY:
5914 case OFPTYPE_PORT_STATS_REPLY:
5915 case OFPTYPE_TABLE_STATS_REPLY:
5916 case OFPTYPE_AGGREGATE_STATS_REPLY:
5917 case OFPTYPE_PORT_DESC_STATS_REPLY:
5918 case OFPTYPE_ROLE_REPLY:
5919 case OFPTYPE_FLOW_MONITOR_PAUSED:
5920 case OFPTYPE_FLOW_MONITOR_RESUMED:
5921 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
5922 case OFPTYPE_GET_ASYNC_REPLY:
5923 case OFPTYPE_GROUP_STATS_REPLY:
5924 case OFPTYPE_GROUP_DESC_STATS_REPLY:
5925 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
5926 case OFPTYPE_METER_STATS_REPLY:
5927 case OFPTYPE_METER_CONFIG_STATS_REPLY:
5928 case OFPTYPE_METER_FEATURES_STATS_REPLY:
5929 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
5930 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
5931 case OFPTYPE_ROLE_STATUS:
5933 if (ofpmsg_is_stat_request(oh)) {
5934 return OFPERR_OFPBRC_BAD_STAT;
5936 return OFPERR_OFPBRC_BAD_TYPE;
5942 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
5943 OVS_EXCLUDED(ofproto_mutex)
5945 int error = handle_openflow__(ofconn, ofp_msg);
5946 if (error && error != OFPROTO_POSTPONE) {
5947 ofconn_send_error(ofconn, ofp_msg->data, error);
5949 COVERAGE_INC(ofproto_recv_openflow);
5950 return error != OFPROTO_POSTPONE;
5953 /* Asynchronous operations. */
5955 /* Creates and returns a new ofopgroup that is not associated with any
5956 * OpenFlow connection.
5958 * The caller should add operations to the returned group with
5959 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5960 static struct ofopgroup *
5961 ofopgroup_create_unattached(struct ofproto *ofproto)
5962 OVS_REQUIRES(ofproto_mutex)
5964 struct ofopgroup *group = xzalloc(sizeof *group);
5965 group->ofproto = ofproto;
5966 list_init(&group->ofproto_node);
5967 list_init(&group->ops);
5968 list_init(&group->ofconn_node);
5972 /* Creates and returns a new ofopgroup for 'ofproto'.
5974 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
5975 * connection. The 'request' and 'buffer_id' arguments are ignored.
5977 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
5978 * If the ofopgroup eventually fails, then the error reply will include
5979 * 'request'. If the ofopgroup eventually succeeds, then the packet with
5980 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
5982 * The caller should add operations to the returned group with
5983 * ofoperation_create() and then submit it with ofopgroup_submit(). */
5984 static struct ofopgroup *
5985 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
5986 const struct ofp_header *request, uint32_t buffer_id)
5987 OVS_REQUIRES(ofproto_mutex)
5989 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
5991 size_t request_len = ntohs(request->length);
5993 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
5995 ofconn_add_opgroup(ofconn, &group->ofconn_node);
5996 group->ofconn = ofconn;
5997 group->request = xmemdup(request, MIN(request_len, 64));
5998 group->buffer_id = buffer_id;
6003 /* Submits 'group' for processing.
6005 * If 'group' contains no operations (e.g. none were ever added, or all of the
6006 * ones that were added completed synchronously), then it is destroyed
6007 * immediately. Otherwise it is added to the ofproto's list of pending
6010 ofopgroup_submit(struct ofopgroup *group)
6011 OVS_REQUIRES(ofproto_mutex)
6013 if (!group->n_running) {
6014 ofopgroup_complete(group);
6016 list_push_back(&group->ofproto->pending, &group->ofproto_node);
6017 group->ofproto->n_pending++;
6022 ofopgroup_complete(struct ofopgroup *group)
6023 OVS_REQUIRES(ofproto_mutex)
6025 struct ofproto *ofproto = group->ofproto;
6027 struct ofconn *abbrev_ofconn;
6028 ovs_be32 abbrev_xid;
6030 struct ofoperation *op, *next_op;
6033 ovs_assert(!group->n_running);
6036 LIST_FOR_EACH (op, group_node, &group->ops) {
6043 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
6044 LIST_FOR_EACH (op, group_node, &group->ops) {
6045 if (op->type != OFOPERATION_DELETE) {
6046 struct ofpbuf *packet;
6049 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
6052 struct rule_execute *re;
6056 ofproto_rule_ref(op->rule);
6058 re = xmalloc(sizeof *re);
6059 re->rule = op->rule;
6060 re->in_port = in_port;
6061 re->packet = packet;
6063 if (!guarded_list_push_back(&ofproto->rule_executes,
6064 &re->list_node, 1024)) {
6065 ofproto_rule_unref(op->rule);
6066 ofpbuf_delete(re->packet);
6075 if (!error && !list_is_empty(&group->ofconn_node)) {
6076 abbrev_ofconn = group->ofconn;
6077 abbrev_xid = group->request->xid;
6079 abbrev_ofconn = NULL;
6080 abbrev_xid = htonl(0);
6082 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
6083 struct rule *rule = op->rule;
6085 /* We generally want to report the change to active OpenFlow flow
6086 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
6088 - The operation failed.
6090 - The affected rule is not visible to controllers.
6092 - The operation's only effect was to update rule->modified. */
6094 || ofproto_rule_is_hidden(rule)
6095 || (op->type == OFOPERATION_MODIFY
6097 && rule->flow_cookie == op->flow_cookie))) {
6098 /* Check that we can just cast from ofoperation_type to
6099 * nx_flow_update_event. */
6100 enum nx_flow_update_event event_type;
6103 case OFOPERATION_ADD:
6104 case OFOPERATION_REPLACE:
6105 event_type = NXFME_ADDED;
6108 case OFOPERATION_DELETE:
6109 event_type = NXFME_DELETED;
6112 case OFOPERATION_MODIFY:
6113 event_type = NXFME_MODIFIED;
6120 ofmonitor_report(ofproto->connmgr, rule, event_type,
6121 op->reason, abbrev_ofconn, abbrev_xid);
6124 rule->pending = NULL;
6127 case OFOPERATION_ADD:
6131 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
6132 if (vid_mask == VLAN_VID_MASK) {
6133 if (ofproto->vlan_bitmap) {
6134 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
6135 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
6136 bitmap_set1(ofproto->vlan_bitmap, vid);
6137 ofproto->vlans_changed = true;
6140 ofproto->vlans_changed = true;
6144 oftable_remove_rule(rule);
6145 ofproto_rule_unref(rule);
6149 case OFOPERATION_DELETE:
6150 ovs_assert(!op->error);
6151 ofproto_rule_unref(rule);
6155 case OFOPERATION_MODIFY:
6156 case OFOPERATION_REPLACE:
6158 long long int now = time_msec();
6160 rule->modified = now;
6161 if (op->type == OFOPERATION_REPLACE) {
6162 rule->created = rule->used = now;
6165 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
6166 ovs_mutex_lock(&rule->mutex);
6167 rule->idle_timeout = op->idle_timeout;
6168 rule->hard_timeout = op->hard_timeout;
6169 ovs_mutex_unlock(&rule->mutex);
6171 struct rule_actions *old_actions;
6173 ovs_mutex_lock(&rule->mutex);
6174 old_actions = rule->actions;
6175 rule->actions = op->actions;
6176 ovs_mutex_unlock(&rule->mutex);
6179 rule_actions_unref(old_actions);
6181 rule->flags = op->flags;
6189 ofoperation_destroy(op);
6192 ofmonitor_flush(ofproto->connmgr);
6194 if (!list_is_empty(&group->ofproto_node)) {
6195 ovs_assert(ofproto->n_pending > 0);
6196 ofproto->n_pending--;
6197 list_remove(&group->ofproto_node);
6199 if (!list_is_empty(&group->ofconn_node)) {
6200 list_remove(&group->ofconn_node);
6202 ofconn_send_error(group->ofconn, group->request, error);
6204 connmgr_retry(ofproto->connmgr);
6206 free(group->request);
6210 /* Initiates a new operation on 'rule', of the specified 'type', within
6211 * 'group'. Prior to calling, 'rule' must not have any pending operation.
6213 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
6214 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
6216 * Returns the newly created ofoperation (which is also available as
6217 * rule->pending). */
6218 static struct ofoperation *
6219 ofoperation_create(struct ofopgroup *group, struct rule *rule,
6220 enum ofoperation_type type,
6221 enum ofp_flow_removed_reason reason)
6222 OVS_REQUIRES(ofproto_mutex)
6224 struct ofproto *ofproto = group->ofproto;
6225 struct ofoperation *op;
6227 ovs_assert(!rule->pending);
6229 op = rule->pending = xzalloc(sizeof *op);
6231 list_push_back(&group->ops, &op->group_node);
6234 op->reason = reason;
6235 op->flow_cookie = rule->flow_cookie;
6236 ovs_mutex_lock(&rule->mutex);
6237 op->idle_timeout = rule->idle_timeout;
6238 op->hard_timeout = rule->hard_timeout;
6239 ovs_mutex_unlock(&rule->mutex);
6240 op->flags = rule->flags;
6244 if (type == OFOPERATION_DELETE) {
6245 hmap_insert(&ofproto->deletions, &op->hmap_node,
6246 cls_rule_hash(&rule->cr, rule->table_id));
6253 ofoperation_destroy(struct ofoperation *op)
6254 OVS_REQUIRES(ofproto_mutex)
6256 struct ofopgroup *group = op->group;
6259 op->rule->pending = NULL;
6261 if (op->type == OFOPERATION_DELETE) {
6262 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
6264 list_remove(&op->group_node);
6265 rule_actions_unref(op->actions);
6269 /* Indicates that 'op' completed with status 'error', which is either 0 to
6270 * indicate success or an OpenFlow error code on failure.
6272 * If 'error' is 0, indicating success, the operation will be committed
6273 * permanently to the flow table.
6275 * If 'error' is nonzero, then generally the operation will be rolled back:
6277 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
6278 * restores the original rule. The caller must have uninitialized any
6279 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
6280 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
6281 * and 7 for the new rule, calling its ->rule_dealloc() function.
6283 * - If 'op' is a "modify flow" operation, ofproto restores the original
6286 * - 'op' must not be a "delete flow" operation. Removing a rule is not
6287 * allowed to fail. It must always succeed.
6289 * Please see the large comment in ofproto/ofproto-provider.h titled
6290 * "Asynchronous Operation Support" for more information. */
6292 ofoperation_complete(struct ofoperation *op, enum ofperr error)
6294 struct ofopgroup *group = op->group;
6296 ovs_assert(group->n_running > 0);
6297 ovs_assert(!error || op->type != OFOPERATION_DELETE);
6300 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
6301 /* This function can be called from ->rule_construct(), in which case
6302 * ofproto_mutex is held, or it can be called from ->run(), in which
6303 * case ofproto_mutex is not held. But only in the latter case can we
6304 * arrive here, so we can safely take ofproto_mutex now. */
6305 ovs_mutex_lock(&ofproto_mutex);
6306 ovs_assert(op->rule->pending == op);
6307 ofopgroup_complete(group);
6308 ovs_mutex_unlock(&ofproto_mutex);
6313 pick_datapath_id(const struct ofproto *ofproto)
6315 const struct ofport *port;
6317 port = ofproto_get_port(ofproto, OFPP_LOCAL);
6319 uint8_t ea[ETH_ADDR_LEN];
6322 error = netdev_get_etheraddr(port->netdev, ea);
6324 return eth_addr_to_uint64(ea);
6326 VLOG_WARN("%s: could not get MAC address for %s (%s)",
6327 ofproto->name, netdev_get_name(port->netdev),
6328 ovs_strerror(error));
6330 return ofproto->fallback_dpid;
6334 pick_fallback_dpid(void)
6336 uint8_t ea[ETH_ADDR_LEN];
6337 eth_addr_nicira_random(ea);
6338 return eth_addr_to_uint64(ea);
6341 /* Table overflow policy. */
6343 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
6344 * to NULL if the table is not configured to evict rules or if the table
6345 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
6346 * or with no timeouts are not evictable.) */
6348 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
6349 OVS_REQUIRES(ofproto_mutex)
6351 struct eviction_group *evg;
6354 if (!table->eviction_fields) {
6358 /* In the common case, the outer and inner loops here will each be entered
6361 * - The inner loop normally "return"s in its first iteration. If the
6362 * eviction group has any evictable rules, then it always returns in
6365 * - The outer loop only iterates more than once if the largest eviction
6366 * group has no evictable rules.
6368 * - The outer loop can exit only if table's 'max_flows' is all filled up
6369 * by unevictable rules. */
6370 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
6373 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
6382 /* Searches 'ofproto' for tables that have more flows than their configured
6383 * maximum and that have flow eviction enabled, and evicts as many flows as
6384 * necessary and currently feasible from them.
6386 * This triggers only when an OpenFlow table has N flows in it and then the
6387 * client configures a maximum number of flows less than N. */
6389 ofproto_evict(struct ofproto *ofproto)
6391 struct oftable *table;
6393 ovs_mutex_lock(&ofproto_mutex);
6394 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
6395 evict_rules_from_table(ofproto, table, 0);
6397 ovs_mutex_unlock(&ofproto_mutex);
6400 /* Eviction groups. */
6402 /* Returns the priority to use for an eviction_group that contains 'n_rules'
6403 * rules. The priority contains low-order random bits to ensure that eviction
6404 * groups with the same number of rules are prioritized randomly. */
6406 eviction_group_priority(size_t n_rules)
6408 uint16_t size = MIN(UINT16_MAX, n_rules);
6409 return (size << 16) | random_uint16();
6412 /* Updates 'evg', an eviction_group within 'table', following a change that
6413 * adds or removes rules in 'evg'. */
6415 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
6416 OVS_REQUIRES(ofproto_mutex)
6418 heap_change(&table->eviction_groups_by_size, &evg->size_node,
6419 eviction_group_priority(heap_count(&evg->rules)));
6422 /* Destroys 'evg', an eviction_group within 'table':
6424 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
6425 * rules themselves, just removes them from the eviction group.)
6427 * - Removes 'evg' from 'table'.
6431 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
6432 OVS_REQUIRES(ofproto_mutex)
6434 while (!heap_is_empty(&evg->rules)) {
6437 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
6438 rule->eviction_group = NULL;
6440 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
6441 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
6442 heap_destroy(&evg->rules);
6446 /* Removes 'rule' from its eviction group, if any. */
6448 eviction_group_remove_rule(struct rule *rule)
6449 OVS_REQUIRES(ofproto_mutex)
6451 if (rule->eviction_group) {
6452 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6453 struct eviction_group *evg = rule->eviction_group;
6455 rule->eviction_group = NULL;
6456 heap_remove(&evg->rules, &rule->evg_node);
6457 if (heap_is_empty(&evg->rules)) {
6458 eviction_group_destroy(table, evg);
6460 eviction_group_resized(table, evg);
6465 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
6466 * returns the hash value. */
6468 eviction_group_hash_rule(struct rule *rule)
6469 OVS_REQUIRES(ofproto_mutex)
6471 struct oftable *table = &rule->ofproto->tables[rule->table_id];
6472 const struct mf_subfield *sf;
6476 hash = table->eviction_group_id_basis;
6477 miniflow_expand(&rule->cr.match.flow, &flow);
6478 for (sf = table->eviction_fields;
6479 sf < &table->eviction_fields[table->n_eviction_fields];
6482 if (mf_are_prereqs_ok(sf->field, &flow)) {
6483 union mf_value value;
6485 mf_get_value(sf->field, &flow, &value);
6487 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
6489 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
6490 unsigned int start = sf->ofs + sf->n_bits;
6491 bitwise_zero(&value, sf->field->n_bytes, start,
6492 sf->field->n_bytes * 8 - start);
6494 hash = hash_bytes(&value, sf->field->n_bytes, hash);
6496 hash = hash_int(hash, 0);
6503 /* Returns an eviction group within 'table' with the given 'id', creating one
6505 static struct eviction_group *
6506 eviction_group_find(struct oftable *table, uint32_t id)
6507 OVS_REQUIRES(ofproto_mutex)
6509 struct eviction_group *evg;
6511 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
6515 evg = xmalloc(sizeof *evg);
6516 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
6517 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
6518 eviction_group_priority(0));
6519 heap_init(&evg->rules);
6524 /* Returns an eviction priority for 'rule'. The return value should be
6525 * interpreted so that higher priorities make a rule more attractive candidates
6528 rule_eviction_priority(struct rule *rule)
6529 OVS_REQUIRES(ofproto_mutex)
6531 long long int hard_expiration;
6532 long long int idle_expiration;
6533 long long int expiration;
6534 uint32_t expiration_offset;
6536 /* Calculate time of expiration. */
6537 ovs_mutex_lock(&rule->mutex);
6538 hard_expiration = (rule->hard_timeout
6539 ? rule->modified + rule->hard_timeout * 1000
6541 idle_expiration = (rule->idle_timeout
6542 ? rule->used + rule->idle_timeout * 1000
6544 expiration = MIN(hard_expiration, idle_expiration);
6545 ovs_mutex_unlock(&rule->mutex);
6546 if (expiration == LLONG_MAX) {
6550 /* Calculate the time of expiration as a number of (approximate) seconds
6551 * after program startup.
6553 * This should work OK for program runs that last UINT32_MAX seconds or
6554 * less. Therefore, please restart OVS at least once every 136 years. */
6555 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
6557 /* Invert the expiration offset because we're using a max-heap. */
6558 return UINT32_MAX - expiration_offset;
6561 /* Adds 'rule' to an appropriate eviction group for its oftable's
6562 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
6563 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
6566 * The caller must ensure that 'rule' is not already in an eviction group. */
6568 eviction_group_add_rule(struct rule *rule)
6569 OVS_REQUIRES(ofproto_mutex)
6571 struct ofproto *ofproto = rule->ofproto;
6572 struct oftable *table = &ofproto->tables[rule->table_id];
6575 ovs_mutex_lock(&rule->mutex);
6576 has_timeout = rule->hard_timeout || rule->idle_timeout;
6577 ovs_mutex_unlock(&rule->mutex);
6579 if (table->eviction_fields && has_timeout) {
6580 struct eviction_group *evg;
6582 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
6584 rule->eviction_group = evg;
6585 heap_insert(&evg->rules, &rule->evg_node,
6586 rule_eviction_priority(rule));
6587 eviction_group_resized(table, evg);
6593 /* Initializes 'table'. */
6595 oftable_init(struct oftable *table)
6597 memset(table, 0, sizeof *table);
6598 classifier_init(&table->cls);
6599 table->max_flows = UINT_MAX;
6602 /* Destroys 'table', including its classifier and eviction groups.
6604 * The caller is responsible for freeing 'table' itself. */
6606 oftable_destroy(struct oftable *table)
6608 ovs_rwlock_rdlock(&table->cls.rwlock);
6609 ovs_assert(classifier_is_empty(&table->cls));
6610 ovs_rwlock_unlock(&table->cls.rwlock);
6611 oftable_disable_eviction(table);
6612 classifier_destroy(&table->cls);
6616 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
6617 * string, then 'table' will use its default name.
6619 * This only affects the name exposed for a table exposed through the OpenFlow
6620 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
6622 oftable_set_name(struct oftable *table, const char *name)
6624 if (name && name[0]) {
6625 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
6626 if (!table->name || strncmp(name, table->name, len)) {
6628 table->name = xmemdup0(name, len);
6636 /* oftables support a choice of two policies when adding a rule would cause the
6637 * number of flows in the table to exceed the configured maximum number: either
6638 * they can refuse to add the new flow or they can evict some existing flow.
6639 * This function configures the former policy on 'table'. */
6641 oftable_disable_eviction(struct oftable *table)
6642 OVS_REQUIRES(ofproto_mutex)
6644 if (table->eviction_fields) {
6645 struct eviction_group *evg, *next;
6647 HMAP_FOR_EACH_SAFE (evg, next, id_node,
6648 &table->eviction_groups_by_id) {
6649 eviction_group_destroy(table, evg);
6651 hmap_destroy(&table->eviction_groups_by_id);
6652 heap_destroy(&table->eviction_groups_by_size);
6654 free(table->eviction_fields);
6655 table->eviction_fields = NULL;
6656 table->n_eviction_fields = 0;
6660 /* oftables support a choice of two policies when adding a rule would cause the
6661 * number of flows in the table to exceed the configured maximum number: either
6662 * they can refuse to add the new flow or they can evict some existing flow.
6663 * This function configures the latter policy on 'table', with fairness based
6664 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
6665 * 'n_fields' as 0 disables fairness.) */
6667 oftable_enable_eviction(struct oftable *table,
6668 const struct mf_subfield *fields, size_t n_fields)
6669 OVS_REQUIRES(ofproto_mutex)
6671 struct cls_cursor cursor;
6674 if (table->eviction_fields
6675 && n_fields == table->n_eviction_fields
6677 || !memcmp(fields, table->eviction_fields,
6678 n_fields * sizeof *fields))) {
6683 oftable_disable_eviction(table);
6685 table->n_eviction_fields = n_fields;
6686 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
6688 table->eviction_group_id_basis = random_uint32();
6689 hmap_init(&table->eviction_groups_by_id);
6690 heap_init(&table->eviction_groups_by_size);
6692 ovs_rwlock_rdlock(&table->cls.rwlock);
6693 cls_cursor_init(&cursor, &table->cls, NULL);
6694 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6695 eviction_group_add_rule(rule);
6697 ovs_rwlock_unlock(&table->cls.rwlock);
6700 /* Removes 'rule' from the oftable that contains it. */
6702 oftable_remove_rule__(struct ofproto *ofproto, struct rule *rule)
6703 OVS_REQUIRES(ofproto_mutex)
6705 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
6707 ovs_rwlock_wrlock(&cls->rwlock);
6708 classifier_remove(cls, CONST_CAST(struct cls_rule *, &rule->cr));
6709 ovs_rwlock_unlock(&cls->rwlock);
6711 cookies_remove(ofproto, rule);
6713 eviction_group_remove_rule(rule);
6714 if (!list_is_empty(&rule->expirable)) {
6715 list_remove(&rule->expirable);
6717 if (!list_is_empty(&rule->meter_list_node)) {
6718 list_remove(&rule->meter_list_node);
6719 list_init(&rule->meter_list_node);
6724 oftable_remove_rule(struct rule *rule)
6725 OVS_REQUIRES(ofproto_mutex)
6727 oftable_remove_rule__(rule->ofproto, rule);
6730 /* Inserts 'rule' into its oftable, which must not already contain any rule for
6731 * the same cls_rule. */
6733 oftable_insert_rule(struct rule *rule)
6734 OVS_REQUIRES(ofproto_mutex)
6736 struct ofproto *ofproto = rule->ofproto;
6737 struct oftable *table = &ofproto->tables[rule->table_id];
6740 ovs_mutex_lock(&rule->mutex);
6741 may_expire = rule->hard_timeout || rule->idle_timeout;
6742 ovs_mutex_unlock(&rule->mutex);
6745 list_insert(&ofproto->expirable, &rule->expirable);
6748 cookies_insert(ofproto, rule);
6750 if (rule->actions->provider_meter_id != UINT32_MAX) {
6751 uint32_t meter_id = ofpacts_get_meter(rule->actions->ofpacts,
6752 rule->actions->ofpacts_len);
6753 struct meter *meter = ofproto->meters[meter_id];
6754 list_insert(&meter->rules, &rule->meter_list_node);
6756 ovs_rwlock_wrlock(&table->cls.rwlock);
6757 classifier_insert(&table->cls, CONST_CAST(struct cls_rule *, &rule->cr));
6758 ovs_rwlock_unlock(&table->cls.rwlock);
6759 eviction_group_add_rule(rule);
6762 /* unixctl commands. */
6765 ofproto_lookup(const char *name)
6767 struct ofproto *ofproto;
6769 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
6771 if (!strcmp(ofproto->name, name)) {
6779 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
6780 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6782 struct ofproto *ofproto;
6786 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
6787 ds_put_format(&results, "%s\n", ofproto->name);
6789 unixctl_command_reply(conn, ds_cstr(&results));
6790 ds_destroy(&results);
6794 ofproto_unixctl_init(void)
6796 static bool registered;
6802 unixctl_command_register("ofproto/list", "", 0, 0,
6803 ofproto_unixctl_list, NULL);
6806 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6808 * This is deprecated. It is only for compatibility with broken device drivers
6809 * in old versions of Linux that do not properly support VLANs when VLAN
6810 * devices are not used. When broken device drivers are no longer in
6811 * widespread use, we will delete these interfaces. */
6813 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
6814 * (exactly) by an OpenFlow rule in 'ofproto'. */
6816 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
6818 const struct oftable *oftable;
6820 free(ofproto->vlan_bitmap);
6821 ofproto->vlan_bitmap = bitmap_allocate(4096);
6822 ofproto->vlans_changed = false;
6824 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
6825 const struct cls_subtable *table;
6827 ovs_rwlock_rdlock(&oftable->cls.rwlock);
6828 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.subtables) {
6829 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
6830 const struct cls_rule *rule;
6832 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
6833 uint16_t vid = miniflow_get_vid(&rule->match.flow);
6834 bitmap_set1(vlan_bitmap, vid);
6835 bitmap_set1(ofproto->vlan_bitmap, vid);
6839 ovs_rwlock_unlock(&oftable->cls.rwlock);
6843 /* Returns true if new VLANs have come into use by the flow table since the
6844 * last call to ofproto_get_vlan_usage().
6846 * We don't track when old VLANs stop being used. */
6848 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
6850 return ofproto->vlans_changed;
6853 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
6854 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
6855 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
6856 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
6857 * then the VLAN device is un-enslaved. */
6859 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
6860 ofp_port_t realdev_ofp_port, int vid)
6862 struct ofport *ofport;
6865 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
6867 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
6869 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
6870 ofproto->name, vlandev_ofp_port);
6874 if (!ofproto->ofproto_class->set_realdev) {
6875 if (!vlandev_ofp_port) {
6878 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
6882 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
6884 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
6885 ofproto->name, vlandev_ofp_port,
6886 netdev_get_name(ofport->netdev), ovs_strerror(error));