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