2 * Copyright (c) 2009, 2010, 2011, 2012 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.
25 #include "byte-order.h"
26 #include "classifier.h"
29 #include "dynamic-string.h"
32 #include "meta-flow.h"
35 #include "ofp-actions.h"
36 #include "ofp-errors.h"
37 #include "ofp-print.h"
40 #include "ofproto-provider.h"
41 #include "openflow/nicira-ext.h"
42 #include "openflow/openflow.h"
46 #include "poll-loop.h"
52 #include "unaligned.h"
56 VLOG_DEFINE_THIS_MODULE(ofproto);
58 COVERAGE_DEFINE(ofproto_error);
59 COVERAGE_DEFINE(ofproto_flush);
60 COVERAGE_DEFINE(ofproto_no_packet_in);
61 COVERAGE_DEFINE(ofproto_packet_out);
62 COVERAGE_DEFINE(ofproto_queue_req);
63 COVERAGE_DEFINE(ofproto_recv_openflow);
64 COVERAGE_DEFINE(ofproto_reinit_ports);
65 COVERAGE_DEFINE(ofproto_uninstallable);
66 COVERAGE_DEFINE(ofproto_update_port);
69 S_OPENFLOW, /* Processing OpenFlow commands. */
70 S_EVICT, /* Evicting flows from over-limit tables. */
71 S_FLUSH, /* Deleting all flow table rules. */
74 enum ofoperation_type {
80 /* A single OpenFlow request can execute any number of operations. The
81 * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
82 * ofconn to which an error reply should be sent if necessary.
84 * ofproto initiates some operations internally. These operations are still
85 * assigned to groups but will not have an associated ofconn. */
87 struct ofproto *ofproto; /* Owning ofproto. */
88 struct list ofproto_node; /* In ofproto's "pending" list. */
89 struct list ops; /* List of "struct ofoperation"s. */
90 int n_running; /* Number of ops still pending. */
92 /* Data needed to send OpenFlow reply on failure or to send a buffered
95 * If list_is_empty(ofconn_node) then this ofopgroup never had an
96 * associated ofconn or its ofconn's connection dropped after it initiated
97 * the operation. In the latter case 'ofconn' is a wild pointer that
98 * refers to freed memory, so the 'ofconn' member must be used only if
99 * !list_is_empty(ofconn_node).
101 struct list ofconn_node; /* In ofconn's list of pending opgroups. */
102 struct ofconn *ofconn; /* ofconn for reply (but see note above). */
103 struct ofp_header *request; /* Original request (truncated at 64 bytes). */
104 uint32_t buffer_id; /* Buffer id from original request. */
107 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
108 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
109 const struct ofp_header *,
111 static void ofopgroup_submit(struct ofopgroup *);
112 static void ofopgroup_complete(struct ofopgroup *);
114 /* A single flow table operation. */
116 struct ofopgroup *group; /* Owning group. */
117 struct list group_node; /* In ofopgroup's "ops" list. */
118 struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
119 struct rule *rule; /* Rule being operated upon. */
120 enum ofoperation_type type; /* Type of operation. */
122 /* OFOPERATION_ADD. */
123 struct rule *victim; /* Rule being replaced, if any.. */
125 /* OFOPERATION_MODIFY: The old actions, if the actions are changing. */
126 struct ofpact *ofpacts;
129 ovs_be64 flow_cookie; /* Rule's old flow cookie. */
130 enum ofperr error; /* 0 if no error. */
133 static struct ofoperation *ofoperation_create(struct ofopgroup *,
135 enum ofoperation_type);
136 static void ofoperation_destroy(struct ofoperation *);
139 static void oftable_init(struct oftable *);
140 static void oftable_destroy(struct oftable *);
142 static void oftable_set_name(struct oftable *, const char *name);
144 static void oftable_disable_eviction(struct oftable *);
145 static void oftable_enable_eviction(struct oftable *,
146 const struct mf_subfield *fields,
149 static void oftable_remove_rule(struct rule *);
150 static struct rule *oftable_replace_rule(struct rule *);
151 static void oftable_substitute_rule(struct rule *old, struct rule *new);
153 /* A set of rules within a single OpenFlow table (oftable) that have the same
154 * values for the oftable's eviction_fields. A rule to be evicted, when one is
155 * needed, is taken from the eviction group that contains the greatest number
158 * An oftable owns any number of eviction groups, each of which contains any
161 * Membership in an eviction group is imprecise, based on the hash of the
162 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
163 * That is, if two rules have different eviction_fields, but those
164 * eviction_fields hash to the same value, then they will belong to the same
165 * eviction_group anyway.
167 * (When eviction is not enabled on an oftable, we don't track any eviction
168 * groups, to save time and space.) */
169 struct eviction_group {
170 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
171 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
172 struct heap rules; /* Contains "struct rule"s. */
175 static struct rule *choose_rule_to_evict(struct oftable *);
176 static void ofproto_evict(struct ofproto *);
177 static uint32_t rule_eviction_priority(struct rule *);
180 static void ofport_destroy__(struct ofport *);
181 static void ofport_destroy(struct ofport *);
183 static void update_port(struct ofproto *, const char *devname);
184 static int init_ports(struct ofproto *);
185 static void reinit_ports(struct ofproto *);
188 static void ofproto_rule_destroy__(struct rule *);
189 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
190 static bool rule_is_modifiable(const struct rule *);
191 static bool rule_is_hidden(const struct rule *);
194 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
195 const struct ofputil_flow_mod *,
196 const struct ofp_header *);
197 static void delete_flow__(struct rule *, struct ofopgroup *);
198 static bool handle_openflow(struct ofconn *, struct ofpbuf *);
199 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
200 const struct ofputil_flow_mod *,
201 const struct ofp_header *);
204 static uint64_t pick_datapath_id(const struct ofproto *);
205 static uint64_t pick_fallback_dpid(void);
206 static void ofproto_destroy__(struct ofproto *);
207 static void update_mtu(struct ofproto *, struct ofport *);
210 static void ofproto_unixctl_init(void);
212 /* All registered ofproto classes, in probe order. */
213 static const struct ofproto_class **ofproto_classes;
214 static size_t n_ofproto_classes;
215 static size_t allocated_ofproto_classes;
217 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
218 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
220 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
223 ofproto_initialize(void)
229 ofproto_class_register(&ofproto_dpif_class);
233 /* 'type' should be a normalized datapath type, as returned by
234 * ofproto_normalize_type(). Returns the corresponding ofproto_class
235 * structure, or a null pointer if there is none registered for 'type'. */
236 static const struct ofproto_class *
237 ofproto_class_find__(const char *type)
241 ofproto_initialize();
242 for (i = 0; i < n_ofproto_classes; i++) {
243 const struct ofproto_class *class = ofproto_classes[i];
248 class->enumerate_types(&types);
249 found = sset_contains(&types, type);
250 sset_destroy(&types);
256 VLOG_WARN("unknown datapath type %s", type);
260 /* Registers a new ofproto class. After successful registration, new ofprotos
261 * of that type can be created using ofproto_create(). */
263 ofproto_class_register(const struct ofproto_class *new_class)
267 for (i = 0; i < n_ofproto_classes; i++) {
268 if (ofproto_classes[i] == new_class) {
273 if (n_ofproto_classes >= allocated_ofproto_classes) {
274 ofproto_classes = x2nrealloc(ofproto_classes,
275 &allocated_ofproto_classes,
276 sizeof *ofproto_classes);
278 ofproto_classes[n_ofproto_classes++] = new_class;
282 /* Unregisters a datapath provider. 'type' must have been previously
283 * registered and not currently be in use by any ofprotos. After
284 * unregistration new datapaths of that type cannot be opened using
285 * ofproto_create(). */
287 ofproto_class_unregister(const struct ofproto_class *class)
291 for (i = 0; i < n_ofproto_classes; i++) {
292 if (ofproto_classes[i] == class) {
293 for (i++; i < n_ofproto_classes; i++) {
294 ofproto_classes[i - 1] = ofproto_classes[i];
300 VLOG_WARN("attempted to unregister an ofproto class that is not "
305 /* Clears 'types' and enumerates all registered ofproto types into it. The
306 * caller must first initialize the sset. */
308 ofproto_enumerate_types(struct sset *types)
312 ofproto_initialize();
313 for (i = 0; i < n_ofproto_classes; i++) {
314 ofproto_classes[i]->enumerate_types(types);
318 /* Returns the fully spelled out name for the given ofproto 'type'.
320 * Normalized type string can be compared with strcmp(). Unnormalized type
321 * string might be the same even if they have different spellings. */
323 ofproto_normalize_type(const char *type)
325 return type && type[0] ? type : "system";
328 /* Clears 'names' and enumerates the names of all known created ofprotos with
329 * the given 'type'. The caller must first initialize the sset. Returns 0 if
330 * successful, otherwise a positive errno value.
332 * Some kinds of datapaths might not be practically enumerable. This is not
333 * considered an error. */
335 ofproto_enumerate_names(const char *type, struct sset *names)
337 const struct ofproto_class *class = ofproto_class_find__(type);
338 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
342 ofproto_create(const char *datapath_name, const char *datapath_type,
343 struct ofproto **ofprotop)
345 const struct ofproto_class *class;
346 struct ofproto *ofproto;
351 ofproto_initialize();
352 ofproto_unixctl_init();
354 datapath_type = ofproto_normalize_type(datapath_type);
355 class = ofproto_class_find__(datapath_type);
357 VLOG_WARN("could not create datapath %s of unknown type %s",
358 datapath_name, datapath_type);
362 ofproto = class->alloc();
364 VLOG_ERR("failed to allocate datapath %s of type %s",
365 datapath_name, datapath_type);
370 memset(ofproto, 0, sizeof *ofproto);
371 ofproto->ofproto_class = class;
372 ofproto->name = xstrdup(datapath_name);
373 ofproto->type = xstrdup(datapath_type);
374 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
375 hash_string(ofproto->name, 0));
376 ofproto->datapath_id = 0;
377 ofproto_set_flow_eviction_threshold(ofproto,
378 OFPROTO_FLOW_EVICTON_THRESHOLD_DEFAULT);
379 ofproto->forward_bpdu = false;
380 ofproto->fallback_dpid = pick_fallback_dpid();
381 ofproto->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
382 ofproto->hw_desc = xstrdup(DEFAULT_HW_DESC);
383 ofproto->sw_desc = xstrdup(DEFAULT_SW_DESC);
384 ofproto->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
385 ofproto->dp_desc = xstrdup(DEFAULT_DP_DESC);
386 ofproto->frag_handling = OFPC_FRAG_NORMAL;
387 hmap_init(&ofproto->ports);
388 shash_init(&ofproto->port_by_name);
389 ofproto->tables = NULL;
390 ofproto->n_tables = 0;
391 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
392 ofproto->state = S_OPENFLOW;
393 list_init(&ofproto->pending);
394 ofproto->n_pending = 0;
395 hmap_init(&ofproto->deletions);
396 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
397 ofproto->first_op = ofproto->last_op = LLONG_MIN;
398 ofproto->next_op_report = LLONG_MAX;
399 ofproto->op_backoff = LLONG_MIN;
400 ofproto->vlan_bitmap = NULL;
401 ofproto->vlans_changed = false;
402 ofproto->min_mtu = INT_MAX;
404 error = ofproto->ofproto_class->construct(ofproto);
406 VLOG_ERR("failed to open datapath %s: %s",
407 datapath_name, strerror(error));
408 ofproto_destroy__(ofproto);
412 assert(ofproto->n_tables);
414 ofproto->datapath_id = pick_datapath_id(ofproto);
422 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
424 struct oftable *table;
426 assert(!ofproto->n_tables);
427 assert(n_tables >= 1 && n_tables <= 255);
429 ofproto->n_tables = n_tables;
430 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
431 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
437 ofproto_get_datapath_id(const struct ofproto *ofproto)
439 return ofproto->datapath_id;
443 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
445 uint64_t old_dpid = p->datapath_id;
446 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
447 if (p->datapath_id != old_dpid) {
448 /* Force all active connections to reconnect, since there is no way to
449 * notify a controller that the datapath ID has changed. */
450 ofproto_reconnect_controllers(p);
455 ofproto_set_controllers(struct ofproto *p,
456 const struct ofproto_controller *controllers,
457 size_t n_controllers)
459 connmgr_set_controllers(p->connmgr, controllers, n_controllers);
463 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
465 connmgr_set_fail_mode(p->connmgr, fail_mode);
468 /* Drops the connections between 'ofproto' and all of its controllers, forcing
469 * them to reconnect. */
471 ofproto_reconnect_controllers(struct ofproto *ofproto)
473 connmgr_reconnect(ofproto->connmgr);
476 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
477 * in-band control should guarantee access, in the same way that in-band
478 * control guarantees access to OpenFlow controllers. */
480 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
481 const struct sockaddr_in *extras, size_t n)
483 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
486 /* Sets the OpenFlow queue used by flows set up by in-band control on
487 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
488 * flows will use the default queue. */
490 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
492 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
495 /* Sets the number of flows at which eviction from the kernel flow table
498 ofproto_set_flow_eviction_threshold(struct ofproto *ofproto, unsigned threshold)
500 if (threshold < OFPROTO_FLOW_EVICTION_THRESHOLD_MIN) {
501 ofproto->flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_MIN;
503 ofproto->flow_eviction_threshold = threshold;
507 /* If forward_bpdu is true, the NORMAL action will forward frames with
508 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
509 * the NORMAL action will drop these frames. */
511 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
513 bool old_val = ofproto->forward_bpdu;
514 ofproto->forward_bpdu = forward_bpdu;
515 if (old_val != ofproto->forward_bpdu) {
516 if (ofproto->ofproto_class->forward_bpdu_changed) {
517 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
522 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
523 * 'idle_time', in seconds. */
525 ofproto_set_mac_idle_time(struct ofproto *ofproto, unsigned idle_time)
527 if (ofproto->ofproto_class->set_mac_idle_time) {
528 ofproto->ofproto_class->set_mac_idle_time(ofproto, idle_time);
533 ofproto_set_desc(struct ofproto *p,
534 const char *mfr_desc, const char *hw_desc,
535 const char *sw_desc, const char *serial_desc,
538 struct ofp_desc_stats *ods;
541 if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
542 VLOG_WARN("%s: truncating mfr_desc, must be less than %zu bytes",
543 p->name, sizeof ods->mfr_desc);
546 p->mfr_desc = xstrdup(mfr_desc);
549 if (strlen(hw_desc) >= sizeof ods->hw_desc) {
550 VLOG_WARN("%s: truncating hw_desc, must be less than %zu bytes",
551 p->name, sizeof ods->hw_desc);
554 p->hw_desc = xstrdup(hw_desc);
557 if (strlen(sw_desc) >= sizeof ods->sw_desc) {
558 VLOG_WARN("%s: truncating sw_desc, must be less than %zu bytes",
559 p->name, sizeof ods->sw_desc);
562 p->sw_desc = xstrdup(sw_desc);
565 if (strlen(serial_desc) >= sizeof ods->serial_num) {
566 VLOG_WARN("%s: truncating serial_desc, must be less than %zu "
567 "bytes", p->name, sizeof ods->serial_num);
569 free(p->serial_desc);
570 p->serial_desc = xstrdup(serial_desc);
573 if (strlen(dp_desc) >= sizeof ods->dp_desc) {
574 VLOG_WARN("%s: truncating dp_desc, must be less than %zu bytes",
575 p->name, sizeof ods->dp_desc);
578 p->dp_desc = xstrdup(dp_desc);
583 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
585 return connmgr_set_snoops(ofproto->connmgr, snoops);
589 ofproto_set_netflow(struct ofproto *ofproto,
590 const struct netflow_options *nf_options)
592 if (nf_options && sset_is_empty(&nf_options->collectors)) {
596 if (ofproto->ofproto_class->set_netflow) {
597 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
599 return nf_options ? EOPNOTSUPP : 0;
604 ofproto_set_sflow(struct ofproto *ofproto,
605 const struct ofproto_sflow_options *oso)
607 if (oso && sset_is_empty(&oso->targets)) {
611 if (ofproto->ofproto_class->set_sflow) {
612 return ofproto->ofproto_class->set_sflow(ofproto, oso);
614 return oso ? EOPNOTSUPP : 0;
618 /* Spanning Tree Protocol (STP) configuration. */
620 /* Configures STP on 'ofproto' using the settings defined in 's'. If
621 * 's' is NULL, disables STP.
623 * Returns 0 if successful, otherwise a positive errno value. */
625 ofproto_set_stp(struct ofproto *ofproto,
626 const struct ofproto_stp_settings *s)
628 return (ofproto->ofproto_class->set_stp
629 ? ofproto->ofproto_class->set_stp(ofproto, s)
633 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
634 * 'enabled' member of 's' is false, then the other members are not
637 * Returns 0 if successful, otherwise a positive errno value. */
639 ofproto_get_stp_status(struct ofproto *ofproto,
640 struct ofproto_stp_status *s)
642 return (ofproto->ofproto_class->get_stp_status
643 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
647 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
648 * in 's'. The caller is responsible for assigning STP port numbers
649 * (using the 'port_num' member in the range of 1 through 255, inclusive)
650 * and ensuring there are no duplicates. If the 's' is NULL, then STP
651 * is disabled on the port.
653 * Returns 0 if successful, otherwise a positive errno value.*/
655 ofproto_port_set_stp(struct ofproto *ofproto, uint16_t ofp_port,
656 const struct ofproto_port_stp_settings *s)
658 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
660 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
661 ofproto->name, ofp_port);
665 return (ofproto->ofproto_class->set_stp_port
666 ? ofproto->ofproto_class->set_stp_port(ofport, s)
670 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
671 * 's'. If the 'enabled' member in 's' is false, then the other members
672 * are not meaningful.
674 * Returns 0 if successful, otherwise a positive errno value.*/
676 ofproto_port_get_stp_status(struct ofproto *ofproto, uint16_t ofp_port,
677 struct ofproto_port_stp_status *s)
679 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
681 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
682 "port %"PRIu16, ofproto->name, ofp_port);
686 return (ofproto->ofproto_class->get_stp_port_status
687 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
691 /* Queue DSCP configuration. */
693 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
694 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
695 * to implement QoS. Instead, it is used to implement features which require
696 * knowledge of what queues exist on a port, and some basic information about
699 * Returns 0 if successful, otherwise a positive errno value. */
701 ofproto_port_set_queues(struct ofproto *ofproto, uint16_t ofp_port,
702 const struct ofproto_port_queue *queues,
705 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
708 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
709 ofproto->name, ofp_port);
713 return (ofproto->ofproto_class->set_queues
714 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
718 /* Connectivity Fault Management configuration. */
720 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
722 ofproto_port_clear_cfm(struct ofproto *ofproto, uint16_t ofp_port)
724 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
725 if (ofport && ofproto->ofproto_class->set_cfm) {
726 ofproto->ofproto_class->set_cfm(ofport, NULL);
730 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
731 * basic configuration from the configuration members in 'cfm', and the remote
732 * maintenance point ID from remote_mpid. Ignores the statistics members of
735 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
737 ofproto_port_set_cfm(struct ofproto *ofproto, uint16_t ofp_port,
738 const struct cfm_settings *s)
740 struct ofport *ofport;
743 ofport = ofproto_get_port(ofproto, ofp_port);
745 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
746 ofproto->name, ofp_port);
750 /* XXX: For configuration simplicity, we only support one remote_mpid
751 * outside of the CFM module. It's not clear if this is the correct long
752 * term solution or not. */
753 error = (ofproto->ofproto_class->set_cfm
754 ? ofproto->ofproto_class->set_cfm(ofport, s)
757 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
758 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
763 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
764 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
765 * 0 if LACP partner information is not current (generally indicating a
766 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
768 ofproto_port_is_lacp_current(struct ofproto *ofproto, uint16_t ofp_port)
770 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
771 return (ofport && ofproto->ofproto_class->port_is_lacp_current
772 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
778 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
779 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
780 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
781 * configuration plus, if there is more than one slave, a bonding
784 * If 'aux' is already registered then this function updates its configuration
785 * to 's'. Otherwise, this function registers a new bundle.
787 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
790 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
791 const struct ofproto_bundle_settings *s)
793 return (ofproto->ofproto_class->bundle_set
794 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
798 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
799 * If no such bundle has been registered, this has no effect. */
801 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
803 return ofproto_bundle_register(ofproto, aux, NULL);
807 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
808 * If 'aux' is already registered then this function updates its configuration
809 * to 's'. Otherwise, this function registers a new mirror. */
811 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
812 const struct ofproto_mirror_settings *s)
814 return (ofproto->ofproto_class->mirror_set
815 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
819 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
820 * If no mirror has been registered, this has no effect. */
822 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
824 return ofproto_mirror_register(ofproto, aux, NULL);
827 /* Retrieves statistics from mirror associated with client data pointer
828 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
829 * 'bytes', respectively. If a particular counters is not supported,
830 * the appropriate argument is set to UINT64_MAX. */
832 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
833 uint64_t *packets, uint64_t *bytes)
835 if (!ofproto->ofproto_class->mirror_get_stats) {
836 *packets = *bytes = UINT64_MAX;
840 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
844 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
845 * which all packets are flooded, instead of using MAC learning. If
846 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
848 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
851 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
853 return (ofproto->ofproto_class->set_flood_vlans
854 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
858 /* Returns true if 'aux' is a registered bundle that is currently in use as the
859 * output for a mirror. */
861 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
863 return (ofproto->ofproto_class->is_mirror_output_bundle
864 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
868 /* Configuration of OpenFlow tables. */
870 /* Returns the number of OpenFlow tables in 'ofproto'. */
872 ofproto_get_n_tables(const struct ofproto *ofproto)
874 return ofproto->n_tables;
877 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
878 * settings from 's'. 'table_id' must be in the range 0 through the number of
879 * OpenFlow tables in 'ofproto' minus 1, inclusive.
881 * For read-only tables, only the name may be configured. */
883 ofproto_configure_table(struct ofproto *ofproto, int table_id,
884 const struct ofproto_table_settings *s)
886 struct oftable *table;
888 assert(table_id >= 0 && table_id < ofproto->n_tables);
889 table = &ofproto->tables[table_id];
891 oftable_set_name(table, s->name);
893 if (table->flags & OFTABLE_READONLY) {
898 oftable_enable_eviction(table, s->groups, s->n_groups);
900 oftable_disable_eviction(table);
903 table->max_flows = s->max_flows;
904 if (classifier_count(&table->cls) > table->max_flows
905 && table->eviction_fields) {
906 /* 'table' contains more flows than allowed. We might not be able to
907 * evict them right away because of the asynchronous nature of flow
908 * table changes. Schedule eviction for later. */
909 switch (ofproto->state) {
911 ofproto->state = S_EVICT;
915 /* We're already deleting flows, nothing more to do. */
922 ofproto_has_snoops(const struct ofproto *ofproto)
924 return connmgr_has_snoops(ofproto->connmgr);
928 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
930 connmgr_get_snoops(ofproto->connmgr, snoops);
934 ofproto_flush__(struct ofproto *ofproto)
936 struct ofopgroup *group;
937 struct oftable *table;
939 if (ofproto->ofproto_class->flush) {
940 ofproto->ofproto_class->flush(ofproto);
943 group = ofopgroup_create_unattached(ofproto);
944 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
945 struct rule *rule, *next_rule;
946 struct cls_cursor cursor;
948 if (table->flags & OFTABLE_HIDDEN) {
952 cls_cursor_init(&cursor, &table->cls, NULL);
953 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
954 if (!rule->pending) {
955 ofoperation_create(group, rule, OFOPERATION_DELETE);
956 oftable_remove_rule(rule);
957 ofproto->ofproto_class->rule_destruct(rule);
961 ofopgroup_submit(group);
965 ofproto_destroy__(struct ofproto *ofproto)
967 struct oftable *table;
969 assert(list_is_empty(&ofproto->pending));
970 assert(!ofproto->n_pending);
972 connmgr_destroy(ofproto->connmgr);
974 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
977 free(ofproto->mfr_desc);
978 free(ofproto->hw_desc);
979 free(ofproto->sw_desc);
980 free(ofproto->serial_desc);
981 free(ofproto->dp_desc);
982 hmap_destroy(&ofproto->ports);
983 shash_destroy(&ofproto->port_by_name);
985 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
986 oftable_destroy(table);
988 free(ofproto->tables);
990 hmap_destroy(&ofproto->deletions);
992 free(ofproto->vlan_bitmap);
994 ofproto->ofproto_class->dealloc(ofproto);
998 ofproto_destroy(struct ofproto *p)
1000 struct ofport *ofport, *next_ofport;
1007 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1008 ofport_destroy(ofport);
1011 p->ofproto_class->destruct(p);
1012 ofproto_destroy__(p);
1015 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1016 * kernel datapath, for example, this destroys the datapath in the kernel, and
1017 * with the netdev-based datapath, it tears down the data structures that
1018 * represent the datapath.
1020 * The datapath should not be currently open as an ofproto. */
1022 ofproto_delete(const char *name, const char *type)
1024 const struct ofproto_class *class = ofproto_class_find__(type);
1025 return (!class ? EAFNOSUPPORT
1026 : !class->del ? EACCES
1027 : class->del(type, name));
1031 process_port_change(struct ofproto *ofproto, int error, char *devname)
1033 if (error == ENOBUFS) {
1034 reinit_ports(ofproto);
1035 } else if (!error) {
1036 update_port(ofproto, devname);
1042 ofproto_run(struct ofproto *p)
1044 struct sset changed_netdevs;
1045 const char *changed_netdev;
1046 struct ofport *ofport;
1049 error = p->ofproto_class->run(p);
1050 if (error && error != EAGAIN) {
1051 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, strerror(error));
1054 if (p->ofproto_class->port_poll) {
1057 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1058 process_port_change(p, error, devname);
1062 /* Update OpenFlow port status for any port whose netdev has changed.
1064 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1065 * destroyed, so it's not safe to update ports directly from the
1066 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1067 * need this two-phase approach. */
1068 sset_init(&changed_netdevs);
1069 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1070 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1071 if (ofport->change_seq != change_seq) {
1072 ofport->change_seq = change_seq;
1073 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1076 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1077 update_port(p, changed_netdev);
1079 sset_destroy(&changed_netdevs);
1083 connmgr_run(p->connmgr, handle_openflow);
1087 connmgr_run(p->connmgr, NULL);
1089 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1090 p->state = S_OPENFLOW;
1095 connmgr_run(p->connmgr, NULL);
1097 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1098 connmgr_flushed(p->connmgr);
1099 p->state = S_OPENFLOW;
1107 if (time_msec() >= p->next_op_report) {
1108 long long int ago = (time_msec() - p->first_op) / 1000;
1109 long long int interval = (p->last_op - p->first_op) / 1000;
1113 ds_put_format(&s, "%d flow_mods ",
1114 p->n_add + p->n_delete + p->n_modify);
1115 if (interval == ago) {
1116 ds_put_format(&s, "in the last %lld s", ago);
1117 } else if (interval) {
1118 ds_put_format(&s, "in the %lld s starting %lld s ago",
1121 ds_put_format(&s, "%lld s ago", ago);
1124 ds_put_cstr(&s, " (");
1126 ds_put_format(&s, "%d adds, ", p->n_add);
1129 ds_put_format(&s, "%d deletes, ", p->n_delete);
1132 ds_put_format(&s, "%d modifications, ", p->n_modify);
1135 ds_put_char(&s, ')');
1137 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1140 p->n_add = p->n_delete = p->n_modify = 0;
1141 p->next_op_report = LLONG_MAX;
1147 /* Performs periodic activity required by 'ofproto' that needs to be done
1148 * with the least possible latency.
1150 * It makes sense to call this function a couple of times per poll loop, to
1151 * provide a significant performance boost on some benchmarks with the
1152 * ofproto-dpif implementation. */
1154 ofproto_run_fast(struct ofproto *p)
1158 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1159 if (error && error != EAGAIN) {
1160 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1161 p->name, strerror(error));
1167 ofproto_wait(struct ofproto *p)
1169 struct ofport *ofport;
1171 p->ofproto_class->wait(p);
1172 if (p->ofproto_class->port_poll_wait) {
1173 p->ofproto_class->port_poll_wait(p);
1176 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1177 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1178 poll_immediate_wake();
1184 connmgr_wait(p->connmgr, true);
1189 connmgr_wait(p->connmgr, false);
1190 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1191 poll_immediate_wake();
1198 ofproto_is_alive(const struct ofproto *p)
1200 return connmgr_has_controllers(p->connmgr);
1203 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1204 * memory_report(). */
1206 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1208 const struct oftable *table;
1209 unsigned int n_rules;
1211 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1212 simap_increase(usage, "ops",
1213 ofproto->n_pending + hmap_count(&ofproto->deletions));
1216 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1217 n_rules += classifier_count(&table->cls);
1219 simap_increase(usage, "rules", n_rules);
1221 if (ofproto->ofproto_class->get_memory_usage) {
1222 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1225 connmgr_get_memory_usage(ofproto->connmgr, usage);
1229 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1232 connmgr_get_controller_info(ofproto->connmgr, info);
1236 ofproto_free_ofproto_controller_info(struct shash *info)
1238 connmgr_free_controller_info(info);
1241 /* Makes a deep copy of 'old' into 'port'. */
1243 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1245 port->name = xstrdup(old->name);
1246 port->type = xstrdup(old->type);
1247 port->ofp_port = old->ofp_port;
1250 /* Frees memory allocated to members of 'ofproto_port'.
1252 * Do not call this function on an ofproto_port obtained from
1253 * ofproto_port_dump_next(): that function retains ownership of the data in the
1256 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1258 free(ofproto_port->name);
1259 free(ofproto_port->type);
1262 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1264 * This function provides no status indication. An error status for the entire
1265 * dump operation is provided when it is completed by calling
1266 * ofproto_port_dump_done().
1269 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1270 const struct ofproto *ofproto)
1272 dump->ofproto = ofproto;
1273 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1277 /* Attempts to retrieve another port from 'dump', which must have been created
1278 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1279 * 'port' and returns true. On failure, returns false.
1281 * Failure might indicate an actual error or merely that the last port has been
1282 * dumped. An error status for the entire dump operation is provided when it
1283 * is completed by calling ofproto_port_dump_done().
1285 * The ofproto owns the data stored in 'port'. It will remain valid until at
1286 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1287 * ofproto_port_dump_done(). */
1289 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1290 struct ofproto_port *port)
1292 const struct ofproto *ofproto = dump->ofproto;
1298 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1301 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1307 /* Completes port table dump operation 'dump', which must have been created
1308 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1309 * error-free, otherwise a positive errno value describing the problem. */
1311 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1313 const struct ofproto *ofproto = dump->ofproto;
1315 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1318 return dump->error == EOF ? 0 : dump->error;
1321 /* Attempts to add 'netdev' as a port on 'ofproto'. If successful, returns 0
1322 * and sets '*ofp_portp' to the new port's OpenFlow port number (if 'ofp_portp'
1323 * is non-null). On failure, returns a positive errno value and sets
1324 * '*ofp_portp' to OFPP_NONE (if 'ofp_portp' is non-null). */
1326 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1327 uint16_t *ofp_portp)
1332 error = ofproto->ofproto_class->port_add(ofproto, netdev, &ofp_port);
1334 update_port(ofproto, netdev_get_name(netdev));
1337 *ofp_portp = error ? OFPP_NONE : ofp_port;
1342 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1343 * initializes '*port' appropriately; on failure, returns a positive errno
1346 * The caller owns the data in 'ofproto_port' and must free it with
1347 * ofproto_port_destroy() when it is no longer needed. */
1349 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1350 struct ofproto_port *port)
1354 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1356 memset(port, 0, sizeof *port);
1361 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1362 * Returns 0 if successful, otherwise a positive errno. */
1364 ofproto_port_del(struct ofproto *ofproto, uint16_t ofp_port)
1366 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1367 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1370 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1371 if (!error && ofport) {
1372 /* 'name' is the netdev's name and update_port() is going to close the
1373 * netdev. Just in case update_port() refers to 'name' after it
1374 * destroys 'ofport', make a copy of it around the update_port()
1376 char *devname = xstrdup(name);
1377 update_port(ofproto, devname);
1383 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1384 * performs the 'n_actions' actions in 'actions'. The new flow will not
1387 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1388 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1389 * controllers; otherwise, it will be hidden.
1391 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1393 * This is a helper function for in-band control and fail-open. */
1395 ofproto_add_flow(struct ofproto *ofproto, const struct cls_rule *cls_rule,
1396 const struct ofpact *ofpacts, size_t ofpacts_len)
1398 const struct rule *rule;
1400 rule = rule_from_cls_rule(classifier_find_rule_exactly(
1401 &ofproto->tables[0].cls, cls_rule));
1402 if (!rule || !ofpacts_equal(rule->ofpacts, rule->ofpacts_len,
1403 ofpacts, ofpacts_len)) {
1404 struct ofputil_flow_mod fm;
1406 memset(&fm, 0, sizeof fm);
1408 fm.buffer_id = UINT32_MAX;
1409 fm.ofpacts = xmemdup(ofpacts, ofpacts_len);
1410 fm.ofpacts_len = ofpacts_len;
1411 add_flow(ofproto, NULL, &fm, NULL);
1416 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1417 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1418 * operation cannot be initiated now but may be retried later.
1420 * This is a helper function for in-band control and fail-open. */
1422 ofproto_flow_mod(struct ofproto *ofproto, const struct ofputil_flow_mod *fm)
1424 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1427 /* Searches for a rule with matching criteria exactly equal to 'target' in
1428 * ofproto's table 0 and, if it finds one, deletes it.
1430 * This is a helper function for in-band control and fail-open. */
1432 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
1436 rule = rule_from_cls_rule(classifier_find_rule_exactly(
1437 &ofproto->tables[0].cls, target));
1439 /* No such rule -> success. */
1441 } else if (rule->pending) {
1442 /* An operation on the rule is already pending -> failure.
1443 * Caller must retry later if it's important. */
1446 /* Initiate deletion -> success. */
1447 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
1448 ofoperation_create(group, rule, OFOPERATION_DELETE);
1449 oftable_remove_rule(rule);
1450 ofproto->ofproto_class->rule_destruct(rule);
1451 ofopgroup_submit(group);
1457 /* Starts the process of deleting all of the flows from all of ofproto's flow
1458 * tables and then reintroducing the flows required by in-band control and
1459 * fail-open. The process will complete in a later call to ofproto_run(). */
1461 ofproto_flush_flows(struct ofproto *ofproto)
1463 COVERAGE_INC(ofproto_flush);
1464 ofproto->state = S_FLUSH;
1468 reinit_ports(struct ofproto *p)
1470 struct ofproto_port_dump dump;
1471 struct sset devnames;
1472 struct ofport *ofport;
1473 struct ofproto_port ofproto_port;
1474 const char *devname;
1476 COVERAGE_INC(ofproto_reinit_ports);
1478 sset_init(&devnames);
1479 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1480 sset_add(&devnames, netdev_get_name(ofport->netdev));
1482 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1483 sset_add(&devnames, ofproto_port.name);
1486 SSET_FOR_EACH (devname, &devnames) {
1487 update_port(p, devname);
1489 sset_destroy(&devnames);
1492 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1493 * pointer if the netdev cannot be opened. On success, also fills in
1495 static struct netdev *
1496 ofport_open(const struct ofproto *ofproto,
1497 const struct ofproto_port *ofproto_port,
1498 struct ofputil_phy_port *pp)
1500 enum netdev_flags flags;
1501 struct netdev *netdev;
1504 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1506 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1507 "cannot be opened (%s)",
1509 ofproto_port->name, ofproto_port->ofp_port,
1510 ofproto_port->name, strerror(error));
1514 pp->port_no = ofproto_port->ofp_port;
1515 netdev_get_etheraddr(netdev, pp->hw_addr);
1516 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1517 netdev_get_flags(netdev, &flags);
1518 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1519 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1520 netdev_get_features(netdev, &pp->curr, &pp->advertised,
1521 &pp->supported, &pp->peer);
1522 pp->curr_speed = netdev_features_to_bps(pp->curr);
1523 pp->max_speed = netdev_features_to_bps(pp->supported);
1528 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
1529 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1532 ofport_equal(const struct ofputil_phy_port *a,
1533 const struct ofputil_phy_port *b)
1535 return (eth_addr_equals(a->hw_addr, b->hw_addr)
1536 && a->state == b->state
1537 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1538 && a->curr == b->curr
1539 && a->advertised == b->advertised
1540 && a->supported == b->supported
1541 && a->peer == b->peer
1542 && a->curr_speed == b->curr_speed
1543 && a->max_speed == b->max_speed);
1546 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1547 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1548 * one with the same name or port number). */
1550 ofport_install(struct ofproto *p,
1551 struct netdev *netdev, const struct ofputil_phy_port *pp)
1553 const char *netdev_name = netdev_get_name(netdev);
1554 struct ofport *ofport;
1557 /* Create ofport. */
1558 ofport = p->ofproto_class->port_alloc();
1563 ofport->ofproto = p;
1564 ofport->netdev = netdev;
1565 ofport->change_seq = netdev_change_seq(netdev);
1567 ofport->ofp_port = pp->port_no;
1569 /* Add port to 'p'. */
1570 hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->ofp_port, 0));
1571 shash_add(&p->port_by_name, netdev_name, ofport);
1573 update_mtu(p, ofport);
1575 /* Let the ofproto_class initialize its private data. */
1576 error = p->ofproto_class->port_construct(ofport);
1580 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
1584 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
1585 p->name, netdev_name, strerror(error));
1587 ofport_destroy__(ofport);
1589 netdev_close(netdev);
1593 /* Removes 'ofport' from 'p' and destroys it. */
1595 ofport_remove(struct ofport *ofport)
1597 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
1599 ofport_destroy(ofport);
1602 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1605 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1607 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1609 ofport_remove(port);
1613 /* Updates 'port' with new 'pp' description.
1615 * Does not handle a name or port number change. The caller must implement
1616 * such a change as a delete followed by an add. */
1618 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
1620 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
1621 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
1622 | (pp->config & OFPUTIL_PC_PORT_DOWN));
1623 port->pp.state = pp->state;
1624 port->pp.curr = pp->curr;
1625 port->pp.advertised = pp->advertised;
1626 port->pp.supported = pp->supported;
1627 port->pp.peer = pp->peer;
1628 port->pp.curr_speed = pp->curr_speed;
1629 port->pp.max_speed = pp->max_speed;
1631 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
1634 /* Update OpenFlow 'state' in 'port' and notify controller. */
1636 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
1638 if (port->pp.state != state) {
1639 port->pp.state = state;
1640 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
1646 ofproto_port_unregister(struct ofproto *ofproto, uint16_t ofp_port)
1648 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
1650 if (port->ofproto->ofproto_class->set_realdev) {
1651 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
1653 if (port->ofproto->ofproto_class->set_stp_port) {
1654 port->ofproto->ofproto_class->set_stp_port(port, NULL);
1656 if (port->ofproto->ofproto_class->set_cfm) {
1657 port->ofproto->ofproto_class->set_cfm(port, NULL);
1659 if (port->ofproto->ofproto_class->bundle_remove) {
1660 port->ofproto->ofproto_class->bundle_remove(port);
1666 ofport_destroy__(struct ofport *port)
1668 struct ofproto *ofproto = port->ofproto;
1669 const char *name = netdev_get_name(port->netdev);
1671 hmap_remove(&ofproto->ports, &port->hmap_node);
1672 shash_delete(&ofproto->port_by_name,
1673 shash_find(&ofproto->port_by_name, name));
1675 netdev_close(port->netdev);
1676 ofproto->ofproto_class->port_dealloc(port);
1680 ofport_destroy(struct ofport *port)
1683 port->ofproto->ofproto_class->port_destruct(port);
1684 ofport_destroy__(port);
1689 ofproto_get_port(const struct ofproto *ofproto, uint16_t ofp_port)
1691 struct ofport *port;
1693 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1694 hash_int(ofp_port, 0), &ofproto->ports) {
1695 if (port->ofp_port == ofp_port) {
1703 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
1705 struct ofproto *ofproto = port->ofproto;
1708 if (ofproto->ofproto_class->port_get_stats) {
1709 error = ofproto->ofproto_class->port_get_stats(port, stats);
1718 update_port(struct ofproto *ofproto, const char *name)
1720 struct ofproto_port ofproto_port;
1721 struct ofputil_phy_port pp;
1722 struct netdev *netdev;
1723 struct ofport *port;
1725 COVERAGE_INC(ofproto_update_port);
1727 /* Fetch 'name''s location and properties from the datapath. */
1728 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
1729 ? ofport_open(ofproto, &ofproto_port, &pp)
1732 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
1733 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
1734 struct netdev *old_netdev = port->netdev;
1736 /* 'name' hasn't changed location. Any properties changed? */
1737 if (!ofport_equal(&port->pp, &pp)) {
1738 ofport_modified(port, &pp);
1741 update_mtu(ofproto, port);
1743 /* Install the newly opened netdev in case it has changed.
1744 * Don't close the old netdev yet in case port_modified has to
1745 * remove a retained reference to it.*/
1746 port->netdev = netdev;
1747 port->change_seq = netdev_change_seq(netdev);
1749 if (port->ofproto->ofproto_class->port_modified) {
1750 port->ofproto->ofproto_class->port_modified(port);
1753 netdev_close(old_netdev);
1755 /* If 'port' is nonnull then its name differs from 'name' and thus
1756 * we should delete it. If we think there's a port named 'name'
1757 * then its port number must be wrong now so delete it too. */
1759 ofport_remove(port);
1761 ofport_remove_with_name(ofproto, name);
1762 ofport_install(ofproto, netdev, &pp);
1765 /* Any port named 'name' is gone now. */
1766 ofport_remove_with_name(ofproto, name);
1768 ofproto_port_destroy(&ofproto_port);
1772 init_ports(struct ofproto *p)
1774 struct ofproto_port_dump dump;
1775 struct ofproto_port ofproto_port;
1777 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1778 uint16_t ofp_port = ofproto_port.ofp_port;
1779 if (ofproto_get_port(p, ofp_port)) {
1780 VLOG_WARN_RL(&rl, "%s: ignoring duplicate port %"PRIu16" "
1781 "in datapath", p->name, ofp_port);
1782 } else if (shash_find(&p->port_by_name, ofproto_port.name)) {
1783 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
1784 p->name, ofproto_port.name);
1786 struct ofputil_phy_port pp;
1787 struct netdev *netdev;
1789 netdev = ofport_open(p, &ofproto_port, &pp);
1791 ofport_install(p, netdev, &pp);
1799 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
1800 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
1802 find_min_mtu(struct ofproto *p)
1804 struct ofport *ofport;
1807 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1808 struct netdev *netdev = ofport->netdev;
1811 /* Skip any internal ports, since that's what we're trying to
1813 if (!strcmp(netdev_get_type(netdev), "internal")) {
1817 if (netdev_get_mtu(netdev, &dev_mtu)) {
1820 if (!mtu || dev_mtu < mtu) {
1825 return mtu ? mtu: ETH_PAYLOAD_MAX;
1828 /* Update MTU of all datapath devices on 'p' to the minimum of the
1829 * non-datapath ports in event of 'port' added or changed. */
1831 update_mtu(struct ofproto *p, struct ofport *port)
1833 struct ofport *ofport;
1834 struct netdev *netdev = port->netdev;
1835 int dev_mtu, old_min;
1837 if (netdev_get_mtu(netdev, &dev_mtu)) {
1841 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
1842 if (dev_mtu > p->min_mtu) {
1843 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
1844 dev_mtu = p->min_mtu;
1847 port->mtu = dev_mtu;
1851 /* For non-internal port find new min mtu. */
1852 old_min = p->min_mtu;
1853 port->mtu = dev_mtu;
1854 p->min_mtu = find_min_mtu(p);
1855 if (p->min_mtu == old_min) {
1859 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1860 struct netdev *netdev = ofport->netdev;
1862 if (!strcmp(netdev_get_type(netdev), "internal")) {
1863 if (!netdev_set_mtu(netdev, p->min_mtu)) {
1864 ofport->mtu = p->min_mtu;
1871 ofproto_rule_destroy__(struct rule *rule)
1874 free(rule->ofpacts);
1875 rule->ofproto->ofproto_class->rule_dealloc(rule);
1879 /* This function allows an ofproto implementation to destroy any rules that
1880 * remain when its ->destruct() function is called. The caller must have
1881 * already uninitialized any derived members of 'rule' (step 5 described in the
1882 * large comment in ofproto/ofproto-provider.h titled "Life Cycle").
1883 * This function implements steps 6 and 7.
1885 * This function should only be called from an ofproto implementation's
1886 * ->destruct() function. It is not suitable elsewhere. */
1888 ofproto_rule_destroy(struct rule *rule)
1890 assert(!rule->pending);
1891 oftable_remove_rule(rule);
1892 ofproto_rule_destroy__(rule);
1895 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
1896 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
1898 rule_has_out_port(const struct rule *rule, uint16_t port)
1900 return (port == OFPP_NONE
1901 || ofpacts_output_to_port(rule->ofpacts, rule->ofpacts_len, port));
1904 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
1905 * statistics appropriately. 'packet' must have at least sizeof(struct
1906 * ofp_packet_in) bytes of headroom.
1908 * 'packet' doesn't necessarily have to match 'rule'. 'rule' will be credited
1909 * with statistics for 'packet' either way.
1911 * Takes ownership of 'packet'. */
1913 rule_execute(struct rule *rule, uint16_t in_port, struct ofpbuf *packet)
1917 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
1919 flow_extract(packet, 0, 0, in_port, &flow);
1920 return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
1923 /* Returns true if 'rule' should be hidden from the controller.
1925 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
1926 * (e.g. by in-band control) and are intentionally hidden from the
1929 rule_is_hidden(const struct rule *rule)
1931 return rule->cr.priority > UINT16_MAX;
1934 static enum oftable_flags
1935 rule_get_flags(const struct rule *rule)
1937 return rule->ofproto->tables[rule->table_id].flags;
1941 rule_is_modifiable(const struct rule *rule)
1943 return !(rule_get_flags(rule) & OFTABLE_READONLY);
1947 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
1949 ofconn_send_reply(ofconn, make_echo_reply(oh));
1954 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
1956 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1957 struct ofputil_switch_features features;
1958 struct ofport *port;
1962 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
1964 assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
1966 features.datapath_id = ofproto->datapath_id;
1967 features.n_buffers = pktbuf_capacity();
1968 features.n_tables = ofproto->n_tables;
1969 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
1970 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
1972 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
1975 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
1977 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
1978 ofputil_put_switch_features_port(&port->pp, b);
1981 ofconn_send_reply(ofconn, b);
1986 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
1988 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1989 struct ofp_switch_config *osc;
1990 enum ofp_config_flags flags;
1994 osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1995 flags = ofproto->frag_handling;
1996 if (ofconn_get_invalid_ttl_to_controller(ofconn)) {
1997 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
1999 osc->flags = htons(flags);
2000 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2001 ofconn_send_reply(ofconn, buf);
2007 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
2009 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2010 uint16_t flags = ntohs(osc->flags);
2012 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2013 || ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
2014 enum ofp_config_flags cur = ofproto->frag_handling;
2015 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2017 assert((cur & OFPC_FRAG_MASK) == cur);
2019 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2020 ofproto->frag_handling = next;
2022 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2024 ofputil_frag_handling_to_string(next));
2028 ofconn_set_invalid_ttl_to_controller(ofconn,
2029 (flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2031 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2036 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2037 * error message code for the caller to propagate upward. Otherwise, returns
2040 * The log message mentions 'msg_type'. */
2042 reject_slave_controller(struct ofconn *ofconn)
2044 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2045 && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
2046 return OFPERR_OFPBRC_EPERM;
2053 handle_packet_out(struct ofconn *ofconn, const struct ofp_packet_out *opo)
2055 struct ofproto *p = ofconn_get_ofproto(ofconn);
2056 struct ofputil_packet_out po;
2057 struct ofpbuf *payload;
2058 uint64_t ofpacts_stub[1024 / 8];
2059 struct ofpbuf ofpacts;
2063 COVERAGE_INC(ofproto_packet_out);
2065 error = reject_slave_controller(ofconn);
2070 /* Decode message. */
2071 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2072 error = ofputil_decode_packet_out(&po, opo, &ofpacts);
2074 goto exit_free_ofpacts;
2078 if (po.buffer_id != UINT32_MAX) {
2079 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2080 if (error || !payload) {
2081 goto exit_free_ofpacts;
2084 payload = xmalloc(sizeof *payload);
2085 ofpbuf_use_const(payload, po.packet, po.packet_len);
2088 /* Send out packet. */
2089 flow_extract(payload, 0, 0, po.in_port, &flow);
2090 error = p->ofproto_class->packet_out(p, payload, &flow,
2091 po.ofpacts, po.ofpacts_len);
2092 ofpbuf_delete(payload);
2095 ofpbuf_uninit(&ofpacts);
2101 update_port_config(struct ofport *port,
2102 enum ofputil_port_config config,
2103 enum ofputil_port_config mask)
2105 enum ofputil_port_config old_config = port->pp.config;
2106 enum ofputil_port_config toggle;
2108 toggle = (config ^ port->pp.config) & mask;
2109 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2110 if (config & OFPUTIL_PC_PORT_DOWN) {
2111 netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
2113 netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
2115 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2118 port->pp.config ^= toggle;
2119 if (port->pp.config != old_config) {
2120 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2125 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2127 struct ofproto *p = ofconn_get_ofproto(ofconn);
2128 struct ofputil_port_mod pm;
2129 struct ofport *port;
2132 error = reject_slave_controller(ofconn);
2137 error = ofputil_decode_port_mod(oh, &pm);
2142 port = ofproto_get_port(p, pm.port_no);
2144 return OFPERR_OFPPMFC_BAD_PORT;
2145 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2146 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2148 update_port_config(port, pm.config, pm.mask);
2150 netdev_set_advertisements(port->netdev, pm.advertise);
2157 handle_desc_stats_request(struct ofconn *ofconn,
2158 const struct ofp_stats_msg *request)
2160 struct ofproto *p = ofconn_get_ofproto(ofconn);
2161 struct ofp_desc_stats *ods;
2164 ods = ofputil_make_stats_reply(sizeof *ods, request, &msg);
2165 ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
2166 ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
2167 ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
2168 ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
2169 ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
2170 ofconn_send_reply(ofconn, msg);
2176 handle_table_stats_request(struct ofconn *ofconn,
2177 const struct ofp_stats_msg *request)
2179 struct ofproto *p = ofconn_get_ofproto(ofconn);
2180 struct ofp_table_stats *ots;
2184 ofputil_make_stats_reply(sizeof(struct ofp_stats_msg), request, &msg);
2186 ots = ofpbuf_put_zeros(msg, sizeof *ots * p->n_tables);
2187 for (i = 0; i < p->n_tables; i++) {
2188 ots[i].table_id = i;
2189 sprintf(ots[i].name, "table%zu", i);
2190 ots[i].wildcards = htonl(OFPFW10_ALL);
2191 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2192 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2195 p->ofproto_class->get_tables(p, ots);
2197 for (i = 0; i < p->n_tables; i++) {
2198 const struct oftable *table = &p->tables[i];
2201 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2204 if (table->max_flows < ntohl(ots[i].max_entries)) {
2205 ots[i].max_entries = htonl(table->max_flows);
2209 ofconn_send_reply(ofconn, msg);
2214 append_port_stat(struct ofport *port, struct list *replies)
2216 struct netdev_stats stats;
2217 struct ofp_port_stats *ops;
2219 /* Intentionally ignore return value, since errors will set
2220 * 'stats' to all-1s, which is correct for OpenFlow, and
2221 * netdev_get_stats() will log errors. */
2222 ofproto_port_get_stats(port, &stats);
2224 ops = ofputil_append_stats_reply(sizeof *ops, replies);
2225 ops->port_no = htons(port->pp.port_no);
2226 memset(ops->pad, 0, sizeof ops->pad);
2227 put_32aligned_be64(&ops->rx_packets, htonll(stats.rx_packets));
2228 put_32aligned_be64(&ops->tx_packets, htonll(stats.tx_packets));
2229 put_32aligned_be64(&ops->rx_bytes, htonll(stats.rx_bytes));
2230 put_32aligned_be64(&ops->tx_bytes, htonll(stats.tx_bytes));
2231 put_32aligned_be64(&ops->rx_dropped, htonll(stats.rx_dropped));
2232 put_32aligned_be64(&ops->tx_dropped, htonll(stats.tx_dropped));
2233 put_32aligned_be64(&ops->rx_errors, htonll(stats.rx_errors));
2234 put_32aligned_be64(&ops->tx_errors, htonll(stats.tx_errors));
2235 put_32aligned_be64(&ops->rx_frame_err, htonll(stats.rx_frame_errors));
2236 put_32aligned_be64(&ops->rx_over_err, htonll(stats.rx_over_errors));
2237 put_32aligned_be64(&ops->rx_crc_err, htonll(stats.rx_crc_errors));
2238 put_32aligned_be64(&ops->collisions, htonll(stats.collisions));
2242 handle_port_stats_request(struct ofconn *ofconn,
2243 const struct ofp_port_stats_request *psr)
2245 struct ofproto *p = ofconn_get_ofproto(ofconn);
2246 struct ofport *port;
2247 struct list replies;
2249 ofputil_start_stats_reply(&psr->osm, &replies);
2250 if (psr->port_no != htons(OFPP_NONE)) {
2251 port = ofproto_get_port(p, ntohs(psr->port_no));
2253 append_port_stat(port, &replies);
2256 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2257 append_port_stat(port, &replies);
2261 ofconn_send_replies(ofconn, &replies);
2266 handle_port_desc_stats_request(struct ofconn *ofconn,
2267 const struct ofp_stats_msg *osm)
2269 struct ofproto *p = ofconn_get_ofproto(ofconn);
2270 struct ofport *port;
2271 struct list replies;
2273 ofputil_start_stats_reply(osm, &replies);
2275 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2276 ofputil_append_port_desc_stats_reply(ofconn_get_protocol(ofconn),
2277 &port->pp, &replies);
2280 ofconn_send_replies(ofconn, &replies);
2285 calc_flow_duration__(long long int start, long long int now,
2286 uint32_t *sec, uint32_t *nsec)
2288 long long int msecs = now - start;
2289 *sec = msecs / 1000;
2290 *nsec = (msecs % 1000) * (1000 * 1000);
2293 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
2294 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
2296 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2298 return (table_id == 0xff || table_id < ofproto->n_tables
2300 : OFPERR_NXBRC_BAD_TABLE_ID);
2304 static struct oftable *
2305 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
2307 struct oftable *table;
2309 for (table = &ofproto->tables[table_id];
2310 table < &ofproto->tables[ofproto->n_tables];
2312 if (!(table->flags & OFTABLE_HIDDEN)) {
2320 static struct oftable *
2321 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
2323 if (table_id == 0xff) {
2324 return next_visible_table(ofproto, 0);
2325 } else if (table_id < ofproto->n_tables) {
2326 return &ofproto->tables[table_id];
2332 static struct oftable *
2333 next_matching_table(const struct ofproto *ofproto,
2334 const struct oftable *table, uint8_t table_id)
2336 return (table_id == 0xff
2337 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
2341 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
2343 * - If TABLE_ID is 0xff, this iterates over every classifier table in
2344 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
2346 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
2347 * only once, for that table. (This can be used to access tables marked
2350 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
2351 * entered at all. (Perhaps you should have validated TABLE_ID with
2352 * check_table_id().)
2354 * All parameters are evaluated multiple times.
2356 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
2357 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
2359 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
2361 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2362 * 'table_id' is 0xff) that match 'match' in the "loose" way required for
2363 * OpenFlow OFPFC_MODIFY and OFPFC_DELETE requests and puts them on list
2366 * If 'out_port' is anything other than OFPP_NONE, then only rules that output
2367 * to 'out_port' are included.
2369 * Hidden rules are always omitted.
2371 * Returns 0 on success, otherwise an OpenFlow error code. */
2373 collect_rules_loose(struct ofproto *ofproto, uint8_t table_id,
2374 const struct cls_rule *match,
2375 ovs_be64 cookie, ovs_be64 cookie_mask,
2376 uint16_t out_port, struct list *rules)
2378 struct oftable *table;
2381 error = check_table_id(ofproto, table_id);
2387 FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2388 struct cls_cursor cursor;
2391 cls_cursor_init(&cursor, &table->cls, match);
2392 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2393 if (rule->pending) {
2394 return OFPROTO_POSTPONE;
2396 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)
2397 && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2398 list_push_back(rules, &rule->ofproto_node);
2405 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2406 * 'table_id' is 0xff) that match 'match' in the "strict" way required for
2407 * OpenFlow OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests and puts them
2410 * If 'out_port' is anything other than OFPP_NONE, then only rules that output
2411 * to 'out_port' are included.
2413 * Hidden rules are always omitted.
2415 * Returns 0 on success, otherwise an OpenFlow error code. */
2417 collect_rules_strict(struct ofproto *ofproto, uint8_t table_id,
2418 const struct cls_rule *match,
2419 ovs_be64 cookie, ovs_be64 cookie_mask,
2420 uint16_t out_port, struct list *rules)
2422 struct oftable *table;
2425 error = check_table_id(ofproto, table_id);
2431 FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2434 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
2437 if (rule->pending) {
2438 return OFPROTO_POSTPONE;
2440 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)
2441 && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2442 list_push_back(rules, &rule->ofproto_node);
2449 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
2450 * forced into the range of a uint16_t. */
2452 age_secs(long long int age_ms)
2454 return (age_ms < 0 ? 0
2455 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
2456 : (unsigned int) age_ms / 1000);
2460 handle_flow_stats_request(struct ofconn *ofconn,
2461 const struct ofp_stats_msg *osm)
2463 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2464 struct ofputil_flow_stats_request fsr;
2465 struct list replies;
2470 error = ofputil_decode_flow_stats_request(&fsr, &osm->header);
2475 error = collect_rules_loose(ofproto, fsr.table_id, &fsr.match,
2476 fsr.cookie, fsr.cookie_mask,
2477 fsr.out_port, &rules);
2482 ofputil_start_stats_reply(osm, &replies);
2483 LIST_FOR_EACH (rule, ofproto_node, &rules) {
2484 long long int now = time_msec();
2485 struct ofputil_flow_stats fs;
2488 fs.cookie = rule->flow_cookie;
2489 fs.table_id = rule->table_id;
2490 calc_flow_duration__(rule->created, now, &fs.duration_sec,
2492 fs.idle_timeout = rule->idle_timeout;
2493 fs.hard_timeout = rule->hard_timeout;
2494 fs.idle_age = age_secs(now - rule->used);
2495 fs.hard_age = age_secs(now - rule->modified);
2496 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
2498 fs.ofpacts = rule->ofpacts;
2499 fs.ofpacts_len = rule->ofpacts_len;
2500 ofputil_append_flow_stats_reply(&fs, &replies);
2502 ofconn_send_replies(ofconn, &replies);
2508 flow_stats_ds(struct rule *rule, struct ds *results)
2510 uint64_t packet_count, byte_count;
2512 rule->ofproto->ofproto_class->rule_get_stats(rule,
2513 &packet_count, &byte_count);
2515 if (rule->table_id != 0) {
2516 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
2518 ds_put_format(results, "duration=%llds, ",
2519 (time_msec() - rule->created) / 1000);
2520 ds_put_format(results, "priority=%u, ", rule->cr.priority);
2521 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
2522 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
2523 cls_rule_format(&rule->cr, results);
2524 ds_put_char(results, ',');
2525 if (rule->ofpacts_len > 0) {
2526 ofpacts_format(rule->ofpacts, rule->ofpacts_len, results);
2528 ds_put_cstr(results, "drop");
2530 ds_put_cstr(results, "\n");
2533 /* Adds a pretty-printed description of all flows to 'results', including
2534 * hidden flows (e.g., set up by in-band control). */
2536 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
2538 struct oftable *table;
2540 OFPROTO_FOR_EACH_TABLE (table, p) {
2541 struct cls_cursor cursor;
2544 cls_cursor_init(&cursor, &table->cls, NULL);
2545 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2546 flow_stats_ds(rule, results);
2551 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
2552 * '*engine_type' and '*engine_id', respectively. */
2554 ofproto_get_netflow_ids(const struct ofproto *ofproto,
2555 uint8_t *engine_type, uint8_t *engine_id)
2557 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
2560 /* Checks the fault status of CFM for 'ofp_port' within 'ofproto'. Returns a
2561 * bitmask of 'cfm_fault_reason's to indicate a CFM fault (generally
2562 * indicating a connectivity problem). Returns zero if CFM is not faulted,
2563 * and -1 if CFM is not enabled on 'port'. */
2565 ofproto_port_get_cfm_fault(const struct ofproto *ofproto, uint16_t ofp_port)
2567 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2568 return (ofport && ofproto->ofproto_class->get_cfm_fault
2569 ? ofproto->ofproto_class->get_cfm_fault(ofport)
2573 /* Gets the MPIDs of the remote maintenance points broadcasting to 'ofp_port'
2574 * within 'ofproto'. Populates 'rmps' with an array of MPIDs owned by
2575 * 'ofproto', and 'n_rmps' with the number of MPIDs in 'rmps'. Returns a
2576 * number less than 0 if CFM is not enabled on 'ofp_port'. */
2578 ofproto_port_get_cfm_remote_mpids(const struct ofproto *ofproto,
2579 uint16_t ofp_port, const uint64_t **rmps,
2582 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2586 return (ofport && ofproto->ofproto_class->get_cfm_remote_mpids
2587 ? ofproto->ofproto_class->get_cfm_remote_mpids(ofport, rmps,
2592 /* Checks the health of the CFM for 'ofp_port' within 'ofproto'. Returns an
2593 * integer value between 0 and 100 to indicate the health of the port as a
2594 * percentage which is the average of cfm health of all the remote_mpids or
2595 * returns -1 if CFM is not enabled on 'ofport'. */
2597 ofproto_port_get_cfm_health(const struct ofproto *ofproto, uint16_t ofp_port)
2599 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2600 return (ofport && ofproto->ofproto_class->get_cfm_health
2601 ? ofproto->ofproto_class->get_cfm_health(ofport)
2606 handle_aggregate_stats_request(struct ofconn *ofconn,
2607 const struct ofp_stats_msg *osm)
2609 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2610 struct ofputil_flow_stats_request request;
2611 struct ofputil_aggregate_stats stats;
2612 bool unknown_packets, unknown_bytes;
2613 struct ofpbuf *reply;
2618 error = ofputil_decode_flow_stats_request(&request, &osm->header);
2623 error = collect_rules_loose(ofproto, request.table_id, &request.match,
2624 request.cookie, request.cookie_mask,
2625 request.out_port, &rules);
2630 memset(&stats, 0, sizeof stats);
2631 unknown_packets = unknown_bytes = false;
2632 LIST_FOR_EACH (rule, ofproto_node, &rules) {
2633 uint64_t packet_count;
2634 uint64_t byte_count;
2636 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
2639 if (packet_count == UINT64_MAX) {
2640 unknown_packets = true;
2642 stats.packet_count += packet_count;
2645 if (byte_count == UINT64_MAX) {
2646 unknown_bytes = true;
2648 stats.byte_count += byte_count;
2653 if (unknown_packets) {
2654 stats.packet_count = UINT64_MAX;
2656 if (unknown_bytes) {
2657 stats.byte_count = UINT64_MAX;
2660 reply = ofputil_encode_aggregate_stats_reply(&stats, osm);
2661 ofconn_send_reply(ofconn, reply);
2666 struct queue_stats_cbdata {
2667 struct ofport *ofport;
2668 struct list replies;
2672 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
2673 const struct netdev_queue_stats *stats)
2675 struct ofp_queue_stats *reply;
2677 reply = ofputil_append_stats_reply(sizeof *reply, &cbdata->replies);
2678 reply->port_no = htons(cbdata->ofport->pp.port_no);
2679 memset(reply->pad, 0, sizeof reply->pad);
2680 reply->queue_id = htonl(queue_id);
2681 put_32aligned_be64(&reply->tx_bytes, htonll(stats->tx_bytes));
2682 put_32aligned_be64(&reply->tx_packets, htonll(stats->tx_packets));
2683 put_32aligned_be64(&reply->tx_errors, htonll(stats->tx_errors));
2687 handle_queue_stats_dump_cb(uint32_t queue_id,
2688 struct netdev_queue_stats *stats,
2691 struct queue_stats_cbdata *cbdata = cbdata_;
2693 put_queue_stats(cbdata, queue_id, stats);
2697 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
2698 struct queue_stats_cbdata *cbdata)
2700 cbdata->ofport = port;
2701 if (queue_id == OFPQ_ALL) {
2702 netdev_dump_queue_stats(port->netdev,
2703 handle_queue_stats_dump_cb, cbdata);
2705 struct netdev_queue_stats stats;
2707 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
2708 put_queue_stats(cbdata, queue_id, &stats);
2710 return OFPERR_OFPQOFC_BAD_QUEUE;
2717 handle_queue_stats_request(struct ofconn *ofconn,
2718 const struct ofp_queue_stats_request *qsr)
2720 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2721 struct queue_stats_cbdata cbdata;
2722 unsigned int port_no;
2723 struct ofport *port;
2727 COVERAGE_INC(ofproto_queue_req);
2729 ofputil_start_stats_reply(&qsr->osm, &cbdata.replies);
2731 port_no = ntohs(qsr->port_no);
2732 queue_id = ntohl(qsr->queue_id);
2733 if (port_no == OFPP_ALL) {
2734 error = OFPERR_OFPQOFC_BAD_QUEUE;
2735 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2736 if (!handle_queue_stats_for_port(port, queue_id, &cbdata)) {
2741 port = ofproto_get_port(ofproto, port_no);
2743 ? handle_queue_stats_for_port(port, queue_id, &cbdata)
2744 : OFPERR_OFPQOFC_BAD_PORT);
2747 ofconn_send_replies(ofconn, &cbdata.replies);
2749 ofpbuf_list_delete(&cbdata.replies);
2756 is_flow_deletion_pending(const struct ofproto *ofproto,
2757 const struct cls_rule *cls_rule,
2760 if (!hmap_is_empty(&ofproto->deletions)) {
2761 struct ofoperation *op;
2763 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
2764 cls_rule_hash(cls_rule, table_id),
2765 &ofproto->deletions) {
2766 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
2775 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
2776 * in which no matching flow already exists in the flow table.
2778 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
2779 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
2780 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
2781 * initiated now but may be retried later.
2783 * Upon successful return, takes ownership of 'fm->ofpacts'. On failure,
2784 * ownership remains with the caller.
2786 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2789 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
2790 const struct ofputil_flow_mod *fm, const struct ofp_header *request)
2792 struct oftable *table;
2793 struct ofopgroup *group;
2794 struct rule *victim;
2798 error = check_table_id(ofproto, fm->table_id);
2804 if (fm->table_id == 0xff) {
2806 if (ofproto->ofproto_class->rule_choose_table) {
2807 error = ofproto->ofproto_class->rule_choose_table(ofproto, &fm->cr,
2812 assert(table_id < ofproto->n_tables);
2813 table = &ofproto->tables[table_id];
2815 table = &ofproto->tables[0];
2817 } else if (fm->table_id < ofproto->n_tables) {
2818 table = &ofproto->tables[fm->table_id];
2820 return OFPERR_NXFMFC_BAD_TABLE_ID;
2823 if (table->flags & OFTABLE_READONLY) {
2824 return OFPERR_OFPBRC_EPERM;
2827 /* Check for overlap, if requested. */
2828 if (fm->flags & OFPFF_CHECK_OVERLAP
2829 && classifier_rule_overlaps(&table->cls, &fm->cr)) {
2830 return OFPERR_OFPFMFC_OVERLAP;
2833 /* Serialize against pending deletion. */
2834 if (is_flow_deletion_pending(ofproto, &fm->cr, table - ofproto->tables)) {
2835 return OFPROTO_POSTPONE;
2838 /* Allocate new rule. */
2839 rule = ofproto->ofproto_class->rule_alloc();
2841 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
2842 ofproto->name, strerror(error));
2845 rule->ofproto = ofproto;
2847 rule->pending = NULL;
2848 rule->flow_cookie = fm->new_cookie;
2849 rule->created = rule->modified = rule->used = time_msec();
2850 rule->idle_timeout = fm->idle_timeout;
2851 rule->hard_timeout = fm->hard_timeout;
2852 rule->table_id = table - ofproto->tables;
2853 rule->send_flow_removed = (fm->flags & OFPFF_SEND_FLOW_REM) != 0;
2854 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
2855 rule->ofpacts_len = fm->ofpacts_len;
2856 rule->evictable = true;
2857 rule->eviction_group = NULL;
2859 /* Insert new rule. */
2860 victim = oftable_replace_rule(rule);
2861 if (victim && !rule_is_modifiable(victim)) {
2862 error = OFPERR_OFPBRC_EPERM;
2863 } else if (victim && victim->pending) {
2864 error = OFPROTO_POSTPONE;
2866 struct ofoperation *op;
2869 if (classifier_count(&table->cls) > table->max_flows) {
2872 was_evictable = rule->evictable;
2873 rule->evictable = false;
2874 evict = choose_rule_to_evict(table);
2875 rule->evictable = was_evictable;
2878 error = OFPERR_OFPFMFC_ALL_TABLES_FULL;
2880 } else if (evict->pending) {
2881 error = OFPROTO_POSTPONE;
2888 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
2889 op = ofoperation_create(group, rule, OFOPERATION_ADD);
2890 op->victim = victim;
2892 error = ofproto->ofproto_class->rule_construct(rule);
2894 op->group->n_running--;
2895 ofoperation_destroy(rule->pending);
2897 delete_flow__(evict, group);
2899 ofopgroup_submit(group);
2903 /* Back out if an error occurred. */
2905 oftable_substitute_rule(rule, victim);
2906 ofproto_rule_destroy__(rule);
2911 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
2913 /* Modifies the rules listed in 'rules', changing their actions to match those
2916 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2919 * Returns 0 on success, otherwise an OpenFlow error code. */
2921 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
2922 const struct ofputil_flow_mod *fm,
2923 const struct ofp_header *request, struct list *rules)
2925 struct ofopgroup *group;
2929 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
2930 error = OFPERR_OFPBRC_EPERM;
2931 LIST_FOR_EACH (rule, ofproto_node, rules) {
2932 struct ofoperation *op;
2933 bool actions_changed;
2934 ovs_be64 new_cookie;
2936 if (rule_is_modifiable(rule)) {
2937 /* At least one rule is modifiable, don't report EPERM error. */
2943 actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
2944 rule->ofpacts, rule->ofpacts_len);
2945 new_cookie = (fm->new_cookie != htonll(UINT64_MAX)
2947 : rule->flow_cookie);
2948 if (!actions_changed && new_cookie == rule->flow_cookie) {
2949 /* No change at all. */
2953 op = ofoperation_create(group, rule, OFOPERATION_MODIFY);
2954 rule->flow_cookie = new_cookie;
2955 if (actions_changed) {
2956 op->ofpacts = rule->ofpacts;
2957 op->ofpacts_len = rule->ofpacts_len;
2958 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
2959 rule->ofpacts_len = fm->ofpacts_len;
2960 rule->ofproto->ofproto_class->rule_modify_actions(rule);
2962 ofoperation_complete(op, 0);
2965 ofopgroup_submit(group);
2970 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
2973 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2976 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
2977 const struct ofputil_flow_mod *fm,
2978 const struct ofp_header *request)
2983 error = collect_rules_loose(ofproto, fm->table_id, &fm->cr,
2984 fm->cookie, fm->cookie_mask,
2988 } else if (list_is_empty(&rules)) {
2989 return fm->cookie_mask ? 0 : add_flow(ofproto, ofconn, fm, request);
2991 return modify_flows__(ofproto, ofconn, fm, request, &rules);
2995 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
2998 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
3001 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3002 const struct ofputil_flow_mod *fm,
3003 const struct ofp_header *request)
3008 error = collect_rules_strict(ofproto, fm->table_id, &fm->cr,
3009 fm->cookie, fm->cookie_mask,
3014 } else if (list_is_empty(&rules)) {
3015 return fm->cookie_mask ? 0 : add_flow(ofproto, ofconn, fm, request);
3017 return list_is_singleton(&rules) ? modify_flows__(ofproto, ofconn,
3018 fm, request, &rules)
3023 /* OFPFC_DELETE implementation. */
3026 delete_flow__(struct rule *rule, struct ofopgroup *group)
3028 struct ofproto *ofproto = rule->ofproto;
3030 ofproto_rule_send_removed(rule, OFPRR_DELETE);
3032 ofoperation_create(group, rule, OFOPERATION_DELETE);
3033 oftable_remove_rule(rule);
3034 ofproto->ofproto_class->rule_destruct(rule);
3037 /* Deletes the rules listed in 'rules'.
3039 * Returns 0 on success, otherwise an OpenFlow error code. */
3041 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3042 const struct ofp_header *request, struct list *rules)
3044 struct rule *rule, *next;
3045 struct ofopgroup *group;
3047 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3048 LIST_FOR_EACH_SAFE (rule, next, ofproto_node, rules) {
3049 delete_flow__(rule, group);
3051 ofopgroup_submit(group);
3056 /* Implements OFPFC_DELETE. */
3058 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3059 const struct ofputil_flow_mod *fm,
3060 const struct ofp_header *request)
3065 error = collect_rules_loose(ofproto, fm->table_id, &fm->cr,
3066 fm->cookie, fm->cookie_mask,
3067 fm->out_port, &rules);
3068 return (error ? error
3069 : !list_is_empty(&rules) ? delete_flows__(ofproto, ofconn, request,
3074 /* Implements OFPFC_DELETE_STRICT. */
3076 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3077 const struct ofputil_flow_mod *fm,
3078 const struct ofp_header *request)
3083 error = collect_rules_strict(ofproto, fm->table_id, &fm->cr,
3084 fm->cookie, fm->cookie_mask,
3085 fm->out_port, &rules);
3086 return (error ? error
3087 : list_is_singleton(&rules) ? delete_flows__(ofproto, ofconn,
3093 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
3095 struct ofputil_flow_removed fr;
3097 if (rule_is_hidden(rule) || !rule->send_flow_removed) {
3102 fr.cookie = rule->flow_cookie;
3104 calc_flow_duration__(rule->created, time_msec(),
3105 &fr.duration_sec, &fr.duration_nsec);
3106 fr.idle_timeout = rule->idle_timeout;
3107 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
3110 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
3114 ofproto_rule_update_used(struct rule *rule, long long int used)
3116 if (used > rule->used) {
3117 struct eviction_group *evg = rule->eviction_group;
3121 heap_change(&evg->rules, &rule->evg_node,
3122 rule_eviction_priority(rule));
3127 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
3128 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
3131 * ofproto implementation ->run() functions should use this function to expire
3132 * OpenFlow flows. */
3134 ofproto_rule_expire(struct rule *rule, uint8_t reason)
3136 struct ofproto *ofproto = rule->ofproto;
3137 struct ofopgroup *group;
3139 assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
3141 ofproto_rule_send_removed(rule, reason);
3143 group = ofopgroup_create_unattached(ofproto);
3144 ofoperation_create(group, rule, OFOPERATION_DELETE);
3145 oftable_remove_rule(rule);
3146 ofproto->ofproto_class->rule_destruct(rule);
3147 ofopgroup_submit(group);
3151 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3153 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3154 struct ofputil_flow_mod fm;
3155 uint64_t ofpacts_stub[1024 / 8];
3156 struct ofpbuf ofpacts;
3160 error = reject_slave_controller(ofconn);
3165 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3166 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
3169 goto exit_free_ofpacts;
3172 /* We do not support the OpenFlow 1.0 emergency flow cache, which is not
3173 * required in OpenFlow 1.0.1 and removed from OpenFlow 1.1. */
3174 if (fm.flags & OFPFF_EMERG) {
3175 /* We do not support the emergency flow cache. It will hopefully get
3176 * dropped from OpenFlow in the near future. There is no good error
3177 * code, so just state that the flow table is full. */
3178 error = OFPERR_OFPFMFC_ALL_TABLES_FULL;
3180 error = handle_flow_mod__(ofconn_get_ofproto(ofconn), ofconn, &fm, oh);
3183 goto exit_free_ofpacts;
3186 /* Record the operation for logging a summary report. */
3187 switch (fm.command) {
3193 case OFPFC_MODIFY_STRICT:
3194 ofproto->n_modify++;
3198 case OFPFC_DELETE_STRICT:
3199 ofproto->n_delete++;
3204 if (ofproto->next_op_report == LLONG_MAX) {
3205 ofproto->first_op = now;
3206 ofproto->next_op_report = MAX(now + 10 * 1000,
3207 ofproto->op_backoff);
3208 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
3210 ofproto->last_op = now;
3213 ofpbuf_uninit(&ofpacts);
3219 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
3220 const struct ofputil_flow_mod *fm,
3221 const struct ofp_header *oh)
3223 if (ofproto->n_pending >= 50) {
3224 assert(!list_is_empty(&ofproto->pending));
3225 return OFPROTO_POSTPONE;
3228 switch (fm->command) {
3230 return add_flow(ofproto, ofconn, fm, oh);
3233 return modify_flows_loose(ofproto, ofconn, fm, oh);
3235 case OFPFC_MODIFY_STRICT:
3236 return modify_flow_strict(ofproto, ofconn, fm, oh);
3239 return delete_flows_loose(ofproto, ofconn, fm, oh);
3241 case OFPFC_DELETE_STRICT:
3242 return delete_flow_strict(ofproto, ofconn, fm, oh);
3245 if (fm->command > 0xff) {
3246 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
3247 "flow_mod_table_id extension is not enabled",
3250 return OFPERR_OFPFMFC_BAD_COMMAND;
3255 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
3257 struct nx_role_request *nrr = (struct nx_role_request *) oh;
3258 struct nx_role_request *reply;
3262 role = ntohl(nrr->role);
3263 if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
3264 && role != NX_ROLE_SLAVE) {
3265 return OFPERR_OFPRRFC_BAD_ROLE;
3268 if (ofconn_get_role(ofconn) != role
3269 && ofconn_has_pending_opgroups(ofconn)) {
3270 return OFPROTO_POSTPONE;
3273 ofconn_set_role(ofconn, role);
3275 reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
3276 reply->role = htonl(role);
3277 ofconn_send_reply(ofconn, buf);
3283 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
3284 const struct ofp_header *oh)
3286 const struct nx_flow_mod_table_id *msg
3287 = (const struct nx_flow_mod_table_id *) oh;
3288 enum ofputil_protocol cur, next;
3290 cur = ofconn_get_protocol(ofconn);
3291 next = ofputil_protocol_set_tid(cur, msg->set != 0);
3292 ofconn_set_protocol(ofconn, next);
3298 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
3300 const struct nx_set_flow_format *msg
3301 = (const struct nx_set_flow_format *) oh;
3302 enum ofputil_protocol cur, next;
3303 enum ofputil_protocol next_base;
3305 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
3307 return OFPERR_OFPBRC_EPERM;
3310 cur = ofconn_get_protocol(ofconn);
3311 next = ofputil_protocol_set_base(cur, next_base);
3312 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
3313 /* Avoid sending async messages in surprising protocol. */
3314 return OFPROTO_POSTPONE;
3317 ofconn_set_protocol(ofconn, next);
3322 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
3323 const struct ofp_header *oh)
3325 const struct nx_set_packet_in_format *msg;
3328 msg = (const struct nx_set_packet_in_format *) oh;
3329 format = ntohl(msg->format);
3330 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
3331 return OFPERR_OFPBRC_EPERM;
3334 if (format != ofconn_get_packet_in_format(ofconn)
3335 && ofconn_has_pending_opgroups(ofconn)) {
3336 /* Avoid sending async message in surprsing packet in format. */
3337 return OFPROTO_POSTPONE;
3340 ofconn_set_packet_in_format(ofconn, format);
3345 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
3347 const struct nx_async_config *msg = (const struct nx_async_config *) oh;
3348 uint32_t master[OAM_N_TYPES];
3349 uint32_t slave[OAM_N_TYPES];
3351 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
3352 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
3353 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
3355 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
3356 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
3357 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
3359 ofconn_set_async_config(ofconn, master, slave);
3360 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
3361 !ofconn_get_miss_send_len(ofconn)) {
3362 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
3369 handle_nxt_set_controller_id(struct ofconn *ofconn,
3370 const struct ofp_header *oh)
3372 const struct nx_controller_id *nci;
3374 nci = (const struct nx_controller_id *) oh;
3375 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
3376 return OFPERR_NXBRC_MUST_BE_ZERO;
3379 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
3384 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
3388 if (ofconn_has_pending_opgroups(ofconn)) {
3389 return OFPROTO_POSTPONE;
3392 make_openflow_xid(sizeof *oh, OFPT10_BARRIER_REPLY, oh->xid, &buf);
3393 ofconn_send_reply(ofconn, buf);
3398 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
3400 const struct ofp_header *oh = msg->data;
3401 const struct ofputil_msg_type *type;
3404 error = ofputil_decode_msg_type(oh, &type);
3409 switch (ofputil_msg_type_code(type)) {
3410 /* OpenFlow requests. */
3411 case OFPUTIL_OFPT_ECHO_REQUEST:
3412 return handle_echo_request(ofconn, oh);
3414 case OFPUTIL_OFPT_FEATURES_REQUEST:
3415 return handle_features_request(ofconn, oh);
3417 case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
3418 return handle_get_config_request(ofconn, oh);
3420 case OFPUTIL_OFPT_SET_CONFIG:
3421 return handle_set_config(ofconn, msg->data);
3423 case OFPUTIL_OFPT_PACKET_OUT:
3424 return handle_packet_out(ofconn, msg->data);
3426 case OFPUTIL_OFPT_PORT_MOD:
3427 return handle_port_mod(ofconn, oh);
3429 case OFPUTIL_OFPT_FLOW_MOD:
3430 return handle_flow_mod(ofconn, oh);
3432 case OFPUTIL_OFPT_BARRIER_REQUEST:
3433 return handle_barrier_request(ofconn, oh);
3435 /* OpenFlow replies. */
3436 case OFPUTIL_OFPT_ECHO_REPLY:
3439 /* Nicira extension requests. */
3440 case OFPUTIL_NXT_ROLE_REQUEST:
3441 return handle_role_request(ofconn, oh);
3443 case OFPUTIL_NXT_FLOW_MOD_TABLE_ID:
3444 return handle_nxt_flow_mod_table_id(ofconn, oh);
3446 case OFPUTIL_NXT_SET_FLOW_FORMAT:
3447 return handle_nxt_set_flow_format(ofconn, oh);
3449 case OFPUTIL_NXT_SET_PACKET_IN_FORMAT:
3450 return handle_nxt_set_packet_in_format(ofconn, oh);
3452 case OFPUTIL_NXT_SET_CONTROLLER_ID:
3453 return handle_nxt_set_controller_id(ofconn, oh);
3455 case OFPUTIL_NXT_FLOW_MOD:
3456 return handle_flow_mod(ofconn, oh);
3458 case OFPUTIL_NXT_FLOW_AGE:
3459 /* Nothing to do. */
3462 case OFPUTIL_NXT_SET_ASYNC_CONFIG:
3463 return handle_nxt_set_async_config(ofconn, oh);
3465 /* Statistics requests. */
3466 case OFPUTIL_OFPST_DESC_REQUEST:
3467 return handle_desc_stats_request(ofconn, msg->data);
3469 case OFPUTIL_OFPST_FLOW_REQUEST:
3470 case OFPUTIL_NXST_FLOW_REQUEST:
3471 return handle_flow_stats_request(ofconn, msg->data);
3473 case OFPUTIL_OFPST_AGGREGATE_REQUEST:
3474 case OFPUTIL_NXST_AGGREGATE_REQUEST:
3475 return handle_aggregate_stats_request(ofconn, msg->data);
3477 case OFPUTIL_OFPST_TABLE_REQUEST:
3478 return handle_table_stats_request(ofconn, msg->data);
3480 case OFPUTIL_OFPST_PORT_REQUEST:
3481 return handle_port_stats_request(ofconn, msg->data);
3483 case OFPUTIL_OFPST_QUEUE_REQUEST:
3484 return handle_queue_stats_request(ofconn, msg->data);
3486 case OFPUTIL_OFPST_PORT_DESC_REQUEST:
3487 return handle_port_desc_stats_request(ofconn, msg->data);
3489 case OFPUTIL_MSG_INVALID:
3490 case OFPUTIL_OFPT_HELLO:
3491 case OFPUTIL_OFPT_ERROR:
3492 case OFPUTIL_OFPT_FEATURES_REPLY:
3493 case OFPUTIL_OFPT_GET_CONFIG_REPLY:
3494 case OFPUTIL_OFPT_PACKET_IN:
3495 case OFPUTIL_OFPT_FLOW_REMOVED:
3496 case OFPUTIL_OFPT_PORT_STATUS:
3497 case OFPUTIL_OFPT_BARRIER_REPLY:
3498 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
3499 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
3500 case OFPUTIL_OFPST_DESC_REPLY:
3501 case OFPUTIL_OFPST_FLOW_REPLY:
3502 case OFPUTIL_OFPST_QUEUE_REPLY:
3503 case OFPUTIL_OFPST_PORT_REPLY:
3504 case OFPUTIL_OFPST_TABLE_REPLY:
3505 case OFPUTIL_OFPST_AGGREGATE_REPLY:
3506 case OFPUTIL_OFPST_PORT_DESC_REPLY:
3507 case OFPUTIL_NXT_ROLE_REPLY:
3508 case OFPUTIL_NXT_FLOW_REMOVED:
3509 case OFPUTIL_NXT_PACKET_IN:
3510 case OFPUTIL_NXST_FLOW_REPLY:
3511 case OFPUTIL_NXST_AGGREGATE_REPLY:
3513 return (oh->type == OFPT10_STATS_REQUEST ||
3514 oh->type == OFPT10_STATS_REPLY
3515 ? OFPERR_OFPBRC_BAD_STAT
3516 : OFPERR_OFPBRC_BAD_TYPE);
3521 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
3523 int error = handle_openflow__(ofconn, ofp_msg);
3524 if (error && error != OFPROTO_POSTPONE) {
3525 ofconn_send_error(ofconn, ofp_msg->data, error);
3527 COVERAGE_INC(ofproto_recv_openflow);
3528 return error != OFPROTO_POSTPONE;
3531 /* Asynchronous operations. */
3533 /* Creates and returns a new ofopgroup that is not associated with any
3534 * OpenFlow connection.
3536 * The caller should add operations to the returned group with
3537 * ofoperation_create() and then submit it with ofopgroup_submit(). */
3538 static struct ofopgroup *
3539 ofopgroup_create_unattached(struct ofproto *ofproto)
3541 struct ofopgroup *group = xzalloc(sizeof *group);
3542 group->ofproto = ofproto;
3543 list_init(&group->ofproto_node);
3544 list_init(&group->ops);
3545 list_init(&group->ofconn_node);
3549 /* Creates and returns a new ofopgroup for 'ofproto'.
3551 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
3552 * connection. The 'request' and 'buffer_id' arguments are ignored.
3554 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
3555 * If the ofopgroup eventually fails, then the error reply will include
3556 * 'request'. If the ofopgroup eventually succeeds, then the packet with
3557 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
3559 * The caller should add operations to the returned group with
3560 * ofoperation_create() and then submit it with ofopgroup_submit(). */
3561 static struct ofopgroup *
3562 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
3563 const struct ofp_header *request, uint32_t buffer_id)
3565 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
3567 size_t request_len = ntohs(request->length);
3569 assert(ofconn_get_ofproto(ofconn) == ofproto);
3571 ofconn_add_opgroup(ofconn, &group->ofconn_node);
3572 group->ofconn = ofconn;
3573 group->request = xmemdup(request, MIN(request_len, 64));
3574 group->buffer_id = buffer_id;
3579 /* Submits 'group' for processing.
3581 * If 'group' contains no operations (e.g. none were ever added, or all of the
3582 * ones that were added completed synchronously), then it is destroyed
3583 * immediately. Otherwise it is added to the ofproto's list of pending
3586 ofopgroup_submit(struct ofopgroup *group)
3588 if (!group->n_running) {
3589 ofopgroup_complete(group);
3591 list_push_back(&group->ofproto->pending, &group->ofproto_node);
3592 group->ofproto->n_pending++;
3597 ofopgroup_complete(struct ofopgroup *group)
3599 struct ofproto *ofproto = group->ofproto;
3600 struct ofoperation *op, *next_op;
3603 assert(!group->n_running);
3606 LIST_FOR_EACH (op, group_node, &group->ops) {
3613 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
3614 LIST_FOR_EACH (op, group_node, &group->ops) {
3615 if (op->type != OFOPERATION_DELETE) {
3616 struct ofpbuf *packet;
3619 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
3623 error = rule_execute(op->rule, in_port, packet);
3630 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
3631 struct rule *rule = op->rule;
3632 rule->pending = NULL;
3635 case OFOPERATION_ADD:
3637 ofproto_rule_destroy__(op->victim);
3638 if ((rule->cr.wc.vlan_tci_mask & htons(VLAN_VID_MASK))
3639 == htons(VLAN_VID_MASK)) {
3640 if (ofproto->vlan_bitmap) {
3641 uint16_t vid = vlan_tci_to_vid(rule->cr.flow.vlan_tci);
3643 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
3644 bitmap_set1(ofproto->vlan_bitmap, vid);
3645 ofproto->vlans_changed = true;
3648 ofproto->vlans_changed = true;
3652 oftable_substitute_rule(rule, op->victim);
3653 ofproto_rule_destroy__(rule);
3657 case OFOPERATION_DELETE:
3659 ofproto_rule_destroy__(rule);
3663 case OFOPERATION_MODIFY:
3665 rule->modified = time_msec();
3667 rule->flow_cookie = op->flow_cookie;
3669 free(rule->ofpacts);
3670 rule->ofpacts = op->ofpacts;
3671 rule->ofpacts_len = op->ofpacts_len;
3673 op->ofpacts_len = 0;
3682 ofoperation_destroy(op);
3685 if (!list_is_empty(&group->ofproto_node)) {
3686 assert(ofproto->n_pending > 0);
3687 ofproto->n_pending--;
3688 list_remove(&group->ofproto_node);
3690 if (!list_is_empty(&group->ofconn_node)) {
3691 list_remove(&group->ofconn_node);
3693 ofconn_send_error(group->ofconn, group->request, error);
3695 connmgr_retry(ofproto->connmgr);
3697 free(group->request);
3701 /* Initiates a new operation on 'rule', of the specified 'type', within
3702 * 'group'. Prior to calling, 'rule' must not have any pending operation.
3704 * Returns the newly created ofoperation (which is also available as
3705 * rule->pending). */
3706 static struct ofoperation *
3707 ofoperation_create(struct ofopgroup *group, struct rule *rule,
3708 enum ofoperation_type type)
3710 struct ofproto *ofproto = group->ofproto;
3711 struct ofoperation *op;
3713 assert(!rule->pending);
3715 op = rule->pending = xzalloc(sizeof *op);
3717 list_push_back(&group->ops, &op->group_node);
3720 op->flow_cookie = rule->flow_cookie;
3724 if (type == OFOPERATION_DELETE) {
3725 hmap_insert(&ofproto->deletions, &op->hmap_node,
3726 cls_rule_hash(&rule->cr, rule->table_id));
3733 ofoperation_destroy(struct ofoperation *op)
3735 struct ofopgroup *group = op->group;
3738 op->rule->pending = NULL;
3740 if (op->type == OFOPERATION_DELETE) {
3741 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
3743 list_remove(&op->group_node);
3748 /* Indicates that 'op' completed with status 'error', which is either 0 to
3749 * indicate success or an OpenFlow error code on failure.
3751 * If 'error' is 0, indicating success, the operation will be committed
3752 * permanently to the flow table. There is one interesting subcase:
3754 * - If 'op' is an "add flow" operation that is replacing an existing rule in
3755 * the flow table (the "victim" rule) by a new one, then the caller must
3756 * have uninitialized any derived state in the victim rule, as in step 5 in
3757 * the "Life Cycle" in ofproto/ofproto-provider.h. ofoperation_complete()
3758 * performs steps 6 and 7 for the victim rule, most notably by calling its
3759 * ->rule_dealloc() function.
3761 * If 'error' is nonzero, then generally the operation will be rolled back:
3763 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
3764 * restores the original rule. The caller must have uninitialized any
3765 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
3766 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
3767 * and 7 for the new rule, calling its ->rule_dealloc() function.
3769 * - If 'op' is a "modify flow" operation, ofproto restores the original
3772 * - 'op' must not be a "delete flow" operation. Removing a rule is not
3773 * allowed to fail. It must always succeed.
3775 * Please see the large comment in ofproto/ofproto-provider.h titled
3776 * "Asynchronous Operation Support" for more information. */
3778 ofoperation_complete(struct ofoperation *op, enum ofperr error)
3780 struct ofopgroup *group = op->group;
3782 assert(op->rule->pending == op);
3783 assert(group->n_running > 0);
3784 assert(!error || op->type != OFOPERATION_DELETE);
3787 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
3788 ofopgroup_complete(group);
3793 ofoperation_get_victim(struct ofoperation *op)
3795 assert(op->type == OFOPERATION_ADD);
3800 pick_datapath_id(const struct ofproto *ofproto)
3802 const struct ofport *port;
3804 port = ofproto_get_port(ofproto, OFPP_LOCAL);
3806 uint8_t ea[ETH_ADDR_LEN];
3809 error = netdev_get_etheraddr(port->netdev, ea);
3811 return eth_addr_to_uint64(ea);
3813 VLOG_WARN("%s: could not get MAC address for %s (%s)",
3814 ofproto->name, netdev_get_name(port->netdev),
3817 return ofproto->fallback_dpid;
3821 pick_fallback_dpid(void)
3823 uint8_t ea[ETH_ADDR_LEN];
3824 eth_addr_nicira_random(ea);
3825 return eth_addr_to_uint64(ea);
3828 /* Table overflow policy. */
3830 /* Chooses and returns a rule to evict from 'table'. Returns NULL if the table
3831 * is not configured to evict rules or if the table contains no evictable
3832 * rules. (Rules with 'evictable' set to false or with no timeouts are not
3834 static struct rule *
3835 choose_rule_to_evict(struct oftable *table)
3837 struct eviction_group *evg;
3839 if (!table->eviction_fields) {
3843 /* In the common case, the outer and inner loops here will each be entered
3846 * - The inner loop normally "return"s in its first iteration. If the
3847 * eviction group has any evictable rules, then it always returns in
3850 * - The outer loop only iterates more than once if the largest eviction
3851 * group has no evictable rules.
3853 * - The outer loop can exit only if table's 'max_flows' is all filled up
3854 * by unevictable rules'. */
3855 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
3858 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
3859 if (rule->evictable) {
3868 /* Searches 'ofproto' for tables that have more flows than their configured
3869 * maximum and that have flow eviction enabled, and evicts as many flows as
3870 * necessary and currently feasible from them.
3872 * This triggers only when an OpenFlow table has N flows in it and then the
3873 * client configures a maximum number of flows less than N. */
3875 ofproto_evict(struct ofproto *ofproto)
3877 struct ofopgroup *group;
3878 struct oftable *table;
3880 group = ofopgroup_create_unattached(ofproto);
3881 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
3882 while (classifier_count(&table->cls) > table->max_flows
3883 && table->eviction_fields) {
3886 rule = choose_rule_to_evict(table);
3887 if (!rule || rule->pending) {
3891 ofoperation_create(group, rule, OFOPERATION_DELETE);
3892 oftable_remove_rule(rule);
3893 ofproto->ofproto_class->rule_destruct(rule);
3896 ofopgroup_submit(group);
3899 /* Eviction groups. */
3901 /* Returns the priority to use for an eviction_group that contains 'n_rules'
3902 * rules. The priority contains low-order random bits to ensure that eviction
3903 * groups with the same number of rules are prioritized randomly. */
3905 eviction_group_priority(size_t n_rules)
3907 uint16_t size = MIN(UINT16_MAX, n_rules);
3908 return (size << 16) | random_uint16();
3911 /* Updates 'evg', an eviction_group within 'table', following a change that
3912 * adds or removes rules in 'evg'. */
3914 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
3916 heap_change(&table->eviction_groups_by_size, &evg->size_node,
3917 eviction_group_priority(heap_count(&evg->rules)));
3920 /* Destroys 'evg', an eviction_group within 'table':
3922 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
3923 * rules themselves, just removes them from the eviction group.)
3925 * - Removes 'evg' from 'table'.
3929 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
3931 while (!heap_is_empty(&evg->rules)) {
3934 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
3935 rule->eviction_group = NULL;
3937 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
3938 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
3939 heap_destroy(&evg->rules);
3943 /* Removes 'rule' from its eviction group, if any. */
3945 eviction_group_remove_rule(struct rule *rule)
3947 if (rule->eviction_group) {
3948 struct oftable *table = &rule->ofproto->tables[rule->table_id];
3949 struct eviction_group *evg = rule->eviction_group;
3951 rule->eviction_group = NULL;
3952 heap_remove(&evg->rules, &rule->evg_node);
3953 if (heap_is_empty(&evg->rules)) {
3954 eviction_group_destroy(table, evg);
3956 eviction_group_resized(table, evg);
3961 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
3962 * returns the hash value. */
3964 eviction_group_hash_rule(struct rule *rule)
3966 struct oftable *table = &rule->ofproto->tables[rule->table_id];
3967 const struct mf_subfield *sf;
3970 hash = table->eviction_group_id_basis;
3971 for (sf = table->eviction_fields;
3972 sf < &table->eviction_fields[table->n_eviction_fields];
3975 if (mf_are_prereqs_ok(sf->field, &rule->cr.flow)) {
3976 union mf_value value;
3978 mf_get_value(sf->field, &rule->cr.flow, &value);
3980 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
3982 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
3983 unsigned int start = sf->ofs + sf->n_bits;
3984 bitwise_zero(&value, sf->field->n_bytes, start,
3985 sf->field->n_bytes * 8 - start);
3987 hash = hash_bytes(&value, sf->field->n_bytes, hash);
3989 hash = hash_int(hash, 0);
3996 /* Returns an eviction group within 'table' with the given 'id', creating one
3998 static struct eviction_group *
3999 eviction_group_find(struct oftable *table, uint32_t id)
4001 struct eviction_group *evg;
4003 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
4007 evg = xmalloc(sizeof *evg);
4008 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
4009 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
4010 eviction_group_priority(0));
4011 heap_init(&evg->rules);
4016 /* Returns an eviction priority for 'rule'. The return value should be
4017 * interpreted so that higher priorities make a rule more attractive candidates
4020 rule_eviction_priority(struct rule *rule)
4022 long long int hard_expiration;
4023 long long int idle_expiration;
4024 long long int expiration;
4025 uint32_t expiration_offset;
4027 /* Calculate time of expiration. */
4028 hard_expiration = (rule->hard_timeout
4029 ? rule->modified + rule->hard_timeout * 1000
4031 idle_expiration = (rule->idle_timeout
4032 ? rule->used + rule->idle_timeout * 1000
4034 expiration = MIN(hard_expiration, idle_expiration);
4035 if (expiration == LLONG_MAX) {
4039 /* Calculate the time of expiration as a number of (approximate) seconds
4040 * after program startup.
4042 * This should work OK for program runs that last UINT32_MAX seconds or
4043 * less. Therefore, please restart OVS at least once every 136 years. */
4044 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
4046 /* Invert the expiration offset because we're using a max-heap. */
4047 return UINT32_MAX - expiration_offset;
4050 /* Adds 'rule' to an appropriate eviction group for its oftable's
4051 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
4052 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
4055 * The caller must ensure that 'rule' is not already in an eviction group. */
4057 eviction_group_add_rule(struct rule *rule)
4059 struct ofproto *ofproto = rule->ofproto;
4060 struct oftable *table = &ofproto->tables[rule->table_id];
4062 if (table->eviction_fields
4063 && (rule->hard_timeout || rule->idle_timeout)) {
4064 struct eviction_group *evg;
4066 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
4068 rule->eviction_group = evg;
4069 heap_insert(&evg->rules, &rule->evg_node,
4070 rule_eviction_priority(rule));
4071 eviction_group_resized(table, evg);
4077 /* Initializes 'table'. */
4079 oftable_init(struct oftable *table)
4081 memset(table, 0, sizeof *table);
4082 classifier_init(&table->cls);
4083 table->max_flows = UINT_MAX;
4086 /* Destroys 'table', including its classifier and eviction groups.
4088 * The caller is responsible for freeing 'table' itself. */
4090 oftable_destroy(struct oftable *table)
4092 assert(classifier_is_empty(&table->cls));
4093 oftable_disable_eviction(table);
4094 classifier_destroy(&table->cls);
4098 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
4099 * string, then 'table' will use its default name.
4101 * This only affects the name exposed for a table exposed through the OpenFlow
4102 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
4104 oftable_set_name(struct oftable *table, const char *name)
4106 if (name && name[0]) {
4107 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
4108 if (!table->name || strncmp(name, table->name, len)) {
4110 table->name = xmemdup0(name, len);
4118 /* oftables support a choice of two policies when adding a rule would cause the
4119 * number of flows in the table to exceed the configured maximum number: either
4120 * they can refuse to add the new flow or they can evict some existing flow.
4121 * This function configures the former policy on 'table'. */
4123 oftable_disable_eviction(struct oftable *table)
4125 if (table->eviction_fields) {
4126 struct eviction_group *evg, *next;
4128 HMAP_FOR_EACH_SAFE (evg, next, id_node,
4129 &table->eviction_groups_by_id) {
4130 eviction_group_destroy(table, evg);
4132 hmap_destroy(&table->eviction_groups_by_id);
4133 heap_destroy(&table->eviction_groups_by_size);
4135 free(table->eviction_fields);
4136 table->eviction_fields = NULL;
4137 table->n_eviction_fields = 0;
4141 /* oftables support a choice of two policies when adding a rule would cause the
4142 * number of flows in the table to exceed the configured maximum number: either
4143 * they can refuse to add the new flow or they can evict some existing flow.
4144 * This function configures the latter policy on 'table', with fairness based
4145 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
4146 * 'n_fields' as 0 disables fairness.) */
4148 oftable_enable_eviction(struct oftable *table,
4149 const struct mf_subfield *fields, size_t n_fields)
4151 struct cls_cursor cursor;
4154 if (table->eviction_fields
4155 && n_fields == table->n_eviction_fields
4157 || !memcmp(fields, table->eviction_fields,
4158 n_fields * sizeof *fields))) {
4163 oftable_disable_eviction(table);
4165 table->n_eviction_fields = n_fields;
4166 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
4168 table->eviction_group_id_basis = random_uint32();
4169 hmap_init(&table->eviction_groups_by_id);
4170 heap_init(&table->eviction_groups_by_size);
4172 cls_cursor_init(&cursor, &table->cls, NULL);
4173 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4174 eviction_group_add_rule(rule);
4178 /* Removes 'rule' from the oftable that contains it. */
4180 oftable_remove_rule(struct rule *rule)
4182 struct ofproto *ofproto = rule->ofproto;
4183 struct oftable *table = &ofproto->tables[rule->table_id];
4185 classifier_remove(&table->cls, &rule->cr);
4186 eviction_group_remove_rule(rule);
4189 /* Inserts 'rule' into its oftable. Removes any existing rule from 'rule''s
4190 * oftable that has an identical cls_rule. Returns the rule that was removed,
4191 * if any, and otherwise NULL. */
4192 static struct rule *
4193 oftable_replace_rule(struct rule *rule)
4195 struct ofproto *ofproto = rule->ofproto;
4196 struct oftable *table = &ofproto->tables[rule->table_id];
4197 struct rule *victim;
4199 victim = rule_from_cls_rule(classifier_replace(&table->cls, &rule->cr));
4201 eviction_group_remove_rule(victim);
4203 eviction_group_add_rule(rule);
4207 /* Removes 'old' from its oftable then, if 'new' is nonnull, inserts 'new'. */
4209 oftable_substitute_rule(struct rule *old, struct rule *new)
4212 oftable_replace_rule(new);
4214 oftable_remove_rule(old);
4218 /* unixctl commands. */
4221 ofproto_lookup(const char *name)
4223 struct ofproto *ofproto;
4225 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
4227 if (!strcmp(ofproto->name, name)) {
4235 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
4236 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
4238 struct ofproto *ofproto;
4242 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
4243 ds_put_format(&results, "%s\n", ofproto->name);
4245 unixctl_command_reply(conn, ds_cstr(&results));
4246 ds_destroy(&results);
4250 ofproto_unixctl_init(void)
4252 static bool registered;
4258 unixctl_command_register("ofproto/list", "", 0, 0,
4259 ofproto_unixctl_list, NULL);
4262 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
4264 * This is deprecated. It is only for compatibility with broken device drivers
4265 * in old versions of Linux that do not properly support VLANs when VLAN
4266 * devices are not used. When broken device drivers are no longer in
4267 * widespread use, we will delete these interfaces. */
4269 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
4270 * (exactly) by an OpenFlow rule in 'ofproto'. */
4272 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
4274 const struct oftable *oftable;
4276 free(ofproto->vlan_bitmap);
4277 ofproto->vlan_bitmap = bitmap_allocate(4096);
4278 ofproto->vlans_changed = false;
4280 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
4281 const struct cls_table *table;
4283 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
4284 if ((table->wc.vlan_tci_mask & htons(VLAN_VID_MASK))
4285 == htons(VLAN_VID_MASK)) {
4286 const struct cls_rule *rule;
4288 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
4289 uint16_t vid = vlan_tci_to_vid(rule->flow.vlan_tci);
4290 bitmap_set1(vlan_bitmap, vid);
4291 bitmap_set1(ofproto->vlan_bitmap, vid);
4298 /* Returns true if new VLANs have come into use by the flow table since the
4299 * last call to ofproto_get_vlan_usage().
4301 * We don't track when old VLANs stop being used. */
4303 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
4305 return ofproto->vlans_changed;
4308 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
4309 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
4310 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
4311 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
4312 * then the VLAN device is un-enslaved. */
4314 ofproto_port_set_realdev(struct ofproto *ofproto, uint16_t vlandev_ofp_port,
4315 uint16_t realdev_ofp_port, int vid)
4317 struct ofport *ofport;
4320 assert(vlandev_ofp_port != realdev_ofp_port);
4322 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
4324 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
4325 ofproto->name, vlandev_ofp_port);
4329 if (!ofproto->ofproto_class->set_realdev) {
4330 if (!vlandev_ofp_port) {
4333 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
4337 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
4339 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
4340 ofproto->name, vlandev_ofp_port,
4341 netdev_get_name(ofport->netdev), strerror(error));