]> git.proxmox.com Git - mirror_ovs.git/blame - ofproto/ofproto.c
datapath: Drop queue information from odp_stats.
[mirror_ovs.git] / ofproto / ofproto.c
CommitLineData
064af421 1/*
db5ce514 2 * Copyright (c) 2009, 2010, 2011 Nicira Networks.
43253595 3 * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
064af421 4 *
a14bc59f
BP
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:
064af421 8 *
a14bc59f
BP
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
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.
064af421
BP
16 */
17
18#include <config.h>
19#include "ofproto.h"
20#include <errno.h>
21#include <inttypes.h>
9d82ec47 22#include <sys/socket.h>
064af421
BP
23#include <net/if.h>
24#include <netinet/in.h>
25#include <stdbool.h>
26#include <stdlib.h>
10a24935 27#include "byte-order.h"
064af421
BP
28#include "classifier.h"
29#include "coverage.h"
30#include "discovery.h"
31#include "dpif.h"
4f2cad2c 32#include "dynamic-string.h"
064af421 33#include "fail-open.h"
ca0f572c
BP
34#include "hash.h"
35#include "hmap.h"
064af421
BP
36#include "in-band.h"
37#include "mac-learning.h"
53ddd40a 38#include "multipath.h"
064af421
BP
39#include "netdev.h"
40#include "netflow.h"
cdee00fd 41#include "netlink.h"
09246b99 42#include "nx-match.h"
064af421
BP
43#include "odp-util.h"
44#include "ofp-print.h"
fa37b408 45#include "ofp-util.h"
72b06300 46#include "ofproto-sflow.h"
064af421
BP
47#include "ofpbuf.h"
48#include "openflow/nicira-ext.h"
49#include "openflow/openflow.h"
064af421
BP
50#include "openvswitch/datapath-protocol.h"
51#include "packets.h"
52#include "pinsched.h"
53#include "pktbuf.h"
54#include "poll-loop.h"
064af421
BP
55#include "rconn.h"
56#include "shash.h"
57#include "status.h"
fe55ad15 58#include "stream-ssl.h"
064af421
BP
59#include "svec.h"
60#include "tag.h"
61#include "timeval.h"
4f2cad2c 62#include "unixctl.h"
064af421 63#include "vconn.h"
5136ce49 64#include "vlog.h"
064af421 65
d98e6007 66VLOG_DEFINE_THIS_MODULE(ofproto);
064af421 67
cc01d0bb
BP
68COVERAGE_DEFINE(facet_changed_rule);
69COVERAGE_DEFINE(facet_revalidate);
d76f09ea 70COVERAGE_DEFINE(odp_overflow);
d76f09ea
BP
71COVERAGE_DEFINE(ofproto_agg_request);
72COVERAGE_DEFINE(ofproto_costly_flags);
73COVERAGE_DEFINE(ofproto_ctlr_action);
cc01d0bb 74COVERAGE_DEFINE(ofproto_del_rule);
d76f09ea
BP
75COVERAGE_DEFINE(ofproto_error);
76COVERAGE_DEFINE(ofproto_expiration);
77COVERAGE_DEFINE(ofproto_expired);
78COVERAGE_DEFINE(ofproto_flows_req);
79COVERAGE_DEFINE(ofproto_flush);
80COVERAGE_DEFINE(ofproto_invalidated);
d76f09ea 81COVERAGE_DEFINE(ofproto_no_packet_in);
d76f09ea
BP
82COVERAGE_DEFINE(ofproto_ofconn_stuck);
83COVERAGE_DEFINE(ofproto_ofp2odp);
84COVERAGE_DEFINE(ofproto_packet_in);
85COVERAGE_DEFINE(ofproto_packet_out);
86COVERAGE_DEFINE(ofproto_queue_req);
87COVERAGE_DEFINE(ofproto_recv_openflow);
88COVERAGE_DEFINE(ofproto_reinit_ports);
d76f09ea
BP
89COVERAGE_DEFINE(ofproto_unexpected_rule);
90COVERAGE_DEFINE(ofproto_uninstallable);
91COVERAGE_DEFINE(ofproto_update_port);
92
72b06300 93#include "sflow_api.h"
064af421 94
f29152ca
BP
95struct rule;
96
064af421 97struct ofport {
ca0f572c 98 struct hmap_node hmap_node; /* In struct ofproto's "ports" hmap. */
064af421
BP
99 struct netdev *netdev;
100 struct ofp_phy_port opp; /* In host byte order. */
ca0f572c 101 uint16_t odp_port;
064af421
BP
102};
103
104static void ofport_free(struct ofport *);
105static void hton_ofp_phy_port(struct ofp_phy_port *);
106
f29152ca
BP
107struct action_xlate_ctx {
108/* action_xlate_ctx_init() initializes these members. */
109
110 /* The ofproto. */
111 struct ofproto *ofproto;
112
113 /* Flow to which the OpenFlow actions apply. xlate_actions() will modify
114 * this flow when actions change header fields. */
115 struct flow flow;
116
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;
120
7aa697dd
BP
121 /* If nonnull, called just before executing a resubmit action.
122 *
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 *);
126
f29152ca
BP
127/* xlate_actions() initializes and uses these members. The client might want
128 * to look at them after it returns. */
129
cdee00fd 130 struct ofpbuf *odp_actions; /* Datapath actions. */
f29152ca
BP
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. */
135
136/* xlate_actions() initializes and uses these members, but the client has no
137 * reason to look at them. */
138
139 int recurse; /* Recursion level, via xlate_table_action. */
cdee00fd
BP
140 int last_pop_priority; /* Offset in 'odp_actions' just past most
141 * recently added ODPAT_SET_PRIORITY. */
f29152ca
BP
142};
143
144static void action_xlate_ctx_init(struct action_xlate_ctx *,
145 struct ofproto *, const struct flow *,
146 const struct ofpbuf *);
cdee00fd
BP
147static struct ofpbuf *xlate_actions(struct action_xlate_ctx *,
148 const union ofp_action *in, size_t n_in);
064af421 149
bcf84111 150/* An OpenFlow flow. */
064af421 151struct rule {
0c43ad9a 152 long long int used; /* Time last used; time created if not used. */
064af421 153 long long int created; /* Creation time. */
064af421 154
bcf84111 155 /* These statistics:
064af421 156 *
bcf84111
BP
157 * - Do include packets and bytes from facets that have been deleted or
158 * whose own statistics have been folded into the rule.
79eee1eb 159 *
bcf84111
BP
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()).
064af421 163 *
bcf84111
BP
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.
167 */
168 uint64_t packet_count; /* Number of packets received. */
169 uint64_t byte_count; /* Number of bytes received. */
170
171 ovs_be64 flow_cookie; /* Controller-issued identifier. */
172
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. */
064af421
BP
180};
181
bcf84111
BP
182static struct rule *rule_from_cls_rule(const struct cls_rule *);
183static bool rule_is_hidden(const struct rule *);
064af421 184
bcf84111 185static struct rule *rule_create(const struct cls_rule *,
0193b2af 186 const union ofp_action *, size_t n_actions,
ca069229 187 uint16_t idle_timeout, uint16_t hard_timeout,
8054fc48 188 ovs_be64 flow_cookie, bool send_flow_removed);
064af421 189static void rule_destroy(struct ofproto *, struct rule *);
bcf84111
BP
190static void rule_free(struct rule *);
191
192static struct rule *rule_lookup(struct ofproto *, const struct flow *);
afe75089 193static void rule_insert(struct ofproto *, struct rule *);
064af421 194static void rule_remove(struct ofproto *, struct rule *);
bcf84111
BP
195
196static void rule_send_removed(struct ofproto *, struct rule *, uint8_t reason);
197
198/* An exact-match instantiation of an OpenFlow flow. */
199struct facet {
200 long long int used; /* Time last used; time created if not used. */
201
202 /* These statistics:
203 *
204 * - Do include packets and bytes sent "by hand", e.g. with
205 * dpif_execute().
206 *
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).
210 *
211 * - Do not include any packets or bytes that can currently be obtained
212 * from the datapath by, e.g., dpif_flow_get().
213 */
214 uint64_t packet_count; /* Number of packets received. */
215 uint64_t byte_count; /* Number of bytes received. */
216
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
219 * byte_count). */
220 uint64_t accounted_bytes;
221
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. */
cf22f8cb 229 size_t actions_len; /* Number of bytes in actions[]. */
cdee00fd 230 struct nlattr *actions; /* Datapath actions. */
bcf84111
BP
231 tag_type tags; /* Tags (set only by hooks). */
232 struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
233};
234
235static struct facet *facet_create(struct ofproto *, struct rule *,
236 const struct flow *,
237 const struct ofpbuf *packet);
238static void facet_remove(struct ofproto *, struct facet *);
239static void facet_free(struct facet *);
240
241static struct facet *facet_lookup_valid(struct ofproto *, const struct flow *);
242static bool facet_revalidate(struct ofproto *, struct facet *);
243
244static void facet_install(struct ofproto *, struct facet *, bool zero_stats);
245static void facet_uninstall(struct ofproto *, struct facet *);
d530fcd2 246static void facet_flush_stats(struct ofproto *, struct facet *);
bcf84111 247
7f7ae89d
BP
248static void facet_make_actions(struct ofproto *, struct facet *,
249 const struct ofpbuf *packet);
bcf84111
BP
250static void facet_update_stats(struct ofproto *, struct facet *,
251 const struct odp_flow_stats *);
064af421 252
76ce9432
BP
253/* ofproto supports two kinds of OpenFlow connections:
254 *
5899143f
BP
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.
76ce9432 258 *
5899143f 259 * - "Service" connections, e.g. from ovs-ofctl. When these connections
76ce9432
BP
260 * drop, it is the other side's responsibility to reconnect them if
261 * necessary. ofproto does not send them asynchronous messages by default.
7d674866
BP
262 *
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
266 * common case.
76ce9432
BP
267 */
268enum ofconn_type {
5899143f
BP
269 OFCONN_PRIMARY, /* An ordinary OpenFlow controller. */
270 OFCONN_SERVICE /* A service connection, e.g. "ovs-ofctl". */
76ce9432 271};
064af421 272
7d674866
BP
273/* A listener for incoming OpenFlow "service" connections. */
274struct ofservice {
275 struct hmap_node node; /* In struct ofproto's "services" hmap. */
276 struct pvconn *pvconn; /* OpenFlow connection listener. */
277
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. */
283};
284
285static struct ofservice *ofservice_lookup(struct ofproto *,
286 const char *target);
287static int ofservice_create(struct ofproto *,
288 const struct ofproto_controller *);
289static void ofservice_reconfigure(struct ofservice *,
290 const struct ofproto_controller *);
291static void ofservice_destroy(struct ofproto *, struct ofservice *);
292
76ce9432
BP
293/* An OpenFlow connection. */
294struct ofconn {
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. */
492f7572 299 enum nx_flow_format flow_format; /* Currently selected flow format. */
76ce9432
BP
300
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. */
306
307 /* Number of OpenFlow messages queued on 'rconn' as replies to OpenFlow
308 * requests, and the maximum number before we stop reading OpenFlow
309 * requests. */
064af421
BP
310#define OFCONN_REPLY_MAX 100
311 struct rconn_packet_counter *reply_counter;
76ce9432 312
5899143f 313 /* type == OFCONN_PRIMARY only. */
9deba63b 314 enum nx_role role; /* Role. */
76ce9432
BP
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. */
d2ede7bc 318 enum ofproto_band band; /* In-band or out-of-band? */
064af421
BP
319};
320
76ce9432
BP
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
326BUILD_ASSERT_DECL(OFPR_NO_MATCH == 0);
327BUILD_ASSERT_DECL(OFPR_NO_MATCH == _ODPL_MISS_NR);
328BUILD_ASSERT_DECL(OFPR_ACTION == 1);
329BUILD_ASSERT_DECL(OFPR_ACTION == _ODPL_ACTION_NR);
330
331static struct ofconn *ofconn_create(struct ofproto *, struct rconn *,
332 enum ofconn_type);
c475ae67 333static void ofconn_destroy(struct ofconn *);
3269c562 334static void ofconn_run(struct ofconn *);
064af421 335static void ofconn_wait(struct ofconn *);
c91248b3 336static bool ofconn_receives_async_msgs(const struct ofconn *);
eb15cdbb 337static char *ofconn_make_name(const struct ofproto *, const char *target);
7d674866 338static void ofconn_set_rate_limit(struct ofconn *, int rate, int burst);
c91248b3 339
064af421
BP
340static void queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
341 struct rconn_packet_counter *counter);
342
856081f6
BP
343static void send_packet_in(struct ofproto *, struct dpif_upcall *,
344 const struct flow *, bool clone);
345static void do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn);
76ce9432 346
064af421
BP
347struct ofproto {
348 /* Settings. */
349 uint64_t datapath_id; /* Datapath ID. */
350 uint64_t fallback_dpid; /* Datapath ID if no better choice found. */
5a719c38
JP
351 char *mfr_desc; /* Manufacturer. */
352 char *hw_desc; /* Hardware. */
353 char *sw_desc; /* Software version. */
354 char *serial_desc; /* Serial number. */
8abc4ed7 355 char *dp_desc; /* Datapath description. */
064af421
BP
356
357 /* Datapath. */
c228a364 358 struct dpif *dpif;
e9e28be3 359 struct netdev_monitor *netdev_monitor;
ca0f572c 360 struct hmap ports; /* Contains "struct ofport"s. */
064af421
BP
361 struct shash port_by_name;
362 uint32_t max_ports;
363
364 /* Configuration. */
365 struct switch_status *switch_status;
064af421 366 struct fail_open *fail_open;
064af421 367 struct netflow *netflow;
72b06300 368 struct ofproto_sflow *sflow;
064af421 369
d2ede7bc
BP
370 /* In-band control. */
371 struct in_band *in_band;
372 long long int next_in_band_update;
917e50e1
BP
373 struct sockaddr_in *extra_in_band_remotes;
374 size_t n_extra_remotes;
b1da6250 375 int in_band_queue;
917e50e1 376
064af421
BP
377 /* Flow table. */
378 struct classifier cls;
064af421 379 long long int next_expiration;
bcf84111
BP
380
381 /* Facets. */
382 struct hmap facets;
383 bool need_revalidate;
064af421
BP
384 struct tag_set revalidate_set;
385
386 /* OpenFlow connections. */
76ce9432
BP
387 struct hmap controllers; /* Controller "struct ofconn"s. */
388 struct list all_conns; /* Contains "struct ofconn"s. */
31681a5d 389 enum ofproto_fail_mode fail_mode;
7d674866
BP
390
391 /* OpenFlow listeners. */
392 struct hmap services; /* Contains "struct ofservice"s. */
064af421
BP
393 struct pvconn **snoops;
394 size_t n_snoops;
395
396 /* Hooks for ovs-vswitchd. */
397 const struct ofhooks *ofhooks;
398 void *aux;
399
400 /* Used by default ofhooks. */
401 struct mac_learning *ml;
402};
403
7aa697dd
BP
404/* Map from dpif name to struct ofproto, for use by unixctl commands. */
405static struct shash all_ofprotos = SHASH_INITIALIZER(&all_ofprotos);
406
064af421
BP
407static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
408
409static const struct ofhooks default_ofhooks;
410
fa60c019 411static uint64_t pick_datapath_id(const struct ofproto *);
064af421 412static uint64_t pick_fallback_dpid(void);
76ce9432 413
0de7a4b4 414static int ofproto_expire(struct ofproto *);
4a4cdb3b 415
856081f6 416static void handle_upcall(struct ofproto *, struct dpif_upcall *);
064af421 417
3269c562 418static void handle_openflow(struct ofconn *, struct ofpbuf *);
064af421 419
ca0f572c 420static struct ofport *get_port(const struct ofproto *, uint16_t odp_port);
064af421
BP
421static void update_port(struct ofproto *, const char *devname);
422static int init_ports(struct ofproto *);
423static void reinit_ports(struct ofproto *);
424
7aa697dd
BP
425static void ofproto_unixctl_init(void);
426
064af421 427int
1a6f1e2a
JG
428ofproto_create(const char *datapath, const char *datapath_type,
429 const struct ofhooks *ofhooks, void *aux,
064af421
BP
430 struct ofproto **ofprotop)
431{
064af421
BP
432 struct odp_stats stats;
433 struct ofproto *p;
c228a364 434 struct dpif *dpif;
064af421
BP
435 int error;
436
437 *ofprotop = NULL;
438
7aa697dd
BP
439 ofproto_unixctl_init();
440
064af421 441 /* Connect to datapath and start listening for messages. */
1a6f1e2a 442 error = dpif_open(datapath, datapath_type, &dpif);
064af421
BP
443 if (error) {
444 VLOG_ERR("failed to open datapath %s: %s", datapath, strerror(error));
445 return error;
446 }
c228a364 447 error = dpif_get_dp_stats(dpif, &stats);
064af421
BP
448 if (error) {
449 VLOG_ERR("failed to obtain stats for datapath %s: %s",
450 datapath, strerror(error));
c228a364 451 dpif_close(dpif);
064af421
BP
452 return error;
453 }
72b06300 454 error = dpif_recv_set_mask(dpif, ODPL_MISS | ODPL_ACTION | ODPL_SFLOW);
064af421
BP
455 if (error) {
456 VLOG_ERR("failed to listen on datapath %s: %s",
457 datapath, strerror(error));
c228a364 458 dpif_close(dpif);
064af421
BP
459 return error;
460 }
c228a364 461 dpif_flow_flush(dpif);
8f24562a 462 dpif_recv_purge(dpif);
064af421
BP
463
464 /* Initialize settings. */
ec6fde61 465 p = xzalloc(sizeof *p);
064af421 466 p->fallback_dpid = pick_fallback_dpid();
fa60c019 467 p->datapath_id = p->fallback_dpid;
5a719c38
JP
468 p->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
469 p->hw_desc = xstrdup(DEFAULT_HW_DESC);
470 p->sw_desc = xstrdup(DEFAULT_SW_DESC);
471 p->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
23ff2821 472 p->dp_desc = xstrdup(DEFAULT_DP_DESC);
064af421
BP
473
474 /* Initialize datapath. */
475 p->dpif = dpif;
8b61709d 476 p->netdev_monitor = netdev_monitor_create();
ca0f572c 477 hmap_init(&p->ports);
064af421
BP
478 shash_init(&p->port_by_name);
479 p->max_ports = stats.max_ports;
480
481 /* Initialize submodules. */
482 p->switch_status = switch_status_create(p);
064af421 483 p->fail_open = NULL;
064af421 484 p->netflow = NULL;
72b06300 485 p->sflow = NULL;
064af421 486
b1da6250
BP
487 /* Initialize in-band control. */
488 p->in_band = NULL;
489 p->in_band_queue = -1;
490
064af421
BP
491 /* Initialize flow table. */
492 classifier_init(&p->cls);
064af421 493 p->next_expiration = time_msec() + 1000;
bcf84111
BP
494
495 /* Initialize facet table. */
496 hmap_init(&p->facets);
497 p->need_revalidate = false;
064af421
BP
498 tag_set_init(&p->revalidate_set);
499
500 /* Initialize OpenFlow connections. */
501 list_init(&p->all_conns);
76ce9432 502 hmap_init(&p->controllers);
7d674866 503 hmap_init(&p->services);
064af421
BP
504 p->snoops = NULL;
505 p->n_snoops = 0;
506
507 /* Initialize hooks. */
508 if (ofhooks) {
509 p->ofhooks = ofhooks;
510 p->aux = aux;
511 p->ml = NULL;
512 } else {
513 p->ofhooks = &default_ofhooks;
514 p->aux = p;
515 p->ml = mac_learning_create();
516 }
517
fa60c019
BP
518 /* Pick final datapath ID. */
519 p->datapath_id = pick_datapath_id(p);
b123cc3c 520 VLOG_INFO("using datapath ID %016"PRIx64, p->datapath_id);
fa60c019 521
7aa697dd
BP
522 shash_add_once(&all_ofprotos, dpif_name(p->dpif), p);
523
064af421
BP
524 *ofprotop = p;
525 return 0;
526}
527
528void
529ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
530{
531 uint64_t old_dpid = p->datapath_id;
fa60c019 532 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
064af421 533 if (p->datapath_id != old_dpid) {
b123cc3c 534 VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
76ce9432
BP
535
536 /* Force all active connections to reconnect, since there is no way to
537 * notify a controller that the datapath ID has changed. */
fa05809b 538 ofproto_reconnect_controllers(p);
064af421
BP
539 }
540}
541
76ce9432
BP
542static bool
543is_discovery_controller(const struct ofproto_controller *c)
544{
545 return !strcmp(c->target, "discover");
546}
547
548static bool
549is_in_band_controller(const struct ofproto_controller *c)
550{
551 return is_discovery_controller(c) || c->band == OFPROTO_IN_BAND;
552}
553
554/* Creates a new controller in 'ofproto'. Some of the settings are initially
555 * drawn from 'c', but update_controller() needs to be called later to finish
556 * the new ofconn's configuration. */
557static void
558add_controller(struct ofproto *ofproto, const struct ofproto_controller *c)
559{
560 struct discovery *discovery;
561 struct ofconn *ofconn;
562
563 if (is_discovery_controller(c)) {
564 int error = discovery_create(c->accept_re, c->update_resolv_conf,
565 ofproto->dpif, ofproto->switch_status,
566 &discovery);
567 if (error) {
568 return;
569 }
570 } else {
571 discovery = NULL;
572 }
573
5899143f 574 ofconn = ofconn_create(ofproto, rconn_create(5, 8), OFCONN_PRIMARY);
76ce9432
BP
575 ofconn->pktbuf = pktbuf_create();
576 ofconn->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
577 if (discovery) {
578 ofconn->discovery = discovery;
579 } else {
eb15cdbb
BP
580 char *name = ofconn_make_name(ofproto, c->target);
581 rconn_connect(ofconn->rconn, c->target, name);
582 free(name);
76ce9432
BP
583 }
584 hmap_insert(&ofproto->controllers, &ofconn->hmap_node,
585 hash_string(c->target, 0));
586}
587
588/* Reconfigures 'ofconn' to match 'c'. This function cannot update an ofconn's
589 * target or turn discovery on or off (these are done by creating new ofconns
590 * and deleting old ones), but it can update the rest of an ofconn's
591 * settings. */
592static void
593update_controller(struct ofconn *ofconn, const struct ofproto_controller *c)
064af421 594{
76ce9432 595 int probe_interval;
79c9f2ee 596
d2ede7bc
BP
597 ofconn->band = (is_in_band_controller(c)
598 ? OFPROTO_IN_BAND : OFPROTO_OUT_OF_BAND);
599
76ce9432 600 rconn_set_max_backoff(ofconn->rconn, c->max_backoff);
79c9f2ee 601
76ce9432
BP
602 probe_interval = c->probe_interval ? MAX(c->probe_interval, 5) : 0;
603 rconn_set_probe_interval(ofconn->rconn, probe_interval);
79c9f2ee 604
76ce9432
BP
605 if (ofconn->discovery) {
606 discovery_set_update_resolv_conf(ofconn->discovery,
607 c->update_resolv_conf);
608 discovery_set_accept_controller_re(ofconn->discovery, c->accept_re);
609 }
79c9f2ee 610
7d674866 611 ofconn_set_rate_limit(ofconn, c->rate_limit, c->burst_limit);
76ce9432 612}
79c9f2ee 613
76ce9432
BP
614static const char *
615ofconn_get_target(const struct ofconn *ofconn)
616{
eb15cdbb 617 return ofconn->discovery ? "discover" : rconn_get_target(ofconn->rconn);
76ce9432
BP
618}
619
620static struct ofconn *
621find_controller_by_target(struct ofproto *ofproto, const char *target)
622{
623 struct ofconn *ofconn;
624
4e8e4213 625 HMAP_FOR_EACH_WITH_HASH (ofconn, hmap_node,
76ce9432
BP
626 hash_string(target, 0), &ofproto->controllers) {
627 if (!strcmp(ofconn_get_target(ofconn), target)) {
628 return ofconn;
79c9f2ee 629 }
064af421 630 }
76ce9432
BP
631 return NULL;
632}
064af421 633
d2ede7bc
BP
634static void
635update_in_band_remotes(struct ofproto *ofproto)
636{
637 const struct ofconn *ofconn;
638 struct sockaddr_in *addrs;
917e50e1 639 size_t max_addrs, n_addrs;
d2ede7bc 640 bool discovery;
917e50e1 641 size_t i;
d2ede7bc 642
917e50e1
BP
643 /* Allocate enough memory for as many remotes as we could possibly have. */
644 max_addrs = ofproto->n_extra_remotes + hmap_count(&ofproto->controllers);
645 addrs = xmalloc(max_addrs * sizeof *addrs);
d2ede7bc
BP
646 n_addrs = 0;
647
648 /* Add all the remotes. */
649 discovery = false;
4e8e4213 650 HMAP_FOR_EACH (ofconn, hmap_node, &ofproto->controllers) {
d2ede7bc
BP
651 struct sockaddr_in *sin = &addrs[n_addrs];
652
487ec65f
BP
653 if (ofconn->band == OFPROTO_OUT_OF_BAND) {
654 continue;
655 }
656
d2ede7bc
BP
657 sin->sin_addr.s_addr = rconn_get_remote_ip(ofconn->rconn);
658 if (sin->sin_addr.s_addr) {
659 sin->sin_port = rconn_get_remote_port(ofconn->rconn);
660 n_addrs++;
661 }
662 if (ofconn->discovery) {
663 discovery = true;
664 }
665 }
917e50e1
BP
666 for (i = 0; i < ofproto->n_extra_remotes; i++) {
667 addrs[n_addrs++] = ofproto->extra_in_band_remotes[i];
668 }
d2ede7bc
BP
669
670 /* Create or update or destroy in-band.
671 *
672 * Ordinarily we only enable in-band if there's at least one remote
673 * address, but discovery needs the in-band rules for DHCP to be installed
674 * even before we know any remote addresses. */
675 if (n_addrs || discovery) {
676 if (!ofproto->in_band) {
677 in_band_create(ofproto, ofproto->dpif, ofproto->switch_status,
678 &ofproto->in_band);
679 }
40cae670
BP
680 if (ofproto->in_band) {
681 in_band_set_remotes(ofproto->in_band, addrs, n_addrs);
682 }
b1da6250 683 in_band_set_queue(ofproto->in_band, ofproto->in_band_queue);
d2ede7bc
BP
684 ofproto->next_in_band_update = time_msec() + 1000;
685 } else {
686 in_band_destroy(ofproto->in_band);
687 ofproto->in_band = NULL;
688 }
689
690 /* Clean up. */
691 free(addrs);
692}
693
31681a5d
JP
694static void
695update_fail_open(struct ofproto *p)
696{
697 struct ofconn *ofconn;
698
699 if (!hmap_is_empty(&p->controllers)
700 && p->fail_mode == OFPROTO_FAIL_STANDALONE) {
701 struct rconn **rconns;
702 size_t n;
703
704 if (!p->fail_open) {
705 p->fail_open = fail_open_create(p, p->switch_status);
706 }
707
708 n = 0;
709 rconns = xmalloc(hmap_count(&p->controllers) * sizeof *rconns);
4e8e4213 710 HMAP_FOR_EACH (ofconn, hmap_node, &p->controllers) {
31681a5d
JP
711 rconns[n++] = ofconn->rconn;
712 }
713
714 fail_open_set_controllers(p->fail_open, rconns, n);
715 /* p->fail_open takes ownership of 'rconns'. */
716 } else {
717 fail_open_destroy(p->fail_open);
718 p->fail_open = NULL;
719 }
720}
721
76ce9432
BP
722void
723ofproto_set_controllers(struct ofproto *p,
724 const struct ofproto_controller *controllers,
725 size_t n_controllers)
726{
727 struct shash new_controllers;
7d674866
BP
728 struct ofconn *ofconn, *next_ofconn;
729 struct ofservice *ofservice, *next_ofservice;
76ce9432 730 bool ss_exists;
76ce9432 731 size_t i;
79c9f2ee 732
7d674866
BP
733 /* Create newly configured controllers and services.
734 * Create a name to ofproto_controller mapping in 'new_controllers'. */
76ce9432
BP
735 shash_init(&new_controllers);
736 for (i = 0; i < n_controllers; i++) {
737 const struct ofproto_controller *c = &controllers[i];
738
7d674866
BP
739 if (!vconn_verify_name(c->target) || !strcmp(c->target, "discover")) {
740 if (!find_controller_by_target(p, c->target)) {
741 add_controller(p, c);
742 }
743 } else if (!pvconn_verify_name(c->target)) {
744 if (!ofservice_lookup(p, c->target) && ofservice_create(p, c)) {
745 continue;
746 }
747 } else {
748 VLOG_WARN_RL(&rl, "%s: unsupported controller \"%s\"",
749 dpif_name(p->dpif), c->target);
750 continue;
76ce9432 751 }
7d674866
BP
752
753 shash_add_once(&new_controllers, c->target, &controllers[i]);
76ce9432
BP
754 }
755
7d674866
BP
756 /* Delete controllers that are no longer configured.
757 * Update configuration of all now-existing controllers. */
76ce9432 758 ss_exists = false;
4e8e4213 759 HMAP_FOR_EACH_SAFE (ofconn, next_ofconn, hmap_node, &p->controllers) {
76ce9432
BP
760 struct ofproto_controller *c;
761
762 c = shash_find_data(&new_controllers, ofconn_get_target(ofconn));
763 if (!c) {
764 ofconn_destroy(ofconn);
79c9f2ee 765 } else {
76ce9432 766 update_controller(ofconn, c);
76ce9432
BP
767 if (ofconn->ss) {
768 ss_exists = true;
769 }
76ce9432
BP
770 }
771 }
7d674866
BP
772
773 /* Delete services that are no longer configured.
774 * Update configuration of all now-existing services. */
4e8e4213 775 HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &p->services) {
7d674866
BP
776 struct ofproto_controller *c;
777
778 c = shash_find_data(&new_controllers,
779 pvconn_get_name(ofservice->pvconn));
780 if (!c) {
781 ofservice_destroy(p, ofservice);
782 } else {
783 ofservice_reconfigure(ofservice, c);
784 }
785 }
786
76ce9432
BP
787 shash_destroy(&new_controllers);
788
d2ede7bc 789 update_in_band_remotes(p);
31681a5d 790 update_fail_open(p);
79c9f2ee 791
76ce9432
BP
792 if (!hmap_is_empty(&p->controllers) && !ss_exists) {
793 ofconn = CONTAINER_OF(hmap_first(&p->controllers),
794 struct ofconn, hmap_node);
795 ofconn->ss = switch_status_register(p->switch_status, "remote",
796 rconn_status_cb, ofconn->rconn);
79c9f2ee 797 }
064af421
BP
798}
799
31681a5d
JP
800void
801ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
802{
803 p->fail_mode = fail_mode;
804 update_fail_open(p);
805}
806
fa05809b
BP
807/* Drops the connections between 'ofproto' and all of its controllers, forcing
808 * them to reconnect. */
809void
810ofproto_reconnect_controllers(struct ofproto *ofproto)
811{
812 struct ofconn *ofconn;
813
4e8e4213 814 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
fa05809b
BP
815 rconn_reconnect(ofconn->rconn);
816 }
817}
818
917e50e1
BP
819static bool
820any_extras_changed(const struct ofproto *ofproto,
821 const struct sockaddr_in *extras, size_t n)
822{
823 size_t i;
824
825 if (n != ofproto->n_extra_remotes) {
826 return true;
827 }
828
829 for (i = 0; i < n; i++) {
830 const struct sockaddr_in *old = &ofproto->extra_in_band_remotes[i];
831 const struct sockaddr_in *new = &extras[i];
832
833 if (old->sin_addr.s_addr != new->sin_addr.s_addr ||
834 old->sin_port != new->sin_port) {
835 return true;
836 }
837 }
838
839 return false;
840}
841
842/* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
843 * in-band control should guarantee access, in the same way that in-band
844 * control guarantees access to OpenFlow controllers. */
845void
846ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
847 const struct sockaddr_in *extras, size_t n)
848{
849 if (!any_extras_changed(ofproto, extras, n)) {
850 return;
851 }
852
853 free(ofproto->extra_in_band_remotes);
854 ofproto->n_extra_remotes = n;
855 ofproto->extra_in_band_remotes = xmemdup(extras, n * sizeof *extras);
856
857 update_in_band_remotes(ofproto);
858}
859
b1da6250
BP
860/* Sets the OpenFlow queue used by flows set up by in-band control on
861 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
862 * flows will use the default queue. */
863void
864ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
865{
866 if (queue_id != ofproto->in_band_queue) {
867 ofproto->in_band_queue = queue_id;
868 update_in_band_remotes(ofproto);
869 }
870}
871
064af421
BP
872void
873ofproto_set_desc(struct ofproto *p,
5a719c38
JP
874 const char *mfr_desc, const char *hw_desc,
875 const char *sw_desc, const char *serial_desc,
8abc4ed7 876 const char *dp_desc)
064af421 877{
5a719c38
JP
878 struct ofp_desc_stats *ods;
879
880 if (mfr_desc) {
881 if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
882 VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
883 sizeof ods->mfr_desc);
884 }
885 free(p->mfr_desc);
886 p->mfr_desc = xstrdup(mfr_desc);
064af421 887 }
5a719c38
JP
888 if (hw_desc) {
889 if (strlen(hw_desc) >= sizeof ods->hw_desc) {
890 VLOG_WARN("truncating hw_desc, must be less than %zu characters",
891 sizeof ods->hw_desc);
892 }
893 free(p->hw_desc);
894 p->hw_desc = xstrdup(hw_desc);
064af421 895 }
5a719c38
JP
896 if (sw_desc) {
897 if (strlen(sw_desc) >= sizeof ods->sw_desc) {
898 VLOG_WARN("truncating sw_desc, must be less than %zu characters",
899 sizeof ods->sw_desc);
900 }
901 free(p->sw_desc);
902 p->sw_desc = xstrdup(sw_desc);
903 }
904 if (serial_desc) {
905 if (strlen(serial_desc) >= sizeof ods->serial_num) {
906 VLOG_WARN("truncating serial_desc, must be less than %zu "
907 "characters",
908 sizeof ods->serial_num);
909 }
910 free(p->serial_desc);
911 p->serial_desc = xstrdup(serial_desc);
064af421 912 }
8abc4ed7 913 if (dp_desc) {
5a719c38
JP
914 if (strlen(dp_desc) >= sizeof ods->dp_desc) {
915 VLOG_WARN("truncating dp_desc, must be less than %zu characters",
916 sizeof ods->dp_desc);
917 }
8abc4ed7
JP
918 free(p->dp_desc);
919 p->dp_desc = xstrdup(dp_desc);
920 }
064af421
BP
921}
922
064af421
BP
923static int
924set_pvconns(struct pvconn ***pvconnsp, size_t *n_pvconnsp,
925 const struct svec *svec)
926{
927 struct pvconn **pvconns = *pvconnsp;
928 size_t n_pvconns = *n_pvconnsp;
929 int retval = 0;
930 size_t i;
931
932 for (i = 0; i < n_pvconns; i++) {
933 pvconn_close(pvconns[i]);
934 }
935 free(pvconns);
936
937 pvconns = xmalloc(svec->n * sizeof *pvconns);
938 n_pvconns = 0;
939 for (i = 0; i < svec->n; i++) {
940 const char *name = svec->names[i];
941 struct pvconn *pvconn;
942 int error;
943
944 error = pvconn_open(name, &pvconn);
945 if (!error) {
946 pvconns[n_pvconns++] = pvconn;
947 } else {
948 VLOG_ERR("failed to listen on %s: %s", name, strerror(error));
949 if (!retval) {
950 retval = error;
951 }
952 }
953 }
954
955 *pvconnsp = pvconns;
956 *n_pvconnsp = n_pvconns;
957
958 return retval;
959}
960
064af421
BP
961int
962ofproto_set_snoops(struct ofproto *ofproto, const struct svec *snoops)
963{
964 return set_pvconns(&ofproto->snoops, &ofproto->n_snoops, snoops);
965}
966
967int
0193b2af
JG
968ofproto_set_netflow(struct ofproto *ofproto,
969 const struct netflow_options *nf_options)
064af421 970{
76343538 971 if (nf_options && nf_options->collectors.n) {
064af421
BP
972 if (!ofproto->netflow) {
973 ofproto->netflow = netflow_create();
974 }
0193b2af 975 return netflow_set_options(ofproto->netflow, nf_options);
064af421
BP
976 } else {
977 netflow_destroy(ofproto->netflow);
978 ofproto->netflow = NULL;
979 return 0;
980 }
981}
982
72b06300
BP
983void
984ofproto_set_sflow(struct ofproto *ofproto,
985 const struct ofproto_sflow_options *oso)
986{
987 struct ofproto_sflow *os = ofproto->sflow;
988 if (oso) {
989 if (!os) {
990 struct ofport *ofport;
72b06300
BP
991
992 os = ofproto->sflow = ofproto_sflow_create(ofproto->dpif);
4e8e4213 993 HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
ca0f572c 994 ofproto_sflow_add_port(os, ofport->odp_port,
72b06300
BP
995 netdev_get_name(ofport->netdev));
996 }
997 }
998 ofproto_sflow_set_options(os, oso);
999 } else {
1000 ofproto_sflow_destroy(os);
1001 ofproto->sflow = NULL;
1002 }
1003}
1004
064af421
BP
1005uint64_t
1006ofproto_get_datapath_id(const struct ofproto *ofproto)
1007{
1008 return ofproto->datapath_id;
1009}
1010
76ce9432 1011bool
7d674866 1012ofproto_has_primary_controller(const struct ofproto *ofproto)
064af421 1013{
76ce9432 1014 return !hmap_is_empty(&ofproto->controllers);
064af421
BP
1015}
1016
abdfe474
JP
1017enum ofproto_fail_mode
1018ofproto_get_fail_mode(const struct ofproto *p)
1019{
1020 return p->fail_mode;
1021}
1022
064af421
BP
1023void
1024ofproto_get_snoops(const struct ofproto *ofproto, struct svec *snoops)
1025{
1026 size_t i;
1027
1028 for (i = 0; i < ofproto->n_snoops; i++) {
1029 svec_add(snoops, pvconn_get_name(ofproto->snoops[i]));
1030 }
1031}
1032
1033void
1034ofproto_destroy(struct ofproto *p)
1035{
7d674866 1036 struct ofservice *ofservice, *next_ofservice;
064af421 1037 struct ofconn *ofconn, *next_ofconn;
ca0f572c 1038 struct ofport *ofport, *next_ofport;
064af421
BP
1039 size_t i;
1040
1041 if (!p) {
1042 return;
1043 }
1044
7aa697dd
BP
1045 shash_find_and_delete(&all_ofprotos, dpif_name(p->dpif));
1046
f7de2cdf 1047 /* Destroy fail-open and in-band early, since they touch the classifier. */
79c9f2ee
BP
1048 fail_open_destroy(p->fail_open);
1049 p->fail_open = NULL;
1050
1051 in_band_destroy(p->in_band);
1052 p->in_band = NULL;
917e50e1 1053 free(p->extra_in_band_remotes);
2f6d3445 1054
064af421
BP
1055 ofproto_flush_flows(p);
1056 classifier_destroy(&p->cls);
bcf84111 1057 hmap_destroy(&p->facets);
064af421 1058
4e8e4213 1059 LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &p->all_conns) {
c475ae67 1060 ofconn_destroy(ofconn);
064af421 1061 }
76ce9432 1062 hmap_destroy(&p->controllers);
064af421 1063
c228a364 1064 dpif_close(p->dpif);
e9e28be3 1065 netdev_monitor_destroy(p->netdev_monitor);
4e8e4213 1066 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
ca0f572c 1067 hmap_remove(&p->ports, &ofport->hmap_node);
064af421
BP
1068 ofport_free(ofport);
1069 }
1070 shash_destroy(&p->port_by_name);
1071
1072 switch_status_destroy(p->switch_status);
064af421 1073 netflow_destroy(p->netflow);
72b06300 1074 ofproto_sflow_destroy(p->sflow);
064af421 1075
4e8e4213 1076 HMAP_FOR_EACH_SAFE (ofservice, next_ofservice, node, &p->services) {
7d674866 1077 ofservice_destroy(p, ofservice);
064af421 1078 }
7d674866 1079 hmap_destroy(&p->services);
064af421
BP
1080
1081 for (i = 0; i < p->n_snoops; i++) {
1082 pvconn_close(p->snoops[i]);
1083 }
1084 free(p->snoops);
1085
1086 mac_learning_destroy(p->ml);
1087
5a719c38
JP
1088 free(p->mfr_desc);
1089 free(p->hw_desc);
1090 free(p->sw_desc);
1091 free(p->serial_desc);
cb871ae0
JP
1092 free(p->dp_desc);
1093
ca0f572c 1094 hmap_destroy(&p->ports);
3b917492 1095
064af421
BP
1096 free(p);
1097}
1098
1099int
1100ofproto_run(struct ofproto *p)
1101{
1102 int error = ofproto_run1(p);
1103 if (!error) {
1104 error = ofproto_run2(p, false);
1105 }
1106 return error;
1107}
1108
e9e28be3
BP
1109static void
1110process_port_change(struct ofproto *ofproto, int error, char *devname)
1111{
1112 if (error == ENOBUFS) {
1113 reinit_ports(ofproto);
1114 } else if (!error) {
1115 update_port(ofproto, devname);
1116 free(devname);
1117 }
1118}
1119
e2bfacb6
BP
1120/* Returns a "preference level" for snooping 'ofconn'. A higher return value
1121 * means that 'ofconn' is more interesting for monitoring than a lower return
1122 * value. */
1123static int
1124snoop_preference(const struct ofconn *ofconn)
1125{
1126 switch (ofconn->role) {
1127 case NX_ROLE_MASTER:
1128 return 3;
1129 case NX_ROLE_OTHER:
1130 return 2;
1131 case NX_ROLE_SLAVE:
1132 return 1;
1133 default:
1134 /* Shouldn't happen. */
1135 return 0;
1136 }
1137}
1138
76ce9432
BP
1139/* One of ofproto's "snoop" pvconns has accepted a new connection on 'vconn'.
1140 * Connects this vconn to a controller. */
1141static void
1142add_snooper(struct ofproto *ofproto, struct vconn *vconn)
1143{
e2bfacb6 1144 struct ofconn *ofconn, *best;
76ce9432 1145
e2bfacb6
BP
1146 /* Pick a controller for monitoring. */
1147 best = NULL;
4e8e4213 1148 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
5899143f 1149 if (ofconn->type == OFCONN_PRIMARY
e2bfacb6
BP
1150 && (!best || snoop_preference(ofconn) > snoop_preference(best))) {
1151 best = ofconn;
76ce9432 1152 }
e2bfacb6 1153 }
76ce9432 1154
e2bfacb6
BP
1155 if (best) {
1156 rconn_add_monitor(best->rconn, vconn);
1157 } else {
1158 VLOG_INFO_RL(&rl, "no controller connection to snoop");
1159 vconn_close(vconn);
76ce9432 1160 }
76ce9432
BP
1161}
1162
064af421
BP
1163int
1164ofproto_run1(struct ofproto *p)
1165{
1166 struct ofconn *ofconn, *next_ofconn;
7d674866 1167 struct ofservice *ofservice;
064af421
BP
1168 char *devname;
1169 int error;
1170 int i;
1171
149f577a
JG
1172 if (shash_is_empty(&p->port_by_name)) {
1173 init_ports(p);
1174 }
1175
064af421 1176 for (i = 0; i < 50; i++) {
856081f6 1177 struct dpif_upcall packet;
064af421 1178
856081f6 1179 error = dpif_recv(p->dpif, &packet);
064af421
BP
1180 if (error) {
1181 if (error == ENODEV) {
1182 /* Someone destroyed the datapath behind our back. The caller
1183 * better destroy us and give up, because we're just going to
1184 * spin from here on out. */
39a559f2
BP
1185 static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
1186 VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
c228a364 1187 dpif_name(p->dpif));
064af421
BP
1188 return ENODEV;
1189 }
1190 break;
1191 }
1192
856081f6 1193 handle_upcall(p, &packet);
064af421
BP
1194 }
1195
e9e28be3
BP
1196 while ((error = dpif_port_poll(p->dpif, &devname)) != EAGAIN) {
1197 process_port_change(p, error, devname);
1198 }
1199 while ((error = netdev_monitor_poll(p->netdev_monitor,
1200 &devname)) != EAGAIN) {
1201 process_port_change(p, error, devname);
064af421
BP
1202 }
1203
1204 if (p->in_band) {
d2ede7bc
BP
1205 if (time_msec() >= p->next_in_band_update) {
1206 update_in_band_remotes(p);
1207 }
064af421
BP
1208 in_band_run(p->in_band);
1209 }
064af421 1210
4e8e4213 1211 LIST_FOR_EACH_SAFE (ofconn, next_ofconn, node, &p->all_conns) {
3269c562 1212 ofconn_run(ofconn);
064af421
BP
1213 }
1214
7778bd15
BP
1215 /* Fail-open maintenance. Do this after processing the ofconns since
1216 * fail-open checks the status of the controller rconn. */
1217 if (p->fail_open) {
1218 fail_open_run(p->fail_open);
1219 }
1220
4e8e4213 1221 HMAP_FOR_EACH (ofservice, node, &p->services) {
064af421
BP
1222 struct vconn *vconn;
1223 int retval;
1224
7d674866 1225 retval = pvconn_accept(ofservice->pvconn, OFP_VERSION, &vconn);
064af421 1226 if (!retval) {
9794e806 1227 struct rconn *rconn;
eb15cdbb 1228 char *name;
9794e806 1229
7d674866 1230 rconn = rconn_create(ofservice->probe_interval, 0);
eb15cdbb
BP
1231 name = ofconn_make_name(p, vconn_get_name(vconn));
1232 rconn_connect_unreliably(rconn, vconn, name);
1233 free(name);
1234
7d674866
BP
1235 ofconn = ofconn_create(p, rconn, OFCONN_SERVICE);
1236 ofconn_set_rate_limit(ofconn, ofservice->rate_limit,
1237 ofservice->burst_limit);
064af421
BP
1238 } else if (retval != EAGAIN) {
1239 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1240 }
1241 }
1242
1243 for (i = 0; i < p->n_snoops; i++) {
1244 struct vconn *vconn;
1245 int retval;
1246
1247 retval = pvconn_accept(p->snoops[i], OFP_VERSION, &vconn);
1248 if (!retval) {
76ce9432 1249 add_snooper(p, vconn);
064af421
BP
1250 } else if (retval != EAGAIN) {
1251 VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
1252 }
1253 }
1254
1255 if (time_msec() >= p->next_expiration) {
0de7a4b4
BP
1256 int delay = ofproto_expire(p);
1257 p->next_expiration = time_msec() + delay;
064af421 1258 COVERAGE_INC(ofproto_expiration);
064af421
BP
1259 }
1260
1261 if (p->netflow) {
1262 netflow_run(p->netflow);
1263 }
72b06300
BP
1264 if (p->sflow) {
1265 ofproto_sflow_run(p->sflow);
1266 }
064af421
BP
1267
1268 return 0;
1269}
1270
064af421
BP
1271int
1272ofproto_run2(struct ofproto *p, bool revalidate_all)
1273{
bcf84111
BP
1274 /* Figure out what we need to revalidate now, if anything. */
1275 struct tag_set revalidate_set = p->revalidate_set;
1276 if (p->need_revalidate) {
1277 revalidate_all = true;
1278 }
1279
1280 /* Clear the revalidation flags. */
1281 tag_set_init(&p->revalidate_set);
1282 p->need_revalidate = false;
1283
1284 /* Now revalidate if there's anything to do. */
1285 if (revalidate_all || !tag_set_is_empty(&revalidate_set)) {
1286 struct facet *facet, *next;
1287
1288 HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &p->facets) {
1289 if (revalidate_all
1290 || tag_set_intersects(&revalidate_set, facet->tags)) {
1291 facet_revalidate(p, facet);
1292 }
1293 }
064af421
BP
1294 }
1295
1296 return 0;
1297}
1298
1299void
1300ofproto_wait(struct ofproto *p)
1301{
7d674866 1302 struct ofservice *ofservice;
064af421
BP
1303 struct ofconn *ofconn;
1304 size_t i;
1305
c228a364 1306 dpif_recv_wait(p->dpif);
e9e28be3
BP
1307 dpif_port_poll_wait(p->dpif);
1308 netdev_monitor_poll_wait(p->netdev_monitor);
4e8e4213 1309 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
064af421
BP
1310 ofconn_wait(ofconn);
1311 }
1312 if (p->in_band) {
7cf8b266 1313 poll_timer_wait_until(p->next_in_band_update);
064af421
BP
1314 in_band_wait(p->in_band);
1315 }
064af421
BP
1316 if (p->fail_open) {
1317 fail_open_wait(p->fail_open);
1318 }
72b06300
BP
1319 if (p->sflow) {
1320 ofproto_sflow_wait(p->sflow);
1321 }
064af421
BP
1322 if (!tag_set_is_empty(&p->revalidate_set)) {
1323 poll_immediate_wake();
1324 }
1325 if (p->need_revalidate) {
1326 /* Shouldn't happen, but if it does just go around again. */
1327 VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1328 poll_immediate_wake();
1329 } else if (p->next_expiration != LLONG_MAX) {
7cf8b266 1330 poll_timer_wait_until(p->next_expiration);
064af421 1331 }
4e8e4213 1332 HMAP_FOR_EACH (ofservice, node, &p->services) {
7d674866 1333 pvconn_wait(ofservice->pvconn);
064af421
BP
1334 }
1335 for (i = 0; i < p->n_snoops; i++) {
1336 pvconn_wait(p->snoops[i]);
1337 }
1338}
1339
1340void
1341ofproto_revalidate(struct ofproto *ofproto, tag_type tag)
1342{
1343 tag_set_add(&ofproto->revalidate_set, tag);
1344}
1345
1346struct tag_set *
1347ofproto_get_revalidate_set(struct ofproto *ofproto)
1348{
1349 return &ofproto->revalidate_set;
1350}
1351
1352bool
1353ofproto_is_alive(const struct ofproto *p)
1354{
76ce9432 1355 return !hmap_is_empty(&p->controllers);
064af421
BP
1356}
1357
bffc0589
AE
1358void
1359ofproto_get_ofproto_controller_info(const struct ofproto * ofproto,
1360 struct shash *info)
1361{
1362 const struct ofconn *ofconn;
1363
1364 shash_init(info);
1365
1366 HMAP_FOR_EACH (ofconn, hmap_node, &ofproto->controllers) {
1367 const struct rconn *rconn = ofconn->rconn;
1368 const int last_error = rconn_get_last_error(rconn);
1369 struct ofproto_controller_info *cinfo = xmalloc(sizeof *cinfo);
1370
1371 shash_add(info, rconn_get_target(rconn), cinfo);
1372
1373 cinfo->is_connected = rconn_is_connected(rconn);
1374 cinfo->role = ofconn->role;
1375
1376 cinfo->pairs.n = 0;
1377
1378 if (last_error == EOF) {
1379 cinfo->pairs.keys[cinfo->pairs.n] = "last_error";
1380 cinfo->pairs.values[cinfo->pairs.n++] = xstrdup("End of file");
1381 } else if (last_error > 0) {
1382 cinfo->pairs.keys[cinfo->pairs.n] = "last_error";
1383 cinfo->pairs.values[cinfo->pairs.n++] =
1384 xstrdup(strerror(last_error));
1385 }
1386
1387 cinfo->pairs.keys[cinfo->pairs.n] = "state";
1388 cinfo->pairs.values[cinfo->pairs.n++] =
1389 xstrdup(rconn_get_state(rconn));
1390
1391 cinfo->pairs.keys[cinfo->pairs.n] = "time_in_state";
1392 cinfo->pairs.values[cinfo->pairs.n++] =
1393 xasprintf("%u", rconn_get_state_elapsed(rconn));
1394 }
1395}
1396
1397void
1398ofproto_free_ofproto_controller_info(struct shash *info)
1399{
1400 struct shash_node *node;
1401
1402 SHASH_FOR_EACH (node, info) {
1403 struct ofproto_controller_info *cinfo = node->data;
1404 while (cinfo->pairs.n) {
1405 free((char *) cinfo->pairs.values[--cinfo->pairs.n]);
1406 }
1407 free(cinfo);
1408 }
1409 shash_destroy(info);
1410}
1411
3a6ccc8c
BP
1412/* Deletes port number 'odp_port' from the datapath for 'ofproto'.
1413 *
1414 * This is almost the same as calling dpif_port_del() directly on the
1415 * datapath, but it also makes 'ofproto' close its open netdev for the port
1416 * (if any). This makes it possible to create a new netdev of a different
1417 * type under the same name, which otherwise the netdev library would refuse
1418 * to do because of the conflict. (The netdev would eventually get closed on
1419 * the next trip through ofproto_run(), but this interface is more direct.)
1420 *
3a6ccc8c
BP
1421 * Returns 0 if successful, otherwise a positive errno. */
1422int
1423ofproto_port_del(struct ofproto *ofproto, uint16_t odp_port)
1424{
1425 struct ofport *ofport = get_port(ofproto, odp_port);
0b61210e 1426 const char *name = ofport ? ofport->opp.name : "<unknown>";
3a6ccc8c
BP
1427 int error;
1428
1429 error = dpif_port_del(ofproto->dpif, odp_port);
1430 if (error) {
1431 VLOG_ERR("%s: failed to remove port %"PRIu16" (%s) interface (%s)",
1432 dpif_name(ofproto->dpif), odp_port, name, strerror(error));
1433 } else if (ofport) {
1434 /* 'name' is ofport->opp.name and update_port() is going to destroy
1435 * 'ofport'. Just in case update_port() refers to 'name' after it
1436 * destroys 'ofport', make a copy of it around the update_port()
1437 * call. */
1438 char *devname = xstrdup(name);
1439 update_port(ofproto, devname);
1440 free(devname);
1441 }
1442 return error;
1443}
1444
a4e2e1f2
EJ
1445/* Checks if 'ofproto' thinks 'odp_port' should be included in floods. Returns
1446 * true if 'odp_port' exists and should be included, false otherwise. */
1447bool
1448ofproto_port_is_floodable(struct ofproto *ofproto, uint16_t odp_port)
1449{
1450 struct ofport *ofport = get_port(ofproto, odp_port);
1451 return ofport && !(ofport->opp.config & OFPPC_NO_FLOOD);
1452}
1453
064af421 1454int
ae412e7d 1455ofproto_send_packet(struct ofproto *p, const struct flow *flow,
064af421
BP
1456 const union ofp_action *actions, size_t n_actions,
1457 const struct ofpbuf *packet)
1458{
f29152ca 1459 struct action_xlate_ctx ctx;
cdee00fd 1460 struct ofpbuf *odp_actions;
064af421 1461
f29152ca 1462 action_xlate_ctx_init(&ctx, p, flow, packet);
cdee00fd 1463 odp_actions = xlate_actions(&ctx, actions, n_actions);
064af421
BP
1464
1465 /* XXX Should we translate the dpif_execute() errno value into an OpenFlow
1466 * error code? */
cdee00fd
BP
1467 dpif_execute(p->dpif, odp_actions->data, odp_actions->size, packet);
1468
1469 ofpbuf_delete(odp_actions);
1470
064af421
BP
1471 return 0;
1472}
1473
fa8b054f
BP
1474/* Adds a flow to the OpenFlow flow table in 'p' that matches 'cls_rule' and
1475 * performs the 'n_actions' actions in 'actions'. The new flow will not
1476 * timeout.
1477 *
1478 * If cls_rule->priority is in the range of priorities supported by OpenFlow
1479 * (0...65535, inclusive) then the flow will be visible to OpenFlow
1480 * controllers; otherwise, it will be hidden.
1481 *
1482 * The caller retains ownership of 'cls_rule' and 'actions'. */
064af421 1483void
cf3fad8a 1484ofproto_add_flow(struct ofproto *p, const struct cls_rule *cls_rule,
fa8b054f 1485 const union ofp_action *actions, size_t n_actions)
064af421
BP
1486{
1487 struct rule *rule;
bcf84111 1488 rule = rule_create(cls_rule, actions, n_actions, 0, 0, 0, false);
afe75089 1489 rule_insert(p, rule);
064af421
BP
1490}
1491
1492void
cf3fad8a 1493ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
064af421
BP
1494{
1495 struct rule *rule;
1496
1497 rule = rule_from_cls_rule(classifier_find_rule_exactly(&ofproto->cls,
cf3fad8a 1498 target));
064af421
BP
1499 if (rule) {
1500 rule_remove(ofproto, rule);
1501 }
1502}
1503
064af421
BP
1504void
1505ofproto_flush_flows(struct ofproto *ofproto)
1506{
bcf84111 1507 struct facet *facet, *next_facet;
5ecc9d81
BP
1508 struct rule *rule, *next_rule;
1509 struct cls_cursor cursor;
bcf84111 1510
064af421 1511 COVERAGE_INC(ofproto_flush);
bcf84111
BP
1512
1513 HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
1514 /* Mark the facet as not installed so that facet_remove() doesn't
1515 * bother trying to uninstall it. There is no point in uninstalling it
1516 * individually since we are about to blow away all the facets with
1517 * dpif_flow_flush(). */
1518 facet->installed = false;
1519 facet_remove(ofproto, facet);
1520 }
5ecc9d81
BP
1521
1522 cls_cursor_init(&cursor, &ofproto->cls, NULL);
1523 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1524 rule_remove(ofproto, rule);
1525 }
1526
c228a364 1527 dpif_flow_flush(ofproto->dpif);
064af421
BP
1528 if (ofproto->in_band) {
1529 in_band_flushed(ofproto->in_band);
1530 }
1531 if (ofproto->fail_open) {
1532 fail_open_flushed(ofproto->fail_open);
1533 }
1534}
1535\f
1536static void
1537reinit_ports(struct ofproto *p)
1538{
b0ec0f27 1539 struct dpif_port_dump dump;
c77d9d13
BP
1540 struct shash_node *node;
1541 struct shash devnames;
064af421 1542 struct ofport *ofport;
4c738a8d 1543 struct dpif_port dpif_port;
064af421 1544
898bf89d
JP
1545 COVERAGE_INC(ofproto_reinit_ports);
1546
c77d9d13 1547 shash_init(&devnames);
4e8e4213 1548 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
c77d9d13 1549 shash_add_once (&devnames, ofport->opp.name, NULL);
064af421 1550 }
4c738a8d
BP
1551 DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
1552 shash_add_once (&devnames, dpif_port.name, NULL);
064af421 1553 }
064af421 1554
c77d9d13
BP
1555 SHASH_FOR_EACH (node, &devnames) {
1556 update_port(p, node->name);
064af421 1557 }
c77d9d13 1558 shash_destroy(&devnames);
064af421
BP
1559}
1560
064af421 1561static struct ofport *
4c738a8d 1562make_ofport(const struct dpif_port *dpif_port)
064af421 1563{
149f577a 1564 struct netdev_options netdev_options;
064af421
BP
1565 enum netdev_flags flags;
1566 struct ofport *ofport;
1567 struct netdev *netdev;
064af421
BP
1568 int error;
1569
149f577a 1570 memset(&netdev_options, 0, sizeof netdev_options);
4c738a8d
BP
1571 netdev_options.name = dpif_port->name;
1572 netdev_options.type = dpif_port->type;
149f577a 1573 netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
149f577a
JG
1574
1575 error = netdev_open(&netdev_options, &netdev);
064af421
BP
1576 if (error) {
1577 VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1578 "cannot be opened (%s)",
4c738a8d
BP
1579 dpif_port->name, dpif_port->port_no,
1580 dpif_port->name, strerror(error));
064af421
BP
1581 return NULL;
1582 }
1583
1584 ofport = xmalloc(sizeof *ofport);
1585 ofport->netdev = netdev;
4c738a8d
BP
1586 ofport->odp_port = dpif_port->port_no;
1587 ofport->opp.port_no = odp_port_to_ofp_port(dpif_port->port_no);
80992a35 1588 netdev_get_etheraddr(netdev, ofport->opp.hw_addr);
4c738a8d 1589 ovs_strlcpy(ofport->opp.name, dpif_port->name, sizeof ofport->opp.name);
064af421
BP
1590
1591 netdev_get_flags(netdev, &flags);
1592 ofport->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
1593
85da620e 1594 ofport->opp.state = netdev_get_carrier(netdev) ? 0 : OFPPS_LINK_DOWN;
064af421
BP
1595
1596 netdev_get_features(netdev,
1597 &ofport->opp.curr, &ofport->opp.advertised,
1598 &ofport->opp.supported, &ofport->opp.peer);
1599 return ofport;
1600}
1601
1602static bool
4c738a8d 1603ofport_conflicts(const struct ofproto *p, const struct dpif_port *dpif_port)
064af421 1604{
4c738a8d 1605 if (get_port(p, dpif_port->port_no)) {
064af421 1606 VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
4c738a8d 1607 dpif_port->port_no);
064af421 1608 return true;
4c738a8d 1609 } else if (shash_find(&p->port_by_name, dpif_port->name)) {
064af421 1610 VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
4c738a8d 1611 dpif_port->name);
064af421
BP
1612 return true;
1613 } else {
1614 return false;
1615 }
1616}
1617
1618static int
1619ofport_equal(const struct ofport *a_, const struct ofport *b_)
1620{
1621 const struct ofp_phy_port *a = &a_->opp;
1622 const struct ofp_phy_port *b = &b_->opp;
1623
1624 BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1625 return (a->port_no == b->port_no
1626 && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
0b61210e 1627 && !strcmp(a->name, b->name)
064af421
BP
1628 && a->state == b->state
1629 && a->config == b->config
1630 && a->curr == b->curr
1631 && a->advertised == b->advertised
1632 && a->supported == b->supported
1633 && a->peer == b->peer);
1634}
1635
1636static void
1637send_port_status(struct ofproto *p, const struct ofport *ofport,
1638 uint8_t reason)
1639{
1640 /* XXX Should limit the number of queued port status change messages. */
1641 struct ofconn *ofconn;
4e8e4213 1642 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
064af421
BP
1643 struct ofp_port_status *ops;
1644 struct ofpbuf *b;
1645
197a992f
BP
1646 /* Primary controllers, even slaves, should always get port status
1647 updates. Otherwise obey ofconn_receives_async_msgs(). */
1648 if (ofconn->type != OFCONN_PRIMARY
1649 && !ofconn_receives_async_msgs(ofconn)) {
9deba63b
BP
1650 continue;
1651 }
1652
064af421
BP
1653 ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
1654 ops->reason = reason;
1655 ops->desc = ofport->opp;
1656 hton_ofp_phy_port(&ops->desc);
1657 queue_tx(b, ofconn, NULL);
1658 }
064af421
BP
1659}
1660
1661static void
1662ofport_install(struct ofproto *p, struct ofport *ofport)
1663{
0b61210e 1664 const char *netdev_name = ofport->opp.name;
72b06300 1665
e9e28be3 1666 netdev_monitor_add(p->netdev_monitor, ofport->netdev);
ca0f572c 1667 hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->odp_port, 0));
72b06300
BP
1668 shash_add(&p->port_by_name, netdev_name, ofport);
1669 if (p->sflow) {
ca0f572c 1670 ofproto_sflow_add_port(p->sflow, ofport->odp_port, netdev_name);
72b06300 1671 }
064af421
BP
1672}
1673
1674static void
1675ofport_remove(struct ofproto *p, struct ofport *ofport)
1676{
e9e28be3 1677 netdev_monitor_remove(p->netdev_monitor, ofport->netdev);
ca0f572c 1678 hmap_remove(&p->ports, &ofport->hmap_node);
064af421 1679 shash_delete(&p->port_by_name,
0b61210e 1680 shash_find(&p->port_by_name, ofport->opp.name));
72b06300 1681 if (p->sflow) {
ca0f572c 1682 ofproto_sflow_del_port(p->sflow, ofport->odp_port);
72b06300 1683 }
064af421
BP
1684}
1685
1686static void
1687ofport_free(struct ofport *ofport)
1688{
1689 if (ofport) {
1690 netdev_close(ofport->netdev);
1691 free(ofport);
1692 }
1693}
1694
ca0f572c
BP
1695static struct ofport *
1696get_port(const struct ofproto *ofproto, uint16_t odp_port)
1697{
1698 struct ofport *port;
1699
4e8e4213 1700 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
ca0f572c
BP
1701 hash_int(odp_port, 0), &ofproto->ports) {
1702 if (port->odp_port == odp_port) {
1703 return port;
1704 }
1705 }
1706 return NULL;
1707}
1708
064af421
BP
1709static void
1710update_port(struct ofproto *p, const char *devname)
1711{
4c738a8d 1712 struct dpif_port dpif_port;
c874dc6d
BP
1713 struct ofport *old_ofport;
1714 struct ofport *new_ofport;
064af421
BP
1715 int error;
1716
1717 COVERAGE_INC(ofproto_update_port);
c874dc6d
BP
1718
1719 /* Query the datapath for port information. */
4c738a8d 1720 error = dpif_port_query_by_name(p->dpif, devname, &dpif_port);
064af421 1721
c874dc6d
BP
1722 /* Find the old ofport. */
1723 old_ofport = shash_find_data(&p->port_by_name, devname);
1724 if (!error) {
1725 if (!old_ofport) {
1726 /* There's no port named 'devname' but there might be a port with
1727 * the same port number. This could happen if a port is deleted
1728 * and then a new one added in its place very quickly, or if a port
1729 * is renamed. In the former case we want to send an OFPPR_DELETE
1730 * and an OFPPR_ADD, and in the latter case we want to send a
1731 * single OFPPR_MODIFY. We can distinguish the cases by comparing
1732 * the old port's ifindex against the new port, or perhaps less
1733 * reliably but more portably by comparing the old port's MAC
1734 * against the new port's MAC. However, this code isn't that smart
1735 * and always sends an OFPPR_MODIFY (XXX). */
4c738a8d 1736 old_ofport = get_port(p, dpif_port.port_no);
064af421 1737 }
c874dc6d 1738 } else if (error != ENOENT && error != ENODEV) {
064af421
BP
1739 VLOG_WARN_RL(&rl, "dpif_port_query_by_name returned unexpected error "
1740 "%s", strerror(error));
4c738a8d 1741 goto exit;
064af421 1742 }
c874dc6d
BP
1743
1744 /* Create a new ofport. */
4c738a8d 1745 new_ofport = !error ? make_ofport(&dpif_port) : NULL;
c874dc6d
BP
1746
1747 /* Eliminate a few pathological cases. */
1748 if (!old_ofport && !new_ofport) {
4c738a8d 1749 goto exit;
c874dc6d
BP
1750 } else if (old_ofport && new_ofport) {
1751 /* Most of the 'config' bits are OpenFlow soft state, but
bc4a55cd
BP
1752 * OFPPC_PORT_DOWN is maintained by the kernel. So transfer the
1753 * OpenFlow bits from old_ofport. (make_ofport() only sets
1754 * OFPPC_PORT_DOWN and leaves the other bits 0.) */
c874dc6d
BP
1755 new_ofport->opp.config |= old_ofport->opp.config & ~OFPPC_PORT_DOWN;
1756
1757 if (ofport_equal(old_ofport, new_ofport)) {
1758 /* False alarm--no change. */
1759 ofport_free(new_ofport);
4c738a8d 1760 goto exit;
c874dc6d
BP
1761 }
1762 }
1763
1764 /* Now deal with the normal cases. */
1765 if (old_ofport) {
1766 ofport_remove(p, old_ofport);
1767 }
1768 if (new_ofport) {
1769 ofport_install(p, new_ofport);
1770 }
1771 send_port_status(p, new_ofport ? new_ofport : old_ofport,
1772 (!old_ofport ? OFPPR_ADD
1773 : !new_ofport ? OFPPR_DELETE
1774 : OFPPR_MODIFY));
1775 ofport_free(old_ofport);
4c738a8d
BP
1776
1777exit:
1778 dpif_port_destroy(&dpif_port);
064af421
BP
1779}
1780
1781static int
1782init_ports(struct ofproto *p)
1783{
b0ec0f27 1784 struct dpif_port_dump dump;
4c738a8d 1785 struct dpif_port dpif_port;
064af421 1786
4c738a8d
BP
1787 DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
1788 if (!ofport_conflicts(p, &dpif_port)) {
1789 struct ofport *ofport = make_ofport(&dpif_port);
064af421
BP
1790 if (ofport) {
1791 ofport_install(p, ofport);
1792 }
1793 }
1794 }
b0ec0f27 1795
064af421
BP
1796 return 0;
1797}
1798\f
1799static struct ofconn *
76ce9432 1800ofconn_create(struct ofproto *p, struct rconn *rconn, enum ofconn_type type)
064af421 1801{
76ce9432
BP
1802 struct ofconn *ofconn = xzalloc(sizeof *ofconn);
1803 ofconn->ofproto = p;
064af421
BP
1804 list_push_back(&p->all_conns, &ofconn->node);
1805 ofconn->rconn = rconn;
76ce9432 1806 ofconn->type = type;
b70eac89 1807 ofconn->flow_format = NXFF_OPENFLOW10;
9deba63b 1808 ofconn->role = NX_ROLE_OTHER;
76ce9432 1809 ofconn->packet_in_counter = rconn_packet_counter_create ();
064af421 1810 ofconn->pktbuf = NULL;
064af421 1811 ofconn->miss_send_len = 0;
064af421
BP
1812 ofconn->reply_counter = rconn_packet_counter_create ();
1813 return ofconn;
1814}
1815
1816static void
c475ae67 1817ofconn_destroy(struct ofconn *ofconn)
064af421 1818{
5899143f 1819 if (ofconn->type == OFCONN_PRIMARY) {
76ce9432
BP
1820 hmap_remove(&ofconn->ofproto->controllers, &ofconn->hmap_node);
1821 }
1822 discovery_destroy(ofconn->discovery);
1823
064af421 1824 list_remove(&ofconn->node);
76ce9432 1825 switch_status_unregister(ofconn->ss);
064af421
BP
1826 rconn_destroy(ofconn->rconn);
1827 rconn_packet_counter_destroy(ofconn->packet_in_counter);
1828 rconn_packet_counter_destroy(ofconn->reply_counter);
1829 pktbuf_destroy(ofconn->pktbuf);
1830 free(ofconn);
1831}
1832
1833static void
3269c562 1834ofconn_run(struct ofconn *ofconn)
064af421 1835{
3269c562 1836 struct ofproto *p = ofconn->ofproto;
064af421 1837 int iteration;
76ce9432
BP
1838 size_t i;
1839
1840 if (ofconn->discovery) {
1841 char *controller_name;
1842 if (rconn_is_connectivity_questionable(ofconn->rconn)) {
1843 discovery_question_connectivity(ofconn->discovery);
1844 }
1845 if (discovery_run(ofconn->discovery, &controller_name)) {
1846 if (controller_name) {
eb15cdbb
BP
1847 char *ofconn_name = ofconn_make_name(p, controller_name);
1848 rconn_connect(ofconn->rconn, controller_name, ofconn_name);
1849 free(ofconn_name);
76ce9432
BP
1850 } else {
1851 rconn_disconnect(ofconn->rconn);
1852 }
1853 }
1854 }
1855
1856 for (i = 0; i < N_SCHEDULERS; i++) {
1857 pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
1858 }
064af421
BP
1859
1860 rconn_run(ofconn->rconn);
1861
1862 if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1863 /* Limit the number of iterations to prevent other tasks from
1864 * starving. */
1865 for (iteration = 0; iteration < 50; iteration++) {
1866 struct ofpbuf *of_msg = rconn_recv(ofconn->rconn);
1867 if (!of_msg) {
1868 break;
1869 }
7778bd15
BP
1870 if (p->fail_open) {
1871 fail_open_maybe_recover(p->fail_open);
1872 }
3269c562 1873 handle_openflow(ofconn, of_msg);
064af421
BP
1874 ofpbuf_delete(of_msg);
1875 }
1876 }
1877
76ce9432 1878 if (!ofconn->discovery && !rconn_is_alive(ofconn->rconn)) {
c475ae67 1879 ofconn_destroy(ofconn);
064af421
BP
1880 }
1881}
1882
1883static void
1884ofconn_wait(struct ofconn *ofconn)
1885{
76ce9432
BP
1886 int i;
1887
1888 if (ofconn->discovery) {
1889 discovery_wait(ofconn->discovery);
1890 }
1891 for (i = 0; i < N_SCHEDULERS; i++) {
1892 pinsched_wait(ofconn->schedulers[i]);
1893 }
064af421
BP
1894 rconn_run_wait(ofconn->rconn);
1895 if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1896 rconn_recv_wait(ofconn->rconn);
1897 } else {
1898 COVERAGE_INC(ofproto_ofconn_stuck);
1899 }
1900}
c91248b3
BP
1901
1902/* Returns true if 'ofconn' should receive asynchronous messages. */
1903static bool
1904ofconn_receives_async_msgs(const struct ofconn *ofconn)
1905{
5899143f
BP
1906 if (ofconn->type == OFCONN_PRIMARY) {
1907 /* Primary controllers always get asynchronous messages unless they
c91248b3
BP
1908 * have configured themselves as "slaves". */
1909 return ofconn->role != NX_ROLE_SLAVE;
1910 } else {
5899143f
BP
1911 /* Service connections don't get asynchronous messages unless they have
1912 * explicitly asked for them by setting a nonzero miss send length. */
c91248b3
BP
1913 return ofconn->miss_send_len > 0;
1914 }
1915}
eb15cdbb
BP
1916
1917/* Returns a human-readable name for an OpenFlow connection between 'ofproto'
1918 * and 'target', suitable for use in log messages for identifying the
1919 * connection.
1920 *
1921 * The name is dynamically allocated. The caller should free it (with free())
1922 * when it is no longer needed. */
1923static char *
1924ofconn_make_name(const struct ofproto *ofproto, const char *target)
1925{
1926 return xasprintf("%s<->%s", dpif_base_name(ofproto->dpif), target);
1927}
7d674866
BP
1928
1929static void
1930ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1931{
1932 int i;
1933
1934 for (i = 0; i < N_SCHEDULERS; i++) {
1935 struct pinsched **s = &ofconn->schedulers[i];
1936
1937 if (rate > 0) {
1938 if (!*s) {
1939 *s = pinsched_create(rate, burst,
1940 ofconn->ofproto->switch_status);
1941 } else {
1942 pinsched_set_limits(*s, rate, burst);
1943 }
1944 } else {
1945 pinsched_destroy(*s);
1946 *s = NULL;
1947 }
1948 }
1949}
1950\f
1951static void
1952ofservice_reconfigure(struct ofservice *ofservice,
1953 const struct ofproto_controller *c)
1954{
1955 ofservice->probe_interval = c->probe_interval;
1956 ofservice->rate_limit = c->rate_limit;
1957 ofservice->burst_limit = c->burst_limit;
1958}
1959
1960/* Creates a new ofservice in 'ofproto'. Returns 0 if successful, otherwise a
1961 * positive errno value. */
1962static int
1963ofservice_create(struct ofproto *ofproto, const struct ofproto_controller *c)
1964{
1965 struct ofservice *ofservice;
1966 struct pvconn *pvconn;
1967 int error;
1968
1969 error = pvconn_open(c->target, &pvconn);
1970 if (error) {
1971 return error;
1972 }
1973
1974 ofservice = xzalloc(sizeof *ofservice);
1975 hmap_insert(&ofproto->services, &ofservice->node,
1976 hash_string(c->target, 0));
1977 ofservice->pvconn = pvconn;
1978
1979 ofservice_reconfigure(ofservice, c);
1980
1981 return 0;
1982}
1983
1984static void
1985ofservice_destroy(struct ofproto *ofproto, struct ofservice *ofservice)
1986{
1987 hmap_remove(&ofproto->services, &ofservice->node);
1988 pvconn_close(ofservice->pvconn);
1989 free(ofservice);
1990}
1991
1992/* Finds and returns the ofservice within 'ofproto' that has the given
1993 * 'target', or a null pointer if none exists. */
1994static struct ofservice *
1995ofservice_lookup(struct ofproto *ofproto, const char *target)
1996{
1997 struct ofservice *ofservice;
1998
4e8e4213
BP
1999 HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
2000 &ofproto->services) {
7d674866
BP
2001 if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
2002 return ofservice;
2003 }
2004 }
2005 return NULL;
2006}
064af421 2007\f
bcf84111
BP
2008/* Returns true if 'rule' should be hidden from the controller.
2009 *
2010 * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2011 * (e.g. by in-band control) and are intentionally hidden from the
2012 * controller. */
2013static bool
2014rule_is_hidden(const struct rule *rule)
2015{
2016 return rule->cr.priority > UINT16_MAX;
2017}
2018
2019/* Creates and returns a new rule initialized as specified.
2020 *
2021 * The caller is responsible for inserting the rule into the classifier (with
2022 * rule_insert()). */
064af421 2023static struct rule *
bcf84111 2024rule_create(const struct cls_rule *cls_rule,
064af421 2025 const union ofp_action *actions, size_t n_actions,
ca069229 2026 uint16_t idle_timeout, uint16_t hard_timeout,
8054fc48 2027 ovs_be64 flow_cookie, bool send_flow_removed)
064af421 2028{
ec6fde61 2029 struct rule *rule = xzalloc(sizeof *rule);
bcf84111 2030 rule->cr = *cls_rule;
064af421
BP
2031 rule->idle_timeout = idle_timeout;
2032 rule->hard_timeout = hard_timeout;
39997502 2033 rule->flow_cookie = flow_cookie;
064af421 2034 rule->used = rule->created = time_msec();
ca069229 2035 rule->send_flow_removed = send_flow_removed;
bcf84111 2036 list_init(&rule->facets);
3dffcf07
BP
2037 if (n_actions > 0) {
2038 rule->n_actions = n_actions;
2039 rule->actions = xmemdup(actions, n_actions * sizeof *actions);
2040 }
0193b2af 2041
064af421
BP
2042 return rule;
2043}
2044
2045static struct rule *
2046rule_from_cls_rule(const struct cls_rule *cls_rule)
2047{
2048 return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
2049}
2050
2051static void
2052rule_free(struct rule *rule)
2053{
2054 free(rule->actions);
064af421
BP
2055 free(rule);
2056}
2057
bcf84111
BP
2058/* Destroys 'rule' and iterates through all of its facets and revalidates them,
2059 * destroying any that no longer has a rule (which is probably all of them).
064af421 2060 *
bcf84111 2061 * The caller must have already removed 'rule' from the classifier. */
064af421
BP
2062static void
2063rule_destroy(struct ofproto *ofproto, struct rule *rule)
2064{
bcf84111
BP
2065 struct facet *facet, *next_facet;
2066 LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2067 facet_revalidate(ofproto, facet);
064af421
BP
2068 }
2069 rule_free(rule);
2070}
2071
bcf84111
BP
2072/* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2073 * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
2074 * count). */
064af421 2075static bool
8054fc48 2076rule_has_out_port(const struct rule *rule, ovs_be16 out_port)
064af421
BP
2077{
2078 const union ofp_action *oa;
2079 struct actions_iterator i;
2080
2081 if (out_port == htons(OFPP_NONE)) {
2082 return true;
2083 }
2084 for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
2085 oa = actions_next(&i)) {
c1c9c9c4 2086 if (action_outputs_to_port(oa, out_port)) {
064af421
BP
2087 return true;
2088 }
2089 }
2090 return false;
2091}
2092
750638bb
BP
2093/* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2094 * 'packet', which arrived on 'in_port'.
2095 *
2096 * Takes ownership of 'packet'. */
9dbb9d5e 2097static bool
856081f6 2098execute_odp_actions(struct ofproto *ofproto, const struct flow *flow,
cf22f8cb 2099 const struct nlattr *odp_actions, size_t actions_len,
750638bb 2100 struct ofpbuf *packet)
9dbb9d5e 2101{
b9298d3f 2102 if (actions_len == NLA_ALIGN(NLA_HDRLEN + sizeof(uint64_t))
cdee00fd 2103 && odp_actions->nla_type == ODPAT_CONTROLLER) {
9dbb9d5e
BP
2104 /* As an optimization, avoid a round-trip from userspace to kernel to
2105 * userspace. This also avoids possibly filling up kernel packet
2106 * buffers along the way. */
856081f6 2107 struct dpif_upcall upcall;
9dbb9d5e 2108
856081f6
BP
2109 upcall.type = _ODPL_ACTION_NR;
2110 upcall.packet = packet;
2111 upcall.key = NULL;
2112 upcall.key_len = 0;
2113 upcall.userdata = nl_attr_get_u64(odp_actions);
2114 upcall.sample_pool = 0;
2115 upcall.actions = NULL;
2116 upcall.actions_len = 0;
9dbb9d5e 2117
856081f6 2118 send_packet_in(ofproto, &upcall, flow, false);
9dbb9d5e 2119
750638bb
BP
2120 return true;
2121 } else {
2122 int error;
9dbb9d5e 2123
cdee00fd 2124 error = dpif_execute(ofproto->dpif, odp_actions, actions_len, packet);
750638bb
BP
2125 ofpbuf_delete(packet);
2126 return !error;
2127 }
9dbb9d5e
BP
2128}
2129
bcf84111
BP
2130/* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2131 * statistics appropriately. 'packet' must have at least sizeof(struct
2132 * ofp_packet_in) bytes of headroom.
064af421 2133 *
bcf84111
BP
2134 * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2135 * applying flow_extract() to 'packet' would yield the same flow as
2136 * 'facet->flow'.
064af421 2137 *
bcf84111
BP
2138 * 'facet' must have accurately composed ODP actions; that is, it must not be
2139 * in need of revalidation.
750638bb
BP
2140 *
2141 * Takes ownership of 'packet'. */
064af421 2142static void
bcf84111
BP
2143facet_execute(struct ofproto *ofproto, struct facet *facet,
2144 struct ofpbuf *packet)
064af421 2145{
750638bb 2146 struct odp_flow_stats stats;
bcf84111
BP
2147
2148 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2149
2150 flow_extract_stats(&facet->flow, packet, &stats);
856081f6 2151 if (execute_odp_actions(ofproto, &facet->flow,
cdee00fd 2152 facet->actions, facet->actions_len, packet)) {
bcf84111
BP
2153 facet_update_stats(ofproto, facet, &stats);
2154 facet->used = time_msec();
2155 netflow_flow_update_time(ofproto->netflow,
2156 &facet->nf_flow, facet->used);
2157 }
2158}
2159
2160/* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2161 * statistics (or the statistics for one of its facets) appropriately.
2162 * 'packet' must have at least sizeof(struct ofp_packet_in) bytes of headroom.
2163 *
2164 * 'packet' doesn't necessarily have to match 'rule'. 'rule' will be credited
2165 * with statistics for 'packet' either way.
2166 *
2167 * Takes ownership of 'packet'. */
2168static void
2169rule_execute(struct ofproto *ofproto, struct rule *rule, uint16_t in_port,
2170 struct ofpbuf *packet)
2171{
f29152ca 2172 struct action_xlate_ctx ctx;
cdee00fd 2173 struct ofpbuf *odp_actions;
bcf84111 2174 struct facet *facet;
bcf84111
BP
2175 struct flow flow;
2176 size_t size;
064af421 2177
750638bb
BP
2178 assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2179
bcf84111
BP
2180 flow_extract(packet, 0, in_port, &flow);
2181
2182 /* First look for a related facet. If we find one, account it to that. */
2183 facet = facet_lookup_valid(ofproto, &flow);
2184 if (facet && facet->rule == rule) {
2185 facet_execute(ofproto, facet, packet);
2186 return;
064af421
BP
2187 }
2188
bcf84111
BP
2189 /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
2190 * create a new facet for it and use that. */
2191 if (rule_lookup(ofproto, &flow) == rule) {
2192 facet = facet_create(ofproto, rule, &flow, packet);
2193 facet_execute(ofproto, facet, packet);
2194 facet_install(ofproto, facet, true);
2195 return;
2196 }
2197
2198 /* We can't account anything to a facet. If we were to try, then that
2199 * facet would have a non-matching rule, busting our invariants. */
f29152ca 2200 action_xlate_ctx_init(&ctx, ofproto, &flow, packet);
cdee00fd 2201 odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
bcf84111 2202 size = packet->size;
856081f6 2203 if (execute_odp_actions(ofproto, &flow, odp_actions->data,
cdee00fd 2204 odp_actions->size, packet)) {
064af421 2205 rule->used = time_msec();
bcf84111
BP
2206 rule->packet_count++;
2207 rule->byte_count += size;
064af421 2208 }
cdee00fd 2209 ofpbuf_delete(odp_actions);
064af421
BP
2210}
2211
afe75089 2212/* Inserts 'rule' into 'p''s flow table. */
064af421 2213static void
afe75089 2214rule_insert(struct ofproto *p, struct rule *rule)
064af421
BP
2215{
2216 struct rule *displaced_rule;
2217
064af421 2218 displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
bcf84111
BP
2219 if (displaced_rule) {
2220 rule_destroy(p, displaced_rule);
064af421 2221 }
bcf84111 2222 p->need_revalidate = true;
064af421
BP
2223}
2224
bcf84111
BP
2225/* Creates and returns a new facet within 'ofproto' owned by 'rule', given a
2226 * 'flow' and an example 'packet' within that flow.
2227 *
2228 * The caller must already have determined that no facet with an identical
2229 * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2230 * 'ofproto''s classifier table. */
2231static struct facet *
2232facet_create(struct ofproto *ofproto, struct rule *rule,
2233 const struct flow *flow, const struct ofpbuf *packet)
064af421 2234{
bcf84111 2235 struct facet *facet;
fbb2ea0b 2236
bcf84111
BP
2237 facet = xzalloc(sizeof *facet);
2238 facet->used = time_msec();
2239 hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2240 list_push_back(&rule->facets, &facet->list_node);
2241 facet->rule = rule;
2242 facet->flow = *flow;
2243 netflow_flow_init(&facet->nf_flow);
2244 netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2245
2246 facet_make_actions(ofproto, facet, packet);
064af421 2247
bcf84111
BP
2248 return facet;
2249}
2250
2251static void
2252facet_free(struct facet *facet)
2253{
2254 free(facet->actions);
2255 free(facet);
064af421
BP
2256}
2257
431d4707 2258/* Remove 'rule' from 'ofproto' and free up the associated memory:
431d4707
BP
2259 *
2260 * - Removes 'rule' from the classifier.
2261 *
bcf84111
BP
2262 * - If 'rule' has facets, revalidates them (and possibly uninstalls and
2263 * destroys them), via rule_destroy().
431d4707 2264 */
064af421
BP
2265static void
2266rule_remove(struct ofproto *ofproto, struct rule *rule)
2267{
bcf84111
BP
2268 COVERAGE_INC(ofproto_del_rule);
2269 ofproto->need_revalidate = true;
064af421
BP
2270 classifier_remove(&ofproto->cls, &rule->cr);
2271 rule_destroy(ofproto, rule);
2272}
2273
bcf84111
BP
2274/* Remove 'facet' from 'ofproto' and free up the associated memory:
2275 *
2276 * - If 'facet' was installed in the datapath, uninstalls it and updates its
2277 * rule's statistics, via facet_uninstall().
2278 *
2279 * - Removes 'facet' from its rule and from ofproto->facets.
2280 */
2281static void
2282facet_remove(struct ofproto *ofproto, struct facet *facet)
2283{
2284 facet_uninstall(ofproto, facet);
d530fcd2 2285 facet_flush_stats(ofproto, facet);
bcf84111
BP
2286 hmap_remove(&ofproto->facets, &facet->hmap_node);
2287 list_remove(&facet->list_node);
2288 facet_free(facet);
2289}
2290
7f7ae89d
BP
2291/* Composes the ODP actions for 'facet' based on its rule's actions. */
2292static void
bcf84111
BP
2293facet_make_actions(struct ofproto *p, struct facet *facet,
2294 const struct ofpbuf *packet)
064af421 2295{
bcf84111 2296 const struct rule *rule = facet->rule;
cdee00fd 2297 struct ofpbuf *odp_actions;
f29152ca 2298 struct action_xlate_ctx ctx;
064af421 2299
f29152ca 2300 action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
cdee00fd 2301 odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
19739aee
JP
2302 facet->tags = ctx.tags;
2303 facet->may_install = ctx.may_set_up_flow;
2304 facet->nf_flow.output_iface = ctx.nf_output_iface;
064af421 2305
cdee00fd
BP
2306 if (facet->actions_len != odp_actions->size
2307 || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
7f7ae89d 2308 free(facet->actions);
cdee00fd
BP
2309 facet->actions_len = odp_actions->size;
2310 facet->actions = xmemdup(odp_actions->data, odp_actions->size);
064af421 2311 }
cdee00fd
BP
2312
2313 ofpbuf_delete(odp_actions);
064af421
BP
2314}
2315
2316static int
bcf84111 2317facet_put__(struct ofproto *ofproto, struct facet *facet, int flags,
064af421
BP
2318 struct odp_flow_put *put)
2319{
36956a7d
BP
2320 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2321 struct ofpbuf key;
2322
2323 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2324 odp_flow_key_from_flow(&key, &facet->flow);
2325 assert(key.base == keybuf);
2326
064af421 2327 memset(&put->flow.stats, 0, sizeof put->flow.stats);
36956a7d
BP
2328 put->flow.key = key.data;
2329 put->flow.key_len = key.size;
bcf84111 2330 put->flow.actions = facet->actions;
cdee00fd 2331 put->flow.actions_len = facet->actions_len;
ab48643b 2332 put->flow.flags = 0;
064af421 2333 put->flags = flags;
c228a364 2334 return dpif_flow_put(ofproto->dpif, put);
064af421
BP
2335}
2336
bcf84111
BP
2337/* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath. If
2338 * 'zero_stats' is true, clears any existing statistics from the datapath for
2339 * 'facet'. */
064af421 2340static void
bcf84111 2341facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
064af421 2342{
bcf84111 2343 if (facet->may_install) {
064af421 2344 struct odp_flow_put put;
bcf84111 2345 int flags;
064af421 2346
bcf84111
BP
2347 flags = ODPPF_CREATE | ODPPF_MODIFY;
2348 if (zero_stats) {
2349 flags |= ODPPF_ZERO_STATS;
2350 }
2351 if (!facet_put__(p, facet, flags, &put)) {
2352 facet->installed = true;
2353 }
064af421
BP
2354 }
2355}
2356
bcf84111
BP
2357/* Ensures that the bytes in 'facet', plus 'extra_bytes', have been passed up
2358 * to the accounting hook function in the ofhooks structure. */
064af421 2359static void
bcf84111
BP
2360facet_account(struct ofproto *ofproto,
2361 struct facet *facet, uint64_t extra_bytes)
064af421 2362{
bcf84111 2363 uint64_t total_bytes = facet->byte_count + extra_bytes;
064af421
BP
2364
2365 if (ofproto->ofhooks->account_flow_cb
bcf84111 2366 && total_bytes > facet->accounted_bytes)
064af421
BP
2367 {
2368 ofproto->ofhooks->account_flow_cb(
cdee00fd 2369 &facet->flow, facet->tags, facet->actions, facet->actions_len,
bcf84111
BP
2370 total_bytes - facet->accounted_bytes, ofproto->aux);
2371 facet->accounted_bytes = total_bytes;
064af421
BP
2372 }
2373}
2374
d530fcd2 2375/* If 'rule' is installed in the datapath, uninstalls it. */
064af421 2376static void
bcf84111 2377facet_uninstall(struct ofproto *p, struct facet *facet)
064af421 2378{
bcf84111 2379 if (facet->installed) {
36956a7d 2380 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
064af421 2381 struct odp_flow odp_flow;
36956a7d 2382 struct ofpbuf key;
064af421 2383
36956a7d
BP
2384 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2385 odp_flow_key_from_flow(&key, &facet->flow);
2386 assert(key.base == keybuf);
2387
2388 odp_flow.key = key.data;
2389 odp_flow.key_len = key.size;
064af421 2390 odp_flow.actions = NULL;
cdee00fd 2391 odp_flow.actions_len = 0;
ab48643b 2392 odp_flow.flags = 0;
c228a364 2393 if (!dpif_flow_del(p->dpif, &odp_flow)) {
bcf84111 2394 facet_update_stats(p, facet, &odp_flow.stats);
064af421 2395 }
bcf84111 2396 facet->installed = false;
064af421
BP
2397 }
2398}
2399
bcf84111
BP
2400/* Returns true if the only action for 'facet' is to send to the controller.
2401 * (We don't report NetFlow expiration messages for such facets because they
2402 * are just part of the control logic for the network, not real traffic). */
0193b2af 2403static bool
bcf84111 2404facet_is_controller_flow(struct facet *facet)
0193b2af 2405{
bcf84111
BP
2406 return (facet
2407 && facet->rule->n_actions == 1
2408 && action_outputs_to_port(&facet->rule->actions[0],
c1c9c9c4 2409 htons(OFPP_CONTROLLER)));
0193b2af
JG
2410}
2411
bcf84111
BP
2412/* Folds all of 'facet''s statistics into its rule. Also updates the
2413 * accounting ofhook and emits a NetFlow expiration if appropriate. */
064af421 2414static void
d530fcd2 2415facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
064af421 2416{
bcf84111 2417 facet_account(ofproto, facet, 0);
064af421 2418
bcf84111 2419 if (ofproto->netflow && !facet_is_controller_flow(facet)) {
064af421 2420 struct ofexpired expired;
bcf84111
BP
2421 expired.flow = facet->flow;
2422 expired.packet_count = facet->packet_count;
2423 expired.byte_count = facet->byte_count;
2424 expired.used = facet->used;
2425 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2426 }
2427
2428 facet->rule->packet_count += facet->packet_count;
2429 facet->rule->byte_count += facet->byte_count;
2430
2431 /* Reset counters to prevent double counting if 'facet' ever gets
2432 * reinstalled. */
2433 facet->packet_count = 0;
2434 facet->byte_count = 0;
2435 facet->accounted_bytes = 0;
2436
2437 netflow_flow_clear(&facet->nf_flow);
2438}
2439
2440/* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2441 * Returns it if found, otherwise a null pointer.
2442 *
2443 * The returned facet might need revalidation; use facet_lookup_valid()
2444 * instead if that is important. */
2445static struct facet *
2446facet_find(struct ofproto *ofproto, const struct flow *flow)
2447{
2448 struct facet *facet;
2449
2450 HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2451 &ofproto->facets) {
2452 if (flow_equal(flow, &facet->flow)) {
2453 return facet;
2454 }
2455 }
2456
2457 return NULL;
2458}
2459
2460/* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2461 * Returns it if found, otherwise a null pointer.
2462 *
2463 * The returned facet is guaranteed to be valid. */
2464static struct facet *
2465facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
2466{
2467 struct facet *facet = facet_find(ofproto, flow);
2468
2469 /* The facet we found might not be valid, since we could be in need of
2470 * revalidation. If it is not valid, don't return it. */
2471 if (facet
2472 && ofproto->need_revalidate
2473 && !facet_revalidate(ofproto, facet)) {
2474 COVERAGE_INC(ofproto_invalidated);
2475 return NULL;
064af421 2476 }
064af421 2477
bcf84111
BP
2478 return facet;
2479}
0193b2af 2480
bcf84111
BP
2481/* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2482 *
2483 * - If the rule found is different from 'facet''s current rule, moves
2484 * 'facet' to the new rule and recompiles its actions.
2485 *
2486 * - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2487 * where it is and recompiles its actions anyway.
2488 *
2489 * - If there is none, destroys 'facet'.
2490 *
d530fcd2 2491 * Returns true if 'facet' still exists, false if it has been destroyed. */
bcf84111
BP
2492static bool
2493facet_revalidate(struct ofproto *ofproto, struct facet *facet)
2494{
f29152ca 2495 struct action_xlate_ctx ctx;
cdee00fd 2496 struct ofpbuf *odp_actions;
d530fcd2 2497 struct rule *new_rule;
d530fcd2 2498 bool actions_changed;
bcf84111
BP
2499
2500 COVERAGE_INC(facet_revalidate);
d530fcd2
BP
2501
2502 /* Determine the new rule. */
2503 new_rule = rule_lookup(ofproto, &facet->flow);
2504 if (!new_rule) {
2505 /* No new rule, so delete the facet. */
bcf84111
BP
2506 facet_remove(ofproto, facet);
2507 return false;
2508 }
2509
d530fcd2
BP
2510 /* Calculate new ODP actions.
2511 *
cdee00fd
BP
2512 * We do not modify any 'facet' state yet, because we might need to, e.g.,
2513 * emit a NetFlow expiration and, if so, we need to have the old state
2514 * around to properly compose it. */
f29152ca 2515 action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
cdee00fd
BP
2516 odp_actions = xlate_actions(&ctx, new_rule->actions, new_rule->n_actions);
2517 actions_changed = (facet->actions_len != odp_actions->size
2518 || memcmp(facet->actions, odp_actions->data,
2519 facet->actions_len));
d530fcd2
BP
2520
2521 /* If the ODP actions changed or the installability changed, then we need
2522 * to talk to the datapath. */
2523 if (actions_changed || facet->may_install != facet->installed) {
2524 if (facet->may_install) {
36956a7d 2525 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
d530fcd2 2526 struct odp_flow_put put;
36956a7d
BP
2527 struct ofpbuf key;
2528
2529 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2530 odp_flow_key_from_flow(&key, &facet->flow);
d530fcd2
BP
2531
2532 memset(&put.flow.stats, 0, sizeof put.flow.stats);
36956a7d
BP
2533 put.flow.key = key.data;
2534 put.flow.key_len = key.size;
cdee00fd
BP
2535 put.flow.actions = odp_actions->data;
2536 put.flow.actions_len = odp_actions->size;
d530fcd2
BP
2537 put.flow.flags = 0;
2538 put.flags = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS;
2539 dpif_flow_put(ofproto->dpif, &put);
2540
2541 facet_update_stats(ofproto, facet, &put.flow.stats);
2542 } else {
2543 facet_uninstall(ofproto, facet);
2544 }
2545
2546 /* The datapath flow is gone or has zeroed stats, so push stats out of
2547 * 'facet' into 'rule'. */
2548 facet_flush_stats(ofproto, facet);
2549 }
2550
2551 /* Update 'facet' now that we've taken care of all the old state. */
f29152ca
BP
2552 facet->tags = ctx.tags;
2553 facet->nf_flow.output_iface = ctx.nf_output_iface;
2554 facet->may_install = ctx.may_set_up_flow;
d530fcd2
BP
2555 if (actions_changed) {
2556 free(facet->actions);
cdee00fd
BP
2557 facet->actions_len = odp_actions->size;
2558 facet->actions = xmemdup(odp_actions->data, odp_actions->size);
d530fcd2
BP
2559 }
2560 if (facet->rule != new_rule) {
bcf84111
BP
2561 COVERAGE_INC(facet_changed_rule);
2562 list_remove(&facet->list_node);
d530fcd2
BP
2563 list_push_back(&new_rule->facets, &facet->list_node);
2564 facet->rule = new_rule;
2565 facet->used = new_rule->created;
0c0afbec 2566 }
bcf84111 2567
cdfcd496
BP
2568 ofpbuf_delete(odp_actions);
2569
bcf84111 2570 return true;
064af421
BP
2571}
2572\f
2573static void
2574queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
2575 struct rconn_packet_counter *counter)
2576{
2577 update_openflow_length(msg);
2578 if (rconn_send(ofconn->rconn, msg, counter)) {
2579 ofpbuf_delete(msg);
2580 }
2581}
2582
064af421
BP
2583static void
2584send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
2585 int error)
2586{
dc4762ed 2587 struct ofpbuf *buf = ofputil_encode_error_msg(error, oh);
26c112c2
BP
2588 if (buf) {
2589 COVERAGE_INC(ofproto_error);
2590 queue_tx(buf, ofconn, ofconn->reply_counter);
2591 }
064af421
BP
2592}
2593
2594static void
2595hton_ofp_phy_port(struct ofp_phy_port *opp)
2596{
2597 opp->port_no = htons(opp->port_no);
2598 opp->config = htonl(opp->config);
2599 opp->state = htonl(opp->state);
2600 opp->curr = htonl(opp->curr);
2601 opp->advertised = htonl(opp->advertised);
2602 opp->supported = htonl(opp->supported);
2603 opp->peer = htonl(opp->peer);
2604}
2605
2606static int
d1e2cf21 2607handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
064af421 2608{
d1e2cf21 2609 queue_tx(make_echo_reply(oh), ofconn, ofconn->reply_counter);
064af421
BP
2610 return 0;
2611}
2612
2613static int
d1e2cf21 2614handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
064af421
BP
2615{
2616 struct ofp_switch_features *osf;
2617 struct ofpbuf *buf;
064af421
BP
2618 struct ofport *port;
2619
2620 osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
3269c562 2621 osf->datapath_id = htonll(ofconn->ofproto->datapath_id);
064af421
BP
2622 osf->n_buffers = htonl(pktbuf_capacity());
2623 osf->n_tables = 2;
2624 osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
0254ae23 2625 OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
064af421
BP
2626 osf->actions = htonl((1u << OFPAT_OUTPUT) |
2627 (1u << OFPAT_SET_VLAN_VID) |
2628 (1u << OFPAT_SET_VLAN_PCP) |
2629 (1u << OFPAT_STRIP_VLAN) |
2630 (1u << OFPAT_SET_DL_SRC) |
2631 (1u << OFPAT_SET_DL_DST) |
2632 (1u << OFPAT_SET_NW_SRC) |
2633 (1u << OFPAT_SET_NW_DST) |
959a2ecd 2634 (1u << OFPAT_SET_NW_TOS) |
064af421 2635 (1u << OFPAT_SET_TP_SRC) |
c1c9c9c4
BP
2636 (1u << OFPAT_SET_TP_DST) |
2637 (1u << OFPAT_ENQUEUE));
064af421 2638
3269c562 2639 HMAP_FOR_EACH (port, hmap_node, &ofconn->ofproto->ports) {
064af421
BP
2640 hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
2641 }
2642
2643 queue_tx(buf, ofconn, ofconn->reply_counter);
2644 return 0;
2645}
2646
2647static int
d1e2cf21 2648handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
064af421
BP
2649{
2650 struct ofpbuf *buf;
2651 struct ofp_switch_config *osc;
2652 uint16_t flags;
2653 bool drop_frags;
2654
2655 /* Figure out flags. */
3269c562 2656 dpif_get_drop_frags(ofconn->ofproto->dpif, &drop_frags);
064af421 2657 flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
064af421
BP
2658
2659 /* Send reply. */
2660 osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
2661 osc->flags = htons(flags);
2662 osc->miss_send_len = htons(ofconn->miss_send_len);
2663 queue_tx(buf, ofconn, ofconn->reply_counter);
2664
2665 return 0;
2666}
2667
2668static int
d1e2cf21 2669handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
064af421 2670{
d1e2cf21 2671 uint16_t flags = ntohs(osc->flags);
064af421 2672
5899143f 2673 if (ofconn->type == OFCONN_PRIMARY && ofconn->role != NX_ROLE_SLAVE) {
064af421
BP
2674 switch (flags & OFPC_FRAG_MASK) {
2675 case OFPC_FRAG_NORMAL:
3269c562 2676 dpif_set_drop_frags(ofconn->ofproto->dpif, false);
064af421
BP
2677 break;
2678 case OFPC_FRAG_DROP:
3269c562 2679 dpif_set_drop_frags(ofconn->ofproto->dpif, true);
064af421
BP
2680 break;
2681 default:
2682 VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
2683 osc->flags);
2684 break;
2685 }
2686 }
2687
064af421
BP
2688 ofconn->miss_send_len = ntohs(osc->miss_send_len);
2689
2690 return 0;
2691}
2692
5f8bfd69
BP
2693/* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
2694 * flow translation. */
33b5304b 2695#define MAX_RESUBMIT_RECURSION 16
5f8bfd69 2696
064af421
BP
2697static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2698 struct action_xlate_ctx *ctx);
2699
2700static void
2701add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
2702{
ca0f572c 2703 const struct ofport *ofport = get_port(ctx->ofproto, port);
6cfaf517
BP
2704
2705 if (ofport) {
2706 if (ofport->opp.config & OFPPC_NO_FWD) {
2707 /* Forwarding disabled on port. */
2708 return;
2709 }
2710 } else {
2711 /*
2712 * We don't have an ofport record for this port, but it doesn't hurt to
2713 * allow forwarding to it anyhow. Maybe such a port will appear later
2714 * and we're pre-populating the flow table.
2715 */
064af421 2716 }
6cfaf517 2717
cdee00fd 2718 nl_msg_put_u32(ctx->odp_actions, ODPAT_OUTPUT, port);
6a07af36 2719 ctx->nf_output_iface = port;
064af421
BP
2720}
2721
2722static struct rule *
bcf84111 2723rule_lookup(struct ofproto *ofproto, const struct flow *flow)
064af421 2724{
3c4486a5 2725 return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
064af421
BP
2726}
2727
2728static void
2729xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2730{
5f8bfd69 2731 if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2c5d1389 2732 uint16_t old_in_port;
064af421 2733 struct rule *rule;
064af421 2734
2c5d1389
BP
2735 /* Look up a flow with 'in_port' as the input port. Then restore the
2736 * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2737 * have surprising behavior). */
2738 old_in_port = ctx->flow.in_port;
e18fe8a2 2739 ctx->flow.in_port = in_port;
bcf84111 2740 rule = rule_lookup(ctx->ofproto, &ctx->flow);
2c5d1389
BP
2741 ctx->flow.in_port = old_in_port;
2742
7aa697dd
BP
2743 if (ctx->resubmit_hook) {
2744 ctx->resubmit_hook(ctx, rule);
2745 }
2746
064af421 2747 if (rule) {
064af421
BP
2748 ctx->recurse++;
2749 do_xlate_actions(rule->actions, rule->n_actions, ctx);
2750 ctx->recurse--;
2751 }
5f8bfd69 2752 } else {
db5ce514 2753 static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
5f8bfd69
BP
2754
2755 VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2756 MAX_RESUBMIT_RECURSION);
064af421
BP
2757 }
2758}
2759
f1588b1f
BP
2760static void
2761flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, uint32_t mask,
cdee00fd 2762 uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
f1588b1f
BP
2763{
2764 struct ofport *ofport;
2765
2766 HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
2767 uint16_t odp_port = ofport->odp_port;
2768 if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
cdee00fd 2769 nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, odp_port);
f1588b1f
BP
2770 }
2771 }
2772 *nf_output_iface = NF_OUT_FLOOD;
2773}
2774
064af421 2775static void
aae51f53
BP
2776xlate_output_action__(struct action_xlate_ctx *ctx,
2777 uint16_t port, uint16_t max_len)
064af421
BP
2778{
2779 uint16_t odp_port;
6a07af36
JG
2780 uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2781
2782 ctx->nf_output_iface = NF_OUT_DROP;
064af421 2783
aae51f53 2784 switch (port) {
064af421 2785 case OFPP_IN_PORT:
e18fe8a2 2786 add_output_action(ctx, ctx->flow.in_port);
064af421
BP
2787 break;
2788 case OFPP_TABLE:
e18fe8a2 2789 xlate_table_action(ctx, ctx->flow.in_port);
064af421
BP
2790 break;
2791 case OFPP_NORMAL:
e18fe8a2 2792 if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
cdee00fd 2793 ctx->odp_actions, &ctx->tags,
6a07af36 2794 &ctx->nf_output_iface,
064af421
BP
2795 ctx->ofproto->aux)) {
2796 COVERAGE_INC(ofproto_uninstallable);
d6fbec6d 2797 ctx->may_set_up_flow = false;
064af421
BP
2798 }
2799 break;
2800 case OFPP_FLOOD:
f1588b1f 2801 flood_packets(ctx->ofproto, ctx->flow.in_port, OFPPC_NO_FLOOD,
cdee00fd 2802 &ctx->nf_output_iface, ctx->odp_actions);
9628cd42 2803 break;
064af421 2804 case OFPP_ALL:
f1588b1f 2805 flood_packets(ctx->ofproto, ctx->flow.in_port, 0,
cdee00fd 2806 &ctx->nf_output_iface, ctx->odp_actions);
064af421
BP
2807 break;
2808 case OFPP_CONTROLLER:
b9298d3f 2809 nl_msg_put_u64(ctx->odp_actions, ODPAT_CONTROLLER, max_len);
064af421
BP
2810 break;
2811 case OFPP_LOCAL:
2812 add_output_action(ctx, ODPP_LOCAL);
2813 break;
2814 default:
aae51f53 2815 odp_port = ofp_port_to_odp_port(port);
e18fe8a2 2816 if (odp_port != ctx->flow.in_port) {
064af421
BP
2817 add_output_action(ctx, odp_port);
2818 }
2819 break;
2820 }
6a07af36
JG
2821
2822 if (prev_nf_output_iface == NF_OUT_FLOOD) {
2823 ctx->nf_output_iface = NF_OUT_FLOOD;
2824 } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2825 ctx->nf_output_iface = prev_nf_output_iface;
2826 } else if (prev_nf_output_iface != NF_OUT_DROP &&
2827 ctx->nf_output_iface != NF_OUT_FLOOD) {
2828 ctx->nf_output_iface = NF_OUT_MULTI;
2829 }
064af421
BP
2830}
2831
aae51f53
BP
2832static void
2833xlate_output_action(struct action_xlate_ctx *ctx,
2834 const struct ofp_action_output *oao)
2835{
2836 xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2837}
2838
c1c9c9c4
BP
2839/* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2840 * optimization, because we're going to add another action that sets the
2841 * priority immediately after, or because there are no actions following the
2842 * pop. */
2843static void
2844remove_pop_action(struct action_xlate_ctx *ctx)
2845{
cdee00fd
BP
2846 if (ctx->odp_actions->size == ctx->last_pop_priority) {
2847 ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
2848 ctx->last_pop_priority = -1;
2849 }
2850}
2851
2852static void
2853add_pop_action(struct action_xlate_ctx *ctx)
2854{
2855 if (ctx->odp_actions->size != ctx->last_pop_priority) {
2856 nl_msg_put_flag(ctx->odp_actions, ODPAT_POP_PRIORITY);
2857 ctx->last_pop_priority = ctx->odp_actions->size;
c1c9c9c4
BP
2858 }
2859}
2860
2861static void
2862xlate_enqueue_action(struct action_xlate_ctx *ctx,
2863 const struct ofp_action_enqueue *oae)
2864{
2865 uint16_t ofp_port, odp_port;
aae51f53
BP
2866 uint32_t priority;
2867 int error;
2868
2869 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2870 &priority);
2871 if (error) {
2872 /* Fall back to ordinary output action. */
2873 xlate_output_action__(ctx, ntohs(oae->port), 0);
2874 return;
2875 }
c1c9c9c4
BP
2876
2877 /* Figure out ODP output port. */
2878 ofp_port = ntohs(oae->port);
2879 if (ofp_port != OFPP_IN_PORT) {
2880 odp_port = ofp_port_to_odp_port(ofp_port);
2881 } else {
2882 odp_port = ctx->flow.in_port;
2883 }
2884
2885 /* Add ODP actions. */
2886 remove_pop_action(ctx);
cdee00fd 2887 nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
c1c9c9c4 2888 add_output_action(ctx, odp_port);
cdee00fd 2889 add_pop_action(ctx);
c1c9c9c4
BP
2890
2891 /* Update NetFlow output port. */
2892 if (ctx->nf_output_iface == NF_OUT_DROP) {
2893 ctx->nf_output_iface = odp_port;
2894 } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2895 ctx->nf_output_iface = NF_OUT_MULTI;
2896 }
2897}
2898
eedc0097
JP
2899static void
2900xlate_set_queue_action(struct action_xlate_ctx *ctx,
2901 const struct nx_action_set_queue *nasq)
2902{
2903 uint32_t priority;
2904 int error;
2905
2906 error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2907 &priority);
2908 if (error) {
2909 /* Couldn't translate queue to a priority, so ignore. A warning
2910 * has already been logged. */
2911 return;
2912 }
2913
2914 remove_pop_action(ctx);
cdee00fd 2915 nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
eedc0097
JP
2916}
2917
350a665f
BP
2918static void
2919xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2920{
66642cb4
BP
2921 ovs_be16 tci = ctx->flow.vlan_tci;
2922 if (!(tci & htons(VLAN_CFI))) {
cdee00fd 2923 nl_msg_put_flag(ctx->odp_actions, ODPAT_STRIP_VLAN);
350a665f 2924 } else {
cdee00fd
BP
2925 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_DL_TCI,
2926 tci & ~htons(VLAN_CFI));
350a665f
BP
2927 }
2928}
2929
7b064a79
BP
2930struct xlate_reg_state {
2931 ovs_be16 vlan_tci;
2932 ovs_be64 tun_id;
2933};
2934
b6c9e612 2935static void
7b064a79
BP
2936save_reg_state(const struct action_xlate_ctx *ctx,
2937 struct xlate_reg_state *state)
b6c9e612 2938{
7b064a79
BP
2939 state->vlan_tci = ctx->flow.vlan_tci;
2940 state->tun_id = ctx->flow.tun_id;
2941}
b6c9e612 2942
7b064a79
BP
2943static void
2944update_reg_state(struct action_xlate_ctx *ctx,
2945 const struct xlate_reg_state *state)
2946{
2947 if (ctx->flow.vlan_tci != state->vlan_tci) {
b6c9e612
BP
2948 xlate_set_dl_tci(ctx);
2949 }
7b064a79 2950 if (ctx->flow.tun_id != state->tun_id) {
926947e6
BP
2951 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, ctx->flow.tun_id);
2952 }
b6c9e612
BP
2953}
2954
064af421
BP
2955static void
2956xlate_nicira_action(struct action_xlate_ctx *ctx,
2957 const struct nx_action_header *nah)
2958{
2959 const struct nx_action_resubmit *nar;
659586ef 2960 const struct nx_action_set_tunnel *nast;
eedc0097 2961 const struct nx_action_set_queue *nasq;
53ddd40a 2962 const struct nx_action_multipath *nam;
e41a9130 2963 enum nx_action_subtype subtype = ntohs(nah->subtype);
7b064a79 2964 struct xlate_reg_state state;
b9298d3f 2965 ovs_be64 tun_id;
064af421
BP
2966
2967 assert(nah->vendor == htonl(NX_VENDOR_ID));
2968 switch (subtype) {
2969 case NXAST_RESUBMIT:
2970 nar = (const struct nx_action_resubmit *) nah;
2971 xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2972 break;
2973
659586ef
JG
2974 case NXAST_SET_TUNNEL:
2975 nast = (const struct nx_action_set_tunnel *) nah;
b9298d3f
BP
2976 tun_id = htonll(ntohl(nast->tun_id));
2977 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
2978 ctx->flow.tun_id = tun_id;
659586ef
JG
2979 break;
2980
401eeb92
BP
2981 case NXAST_DROP_SPOOFED_ARP:
2982 if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
cdee00fd 2983 nl_msg_put_flag(ctx->odp_actions, ODPAT_DROP_SPOOFED_ARP);
401eeb92
BP
2984 }
2985 break;
2986
eedc0097
JP
2987 case NXAST_SET_QUEUE:
2988 nasq = (const struct nx_action_set_queue *) nah;
2989 xlate_set_queue_action(ctx, nasq);
2990 break;
2991
2992 case NXAST_POP_QUEUE:
cdee00fd 2993 add_pop_action(ctx);
eedc0097
JP
2994 break;
2995
b6c9e612 2996 case NXAST_REG_MOVE:
7b064a79
BP
2997 save_reg_state(ctx, &state);
2998 nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
2999 &ctx->flow);
3000 update_reg_state(ctx, &state);
b6c9e612
BP
3001 break;
3002
3003 case NXAST_REG_LOAD:
7b064a79 3004 save_reg_state(ctx, &state);
b6c9e612
BP
3005 nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
3006 &ctx->flow);
7b064a79
BP
3007 update_reg_state(ctx, &state);
3008 break;
96fc46e8
BP
3009
3010 case NXAST_NOTE:
3011 /* Nothing to do. */
b6c9e612
BP
3012 break;
3013
b9298d3f
BP
3014 case NXAST_SET_TUNNEL64:
3015 tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
3016 nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
3017 ctx->flow.tun_id = tun_id;
3018 break;
3019
53ddd40a
BP
3020 case NXAST_MULTIPATH:
3021 nam = (const struct nx_action_multipath *) nah;
3022 multipath_execute(nam, &ctx->flow);
3023 break;
3024
999f0d45 3025 /* If you add a new action here that modifies flow data, don't forget to
c1c9c9c4 3026 * update the flow key in ctx->flow at the same time. */
999f0d45 3027
e41a9130 3028 case NXAST_SNAT__OBSOLETE:
064af421 3029 default:
e41a9130 3030 VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
064af421
BP
3031 break;
3032 }
3033}
3034
3035static void
3036do_xlate_actions(const union ofp_action *in, size_t n_in,
3037 struct action_xlate_ctx *ctx)
3038{
3039 struct actions_iterator iter;
3040 const union ofp_action *ia;
3041 const struct ofport *port;
3042
ca0f572c 3043 port = get_port(ctx->ofproto, ctx->flow.in_port);
064af421 3044 if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
ba186119 3045 port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
064af421
BP
3046 ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
3047 /* Drop this flow. */
3048 return;
3049 }
3050
3051 for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
e41a9130 3052 enum ofp_action_type type = ntohs(ia->type);
cdee00fd 3053 const struct ofp_action_dl_addr *oada;
064af421
BP
3054
3055 switch (type) {
3056 case OFPAT_OUTPUT:
3057 xlate_output_action(ctx, &ia->output);
3058 break;
3059
3060 case OFPAT_SET_VLAN_VID:
66642cb4
BP
3061 ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3062 ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
350a665f 3063 xlate_set_dl_tci(ctx);
064af421
BP
3064 break;
3065
3066 case OFPAT_SET_VLAN_PCP:
66642cb4
BP
3067 ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3068 ctx->flow.vlan_tci |= htons(
3069 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
350a665f 3070 xlate_set_dl_tci(ctx);
064af421
BP
3071 break;
3072
3073 case OFPAT_STRIP_VLAN:
66642cb4 3074 ctx->flow.vlan_tci = htons(0);
350a665f 3075 xlate_set_dl_tci(ctx);
064af421
BP
3076 break;
3077
3078 case OFPAT_SET_DL_SRC:
cdee00fd
BP
3079 oada = ((struct ofp_action_dl_addr *) ia);
3080 nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_SRC,
3081 oada->dl_addr, ETH_ADDR_LEN);
3082 memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
064af421
BP
3083 break;
3084
3085 case OFPAT_SET_DL_DST:
cdee00fd
BP
3086 oada = ((struct ofp_action_dl_addr *) ia);
3087 nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_DST,
3088 oada->dl_addr, ETH_ADDR_LEN);
3089 memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
064af421
BP
3090 break;
3091
3092 case OFPAT_SET_NW_SRC:
cdee00fd
BP
3093 nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_SRC,
3094 ia->nw_addr.nw_addr);
3095 ctx->flow.nw_src = ia->nw_addr.nw_addr;
064af421
BP
3096 break;
3097
2d70a31a 3098 case OFPAT_SET_NW_DST:
cdee00fd
BP
3099 nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_DST,
3100 ia->nw_addr.nw_addr);
3101 ctx->flow.nw_dst = ia->nw_addr.nw_addr;
2d38e234 3102 break;
959a2ecd
JP
3103
3104 case OFPAT_SET_NW_TOS:
cdee00fd
BP
3105 nl_msg_put_u8(ctx->odp_actions, ODPAT_SET_NW_TOS,
3106 ia->nw_tos.nw_tos);
3107 ctx->flow.nw_tos = ia->nw_tos.nw_tos;
2d70a31a
JP
3108 break;
3109
064af421 3110 case OFPAT_SET_TP_SRC:
cdee00fd
BP
3111 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_SRC,
3112 ia->tp_port.tp_port);
3113 ctx->flow.tp_src = ia->tp_port.tp_port;
064af421
BP
3114 break;
3115
2d70a31a 3116 case OFPAT_SET_TP_DST:
cdee00fd
BP
3117 nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_DST,
3118 ia->tp_port.tp_port);
3119 ctx->flow.tp_dst = ia->tp_port.tp_port;
2d70a31a
JP
3120 break;
3121
064af421
BP
3122 case OFPAT_VENDOR:
3123 xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
3124 break;
3125
c1c9c9c4
BP
3126 case OFPAT_ENQUEUE:
3127 xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3128 break;
3129
064af421 3130 default:
e41a9130 3131 VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
064af421
BP
3132 break;
3133 }
3134 }
3135}
3136
f29152ca
BP
3137static void
3138action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3139 struct ofproto *ofproto, const struct flow *flow,
3140 const struct ofpbuf *packet)
064af421 3141{
f29152ca
BP
3142 ctx->ofproto = ofproto;
3143 ctx->flow = *flow;
3144 ctx->packet = packet;
7aa697dd 3145 ctx->resubmit_hook = NULL;
f29152ca 3146}
1eb0942d 3147
cdee00fd 3148static struct ofpbuf *
f29152ca
BP
3149xlate_actions(struct action_xlate_ctx *ctx,
3150 const union ofp_action *in, size_t n_in)
3151{
064af421 3152 COVERAGE_INC(ofproto_ofp2odp);
cdee00fd
BP
3153
3154 ctx->odp_actions = ofpbuf_new(512);
f29152ca
BP
3155 ctx->tags = 0;
3156 ctx->may_set_up_flow = true;
3157 ctx->nf_output_iface = NF_OUT_DROP;
3158 ctx->recurse = 0;
cdee00fd 3159 ctx->last_pop_priority = -1;
f29152ca
BP
3160 do_xlate_actions(in, n_in, ctx);
3161 remove_pop_action(ctx);
0ad9b732 3162
d6fbec6d 3163 /* Check with in-band control to see if we're allowed to set up this
0ad9b732 3164 * flow. */
cdee00fd
BP
3165 if (!in_band_rule_check(ctx->ofproto->in_band, &ctx->flow,
3166 ctx->odp_actions->data, ctx->odp_actions->size)) {
f29152ca 3167 ctx->may_set_up_flow = false;
0ad9b732
JP
3168 }
3169
cdee00fd 3170 return ctx->odp_actions;
064af421
BP
3171}
3172
9deba63b
BP
3173/* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
3174 * error message code (composed with ofp_mkerr()) for the caller to propagate
3175 * upward. Otherwise, returns 0.
3176 *
2228b50d 3177 * The log message mentions 'msg_type'. */
9deba63b 3178static int
2228b50d 3179reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
9deba63b 3180{
5899143f 3181 if (ofconn->type == OFCONN_PRIMARY && ofconn->role == NX_ROLE_SLAVE) {
9deba63b 3182 static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
9deba63b 3183 VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
2228b50d 3184 msg_type);
9deba63b
BP
3185
3186 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3187 } else {
3188 return 0;
3189 }
3190}
3191
064af421 3192static int
d1e2cf21 3193handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
064af421 3194{
3269c562 3195 struct ofproto *p = ofconn->ofproto;
064af421
BP
3196 struct ofp_packet_out *opo;
3197 struct ofpbuf payload, *buffer;
ac51afaf 3198 union ofp_action *ofp_actions;
f29152ca 3199 struct action_xlate_ctx ctx;
cdee00fd 3200 struct ofpbuf *odp_actions;
ac51afaf 3201 struct ofpbuf request;
ae412e7d 3202 struct flow flow;
ac51afaf 3203 size_t n_ofp_actions;
064af421 3204 uint16_t in_port;
064af421
BP
3205 int error;
3206
ac51afaf
BP
3207 COVERAGE_INC(ofproto_packet_out);
3208
2228b50d 3209 error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
9deba63b
BP
3210 if (error) {
3211 return error;
3212 }
3213
ac51afaf 3214 /* Get ofp_packet_out. */
0bc9407d 3215 ofpbuf_use_const(&request, oh, ntohs(oh->length));
bbc32a88 3216 opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
ac51afaf
BP
3217
3218 /* Get actions. */
3219 error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
3220 &ofp_actions, &n_ofp_actions);
064af421
BP
3221 if (error) {
3222 return error;
3223 }
064af421 3224
ac51afaf 3225 /* Get payload. */
064af421
BP
3226 if (opo->buffer_id != htonl(UINT32_MAX)) {
3227 error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
3228 &buffer, &in_port);
7778bd15 3229 if (error || !buffer) {
064af421
BP
3230 return error;
3231 }
3232 payload = *buffer;
3233 } else {
ac51afaf 3234 payload = request;
064af421
BP
3235 buffer = NULL;
3236 }
3237
ac51afaf
BP
3238 /* Extract flow, check actions. */
3239 flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
3240 &flow);
f1defbf9 3241 error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
ac51afaf
BP
3242 if (error) {
3243 goto exit;
3244 }
3245
3246 /* Send. */
f29152ca 3247 action_xlate_ctx_init(&ctx, p, &flow, &payload);
cdee00fd
BP
3248 odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
3249 dpif_execute(p->dpif, odp_actions->data, odp_actions->size, &payload);
3250 ofpbuf_delete(odp_actions);
064af421 3251
ac51afaf
BP
3252exit:
3253 ofpbuf_delete(buffer);
3254 return 0;
064af421
BP
3255}
3256
3257static void
3258update_port_config(struct ofproto *p, struct ofport *port,
3259 uint32_t config, uint32_t mask)
3260{
3261 mask &= config ^ port->opp.config;
3262 if (mask & OFPPC_PORT_DOWN) {
3263 if (config & OFPPC_PORT_DOWN) {
3264 netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
3265 } else {
3266 netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
3267 }
3268 }
f1588b1f
BP
3269#define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP | \
3270 OFPPC_NO_FWD | OFPPC_NO_FLOOD)
064af421
BP
3271 if (mask & REVALIDATE_BITS) {
3272 COVERAGE_INC(ofproto_costly_flags);
3273 port->opp.config ^= mask & REVALIDATE_BITS;
3274 p->need_revalidate = true;
3275 }
3276#undef REVALIDATE_BITS
064af421
BP
3277 if (mask & OFPPC_NO_PACKET_IN) {
3278 port->opp.config ^= OFPPC_NO_PACKET_IN;
3279 }
3280}
3281
3282static int
d1e2cf21 3283handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
064af421 3284{
3269c562 3285 struct ofproto *p = ofconn->ofproto;
d1e2cf21 3286 const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
064af421
BP
3287 struct ofport *port;
3288 int error;
3289
2228b50d 3290 error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
9deba63b
BP
3291 if (error) {
3292 return error;
3293 }
064af421 3294
ca0f572c 3295 port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
064af421
BP
3296 if (!port) {
3297 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
3298 } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
3299 return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
3300 } else {
3301 update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
3302 if (opm->advertise) {
3303 netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
3304 }
3305 }
3306 return 0;
3307}
3308
3309static struct ofpbuf *
06a5e131 3310make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
064af421
BP
3311{
3312 struct ofp_stats_reply *osr;
3313 struct ofpbuf *msg;
3314
3315 msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
3316 osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
3317 osr->type = type;
3318 osr->flags = htons(0);
3319 return msg;
3320}
3321
3322static struct ofpbuf *
d1e2cf21 3323start_ofp_stats_reply(const struct ofp_header *request, size_t body_len)
064af421 3324{
d1e2cf21
BP
3325 const struct ofp_stats_request *osr
3326 = (const struct ofp_stats_request *) request;
3327 return make_ofp_stats_reply(osr->header.xid, osr->type, body_len);
064af421
BP
3328}
3329
3330static void *
06a5e131
BP
3331append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
3332 struct ofpbuf **msgp)
064af421
BP
3333{
3334 struct ofpbuf *msg = *msgp;
3335 assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
3336 if (nbytes + msg->size > UINT16_MAX) {
3337 struct ofp_stats_reply *reply = msg->data;
3338 reply->flags = htons(OFPSF_REPLY_MORE);
06a5e131 3339 *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
064af421
BP
3340 queue_tx(msg, ofconn, ofconn->reply_counter);
3341 }
3342 return ofpbuf_put_uninit(*msgp, nbytes);
3343}
3344
09246b99
BP
3345static struct ofpbuf *
3346make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
3347{
3348 struct nicira_stats_msg *nsm;
3349 struct ofpbuf *msg;
3350
3351 msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
3352 nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
3353 nsm->type = htons(OFPST_VENDOR);
3354 nsm->flags = htons(0);
3355 nsm->vendor = htonl(NX_VENDOR_ID);
d5f2379b 3356 nsm->subtype = subtype;
09246b99
BP
3357 return msg;
3358}
3359
3360static struct ofpbuf *
3361start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
3362{
3363 return make_nxstats_reply(request->header.xid, request->subtype, body_len);
3364}
3365
3366static void
3367append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
3368 struct ofpbuf **msgp)
3369{
3370 struct ofpbuf *msg = *msgp;
3371 assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
3372 if (nbytes + msg->size > UINT16_MAX) {
3373 struct nicira_stats_msg *reply = msg->data;
3374 reply->flags = htons(OFPSF_REPLY_MORE);
3375 *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
3376 queue_tx(msg, ofconn, ofconn->reply_counter);
3377 }
3378 ofpbuf_prealloc_tailroom(*msgp, nbytes);
3379}
3380
064af421 3381static int
3269c562 3382handle_desc_stats_request(struct ofconn *ofconn,
d1e2cf21 3383 const struct ofp_header *request)
064af421 3384{
3269c562 3385 struct ofproto *p = ofconn->ofproto;
064af421
BP
3386 struct ofp_desc_stats *ods;
3387 struct ofpbuf *msg;
3388
06a5e131
BP
3389 msg = start_ofp_stats_reply(request, sizeof *ods);
3390 ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
5a719c38
JP
3391 memset(ods, 0, sizeof *ods);
3392 ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
3393 ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
3394 ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
3395 ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
3396 ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
064af421
BP
3397 queue_tx(msg, ofconn, ofconn->reply_counter);
3398
3399 return 0;
3400}
3401
064af421 3402static int
3269c562 3403handle_table_stats_request(struct ofconn *ofconn,
d1e2cf21 3404 const struct ofp_header *request)
064af421 3405{
3269c562 3406 struct ofproto *p = ofconn->ofproto;
064af421
BP
3407 struct ofp_table_stats *ots;
3408 struct ofpbuf *msg;
064af421 3409
06a5e131 3410 msg = start_ofp_stats_reply(request, sizeof *ots * 2);
064af421 3411
064af421 3412 /* Classifier table. */
06a5e131 3413 ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
064af421 3414 memset(ots, 0, sizeof *ots);
064af421 3415 strcpy(ots->name, "classifier");
b70eac89 3416 ots->wildcards = (ofconn->flow_format == NXFF_OPENFLOW10
f9bfea14 3417 ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
ad828225 3418 ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
bcf84111 3419 ots->active_count = htonl(classifier_count(&p->cls));
064af421
BP
3420 ots->lookup_count = htonll(0); /* XXX */
3421 ots->matched_count = htonll(0); /* XXX */
3422
3423 queue_tx(msg, ofconn, ofconn->reply_counter);
3424 return 0;
3425}
3426
abaad8cf 3427static void
ca0f572c 3428append_port_stat(struct ofport *port, struct ofconn *ofconn,
a4948b95 3429 struct ofpbuf **msgp)
abaad8cf
JP
3430{
3431 struct netdev_stats stats;
3432 struct ofp_port_stats *ops;
3433
d295e8e9
JP
3434 /* Intentionally ignore return value, since errors will set
3435 * 'stats' to all-1s, which is correct for OpenFlow, and
abaad8cf
JP
3436 * netdev_get_stats() will log errors. */
3437 netdev_get_stats(port->netdev, &stats);
3438
06a5e131 3439 ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
ca0f572c 3440 ops->port_no = htons(port->opp.port_no);
abaad8cf
JP
3441 memset(ops->pad, 0, sizeof ops->pad);
3442 ops->rx_packets = htonll(stats.rx_packets);
3443 ops->tx_packets = htonll(stats.tx_packets);
3444 ops->rx_bytes = htonll(stats.rx_bytes);
3445 ops->tx_bytes = htonll(stats.tx_bytes);
3446 ops->rx_dropped = htonll(stats.rx_dropped);
3447 ops->tx_dropped = htonll(stats.tx_dropped);
3448 ops->rx_errors = htonll(stats.rx_errors);
3449 ops->tx_errors = htonll(stats.tx_errors);
3450 ops->rx_frame_err = htonll(stats.rx_frame_errors);
3451 ops->rx_over_err = htonll(stats.rx_over_errors);
3452 ops->rx_crc_err = htonll(stats.rx_crc_errors);
3453 ops->collisions = htonll(stats.collisions);
3454}
3455
064af421 3456static int
d1e2cf21 3457handle_port_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
064af421 3458{
3269c562 3459 struct ofproto *p = ofconn->ofproto;
d1e2cf21 3460 const struct ofp_port_stats_request *psr = ofputil_stats_body(oh);
064af421
BP
3461 struct ofp_port_stats *ops;
3462 struct ofpbuf *msg;
3463 struct ofport *port;
064af421 3464
d1e2cf21 3465 msg = start_ofp_stats_reply(oh, sizeof *ops * 16);
abaad8cf 3466 if (psr->port_no != htons(OFPP_NONE)) {
ca0f572c 3467 port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
abaad8cf 3468 if (port) {
ca0f572c 3469 append_port_stat(port, ofconn, &msg);
abaad8cf
JP
3470 }
3471 } else {
4e8e4213 3472 HMAP_FOR_EACH (port, hmap_node, &p->ports) {
ca0f572c 3473 append_port_stat(port, ofconn, &msg);
abaad8cf 3474 }
064af421
BP
3475 }
3476
3477 queue_tx(msg, ofconn, ofconn->reply_counter);
3478 return 0;
3479}
3480
01149cfd 3481/* Obtains statistic counters for 'rule' within 'p' and stores them into
bcf84111
BP
3482 * '*packet_countp' and '*byte_countp'. The returned statistics include
3483 * statistics for all of 'rule''s facets. */
064af421
BP
3484static void
3485query_stats(struct ofproto *p, struct rule *rule,
3486 uint64_t *packet_countp, uint64_t *byte_countp)
3487{
36956a7d 3488 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
064af421 3489 uint64_t packet_count, byte_count;
bcf84111 3490 struct facet *facet;
36956a7d 3491 struct ofpbuf key;
064af421 3492
01149cfd 3493 /* Start from historical data for 'rule' itself that are no longer tracked
bcf84111 3494 * by the datapath. This counts, for example, facets that have expired. */
b3137fe8
JG
3495 packet_count = rule->packet_count;
3496 byte_count = rule->byte_count;
3497
36956a7d
BP
3498 /* Ask the datapath for statistics on all of the rule's facets. (We could
3499 * batch up statistics requests using dpif_flow_get_multiple(), but that is
3500 * not yet implemented.)
01149cfd
BP
3501 *
3502 * Also, add any statistics that are not tracked by the datapath for each
bcf84111 3503 * facet. This includes, for example, statistics for packets that were
01149cfd 3504 * executed "by hand" by ofproto via dpif_execute() but must be accounted
bcf84111 3505 * to a rule. */
36956a7d 3506 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
bcf84111 3507 LIST_FOR_EACH (facet, list_node, &rule->facets) {
36956a7d 3508 struct odp_flow odp_flow;
064af421 3509
36956a7d
BP
3510 ofpbuf_clear(&key);
3511 odp_flow_key_from_flow(&key, &facet->flow);
bcf84111 3512
36956a7d
BP
3513 odp_flow.key = key.data;
3514 odp_flow.key_len = key.size;
3515 odp_flow.actions = NULL;
3516 odp_flow.actions_len = 0;
3517 odp_flow.flags = 0;
3518 if (!dpif_flow_get(p->dpif, &odp_flow)) {
3519 packet_count += odp_flow.stats.n_packets;
3520 byte_count += odp_flow.stats.n_bytes;
064af421 3521 }
36956a7d
BP
3522
3523 packet_count += facet->packet_count;
3524 byte_count += facet->byte_count;
064af421 3525 }
064af421 3526
01149cfd 3527 /* Return the stats to the caller. */
064af421
BP
3528 *packet_countp = packet_count;
3529 *byte_countp = byte_count;
3530}
3531
c6ebb8fb
BP
3532static void
3533calc_flow_duration(long long int start, ovs_be32 *sec, ovs_be32 *nsec)
3534{
3535 long long int msecs = time_msec() - start;
3536 *sec = htonl(msecs / 1000);
3537 *nsec = htonl((msecs % 1000) * (1000 * 1000));
3538}
3539
064af421 3540static void
5ecc9d81
BP
3541put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
3542 ovs_be16 out_port, struct ofpbuf **replyp)
064af421 3543{
064af421
BP
3544 struct ofp_flow_stats *ofs;
3545 uint64_t packet_count, byte_count;
3546 size_t act_len, len;
3547
5ecc9d81 3548 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
064af421
BP
3549 return;
3550 }
3551
3552 act_len = sizeof *rule->actions * rule->n_actions;
3553 len = offsetof(struct ofp_flow_stats, actions) + act_len;
3554
5ecc9d81 3555 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
064af421 3556
5ecc9d81 3557 ofs = append_ofp_stats_reply(len, ofconn, replyp);
064af421 3558 ofs->length = htons(len);
ad828225 3559 ofs->table_id = 0;
064af421 3560 ofs->pad = 0;
ff9d3826
BP
3561 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofs->match,
3562 rule->flow_cookie, &ofs->cookie);
c6ebb8fb 3563 calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
064af421
BP
3564 ofs->priority = htons(rule->cr.priority);
3565 ofs->idle_timeout = htons(rule->idle_timeout);
3566 ofs->hard_timeout = htons(rule->hard_timeout);
39997502 3567 memset(ofs->pad2, 0, sizeof ofs->pad2);
064af421
BP
3568 ofs->packet_count = htonll(packet_count);
3569 ofs->byte_count = htonll(byte_count);
3dffcf07
BP
3570 if (rule->n_actions > 0) {
3571 memcpy(ofs->actions, rule->actions, act_len);
3572 }
064af421
BP
3573}
3574
3c4486a5
BP
3575static bool
3576is_valid_table(uint8_t table_id)
064af421 3577{
3c4486a5 3578 return table_id == 0 || table_id == 0xff;
064af421
BP
3579}
3580
3581static int
d1e2cf21 3582handle_flow_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
064af421 3583{
d1e2cf21 3584 const struct ofp_flow_stats_request *fsr = ofputil_stats_body(oh);
5ecc9d81 3585 struct ofpbuf *reply;
064af421 3586
064af421 3587 COVERAGE_INC(ofproto_flows_req);
d1e2cf21 3588 reply = start_ofp_stats_reply(oh, 1024);
3c4486a5 3589 if (is_valid_table(fsr->table_id)) {
5ecc9d81 3590 struct cls_cursor cursor;
3c4486a5 3591 struct cls_rule target;
5ecc9d81 3592 struct rule *rule;
3c4486a5 3593
d8ae4d67
BP
3594 ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
3595 &target);
5ecc9d81
BP
3596 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3597 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3598 put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
3599 }
3c4486a5 3600 }
5ecc9d81 3601 queue_tx(reply, ofconn, ofconn->reply_counter);
3c4486a5 3602
064af421
BP
3603 return 0;
3604}
3605
09246b99 3606static void
5ecc9d81
BP
3607put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
3608 ovs_be16 out_port, struct ofpbuf **replyp)
09246b99 3609{
09246b99
BP
3610 struct nx_flow_stats *nfs;
3611 uint64_t packet_count, byte_count;
3612 size_t act_len, start_len;
5ecc9d81 3613 struct ofpbuf *reply;
09246b99 3614
5ecc9d81 3615 if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
09246b99
BP
3616 return;
3617 }
3618
5ecc9d81 3619 query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
09246b99
BP
3620
3621 act_len = sizeof *rule->actions * rule->n_actions;
3622
5ecc9d81 3623 append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
1dfee98d 3624 start_len = (*replyp)->size;
5ecc9d81
BP
3625 reply = *replyp;
3626
3627 nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
09246b99
BP
3628 nfs->table_id = 0;
3629 nfs->pad = 0;
3630 calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
3631 nfs->cookie = rule->flow_cookie;
3632 nfs->priority = htons(rule->cr.priority);
3633 nfs->idle_timeout = htons(rule->idle_timeout);
3634 nfs->hard_timeout = htons(rule->hard_timeout);
5ecc9d81 3635 nfs->match_len = htons(nx_put_match(reply, &rule->cr));
09246b99
BP
3636 memset(nfs->pad2, 0, sizeof nfs->pad2);
3637 nfs->packet_count = htonll(packet_count);
3638 nfs->byte_count = htonll(byte_count);
3639 if (rule->n_actions > 0) {
5ecc9d81 3640 ofpbuf_put(reply, rule->actions, act_len);
09246b99 3641 }
5ecc9d81 3642 nfs->length = htons(reply->size - start_len);
09246b99
BP
3643}
3644
3645static int
d1e2cf21 3646handle_nxst_flow(struct ofconn *ofconn, const struct ofp_header *oh)
09246b99
BP
3647{
3648 struct nx_flow_stats_request *nfsr;
09246b99 3649 struct cls_rule target;
5ecc9d81 3650 struct ofpbuf *reply;
d1e2cf21 3651 struct ofpbuf b;
09246b99
BP
3652 int error;
3653
0bc9407d 3654 ofpbuf_use_const(&b, oh, ntohs(oh->length));
d1e2cf21 3655
09246b99 3656 /* Dissect the message. */
bbc32a88 3657 nfsr = ofpbuf_pull(&b, sizeof *nfsr);
d1e2cf21 3658 error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &target);
09246b99
BP
3659 if (error) {
3660 return error;
3661 }
d1e2cf21
BP
3662 if (b.size) {
3663 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3664 }
09246b99
BP
3665
3666 COVERAGE_INC(ofproto_flows_req);
5ecc9d81 3667 reply = start_nxstats_reply(&nfsr->nsm, 1024);
3c4486a5 3668 if (is_valid_table(nfsr->table_id)) {
5ecc9d81
BP
3669 struct cls_cursor cursor;
3670 struct rule *rule;
3671
3672 cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3673 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3674 put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
3675 }
3c4486a5 3676 }
5ecc9d81
BP
3677 queue_tx(reply, ofconn, ofconn->reply_counter);
3678
09246b99
BP
3679 return 0;
3680}
3681
4f2cad2c 3682static void
5ecc9d81 3683flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
4f2cad2c 3684{
4f2cad2c
JP
3685 uint64_t packet_count, byte_count;
3686 size_t act_len = sizeof *rule->actions * rule->n_actions;
3687
5ecc9d81 3688 query_stats(ofproto, rule, &packet_count, &byte_count);
4f2cad2c
JP
3689
3690 ds_put_format(results, "duration=%llds, ",
3691 (time_msec() - rule->created) / 1000);
52ae00b3 3692 ds_put_format(results, "priority=%u, ", rule->cr.priority);
4f2cad2c
JP
3693 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3694 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
cb833cf6 3695 cls_rule_format(&rule->cr, results);
3dffcf07
BP
3696 if (act_len > 0) {
3697 ofp_print_actions(results, &rule->actions->header, act_len);
3c8552c1
JP
3698 } else {
3699 ds_put_cstr(results, "drop");
3dffcf07 3700 }
4f2cad2c
JP
3701 ds_put_cstr(results, "\n");
3702}
3703
d295e8e9 3704/* Adds a pretty-printed description of all flows to 'results', including
4f2cad2c
JP
3705 * those marked hidden by secchan (e.g., by in-band control). */
3706void
3707ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3708{
5ecc9d81
BP
3709 struct cls_cursor cursor;
3710 struct rule *rule;
064af421 3711
5ecc9d81
BP
3712 cls_cursor_init(&cursor, &p->cls, NULL);
3713 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3714 flow_stats_ds(p, rule, results);
064af421 3715 }
064af421
BP
3716}
3717
27d34fce
BP
3718static void
3719query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
734bbeb4 3720 ovs_be16 out_port, uint8_t table_id,
27d34fce
BP
3721 struct ofp_aggregate_stats_reply *oasr)
3722{
5ecc9d81
BP
3723 uint64_t total_packets = 0;
3724 uint64_t total_bytes = 0;
3725 int n_flows = 0;
27d34fce
BP
3726
3727 COVERAGE_INC(ofproto_agg_request);
5ecc9d81 3728
3c4486a5 3729 if (is_valid_table(table_id)) {
5ecc9d81
BP
3730 struct cls_cursor cursor;
3731 struct rule *rule;
3c4486a5 3732
5ecc9d81
BP
3733 cls_cursor_init(&cursor, &ofproto->cls, target);
3734 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3735 if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
3736 uint64_t packet_count;
3737 uint64_t byte_count;
3738
3739 query_stats(ofproto, rule, &packet_count, &byte_count);
3740
3741 total_packets += packet_count;
3742 total_bytes += byte_count;
3743 n_flows++;
3744 }
3745 }
3c4486a5 3746 }
27d34fce 3747
5ecc9d81
BP
3748 oasr->flow_count = htonl(n_flows);
3749 oasr->packet_count = htonll(total_packets);
3750 oasr->byte_count = htonll(total_bytes);
27d34fce
BP
3751 memset(oasr->pad, 0, sizeof oasr->pad);
3752}
3753
064af421 3754static int
3269c562 3755handle_aggregate_stats_request(struct ofconn *ofconn,
d1e2cf21 3756 const struct ofp_header *oh)
064af421 3757{
d1e2cf21 3758 const struct ofp_aggregate_stats_request *request = ofputil_stats_body(oh);
064af421 3759 struct ofp_aggregate_stats_reply *reply;
064af421
BP
3760 struct cls_rule target;
3761 struct ofpbuf *msg;
3762
d8ae4d67
BP
3763 ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
3764 &target);
064af421 3765
d1e2cf21 3766 msg = start_ofp_stats_reply(oh, sizeof *reply);
06a5e131 3767 reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
27d34fce
BP
3768 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3769 request->table_id, reply);
064af421
BP
3770 queue_tx(msg, ofconn, ofconn->reply_counter);
3771 return 0;
3772}
3773
09246b99 3774static int
d1e2cf21 3775handle_nxst_aggregate(struct ofconn *ofconn, const struct ofp_header *oh)
09246b99
BP
3776{
3777 struct nx_aggregate_stats_request *request;
3778 struct ofp_aggregate_stats_reply *reply;
3779 struct cls_rule target;
d1e2cf21 3780 struct ofpbuf b;
09246b99
BP
3781 struct ofpbuf *buf;
3782 int error;
3783
0bc9407d 3784 ofpbuf_use_const(&b, oh, ntohs(oh->length));
d1e2cf21 3785
09246b99 3786 /* Dissect the message. */
bbc32a88 3787 request = ofpbuf_pull(&b, sizeof *request);
d1e2cf21 3788 error = nx_pull_match(&b, ntohs(request->match_len), 0, &target);
09246b99
BP
3789 if (error) {
3790 return error;
3791 }
d1e2cf21
BP
3792 if (b.size) {
3793 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3794 }
09246b99
BP
3795
3796 /* Reply. */
3797 COVERAGE_INC(ofproto_flows_req);
3798 buf = start_nxstats_reply(&request->nsm, sizeof *reply);
3799 reply = ofpbuf_put_uninit(buf, sizeof *reply);
3800 query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3801 request->table_id, reply);
3802 queue_tx(buf, ofconn, ofconn->reply_counter);
3803
3804 return 0;
3805}
3806
c1c9c9c4
BP
3807struct queue_stats_cbdata {
3808 struct ofconn *ofconn;
ca0f572c 3809 struct ofport *ofport;
c1c9c9c4 3810 struct ofpbuf *msg;
c1c9c9c4
BP
3811};
3812
3813static void
db9220c3 3814put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
c1c9c9c4
BP
3815 const struct netdev_queue_stats *stats)
3816{
3817 struct ofp_queue_stats *reply;
3818
06a5e131 3819 reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
ca0f572c 3820 reply->port_no = htons(cbdata->ofport->opp.port_no);
c1c9c9c4
BP
3821 memset(reply->pad, 0, sizeof reply->pad);
3822 reply->queue_id = htonl(queue_id);
3823 reply->tx_bytes = htonll(stats->tx_bytes);
3824 reply->tx_packets = htonll(stats->tx_packets);
3825 reply->tx_errors = htonll(stats->tx_errors);
3826}
3827
3828static void
db9220c3 3829handle_queue_stats_dump_cb(uint32_t queue_id,
c1c9c9c4
BP
3830 struct netdev_queue_stats *stats,
3831 void *cbdata_)
3832{
3833 struct queue_stats_cbdata *cbdata = cbdata_;
3834
3835 put_queue_stats(cbdata, queue_id, stats);
3836}
3837
3838static void
ca0f572c 3839handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
c1c9c9c4
BP
3840 struct queue_stats_cbdata *cbdata)
3841{
ca0f572c 3842 cbdata->ofport = port;
c1c9c9c4
BP
3843 if (queue_id == OFPQ_ALL) {
3844 netdev_dump_queue_stats(port->netdev,
3845 handle_queue_stats_dump_cb, cbdata);
3846 } else {
3847 struct netdev_queue_stats stats;
3848
1ac788f6
BP
3849 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3850 put_queue_stats(cbdata, queue_id, &stats);
3851 }
c1c9c9c4
BP
3852 }
3853}
3854
3855static int
d1e2cf21 3856handle_queue_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
c1c9c9c4 3857{
3269c562 3858 struct ofproto *ofproto = ofconn->ofproto;
d1e2cf21 3859 const struct ofp_queue_stats_request *qsr;
c1c9c9c4
BP
3860 struct queue_stats_cbdata cbdata;
3861 struct ofport *port;
3862 unsigned int port_no;
3863 uint32_t queue_id;
3864
d1e2cf21
BP
3865 qsr = ofputil_stats_body(oh);
3866 if (!qsr) {
c1c9c9c4
BP
3867 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3868 }
c1c9c9c4
BP
3869
3870 COVERAGE_INC(ofproto_queue_req);
3871
3872 cbdata.ofconn = ofconn;
d1e2cf21 3873 cbdata.msg = start_ofp_stats_reply(oh, 128);
c1c9c9c4
BP
3874
3875 port_no = ntohs(qsr->port_no);
3876 queue_id = ntohl(qsr->queue_id);
3877 if (port_no == OFPP_ALL) {
4e8e4213 3878 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
ca0f572c 3879 handle_queue_stats_for_port(port, queue_id, &cbdata);
c1c9c9c4
BP
3880 }
3881 } else if (port_no < ofproto->max_ports) {
ca0f572c 3882 port = get_port(ofproto, ofp_port_to_odp_port(port_no));
c1c9c9c4 3883 if (port) {
ca0f572c 3884 handle_queue_stats_for_port(port, queue_id, &cbdata);
c1c9c9c4
BP
3885 }
3886 } else {
3887 ofpbuf_delete(cbdata.msg);
3888 return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
3889 }
3890 queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
3891
3892 return 0;
3893}
3894
064af421
BP
3895static long long int
3896msec_from_nsec(uint64_t sec, uint32_t nsec)
3897{
3898 return !sec ? 0 : sec * 1000 + nsec / 1000000;
3899}
3900
3901static void
bcf84111
BP
3902facet_update_time(struct ofproto *ofproto, struct facet *facet,
3903 const struct odp_flow_stats *stats)
064af421
BP
3904{
3905 long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
bcf84111
BP
3906 if (used > facet->used) {
3907 facet->used = used;
3908 if (used > facet->rule->used) {
3909 facet->rule->used = used;
4836f9f2 3910 }
bcf84111 3911 netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
064af421
BP
3912 }
3913}
3914
bcf84111
BP
3915/* Folds the statistics from 'stats' into the counters in 'facet'.
3916 *
3917 * Because of the meaning of a facet's counters, it only makes sense to do this
3918 * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3919 * packet that was sent by hand or if it represents statistics that have been
3920 * cleared out of the datapath. */
064af421 3921static void
bcf84111
BP
3922facet_update_stats(struct ofproto *ofproto, struct facet *facet,
3923 const struct odp_flow_stats *stats)
064af421 3924{
064af421 3925 if (stats->n_packets) {
bcf84111
BP
3926 facet_update_time(ofproto, facet, stats);
3927 facet->packet_count += stats->n_packets;
3928 facet->byte_count += stats->n_bytes;
3929 netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
064af421
BP
3930 }
3931}
3932
79eee1eb
BP
3933/* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3934 * in which no matching flow already exists in the flow table.
3935 *
3936 * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3269c562
BP
3937 * ofp_actions, to ofconn->ofproto's flow table. Returns 0 on success or an
3938 * OpenFlow error code as encoded by ofp_mkerr() on failure.
79eee1eb
BP
3939 *
3940 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3941 * if any. */
064af421 3942static int
3052b0c5 3943add_flow(struct ofconn *ofconn, struct flow_mod *fm)
064af421 3944{
3269c562 3945 struct ofproto *p = ofconn->ofproto;
064af421
BP
3946 struct ofpbuf *packet;
3947 struct rule *rule;
3948 uint16_t in_port;
3949 int error;
3950
3052b0c5
BP
3951 if (fm->flags & OFPFF_CHECK_OVERLAP
3952 && classifier_rule_overlaps(&p->cls, &fm->cr)) {
3953 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
49bdc010
JP
3954 }
3955
064af421 3956 error = 0;
3052b0c5
BP
3957 if (fm->buffer_id != UINT32_MAX) {
3958 error = pktbuf_retrieve(ofconn->pktbuf, fm->buffer_id,
064af421 3959 &packet, &in_port);
212fe71c
BP
3960 } else {
3961 packet = NULL;
165cd8a3 3962 in_port = UINT16_MAX;
064af421
BP
3963 }
3964
bcf84111
BP
3965 rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
3966 fm->idle_timeout, fm->hard_timeout, fm->cookie,
3967 fm->flags & OFPFF_SEND_FLOW_REM);
afe75089
BP
3968 rule_insert(p, rule);
3969 if (packet) {
3970 rule_execute(p, rule, in_port, packet);
3971 }
064af421
BP
3972 return error;
3973}
3974
79eee1eb 3975static struct rule *
3052b0c5 3976find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
064af421 3977{
3052b0c5 3978 return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
79eee1eb 3979}
064af421 3980
79eee1eb 3981static int
3269c562 3982send_buffered_packet(struct ofconn *ofconn,
3052b0c5 3983 struct rule *rule, uint32_t buffer_id)
79eee1eb
BP
3984{
3985 struct ofpbuf *packet;
3986 uint16_t in_port;
79eee1eb 3987 int error;
064af421 3988
3052b0c5 3989 if (buffer_id == UINT32_MAX) {
79eee1eb 3990 return 0;
064af421 3991 }
79eee1eb 3992
3052b0c5 3993 error = pktbuf_retrieve(ofconn->pktbuf, buffer_id, &packet, &in_port);
79eee1eb
BP
3994 if (error) {
3995 return error;
3996 }
3997
bcf84111 3998 rule_execute(ofconn->ofproto, rule, in_port, packet);
79eee1eb 3999
064af421
BP
4000 return 0;
4001}
79eee1eb
BP
4002\f
4003/* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
064af421
BP
4004
4005struct modify_flows_cbdata {
4006 struct ofproto *ofproto;
3052b0c5 4007 const struct flow_mod *fm;
79eee1eb 4008 struct rule *match;
064af421
BP
4009};
4010
3052b0c5
BP
4011static int modify_flow(struct ofproto *, const struct flow_mod *,
4012 struct rule *);
79eee1eb
BP
4013
4014/* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code as
4015 * encoded by ofp_mkerr() on failure.
4016 *
4017 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4018 * if any. */
4019static int
3052b0c5 4020modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
79eee1eb 4021{
5ecc9d81
BP
4022 struct ofproto *p = ofconn->ofproto;
4023 struct rule *match = NULL;
4024 struct cls_cursor cursor;
4025 struct rule *rule;
79eee1eb 4026
5ecc9d81
BP
4027 cls_cursor_init(&cursor, &p->cls, &fm->cr);
4028 CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4029 if (!rule_is_hidden(rule)) {
4030 match = rule;
4031 modify_flow(p, fm, rule);
4032 }
4033 }
79eee1eb 4034
5ecc9d81 4035 if (match) {
d6302b0f
BP
4036 /* This credits the packet to whichever flow happened to match last.
4037 * That's weird. Maybe we should do a lookup for the flow that
4038 * actually matches the packet? Who knows. */
5ecc9d81 4039 send_buffered_packet(ofconn, match, fm->buffer_id);
79eee1eb
BP
4040 return 0;
4041 } else {
3052b0c5 4042 return add_flow(ofconn, fm);
79eee1eb
BP
4043 }
4044}
4045
4046/* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
4047 * code as encoded by ofp_mkerr() on failure.
4048 *
4049 * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4050 * if any. */
4051static int
3052b0c5 4052modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
79eee1eb 4053{
3052b0c5
BP
4054 struct ofproto *p = ofconn->ofproto;
4055 struct rule *rule = find_flow_strict(p, fm);
79eee1eb 4056 if (rule && !rule_is_hidden(rule)) {
3052b0c5
BP
4057 modify_flow(p, fm, rule);
4058 return send_buffered_packet(ofconn, rule, fm->buffer_id);
79eee1eb 4059 } else {
3052b0c5 4060 return add_flow(ofconn, fm);
79eee1eb
BP
4061 }
4062}
4063
79eee1eb
BP
4064/* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
4065 * been identified as a flow in 'p''s flow table to be modified, by changing
4066 * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
4067 * ofp_action[] structures). */
064af421 4068static int
3052b0c5 4069modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
064af421 4070{
3052b0c5 4071 size_t actions_len = fm->n_actions * sizeof *rule->actions;
79eee1eb 4072
3052b0c5 4073 rule->flow_cookie = fm->cookie;
79eee1eb
BP
4074
4075 /* If the actions are the same, do nothing. */
3052b0c5
BP
4076 if (fm->n_actions == rule->n_actions
4077 && (!fm->n_actions
4078 || !memcmp(fm->actions, rule->actions, actions_len))) {
79eee1eb
BP
4079 return 0;
4080 }
4081
4082 /* Replace actions. */
4083 free(rule->actions);
3052b0c5
BP
4084 rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
4085 rule->n_actions = fm->n_actions;
79eee1eb 4086
bcf84111 4087 p->need_revalidate = true;
79eee1eb
BP
4088
4089 return 0;
4090}
4091\f
4092/* OFPFC_DELETE implementation. */
4093
8054fc48 4094static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
79eee1eb
BP
4095
4096/* Implements OFPFC_DELETE. */
4097static void
3052b0c5 4098delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
79eee1eb 4099{
5ecc9d81
BP
4100 struct rule *rule, *next_rule;
4101 struct cls_cursor cursor;
064af421 4102
5ecc9d81
BP
4103 cls_cursor_init(&cursor, &p->cls, &fm->cr);
4104 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4105 delete_flow(p, rule, htons(fm->out_port));
4106 }
064af421
BP
4107}
4108
79eee1eb
BP
4109/* Implements OFPFC_DELETE_STRICT. */
4110static void
3052b0c5 4111delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
79eee1eb 4112{
3052b0c5 4113 struct rule *rule = find_flow_strict(p, fm);
79eee1eb 4114 if (rule) {
3052b0c5 4115 delete_flow(p, rule, htons(fm->out_port));
79eee1eb
BP
4116 }
4117}
4118
79eee1eb
BP
4119/* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
4120 * been identified as a flow to delete from 'p''s flow table, by deleting the
4121 * flow and sending out a OFPT_FLOW_REMOVED message to any interested
4122 * controller.
4123 *
4124 * Will not delete 'rule' if it is hidden. Will delete 'rule' only if
4125 * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
4126 * specified 'out_port'. */
4127static void
8054fc48 4128delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
79eee1eb
BP
4129{
4130 if (rule_is_hidden(rule)) {
4131 return;
4132 }
4133
4134 if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
4135 return;
4136 }
4137
bcf84111 4138 rule_send_removed(p, rule, OFPRR_DELETE);
79eee1eb
BP
4139 rule_remove(p, rule);
4140}
4141\f
064af421 4142static int
2e4f5fcf 4143handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
064af421 4144{
3052b0c5 4145 struct ofproto *p = ofconn->ofproto;
2e4f5fcf 4146 struct flow_mod fm;
064af421
BP
4147 int error;
4148
3052b0c5 4149 error = reject_slave_controller(ofconn, "flow_mod");
9deba63b
BP
4150 if (error) {
4151 return error;
4152 }
3052b0c5 4153
2e4f5fcf 4154 error = ofputil_decode_flow_mod(&fm, oh, ofconn->flow_format);
064af421
BP
4155 if (error) {
4156 return error;
4157 }
4158
2e4f5fcf
BP
4159 /* We do not support the emergency flow cache. It will hopefully get
4160 * dropped from OpenFlow in the near future. */
4161 if (fm.flags & OFPFF_EMERG) {
49bdc010
JP
4162 /* There isn't a good fit for an error code, so just state that the
4163 * flow table is full. */
4164 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
4165 }
4166
2e4f5fcf
BP
4167 error = validate_actions(fm.actions, fm.n_actions,
4168 &fm.cr.flow, p->max_ports);
4169 if (error) {
4170 return error;
4171 }
4172
4173 switch (fm.command) {
3052b0c5 4174 case OFPFC_ADD:
2e4f5fcf 4175 return add_flow(ofconn, &fm);
3052b0c5
BP
4176
4177 case OFPFC_MODIFY:
2e4f5fcf 4178 return modify_flows_loose(ofconn, &fm);
3052b0c5
BP
4179
4180 case OFPFC_MODIFY_STRICT:
2e4f5fcf 4181 return modify_flow_strict(ofconn, &fm);
3052b0c5
BP
4182
4183 case OFPFC_DELETE:
2e4f5fcf 4184 delete_flows_loose(p, &fm);
3052b0c5
BP
4185 return 0;
4186
4187 case OFPFC_DELETE_STRICT:
2e4f5fcf 4188 delete_flow_strict(p, &fm);
3052b0c5
BP
4189 return 0;
4190
4191 default:
4192 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
4193 }
4194}
4195
659586ef 4196static int
d1e2cf21 4197handle_tun_id_from_cookie(struct ofconn *ofconn, const struct ofp_header *oh)
659586ef 4198{
d1e2cf21
BP
4199 const struct nxt_tun_id_cookie *msg
4200 = (const struct nxt_tun_id_cookie *) oh;
659586ef 4201
b70eac89 4202 ofconn->flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
659586ef
JG
4203 return 0;
4204}
4205
9deba63b 4206static int
d1e2cf21 4207handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
9deba63b 4208{
d1e2cf21 4209 struct nx_role_request *nrr = (struct nx_role_request *) oh;
9deba63b
BP
4210 struct nx_role_request *reply;
4211 struct ofpbuf *buf;
4212 uint32_t role;
4213
5899143f 4214 if (ofconn->type != OFCONN_PRIMARY) {
9deba63b
BP
4215 VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
4216 "connection");
4217 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4218 }
4219
4220 role = ntohl(nrr->role);
4221 if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
4222 && role != NX_ROLE_SLAVE) {
4223 VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
4224
4225 /* There's no good error code for this. */
4226 return ofp_mkerr(OFPET_BAD_REQUEST, -1);
4227 }
4228
4229 if (role == NX_ROLE_MASTER) {
4230 struct ofconn *other;
4231
3269c562 4232 HMAP_FOR_EACH (other, hmap_node, &ofconn->ofproto->controllers) {
9deba63b
BP
4233 if (other->role == NX_ROLE_MASTER) {
4234 other->role = NX_ROLE_SLAVE;
4235 }
4236 }
4237 }
4238 ofconn->role = role;
4239
d1e2cf21 4240 reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
9deba63b
BP
4241 reply->role = htonl(role);
4242 queue_tx(buf, ofconn, ofconn->reply_counter);
4243
4244 return 0;
4245}
4246
09246b99 4247static int
d1e2cf21 4248handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
09246b99 4249{
d1e2cf21
BP
4250 const struct nxt_set_flow_format *msg
4251 = (const struct nxt_set_flow_format *) oh;
09246b99 4252 uint32_t format;
09246b99
BP
4253
4254 format = ntohl(msg->format);
4255 if (format == NXFF_OPENFLOW10
4256 || format == NXFF_TUN_ID_FROM_COOKIE
4257 || format == NXFF_NXM) {
4258 ofconn->flow_format = format;
4259 return 0;
4260 } else {
4261 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4262 }
4263}
4264
064af421 4265static int
d1e2cf21 4266handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
246e61ea
JP
4267{
4268 struct ofp_header *ob;
4269 struct ofpbuf *buf;
4270
4271 /* Currently, everything executes synchronously, so we can just
4272 * immediately send the barrier reply. */
4273 ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
4274 queue_tx(buf, ofconn, ofconn->reply_counter);
4275 return 0;
4276}
4277
d1e2cf21
BP
4278static int
4279handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
064af421 4280{
d1e2cf21
BP
4281 const struct ofp_header *oh = msg->data;
4282 const struct ofputil_msg_type *type;
064af421
BP
4283 int error;
4284
d1e2cf21
BP
4285 error = ofputil_decode_msg_type(oh, &type);
4286 if (error) {
4287 return error;
4288 }
064af421 4289
d1e2cf21
BP
4290 switch (ofputil_msg_type_code(type)) {
4291 /* OpenFlow requests. */
4292 case OFPUTIL_OFPT_ECHO_REQUEST:
4293 return handle_echo_request(ofconn, oh);
064af421 4294
d1e2cf21
BP
4295 case OFPUTIL_OFPT_FEATURES_REQUEST:
4296 return handle_features_request(ofconn, oh);
064af421 4297
d1e2cf21
BP
4298 case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
4299 return handle_get_config_request(ofconn, oh);
064af421 4300
d1e2cf21
BP
4301 case OFPUTIL_OFPT_SET_CONFIG:
4302 return handle_set_config(ofconn, msg->data);
064af421 4303
d1e2cf21
BP
4304 case OFPUTIL_OFPT_PACKET_OUT:
4305 return handle_packet_out(ofconn, oh);
064af421 4306
d1e2cf21
BP
4307 case OFPUTIL_OFPT_PORT_MOD:
4308 return handle_port_mod(ofconn, oh);
064af421 4309
d1e2cf21 4310 case OFPUTIL_OFPT_FLOW_MOD:
2e4f5fcf 4311 return handle_flow_mod(ofconn, oh);
064af421 4312
d1e2cf21
BP
4313 case OFPUTIL_OFPT_BARRIER_REQUEST:
4314 return handle_barrier_request(ofconn, oh);
064af421 4315
d1e2cf21
BP
4316 /* OpenFlow replies. */
4317 case OFPUTIL_OFPT_ECHO_REPLY:
4318 return 0;
246e61ea 4319
d1e2cf21
BP
4320 /* Nicira extension requests. */
4321 case OFPUTIL_NXT_STATUS_REQUEST:
4322 return switch_status_handle_request(
4323 ofconn->ofproto->switch_status, ofconn->rconn, oh);
4324
4325 case OFPUTIL_NXT_TUN_ID_FROM_COOKIE:
4326 return handle_tun_id_from_cookie(ofconn, oh);
4327
4328 case OFPUTIL_NXT_ROLE_REQUEST:
4329 return handle_role_request(ofconn, oh);
4330
4331 case OFPUTIL_NXT_SET_FLOW_FORMAT:
4332 return handle_nxt_set_flow_format(ofconn, oh);
4333
4334 case OFPUTIL_NXT_FLOW_MOD:
2e4f5fcf 4335 return handle_flow_mod(ofconn, oh);
d1e2cf21
BP
4336
4337 /* OpenFlow statistics requests. */
4338 case OFPUTIL_OFPST_DESC_REQUEST:
4339 return handle_desc_stats_request(ofconn, oh);
4340
4341 case OFPUTIL_OFPST_FLOW_REQUEST:
4342 return handle_flow_stats_request(ofconn, oh);
4343
4344 case OFPUTIL_OFPST_AGGREGATE_REQUEST:
4345 return handle_aggregate_stats_request(ofconn, oh);
4346
4347 case OFPUTIL_OFPST_TABLE_REQUEST:
4348 return handle_table_stats_request(ofconn, oh);
4349
4350 case OFPUTIL_OFPST_PORT_REQUEST:
4351 return handle_port_stats_request(ofconn, oh);
4352
4353 case OFPUTIL_OFPST_QUEUE_REQUEST:
4354 return handle_queue_stats_request(ofconn, oh);
4355
4356 /* Nicira extension statistics requests. */
4357 case OFPUTIL_NXST_FLOW_REQUEST:
4358 return handle_nxst_flow(ofconn, oh);
4359
4360 case OFPUTIL_NXST_AGGREGATE_REQUEST:
4361 return handle_nxst_aggregate(ofconn, oh);
4362
4363 case OFPUTIL_INVALID:
4364 case OFPUTIL_OFPT_HELLO:
4365 case OFPUTIL_OFPT_ERROR:
4366 case OFPUTIL_OFPT_FEATURES_REPLY:
4367 case OFPUTIL_OFPT_GET_CONFIG_REPLY:
4368 case OFPUTIL_OFPT_PACKET_IN:
4369 case OFPUTIL_OFPT_FLOW_REMOVED:
4370 case OFPUTIL_OFPT_PORT_STATUS:
4371 case OFPUTIL_OFPT_BARRIER_REPLY:
4372 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
4373 case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
4374 case OFPUTIL_OFPST_DESC_REPLY:
4375 case OFPUTIL_OFPST_FLOW_REPLY:
4376 case OFPUTIL_OFPST_QUEUE_REPLY:
4377 case OFPUTIL_OFPST_PORT_REPLY:
4378 case OFPUTIL_OFPST_TABLE_REPLY:
4379 case OFPUTIL_OFPST_AGGREGATE_REPLY:
4380 case OFPUTIL_NXT_STATUS_REPLY:
4381 case OFPUTIL_NXT_ROLE_REPLY:
4382 case OFPUTIL_NXT_FLOW_REMOVED:
4383 case OFPUTIL_NXST_FLOW_REPLY:
4384 case OFPUTIL_NXST_AGGREGATE_REPLY:
064af421
BP
4385 default:
4386 if (VLOG_IS_WARN_ENABLED()) {
4387 char *s = ofp_to_string(oh, ntohs(oh->length), 2);
4388 VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
4389 free(s);
4390 }
d1e2cf21
BP
4391 if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
4392 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
4393 } else {
4394 return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
4395 }
064af421 4396 }
d1e2cf21 4397}
064af421 4398
d1e2cf21
BP
4399static void
4400handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4401{
4402 int error = handle_openflow__(ofconn, ofp_msg);
064af421
BP
4403 if (error) {
4404 send_error_oh(ofconn, ofp_msg->data, error);
4405 }
d1e2cf21 4406 COVERAGE_INC(ofproto_recv_openflow);
064af421
BP
4407}
4408\f
4409static void
856081f6 4410handle_miss_upcall(struct ofproto *p, struct dpif_upcall *upcall)
064af421 4411{
bcf84111 4412 struct facet *facet;
ae412e7d 4413 struct flow flow;
064af421 4414
856081f6
BP
4415 /* Obtain in_port and tun_id, at least. */
4416 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
064af421 4417
856081f6
BP
4418 /* Set header pointers in 'flow'. */
4419 flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
4617e2c1 4420
0ad9b732
JP
4421 /* Check with in-band control to see if this packet should be sent
4422 * to the local port regardless of the flow table. */
856081f6 4423 if (in_band_msg_in_hook(p->in_band, &flow, upcall->packet)) {
cdee00fd 4424 struct ofpbuf odp_actions;
0ad9b732 4425
cdee00fd
BP
4426 ofpbuf_init(&odp_actions, 32);
4427 nl_msg_put_u32(&odp_actions, ODPAT_OUTPUT, ODPP_LOCAL);
856081f6
BP
4428 dpif_execute(p->dpif, odp_actions.data, odp_actions.size,
4429 upcall->packet);
cdee00fd 4430 ofpbuf_uninit(&odp_actions);
0ad9b732
JP
4431 }
4432
bcf84111
BP
4433 facet = facet_lookup_valid(p, &flow);
4434 if (!facet) {
4435 struct rule *rule = rule_lookup(p, &flow);
4436 if (!rule) {
4437 /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
856081f6 4438 struct ofport *port = get_port(p, flow.in_port);
bcf84111
BP
4439 if (port) {
4440 if (port->opp.config & OFPPC_NO_PACKET_IN) {
4441 COVERAGE_INC(ofproto_no_packet_in);
4442 /* XXX install 'drop' flow entry */
856081f6 4443 ofpbuf_delete(upcall->packet);
bcf84111
BP
4444 return;
4445 }
4446 } else {
4447 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
856081f6 4448 flow.in_port);
064af421 4449 }
064af421 4450
bcf84111 4451 COVERAGE_INC(ofproto_packet_in);
856081f6 4452 send_packet_in(p, upcall, &flow, false);
bcf84111 4453 return;
064af421 4454 }
bcf84111 4455
856081f6 4456 facet = facet_create(p, rule, &flow, upcall->packet);
bcf84111
BP
4457 } else if (!facet->may_install) {
4458 /* The facet is not installable, that is, we need to process every
4459 * packet, so process the current packet's actions into 'facet'. */
856081f6 4460 facet_make_actions(p, facet, upcall->packet);
064af421
BP
4461 }
4462
bcf84111 4463 if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
7778bd15
BP
4464 /*
4465 * Extra-special case for fail-open mode.
4466 *
4467 * We are in fail-open mode and the packet matched the fail-open rule,
4468 * but we are connected to a controller too. We should send the packet
4469 * up to the controller in the hope that it will try to set up a flow
4470 * and thereby allow us to exit fail-open.
4471 *
4472 * See the top-level comment in fail-open.c for more information.
4473 */
856081f6 4474 send_packet_in(p, upcall, &flow, true);
7778bd15 4475 }
750638bb 4476
856081f6 4477 facet_execute(p, facet, upcall->packet);
bcf84111 4478 facet_install(p, facet, false);
064af421 4479}
72b06300
BP
4480
4481static void
856081f6 4482handle_upcall(struct ofproto *p, struct dpif_upcall *upcall)
72b06300 4483{
856081f6 4484 struct flow flow;
72b06300 4485
856081f6 4486 switch (upcall->type) {
72b06300
BP
4487 case _ODPL_ACTION_NR:
4488 COVERAGE_INC(ofproto_ctlr_action);
856081f6
BP
4489 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4490 send_packet_in(p, upcall, &flow, false);
72b06300
BP
4491 break;
4492
4493 case _ODPL_SFLOW_NR:
4494 if (p->sflow) {
856081f6
BP
4495 odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4496 ofproto_sflow_received(p->sflow, upcall, &flow);
72b06300 4497 }
856081f6 4498 ofpbuf_delete(upcall->packet);
72b06300
BP
4499 break;
4500
4501 case _ODPL_MISS_NR:
856081f6 4502 handle_miss_upcall(p, upcall);
72b06300
BP
4503 break;
4504
4505 default:
856081f6 4506 VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
72b06300
BP
4507 break;
4508 }
4509}
064af421 4510\f
4a4cdb3b
BP
4511/* Flow expiration. */
4512
0de7a4b4 4513static int ofproto_dp_max_idle(const struct ofproto *);
4a4cdb3b 4514static void ofproto_update_used(struct ofproto *);
5ecc9d81 4515static void rule_expire(struct ofproto *, struct rule *);
bcf84111 4516static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
4a4cdb3b
BP
4517
4518/* This function is called periodically by ofproto_run(). Its job is to
4519 * collect updates for the flows that have been installed into the datapath,
4520 * most importantly when they last were used, and then use that information to
0de7a4b4
BP
4521 * expire flows that have not been used recently.
4522 *
4523 * Returns the number of milliseconds after which it should be called again. */
4524static int
4a4cdb3b
BP
4525ofproto_expire(struct ofproto *ofproto)
4526{
5ecc9d81
BP
4527 struct rule *rule, *next_rule;
4528 struct cls_cursor cursor;
4529 int dp_max_idle;
4a4cdb3b
BP
4530
4531 /* Update 'used' for each flow in the datapath. */
4532 ofproto_update_used(ofproto);
4533
bcf84111 4534 /* Expire facets that have been idle too long. */
5ecc9d81
BP
4535 dp_max_idle = ofproto_dp_max_idle(ofproto);
4536 ofproto_expire_facets(ofproto, dp_max_idle);
bcf84111
BP
4537
4538 /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
5ecc9d81
BP
4539 cls_cursor_init(&cursor, &ofproto->cls, NULL);
4540 CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4541 rule_expire(ofproto, rule);
4542 }
4a4cdb3b
BP
4543
4544 /* Let the hook know that we're at a stable point: all outstanding data
4545 * in existing flows has been accounted to the account_cb. Thus, the
4546 * hook can now reasonably do operations that depend on having accurate
4547 * flow volume accounting (currently, that's just bond rebalancing). */
4548 if (ofproto->ofhooks->account_checkpoint_cb) {
4549 ofproto->ofhooks->account_checkpoint_cb(ofproto->aux);
4550 }
0de7a4b4 4551
5ecc9d81 4552 return MIN(dp_max_idle, 1000);
4a4cdb3b
BP
4553}
4554
bcf84111 4555/* Update 'used' member of installed facets. */
4a4cdb3b
BP
4556static void
4557ofproto_update_used(struct ofproto *p)
4558{
704a1e09 4559 struct dpif_flow_dump dump;
4a4cdb3b 4560
704a1e09 4561 dpif_flow_dump_start(&dump, p->dpif);
36956a7d
BP
4562 for (;;) {
4563 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
bcf84111 4564 struct facet *facet;
36956a7d 4565 struct odp_flow f;
ae412e7d 4566 struct flow flow;
14608a15 4567
36956a7d
BP
4568 memset(&f, 0, sizeof f);
4569 f.key = (struct nlattr *) keybuf;
4570 f.key_len = sizeof keybuf;
4571 if (!dpif_flow_dump_next(&dump, &f)) {
4572 break;
4573 }
4574
4575 if (f.key_len > sizeof keybuf) {
4576 VLOG_WARN_RL(&rl, "ODP flow key overflowed buffer");
4577 continue;
4578 }
4579 if (odp_flow_key_to_flow(f.key, f.key_len, &flow)) {
4580 struct ds s;
4581
4582 ds_init(&s);
4583 odp_flow_key_format(f.key, f.key_len, &s);
4584 VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
4585 ds_cstr(&s));
4586 ds_destroy(&s);
4587
4588 continue;
4589 }
bcf84111 4590 facet = facet_find(p, &flow);
4a4cdb3b 4591
bcf84111 4592 if (facet && facet->installed) {
704a1e09
BP
4593 facet_update_time(p, facet, &f.stats);
4594 facet_account(p, facet, f.stats.n_bytes);
4a4cdb3b
BP
4595 } else {
4596 /* There's a flow in the datapath that we know nothing about.
4597 * Delete it. */
4598 COVERAGE_INC(ofproto_unexpected_rule);
704a1e09 4599 dpif_flow_del(p->dpif, &f);
4a4cdb3b 4600 }
4a4cdb3b 4601 }
704a1e09 4602 dpif_flow_dump_done(&dump);
4a4cdb3b
BP
4603}
4604
0de7a4b4 4605/* Calculates and returns the number of milliseconds of idle time after which
bcf84111 4606 * facets should expire from the datapath and we should fold their statistics
0de7a4b4
BP
4607 * into their parent rules in userspace. */
4608static int
4609ofproto_dp_max_idle(const struct ofproto *ofproto)
4610{
4611 /*
4612 * Idle time histogram.
4613 *
bcf84111 4614 * Most of the time a switch has a relatively small number of facets. When
0de7a4b4
BP
4615 * this is the case we might as well keep statistics for all of them in
4616 * userspace and to cache them in the kernel datapath for performance as
4617 * well.
4618 *
bcf84111 4619 * As the number of facets increases, the memory required to maintain
0de7a4b4 4620 * statistics about them in userspace and in the kernel becomes
bcf84111 4621 * significant. However, with a large number of facets it is likely that
0de7a4b4
BP
4622 * only a few of them are "heavy hitters" that consume a large amount of
4623 * bandwidth. At this point, only heavy hitters are worth caching in the
bcf84111 4624 * kernel and maintaining in userspaces; other facets we can discard.
0de7a4b4
BP
4625 *
4626 * The technique used to compute the idle time is to build a histogram with
bcf84111
BP
4627 * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each. Each facet
4628 * that is installed in the kernel gets dropped in the appropriate bucket.
0de7a4b4 4629 * After the histogram has been built, we compute the cutoff so that only
bcf84111
BP
4630 * the most-recently-used 1% of facets (but at least 1000 flows) are kept
4631 * cached. At least the most-recently-used bucket of facets is kept, so
4632 * actually an arbitrary number of facets can be kept in any given
0de7a4b4
BP
4633 * expiration run (though the next run will delete most of those unless
4634 * they receive additional data).
4635 *
bcf84111
BP
4636 * This requires a second pass through the facets, in addition to the pass
4637 * made by ofproto_update_used(), because the former function never looks
4638 * at uninstallable facets.
0de7a4b4
BP
4639 */
4640 enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4641 enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4642 int buckets[N_BUCKETS] = { 0 };
bcf84111 4643 struct facet *facet;
0de7a4b4 4644 int total, bucket;
0de7a4b4
BP
4645 long long int now;
4646 int i;
4647
bcf84111 4648 total = hmap_count(&ofproto->facets);
0de7a4b4
BP
4649 if (total <= 1000) {
4650 return N_BUCKETS * BUCKET_WIDTH;
4651 }
4652
4653 /* Build histogram. */
4654 now = time_msec();
bcf84111
BP
4655 HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
4656 long long int idle = now - facet->used;
0de7a4b4
BP
4657 int bucket = (idle <= 0 ? 0
4658 : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4659 : (unsigned int) idle / BUCKET_WIDTH);
4660 buckets[bucket]++;
4661 }
4662
4663 /* Find the first bucket whose flows should be expired. */
4664 for (bucket = 0; bucket < N_BUCKETS; bucket++) {
4665 if (buckets[bucket]) {
4666 int subtotal = 0;
4667 do {
4668 subtotal += buckets[bucket++];
4669 } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
4670 break;
4671 }
4672 }
4673
4674 if (VLOG_IS_DBG_ENABLED()) {
4675 struct ds s;
4676
4677 ds_init(&s);
4678 ds_put_cstr(&s, "keep");
4679 for (i = 0; i < N_BUCKETS; i++) {
4680 if (i == bucket) {
4681 ds_put_cstr(&s, ", drop");
4682 }
4683 if (buckets[i]) {
4684 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4685 }
4686 }
4687 VLOG_INFO("%s: %s (msec:count)",
4688 dpif_name(ofproto->dpif), ds_cstr(&s));
4689 ds_destroy(&s);
4690 }
4691
4692 return bucket * BUCKET_WIDTH;
4693}
4694
4a4cdb3b 4695static void
bcf84111 4696facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
4a4cdb3b 4697{
bcf84111
BP
4698 if (ofproto->netflow && !facet_is_controller_flow(facet) &&
4699 netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
4a4cdb3b
BP
4700 struct ofexpired expired;
4701 struct odp_flow odp_flow;
4702
4703 /* Get updated flow stats.
4704 *
4705 * XXX We could avoid this call entirely if (1) ofproto_update_used()
4706 * updated TCP flags and (2) the dpif_flow_list_all() in
4707 * ofproto_update_used() zeroed TCP flags. */
4708 memset(&odp_flow, 0, sizeof odp_flow);
bcf84111 4709 if (facet->installed) {
36956a7d
BP
4710 uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
4711 struct ofpbuf key;
4712
4713 ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
4714 odp_flow_key_from_flow(&key, &facet->flow);
4715
4716 odp_flow.key = key.data;
4717 odp_flow.key_len = key.size;
4a4cdb3b
BP
4718 odp_flow.flags = ODPFF_ZERO_TCP_FLAGS;
4719 dpif_flow_get(ofproto->dpif, &odp_flow);
4720
4721 if (odp_flow.stats.n_packets) {
bcf84111
BP
4722 facet_update_time(ofproto, facet, &odp_flow.stats);
4723 netflow_flow_update_flags(&facet->nf_flow,
4a4cdb3b
BP
4724 odp_flow.stats.tcp_flags);
4725 }
4726 }
4727
bcf84111
BP
4728 expired.flow = facet->flow;
4729 expired.packet_count = facet->packet_count +
4a4cdb3b 4730 odp_flow.stats.n_packets;
bcf84111
BP
4731 expired.byte_count = facet->byte_count + odp_flow.stats.n_bytes;
4732 expired.used = facet->used;
4733
4734 netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4735 }
4736}
4a4cdb3b 4737
bcf84111
BP
4738static void
4739ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
4740{
4741 long long int cutoff = time_msec() - dp_max_idle;
4742 struct facet *facet, *next_facet;
4743
4744 HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
4745 facet_active_timeout(ofproto, facet);
4746 if (facet->used < cutoff) {
4747 facet_remove(ofproto, facet);
4748 }
4a4cdb3b
BP
4749 }
4750}
4751
5ecc9d81
BP
4752/* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4753 * then delete it entirely. */
4a4cdb3b 4754static void
5ecc9d81 4755rule_expire(struct ofproto *ofproto, struct rule *rule)
4a4cdb3b 4756{
bcf84111
BP
4757 struct facet *facet, *next_facet;
4758 long long int now;
4759 uint8_t reason;
4a4cdb3b 4760
bcf84111 4761 /* Has 'rule' expired? */
4a4cdb3b 4762 now = time_msec();
bcf84111
BP
4763 if (rule->hard_timeout
4764 && now > rule->created + rule->hard_timeout * 1000) {
4765 reason = OFPRR_HARD_TIMEOUT;
4766 } else if (rule->idle_timeout && list_is_empty(&rule->facets)
4767 && now >rule->used + rule->idle_timeout * 1000) {
4768 reason = OFPRR_IDLE_TIMEOUT;
4a4cdb3b 4769 } else {
bcf84111 4770 return;
4a4cdb3b 4771 }
064af421 4772
bcf84111 4773 COVERAGE_INC(ofproto_expired);
064af421 4774
bcf84111
BP
4775 /* Update stats. (This is a no-op if the rule expired due to an idle
4776 * timeout, because that only happens when the rule has no facets left.) */
4777 LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
5ecc9d81 4778 facet_remove(ofproto, facet);
064af421
BP
4779 }
4780
bcf84111
BP
4781 /* Get rid of the rule. */
4782 if (!rule_is_hidden(rule)) {
5ecc9d81 4783 rule_send_removed(ofproto, rule, reason);
bcf84111 4784 }
5ecc9d81 4785 rule_remove(ofproto, rule);
064af421 4786}
bcf84111 4787\f
064af421 4788static struct ofpbuf *
09246b99
BP
4789compose_ofp_flow_removed(struct ofconn *ofconn, const struct rule *rule,
4790 uint8_t reason)
064af421 4791{
ca069229 4792 struct ofp_flow_removed *ofr;
064af421
BP
4793 struct ofpbuf *buf;
4794
0224fbde 4795 ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0), &buf);
ff9d3826
BP
4796 ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofr->match,
4797 rule->flow_cookie, &ofr->cookie);
ca069229
JP
4798 ofr->priority = htons(rule->cr.priority);
4799 ofr->reason = reason;
c6ebb8fb 4800 calc_flow_duration(rule->created, &ofr->duration_sec, &ofr->duration_nsec);
ca069229
JP
4801 ofr->idle_timeout = htons(rule->idle_timeout);
4802 ofr->packet_count = htonll(rule->packet_count);
4803 ofr->byte_count = htonll(rule->byte_count);
064af421
BP
4804
4805 return buf;
4806}
4807
09246b99
BP
4808static struct ofpbuf *
4809compose_nx_flow_removed(const struct rule *rule, uint8_t reason)
4810{
4811 struct nx_flow_removed *nfr;
4812 struct ofpbuf *buf;
4813 int match_len;
4814
0224fbde 4815 make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &buf);
09246b99 4816 match_len = nx_put_match(buf, &rule->cr);
0224fbde 4817
4d0ed519 4818 nfr = buf->data;
09246b99
BP
4819 nfr->cookie = rule->flow_cookie;
4820 nfr->priority = htons(rule->cr.priority);
4821 nfr->reason = reason;
4822 calc_flow_duration(rule->created, &nfr->duration_sec, &nfr->duration_nsec);
4823 nfr->idle_timeout = htons(rule->idle_timeout);
4824 nfr->match_len = htons(match_len);
4825 nfr->packet_count = htonll(rule->packet_count);
4826 nfr->byte_count = htonll(rule->byte_count);
4827
4828 return buf;
4829}
4830
ca069229 4831static void
bcf84111 4832rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
064af421
BP
4833{
4834 struct ofconn *ofconn;
064af421 4835
3b587616
BP
4836 if (!rule->send_flow_removed) {
4837 return;
4838 }
4839
4e8e4213 4840 LIST_FOR_EACH (ofconn, node, &p->all_conns) {
7a0efeb5
BP
4841 struct ofpbuf *msg;
4842
4843 if (!rconn_is_connected(ofconn->rconn)
4844 || !ofconn_receives_async_msgs(ofconn)) {
4845 continue;
064af421 4846 }
7a0efeb5 4847
09246b99
BP
4848 msg = (ofconn->flow_format == NXFF_NXM
4849 ? compose_nx_flow_removed(rule, reason)
4850 : compose_ofp_flow_removed(ofconn, rule, reason));
6d6c7259
BP
4851
4852 /* Account flow expirations under ofconn->reply_counter, the counter
4853 * for replies to OpenFlow requests. That works because preventing
4854 * OpenFlow requests from being processed also prevents new flows from
4855 * being added (and expiring). (It also prevents processing OpenFlow
4856 * requests that would not add new flows, so it is imperfect.) */
7a0efeb5 4857 queue_tx(msg, ofconn, ofconn->reply_counter);
064af421
BP
4858 }
4859}
4860
856081f6 4861/* pinsched callback for sending 'ofp_packet_in' on 'ofconn'. */
064af421 4862static void
856081f6 4863do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn_)
064af421 4864{
76ce9432 4865 struct ofconn *ofconn = ofconn_;
43253595 4866
856081f6 4867 rconn_send_with_limit(ofconn->rconn, ofp_packet_in,
43253595
BP
4868 ofconn->packet_in_counter, 100);
4869}
4870
856081f6
BP
4871/* Takes 'upcall', whose packet has the flow specified by 'flow', composes an
4872 * OpenFlow packet-in message from it, and passes it to 'ofconn''s packet
4873 * scheduler for sending.
43253595 4874 *
856081f6
BP
4875 * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
4876 * Otherwise, ownership is transferred to this function. */
43253595 4877static void
856081f6
BP
4878schedule_packet_in(struct ofconn *ofconn, struct dpif_upcall *upcall,
4879 const struct flow *flow, bool clone)
43253595 4880{
856081f6 4881 enum { OPI_SIZE = offsetof(struct ofp_packet_in, data) };
76ce9432 4882 struct ofproto *ofproto = ofconn->ofproto;
856081f6
BP
4883 struct ofp_packet_in *opi;
4884 int total_len, send_len;
4885 struct ofpbuf *packet;
76ce9432 4886 uint32_t buffer_id;
064af421 4887
856081f6
BP
4888 /* Get OpenFlow buffer_id. */
4889 if (upcall->type == _ODPL_ACTION_NR) {
76ce9432 4890 buffer_id = UINT32_MAX;
43253595
BP
4891 } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
4892 buffer_id = pktbuf_get_null();
89b9612d
BP
4893 } else if (!ofconn->pktbuf) {
4894 buffer_id = UINT32_MAX;
76ce9432 4895 } else {
856081f6 4896 buffer_id = pktbuf_save(ofconn->pktbuf, upcall->packet, flow->in_port);
76ce9432 4897 }
372179d4 4898
43253595 4899 /* Figure out how much of the packet to send. */
856081f6 4900 total_len = send_len = upcall->packet->size;
43253595
BP
4901 if (buffer_id != UINT32_MAX) {
4902 send_len = MIN(send_len, ofconn->miss_send_len);
4903 }
856081f6
BP
4904 if (upcall->type == _ODPL_ACTION_NR) {
4905 send_len = MIN(send_len, upcall->userdata);
4906 }
064af421 4907
856081f6 4908 /* Copy or steal buffer for OFPT_PACKET_IN. */
43253595 4909 if (clone) {
856081f6
BP
4910 packet = ofpbuf_clone_data_with_headroom(upcall->packet->data,
4911 send_len, OPI_SIZE);
43253595 4912 } else {
856081f6
BP
4913 packet = upcall->packet;
4914 packet->size = send_len;
43253595
BP
4915 }
4916
856081f6
BP
4917 /* Add OFPT_PACKET_IN. */
4918 opi = ofpbuf_push_zeros(packet, OPI_SIZE);
4919 opi->header.version = OFP_VERSION;
4920 opi->header.type = OFPT_PACKET_IN;
4921 opi->total_len = htons(total_len);
4922 opi->in_port = htons(odp_port_to_ofp_port(flow->in_port));
4923 opi->reason = upcall->type == _ODPL_MISS_NR ? OFPR_NO_MATCH : OFPR_ACTION;
43253595
BP
4924 opi->buffer_id = htonl(buffer_id);
4925 update_openflow_length(packet);
4926
4927 /* Hand over to packet scheduler. It might immediately call into
4928 * do_send_packet_in() or it might buffer it for a while (until a later
4929 * call to pinsched_run()). */
856081f6 4930 pinsched_send(ofconn->schedulers[opi->reason], flow->in_port,
43253595 4931 packet, do_send_packet_in, ofconn);
064af421
BP
4932}
4933
856081f6
BP
4934/* Given 'upcall', of type _ODPL_ACTION_NR or _ODPL_MISS_NR, sends an
4935 * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
4936 * their individual configurations.
43253595
BP
4937 *
4938 * Takes ownership of 'packet'. */
4939static void
856081f6
BP
4940send_packet_in(struct ofproto *ofproto, struct dpif_upcall *upcall,
4941 const struct flow *flow, bool clone)
43253595 4942{
76ce9432 4943 struct ofconn *ofconn, *prev;
76ce9432
BP
4944
4945 prev = NULL;
4e8e4213 4946 LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
c91248b3 4947 if (ofconn_receives_async_msgs(ofconn)) {
9deba63b 4948 if (prev) {
856081f6 4949 schedule_packet_in(prev, upcall, flow, true);
9deba63b
BP
4950 }
4951 prev = ofconn;
064af421 4952 }
76ce9432
BP
4953 }
4954 if (prev) {
856081f6
BP
4955 schedule_packet_in(prev, upcall, flow, clone);
4956 } else if (!clone) {
4957 ofpbuf_delete(upcall->packet);
064af421 4958 }
064af421
BP
4959}
4960
4961static uint64_t
fa60c019 4962pick_datapath_id(const struct ofproto *ofproto)
064af421 4963{
fa60c019 4964 const struct ofport *port;
064af421 4965
ca0f572c 4966 port = get_port(ofproto, ODPP_LOCAL);
fa60c019
BP
4967 if (port) {
4968 uint8_t ea[ETH_ADDR_LEN];
4969 int error;
4970
4971 error = netdev_get_etheraddr(port->netdev, ea);
064af421
BP
4972 if (!error) {
4973 return eth_addr_to_uint64(ea);
4974 }
4975 VLOG_WARN("could not get MAC address for %s (%s)",
fa60c019 4976 netdev_get_name(port->netdev), strerror(error));
064af421 4977 }
fa60c019 4978 return ofproto->fallback_dpid;
064af421
BP
4979}
4980
4981static uint64_t
4982pick_fallback_dpid(void)
4983{
4984 uint8_t ea[ETH_ADDR_LEN];
70150daf 4985 eth_addr_nicira_random(ea);
064af421
BP
4986 return eth_addr_to_uint64(ea);
4987}
4988\f
7aa697dd
BP
4989static void
4990ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
4991 void *aux OVS_UNUSED)
4992{
4993 const struct shash_node *node;
4994 struct ds results;
4995
4996 ds_init(&results);
4997 SHASH_FOR_EACH (node, &all_ofprotos) {
4998 ds_put_format(&results, "%s\n", node->name);
4999 }
5000 unixctl_command_reply(conn, 200, ds_cstr(&results));
5001 ds_destroy(&results);
5002}
5003
5004struct ofproto_trace {
5005 struct action_xlate_ctx ctx;
5006 struct flow flow;
5007 struct ds *result;
5008};
5009
5010static void
5011trace_format_rule(struct ds *result, int level, const struct rule *rule)
5012{
5013 ds_put_char_multiple(result, '\t', level);
5014 if (!rule) {
5015 ds_put_cstr(result, "No match\n");
5016 return;
5017 }
5018
5019 ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
5020 ntohll(rule->flow_cookie));
5021 cls_rule_format(&rule->cr, result);
5022 ds_put_char(result, '\n');
5023
5024 ds_put_char_multiple(result, '\t', level);
5025 ds_put_cstr(result, "OpenFlow ");
5026 ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
5027 rule->n_actions * sizeof *rule->actions);
5028 ds_put_char(result, '\n');
5029}
5030
5031static void
5032trace_format_flow(struct ds *result, int level, const char *title,
5033 struct ofproto_trace *trace)
5034{
5035 ds_put_char_multiple(result, '\t', level);
5036 ds_put_format(result, "%s: ", title);
5037 if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5038 ds_put_cstr(result, "unchanged");
5039 } else {
5040 flow_format(result, &trace->ctx.flow);
5041 trace->flow = trace->ctx.flow;
5042 }
5043 ds_put_char(result, '\n');
5044}
5045
5046static void
5047trace_resubmit(struct action_xlate_ctx *ctx, const struct rule *rule)
5048{
5049 struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5050 struct ds *result = trace->result;
5051
5052 ds_put_char(result, '\n');
5053 trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5054 trace_format_rule(result, ctx->recurse + 1, rule);
5055}
5056
5057static void
5058ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5059 void *aux OVS_UNUSED)
5060{
5061 char *dpname, *in_port_s, *tun_id_s, *packet_s;
5062 char *args = xstrdup(args_);
5063 char *save_ptr = NULL;
5064 struct ofproto *ofproto;
5065 struct ofpbuf packet;
5066 struct rule *rule;
5067 struct ds result;
5068 struct flow flow;
5069 uint16_t in_port;
11e6a15b 5070 ovs_be64 tun_id;
7aa697dd
BP
5071 char *s;
5072
5073 ofpbuf_init(&packet, strlen(args) / 2);
5074 ds_init(&result);
5075
5076 dpname = strtok_r(args, " ", &save_ptr);
5077 tun_id_s = strtok_r(NULL, " ", &save_ptr);
5078 in_port_s = strtok_r(NULL, " ", &save_ptr);
5079 packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5080 if (!dpname || !in_port_s || !packet_s) {
5081 unixctl_command_reply(conn, 501, "Bad command syntax");
5082 goto exit;
5083 }
5084
5085 ofproto = shash_find_data(&all_ofprotos, dpname);
5086 if (!ofproto) {
5087 unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5088 "for help)");
5089 goto exit;
5090 }
5091
11e6a15b 5092 tun_id = htonll(strtoull(tun_id_s, NULL, 10));
7aa697dd
BP
5093 in_port = ofp_port_to_odp_port(atoi(in_port_s));
5094
5095 packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
5096 packet_s += strspn(packet_s, " ");
5097 if (*packet_s != '\0') {
5098 unixctl_command_reply(conn, 501, "Trailing garbage in command");
5099 goto exit;
5100 }
5101 if (packet.size < ETH_HEADER_LEN) {
5102 unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
5103 goto exit;
5104 }
5105
5106 ds_put_cstr(&result, "Packet: ");
5107 s = ofp_packet_to_string(packet.data, packet.size, packet.size);
5108 ds_put_cstr(&result, s);
5109 free(s);
5110
5111 flow_extract(&packet, tun_id, in_port, &flow);
5112 ds_put_cstr(&result, "Flow: ");
5113 flow_format(&result, &flow);
5114 ds_put_char(&result, '\n');
5115
5116 rule = rule_lookup(ofproto, &flow);
5117 trace_format_rule(&result, 0, rule);
5118 if (rule) {
5119 struct ofproto_trace trace;
cdee00fd 5120 struct ofpbuf *odp_actions;
7aa697dd
BP
5121
5122 trace.result = &result;
5123 trace.flow = flow;
5124 action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
5125 trace.ctx.resubmit_hook = trace_resubmit;
cdee00fd
BP
5126 odp_actions = xlate_actions(&trace.ctx,
5127 rule->actions, rule->n_actions);
7aa697dd
BP
5128
5129 ds_put_char(&result, '\n');
5130 trace_format_flow(&result, 0, "Final flow", &trace);
5131 ds_put_cstr(&result, "Datapath actions: ");
cdee00fd
BP
5132 format_odp_actions(&result, odp_actions->data, odp_actions->size);
5133 ofpbuf_delete(odp_actions);
7aa697dd
BP
5134 }
5135
5136 unixctl_command_reply(conn, 200, ds_cstr(&result));
5137
5138exit:
5139 ds_destroy(&result);
5140 ofpbuf_uninit(&packet);
5141 free(args);
5142}
5143
5144static void
5145ofproto_unixctl_init(void)
5146{
5147 static bool registered;
5148 if (registered) {
5149 return;
5150 }
5151 registered = true;
5152
5153 unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
5154 unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
5155}
5156\f
064af421 5157static bool
ae412e7d 5158default_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
cdee00fd 5159 struct ofpbuf *odp_actions, tag_type *tags,
6a07af36 5160 uint16_t *nf_output_iface, void *ofproto_)
064af421
BP
5161{
5162 struct ofproto *ofproto = ofproto_;
5163 int out_port;
5164
5165 /* Drop frames for reserved multicast addresses. */
5166 if (eth_addr_is_reserved(flow->dl_dst)) {
5167 return true;
5168 }
5169
5170 /* Learn source MAC (but don't try to learn from revalidation). */
5171 if (packet != NULL) {
5172 tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
7febb910
JG
5173 0, flow->in_port,
5174 GRAT_ARP_LOCK_NONE);
064af421
BP
5175 if (rev_tag) {
5176 /* The log messages here could actually be useful in debugging,
5177 * so keep the rate limit relatively high. */
5178 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5179 VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
5180 ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
5181 ofproto_revalidate(ofproto, rev_tag);
5182 }
5183 }
5184
5185 /* Determine output port. */
7febb910
JG
5186 out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags,
5187 NULL);
064af421 5188 if (out_port < 0) {
f1588b1f 5189 flood_packets(ofproto, flow->in_port, OFPPC_NO_FLOOD,
cdee00fd 5190 nf_output_iface, odp_actions);
064af421 5191 } else if (out_port != flow->in_port) {
cdee00fd 5192 nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, out_port);
6a07af36 5193 *nf_output_iface = out_port;
064af421
BP
5194 } else {
5195 /* Drop. */
5196 }
5197
5198 return true;
5199}
5200
5201static const struct ofhooks default_ofhooks = {
064af421
BP
5202 default_normal_ofhook_cb,
5203 NULL,
5204 NULL
5205};