2 * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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.
22 #include <sys/socket.h>
24 #include <netinet/in.h>
27 #include "byte-order.h"
28 #include "classifier.h"
30 #include "discovery.h"
32 #include "dynamic-string.h"
33 #include "fail-open.h"
37 #include "mac-learning.h"
38 #include "multipath.h"
44 #include "ofp-print.h"
46 #include "ofproto-sflow.h"
48 #include "openflow/nicira-ext.h"
49 #include "openflow/openflow.h"
50 #include "openvswitch/datapath-protocol.h"
54 #include "poll-loop.h"
58 #include "stream-ssl.h"
66 VLOG_DEFINE_THIS_MODULE(ofproto);
68 COVERAGE_DEFINE(facet_changed_rule);
69 COVERAGE_DEFINE(facet_revalidate);
70 COVERAGE_DEFINE(odp_overflow);
71 COVERAGE_DEFINE(ofproto_agg_request);
72 COVERAGE_DEFINE(ofproto_costly_flags);
73 COVERAGE_DEFINE(ofproto_ctlr_action);
74 COVERAGE_DEFINE(ofproto_del_rule);
75 COVERAGE_DEFINE(ofproto_error);
76 COVERAGE_DEFINE(ofproto_expiration);
77 COVERAGE_DEFINE(ofproto_expired);
78 COVERAGE_DEFINE(ofproto_flows_req);
79 COVERAGE_DEFINE(ofproto_flush);
80 COVERAGE_DEFINE(ofproto_invalidated);
81 COVERAGE_DEFINE(ofproto_no_packet_in);
82 COVERAGE_DEFINE(ofproto_ofconn_stuck);
83 COVERAGE_DEFINE(ofproto_ofp2odp);
84 COVERAGE_DEFINE(ofproto_packet_in);
85 COVERAGE_DEFINE(ofproto_packet_out);
86 COVERAGE_DEFINE(ofproto_queue_req);
87 COVERAGE_DEFINE(ofproto_recv_openflow);
88 COVERAGE_DEFINE(ofproto_reinit_ports);
89 COVERAGE_DEFINE(ofproto_unexpected_rule);
90 COVERAGE_DEFINE(ofproto_uninstallable);
91 COVERAGE_DEFINE(ofproto_update_port);
93 #include "sflow_api.h"
98 struct hmap_node hmap_node; /* In struct ofproto's "ports" hmap. */
99 struct netdev *netdev;
100 struct ofp_phy_port opp; /* In host byte order. */
104 static void ofport_free(struct ofport *);
105 static void hton_ofp_phy_port(struct ofp_phy_port *);
107 struct action_xlate_ctx {
108 /* action_xlate_ctx_init() initializes these members. */
111 struct ofproto *ofproto;
113 /* Flow to which the OpenFlow actions apply. xlate_actions() will modify
114 * this flow when actions change header fields. */
117 /* The packet corresponding to 'flow', or a null pointer if we are
118 * revalidating without a packet to refer to. */
119 const struct ofpbuf *packet;
121 /* If nonnull, called just before executing a resubmit action.
123 * This is normally null so the client has to set it manually after
124 * calling action_xlate_ctx_init(). */
125 void (*resubmit_hook)(struct action_xlate_ctx *, const struct rule *);
127 /* xlate_actions() initializes and uses these members. The client might want
128 * to look at them after it returns. */
130 struct ofpbuf *odp_actions; /* Datapath actions. */
131 tag_type tags; /* Tags associated with OFPP_NORMAL actions. */
132 bool may_set_up_flow; /* True ordinarily; false if the actions must
133 * be reassessed for every packet. */
134 uint16_t nf_output_iface; /* Output interface index for NetFlow. */
136 /* xlate_actions() initializes and uses these members, but the client has no
137 * reason to look at them. */
139 int recurse; /* Recursion level, via xlate_table_action. */
140 int last_pop_priority; /* Offset in 'odp_actions' just past most
141 * recently added ODPAT_SET_PRIORITY. */
144 static void action_xlate_ctx_init(struct action_xlate_ctx *,
145 struct ofproto *, const struct flow *,
146 const struct ofpbuf *);
147 static struct ofpbuf *xlate_actions(struct action_xlate_ctx *,
148 const union ofp_action *in, size_t n_in);
150 /* An OpenFlow flow. */
152 long long int used; /* Time last used; time created if not used. */
153 long long int created; /* Creation time. */
157 * - Do include packets and bytes from facets that have been deleted or
158 * whose own statistics have been folded into the rule.
160 * - Do include packets and bytes sent "by hand" that were accounted to
161 * the rule without any facet being involved (this is a rare corner
162 * case in rule_execute()).
164 * - Do not include packet or bytes that can be obtained from any facet's
165 * packet_count or byte_count member or that can be obtained from the
166 * datapath by, e.g., dpif_flow_get() for any facet.
168 uint64_t packet_count; /* Number of packets received. */
169 uint64_t byte_count; /* Number of bytes received. */
171 ovs_be64 flow_cookie; /* Controller-issued identifier. */
173 struct cls_rule cr; /* In owning ofproto's classifier. */
174 uint16_t idle_timeout; /* In seconds from time of last use. */
175 uint16_t hard_timeout; /* In seconds from time of creation. */
176 bool send_flow_removed; /* Send a flow removed message? */
177 int n_actions; /* Number of elements in actions[]. */
178 union ofp_action *actions; /* OpenFlow actions. */
179 struct list facets; /* List of "struct facet"s. */
182 static struct rule *rule_from_cls_rule(const struct cls_rule *);
183 static bool rule_is_hidden(const struct rule *);
185 static struct rule *rule_create(const struct cls_rule *,
186 const union ofp_action *, size_t n_actions,
187 uint16_t idle_timeout, uint16_t hard_timeout,
188 ovs_be64 flow_cookie, bool send_flow_removed);
189 static void rule_destroy(struct ofproto *, struct rule *);
190 static void rule_free(struct rule *);
192 static struct rule *rule_lookup(struct ofproto *, const struct flow *);
193 static void rule_insert(struct ofproto *, struct rule *);
194 static void rule_remove(struct ofproto *, struct rule *);
196 static void rule_send_removed(struct ofproto *, struct rule *, uint8_t reason);
198 /* An exact-match instantiation of an OpenFlow flow. */
200 long long int used; /* Time last used; time created if not used. */
204 * - Do include packets and bytes sent "by hand", e.g. with
207 * - Do include packets and bytes that were obtained from the datapath
208 * when a flow was deleted (e.g. dpif_flow_del()) or when its
209 * statistics were reset (e.g. dpif_flow_put() with ODPPF_ZERO_STATS).
211 * - Do not include any packets or bytes that can currently be obtained
212 * from the datapath by, e.g., dpif_flow_get().
214 uint64_t packet_count; /* Number of packets received. */
215 uint64_t byte_count; /* Number of bytes received. */
217 /* Number of bytes passed to account_cb. This may include bytes that can
218 * currently obtained from the datapath (thus, it can be greater than
220 uint64_t accounted_bytes;
222 struct hmap_node hmap_node; /* In owning ofproto's 'facets' hmap. */
223 struct list list_node; /* In owning rule's 'facets' list. */
224 struct rule *rule; /* Owning rule. */
225 struct flow flow; /* Exact-match flow. */
226 bool installed; /* Installed in datapath? */
227 bool may_install; /* True ordinarily; false if actions must
228 * be reassessed for every packet. */
229 size_t actions_len; /* Number of bytes in actions[]. */
230 struct nlattr *actions; /* Datapath actions. */
231 tag_type tags; /* Tags (set only by hooks). */
232 struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
235 static struct facet *facet_create(struct ofproto *, struct rule *,
237 const struct ofpbuf *packet);
238 static void facet_remove(struct ofproto *, struct facet *);
239 static void facet_free(struct facet *);
241 static struct facet *facet_lookup_valid(struct ofproto *, const struct flow *);
242 static bool facet_revalidate(struct ofproto *, struct facet *);
244 static void facet_install(struct ofproto *, struct facet *, bool zero_stats);
245 static void facet_uninstall(struct ofproto *, struct facet *);
246 static void facet_flush_stats(struct ofproto *, struct facet *);
248 static void facet_make_actions(struct ofproto *, struct facet *,
249 const struct ofpbuf *packet);
250 static void facet_update_stats(struct ofproto *, struct facet *,
251 const struct odp_flow_stats *);
253 /* ofproto supports two kinds of OpenFlow connections:
255 * - "Primary" connections to ordinary OpenFlow controllers. ofproto
256 * maintains persistent connections to these controllers and by default
257 * sends them asynchronous messages such as packet-ins.
259 * - "Service" connections, e.g. from ovs-ofctl. When these connections
260 * drop, it is the other side's responsibility to reconnect them if
261 * necessary. ofproto does not send them asynchronous messages by default.
263 * Currently, active (tcp, ssl, unix) connections are always "primary"
264 * connections and passive (ptcp, pssl, punix) connections are always "service"
265 * connections. There is no inherent reason for this, but it reflects the
269 OFCONN_PRIMARY, /* An ordinary OpenFlow controller. */
270 OFCONN_SERVICE /* A service connection, e.g. "ovs-ofctl". */
273 /* A listener for incoming OpenFlow "service" connections. */
275 struct hmap_node node; /* In struct ofproto's "services" hmap. */
276 struct pvconn *pvconn; /* OpenFlow connection listener. */
278 /* These are not used by ofservice directly. They are settings for
279 * accepted "struct ofconn"s from the pvconn. */
280 int probe_interval; /* Max idle time before probing, in seconds. */
281 int rate_limit; /* Max packet-in rate in packets per second. */
282 int burst_limit; /* Limit on accumulating packet credits. */
285 static struct ofservice *ofservice_lookup(struct ofproto *,
287 static int ofservice_create(struct ofproto *,
288 const struct ofproto_controller *);
289 static void ofservice_reconfigure(struct ofservice *,
290 const struct ofproto_controller *);
291 static void ofservice_destroy(struct ofproto *, struct ofservice *);
293 /* An OpenFlow connection. */
295 struct ofproto *ofproto; /* The ofproto that owns this connection. */
296 struct list node; /* In struct ofproto's "all_conns" list. */
297 struct rconn *rconn; /* OpenFlow connection. */
298 enum ofconn_type type; /* Type. */
299 enum nx_flow_format flow_format; /* Currently selected flow format. */
301 /* OFPT_PACKET_IN related data. */
302 struct rconn_packet_counter *packet_in_counter; /* # queued on 'rconn'. */
303 struct pinsched *schedulers[2]; /* Indexed by reason code; see below. */
304 struct pktbuf *pktbuf; /* OpenFlow packet buffers. */
305 int miss_send_len; /* Bytes to send of buffered packets. */
307 /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
308 * requests, and the maximum number before we stop reading OpenFlow
310 #define OFCONN_REPLY_MAX 100
311 struct rconn_packet_counter *reply_counter;
313 /* type == OFCONN_PRIMARY only. */
314 enum nx_role role; /* Role. */
315 struct hmap_node hmap_node; /* In struct ofproto's "controllers" map. */
316 struct discovery *discovery; /* Controller discovery object, if enabled. */
317 struct status_category *ss; /* Switch status category. */
318 enum ofproto_band band; /* In-band or out-of-band? */
321 /* We use OFPR_NO_MATCH and OFPR_ACTION as indexes into struct ofconn's
322 * "schedulers" array. Their values are 0 and 1, and their meanings and values
323 * coincide with _ODPL_MISS_NR and _ODPL_ACTION_NR, so this is convenient. In
324 * case anything ever changes, check their values here. */
325 #define N_SCHEDULERS 2
326 BUILD_ASSERT_DECL(OFPR_NO_MATCH == 0);
327 BUILD_ASSERT_DECL(OFPR_NO_MATCH == _ODPL_MISS_NR);
328 BUILD_ASSERT_DECL(OFPR_ACTION == 1);
329 BUILD_ASSERT_DECL(OFPR_ACTION == _ODPL_ACTION_NR);
331 static struct ofconn *ofconn_create(struct ofproto *, struct rconn *,
333 static void ofconn_destroy(struct ofconn *);
334 static void ofconn_run(struct ofconn *);
335 static void ofconn_wait(struct ofconn *);
336 static bool ofconn_receives_async_msgs(const struct ofconn *);
337 static char *ofconn_make_name(const struct ofproto *, const char *target);
338 static void ofconn_set_rate_limit(struct ofconn *, int rate, int burst);
340 static void queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
341 struct rconn_packet_counter *counter);
343 static void send_packet_in(struct ofproto *, struct dpif_upcall *,
344 const struct flow *, bool clone);
345 static void do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn);
349 uint64_t datapath_id; /* Datapath ID. */
350 uint64_t fallback_dpid; /* Datapath ID if no better choice found. */
351 char *mfr_desc; /* Manufacturer. */
352 char *hw_desc; /* Hardware. */
353 char *sw_desc; /* Software version. */
354 char *serial_desc; /* Serial number. */
355 char *dp_desc; /* Datapath description. */
359 struct netdev_monitor *netdev_monitor;
360 struct hmap ports; /* Contains "struct ofport"s. */
361 struct shash port_by_name;
365 struct switch_status *switch_status;
366 struct fail_open *fail_open;
367 struct netflow *netflow;
368 struct ofproto_sflow *sflow;
370 /* In-band control. */
371 struct in_band *in_band;
372 long long int next_in_band_update;
373 struct sockaddr_in *extra_in_band_remotes;
374 size_t n_extra_remotes;
378 struct classifier cls;
379 long long int next_expiration;
383 bool need_revalidate;
384 struct tag_set revalidate_set;
386 /* OpenFlow connections. */
387 struct hmap controllers; /* Controller "struct ofconn"s. */
388 struct list all_conns; /* Contains "struct ofconn"s. */
389 enum ofproto_fail_mode fail_mode;
391 /* OpenFlow listeners. */
392 struct hmap services; /* Contains "struct ofservice"s. */
393 struct pvconn **snoops;
396 /* Hooks for ovs-vswitchd. */
397 const struct ofhooks *ofhooks;
400 /* Used by default ofhooks. */
401 struct mac_learning *ml;
404 /* Map from dpif name to struct ofproto, for use by unixctl commands. */
405 static struct shash all_ofprotos = SHASH_INITIALIZER(&all_ofprotos);
407 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
409 static const struct ofhooks default_ofhooks;
411 static uint64_t pick_datapath_id(const struct ofproto *);
412 static uint64_t pick_fallback_dpid(void);
414 static int ofproto_expire(struct ofproto *);
416 static void handle_upcall(struct ofproto *, struct dpif_upcall *);
418 static void handle_openflow(struct ofconn *, struct ofpbuf *);
420 static struct ofport *get_port(const struct ofproto *, uint16_t odp_port);
421 static void update_port(struct ofproto *, const char *devname);
422 static int init_ports(struct ofproto *);
423 static void reinit_ports(struct ofproto *);
425 static void ofproto_unixctl_init(void);
428 ofproto_create(const char *datapath, const char *datapath_type,
429 const struct ofhooks *ofhooks, void *aux,
430 struct ofproto **ofprotop)
438 ofproto_unixctl_init();
440 /* Connect to datapath and start listening for messages. */
441 error = dpif_open(datapath, datapath_type, &dpif);
443 VLOG_ERR("failed to open datapath %s: %s", datapath, strerror(error));
446 error = dpif_recv_set_mask(dpif, ODPL_MISS | ODPL_ACTION | ODPL_SFLOW);
448 VLOG_ERR("failed to listen on datapath %s: %s",
449 datapath, strerror(error));
453 dpif_flow_flush(dpif);
454 dpif_recv_purge(dpif);
456 /* Initialize settings. */
457 p = xzalloc(sizeof *p);
458 p->fallback_dpid = pick_fallback_dpid();
459 p->datapath_id = p->fallback_dpid;
460 p->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
461 p->hw_desc = xstrdup(DEFAULT_HW_DESC);
462 p->sw_desc = xstrdup(DEFAULT_SW_DESC);
463 p->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
464 p->dp_desc = xstrdup(DEFAULT_DP_DESC);
466 /* Initialize datapath. */
468 p->netdev_monitor = netdev_monitor_create();
469 hmap_init(&p->ports);
470 shash_init(&p->port_by_name);
471 p->max_ports = dpif_get_max_ports(dpif);
473 /* Initialize submodules. */
474 p->switch_status = switch_status_create(p);
479 /* Initialize in-band control. */
481 p->in_band_queue = -1;
483 /* Initialize flow table. */
484 classifier_init(&p->cls);
485 p->next_expiration = time_msec() + 1000;
487 /* Initialize facet table. */
488 hmap_init(&p->facets);
489 p->need_revalidate = false;
490 tag_set_init(&p->revalidate_set);
492 /* Initialize OpenFlow connections. */
493 list_init(&p->all_conns);
494 hmap_init(&p->controllers);
495 hmap_init(&p->services);
499 /* Initialize hooks. */
501 p->ofhooks = ofhooks;
505 p->ofhooks = &default_ofhooks;
507 p->ml = mac_learning_create();
510 /* Pick final datapath ID. */
511 p->datapath_id = pick_datapath_id(p);
512 VLOG_INFO("using datapath ID %016"PRIx64, p->datapath_id);
514 shash_add_once(&all_ofprotos, dpif_name(p->dpif), p);
521 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
523 uint64_t old_dpid = p->datapath_id;
524 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
525 if (p->datapath_id != old_dpid) {
526 VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
528 /* Force all active connections to reconnect, since there is no way to
529 * notify a controller that the datapath ID has changed. */
530 ofproto_reconnect_controllers(p);
535 is_discovery_controller(const struct ofproto_controller *c)
537 return !strcmp(c->target, "discover");
541 is_in_band_controller(const struct ofproto_controller *c)
543 return is_discovery_controller(c) || c->band == OFPROTO_IN_BAND;
546 /* Creates a new controller in 'ofproto'. Some of the settings are initially
547 * drawn from 'c', but update_controller() needs to be called later to finish
548 * the new ofconn's configuration. */
550 add_controller(struct ofproto *ofproto, const struct ofproto_controller *c)
552 struct discovery *discovery;
553 struct ofconn *ofconn;
555 if (is_discovery_controller(c)) {
556 int error = discovery_create(c->accept_re, c->update_resolv_conf,
557 ofproto->dpif, ofproto->switch_status,
566 ofconn = ofconn_create(ofproto, rconn_create(5, 8), OFCONN_PRIMARY);
567 ofconn->pktbuf = pktbuf_create();
568 ofconn->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
570 ofconn->discovery = discovery;
572 char *name = ofconn_make_name(ofproto, c->target);
573 rconn_connect(ofconn->rconn, c->target, name);
576 hmap_insert(&ofproto->controllers, &ofconn->hmap_node,
577 hash_string(c->target, 0));
580 /* Reconfigures 'ofconn' to match 'c'. This function cannot update an ofconn's
581 * target or turn discovery on or off (these are done by creating new ofconns
582 * and deleting old ones), but it can update the rest of an ofconn's
585 update_controller(struct ofconn *ofconn, const struct ofproto_controller *c)
589 ofconn->band = (is_in_band_controller(c)
590 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
592 rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
594 probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
595 rconn_set_probe_interval(ofconn->rconn, probe_interval);
597 if (ofconn->discovery) {
598 discovery_set_update_resolv_conf(ofconn->discovery,
599 c->update_resolv_conf);
600 discovery_set_accept_controller_re(ofconn->discovery, c->accept_re);
603 ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
607 ofconn_get_target(const struct ofconn *ofconn)
609 return ofconn->discovery ? "discover" : rconn_get_target(ofconn->rconn);
612 static struct ofconn *
613 find_controller_by_target(struct ofproto *ofproto, const char *target)
615 struct ofconn *ofconn;
617 HMAP_FOR_EACH_WITH_HASH (ofconn, hmap_node,
618 hash_string(target, 0), &ofproto->controllers) {
619 if (!strcmp(ofconn_get_target(ofconn), target)) {
627 update_in_band_remotes(struct ofproto *ofproto)
629 const struct ofconn *ofconn;
630 struct sockaddr_in *addrs;
631 size_t max_addrs, n_addrs;
635 /* Allocate enough memory for as many remotes as we could possibly have. */
636 max_addrs = ofproto->n_extra_remotes + hmap_count(&ofproto->controllers);
637 addrs = xmalloc(max_addrs * sizeof *addrs);
640 /* Add all the remotes. */
642 HMAP_FOR_EACH (ofconn, hmap_node, &ofproto->controllers) {
643 struct sockaddr_in *sin = &addrs[n_addrs];
645 if (ofconn->band == OFPROTO_OUT_OF_BAND) {
649 sin->sin_addr.s_addr = rconn_get_remote_ip(ofconn->rconn);
650 if (sin->sin_addr.s_addr) {
651 sin->sin_port = rconn_get_remote_port(ofconn->rconn);
654 if (ofconn->discovery) {
658 for (i = 0; i < ofproto->n_extra_remotes; i++) {
659 addrs[n_addrs++] = ofproto->extra_in_band_remotes[i];
662 /* Create or update or destroy in-band.
664 * Ordinarily we only enable in-band if there's at least one remote
665 * address, but discovery needs the in-band rules for DHCP to be installed
666 * even before we know any remote addresses. */
667 if (n_addrs || discovery) {
668 if (!ofproto->in_band) {
669 in_band_create(ofproto, ofproto->dpif, ofproto->switch_status,
672 if (ofproto->in_band) {
673 in_band_set_remotes(ofproto->in_band, addrs, n_addrs);
675 in_band_set_queue(ofproto->in_band, ofproto->in_band_queue);
676 ofproto->next_in_band_update = time_msec() + 1000;
678 in_band_destroy(ofproto->in_band);
679 ofproto->in_band = NULL;
687 update_fail_open(struct ofproto *p)
689 struct ofconn *ofconn;
691 if (!hmap_is_empty(&p->controllers)
692 && p->fail_mode == OFPROTO_FAIL_STANDALONE) {
693 struct rconn **rconns;
697 p->fail_open = fail_open_create(p, p->switch_status);
701 rconns = xmalloc(hmap_count(&p->controllers) * sizeof *rconns);
702 HMAP_FOR_EACH (ofconn, hmap_node, &p->controllers) {
703 rconns[n++] = ofconn->rconn;
706 fail_open_set_controllers(p->fail_open, rconns, n);
707 /* p->fail_open takes ownership of 'rconns'. */
709 fail_open_destroy(p->fail_open);
715 ofproto_set_controllers(struct ofproto *p,
716 const struct ofproto_controller *controllers,
717 size_t n_controllers)
719 struct shash new_controllers;
720 struct ofconn *ofconn, *next_ofconn;
721 struct ofservice *ofservice, *next_ofservice;
725 /* Create newly configured controllers and services.
726 * Create a name to ofproto_controller mapping in 'new_controllers'. */
727 shash_init(&new_controllers);
728 for (i = 0; i < n_controllers; i++) {
729 const struct ofproto_controller *c = &controllers[i];
731 if (!vconn_verify_name(c->target) || !strcmp(c->target, "discover")) {
732 if (!find_controller_by_target(p, c->target)) {
733 add_controller(p, c);
735 } else if (!pvconn_verify_name(c->target)) {
736 if (!ofservice_lookup(p, c->target) && ofservice_create(p, c)) {
740 VLOG_WARN_RL(&rl, "%s: unsupported controller \"%s\"",
741 dpif_name(p->dpif), c->target);
745 shash_add_once(&new_controllers, c->target, &controllers[i]);
748 /* Delete controllers that are no longer configured.
749 * Update configuration of all now-existing controllers. */
751 HMAP_FOR_EACH_SAFE (ofconn, next_ofconn, hmap_node, &p->controllers) {
752 struct ofproto_controller *c;
754 c = shash_find_data(&new_controllers, ofconn_get_target(ofconn));
756 ofconn_destroy(ofconn);
758 update_controller(ofconn, c);
765 /* Delete services that are no longer configured.
766 * Update configuration of all now-existing services. */
767 HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &p->services) {
768 struct ofproto_controller *c;
770 c = shash_find_data(&new_controllers,
771 pvconn_get_name(ofservice->pvconn));
773 ofservice_destroy(p, ofservice);
775 ofservice_reconfigure(ofservice, c);
779 shash_destroy(&new_controllers);
781 update_in_band_remotes(p);
784 if (!hmap_is_empty(&p->controllers) && !ss_exists) {
785 ofconn = CONTAINER_OF(hmap_first(&p->controllers),
786 struct ofconn, hmap_node);
787 ofconn->ss = switch_status_register(p->switch_status, "remote",
788 rconn_status_cb, ofconn->rconn);
793 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
795 p->fail_mode = fail_mode;
799 /* Drops the connections between 'ofproto' and all of its controllers, forcing
800 * them to reconnect. */
802 ofproto_reconnect_controllers(struct ofproto *ofproto)
804 struct ofconn *ofconn;
806 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
807 rconn_reconnect(ofconn->rconn);
812 any_extras_changed(const struct ofproto *ofproto,
813 const struct sockaddr_in *extras, size_t n)
817 if (n != ofproto->n_extra_remotes) {
821 for (i = 0; i < n; i++) {
822 const struct sockaddr_in *old = &ofproto->extra_in_band_remotes[i];
823 const struct sockaddr_in *new = &extras[i];
825 if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
826 old->sin_port != new->sin_port) {
834 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
835 * in-band control should guarantee access, in the same way that in-band
836 * control guarantees access to OpenFlow controllers. */
838 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
839 const struct sockaddr_in *extras, size_t n)
841 if (!any_extras_changed(ofproto, extras, n)) {
845 free(ofproto->extra_in_band_remotes);
846 ofproto->n_extra_remotes = n;
847 ofproto->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
849 update_in_band_remotes(ofproto);
852 /* Sets the OpenFlow queue used by flows set up by in-band control on
853 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
854 * flows will use the default queue. */
856 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
858 if (queue_id != ofproto->in_band_queue) {
859 ofproto->in_band_queue = queue_id;
860 update_in_band_remotes(ofproto);
865 ofproto_set_desc(struct ofproto *p,
866 const char *mfr_desc, const char *hw_desc,
867 const char *sw_desc, const char *serial_desc,
870 struct ofp_desc_stats *ods;
873 if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
874 VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
875 sizeof ods->mfr_desc);
878 p->mfr_desc = xstrdup(mfr_desc);
881 if (strlen(hw_desc) >= sizeof ods->hw_desc) {
882 VLOG_WARN("truncating hw_desc, must be less than %zu characters",
883 sizeof ods->hw_desc);
886 p->hw_desc = xstrdup(hw_desc);
889 if (strlen(sw_desc) >= sizeof ods->sw_desc) {
890 VLOG_WARN("truncating sw_desc, must be less than %zu characters",
891 sizeof ods->sw_desc);
894 p->sw_desc = xstrdup(sw_desc);
897 if (strlen(serial_desc) >= sizeof ods->serial_num) {
898 VLOG_WARN("truncating serial_desc, must be less than %zu "
900 sizeof ods->serial_num);
902 free(p->serial_desc);
903 p->serial_desc = xstrdup(serial_desc);
906 if (strlen(dp_desc) >= sizeof ods->dp_desc) {
907 VLOG_WARN("truncating dp_desc, must be less than %zu characters",
908 sizeof ods->dp_desc);
911 p->dp_desc = xstrdup(dp_desc);
916 set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
917 const struct svec *svec)
919 struct pvconn **pvconns = *pvconnsp;
920 size_t n_pvconns = *n_pvconnsp;
924 for (i = 0; i < n_pvconns; i++) {
925 pvconn_close(pvconns[i]);
929 pvconns = xmalloc(svec->n * sizeof *pvconns);
931 for (i = 0; i < svec->n; i++) {
932 const char *name = svec->names[i];
933 struct pvconn *pvconn;
936 error = pvconn_open(name, &pvconn);
938 pvconns[n_pvconns++] = pvconn;
940 VLOG_ERR("failed to listen on %s: %s", name, strerror(error));
948 *n_pvconnsp = n_pvconns;
954 ofproto_set_snoops(struct ofproto *ofproto, const struct svec *snoops)
956 return set_pvconns(&ofproto->snoops, &ofproto->n_snoops, snoops);
960 ofproto_set_netflow(struct ofproto *ofproto,
961 const struct netflow_options *nf_options)
963 if (nf_options && nf_options->collectors.n) {
964 if (!ofproto->netflow) {
965 ofproto->netflow = netflow_create();
967 return netflow_set_options(ofproto->netflow, nf_options);
969 netflow_destroy(ofproto->netflow);
970 ofproto->netflow = NULL;
976 ofproto_set_sflow(struct ofproto *ofproto,
977 const struct ofproto_sflow_options *oso)
979 struct ofproto_sflow *os = ofproto->sflow;
982 struct ofport *ofport;
984 os = ofproto->sflow = ofproto_sflow_create(ofproto->dpif);
985 HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
986 ofproto_sflow_add_port(os, ofport->odp_port,
987 netdev_get_name(ofport->netdev));
990 ofproto_sflow_set_options(os, oso);
992 ofproto_sflow_destroy(os);
993 ofproto->sflow = NULL;
998 ofproto_get_datapath_id(const struct ofproto *ofproto)
1000 return ofproto->datapath_id;
1004 ofproto_has_primary_controller(const struct ofproto *ofproto)
1006 return !hmap_is_empty(&ofproto->controllers);
1009 enum ofproto_fail_mode
1010 ofproto_get_fail_mode(const struct ofproto *p)
1012 return p->fail_mode;
1016 ofproto_get_snoops(const struct ofproto *ofproto, struct svec *snoops)
1020 for (i = 0; i < ofproto->n_snoops; i++) {
1021 svec_add(snoops, pvconn_get_name(ofproto->snoops[i]));
1026 ofproto_destroy(struct ofproto *p)
1028 struct ofservice *ofservice, *next_ofservice;
1029 struct ofconn *ofconn, *next_ofconn;
1030 struct ofport *ofport, *next_ofport;
1037 shash_find_and_delete(&all_ofprotos, dpif_name(p->dpif));
1039 /* Destroy fail-open and in-band early, since they touch the classifier. */
1040 fail_open_destroy(p->fail_open);
1041 p->fail_open = NULL;
1043 in_band_destroy(p->in_band);
1045 free(p->extra_in_band_remotes);
1047 ofproto_flush_flows(p);
1048 classifier_destroy(&p->cls);
1049 hmap_destroy(&p->facets);
1051 LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &p->all_conns) {
1052 ofconn_destroy(ofconn);
1054 hmap_destroy(&p->controllers);
1056 dpif_close(p->dpif);
1057 netdev_monitor_destroy(p->netdev_monitor);
1058 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1059 hmap_remove(&p->ports, &ofport->hmap_node);
1060 ofport_free(ofport);
1062 shash_destroy(&p->port_by_name);
1064 switch_status_destroy(p->switch_status);
1065 netflow_destroy(p->netflow);
1066 ofproto_sflow_destroy(p->sflow);
1068 HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &p->services) {
1069 ofservice_destroy(p, ofservice);
1071 hmap_destroy(&p->services);
1073 for (i = 0; i < p->n_snoops; i++) {
1074 pvconn_close(p->snoops[i]);
1078 mac_learning_destroy(p->ml);
1083 free(p->serial_desc);
1086 hmap_destroy(&p->ports);
1092 ofproto_run(struct ofproto *p)
1094 int error = ofproto_run1(p);
1096 error = ofproto_run2(p, false);
1102 process_port_change(struct ofproto *ofproto, int error, char *devname)
1104 if (error == ENOBUFS) {
1105 reinit_ports(ofproto);
1106 } else if (!error) {
1107 update_port(ofproto, devname);
1112 /* Returns a "preference level" for snooping 'ofconn'. A higher return value
1113 * means that 'ofconn' is more interesting for monitoring than a lower return
1116 snoop_preference(const struct ofconn *ofconn)
1118 switch (ofconn->role) {
1119 case NX_ROLE_MASTER:
1126 /* Shouldn't happen. */
1131 /* One of ofproto's "snoop" pvconns has accepted a new connection on 'vconn'.
1132 * Connects this vconn to a controller. */
1134 add_snooper(struct ofproto *ofproto, struct vconn *vconn)
1136 struct ofconn *ofconn, *best;
1138 /* Pick a controller for monitoring. */
1140 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
1141 if (ofconn->type == OFCONN_PRIMARY
1142 && (!best || snoop_preference(ofconn) > snoop_preference(best))) {
1148 rconn_add_monitor(best->rconn, vconn);
1150 VLOG_INFO_RL(&rl, "no controller connection to snoop");
1156 ofproto_run1(struct ofproto *p)
1158 struct ofconn *ofconn, *next_ofconn;
1159 struct ofservice *ofservice;
1164 if (shash_is_empty(&p->port_by_name)) {
1168 for (i = 0; i < 50; i++) {
1169 struct dpif_upcall packet;
1171 error = dpif_recv(p->dpif, &packet);
1173 if (error == ENODEV) {
1174 /* Someone destroyed the datapath behind our back. The caller
1175 * better destroy us and give up, because we're just going to
1176 * spin from here on out. */
1177 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
1178 VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
1179 dpif_name(p->dpif));
1185 handle_upcall(p, &packet);
1188 while ((error = dpif_port_poll(p->dpif, &devname)) != EAGAIN) {
1189 process_port_change(p, error, devname);
1191 while ((error = netdev_monitor_poll(p->netdev_monitor,
1192 &devname)) != EAGAIN) {
1193 process_port_change(p, error, devname);
1197 if (time_msec() >= p->next_in_band_update) {
1198 update_in_band_remotes(p);
1200 in_band_run(p->in_band);
1203 LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &p->all_conns) {
1207 /* Fail-open maintenance. Do this after processing the ofconns since
1208 * fail-open checks the status of the controller rconn. */
1210 fail_open_run(p->fail_open);
1213 HMAP_FOR_EACH (ofservice, node, &p->services) {
1214 struct vconn *vconn;
1217 retval = pvconn_accept(ofservice->pvconn, OFP_VERSION, &vconn);
1219 struct rconn *rconn;
1222 rconn = rconn_create(ofservice->probe_interval, 0);
1223 name = ofconn_make_name(p, vconn_get_name(vconn));
1224 rconn_connect_unreliably(rconn, vconn, name);
1227 ofconn = ofconn_create(p, rconn, OFCONN_SERVICE);
1228 ofconn_set_rate_limit(ofconn, ofservice->rate_limit,
1229 ofservice->burst_limit);
1230 } else if (retval != EAGAIN) {
1231 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1235 for (i = 0; i < p->n_snoops; i++) {
1236 struct vconn *vconn;
1239 retval = pvconn_accept(p->snoops[i], OFP_VERSION, &vconn);
1241 add_snooper(p, vconn);
1242 } else if (retval != EAGAIN) {
1243 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1247 if (time_msec() >= p->next_expiration) {
1248 int delay = ofproto_expire(p);
1249 p->next_expiration = time_msec() + delay;
1250 COVERAGE_INC(ofproto_expiration);
1254 netflow_run(p->netflow);
1257 ofproto_sflow_run(p->sflow);
1264 ofproto_run2(struct ofproto *p, bool revalidate_all)
1266 /* Figure out what we need to revalidate now, if anything. */
1267 struct tag_set revalidate_set = p->revalidate_set;
1268 if (p->need_revalidate) {
1269 revalidate_all = true;
1272 /* Clear the revalidation flags. */
1273 tag_set_init(&p->revalidate_set);
1274 p->need_revalidate = false;
1276 /* Now revalidate if there's anything to do. */
1277 if (revalidate_all || !tag_set_is_empty(&revalidate_set)) {
1278 struct facet *facet, *next;
1280 HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &p->facets) {
1282 || tag_set_intersects(&revalidate_set, facet->tags)) {
1283 facet_revalidate(p, facet);
1292 ofproto_wait(struct ofproto *p)
1294 struct ofservice *ofservice;
1295 struct ofconn *ofconn;
1298 dpif_recv_wait(p->dpif);
1299 dpif_port_poll_wait(p->dpif);
1300 netdev_monitor_poll_wait(p->netdev_monitor);
1301 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
1302 ofconn_wait(ofconn);
1305 poll_timer_wait_until(p->next_in_band_update);
1306 in_band_wait(p->in_band);
1309 fail_open_wait(p->fail_open);
1312 ofproto_sflow_wait(p->sflow);
1314 if (!tag_set_is_empty(&p->revalidate_set)) {
1315 poll_immediate_wake();
1317 if (p->need_revalidate) {
1318 /* Shouldn't happen, but if it does just go around again. */
1319 VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1320 poll_immediate_wake();
1321 } else if (p->next_expiration != LLONG_MAX) {
1322 poll_timer_wait_until(p->next_expiration);
1324 HMAP_FOR_EACH (ofservice, node, &p->services) {
1325 pvconn_wait(ofservice->pvconn);
1327 for (i = 0; i < p->n_snoops; i++) {
1328 pvconn_wait(p->snoops[i]);
1333 ofproto_revalidate(struct ofproto *ofproto, tag_type tag)
1335 tag_set_add(&ofproto->revalidate_set, tag);
1339 ofproto_get_revalidate_set(struct ofproto *ofproto)
1341 return &ofproto->revalidate_set;
1345 ofproto_is_alive(const struct ofproto *p)
1347 return !hmap_is_empty(&p->controllers);
1351 ofproto_get_ofproto_controller_info(const struct ofproto * ofproto,
1354 const struct ofconn *ofconn;
1358 HMAP_FOR_EACH (ofconn, hmap_node, &ofproto->controllers) {
1359 const struct rconn *rconn = ofconn->rconn;
1360 const int last_error = rconn_get_last_error(rconn);
1361 struct ofproto_controller_info *cinfo = xmalloc(sizeof *cinfo);
1363 shash_add(info, rconn_get_target(rconn), cinfo);
1365 cinfo->is_connected = rconn_is_connected(rconn);
1366 cinfo->role = ofconn->role;
1370 if (last_error == EOF) {
1371 cinfo->pairs.keys[cinfo->pairs.n] = "last_error";
1372 cinfo->pairs.values[cinfo->pairs.n++] = xstrdup("End of file");
1373 } else if (last_error > 0) {
1374 cinfo->pairs.keys[cinfo->pairs.n] = "last_error";
1375 cinfo->pairs.values[cinfo->pairs.n++] =
1376 xstrdup(strerror(last_error));
1379 cinfo->pairs.keys[cinfo->pairs.n] = "state";
1380 cinfo->pairs.values[cinfo->pairs.n++] =
1381 xstrdup(rconn_get_state(rconn));
1383 cinfo->pairs.keys[cinfo->pairs.n] = "time_in_state";
1384 cinfo->pairs.values[cinfo->pairs.n++] =
1385 xasprintf("%u", rconn_get_state_elapsed(rconn));
1390 ofproto_free_ofproto_controller_info(struct shash *info)
1392 struct shash_node *node;
1394 SHASH_FOR_EACH (node, info) {
1395 struct ofproto_controller_info *cinfo = node->data;
1396 while (cinfo->pairs.n) {
1397 free((char *) cinfo->pairs.values[--cinfo->pairs.n]);
1401 shash_destroy(info);
1404 /* Deletes port number 'odp_port' from the datapath for 'ofproto'.
1406 * This is almost the same as calling dpif_port_del() directly on the
1407 * datapath, but it also makes 'ofproto' close its open netdev for the port
1408 * (if any). This makes it possible to create a new netdev of a different
1409 * type under the same name, which otherwise the netdev library would refuse
1410 * to do because of the conflict. (The netdev would eventually get closed on
1411 * the next trip through ofproto_run(), but this interface is more direct.)
1413 * Returns 0 if successful, otherwise a positive errno. */
1415 ofproto_port_del(struct ofproto *ofproto, uint16_t odp_port)
1417 struct ofport *ofport = get_port(ofproto, odp_port);
1418 const char *name = ofport ? ofport->opp.name : "<unknown>";
1421 error = dpif_port_del(ofproto->dpif, odp_port);
1423 VLOG_ERR("%s: failed to remove port %"PRIu16" (%s) interface (%s)",
1424 dpif_name(ofproto->dpif), odp_port, name, strerror(error));
1425 } else if (ofport) {
1426 /* 'name' is ofport->opp.name and update_port() is going to destroy
1427 * 'ofport'. Just in case update_port() refers to 'name' after it
1428 * destroys 'ofport', make a copy of it around the update_port()
1430 char *devname = xstrdup(name);
1431 update_port(ofproto, devname);
1437 /* Checks if 'ofproto' thinks 'odp_port' should be included in floods. Returns
1438 * true if 'odp_port' exists and should be included, false otherwise. */
1440 ofproto_port_is_floodable(struct ofproto *ofproto, uint16_t odp_port)
1442 struct ofport *ofport = get_port(ofproto, odp_port);
1443 return ofport && !(ofport->opp.config & OFPPC_NO_FLOOD);
1447 ofproto_send_packet(struct ofproto *p, const struct flow *flow,
1448 const union ofp_action *actions, size_t n_actions,
1449 const struct ofpbuf *packet)
1451 struct action_xlate_ctx ctx;
1452 struct ofpbuf *odp_actions;
1454 action_xlate_ctx_init(&ctx, p, flow, packet);
1455 odp_actions = xlate_actions(&ctx, actions, n_actions);
1457 /* XXX Should we translate the dpif_execute() errno value into an OpenFlow
1459 dpif_execute(p->dpif, odp_actions->data, odp_actions->size, packet);
1461 ofpbuf_delete(odp_actions);
1466 /* Adds a flow to the OpenFlow flow table in 'p' that matches 'cls_rule' and
1467 * performs the 'n_actions' actions in 'actions'. The new flow will not
1470 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1471 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1472 * controllers; otherwise, it will be hidden.
1474 * The caller retains ownership of 'cls_rule' and 'actions'. */
1476 ofproto_add_flow(struct ofproto *p, const struct cls_rule *cls_rule,
1477 const union ofp_action *actions, size_t n_actions)
1480 rule = rule_create(cls_rule, actions, n_actions, 0, 0, 0, false);
1481 rule_insert(p, rule);
1485 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
1489 rule = rule_from_cls_rule(classifier_find_rule_exactly(&ofproto->cls,
1492 rule_remove(ofproto, rule);
1497 ofproto_flush_flows(struct ofproto *ofproto)
1499 struct facet *facet, *next_facet;
1500 struct rule *rule, *next_rule;
1501 struct cls_cursor cursor;
1503 COVERAGE_INC(ofproto_flush);
1505 HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
1506 /* Mark the facet as not installed so that facet_remove() doesn't
1507 * bother trying to uninstall it. There is no point in uninstalling it
1508 * individually since we are about to blow away all the facets with
1509 * dpif_flow_flush(). */
1510 facet->installed = false;
1511 facet_remove(ofproto, facet);
1514 cls_cursor_init(&cursor, &ofproto->cls, NULL);
1515 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1516 rule_remove(ofproto, rule);
1519 dpif_flow_flush(ofproto->dpif);
1520 if (ofproto->in_band) {
1521 in_band_flushed(ofproto->in_band);
1523 if (ofproto->fail_open) {
1524 fail_open_flushed(ofproto->fail_open);
1529 reinit_ports(struct ofproto *p)
1531 struct dpif_port_dump dump;
1532 struct shash_node *node;
1533 struct shash devnames;
1534 struct ofport *ofport;
1535 struct dpif_port dpif_port;
1537 COVERAGE_INC(ofproto_reinit_ports);
1539 shash_init(&devnames);
1540 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1541 shash_add_once (&devnames, ofport->opp.name, NULL);
1543 DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
1544 shash_add_once (&devnames, dpif_port.name, NULL);
1547 SHASH_FOR_EACH (node, &devnames) {
1548 update_port(p, node->name);
1550 shash_destroy(&devnames);
1553 static struct ofport *
1554 make_ofport(const struct dpif_port *dpif_port)
1556 struct netdev_options netdev_options;
1557 enum netdev_flags flags;
1558 struct ofport *ofport;
1559 struct netdev *netdev;
1562 memset(&netdev_options, 0, sizeof netdev_options);
1563 netdev_options.name = dpif_port->name;
1564 netdev_options.type = dpif_port->type;
1565 netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
1567 error = netdev_open(&netdev_options, &netdev);
1569 VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1570 "cannot be opened (%s)",
1571 dpif_port->name, dpif_port->port_no,
1572 dpif_port->name, strerror(error));
1576 ofport = xmalloc(sizeof *ofport);
1577 ofport->netdev = netdev;
1578 ofport->odp_port = dpif_port->port_no;
1579 ofport->opp.port_no = odp_port_to_ofp_port(dpif_port->port_no);
1580 netdev_get_etheraddr(netdev, ofport->opp.hw_addr);
1581 ovs_strlcpy(ofport->opp.name, dpif_port->name, sizeof ofport->opp.name);
1583 netdev_get_flags(netdev, &flags);
1584 ofport->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
1586 ofport->opp.state = netdev_get_carrier(netdev) ? 0 : OFPPS_LINK_DOWN;
1588 netdev_get_features(netdev,
1589 &ofport->opp.curr, &ofport->opp.advertised,
1590 &ofport->opp.supported, &ofport->opp.peer);
1595 ofport_conflicts(const struct ofproto *p, const struct dpif_port *dpif_port)
1597 if (get_port(p, dpif_port->port_no)) {
1598 VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1599 dpif_port->port_no);
1601 } else if (shash_find(&p->port_by_name, dpif_port->name)) {
1602 VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1611 ofport_equal(const struct ofport *a_, const struct ofport *b_)
1613 const struct ofp_phy_port *a = &a_->opp;
1614 const struct ofp_phy_port *b = &b_->opp;
1616 BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1617 return (a->port_no == b->port_no
1618 && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1619 && !strcmp(a->name, b->name)
1620 && a->state == b->state
1621 && a->config == b->config
1622 && a->curr == b->curr
1623 && a->advertised == b->advertised
1624 && a->supported == b->supported
1625 && a->peer == b->peer);
1629 send_port_status(struct ofproto *p, const struct ofport *ofport,
1632 /* XXX Should limit the number of queued port status change messages. */
1633 struct ofconn *ofconn;
1634 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
1635 struct ofp_port_status *ops;
1638 /* Primary controllers, even slaves, should always get port status
1639 updates. Otherwise obey ofconn_receives_async_msgs(). */
1640 if (ofconn->type != OFCONN_PRIMARY
1641 && !ofconn_receives_async_msgs(ofconn)) {
1645 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
1646 ops->reason = reason;
1647 ops->desc = ofport->opp;
1648 hton_ofp_phy_port(&ops->desc);
1649 queue_tx(b, ofconn, NULL);
1654 ofport_install(struct ofproto *p, struct ofport *ofport)
1656 const char *netdev_name = ofport->opp.name;
1658 netdev_monitor_add(p->netdev_monitor, ofport->netdev);
1659 hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->odp_port, 0));
1660 shash_add(&p->port_by_name, netdev_name, ofport);
1662 ofproto_sflow_add_port(p->sflow, ofport->odp_port, netdev_name);
1667 ofport_remove(struct ofproto *p, struct ofport *ofport)
1669 netdev_monitor_remove(p->netdev_monitor, ofport->netdev);
1670 hmap_remove(&p->ports, &ofport->hmap_node);
1671 shash_delete(&p->port_by_name,
1672 shash_find(&p->port_by_name, ofport->opp.name));
1674 ofproto_sflow_del_port(p->sflow, ofport->odp_port);
1679 ofport_free(struct ofport *ofport)
1682 netdev_close(ofport->netdev);
1687 static struct ofport *
1688 get_port(const struct ofproto *ofproto, uint16_t odp_port)
1690 struct ofport *port;
1692 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1693 hash_int(odp_port, 0), &ofproto->ports) {
1694 if (port->odp_port == odp_port) {
1702 update_port(struct ofproto *p, const char *devname)
1704 struct dpif_port dpif_port;
1705 struct ofport *old_ofport;
1706 struct ofport *new_ofport;
1709 COVERAGE_INC(ofproto_update_port);
1711 /* Query the datapath for port information. */
1712 error = dpif_port_query_by_name(p->dpif, devname, &dpif_port);
1714 /* Find the old ofport. */
1715 old_ofport = shash_find_data(&p->port_by_name, devname);
1718 /* There's no port named 'devname' but there might be a port with
1719 * the same port number. This could happen if a port is deleted
1720 * and then a new one added in its place very quickly, or if a port
1721 * is renamed. In the former case we want to send an OFPPR_DELETE
1722 * and an OFPPR_ADD, and in the latter case we want to send a
1723 * single OFPPR_MODIFY. We can distinguish the cases by comparing
1724 * the old port's ifindex against the new port, or perhaps less
1725 * reliably but more portably by comparing the old port's MAC
1726 * against the new port's MAC. However, this code isn't that smart
1727 * and always sends an OFPPR_MODIFY (XXX). */
1728 old_ofport = get_port(p, dpif_port.port_no);
1730 } else if (error != ENOENT && error != ENODEV) {
1731 VLOG_WARN_RL(&rl, "dpif_port_query_by_name returned unexpected error "
1732 "%s", strerror(error));
1736 /* Create a new ofport. */
1737 new_ofport = !error ? make_ofport(&dpif_port) : NULL;
1739 /* Eliminate a few pathological cases. */
1740 if (!old_ofport && !new_ofport) {
1742 } else if (old_ofport && new_ofport) {
1743 /* Most of the 'config' bits are OpenFlow soft state, but
1744 * OFPPC_PORT_DOWN is maintained by the kernel. So transfer the
1745 * OpenFlow bits from old_ofport. (make_ofport() only sets
1746 * OFPPC_PORT_DOWN and leaves the other bits 0.) */
1747 new_ofport->opp.config |= old_ofport->opp.config & ~OFPPC_PORT_DOWN;
1749 if (ofport_equal(old_ofport, new_ofport)) {
1750 /* False alarm--no change. */
1751 ofport_free(new_ofport);
1756 /* Now deal with the normal cases. */
1758 ofport_remove(p, old_ofport);
1761 ofport_install(p, new_ofport);
1763 send_port_status(p, new_ofport ? new_ofport : old_ofport,
1764 (!old_ofport ? OFPPR_ADD
1765 : !new_ofport ? OFPPR_DELETE
1767 ofport_free(old_ofport);
1770 dpif_port_destroy(&dpif_port);
1774 init_ports(struct ofproto *p)
1776 struct dpif_port_dump dump;
1777 struct dpif_port dpif_port;
1779 DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
1780 if (!ofport_conflicts(p, &dpif_port)) {
1781 struct ofport *ofport = make_ofport(&dpif_port);
1783 ofport_install(p, ofport);
1791 static struct ofconn *
1792 ofconn_create(struct ofproto *p, struct rconn *rconn, enum ofconn_type type)
1794 struct ofconn *ofconn = xzalloc(sizeof *ofconn);
1795 ofconn->ofproto = p;
1796 list_push_back(&p->all_conns, &ofconn->node);
1797 ofconn->rconn = rconn;
1798 ofconn->type = type;
1799 ofconn->flow_format = NXFF_OPENFLOW10;
1800 ofconn->role = NX_ROLE_OTHER;
1801 ofconn->packet_in_counter = rconn_packet_counter_create ();
1802 ofconn->pktbuf = NULL;
1803 ofconn->miss_send_len = 0;
1804 ofconn->reply_counter = rconn_packet_counter_create ();
1809 ofconn_destroy(struct ofconn *ofconn)
1811 if (ofconn->type == OFCONN_PRIMARY) {
1812 hmap_remove(&ofconn->ofproto->controllers, &ofconn->hmap_node);
1814 discovery_destroy(ofconn->discovery);
1816 list_remove(&ofconn->node);
1817 switch_status_unregister(ofconn->ss);
1818 rconn_destroy(ofconn->rconn);
1819 rconn_packet_counter_destroy(ofconn->packet_in_counter);
1820 rconn_packet_counter_destroy(ofconn->reply_counter);
1821 pktbuf_destroy(ofconn->pktbuf);
1826 ofconn_run(struct ofconn *ofconn)
1828 struct ofproto *p = ofconn->ofproto;
1832 if (ofconn->discovery) {
1833 char *controller_name;
1834 if (rconn_is_connectivity_questionable(ofconn->rconn)) {
1835 discovery_question_connectivity(ofconn->discovery);
1837 if (discovery_run(ofconn->discovery, &controller_name)) {
1838 if (controller_name) {
1839 char *ofconn_name = ofconn_make_name(p, controller_name);
1840 rconn_connect(ofconn->rconn, controller_name, ofconn_name);
1843 rconn_disconnect(ofconn->rconn);
1848 for (i = 0; i < N_SCHEDULERS; i++) {
1849 pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
1852 rconn_run(ofconn->rconn);
1854 if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1855 /* Limit the number of iterations to prevent other tasks from
1857 for (iteration = 0; iteration < 50; iteration++) {
1858 struct ofpbuf *of_msg = rconn_recv(ofconn->rconn);
1863 fail_open_maybe_recover(p->fail_open);
1865 handle_openflow(ofconn, of_msg);
1866 ofpbuf_delete(of_msg);
1870 if (!ofconn->discovery && !rconn_is_alive(ofconn->rconn)) {
1871 ofconn_destroy(ofconn);
1876 ofconn_wait(struct ofconn *ofconn)
1880 if (ofconn->discovery) {
1881 discovery_wait(ofconn->discovery);
1883 for (i = 0; i < N_SCHEDULERS; i++) {
1884 pinsched_wait(ofconn->schedulers[i]);
1886 rconn_run_wait(ofconn->rconn);
1887 if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1888 rconn_recv_wait(ofconn->rconn);
1890 COVERAGE_INC(ofproto_ofconn_stuck);
1894 /* Returns true if 'ofconn' should receive asynchronous messages. */
1896 ofconn_receives_async_msgs(const struct ofconn *ofconn)
1898 if (ofconn->type == OFCONN_PRIMARY) {
1899 /* Primary controllers always get asynchronous messages unless they
1900 * have configured themselves as "slaves". */
1901 return ofconn->role != NX_ROLE_SLAVE;
1903 /* Service connections don't get asynchronous messages unless they have
1904 * explicitly asked for them by setting a nonzero miss send length. */
1905 return ofconn->miss_send_len > 0;
1909 /* Returns a human-readable name for an OpenFlow connection between 'ofproto'
1910 * and 'target', suitable for use in log messages for identifying the
1913 * The name is dynamically allocated. The caller should free it (with free())
1914 * when it is no longer needed. */
1916 ofconn_make_name(const struct ofproto *ofproto, const char *target)
1918 return xasprintf("%s<->%s", dpif_base_name(ofproto->dpif), target);
1922 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1926 for (i = 0; i < N_SCHEDULERS; i++) {
1927 struct pinsched **s = &ofconn->schedulers[i];
1931 *s = pinsched_create(rate, burst,
1932 ofconn->ofproto->switch_status);
1934 pinsched_set_limits(*s, rate, burst);
1937 pinsched_destroy(*s);
1944 ofservice_reconfigure(struct ofservice *ofservice,
1945 const struct ofproto_controller *c)
1947 ofservice->probe_interval = c->probe_interval;
1948 ofservice->rate_limit = c->rate_limit;
1949 ofservice->burst_limit = c->burst_limit;
1952 /* Creates a new ofservice in 'ofproto'. Returns 0 if successful, otherwise a
1953 * positive errno value. */
1955 ofservice_create(struct ofproto *ofproto, const struct ofproto_controller *c)
1957 struct ofservice *ofservice;
1958 struct pvconn *pvconn;
1961 error = pvconn_open(c->target, &pvconn);
1966 ofservice = xzalloc(sizeof *ofservice);
1967 hmap_insert(&ofproto->services, &ofservice->node,
1968 hash_string(c->target, 0));
1969 ofservice->pvconn = pvconn;
1971 ofservice_reconfigure(ofservice, c);
1977 ofservice_destroy(struct ofproto *ofproto, struct ofservice *ofservice)
1979 hmap_remove(&ofproto->services, &ofservice->node);
1980 pvconn_close(ofservice->pvconn);
1984 /* Finds and returns the ofservice within 'ofproto' that has the given
1985 * 'target', or a null pointer if none exists. */
1986 static struct ofservice *
1987 ofservice_lookup(struct ofproto *ofproto, const char *target)
1989 struct ofservice *ofservice;
1991 HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
1992 &ofproto->services) {
1993 if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
2000 /* Returns true if 'rule' should be hidden from the controller.
2002 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2003 * (e.g. by in-band control) and are intentionally hidden from the
2006 rule_is_hidden(const struct rule *rule)
2008 return rule->cr.priority > UINT16_MAX;
2011 /* Creates and returns a new rule initialized as specified.
2013 * The caller is responsible for inserting the rule into the classifier (with
2014 * rule_insert()). */
2015 static struct rule *
2016 rule_create(const struct cls_rule *cls_rule,
2017 const union ofp_action *actions, size_t n_actions,
2018 uint16_t idle_timeout, uint16_t hard_timeout,
2019 ovs_be64 flow_cookie, bool send_flow_removed)
2021 struct rule *rule = xzalloc(sizeof *rule);
2022 rule->cr = *cls_rule;
2023 rule->idle_timeout = idle_timeout;
2024 rule->hard_timeout = hard_timeout;
2025 rule->flow_cookie = flow_cookie;
2026 rule->used = rule->created = time_msec();
2027 rule->send_flow_removed = send_flow_removed;
2028 list_init(&rule->facets);
2029 if (n_actions > 0) {
2030 rule->n_actions = n_actions;
2031 rule->actions = xmemdup(actions, n_actions * sizeof *actions);
2037 static struct rule *
2038 rule_from_cls_rule(const struct cls_rule *cls_rule)
2040 return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
2044 rule_free(struct rule *rule)
2046 free(rule->actions);
2050 /* Destroys 'rule' and iterates through all of its facets and revalidates them,
2051 * destroying any that no longer has a rule (which is probably all of them).
2053 * The caller must have already removed 'rule' from the classifier. */
2055 rule_destroy(struct ofproto *ofproto, struct rule *rule)
2057 struct facet *facet, *next_facet;
2058 LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2059 facet_revalidate(ofproto, facet);
2064 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2065 * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
2068 rule_has_out_port(const struct rule *rule, ovs_be16 out_port)
2070 const union ofp_action *oa;
2071 struct actions_iterator i;
2073 if (out_port == htons(OFPP_NONE)) {
2076 for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
2077 oa = actions_next(&i)) {
2078 if (action_outputs_to_port(oa, out_port)) {
2085 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2086 * 'packet', which arrived on 'in_port'.
2088 * Takes ownership of 'packet'. */
2090 execute_odp_actions(struct ofproto *ofproto, const struct flow *flow,
2091 const struct nlattr *odp_actions, size_t actions_len,
2092 struct ofpbuf *packet)
2094 if (actions_len == NLA_ALIGN(NLA_HDRLEN + sizeof(uint64_t))
2095 && odp_actions->nla_type == ODPAT_CONTROLLER) {
2096 /* As an optimization, avoid a round-trip from userspace to kernel to
2097 * userspace. This also avoids possibly filling up kernel packet
2098 * buffers along the way. */
2099 struct dpif_upcall upcall;
2101 upcall.type = _ODPL_ACTION_NR;
2102 upcall.packet = packet;
2105 upcall.userdata = nl_attr_get_u64(odp_actions);
2106 upcall.sample_pool = 0;
2107 upcall.actions = NULL;
2108 upcall.actions_len = 0;
2110 send_packet_in(ofproto, &upcall, flow, false);
2116 error = dpif_execute(ofproto->dpif, odp_actions, actions_len, packet);
2117 ofpbuf_delete(packet);
2122 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2123 * statistics appropriately. 'packet' must have at least sizeof(struct
2124 * ofp_packet_in) bytes of headroom.
2126 * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2127 * applying flow_extract() to 'packet' would yield the same flow as
2130 * 'facet' must have accurately composed ODP actions; that is, it must not be
2131 * in need of revalidation.
2133 * Takes ownership of 'packet'. */
2135 facet_execute(struct ofproto *ofproto, struct facet *facet,
2136 struct ofpbuf *packet)
2138 struct odp_flow_stats stats;
2140 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2142 flow_extract_stats(&facet->flow, packet, &stats);
2143 if (execute_odp_actions(ofproto, &facet->flow,
2144 facet->actions, facet->actions_len, packet)) {
2145 facet_update_stats(ofproto, facet, &stats);
2146 facet->used = time_msec();
2147 netflow_flow_update_time(ofproto->netflow,
2148 &facet->nf_flow, facet->used);
2152 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2153 * statistics (or the statistics for one of its facets) appropriately.
2154 * 'packet' must have at least sizeof(struct ofp_packet_in) bytes of headroom.
2156 * 'packet' doesn't necessarily have to match 'rule'. 'rule' will be credited
2157 * with statistics for 'packet' either way.
2159 * Takes ownership of 'packet'. */
2161 rule_execute(struct ofproto *ofproto, struct rule *rule, uint16_t in_port,
2162 struct ofpbuf *packet)
2164 struct action_xlate_ctx ctx;
2165 struct ofpbuf *odp_actions;
2166 struct facet *facet;
2170 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2172 flow_extract(packet, 0, in_port, &flow);
2174 /* First look for a related facet. If we find one, account it to that. */
2175 facet = facet_lookup_valid(ofproto, &flow);
2176 if (facet && facet->rule == rule) {
2177 facet_execute(ofproto, facet, packet);
2181 /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
2182 * create a new facet for it and use that. */
2183 if (rule_lookup(ofproto, &flow) == rule) {
2184 facet = facet_create(ofproto, rule, &flow, packet);
2185 facet_execute(ofproto, facet, packet);
2186 facet_install(ofproto, facet, true);
2190 /* We can't account anything to a facet. If we were to try, then that
2191 * facet would have a non-matching rule, busting our invariants. */
2192 action_xlate_ctx_init(&ctx, ofproto, &flow, packet);
2193 odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
2194 size = packet->size;
2195 if (execute_odp_actions(ofproto, &flow, odp_actions->data,
2196 odp_actions->size, packet)) {
2197 rule->used = time_msec();
2198 rule->packet_count++;
2199 rule->byte_count += size;
2201 ofpbuf_delete(odp_actions);
2204 /* Inserts 'rule' into 'p''s flow table. */
2206 rule_insert(struct ofproto *p, struct rule *rule)
2208 struct rule *displaced_rule;
2210 displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
2211 if (displaced_rule) {
2212 rule_destroy(p, displaced_rule);
2214 p->need_revalidate = true;
2217 /* Creates and returns a new facet within 'ofproto' owned by 'rule', given a
2218 * 'flow' and an example 'packet' within that flow.
2220 * The caller must already have determined that no facet with an identical
2221 * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2222 * 'ofproto''s classifier table. */
2223 static struct facet *
2224 facet_create(struct ofproto *ofproto, struct rule *rule,
2225 const struct flow *flow, const struct ofpbuf *packet)
2227 struct facet *facet;
2229 facet = xzalloc(sizeof *facet);
2230 facet->used = time_msec();
2231 hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2232 list_push_back(&rule->facets, &facet->list_node);
2234 facet->flow = *flow;
2235 netflow_flow_init(&facet->nf_flow);
2236 netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2238 facet_make_actions(ofproto, facet, packet);
2244 facet_free(struct facet *facet)
2246 free(facet->actions);
2250 /* Remove 'rule' from 'ofproto' and free up the associated memory:
2252 * - Removes 'rule' from the classifier.
2254 * - If 'rule' has facets, revalidates them (and possibly uninstalls and
2255 * destroys them), via rule_destroy().
2258 rule_remove(struct ofproto *ofproto, struct rule *rule)
2260 COVERAGE_INC(ofproto_del_rule);
2261 ofproto->need_revalidate = true;
2262 classifier_remove(&ofproto->cls, &rule->cr);
2263 rule_destroy(ofproto, rule);
2266 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2268 * - If 'facet' was installed in the datapath, uninstalls it and updates its
2269 * rule's statistics, via facet_uninstall().
2271 * - Removes 'facet' from its rule and from ofproto->facets.
2274 facet_remove(struct ofproto *ofproto, struct facet *facet)
2276 facet_uninstall(ofproto, facet);
2277 facet_flush_stats(ofproto, facet);
2278 hmap_remove(&ofproto->facets, &facet->hmap_node);
2279 list_remove(&facet->list_node);
2283 /* Composes the ODP actions for 'facet' based on its rule's actions. */
2285 facet_make_actions(struct ofproto *p, struct facet *facet,
2286 const struct ofpbuf *packet)
2288 const struct rule *rule = facet->rule;
2289 struct ofpbuf *odp_actions;
2290 struct action_xlate_ctx ctx;
2292 action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2293 odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
2294 facet->tags = ctx.tags;
2295 facet->may_install = ctx.may_set_up_flow;
2296 facet->nf_flow.output_iface = ctx.nf_output_iface;
2298 if (facet->actions_len != odp_actions->size
2299 || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2300 free(facet->actions);
2301 facet->actions_len = odp_actions->size;
2302 facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2305 ofpbuf_delete(odp_actions);
2309 facet_put__(struct ofproto *ofproto, struct facet *facet, int flags)
2311 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2314 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2315 odp_flow_key_from_flow(&key, &facet->flow);
2316 assert(key.base == keybuf);
2318 return dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
2319 facet->actions, facet->actions_len, NULL);
2322 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath. If
2323 * 'zero_stats' is true, clears any existing statistics from the datapath for
2326 facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
2328 if (facet->may_install) {
2329 int flags = ODPPF_CREATE | ODPPF_MODIFY;
2331 flags |= ODPPF_ZERO_STATS;
2333 if (!facet_put__(p, facet, flags)) {
2334 facet->installed = true;
2339 /* Ensures that the bytes in 'facet', plus 'extra_bytes', have been passed up
2340 * to the accounting hook function in the ofhooks structure. */
2342 facet_account(struct ofproto *ofproto,
2343 struct facet *facet, uint64_t extra_bytes)
2345 uint64_t total_bytes = facet->byte_count + extra_bytes;
2347 if (ofproto->ofhooks->account_flow_cb
2348 && total_bytes > facet->accounted_bytes)
2350 ofproto->ofhooks->account_flow_cb(
2351 &facet->flow, facet->tags, facet->actions, facet->actions_len,
2352 total_bytes - facet->accounted_bytes, ofproto->aux);
2353 facet->accounted_bytes = total_bytes;
2357 /* If 'rule' is installed in the datapath, uninstalls it. */
2359 facet_uninstall(struct ofproto *p, struct facet *facet)
2361 if (facet->installed) {
2362 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2363 struct odp_flow_stats stats;
2366 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2367 odp_flow_key_from_flow(&key, &facet->flow);
2368 assert(key.base == keybuf);
2370 if (!dpif_flow_del(p->dpif, key.data, key.size, &stats)) {
2371 facet_update_stats(p, facet, &stats);
2373 facet->installed = false;
2377 /* Returns true if the only action for 'facet' is to send to the controller.
2378 * (We don't report NetFlow expiration messages for such facets because they
2379 * are just part of the control logic for the network, not real traffic). */
2381 facet_is_controller_flow(struct facet *facet)
2384 && facet->rule->n_actions == 1
2385 && action_outputs_to_port(&facet->rule->actions[0],
2386 htons(OFPP_CONTROLLER)));
2389 /* Folds all of 'facet''s statistics into its rule. Also updates the
2390 * accounting ofhook and emits a NetFlow expiration if appropriate. */
2392 facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
2394 facet_account(ofproto, facet, 0);
2396 if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2397 struct ofexpired expired;
2398 expired.flow = facet->flow;
2399 expired.packet_count = facet->packet_count;
2400 expired.byte_count = facet->byte_count;
2401 expired.used = facet->used;
2402 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2405 facet->rule->packet_count += facet->packet_count;
2406 facet->rule->byte_count += facet->byte_count;
2408 /* Reset counters to prevent double counting if 'facet' ever gets
2410 facet->packet_count = 0;
2411 facet->byte_count = 0;
2412 facet->accounted_bytes = 0;
2414 netflow_flow_clear(&facet->nf_flow);
2417 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2418 * Returns it if found, otherwise a null pointer.
2420 * The returned facet might need revalidation; use facet_lookup_valid()
2421 * instead if that is important. */
2422 static struct facet *
2423 facet_find(struct ofproto *ofproto, const struct flow *flow)
2425 struct facet *facet;
2427 HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2429 if (flow_equal(flow, &facet->flow)) {
2437 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2438 * Returns it if found, otherwise a null pointer.
2440 * The returned facet is guaranteed to be valid. */
2441 static struct facet *
2442 facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
2444 struct facet *facet = facet_find(ofproto, flow);
2446 /* The facet we found might not be valid, since we could be in need of
2447 * revalidation. If it is not valid, don't return it. */
2449 && ofproto->need_revalidate
2450 && !facet_revalidate(ofproto, facet)) {
2451 COVERAGE_INC(ofproto_invalidated);
2458 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2460 * - If the rule found is different from 'facet''s current rule, moves
2461 * 'facet' to the new rule and recompiles its actions.
2463 * - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2464 * where it is and recompiles its actions anyway.
2466 * - If there is none, destroys 'facet'.
2468 * Returns true if 'facet' still exists, false if it has been destroyed. */
2470 facet_revalidate(struct ofproto *ofproto, struct facet *facet)
2472 struct action_xlate_ctx ctx;
2473 struct ofpbuf *odp_actions;
2474 struct rule *new_rule;
2475 bool actions_changed;
2477 COVERAGE_INC(facet_revalidate);
2479 /* Determine the new rule. */
2480 new_rule = rule_lookup(ofproto, &facet->flow);
2482 /* No new rule, so delete the facet. */
2483 facet_remove(ofproto, facet);
2487 /* Calculate new ODP actions.
2489 * We do not modify any 'facet' state yet, because we might need to, e.g.,
2490 * emit a NetFlow expiration and, if so, we need to have the old state
2491 * around to properly compose it. */
2492 action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2493 odp_actions = xlate_actions(&ctx, new_rule->actions, new_rule->n_actions);
2494 actions_changed = (facet->actions_len != odp_actions->size
2495 || memcmp(facet->actions, odp_actions->data,
2496 facet->actions_len));
2498 /* If the ODP actions changed or the installability changed, then we need
2499 * to talk to the datapath. */
2500 if (actions_changed || facet->may_install != facet->installed) {
2501 if (facet->may_install) {
2502 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2503 struct odp_flow_stats stats;
2506 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2507 odp_flow_key_from_flow(&key, &facet->flow);
2509 dpif_flow_put(ofproto->dpif,
2510 ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS,
2512 odp_actions->data, odp_actions->size, &stats);
2514 facet_update_stats(ofproto, facet, &stats);
2516 facet_uninstall(ofproto, facet);
2519 /* The datapath flow is gone or has zeroed stats, so push stats out of
2520 * 'facet' into 'rule'. */
2521 facet_flush_stats(ofproto, facet);
2524 /* Update 'facet' now that we've taken care of all the old state. */
2525 facet->tags = ctx.tags;
2526 facet->nf_flow.output_iface = ctx.nf_output_iface;
2527 facet->may_install = ctx.may_set_up_flow;
2528 if (actions_changed) {
2529 free(facet->actions);
2530 facet->actions_len = odp_actions->size;
2531 facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2533 if (facet->rule != new_rule) {
2534 COVERAGE_INC(facet_changed_rule);
2535 list_remove(&facet->list_node);
2536 list_push_back(&new_rule->facets, &facet->list_node);
2537 facet->rule = new_rule;
2538 facet->used = new_rule->created;
2541 ofpbuf_delete(odp_actions);
2547 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
2548 struct rconn_packet_counter *counter)
2550 update_openflow_length(msg);
2551 if (rconn_send(ofconn->rconn, msg, counter)) {
2557 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
2560 struct ofpbuf *buf = ofputil_encode_error_msg(error, oh);
2562 COVERAGE_INC(ofproto_error);
2563 queue_tx(buf, ofconn, ofconn->reply_counter);
2568 hton_ofp_phy_port(struct ofp_phy_port *opp)
2570 opp->port_no = htons(opp->port_no);
2571 opp->config = htonl(opp->config);
2572 opp->state = htonl(opp->state);
2573 opp->curr = htonl(opp->curr);
2574 opp->advertised = htonl(opp->advertised);
2575 opp->supported = htonl(opp->supported);
2576 opp->peer = htonl(opp->peer);
2580 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2582 queue_tx(make_echo_reply(oh), ofconn, ofconn->reply_counter);
2587 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2589 struct ofp_switch_features *osf;
2591 struct ofport *port;
2593 osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
2594 osf->datapath_id = htonll(ofconn->ofproto->datapath_id);
2595 osf->n_buffers = htonl(pktbuf_capacity());
2597 osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
2598 OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
2599 osf->actions = htonl((1u << OFPAT_OUTPUT) |
2600 (1u << OFPAT_SET_VLAN_VID) |
2601 (1u << OFPAT_SET_VLAN_PCP) |
2602 (1u << OFPAT_STRIP_VLAN) |
2603 (1u << OFPAT_SET_DL_SRC) |
2604 (1u << OFPAT_SET_DL_DST) |
2605 (1u << OFPAT_SET_NW_SRC) |
2606 (1u << OFPAT_SET_NW_DST) |
2607 (1u << OFPAT_SET_NW_TOS) |
2608 (1u << OFPAT_SET_TP_SRC) |
2609 (1u << OFPAT_SET_TP_DST) |
2610 (1u << OFPAT_ENQUEUE));
2612 HMAP_FOR_EACH (port, hmap_node, &ofconn->ofproto->ports) {
2613 hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
2616 queue_tx(buf, ofconn, ofconn->reply_counter);
2621 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2624 struct ofp_switch_config *osc;
2628 /* Figure out flags. */
2629 dpif_get_drop_frags(ofconn->ofproto->dpif, &drop_frags);
2630 flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
2633 osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
2634 osc->flags = htons(flags);
2635 osc->miss_send_len = htons(ofconn->miss_send_len);
2636 queue_tx(buf, ofconn, ofconn->reply_counter);
2642 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
2644 uint16_t flags = ntohs(osc->flags);
2646 if (ofconn->type == OFCONN_PRIMARY && ofconn->role != NX_ROLE_SLAVE) {
2647 switch (flags & OFPC_FRAG_MASK) {
2648 case OFPC_FRAG_NORMAL:
2649 dpif_set_drop_frags(ofconn->ofproto->dpif, false);
2651 case OFPC_FRAG_DROP:
2652 dpif_set_drop_frags(ofconn->ofproto->dpif, true);
2655 VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
2661 ofconn->miss_send_len = ntohs(osc->miss_send_len);
2666 /* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
2667 * flow translation. */
2668 #define MAX_RESUBMIT_RECURSION 16
2670 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2671 struct action_xlate_ctx *ctx);
2674 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
2676 const struct ofport *ofport = get_port(ctx->ofproto, port);
2679 if (ofport->opp.config & OFPPC_NO_FWD) {
2680 /* Forwarding disabled on port. */
2685 * We don't have an ofport record for this port, but it doesn't hurt to
2686 * allow forwarding to it anyhow. Maybe such a port will appear later
2687 * and we're pre-populating the flow table.
2691 nl_msg_put_u32(ctx->odp_actions, ODPAT_OUTPUT, port);
2692 ctx->nf_output_iface = port;
2695 static struct rule *
2696 rule_lookup(struct ofproto *ofproto, const struct flow *flow)
2698 return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
2702 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2704 if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2705 uint16_t old_in_port;
2708 /* Look up a flow with 'in_port' as the input port. Then restore the
2709 * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2710 * have surprising behavior). */
2711 old_in_port = ctx->flow.in_port;
2712 ctx->flow.in_port = in_port;
2713 rule = rule_lookup(ctx->ofproto, &ctx->flow);
2714 ctx->flow.in_port = old_in_port;
2716 if (ctx->resubmit_hook) {
2717 ctx->resubmit_hook(ctx, rule);
2722 do_xlate_actions(rule->actions, rule->n_actions, ctx);
2726 static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2728 VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2729 MAX_RESUBMIT_RECURSION);
2734 flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, uint32_t mask,
2735 uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
2737 struct ofport *ofport;
2739 HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
2740 uint16_t odp_port = ofport->odp_port;
2741 if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
2742 nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, odp_port);
2745 *nf_output_iface = NF_OUT_FLOOD;
2749 xlate_output_action__(struct action_xlate_ctx *ctx,
2750 uint16_t port, uint16_t max_len)
2753 uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2755 ctx->nf_output_iface = NF_OUT_DROP;
2759 add_output_action(ctx, ctx->flow.in_port);
2762 xlate_table_action(ctx, ctx->flow.in_port);
2765 if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
2766 ctx->odp_actions, &ctx->tags,
2767 &ctx->nf_output_iface,
2768 ctx->ofproto->aux)) {
2769 COVERAGE_INC(ofproto_uninstallable);
2770 ctx->may_set_up_flow = false;
2774 flood_packets(ctx->ofproto, ctx->flow.in_port, OFPPC_NO_FLOOD,
2775 &ctx->nf_output_iface, ctx->odp_actions);
2778 flood_packets(ctx->ofproto, ctx->flow.in_port, 0,
2779 &ctx->nf_output_iface, ctx->odp_actions);
2781 case OFPP_CONTROLLER:
2782 nl_msg_put_u64(ctx->odp_actions, ODPAT_CONTROLLER, max_len);
2785 add_output_action(ctx, ODPP_LOCAL);
2788 odp_port = ofp_port_to_odp_port(port);
2789 if (odp_port != ctx->flow.in_port) {
2790 add_output_action(ctx, odp_port);
2795 if (prev_nf_output_iface == NF_OUT_FLOOD) {
2796 ctx->nf_output_iface = NF_OUT_FLOOD;
2797 } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2798 ctx->nf_output_iface = prev_nf_output_iface;
2799 } else if (prev_nf_output_iface != NF_OUT_DROP &&
2800 ctx->nf_output_iface != NF_OUT_FLOOD) {
2801 ctx->nf_output_iface = NF_OUT_MULTI;
2806 xlate_output_action(struct action_xlate_ctx *ctx,
2807 const struct ofp_action_output *oao)
2809 xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2812 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2813 * optimization, because we're going to add another action that sets the
2814 * priority immediately after, or because there are no actions following the
2817 remove_pop_action(struct action_xlate_ctx *ctx)
2819 if (ctx->odp_actions->size == ctx->last_pop_priority) {
2820 ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
2821 ctx->last_pop_priority = -1;
2826 add_pop_action(struct action_xlate_ctx *ctx)
2828 if (ctx->odp_actions->size != ctx->last_pop_priority) {
2829 nl_msg_put_flag(ctx->odp_actions, ODPAT_POP_PRIORITY);
2830 ctx->last_pop_priority = ctx->odp_actions->size;
2835 xlate_enqueue_action(struct action_xlate_ctx *ctx,
2836 const struct ofp_action_enqueue *oae)
2838 uint16_t ofp_port, odp_port;
2842 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2845 /* Fall back to ordinary output action. */
2846 xlate_output_action__(ctx, ntohs(oae->port), 0);
2850 /* Figure out ODP output port. */
2851 ofp_port = ntohs(oae->port);
2852 if (ofp_port != OFPP_IN_PORT) {
2853 odp_port = ofp_port_to_odp_port(ofp_port);
2855 odp_port = ctx->flow.in_port;
2858 /* Add ODP actions. */
2859 remove_pop_action(ctx);
2860 nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2861 add_output_action(ctx, odp_port);
2862 add_pop_action(ctx);
2864 /* Update NetFlow output port. */
2865 if (ctx->nf_output_iface == NF_OUT_DROP) {
2866 ctx->nf_output_iface = odp_port;
2867 } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2868 ctx->nf_output_iface = NF_OUT_MULTI;
2873 xlate_set_queue_action(struct action_xlate_ctx *ctx,
2874 const struct nx_action_set_queue *nasq)
2879 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2882 /* Couldn't translate queue to a priority, so ignore. A warning
2883 * has already been logged. */
2887 remove_pop_action(ctx);
2888 nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2892 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2894 ovs_be16 tci = ctx->flow.vlan_tci;
2895 if (!(tci & htons(VLAN_CFI))) {
2896 nl_msg_put_flag(ctx->odp_actions, ODPAT_STRIP_VLAN);
2898 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_DL_TCI,
2899 tci & ~htons(VLAN_CFI));
2903 struct xlate_reg_state {
2909 save_reg_state(const struct action_xlate_ctx *ctx,
2910 struct xlate_reg_state *state)
2912 state->vlan_tci = ctx->flow.vlan_tci;
2913 state->tun_id = ctx->flow.tun_id;
2917 update_reg_state(struct action_xlate_ctx *ctx,
2918 const struct xlate_reg_state *state)
2920 if (ctx->flow.vlan_tci != state->vlan_tci) {
2921 xlate_set_dl_tci(ctx);
2923 if (ctx->flow.tun_id != state->tun_id) {
2924 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, ctx->flow.tun_id);
2929 xlate_nicira_action(struct action_xlate_ctx *ctx,
2930 const struct nx_action_header *nah)
2932 const struct nx_action_resubmit *nar;
2933 const struct nx_action_set_tunnel *nast;
2934 const struct nx_action_set_queue *nasq;
2935 const struct nx_action_multipath *nam;
2936 enum nx_action_subtype subtype = ntohs(nah->subtype);
2937 struct xlate_reg_state state;
2940 assert(nah->vendor == htonl(NX_VENDOR_ID));
2942 case NXAST_RESUBMIT:
2943 nar = (const struct nx_action_resubmit *) nah;
2944 xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2947 case NXAST_SET_TUNNEL:
2948 nast = (const struct nx_action_set_tunnel *) nah;
2949 tun_id = htonll(ntohl(nast->tun_id));
2950 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
2951 ctx->flow.tun_id = tun_id;
2954 case NXAST_DROP_SPOOFED_ARP:
2955 if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
2956 nl_msg_put_flag(ctx->odp_actions, ODPAT_DROP_SPOOFED_ARP);
2960 case NXAST_SET_QUEUE:
2961 nasq = (const struct nx_action_set_queue *) nah;
2962 xlate_set_queue_action(ctx, nasq);
2965 case NXAST_POP_QUEUE:
2966 add_pop_action(ctx);
2969 case NXAST_REG_MOVE:
2970 save_reg_state(ctx, &state);
2971 nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
2973 update_reg_state(ctx, &state);
2976 case NXAST_REG_LOAD:
2977 save_reg_state(ctx, &state);
2978 nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
2980 update_reg_state(ctx, &state);
2984 /* Nothing to do. */
2987 case NXAST_SET_TUNNEL64:
2988 tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
2989 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
2990 ctx->flow.tun_id = tun_id;
2993 case NXAST_MULTIPATH:
2994 nam = (const struct nx_action_multipath *) nah;
2995 multipath_execute(nam, &ctx->flow);
2998 /* If you add a new action here that modifies flow data, don't forget to
2999 * update the flow key in ctx->flow at the same time. */
3001 case NXAST_SNAT__OBSOLETE:
3003 VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
3009 do_xlate_actions(const union ofp_action *in, size_t n_in,
3010 struct action_xlate_ctx *ctx)
3012 struct actions_iterator iter;
3013 const union ofp_action *ia;
3014 const struct ofport *port;
3016 port = get_port(ctx->ofproto, ctx->flow.in_port);
3017 if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
3018 port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
3019 ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
3020 /* Drop this flow. */
3024 for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
3025 enum ofp_action_type type = ntohs(ia->type);
3026 const struct ofp_action_dl_addr *oada;
3030 xlate_output_action(ctx, &ia->output);
3033 case OFPAT_SET_VLAN_VID:
3034 ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3035 ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
3036 xlate_set_dl_tci(ctx);
3039 case OFPAT_SET_VLAN_PCP:
3040 ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3041 ctx->flow.vlan_tci |= htons(
3042 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
3043 xlate_set_dl_tci(ctx);
3046 case OFPAT_STRIP_VLAN:
3047 ctx->flow.vlan_tci = htons(0);
3048 xlate_set_dl_tci(ctx);
3051 case OFPAT_SET_DL_SRC:
3052 oada = ((struct ofp_action_dl_addr *) ia);
3053 nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_SRC,
3054 oada->dl_addr, ETH_ADDR_LEN);
3055 memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
3058 case OFPAT_SET_DL_DST:
3059 oada = ((struct ofp_action_dl_addr *) ia);
3060 nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_DST,
3061 oada->dl_addr, ETH_ADDR_LEN);
3062 memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
3065 case OFPAT_SET_NW_SRC:
3066 nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_SRC,
3067 ia->nw_addr.nw_addr);
3068 ctx->flow.nw_src = ia->nw_addr.nw_addr;
3071 case OFPAT_SET_NW_DST:
3072 nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_DST,
3073 ia->nw_addr.nw_addr);
3074 ctx->flow.nw_dst = ia->nw_addr.nw_addr;
3077 case OFPAT_SET_NW_TOS:
3078 nl_msg_put_u8(ctx->odp_actions, ODPAT_SET_NW_TOS,
3080 ctx->flow.nw_tos = ia->nw_tos.nw_tos;
3083 case OFPAT_SET_TP_SRC:
3084 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_SRC,
3085 ia->tp_port.tp_port);
3086 ctx->flow.tp_src = ia->tp_port.tp_port;
3089 case OFPAT_SET_TP_DST:
3090 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_DST,
3091 ia->tp_port.tp_port);
3092 ctx->flow.tp_dst = ia->tp_port.tp_port;
3096 xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
3100 xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3104 VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
3111 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3112 struct ofproto *ofproto, const struct flow *flow,
3113 const struct ofpbuf *packet)
3115 ctx->ofproto = ofproto;
3117 ctx->packet = packet;
3118 ctx->resubmit_hook = NULL;
3121 static struct ofpbuf *
3122 xlate_actions(struct action_xlate_ctx *ctx,
3123 const union ofp_action *in, size_t n_in)
3125 COVERAGE_INC(ofproto_ofp2odp);
3127 ctx->odp_actions = ofpbuf_new(512);
3129 ctx->may_set_up_flow = true;
3130 ctx->nf_output_iface = NF_OUT_DROP;
3132 ctx->last_pop_priority = -1;
3133 do_xlate_actions(in, n_in, ctx);
3134 remove_pop_action(ctx);
3136 /* Check with in-band control to see if we're allowed to set up this
3138 if (!in_band_rule_check(ctx->ofproto->in_band, &ctx->flow,
3139 ctx->odp_actions->data, ctx->odp_actions->size)) {
3140 ctx->may_set_up_flow = false;
3143 return ctx->odp_actions;
3146 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
3147 * error message code (composed with ofp_mkerr()) for the caller to propagate
3148 * upward. Otherwise, returns 0.
3150 * The log message mentions 'msg_type'. */
3152 reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
3154 if (ofconn->type == OFCONN_PRIMARY && ofconn->role == NX_ROLE_SLAVE) {
3155 static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
3156 VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
3159 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3166 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
3168 struct ofproto *p = ofconn->ofproto;
3169 struct ofp_packet_out *opo;
3170 struct ofpbuf payload, *buffer;
3171 union ofp_action *ofp_actions;
3172 struct action_xlate_ctx ctx;
3173 struct ofpbuf *odp_actions;
3174 struct ofpbuf request;
3176 size_t n_ofp_actions;
3180 COVERAGE_INC(ofproto_packet_out);
3182 error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
3187 /* Get ofp_packet_out. */
3188 ofpbuf_use_const(&request, oh, ntohs(oh->length));
3189 opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
3192 error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
3193 &ofp_actions, &n_ofp_actions);
3199 if (opo->buffer_id != htonl(UINT32_MAX)) {
3200 error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
3202 if (error || !buffer) {
3211 /* Extract flow, check actions. */
3212 flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
3214 error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
3220 action_xlate_ctx_init(&ctx, p, &flow, &payload);
3221 odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
3222 dpif_execute(p->dpif, odp_actions->data, odp_actions->size, &payload);
3223 ofpbuf_delete(odp_actions);
3226 ofpbuf_delete(buffer);
3231 update_port_config(struct ofproto *p, struct ofport *port,
3232 uint32_t config, uint32_t mask)
3234 mask &= config ^ port->opp.config;
3235 if (mask & OFPPC_PORT_DOWN) {
3236 if (config & OFPPC_PORT_DOWN) {
3237 netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
3239 netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
3242 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | \
3243 OFPPC_NO_FWD | OFPPC_NO_FLOOD)
3244 if (mask & REVALIDATE_BITS) {
3245 COVERAGE_INC(ofproto_costly_flags);
3246 port->opp.config ^= mask & REVALIDATE_BITS;
3247 p->need_revalidate = true;
3249 #undef REVALIDATE_BITS
3250 if (mask & OFPPC_NO_PACKET_IN) {
3251 port->opp.config ^= OFPPC_NO_PACKET_IN;
3256 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3258 struct ofproto *p = ofconn->ofproto;
3259 const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
3260 struct ofport *port;
3263 error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
3268 port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
3270 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
3271 } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
3272 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
3274 update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
3275 if (opm->advertise) {
3276 netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
3282 static struct ofpbuf *
3283 make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
3285 struct ofp_stats_reply *osr;
3288 msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
3289 osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
3291 osr->flags = htons(0);
3295 static struct ofpbuf *
3296 start_ofp_stats_reply(const struct ofp_header *request, size_t body_len)
3298 const struct ofp_stats_request *osr
3299 = (const struct ofp_stats_request *) request;
3300 return make_ofp_stats_reply(osr->header.xid, osr->type, body_len);
3304 append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
3305 struct ofpbuf **msgp)
3307 struct ofpbuf *msg = *msgp;
3308 assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
3309 if (nbytes + msg->size > UINT16_MAX) {
3310 struct ofp_stats_reply *reply = msg->data;
3311 reply->flags = htons(OFPSF_REPLY_MORE);
3312 *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
3313 queue_tx(msg, ofconn, ofconn->reply_counter);
3315 return ofpbuf_put_uninit(*msgp, nbytes);
3318 static struct ofpbuf *
3319 make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
3321 struct nicira_stats_msg *nsm;
3324 msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
3325 nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
3326 nsm->type = htons(OFPST_VENDOR);
3327 nsm->flags = htons(0);
3328 nsm->vendor = htonl(NX_VENDOR_ID);
3329 nsm->subtype = subtype;
3333 static struct ofpbuf *
3334 start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
3336 return make_nxstats_reply(request->header.xid, request->subtype, body_len);
3340 append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
3341 struct ofpbuf **msgp)
3343 struct ofpbuf *msg = *msgp;
3344 assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
3345 if (nbytes + msg->size > UINT16_MAX) {
3346 struct nicira_stats_msg *reply = msg->data;
3347 reply->flags = htons(OFPSF_REPLY_MORE);
3348 *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
3349 queue_tx(msg, ofconn, ofconn->reply_counter);
3351 ofpbuf_prealloc_tailroom(*msgp, nbytes);
3355 handle_desc_stats_request(struct ofconn *ofconn,
3356 const struct ofp_header *request)
3358 struct ofproto *p = ofconn->ofproto;
3359 struct ofp_desc_stats *ods;
3362 msg = start_ofp_stats_reply(request, sizeof *ods);
3363 ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
3364 memset(ods, 0, sizeof *ods);
3365 ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
3366 ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
3367 ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
3368 ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
3369 ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
3370 queue_tx(msg, ofconn, ofconn->reply_counter);
3376 handle_table_stats_request(struct ofconn *ofconn,
3377 const struct ofp_header *request)
3379 struct ofproto *p = ofconn->ofproto;
3380 struct ofp_table_stats *ots;
3383 msg = start_ofp_stats_reply(request, sizeof *ots * 2);
3385 /* Classifier table. */
3386 ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
3387 memset(ots, 0, sizeof *ots);
3388 strcpy(ots->name, "classifier");
3389 ots->wildcards = (ofconn->flow_format == NXFF_OPENFLOW10
3390 ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
3391 ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
3392 ots->active_count = htonl(classifier_count(&p->cls));
3393 ots->lookup_count = htonll(0); /* XXX */
3394 ots->matched_count = htonll(0); /* XXX */
3396 queue_tx(msg, ofconn, ofconn->reply_counter);
3401 append_port_stat(struct ofport *port, struct ofconn *ofconn,
3402 struct ofpbuf **msgp)
3404 struct netdev_stats stats;
3405 struct ofp_port_stats *ops;
3407 /* Intentionally ignore return value, since errors will set
3408 * 'stats' to all-1s, which is correct for OpenFlow, and
3409 * netdev_get_stats() will log errors. */
3410 netdev_get_stats(port->netdev, &stats);
3412 ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
3413 ops->port_no = htons(port->opp.port_no);
3414 memset(ops->pad, 0, sizeof ops->pad);
3415 ops->rx_packets = htonll(stats.rx_packets);
3416 ops->tx_packets = htonll(stats.tx_packets);
3417 ops->rx_bytes = htonll(stats.rx_bytes);
3418 ops->tx_bytes = htonll(stats.tx_bytes);
3419 ops->rx_dropped = htonll(stats.rx_dropped);
3420 ops->tx_dropped = htonll(stats.tx_dropped);
3421 ops->rx_errors = htonll(stats.rx_errors);
3422 ops->tx_errors = htonll(stats.tx_errors);
3423 ops->rx_frame_err = htonll(stats.rx_frame_errors);
3424 ops->rx_over_err = htonll(stats.rx_over_errors);
3425 ops->rx_crc_err = htonll(stats.rx_crc_errors);
3426 ops->collisions = htonll(stats.collisions);
3430 handle_port_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3432 struct ofproto *p = ofconn->ofproto;
3433 const struct ofp_port_stats_request *psr = ofputil_stats_body(oh);
3434 struct ofp_port_stats *ops;
3436 struct ofport *port;
3438 msg = start_ofp_stats_reply(oh, sizeof *ops * 16);
3439 if (psr->port_no != htons(OFPP_NONE)) {
3440 port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
3442 append_port_stat(port, ofconn, &msg);
3445 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3446 append_port_stat(port, ofconn, &msg);
3450 queue_tx(msg, ofconn, ofconn->reply_counter);
3454 /* Obtains statistic counters for 'rule' within 'p' and stores them into
3455 * '*packet_countp' and '*byte_countp'. The returned statistics include
3456 * statistics for all of 'rule''s facets. */
3458 query_stats(struct ofproto *p, struct rule *rule,
3459 uint64_t *packet_countp, uint64_t *byte_countp)
3461 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
3462 uint64_t packet_count, byte_count;
3463 struct facet *facet;
3466 /* Start from historical data for 'rule' itself that are no longer tracked
3467 * by the datapath. This counts, for example, facets that have expired. */
3468 packet_count = rule->packet_count;
3469 byte_count = rule->byte_count;
3471 /* Ask the datapath for statistics on all of the rule's facets.
3473 * Also, add any statistics that are not tracked by the datapath for each
3474 * facet. This includes, for example, statistics for packets that were
3475 * executed "by hand" by ofproto via dpif_execute() but must be accounted
3477 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
3478 LIST_FOR_EACH (facet, list_node, &rule->facets) {
3479 struct odp_flow_stats stats;
3482 odp_flow_key_from_flow(&key, &facet->flow);
3483 dpif_flow_get(p->dpif, 0, key.data, key.size, NULL, &stats);
3485 packet_count += stats.n_packets + facet->packet_count;
3486 byte_count += stats.n_bytes + facet->byte_count;
3489 /* Return the stats to the caller. */
3490 *packet_countp = packet_count;
3491 *byte_countp = byte_count;
3495 calc_flow_duration(long long int start, ovs_be32 *sec, ovs_be32 *nsec)
3497 long long int msecs = time_msec() - start;
3498 *sec = htonl(msecs / 1000);
3499 *nsec = htonl((msecs % 1000) * (1000 * 1000));
3503 put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
3504 ovs_be16 out_port, struct ofpbuf **replyp)
3506 struct ofp_flow_stats *ofs;
3507 uint64_t packet_count, byte_count;
3508 size_t act_len, len;
3510 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3514 act_len = sizeof *rule->actions * rule->n_actions;
3515 len = offsetof(struct ofp_flow_stats, actions) + act_len;
3517 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3519 ofs = append_ofp_stats_reply(len, ofconn, replyp);
3520 ofs->length = htons(len);
3523 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofs->match,
3524 rule->flow_cookie, &ofs->cookie);
3525 calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
3526 ofs->priority = htons(rule->cr.priority);
3527 ofs->idle_timeout = htons(rule->idle_timeout);
3528 ofs->hard_timeout = htons(rule->hard_timeout);
3529 memset(ofs->pad2, 0, sizeof ofs->pad2);
3530 ofs->packet_count = htonll(packet_count);
3531 ofs->byte_count = htonll(byte_count);
3532 if (rule->n_actions > 0) {
3533 memcpy(ofs->actions, rule->actions, act_len);
3538 is_valid_table(uint8_t table_id)
3540 return table_id == 0 || table_id == 0xff;
3544 handle_flow_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3546 const struct ofp_flow_stats_request *fsr = ofputil_stats_body(oh);
3547 struct ofpbuf *reply;
3549 COVERAGE_INC(ofproto_flows_req);
3550 reply = start_ofp_stats_reply(oh, 1024);
3551 if (is_valid_table(fsr->table_id)) {
3552 struct cls_cursor cursor;
3553 struct cls_rule target;
3556 ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
3558 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3559 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3560 put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
3563 queue_tx(reply, ofconn, ofconn->reply_counter);
3569 put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
3570 ovs_be16 out_port, struct ofpbuf **replyp)
3572 struct nx_flow_stats *nfs;
3573 uint64_t packet_count, byte_count;
3574 size_t act_len, start_len;
3575 struct ofpbuf *reply;
3577 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3581 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3583 act_len = sizeof *rule->actions * rule->n_actions;
3585 append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
3586 start_len = (*replyp)->size;
3589 nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
3592 calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
3593 nfs->cookie = rule->flow_cookie;
3594 nfs->priority = htons(rule->cr.priority);
3595 nfs->idle_timeout = htons(rule->idle_timeout);
3596 nfs->hard_timeout = htons(rule->hard_timeout);
3597 nfs->match_len = htons(nx_put_match(reply, &rule->cr));
3598 memset(nfs->pad2, 0, sizeof nfs->pad2);
3599 nfs->packet_count = htonll(packet_count);
3600 nfs->byte_count = htonll(byte_count);
3601 if (rule->n_actions > 0) {
3602 ofpbuf_put(reply, rule->actions, act_len);
3604 nfs->length = htons(reply->size - start_len);
3608 handle_nxst_flow(struct ofconn *ofconn, const struct ofp_header *oh)
3610 struct nx_flow_stats_request *nfsr;
3611 struct cls_rule target;
3612 struct ofpbuf *reply;
3616 ofpbuf_use_const(&b, oh, ntohs(oh->length));
3618 /* Dissect the message. */
3619 nfsr = ofpbuf_pull(&b, sizeof *nfsr);
3620 error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &target);
3625 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3628 COVERAGE_INC(ofproto_flows_req);
3629 reply = start_nxstats_reply(&nfsr->nsm, 1024);
3630 if (is_valid_table(nfsr->table_id)) {
3631 struct cls_cursor cursor;
3634 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3635 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3636 put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
3639 queue_tx(reply, ofconn, ofconn->reply_counter);
3645 flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
3647 uint64_t packet_count, byte_count;
3648 size_t act_len = sizeof *rule->actions * rule->n_actions;
3650 query_stats(ofproto, rule, &packet_count, &byte_count);
3652 ds_put_format(results, "duration=%llds, ",
3653 (time_msec() - rule->created) / 1000);
3654 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3655 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3656 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3657 cls_rule_format(&rule->cr, results);
3659 ofp_print_actions(results, &rule->actions->header, act_len);
3661 ds_put_cstr(results, "drop");
3663 ds_put_cstr(results, "\n");
3666 /* Adds a pretty-printed description of all flows to 'results', including
3667 * those marked hidden by secchan (e.g., by in-band control). */
3669 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3671 struct cls_cursor cursor;
3674 cls_cursor_init(&cursor, &p->cls, NULL);
3675 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3676 flow_stats_ds(p, rule, results);
3681 query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
3682 ovs_be16 out_port, uint8_t table_id,
3683 struct ofp_aggregate_stats_reply *oasr)
3685 uint64_t total_packets = 0;
3686 uint64_t total_bytes = 0;
3689 COVERAGE_INC(ofproto_agg_request);
3691 if (is_valid_table(table_id)) {
3692 struct cls_cursor cursor;
3695 cls_cursor_init(&cursor, &ofproto->cls, target);
3696 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3697 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
3698 uint64_t packet_count;
3699 uint64_t byte_count;
3701 query_stats(ofproto, rule, &packet_count, &byte_count);
3703 total_packets += packet_count;
3704 total_bytes += byte_count;
3710 oasr->flow_count = htonl(n_flows);
3711 oasr->packet_count = htonll(total_packets);
3712 oasr->byte_count = htonll(total_bytes);
3713 memset(oasr->pad, 0, sizeof oasr->pad);
3717 handle_aggregate_stats_request(struct ofconn *ofconn,
3718 const struct ofp_header *oh)
3720 const struct ofp_aggregate_stats_request *request = ofputil_stats_body(oh);
3721 struct ofp_aggregate_stats_reply *reply;
3722 struct cls_rule target;
3725 ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
3728 msg = start_ofp_stats_reply(oh, sizeof *reply);
3729 reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
3730 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3731 request->table_id, reply);
3732 queue_tx(msg, ofconn, ofconn->reply_counter);
3737 handle_nxst_aggregate(struct ofconn *ofconn, const struct ofp_header *oh)
3739 struct nx_aggregate_stats_request *request;
3740 struct ofp_aggregate_stats_reply *reply;
3741 struct cls_rule target;
3746 ofpbuf_use_const(&b, oh, ntohs(oh->length));
3748 /* Dissect the message. */
3749 request = ofpbuf_pull(&b, sizeof *request);
3750 error = nx_pull_match(&b, ntohs(request->match_len), 0, &target);
3755 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3759 COVERAGE_INC(ofproto_flows_req);
3760 buf = start_nxstats_reply(&request->nsm, sizeof *reply);
3761 reply = ofpbuf_put_uninit(buf, sizeof *reply);
3762 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3763 request->table_id, reply);
3764 queue_tx(buf, ofconn, ofconn->reply_counter);
3769 struct queue_stats_cbdata {
3770 struct ofconn *ofconn;
3771 struct ofport *ofport;
3776 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3777 const struct netdev_queue_stats *stats)
3779 struct ofp_queue_stats *reply;
3781 reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
3782 reply->port_no = htons(cbdata->ofport->opp.port_no);
3783 memset(reply->pad, 0, sizeof reply->pad);
3784 reply->queue_id = htonl(queue_id);
3785 reply->tx_bytes = htonll(stats->tx_bytes);
3786 reply->tx_packets = htonll(stats->tx_packets);
3787 reply->tx_errors = htonll(stats->tx_errors);
3791 handle_queue_stats_dump_cb(uint32_t queue_id,
3792 struct netdev_queue_stats *stats,
3795 struct queue_stats_cbdata *cbdata = cbdata_;
3797 put_queue_stats(cbdata, queue_id, stats);
3801 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3802 struct queue_stats_cbdata *cbdata)
3804 cbdata->ofport = port;
3805 if (queue_id == OFPQ_ALL) {
3806 netdev_dump_queue_stats(port->netdev,
3807 handle_queue_stats_dump_cb, cbdata);
3809 struct netdev_queue_stats stats;
3811 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3812 put_queue_stats(cbdata, queue_id, &stats);
3818 handle_queue_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3820 struct ofproto *ofproto = ofconn->ofproto;
3821 const struct ofp_queue_stats_request *qsr;
3822 struct queue_stats_cbdata cbdata;
3823 struct ofport *port;
3824 unsigned int port_no;
3827 qsr = ofputil_stats_body(oh);
3829 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3832 COVERAGE_INC(ofproto_queue_req);
3834 cbdata.ofconn = ofconn;
3835 cbdata.msg = start_ofp_stats_reply(oh, 128);
3837 port_no = ntohs(qsr->port_no);
3838 queue_id = ntohl(qsr->queue_id);
3839 if (port_no == OFPP_ALL) {
3840 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3841 handle_queue_stats_for_port(port, queue_id, &cbdata);
3843 } else if (port_no < ofproto->max_ports) {
3844 port = get_port(ofproto, ofp_port_to_odp_port(port_no));
3846 handle_queue_stats_for_port(port, queue_id, &cbdata);
3849 ofpbuf_delete(cbdata.msg);
3850 return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
3852 queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
3857 static long long int
3858 msec_from_nsec(uint64_t sec, uint32_t nsec)
3860 return !sec ? 0 : sec * 1000 + nsec / 1000000;
3864 facet_update_time(struct ofproto *ofproto, struct facet *facet,
3865 const struct odp_flow_stats *stats)
3867 long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
3868 if (used > facet->used) {
3870 if (used > facet->rule->used) {
3871 facet->rule->used = used;
3873 netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3877 /* Folds the statistics from 'stats' into the counters in 'facet'.
3879 * Because of the meaning of a facet's counters, it only makes sense to do this
3880 * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3881 * packet that was sent by hand or if it represents statistics that have been
3882 * cleared out of the datapath. */
3884 facet_update_stats(struct ofproto *ofproto, struct facet *facet,
3885 const struct odp_flow_stats *stats)
3887 if (stats->n_packets) {
3888 facet_update_time(ofproto, facet, stats);
3889 facet->packet_count += stats->n_packets;
3890 facet->byte_count += stats->n_bytes;
3891 netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3895 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3896 * in which no matching flow already exists in the flow table.
3898 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3899 * ofp_actions, to ofconn->ofproto's flow table. Returns 0 on success or an
3900 * OpenFlow error code as encoded by ofp_mkerr() on failure.
3902 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3905 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
3907 struct ofproto *p = ofconn->ofproto;
3908 struct ofpbuf *packet;
3913 if (fm->flags & OFPFF_CHECK_OVERLAP
3914 && classifier_rule_overlaps(&p->cls, &fm->cr)) {
3915 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
3919 if (fm->buffer_id != UINT32_MAX) {
3920 error = pktbuf_retrieve(ofconn->pktbuf, fm->buffer_id,
3924 in_port = UINT16_MAX;
3927 rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
3928 fm->idle_timeout, fm->hard_timeout, fm->cookie,
3929 fm->flags & OFPFF_SEND_FLOW_REM);
3930 rule_insert(p, rule);
3932 rule_execute(p, rule, in_port, packet);
3937 static struct rule *
3938 find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
3940 return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
3944 send_buffered_packet(struct ofconn *ofconn,
3945 struct rule *rule, uint32_t buffer_id)
3947 struct ofpbuf *packet;
3951 if (buffer_id == UINT32_MAX) {
3955 error = pktbuf_retrieve(ofconn->pktbuf, buffer_id, &packet, &in_port);
3960 rule_execute(ofconn->ofproto, rule, in_port, packet);
3965 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3967 struct modify_flows_cbdata {
3968 struct ofproto *ofproto;
3969 const struct flow_mod *fm;
3973 static int modify_flow(struct ofproto *, const struct flow_mod *,
3976 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code as
3977 * encoded by ofp_mkerr() on failure.
3979 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3982 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
3984 struct ofproto *p = ofconn->ofproto;
3985 struct rule *match = NULL;
3986 struct cls_cursor cursor;
3989 cls_cursor_init(&cursor, &p->cls, &fm->cr);
3990 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3991 if (!rule_is_hidden(rule)) {
3993 modify_flow(p, fm, rule);
3998 /* This credits the packet to whichever flow happened to match last.
3999 * That's weird. Maybe we should do a lookup for the flow that
4000 * actually matches the packet? Who knows. */
4001 send_buffered_packet(ofconn, match, fm->buffer_id);
4004 return add_flow(ofconn, fm);
4008 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4009 * code as encoded by ofp_mkerr() on failure.
4011 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4014 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
4016 struct ofproto *p = ofconn->ofproto;
4017 struct rule *rule = find_flow_strict(p, fm);
4018 if (rule && !rule_is_hidden(rule)) {
4019 modify_flow(p, fm, rule);
4020 return send_buffered_packet(ofconn, rule, fm->buffer_id);
4022 return add_flow(ofconn, fm);
4026 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
4027 * been identified as a flow in 'p''s flow table to be modified, by changing
4028 * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
4029 * ofp_action[] structures). */
4031 modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
4033 size_t actions_len = fm->n_actions * sizeof *rule->actions;
4035 rule->flow_cookie = fm->cookie;
4037 /* If the actions are the same, do nothing. */
4038 if (fm->n_actions == rule->n_actions
4040 || !memcmp(fm->actions, rule->actions, actions_len))) {
4044 /* Replace actions. */
4045 free(rule->actions);
4046 rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
4047 rule->n_actions = fm->n_actions;
4049 p->need_revalidate = true;
4054 /* OFPFC_DELETE implementation. */
4056 static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
4058 /* Implements OFPFC_DELETE. */
4060 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
4062 struct rule *rule, *next_rule;
4063 struct cls_cursor cursor;
4065 cls_cursor_init(&cursor, &p->cls, &fm->cr);
4066 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4067 delete_flow(p, rule, htons(fm->out_port));
4071 /* Implements OFPFC_DELETE_STRICT. */
4073 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
4075 struct rule *rule = find_flow_strict(p, fm);
4077 delete_flow(p, rule, htons(fm->out_port));
4081 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
4082 * been identified as a flow to delete from 'p''s flow table, by deleting the
4083 * flow and sending out a OFPT_FLOW_REMOVED message to any interested
4086 * Will not delete 'rule' if it is hidden. Will delete 'rule' only if
4087 * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
4088 * specified 'out_port'. */
4090 delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
4092 if (rule_is_hidden(rule)) {
4096 if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
4100 rule_send_removed(p, rule, OFPRR_DELETE);
4101 rule_remove(p, rule);
4105 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4107 struct ofproto *p = ofconn->ofproto;
4111 error = reject_slave_controller(ofconn, "flow_mod");
4116 error = ofputil_decode_flow_mod(&fm, oh, ofconn->flow_format);
4121 /* We do not support the emergency flow cache. It will hopefully get
4122 * dropped from OpenFlow in the near future. */
4123 if (fm.flags & OFPFF_EMERG) {
4124 /* There isn't a good fit for an error code, so just state that the
4125 * flow table is full. */
4126 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
4129 error = validate_actions(fm.actions, fm.n_actions,
4130 &fm.cr.flow, p->max_ports);
4135 switch (fm.command) {
4137 return add_flow(ofconn, &fm);
4140 return modify_flows_loose(ofconn, &fm);
4142 case OFPFC_MODIFY_STRICT:
4143 return modify_flow_strict(ofconn, &fm);
4146 delete_flows_loose(p, &fm);
4149 case OFPFC_DELETE_STRICT:
4150 delete_flow_strict(p, &fm);
4154 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
4159 handle_tun_id_from_cookie(struct ofconn *ofconn, const struct ofp_header *oh)
4161 const struct nxt_tun_id_cookie *msg
4162 = (const struct nxt_tun_id_cookie *) oh;
4164 ofconn->flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
4169 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4171 struct nx_role_request *nrr = (struct nx_role_request *) oh;
4172 struct nx_role_request *reply;
4176 if (ofconn->type != OFCONN_PRIMARY) {
4177 VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
4179 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4182 role = ntohl(nrr->role);
4183 if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
4184 && role != NX_ROLE_SLAVE) {
4185 VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
4187 /* There's no good error code for this. */
4188 return ofp_mkerr(OFPET_BAD_REQUEST, -1);
4191 if (role == NX_ROLE_MASTER) {
4192 struct ofconn *other;
4194 HMAP_FOR_EACH (other, hmap_node, &ofconn->ofproto->controllers) {
4195 if (other->role == NX_ROLE_MASTER) {
4196 other->role = NX_ROLE_SLAVE;
4200 ofconn->role = role;
4202 reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
4203 reply->role = htonl(role);
4204 queue_tx(buf, ofconn, ofconn->reply_counter);
4210 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4212 const struct nxt_set_flow_format *msg
4213 = (const struct nxt_set_flow_format *) oh;
4216 format = ntohl(msg->format);
4217 if (format == NXFF_OPENFLOW10
4218 || format == NXFF_TUN_ID_FROM_COOKIE
4219 || format == NXFF_NXM) {
4220 ofconn->flow_format = format;
4223 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4228 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4230 struct ofp_header *ob;
4233 /* Currently, everything executes synchronously, so we can just
4234 * immediately send the barrier reply. */
4235 ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
4236 queue_tx(buf, ofconn, ofconn->reply_counter);
4241 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4243 const struct ofp_header *oh = msg->data;
4244 const struct ofputil_msg_type *type;
4247 error = ofputil_decode_msg_type(oh, &type);
4252 switch (ofputil_msg_type_code(type)) {
4253 /* OpenFlow requests. */
4254 case OFPUTIL_OFPT_ECHO_REQUEST:
4255 return handle_echo_request(ofconn, oh);
4257 case OFPUTIL_OFPT_FEATURES_REQUEST:
4258 return handle_features_request(ofconn, oh);
4260 case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
4261 return handle_get_config_request(ofconn, oh);
4263 case OFPUTIL_OFPT_SET_CONFIG:
4264 return handle_set_config(ofconn, msg->data);
4266 case OFPUTIL_OFPT_PACKET_OUT:
4267 return handle_packet_out(ofconn, oh);
4269 case OFPUTIL_OFPT_PORT_MOD:
4270 return handle_port_mod(ofconn, oh);
4272 case OFPUTIL_OFPT_FLOW_MOD:
4273 return handle_flow_mod(ofconn, oh);
4275 case OFPUTIL_OFPT_BARRIER_REQUEST:
4276 return handle_barrier_request(ofconn, oh);
4278 /* OpenFlow replies. */
4279 case OFPUTIL_OFPT_ECHO_REPLY:
4282 /* Nicira extension requests. */
4283 case OFPUTIL_NXT_STATUS_REQUEST:
4284 return switch_status_handle_request(
4285 ofconn->ofproto->switch_status, ofconn->rconn, oh);
4287 case OFPUTIL_NXT_TUN_ID_FROM_COOKIE:
4288 return handle_tun_id_from_cookie(ofconn, oh);
4290 case OFPUTIL_NXT_ROLE_REQUEST:
4291 return handle_role_request(ofconn, oh);
4293 case OFPUTIL_NXT_SET_FLOW_FORMAT:
4294 return handle_nxt_set_flow_format(ofconn, oh);
4296 case OFPUTIL_NXT_FLOW_MOD:
4297 return handle_flow_mod(ofconn, oh);
4299 /* OpenFlow statistics requests. */
4300 case OFPUTIL_OFPST_DESC_REQUEST:
4301 return handle_desc_stats_request(ofconn, oh);
4303 case OFPUTIL_OFPST_FLOW_REQUEST:
4304 return handle_flow_stats_request(ofconn, oh);
4306 case OFPUTIL_OFPST_AGGREGATE_REQUEST:
4307 return handle_aggregate_stats_request(ofconn, oh);
4309 case OFPUTIL_OFPST_TABLE_REQUEST:
4310 return handle_table_stats_request(ofconn, oh);
4312 case OFPUTIL_OFPST_PORT_REQUEST:
4313 return handle_port_stats_request(ofconn, oh);
4315 case OFPUTIL_OFPST_QUEUE_REQUEST:
4316 return handle_queue_stats_request(ofconn, oh);
4318 /* Nicira extension statistics requests. */
4319 case OFPUTIL_NXST_FLOW_REQUEST:
4320 return handle_nxst_flow(ofconn, oh);
4322 case OFPUTIL_NXST_AGGREGATE_REQUEST:
4323 return handle_nxst_aggregate(ofconn, oh);
4325 case OFPUTIL_INVALID:
4326 case OFPUTIL_OFPT_HELLO:
4327 case OFPUTIL_OFPT_ERROR:
4328 case OFPUTIL_OFPT_FEATURES_REPLY:
4329 case OFPUTIL_OFPT_GET_CONFIG_REPLY:
4330 case OFPUTIL_OFPT_PACKET_IN:
4331 case OFPUTIL_OFPT_FLOW_REMOVED:
4332 case OFPUTIL_OFPT_PORT_STATUS:
4333 case OFPUTIL_OFPT_BARRIER_REPLY:
4334 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
4335 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
4336 case OFPUTIL_OFPST_DESC_REPLY:
4337 case OFPUTIL_OFPST_FLOW_REPLY:
4338 case OFPUTIL_OFPST_QUEUE_REPLY:
4339 case OFPUTIL_OFPST_PORT_REPLY:
4340 case OFPUTIL_OFPST_TABLE_REPLY:
4341 case OFPUTIL_OFPST_AGGREGATE_REPLY:
4342 case OFPUTIL_NXT_STATUS_REPLY:
4343 case OFPUTIL_NXT_ROLE_REPLY:
4344 case OFPUTIL_NXT_FLOW_REMOVED:
4345 case OFPUTIL_NXST_FLOW_REPLY:
4346 case OFPUTIL_NXST_AGGREGATE_REPLY:
4348 if (VLOG_IS_WARN_ENABLED()) {
4349 char *s = ofp_to_string(oh, ntohs(oh->length), 2);
4350 VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
4353 if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
4354 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
4356 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
4362 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4364 int error = handle_openflow__(ofconn, ofp_msg);
4366 send_error_oh(ofconn, ofp_msg->data, error);
4368 COVERAGE_INC(ofproto_recv_openflow);
4372 handle_miss_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4374 struct facet *facet;
4377 /* Obtain in_port and tun_id, at least. */
4378 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4380 /* Set header pointers in 'flow'. */
4381 flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
4383 /* Check with in-band control to see if this packet should be sent
4384 * to the local port regardless of the flow table. */
4385 if (in_band_msg_in_hook(p->in_band, &flow, upcall->packet)) {
4386 struct ofpbuf odp_actions;
4388 ofpbuf_init(&odp_actions, 32);
4389 nl_msg_put_u32(&odp_actions, ODPAT_OUTPUT, ODPP_LOCAL);
4390 dpif_execute(p->dpif, odp_actions.data, odp_actions.size,
4392 ofpbuf_uninit(&odp_actions);
4395 facet = facet_lookup_valid(p, &flow);
4397 struct rule *rule = rule_lookup(p, &flow);
4399 /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
4400 struct ofport *port = get_port(p, flow.in_port);
4402 if (port->opp.config & OFPPC_NO_PACKET_IN) {
4403 COVERAGE_INC(ofproto_no_packet_in);
4404 /* XXX install 'drop' flow entry */
4405 ofpbuf_delete(upcall->packet);
4409 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
4413 COVERAGE_INC(ofproto_packet_in);
4414 send_packet_in(p, upcall, &flow, false);
4418 facet = facet_create(p, rule, &flow, upcall->packet);
4419 } else if (!facet->may_install) {
4420 /* The facet is not installable, that is, we need to process every
4421 * packet, so process the current packet's actions into 'facet'. */
4422 facet_make_actions(p, facet, upcall->packet);
4425 if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
4427 * Extra-special case for fail-open mode.
4429 * We are in fail-open mode and the packet matched the fail-open rule,
4430 * but we are connected to a controller too. We should send the packet
4431 * up to the controller in the hope that it will try to set up a flow
4432 * and thereby allow us to exit fail-open.
4434 * See the top-level comment in fail-open.c for more information.
4436 send_packet_in(p, upcall, &flow, true);
4439 facet_execute(p, facet, upcall->packet);
4440 facet_install(p, facet, false);
4444 handle_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4448 switch (upcall->type) {
4449 case _ODPL_ACTION_NR:
4450 COVERAGE_INC(ofproto_ctlr_action);
4451 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4452 send_packet_in(p, upcall, &flow, false);
4455 case _ODPL_SFLOW_NR:
4457 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4458 ofproto_sflow_received(p->sflow, upcall, &flow);
4460 ofpbuf_delete(upcall->packet);
4464 handle_miss_upcall(p, upcall);
4468 VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
4473 /* Flow expiration. */
4475 static int ofproto_dp_max_idle(const struct ofproto *);
4476 static void ofproto_update_used(struct ofproto *);
4477 static void rule_expire(struct ofproto *, struct rule *);
4478 static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
4480 /* This function is called periodically by ofproto_run(). Its job is to
4481 * collect updates for the flows that have been installed into the datapath,
4482 * most importantly when they last were used, and then use that information to
4483 * expire flows that have not been used recently.
4485 * Returns the number of milliseconds after which it should be called again. */
4487 ofproto_expire(struct ofproto *ofproto)
4489 struct rule *rule, *next_rule;
4490 struct cls_cursor cursor;
4493 /* Update 'used' for each flow in the datapath. */
4494 ofproto_update_used(ofproto);
4496 /* Expire facets that have been idle too long. */
4497 dp_max_idle = ofproto_dp_max_idle(ofproto);
4498 ofproto_expire_facets(ofproto, dp_max_idle);
4500 /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
4501 cls_cursor_init(&cursor, &ofproto->cls, NULL);
4502 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4503 rule_expire(ofproto, rule);
4506 /* Let the hook know that we're at a stable point: all outstanding data
4507 * in existing flows has been accounted to the account_cb. Thus, the
4508 * hook can now reasonably do operations that depend on having accurate
4509 * flow volume accounting (currently, that's just bond rebalancing). */
4510 if (ofproto->ofhooks->account_checkpoint_cb) {
4511 ofproto->ofhooks->account_checkpoint_cb(ofproto->aux);
4514 return MIN(dp_max_idle, 1000);
4517 /* Update 'used' member of installed facets. */
4519 ofproto_update_used(struct ofproto *p)
4521 const struct odp_flow_stats *stats;
4522 struct dpif_flow_dump dump;
4523 const struct nlattr *key;
4526 dpif_flow_dump_start(&dump, p->dpif);
4527 while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
4528 struct facet *facet;
4531 if (odp_flow_key_to_flow(key, key_len, &flow)) {
4535 odp_flow_key_format(key, key_len, &s);
4536 VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
4542 facet = facet_find(p, &flow);
4544 if (facet && facet->installed) {
4545 facet_update_time(p, facet, stats);
4546 facet_account(p, facet, stats->n_bytes);
4548 /* There's a flow in the datapath that we know nothing about.
4550 COVERAGE_INC(ofproto_unexpected_rule);
4551 dpif_flow_del(p->dpif, key, key_len, NULL);
4554 dpif_flow_dump_done(&dump);
4557 /* Calculates and returns the number of milliseconds of idle time after which
4558 * facets should expire from the datapath and we should fold their statistics
4559 * into their parent rules in userspace. */
4561 ofproto_dp_max_idle(const struct ofproto *ofproto)
4564 * Idle time histogram.
4566 * Most of the time a switch has a relatively small number of facets. When
4567 * this is the case we might as well keep statistics for all of them in
4568 * userspace and to cache them in the kernel datapath for performance as
4571 * As the number of facets increases, the memory required to maintain
4572 * statistics about them in userspace and in the kernel becomes
4573 * significant. However, with a large number of facets it is likely that
4574 * only a few of them are "heavy hitters" that consume a large amount of
4575 * bandwidth. At this point, only heavy hitters are worth caching in the
4576 * kernel and maintaining in userspaces; other facets we can discard.
4578 * The technique used to compute the idle time is to build a histogram with
4579 * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each. Each facet
4580 * that is installed in the kernel gets dropped in the appropriate bucket.
4581 * After the histogram has been built, we compute the cutoff so that only
4582 * the most-recently-used 1% of facets (but at least 1000 flows) are kept
4583 * cached. At least the most-recently-used bucket of facets is kept, so
4584 * actually an arbitrary number of facets can be kept in any given
4585 * expiration run (though the next run will delete most of those unless
4586 * they receive additional data).
4588 * This requires a second pass through the facets, in addition to the pass
4589 * made by ofproto_update_used(), because the former function never looks
4590 * at uninstallable facets.
4592 enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4593 enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4594 int buckets[N_BUCKETS] = { 0 };
4595 struct facet *facet;
4600 total = hmap_count(&ofproto->facets);
4601 if (total <= 1000) {
4602 return N_BUCKETS * BUCKET_WIDTH;
4605 /* Build histogram. */
4607 HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
4608 long long int idle = now - facet->used;
4609 int bucket = (idle <= 0 ? 0
4610 : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4611 : (unsigned int) idle / BUCKET_WIDTH);
4615 /* Find the first bucket whose flows should be expired. */
4616 for (bucket = 0; bucket < N_BUCKETS; bucket++) {
4617 if (buckets[bucket]) {
4620 subtotal += buckets[bucket++];
4621 } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
4626 if (VLOG_IS_DBG_ENABLED()) {
4630 ds_put_cstr(&s, "keep");
4631 for (i = 0; i < N_BUCKETS; i++) {
4633 ds_put_cstr(&s, ", drop");
4636 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4639 VLOG_INFO("%s: %s (msec:count)",
4640 dpif_name(ofproto->dpif), ds_cstr(&s));
4644 return bucket * BUCKET_WIDTH;
4648 facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
4650 if (ofproto->netflow && !facet_is_controller_flow(facet) &&
4651 netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
4652 struct ofexpired expired;
4654 expired.flow = facet->flow;
4655 expired.packet_count = facet->packet_count;
4656 expired.byte_count = facet->byte_count;
4657 expired.used = facet->used;
4659 /* Get updated flow stats.
4661 * XXX We could avoid this call entirely if (1) ofproto_update_used()
4662 * updated TCP flags and (2) the dpif_flow_list_all() in
4663 * ofproto_update_used() zeroed TCP flags. */
4664 if (facet->installed) {
4665 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
4666 struct odp_flow_stats stats;
4669 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
4670 odp_flow_key_from_flow(&key, &facet->flow);
4672 if (!dpif_flow_get(ofproto->dpif, ODPFF_ZERO_TCP_FLAGS,
4673 key.data, key.size, NULL, &stats)) {
4674 expired.packet_count += stats.n_packets;
4675 expired.byte_count += stats.n_bytes;
4676 if (stats.n_packets) {
4677 facet_update_time(ofproto, facet, &stats);
4678 netflow_flow_update_flags(&facet->nf_flow,
4684 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4689 ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
4691 long long int cutoff = time_msec() - dp_max_idle;
4692 struct facet *facet, *next_facet;
4694 HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
4695 facet_active_timeout(ofproto, facet);
4696 if (facet->used < cutoff) {
4697 facet_remove(ofproto, facet);
4702 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4703 * then delete it entirely. */
4705 rule_expire(struct ofproto *ofproto, struct rule *rule)
4707 struct facet *facet, *next_facet;
4711 /* Has 'rule' expired? */
4713 if (rule->hard_timeout
4714 && now > rule->created + rule->hard_timeout * 1000) {
4715 reason = OFPRR_HARD_TIMEOUT;
4716 } else if (rule->idle_timeout && list_is_empty(&rule->facets)
4717 && now >rule->used + rule->idle_timeout * 1000) {
4718 reason = OFPRR_IDLE_TIMEOUT;
4723 COVERAGE_INC(ofproto_expired);
4725 /* Update stats. (This is a no-op if the rule expired due to an idle
4726 * timeout, because that only happens when the rule has no facets left.) */
4727 LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4728 facet_remove(ofproto, facet);
4731 /* Get rid of the rule. */
4732 if (!rule_is_hidden(rule)) {
4733 rule_send_removed(ofproto, rule, reason);
4735 rule_remove(ofproto, rule);
4738 static struct ofpbuf *
4739 compose_ofp_flow_removed(struct ofconn *ofconn, const struct rule *rule,
4742 struct ofp_flow_removed *ofr;
4745 ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0), &buf);
4746 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofr->match,
4747 rule->flow_cookie, &ofr->cookie);
4748 ofr->priority = htons(rule->cr.priority);
4749 ofr->reason = reason;
4750 calc_flow_duration(rule->created, &ofr->duration_sec, &ofr->duration_nsec);
4751 ofr->idle_timeout = htons(rule->idle_timeout);
4752 ofr->packet_count = htonll(rule->packet_count);
4753 ofr->byte_count = htonll(rule->byte_count);
4758 static struct ofpbuf *
4759 compose_nx_flow_removed(const struct rule *rule, uint8_t reason)
4761 struct nx_flow_removed *nfr;
4765 make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &buf);
4766 match_len = nx_put_match(buf, &rule->cr);
4769 nfr->cookie = rule->flow_cookie;
4770 nfr->priority = htons(rule->cr.priority);
4771 nfr->reason = reason;
4772 calc_flow_duration(rule->created, &nfr->duration_sec, &nfr->duration_nsec);
4773 nfr->idle_timeout = htons(rule->idle_timeout);
4774 nfr->match_len = htons(match_len);
4775 nfr->packet_count = htonll(rule->packet_count);
4776 nfr->byte_count = htonll(rule->byte_count);
4782 rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
4784 struct ofconn *ofconn;
4786 if (!rule->send_flow_removed) {
4790 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
4793 if (!rconn_is_connected(ofconn->rconn)
4794 || !ofconn_receives_async_msgs(ofconn)) {
4798 msg = (ofconn->flow_format == NXFF_NXM
4799 ? compose_nx_flow_removed(rule, reason)
4800 : compose_ofp_flow_removed(ofconn, rule, reason));
4802 /* Account flow expirations under ofconn->reply_counter, the counter
4803 * for replies to OpenFlow requests. That works because preventing
4804 * OpenFlow requests from being processed also prevents new flows from
4805 * being added (and expiring). (It also prevents processing OpenFlow
4806 * requests that would not add new flows, so it is imperfect.) */
4807 queue_tx(msg, ofconn, ofconn->reply_counter);
4811 /* pinsched callback for sending 'ofp_packet_in' on 'ofconn'. */
4813 do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn_)
4815 struct ofconn *ofconn = ofconn_;
4817 rconn_send_with_limit(ofconn->rconn, ofp_packet_in,
4818 ofconn->packet_in_counter, 100);
4821 /* Takes 'upcall', whose packet has the flow specified by 'flow', composes an
4822 * OpenFlow packet-in message from it, and passes it to 'ofconn''s packet
4823 * scheduler for sending.
4825 * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
4826 * Otherwise, ownership is transferred to this function. */
4828 schedule_packet_in(struct ofconn *ofconn, struct dpif_upcall *upcall,
4829 const struct flow *flow, bool clone)
4831 enum { OPI_SIZE = offsetof(struct ofp_packet_in, data) };
4832 struct ofproto *ofproto = ofconn->ofproto;
4833 struct ofp_packet_in *opi;
4834 int total_len, send_len;
4835 struct ofpbuf *packet;
4838 /* Get OpenFlow buffer_id. */
4839 if (upcall->type == _ODPL_ACTION_NR) {
4840 buffer_id = UINT32_MAX;
4841 } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
4842 buffer_id = pktbuf_get_null();
4843 } else if (!ofconn->pktbuf) {
4844 buffer_id = UINT32_MAX;
4846 buffer_id = pktbuf_save(ofconn->pktbuf, upcall->packet, flow->in_port);
4849 /* Figure out how much of the packet to send. */
4850 total_len = send_len = upcall->packet->size;
4851 if (buffer_id != UINT32_MAX) {
4852 send_len = MIN(send_len, ofconn->miss_send_len);
4854 if (upcall->type == _ODPL_ACTION_NR) {
4855 send_len = MIN(send_len, upcall->userdata);
4858 /* Copy or steal buffer for OFPT_PACKET_IN. */
4860 packet = ofpbuf_clone_data_with_headroom(upcall->packet->data,
4861 send_len, OPI_SIZE);
4863 packet = upcall->packet;
4864 packet->size = send_len;
4867 /* Add OFPT_PACKET_IN. */
4868 opi = ofpbuf_push_zeros(packet, OPI_SIZE);
4869 opi->header.version = OFP_VERSION;
4870 opi->header.type = OFPT_PACKET_IN;
4871 opi->total_len = htons(total_len);
4872 opi->in_port = htons(odp_port_to_ofp_port(flow->in_port));
4873 opi->reason = upcall->type == _ODPL_MISS_NR ? OFPR_NO_MATCH : OFPR_ACTION;
4874 opi->buffer_id = htonl(buffer_id);
4875 update_openflow_length(packet);
4877 /* Hand over to packet scheduler. It might immediately call into
4878 * do_send_packet_in() or it might buffer it for a while (until a later
4879 * call to pinsched_run()). */
4880 pinsched_send(ofconn->schedulers[opi->reason], flow->in_port,
4881 packet, do_send_packet_in, ofconn);
4884 /* Given 'upcall', of type _ODPL_ACTION_NR or _ODPL_MISS_NR, sends an
4885 * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
4886 * their individual configurations.
4888 * Takes ownership of 'packet'. */
4890 send_packet_in(struct ofproto *ofproto, struct dpif_upcall *upcall,
4891 const struct flow *flow, bool clone)
4893 struct ofconn *ofconn, *prev;
4896 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
4897 if (ofconn_receives_async_msgs(ofconn)) {
4899 schedule_packet_in(prev, upcall, flow, true);
4905 schedule_packet_in(prev, upcall, flow, clone);
4906 } else if (!clone) {
4907 ofpbuf_delete(upcall->packet);
4912 pick_datapath_id(const struct ofproto *ofproto)
4914 const struct ofport *port;
4916 port = get_port(ofproto, ODPP_LOCAL);
4918 uint8_t ea[ETH_ADDR_LEN];
4921 error = netdev_get_etheraddr(port->netdev, ea);
4923 return eth_addr_to_uint64(ea);
4925 VLOG_WARN("could not get MAC address for %s (%s)",
4926 netdev_get_name(port->netdev), strerror(error));
4928 return ofproto->fallback_dpid;
4932 pick_fallback_dpid(void)
4934 uint8_t ea[ETH_ADDR_LEN];
4935 eth_addr_nicira_random(ea);
4936 return eth_addr_to_uint64(ea);
4940 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
4941 void *aux OVS_UNUSED)
4943 const struct shash_node *node;
4947 SHASH_FOR_EACH (node, &all_ofprotos) {
4948 ds_put_format(&results, "%s\n", node->name);
4950 unixctl_command_reply(conn, 200, ds_cstr(&results));
4951 ds_destroy(&results);
4954 struct ofproto_trace {
4955 struct action_xlate_ctx ctx;
4961 trace_format_rule(struct ds *result, int level, const struct rule *rule)
4963 ds_put_char_multiple(result, '\t', level);
4965 ds_put_cstr(result, "No match\n");
4969 ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
4970 ntohll(rule->flow_cookie));
4971 cls_rule_format(&rule->cr, result);
4972 ds_put_char(result, '\n');
4974 ds_put_char_multiple(result, '\t', level);
4975 ds_put_cstr(result, "OpenFlow ");
4976 ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
4977 rule->n_actions * sizeof *rule->actions);
4978 ds_put_char(result, '\n');
4982 trace_format_flow(struct ds *result, int level, const char *title,
4983 struct ofproto_trace *trace)
4985 ds_put_char_multiple(result, '\t', level);
4986 ds_put_format(result, "%s: ", title);
4987 if (flow_equal(&trace->ctx.flow, &trace->flow)) {
4988 ds_put_cstr(result, "unchanged");
4990 flow_format(result, &trace->ctx.flow);
4991 trace->flow = trace->ctx.flow;
4993 ds_put_char(result, '\n');
4997 trace_resubmit(struct action_xlate_ctx *ctx, const struct rule *rule)
4999 struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5000 struct ds *result = trace->result;
5002 ds_put_char(result, '\n');
5003 trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5004 trace_format_rule(result, ctx->recurse + 1, rule);
5008 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5009 void *aux OVS_UNUSED)
5011 char *dpname, *in_port_s, *tun_id_s, *packet_s;
5012 char *args = xstrdup(args_);
5013 char *save_ptr = NULL;
5014 struct ofproto *ofproto;
5015 struct ofpbuf packet;
5023 ofpbuf_init(&packet, strlen(args) / 2);
5026 dpname = strtok_r(args, " ", &save_ptr);
5027 tun_id_s = strtok_r(NULL, " ", &save_ptr);
5028 in_port_s = strtok_r(NULL, " ", &save_ptr);
5029 packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5030 if (!dpname || !in_port_s || !packet_s) {
5031 unixctl_command_reply(conn, 501, "Bad command syntax");
5035 ofproto = shash_find_data(&all_ofprotos, dpname);
5037 unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5042 tun_id = htonll(strtoull(tun_id_s, NULL, 10));
5043 in_port = ofp_port_to_odp_port(atoi(in_port_s));
5045 packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
5046 packet_s += strspn(packet_s, " ");
5047 if (*packet_s != '\0') {
5048 unixctl_command_reply(conn, 501, "Trailing garbage in command");
5051 if (packet.size < ETH_HEADER_LEN) {
5052 unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
5056 ds_put_cstr(&result, "Packet: ");
5057 s = ofp_packet_to_string(packet.data, packet.size, packet.size);
5058 ds_put_cstr(&result, s);
5061 flow_extract(&packet, tun_id, in_port, &flow);
5062 ds_put_cstr(&result, "Flow: ");
5063 flow_format(&result, &flow);
5064 ds_put_char(&result, '\n');
5066 rule = rule_lookup(ofproto, &flow);
5067 trace_format_rule(&result, 0, rule);
5069 struct ofproto_trace trace;
5070 struct ofpbuf *odp_actions;
5072 trace.result = &result;
5074 action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
5075 trace.ctx.resubmit_hook = trace_resubmit;
5076 odp_actions = xlate_actions(&trace.ctx,
5077 rule->actions, rule->n_actions);
5079 ds_put_char(&result, '\n');
5080 trace_format_flow(&result, 0, "Final flow", &trace);
5081 ds_put_cstr(&result, "Datapath actions: ");
5082 format_odp_actions(&result, odp_actions->data, odp_actions->size);
5083 ofpbuf_delete(odp_actions);
5086 unixctl_command_reply(conn, 200, ds_cstr(&result));
5089 ds_destroy(&result);
5090 ofpbuf_uninit(&packet);
5095 ofproto_unixctl_init(void)
5097 static bool registered;
5103 unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
5104 unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
5108 default_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
5109 struct ofpbuf *odp_actions, tag_type *tags,
5110 uint16_t *nf_output_iface, void *ofproto_)
5112 struct ofproto *ofproto = ofproto_;
5115 /* Drop frames for reserved multicast addresses. */
5116 if (eth_addr_is_reserved(flow->dl_dst)) {
5120 /* Learn source MAC (but don't try to learn from revalidation). */
5121 if (packet != NULL) {
5122 tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
5124 GRAT_ARP_LOCK_NONE);
5126 /* The log messages here could actually be useful in debugging,
5127 * so keep the rate limit relatively high. */
5128 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5129 VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
5130 ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
5131 ofproto_revalidate(ofproto, rev_tag);
5135 /* Determine output port. */
5136 out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags,
5139 flood_packets(ofproto, flow->in_port, OFPPC_NO_FLOOD,
5140 nf_output_iface, odp_actions);
5141 } else if (out_port != flow->in_port) {
5142 nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, out_port);
5143 *nf_output_iface = out_port;
5151 static const struct ofhooks default_ofhooks = {
5152 default_normal_ofhook_cb,