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. */
121 struct rule *victim; /* OFOPERATION_ADD: Replaced rule. */
122 struct ofpact *ofpacts; /* OFOPERATION_MODIFY: Replaced actions. */
123 size_t ofpacts_len; /* OFOPERATION_MODIFY: Bytes of ofpacts. */
124 ovs_be64 flow_cookie; /* Rule's old flow cookie. */
125 enum ofperr error; /* 0 if no error. */
128 static struct ofoperation *ofoperation_create(struct ofopgroup *,
130 enum ofoperation_type);
131 static void ofoperation_destroy(struct ofoperation *);
134 static void oftable_init(struct oftable *);
135 static void oftable_destroy(struct oftable *);
137 static void oftable_set_name(struct oftable *, const char *name);
139 static void oftable_disable_eviction(struct oftable *);
140 static void oftable_enable_eviction(struct oftable *,
141 const struct mf_subfield *fields,
144 static void oftable_remove_rule(struct rule *);
145 static struct rule *oftable_replace_rule(struct rule *);
146 static void oftable_substitute_rule(struct rule *old, struct rule *new);
148 /* A set of rules within a single OpenFlow table (oftable) that have the same
149 * values for the oftable's eviction_fields. A rule to be evicted, when one is
150 * needed, is taken from the eviction group that contains the greatest number
153 * An oftable owns any number of eviction groups, each of which contains any
156 * Membership in an eviction group is imprecise, based on the hash of the
157 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
158 * That is, if two rules have different eviction_fields, but those
159 * eviction_fields hash to the same value, then they will belong to the same
160 * eviction_group anyway.
162 * (When eviction is not enabled on an oftable, we don't track any eviction
163 * groups, to save time and space.) */
164 struct eviction_group {
165 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
166 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
167 struct heap rules; /* Contains "struct rule"s. */
170 static struct rule *choose_rule_to_evict(struct oftable *);
171 static void ofproto_evict(struct ofproto *);
172 static uint32_t rule_eviction_priority(struct rule *);
175 static void ofport_destroy__(struct ofport *);
176 static void ofport_destroy(struct ofport *);
178 static void update_port(struct ofproto *, const char *devname);
179 static int init_ports(struct ofproto *);
180 static void reinit_ports(struct ofproto *);
183 static void ofproto_rule_destroy__(struct rule *);
184 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
185 static bool rule_is_modifiable(const struct rule *);
186 static bool rule_is_hidden(const struct rule *);
189 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
190 const struct ofputil_flow_mod *,
191 const struct ofp_header *);
192 static void delete_flow__(struct rule *, struct ofopgroup *);
193 static bool handle_openflow(struct ofconn *, struct ofpbuf *);
194 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
195 const struct ofputil_flow_mod *,
196 const struct ofp_header *);
199 static uint64_t pick_datapath_id(const struct ofproto *);
200 static uint64_t pick_fallback_dpid(void);
201 static void ofproto_destroy__(struct ofproto *);
202 static void update_mtu(struct ofproto *, struct ofport *);
205 static void ofproto_unixctl_init(void);
207 /* All registered ofproto classes, in probe order. */
208 static const struct ofproto_class **ofproto_classes;
209 static size_t n_ofproto_classes;
210 static size_t allocated_ofproto_classes;
212 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
213 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
215 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
218 ofproto_initialize(void)
224 ofproto_class_register(&ofproto_dpif_class);
228 /* 'type' should be a normalized datapath type, as returned by
229 * ofproto_normalize_type(). Returns the corresponding ofproto_class
230 * structure, or a null pointer if there is none registered for 'type'. */
231 static const struct ofproto_class *
232 ofproto_class_find__(const char *type)
236 ofproto_initialize();
237 for (i = 0; i < n_ofproto_classes; i++) {
238 const struct ofproto_class *class = ofproto_classes[i];
243 class->enumerate_types(&types);
244 found = sset_contains(&types, type);
245 sset_destroy(&types);
251 VLOG_WARN("unknown datapath type %s", type);
255 /* Registers a new ofproto class. After successful registration, new ofprotos
256 * of that type can be created using ofproto_create(). */
258 ofproto_class_register(const struct ofproto_class *new_class)
262 for (i = 0; i < n_ofproto_classes; i++) {
263 if (ofproto_classes[i] == new_class) {
268 if (n_ofproto_classes >= allocated_ofproto_classes) {
269 ofproto_classes = x2nrealloc(ofproto_classes,
270 &allocated_ofproto_classes,
271 sizeof *ofproto_classes);
273 ofproto_classes[n_ofproto_classes++] = new_class;
277 /* Unregisters a datapath provider. 'type' must have been previously
278 * registered and not currently be in use by any ofprotos. After
279 * unregistration new datapaths of that type cannot be opened using
280 * ofproto_create(). */
282 ofproto_class_unregister(const struct ofproto_class *class)
286 for (i = 0; i < n_ofproto_classes; i++) {
287 if (ofproto_classes[i] == class) {
288 for (i++; i < n_ofproto_classes; i++) {
289 ofproto_classes[i - 1] = ofproto_classes[i];
295 VLOG_WARN("attempted to unregister an ofproto class that is not "
300 /* Clears 'types' and enumerates all registered ofproto types into it. The
301 * caller must first initialize the sset. */
303 ofproto_enumerate_types(struct sset *types)
307 ofproto_initialize();
308 for (i = 0; i < n_ofproto_classes; i++) {
309 ofproto_classes[i]->enumerate_types(types);
313 /* Returns the fully spelled out name for the given ofproto 'type'.
315 * Normalized type string can be compared with strcmp(). Unnormalized type
316 * string might be the same even if they have different spellings. */
318 ofproto_normalize_type(const char *type)
320 return type && type[0] ? type : "system";
323 /* Clears 'names' and enumerates the names of all known created ofprotos with
324 * the given 'type'. The caller must first initialize the sset. Returns 0 if
325 * successful, otherwise a positive errno value.
327 * Some kinds of datapaths might not be practically enumerable. This is not
328 * considered an error. */
330 ofproto_enumerate_names(const char *type, struct sset *names)
332 const struct ofproto_class *class = ofproto_class_find__(type);
333 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
337 ofproto_create(const char *datapath_name, const char *datapath_type,
338 struct ofproto **ofprotop)
340 const struct ofproto_class *class;
341 struct ofproto *ofproto;
346 ofproto_initialize();
347 ofproto_unixctl_init();
349 datapath_type = ofproto_normalize_type(datapath_type);
350 class = ofproto_class_find__(datapath_type);
352 VLOG_WARN("could not create datapath %s of unknown type %s",
353 datapath_name, datapath_type);
357 ofproto = class->alloc();
359 VLOG_ERR("failed to allocate datapath %s of type %s",
360 datapath_name, datapath_type);
365 memset(ofproto, 0, sizeof *ofproto);
366 ofproto->ofproto_class = class;
367 ofproto->name = xstrdup(datapath_name);
368 ofproto->type = xstrdup(datapath_type);
369 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
370 hash_string(ofproto->name, 0));
371 ofproto->datapath_id = 0;
372 ofproto_set_flow_eviction_threshold(ofproto,
373 OFPROTO_FLOW_EVICTON_THRESHOLD_DEFAULT);
374 ofproto->forward_bpdu = false;
375 ofproto->fallback_dpid = pick_fallback_dpid();
376 ofproto->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
377 ofproto->hw_desc = xstrdup(DEFAULT_HW_DESC);
378 ofproto->sw_desc = xstrdup(DEFAULT_SW_DESC);
379 ofproto->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
380 ofproto->dp_desc = xstrdup(DEFAULT_DP_DESC);
381 ofproto->frag_handling = OFPC_FRAG_NORMAL;
382 hmap_init(&ofproto->ports);
383 shash_init(&ofproto->port_by_name);
384 ofproto->tables = NULL;
385 ofproto->n_tables = 0;
386 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
387 ofproto->state = S_OPENFLOW;
388 list_init(&ofproto->pending);
389 ofproto->n_pending = 0;
390 hmap_init(&ofproto->deletions);
391 ofproto->n_add = ofproto->n_delete = ofproto->n_modify = 0;
392 ofproto->first_op = ofproto->last_op = LLONG_MIN;
393 ofproto->next_op_report = LLONG_MAX;
394 ofproto->op_backoff = LLONG_MIN;
395 ofproto->vlan_bitmap = NULL;
396 ofproto->vlans_changed = false;
397 ofproto->min_mtu = INT_MAX;
399 error = ofproto->ofproto_class->construct(ofproto);
401 VLOG_ERR("failed to open datapath %s: %s",
402 datapath_name, strerror(error));
403 ofproto_destroy__(ofproto);
407 assert(ofproto->n_tables);
409 ofproto->datapath_id = pick_datapath_id(ofproto);
417 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
419 struct oftable *table;
421 assert(!ofproto->n_tables);
422 assert(n_tables >= 1 && n_tables <= 255);
424 ofproto->n_tables = n_tables;
425 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
426 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
432 ofproto_get_datapath_id(const struct ofproto *ofproto)
434 return ofproto->datapath_id;
438 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
440 uint64_t old_dpid = p->datapath_id;
441 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
442 if (p->datapath_id != old_dpid) {
443 /* Force all active connections to reconnect, since there is no way to
444 * notify a controller that the datapath ID has changed. */
445 ofproto_reconnect_controllers(p);
450 ofproto_set_controllers(struct ofproto *p,
451 const struct ofproto_controller *controllers,
452 size_t n_controllers)
454 connmgr_set_controllers(p->connmgr, controllers, n_controllers);
458 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
460 connmgr_set_fail_mode(p->connmgr, fail_mode);
463 /* Drops the connections between 'ofproto' and all of its controllers, forcing
464 * them to reconnect. */
466 ofproto_reconnect_controllers(struct ofproto *ofproto)
468 connmgr_reconnect(ofproto->connmgr);
471 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
472 * in-band control should guarantee access, in the same way that in-band
473 * control guarantees access to OpenFlow controllers. */
475 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
476 const struct sockaddr_in *extras, size_t n)
478 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
481 /* Sets the OpenFlow queue used by flows set up by in-band control on
482 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
483 * flows will use the default queue. */
485 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
487 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
490 /* Sets the number of flows at which eviction from the kernel flow table
493 ofproto_set_flow_eviction_threshold(struct ofproto *ofproto, unsigned threshold)
495 if (threshold < OFPROTO_FLOW_EVICTION_THRESHOLD_MIN) {
496 ofproto->flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_MIN;
498 ofproto->flow_eviction_threshold = threshold;
502 /* If forward_bpdu is true, the NORMAL action will forward frames with
503 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
504 * the NORMAL action will drop these frames. */
506 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
508 bool old_val = ofproto->forward_bpdu;
509 ofproto->forward_bpdu = forward_bpdu;
510 if (old_val != ofproto->forward_bpdu) {
511 if (ofproto->ofproto_class->forward_bpdu_changed) {
512 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
517 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
518 * 'idle_time', in seconds. */
520 ofproto_set_mac_idle_time(struct ofproto *ofproto, unsigned idle_time)
522 if (ofproto->ofproto_class->set_mac_idle_time) {
523 ofproto->ofproto_class->set_mac_idle_time(ofproto, idle_time);
528 ofproto_set_desc(struct ofproto *p,
529 const char *mfr_desc, const char *hw_desc,
530 const char *sw_desc, const char *serial_desc,
533 struct ofp_desc_stats *ods;
536 if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
537 VLOG_WARN("%s: truncating mfr_desc, must be less than %zu bytes",
538 p->name, sizeof ods->mfr_desc);
541 p->mfr_desc = xstrdup(mfr_desc);
544 if (strlen(hw_desc) >= sizeof ods->hw_desc) {
545 VLOG_WARN("%s: truncating hw_desc, must be less than %zu bytes",
546 p->name, sizeof ods->hw_desc);
549 p->hw_desc = xstrdup(hw_desc);
552 if (strlen(sw_desc) >= sizeof ods->sw_desc) {
553 VLOG_WARN("%s: truncating sw_desc, must be less than %zu bytes",
554 p->name, sizeof ods->sw_desc);
557 p->sw_desc = xstrdup(sw_desc);
560 if (strlen(serial_desc) >= sizeof ods->serial_num) {
561 VLOG_WARN("%s: truncating serial_desc, must be less than %zu "
562 "bytes", p->name, sizeof ods->serial_num);
564 free(p->serial_desc);
565 p->serial_desc = xstrdup(serial_desc);
568 if (strlen(dp_desc) >= sizeof ods->dp_desc) {
569 VLOG_WARN("%s: truncating dp_desc, must be less than %zu bytes",
570 p->name, sizeof ods->dp_desc);
573 p->dp_desc = xstrdup(dp_desc);
578 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
580 return connmgr_set_snoops(ofproto->connmgr, snoops);
584 ofproto_set_netflow(struct ofproto *ofproto,
585 const struct netflow_options *nf_options)
587 if (nf_options && sset_is_empty(&nf_options->collectors)) {
591 if (ofproto->ofproto_class->set_netflow) {
592 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
594 return nf_options ? EOPNOTSUPP : 0;
599 ofproto_set_sflow(struct ofproto *ofproto,
600 const struct ofproto_sflow_options *oso)
602 if (oso && sset_is_empty(&oso->targets)) {
606 if (ofproto->ofproto_class->set_sflow) {
607 return ofproto->ofproto_class->set_sflow(ofproto, oso);
609 return oso ? EOPNOTSUPP : 0;
613 /* Spanning Tree Protocol (STP) configuration. */
615 /* Configures STP on 'ofproto' using the settings defined in 's'. If
616 * 's' is NULL, disables STP.
618 * Returns 0 if successful, otherwise a positive errno value. */
620 ofproto_set_stp(struct ofproto *ofproto,
621 const struct ofproto_stp_settings *s)
623 return (ofproto->ofproto_class->set_stp
624 ? ofproto->ofproto_class->set_stp(ofproto, s)
628 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
629 * 'enabled' member of 's' is false, then the other members are not
632 * Returns 0 if successful, otherwise a positive errno value. */
634 ofproto_get_stp_status(struct ofproto *ofproto,
635 struct ofproto_stp_status *s)
637 return (ofproto->ofproto_class->get_stp_status
638 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
642 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
643 * in 's'. The caller is responsible for assigning STP port numbers
644 * (using the 'port_num' member in the range of 1 through 255, inclusive)
645 * and ensuring there are no duplicates. If the 's' is NULL, then STP
646 * is disabled on the port.
648 * Returns 0 if successful, otherwise a positive errno value.*/
650 ofproto_port_set_stp(struct ofproto *ofproto, uint16_t ofp_port,
651 const struct ofproto_port_stp_settings *s)
653 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
655 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
656 ofproto->name, ofp_port);
660 return (ofproto->ofproto_class->set_stp_port
661 ? ofproto->ofproto_class->set_stp_port(ofport, s)
665 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
666 * 's'. If the 'enabled' member in 's' is false, then the other members
667 * are not meaningful.
669 * Returns 0 if successful, otherwise a positive errno value.*/
671 ofproto_port_get_stp_status(struct ofproto *ofproto, uint16_t ofp_port,
672 struct ofproto_port_stp_status *s)
674 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
676 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
677 "port %"PRIu16, ofproto->name, ofp_port);
681 return (ofproto->ofproto_class->get_stp_port_status
682 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
686 /* Queue DSCP configuration. */
688 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
689 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
690 * to implement QoS. Instead, it is used to implement features which require
691 * knowledge of what queues exist on a port, and some basic information about
694 * Returns 0 if successful, otherwise a positive errno value. */
696 ofproto_port_set_queues(struct ofproto *ofproto, uint16_t ofp_port,
697 const struct ofproto_port_queue *queues,
700 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
703 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
704 ofproto->name, ofp_port);
708 return (ofproto->ofproto_class->set_queues
709 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
713 /* Connectivity Fault Management configuration. */
715 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
717 ofproto_port_clear_cfm(struct ofproto *ofproto, uint16_t ofp_port)
719 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
720 if (ofport && ofproto->ofproto_class->set_cfm) {
721 ofproto->ofproto_class->set_cfm(ofport, NULL);
725 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
726 * basic configuration from the configuration members in 'cfm', and the remote
727 * maintenance point ID from remote_mpid. Ignores the statistics members of
730 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
732 ofproto_port_set_cfm(struct ofproto *ofproto, uint16_t ofp_port,
733 const struct cfm_settings *s)
735 struct ofport *ofport;
738 ofport = ofproto_get_port(ofproto, ofp_port);
740 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
741 ofproto->name, ofp_port);
745 /* XXX: For configuration simplicity, we only support one remote_mpid
746 * outside of the CFM module. It's not clear if this is the correct long
747 * term solution or not. */
748 error = (ofproto->ofproto_class->set_cfm
749 ? ofproto->ofproto_class->set_cfm(ofport, s)
752 VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
753 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
758 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
759 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
760 * 0 if LACP partner information is not current (generally indicating a
761 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
763 ofproto_port_is_lacp_current(struct ofproto *ofproto, uint16_t ofp_port)
765 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
766 return (ofport && ofproto->ofproto_class->port_is_lacp_current
767 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
773 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
774 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
775 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
776 * configuration plus, if there is more than one slave, a bonding
779 * If 'aux' is already registered then this function updates its configuration
780 * to 's'. Otherwise, this function registers a new bundle.
782 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
785 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
786 const struct ofproto_bundle_settings *s)
788 return (ofproto->ofproto_class->bundle_set
789 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
793 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
794 * If no such bundle has been registered, this has no effect. */
796 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
798 return ofproto_bundle_register(ofproto, aux, NULL);
802 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
803 * If 'aux' is already registered then this function updates its configuration
804 * to 's'. Otherwise, this function registers a new mirror. */
806 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
807 const struct ofproto_mirror_settings *s)
809 return (ofproto->ofproto_class->mirror_set
810 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
814 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
815 * If no mirror has been registered, this has no effect. */
817 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
819 return ofproto_mirror_register(ofproto, aux, NULL);
822 /* Retrieves statistics from mirror associated with client data pointer
823 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
824 * 'bytes', respectively. If a particular counters is not supported,
825 * the appropriate argument is set to UINT64_MAX. */
827 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
828 uint64_t *packets, uint64_t *bytes)
830 if (!ofproto->ofproto_class->mirror_get_stats) {
831 *packets = *bytes = UINT64_MAX;
835 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
839 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
840 * which all packets are flooded, instead of using MAC learning. If
841 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
843 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
846 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
848 return (ofproto->ofproto_class->set_flood_vlans
849 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
853 /* Returns true if 'aux' is a registered bundle that is currently in use as the
854 * output for a mirror. */
856 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
858 return (ofproto->ofproto_class->is_mirror_output_bundle
859 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
863 /* Configuration of OpenFlow tables. */
865 /* Returns the number of OpenFlow tables in 'ofproto'. */
867 ofproto_get_n_tables(const struct ofproto *ofproto)
869 return ofproto->n_tables;
872 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
873 * settings from 's'. 'table_id' must be in the range 0 through the number of
874 * OpenFlow tables in 'ofproto' minus 1, inclusive.
876 * For read-only tables, only the name may be configured. */
878 ofproto_configure_table(struct ofproto *ofproto, int table_id,
879 const struct ofproto_table_settings *s)
881 struct oftable *table;
883 assert(table_id >= 0 && table_id < ofproto->n_tables);
884 table = &ofproto->tables[table_id];
886 oftable_set_name(table, s->name);
888 if (table->flags & OFTABLE_READONLY) {
893 oftable_enable_eviction(table, s->groups, s->n_groups);
895 oftable_disable_eviction(table);
898 table->max_flows = s->max_flows;
899 if (classifier_count(&table->cls) > table->max_flows
900 && table->eviction_fields) {
901 /* 'table' contains more flows than allowed. We might not be able to
902 * evict them right away because of the asynchronous nature of flow
903 * table changes. Schedule eviction for later. */
904 switch (ofproto->state) {
906 ofproto->state = S_EVICT;
910 /* We're already deleting flows, nothing more to do. */
917 ofproto_has_snoops(const struct ofproto *ofproto)
919 return connmgr_has_snoops(ofproto->connmgr);
923 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
925 connmgr_get_snoops(ofproto->connmgr, snoops);
929 ofproto_flush__(struct ofproto *ofproto)
931 struct ofopgroup *group;
932 struct oftable *table;
934 if (ofproto->ofproto_class->flush) {
935 ofproto->ofproto_class->flush(ofproto);
938 group = ofopgroup_create_unattached(ofproto);
939 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
940 struct rule *rule, *next_rule;
941 struct cls_cursor cursor;
943 if (table->flags & OFTABLE_HIDDEN) {
947 cls_cursor_init(&cursor, &table->cls, NULL);
948 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
949 if (!rule->pending) {
950 ofoperation_create(group, rule, OFOPERATION_DELETE);
951 oftable_remove_rule(rule);
952 ofproto->ofproto_class->rule_destruct(rule);
956 ofopgroup_submit(group);
960 ofproto_destroy__(struct ofproto *ofproto)
962 struct oftable *table;
964 assert(list_is_empty(&ofproto->pending));
965 assert(!ofproto->n_pending);
967 connmgr_destroy(ofproto->connmgr);
969 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
972 free(ofproto->mfr_desc);
973 free(ofproto->hw_desc);
974 free(ofproto->sw_desc);
975 free(ofproto->serial_desc);
976 free(ofproto->dp_desc);
977 hmap_destroy(&ofproto->ports);
978 shash_destroy(&ofproto->port_by_name);
980 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
981 oftable_destroy(table);
983 free(ofproto->tables);
985 hmap_destroy(&ofproto->deletions);
987 free(ofproto->vlan_bitmap);
989 ofproto->ofproto_class->dealloc(ofproto);
993 ofproto_destroy(struct ofproto *p)
995 struct ofport *ofport, *next_ofport;
1002 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1003 ofport_destroy(ofport);
1006 p->ofproto_class->destruct(p);
1007 ofproto_destroy__(p);
1010 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1011 * kernel datapath, for example, this destroys the datapath in the kernel, and
1012 * with the netdev-based datapath, it tears down the data structures that
1013 * represent the datapath.
1015 * The datapath should not be currently open as an ofproto. */
1017 ofproto_delete(const char *name, const char *type)
1019 const struct ofproto_class *class = ofproto_class_find__(type);
1020 return (!class ? EAFNOSUPPORT
1021 : !class->del ? EACCES
1022 : class->del(type, name));
1026 process_port_change(struct ofproto *ofproto, int error, char *devname)
1028 if (error == ENOBUFS) {
1029 reinit_ports(ofproto);
1030 } else if (!error) {
1031 update_port(ofproto, devname);
1037 ofproto_run(struct ofproto *p)
1039 struct sset changed_netdevs;
1040 const char *changed_netdev;
1041 struct ofport *ofport;
1044 error = p->ofproto_class->run(p);
1045 if (error && error != EAGAIN) {
1046 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, strerror(error));
1049 if (p->ofproto_class->port_poll) {
1052 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1053 process_port_change(p, error, devname);
1057 /* Update OpenFlow port status for any port whose netdev has changed.
1059 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1060 * destroyed, so it's not safe to update ports directly from the
1061 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1062 * need this two-phase approach. */
1063 sset_init(&changed_netdevs);
1064 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1065 unsigned int change_seq = netdev_change_seq(ofport->netdev);
1066 if (ofport->change_seq != change_seq) {
1067 ofport->change_seq = change_seq;
1068 sset_add(&changed_netdevs, netdev_get_name(ofport->netdev));
1071 SSET_FOR_EACH (changed_netdev, &changed_netdevs) {
1072 update_port(p, changed_netdev);
1074 sset_destroy(&changed_netdevs);
1078 connmgr_run(p->connmgr, handle_openflow);
1082 connmgr_run(p->connmgr, NULL);
1084 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1085 p->state = S_OPENFLOW;
1090 connmgr_run(p->connmgr, NULL);
1092 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1093 connmgr_flushed(p->connmgr);
1094 p->state = S_OPENFLOW;
1102 if (time_msec() >= p->next_op_report) {
1103 long long int ago = (time_msec() - p->first_op) / 1000;
1104 long long int interval = (p->last_op - p->first_op) / 1000;
1108 ds_put_format(&s, "%d flow_mods ",
1109 p->n_add + p->n_delete + p->n_modify);
1110 if (interval == ago) {
1111 ds_put_format(&s, "in the last %lld s", ago);
1112 } else if (interval) {
1113 ds_put_format(&s, "in the %lld s starting %lld s ago",
1116 ds_put_format(&s, "%lld s ago", ago);
1119 ds_put_cstr(&s, " (");
1121 ds_put_format(&s, "%d adds, ", p->n_add);
1124 ds_put_format(&s, "%d deletes, ", p->n_delete);
1127 ds_put_format(&s, "%d modifications, ", p->n_modify);
1130 ds_put_char(&s, ')');
1132 VLOG_INFO("%s: %s", p->name, ds_cstr(&s));
1135 p->n_add = p->n_delete = p->n_modify = 0;
1136 p->next_op_report = LLONG_MAX;
1142 /* Performs periodic activity required by 'ofproto' that needs to be done
1143 * with the least possible latency.
1145 * It makes sense to call this function a couple of times per poll loop, to
1146 * provide a significant performance boost on some benchmarks with the
1147 * ofproto-dpif implementation. */
1149 ofproto_run_fast(struct ofproto *p)
1153 error = p->ofproto_class->run_fast ? p->ofproto_class->run_fast(p) : 0;
1154 if (error && error != EAGAIN) {
1155 VLOG_ERR_RL(&rl, "%s: fastpath run failed (%s)",
1156 p->name, strerror(error));
1162 ofproto_wait(struct ofproto *p)
1164 struct ofport *ofport;
1166 p->ofproto_class->wait(p);
1167 if (p->ofproto_class->port_poll_wait) {
1168 p->ofproto_class->port_poll_wait(p);
1171 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1172 if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
1173 poll_immediate_wake();
1179 connmgr_wait(p->connmgr, true);
1184 connmgr_wait(p->connmgr, false);
1185 if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
1186 poll_immediate_wake();
1193 ofproto_is_alive(const struct ofproto *p)
1195 return connmgr_has_controllers(p->connmgr);
1198 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1199 * memory_report(). */
1201 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1203 const struct oftable *table;
1204 unsigned int n_rules;
1206 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1207 simap_increase(usage, "ops",
1208 ofproto->n_pending + hmap_count(&ofproto->deletions));
1211 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1212 n_rules += classifier_count(&table->cls);
1214 simap_increase(usage, "rules", n_rules);
1216 if (ofproto->ofproto_class->get_memory_usage) {
1217 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1220 connmgr_get_memory_usage(ofproto->connmgr, usage);
1224 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1227 connmgr_get_controller_info(ofproto->connmgr, info);
1231 ofproto_free_ofproto_controller_info(struct shash *info)
1233 connmgr_free_controller_info(info);
1236 /* Makes a deep copy of 'old' into 'port'. */
1238 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1240 port->name = xstrdup(old->name);
1241 port->type = xstrdup(old->type);
1242 port->ofp_port = old->ofp_port;
1245 /* Frees memory allocated to members of 'ofproto_port'.
1247 * Do not call this function on an ofproto_port obtained from
1248 * ofproto_port_dump_next(): that function retains ownership of the data in the
1251 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1253 free(ofproto_port->name);
1254 free(ofproto_port->type);
1257 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1259 * This function provides no status indication. An error status for the entire
1260 * dump operation is provided when it is completed by calling
1261 * ofproto_port_dump_done().
1264 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1265 const struct ofproto *ofproto)
1267 dump->ofproto = ofproto;
1268 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1272 /* Attempts to retrieve another port from 'dump', which must have been created
1273 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1274 * 'port' and returns true. On failure, returns false.
1276 * Failure might indicate an actual error or merely that the last port has been
1277 * dumped. An error status for the entire dump operation is provided when it
1278 * is completed by calling ofproto_port_dump_done().
1280 * The ofproto owns the data stored in 'port'. It will remain valid until at
1281 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1282 * ofproto_port_dump_done(). */
1284 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1285 struct ofproto_port *port)
1287 const struct ofproto *ofproto = dump->ofproto;
1293 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1296 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1302 /* Completes port table dump operation 'dump', which must have been created
1303 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1304 * error-free, otherwise a positive errno value describing the problem. */
1306 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1308 const struct ofproto *ofproto = dump->ofproto;
1310 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1313 return dump->error == EOF ? 0 : dump->error;
1316 /* Attempts to add 'netdev' as a port on 'ofproto'. If successful, returns 0
1317 * and sets '*ofp_portp' to the new port's OpenFlow port number (if 'ofp_portp'
1318 * is non-null). On failure, returns a positive errno value and sets
1319 * '*ofp_portp' to OFPP_NONE (if 'ofp_portp' is non-null). */
1321 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1322 uint16_t *ofp_portp)
1327 error = ofproto->ofproto_class->port_add(ofproto, netdev, &ofp_port);
1329 update_port(ofproto, netdev_get_name(netdev));
1332 *ofp_portp = error ? OFPP_NONE : ofp_port;
1337 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
1338 * initializes '*port' appropriately; on failure, returns a positive errno
1341 * The caller owns the data in 'ofproto_port' and must free it with
1342 * ofproto_port_destroy() when it is no longer needed. */
1344 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1345 struct ofproto_port *port)
1349 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1351 memset(port, 0, sizeof *port);
1356 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1357 * Returns 0 if successful, otherwise a positive errno. */
1359 ofproto_port_del(struct ofproto *ofproto, uint16_t ofp_port)
1361 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1362 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1365 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1366 if (!error && ofport) {
1367 /* 'name' is the netdev's name and update_port() is going to close the
1368 * netdev. Just in case update_port() refers to 'name' after it
1369 * destroys 'ofport', make a copy of it around the update_port()
1371 char *devname = xstrdup(name);
1372 update_port(ofproto, devname);
1378 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1379 * performs the 'n_actions' actions in 'actions'. The new flow will not
1382 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1383 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1384 * controllers; otherwise, it will be hidden.
1386 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1388 * This is a helper function for in-band control and fail-open. */
1390 ofproto_add_flow(struct ofproto *ofproto, const struct cls_rule *cls_rule,
1391 const struct ofpact *ofpacts, size_t ofpacts_len)
1393 const struct rule *rule;
1395 rule = rule_from_cls_rule(classifier_find_rule_exactly(
1396 &ofproto->tables[0].cls, cls_rule));
1397 if (!rule || !ofpacts_equal(rule->ofpacts, rule->ofpacts_len,
1398 ofpacts, ofpacts_len)) {
1399 struct ofputil_flow_mod fm;
1401 memset(&fm, 0, sizeof fm);
1403 fm.buffer_id = UINT32_MAX;
1404 fm.ofpacts = xmemdup(ofpacts, ofpacts_len);
1405 fm.ofpacts_len = ofpacts_len;
1406 add_flow(ofproto, NULL, &fm, NULL);
1411 /* Executes the flow modification specified in 'fm'. Returns 0 on success, an
1412 * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1413 * operation cannot be initiated now but may be retried later.
1415 * This is a helper function for in-band control and fail-open. */
1417 ofproto_flow_mod(struct ofproto *ofproto, const struct ofputil_flow_mod *fm)
1419 return handle_flow_mod__(ofproto, NULL, fm, NULL);
1422 /* Searches for a rule with matching criteria exactly equal to 'target' in
1423 * ofproto's table 0 and, if it finds one, deletes it.
1425 * This is a helper function for in-band control and fail-open. */
1427 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
1431 rule = rule_from_cls_rule(classifier_find_rule_exactly(
1432 &ofproto->tables[0].cls, target));
1434 /* No such rule -> success. */
1436 } else if (rule->pending) {
1437 /* An operation on the rule is already pending -> failure.
1438 * Caller must retry later if it's important. */
1441 /* Initiate deletion -> success. */
1442 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
1443 ofoperation_create(group, rule, OFOPERATION_DELETE);
1444 oftable_remove_rule(rule);
1445 ofproto->ofproto_class->rule_destruct(rule);
1446 ofopgroup_submit(group);
1452 /* Starts the process of deleting all of the flows from all of ofproto's flow
1453 * tables and then reintroducing the flows required by in-band control and
1454 * fail-open. The process will complete in a later call to ofproto_run(). */
1456 ofproto_flush_flows(struct ofproto *ofproto)
1458 COVERAGE_INC(ofproto_flush);
1459 ofproto->state = S_FLUSH;
1463 reinit_ports(struct ofproto *p)
1465 struct ofproto_port_dump dump;
1466 struct sset devnames;
1467 struct ofport *ofport;
1468 struct ofproto_port ofproto_port;
1469 const char *devname;
1471 COVERAGE_INC(ofproto_reinit_ports);
1473 sset_init(&devnames);
1474 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1475 sset_add(&devnames, netdev_get_name(ofport->netdev));
1477 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1478 sset_add(&devnames, ofproto_port.name);
1481 SSET_FOR_EACH (devname, &devnames) {
1482 update_port(p, devname);
1484 sset_destroy(&devnames);
1487 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
1488 * pointer if the netdev cannot be opened. On success, also fills in
1490 static struct netdev *
1491 ofport_open(const struct ofproto *ofproto,
1492 const struct ofproto_port *ofproto_port,
1493 struct ofputil_phy_port *pp)
1495 enum netdev_flags flags;
1496 struct netdev *netdev;
1499 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1501 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
1502 "cannot be opened (%s)",
1504 ofproto_port->name, ofproto_port->ofp_port,
1505 ofproto_port->name, strerror(error));
1509 pp->port_no = ofproto_port->ofp_port;
1510 netdev_get_etheraddr(netdev, pp->hw_addr);
1511 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
1512 netdev_get_flags(netdev, &flags);
1513 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
1514 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
1515 netdev_get_features(netdev, &pp->curr, &pp->advertised,
1516 &pp->supported, &pp->peer);
1517 pp->curr_speed = netdev_features_to_bps(pp->curr);
1518 pp->max_speed = netdev_features_to_bps(pp->supported);
1523 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
1524 * port number, and 'config' bits other than OFPUTIL_PS_LINK_DOWN are
1527 ofport_equal(const struct ofputil_phy_port *a,
1528 const struct ofputil_phy_port *b)
1530 return (eth_addr_equals(a->hw_addr, b->hw_addr)
1531 && a->state == b->state
1532 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
1533 && a->curr == b->curr
1534 && a->advertised == b->advertised
1535 && a->supported == b->supported
1536 && a->peer == b->peer
1537 && a->curr_speed == b->curr_speed
1538 && a->max_speed == b->max_speed);
1541 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1542 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1543 * one with the same name or port number). */
1545 ofport_install(struct ofproto *p,
1546 struct netdev *netdev, const struct ofputil_phy_port *pp)
1548 const char *netdev_name = netdev_get_name(netdev);
1549 struct ofport *ofport;
1552 /* Create ofport. */
1553 ofport = p->ofproto_class->port_alloc();
1558 ofport->ofproto = p;
1559 ofport->netdev = netdev;
1560 ofport->change_seq = netdev_change_seq(netdev);
1562 ofport->ofp_port = pp->port_no;
1564 /* Add port to 'p'. */
1565 hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->ofp_port, 0));
1566 shash_add(&p->port_by_name, netdev_name, ofport);
1568 update_mtu(p, ofport);
1570 /* Let the ofproto_class initialize its private data. */
1571 error = p->ofproto_class->port_construct(ofport);
1575 connmgr_send_port_status(p->connmgr, pp, OFPPR_ADD);
1579 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
1580 p->name, netdev_name, strerror(error));
1582 ofport_destroy__(ofport);
1584 netdev_close(netdev);
1588 /* Removes 'ofport' from 'p' and destroys it. */
1590 ofport_remove(struct ofport *ofport)
1592 connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->pp,
1594 ofport_destroy(ofport);
1597 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1600 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1602 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1604 ofport_remove(port);
1608 /* Updates 'port' with new 'pp' description.
1610 * Does not handle a name or port number change. The caller must implement
1611 * such a change as a delete followed by an add. */
1613 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
1615 memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
1616 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
1617 | (pp->config & OFPUTIL_PC_PORT_DOWN));
1618 port->pp.state = pp->state;
1619 port->pp.curr = pp->curr;
1620 port->pp.advertised = pp->advertised;
1621 port->pp.supported = pp->supported;
1622 port->pp.peer = pp->peer;
1623 port->pp.curr_speed = pp->curr_speed;
1624 port->pp.max_speed = pp->max_speed;
1626 connmgr_send_port_status(port->ofproto->connmgr, &port->pp, OFPPR_MODIFY);
1629 /* Update OpenFlow 'state' in 'port' and notify controller. */
1631 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
1633 if (port->pp.state != state) {
1634 port->pp.state = state;
1635 connmgr_send_port_status(port->ofproto->connmgr, &port->pp,
1641 ofproto_port_unregister(struct ofproto *ofproto, uint16_t ofp_port)
1643 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
1645 if (port->ofproto->ofproto_class->set_realdev) {
1646 port->ofproto->ofproto_class->set_realdev(port, 0, 0);
1648 if (port->ofproto->ofproto_class->set_stp_port) {
1649 port->ofproto->ofproto_class->set_stp_port(port, NULL);
1651 if (port->ofproto->ofproto_class->set_cfm) {
1652 port->ofproto->ofproto_class->set_cfm(port, NULL);
1654 if (port->ofproto->ofproto_class->bundle_remove) {
1655 port->ofproto->ofproto_class->bundle_remove(port);
1661 ofport_destroy__(struct ofport *port)
1663 struct ofproto *ofproto = port->ofproto;
1664 const char *name = netdev_get_name(port->netdev);
1666 hmap_remove(&ofproto->ports, &port->hmap_node);
1667 shash_delete(&ofproto->port_by_name,
1668 shash_find(&ofproto->port_by_name, name));
1670 netdev_close(port->netdev);
1671 ofproto->ofproto_class->port_dealloc(port);
1675 ofport_destroy(struct ofport *port)
1678 port->ofproto->ofproto_class->port_destruct(port);
1679 ofport_destroy__(port);
1684 ofproto_get_port(const struct ofproto *ofproto, uint16_t ofp_port)
1686 struct ofport *port;
1688 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1689 hash_int(ofp_port, 0), &ofproto->ports) {
1690 if (port->ofp_port == ofp_port) {
1698 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
1700 struct ofproto *ofproto = port->ofproto;
1703 if (ofproto->ofproto_class->port_get_stats) {
1704 error = ofproto->ofproto_class->port_get_stats(port, stats);
1713 update_port(struct ofproto *ofproto, const char *name)
1715 struct ofproto_port ofproto_port;
1716 struct ofputil_phy_port pp;
1717 struct netdev *netdev;
1718 struct ofport *port;
1720 COVERAGE_INC(ofproto_update_port);
1722 /* Fetch 'name''s location and properties from the datapath. */
1723 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
1724 ? ofport_open(ofproto, &ofproto_port, &pp)
1727 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
1728 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
1729 struct netdev *old_netdev = port->netdev;
1731 /* 'name' hasn't changed location. Any properties changed? */
1732 if (!ofport_equal(&port->pp, &pp)) {
1733 ofport_modified(port, &pp);
1736 update_mtu(ofproto, port);
1738 /* Install the newly opened netdev in case it has changed.
1739 * Don't close the old netdev yet in case port_modified has to
1740 * remove a retained reference to it.*/
1741 port->netdev = netdev;
1742 port->change_seq = netdev_change_seq(netdev);
1744 if (port->ofproto->ofproto_class->port_modified) {
1745 port->ofproto->ofproto_class->port_modified(port);
1748 netdev_close(old_netdev);
1750 /* If 'port' is nonnull then its name differs from 'name' and thus
1751 * we should delete it. If we think there's a port named 'name'
1752 * then its port number must be wrong now so delete it too. */
1754 ofport_remove(port);
1756 ofport_remove_with_name(ofproto, name);
1757 ofport_install(ofproto, netdev, &pp);
1760 /* Any port named 'name' is gone now. */
1761 ofport_remove_with_name(ofproto, name);
1763 ofproto_port_destroy(&ofproto_port);
1767 init_ports(struct ofproto *p)
1769 struct ofproto_port_dump dump;
1770 struct ofproto_port ofproto_port;
1772 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1773 uint16_t ofp_port = ofproto_port.ofp_port;
1774 if (ofproto_get_port(p, ofp_port)) {
1775 VLOG_WARN_RL(&rl, "%s: ignoring duplicate port %"PRIu16" "
1776 "in datapath", p->name, ofp_port);
1777 } else if (shash_find(&p->port_by_name, ofproto_port.name)) {
1778 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
1779 p->name, ofproto_port.name);
1781 struct ofputil_phy_port pp;
1782 struct netdev *netdev;
1784 netdev = ofport_open(p, &ofproto_port, &pp);
1786 ofport_install(p, netdev, &pp);
1794 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
1795 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
1797 find_min_mtu(struct ofproto *p)
1799 struct ofport *ofport;
1802 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1803 struct netdev *netdev = ofport->netdev;
1806 /* Skip any internal ports, since that's what we're trying to
1808 if (!strcmp(netdev_get_type(netdev), "internal")) {
1812 if (netdev_get_mtu(netdev, &dev_mtu)) {
1815 if (!mtu || dev_mtu < mtu) {
1820 return mtu ? mtu: ETH_PAYLOAD_MAX;
1823 /* Update MTU of all datapath devices on 'p' to the minimum of the
1824 * non-datapath ports in event of 'port' added or changed. */
1826 update_mtu(struct ofproto *p, struct ofport *port)
1828 struct ofport *ofport;
1829 struct netdev *netdev = port->netdev;
1830 int dev_mtu, old_min;
1832 if (netdev_get_mtu(netdev, &dev_mtu)) {
1836 if (!strcmp(netdev_get_type(port->netdev), "internal")) {
1837 if (dev_mtu > p->min_mtu) {
1838 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
1839 dev_mtu = p->min_mtu;
1842 port->mtu = dev_mtu;
1846 /* For non-internal port find new min mtu. */
1847 old_min = p->min_mtu;
1848 port->mtu = dev_mtu;
1849 p->min_mtu = find_min_mtu(p);
1850 if (p->min_mtu == old_min) {
1854 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1855 struct netdev *netdev = ofport->netdev;
1857 if (!strcmp(netdev_get_type(netdev), "internal")) {
1858 if (!netdev_set_mtu(netdev, p->min_mtu)) {
1859 ofport->mtu = p->min_mtu;
1866 ofproto_rule_destroy__(struct rule *rule)
1869 free(rule->ofpacts);
1870 rule->ofproto->ofproto_class->rule_dealloc(rule);
1874 /* This function allows an ofproto implementation to destroy any rules that
1875 * remain when its ->destruct() function is called. The caller must have
1876 * already uninitialized any derived members of 'rule' (step 5 described in the
1877 * large comment in ofproto/ofproto-provider.h titled "Life Cycle").
1878 * This function implements steps 6 and 7.
1880 * This function should only be called from an ofproto implementation's
1881 * ->destruct() function. It is not suitable elsewhere. */
1883 ofproto_rule_destroy(struct rule *rule)
1885 assert(!rule->pending);
1886 oftable_remove_rule(rule);
1887 ofproto_rule_destroy__(rule);
1890 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
1891 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
1893 rule_has_out_port(const struct rule *rule, uint16_t port)
1895 return (port == OFPP_NONE
1896 || ofpacts_output_to_port(rule->ofpacts, rule->ofpacts_len, port));
1899 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
1900 * statistics appropriately. 'packet' must have at least sizeof(struct
1901 * ofp_packet_in) bytes of headroom.
1903 * 'packet' doesn't necessarily have to match 'rule'. 'rule' will be credited
1904 * with statistics for 'packet' either way.
1906 * Takes ownership of 'packet'. */
1908 rule_execute(struct rule *rule, uint16_t in_port, struct ofpbuf *packet)
1912 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
1914 flow_extract(packet, 0, 0, in_port, &flow);
1915 return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
1918 /* Returns true if 'rule' should be hidden from the controller.
1920 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
1921 * (e.g. by in-band control) and are intentionally hidden from the
1924 rule_is_hidden(const struct rule *rule)
1926 return rule->cr.priority > UINT16_MAX;
1929 static enum oftable_flags
1930 rule_get_flags(const struct rule *rule)
1932 return rule->ofproto->tables[rule->table_id].flags;
1936 rule_is_modifiable(const struct rule *rule)
1938 return !(rule_get_flags(rule) & OFTABLE_READONLY);
1942 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
1944 ofconn_send_reply(ofconn, make_echo_reply(oh));
1949 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
1951 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1952 struct ofputil_switch_features features;
1953 struct ofport *port;
1957 ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
1959 assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
1961 features.datapath_id = ofproto->datapath_id;
1962 features.n_buffers = pktbuf_capacity();
1963 features.n_tables = ofproto->n_tables;
1964 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
1965 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
1967 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
1970 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
1972 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
1973 ofputil_put_switch_features_port(&port->pp, b);
1976 ofconn_send_reply(ofconn, b);
1981 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
1983 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1984 struct ofp_switch_config *osc;
1985 enum ofp_config_flags flags;
1989 osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1990 flags = ofproto->frag_handling;
1991 if (ofconn_get_invalid_ttl_to_controller(ofconn)) {
1992 flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
1994 osc->flags = htons(flags);
1995 osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
1996 ofconn_send_reply(ofconn, buf);
2002 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
2004 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2005 uint16_t flags = ntohs(osc->flags);
2007 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2008 || ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
2009 enum ofp_config_flags cur = ofproto->frag_handling;
2010 enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2012 assert((cur & OFPC_FRAG_MASK) == cur);
2014 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2015 ofproto->frag_handling = next;
2017 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2019 ofputil_frag_handling_to_string(next));
2023 ofconn_set_invalid_ttl_to_controller(ofconn,
2024 (flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2026 ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2031 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
2032 * error message code for the caller to propagate upward. Otherwise, returns
2035 * The log message mentions 'msg_type'. */
2037 reject_slave_controller(struct ofconn *ofconn)
2039 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2040 && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
2041 return OFPERR_OFPBRC_EPERM;
2048 handle_packet_out(struct ofconn *ofconn, const struct ofp_packet_out *opo)
2050 struct ofproto *p = ofconn_get_ofproto(ofconn);
2051 struct ofputil_packet_out po;
2052 struct ofpbuf *payload;
2053 uint64_t ofpacts_stub[1024 / 8];
2054 struct ofpbuf ofpacts;
2058 COVERAGE_INC(ofproto_packet_out);
2060 error = reject_slave_controller(ofconn);
2065 /* Decode message. */
2066 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2067 error = ofputil_decode_packet_out(&po, opo, &ofpacts);
2069 goto exit_free_ofpacts;
2073 if (po.buffer_id != UINT32_MAX) {
2074 error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2075 if (error || !payload) {
2076 goto exit_free_ofpacts;
2079 payload = xmalloc(sizeof *payload);
2080 ofpbuf_use_const(payload, po.packet, po.packet_len);
2083 /* Send out packet. */
2084 flow_extract(payload, 0, 0, po.in_port, &flow);
2085 error = p->ofproto_class->packet_out(p, payload, &flow,
2086 po.ofpacts, po.ofpacts_len);
2087 ofpbuf_delete(payload);
2090 ofpbuf_uninit(&ofpacts);
2096 update_port_config(struct ofport *port,
2097 enum ofputil_port_config config,
2098 enum ofputil_port_config mask)
2100 enum ofputil_port_config old_config = port->pp.config;
2101 enum ofputil_port_config toggle;
2103 toggle = (config ^ port->pp.config) & mask;
2104 if (toggle & OFPUTIL_PC_PORT_DOWN) {
2105 if (config & OFPUTIL_PC_PORT_DOWN) {
2106 netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
2108 netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
2110 toggle &= ~OFPUTIL_PC_PORT_DOWN;
2113 port->pp.config ^= toggle;
2114 if (port->pp.config != old_config) {
2115 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
2120 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2122 struct ofproto *p = ofconn_get_ofproto(ofconn);
2123 struct ofputil_port_mod pm;
2124 struct ofport *port;
2127 error = reject_slave_controller(ofconn);
2132 error = ofputil_decode_port_mod(oh, &pm);
2137 port = ofproto_get_port(p, pm.port_no);
2139 return OFPERR_OFPPMFC_BAD_PORT;
2140 } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
2141 return OFPERR_OFPPMFC_BAD_HW_ADDR;
2143 update_port_config(port, pm.config, pm.mask);
2145 netdev_set_advertisements(port->netdev, pm.advertise);
2152 handle_desc_stats_request(struct ofconn *ofconn,
2153 const struct ofp_stats_msg *request)
2155 struct ofproto *p = ofconn_get_ofproto(ofconn);
2156 struct ofp_desc_stats *ods;
2159 ods = ofputil_make_stats_reply(sizeof *ods, request, &msg);
2160 ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
2161 ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
2162 ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
2163 ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
2164 ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
2165 ofconn_send_reply(ofconn, msg);
2171 handle_table_stats_request(struct ofconn *ofconn,
2172 const struct ofp_stats_msg *request)
2174 struct ofproto *p = ofconn_get_ofproto(ofconn);
2175 struct ofp_table_stats *ots;
2179 ofputil_make_stats_reply(sizeof(struct ofp_stats_msg), request, &msg);
2181 ots = ofpbuf_put_zeros(msg, sizeof *ots * p->n_tables);
2182 for (i = 0; i < p->n_tables; i++) {
2183 ots[i].table_id = i;
2184 sprintf(ots[i].name, "table%zu", i);
2185 ots[i].wildcards = htonl(OFPFW10_ALL);
2186 ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
2187 ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
2190 p->ofproto_class->get_tables(p, ots);
2192 for (i = 0; i < p->n_tables; i++) {
2193 const struct oftable *table = &p->tables[i];
2196 ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
2199 if (table->max_flows < ntohl(ots[i].max_entries)) {
2200 ots[i].max_entries = htonl(table->max_flows);
2204 ofconn_send_reply(ofconn, msg);
2209 append_port_stat(struct ofport *port, struct list *replies)
2211 struct netdev_stats stats;
2212 struct ofp_port_stats *ops;
2214 /* Intentionally ignore return value, since errors will set
2215 * 'stats' to all-1s, which is correct for OpenFlow, and
2216 * netdev_get_stats() will log errors. */
2217 ofproto_port_get_stats(port, &stats);
2219 ops = ofputil_append_stats_reply(sizeof *ops, replies);
2220 ops->port_no = htons(port->pp.port_no);
2221 memset(ops->pad, 0, sizeof ops->pad);
2222 put_32aligned_be64(&ops->rx_packets, htonll(stats.rx_packets));
2223 put_32aligned_be64(&ops->tx_packets, htonll(stats.tx_packets));
2224 put_32aligned_be64(&ops->rx_bytes, htonll(stats.rx_bytes));
2225 put_32aligned_be64(&ops->tx_bytes, htonll(stats.tx_bytes));
2226 put_32aligned_be64(&ops->rx_dropped, htonll(stats.rx_dropped));
2227 put_32aligned_be64(&ops->tx_dropped, htonll(stats.tx_dropped));
2228 put_32aligned_be64(&ops->rx_errors, htonll(stats.rx_errors));
2229 put_32aligned_be64(&ops->tx_errors, htonll(stats.tx_errors));
2230 put_32aligned_be64(&ops->rx_frame_err, htonll(stats.rx_frame_errors));
2231 put_32aligned_be64(&ops->rx_over_err, htonll(stats.rx_over_errors));
2232 put_32aligned_be64(&ops->rx_crc_err, htonll(stats.rx_crc_errors));
2233 put_32aligned_be64(&ops->collisions, htonll(stats.collisions));
2237 handle_port_stats_request(struct ofconn *ofconn,
2238 const struct ofp_port_stats_request *psr)
2240 struct ofproto *p = ofconn_get_ofproto(ofconn);
2241 struct ofport *port;
2242 struct list replies;
2244 ofputil_start_stats_reply(&psr->osm, &replies);
2245 if (psr->port_no != htons(OFPP_NONE)) {
2246 port = ofproto_get_port(p, ntohs(psr->port_no));
2248 append_port_stat(port, &replies);
2251 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2252 append_port_stat(port, &replies);
2256 ofconn_send_replies(ofconn, &replies);
2261 handle_port_desc_stats_request(struct ofconn *ofconn,
2262 const struct ofp_stats_msg *osm)
2264 struct ofproto *p = ofconn_get_ofproto(ofconn);
2265 struct ofport *port;
2266 struct list replies;
2268 ofputil_start_stats_reply(osm, &replies);
2270 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
2271 ofputil_append_port_desc_stats_reply(ofconn_get_protocol(ofconn),
2272 &port->pp, &replies);
2275 ofconn_send_replies(ofconn, &replies);
2280 calc_flow_duration__(long long int start, long long int now,
2281 uint32_t *sec, uint32_t *nsec)
2283 long long int msecs = now - start;
2284 *sec = msecs / 1000;
2285 *nsec = (msecs % 1000) * (1000 * 1000);
2288 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
2289 * 0 if 'table_id' is OK, otherwise an OpenFlow error code. */
2291 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
2293 return (table_id == 0xff || table_id < ofproto->n_tables
2295 : OFPERR_NXBRC_BAD_TABLE_ID);
2299 static struct oftable *
2300 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
2302 struct oftable *table;
2304 for (table = &ofproto->tables[table_id];
2305 table < &ofproto->tables[ofproto->n_tables];
2307 if (!(table->flags & OFTABLE_HIDDEN)) {
2315 static struct oftable *
2316 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
2318 if (table_id == 0xff) {
2319 return next_visible_table(ofproto, 0);
2320 } else if (table_id < ofproto->n_tables) {
2321 return &ofproto->tables[table_id];
2327 static struct oftable *
2328 next_matching_table(const struct ofproto *ofproto,
2329 const struct oftable *table, uint8_t table_id)
2331 return (table_id == 0xff
2332 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
2336 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
2338 * - If TABLE_ID is 0xff, this iterates over every classifier table in
2339 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
2341 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
2342 * only once, for that table. (This can be used to access tables marked
2345 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
2346 * entered at all. (Perhaps you should have validated TABLE_ID with
2347 * check_table_id().)
2349 * All parameters are evaluated multiple times.
2351 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
2352 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
2354 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
2356 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2357 * 'table_id' is 0xff) that match 'match' in the "loose" way required for
2358 * OpenFlow OFPFC_MODIFY and OFPFC_DELETE requests and puts them on list
2361 * If 'out_port' is anything other than OFPP_NONE, then only rules that output
2362 * to 'out_port' are included.
2364 * Hidden rules are always omitted.
2366 * Returns 0 on success, otherwise an OpenFlow error code. */
2368 collect_rules_loose(struct ofproto *ofproto, uint8_t table_id,
2369 const struct cls_rule *match,
2370 ovs_be64 cookie, ovs_be64 cookie_mask,
2371 uint16_t out_port, struct list *rules)
2373 struct oftable *table;
2376 error = check_table_id(ofproto, table_id);
2382 FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2383 struct cls_cursor cursor;
2386 cls_cursor_init(&cursor, &table->cls, match);
2387 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2388 if (rule->pending) {
2389 return OFPROTO_POSTPONE;
2391 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)
2392 && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2393 list_push_back(rules, &rule->ofproto_node);
2400 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
2401 * 'table_id' is 0xff) that match 'match' in the "strict" way required for
2402 * OpenFlow OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests and puts them
2405 * If 'out_port' is anything other than OFPP_NONE, then only rules that output
2406 * to 'out_port' are included.
2408 * Hidden rules are always omitted.
2410 * Returns 0 on success, otherwise an OpenFlow error code. */
2412 collect_rules_strict(struct ofproto *ofproto, uint8_t table_id,
2413 const struct cls_rule *match,
2414 ovs_be64 cookie, ovs_be64 cookie_mask,
2415 uint16_t out_port, struct list *rules)
2417 struct oftable *table;
2420 error = check_table_id(ofproto, table_id);
2426 FOR_EACH_MATCHING_TABLE (table, table_id, ofproto) {
2429 rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
2432 if (rule->pending) {
2433 return OFPROTO_POSTPONE;
2435 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)
2436 && !((rule->flow_cookie ^ cookie) & cookie_mask)) {
2437 list_push_back(rules, &rule->ofproto_node);
2444 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
2445 * forced into the range of a uint16_t. */
2447 age_secs(long long int age_ms)
2449 return (age_ms < 0 ? 0
2450 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
2451 : (unsigned int) age_ms / 1000);
2455 handle_flow_stats_request(struct ofconn *ofconn,
2456 const struct ofp_stats_msg *osm)
2458 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2459 struct ofputil_flow_stats_request fsr;
2460 struct list replies;
2465 error = ofputil_decode_flow_stats_request(&fsr, &osm->header);
2470 error = collect_rules_loose(ofproto, fsr.table_id, &fsr.match,
2471 fsr.cookie, fsr.cookie_mask,
2472 fsr.out_port, &rules);
2477 ofputil_start_stats_reply(osm, &replies);
2478 LIST_FOR_EACH (rule, ofproto_node, &rules) {
2479 long long int now = time_msec();
2480 struct ofputil_flow_stats fs;
2483 fs.cookie = rule->flow_cookie;
2484 fs.table_id = rule->table_id;
2485 calc_flow_duration__(rule->created, now, &fs.duration_sec,
2487 fs.idle_timeout = rule->idle_timeout;
2488 fs.hard_timeout = rule->hard_timeout;
2489 fs.idle_age = age_secs(now - rule->used);
2490 fs.hard_age = age_secs(now - rule->modified);
2491 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
2493 fs.ofpacts = rule->ofpacts;
2494 fs.ofpacts_len = rule->ofpacts_len;
2495 ofputil_append_flow_stats_reply(&fs, &replies);
2497 ofconn_send_replies(ofconn, &replies);
2503 flow_stats_ds(struct rule *rule, struct ds *results)
2505 uint64_t packet_count, byte_count;
2507 rule->ofproto->ofproto_class->rule_get_stats(rule,
2508 &packet_count, &byte_count);
2510 if (rule->table_id != 0) {
2511 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
2513 ds_put_format(results, "duration=%llds, ",
2514 (time_msec() - rule->created) / 1000);
2515 ds_put_format(results, "priority=%u, ", rule->cr.priority);
2516 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
2517 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
2518 cls_rule_format(&rule->cr, results);
2519 ds_put_char(results, ',');
2520 if (rule->ofpacts_len > 0) {
2521 ofpacts_format(rule->ofpacts, rule->ofpacts_len, results);
2523 ds_put_cstr(results, "drop");
2525 ds_put_cstr(results, "\n");
2528 /* Adds a pretty-printed description of all flows to 'results', including
2529 * hidden flows (e.g., set up by in-band control). */
2531 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
2533 struct oftable *table;
2535 OFPROTO_FOR_EACH_TABLE (table, p) {
2536 struct cls_cursor cursor;
2539 cls_cursor_init(&cursor, &table->cls, NULL);
2540 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2541 flow_stats_ds(rule, results);
2546 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
2547 * '*engine_type' and '*engine_id', respectively. */
2549 ofproto_get_netflow_ids(const struct ofproto *ofproto,
2550 uint8_t *engine_type, uint8_t *engine_id)
2552 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
2555 /* Checks the fault status of CFM for 'ofp_port' within 'ofproto'. Returns a
2556 * bitmask of 'cfm_fault_reason's to indicate a CFM fault (generally
2557 * indicating a connectivity problem). Returns zero if CFM is not faulted,
2558 * and -1 if CFM is not enabled on 'port'. */
2560 ofproto_port_get_cfm_fault(const struct ofproto *ofproto, uint16_t ofp_port)
2562 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2563 return (ofport && ofproto->ofproto_class->get_cfm_fault
2564 ? ofproto->ofproto_class->get_cfm_fault(ofport)
2568 /* Gets the MPIDs of the remote maintenance points broadcasting to 'ofp_port'
2569 * within 'ofproto'. Populates 'rmps' with an array of MPIDs owned by
2570 * 'ofproto', and 'n_rmps' with the number of MPIDs in 'rmps'. Returns a
2571 * number less than 0 if CFM is not enabled on 'ofp_port'. */
2573 ofproto_port_get_cfm_remote_mpids(const struct ofproto *ofproto,
2574 uint16_t ofp_port, const uint64_t **rmps,
2577 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2581 return (ofport && ofproto->ofproto_class->get_cfm_remote_mpids
2582 ? ofproto->ofproto_class->get_cfm_remote_mpids(ofport, rmps,
2587 /* Checks the health of the CFM for 'ofp_port' within 'ofproto'. Returns an
2588 * integer value between 0 and 100 to indicate the health of the port as a
2589 * percentage which is the average of cfm health of all the remote_mpids or
2590 * returns -1 if CFM is not enabled on 'ofport'. */
2592 ofproto_port_get_cfm_health(const struct ofproto *ofproto, uint16_t ofp_port)
2594 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2595 return (ofport && ofproto->ofproto_class->get_cfm_health
2596 ? ofproto->ofproto_class->get_cfm_health(ofport)
2601 handle_aggregate_stats_request(struct ofconn *ofconn,
2602 const struct ofp_stats_msg *osm)
2604 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2605 struct ofputil_flow_stats_request request;
2606 struct ofputil_aggregate_stats stats;
2607 bool unknown_packets, unknown_bytes;
2608 struct ofpbuf *reply;
2613 error = ofputil_decode_flow_stats_request(&request, &osm->header);
2618 error = collect_rules_loose(ofproto, request.table_id, &request.match,
2619 request.cookie, request.cookie_mask,
2620 request.out_port, &rules);
2625 memset(&stats, 0, sizeof stats);
2626 unknown_packets = unknown_bytes = false;
2627 LIST_FOR_EACH (rule, ofproto_node, &rules) {
2628 uint64_t packet_count;
2629 uint64_t byte_count;
2631 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
2634 if (packet_count == UINT64_MAX) {
2635 unknown_packets = true;
2637 stats.packet_count += packet_count;
2640 if (byte_count == UINT64_MAX) {
2641 unknown_bytes = true;
2643 stats.byte_count += byte_count;
2648 if (unknown_packets) {
2649 stats.packet_count = UINT64_MAX;
2651 if (unknown_bytes) {
2652 stats.byte_count = UINT64_MAX;
2655 reply = ofputil_encode_aggregate_stats_reply(&stats, osm);
2656 ofconn_send_reply(ofconn, reply);
2661 struct queue_stats_cbdata {
2662 struct ofport *ofport;
2663 struct list replies;
2667 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
2668 const struct netdev_queue_stats *stats)
2670 struct ofp_queue_stats *reply;
2672 reply = ofputil_append_stats_reply(sizeof *reply, &cbdata->replies);
2673 reply->port_no = htons(cbdata->ofport->pp.port_no);
2674 memset(reply->pad, 0, sizeof reply->pad);
2675 reply->queue_id = htonl(queue_id);
2676 put_32aligned_be64(&reply->tx_bytes, htonll(stats->tx_bytes));
2677 put_32aligned_be64(&reply->tx_packets, htonll(stats->tx_packets));
2678 put_32aligned_be64(&reply->tx_errors, htonll(stats->tx_errors));
2682 handle_queue_stats_dump_cb(uint32_t queue_id,
2683 struct netdev_queue_stats *stats,
2686 struct queue_stats_cbdata *cbdata = cbdata_;
2688 put_queue_stats(cbdata, queue_id, stats);
2692 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
2693 struct queue_stats_cbdata *cbdata)
2695 cbdata->ofport = port;
2696 if (queue_id == OFPQ_ALL) {
2697 netdev_dump_queue_stats(port->netdev,
2698 handle_queue_stats_dump_cb, cbdata);
2700 struct netdev_queue_stats stats;
2702 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
2703 put_queue_stats(cbdata, queue_id, &stats);
2705 return OFPERR_OFPQOFC_BAD_QUEUE;
2712 handle_queue_stats_request(struct ofconn *ofconn,
2713 const struct ofp_queue_stats_request *qsr)
2715 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2716 struct queue_stats_cbdata cbdata;
2717 unsigned int port_no;
2718 struct ofport *port;
2722 COVERAGE_INC(ofproto_queue_req);
2724 ofputil_start_stats_reply(&qsr->osm, &cbdata.replies);
2726 port_no = ntohs(qsr->port_no);
2727 queue_id = ntohl(qsr->queue_id);
2728 if (port_no == OFPP_ALL) {
2729 error = OFPERR_OFPQOFC_BAD_QUEUE;
2730 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2731 if (!handle_queue_stats_for_port(port, queue_id, &cbdata)) {
2736 port = ofproto_get_port(ofproto, port_no);
2738 ? handle_queue_stats_for_port(port, queue_id, &cbdata)
2739 : OFPERR_OFPQOFC_BAD_PORT);
2742 ofconn_send_replies(ofconn, &cbdata.replies);
2744 ofpbuf_list_delete(&cbdata.replies);
2751 is_flow_deletion_pending(const struct ofproto *ofproto,
2752 const struct cls_rule *cls_rule,
2755 if (!hmap_is_empty(&ofproto->deletions)) {
2756 struct ofoperation *op;
2758 HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
2759 cls_rule_hash(cls_rule, table_id),
2760 &ofproto->deletions) {
2761 if (cls_rule_equal(cls_rule, &op->rule->cr)) {
2770 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
2771 * in which no matching flow already exists in the flow table.
2773 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
2774 * ofp_actions, to the ofproto's flow table. Returns 0 on success, an OpenFlow
2775 * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
2776 * initiated now but may be retried later.
2778 * Upon successful return, takes ownership of 'fm->ofpacts'. On failure,
2779 * ownership remains with the caller.
2781 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2784 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
2785 const struct ofputil_flow_mod *fm, const struct ofp_header *request)
2787 struct oftable *table;
2788 struct ofopgroup *group;
2789 struct rule *victim;
2793 error = check_table_id(ofproto, fm->table_id);
2799 if (fm->table_id == 0xff) {
2801 if (ofproto->ofproto_class->rule_choose_table) {
2802 error = ofproto->ofproto_class->rule_choose_table(ofproto, &fm->cr,
2807 assert(table_id < ofproto->n_tables);
2808 table = &ofproto->tables[table_id];
2810 table = &ofproto->tables[0];
2812 } else if (fm->table_id < ofproto->n_tables) {
2813 table = &ofproto->tables[fm->table_id];
2815 return OFPERR_NXFMFC_BAD_TABLE_ID;
2818 if (table->flags & OFTABLE_READONLY) {
2819 return OFPERR_OFPBRC_EPERM;
2822 /* Check for overlap, if requested. */
2823 if (fm->flags & OFPFF_CHECK_OVERLAP
2824 && classifier_rule_overlaps(&table->cls, &fm->cr)) {
2825 return OFPERR_OFPFMFC_OVERLAP;
2828 /* Serialize against pending deletion. */
2829 if (is_flow_deletion_pending(ofproto, &fm->cr, table - ofproto->tables)) {
2830 return OFPROTO_POSTPONE;
2833 /* Allocate new rule. */
2834 rule = ofproto->ofproto_class->rule_alloc();
2836 VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
2837 ofproto->name, strerror(error));
2840 rule->ofproto = ofproto;
2842 rule->pending = NULL;
2843 rule->flow_cookie = fm->new_cookie;
2844 rule->created = rule->modified = rule->used = time_msec();
2845 rule->idle_timeout = fm->idle_timeout;
2846 rule->hard_timeout = fm->hard_timeout;
2847 rule->table_id = table - ofproto->tables;
2848 rule->send_flow_removed = (fm->flags & OFPFF_SEND_FLOW_REM) != 0;
2849 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
2850 rule->ofpacts_len = fm->ofpacts_len;
2851 rule->evictable = true;
2852 rule->eviction_group = NULL;
2854 /* Insert new rule. */
2855 victim = oftable_replace_rule(rule);
2856 if (victim && !rule_is_modifiable(victim)) {
2857 error = OFPERR_OFPBRC_EPERM;
2858 } else if (victim && victim->pending) {
2859 error = OFPROTO_POSTPONE;
2861 struct ofoperation *op;
2864 if (classifier_count(&table->cls) > table->max_flows) {
2867 was_evictable = rule->evictable;
2868 rule->evictable = false;
2869 evict = choose_rule_to_evict(table);
2870 rule->evictable = was_evictable;
2873 error = OFPERR_OFPFMFC_ALL_TABLES_FULL;
2875 } else if (evict->pending) {
2876 error = OFPROTO_POSTPONE;
2883 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
2884 op = ofoperation_create(group, rule, OFOPERATION_ADD);
2885 op->victim = victim;
2887 error = ofproto->ofproto_class->rule_construct(rule);
2889 op->group->n_running--;
2890 ofoperation_destroy(rule->pending);
2892 delete_flow__(evict, group);
2894 ofopgroup_submit(group);
2898 /* Back out if an error occurred. */
2900 oftable_substitute_rule(rule, victim);
2901 ofproto_rule_destroy__(rule);
2906 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
2908 /* Modifies the rules listed in 'rules', changing their actions to match those
2911 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2914 * Returns 0 on success, otherwise an OpenFlow error code. */
2916 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
2917 const struct ofputil_flow_mod *fm,
2918 const struct ofp_header *request, struct list *rules)
2920 struct ofopgroup *group;
2924 group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
2925 error = OFPERR_OFPBRC_EPERM;
2926 LIST_FOR_EACH (rule, ofproto_node, rules) {
2927 if (rule_is_modifiable(rule)) {
2928 /* At least one rule is modifiable, don't report EPERM error. */
2934 if (!ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
2935 rule->ofpacts, rule->ofpacts_len)) {
2936 struct ofoperation *op;
2938 op = ofoperation_create(group, rule, OFOPERATION_MODIFY);
2939 op->ofpacts = rule->ofpacts;
2940 op->ofpacts_len = rule->ofpacts_len;
2941 rule->ofpacts = xmemdup(fm->ofpacts, fm->ofpacts_len);
2942 rule->ofpacts_len = fm->ofpacts_len;
2943 rule->ofproto->ofproto_class->rule_modify_actions(rule);
2945 rule->modified = time_msec();
2947 if (fm->new_cookie != htonll(UINT64_MAX)) {
2948 rule->flow_cookie = fm->new_cookie;
2951 ofopgroup_submit(group);
2956 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
2959 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2962 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
2963 const struct ofputil_flow_mod *fm,
2964 const struct ofp_header *request)
2969 error = collect_rules_loose(ofproto, fm->table_id, &fm->cr,
2970 fm->cookie, fm->cookie_mask,
2974 } else if (list_is_empty(&rules)) {
2975 return fm->cookie_mask ? 0 : add_flow(ofproto, ofconn, fm, request);
2977 return modify_flows__(ofproto, ofconn, fm, request, &rules);
2981 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
2984 * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2987 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
2988 const struct ofputil_flow_mod *fm,
2989 const struct ofp_header *request)
2994 error = collect_rules_strict(ofproto, fm->table_id, &fm->cr,
2995 fm->cookie, fm->cookie_mask,
3000 } else if (list_is_empty(&rules)) {
3001 return fm->cookie_mask ? 0 : add_flow(ofproto, ofconn, fm, request);
3003 return list_is_singleton(&rules) ? modify_flows__(ofproto, ofconn,
3004 fm, request, &rules)
3009 /* OFPFC_DELETE implementation. */
3012 delete_flow__(struct rule *rule, struct ofopgroup *group)
3014 struct ofproto *ofproto = rule->ofproto;
3016 ofproto_rule_send_removed(rule, OFPRR_DELETE);
3018 ofoperation_create(group, rule, OFOPERATION_DELETE);
3019 oftable_remove_rule(rule);
3020 ofproto->ofproto_class->rule_destruct(rule);
3023 /* Deletes the rules listed in 'rules'.
3025 * Returns 0 on success, otherwise an OpenFlow error code. */
3027 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
3028 const struct ofp_header *request, struct list *rules)
3030 struct rule *rule, *next;
3031 struct ofopgroup *group;
3033 group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
3034 LIST_FOR_EACH_SAFE (rule, next, ofproto_node, rules) {
3035 delete_flow__(rule, group);
3037 ofopgroup_submit(group);
3042 /* Implements OFPFC_DELETE. */
3044 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
3045 const struct ofputil_flow_mod *fm,
3046 const struct ofp_header *request)
3051 error = collect_rules_loose(ofproto, fm->table_id, &fm->cr,
3052 fm->cookie, fm->cookie_mask,
3053 fm->out_port, &rules);
3054 return (error ? error
3055 : !list_is_empty(&rules) ? delete_flows__(ofproto, ofconn, request,
3060 /* Implements OFPFC_DELETE_STRICT. */
3062 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
3063 const struct ofputil_flow_mod *fm,
3064 const struct ofp_header *request)
3069 error = collect_rules_strict(ofproto, fm->table_id, &fm->cr,
3070 fm->cookie, fm->cookie_mask,
3071 fm->out_port, &rules);
3072 return (error ? error
3073 : list_is_singleton(&rules) ? delete_flows__(ofproto, ofconn,
3079 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
3081 struct ofputil_flow_removed fr;
3083 if (rule_is_hidden(rule) || !rule->send_flow_removed) {
3088 fr.cookie = rule->flow_cookie;
3090 calc_flow_duration__(rule->created, time_msec(),
3091 &fr.duration_sec, &fr.duration_nsec);
3092 fr.idle_timeout = rule->idle_timeout;
3093 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
3096 connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
3100 ofproto_rule_update_used(struct rule *rule, long long int used)
3102 if (used > rule->used) {
3103 struct eviction_group *evg = rule->eviction_group;
3107 heap_change(&evg->rules, &rule->evg_node,
3108 rule_eviction_priority(rule));
3113 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
3114 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
3117 * ofproto implementation ->run() functions should use this function to expire
3118 * OpenFlow flows. */
3120 ofproto_rule_expire(struct rule *rule, uint8_t reason)
3122 struct ofproto *ofproto = rule->ofproto;
3123 struct ofopgroup *group;
3125 assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
3127 ofproto_rule_send_removed(rule, reason);
3129 group = ofopgroup_create_unattached(ofproto);
3130 ofoperation_create(group, rule, OFOPERATION_DELETE);
3131 oftable_remove_rule(rule);
3132 ofproto->ofproto_class->rule_destruct(rule);
3133 ofopgroup_submit(group);
3137 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3139 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3140 struct ofputil_flow_mod fm;
3141 uint64_t ofpacts_stub[1024 / 8];
3142 struct ofpbuf ofpacts;
3146 error = reject_slave_controller(ofconn);
3151 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3152 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
3155 goto exit_free_ofpacts;
3158 /* We do not support the OpenFlow 1.0 emergency flow cache, which is not
3159 * required in OpenFlow 1.0.1 and removed from OpenFlow 1.1. */
3160 if (fm.flags & OFPFF_EMERG) {
3161 /* We do not support the emergency flow cache. It will hopefully get
3162 * dropped from OpenFlow in the near future. There is no good error
3163 * code, so just state that the flow table is full. */
3164 error = OFPERR_OFPFMFC_ALL_TABLES_FULL;
3166 error = handle_flow_mod__(ofconn_get_ofproto(ofconn), ofconn, &fm, oh);
3169 goto exit_free_ofpacts;
3172 /* Record the operation for logging a summary report. */
3173 switch (fm.command) {
3179 case OFPFC_MODIFY_STRICT:
3180 ofproto->n_modify++;
3184 case OFPFC_DELETE_STRICT:
3185 ofproto->n_delete++;
3190 if (ofproto->next_op_report == LLONG_MAX) {
3191 ofproto->first_op = now;
3192 ofproto->next_op_report = MAX(now + 10 * 1000,
3193 ofproto->op_backoff);
3194 ofproto->op_backoff = ofproto->next_op_report + 60 * 1000;
3196 ofproto->last_op = now;
3199 ofpbuf_uninit(&ofpacts);
3205 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
3206 const struct ofputil_flow_mod *fm,
3207 const struct ofp_header *oh)
3209 if (ofproto->n_pending >= 50) {
3210 assert(!list_is_empty(&ofproto->pending));
3211 return OFPROTO_POSTPONE;
3214 switch (fm->command) {
3216 return add_flow(ofproto, ofconn, fm, oh);
3219 return modify_flows_loose(ofproto, ofconn, fm, oh);
3221 case OFPFC_MODIFY_STRICT:
3222 return modify_flow_strict(ofproto, ofconn, fm, oh);
3225 return delete_flows_loose(ofproto, ofconn, fm, oh);
3227 case OFPFC_DELETE_STRICT:
3228 return delete_flow_strict(ofproto, ofconn, fm, oh);
3231 if (fm->command > 0xff) {
3232 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
3233 "flow_mod_table_id extension is not enabled",
3236 return OFPERR_OFPFMFC_BAD_COMMAND;
3241 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
3243 struct nx_role_request *nrr = (struct nx_role_request *) oh;
3244 struct nx_role_request *reply;
3248 role = ntohl(nrr->role);
3249 if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
3250 && role != NX_ROLE_SLAVE) {
3251 return OFPERR_OFPRRFC_BAD_ROLE;
3254 if (ofconn_get_role(ofconn) != role
3255 && ofconn_has_pending_opgroups(ofconn)) {
3256 return OFPROTO_POSTPONE;
3259 ofconn_set_role(ofconn, role);
3261 reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
3262 reply->role = htonl(role);
3263 ofconn_send_reply(ofconn, buf);
3269 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
3270 const struct ofp_header *oh)
3272 const struct nx_flow_mod_table_id *msg
3273 = (const struct nx_flow_mod_table_id *) oh;
3274 enum ofputil_protocol cur, next;
3276 cur = ofconn_get_protocol(ofconn);
3277 next = ofputil_protocol_set_tid(cur, msg->set != 0);
3278 ofconn_set_protocol(ofconn, next);
3284 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
3286 const struct nx_set_flow_format *msg
3287 = (const struct nx_set_flow_format *) oh;
3288 enum ofputil_protocol cur, next;
3289 enum ofputil_protocol next_base;
3291 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
3293 return OFPERR_OFPBRC_EPERM;
3296 cur = ofconn_get_protocol(ofconn);
3297 next = ofputil_protocol_set_base(cur, next_base);
3298 if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
3299 /* Avoid sending async messages in surprising protocol. */
3300 return OFPROTO_POSTPONE;
3303 ofconn_set_protocol(ofconn, next);
3308 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
3309 const struct ofp_header *oh)
3311 const struct nx_set_packet_in_format *msg;
3314 msg = (const struct nx_set_packet_in_format *) oh;
3315 format = ntohl(msg->format);
3316 if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
3317 return OFPERR_OFPBRC_EPERM;
3320 if (format != ofconn_get_packet_in_format(ofconn)
3321 && ofconn_has_pending_opgroups(ofconn)) {
3322 /* Avoid sending async message in surprsing packet in format. */
3323 return OFPROTO_POSTPONE;
3326 ofconn_set_packet_in_format(ofconn, format);
3331 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
3333 const struct nx_async_config *msg = (const struct nx_async_config *) oh;
3334 uint32_t master[OAM_N_TYPES];
3335 uint32_t slave[OAM_N_TYPES];
3337 master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
3338 master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
3339 master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
3341 slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
3342 slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
3343 slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
3345 ofconn_set_async_config(ofconn, master, slave);
3346 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
3347 !ofconn_get_miss_send_len(ofconn)) {
3348 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
3355 handle_nxt_set_controller_id(struct ofconn *ofconn,
3356 const struct ofp_header *oh)
3358 const struct nx_controller_id *nci;
3360 nci = (const struct nx_controller_id *) oh;
3361 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
3362 return OFPERR_NXBRC_MUST_BE_ZERO;
3365 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
3370 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
3374 if (ofconn_has_pending_opgroups(ofconn)) {
3375 return OFPROTO_POSTPONE;
3378 make_openflow_xid(sizeof *oh, OFPT10_BARRIER_REPLY, oh->xid, &buf);
3379 ofconn_send_reply(ofconn, buf);
3384 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
3386 const struct ofp_header *oh = msg->data;
3387 const struct ofputil_msg_type *type;
3390 error = ofputil_decode_msg_type(oh, &type);
3395 switch (ofputil_msg_type_code(type)) {
3396 /* OpenFlow requests. */
3397 case OFPUTIL_OFPT_ECHO_REQUEST:
3398 return handle_echo_request(ofconn, oh);
3400 case OFPUTIL_OFPT_FEATURES_REQUEST:
3401 return handle_features_request(ofconn, oh);
3403 case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
3404 return handle_get_config_request(ofconn, oh);
3406 case OFPUTIL_OFPT_SET_CONFIG:
3407 return handle_set_config(ofconn, msg->data);
3409 case OFPUTIL_OFPT_PACKET_OUT:
3410 return handle_packet_out(ofconn, msg->data);
3412 case OFPUTIL_OFPT_PORT_MOD:
3413 return handle_port_mod(ofconn, oh);
3415 case OFPUTIL_OFPT_FLOW_MOD:
3416 return handle_flow_mod(ofconn, oh);
3418 case OFPUTIL_OFPT_BARRIER_REQUEST:
3419 return handle_barrier_request(ofconn, oh);
3421 /* OpenFlow replies. */
3422 case OFPUTIL_OFPT_ECHO_REPLY:
3425 /* Nicira extension requests. */
3426 case OFPUTIL_NXT_ROLE_REQUEST:
3427 return handle_role_request(ofconn, oh);
3429 case OFPUTIL_NXT_FLOW_MOD_TABLE_ID:
3430 return handle_nxt_flow_mod_table_id(ofconn, oh);
3432 case OFPUTIL_NXT_SET_FLOW_FORMAT:
3433 return handle_nxt_set_flow_format(ofconn, oh);
3435 case OFPUTIL_NXT_SET_PACKET_IN_FORMAT:
3436 return handle_nxt_set_packet_in_format(ofconn, oh);
3438 case OFPUTIL_NXT_SET_CONTROLLER_ID:
3439 return handle_nxt_set_controller_id(ofconn, oh);
3441 case OFPUTIL_NXT_FLOW_MOD:
3442 return handle_flow_mod(ofconn, oh);
3444 case OFPUTIL_NXT_FLOW_AGE:
3445 /* Nothing to do. */
3448 case OFPUTIL_NXT_SET_ASYNC_CONFIG:
3449 return handle_nxt_set_async_config(ofconn, oh);
3451 /* Statistics requests. */
3452 case OFPUTIL_OFPST_DESC_REQUEST:
3453 return handle_desc_stats_request(ofconn, msg->data);
3455 case OFPUTIL_OFPST_FLOW_REQUEST:
3456 case OFPUTIL_NXST_FLOW_REQUEST:
3457 return handle_flow_stats_request(ofconn, msg->data);
3459 case OFPUTIL_OFPST_AGGREGATE_REQUEST:
3460 case OFPUTIL_NXST_AGGREGATE_REQUEST:
3461 return handle_aggregate_stats_request(ofconn, msg->data);
3463 case OFPUTIL_OFPST_TABLE_REQUEST:
3464 return handle_table_stats_request(ofconn, msg->data);
3466 case OFPUTIL_OFPST_PORT_REQUEST:
3467 return handle_port_stats_request(ofconn, msg->data);
3469 case OFPUTIL_OFPST_QUEUE_REQUEST:
3470 return handle_queue_stats_request(ofconn, msg->data);
3472 case OFPUTIL_OFPST_PORT_DESC_REQUEST:
3473 return handle_port_desc_stats_request(ofconn, msg->data);
3475 case OFPUTIL_MSG_INVALID:
3476 case OFPUTIL_OFPT_HELLO:
3477 case OFPUTIL_OFPT_ERROR:
3478 case OFPUTIL_OFPT_FEATURES_REPLY:
3479 case OFPUTIL_OFPT_GET_CONFIG_REPLY:
3480 case OFPUTIL_OFPT_PACKET_IN:
3481 case OFPUTIL_OFPT_FLOW_REMOVED:
3482 case OFPUTIL_OFPT_PORT_STATUS:
3483 case OFPUTIL_OFPT_BARRIER_REPLY:
3484 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
3485 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
3486 case OFPUTIL_OFPST_DESC_REPLY:
3487 case OFPUTIL_OFPST_FLOW_REPLY:
3488 case OFPUTIL_OFPST_QUEUE_REPLY:
3489 case OFPUTIL_OFPST_PORT_REPLY:
3490 case OFPUTIL_OFPST_TABLE_REPLY:
3491 case OFPUTIL_OFPST_AGGREGATE_REPLY:
3492 case OFPUTIL_OFPST_PORT_DESC_REPLY:
3493 case OFPUTIL_NXT_ROLE_REPLY:
3494 case OFPUTIL_NXT_FLOW_REMOVED:
3495 case OFPUTIL_NXT_PACKET_IN:
3496 case OFPUTIL_NXST_FLOW_REPLY:
3497 case OFPUTIL_NXST_AGGREGATE_REPLY:
3499 return (oh->type == OFPT10_STATS_REQUEST ||
3500 oh->type == OFPT10_STATS_REPLY
3501 ? OFPERR_OFPBRC_BAD_STAT
3502 : OFPERR_OFPBRC_BAD_TYPE);
3507 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
3509 int error = handle_openflow__(ofconn, ofp_msg);
3510 if (error && error != OFPROTO_POSTPONE) {
3511 ofconn_send_error(ofconn, ofp_msg->data, error);
3513 COVERAGE_INC(ofproto_recv_openflow);
3514 return error != OFPROTO_POSTPONE;
3517 /* Asynchronous operations. */
3519 /* Creates and returns a new ofopgroup that is not associated with any
3520 * OpenFlow connection.
3522 * The caller should add operations to the returned group with
3523 * ofoperation_create() and then submit it with ofopgroup_submit(). */
3524 static struct ofopgroup *
3525 ofopgroup_create_unattached(struct ofproto *ofproto)
3527 struct ofopgroup *group = xzalloc(sizeof *group);
3528 group->ofproto = ofproto;
3529 list_init(&group->ofproto_node);
3530 list_init(&group->ops);
3531 list_init(&group->ofconn_node);
3535 /* Creates and returns a new ofopgroup for 'ofproto'.
3537 * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
3538 * connection. The 'request' and 'buffer_id' arguments are ignored.
3540 * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
3541 * If the ofopgroup eventually fails, then the error reply will include
3542 * 'request'. If the ofopgroup eventually succeeds, then the packet with
3543 * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
3545 * The caller should add operations to the returned group with
3546 * ofoperation_create() and then submit it with ofopgroup_submit(). */
3547 static struct ofopgroup *
3548 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
3549 const struct ofp_header *request, uint32_t buffer_id)
3551 struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
3553 size_t request_len = ntohs(request->length);
3555 assert(ofconn_get_ofproto(ofconn) == ofproto);
3557 ofconn_add_opgroup(ofconn, &group->ofconn_node);
3558 group->ofconn = ofconn;
3559 group->request = xmemdup(request, MIN(request_len, 64));
3560 group->buffer_id = buffer_id;
3565 /* Submits 'group' for processing.
3567 * If 'group' contains no operations (e.g. none were ever added, or all of the
3568 * ones that were added completed synchronously), then it is destroyed
3569 * immediately. Otherwise it is added to the ofproto's list of pending
3572 ofopgroup_submit(struct ofopgroup *group)
3574 if (!group->n_running) {
3575 ofopgroup_complete(group);
3577 list_push_back(&group->ofproto->pending, &group->ofproto_node);
3578 group->ofproto->n_pending++;
3583 ofopgroup_complete(struct ofopgroup *group)
3585 struct ofproto *ofproto = group->ofproto;
3586 struct ofoperation *op, *next_op;
3589 assert(!group->n_running);
3592 LIST_FOR_EACH (op, group_node, &group->ops) {
3599 if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
3600 LIST_FOR_EACH (op, group_node, &group->ops) {
3601 if (op->type != OFOPERATION_DELETE) {
3602 struct ofpbuf *packet;
3605 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
3609 error = rule_execute(op->rule, in_port, packet);
3616 LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
3617 struct rule *rule = op->rule;
3618 rule->pending = NULL;
3621 case OFOPERATION_ADD:
3623 ofproto_rule_destroy__(op->victim);
3624 if ((rule->cr.wc.vlan_tci_mask & htons(VLAN_VID_MASK))
3625 == htons(VLAN_VID_MASK)) {
3626 if (ofproto->vlan_bitmap) {
3627 uint16_t vid = vlan_tci_to_vid(rule->cr.flow.vlan_tci);
3629 if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
3630 bitmap_set1(ofproto->vlan_bitmap, vid);
3631 ofproto->vlans_changed = true;
3634 ofproto->vlans_changed = true;
3638 oftable_substitute_rule(rule, op->victim);
3639 ofproto_rule_destroy__(rule);
3643 case OFOPERATION_DELETE:
3645 ofproto_rule_destroy__(rule);
3649 case OFOPERATION_MODIFY:
3651 rule->modified = time_msec();
3653 free(rule->ofpacts);
3654 rule->ofpacts = op->ofpacts;
3655 rule->ofpacts_len = op->ofpacts_len;
3657 op->ofpacts_len = 0;
3665 ofoperation_destroy(op);
3668 if (!list_is_empty(&group->ofproto_node)) {
3669 assert(ofproto->n_pending > 0);
3670 ofproto->n_pending--;
3671 list_remove(&group->ofproto_node);
3673 if (!list_is_empty(&group->ofconn_node)) {
3674 list_remove(&group->ofconn_node);
3676 ofconn_send_error(group->ofconn, group->request, error);
3678 connmgr_retry(ofproto->connmgr);
3680 free(group->request);
3684 /* Initiates a new operation on 'rule', of the specified 'type', within
3685 * 'group'. Prior to calling, 'rule' must not have any pending operation.
3687 * Returns the newly created ofoperation (which is also available as
3688 * rule->pending). */
3689 static struct ofoperation *
3690 ofoperation_create(struct ofopgroup *group, struct rule *rule,
3691 enum ofoperation_type type)
3693 struct ofproto *ofproto = group->ofproto;
3694 struct ofoperation *op;
3696 assert(!rule->pending);
3698 op = rule->pending = xzalloc(sizeof *op);
3700 list_push_back(&group->ops, &op->group_node);
3703 op->flow_cookie = rule->flow_cookie;
3707 if (type == OFOPERATION_DELETE) {
3708 hmap_insert(&ofproto->deletions, &op->hmap_node,
3709 cls_rule_hash(&rule->cr, rule->table_id));
3716 ofoperation_destroy(struct ofoperation *op)
3718 struct ofopgroup *group = op->group;
3721 op->rule->pending = NULL;
3723 if (op->type == OFOPERATION_DELETE) {
3724 hmap_remove(&group->ofproto->deletions, &op->hmap_node);
3726 list_remove(&op->group_node);
3731 /* Indicates that 'op' completed with status 'error', which is either 0 to
3732 * indicate success or an OpenFlow error code on failure.
3734 * If 'error' is 0, indicating success, the operation will be committed
3735 * permanently to the flow table. There is one interesting subcase:
3737 * - If 'op' is an "add flow" operation that is replacing an existing rule in
3738 * the flow table (the "victim" rule) by a new one, then the caller must
3739 * have uninitialized any derived state in the victim rule, as in step 5 in
3740 * the "Life Cycle" in ofproto/ofproto-provider.h. ofoperation_complete()
3741 * performs steps 6 and 7 for the victim rule, most notably by calling its
3742 * ->rule_dealloc() function.
3744 * If 'error' is nonzero, then generally the operation will be rolled back:
3746 * - If 'op' is an "add flow" operation, ofproto removes the new rule or
3747 * restores the original rule. The caller must have uninitialized any
3748 * derived state in the new rule, as in step 5 of in the "Life Cycle" in
3749 * ofproto/ofproto-provider.h. ofoperation_complete() performs steps 6 and
3750 * and 7 for the new rule, calling its ->rule_dealloc() function.
3752 * - If 'op' is a "modify flow" operation, ofproto restores the original
3755 * - 'op' must not be a "delete flow" operation. Removing a rule is not
3756 * allowed to fail. It must always succeed.
3758 * Please see the large comment in ofproto/ofproto-provider.h titled
3759 * "Asynchronous Operation Support" for more information. */
3761 ofoperation_complete(struct ofoperation *op, enum ofperr error)
3763 struct ofopgroup *group = op->group;
3765 assert(op->rule->pending == op);
3766 assert(group->n_running > 0);
3767 assert(!error || op->type != OFOPERATION_DELETE);
3770 if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
3771 ofopgroup_complete(group);
3776 ofoperation_get_victim(struct ofoperation *op)
3778 assert(op->type == OFOPERATION_ADD);
3783 pick_datapath_id(const struct ofproto *ofproto)
3785 const struct ofport *port;
3787 port = ofproto_get_port(ofproto, OFPP_LOCAL);
3789 uint8_t ea[ETH_ADDR_LEN];
3792 error = netdev_get_etheraddr(port->netdev, ea);
3794 return eth_addr_to_uint64(ea);
3796 VLOG_WARN("%s: could not get MAC address for %s (%s)",
3797 ofproto->name, netdev_get_name(port->netdev),
3800 return ofproto->fallback_dpid;
3804 pick_fallback_dpid(void)
3806 uint8_t ea[ETH_ADDR_LEN];
3807 eth_addr_nicira_random(ea);
3808 return eth_addr_to_uint64(ea);
3811 /* Table overflow policy. */
3813 /* Chooses and returns a rule to evict from 'table'. Returns NULL if the table
3814 * is not configured to evict rules or if the table contains no evictable
3815 * rules. (Rules with 'evictable' set to false or with no timeouts are not
3817 static struct rule *
3818 choose_rule_to_evict(struct oftable *table)
3820 struct eviction_group *evg;
3822 if (!table->eviction_fields) {
3826 /* In the common case, the outer and inner loops here will each be entered
3829 * - The inner loop normally "return"s in its first iteration. If the
3830 * eviction group has any evictable rules, then it always returns in
3833 * - The outer loop only iterates more than once if the largest eviction
3834 * group has no evictable rules.
3836 * - The outer loop can exit only if table's 'max_flows' is all filled up
3837 * by unevictable rules'. */
3838 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
3841 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
3842 if (rule->evictable) {
3851 /* Searches 'ofproto' for tables that have more flows than their configured
3852 * maximum and that have flow eviction enabled, and evicts as many flows as
3853 * necessary and currently feasible from them.
3855 * This triggers only when an OpenFlow table has N flows in it and then the
3856 * client configures a maximum number of flows less than N. */
3858 ofproto_evict(struct ofproto *ofproto)
3860 struct ofopgroup *group;
3861 struct oftable *table;
3863 group = ofopgroup_create_unattached(ofproto);
3864 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
3865 while (classifier_count(&table->cls) > table->max_flows
3866 && table->eviction_fields) {
3869 rule = choose_rule_to_evict(table);
3870 if (!rule || rule->pending) {
3874 ofoperation_create(group, rule, OFOPERATION_DELETE);
3875 oftable_remove_rule(rule);
3876 ofproto->ofproto_class->rule_destruct(rule);
3879 ofopgroup_submit(group);
3882 /* Eviction groups. */
3884 /* Returns the priority to use for an eviction_group that contains 'n_rules'
3885 * rules. The priority contains low-order random bits to ensure that eviction
3886 * groups with the same number of rules are prioritized randomly. */
3888 eviction_group_priority(size_t n_rules)
3890 uint16_t size = MIN(UINT16_MAX, n_rules);
3891 return (size << 16) | random_uint16();
3894 /* Updates 'evg', an eviction_group within 'table', following a change that
3895 * adds or removes rules in 'evg'. */
3897 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
3899 heap_change(&table->eviction_groups_by_size, &evg->size_node,
3900 eviction_group_priority(heap_count(&evg->rules)));
3903 /* Destroys 'evg', an eviction_group within 'table':
3905 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
3906 * rules themselves, just removes them from the eviction group.)
3908 * - Removes 'evg' from 'table'.
3912 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
3914 while (!heap_is_empty(&evg->rules)) {
3917 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
3918 rule->eviction_group = NULL;
3920 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
3921 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
3922 heap_destroy(&evg->rules);
3926 /* Removes 'rule' from its eviction group, if any. */
3928 eviction_group_remove_rule(struct rule *rule)
3930 if (rule->eviction_group) {
3931 struct oftable *table = &rule->ofproto->tables[rule->table_id];
3932 struct eviction_group *evg = rule->eviction_group;
3934 rule->eviction_group = NULL;
3935 heap_remove(&evg->rules, &rule->evg_node);
3936 if (heap_is_empty(&evg->rules)) {
3937 eviction_group_destroy(table, evg);
3939 eviction_group_resized(table, evg);
3944 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
3945 * returns the hash value. */
3947 eviction_group_hash_rule(struct rule *rule)
3949 struct oftable *table = &rule->ofproto->tables[rule->table_id];
3950 const struct mf_subfield *sf;
3953 hash = table->eviction_group_id_basis;
3954 for (sf = table->eviction_fields;
3955 sf < &table->eviction_fields[table->n_eviction_fields];
3958 if (mf_are_prereqs_ok(sf->field, &rule->cr.flow)) {
3959 union mf_value value;
3961 mf_get_value(sf->field, &rule->cr.flow, &value);
3963 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
3965 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
3966 unsigned int start = sf->ofs + sf->n_bits;
3967 bitwise_zero(&value, sf->field->n_bytes, start,
3968 sf->field->n_bytes * 8 - start);
3970 hash = hash_bytes(&value, sf->field->n_bytes, hash);
3972 hash = hash_int(hash, 0);
3979 /* Returns an eviction group within 'table' with the given 'id', creating one
3981 static struct eviction_group *
3982 eviction_group_find(struct oftable *table, uint32_t id)
3984 struct eviction_group *evg;
3986 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
3990 evg = xmalloc(sizeof *evg);
3991 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
3992 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
3993 eviction_group_priority(0));
3994 heap_init(&evg->rules);
3999 /* Returns an eviction priority for 'rule'. The return value should be
4000 * interpreted so that higher priorities make a rule more attractive candidates
4003 rule_eviction_priority(struct rule *rule)
4005 long long int hard_expiration;
4006 long long int idle_expiration;
4007 long long int expiration;
4008 uint32_t expiration_offset;
4010 /* Calculate time of expiration. */
4011 hard_expiration = (rule->hard_timeout
4012 ? rule->modified + rule->hard_timeout * 1000
4014 idle_expiration = (rule->idle_timeout
4015 ? rule->used + rule->idle_timeout * 1000
4017 expiration = MIN(hard_expiration, idle_expiration);
4018 if (expiration == LLONG_MAX) {
4022 /* Calculate the time of expiration as a number of (approximate) seconds
4023 * after program startup.
4025 * This should work OK for program runs that last UINT32_MAX seconds or
4026 * less. Therefore, please restart OVS at least once every 136 years. */
4027 expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
4029 /* Invert the expiration offset because we're using a max-heap. */
4030 return UINT32_MAX - expiration_offset;
4033 /* Adds 'rule' to an appropriate eviction group for its oftable's
4034 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
4035 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
4038 * The caller must ensure that 'rule' is not already in an eviction group. */
4040 eviction_group_add_rule(struct rule *rule)
4042 struct ofproto *ofproto = rule->ofproto;
4043 struct oftable *table = &ofproto->tables[rule->table_id];
4045 if (table->eviction_fields
4046 && (rule->hard_timeout || rule->idle_timeout)) {
4047 struct eviction_group *evg;
4049 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
4051 rule->eviction_group = evg;
4052 heap_insert(&evg->rules, &rule->evg_node,
4053 rule_eviction_priority(rule));
4054 eviction_group_resized(table, evg);
4060 /* Initializes 'table'. */
4062 oftable_init(struct oftable *table)
4064 memset(table, 0, sizeof *table);
4065 classifier_init(&table->cls);
4066 table->max_flows = UINT_MAX;
4069 /* Destroys 'table', including its classifier and eviction groups.
4071 * The caller is responsible for freeing 'table' itself. */
4073 oftable_destroy(struct oftable *table)
4075 assert(classifier_is_empty(&table->cls));
4076 oftable_disable_eviction(table);
4077 classifier_destroy(&table->cls);
4081 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
4082 * string, then 'table' will use its default name.
4084 * This only affects the name exposed for a table exposed through the OpenFlow
4085 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
4087 oftable_set_name(struct oftable *table, const char *name)
4089 if (name && name[0]) {
4090 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
4091 if (!table->name || strncmp(name, table->name, len)) {
4093 table->name = xmemdup0(name, len);
4101 /* oftables support a choice of two policies when adding a rule would cause the
4102 * number of flows in the table to exceed the configured maximum number: either
4103 * they can refuse to add the new flow or they can evict some existing flow.
4104 * This function configures the former policy on 'table'. */
4106 oftable_disable_eviction(struct oftable *table)
4108 if (table->eviction_fields) {
4109 struct eviction_group *evg, *next;
4111 HMAP_FOR_EACH_SAFE (evg, next, id_node,
4112 &table->eviction_groups_by_id) {
4113 eviction_group_destroy(table, evg);
4115 hmap_destroy(&table->eviction_groups_by_id);
4116 heap_destroy(&table->eviction_groups_by_size);
4118 free(table->eviction_fields);
4119 table->eviction_fields = NULL;
4120 table->n_eviction_fields = 0;
4124 /* oftables support a choice of two policies when adding a rule would cause the
4125 * number of flows in the table to exceed the configured maximum number: either
4126 * they can refuse to add the new flow or they can evict some existing flow.
4127 * This function configures the latter policy on 'table', with fairness based
4128 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
4129 * 'n_fields' as 0 disables fairness.) */
4131 oftable_enable_eviction(struct oftable *table,
4132 const struct mf_subfield *fields, size_t n_fields)
4134 struct cls_cursor cursor;
4137 if (table->eviction_fields
4138 && n_fields == table->n_eviction_fields
4140 || !memcmp(fields, table->eviction_fields,
4141 n_fields * sizeof *fields))) {
4146 oftable_disable_eviction(table);
4148 table->n_eviction_fields = n_fields;
4149 table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
4151 table->eviction_group_id_basis = random_uint32();
4152 hmap_init(&table->eviction_groups_by_id);
4153 heap_init(&table->eviction_groups_by_size);
4155 cls_cursor_init(&cursor, &table->cls, NULL);
4156 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4157 eviction_group_add_rule(rule);
4161 /* Removes 'rule' from the oftable that contains it. */
4163 oftable_remove_rule(struct rule *rule)
4165 struct ofproto *ofproto = rule->ofproto;
4166 struct oftable *table = &ofproto->tables[rule->table_id];
4168 classifier_remove(&table->cls, &rule->cr);
4169 eviction_group_remove_rule(rule);
4172 /* Inserts 'rule' into its oftable. Removes any existing rule from 'rule''s
4173 * oftable that has an identical cls_rule. Returns the rule that was removed,
4174 * if any, and otherwise NULL. */
4175 static struct rule *
4176 oftable_replace_rule(struct rule *rule)
4178 struct ofproto *ofproto = rule->ofproto;
4179 struct oftable *table = &ofproto->tables[rule->table_id];
4180 struct rule *victim;
4182 victim = rule_from_cls_rule(classifier_replace(&table->cls, &rule->cr));
4184 eviction_group_remove_rule(victim);
4186 eviction_group_add_rule(rule);
4190 /* Removes 'old' from its oftable then, if 'new' is nonnull, inserts 'new'. */
4192 oftable_substitute_rule(struct rule *old, struct rule *new)
4195 oftable_replace_rule(new);
4197 oftable_remove_rule(old);
4201 /* unixctl commands. */
4204 ofproto_lookup(const char *name)
4206 struct ofproto *ofproto;
4208 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
4210 if (!strcmp(ofproto->name, name)) {
4218 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
4219 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
4221 struct ofproto *ofproto;
4225 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
4226 ds_put_format(&results, "%s\n", ofproto->name);
4228 unixctl_command_reply(conn, ds_cstr(&results));
4229 ds_destroy(&results);
4233 ofproto_unixctl_init(void)
4235 static bool registered;
4241 unixctl_command_register("ofproto/list", "", 0, 0,
4242 ofproto_unixctl_list, NULL);
4245 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
4247 * This is deprecated. It is only for compatibility with broken device drivers
4248 * in old versions of Linux that do not properly support VLANs when VLAN
4249 * devices are not used. When broken device drivers are no longer in
4250 * widespread use, we will delete these interfaces. */
4252 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
4253 * (exactly) by an OpenFlow rule in 'ofproto'. */
4255 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
4257 const struct oftable *oftable;
4259 free(ofproto->vlan_bitmap);
4260 ofproto->vlan_bitmap = bitmap_allocate(4096);
4261 ofproto->vlans_changed = false;
4263 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
4264 const struct cls_table *table;
4266 HMAP_FOR_EACH (table, hmap_node, &oftable->cls.tables) {
4267 if ((table->wc.vlan_tci_mask & htons(VLAN_VID_MASK))
4268 == htons(VLAN_VID_MASK)) {
4269 const struct cls_rule *rule;
4271 HMAP_FOR_EACH (rule, hmap_node, &table->rules) {
4272 uint16_t vid = vlan_tci_to_vid(rule->flow.vlan_tci);
4273 bitmap_set1(vlan_bitmap, vid);
4274 bitmap_set1(ofproto->vlan_bitmap, vid);
4281 /* Returns true if new VLANs have come into use by the flow table since the
4282 * last call to ofproto_get_vlan_usage().
4284 * We don't track when old VLANs stop being used. */
4286 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
4288 return ofproto->vlans_changed;
4291 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
4292 * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'. If
4293 * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
4294 * device as a VLAN splinter for VLAN ID 'vid'. If 'realdev_ofp_port' is zero,
4295 * then the VLAN device is un-enslaved. */
4297 ofproto_port_set_realdev(struct ofproto *ofproto, uint16_t vlandev_ofp_port,
4298 uint16_t realdev_ofp_port, int vid)
4300 struct ofport *ofport;
4303 assert(vlandev_ofp_port != realdev_ofp_port);
4305 ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
4307 VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
4308 ofproto->name, vlandev_ofp_port);
4312 if (!ofproto->ofproto_class->set_realdev) {
4313 if (!vlandev_ofp_port) {
4316 VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
4320 error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
4322 VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
4323 ofproto->name, vlandev_ofp_port,
4324 netdev_get_name(ofport->netdev), strerror(error));