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,
2310 struct odp_flow_put *put)
2312 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2315 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2316 odp_flow_key_from_flow(&key, &facet->flow);
2317 assert(key.base == keybuf);
2319 memset(&put->flow.stats, 0, sizeof put->flow.stats);
2320 put->flow.key = key.data;
2321 put->flow.key_len = key.size;
2322 put->flow.actions = facet->actions;
2323 put->flow.actions_len = facet->actions_len;
2324 put->flow.flags = 0;
2326 return dpif_flow_put(ofproto->dpif, put);
2329 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath. If
2330 * 'zero_stats' is true, clears any existing statistics from the datapath for
2333 facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
2335 if (facet->may_install) {
2336 struct odp_flow_put put;
2339 flags = ODPPF_CREATE | ODPPF_MODIFY;
2341 flags |= ODPPF_ZERO_STATS;
2343 if (!facet_put__(p, facet, flags, &put)) {
2344 facet->installed = true;
2349 /* Ensures that the bytes in 'facet', plus 'extra_bytes', have been passed up
2350 * to the accounting hook function in the ofhooks structure. */
2352 facet_account(struct ofproto *ofproto,
2353 struct facet *facet, uint64_t extra_bytes)
2355 uint64_t total_bytes = facet->byte_count + extra_bytes;
2357 if (ofproto->ofhooks->account_flow_cb
2358 && total_bytes > facet->accounted_bytes)
2360 ofproto->ofhooks->account_flow_cb(
2361 &facet->flow, facet->tags, facet->actions, facet->actions_len,
2362 total_bytes - facet->accounted_bytes, ofproto->aux);
2363 facet->accounted_bytes = total_bytes;
2367 /* If 'rule' is installed in the datapath, uninstalls it. */
2369 facet_uninstall(struct ofproto *p, struct facet *facet)
2371 if (facet->installed) {
2372 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2373 struct odp_flow odp_flow;
2376 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2377 odp_flow_key_from_flow(&key, &facet->flow);
2378 assert(key.base == keybuf);
2380 odp_flow.key = key.data;
2381 odp_flow.key_len = key.size;
2382 odp_flow.actions = NULL;
2383 odp_flow.actions_len = 0;
2385 if (!dpif_flow_del(p->dpif, &odp_flow)) {
2386 facet_update_stats(p, facet, &odp_flow.stats);
2388 facet->installed = false;
2392 /* Returns true if the only action for 'facet' is to send to the controller.
2393 * (We don't report NetFlow expiration messages for such facets because they
2394 * are just part of the control logic for the network, not real traffic). */
2396 facet_is_controller_flow(struct facet *facet)
2399 && facet->rule->n_actions == 1
2400 && action_outputs_to_port(&facet->rule->actions[0],
2401 htons(OFPP_CONTROLLER)));
2404 /* Folds all of 'facet''s statistics into its rule. Also updates the
2405 * accounting ofhook and emits a NetFlow expiration if appropriate. */
2407 facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
2409 facet_account(ofproto, facet, 0);
2411 if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2412 struct ofexpired expired;
2413 expired.flow = facet->flow;
2414 expired.packet_count = facet->packet_count;
2415 expired.byte_count = facet->byte_count;
2416 expired.used = facet->used;
2417 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2420 facet->rule->packet_count += facet->packet_count;
2421 facet->rule->byte_count += facet->byte_count;
2423 /* Reset counters to prevent double counting if 'facet' ever gets
2425 facet->packet_count = 0;
2426 facet->byte_count = 0;
2427 facet->accounted_bytes = 0;
2429 netflow_flow_clear(&facet->nf_flow);
2432 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2433 * Returns it if found, otherwise a null pointer.
2435 * The returned facet might need revalidation; use facet_lookup_valid()
2436 * instead if that is important. */
2437 static struct facet *
2438 facet_find(struct ofproto *ofproto, const struct flow *flow)
2440 struct facet *facet;
2442 HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2444 if (flow_equal(flow, &facet->flow)) {
2452 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2453 * Returns it if found, otherwise a null pointer.
2455 * The returned facet is guaranteed to be valid. */
2456 static struct facet *
2457 facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
2459 struct facet *facet = facet_find(ofproto, flow);
2461 /* The facet we found might not be valid, since we could be in need of
2462 * revalidation. If it is not valid, don't return it. */
2464 && ofproto->need_revalidate
2465 && !facet_revalidate(ofproto, facet)) {
2466 COVERAGE_INC(ofproto_invalidated);
2473 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2475 * - If the rule found is different from 'facet''s current rule, moves
2476 * 'facet' to the new rule and recompiles its actions.
2478 * - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2479 * where it is and recompiles its actions anyway.
2481 * - If there is none, destroys 'facet'.
2483 * Returns true if 'facet' still exists, false if it has been destroyed. */
2485 facet_revalidate(struct ofproto *ofproto, struct facet *facet)
2487 struct action_xlate_ctx ctx;
2488 struct ofpbuf *odp_actions;
2489 struct rule *new_rule;
2490 bool actions_changed;
2492 COVERAGE_INC(facet_revalidate);
2494 /* Determine the new rule. */
2495 new_rule = rule_lookup(ofproto, &facet->flow);
2497 /* No new rule, so delete the facet. */
2498 facet_remove(ofproto, facet);
2502 /* Calculate new ODP actions.
2504 * We do not modify any 'facet' state yet, because we might need to, e.g.,
2505 * emit a NetFlow expiration and, if so, we need to have the old state
2506 * around to properly compose it. */
2507 action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2508 odp_actions = xlate_actions(&ctx, new_rule->actions, new_rule->n_actions);
2509 actions_changed = (facet->actions_len != odp_actions->size
2510 || memcmp(facet->actions, odp_actions->data,
2511 facet->actions_len));
2513 /* If the ODP actions changed or the installability changed, then we need
2514 * to talk to the datapath. */
2515 if (actions_changed || facet->may_install != facet->installed) {
2516 if (facet->may_install) {
2517 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2518 struct odp_flow_put put;
2521 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2522 odp_flow_key_from_flow(&key, &facet->flow);
2524 memset(&put.flow.stats, 0, sizeof put.flow.stats);
2525 put.flow.key = key.data;
2526 put.flow.key_len = key.size;
2527 put.flow.actions = odp_actions->data;
2528 put.flow.actions_len = odp_actions->size;
2530 put.flags = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS;
2531 dpif_flow_put(ofproto->dpif, &put);
2533 facet_update_stats(ofproto, facet, &put.flow.stats);
2535 facet_uninstall(ofproto, facet);
2538 /* The datapath flow is gone or has zeroed stats, so push stats out of
2539 * 'facet' into 'rule'. */
2540 facet_flush_stats(ofproto, facet);
2543 /* Update 'facet' now that we've taken care of all the old state. */
2544 facet->tags = ctx.tags;
2545 facet->nf_flow.output_iface = ctx.nf_output_iface;
2546 facet->may_install = ctx.may_set_up_flow;
2547 if (actions_changed) {
2548 free(facet->actions);
2549 facet->actions_len = odp_actions->size;
2550 facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2552 if (facet->rule != new_rule) {
2553 COVERAGE_INC(facet_changed_rule);
2554 list_remove(&facet->list_node);
2555 list_push_back(&new_rule->facets, &facet->list_node);
2556 facet->rule = new_rule;
2557 facet->used = new_rule->created;
2560 ofpbuf_delete(odp_actions);
2566 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
2567 struct rconn_packet_counter *counter)
2569 update_openflow_length(msg);
2570 if (rconn_send(ofconn->rconn, msg, counter)) {
2576 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
2579 struct ofpbuf *buf = ofputil_encode_error_msg(error, oh);
2581 COVERAGE_INC(ofproto_error);
2582 queue_tx(buf, ofconn, ofconn->reply_counter);
2587 hton_ofp_phy_port(struct ofp_phy_port *opp)
2589 opp->port_no = htons(opp->port_no);
2590 opp->config = htonl(opp->config);
2591 opp->state = htonl(opp->state);
2592 opp->curr = htonl(opp->curr);
2593 opp->advertised = htonl(opp->advertised);
2594 opp->supported = htonl(opp->supported);
2595 opp->peer = htonl(opp->peer);
2599 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2601 queue_tx(make_echo_reply(oh), ofconn, ofconn->reply_counter);
2606 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2608 struct ofp_switch_features *osf;
2610 struct ofport *port;
2612 osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
2613 osf->datapath_id = htonll(ofconn->ofproto->datapath_id);
2614 osf->n_buffers = htonl(pktbuf_capacity());
2616 osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
2617 OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
2618 osf->actions = htonl((1u << OFPAT_OUTPUT) |
2619 (1u << OFPAT_SET_VLAN_VID) |
2620 (1u << OFPAT_SET_VLAN_PCP) |
2621 (1u << OFPAT_STRIP_VLAN) |
2622 (1u << OFPAT_SET_DL_SRC) |
2623 (1u << OFPAT_SET_DL_DST) |
2624 (1u << OFPAT_SET_NW_SRC) |
2625 (1u << OFPAT_SET_NW_DST) |
2626 (1u << OFPAT_SET_NW_TOS) |
2627 (1u << OFPAT_SET_TP_SRC) |
2628 (1u << OFPAT_SET_TP_DST) |
2629 (1u << OFPAT_ENQUEUE));
2631 HMAP_FOR_EACH (port, hmap_node, &ofconn->ofproto->ports) {
2632 hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
2635 queue_tx(buf, ofconn, ofconn->reply_counter);
2640 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2643 struct ofp_switch_config *osc;
2647 /* Figure out flags. */
2648 dpif_get_drop_frags(ofconn->ofproto->dpif, &drop_frags);
2649 flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
2652 osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
2653 osc->flags = htons(flags);
2654 osc->miss_send_len = htons(ofconn->miss_send_len);
2655 queue_tx(buf, ofconn, ofconn->reply_counter);
2661 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
2663 uint16_t flags = ntohs(osc->flags);
2665 if (ofconn->type == OFCONN_PRIMARY && ofconn->role != NX_ROLE_SLAVE) {
2666 switch (flags & OFPC_FRAG_MASK) {
2667 case OFPC_FRAG_NORMAL:
2668 dpif_set_drop_frags(ofconn->ofproto->dpif, false);
2670 case OFPC_FRAG_DROP:
2671 dpif_set_drop_frags(ofconn->ofproto->dpif, true);
2674 VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
2680 ofconn->miss_send_len = ntohs(osc->miss_send_len);
2685 /* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
2686 * flow translation. */
2687 #define MAX_RESUBMIT_RECURSION 16
2689 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2690 struct action_xlate_ctx *ctx);
2693 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
2695 const struct ofport *ofport = get_port(ctx->ofproto, port);
2698 if (ofport->opp.config & OFPPC_NO_FWD) {
2699 /* Forwarding disabled on port. */
2704 * We don't have an ofport record for this port, but it doesn't hurt to
2705 * allow forwarding to it anyhow. Maybe such a port will appear later
2706 * and we're pre-populating the flow table.
2710 nl_msg_put_u32(ctx->odp_actions, ODPAT_OUTPUT, port);
2711 ctx->nf_output_iface = port;
2714 static struct rule *
2715 rule_lookup(struct ofproto *ofproto, const struct flow *flow)
2717 return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
2721 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2723 if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2724 uint16_t old_in_port;
2727 /* Look up a flow with 'in_port' as the input port. Then restore the
2728 * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2729 * have surprising behavior). */
2730 old_in_port = ctx->flow.in_port;
2731 ctx->flow.in_port = in_port;
2732 rule = rule_lookup(ctx->ofproto, &ctx->flow);
2733 ctx->flow.in_port = old_in_port;
2735 if (ctx->resubmit_hook) {
2736 ctx->resubmit_hook(ctx, rule);
2741 do_xlate_actions(rule->actions, rule->n_actions, ctx);
2745 static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2747 VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2748 MAX_RESUBMIT_RECURSION);
2753 flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, uint32_t mask,
2754 uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
2756 struct ofport *ofport;
2758 HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
2759 uint16_t odp_port = ofport->odp_port;
2760 if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
2761 nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, odp_port);
2764 *nf_output_iface = NF_OUT_FLOOD;
2768 xlate_output_action__(struct action_xlate_ctx *ctx,
2769 uint16_t port, uint16_t max_len)
2772 uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2774 ctx->nf_output_iface = NF_OUT_DROP;
2778 add_output_action(ctx, ctx->flow.in_port);
2781 xlate_table_action(ctx, ctx->flow.in_port);
2784 if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
2785 ctx->odp_actions, &ctx->tags,
2786 &ctx->nf_output_iface,
2787 ctx->ofproto->aux)) {
2788 COVERAGE_INC(ofproto_uninstallable);
2789 ctx->may_set_up_flow = false;
2793 flood_packets(ctx->ofproto, ctx->flow.in_port, OFPPC_NO_FLOOD,
2794 &ctx->nf_output_iface, ctx->odp_actions);
2797 flood_packets(ctx->ofproto, ctx->flow.in_port, 0,
2798 &ctx->nf_output_iface, ctx->odp_actions);
2800 case OFPP_CONTROLLER:
2801 nl_msg_put_u64(ctx->odp_actions, ODPAT_CONTROLLER, max_len);
2804 add_output_action(ctx, ODPP_LOCAL);
2807 odp_port = ofp_port_to_odp_port(port);
2808 if (odp_port != ctx->flow.in_port) {
2809 add_output_action(ctx, odp_port);
2814 if (prev_nf_output_iface == NF_OUT_FLOOD) {
2815 ctx->nf_output_iface = NF_OUT_FLOOD;
2816 } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2817 ctx->nf_output_iface = prev_nf_output_iface;
2818 } else if (prev_nf_output_iface != NF_OUT_DROP &&
2819 ctx->nf_output_iface != NF_OUT_FLOOD) {
2820 ctx->nf_output_iface = NF_OUT_MULTI;
2825 xlate_output_action(struct action_xlate_ctx *ctx,
2826 const struct ofp_action_output *oao)
2828 xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2831 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2832 * optimization, because we're going to add another action that sets the
2833 * priority immediately after, or because there are no actions following the
2836 remove_pop_action(struct action_xlate_ctx *ctx)
2838 if (ctx->odp_actions->size == ctx->last_pop_priority) {
2839 ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
2840 ctx->last_pop_priority = -1;
2845 add_pop_action(struct action_xlate_ctx *ctx)
2847 if (ctx->odp_actions->size != ctx->last_pop_priority) {
2848 nl_msg_put_flag(ctx->odp_actions, ODPAT_POP_PRIORITY);
2849 ctx->last_pop_priority = ctx->odp_actions->size;
2854 xlate_enqueue_action(struct action_xlate_ctx *ctx,
2855 const struct ofp_action_enqueue *oae)
2857 uint16_t ofp_port, odp_port;
2861 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2864 /* Fall back to ordinary output action. */
2865 xlate_output_action__(ctx, ntohs(oae->port), 0);
2869 /* Figure out ODP output port. */
2870 ofp_port = ntohs(oae->port);
2871 if (ofp_port != OFPP_IN_PORT) {
2872 odp_port = ofp_port_to_odp_port(ofp_port);
2874 odp_port = ctx->flow.in_port;
2877 /* Add ODP actions. */
2878 remove_pop_action(ctx);
2879 nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2880 add_output_action(ctx, odp_port);
2881 add_pop_action(ctx);
2883 /* Update NetFlow output port. */
2884 if (ctx->nf_output_iface == NF_OUT_DROP) {
2885 ctx->nf_output_iface = odp_port;
2886 } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2887 ctx->nf_output_iface = NF_OUT_MULTI;
2892 xlate_set_queue_action(struct action_xlate_ctx *ctx,
2893 const struct nx_action_set_queue *nasq)
2898 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2901 /* Couldn't translate queue to a priority, so ignore. A warning
2902 * has already been logged. */
2906 remove_pop_action(ctx);
2907 nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2911 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2913 ovs_be16 tci = ctx->flow.vlan_tci;
2914 if (!(tci & htons(VLAN_CFI))) {
2915 nl_msg_put_flag(ctx->odp_actions, ODPAT_STRIP_VLAN);
2917 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_DL_TCI,
2918 tci & ~htons(VLAN_CFI));
2922 struct xlate_reg_state {
2928 save_reg_state(const struct action_xlate_ctx *ctx,
2929 struct xlate_reg_state *state)
2931 state->vlan_tci = ctx->flow.vlan_tci;
2932 state->tun_id = ctx->flow.tun_id;
2936 update_reg_state(struct action_xlate_ctx *ctx,
2937 const struct xlate_reg_state *state)
2939 if (ctx->flow.vlan_tci != state->vlan_tci) {
2940 xlate_set_dl_tci(ctx);
2942 if (ctx->flow.tun_id != state->tun_id) {
2943 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, ctx->flow.tun_id);
2948 xlate_nicira_action(struct action_xlate_ctx *ctx,
2949 const struct nx_action_header *nah)
2951 const struct nx_action_resubmit *nar;
2952 const struct nx_action_set_tunnel *nast;
2953 const struct nx_action_set_queue *nasq;
2954 const struct nx_action_multipath *nam;
2955 enum nx_action_subtype subtype = ntohs(nah->subtype);
2956 struct xlate_reg_state state;
2959 assert(nah->vendor == htonl(NX_VENDOR_ID));
2961 case NXAST_RESUBMIT:
2962 nar = (const struct nx_action_resubmit *) nah;
2963 xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2966 case NXAST_SET_TUNNEL:
2967 nast = (const struct nx_action_set_tunnel *) nah;
2968 tun_id = htonll(ntohl(nast->tun_id));
2969 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
2970 ctx->flow.tun_id = tun_id;
2973 case NXAST_DROP_SPOOFED_ARP:
2974 if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
2975 nl_msg_put_flag(ctx->odp_actions, ODPAT_DROP_SPOOFED_ARP);
2979 case NXAST_SET_QUEUE:
2980 nasq = (const struct nx_action_set_queue *) nah;
2981 xlate_set_queue_action(ctx, nasq);
2984 case NXAST_POP_QUEUE:
2985 add_pop_action(ctx);
2988 case NXAST_REG_MOVE:
2989 save_reg_state(ctx, &state);
2990 nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
2992 update_reg_state(ctx, &state);
2995 case NXAST_REG_LOAD:
2996 save_reg_state(ctx, &state);
2997 nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
2999 update_reg_state(ctx, &state);
3003 /* Nothing to do. */
3006 case NXAST_SET_TUNNEL64:
3007 tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
3008 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
3009 ctx->flow.tun_id = tun_id;
3012 case NXAST_MULTIPATH:
3013 nam = (const struct nx_action_multipath *) nah;
3014 multipath_execute(nam, &ctx->flow);
3017 /* If you add a new action here that modifies flow data, don't forget to
3018 * update the flow key in ctx->flow at the same time. */
3020 case NXAST_SNAT__OBSOLETE:
3022 VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
3028 do_xlate_actions(const union ofp_action *in, size_t n_in,
3029 struct action_xlate_ctx *ctx)
3031 struct actions_iterator iter;
3032 const union ofp_action *ia;
3033 const struct ofport *port;
3035 port = get_port(ctx->ofproto, ctx->flow.in_port);
3036 if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
3037 port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
3038 ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
3039 /* Drop this flow. */
3043 for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
3044 enum ofp_action_type type = ntohs(ia->type);
3045 const struct ofp_action_dl_addr *oada;
3049 xlate_output_action(ctx, &ia->output);
3052 case OFPAT_SET_VLAN_VID:
3053 ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3054 ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
3055 xlate_set_dl_tci(ctx);
3058 case OFPAT_SET_VLAN_PCP:
3059 ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3060 ctx->flow.vlan_tci |= htons(
3061 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
3062 xlate_set_dl_tci(ctx);
3065 case OFPAT_STRIP_VLAN:
3066 ctx->flow.vlan_tci = htons(0);
3067 xlate_set_dl_tci(ctx);
3070 case OFPAT_SET_DL_SRC:
3071 oada = ((struct ofp_action_dl_addr *) ia);
3072 nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_SRC,
3073 oada->dl_addr, ETH_ADDR_LEN);
3074 memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
3077 case OFPAT_SET_DL_DST:
3078 oada = ((struct ofp_action_dl_addr *) ia);
3079 nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_DST,
3080 oada->dl_addr, ETH_ADDR_LEN);
3081 memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
3084 case OFPAT_SET_NW_SRC:
3085 nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_SRC,
3086 ia->nw_addr.nw_addr);
3087 ctx->flow.nw_src = ia->nw_addr.nw_addr;
3090 case OFPAT_SET_NW_DST:
3091 nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_DST,
3092 ia->nw_addr.nw_addr);
3093 ctx->flow.nw_dst = ia->nw_addr.nw_addr;
3096 case OFPAT_SET_NW_TOS:
3097 nl_msg_put_u8(ctx->odp_actions, ODPAT_SET_NW_TOS,
3099 ctx->flow.nw_tos = ia->nw_tos.nw_tos;
3102 case OFPAT_SET_TP_SRC:
3103 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_SRC,
3104 ia->tp_port.tp_port);
3105 ctx->flow.tp_src = ia->tp_port.tp_port;
3108 case OFPAT_SET_TP_DST:
3109 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_DST,
3110 ia->tp_port.tp_port);
3111 ctx->flow.tp_dst = ia->tp_port.tp_port;
3115 xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
3119 xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3123 VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
3130 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3131 struct ofproto *ofproto, const struct flow *flow,
3132 const struct ofpbuf *packet)
3134 ctx->ofproto = ofproto;
3136 ctx->packet = packet;
3137 ctx->resubmit_hook = NULL;
3140 static struct ofpbuf *
3141 xlate_actions(struct action_xlate_ctx *ctx,
3142 const union ofp_action *in, size_t n_in)
3144 COVERAGE_INC(ofproto_ofp2odp);
3146 ctx->odp_actions = ofpbuf_new(512);
3148 ctx->may_set_up_flow = true;
3149 ctx->nf_output_iface = NF_OUT_DROP;
3151 ctx->last_pop_priority = -1;
3152 do_xlate_actions(in, n_in, ctx);
3153 remove_pop_action(ctx);
3155 /* Check with in-band control to see if we're allowed to set up this
3157 if (!in_band_rule_check(ctx->ofproto->in_band, &ctx->flow,
3158 ctx->odp_actions->data, ctx->odp_actions->size)) {
3159 ctx->may_set_up_flow = false;
3162 return ctx->odp_actions;
3165 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
3166 * error message code (composed with ofp_mkerr()) for the caller to propagate
3167 * upward. Otherwise, returns 0.
3169 * The log message mentions 'msg_type'. */
3171 reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
3173 if (ofconn->type == OFCONN_PRIMARY && ofconn->role == NX_ROLE_SLAVE) {
3174 static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
3175 VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
3178 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3185 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
3187 struct ofproto *p = ofconn->ofproto;
3188 struct ofp_packet_out *opo;
3189 struct ofpbuf payload, *buffer;
3190 union ofp_action *ofp_actions;
3191 struct action_xlate_ctx ctx;
3192 struct ofpbuf *odp_actions;
3193 struct ofpbuf request;
3195 size_t n_ofp_actions;
3199 COVERAGE_INC(ofproto_packet_out);
3201 error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
3206 /* Get ofp_packet_out. */
3207 ofpbuf_use_const(&request, oh, ntohs(oh->length));
3208 opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
3211 error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
3212 &ofp_actions, &n_ofp_actions);
3218 if (opo->buffer_id != htonl(UINT32_MAX)) {
3219 error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
3221 if (error || !buffer) {
3230 /* Extract flow, check actions. */
3231 flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
3233 error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
3239 action_xlate_ctx_init(&ctx, p, &flow, &payload);
3240 odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
3241 dpif_execute(p->dpif, odp_actions->data, odp_actions->size, &payload);
3242 ofpbuf_delete(odp_actions);
3245 ofpbuf_delete(buffer);
3250 update_port_config(struct ofproto *p, struct ofport *port,
3251 uint32_t config, uint32_t mask)
3253 mask &= config ^ port->opp.config;
3254 if (mask & OFPPC_PORT_DOWN) {
3255 if (config & OFPPC_PORT_DOWN) {
3256 netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
3258 netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
3261 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | \
3262 OFPPC_NO_FWD | OFPPC_NO_FLOOD)
3263 if (mask & REVALIDATE_BITS) {
3264 COVERAGE_INC(ofproto_costly_flags);
3265 port->opp.config ^= mask & REVALIDATE_BITS;
3266 p->need_revalidate = true;
3268 #undef REVALIDATE_BITS
3269 if (mask & OFPPC_NO_PACKET_IN) {
3270 port->opp.config ^= OFPPC_NO_PACKET_IN;
3275 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3277 struct ofproto *p = ofconn->ofproto;
3278 const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
3279 struct ofport *port;
3282 error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
3287 port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
3289 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
3290 } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
3291 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
3293 update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
3294 if (opm->advertise) {
3295 netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
3301 static struct ofpbuf *
3302 make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
3304 struct ofp_stats_reply *osr;
3307 msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
3308 osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
3310 osr->flags = htons(0);
3314 static struct ofpbuf *
3315 start_ofp_stats_reply(const struct ofp_header *request, size_t body_len)
3317 const struct ofp_stats_request *osr
3318 = (const struct ofp_stats_request *) request;
3319 return make_ofp_stats_reply(osr->header.xid, osr->type, body_len);
3323 append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
3324 struct ofpbuf **msgp)
3326 struct ofpbuf *msg = *msgp;
3327 assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
3328 if (nbytes + msg->size > UINT16_MAX) {
3329 struct ofp_stats_reply *reply = msg->data;
3330 reply->flags = htons(OFPSF_REPLY_MORE);
3331 *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
3332 queue_tx(msg, ofconn, ofconn->reply_counter);
3334 return ofpbuf_put_uninit(*msgp, nbytes);
3337 static struct ofpbuf *
3338 make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
3340 struct nicira_stats_msg *nsm;
3343 msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
3344 nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
3345 nsm->type = htons(OFPST_VENDOR);
3346 nsm->flags = htons(0);
3347 nsm->vendor = htonl(NX_VENDOR_ID);
3348 nsm->subtype = subtype;
3352 static struct ofpbuf *
3353 start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
3355 return make_nxstats_reply(request->header.xid, request->subtype, body_len);
3359 append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
3360 struct ofpbuf **msgp)
3362 struct ofpbuf *msg = *msgp;
3363 assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
3364 if (nbytes + msg->size > UINT16_MAX) {
3365 struct nicira_stats_msg *reply = msg->data;
3366 reply->flags = htons(OFPSF_REPLY_MORE);
3367 *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
3368 queue_tx(msg, ofconn, ofconn->reply_counter);
3370 ofpbuf_prealloc_tailroom(*msgp, nbytes);
3374 handle_desc_stats_request(struct ofconn *ofconn,
3375 const struct ofp_header *request)
3377 struct ofproto *p = ofconn->ofproto;
3378 struct ofp_desc_stats *ods;
3381 msg = start_ofp_stats_reply(request, sizeof *ods);
3382 ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
3383 memset(ods, 0, sizeof *ods);
3384 ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
3385 ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
3386 ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
3387 ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
3388 ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
3389 queue_tx(msg, ofconn, ofconn->reply_counter);
3395 handle_table_stats_request(struct ofconn *ofconn,
3396 const struct ofp_header *request)
3398 struct ofproto *p = ofconn->ofproto;
3399 struct ofp_table_stats *ots;
3402 msg = start_ofp_stats_reply(request, sizeof *ots * 2);
3404 /* Classifier table. */
3405 ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
3406 memset(ots, 0, sizeof *ots);
3407 strcpy(ots->name, "classifier");
3408 ots->wildcards = (ofconn->flow_format == NXFF_OPENFLOW10
3409 ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
3410 ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
3411 ots->active_count = htonl(classifier_count(&p->cls));
3412 ots->lookup_count = htonll(0); /* XXX */
3413 ots->matched_count = htonll(0); /* XXX */
3415 queue_tx(msg, ofconn, ofconn->reply_counter);
3420 append_port_stat(struct ofport *port, struct ofconn *ofconn,
3421 struct ofpbuf **msgp)
3423 struct netdev_stats stats;
3424 struct ofp_port_stats *ops;
3426 /* Intentionally ignore return value, since errors will set
3427 * 'stats' to all-1s, which is correct for OpenFlow, and
3428 * netdev_get_stats() will log errors. */
3429 netdev_get_stats(port->netdev, &stats);
3431 ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
3432 ops->port_no = htons(port->opp.port_no);
3433 memset(ops->pad, 0, sizeof ops->pad);
3434 ops->rx_packets = htonll(stats.rx_packets);
3435 ops->tx_packets = htonll(stats.tx_packets);
3436 ops->rx_bytes = htonll(stats.rx_bytes);
3437 ops->tx_bytes = htonll(stats.tx_bytes);
3438 ops->rx_dropped = htonll(stats.rx_dropped);
3439 ops->tx_dropped = htonll(stats.tx_dropped);
3440 ops->rx_errors = htonll(stats.rx_errors);
3441 ops->tx_errors = htonll(stats.tx_errors);
3442 ops->rx_frame_err = htonll(stats.rx_frame_errors);
3443 ops->rx_over_err = htonll(stats.rx_over_errors);
3444 ops->rx_crc_err = htonll(stats.rx_crc_errors);
3445 ops->collisions = htonll(stats.collisions);
3449 handle_port_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3451 struct ofproto *p = ofconn->ofproto;
3452 const struct ofp_port_stats_request *psr = ofputil_stats_body(oh);
3453 struct ofp_port_stats *ops;
3455 struct ofport *port;
3457 msg = start_ofp_stats_reply(oh, sizeof *ops * 16);
3458 if (psr->port_no != htons(OFPP_NONE)) {
3459 port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
3461 append_port_stat(port, ofconn, &msg);
3464 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3465 append_port_stat(port, ofconn, &msg);
3469 queue_tx(msg, ofconn, ofconn->reply_counter);
3473 /* Obtains statistic counters for 'rule' within 'p' and stores them into
3474 * '*packet_countp' and '*byte_countp'. The returned statistics include
3475 * statistics for all of 'rule''s facets. */
3477 query_stats(struct ofproto *p, struct rule *rule,
3478 uint64_t *packet_countp, uint64_t *byte_countp)
3480 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
3481 uint64_t packet_count, byte_count;
3482 struct facet *facet;
3485 /* Start from historical data for 'rule' itself that are no longer tracked
3486 * by the datapath. This counts, for example, facets that have expired. */
3487 packet_count = rule->packet_count;
3488 byte_count = rule->byte_count;
3490 /* Ask the datapath for statistics on all of the rule's facets.
3492 * Also, add any statistics that are not tracked by the datapath for each
3493 * facet. This includes, for example, statistics for packets that were
3494 * executed "by hand" by ofproto via dpif_execute() but must be accounted
3496 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
3497 LIST_FOR_EACH (facet, list_node, &rule->facets) {
3498 struct odp_flow odp_flow;
3501 odp_flow_key_from_flow(&key, &facet->flow);
3503 odp_flow.key = key.data;
3504 odp_flow.key_len = key.size;
3505 odp_flow.actions = NULL;
3506 odp_flow.actions_len = 0;
3508 if (!dpif_flow_get(p->dpif, &odp_flow)) {
3509 packet_count += odp_flow.stats.n_packets;
3510 byte_count += odp_flow.stats.n_bytes;
3513 packet_count += facet->packet_count;
3514 byte_count += facet->byte_count;
3517 /* Return the stats to the caller. */
3518 *packet_countp = packet_count;
3519 *byte_countp = byte_count;
3523 calc_flow_duration(long long int start, ovs_be32 *sec, ovs_be32 *nsec)
3525 long long int msecs = time_msec() - start;
3526 *sec = htonl(msecs / 1000);
3527 *nsec = htonl((msecs % 1000) * (1000 * 1000));
3531 put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
3532 ovs_be16 out_port, struct ofpbuf **replyp)
3534 struct ofp_flow_stats *ofs;
3535 uint64_t packet_count, byte_count;
3536 size_t act_len, len;
3538 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3542 act_len = sizeof *rule->actions * rule->n_actions;
3543 len = offsetof(struct ofp_flow_stats, actions) + act_len;
3545 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3547 ofs = append_ofp_stats_reply(len, ofconn, replyp);
3548 ofs->length = htons(len);
3551 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofs->match,
3552 rule->flow_cookie, &ofs->cookie);
3553 calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
3554 ofs->priority = htons(rule->cr.priority);
3555 ofs->idle_timeout = htons(rule->idle_timeout);
3556 ofs->hard_timeout = htons(rule->hard_timeout);
3557 memset(ofs->pad2, 0, sizeof ofs->pad2);
3558 ofs->packet_count = htonll(packet_count);
3559 ofs->byte_count = htonll(byte_count);
3560 if (rule->n_actions > 0) {
3561 memcpy(ofs->actions, rule->actions, act_len);
3566 is_valid_table(uint8_t table_id)
3568 return table_id == 0 || table_id == 0xff;
3572 handle_flow_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3574 const struct ofp_flow_stats_request *fsr = ofputil_stats_body(oh);
3575 struct ofpbuf *reply;
3577 COVERAGE_INC(ofproto_flows_req);
3578 reply = start_ofp_stats_reply(oh, 1024);
3579 if (is_valid_table(fsr->table_id)) {
3580 struct cls_cursor cursor;
3581 struct cls_rule target;
3584 ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
3586 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3587 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3588 put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
3591 queue_tx(reply, ofconn, ofconn->reply_counter);
3597 put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
3598 ovs_be16 out_port, struct ofpbuf **replyp)
3600 struct nx_flow_stats *nfs;
3601 uint64_t packet_count, byte_count;
3602 size_t act_len, start_len;
3603 struct ofpbuf *reply;
3605 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3609 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3611 act_len = sizeof *rule->actions * rule->n_actions;
3613 append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
3614 start_len = (*replyp)->size;
3617 nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
3620 calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
3621 nfs->cookie = rule->flow_cookie;
3622 nfs->priority = htons(rule->cr.priority);
3623 nfs->idle_timeout = htons(rule->idle_timeout);
3624 nfs->hard_timeout = htons(rule->hard_timeout);
3625 nfs->match_len = htons(nx_put_match(reply, &rule->cr));
3626 memset(nfs->pad2, 0, sizeof nfs->pad2);
3627 nfs->packet_count = htonll(packet_count);
3628 nfs->byte_count = htonll(byte_count);
3629 if (rule->n_actions > 0) {
3630 ofpbuf_put(reply, rule->actions, act_len);
3632 nfs->length = htons(reply->size - start_len);
3636 handle_nxst_flow(struct ofconn *ofconn, const struct ofp_header *oh)
3638 struct nx_flow_stats_request *nfsr;
3639 struct cls_rule target;
3640 struct ofpbuf *reply;
3644 ofpbuf_use_const(&b, oh, ntohs(oh->length));
3646 /* Dissect the message. */
3647 nfsr = ofpbuf_pull(&b, sizeof *nfsr);
3648 error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &target);
3653 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3656 COVERAGE_INC(ofproto_flows_req);
3657 reply = start_nxstats_reply(&nfsr->nsm, 1024);
3658 if (is_valid_table(nfsr->table_id)) {
3659 struct cls_cursor cursor;
3662 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3663 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3664 put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
3667 queue_tx(reply, ofconn, ofconn->reply_counter);
3673 flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
3675 uint64_t packet_count, byte_count;
3676 size_t act_len = sizeof *rule->actions * rule->n_actions;
3678 query_stats(ofproto, rule, &packet_count, &byte_count);
3680 ds_put_format(results, "duration=%llds, ",
3681 (time_msec() - rule->created) / 1000);
3682 ds_put_format(results, "priority=%u, ", rule->cr.priority);
3683 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3684 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3685 cls_rule_format(&rule->cr, results);
3687 ofp_print_actions(results, &rule->actions->header, act_len);
3689 ds_put_cstr(results, "drop");
3691 ds_put_cstr(results, "\n");
3694 /* Adds a pretty-printed description of all flows to 'results', including
3695 * those marked hidden by secchan (e.g., by in-band control). */
3697 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3699 struct cls_cursor cursor;
3702 cls_cursor_init(&cursor, &p->cls, NULL);
3703 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3704 flow_stats_ds(p, rule, results);
3709 query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
3710 ovs_be16 out_port, uint8_t table_id,
3711 struct ofp_aggregate_stats_reply *oasr)
3713 uint64_t total_packets = 0;
3714 uint64_t total_bytes = 0;
3717 COVERAGE_INC(ofproto_agg_request);
3719 if (is_valid_table(table_id)) {
3720 struct cls_cursor cursor;
3723 cls_cursor_init(&cursor, &ofproto->cls, target);
3724 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3725 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
3726 uint64_t packet_count;
3727 uint64_t byte_count;
3729 query_stats(ofproto, rule, &packet_count, &byte_count);
3731 total_packets += packet_count;
3732 total_bytes += byte_count;
3738 oasr->flow_count = htonl(n_flows);
3739 oasr->packet_count = htonll(total_packets);
3740 oasr->byte_count = htonll(total_bytes);
3741 memset(oasr->pad, 0, sizeof oasr->pad);
3745 handle_aggregate_stats_request(struct ofconn *ofconn,
3746 const struct ofp_header *oh)
3748 const struct ofp_aggregate_stats_request *request = ofputil_stats_body(oh);
3749 struct ofp_aggregate_stats_reply *reply;
3750 struct cls_rule target;
3753 ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
3756 msg = start_ofp_stats_reply(oh, sizeof *reply);
3757 reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
3758 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3759 request->table_id, reply);
3760 queue_tx(msg, ofconn, ofconn->reply_counter);
3765 handle_nxst_aggregate(struct ofconn *ofconn, const struct ofp_header *oh)
3767 struct nx_aggregate_stats_request *request;
3768 struct ofp_aggregate_stats_reply *reply;
3769 struct cls_rule target;
3774 ofpbuf_use_const(&b, oh, ntohs(oh->length));
3776 /* Dissect the message. */
3777 request = ofpbuf_pull(&b, sizeof *request);
3778 error = nx_pull_match(&b, ntohs(request->match_len), 0, &target);
3783 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3787 COVERAGE_INC(ofproto_flows_req);
3788 buf = start_nxstats_reply(&request->nsm, sizeof *reply);
3789 reply = ofpbuf_put_uninit(buf, sizeof *reply);
3790 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3791 request->table_id, reply);
3792 queue_tx(buf, ofconn, ofconn->reply_counter);
3797 struct queue_stats_cbdata {
3798 struct ofconn *ofconn;
3799 struct ofport *ofport;
3804 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3805 const struct netdev_queue_stats *stats)
3807 struct ofp_queue_stats *reply;
3809 reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
3810 reply->port_no = htons(cbdata->ofport->opp.port_no);
3811 memset(reply->pad, 0, sizeof reply->pad);
3812 reply->queue_id = htonl(queue_id);
3813 reply->tx_bytes = htonll(stats->tx_bytes);
3814 reply->tx_packets = htonll(stats->tx_packets);
3815 reply->tx_errors = htonll(stats->tx_errors);
3819 handle_queue_stats_dump_cb(uint32_t queue_id,
3820 struct netdev_queue_stats *stats,
3823 struct queue_stats_cbdata *cbdata = cbdata_;
3825 put_queue_stats(cbdata, queue_id, stats);
3829 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3830 struct queue_stats_cbdata *cbdata)
3832 cbdata->ofport = port;
3833 if (queue_id == OFPQ_ALL) {
3834 netdev_dump_queue_stats(port->netdev,
3835 handle_queue_stats_dump_cb, cbdata);
3837 struct netdev_queue_stats stats;
3839 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3840 put_queue_stats(cbdata, queue_id, &stats);
3846 handle_queue_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3848 struct ofproto *ofproto = ofconn->ofproto;
3849 const struct ofp_queue_stats_request *qsr;
3850 struct queue_stats_cbdata cbdata;
3851 struct ofport *port;
3852 unsigned int port_no;
3855 qsr = ofputil_stats_body(oh);
3857 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3860 COVERAGE_INC(ofproto_queue_req);
3862 cbdata.ofconn = ofconn;
3863 cbdata.msg = start_ofp_stats_reply(oh, 128);
3865 port_no = ntohs(qsr->port_no);
3866 queue_id = ntohl(qsr->queue_id);
3867 if (port_no == OFPP_ALL) {
3868 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3869 handle_queue_stats_for_port(port, queue_id, &cbdata);
3871 } else if (port_no < ofproto->max_ports) {
3872 port = get_port(ofproto, ofp_port_to_odp_port(port_no));
3874 handle_queue_stats_for_port(port, queue_id, &cbdata);
3877 ofpbuf_delete(cbdata.msg);
3878 return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
3880 queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
3885 static long long int
3886 msec_from_nsec(uint64_t sec, uint32_t nsec)
3888 return !sec ? 0 : sec * 1000 + nsec / 1000000;
3892 facet_update_time(struct ofproto *ofproto, struct facet *facet,
3893 const struct odp_flow_stats *stats)
3895 long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
3896 if (used > facet->used) {
3898 if (used > facet->rule->used) {
3899 facet->rule->used = used;
3901 netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3905 /* Folds the statistics from 'stats' into the counters in 'facet'.
3907 * Because of the meaning of a facet's counters, it only makes sense to do this
3908 * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3909 * packet that was sent by hand or if it represents statistics that have been
3910 * cleared out of the datapath. */
3912 facet_update_stats(struct ofproto *ofproto, struct facet *facet,
3913 const struct odp_flow_stats *stats)
3915 if (stats->n_packets) {
3916 facet_update_time(ofproto, facet, stats);
3917 facet->packet_count += stats->n_packets;
3918 facet->byte_count += stats->n_bytes;
3919 netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3923 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3924 * in which no matching flow already exists in the flow table.
3926 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3927 * ofp_actions, to ofconn->ofproto's flow table. Returns 0 on success or an
3928 * OpenFlow error code as encoded by ofp_mkerr() on failure.
3930 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3933 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
3935 struct ofproto *p = ofconn->ofproto;
3936 struct ofpbuf *packet;
3941 if (fm->flags & OFPFF_CHECK_OVERLAP
3942 && classifier_rule_overlaps(&p->cls, &fm->cr)) {
3943 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
3947 if (fm->buffer_id != UINT32_MAX) {
3948 error = pktbuf_retrieve(ofconn->pktbuf, fm->buffer_id,
3952 in_port = UINT16_MAX;
3955 rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
3956 fm->idle_timeout, fm->hard_timeout, fm->cookie,
3957 fm->flags & OFPFF_SEND_FLOW_REM);
3958 rule_insert(p, rule);
3960 rule_execute(p, rule, in_port, packet);
3965 static struct rule *
3966 find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
3968 return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
3972 send_buffered_packet(struct ofconn *ofconn,
3973 struct rule *rule, uint32_t buffer_id)
3975 struct ofpbuf *packet;
3979 if (buffer_id == UINT32_MAX) {
3983 error = pktbuf_retrieve(ofconn->pktbuf, buffer_id, &packet, &in_port);
3988 rule_execute(ofconn->ofproto, rule, in_port, packet);
3993 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3995 struct modify_flows_cbdata {
3996 struct ofproto *ofproto;
3997 const struct flow_mod *fm;
4001 static int modify_flow(struct ofproto *, const struct flow_mod *,
4004 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code as
4005 * encoded by ofp_mkerr() on failure.
4007 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4010 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
4012 struct ofproto *p = ofconn->ofproto;
4013 struct rule *match = NULL;
4014 struct cls_cursor cursor;
4017 cls_cursor_init(&cursor, &p->cls, &fm->cr);
4018 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4019 if (!rule_is_hidden(rule)) {
4021 modify_flow(p, fm, rule);
4026 /* This credits the packet to whichever flow happened to match last.
4027 * That's weird. Maybe we should do a lookup for the flow that
4028 * actually matches the packet? Who knows. */
4029 send_buffered_packet(ofconn, match, fm->buffer_id);
4032 return add_flow(ofconn, fm);
4036 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4037 * code as encoded by ofp_mkerr() on failure.
4039 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4042 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
4044 struct ofproto *p = ofconn->ofproto;
4045 struct rule *rule = find_flow_strict(p, fm);
4046 if (rule && !rule_is_hidden(rule)) {
4047 modify_flow(p, fm, rule);
4048 return send_buffered_packet(ofconn, rule, fm->buffer_id);
4050 return add_flow(ofconn, fm);
4054 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
4055 * been identified as a flow in 'p''s flow table to be modified, by changing
4056 * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
4057 * ofp_action[] structures). */
4059 modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
4061 size_t actions_len = fm->n_actions * sizeof *rule->actions;
4063 rule->flow_cookie = fm->cookie;
4065 /* If the actions are the same, do nothing. */
4066 if (fm->n_actions == rule->n_actions
4068 || !memcmp(fm->actions, rule->actions, actions_len))) {
4072 /* Replace actions. */
4073 free(rule->actions);
4074 rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
4075 rule->n_actions = fm->n_actions;
4077 p->need_revalidate = true;
4082 /* OFPFC_DELETE implementation. */
4084 static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
4086 /* Implements OFPFC_DELETE. */
4088 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
4090 struct rule *rule, *next_rule;
4091 struct cls_cursor cursor;
4093 cls_cursor_init(&cursor, &p->cls, &fm->cr);
4094 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4095 delete_flow(p, rule, htons(fm->out_port));
4099 /* Implements OFPFC_DELETE_STRICT. */
4101 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
4103 struct rule *rule = find_flow_strict(p, fm);
4105 delete_flow(p, rule, htons(fm->out_port));
4109 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
4110 * been identified as a flow to delete from 'p''s flow table, by deleting the
4111 * flow and sending out a OFPT_FLOW_REMOVED message to any interested
4114 * Will not delete 'rule' if it is hidden. Will delete 'rule' only if
4115 * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
4116 * specified 'out_port'. */
4118 delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
4120 if (rule_is_hidden(rule)) {
4124 if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
4128 rule_send_removed(p, rule, OFPRR_DELETE);
4129 rule_remove(p, rule);
4133 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4135 struct ofproto *p = ofconn->ofproto;
4139 error = reject_slave_controller(ofconn, "flow_mod");
4144 error = ofputil_decode_flow_mod(&fm, oh, ofconn->flow_format);
4149 /* We do not support the emergency flow cache. It will hopefully get
4150 * dropped from OpenFlow in the near future. */
4151 if (fm.flags & OFPFF_EMERG) {
4152 /* There isn't a good fit for an error code, so just state that the
4153 * flow table is full. */
4154 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
4157 error = validate_actions(fm.actions, fm.n_actions,
4158 &fm.cr.flow, p->max_ports);
4163 switch (fm.command) {
4165 return add_flow(ofconn, &fm);
4168 return modify_flows_loose(ofconn, &fm);
4170 case OFPFC_MODIFY_STRICT:
4171 return modify_flow_strict(ofconn, &fm);
4174 delete_flows_loose(p, &fm);
4177 case OFPFC_DELETE_STRICT:
4178 delete_flow_strict(p, &fm);
4182 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
4187 handle_tun_id_from_cookie(struct ofconn *ofconn, const struct ofp_header *oh)
4189 const struct nxt_tun_id_cookie *msg
4190 = (const struct nxt_tun_id_cookie *) oh;
4192 ofconn->flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
4197 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4199 struct nx_role_request *nrr = (struct nx_role_request *) oh;
4200 struct nx_role_request *reply;
4204 if (ofconn->type != OFCONN_PRIMARY) {
4205 VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
4207 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4210 role = ntohl(nrr->role);
4211 if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
4212 && role != NX_ROLE_SLAVE) {
4213 VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
4215 /* There's no good error code for this. */
4216 return ofp_mkerr(OFPET_BAD_REQUEST, -1);
4219 if (role == NX_ROLE_MASTER) {
4220 struct ofconn *other;
4222 HMAP_FOR_EACH (other, hmap_node, &ofconn->ofproto->controllers) {
4223 if (other->role == NX_ROLE_MASTER) {
4224 other->role = NX_ROLE_SLAVE;
4228 ofconn->role = role;
4230 reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
4231 reply->role = htonl(role);
4232 queue_tx(buf, ofconn, ofconn->reply_counter);
4238 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4240 const struct nxt_set_flow_format *msg
4241 = (const struct nxt_set_flow_format *) oh;
4244 format = ntohl(msg->format);
4245 if (format == NXFF_OPENFLOW10
4246 || format == NXFF_TUN_ID_FROM_COOKIE
4247 || format == NXFF_NXM) {
4248 ofconn->flow_format = format;
4251 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4256 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4258 struct ofp_header *ob;
4261 /* Currently, everything executes synchronously, so we can just
4262 * immediately send the barrier reply. */
4263 ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
4264 queue_tx(buf, ofconn, ofconn->reply_counter);
4269 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4271 const struct ofp_header *oh = msg->data;
4272 const struct ofputil_msg_type *type;
4275 error = ofputil_decode_msg_type(oh, &type);
4280 switch (ofputil_msg_type_code(type)) {
4281 /* OpenFlow requests. */
4282 case OFPUTIL_OFPT_ECHO_REQUEST:
4283 return handle_echo_request(ofconn, oh);
4285 case OFPUTIL_OFPT_FEATURES_REQUEST:
4286 return handle_features_request(ofconn, oh);
4288 case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
4289 return handle_get_config_request(ofconn, oh);
4291 case OFPUTIL_OFPT_SET_CONFIG:
4292 return handle_set_config(ofconn, msg->data);
4294 case OFPUTIL_OFPT_PACKET_OUT:
4295 return handle_packet_out(ofconn, oh);
4297 case OFPUTIL_OFPT_PORT_MOD:
4298 return handle_port_mod(ofconn, oh);
4300 case OFPUTIL_OFPT_FLOW_MOD:
4301 return handle_flow_mod(ofconn, oh);
4303 case OFPUTIL_OFPT_BARRIER_REQUEST:
4304 return handle_barrier_request(ofconn, oh);
4306 /* OpenFlow replies. */
4307 case OFPUTIL_OFPT_ECHO_REPLY:
4310 /* Nicira extension requests. */
4311 case OFPUTIL_NXT_STATUS_REQUEST:
4312 return switch_status_handle_request(
4313 ofconn->ofproto->switch_status, ofconn->rconn, oh);
4315 case OFPUTIL_NXT_TUN_ID_FROM_COOKIE:
4316 return handle_tun_id_from_cookie(ofconn, oh);
4318 case OFPUTIL_NXT_ROLE_REQUEST:
4319 return handle_role_request(ofconn, oh);
4321 case OFPUTIL_NXT_SET_FLOW_FORMAT:
4322 return handle_nxt_set_flow_format(ofconn, oh);
4324 case OFPUTIL_NXT_FLOW_MOD:
4325 return handle_flow_mod(ofconn, oh);
4327 /* OpenFlow statistics requests. */
4328 case OFPUTIL_OFPST_DESC_REQUEST:
4329 return handle_desc_stats_request(ofconn, oh);
4331 case OFPUTIL_OFPST_FLOW_REQUEST:
4332 return handle_flow_stats_request(ofconn, oh);
4334 case OFPUTIL_OFPST_AGGREGATE_REQUEST:
4335 return handle_aggregate_stats_request(ofconn, oh);
4337 case OFPUTIL_OFPST_TABLE_REQUEST:
4338 return handle_table_stats_request(ofconn, oh);
4340 case OFPUTIL_OFPST_PORT_REQUEST:
4341 return handle_port_stats_request(ofconn, oh);
4343 case OFPUTIL_OFPST_QUEUE_REQUEST:
4344 return handle_queue_stats_request(ofconn, oh);
4346 /* Nicira extension statistics requests. */
4347 case OFPUTIL_NXST_FLOW_REQUEST:
4348 return handle_nxst_flow(ofconn, oh);
4350 case OFPUTIL_NXST_AGGREGATE_REQUEST:
4351 return handle_nxst_aggregate(ofconn, oh);
4353 case OFPUTIL_INVALID:
4354 case OFPUTIL_OFPT_HELLO:
4355 case OFPUTIL_OFPT_ERROR:
4356 case OFPUTIL_OFPT_FEATURES_REPLY:
4357 case OFPUTIL_OFPT_GET_CONFIG_REPLY:
4358 case OFPUTIL_OFPT_PACKET_IN:
4359 case OFPUTIL_OFPT_FLOW_REMOVED:
4360 case OFPUTIL_OFPT_PORT_STATUS:
4361 case OFPUTIL_OFPT_BARRIER_REPLY:
4362 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
4363 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
4364 case OFPUTIL_OFPST_DESC_REPLY:
4365 case OFPUTIL_OFPST_FLOW_REPLY:
4366 case OFPUTIL_OFPST_QUEUE_REPLY:
4367 case OFPUTIL_OFPST_PORT_REPLY:
4368 case OFPUTIL_OFPST_TABLE_REPLY:
4369 case OFPUTIL_OFPST_AGGREGATE_REPLY:
4370 case OFPUTIL_NXT_STATUS_REPLY:
4371 case OFPUTIL_NXT_ROLE_REPLY:
4372 case OFPUTIL_NXT_FLOW_REMOVED:
4373 case OFPUTIL_NXST_FLOW_REPLY:
4374 case OFPUTIL_NXST_AGGREGATE_REPLY:
4376 if (VLOG_IS_WARN_ENABLED()) {
4377 char *s = ofp_to_string(oh, ntohs(oh->length), 2);
4378 VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
4381 if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
4382 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
4384 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
4390 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4392 int error = handle_openflow__(ofconn, ofp_msg);
4394 send_error_oh(ofconn, ofp_msg->data, error);
4396 COVERAGE_INC(ofproto_recv_openflow);
4400 handle_miss_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4402 struct facet *facet;
4405 /* Obtain in_port and tun_id, at least. */
4406 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4408 /* Set header pointers in 'flow'. */
4409 flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
4411 /* Check with in-band control to see if this packet should be sent
4412 * to the local port regardless of the flow table. */
4413 if (in_band_msg_in_hook(p->in_band, &flow, upcall->packet)) {
4414 struct ofpbuf odp_actions;
4416 ofpbuf_init(&odp_actions, 32);
4417 nl_msg_put_u32(&odp_actions, ODPAT_OUTPUT, ODPP_LOCAL);
4418 dpif_execute(p->dpif, odp_actions.data, odp_actions.size,
4420 ofpbuf_uninit(&odp_actions);
4423 facet = facet_lookup_valid(p, &flow);
4425 struct rule *rule = rule_lookup(p, &flow);
4427 /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
4428 struct ofport *port = get_port(p, flow.in_port);
4430 if (port->opp.config & OFPPC_NO_PACKET_IN) {
4431 COVERAGE_INC(ofproto_no_packet_in);
4432 /* XXX install 'drop' flow entry */
4433 ofpbuf_delete(upcall->packet);
4437 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
4441 COVERAGE_INC(ofproto_packet_in);
4442 send_packet_in(p, upcall, &flow, false);
4446 facet = facet_create(p, rule, &flow, upcall->packet);
4447 } else if (!facet->may_install) {
4448 /* The facet is not installable, that is, we need to process every
4449 * packet, so process the current packet's actions into 'facet'. */
4450 facet_make_actions(p, facet, upcall->packet);
4453 if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
4455 * Extra-special case for fail-open mode.
4457 * We are in fail-open mode and the packet matched the fail-open rule,
4458 * but we are connected to a controller too. We should send the packet
4459 * up to the controller in the hope that it will try to set up a flow
4460 * and thereby allow us to exit fail-open.
4462 * See the top-level comment in fail-open.c for more information.
4464 send_packet_in(p, upcall, &flow, true);
4467 facet_execute(p, facet, upcall->packet);
4468 facet_install(p, facet, false);
4472 handle_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4476 switch (upcall->type) {
4477 case _ODPL_ACTION_NR:
4478 COVERAGE_INC(ofproto_ctlr_action);
4479 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4480 send_packet_in(p, upcall, &flow, false);
4483 case _ODPL_SFLOW_NR:
4485 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4486 ofproto_sflow_received(p->sflow, upcall, &flow);
4488 ofpbuf_delete(upcall->packet);
4492 handle_miss_upcall(p, upcall);
4496 VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
4501 /* Flow expiration. */
4503 static int ofproto_dp_max_idle(const struct ofproto *);
4504 static void ofproto_update_used(struct ofproto *);
4505 static void rule_expire(struct ofproto *, struct rule *);
4506 static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
4508 /* This function is called periodically by ofproto_run(). Its job is to
4509 * collect updates for the flows that have been installed into the datapath,
4510 * most importantly when they last were used, and then use that information to
4511 * expire flows that have not been used recently.
4513 * Returns the number of milliseconds after which it should be called again. */
4515 ofproto_expire(struct ofproto *ofproto)
4517 struct rule *rule, *next_rule;
4518 struct cls_cursor cursor;
4521 /* Update 'used' for each flow in the datapath. */
4522 ofproto_update_used(ofproto);
4524 /* Expire facets that have been idle too long. */
4525 dp_max_idle = ofproto_dp_max_idle(ofproto);
4526 ofproto_expire_facets(ofproto, dp_max_idle);
4528 /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
4529 cls_cursor_init(&cursor, &ofproto->cls, NULL);
4530 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4531 rule_expire(ofproto, rule);
4534 /* Let the hook know that we're at a stable point: all outstanding data
4535 * in existing flows has been accounted to the account_cb. Thus, the
4536 * hook can now reasonably do operations that depend on having accurate
4537 * flow volume accounting (currently, that's just bond rebalancing). */
4538 if (ofproto->ofhooks->account_checkpoint_cb) {
4539 ofproto->ofhooks->account_checkpoint_cb(ofproto->aux);
4542 return MIN(dp_max_idle, 1000);
4545 /* Update 'used' member of installed facets. */
4547 ofproto_update_used(struct ofproto *p)
4549 struct dpif_flow_dump dump;
4551 dpif_flow_dump_start(&dump, p->dpif);
4553 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
4554 struct facet *facet;
4558 memset(&f, 0, sizeof f);
4559 f.key = (struct nlattr *) keybuf;
4560 f.key_len = sizeof keybuf;
4561 if (!dpif_flow_dump_next(&dump, &f)) {
4565 if (f.key_len > sizeof keybuf) {
4566 VLOG_WARN_RL(&rl, "ODP flow key overflowed buffer");
4569 if (odp_flow_key_to_flow(f.key, f.key_len, &flow)) {
4573 odp_flow_key_format(f.key, f.key_len, &s);
4574 VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
4580 facet = facet_find(p, &flow);
4582 if (facet && facet->installed) {
4583 facet_update_time(p, facet, &f.stats);
4584 facet_account(p, facet, f.stats.n_bytes);
4586 /* There's a flow in the datapath that we know nothing about.
4588 COVERAGE_INC(ofproto_unexpected_rule);
4589 dpif_flow_del(p->dpif, &f);
4592 dpif_flow_dump_done(&dump);
4595 /* Calculates and returns the number of milliseconds of idle time after which
4596 * facets should expire from the datapath and we should fold their statistics
4597 * into their parent rules in userspace. */
4599 ofproto_dp_max_idle(const struct ofproto *ofproto)
4602 * Idle time histogram.
4604 * Most of the time a switch has a relatively small number of facets. When
4605 * this is the case we might as well keep statistics for all of them in
4606 * userspace and to cache them in the kernel datapath for performance as
4609 * As the number of facets increases, the memory required to maintain
4610 * statistics about them in userspace and in the kernel becomes
4611 * significant. However, with a large number of facets it is likely that
4612 * only a few of them are "heavy hitters" that consume a large amount of
4613 * bandwidth. At this point, only heavy hitters are worth caching in the
4614 * kernel and maintaining in userspaces; other facets we can discard.
4616 * The technique used to compute the idle time is to build a histogram with
4617 * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each. Each facet
4618 * that is installed in the kernel gets dropped in the appropriate bucket.
4619 * After the histogram has been built, we compute the cutoff so that only
4620 * the most-recently-used 1% of facets (but at least 1000 flows) are kept
4621 * cached. At least the most-recently-used bucket of facets is kept, so
4622 * actually an arbitrary number of facets can be kept in any given
4623 * expiration run (though the next run will delete most of those unless
4624 * they receive additional data).
4626 * This requires a second pass through the facets, in addition to the pass
4627 * made by ofproto_update_used(), because the former function never looks
4628 * at uninstallable facets.
4630 enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4631 enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4632 int buckets[N_BUCKETS] = { 0 };
4633 struct facet *facet;
4638 total = hmap_count(&ofproto->facets);
4639 if (total <= 1000) {
4640 return N_BUCKETS * BUCKET_WIDTH;
4643 /* Build histogram. */
4645 HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
4646 long long int idle = now - facet->used;
4647 int bucket = (idle <= 0 ? 0
4648 : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4649 : (unsigned int) idle / BUCKET_WIDTH);
4653 /* Find the first bucket whose flows should be expired. */
4654 for (bucket = 0; bucket < N_BUCKETS; bucket++) {
4655 if (buckets[bucket]) {
4658 subtotal += buckets[bucket++];
4659 } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
4664 if (VLOG_IS_DBG_ENABLED()) {
4668 ds_put_cstr(&s, "keep");
4669 for (i = 0; i < N_BUCKETS; i++) {
4671 ds_put_cstr(&s, ", drop");
4674 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4677 VLOG_INFO("%s: %s (msec:count)",
4678 dpif_name(ofproto->dpif), ds_cstr(&s));
4682 return bucket * BUCKET_WIDTH;
4686 facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
4688 if (ofproto->netflow && !facet_is_controller_flow(facet) &&
4689 netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
4690 struct ofexpired expired;
4691 struct odp_flow odp_flow;
4693 /* Get updated flow stats.
4695 * XXX We could avoid this call entirely if (1) ofproto_update_used()
4696 * updated TCP flags and (2) the dpif_flow_list_all() in
4697 * ofproto_update_used() zeroed TCP flags. */
4698 memset(&odp_flow, 0, sizeof odp_flow);
4699 if (facet->installed) {
4700 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
4703 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
4704 odp_flow_key_from_flow(&key, &facet->flow);
4706 odp_flow.key = key.data;
4707 odp_flow.key_len = key.size;
4708 odp_flow.flags = ODPFF_ZERO_TCP_FLAGS;
4709 dpif_flow_get(ofproto->dpif, &odp_flow);
4711 if (odp_flow.stats.n_packets) {
4712 facet_update_time(ofproto, facet, &odp_flow.stats);
4713 netflow_flow_update_flags(&facet->nf_flow,
4714 odp_flow.stats.tcp_flags);
4718 expired.flow = facet->flow;
4719 expired.packet_count = facet->packet_count +
4720 odp_flow.stats.n_packets;
4721 expired.byte_count = facet->byte_count + odp_flow.stats.n_bytes;
4722 expired.used = facet->used;
4724 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4729 ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
4731 long long int cutoff = time_msec() - dp_max_idle;
4732 struct facet *facet, *next_facet;
4734 HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
4735 facet_active_timeout(ofproto, facet);
4736 if (facet->used < cutoff) {
4737 facet_remove(ofproto, facet);
4742 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4743 * then delete it entirely. */
4745 rule_expire(struct ofproto *ofproto, struct rule *rule)
4747 struct facet *facet, *next_facet;
4751 /* Has 'rule' expired? */
4753 if (rule->hard_timeout
4754 && now > rule->created + rule->hard_timeout * 1000) {
4755 reason = OFPRR_HARD_TIMEOUT;
4756 } else if (rule->idle_timeout && list_is_empty(&rule->facets)
4757 && now >rule->used + rule->idle_timeout * 1000) {
4758 reason = OFPRR_IDLE_TIMEOUT;
4763 COVERAGE_INC(ofproto_expired);
4765 /* Update stats. (This is a no-op if the rule expired due to an idle
4766 * timeout, because that only happens when the rule has no facets left.) */
4767 LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4768 facet_remove(ofproto, facet);
4771 /* Get rid of the rule. */
4772 if (!rule_is_hidden(rule)) {
4773 rule_send_removed(ofproto, rule, reason);
4775 rule_remove(ofproto, rule);
4778 static struct ofpbuf *
4779 compose_ofp_flow_removed(struct ofconn *ofconn, const struct rule *rule,
4782 struct ofp_flow_removed *ofr;
4785 ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0), &buf);
4786 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofr->match,
4787 rule->flow_cookie, &ofr->cookie);
4788 ofr->priority = htons(rule->cr.priority);
4789 ofr->reason = reason;
4790 calc_flow_duration(rule->created, &ofr->duration_sec, &ofr->duration_nsec);
4791 ofr->idle_timeout = htons(rule->idle_timeout);
4792 ofr->packet_count = htonll(rule->packet_count);
4793 ofr->byte_count = htonll(rule->byte_count);
4798 static struct ofpbuf *
4799 compose_nx_flow_removed(const struct rule *rule, uint8_t reason)
4801 struct nx_flow_removed *nfr;
4805 make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &buf);
4806 match_len = nx_put_match(buf, &rule->cr);
4809 nfr->cookie = rule->flow_cookie;
4810 nfr->priority = htons(rule->cr.priority);
4811 nfr->reason = reason;
4812 calc_flow_duration(rule->created, &nfr->duration_sec, &nfr->duration_nsec);
4813 nfr->idle_timeout = htons(rule->idle_timeout);
4814 nfr->match_len = htons(match_len);
4815 nfr->packet_count = htonll(rule->packet_count);
4816 nfr->byte_count = htonll(rule->byte_count);
4822 rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
4824 struct ofconn *ofconn;
4826 if (!rule->send_flow_removed) {
4830 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
4833 if (!rconn_is_connected(ofconn->rconn)
4834 || !ofconn_receives_async_msgs(ofconn)) {
4838 msg = (ofconn->flow_format == NXFF_NXM
4839 ? compose_nx_flow_removed(rule, reason)
4840 : compose_ofp_flow_removed(ofconn, rule, reason));
4842 /* Account flow expirations under ofconn->reply_counter, the counter
4843 * for replies to OpenFlow requests. That works because preventing
4844 * OpenFlow requests from being processed also prevents new flows from
4845 * being added (and expiring). (It also prevents processing OpenFlow
4846 * requests that would not add new flows, so it is imperfect.) */
4847 queue_tx(msg, ofconn, ofconn->reply_counter);
4851 /* pinsched callback for sending 'ofp_packet_in' on 'ofconn'. */
4853 do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn_)
4855 struct ofconn *ofconn = ofconn_;
4857 rconn_send_with_limit(ofconn->rconn, ofp_packet_in,
4858 ofconn->packet_in_counter, 100);
4861 /* Takes 'upcall', whose packet has the flow specified by 'flow', composes an
4862 * OpenFlow packet-in message from it, and passes it to 'ofconn''s packet
4863 * scheduler for sending.
4865 * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
4866 * Otherwise, ownership is transferred to this function. */
4868 schedule_packet_in(struct ofconn *ofconn, struct dpif_upcall *upcall,
4869 const struct flow *flow, bool clone)
4871 enum { OPI_SIZE = offsetof(struct ofp_packet_in, data) };
4872 struct ofproto *ofproto = ofconn->ofproto;
4873 struct ofp_packet_in *opi;
4874 int total_len, send_len;
4875 struct ofpbuf *packet;
4878 /* Get OpenFlow buffer_id. */
4879 if (upcall->type == _ODPL_ACTION_NR) {
4880 buffer_id = UINT32_MAX;
4881 } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
4882 buffer_id = pktbuf_get_null();
4883 } else if (!ofconn->pktbuf) {
4884 buffer_id = UINT32_MAX;
4886 buffer_id = pktbuf_save(ofconn->pktbuf, upcall->packet, flow->in_port);
4889 /* Figure out how much of the packet to send. */
4890 total_len = send_len = upcall->packet->size;
4891 if (buffer_id != UINT32_MAX) {
4892 send_len = MIN(send_len, ofconn->miss_send_len);
4894 if (upcall->type == _ODPL_ACTION_NR) {
4895 send_len = MIN(send_len, upcall->userdata);
4898 /* Copy or steal buffer for OFPT_PACKET_IN. */
4900 packet = ofpbuf_clone_data_with_headroom(upcall->packet->data,
4901 send_len, OPI_SIZE);
4903 packet = upcall->packet;
4904 packet->size = send_len;
4907 /* Add OFPT_PACKET_IN. */
4908 opi = ofpbuf_push_zeros(packet, OPI_SIZE);
4909 opi->header.version = OFP_VERSION;
4910 opi->header.type = OFPT_PACKET_IN;
4911 opi->total_len = htons(total_len);
4912 opi->in_port = htons(odp_port_to_ofp_port(flow->in_port));
4913 opi->reason = upcall->type == _ODPL_MISS_NR ? OFPR_NO_MATCH : OFPR_ACTION;
4914 opi->buffer_id = htonl(buffer_id);
4915 update_openflow_length(packet);
4917 /* Hand over to packet scheduler. It might immediately call into
4918 * do_send_packet_in() or it might buffer it for a while (until a later
4919 * call to pinsched_run()). */
4920 pinsched_send(ofconn->schedulers[opi->reason], flow->in_port,
4921 packet, do_send_packet_in, ofconn);
4924 /* Given 'upcall', of type _ODPL_ACTION_NR or _ODPL_MISS_NR, sends an
4925 * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
4926 * their individual configurations.
4928 * Takes ownership of 'packet'. */
4930 send_packet_in(struct ofproto *ofproto, struct dpif_upcall *upcall,
4931 const struct flow *flow, bool clone)
4933 struct ofconn *ofconn, *prev;
4936 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
4937 if (ofconn_receives_async_msgs(ofconn)) {
4939 schedule_packet_in(prev, upcall, flow, true);
4945 schedule_packet_in(prev, upcall, flow, clone);
4946 } else if (!clone) {
4947 ofpbuf_delete(upcall->packet);
4952 pick_datapath_id(const struct ofproto *ofproto)
4954 const struct ofport *port;
4956 port = get_port(ofproto, ODPP_LOCAL);
4958 uint8_t ea[ETH_ADDR_LEN];
4961 error = netdev_get_etheraddr(port->netdev, ea);
4963 return eth_addr_to_uint64(ea);
4965 VLOG_WARN("could not get MAC address for %s (%s)",
4966 netdev_get_name(port->netdev), strerror(error));
4968 return ofproto->fallback_dpid;
4972 pick_fallback_dpid(void)
4974 uint8_t ea[ETH_ADDR_LEN];
4975 eth_addr_nicira_random(ea);
4976 return eth_addr_to_uint64(ea);
4980 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
4981 void *aux OVS_UNUSED)
4983 const struct shash_node *node;
4987 SHASH_FOR_EACH (node, &all_ofprotos) {
4988 ds_put_format(&results, "%s\n", node->name);
4990 unixctl_command_reply(conn, 200, ds_cstr(&results));
4991 ds_destroy(&results);
4994 struct ofproto_trace {
4995 struct action_xlate_ctx ctx;
5001 trace_format_rule(struct ds *result, int level, const struct rule *rule)
5003 ds_put_char_multiple(result, '\t', level);
5005 ds_put_cstr(result, "No match\n");
5009 ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
5010 ntohll(rule->flow_cookie));
5011 cls_rule_format(&rule->cr, result);
5012 ds_put_char(result, '\n');
5014 ds_put_char_multiple(result, '\t', level);
5015 ds_put_cstr(result, "OpenFlow ");
5016 ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
5017 rule->n_actions * sizeof *rule->actions);
5018 ds_put_char(result, '\n');
5022 trace_format_flow(struct ds *result, int level, const char *title,
5023 struct ofproto_trace *trace)
5025 ds_put_char_multiple(result, '\t', level);
5026 ds_put_format(result, "%s: ", title);
5027 if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5028 ds_put_cstr(result, "unchanged");
5030 flow_format(result, &trace->ctx.flow);
5031 trace->flow = trace->ctx.flow;
5033 ds_put_char(result, '\n');
5037 trace_resubmit(struct action_xlate_ctx *ctx, const struct rule *rule)
5039 struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5040 struct ds *result = trace->result;
5042 ds_put_char(result, '\n');
5043 trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5044 trace_format_rule(result, ctx->recurse + 1, rule);
5048 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5049 void *aux OVS_UNUSED)
5051 char *dpname, *in_port_s, *tun_id_s, *packet_s;
5052 char *args = xstrdup(args_);
5053 char *save_ptr = NULL;
5054 struct ofproto *ofproto;
5055 struct ofpbuf packet;
5063 ofpbuf_init(&packet, strlen(args) / 2);
5066 dpname = strtok_r(args, " ", &save_ptr);
5067 tun_id_s = strtok_r(NULL, " ", &save_ptr);
5068 in_port_s = strtok_r(NULL, " ", &save_ptr);
5069 packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5070 if (!dpname || !in_port_s || !packet_s) {
5071 unixctl_command_reply(conn, 501, "Bad command syntax");
5075 ofproto = shash_find_data(&all_ofprotos, dpname);
5077 unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5082 tun_id = htonll(strtoull(tun_id_s, NULL, 10));
5083 in_port = ofp_port_to_odp_port(atoi(in_port_s));
5085 packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
5086 packet_s += strspn(packet_s, " ");
5087 if (*packet_s != '\0') {
5088 unixctl_command_reply(conn, 501, "Trailing garbage in command");
5091 if (packet.size < ETH_HEADER_LEN) {
5092 unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
5096 ds_put_cstr(&result, "Packet: ");
5097 s = ofp_packet_to_string(packet.data, packet.size, packet.size);
5098 ds_put_cstr(&result, s);
5101 flow_extract(&packet, tun_id, in_port, &flow);
5102 ds_put_cstr(&result, "Flow: ");
5103 flow_format(&result, &flow);
5104 ds_put_char(&result, '\n');
5106 rule = rule_lookup(ofproto, &flow);
5107 trace_format_rule(&result, 0, rule);
5109 struct ofproto_trace trace;
5110 struct ofpbuf *odp_actions;
5112 trace.result = &result;
5114 action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
5115 trace.ctx.resubmit_hook = trace_resubmit;
5116 odp_actions = xlate_actions(&trace.ctx,
5117 rule->actions, rule->n_actions);
5119 ds_put_char(&result, '\n');
5120 trace_format_flow(&result, 0, "Final flow", &trace);
5121 ds_put_cstr(&result, "Datapath actions: ");
5122 format_odp_actions(&result, odp_actions->data, odp_actions->size);
5123 ofpbuf_delete(odp_actions);
5126 unixctl_command_reply(conn, 200, ds_cstr(&result));
5129 ds_destroy(&result);
5130 ofpbuf_uninit(&packet);
5135 ofproto_unixctl_init(void)
5137 static bool registered;
5143 unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
5144 unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
5148 default_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
5149 struct ofpbuf *odp_actions, tag_type *tags,
5150 uint16_t *nf_output_iface, void *ofproto_)
5152 struct ofproto *ofproto = ofproto_;
5155 /* Drop frames for reserved multicast addresses. */
5156 if (eth_addr_is_reserved(flow->dl_dst)) {
5160 /* Learn source MAC (but don't try to learn from revalidation). */
5161 if (packet != NULL) {
5162 tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
5164 GRAT_ARP_LOCK_NONE);
5166 /* The log messages here could actually be useful in debugging,
5167 * so keep the rate limit relatively high. */
5168 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5169 VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
5170 ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
5171 ofproto_revalidate(ofproto, rev_tag);
5175 /* Determine output port. */
5176 out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags,
5179 flood_packets(ofproto, flow->in_port, OFPPC_NO_FLOOD,
5180 nf_output_iface, odp_actions);
5181 } else if (out_port != flow->in_port) {
5182 nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, out_port);
5183 *nf_output_iface = out_port;
5191 static const struct ofhooks default_ofhooks = {
5192 default_normal_ofhook_cb,