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