2 * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3 * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
26 #include "byte-order.h"
27 #include "classifier.h"
30 #include "dynamic-string.h"
33 #include "meta-flow.h"
36 #include "ofp-actions.h"
37 #include "ofp-errors.h"
39 #include "ofp-print.h"
42 #include "ofproto-provider.h"
43 #include "openflow/nicira-ext.h"
44 #include "openflow/openflow.h"
48 #include "poll-loop.h"
54 #include "unaligned.h"
58 VLOG_DEFINE_THIS_MODULE(ofproto);
60 COVERAGE_DEFINE(ofproto_error);
61 COVERAGE_DEFINE(ofproto_flush);
62 COVERAGE_DEFINE(ofproto_no_packet_in);
63 COVERAGE_DEFINE(ofproto_packet_out);
64 COVERAGE_DEFINE(ofproto_queue_req);
65 COVERAGE_DEFINE(ofproto_recv_openflow);
66 COVERAGE_DEFINE(ofproto_reinit_ports);
67 COVERAGE_DEFINE(ofproto_uninstallable);
68 COVERAGE_DEFINE(ofproto_update_port);
71 S_OPENFLOW, /* Processing OpenFlow commands. */
72 S_EVICT, /* Evicting flows from over-limit tables. */
73 S_FLUSH, /* Deleting all flow table rules. */
76 enum ofoperation_type {
83 /* A single OpenFlow request can execute any number of operations. The
84 * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
85 * ofconn to which an error reply should be sent if necessary.
87 * ofproto initiates some operations internally. These operations are still
88 * assigned to groups but will not have an associated ofconn. */
90 struct ofproto *ofproto; /* Owning ofproto. */
91 struct list ofproto_node; /* In ofproto's "pending" list. */
92 struct list ops; /* List of "struct ofoperation"s. */
93 int n_running; /* Number of ops still pending. */
95 /* Data needed to send OpenFlow reply on failure or to send a buffered
98 * If list_is_empty(ofconn_node) then this ofopgroup never had an
99 * associated ofconn or its ofconn's connection dropped after it initiated
100 * the operation. In the latter case 'ofconn' is a wild pointer that
101 * refers to freed memory, so the 'ofconn' member must be used only if
102 * !list_is_empty(ofconn_node).
104 struct list ofconn_node; /* In ofconn's list of pending opgroups. */
105 struct ofconn *ofconn; /* ofconn for reply (but see note above). */
106 struct ofp_header *request; /* Original request (truncated at 64 bytes). */
107 uint32_t buffer_id; /* Buffer id from original request. */
110 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
111 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
112 const struct ofp_header *,
114 static void ofopgroup_submit(struct ofopgroup *);
115 static void ofopgroup_complete(struct ofopgroup *);
117 /* A single flow table operation. */
119 struct ofopgroup *group; /* Owning group. */
120 struct list group_node; /* In ofopgroup's "ops" list. */
121 struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
122 struct rule *rule; /* Rule being operated upon. */
123 enum ofoperation_type type; /* Type of operation. */
125 /* OFOPERATION_MODIFY, OFOPERATION_REPLACE: The old actions, if the actions
127 struct ofpact *ofpacts;
131 /* OFOPERATION_DELETE. */
132 enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
134 ovs_be64 flow_cookie; /* Rule's old flow cookie. */
135 uint16_t idle_timeout; /* Rule's old idle timeout. */
136 uint16_t hard_timeout; /* Rule's old hard timeout. */
137 bool send_flow_removed; /* Rule's old 'send_flow_removed'. */
138 enum ofperr error; /* 0 if no error. */
141 static struct ofoperation *ofoperation_create(struct ofopgroup *,
143 enum ofoperation_type,
144 enum ofp_flow_removed_reason);
145 static void ofoperation_destroy(struct ofoperation *);
148 static void oftable_init(struct oftable *);
149 static void oftable_destroy(struct oftable *);
151 static void oftable_set_name(struct oftable *, const char *name);
153 static void oftable_disable_eviction(struct oftable *);
154 static void oftable_enable_eviction(struct oftable *,
155 const struct mf_subfield *fields,
158 static void oftable_remove_rule(struct rule *rule) OVS_RELEASES(rule->rwlock);
159 static void oftable_remove_rule__(struct ofproto *ofproto,
160 struct classifier *cls, struct rule *rule)
161 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock);
162 static void oftable_insert_rule(struct rule *);
164 /* A set of rules within a single OpenFlow table (oftable) that have the same
165 * values for the oftable's eviction_fields. A rule to be evicted, when one is
166 * needed, is taken from the eviction group that contains the greatest number
169 * An oftable owns any number of eviction groups, each of which contains any
172 * Membership in an eviction group is imprecise, based on the hash of the
173 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
174 * That is, if two rules have different eviction_fields, but those
175 * eviction_fields hash to the same value, then they will belong to the same
176 * eviction_group anyway.
178 * (When eviction is not enabled on an oftable, we don't track any eviction
179 * groups, to save time and space.) */
180 struct eviction_group {
181 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
182 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
183 struct heap rules; /* Contains "struct rule"s. */
186 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep)
187 OVS_TRY_WRLOCK(true, (*rulep)->rwlock);
188 static void ofproto_evict(struct ofproto *);
189 static uint32_t rule_eviction_priority(struct rule *);
190 static void eviction_group_add_rule(struct rule *);
191 static void eviction_group_remove_rule(struct rule *);
194 static void ofport_destroy__(struct ofport *);
195 static void ofport_destroy(struct ofport *);
197 static void update_port(struct ofproto *, const char *devname);
198 static int init_ports(struct ofproto *);
199 static void reinit_ports(struct ofproto *);
202 static void ofproto_rule_destroy__(struct rule *);
203 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
204 static bool rule_is_modifiable(const struct rule *);
207 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
208 struct ofputil_flow_mod *,
209 const struct ofp_header *);
210 static enum ofperr modify_flows__(struct ofproto *, struct ofconn *,
211 struct ofputil_flow_mod *,
212 const struct ofp_header *, struct list *);
213 static void delete_flow__(struct rule *rule, struct ofopgroup *,
214 enum ofp_flow_removed_reason)
215 OVS_RELEASES(rule->rwlock);
216 static bool handle_openflow(struct ofconn *, const struct ofpbuf *);
217 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
218 struct ofputil_flow_mod *,
219 const struct ofp_header *);
220 static void calc_duration(long long int start, long long int now,
221 uint32_t *sec, uint32_t *nsec);
224 static uint64_t pick_datapath_id(const struct ofproto *);
225 static uint64_t pick_fallback_dpid(void);
226 static void ofproto_destroy__(struct ofproto *);
227 static void update_mtu(struct ofproto *, struct ofport *);
228 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
231 static void ofproto_unixctl_init(void);
233 /* All registered ofproto classes, in probe order. */
234 static const struct ofproto_class **ofproto_classes;
235 static size_t n_ofproto_classes;
236 static size_t allocated_ofproto_classes;
238 unsigned flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_DEFAULT;
239 unsigned n_handler_threads;
240 enum ofproto_flow_miss_model flow_miss_model = OFPROTO_HANDLE_MISS_AUTO;
242 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
243 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
245 /* Initial mappings of port to OpenFlow number mappings. */
246 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
248 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
250 /* The default value of true waits for flow restore. */
251 static bool flow_restore_wait = true;
253 /* Must be called to initialize the ofproto library.
255 * The caller may pass in 'iface_hints', which contains an shash of
256 * "iface_hint" elements indexed by the interface's name. The provider
257 * may use these hints to describe the startup configuration in order to
258 * reinitialize its state. The caller owns the provided data, so a
259 * provider will make copies of anything required. An ofproto provider
260 * will remove any existing state that is not described by the hint, and
261 * may choose to remove it all. */
263 ofproto_init(const struct shash *iface_hints)
265 struct shash_node *node;
268 ofproto_class_register(&ofproto_dpif_class);
270 /* Make a local copy, since we don't own 'iface_hints' elements. */
271 SHASH_FOR_EACH(node, iface_hints) {
272 const struct iface_hint *orig_hint = node->data;
273 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
274 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
276 new_hint->br_name = xstrdup(orig_hint->br_name);
277 new_hint->br_type = xstrdup(br_type);
278 new_hint->ofp_port = orig_hint->ofp_port;
280 shash_add(&init_ofp_ports, node->name, new_hint);
283 for (i = 0; i < n_ofproto_classes; i++) {
284 ofproto_classes[i]->init(&init_ofp_ports);
288 /* 'type' should be a normalized datapath type, as returned by
289 * ofproto_normalize_type(). Returns the corresponding ofproto_class
290 * structure, or a null pointer if there is none registered for 'type'. */
291 static const struct ofproto_class *
292 ofproto_class_find__(const char *type)
296 for (i = 0; i < n_ofproto_classes; i++) {
297 const struct ofproto_class *class = ofproto_classes[i];
302 class->enumerate_types(&types);
303 found = sset_contains(&types, type);
304 sset_destroy(&types);
310 VLOG_WARN("unknown datapath type %s", type);
314 /* Registers a new ofproto class. After successful registration, new ofprotos
315 * of that type can be created using ofproto_create(). */
317 ofproto_class_register(const struct ofproto_class *new_class)
321 for (i = 0; i < n_ofproto_classes; i++) {
322 if (ofproto_classes[i] == new_class) {
327 if (n_ofproto_classes >= allocated_ofproto_classes) {
328 ofproto_classes = x2nrealloc(ofproto_classes,
329 &allocated_ofproto_classes,
330 sizeof *ofproto_classes);
332 ofproto_classes[n_ofproto_classes++] = new_class;
336 /* Unregisters a datapath provider. 'type' must have been previously
337 * registered and not currently be in use by any ofprotos. After
338 * unregistration new datapaths of that type cannot be opened using
339 * ofproto_create(). */
341 ofproto_class_unregister(const struct ofproto_class *class)
345 for (i = 0; i < n_ofproto_classes; i++) {
346 if (ofproto_classes[i] == class) {
347 for (i++; i < n_ofproto_classes; i++) {
348 ofproto_classes[i - 1] = ofproto_classes[i];
354 VLOG_WARN("attempted to unregister an ofproto class that is not "
359 /* Clears 'types' and enumerates all registered ofproto types into it. The
360 * caller must first initialize the sset. */
362 ofproto_enumerate_types(struct sset *types)
366 for (i = 0; i < n_ofproto_classes; i++) {
367 ofproto_classes[i]->enumerate_types(types);
371 /* Returns the fully spelled out name for the given ofproto 'type'.
373 * Normalized type string can be compared with strcmp(). Unnormalized type
374 * string might be the same even if they have different spellings. */
376 ofproto_normalize_type(const char *type)
378 return type && type[0] ? type : "system";
381 /* Clears 'names' and enumerates the names of all known created ofprotos with
382 * the given 'type'. The caller must first initialize the sset. Returns 0 if
383 * successful, otherwise a positive errno value.
385 * Some kinds of datapaths might not be practically enumerable. This is not
386 * considered an error. */
388 ofproto_enumerate_names(const char *type, struct sset *names)
390 const struct ofproto_class *class = ofproto_class_find__(type);
391 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
395 ofproto_create(const char *datapath_name, const char *datapath_type,
396 struct ofproto **ofprotop)
398 const struct ofproto_class *class;
399 struct ofproto *ofproto;
405 ofproto_unixctl_init();
407 datapath_type = ofproto_normalize_type(datapath_type);
408 class = ofproto_class_find__(datapath_type);
410 VLOG_WARN("could not create datapath %s of unknown type %s",
411 datapath_name, datapath_type);
415 ofproto = class->alloc();
417 VLOG_ERR("failed to allocate datapath %s of type %s",
418 datapath_name, datapath_type);
423 memset(ofproto, 0, sizeof *ofproto);
424 ofproto->ofproto_class = class;
425 ofproto->name = xstrdup(datapath_name);
426 ofproto->type = xstrdup(datapath_type);
427 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
428 hash_string(ofproto->name, 0));
429 ofproto->datapath_id = 0;
430 ofproto->forward_bpdu = false;
431 ofproto->fallback_dpid = pick_fallback_dpid();
432 ofproto->mfr_desc = NULL;
433 ofproto->hw_desc = NULL;
434 ofproto->sw_desc = NULL;
435 ofproto->serial_desc = NULL;
436 ofproto->dp_desc = NULL;
437 ofproto->frag_handling = OFPC_FRAG_NORMAL;
438 hmap_init(&ofproto->ports);
439 shash_init(&ofproto->port_by_name);
440 simap_init(&ofproto->ofp_requests);
441 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
442 ofproto->eviction_group_timer = LLONG_MIN;
443 ofproto->tables = NULL;
444 ofproto->n_tables = 0;
445 hindex_init(&ofproto->cookies);
446 list_init(&ofproto->expirable);
447 ovs_mutex_init_recursive(&ofproto->expirable_mutex);
448 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
449 ofproto->state = S_OPENFLOW;
450 list_init(&ofproto->pending);
451 ofproto->n_pending = 0;
452 hmap_init(&ofproto->deletions);
453 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
454 ofproto->first_op = ofproto->last_op = LLONG_MIN;
455 ofproto->next_op_report = LLONG_MAX;
456 ofproto->op_backoff = LLONG_MIN;
457 ofproto->vlan_bitmap = NULL;
458 ofproto->vlans_changed = false;
459 ofproto->min_mtu = INT_MAX;
461 error = ofproto->ofproto_class->construct(ofproto);
463 VLOG_ERR("failed to open datapath %s: %s",
464 datapath_name, ovs_strerror(error));
465 ofproto_destroy__(ofproto);
469 /* The "max_ports" member should have been set by ->construct(ofproto).
470 * Port 0 is not a valid OpenFlow port, so mark that as unavailable. */
471 ofproto->ofp_port_ids = bitmap_allocate(ofproto->max_ports);
472 bitmap_set1(ofproto->ofp_port_ids, 0);
474 /* Check that hidden tables, if any, are at the end. */
475 ovs_assert(ofproto->n_tables);
476 for (i = 0; i + 1 < ofproto->n_tables; i++) {
477 enum oftable_flags flags = ofproto->tables[i].flags;
478 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
480 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
483 ofproto->datapath_id = pick_datapath_id(ofproto);
486 /* Initialize meters table. */
487 if (ofproto->ofproto_class->meter_get_features) {
488 ofproto->ofproto_class->meter_get_features(ofproto,
489 &ofproto->meter_features);
491 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
493 ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
494 * sizeof(struct meter *));
500 /* Must be called (only) by an ofproto implementation in its constructor
501 * function. See the large comment on 'construct' in struct ofproto_class for
504 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
506 struct oftable *table;
508 ovs_assert(!ofproto->n_tables);
509 ovs_assert(n_tables >= 1 && n_tables <= 255);
511 ofproto->n_tables = n_tables;
512 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
513 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
518 /* To be optionally called (only) by an ofproto implementation in its
519 * constructor function. See the large comment on 'construct' in struct
520 * ofproto_class for details.
522 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
523 * will then ensure that actions passed into the ofproto implementation will
524 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
525 * function is not called, there will be no such restriction.
527 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
528 * the 'max_ports' restriction. */
530 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
532 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
533 ofproto->max_ports = max_ports;
537 ofproto_get_datapath_id(const struct ofproto *ofproto)
539 return ofproto->datapath_id;
543 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
545 uint64_t old_dpid = p->datapath_id;
546 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
547 if (p->datapath_id != old_dpid) {
548 /* Force all active connections to reconnect, since there is no way to
549 * notify a controller that the datapath ID has changed. */
550 ofproto_reconnect_controllers(p);
555 ofproto_set_controllers(struct ofproto *p,
556 const struct ofproto_controller *controllers,
557 size_t n_controllers, uint32_t allowed_versions)
559 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
564 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
566 connmgr_set_fail_mode(p->connmgr, fail_mode);
569 /* Drops the connections between 'ofproto' and all of its controllers, forcing
570 * them to reconnect. */
572 ofproto_reconnect_controllers(struct ofproto *ofproto)
574 connmgr_reconnect(ofproto->connmgr);
577 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
578 * in-band control should guarantee access, in the same way that in-band
579 * control guarantees access to OpenFlow controllers. */
581 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
582 const struct sockaddr_in *extras, size_t n)
584 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
587 /* Sets the OpenFlow queue used by flows set up by in-band control on
588 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
589 * flows will use the default queue. */
591 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
593 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
596 /* Sets the number of flows at which eviction from the kernel flow table
599 ofproto_set_flow_eviction_threshold(unsigned threshold)
601 flow_eviction_threshold = MAX(OFPROTO_FLOW_EVICTION_THRESHOLD_MIN,
605 /* Sets the path for handling flow misses. */
607 ofproto_set_flow_miss_model(unsigned model)
609 flow_miss_model = model;
612 /* If forward_bpdu is true, the NORMAL action will forward frames with
613 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
614 * the NORMAL action will drop these frames. */
616 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
618 bool old_val = ofproto->forward_bpdu;
619 ofproto->forward_bpdu = forward_bpdu;
620 if (old_val != ofproto->forward_bpdu) {
621 if (ofproto->ofproto_class->forward_bpdu_changed) {
622 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
627 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
628 * 'idle_time', in seconds, and the maximum number of MAC table entries to
631 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
634 if (ofproto->ofproto_class->set_mac_table_config) {
635 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
640 /* Sets number of upcall handler threads. The default is
641 * (number of online cores - 1). */
643 ofproto_set_n_handler_threads(unsigned limit)
646 n_handler_threads = limit;
648 n_handler_threads = MAX(1, sysconf(_SC_NPROCESSORS_ONLN) - 1);
653 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
656 p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
660 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
662 return connmgr_set_snoops(ofproto->connmgr, snoops);
666 ofproto_set_netflow(struct ofproto *ofproto,
667 const struct netflow_options *nf_options)
669 if (nf_options && sset_is_empty(&nf_options->collectors)) {
673 if (ofproto->ofproto_class->set_netflow) {
674 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
676 return nf_options ? EOPNOTSUPP : 0;
681 ofproto_set_sflow(struct ofproto *ofproto,
682 const struct ofproto_sflow_options *oso)
684 if (oso && sset_is_empty(&oso->targets)) {
688 if (ofproto->ofproto_class->set_sflow) {
689 return ofproto->ofproto_class->set_sflow(ofproto, oso);
691 return oso ? EOPNOTSUPP : 0;
696 ofproto_set_ipfix(struct ofproto *ofproto,
697 const struct ofproto_ipfix_bridge_exporter_options *bo,
698 const struct ofproto_ipfix_flow_exporter_options *fo,
701 if (ofproto->ofproto_class->set_ipfix) {
702 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
704 return (bo || fo) ? EOPNOTSUPP : 0;
709 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
711 flow_restore_wait = flow_restore_wait_db;
715 ofproto_get_flow_restore_wait(void)
717 return flow_restore_wait;
721 /* Spanning Tree Protocol (STP) configuration. */
723 /* Configures STP on 'ofproto' using the settings defined in 's'. If
724 * 's' is NULL, disables STP.
726 * Returns 0 if successful, otherwise a positive errno value. */
728 ofproto_set_stp(struct ofproto *ofproto,
729 const struct ofproto_stp_settings *s)
731 return (ofproto->ofproto_class->set_stp
732 ? ofproto->ofproto_class->set_stp(ofproto, s)
736 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
737 * 'enabled' member of 's' is false, then the other members are not
740 * Returns 0 if successful, otherwise a positive errno value. */
742 ofproto_get_stp_status(struct ofproto *ofproto,
743 struct ofproto_stp_status *s)
745 return (ofproto->ofproto_class->get_stp_status
746 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
750 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
751 * in 's'. The caller is responsible for assigning STP port numbers
752 * (using the 'port_num' member in the range of 1 through 255, inclusive)
753 * and ensuring there are no duplicates. If the 's' is NULL, then STP
754 * is disabled on the port.
756 * Returns 0 if successful, otherwise a positive errno value.*/
758 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
759 const struct ofproto_port_stp_settings *s)
761 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
763 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
764 ofproto->name, ofp_port);
768 return (ofproto->ofproto_class->set_stp_port
769 ? ofproto->ofproto_class->set_stp_port(ofport, s)
773 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
774 * 's'. If the 'enabled' member in 's' is false, then the other members
775 * are not meaningful.
777 * Returns 0 if successful, otherwise a positive errno value.*/
779 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
780 struct ofproto_port_stp_status *s)
782 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
784 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
785 "port %"PRIu16, ofproto->name, ofp_port);
789 return (ofproto->ofproto_class->get_stp_port_status
790 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
794 /* Queue DSCP configuration. */
796 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
797 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
798 * to implement QoS. Instead, it is used to implement features which require
799 * knowledge of what queues exist on a port, and some basic information about
802 * Returns 0 if successful, otherwise a positive errno value. */
804 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
805 const struct ofproto_port_queue *queues,
808 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
811 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
812 ofproto->name, ofp_port);
816 return (ofproto->ofproto_class->set_queues
817 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
821 /* Connectivity Fault Management configuration. */
823 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
825 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
827 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
828 if (ofport && ofproto->ofproto_class->set_cfm) {
829 ofproto->ofproto_class->set_cfm(ofport, NULL);
833 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
834 * basic configuration from the configuration members in 'cfm', and the remote
835 * maintenance point ID from remote_mpid. Ignores the statistics members of
838 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
840 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
841 const struct cfm_settings *s)
843 struct ofport *ofport;
846 ofport = ofproto_get_port(ofproto, ofp_port);
848 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
849 ofproto->name, ofp_port);
853 /* XXX: For configuration simplicity, we only support one remote_mpid
854 * outside of the CFM module. It's not clear if this is the correct long
855 * term solution or not. */
856 error = (ofproto->ofproto_class->set_cfm
857 ? ofproto->ofproto_class->set_cfm(ofport, s)
860 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
861 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
862 ovs_strerror(error));
866 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
867 * 'ofproto' does not have a port 'ofp_port'. */
869 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
870 const struct smap *cfg)
872 struct ofport *ofport;
875 ofport = ofproto_get_port(ofproto, ofp_port);
877 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
878 ofproto->name, ofp_port);
882 error = (ofproto->ofproto_class->set_bfd
883 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
886 VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
887 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
888 ovs_strerror(error));
892 /* Populates 'status' with key value pairs indicating the status of the BFD
893 * session on 'ofp_port'. This information is intended to be populated in the
894 * OVS database. Has no effect if 'ofp_port' is not na OpenFlow port in
897 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
900 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
901 return (ofport && ofproto->ofproto_class->get_bfd_status
902 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
906 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
907 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
908 * 0 if LACP partner information is not current (generally indicating a
909 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
911 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
913 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
914 return (ofport && ofproto->ofproto_class->port_is_lacp_current
915 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
921 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
922 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
923 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
924 * configuration plus, if there is more than one slave, a bonding
927 * If 'aux' is already registered then this function updates its configuration
928 * to 's'. Otherwise, this function registers a new bundle.
930 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
933 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
934 const struct ofproto_bundle_settings *s)
936 return (ofproto->ofproto_class->bundle_set
937 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
941 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
942 * If no such bundle has been registered, this has no effect. */
944 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
946 return ofproto_bundle_register(ofproto, aux, NULL);
950 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
951 * If 'aux' is already registered then this function updates its configuration
952 * to 's'. Otherwise, this function registers a new mirror. */
954 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
955 const struct ofproto_mirror_settings *s)
957 return (ofproto->ofproto_class->mirror_set
958 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
962 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
963 * If no mirror has been registered, this has no effect. */
965 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
967 return ofproto_mirror_register(ofproto, aux, NULL);
970 /* Retrieves statistics from mirror associated with client data pointer
971 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
972 * 'bytes', respectively. If a particular counters is not supported,
973 * the appropriate argument is set to UINT64_MAX. */
975 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
976 uint64_t *packets, uint64_t *bytes)
978 if (!ofproto->ofproto_class->mirror_get_stats) {
979 *packets = *bytes = UINT64_MAX;
983 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
987 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
988 * which all packets are flooded, instead of using MAC learning. If
989 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
991 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
994 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
996 return (ofproto->ofproto_class->set_flood_vlans
997 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1001 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1002 * output for a mirror. */
1004 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1006 return (ofproto->ofproto_class->is_mirror_output_bundle
1007 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1011 /* Configuration of OpenFlow tables. */
1013 /* Returns the number of OpenFlow tables in 'ofproto'. */
1015 ofproto_get_n_tables(const struct ofproto *ofproto)
1017 return ofproto->n_tables;
1020 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1021 * settings from 's'. 'table_id' must be in the range 0 through the number of
1022 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1024 * For read-only tables, only the name may be configured. */
1026 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1027 const struct ofproto_table_settings *s)
1029 struct oftable *table;
1031 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1032 table = &ofproto->tables[table_id];
1034 oftable_set_name(table, s->name);
1036 if (table->flags & OFTABLE_READONLY) {
1041 oftable_enable_eviction(table, s->groups, s->n_groups);
1043 oftable_disable_eviction(table);
1046 table->max_flows = s->max_flows;
1047 ovs_rwlock_rdlock(&table->cls.rwlock);
1048 if (classifier_count(&table->cls) > table->max_flows
1049 && table->eviction_fields) {
1050 /* 'table' contains more flows than allowed. We might not be able to
1051 * evict them right away because of the asynchronous nature of flow
1052 * table changes. Schedule eviction for later. */
1053 switch (ofproto->state) {
1055 ofproto->state = S_EVICT;
1059 /* We're already deleting flows, nothing more to do. */
1063 ovs_rwlock_unlock(&table->cls.rwlock);
1067 ofproto_has_snoops(const struct ofproto *ofproto)
1069 return connmgr_has_snoops(ofproto->connmgr);
1073 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1075 connmgr_get_snoops(ofproto->connmgr, snoops);
1078 /* Deletes 'rule' from 'cls' within 'ofproto'.
1080 * The 'cls' argument is redundant (it is &ofproto->tables[rule->table_id].cls)
1081 * but it allows Clang to do better checking. */
1083 ofproto_delete_rule(struct ofproto *ofproto, struct classifier *cls,
1085 OVS_REQ_WRLOCK(cls->rwlock)
1087 struct ofopgroup *group;
1089 ovs_assert(!rule->pending);
1090 ovs_assert(cls == &ofproto->tables[rule->table_id].cls);
1092 group = ofopgroup_create_unattached(ofproto);
1093 ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1094 ovs_rwlock_wrlock(&rule->rwlock);
1095 oftable_remove_rule__(ofproto, cls, rule);
1096 ofproto->ofproto_class->rule_delete(rule);
1097 ofopgroup_submit(group);
1101 ofproto_flush__(struct ofproto *ofproto)
1103 struct oftable *table;
1105 if (ofproto->ofproto_class->flush) {
1106 ofproto->ofproto_class->flush(ofproto);
1109 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1110 struct rule *rule, *next_rule;
1111 struct cls_cursor cursor;
1113 if (table->flags & OFTABLE_HIDDEN) {
1117 ovs_rwlock_wrlock(&table->cls.rwlock);
1118 cls_cursor_init(&cursor, &table->cls, NULL);
1119 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1120 if (!rule->pending) {
1121 ofproto_delete_rule(ofproto, &table->cls, rule);
1124 ovs_rwlock_unlock(&table->cls.rwlock);
1129 ofproto_destroy__(struct ofproto *ofproto)
1131 struct oftable *table;
1133 ovs_assert(list_is_empty(&ofproto->pending));
1134 ovs_assert(!ofproto->n_pending);
1136 if (ofproto->meters) {
1137 meter_delete(ofproto, 1, ofproto->meter_features.max_meters);
1138 free(ofproto->meters);
1141 connmgr_destroy(ofproto->connmgr);
1143 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1144 free(ofproto->name);
1145 free(ofproto->type);
1146 free(ofproto->mfr_desc);
1147 free(ofproto->hw_desc);
1148 free(ofproto->sw_desc);
1149 free(ofproto->serial_desc);
1150 free(ofproto->dp_desc);
1151 hmap_destroy(&ofproto->ports);
1152 shash_destroy(&ofproto->port_by_name);
1153 bitmap_free(ofproto->ofp_port_ids);
1154 simap_destroy(&ofproto->ofp_requests);
1156 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1157 oftable_destroy(table);
1159 free(ofproto->tables);
1161 hmap_destroy(&ofproto->deletions);
1163 free(ofproto->vlan_bitmap);
1165 ovs_mutex_destroy(&ofproto->expirable_mutex);
1166 ofproto->ofproto_class->dealloc(ofproto);
1170 ofproto_destroy(struct ofproto *p)
1172 struct ofport *ofport, *next_ofport;
1179 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1180 ofport_destroy(ofport);
1183 p->ofproto_class->destruct(p);
1184 ofproto_destroy__(p);
1187 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1188 * kernel datapath, for example, this destroys the datapath in the kernel, and
1189 * with the netdev-based datapath, it tears down the data structures that
1190 * represent the datapath.
1192 * The datapath should not be currently open as an ofproto. */
1194 ofproto_delete(const char *name, const char *type)
1196 const struct ofproto_class *class = ofproto_class_find__(type);
1197 return (!class ? EAFNOSUPPORT
1198 : !class->del ? EACCES
1199 : class->del(type, name));
1203 process_port_change(struct ofproto *ofproto, int error, char *devname)
1205 if (error == ENOBUFS) {
1206 reinit_ports(ofproto);
1207 } else if (!error) {
1208 update_port(ofproto, devname);
1214 ofproto_type_run(const char *datapath_type)
1216 const struct ofproto_class *class;
1219 datapath_type = ofproto_normalize_type(datapath_type);
1220 class = ofproto_class_find__(datapath_type);
1222 error = class->type_run ? class->type_run(datapath_type) : 0;
1223 if (error && error != EAGAIN) {
1224 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1225 datapath_type, ovs_strerror(error));
1231 ofproto_type_run_fast(const char *datapath_type)
1233 const struct ofproto_class *class;
1236 datapath_type = ofproto_normalize_type(datapath_type);
1237 class = ofproto_class_find__(datapath_type);
1239 error = class->type_run_fast ? class->type_run_fast(datapath_type) : 0;
1240 if (error && error != EAGAIN) {
1241 VLOG_ERR_RL(&rl, "%s: type_run_fast failed (%s)",
1242 datapath_type, ovs_strerror(error));
1248 ofproto_type_wait(const char *datapath_type)
1250 const struct ofproto_class *class;
1252 datapath_type = ofproto_normalize_type(datapath_type);
1253 class = ofproto_class_find__(datapath_type);
1255 if (class->type_wait) {
1256 class->type_wait(datapath_type);
1261 ofproto_run(struct ofproto *p)
1263 struct sset changed_netdevs;
1264 const char *changed_netdev;
1265 struct ofport *ofport;
1268 error = p->ofproto_class->run(p);
1269 if (error && error != EAGAIN) {
1270 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1273 /* Restore the eviction group heap invariant occasionally. */
1274 if (p->eviction_group_timer < time_msec()) {
1277 p->eviction_group_timer = time_msec() + 1000;
1279 for (i = 0; i < p->n_tables; i++) {
1280 struct oftable *table = &p->tables[i];
1281 struct eviction_group *evg;
1282 struct cls_cursor cursor;
1286 if (!table->eviction_fields) {
1290 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1291 heap_rebuild(&evg->rules);
1294 ovs_rwlock_rdlock(&table->cls.rwlock);
1295 cls_cursor_init(&cursor, &table->cls, &cr);
1296 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1297 if (!rule->eviction_group
1298 && (rule->idle_timeout || rule->hard_timeout)) {
1299 eviction_group_add_rule(rule);
1302 ovs_rwlock_unlock(&table->cls.rwlock);
1306 if (p->ofproto_class->port_poll) {
1309 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1310 process_port_change(p, error, devname);
1314 /* Update OpenFlow port status for any port whose netdev has changed.
1316 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1317 * destroyed, so it's not safe to update ports directly from the
1318 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1319 * need this two-phase approach. */
1320 sset_init(&changed_netdevs);
1321 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1322 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1323 if (ofport->change_seq != change_seq) {
1324 ofport->change_seq = change_seq;
1325 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1328 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1329 update_port(p, changed_netdev);
1331 sset_destroy(&changed_netdevs);
1335 connmgr_run(p->connmgr, handle_openflow);
1339 connmgr_run(p->connmgr, NULL);
1341 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1342 p->state = S_OPENFLOW;
1347 connmgr_run(p->connmgr, NULL);
1349 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1350 connmgr_flushed(p->connmgr);
1351 p->state = S_OPENFLOW;
1359 if (time_msec() >= p->next_op_report) {
1360 long long int ago = (time_msec() - p->first_op) / 1000;
1361 long long int interval = (p->last_op - p->first_op) / 1000;
1365 ds_put_format(&s, "%d flow_mods ",
1366 p->n_add + p->n_delete + p->n_modify);
1367 if (interval == ago) {
1368 ds_put_format(&s, "in the last %lld s", ago);
1369 } else if (interval) {
1370 ds_put_format(&s, "in the %lld s starting %lld s ago",
1373 ds_put_format(&s, "%lld s ago", ago);
1376 ds_put_cstr(&s, " (");
1378 ds_put_format(&s, "%d adds, ", p->n_add);
1381 ds_put_format(&s, "%d deletes, ", p->n_delete);
1384 ds_put_format(&s, "%d modifications, ", p->n_modify);
1387 ds_put_char(&s, ')');
1389 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1392 p->n_add = p->n_delete = p->n_modify = 0;
1393 p->next_op_report = LLONG_MAX;
1399 /* Performs periodic activity required by 'ofproto' that needs to be done
1400 * with the least possible latency.
1402 * It makes sense to call this function a couple of times per poll loop, to
1403 * provide a significant performance boost on some benchmarks with the
1404 * ofproto-dpif implementation. */
1406 ofproto_run_fast(struct ofproto *p)
1410 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1411 if (error && error != EAGAIN) {
1412 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1413 p->name, ovs_strerror(error));
1419 ofproto_wait(struct ofproto *p)
1421 struct ofport *ofport;
1423 p->ofproto_class->wait(p);
1424 if (p->ofproto_class->port_poll_wait) {
1425 p->ofproto_class->port_poll_wait(p);
1428 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1429 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1430 poll_immediate_wake();
1436 connmgr_wait(p->connmgr, true);
1441 connmgr_wait(p->connmgr, false);
1442 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1443 poll_immediate_wake();
1450 ofproto_is_alive(const struct ofproto *p)
1452 return connmgr_has_controllers(p->connmgr);
1455 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1456 * memory_report(). */
1458 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1460 const struct oftable *table;
1461 unsigned int n_rules;
1463 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1464 simap_increase(usage, "ops",
1465 ofproto->n_pending + hmap_count(&ofproto->deletions));
1468 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1469 ovs_rwlock_rdlock(&table->cls.rwlock);
1470 n_rules += classifier_count(&table->cls);
1471 ovs_rwlock_unlock(&table->cls.rwlock);
1473 simap_increase(usage, "rules", n_rules);
1475 if (ofproto->ofproto_class->get_memory_usage) {
1476 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1479 connmgr_get_memory_usage(ofproto->connmgr, usage);
1483 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1486 connmgr_get_controller_info(ofproto->connmgr, info);
1490 ofproto_free_ofproto_controller_info(struct shash *info)
1492 connmgr_free_controller_info(info);
1495 /* Makes a deep copy of 'old' into 'port'. */
1497 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1499 port->name = xstrdup(old->name);
1500 port->type = xstrdup(old->type);
1501 port->ofp_port = old->ofp_port;
1504 /* Frees memory allocated to members of 'ofproto_port'.
1506 * Do not call this function on an ofproto_port obtained from
1507 * ofproto_port_dump_next(): that function retains ownership of the data in the
1510 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1512 free(ofproto_port->name);
1513 free(ofproto_port->type);
1516 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1518 * This function provides no status indication. An error status for the entire
1519 * dump operation is provided when it is completed by calling
1520 * ofproto_port_dump_done().
1523 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1524 const struct ofproto *ofproto)
1526 dump->ofproto = ofproto;
1527 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1531 /* Attempts to retrieve another port from 'dump', which must have been created
1532 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1533 * 'port' and returns true. On failure, returns false.
1535 * Failure might indicate an actual error or merely that the last port has been
1536 * dumped. An error status for the entire dump operation is provided when it
1537 * is completed by calling ofproto_port_dump_done().
1539 * The ofproto owns the data stored in 'port'. It will remain valid until at
1540 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1541 * ofproto_port_dump_done(). */
1543 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1544 struct ofproto_port *port)
1546 const struct ofproto *ofproto = dump->ofproto;
1552 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1555 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1561 /* Completes port table dump operation 'dump', which must have been created
1562 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1563 * error-free, otherwise a positive errno value describing the problem. */
1565 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1567 const struct ofproto *ofproto = dump->ofproto;
1569 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1572 return dump->error == EOF ? 0 : dump->error;
1575 /* Returns the type to pass to netdev_open() when a datapath of type
1576 * 'datapath_type' has a port of type 'port_type', for a few special
1577 * cases when a netdev type differs from a port type. For example, when
1578 * using the userspace datapath, a port of type "internal" needs to be
1581 * Returns either 'type' itself or a string literal, which must not be
1584 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1586 const struct ofproto_class *class;
1588 datapath_type = ofproto_normalize_type(datapath_type);
1589 class = ofproto_class_find__(datapath_type);
1594 return (class->port_open_type
1595 ? class->port_open_type(datapath_type, port_type)
1599 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1600 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1601 * the port's OpenFlow port number.
1603 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1604 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1605 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1606 * 'ofp_portp' is non-null). */
1608 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1609 ofp_port_t *ofp_portp)
1611 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1614 error = ofproto->ofproto_class->port_add(ofproto, netdev);
1616 const char *netdev_name = netdev_get_name(netdev);
1618 simap_put(&ofproto->ofp_requests, netdev_name,
1619 ofp_to_u16(ofp_port));
1620 update_port(ofproto, netdev_name);
1623 struct ofproto_port ofproto_port;
1625 ofproto_port_query_by_name(ofproto, netdev_get_name(netdev),
1627 *ofp_portp = error ? OFPP_NONE : ofproto_port.ofp_port;
1628 ofproto_port_destroy(&ofproto_port);
1633 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1634 * initializes '*port' appropriately; on failure, returns a positive errno
1637 * The caller owns the data in 'ofproto_port' and must free it with
1638 * ofproto_port_destroy() when it is no longer needed. */
1640 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1641 struct ofproto_port *port)
1645 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1647 memset(port, 0, sizeof *port);
1652 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1653 * Returns 0 if successful, otherwise a positive errno. */
1655 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1657 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1658 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1659 struct simap_node *ofp_request_node;
1662 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1663 if (ofp_request_node) {
1664 simap_delete(&ofproto->ofp_requests, ofp_request_node);
1667 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1668 if (!error && ofport) {
1669 /* 'name' is the netdev's name and update_port() is going to close the
1670 * netdev. Just in case update_port() refers to 'name' after it
1671 * destroys 'ofport', make a copy of it around the update_port()
1673 char *devname = xstrdup(name);
1674 update_port(ofproto, devname);
1680 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1681 * performs the 'n_actions' actions in 'actions'. The new flow will not
1684 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1685 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1686 * controllers; otherwise, it will be hidden.
1688 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1690 * This is a helper function for in-band control and fail-open. */
1692 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1693 unsigned int priority,
1694 const struct ofpact *ofpacts, size_t ofpacts_len)
1696 const struct rule *rule;
1698 ovs_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1699 rule = rule_from_cls_rule(classifier_find_match_exactly(
1700 &ofproto->tables[0].cls, match, priority));
1701 ovs_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1702 if (!rule || !ofpacts_equal(rule->ofpacts, rule->ofpacts_len,
1703 ofpacts, ofpacts_len)) {
1704 struct ofputil_flow_mod fm;
1706 memset(&fm, 0, sizeof fm);
1708 fm.priority = priority;
1709 fm.buffer_id = UINT32_MAX;
1710 fm.ofpacts = xmemdup(ofpacts, ofpacts_len);
1711 fm.ofpacts_len = ofpacts_len;
1712 add_flow(ofproto, NULL, &fm, NULL);
1717 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1718 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1719 * operation cannot be initiated now but may be retried later.
1721 * This is a helper function for in-band control and fail-open. */
1723 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1725 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1728 /* Searches for a rule with matching criteria exactly equal to 'target' in
1729 * ofproto's table 0 and, if it finds one, deletes it.
1731 * This is a helper function for in-band control and fail-open. */
1733 ofproto_delete_flow(struct ofproto *ofproto,
1734 const struct match *target, unsigned int priority)
1736 struct classifier *cls = &ofproto->tables[0].cls;
1739 ovs_rwlock_rdlock(&cls->rwlock);
1740 rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
1742 ovs_rwlock_unlock(&cls->rwlock);
1744 /* No such rule -> success. */
1746 } else if (rule->pending) {
1747 /* An operation on the rule is already pending -> failure.
1748 * Caller must retry later if it's important. */
1751 /* Initiate deletion -> success. */
1752 ovs_rwlock_wrlock(&cls->rwlock);
1753 ofproto_delete_rule(ofproto, cls, rule);
1754 ovs_rwlock_unlock(&cls->rwlock);
1761 /* Starts the process of deleting all of the flows from all of ofproto's flow
1762 * tables and then reintroducing the flows required by in-band control and
1763 * fail-open. The process will complete in a later call to ofproto_run(). */
1765 ofproto_flush_flows(struct ofproto *ofproto)
1767 COVERAGE_INC(ofproto_flush);
1768 ofproto->state = S_FLUSH;
1772 reinit_ports(struct ofproto *p)
1774 struct ofproto_port_dump dump;
1775 struct sset devnames;
1776 struct ofport *ofport;
1777 struct ofproto_port ofproto_port;
1778 const char *devname;
1780 COVERAGE_INC(ofproto_reinit_ports);
1782 sset_init(&devnames);
1783 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1784 sset_add(&devnames, netdev_get_name(ofport->netdev));
1786 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1787 sset_add(&devnames, ofproto_port.name);
1790 SSET_FOR_EACH (devname, &devnames) {
1791 update_port(p, devname);
1793 sset_destroy(&devnames);
1797 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
1801 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
1802 port_idx = port_idx ? port_idx : UINT16_MAX;
1804 if (port_idx >= ofproto->max_ports
1805 || bitmap_is_set(ofproto->ofp_port_ids, port_idx)) {
1806 uint16_t end_port_no = ofproto->alloc_port_no;
1808 /* Search for a free OpenFlow port number. We try not to
1809 * immediately reuse them to prevent problems due to old
1812 if (++ofproto->alloc_port_no >= ofproto->max_ports) {
1813 ofproto->alloc_port_no = 0;
1815 if (!bitmap_is_set(ofproto->ofp_port_ids,
1816 ofproto->alloc_port_no)) {
1817 port_idx = ofproto->alloc_port_no;
1820 if (ofproto->alloc_port_no == end_port_no) {
1825 bitmap_set1(ofproto->ofp_port_ids, port_idx);
1826 return u16_to_ofp(port_idx);
1830 dealloc_ofp_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
1832 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
1833 bitmap_set0(ofproto->ofp_port_ids, ofp_to_u16(ofp_port));
1837 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1838 * pointer if the netdev cannot be opened. On success, also fills in
1840 static struct netdev *
1841 ofport_open(struct ofproto *ofproto,
1842 struct ofproto_port *ofproto_port,
1843 struct ofputil_phy_port *pp)
1845 enum netdev_flags flags;
1846 struct netdev *netdev;
1849 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1851 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1852 "cannot be opened (%s)",
1854 ofproto_port->name, ofproto_port->ofp_port,
1855 ofproto_port->name, ovs_strerror(error));
1859 if (ofproto_port->ofp_port == OFPP_NONE) {
1860 if (!strcmp(ofproto->name, ofproto_port->name)) {
1861 ofproto_port->ofp_port = OFPP_LOCAL;
1863 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
1864 ofproto_port->name);
1867 pp->port_no = ofproto_port->ofp_port;
1868 netdev_get_etheraddr(netdev, pp->hw_addr);
1869 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1870 netdev_get_flags(netdev, &flags);
1871 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1872 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1873 netdev_get_features(netdev, &pp->curr, &pp->advertised,
1874 &pp->supported, &pp->peer);
1875 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
1876 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
1881 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
1882 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1885 ofport_equal(const struct ofputil_phy_port *a,
1886 const struct ofputil_phy_port *b)
1888 return (eth_addr_equals(a->hw_addr, b->hw_addr)
1889 && a->state == b->state
1890 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1891 && a->curr == b->curr
1892 && a->advertised == b->advertised
1893 && a->supported == b->supported
1894 && a->peer == b->peer
1895 && a->curr_speed == b->curr_speed
1896 && a->max_speed == b->max_speed);
1899 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1900 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1901 * one with the same name or port number). */
1903 ofport_install(struct ofproto *p,
1904 struct netdev *netdev, const struct ofputil_phy_port *pp)
1906 const char *netdev_name = netdev_get_name(netdev);
1907 struct ofport *ofport;
1910 /* Create ofport. */
1911 ofport = p->ofproto_class->port_alloc();
1916 ofport->ofproto = p;
1917 ofport->netdev = netdev;
1918 ofport->change_seq = netdev_change_seq(netdev);
1920 ofport->ofp_port = pp->port_no;
1921 ofport->created = time_msec();
1923 /* Add port to 'p'. */
1924 hmap_insert(&p->ports, &ofport->hmap_node,
1925 hash_ofp_port(ofport->ofp_port));
1926 shash_add(&p->port_by_name, netdev_name, ofport);
1928 update_mtu(p, ofport);
1930 /* Let the ofproto_class initialize its private data. */
1931 error = p->ofproto_class->port_construct(ofport);
1935 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
1939 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
1940 p->name, netdev_name, ovs_strerror(error));
1942 ofport_destroy__(ofport);
1944 netdev_close(netdev);
1948 /* Removes 'ofport' from 'p' and destroys it. */
1950 ofport_remove(struct ofport *ofport)
1952 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
1954 ofport_destroy(ofport);
1957 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1960 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1962 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1964 ofport_remove(port);
1968 /* Updates 'port' with new 'pp' description.
1970 * Does not handle a name or port number change. The caller must implement
1971 * such a change as a delete followed by an add. */
1973 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
1975 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
1976 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
1977 | (pp->config & OFPUTIL_PC_PORT_DOWN));
1978 port->pp.state = pp->state;
1979 port->pp.curr = pp->curr;
1980 port->pp.advertised = pp->advertised;
1981 port->pp.supported = pp->supported;
1982 port->pp.peer = pp->peer;
1983 port->pp.curr_speed = pp->curr_speed;
1984 port->pp.max_speed = pp->max_speed;
1986 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
1989 /* Update OpenFlow 'state' in 'port' and notify controller. */
1991 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
1993 if (port->pp.state != state) {
1994 port->pp.state = state;
1995 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
2001 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2003 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2005 if (port->ofproto->ofproto_class->set_realdev) {
2006 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2008 if (port->ofproto->ofproto_class->set_stp_port) {
2009 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2011 if (port->ofproto->ofproto_class->set_cfm) {
2012 port->ofproto->ofproto_class->set_cfm(port, NULL);
2014 if (port->ofproto->ofproto_class->bundle_remove) {
2015 port->ofproto->ofproto_class->bundle_remove(port);
2021 ofport_destroy__(struct ofport *port)
2023 struct ofproto *ofproto = port->ofproto;
2024 const char *name = netdev_get_name(port->netdev);
2026 hmap_remove(&ofproto->ports, &port->hmap_node);
2027 shash_delete(&ofproto->port_by_name,
2028 shash_find(&ofproto->port_by_name, name));
2030 netdev_close(port->netdev);
2031 ofproto->ofproto_class->port_dealloc(port);
2035 ofport_destroy(struct ofport *port)
2038 dealloc_ofp_port(port->ofproto, port->ofp_port);
2039 port->ofproto->ofproto_class->port_destruct(port);
2040 ofport_destroy__(port);
2045 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2047 struct ofport *port;
2049 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2051 if (port->ofp_port == ofp_port) {
2059 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2061 struct ofproto *ofproto = port->ofproto;
2064 if (ofproto->ofproto_class->port_get_stats) {
2065 error = ofproto->ofproto_class->port_get_stats(port, stats);
2074 update_port(struct ofproto *ofproto, const char *name)
2076 struct ofproto_port ofproto_port;
2077 struct ofputil_phy_port pp;
2078 struct netdev *netdev;
2079 struct ofport *port;
2081 COVERAGE_INC(ofproto_update_port);
2083 /* Fetch 'name''s location and properties from the datapath. */
2084 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2085 ? ofport_open(ofproto, &ofproto_port, &pp)
2089 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2090 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2091 struct netdev *old_netdev = port->netdev;
2093 /* 'name' hasn't changed location. Any properties changed? */
2094 if (!ofport_equal(&port->pp, &pp)) {
2095 ofport_modified(port, &pp);
2098 update_mtu(ofproto, port);
2100 /* Install the newly opened netdev in case it has changed.
2101 * Don't close the old netdev yet in case port_modified has to
2102 * remove a retained reference to it.*/
2103 port->netdev = netdev;
2104 port->change_seq = netdev_change_seq(netdev);
2106 if (port->ofproto->ofproto_class->port_modified) {
2107 port->ofproto->ofproto_class->port_modified(port);
2110 netdev_close(old_netdev);
2112 /* If 'port' is nonnull then its name differs from 'name' and thus
2113 * we should delete it. If we think there's a port named 'name'
2114 * then its port number must be wrong now so delete it too. */
2116 ofport_remove(port);
2118 ofport_remove_with_name(ofproto, name);
2119 ofport_install(ofproto, netdev, &pp);
2122 /* Any port named 'name' is gone now. */
2123 ofport_remove_with_name(ofproto, name);
2125 ofproto_port_destroy(&ofproto_port);
2129 init_ports(struct ofproto *p)
2131 struct ofproto_port_dump dump;
2132 struct ofproto_port ofproto_port;
2133 struct shash_node *node, *next;
2135 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2136 const char *name = ofproto_port.name;
2138 if (shash_find(&p->port_by_name, name)) {
2139 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2142 struct ofputil_phy_port pp;
2143 struct netdev *netdev;
2145 /* Check if an OpenFlow port number had been requested. */
2146 node = shash_find(&init_ofp_ports, name);
2148 const struct iface_hint *iface_hint = node->data;
2149 simap_put(&p->ofp_requests, name,
2150 ofp_to_u16(iface_hint->ofp_port));
2153 netdev = ofport_open(p, &ofproto_port, &pp);
2155 ofport_install(p, netdev, &pp);
2156 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2157 p->alloc_port_no = MAX(p->alloc_port_no,
2158 ofp_to_u16(ofproto_port.ofp_port));
2164 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2165 struct iface_hint *iface_hint = node->data;
2167 if (!strcmp(iface_hint->br_name, p->name)) {
2168 free(iface_hint->br_name);
2169 free(iface_hint->br_type);
2171 shash_delete(&init_ofp_ports, node);
2178 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2179 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2181 find_min_mtu(struct ofproto *p)
2183 struct ofport *ofport;
2186 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2187 struct netdev *netdev = ofport->netdev;
2190 /* Skip any internal ports, since that's what we're trying to
2192 if (!strcmp(netdev_get_type(netdev), "internal")) {
2196 if (netdev_get_mtu(netdev, &dev_mtu)) {
2199 if (!mtu || dev_mtu < mtu) {
2204 return mtu ? mtu: ETH_PAYLOAD_MAX;
2207 /* Update MTU of all datapath devices on 'p' to the minimum of the
2208 * non-datapath ports in event of 'port' added or changed. */
2210 update_mtu(struct ofproto *p, struct ofport *port)
2212 struct ofport *ofport;
2213 struct netdev *netdev = port->netdev;
2214 int dev_mtu, old_min;
2216 if (netdev_get_mtu(netdev, &dev_mtu)) {
2220 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2221 if (dev_mtu > p->min_mtu) {
2222 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2223 dev_mtu = p->min_mtu;
2226 port->mtu = dev_mtu;
2230 /* For non-internal port find new min mtu. */
2231 old_min = p->min_mtu;
2232 port->mtu = dev_mtu;
2233 p->min_mtu = find_min_mtu(p);
2234 if (p->min_mtu == old_min) {
2238 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2239 struct netdev *netdev = ofport->netdev;
2241 if (!strcmp(netdev_get_type(netdev), "internal")) {
2242 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2243 ofport->mtu = p->min_mtu;
2250 ofproto_rule_destroy__(struct rule *rule)
2253 rule->ofproto->ofproto_class->rule_destruct(rule);
2254 cls_rule_destroy(&rule->cr);
2255 free(rule->ofpacts);
2256 ovs_mutex_destroy(&rule->timeout_mutex);
2257 ovs_rwlock_destroy(&rule->rwlock);
2258 rule->ofproto->ofproto_class->rule_dealloc(rule);
2262 /* This function allows an ofproto implementation to destroy any rules that
2263 * remain when its ->destruct() function is called.. This function implements
2264 * steps 4.4 and 4.5 in the section titled "Rule Life Cycle" in
2265 * ofproto-provider.h.
2267 * This function should only be called from an ofproto implementation's
2268 * ->destruct() function. It is not suitable elsewhere. */
2270 ofproto_rule_delete(struct ofproto *ofproto, struct classifier *cls,
2272 OVS_REQ_WRLOCK(cls->rwlock)
2274 ofproto_delete_rule(ofproto, cls, rule);
2277 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2278 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2280 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2282 return (port == OFPP_ANY
2283 || ofpacts_output_to_port(rule->ofpacts, rule->ofpacts_len, port));
2286 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2287 * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2289 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2291 if (ofproto_rule_has_out_port(op->rule, out_port)) {
2296 case OFOPERATION_ADD:
2297 case OFOPERATION_DELETE:
2300 case OFOPERATION_MODIFY:
2301 case OFOPERATION_REPLACE:
2302 return ofpacts_output_to_port(op->ofpacts, op->ofpacts_len, out_port);
2308 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2309 * statistics appropriately.
2311 * 'packet' doesn't necessarily have to match 'rule'. 'rule' will be credited
2312 * with statistics for 'packet' either way.
2314 * Takes ownership of 'packet'. */
2316 rule_execute(struct rule *rule, ofp_port_t in_port, struct ofpbuf *packet)
2319 union flow_in_port in_port_;
2321 in_port_.ofp_port = in_port;
2322 flow_extract(packet, 0, 0, NULL, &in_port_, &flow);
2323 return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
2326 /* Returns true if 'rule' should be hidden from the controller.
2328 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2329 * (e.g. by in-band control) and are intentionally hidden from the
2332 ofproto_rule_is_hidden(const struct rule *rule)
2334 return rule->cr.priority > UINT16_MAX;
2337 static enum oftable_flags
2338 rule_get_flags(const struct rule *rule)
2340 return rule->ofproto->tables[rule->table_id].flags;
2344 rule_is_modifiable(const struct rule *rule)
2346 return !(rule_get_flags(rule) & OFTABLE_READONLY);
2350 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2352 ofconn_send_reply(ofconn, make_echo_reply(oh));
2357 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2359 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2360 struct ofputil_switch_features features;
2361 struct ofport *port;
2367 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2369 ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2371 /* Count only non-hidden tables in the number of tables. (Hidden tables,
2372 * if present, are always at the end.) */
2373 n_tables = ofproto->n_tables;
2374 for (i = 0; i < ofproto->n_tables; i++) {
2375 if (ofproto->tables[i].flags & OFTABLE_HIDDEN) {
2381 features.datapath_id = ofproto->datapath_id;
2382 features.n_buffers = pktbuf_capacity();
2383 features.n_tables = n_tables;
2384 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2385 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2387 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2389 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2390 features.auxiliary_id = 0;
2391 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2393 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2394 ofputil_put_switch_features_port(&port->pp, b);
2397 ofconn_send_reply(ofconn, b);
2402 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2404 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2405 struct ofp_switch_config *osc;
2406 enum ofp_config_flags flags;
2410 buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2411 osc = ofpbuf_put_uninit(buf, sizeof *osc);
2412 flags = ofproto->frag_handling;
2413 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2414 if (oh->version < OFP13_VERSION
2415 && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2416 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2418 osc->flags = htons(flags);
2419 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2420 ofconn_send_reply(ofconn, buf);
2426 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2428 const struct ofp_switch_config *osc = ofpmsg_body(oh);
2429 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2430 uint16_t flags = ntohs(osc->flags);
2432 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2433 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2434 enum ofp_config_flags cur = ofproto->frag_handling;
2435 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2437 ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2439 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2440 ofproto->frag_handling = next;
2442 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2444 ofputil_frag_handling_to_string(next));
2448 /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2449 ofconn_set_invalid_ttl_to_controller(ofconn,
2450 (oh->version < OFP13_VERSION
2451 && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2453 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2458 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2459 * error message code for the caller to propagate upward. Otherwise, returns
2462 * The log message mentions 'msg_type'. */
2464 reject_slave_controller(struct ofconn *ofconn)
2466 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2467 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2468 return OFPERR_OFPBRC_EPERM;
2474 /* Finds the OFPACT_METER action, if any, in the 'ofpacts_len' bytes of
2475 * 'ofpacts'. If found, returns its meter ID; if not, returns 0.
2477 * This function relies on the order of 'ofpacts' being correct (as checked by
2478 * ofpacts_verify()). */
2480 find_meter(const struct ofpact ofpacts[], size_t ofpacts_len)
2482 const struct ofpact *a;
2484 OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
2485 enum ovs_instruction_type inst;
2487 inst = ovs_instruction_type_from_ofpact_type(a->type);
2488 if (a->type == OFPACT_METER) {
2489 return ofpact_get_METER(a)->meter_id;
2490 } else if (inst > OVSINST_OFPIT13_METER) {
2498 /* Checks that the 'ofpacts_len' bytes of actions in 'ofpacts' are appropriate
2499 * for a packet with the prerequisites satisfied by 'flow' in table 'table_id'.
2500 * 'flow' may be temporarily modified, but is restored at return.
2503 ofproto_check_ofpacts(struct ofproto *ofproto,
2504 const struct ofpact ofpacts[], size_t ofpacts_len,
2505 struct flow *flow, uint8_t table_id)
2510 error = ofpacts_check(ofpacts, ofpacts_len, flow,
2511 u16_to_ofp(ofproto->max_ports), table_id);
2516 mid = find_meter(ofpacts, ofpacts_len);
2517 if (mid && ofproto_get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2518 return OFPERR_OFPMMFC_INVALID_METER;
2524 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2526 struct ofproto *p = ofconn_get_ofproto(ofconn);
2527 struct ofputil_packet_out po;
2528 struct ofpbuf *payload;
2529 uint64_t ofpacts_stub[1024 / 8];
2530 struct ofpbuf ofpacts;
2532 union flow_in_port in_port_;
2535 COVERAGE_INC(ofproto_packet_out);
2537 error = reject_slave_controller(ofconn);
2542 /* Decode message. */
2543 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2544 error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2546 goto exit_free_ofpacts;
2548 if (ofp_to_u16(po.in_port) >= p->max_ports
2549 && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2550 error = OFPERR_OFPBRC_BAD_PORT;
2551 goto exit_free_ofpacts;
2556 if (po.buffer_id != UINT32_MAX) {
2557 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2558 if (error || !payload) {
2559 goto exit_free_ofpacts;
2562 /* Ensure that the L3 header is 32-bit aligned. */
2563 payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2566 /* Verify actions against packet, then send packet if successful. */
2567 in_port_.ofp_port = po.in_port;
2568 flow_extract(payload, 0, 0, NULL, &in_port_, &flow);
2569 error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len, &flow, 0);
2571 error = p->ofproto_class->packet_out(p, payload, &flow,
2572 po.ofpacts, po.ofpacts_len);
2574 ofpbuf_delete(payload);
2577 ofpbuf_uninit(&ofpacts);
2583 update_port_config(struct ofport *port,
2584 enum ofputil_port_config config,
2585 enum ofputil_port_config mask)
2587 enum ofputil_port_config old_config = port->pp.config;
2588 enum ofputil_port_config toggle;
2590 toggle = (config ^ port->pp.config) & mask;
2591 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2592 if (config & OFPUTIL_PC_PORT_DOWN) {
2593 netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL);
2595 netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL);
2597 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2600 port->pp.config ^= toggle;
2601 if (port->pp.config != old_config) {
2602 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2607 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2609 struct ofproto *p = ofconn_get_ofproto(ofconn);
2610 struct ofputil_port_mod pm;
2611 struct ofport *port;
2614 error = reject_slave_controller(ofconn);
2619 error = ofputil_decode_port_mod(oh, &pm);
2624 port = ofproto_get_port(p, pm.port_no);
2626 return OFPERR_OFPPMFC_BAD_PORT;
2627 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2628 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2630 update_port_config(port, pm.config, pm.mask);
2632 netdev_set_advertisements(port->netdev, pm.advertise);
2639 handle_desc_stats_request(struct ofconn *ofconn,
2640 const struct ofp_header *request)
2642 static const char *default_mfr_desc = "Nicira, Inc.";
2643 static const char *default_hw_desc = "Open vSwitch";
2644 static const char *default_sw_desc = VERSION;
2645 static const char *default_serial_desc = "None";
2646 static const char *default_dp_desc = "None";
2648 struct ofproto *p = ofconn_get_ofproto(ofconn);
2649 struct ofp_desc_stats *ods;
2652 msg = ofpraw_alloc_stats_reply(request, 0);
2653 ods = ofpbuf_put_zeros(msg, sizeof *ods);
2654 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
2655 sizeof ods->mfr_desc);
2656 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
2657 sizeof ods->hw_desc);
2658 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
2659 sizeof ods->sw_desc);
2660 ovs_strlcpy(ods->serial_num,
2661 p->serial_desc ? p->serial_desc : default_serial_desc,
2662 sizeof ods->serial_num);
2663 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
2664 sizeof ods->dp_desc);
2665 ofconn_send_reply(ofconn, msg);
2671 handle_table_stats_request(struct ofconn *ofconn,
2672 const struct ofp_header *request)
2674 struct ofproto *p = ofconn_get_ofproto(ofconn);
2675 struct ofp12_table_stats *ots;
2680 /* Set up default values.
2682 * ofp12_table_stats is used as a generic structure as
2683 * it is able to hold all the fields for ofp10_table_stats
2684 * and ofp11_table_stats (and of course itself).
2686 ots = xcalloc(p->n_tables, sizeof *ots);
2687 for (i = 0; i < p->n_tables; i++) {
2688 ots[i].table_id = i;
2689 sprintf(ots[i].name, "table%zu", i);
2690 ots[i].match = htonll(OFPXMT12_MASK);
2691 ots[i].wildcards = htonll(OFPXMT12_MASK);
2692 ots[i].write_actions = htonl(OFPAT11_OUTPUT);
2693 ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
2694 ots[i].write_setfields = htonll(OFPXMT12_MASK);
2695 ots[i].apply_setfields = htonll(OFPXMT12_MASK);
2696 ots[i].metadata_match = htonll(UINT64_MAX);
2697 ots[i].metadata_write = htonll(UINT64_MAX);
2698 ots[i].instructions = htonl(OFPIT11_ALL);
2699 ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
2700 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2701 ovs_rwlock_rdlock(&p->tables[i].cls.rwlock);
2702 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2703 ovs_rwlock_unlock(&p->tables[i].cls.rwlock);
2706 p->ofproto_class->get_tables(p, ots);
2708 /* Post-process the tables, dropping hidden tables. */
2709 n_tables = p->n_tables;
2710 for (i = 0; i < p->n_tables; i++) {
2711 const struct oftable *table = &p->tables[i];
2713 if (table->flags & OFTABLE_HIDDEN) {
2719 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2722 if (table->max_flows < ntohl(ots[i].max_entries)) {
2723 ots[i].max_entries = htonl(table->max_flows);
2727 msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
2728 ofconn_send_reply(ofconn, msg);
2736 append_port_stat(struct ofport *port, struct list *replies)
2738 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
2740 calc_duration(port->created, time_msec(),
2741 &ops.duration_sec, &ops.duration_nsec);
2743 /* Intentionally ignore return value, since errors will set
2744 * 'stats' to all-1s, which is correct for OpenFlow, and
2745 * netdev_get_stats() will log errors. */
2746 ofproto_port_get_stats(port, &ops.stats);
2748 ofputil_append_port_stat(replies, &ops);
2752 handle_port_stats_request(struct ofconn *ofconn,
2753 const struct ofp_header *request)
2755 struct ofproto *p = ofconn_get_ofproto(ofconn);
2756 struct ofport *port;
2757 struct list replies;
2761 error = ofputil_decode_port_stats_request(request, &port_no);
2766 ofpmp_init(&replies, request);
2767 if (port_no != OFPP_ANY) {
2768 port = ofproto_get_port(p, port_no);
2770 append_port_stat(port, &replies);
2773 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2774 append_port_stat(port, &replies);
2778 ofconn_send_replies(ofconn, &replies);
2783 handle_port_desc_stats_request(struct ofconn *ofconn,
2784 const struct ofp_header *request)
2786 struct ofproto *p = ofconn_get_ofproto(ofconn);
2787 enum ofp_version version;
2788 struct ofport *port;
2789 struct list replies;
2791 ofpmp_init(&replies, request);
2793 version = ofputil_protocol_to_ofp_version(ofconn_get_protocol(ofconn));
2794 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2795 ofputil_append_port_desc_stats_reply(version, &port->pp, &replies);
2798 ofconn_send_replies(ofconn, &replies);
2803 hash_cookie(ovs_be64 cookie)
2805 return hash_2words((OVS_FORCE uint64_t)cookie >> 32,
2806 (OVS_FORCE uint64_t)cookie);
2810 cookies_insert(struct ofproto *ofproto, struct rule *rule)
2812 hindex_insert(&ofproto->cookies, &rule->cookie_node,
2813 hash_cookie(rule->flow_cookie));
2817 cookies_remove(struct ofproto *ofproto, struct rule *rule)
2819 hindex_remove(&ofproto->cookies, &rule->cookie_node);
2823 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
2824 ovs_be64 new_cookie)
2826 if (new_cookie != rule->flow_cookie) {
2827 cookies_remove(ofproto, rule);
2829 ovs_rwlock_wrlock(&rule->rwlock);
2830 rule->flow_cookie = new_cookie;
2831 ovs_rwlock_unlock(&rule->rwlock);
2833 cookies_insert(ofproto, rule);
2838 calc_duration(long long int start, long long int now,
2839 uint32_t *sec, uint32_t *nsec)
2841 long long int msecs = now - start;
2842 *sec = msecs / 1000;
2843 *nsec = (msecs % 1000) * (1000 * 1000);
2846 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
2847 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
2849 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2851 return (table_id == 0xff || table_id < ofproto->n_tables
2853 : OFPERR_OFPBRC_BAD_TABLE_ID);
2857 static struct oftable *
2858 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
2860 struct oftable *table;
2862 for (table = &ofproto->tables[table_id];
2863 table < &ofproto->tables[ofproto->n_tables];
2865 if (!(table->flags & OFTABLE_HIDDEN)) {
2873 static struct oftable *
2874 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
2876 if (table_id == 0xff) {
2877 return next_visible_table(ofproto, 0);
2878 } else if (table_id < ofproto->n_tables) {
2879 return &ofproto->tables[table_id];
2885 static struct oftable *
2886 next_matching_table(const struct ofproto *ofproto,
2887 const struct oftable *table, uint8_t table_id)
2889 return (table_id == 0xff
2890 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
2894 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
2896 * - If TABLE_ID is 0xff, this iterates over every classifier table in
2897 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
2899 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
2900 * only once, for that table. (This can be used to access tables marked
2903 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
2904 * entered at all. (Perhaps you should have validated TABLE_ID with
2905 * check_table_id().)
2907 * All parameters are evaluated multiple times.
2909 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
2910 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
2912 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
2914 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2915 * 'table_id' is 0xff) that match 'match' in the "loose" way required for
2916 * OpenFlow OFPFC_MODIFY and OFPFC_DELETE requests and puts them on list
2919 * If 'out_port' is anything other than OFPP_ANY, then only rules that output
2920 * to 'out_port' are included.
2922 * Hidden rules are always omitted.
2924 * Returns 0 on success, otherwise an OpenFlow error code. */
2926 collect_rules_loose(struct ofproto *ofproto, uint8_t table_id,
2927 const struct match *match,
2928 ovs_be64 cookie, ovs_be64 cookie_mask,
2929 ofp_port_t out_port, struct list *rules)
2931 struct oftable *table;
2935 error = check_table_id(ofproto, table_id);
2941 cls_rule_init(&cr, match, 0);
2943 if (cookie_mask == htonll(UINT64_MAX)) {
2946 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node, hash_cookie(cookie),
2947 &ofproto->cookies) {
2948 if (table_id != rule->table_id && table_id != 0xff) {
2951 if (ofproto_rule_is_hidden(rule)) {
2954 if (cls_rule_is_loose_match(&rule->cr, &cr.match)) {
2955 if (rule->pending) {
2956 error = OFPROTO_POSTPONE;
2959 if (rule->flow_cookie == cookie /* Hash collisions possible. */
2960 && ofproto_rule_has_out_port(rule, out_port)) {
2961 list_push_back(rules, &rule->ofproto_node);
2968 FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2969 struct cls_cursor cursor;
2972 ovs_rwlock_rdlock(&table->cls.rwlock);
2973 cls_cursor_init(&cursor, &table->cls, &cr);
2974 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2975 if (rule->pending) {
2976 ovs_rwlock_unlock(&table->cls.rwlock);
2977 error = OFPROTO_POSTPONE;
2980 if (!ofproto_rule_is_hidden(rule)
2981 && ofproto_rule_has_out_port(rule, out_port)
2982 && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2983 list_push_back(rules, &rule->ofproto_node);
2986 ovs_rwlock_unlock(&table->cls.rwlock);
2990 cls_rule_destroy(&cr);
2994 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2995 * 'table_id' is 0xff) that match 'match' in the "strict" way required for
2996 * OpenFlow OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests and puts them
2999 * If 'out_port' is anything other than OFPP_ANY, then only rules that output
3000 * to 'out_port' are included.
3002 * Hidden rules are always omitted.
3004 * Returns 0 on success, otherwise an OpenFlow error code. */
3006 collect_rules_strict(struct ofproto *ofproto, uint8_t table_id,
3007 const struct match *match, unsigned int priority,
3008 ovs_be64 cookie, ovs_be64 cookie_mask,
3009 ofp_port_t out_port, struct list *rules)
3011 struct oftable *table;
3015 error = check_table_id(ofproto, table_id);
3021 cls_rule_init(&cr, match, priority);
3023 if (cookie_mask == htonll(UINT64_MAX)) {
3026 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node, hash_cookie(cookie),
3027 &ofproto->cookies) {
3028 if (table_id != rule->table_id && table_id != 0xff) {
3031 if (ofproto_rule_is_hidden(rule)) {
3034 if (cls_rule_equal(&rule->cr, &cr)) {
3035 if (rule->pending) {
3036 error = OFPROTO_POSTPONE;
3039 if (rule->flow_cookie == cookie /* Hash collisions possible. */
3040 && ofproto_rule_has_out_port(rule, out_port)) {
3041 list_push_back(rules, &rule->ofproto_node);
3048 FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
3051 ovs_rwlock_rdlock(&table->cls.rwlock);
3052 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
3054 ovs_rwlock_unlock(&table->cls.rwlock);
3056 if (rule->pending) {
3057 error = OFPROTO_POSTPONE;
3060 if (!ofproto_rule_is_hidden(rule)
3061 && ofproto_rule_has_out_port(rule, out_port)
3062 && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
3063 list_push_back(rules, &rule->ofproto_node);
3069 cls_rule_destroy(&cr);
3073 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3074 * forced into the range of a uint16_t. */
3076 age_secs(long long int age_ms)
3078 return (age_ms < 0 ? 0
3079 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3080 : (unsigned int) age_ms / 1000);
3084 handle_flow_stats_request(struct ofconn *ofconn,
3085 const struct ofp_header *request)
3087 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3088 struct ofputil_flow_stats_request fsr;
3089 struct list replies;
3094 error = ofputil_decode_flow_stats_request(&fsr, request);
3099 error = collect_rules_loose(ofproto, fsr.table_id, &fsr.match,
3100 fsr.cookie, fsr.cookie_mask,
3101 fsr.out_port, &rules);
3106 ofpmp_init(&replies, request);
3107 LIST_FOR_EACH (rule, ofproto_node, &rules) {
3108 long long int now = time_msec();
3109 struct ofputil_flow_stats fs;
3111 minimatch_expand(&rule->cr.match, &fs.match);
3112 fs.priority = rule->cr.priority;
3113 fs.cookie = rule->flow_cookie;
3114 fs.table_id = rule->table_id;
3115 calc_duration(rule->created, now, &fs.duration_sec, &fs.duration_nsec);
3116 fs.idle_age = age_secs(now - rule->used);
3117 fs.hard_age = age_secs(now - rule->modified);
3118 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3120 fs.ofpacts = rule->ofpacts;
3121 fs.ofpacts_len = rule->ofpacts_len;
3123 ovs_mutex_lock(&rule->timeout_mutex);
3124 fs.idle_timeout = rule->idle_timeout;
3125 fs.hard_timeout = rule->hard_timeout;
3126 ovs_mutex_unlock(&rule->timeout_mutex);
3129 if (rule->send_flow_removed) {
3130 fs.flags |= OFPUTIL_FF_SEND_FLOW_REM;
3131 /* FIXME: Implement OFPUTIL_FF_NO_PKT_COUNTS and
3132 OFPUTIL_FF_NO_BYT_COUNTS. */
3134 ofputil_append_flow_stats_reply(&fs, &replies);
3136 ofconn_send_replies(ofconn, &replies);
3142 flow_stats_ds(struct rule *rule, struct ds *results)
3144 uint64_t packet_count, byte_count;
3146 rule->ofproto->ofproto_class->rule_get_stats(rule,
3147 &packet_count, &byte_count);
3149 if (rule->table_id != 0) {
3150 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3152 ds_put_format(results, "duration=%llds, ",
3153 (time_msec() - rule->created) / 1000);
3154 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3155 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3156 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3157 cls_rule_format(&rule->cr, results);
3158 ds_put_char(results, ',');
3159 ofpacts_format(rule->ofpacts, rule->ofpacts_len, results);
3160 ds_put_cstr(results, "\n");
3163 /* Adds a pretty-printed description of all flows to 'results', including
3164 * hidden flows (e.g., set up by in-band control). */
3166 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3168 struct oftable *table;
3170 OFPROTO_FOR_EACH_TABLE (table, p) {
3171 struct cls_cursor cursor;
3174 ovs_rwlock_rdlock(&table->cls.rwlock);
3175 cls_cursor_init(&cursor, &table->cls, NULL);
3176 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3177 flow_stats_ds(rule, results);
3179 ovs_rwlock_unlock(&table->cls.rwlock);
3183 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3184 * '*engine_type' and '*engine_id', respectively. */
3186 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3187 uint8_t *engine_type, uint8_t *engine_id)
3189 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3192 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'. Returns
3193 * true if the port's CFM status was successfully stored into '*status'.
3194 * Returns false if the port did not have CFM configured, in which case
3195 * '*status' is indeterminate.
3197 * The caller must provide and owns '*status', and must free 'status->rmps'. */
3199 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3200 struct ofproto_cfm_status *status)
3202 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3204 && ofproto->ofproto_class->get_cfm_status
3205 && ofproto->ofproto_class->get_cfm_status(ofport, status));
3209 handle_aggregate_stats_request(struct ofconn *ofconn,
3210 const struct ofp_header *oh)
3212 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3213 struct ofputil_flow_stats_request request;
3214 struct ofputil_aggregate_stats stats;
3215 bool unknown_packets, unknown_bytes;
3216 struct ofpbuf *reply;
3221 error = ofputil_decode_flow_stats_request(&request, oh);
3226 error = collect_rules_loose(ofproto, request.table_id, &request.match,
3227 request.cookie, request.cookie_mask,
3228 request.out_port, &rules);
3233 memset(&stats, 0, sizeof stats);
3234 unknown_packets = unknown_bytes = false;
3235 LIST_FOR_EACH (rule, ofproto_node, &rules) {
3236 uint64_t packet_count;
3237 uint64_t byte_count;
3239 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3242 if (packet_count == UINT64_MAX) {
3243 unknown_packets = true;
3245 stats.packet_count += packet_count;
3248 if (byte_count == UINT64_MAX) {
3249 unknown_bytes = true;
3251 stats.byte_count += byte_count;
3256 if (unknown_packets) {
3257 stats.packet_count = UINT64_MAX;
3259 if (unknown_bytes) {
3260 stats.byte_count = UINT64_MAX;
3263 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3264 ofconn_send_reply(ofconn, reply);
3269 struct queue_stats_cbdata {
3270 struct ofport *ofport;
3271 struct list replies;
3276 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3277 const struct netdev_queue_stats *stats)
3279 struct ofputil_queue_stats oqs;
3281 oqs.port_no = cbdata->ofport->pp.port_no;
3282 oqs.queue_id = queue_id;
3283 oqs.tx_bytes = stats->tx_bytes;
3284 oqs.tx_packets = stats->tx_packets;
3285 oqs.tx_errors = stats->tx_errors;
3286 if (stats->created != LLONG_MIN) {
3287 calc_duration(stats->created, cbdata->now,
3288 &oqs.duration_sec, &oqs.duration_nsec);
3290 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3292 ofputil_append_queue_stat(&cbdata->replies, &oqs);
3296 handle_queue_stats_dump_cb(uint32_t queue_id,
3297 struct netdev_queue_stats *stats,
3300 struct queue_stats_cbdata *cbdata = cbdata_;
3302 put_queue_stats(cbdata, queue_id, stats);
3306 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3307 struct queue_stats_cbdata *cbdata)
3309 cbdata->ofport = port;
3310 if (queue_id == OFPQ_ALL) {
3311 netdev_dump_queue_stats(port->netdev,
3312 handle_queue_stats_dump_cb, cbdata);
3314 struct netdev_queue_stats stats;
3316 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3317 put_queue_stats(cbdata, queue_id, &stats);
3319 return OFPERR_OFPQOFC_BAD_QUEUE;
3326 handle_queue_stats_request(struct ofconn *ofconn,
3327 const struct ofp_header *rq)
3329 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3330 struct queue_stats_cbdata cbdata;
3331 struct ofport *port;
3333 struct ofputil_queue_stats_request oqsr;
3335 COVERAGE_INC(ofproto_queue_req);
3337 ofpmp_init(&cbdata.replies, rq);
3338 cbdata.now = time_msec();
3340 error = ofputil_decode_queue_stats_request(rq, &oqsr);
3345 if (oqsr.port_no == OFPP_ANY) {
3346 error = OFPERR_OFPQOFC_BAD_QUEUE;
3347 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3348 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3353 port = ofproto_get_port(ofproto, oqsr.port_no);
3355 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3356 : OFPERR_OFPQOFC_BAD_PORT);
3359 ofconn_send_replies(ofconn, &cbdata.replies);
3361 ofpbuf_list_delete(&cbdata.replies);
3368 is_flow_deletion_pending(const struct ofproto *ofproto,
3369 const struct cls_rule *cls_rule,
3372 if (!hmap_is_empty(&ofproto->deletions)) {
3373 struct ofoperation *op;
3375 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3376 cls_rule_hash(cls_rule, table_id),
3377 &ofproto->deletions) {
3378 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
3388 evict_rule_from_table(struct ofproto *ofproto, struct oftable *table)
3393 ovs_rwlock_rdlock(&table->cls.rwlock);
3394 n_rules = classifier_count(&table->cls);
3395 ovs_rwlock_unlock(&table->cls.rwlock);
3397 if (n_rules < table->max_flows) {
3399 } else if (!choose_rule_to_evict(table, &rule)) {
3400 return OFPERR_OFPFMFC_TABLE_FULL;
3401 } else if (rule->pending) {
3402 ovs_rwlock_unlock(&rule->rwlock);
3403 return OFPROTO_POSTPONE;
3405 struct ofopgroup *group;
3407 group = ofopgroup_create_unattached(ofproto);
3408 delete_flow__(rule, group, OFPRR_EVICTION);
3409 ofopgroup_submit(group);
3415 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3416 * in which no matching flow already exists in the flow table.
3418 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3419 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
3420 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3421 * initiated now but may be retried later.
3423 * Upon successful return, takes ownership of 'fm->ofpacts'. On failure,
3424 * ownership remains with the caller.
3426 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3429 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3430 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3432 struct oftable *table;
3433 struct ofopgroup *group;
3439 error = check_table_id(ofproto, fm->table_id);
3445 if (fm->table_id == 0xff) {
3446 if (ofproto->ofproto_class->rule_choose_table) {
3447 error = ofproto->ofproto_class->rule_choose_table(ofproto,
3453 ovs_assert(table_id < ofproto->n_tables);
3457 } else if (fm->table_id < ofproto->n_tables) {
3458 table_id = fm->table_id;
3460 return OFPERR_OFPBRC_BAD_TABLE_ID;
3463 table = &ofproto->tables[table_id];
3465 if (table->flags & OFTABLE_READONLY) {
3466 return OFPERR_OFPBRC_EPERM;
3469 cls_rule_init(&cr, &fm->match, fm->priority);
3471 /* Transform "add" into "modify" if there's an existing identical flow. */
3472 ovs_rwlock_rdlock(&table->cls.rwlock);
3473 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
3474 ovs_rwlock_unlock(&table->cls.rwlock);
3476 cls_rule_destroy(&cr);
3477 if (!rule_is_modifiable(rule)) {
3478 return OFPERR_OFPBRC_EPERM;
3479 } else if (rule->pending) {
3480 return OFPROTO_POSTPONE;
3485 list_push_back(&rules, &rule->ofproto_node);
3486 fm->modify_cookie = true;
3487 return modify_flows__(ofproto, ofconn, fm, request, &rules);
3491 /* Verify actions. */
3492 error = ofproto_check_ofpacts(ofproto, fm->ofpacts, fm->ofpacts_len,
3493 &fm->match.flow, table_id);
3495 cls_rule_destroy(&cr);
3499 /* Serialize against pending deletion. */
3500 if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
3501 cls_rule_destroy(&cr);
3502 return OFPROTO_POSTPONE;
3505 /* Check for overlap, if requested. */
3506 if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
3509 ovs_rwlock_rdlock(&table->cls.rwlock);
3510 overlaps = classifier_rule_overlaps(&table->cls, &cr);
3511 ovs_rwlock_unlock(&table->cls.rwlock);
3514 cls_rule_destroy(&cr);
3515 return OFPERR_OFPFMFC_OVERLAP;
3519 /* If necessary, evict an existing rule to clear out space. */
3520 error = evict_rule_from_table(ofproto, table);
3522 cls_rule_destroy(&cr);
3526 /* Allocate new rule. */
3527 rule = ofproto->ofproto_class->rule_alloc();
3529 cls_rule_destroy(&cr);
3530 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
3531 ofproto->name, ovs_strerror(error));
3535 /* Initialize base state. */
3536 rule->ofproto = ofproto;
3537 cls_rule_move(&rule->cr, &cr);
3538 rule->pending = NULL;
3539 rule->flow_cookie = fm->new_cookie;
3540 rule->created = rule->modified = rule->used = time_msec();
3542 ovs_mutex_init(&rule->timeout_mutex);
3543 ovs_mutex_lock(&rule->timeout_mutex);
3544 rule->idle_timeout = fm->idle_timeout;
3545 rule->hard_timeout = fm->hard_timeout;
3546 ovs_mutex_unlock(&rule->timeout_mutex);
3548 rule->table_id = table - ofproto->tables;
3549 rule->send_flow_removed = (fm->flags & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3550 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3551 rule->ofpacts_len = fm->ofpacts_len;
3552 rule->meter_id = find_meter(rule->ofpacts, rule->ofpacts_len);
3553 list_init(&rule->meter_list_node);
3554 rule->eviction_group = NULL;
3555 list_init(&rule->expirable);
3556 rule->monitor_flags = 0;
3557 rule->add_seqno = 0;
3558 rule->modify_seqno = 0;
3559 ovs_rwlock_init(&rule->rwlock);
3561 /* Construct rule, initializing derived state. */
3562 error = ofproto->ofproto_class->rule_construct(rule);
3564 ofproto_rule_destroy__(rule);
3569 oftable_insert_rule(rule);
3571 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3572 ofoperation_create(group, rule, OFOPERATION_ADD, 0);
3573 ofproto->ofproto_class->rule_insert(rule);
3574 ofopgroup_submit(group);
3579 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3581 /* Modifies the rules listed in 'rules', changing their actions to match those
3584 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3587 * Returns 0 on success, otherwise an OpenFlow error code. */
3589 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3590 struct ofputil_flow_mod *fm, const struct ofp_header *request,
3593 enum ofoperation_type type;
3594 struct ofopgroup *group;
3598 type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
3599 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
3600 error = OFPERR_OFPBRC_EPERM;
3601 LIST_FOR_EACH (rule, ofproto_node, rules) {
3602 struct ofoperation *op;
3603 bool actions_changed;
3604 bool reset_counters;
3606 /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
3608 if (rule_is_modifiable(rule)) {
3609 /* At least one rule is modifiable, don't report EPERM error. */
3615 /* Verify actions. */
3616 error = ofpacts_check(fm->ofpacts, fm->ofpacts_len, &fm->match.flow,
3617 u16_to_ofp(ofproto->max_ports), rule->table_id);
3622 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
3623 rule->ofpacts, rule->ofpacts_len);
3625 op = ofoperation_create(group, rule, type, 0);
3627 if (fm->modify_cookie && fm->new_cookie != htonll(UINT64_MAX)) {
3628 ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
3630 if (type == OFOPERATION_REPLACE) {
3631 ovs_mutex_lock(&rule->timeout_mutex);
3632 rule->idle_timeout = fm->idle_timeout;
3633 rule->hard_timeout = fm->hard_timeout;
3634 ovs_mutex_unlock(&rule->timeout_mutex);
3636 rule->send_flow_removed = (fm->flags
3637 & OFPUTIL_FF_SEND_FLOW_REM) != 0;
3639 if (fm->idle_timeout || fm->hard_timeout) {
3640 if (!rule->eviction_group) {
3641 eviction_group_add_rule(rule);
3644 eviction_group_remove_rule(rule);
3648 reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
3649 if (actions_changed || reset_counters) {
3650 op->ofpacts = rule->ofpacts;
3651 op->ofpacts_len = rule->ofpacts_len;
3652 op->meter_id = rule->meter_id;
3654 ovs_rwlock_wrlock(&rule->rwlock);
3655 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
3656 rule->ofpacts_len = fm->ofpacts_len;
3657 ovs_rwlock_unlock(&rule->rwlock);
3659 rule->meter_id = find_meter(rule->ofpacts, rule->ofpacts_len);
3660 rule->ofproto->ofproto_class->rule_modify_actions(rule,
3663 ofoperation_complete(op, 0);
3666 ofopgroup_submit(group);
3672 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
3673 struct ofputil_flow_mod *fm, const struct ofp_header *request)
3675 if (fm->cookie_mask != htonll(0) || fm->new_cookie == htonll(UINT64_MAX)) {
3678 return add_flow(ofproto, ofconn, fm, request);
3681 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
3684 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3687 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3688 struct ofputil_flow_mod *fm,
3689 const struct ofp_header *request)
3694 error = collect_rules_loose(ofproto, fm->table_id, &fm->match,
3695 fm->cookie, fm->cookie_mask,
3699 } else if (list_is_empty(&rules)) {
3700 return modify_flows_add(ofproto, ofconn, fm, request);
3702 return modify_flows__(ofproto, ofconn, fm, request, &rules);
3706 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
3709 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3712 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3713 struct ofputil_flow_mod *fm,
3714 const struct ofp_header *request)
3719 error = collect_rules_strict(ofproto, fm->table_id, &fm->match,
3720 fm->priority, fm->cookie, fm->cookie_mask,
3725 } else if (list_is_empty(&rules)) {
3726 return modify_flows_add(ofproto, ofconn, fm, request);
3728 return list_is_singleton(&rules) ? modify_flows__(ofproto, ofconn,
3729 fm, request, &rules)
3734 /* OFPFC_DELETE implementation. */
3737 delete_flow__(struct rule *rule, struct ofopgroup *group,
3738 enum ofp_flow_removed_reason reason)
3740 struct ofproto *ofproto = rule->ofproto;
3742 ofproto_rule_send_removed(rule, reason);
3744 ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
3745 oftable_remove_rule(rule);
3746 ofproto->ofproto_class->rule_delete(rule);
3749 /* Deletes the rules listed in 'rules'.
3751 * Returns 0 on success, otherwise an OpenFlow error code. */
3753 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3754 const struct ofp_header *request, struct list *rules,
3755 enum ofp_flow_removed_reason reason)
3757 struct rule *rule, *next;
3758 struct ofopgroup *group;
3760 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3761 LIST_FOR_EACH_SAFE (rule, next, ofproto_node, rules) {
3762 ovs_rwlock_wrlock(&rule->rwlock);
3763 delete_flow__(rule, group, reason);
3765 ofopgroup_submit(group);
3770 /* Implements OFPFC_DELETE. */
3772 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3773 const struct ofputil_flow_mod *fm,
3774 const struct ofp_header *request)
3779 error = collect_rules_loose(ofproto, fm->table_id, &fm->match,
3780 fm->cookie, fm->cookie_mask,
3781 fm->out_port, &rules);
3782 return (error ? error
3783 : !list_is_empty(&rules) ? delete_flows__(ofproto, ofconn, request,
3784 &rules, OFPRR_DELETE)
3788 /* Implements OFPFC_DELETE_STRICT. */
3790 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3791 const struct ofputil_flow_mod *fm,
3792 const struct ofp_header *request)
3797 error = collect_rules_strict(ofproto, fm->table_id, &fm->match,
3798 fm->priority, fm->cookie, fm->cookie_mask,
3799 fm->out_port, &rules);
3800 return (error ? error
3801 : list_is_singleton(&rules) ? delete_flows__(ofproto, ofconn,
3808 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
3810 struct ofputil_flow_removed fr;
3812 if (ofproto_rule_is_hidden(rule) || !rule->send_flow_removed) {
3816 minimatch_expand(&rule->cr.match, &fr.match);
3817 fr.priority = rule->cr.priority;
3818 fr.cookie = rule->flow_cookie;
3820 fr.table_id = rule->table_id;
3821 calc_duration(rule->created, time_msec(),
3822 &fr.duration_sec, &fr.duration_nsec);
3823 ovs_mutex_lock(&rule->timeout_mutex);
3824 fr.idle_timeout = rule->idle_timeout;
3825 fr.hard_timeout = rule->hard_timeout;
3826 ovs_mutex_unlock(&rule->timeout_mutex);
3827 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
3830 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
3833 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
3834 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
3837 * 'rule' must not have a pending operation (that is, 'rule->pending' must be
3840 * ofproto implementation ->run() functions should use this function to expire
3841 * OpenFlow flows. */
3843 ofproto_rule_expire(struct rule *rule, uint8_t reason)
3845 struct ofproto *ofproto = rule->ofproto;
3846 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
3848 ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
3849 ofproto_rule_send_removed(rule, reason);
3851 ovs_rwlock_wrlock(&cls->rwlock);
3852 ofproto_delete_rule(ofproto, cls, rule);
3853 ovs_rwlock_unlock(&cls->rwlock);
3856 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
3857 * means "infinite". */
3859 reduce_timeout(uint16_t max, uint16_t *timeout)
3861 if (max && (!*timeout || *timeout > max)) {
3866 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
3867 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
3868 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
3870 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
3872 ofproto_rule_reduce_timeouts(struct rule *rule,
3873 uint16_t idle_timeout, uint16_t hard_timeout)
3874 OVS_EXCLUDED(rule->ofproto->expirable_mutex, rule->timeout_mutex)
3876 if (!idle_timeout && !hard_timeout) {
3880 ovs_mutex_lock(&rule->ofproto->expirable_mutex);
3881 if (list_is_empty(&rule->expirable)) {
3882 list_insert(&rule->ofproto->expirable, &rule->expirable);
3884 ovs_mutex_unlock(&rule->ofproto->expirable_mutex);
3886 ovs_mutex_lock(&rule->timeout_mutex);
3887 reduce_timeout(idle_timeout, &rule->idle_timeout);
3888 reduce_timeout(hard_timeout, &rule->hard_timeout);
3889 ovs_mutex_unlock(&rule->timeout_mutex);
3893 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3895 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3896 struct ofputil_flow_mod fm;
3897 uint64_t ofpacts_stub[1024 / 8];
3898 struct ofpbuf ofpacts;
3902 error = reject_slave_controller(ofconn);
3907 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3908 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
3911 error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
3914 goto exit_free_ofpacts;
3917 /* Record the operation for logging a summary report. */
3918 switch (fm.command) {
3924 case OFPFC_MODIFY_STRICT:
3925 ofproto->n_modify++;
3929 case OFPFC_DELETE_STRICT:
3930 ofproto->n_delete++;
3935 if (ofproto->next_op_report == LLONG_MAX) {
3936 ofproto->first_op = now;
3937 ofproto->next_op_report = MAX(now + 10 * 1000,
3938 ofproto->op_backoff);
3939 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
3941 ofproto->last_op = now;
3944 ofpbuf_uninit(&ofpacts);
3950 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
3951 struct ofputil_flow_mod *fm, const struct ofp_header *oh)
3953 if (ofproto->n_pending >= 50) {
3954 ovs_assert(!list_is_empty(&ofproto->pending));
3955 return OFPROTO_POSTPONE;
3958 switch (fm->command) {
3960 return add_flow(ofproto, ofconn, fm, oh);
3963 return modify_flows_loose(ofproto, ofconn, fm, oh);
3965 case OFPFC_MODIFY_STRICT:
3966 return modify_flow_strict(ofproto, ofconn, fm, oh);
3969 return delete_flows_loose(ofproto, ofconn, fm, oh);
3971 case OFPFC_DELETE_STRICT:
3972 return delete_flow_strict(ofproto, ofconn, fm, oh);
3975 if (fm->command > 0xff) {
3976 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
3977 "flow_mod_table_id extension is not enabled",
3980 return OFPERR_OFPFMFC_BAD_COMMAND;
3985 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
3987 struct ofputil_role_request request;
3988 struct ofputil_role_request reply;
3992 error = ofputil_decode_role_message(oh, &request);
3997 if (request.role != OFPCR12_ROLE_NOCHANGE) {
3998 if (ofconn_get_role(ofconn) != request.role
3999 && ofconn_has_pending_opgroups(ofconn)) {
4000 return OFPROTO_POSTPONE;
4003 if (request.have_generation_id
4004 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4005 return OFPERR_OFPRRFC_STALE;
4008 ofconn_set_role(ofconn, request.role);
4011 reply.role = ofconn_get_role(ofconn);
4012 reply.have_generation_id = ofconn_get_master_election_id(
4013 ofconn, &reply.generation_id);
4014 buf = ofputil_encode_role_reply(oh, &reply);
4015 ofconn_send_reply(ofconn, buf);
4021 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4022 const struct ofp_header *oh)
4024 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4025 enum ofputil_protocol cur, next;
4027 cur = ofconn_get_protocol(ofconn);
4028 next = ofputil_protocol_set_tid(cur, msg->set != 0);
4029 ofconn_set_protocol(ofconn, next);
4035 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4037 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4038 enum ofputil_protocol cur, next;
4039 enum ofputil_protocol next_base;
4041 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4043 return OFPERR_OFPBRC_EPERM;
4046 cur = ofconn_get_protocol(ofconn);
4047 next = ofputil_protocol_set_base(cur, next_base);
4048 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4049 /* Avoid sending async messages in surprising protocol. */
4050 return OFPROTO_POSTPONE;
4053 ofconn_set_protocol(ofconn, next);
4058 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4059 const struct ofp_header *oh)
4061 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4064 format = ntohl(msg->format);
4065 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4066 return OFPERR_OFPBRC_EPERM;
4069 if (format != ofconn_get_packet_in_format(ofconn)
4070 && ofconn_has_pending_opgroups(ofconn)) {
4071 /* Avoid sending async message in surprsing packet in format. */
4072 return OFPROTO_POSTPONE;
4075 ofconn_set_packet_in_format(ofconn, format);
4080 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4082 const struct nx_async_config *msg = ofpmsg_body(oh);
4083 uint32_t master[OAM_N_TYPES];
4084 uint32_t slave[OAM_N_TYPES];
4086 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4087 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4088 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4090 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4091 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4092 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4094 ofconn_set_async_config(ofconn, master, slave);
4095 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4096 !ofconn_get_miss_send_len(ofconn)) {
4097 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4104 handle_nxt_set_controller_id(struct ofconn *ofconn,
4105 const struct ofp_header *oh)
4107 const struct nx_controller_id *nci = ofpmsg_body(oh);
4109 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4110 return OFPERR_NXBRC_MUST_BE_ZERO;
4113 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4118 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4122 if (ofconn_has_pending_opgroups(ofconn)) {
4123 return OFPROTO_POSTPONE;
4126 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4127 ? OFPRAW_OFPT10_BARRIER_REPLY
4128 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4129 ofconn_send_reply(ofconn, buf);
4134 ofproto_compose_flow_refresh_update(const struct rule *rule,
4135 enum nx_flow_monitor_flags flags,
4138 struct ofoperation *op = rule->pending;
4139 struct ofputil_flow_update fu;
4142 if (op && op->type == OFOPERATION_ADD) {
4143 /* We'll report the final flow when the operation completes. Reporting
4144 * it now would cause a duplicate report later. */
4148 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4149 ? NXFME_ADDED : NXFME_MODIFIED);
4151 ovs_mutex_lock(&rule->timeout_mutex);
4152 fu.idle_timeout = rule->idle_timeout;
4153 fu.hard_timeout = rule->hard_timeout;
4154 ovs_mutex_unlock(&rule->timeout_mutex);
4155 fu.table_id = rule->table_id;
4156 fu.cookie = rule->flow_cookie;
4157 minimatch_expand(&rule->cr.match, &match);
4159 fu.priority = rule->cr.priority;
4160 if (!(flags & NXFMF_ACTIONS)) {
4164 fu.ofpacts = rule->ofpacts;
4165 fu.ofpacts_len = rule->ofpacts_len;
4167 /* An operation is in progress. Use the previous version of the flow's
4168 * actions, so that when the operation commits we report the change. */
4170 case OFOPERATION_ADD:
4173 case OFOPERATION_MODIFY:
4174 case OFOPERATION_REPLACE:
4176 fu.ofpacts = op->ofpacts;
4177 fu.ofpacts_len = op->ofpacts_len;
4179 fu.ofpacts = rule->ofpacts;
4180 fu.ofpacts_len = rule->ofpacts_len;
4184 case OFOPERATION_DELETE:
4185 fu.ofpacts = rule->ofpacts;
4186 fu.ofpacts_len = rule->ofpacts_len;
4194 if (list_is_empty(msgs)) {
4195 ofputil_start_flow_update(msgs);
4197 ofputil_append_flow_update(&fu, msgs);
4201 ofmonitor_compose_refresh_updates(struct list *rules, struct list *msgs)
4205 LIST_FOR_EACH (rule, ofproto_node, rules) {
4206 enum nx_flow_monitor_flags flags = rule->monitor_flags;
4207 rule->monitor_flags = 0;
4209 ofproto_compose_flow_refresh_update(rule, flags, msgs);
4214 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4215 struct rule *rule, uint64_t seqno,
4218 enum nx_flow_monitor_flags update;
4220 if (ofproto_rule_is_hidden(rule)) {
4225 ? ofoperation_has_out_port(rule->pending, m->out_port)
4226 : ofproto_rule_has_out_port(rule, m->out_port))) {
4231 if (rule->add_seqno > seqno) {
4232 update = NXFMF_ADD | NXFMF_MODIFY;
4233 } else if (rule->modify_seqno > seqno) {
4234 update = NXFMF_MODIFY;
4239 if (!(m->flags & update)) {
4243 update = NXFMF_INITIAL;
4246 if (!rule->monitor_flags) {
4247 list_push_back(rules, &rule->ofproto_node);
4249 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4253 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4257 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4258 const struct ofoperation *op;
4259 const struct oftable *table;
4260 struct cls_rule target;
4262 cls_rule_init_from_minimatch(&target, &m->match, 0);
4263 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4264 struct cls_cursor cursor;
4267 ovs_rwlock_rdlock(&table->cls.rwlock);
4268 cls_cursor_init(&cursor, &table->cls, &target);
4269 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4270 ovs_assert(!rule->pending); /* XXX */
4271 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4273 ovs_rwlock_unlock(&table->cls.rwlock);
4276 HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4277 struct rule *rule = op->rule;
4279 if (((m->table_id == 0xff
4280 ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4281 : m->table_id == rule->table_id))
4282 && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4283 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4286 cls_rule_destroy(&target);
4290 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4293 if (m->flags & NXFMF_INITIAL) {
4294 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4299 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4300 uint64_t seqno, struct list *rules)
4302 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4306 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4308 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4309 struct ofmonitor **monitors;
4310 size_t n_monitors, allocated_monitors;
4311 struct list replies;
4318 ofpbuf_use_const(&b, oh, ntohs(oh->length));
4320 n_monitors = allocated_monitors = 0;
4322 struct ofputil_flow_monitor_request request;
4323 struct ofmonitor *m;
4326 retval = ofputil_decode_flow_monitor_request(&request, &b);
4327 if (retval == EOF) {
4329 } else if (retval) {
4334 if (request.table_id != 0xff
4335 && request.table_id >= ofproto->n_tables) {
4336 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4340 error = ofmonitor_create(&request, ofconn, &m);
4345 if (n_monitors >= allocated_monitors) {
4346 monitors = x2nrealloc(monitors, &allocated_monitors,
4349 monitors[n_monitors++] = m;
4353 for (i = 0; i < n_monitors; i++) {
4354 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4357 ofpmp_init(&replies, oh);
4358 ofmonitor_compose_refresh_updates(&rules, &replies);
4359 ofconn_send_replies(ofconn, &replies);
4366 for (i = 0; i < n_monitors; i++) {
4367 ofmonitor_destroy(monitors[i]);
4374 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4376 struct ofmonitor *m;
4379 id = ofputil_decode_flow_monitor_cancel(oh);
4380 m = ofmonitor_lookup(ofconn, id);
4382 return OFPERR_NXBRC_FM_BAD_ID;
4385 ofmonitor_destroy(m);
4389 /* Meters implementation.
4391 * Meter table entry, indexed by the OpenFlow meter_id.
4392 * These are always dynamically allocated to allocate enough space for
4394 * 'created' is used to compute the duration for meter stats.
4395 * 'list rules' is needed so that we can delete the dependent rules when the
4396 * meter table entry is deleted.
4397 * 'provider_meter_id' is for the provider's private use.
4400 long long int created; /* Time created. */
4401 struct list rules; /* List of "struct rule_dpif"s. */
4402 ofproto_meter_id provider_meter_id;
4403 uint16_t flags; /* Meter flags. */
4404 uint16_t n_bands; /* Number of meter bands. */
4405 struct ofputil_meter_band *bands;
4409 * This is used in instruction validation at flow set-up time,
4410 * as flows may not use non-existing meters.
4411 * This is also used by ofproto-providers to translate OpenFlow meter_ids
4412 * in METER instructions to the corresponding provider meter IDs.
4413 * Return value of UINT32_MAX signifies an invalid meter.
4416 ofproto_get_provider_meter_id(const struct ofproto * ofproto,
4417 uint32_t of_meter_id)
4419 if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
4420 const struct meter *meter = ofproto->meters[of_meter_id];
4422 return meter->provider_meter_id.uint32;
4429 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
4433 meter->flags = config->flags;
4434 meter->n_bands = config->n_bands;
4435 meter->bands = xmemdup(config->bands,
4436 config->n_bands * sizeof *meter->bands);
4439 static struct meter *
4440 meter_create(const struct ofputil_meter_config *config,
4441 ofproto_meter_id provider_meter_id)
4443 struct meter *meter;
4445 meter = xzalloc(sizeof *meter);
4446 meter->provider_meter_id = provider_meter_id;
4447 meter->created = time_msec();
4448 list_init(&meter->rules);
4450 meter_update(meter, config);
4456 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
4459 for (mid = first; mid <= last; ++mid) {
4460 struct meter *meter = ofproto->meters[mid];
4462 ofproto->meters[mid] = NULL;
4463 ofproto->ofproto_class->meter_del(ofproto,
4464 meter->provider_meter_id);
4472 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4474 ofproto_meter_id provider_meter_id = { UINT32_MAX };
4475 struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
4479 return OFPERR_OFPMMFC_METER_EXISTS;
4482 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
4485 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
4486 *meterp = meter_create(&mm->meter, provider_meter_id);
4492 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
4494 struct meter *meter = ofproto->meters[mm->meter.meter_id];
4498 return OFPERR_OFPMMFC_UNKNOWN_METER;
4501 error = ofproto->ofproto_class->meter_set(ofproto,
4502 &meter->provider_meter_id,
4504 ovs_assert(meter->provider_meter_id.uint32 != UINT32_MAX);
4506 meter_update(meter, &mm->meter);
4512 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
4513 struct ofputil_meter_mod *mm)
4515 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4516 uint32_t meter_id = mm->meter.meter_id;
4517 uint32_t first, last;
4520 if (meter_id == OFPM13_ALL) {
4522 last = ofproto->meter_features.max_meters;
4524 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
4527 first = last = meter_id;
4530 /* First delete the rules that use this meter. If any of those rules are
4531 * currently being modified, postpone the whole operation until later. */
4533 for (meter_id = first; meter_id <= last; ++meter_id) {
4534 struct meter *meter = ofproto->meters[meter_id];
4535 if (meter && !list_is_empty(&meter->rules)) {
4538 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
4539 if (rule->pending) {
4540 return OFPROTO_POSTPONE;
4542 list_push_back(&rules, &rule->ofproto_node);
4546 if (!list_is_empty(&rules)) {
4547 delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
4550 /* Delete the meters. */
4551 meter_delete(ofproto, first, last);
4557 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4559 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4560 struct ofputil_meter_mod mm;
4561 uint64_t bands_stub[256 / 8];
4562 struct ofpbuf bands;
4566 error = reject_slave_controller(ofconn);
4571 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4573 error = ofputil_decode_meter_mod(oh, &mm, &bands);
4575 goto exit_free_bands;
4578 meter_id = mm.meter.meter_id;
4580 if (mm.command != OFPMC13_DELETE) {
4581 /* Fails also when meters are not implemented by the provider. */
4582 if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
4583 error = OFPERR_OFPMMFC_INVALID_METER;
4584 goto exit_free_bands;
4586 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
4587 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
4588 goto exit_free_bands;
4592 switch (mm.command) {
4594 error = handle_add_meter(ofproto, &mm);
4597 case OFPMC13_MODIFY:
4598 error = handle_modify_meter(ofproto, &mm);
4601 case OFPMC13_DELETE:
4602 error = handle_delete_meter(ofconn, oh, &mm);
4606 error = OFPERR_OFPMMFC_BAD_COMMAND;
4611 ofpbuf_uninit(&bands);
4616 handle_meter_features_request(struct ofconn *ofconn,
4617 const struct ofp_header *request)
4619 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4620 struct ofputil_meter_features features;
4623 if (ofproto->ofproto_class->meter_get_features) {
4624 ofproto->ofproto_class->meter_get_features(ofproto, &features);
4626 memset(&features, 0, sizeof features);
4628 b = ofputil_encode_meter_features_reply(&features, request);
4630 ofconn_send_reply(ofconn, b);
4635 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
4638 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4639 struct list replies;
4640 uint64_t bands_stub[256 / 8];
4641 struct ofpbuf bands;
4642 uint32_t meter_id, first, last;
4644 ofputil_decode_meter_request(request, &meter_id);
4646 if (meter_id == OFPM13_ALL) {
4648 last = ofproto->meter_features.max_meters;
4650 if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
4651 !ofproto->meters[meter_id]) {
4652 return OFPERR_OFPMMFC_UNKNOWN_METER;
4654 first = last = meter_id;
4657 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
4658 ofpmp_init(&replies, request);
4660 for (meter_id = first; meter_id <= last; ++meter_id) {
4661 struct meter *meter = ofproto->meters[meter_id];
4663 continue; /* Skip non-existing meters. */
4665 if (type == OFPTYPE_METER_STATS_REQUEST) {
4666 struct ofputil_meter_stats stats;
4668 stats.meter_id = meter_id;
4670 /* Provider sets the packet and byte counts, we do the rest. */
4671 stats.flow_count = list_size(&meter->rules);
4672 calc_duration(meter->created, time_msec(),
4673 &stats.duration_sec, &stats.duration_nsec);
4674 stats.n_bands = meter->n_bands;
4675 ofpbuf_clear(&bands);
4677 = ofpbuf_put_uninit(&bands,
4678 meter->n_bands * sizeof *stats.bands);
4680 if (!ofproto->ofproto_class->meter_get(ofproto,
4681 meter->provider_meter_id,
4683 ofputil_append_meter_stats(&replies, &stats);
4685 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
4686 struct ofputil_meter_config config;
4688 config.meter_id = meter_id;
4689 config.flags = meter->flags;
4690 config.n_bands = meter->n_bands;
4691 config.bands = meter->bands;
4692 ofputil_append_meter_config(&replies, &config);
4696 ofconn_send_replies(ofconn, &replies);
4697 ofpbuf_uninit(&bands);
4702 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4704 const struct ofp_header *oh = msg->data;
4708 error = ofptype_decode(&type, oh);
4714 /* OpenFlow requests. */
4715 case OFPTYPE_ECHO_REQUEST:
4716 return handle_echo_request(ofconn, oh);
4718 case OFPTYPE_FEATURES_REQUEST:
4719 return handle_features_request(ofconn, oh);
4721 case OFPTYPE_GET_CONFIG_REQUEST:
4722 return handle_get_config_request(ofconn, oh);
4724 case OFPTYPE_SET_CONFIG:
4725 return handle_set_config(ofconn, oh);
4727 case OFPTYPE_PACKET_OUT:
4728 return handle_packet_out(ofconn, oh);
4730 case OFPTYPE_PORT_MOD:
4731 return handle_port_mod(ofconn, oh);
4733 case OFPTYPE_FLOW_MOD:
4734 return handle_flow_mod(ofconn, oh);
4736 case OFPTYPE_METER_MOD:
4737 return handle_meter_mod(ofconn, oh);
4739 case OFPTYPE_BARRIER_REQUEST:
4740 return handle_barrier_request(ofconn, oh);
4742 case OFPTYPE_ROLE_REQUEST:
4743 return handle_role_request(ofconn, oh);
4745 /* OpenFlow replies. */
4746 case OFPTYPE_ECHO_REPLY:
4749 /* Nicira extension requests. */
4750 case OFPTYPE_FLOW_MOD_TABLE_ID:
4751 return handle_nxt_flow_mod_table_id(ofconn, oh);
4753 case OFPTYPE_SET_FLOW_FORMAT:
4754 return handle_nxt_set_flow_format(ofconn, oh);
4756 case OFPTYPE_SET_PACKET_IN_FORMAT:
4757 return handle_nxt_set_packet_in_format(ofconn, oh);
4759 case OFPTYPE_SET_CONTROLLER_ID:
4760 return handle_nxt_set_controller_id(ofconn, oh);
4762 case OFPTYPE_FLOW_AGE:
4763 /* Nothing to do. */
4766 case OFPTYPE_FLOW_MONITOR_CANCEL:
4767 return handle_flow_monitor_cancel(ofconn, oh);
4769 case OFPTYPE_SET_ASYNC_CONFIG:
4770 return handle_nxt_set_async_config(ofconn, oh);
4772 /* Statistics requests. */
4773 case OFPTYPE_DESC_STATS_REQUEST:
4774 return handle_desc_stats_request(ofconn, oh);
4776 case OFPTYPE_FLOW_STATS_REQUEST:
4777 return handle_flow_stats_request(ofconn, oh);
4779 case OFPTYPE_AGGREGATE_STATS_REQUEST:
4780 return handle_aggregate_stats_request(ofconn, oh);
4782 case OFPTYPE_TABLE_STATS_REQUEST:
4783 return handle_table_stats_request(ofconn, oh);
4785 case OFPTYPE_PORT_STATS_REQUEST:
4786 return handle_port_stats_request(ofconn, oh);
4788 case OFPTYPE_QUEUE_STATS_REQUEST:
4789 return handle_queue_stats_request(ofconn, oh);
4791 case OFPTYPE_PORT_DESC_STATS_REQUEST:
4792 return handle_port_desc_stats_request(ofconn, oh);
4794 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
4795 return handle_flow_monitor_request(ofconn, oh);
4797 case OFPTYPE_METER_STATS_REQUEST:
4798 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
4799 return handle_meter_request(ofconn, oh, type);
4801 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
4802 return handle_meter_features_request(ofconn, oh);
4804 /* FIXME: Change the following once they are implemented: */
4805 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
4806 case OFPTYPE_GET_ASYNC_REQUEST:
4807 case OFPTYPE_GROUP_STATS_REQUEST:
4808 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
4809 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
4810 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
4811 return OFPERR_OFPBRC_BAD_TYPE;
4815 case OFPTYPE_FEATURES_REPLY:
4816 case OFPTYPE_GET_CONFIG_REPLY:
4817 case OFPTYPE_PACKET_IN:
4818 case OFPTYPE_FLOW_REMOVED:
4819 case OFPTYPE_PORT_STATUS:
4820 case OFPTYPE_BARRIER_REPLY:
4821 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
4822 case OFPTYPE_DESC_STATS_REPLY:
4823 case OFPTYPE_FLOW_STATS_REPLY:
4824 case OFPTYPE_QUEUE_STATS_REPLY:
4825 case OFPTYPE_PORT_STATS_REPLY:
4826 case OFPTYPE_TABLE_STATS_REPLY:
4827 case OFPTYPE_AGGREGATE_STATS_REPLY:
4828 case OFPTYPE_PORT_DESC_STATS_REPLY:
4829 case OFPTYPE_ROLE_REPLY:
4830 case OFPTYPE_FLOW_MONITOR_PAUSED:
4831 case OFPTYPE_FLOW_MONITOR_RESUMED:
4832 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
4833 case OFPTYPE_GET_ASYNC_REPLY:
4834 case OFPTYPE_GROUP_STATS_REPLY:
4835 case OFPTYPE_GROUP_DESC_STATS_REPLY:
4836 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
4837 case OFPTYPE_METER_STATS_REPLY:
4838 case OFPTYPE_METER_CONFIG_STATS_REPLY:
4839 case OFPTYPE_METER_FEATURES_STATS_REPLY:
4840 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
4842 return OFPERR_OFPBRC_BAD_TYPE;
4847 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
4849 int error = handle_openflow__(ofconn, ofp_msg);
4850 if (error && error != OFPROTO_POSTPONE) {
4851 ofconn_send_error(ofconn, ofp_msg->data, error);
4853 COVERAGE_INC(ofproto_recv_openflow);
4854 return error != OFPROTO_POSTPONE;
4857 /* Asynchronous operations. */
4859 /* Creates and returns a new ofopgroup that is not associated with any
4860 * OpenFlow connection.
4862 * The caller should add operations to the returned group with
4863 * ofoperation_create() and then submit it with ofopgroup_submit(). */
4864 static struct ofopgroup *
4865 ofopgroup_create_unattached(struct ofproto *ofproto)
4867 struct ofopgroup *group = xzalloc(sizeof *group);
4868 group->ofproto = ofproto;
4869 list_init(&group->ofproto_node);
4870 list_init(&group->ops);
4871 list_init(&group->ofconn_node);
4875 /* Creates and returns a new ofopgroup for 'ofproto'.
4877 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
4878 * connection. The 'request' and 'buffer_id' arguments are ignored.
4880 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
4881 * If the ofopgroup eventually fails, then the error reply will include
4882 * 'request'. If the ofopgroup eventually succeeds, then the packet with
4883 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
4885 * The caller should add operations to the returned group with
4886 * ofoperation_create() and then submit it with ofopgroup_submit(). */
4887 static struct ofopgroup *
4888 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
4889 const struct ofp_header *request, uint32_t buffer_id)
4891 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
4893 size_t request_len = ntohs(request->length);
4895 ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
4897 ofconn_add_opgroup(ofconn, &group->ofconn_node);
4898 group->ofconn = ofconn;
4899 group->request = xmemdup(request, MIN(request_len, 64));
4900 group->buffer_id = buffer_id;
4905 /* Submits 'group' for processing.
4907 * If 'group' contains no operations (e.g. none were ever added, or all of the
4908 * ones that were added completed synchronously), then it is destroyed
4909 * immediately. Otherwise it is added to the ofproto's list of pending
4912 ofopgroup_submit(struct ofopgroup *group)
4914 if (!group->n_running) {
4915 ofopgroup_complete(group);
4917 list_push_back(&group->ofproto->pending, &group->ofproto_node);
4918 group->ofproto->n_pending++;
4923 ofopgroup_complete(struct ofopgroup *group)
4925 struct ofproto *ofproto = group->ofproto;
4927 struct ofconn *abbrev_ofconn;
4928 ovs_be32 abbrev_xid;
4930 struct ofoperation *op, *next_op;
4933 ovs_assert(!group->n_running);
4936 LIST_FOR_EACH (op, group_node, &group->ops) {
4943 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
4944 LIST_FOR_EACH (op, group_node, &group->ops) {
4945 if (op->type != OFOPERATION_DELETE) {
4946 struct ofpbuf *packet;
4949 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
4953 error = rule_execute(op->rule, in_port, packet);
4960 if (!error && !list_is_empty(&group->ofconn_node)) {
4961 abbrev_ofconn = group->ofconn;
4962 abbrev_xid = group->request->xid;
4964 abbrev_ofconn = NULL;
4965 abbrev_xid = htonl(0);
4967 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
4968 struct rule *rule = op->rule;
4970 /* We generally want to report the change to active OpenFlow flow
4971 monitors (e.g. NXST_FLOW_MONITOR). There are three exceptions:
4973 - The operation failed.
4975 - The affected rule is not visible to controllers.
4977 - The operation's only effect was to update rule->modified. */
4979 || ofproto_rule_is_hidden(rule)
4980 || (op->type == OFOPERATION_MODIFY
4982 && rule->flow_cookie == op->flow_cookie))) {
4983 /* Check that we can just cast from ofoperation_type to
4984 * nx_flow_update_event. */
4985 enum nx_flow_update_event event_type;
4988 case OFOPERATION_ADD:
4989 case OFOPERATION_REPLACE:
4990 event_type = NXFME_ADDED;
4993 case OFOPERATION_DELETE:
4994 event_type = NXFME_DELETED;
4997 case OFOPERATION_MODIFY:
4998 event_type = NXFME_MODIFIED;
5005 ofmonitor_report(ofproto->connmgr, rule, event_type,
5006 op->reason, abbrev_ofconn, abbrev_xid);
5009 rule->pending = NULL;
5012 case OFOPERATION_ADD:
5016 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
5017 if (vid_mask == VLAN_VID_MASK) {
5018 if (ofproto->vlan_bitmap) {
5019 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
5020 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
5021 bitmap_set1(ofproto->vlan_bitmap, vid);
5022 ofproto->vlans_changed = true;
5025 ofproto->vlans_changed = true;
5029 ovs_rwlock_wrlock(&rule->rwlock);
5030 oftable_remove_rule(rule);
5031 ofproto_rule_destroy__(rule);
5035 case OFOPERATION_DELETE:
5036 ovs_assert(!op->error);
5037 ofproto_rule_destroy__(rule);
5041 case OFOPERATION_MODIFY:
5042 case OFOPERATION_REPLACE:
5044 long long int now = time_msec();
5046 rule->modified = now;
5047 if (op->type == OFOPERATION_REPLACE) {
5048 rule->created = rule->used = now;
5051 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
5052 ovs_mutex_lock(&rule->timeout_mutex);
5053 rule->idle_timeout = op->idle_timeout;
5054 rule->hard_timeout = op->hard_timeout;
5055 ovs_mutex_unlock(&rule->timeout_mutex);
5057 free(rule->ofpacts);
5059 ovs_rwlock_wrlock(&rule->rwlock);
5060 rule->ofpacts = op->ofpacts;
5061 rule->ofpacts_len = op->ofpacts_len;
5062 ovs_rwlock_unlock(&rule->rwlock);
5065 op->ofpacts_len = 0;
5067 rule->send_flow_removed = op->send_flow_removed;
5075 ofoperation_destroy(op);
5078 ofmonitor_flush(ofproto->connmgr);
5080 if (!list_is_empty(&group->ofproto_node)) {
5081 ovs_assert(ofproto->n_pending > 0);
5082 ofproto->n_pending--;
5083 list_remove(&group->ofproto_node);
5085 if (!list_is_empty(&group->ofconn_node)) {
5086 list_remove(&group->ofconn_node);
5088 ofconn_send_error(group->ofconn, group->request, error);
5090 connmgr_retry(ofproto->connmgr);
5092 free(group->request);
5096 /* Initiates a new operation on 'rule', of the specified 'type', within
5097 * 'group'. Prior to calling, 'rule' must not have any pending operation.
5099 * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
5100 * the flow is being deleted. For other 'type's, 'reason' is ignored (use 0).
5102 * Returns the newly created ofoperation (which is also available as
5103 * rule->pending). */
5104 static struct ofoperation *
5105 ofoperation_create(struct ofopgroup *group, struct rule *rule,
5106 enum ofoperation_type type,
5107 enum ofp_flow_removed_reason reason)
5109 struct ofproto *ofproto = group->ofproto;
5110 struct ofoperation *op;
5112 ovs_assert(!rule->pending);
5114 op = rule->pending = xzalloc(sizeof *op);
5116 list_push_back(&group->ops, &op->group_node);
5119 op->reason = reason;
5120 op->flow_cookie = rule->flow_cookie;
5121 ovs_mutex_lock(&rule->timeout_mutex);
5122 op->idle_timeout = rule->idle_timeout;
5123 op->hard_timeout = rule->hard_timeout;
5124 ovs_mutex_unlock(&rule->timeout_mutex);
5125 op->send_flow_removed = rule->send_flow_removed;
5129 if (type == OFOPERATION_DELETE) {
5130 hmap_insert(&ofproto->deletions, &op->hmap_node,
5131 cls_rule_hash(&rule->cr, rule->table_id));
5138 ofoperation_destroy(struct ofoperation *op)
5140 struct ofopgroup *group = op->group;
5143 op->rule->pending = NULL;
5145 if (op->type == OFOPERATION_DELETE) {
5146 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
5148 list_remove(&op->group_node);
5153 /* Indicates that 'op' completed with status 'error', which is either 0 to
5154 * indicate success or an OpenFlow error code on failure.
5156 * If 'error' is 0, indicating success, the operation will be committed
5157 * permanently to the flow table.
5159 * If 'error' is nonzero, then generally the operation will be rolled back:
5161 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
5162 * restores the original rule. The caller must have uninitialized any
5163 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
5164 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
5165 * and 7 for the new rule, calling its ->rule_dealloc() function.
5167 * - If 'op' is a "modify flow" operation, ofproto restores the original
5170 * - 'op' must not be a "delete flow" operation. Removing a rule is not
5171 * allowed to fail. It must always succeed.
5173 * Please see the large comment in ofproto/ofproto-provider.h titled
5174 * "Asynchronous Operation Support" for more information. */
5176 ofoperation_complete(struct ofoperation *op, enum ofperr error)
5178 struct ofopgroup *group = op->group;
5180 ovs_assert(op->rule->pending == op);
5181 ovs_assert(group->n_running > 0);
5182 ovs_assert(!error || op->type != OFOPERATION_DELETE);
5185 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
5186 ofopgroup_complete(group);
5191 pick_datapath_id(const struct ofproto *ofproto)
5193 const struct ofport *port;
5195 port = ofproto_get_port(ofproto, OFPP_LOCAL);
5197 uint8_t ea[ETH_ADDR_LEN];
5200 error = netdev_get_etheraddr(port->netdev, ea);
5202 return eth_addr_to_uint64(ea);
5204 VLOG_WARN("%s: could not get MAC address for %s (%s)",
5205 ofproto->name, netdev_get_name(port->netdev),
5206 ovs_strerror(error));
5208 return ofproto->fallback_dpid;
5212 pick_fallback_dpid(void)
5214 uint8_t ea[ETH_ADDR_LEN];
5215 eth_addr_nicira_random(ea);
5216 return eth_addr_to_uint64(ea);
5219 /* Table overflow policy. */
5221 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
5222 * to NULL if the table is not configured to evict rules or if the table
5223 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
5224 * or with no timeouts are not evictable.) */
5226 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
5228 struct eviction_group *evg;
5231 if (!table->eviction_fields) {
5235 /* In the common case, the outer and inner loops here will each be entered
5238 * - The inner loop normally "return"s in its first iteration. If the
5239 * eviction group has any evictable rules, then it always returns in
5242 * - The outer loop only iterates more than once if the largest eviction
5243 * group has no evictable rules.
5245 * - The outer loop can exit only if table's 'max_flows' is all filled up
5246 * by unevictable rules. */
5247 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
5250 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
5251 if (!ovs_rwlock_trywrlock(&rule->rwlock)) {
5261 /* Searches 'ofproto' for tables that have more flows than their configured
5262 * maximum and that have flow eviction enabled, and evicts as many flows as
5263 * necessary and currently feasible from them.
5265 * This triggers only when an OpenFlow table has N flows in it and then the
5266 * client configures a maximum number of flows less than N. */
5268 ofproto_evict(struct ofproto *ofproto)
5270 struct ofopgroup *group;
5271 struct oftable *table;
5273 group = ofopgroup_create_unattached(ofproto);
5274 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
5275 while (table->eviction_fields) {
5279 ovs_rwlock_rdlock(&table->cls.rwlock);
5280 n_rules = classifier_count(&table->cls);
5281 ovs_rwlock_unlock(&table->cls.rwlock);
5283 if (n_rules <= table->max_flows) {
5287 if (!choose_rule_to_evict(table, &rule)) {
5291 if (rule->pending) {
5292 ovs_rwlock_unlock(&rule->rwlock);
5296 ofoperation_create(group, rule,
5297 OFOPERATION_DELETE, OFPRR_EVICTION);
5298 oftable_remove_rule(rule);
5299 ofproto->ofproto_class->rule_delete(rule);
5302 ofopgroup_submit(group);
5305 /* Eviction groups. */
5307 /* Returns the priority to use for an eviction_group that contains 'n_rules'
5308 * rules. The priority contains low-order random bits to ensure that eviction
5309 * groups with the same number of rules are prioritized randomly. */
5311 eviction_group_priority(size_t n_rules)
5313 uint16_t size = MIN(UINT16_MAX, n_rules);
5314 return (size << 16) | random_uint16();
5317 /* Updates 'evg', an eviction_group within 'table', following a change that
5318 * adds or removes rules in 'evg'. */
5320 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
5322 heap_change(&table->eviction_groups_by_size, &evg->size_node,
5323 eviction_group_priority(heap_count(&evg->rules)));
5326 /* Destroys 'evg', an eviction_group within 'table':
5328 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
5329 * rules themselves, just removes them from the eviction group.)
5331 * - Removes 'evg' from 'table'.
5335 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
5337 while (!heap_is_empty(&evg->rules)) {
5340 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
5341 rule->eviction_group = NULL;
5343 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
5344 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
5345 heap_destroy(&evg->rules);
5349 /* Removes 'rule' from its eviction group, if any. */
5351 eviction_group_remove_rule(struct rule *rule)
5353 if (rule->eviction_group) {
5354 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5355 struct eviction_group *evg = rule->eviction_group;
5357 rule->eviction_group = NULL;
5358 heap_remove(&evg->rules, &rule->evg_node);
5359 if (heap_is_empty(&evg->rules)) {
5360 eviction_group_destroy(table, evg);
5362 eviction_group_resized(table, evg);
5367 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
5368 * returns the hash value. */
5370 eviction_group_hash_rule(struct rule *rule)
5372 struct oftable *table = &rule->ofproto->tables[rule->table_id];
5373 const struct mf_subfield *sf;
5377 hash = table->eviction_group_id_basis;
5378 miniflow_expand(&rule->cr.match.flow, &flow);
5379 for (sf = table->eviction_fields;
5380 sf < &table->eviction_fields[table->n_eviction_fields];
5383 if (mf_are_prereqs_ok(sf->field, &flow)) {
5384 union mf_value value;
5386 mf_get_value(sf->field, &flow, &value);
5388 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
5390 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
5391 unsigned int start = sf->ofs + sf->n_bits;
5392 bitwise_zero(&value, sf->field->n_bytes, start,
5393 sf->field->n_bytes * 8 - start);
5395 hash = hash_bytes(&value, sf->field->n_bytes, hash);
5397 hash = hash_int(hash, 0);
5404 /* Returns an eviction group within 'table' with the given 'id', creating one
5406 static struct eviction_group *
5407 eviction_group_find(struct oftable *table, uint32_t id)
5409 struct eviction_group *evg;
5411 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
5415 evg = xmalloc(sizeof *evg);
5416 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
5417 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
5418 eviction_group_priority(0));
5419 heap_init(&evg->rules);
5424 /* Returns an eviction priority for 'rule'. The return value should be
5425 * interpreted so that higher priorities make a rule more attractive candidates
5428 rule_eviction_priority(struct rule *rule)
5430 long long int hard_expiration;
5431 long long int idle_expiration;
5432 long long int expiration;
5433 uint32_t expiration_offset;
5435 /* Calculate time of expiration. */
5436 ovs_mutex_lock(&rule->timeout_mutex);
5437 hard_expiration = (rule->hard_timeout
5438 ? rule->modified + rule->hard_timeout * 1000
5440 idle_expiration = (rule->idle_timeout
5441 ? rule->used + rule->idle_timeout * 1000
5443 expiration = MIN(hard_expiration, idle_expiration);
5444 ovs_mutex_unlock(&rule->timeout_mutex);
5445 if (expiration == LLONG_MAX) {
5449 /* Calculate the time of expiration as a number of (approximate) seconds
5450 * after program startup.
5452 * This should work OK for program runs that last UINT32_MAX seconds or
5453 * less. Therefore, please restart OVS at least once every 136 years. */
5454 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
5456 /* Invert the expiration offset because we're using a max-heap. */
5457 return UINT32_MAX - expiration_offset;
5460 /* Adds 'rule' to an appropriate eviction group for its oftable's
5461 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
5462 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
5465 * The caller must ensure that 'rule' is not already in an eviction group. */
5467 eviction_group_add_rule(struct rule *rule)
5469 struct ofproto *ofproto = rule->ofproto;
5470 struct oftable *table = &ofproto->tables[rule->table_id];
5473 ovs_mutex_lock(&rule->timeout_mutex);
5474 has_timeout = rule->hard_timeout || rule->idle_timeout;
5475 ovs_mutex_unlock(&rule->timeout_mutex);
5477 if (table->eviction_fields && has_timeout) {
5478 struct eviction_group *evg;
5480 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
5482 rule->eviction_group = evg;
5483 heap_insert(&evg->rules, &rule->evg_node,
5484 rule_eviction_priority(rule));
5485 eviction_group_resized(table, evg);
5491 /* Initializes 'table'. */
5493 oftable_init(struct oftable *table)
5495 memset(table, 0, sizeof *table);
5496 classifier_init(&table->cls);
5497 table->max_flows = UINT_MAX;
5500 /* Destroys 'table', including its classifier and eviction groups.
5502 * The caller is responsible for freeing 'table' itself. */
5504 oftable_destroy(struct oftable *table)
5506 ovs_rwlock_rdlock(&table->cls.rwlock);
5507 ovs_assert(classifier_is_empty(&table->cls));
5508 ovs_rwlock_unlock(&table->cls.rwlock);
5509 oftable_disable_eviction(table);
5510 classifier_destroy(&table->cls);
5514 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
5515 * string, then 'table' will use its default name.
5517 * This only affects the name exposed for a table exposed through the OpenFlow
5518 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
5520 oftable_set_name(struct oftable *table, const char *name)
5522 if (name && name[0]) {
5523 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
5524 if (!table->name || strncmp(name, table->name, len)) {
5526 table->name = xmemdup0(name, len);
5534 /* oftables support a choice of two policies when adding a rule would cause the
5535 * number of flows in the table to exceed the configured maximum number: either
5536 * they can refuse to add the new flow or they can evict some existing flow.
5537 * This function configures the former policy on 'table'. */
5539 oftable_disable_eviction(struct oftable *table)
5541 if (table->eviction_fields) {
5542 struct eviction_group *evg, *next;
5544 HMAP_FOR_EACH_SAFE (evg, next, id_node,
5545 &table->eviction_groups_by_id) {
5546 eviction_group_destroy(table, evg);
5548 hmap_destroy(&table->eviction_groups_by_id);
5549 heap_destroy(&table->eviction_groups_by_size);
5551 free(table->eviction_fields);
5552 table->eviction_fields = NULL;
5553 table->n_eviction_fields = 0;
5557 /* oftables support a choice of two policies when adding a rule would cause the
5558 * number of flows in the table to exceed the configured maximum number: either
5559 * they can refuse to add the new flow or they can evict some existing flow.
5560 * This function configures the latter policy on 'table', with fairness based
5561 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
5562 * 'n_fields' as 0 disables fairness.) */
5564 oftable_enable_eviction(struct oftable *table,
5565 const struct mf_subfield *fields, size_t n_fields)
5567 struct cls_cursor cursor;
5570 if (table->eviction_fields
5571 && n_fields == table->n_eviction_fields
5573 || !memcmp(fields, table->eviction_fields,
5574 n_fields * sizeof *fields))) {
5579 oftable_disable_eviction(table);
5581 table->n_eviction_fields = n_fields;
5582 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
5584 table->eviction_group_id_basis = random_uint32();
5585 hmap_init(&table->eviction_groups_by_id);
5586 heap_init(&table->eviction_groups_by_size);
5588 ovs_rwlock_rdlock(&table->cls.rwlock);
5589 cls_cursor_init(&cursor, &table->cls, NULL);
5590 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
5591 eviction_group_add_rule(rule);
5593 ovs_rwlock_unlock(&table->cls.rwlock);
5596 /* Removes 'rule' from the oftable that contains it. */
5598 oftable_remove_rule__(struct ofproto *ofproto, struct classifier *cls,
5600 OVS_REQ_WRLOCK(cls->rwlock) OVS_RELEASES(rule->rwlock)
5602 classifier_remove(cls, &rule->cr);
5603 if (rule->meter_id) {
5604 list_remove(&rule->meter_list_node);
5606 cookies_remove(ofproto, rule);
5607 eviction_group_remove_rule(rule);
5608 ovs_mutex_lock(&ofproto->expirable_mutex);
5609 if (!list_is_empty(&rule->expirable)) {
5610 list_remove(&rule->expirable);
5612 ovs_mutex_unlock(&ofproto->expirable_mutex);
5613 if (!list_is_empty(&rule->meter_list_node)) {
5614 list_remove(&rule->meter_list_node);
5616 ovs_rwlock_unlock(&rule->rwlock);
5620 oftable_remove_rule(struct rule *rule)
5622 struct ofproto *ofproto = rule->ofproto;
5623 struct oftable *table = &ofproto->tables[rule->table_id];
5625 ovs_rwlock_wrlock(&table->cls.rwlock);
5626 oftable_remove_rule__(ofproto, &table->cls, rule);
5627 ovs_rwlock_unlock(&table->cls.rwlock);
5630 /* Inserts 'rule' into its oftable, which must not already contain any rule for
5631 * the same cls_rule. */
5633 oftable_insert_rule(struct rule *rule)
5635 struct ofproto *ofproto = rule->ofproto;
5636 struct oftable *table = &ofproto->tables[rule->table_id];
5639 ovs_mutex_lock(&rule->timeout_mutex);
5640 may_expire = rule->hard_timeout || rule->idle_timeout;
5641 ovs_mutex_unlock(&rule->timeout_mutex);
5644 ovs_mutex_lock(&ofproto->expirable_mutex);
5645 list_insert(&ofproto->expirable, &rule->expirable);
5646 ovs_mutex_unlock(&ofproto->expirable_mutex);
5648 cookies_insert(ofproto, rule);
5649 if (rule->meter_id) {
5650 struct meter *meter = ofproto->meters[rule->meter_id];
5651 list_insert(&meter->rules, &rule->meter_list_node);
5653 ovs_rwlock_wrlock(&table->cls.rwlock);
5654 classifier_insert(&table->cls, &rule->cr);
5655 ovs_rwlock_unlock(&table->cls.rwlock);
5656 eviction_group_add_rule(rule);
5659 /* unixctl commands. */
5662 ofproto_lookup(const char *name)
5664 struct ofproto *ofproto;
5666 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
5668 if (!strcmp(ofproto->name, name)) {
5676 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
5677 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
5679 struct ofproto *ofproto;
5683 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
5684 ds_put_format(&results, "%s\n", ofproto->name);
5686 unixctl_command_reply(conn, ds_cstr(&results));
5687 ds_destroy(&results);
5691 ofproto_unixctl_init(void)
5693 static bool registered;
5699 unixctl_command_register("ofproto/list", "", 0, 0,
5700 ofproto_unixctl_list, NULL);
5703 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
5705 * This is deprecated. It is only for compatibility with broken device drivers
5706 * in old versions of Linux that do not properly support VLANs when VLAN
5707 * devices are not used. When broken device drivers are no longer in
5708 * widespread use, we will delete these interfaces. */
5710 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
5711 * (exactly) by an OpenFlow rule in 'ofproto'. */
5713 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
5715 const struct oftable *oftable;
5717 free(ofproto->vlan_bitmap);
5718 ofproto->vlan_bitmap = bitmap_allocate(4096);
5719 ofproto->vlans_changed = false;
5721 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
5722 const struct cls_table *table;
5724 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
5725 if (minimask_get_vid_mask(&table->mask) == VLAN_VID_MASK) {
5726 const struct cls_rule *rule;
5728 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
5729 uint16_t vid = miniflow_get_vid(&rule->match.flow);
5730 bitmap_set1(vlan_bitmap, vid);
5731 bitmap_set1(ofproto->vlan_bitmap, vid);
5738 /* Returns true if new VLANs have come into use by the flow table since the
5739 * last call to ofproto_get_vlan_usage().
5741 * We don't track when old VLANs stop being used. */
5743 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
5745 return ofproto->vlans_changed;
5748 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
5749 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
5750 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
5751 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
5752 * then the VLAN device is un-enslaved. */
5754 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
5755 ofp_port_t realdev_ofp_port, int vid)
5757 struct ofport *ofport;
5760 ovs_assert(vlandev_ofp_port != realdev_ofp_port);
5762 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
5764 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
5765 ofproto->name, vlandev_ofp_port);
5769 if (!ofproto->ofproto_class->set_realdev) {
5770 if (!vlandev_ofp_port) {
5773 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
5777 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
5779 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
5780 ofproto->name, vlandev_ofp_port,
5781 netdev_get_name(ofport->netdev), ovs_strerror(error));