datapath: Change listing ports to use an iterator concept.
[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 dpif_port_dump dump;
1540     struct shash_node *node;
1541     struct shash devnames;
1542     struct ofport *ofport;
1543     struct odp_port odp_port;
1544
1545     COVERAGE_INC(ofproto_reinit_ports);
1546
1547     shash_init(&devnames);
1548     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1549         shash_add_once (&devnames, ofport->opp.name, NULL);
1550     }
1551     DPIF_PORT_FOR_EACH (&odp_port, &dump, p->dpif) {
1552         shash_add_once (&devnames, odp_port.devname, NULL);
1553     }
1554
1555     SHASH_FOR_EACH (node, &devnames) {
1556         update_port(p, node->name);
1557     }
1558     shash_destroy(&devnames);
1559 }
1560
1561 static struct ofport *
1562 make_ofport(const struct odp_port *odp_port)
1563 {
1564     struct netdev_options netdev_options;
1565     enum netdev_flags flags;
1566     struct ofport *ofport;
1567     struct netdev *netdev;
1568     int error;
1569
1570     memset(&netdev_options, 0, sizeof netdev_options);
1571     netdev_options.name = odp_port->devname;
1572     netdev_options.type = odp_port->type;
1573     netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
1574
1575     error = netdev_open(&netdev_options, &netdev);
1576     if (error) {
1577         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1578                      "cannot be opened (%s)",
1579                      odp_port->devname, odp_port->port,
1580                      odp_port->devname, strerror(error));
1581         return NULL;
1582     }
1583
1584     ofport = xmalloc(sizeof *ofport);
1585     ofport->netdev = netdev;
1586     ofport->odp_port = odp_port->port;
1587     ofport->opp.port_no = odp_port_to_ofp_port(odp_port->port);
1588     netdev_get_etheraddr(netdev, ofport->opp.hw_addr);
1589     memcpy(ofport->opp.name, odp_port->devname,
1590            MIN(sizeof ofport->opp.name, sizeof odp_port->devname));
1591     ofport->opp.name[sizeof ofport->opp.name - 1] = '\0';
1592
1593     netdev_get_flags(netdev, &flags);
1594     ofport->opp.config = flags & NETDEV_UP ? 0 : OFPPC_PORT_DOWN;
1595
1596     ofport->opp.state = netdev_get_carrier(netdev) ? 0 : OFPPS_LINK_DOWN;
1597
1598     netdev_get_features(netdev,
1599                         &ofport->opp.curr, &ofport->opp.advertised,
1600                         &ofport->opp.supported, &ofport->opp.peer);
1601     return ofport;
1602 }
1603
1604 static bool
1605 ofport_conflicts(const struct ofproto *p, const struct odp_port *odp_port)
1606 {
1607     if (get_port(p, odp_port->port)) {
1608         VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1609                      odp_port->port);
1610         return true;
1611     } else if (shash_find(&p->port_by_name, odp_port->devname)) {
1612         VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1613                      odp_port->devname);
1614         return true;
1615     } else {
1616         return false;
1617     }
1618 }
1619
1620 static int
1621 ofport_equal(const struct ofport *a_, const struct ofport *b_)
1622 {
1623     const struct ofp_phy_port *a = &a_->opp;
1624     const struct ofp_phy_port *b = &b_->opp;
1625
1626     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1627     return (a->port_no == b->port_no
1628             && !memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1629             && !strcmp(a->name, b->name)
1630             && a->state == b->state
1631             && a->config == b->config
1632             && a->curr == b->curr
1633             && a->advertised == b->advertised
1634             && a->supported == b->supported
1635             && a->peer == b->peer);
1636 }
1637
1638 static void
1639 send_port_status(struct ofproto *p, const struct ofport *ofport,
1640                  uint8_t reason)
1641 {
1642     /* XXX Should limit the number of queued port status change messages. */
1643     struct ofconn *ofconn;
1644     LIST_FOR_EACH (ofconn, node, &p->all_conns) {
1645         struct ofp_port_status *ops;
1646         struct ofpbuf *b;
1647
1648         /* Primary controllers, even slaves, should always get port status
1649            updates.  Otherwise obey ofconn_receives_async_msgs(). */
1650         if (ofconn->type != OFCONN_PRIMARY
1651             && !ofconn_receives_async_msgs(ofconn)) {
1652             continue;
1653         }
1654
1655         ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &b);
1656         ops->reason = reason;
1657         ops->desc = ofport->opp;
1658         hton_ofp_phy_port(&ops->desc);
1659         queue_tx(b, ofconn, NULL);
1660     }
1661 }
1662
1663 static void
1664 ofport_install(struct ofproto *p, struct ofport *ofport)
1665 {
1666     const char *netdev_name = ofport->opp.name;
1667
1668     netdev_monitor_add(p->netdev_monitor, ofport->netdev);
1669     hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->odp_port, 0));
1670     shash_add(&p->port_by_name, netdev_name, ofport);
1671     if (p->sflow) {
1672         ofproto_sflow_add_port(p->sflow, ofport->odp_port, netdev_name);
1673     }
1674 }
1675
1676 static void
1677 ofport_remove(struct ofproto *p, struct ofport *ofport)
1678 {
1679     netdev_monitor_remove(p->netdev_monitor, ofport->netdev);
1680     hmap_remove(&p->ports, &ofport->hmap_node);
1681     shash_delete(&p->port_by_name,
1682                  shash_find(&p->port_by_name, ofport->opp.name));
1683     if (p->sflow) {
1684         ofproto_sflow_del_port(p->sflow, ofport->odp_port);
1685     }
1686 }
1687
1688 static void
1689 ofport_free(struct ofport *ofport)
1690 {
1691     if (ofport) {
1692         netdev_close(ofport->netdev);
1693         free(ofport);
1694     }
1695 }
1696
1697 static struct ofport *
1698 get_port(const struct ofproto *ofproto, uint16_t odp_port)
1699 {
1700     struct ofport *port;
1701
1702     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1703                              hash_int(odp_port, 0), &ofproto->ports) {
1704         if (port->odp_port == odp_port) {
1705             return port;
1706         }
1707     }
1708     return NULL;
1709 }
1710
1711 static void
1712 update_port(struct ofproto *p, const char *devname)
1713 {
1714     struct odp_port odp_port;
1715     struct ofport *old_ofport;
1716     struct ofport *new_ofport;
1717     int error;
1718
1719     COVERAGE_INC(ofproto_update_port);
1720
1721     /* Query the datapath for port information. */
1722     error = dpif_port_query_by_name(p->dpif, devname, &odp_port);
1723
1724     /* Find the old ofport. */
1725     old_ofport = shash_find_data(&p->port_by_name, devname);
1726     if (!error) {
1727         if (!old_ofport) {
1728             /* There's no port named 'devname' but there might be a port with
1729              * the same port number.  This could happen if a port is deleted
1730              * and then a new one added in its place very quickly, or if a port
1731              * is renamed.  In the former case we want to send an OFPPR_DELETE
1732              * and an OFPPR_ADD, and in the latter case we want to send a
1733              * single OFPPR_MODIFY.  We can distinguish the cases by comparing
1734              * the old port's ifindex against the new port, or perhaps less
1735              * reliably but more portably by comparing the old port's MAC
1736              * against the new port's MAC.  However, this code isn't that smart
1737              * and always sends an OFPPR_MODIFY (XXX). */
1738             old_ofport = get_port(p, odp_port.port);
1739         }
1740     } else if (error != ENOENT && error != ENODEV) {
1741         VLOG_WARN_RL(&rl, "dpif_port_query_by_name returned unexpected error "
1742                      "%s", strerror(error));
1743         return;
1744     }
1745
1746     /* Create a new ofport. */
1747     new_ofport = !error ? make_ofport(&odp_port) : NULL;
1748
1749     /* Eliminate a few pathological cases. */
1750     if (!old_ofport && !new_ofport) {
1751         return;
1752     } else if (old_ofport && new_ofport) {
1753         /* Most of the 'config' bits are OpenFlow soft state, but
1754          * OFPPC_PORT_DOWN is maintained by the kernel.  So transfer the
1755          * OpenFlow bits from old_ofport.  (make_ofport() only sets
1756          * OFPPC_PORT_DOWN and leaves the other bits 0.)  */
1757         new_ofport->opp.config |= old_ofport->opp.config & ~OFPPC_PORT_DOWN;
1758
1759         if (ofport_equal(old_ofport, new_ofport)) {
1760             /* False alarm--no change. */
1761             ofport_free(new_ofport);
1762             return;
1763         }
1764     }
1765
1766     /* Now deal with the normal cases. */
1767     if (old_ofport) {
1768         ofport_remove(p, old_ofport);
1769     }
1770     if (new_ofport) {
1771         ofport_install(p, new_ofport);
1772     }
1773     send_port_status(p, new_ofport ? new_ofport : old_ofport,
1774                      (!old_ofport ? OFPPR_ADD
1775                       : !new_ofport ? OFPPR_DELETE
1776                       : OFPPR_MODIFY));
1777     ofport_free(old_ofport);
1778 }
1779
1780 static int
1781 init_ports(struct ofproto *p)
1782 {
1783     struct dpif_port_dump dump;
1784     struct odp_port odp_port;
1785
1786     DPIF_PORT_FOR_EACH (&odp_port, &dump, p->dpif) {
1787         if (!ofport_conflicts(p, &odp_port)) {
1788             struct ofport *ofport = make_ofport(&odp_port);
1789             if (ofport) {
1790                 ofport_install(p, ofport);
1791             }
1792         }
1793     }
1794
1795     return 0;
1796 }
1797 \f
1798 static struct ofconn *
1799 ofconn_create(struct ofproto *p, struct rconn *rconn, enum ofconn_type type)
1800 {
1801     struct ofconn *ofconn = xzalloc(sizeof *ofconn);
1802     ofconn->ofproto = p;
1803     list_push_back(&p->all_conns, &ofconn->node);
1804     ofconn->rconn = rconn;
1805     ofconn->type = type;
1806     ofconn->flow_format = NXFF_OPENFLOW10;
1807     ofconn->role = NX_ROLE_OTHER;
1808     ofconn->packet_in_counter = rconn_packet_counter_create ();
1809     ofconn->pktbuf = NULL;
1810     ofconn->miss_send_len = 0;
1811     ofconn->reply_counter = rconn_packet_counter_create ();
1812     return ofconn;
1813 }
1814
1815 static void
1816 ofconn_destroy(struct ofconn *ofconn)
1817 {
1818     if (ofconn->type == OFCONN_PRIMARY) {
1819         hmap_remove(&ofconn->ofproto->controllers, &ofconn->hmap_node);
1820     }
1821     discovery_destroy(ofconn->discovery);
1822
1823     list_remove(&ofconn->node);
1824     switch_status_unregister(ofconn->ss);
1825     rconn_destroy(ofconn->rconn);
1826     rconn_packet_counter_destroy(ofconn->packet_in_counter);
1827     rconn_packet_counter_destroy(ofconn->reply_counter);
1828     pktbuf_destroy(ofconn->pktbuf);
1829     free(ofconn);
1830 }
1831
1832 static void
1833 ofconn_run(struct ofconn *ofconn)
1834 {
1835     struct ofproto *p = ofconn->ofproto;
1836     int iteration;
1837     size_t i;
1838
1839     if (ofconn->discovery) {
1840         char *controller_name;
1841         if (rconn_is_connectivity_questionable(ofconn->rconn)) {
1842             discovery_question_connectivity(ofconn->discovery);
1843         }
1844         if (discovery_run(ofconn->discovery, &controller_name)) {
1845             if (controller_name) {
1846                 char *ofconn_name = ofconn_make_name(p, controller_name);
1847                 rconn_connect(ofconn->rconn, controller_name, ofconn_name);
1848                 free(ofconn_name);
1849             } else {
1850                 rconn_disconnect(ofconn->rconn);
1851             }
1852         }
1853     }
1854
1855     for (i = 0; i < N_SCHEDULERS; i++) {
1856         pinsched_run(ofconn->schedulers[i], do_send_packet_in, ofconn);
1857     }
1858
1859     rconn_run(ofconn->rconn);
1860
1861     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1862         /* Limit the number of iterations to prevent other tasks from
1863          * starving. */
1864         for (iteration = 0; iteration < 50; iteration++) {
1865             struct ofpbuf *of_msg = rconn_recv(ofconn->rconn);
1866             if (!of_msg) {
1867                 break;
1868             }
1869             if (p->fail_open) {
1870                 fail_open_maybe_recover(p->fail_open);
1871             }
1872             handle_openflow(ofconn, of_msg);
1873             ofpbuf_delete(of_msg);
1874         }
1875     }
1876
1877     if (!ofconn->discovery && !rconn_is_alive(ofconn->rconn)) {
1878         ofconn_destroy(ofconn);
1879     }
1880 }
1881
1882 static void
1883 ofconn_wait(struct ofconn *ofconn)
1884 {
1885     int i;
1886
1887     if (ofconn->discovery) {
1888         discovery_wait(ofconn->discovery);
1889     }
1890     for (i = 0; i < N_SCHEDULERS; i++) {
1891         pinsched_wait(ofconn->schedulers[i]);
1892     }
1893     rconn_run_wait(ofconn->rconn);
1894     if (rconn_packet_counter_read (ofconn->reply_counter) < OFCONN_REPLY_MAX) {
1895         rconn_recv_wait(ofconn->rconn);
1896     } else {
1897         COVERAGE_INC(ofproto_ofconn_stuck);
1898     }
1899 }
1900
1901 /* Returns true if 'ofconn' should receive asynchronous messages. */
1902 static bool
1903 ofconn_receives_async_msgs(const struct ofconn *ofconn)
1904 {
1905     if (ofconn->type == OFCONN_PRIMARY) {
1906         /* Primary controllers always get asynchronous messages unless they
1907          * have configured themselves as "slaves".  */
1908         return ofconn->role != NX_ROLE_SLAVE;
1909     } else {
1910         /* Service connections don't get asynchronous messages unless they have
1911          * explicitly asked for them by setting a nonzero miss send length. */
1912         return ofconn->miss_send_len > 0;
1913     }
1914 }
1915
1916 /* Returns a human-readable name for an OpenFlow connection between 'ofproto'
1917  * and 'target', suitable for use in log messages for identifying the
1918  * connection.
1919  *
1920  * The name is dynamically allocated.  The caller should free it (with free())
1921  * when it is no longer needed. */
1922 static char *
1923 ofconn_make_name(const struct ofproto *ofproto, const char *target)
1924 {
1925     return xasprintf("%s<->%s", dpif_base_name(ofproto->dpif), target);
1926 }
1927
1928 static void
1929 ofconn_set_rate_limit(struct ofconn *ofconn, int rate, int burst)
1930 {
1931     int i;
1932
1933     for (i = 0; i < N_SCHEDULERS; i++) {
1934         struct pinsched **s = &ofconn->schedulers[i];
1935
1936         if (rate > 0) {
1937             if (!*s) {
1938                 *s = pinsched_create(rate, burst,
1939                                      ofconn->ofproto->switch_status);
1940             } else {
1941                 pinsched_set_limits(*s, rate, burst);
1942             }
1943         } else {
1944             pinsched_destroy(*s);
1945             *s = NULL;
1946         }
1947     }
1948 }
1949 \f
1950 static void
1951 ofservice_reconfigure(struct ofservice *ofservice,
1952                       const struct ofproto_controller *c)
1953 {
1954     ofservice->probe_interval = c->probe_interval;
1955     ofservice->rate_limit = c->rate_limit;
1956     ofservice->burst_limit = c->burst_limit;
1957 }
1958
1959 /* Creates a new ofservice in 'ofproto'.  Returns 0 if successful, otherwise a
1960  * positive errno value. */
1961 static int
1962 ofservice_create(struct ofproto *ofproto, const struct ofproto_controller *c)
1963 {
1964     struct ofservice *ofservice;
1965     struct pvconn *pvconn;
1966     int error;
1967
1968     error = pvconn_open(c->target, &pvconn);
1969     if (error) {
1970         return error;
1971     }
1972
1973     ofservice = xzalloc(sizeof *ofservice);
1974     hmap_insert(&ofproto->services, &ofservice->node,
1975                 hash_string(c->target, 0));
1976     ofservice->pvconn = pvconn;
1977
1978     ofservice_reconfigure(ofservice, c);
1979
1980     return 0;
1981 }
1982
1983 static void
1984 ofservice_destroy(struct ofproto *ofproto, struct ofservice *ofservice)
1985 {
1986     hmap_remove(&ofproto->services, &ofservice->node);
1987     pvconn_close(ofservice->pvconn);
1988     free(ofservice);
1989 }
1990
1991 /* Finds and returns the ofservice within 'ofproto' that has the given
1992  * 'target', or a null pointer if none exists. */
1993 static struct ofservice *
1994 ofservice_lookup(struct ofproto *ofproto, const char *target)
1995 {
1996     struct ofservice *ofservice;
1997
1998     HMAP_FOR_EACH_WITH_HASH (ofservice, node, hash_string(target, 0),
1999                              &ofproto->services) {
2000         if (!strcmp(pvconn_get_name(ofservice->pvconn), target)) {
2001             return ofservice;
2002         }
2003     }
2004     return NULL;
2005 }
2006 \f
2007 /* Returns true if 'rule' should be hidden from the controller.
2008  *
2009  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2010  * (e.g. by in-band control) and are intentionally hidden from the
2011  * controller. */
2012 static bool
2013 rule_is_hidden(const struct rule *rule)
2014 {
2015     return rule->cr.priority > UINT16_MAX;
2016 }
2017
2018 /* Creates and returns a new rule initialized as specified.
2019  *
2020  * The caller is responsible for inserting the rule into the classifier (with
2021  * rule_insert()). */
2022 static struct rule *
2023 rule_create(const struct cls_rule *cls_rule,
2024             const union ofp_action *actions, size_t n_actions,
2025             uint16_t idle_timeout, uint16_t hard_timeout,
2026             ovs_be64 flow_cookie, bool send_flow_removed)
2027 {
2028     struct rule *rule = xzalloc(sizeof *rule);
2029     rule->cr = *cls_rule;
2030     rule->idle_timeout = idle_timeout;
2031     rule->hard_timeout = hard_timeout;
2032     rule->flow_cookie = flow_cookie;
2033     rule->used = rule->created = time_msec();
2034     rule->send_flow_removed = send_flow_removed;
2035     list_init(&rule->facets);
2036     if (n_actions > 0) {
2037         rule->n_actions = n_actions;
2038         rule->actions = xmemdup(actions, n_actions * sizeof *actions);
2039     }
2040
2041     return rule;
2042 }
2043
2044 static struct rule *
2045 rule_from_cls_rule(const struct cls_rule *cls_rule)
2046 {
2047     return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
2048 }
2049
2050 static void
2051 rule_free(struct rule *rule)
2052 {
2053     free(rule->actions);
2054     free(rule);
2055 }
2056
2057 /* Destroys 'rule' and iterates through all of its facets and revalidates them,
2058  * destroying any that no longer has a rule (which is probably all of them).
2059  *
2060  * The caller must have already removed 'rule' from the classifier. */
2061 static void
2062 rule_destroy(struct ofproto *ofproto, struct rule *rule)
2063 {
2064     struct facet *facet, *next_facet;
2065     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2066         facet_revalidate(ofproto, facet);
2067     }
2068     rule_free(rule);
2069 }
2070
2071 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2072  * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
2073  * count). */
2074 static bool
2075 rule_has_out_port(const struct rule *rule, ovs_be16 out_port)
2076 {
2077     const union ofp_action *oa;
2078     struct actions_iterator i;
2079
2080     if (out_port == htons(OFPP_NONE)) {
2081         return true;
2082     }
2083     for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
2084          oa = actions_next(&i)) {
2085         if (action_outputs_to_port(oa, out_port)) {
2086             return true;
2087         }
2088     }
2089     return false;
2090 }
2091
2092 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2093  * 'packet', which arrived on 'in_port'.
2094  *
2095  * Takes ownership of 'packet'. */
2096 static bool
2097 execute_odp_actions(struct ofproto *ofproto, const struct flow *flow,
2098                     const struct nlattr *odp_actions, size_t actions_len,
2099                     struct ofpbuf *packet)
2100 {
2101     if (actions_len == NLA_ALIGN(NLA_HDRLEN + sizeof(uint64_t))
2102         && odp_actions->nla_type == ODPAT_CONTROLLER) {
2103         /* As an optimization, avoid a round-trip from userspace to kernel to
2104          * userspace.  This also avoids possibly filling up kernel packet
2105          * buffers along the way. */
2106         struct dpif_upcall upcall;
2107
2108         upcall.type = _ODPL_ACTION_NR;
2109         upcall.packet = packet;
2110         upcall.key = NULL;
2111         upcall.key_len = 0;
2112         upcall.userdata = nl_attr_get_u64(odp_actions);
2113         upcall.sample_pool = 0;
2114         upcall.actions = NULL;
2115         upcall.actions_len = 0;
2116
2117         send_packet_in(ofproto, &upcall, flow, false);
2118
2119         return true;
2120     } else {
2121         int error;
2122
2123         error = dpif_execute(ofproto->dpif, odp_actions, actions_len, packet);
2124         ofpbuf_delete(packet);
2125         return !error;
2126     }
2127 }
2128
2129 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2130  * statistics appropriately.  'packet' must have at least sizeof(struct
2131  * ofp_packet_in) bytes of headroom.
2132  *
2133  * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2134  * applying flow_extract() to 'packet' would yield the same flow as
2135  * 'facet->flow'.
2136  *
2137  * 'facet' must have accurately composed ODP actions; that is, it must not be
2138  * in need of revalidation.
2139  *
2140  * Takes ownership of 'packet'. */
2141 static void
2142 facet_execute(struct ofproto *ofproto, struct facet *facet,
2143               struct ofpbuf *packet)
2144 {
2145     struct odp_flow_stats stats;
2146
2147     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2148
2149     flow_extract_stats(&facet->flow, packet, &stats);
2150     if (execute_odp_actions(ofproto, &facet->flow,
2151                             facet->actions, facet->actions_len, packet)) {
2152         facet_update_stats(ofproto, facet, &stats);
2153         facet->used = time_msec();
2154         netflow_flow_update_time(ofproto->netflow,
2155                                  &facet->nf_flow, facet->used);
2156     }
2157 }
2158
2159 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2160  * statistics (or the statistics for one of its facets) appropriately.
2161  * 'packet' must have at least sizeof(struct ofp_packet_in) bytes of headroom.
2162  *
2163  * 'packet' doesn't necessarily have to match 'rule'.  'rule' will be credited
2164  * with statistics for 'packet' either way.
2165  *
2166  * Takes ownership of 'packet'. */
2167 static void
2168 rule_execute(struct ofproto *ofproto, struct rule *rule, uint16_t in_port,
2169              struct ofpbuf *packet)
2170 {
2171     struct action_xlate_ctx ctx;
2172     struct ofpbuf *odp_actions;
2173     struct facet *facet;
2174     struct flow flow;
2175     size_t size;
2176
2177     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2178
2179     flow_extract(packet, 0, in_port, &flow);
2180
2181     /* First look for a related facet.  If we find one, account it to that. */
2182     facet = facet_lookup_valid(ofproto, &flow);
2183     if (facet && facet->rule == rule) {
2184         facet_execute(ofproto, facet, packet);
2185         return;
2186     }
2187
2188     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
2189      * create a new facet for it and use that. */
2190     if (rule_lookup(ofproto, &flow) == rule) {
2191         facet = facet_create(ofproto, rule, &flow, packet);
2192         facet_execute(ofproto, facet, packet);
2193         facet_install(ofproto, facet, true);
2194         return;
2195     }
2196
2197     /* We can't account anything to a facet.  If we were to try, then that
2198      * facet would have a non-matching rule, busting our invariants. */
2199     action_xlate_ctx_init(&ctx, ofproto, &flow, packet);
2200     odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
2201     size = packet->size;
2202     if (execute_odp_actions(ofproto, &flow, odp_actions->data,
2203                             odp_actions->size, packet)) {
2204         rule->used = time_msec();
2205         rule->packet_count++;
2206         rule->byte_count += size;
2207     }
2208     ofpbuf_delete(odp_actions);
2209 }
2210
2211 /* Inserts 'rule' into 'p''s flow table. */
2212 static void
2213 rule_insert(struct ofproto *p, struct rule *rule)
2214 {
2215     struct rule *displaced_rule;
2216
2217     displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
2218     if (displaced_rule) {
2219         rule_destroy(p, displaced_rule);
2220     }
2221     p->need_revalidate = true;
2222 }
2223
2224 /* Creates and returns a new facet within 'ofproto' owned by 'rule', given a
2225  * 'flow' and an example 'packet' within that flow.
2226  *
2227  * The caller must already have determined that no facet with an identical
2228  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2229  * 'ofproto''s classifier table. */
2230 static struct facet *
2231 facet_create(struct ofproto *ofproto, struct rule *rule,
2232              const struct flow *flow, const struct ofpbuf *packet)
2233 {
2234     struct facet *facet;
2235
2236     facet = xzalloc(sizeof *facet);
2237     facet->used = time_msec();
2238     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2239     list_push_back(&rule->facets, &facet->list_node);
2240     facet->rule = rule;
2241     facet->flow = *flow;
2242     netflow_flow_init(&facet->nf_flow);
2243     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2244
2245     facet_make_actions(ofproto, facet, packet);
2246
2247     return facet;
2248 }
2249
2250 static void
2251 facet_free(struct facet *facet)
2252 {
2253     free(facet->actions);
2254     free(facet);
2255 }
2256
2257 /* Remove 'rule' from 'ofproto' and free up the associated memory:
2258  *
2259  *   - Removes 'rule' from the classifier.
2260  *
2261  *   - If 'rule' has facets, revalidates them (and possibly uninstalls and
2262  *     destroys them), via rule_destroy().
2263  */
2264 static void
2265 rule_remove(struct ofproto *ofproto, struct rule *rule)
2266 {
2267     COVERAGE_INC(ofproto_del_rule);
2268     ofproto->need_revalidate = true;
2269     classifier_remove(&ofproto->cls, &rule->cr);
2270     rule_destroy(ofproto, rule);
2271 }
2272
2273 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2274  *
2275  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
2276  *     rule's statistics, via facet_uninstall().
2277  *
2278  *   - Removes 'facet' from its rule and from ofproto->facets.
2279  */
2280 static void
2281 facet_remove(struct ofproto *ofproto, struct facet *facet)
2282 {
2283     facet_uninstall(ofproto, facet);
2284     facet_flush_stats(ofproto, facet);
2285     hmap_remove(&ofproto->facets, &facet->hmap_node);
2286     list_remove(&facet->list_node);
2287     facet_free(facet);
2288 }
2289
2290 /* Composes the ODP actions for 'facet' based on its rule's actions. */
2291 static void
2292 facet_make_actions(struct ofproto *p, struct facet *facet,
2293                    const struct ofpbuf *packet)
2294 {
2295     const struct rule *rule = facet->rule;
2296     struct ofpbuf *odp_actions;
2297     struct action_xlate_ctx ctx;
2298
2299     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2300     odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
2301     facet->tags = ctx.tags;
2302     facet->may_install = ctx.may_set_up_flow;
2303     facet->nf_flow.output_iface = ctx.nf_output_iface;
2304
2305     if (facet->actions_len != odp_actions->size
2306         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2307         free(facet->actions);
2308         facet->actions_len = odp_actions->size;
2309         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2310     }
2311
2312     ofpbuf_delete(odp_actions);
2313 }
2314
2315 static int
2316 facet_put__(struct ofproto *ofproto, struct facet *facet, int flags,
2317             struct odp_flow_put *put)
2318 {
2319     uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2320     struct ofpbuf key;
2321
2322     ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2323     odp_flow_key_from_flow(&key, &facet->flow);
2324     assert(key.base == keybuf);
2325
2326     memset(&put->flow.stats, 0, sizeof put->flow.stats);
2327     put->flow.key = key.data;
2328     put->flow.key_len = key.size;
2329     put->flow.actions = facet->actions;
2330     put->flow.actions_len = facet->actions_len;
2331     put->flow.flags = 0;
2332     put->flags = flags;
2333     return dpif_flow_put(ofproto->dpif, put);
2334 }
2335
2336 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
2337  * 'zero_stats' is true, clears any existing statistics from the datapath for
2338  * 'facet'. */
2339 static void
2340 facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
2341 {
2342     if (facet->may_install) {
2343         struct odp_flow_put put;
2344         int flags;
2345
2346         flags = ODPPF_CREATE | ODPPF_MODIFY;
2347         if (zero_stats) {
2348             flags |= ODPPF_ZERO_STATS;
2349         }
2350         if (!facet_put__(p, facet, flags, &put)) {
2351             facet->installed = true;
2352         }
2353     }
2354 }
2355
2356 /* Ensures that the bytes in 'facet', plus 'extra_bytes', have been passed up
2357  * to the accounting hook function in the ofhooks structure. */
2358 static void
2359 facet_account(struct ofproto *ofproto,
2360               struct facet *facet, uint64_t extra_bytes)
2361 {
2362     uint64_t total_bytes = facet->byte_count + extra_bytes;
2363
2364     if (ofproto->ofhooks->account_flow_cb
2365         && total_bytes > facet->accounted_bytes)
2366     {
2367         ofproto->ofhooks->account_flow_cb(
2368             &facet->flow, facet->tags, facet->actions, facet->actions_len,
2369             total_bytes - facet->accounted_bytes, ofproto->aux);
2370         facet->accounted_bytes = total_bytes;
2371     }
2372 }
2373
2374 /* If 'rule' is installed in the datapath, uninstalls it. */
2375 static void
2376 facet_uninstall(struct ofproto *p, struct facet *facet)
2377 {
2378     if (facet->installed) {
2379         uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2380         struct odp_flow odp_flow;
2381         struct ofpbuf key;
2382
2383         ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2384         odp_flow_key_from_flow(&key, &facet->flow);
2385         assert(key.base == keybuf);
2386
2387         odp_flow.key = key.data;
2388         odp_flow.key_len = key.size;
2389         odp_flow.actions = NULL;
2390         odp_flow.actions_len = 0;
2391         odp_flow.flags = 0;
2392         if (!dpif_flow_del(p->dpif, &odp_flow)) {
2393             facet_update_stats(p, facet, &odp_flow.stats);
2394         }
2395         facet->installed = false;
2396     }
2397 }
2398
2399 /* Returns true if the only action for 'facet' is to send to the controller.
2400  * (We don't report NetFlow expiration messages for such facets because they
2401  * are just part of the control logic for the network, not real traffic). */
2402 static bool
2403 facet_is_controller_flow(struct facet *facet)
2404 {
2405     return (facet
2406             && facet->rule->n_actions == 1
2407             && action_outputs_to_port(&facet->rule->actions[0],
2408                                       htons(OFPP_CONTROLLER)));
2409 }
2410
2411 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2412  * accounting ofhook and emits a NetFlow expiration if appropriate.  */
2413 static void
2414 facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
2415 {
2416     facet_account(ofproto, facet, 0);
2417
2418     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2419         struct ofexpired expired;
2420         expired.flow = facet->flow;
2421         expired.packet_count = facet->packet_count;
2422         expired.byte_count = facet->byte_count;
2423         expired.used = facet->used;
2424         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2425     }
2426
2427     facet->rule->packet_count += facet->packet_count;
2428     facet->rule->byte_count += facet->byte_count;
2429
2430     /* Reset counters to prevent double counting if 'facet' ever gets
2431      * reinstalled. */
2432     facet->packet_count = 0;
2433     facet->byte_count = 0;
2434     facet->accounted_bytes = 0;
2435
2436     netflow_flow_clear(&facet->nf_flow);
2437 }
2438
2439 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2440  * Returns it if found, otherwise a null pointer.
2441  *
2442  * The returned facet might need revalidation; use facet_lookup_valid()
2443  * instead if that is important. */
2444 static struct facet *
2445 facet_find(struct ofproto *ofproto, const struct flow *flow)
2446 {
2447     struct facet *facet;
2448
2449     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2450                              &ofproto->facets) {
2451         if (flow_equal(flow, &facet->flow)) {
2452             return facet;
2453         }
2454     }
2455
2456     return NULL;
2457 }
2458
2459 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2460  * Returns it if found, otherwise a null pointer.
2461  *
2462  * The returned facet is guaranteed to be valid. */
2463 static struct facet *
2464 facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
2465 {
2466     struct facet *facet = facet_find(ofproto, flow);
2467
2468     /* The facet we found might not be valid, since we could be in need of
2469      * revalidation.  If it is not valid, don't return it. */
2470     if (facet
2471         && ofproto->need_revalidate
2472         && !facet_revalidate(ofproto, facet)) {
2473         COVERAGE_INC(ofproto_invalidated);
2474         return NULL;
2475     }
2476
2477     return facet;
2478 }
2479
2480 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2481  *
2482  *   - If the rule found is different from 'facet''s current rule, moves
2483  *     'facet' to the new rule and recompiles its actions.
2484  *
2485  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2486  *     where it is and recompiles its actions anyway.
2487  *
2488  *   - If there is none, destroys 'facet'.
2489  *
2490  * Returns true if 'facet' still exists, false if it has been destroyed. */
2491 static bool
2492 facet_revalidate(struct ofproto *ofproto, struct facet *facet)
2493 {
2494     struct action_xlate_ctx ctx;
2495     struct ofpbuf *odp_actions;
2496     struct rule *new_rule;
2497     bool actions_changed;
2498
2499     COVERAGE_INC(facet_revalidate);
2500
2501     /* Determine the new rule. */
2502     new_rule = rule_lookup(ofproto, &facet->flow);
2503     if (!new_rule) {
2504         /* No new rule, so delete the facet. */
2505         facet_remove(ofproto, facet);
2506         return false;
2507     }
2508
2509     /* Calculate new ODP actions.
2510      *
2511      * We do not modify any 'facet' state yet, because we might need to, e.g.,
2512      * emit a NetFlow expiration and, if so, we need to have the old state
2513      * around to properly compose it. */
2514     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2515     odp_actions = xlate_actions(&ctx, new_rule->actions, new_rule->n_actions);
2516     actions_changed = (facet->actions_len != odp_actions->size
2517                        || memcmp(facet->actions, odp_actions->data,
2518                                  facet->actions_len));
2519
2520     /* If the ODP actions changed or the installability changed, then we need
2521      * to talk to the datapath. */
2522     if (actions_changed || facet->may_install != facet->installed) {
2523         if (facet->may_install) {
2524             uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2525             struct odp_flow_put put;
2526             struct ofpbuf key;
2527
2528             ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2529             odp_flow_key_from_flow(&key, &facet->flow);
2530
2531             memset(&put.flow.stats, 0, sizeof put.flow.stats);
2532             put.flow.key = key.data;
2533             put.flow.key_len = key.size;
2534             put.flow.actions = odp_actions->data;
2535             put.flow.actions_len = odp_actions->size;
2536             put.flow.flags = 0;
2537             put.flags = ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS;
2538             dpif_flow_put(ofproto->dpif, &put);
2539
2540             facet_update_stats(ofproto, facet, &put.flow.stats);
2541         } else {
2542             facet_uninstall(ofproto, facet);
2543         }
2544
2545         /* The datapath flow is gone or has zeroed stats, so push stats out of
2546          * 'facet' into 'rule'. */
2547         facet_flush_stats(ofproto, facet);
2548     }
2549
2550     /* Update 'facet' now that we've taken care of all the old state. */
2551     facet->tags = ctx.tags;
2552     facet->nf_flow.output_iface = ctx.nf_output_iface;
2553     facet->may_install = ctx.may_set_up_flow;
2554     if (actions_changed) {
2555         free(facet->actions);
2556         facet->actions_len = odp_actions->size;
2557         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2558     }
2559     if (facet->rule != new_rule) {
2560         COVERAGE_INC(facet_changed_rule);
2561         list_remove(&facet->list_node);
2562         list_push_back(&new_rule->facets, &facet->list_node);
2563         facet->rule = new_rule;
2564         facet->used = new_rule->created;
2565     }
2566
2567     ofpbuf_delete(odp_actions);
2568
2569     return true;
2570 }
2571 \f
2572 static void
2573 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
2574          struct rconn_packet_counter *counter)
2575 {
2576     update_openflow_length(msg);
2577     if (rconn_send(ofconn->rconn, msg, counter)) {
2578         ofpbuf_delete(msg);
2579     }
2580 }
2581
2582 static void
2583 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
2584               int error)
2585 {
2586     struct ofpbuf *buf = ofputil_encode_error_msg(error, oh);
2587     if (buf) {
2588         COVERAGE_INC(ofproto_error);
2589         queue_tx(buf, ofconn, ofconn->reply_counter);
2590     }
2591 }
2592
2593 static void
2594 hton_ofp_phy_port(struct ofp_phy_port *opp)
2595 {
2596     opp->port_no = htons(opp->port_no);
2597     opp->config = htonl(opp->config);
2598     opp->state = htonl(opp->state);
2599     opp->curr = htonl(opp->curr);
2600     opp->advertised = htonl(opp->advertised);
2601     opp->supported = htonl(opp->supported);
2602     opp->peer = htonl(opp->peer);
2603 }
2604
2605 static int
2606 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2607 {
2608     queue_tx(make_echo_reply(oh), ofconn, ofconn->reply_counter);
2609     return 0;
2610 }
2611
2612 static int
2613 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2614 {
2615     struct ofp_switch_features *osf;
2616     struct ofpbuf *buf;
2617     struct ofport *port;
2618
2619     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
2620     osf->datapath_id = htonll(ofconn->ofproto->datapath_id);
2621     osf->n_buffers = htonl(pktbuf_capacity());
2622     osf->n_tables = 2;
2623     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
2624                               OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
2625     osf->actions = htonl((1u << OFPAT_OUTPUT) |
2626                          (1u << OFPAT_SET_VLAN_VID) |
2627                          (1u << OFPAT_SET_VLAN_PCP) |
2628                          (1u << OFPAT_STRIP_VLAN) |
2629                          (1u << OFPAT_SET_DL_SRC) |
2630                          (1u << OFPAT_SET_DL_DST) |
2631                          (1u << OFPAT_SET_NW_SRC) |
2632                          (1u << OFPAT_SET_NW_DST) |
2633                          (1u << OFPAT_SET_NW_TOS) |
2634                          (1u << OFPAT_SET_TP_SRC) |
2635                          (1u << OFPAT_SET_TP_DST) |
2636                          (1u << OFPAT_ENQUEUE));
2637
2638     HMAP_FOR_EACH (port, hmap_node, &ofconn->ofproto->ports) {
2639         hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
2640     }
2641
2642     queue_tx(buf, ofconn, ofconn->reply_counter);
2643     return 0;
2644 }
2645
2646 static int
2647 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2648 {
2649     struct ofpbuf *buf;
2650     struct ofp_switch_config *osc;
2651     uint16_t flags;
2652     bool drop_frags;
2653
2654     /* Figure out flags. */
2655     dpif_get_drop_frags(ofconn->ofproto->dpif, &drop_frags);
2656     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
2657
2658     /* Send reply. */
2659     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
2660     osc->flags = htons(flags);
2661     osc->miss_send_len = htons(ofconn->miss_send_len);
2662     queue_tx(buf, ofconn, ofconn->reply_counter);
2663
2664     return 0;
2665 }
2666
2667 static int
2668 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
2669 {
2670     uint16_t flags = ntohs(osc->flags);
2671
2672     if (ofconn->type == OFCONN_PRIMARY && ofconn->role != NX_ROLE_SLAVE) {
2673         switch (flags & OFPC_FRAG_MASK) {
2674         case OFPC_FRAG_NORMAL:
2675             dpif_set_drop_frags(ofconn->ofproto->dpif, false);
2676             break;
2677         case OFPC_FRAG_DROP:
2678             dpif_set_drop_frags(ofconn->ofproto->dpif, true);
2679             break;
2680         default:
2681             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
2682                          osc->flags);
2683             break;
2684         }
2685     }
2686
2687     ofconn->miss_send_len = ntohs(osc->miss_send_len);
2688
2689     return 0;
2690 }
2691
2692 /* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
2693  * flow translation. */
2694 #define MAX_RESUBMIT_RECURSION 16
2695
2696 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2697                              struct action_xlate_ctx *ctx);
2698
2699 static void
2700 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
2701 {
2702     const struct ofport *ofport = get_port(ctx->ofproto, port);
2703
2704     if (ofport) {
2705         if (ofport->opp.config & OFPPC_NO_FWD) {
2706             /* Forwarding disabled on port. */
2707             return;
2708         }
2709     } else {
2710         /*
2711          * We don't have an ofport record for this port, but it doesn't hurt to
2712          * allow forwarding to it anyhow.  Maybe such a port will appear later
2713          * and we're pre-populating the flow table.
2714          */
2715     }
2716
2717     nl_msg_put_u32(ctx->odp_actions, ODPAT_OUTPUT, port);
2718     ctx->nf_output_iface = port;
2719 }
2720
2721 static struct rule *
2722 rule_lookup(struct ofproto *ofproto, const struct flow *flow)
2723 {
2724     return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
2725 }
2726
2727 static void
2728 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2729 {
2730     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2731         uint16_t old_in_port;
2732         struct rule *rule;
2733
2734         /* Look up a flow with 'in_port' as the input port.  Then restore the
2735          * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2736          * have surprising behavior). */
2737         old_in_port = ctx->flow.in_port;
2738         ctx->flow.in_port = in_port;
2739         rule = rule_lookup(ctx->ofproto, &ctx->flow);
2740         ctx->flow.in_port = old_in_port;
2741
2742         if (ctx->resubmit_hook) {
2743             ctx->resubmit_hook(ctx, rule);
2744         }
2745
2746         if (rule) {
2747             ctx->recurse++;
2748             do_xlate_actions(rule->actions, rule->n_actions, ctx);
2749             ctx->recurse--;
2750         }
2751     } else {
2752         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2753
2754         VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2755                     MAX_RESUBMIT_RECURSION);
2756     }
2757 }
2758
2759 static void
2760 flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, uint32_t mask,
2761               uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
2762 {
2763     struct ofport *ofport;
2764
2765     HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
2766         uint16_t odp_port = ofport->odp_port;
2767         if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
2768             nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, odp_port);
2769         }
2770     }
2771     *nf_output_iface = NF_OUT_FLOOD;
2772 }
2773
2774 static void
2775 xlate_output_action__(struct action_xlate_ctx *ctx,
2776                       uint16_t port, uint16_t max_len)
2777 {
2778     uint16_t odp_port;
2779     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2780
2781     ctx->nf_output_iface = NF_OUT_DROP;
2782
2783     switch (port) {
2784     case OFPP_IN_PORT:
2785         add_output_action(ctx, ctx->flow.in_port);
2786         break;
2787     case OFPP_TABLE:
2788         xlate_table_action(ctx, ctx->flow.in_port);
2789         break;
2790     case OFPP_NORMAL:
2791         if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
2792                                               ctx->odp_actions, &ctx->tags,
2793                                               &ctx->nf_output_iface,
2794                                               ctx->ofproto->aux)) {
2795             COVERAGE_INC(ofproto_uninstallable);
2796             ctx->may_set_up_flow = false;
2797         }
2798         break;
2799     case OFPP_FLOOD:
2800         flood_packets(ctx->ofproto, ctx->flow.in_port, OFPPC_NO_FLOOD,
2801                       &ctx->nf_output_iface, ctx->odp_actions);
2802         break;
2803     case OFPP_ALL:
2804         flood_packets(ctx->ofproto, ctx->flow.in_port, 0,
2805                       &ctx->nf_output_iface, ctx->odp_actions);
2806         break;
2807     case OFPP_CONTROLLER:
2808         nl_msg_put_u64(ctx->odp_actions, ODPAT_CONTROLLER, max_len);
2809         break;
2810     case OFPP_LOCAL:
2811         add_output_action(ctx, ODPP_LOCAL);
2812         break;
2813     default:
2814         odp_port = ofp_port_to_odp_port(port);
2815         if (odp_port != ctx->flow.in_port) {
2816             add_output_action(ctx, odp_port);
2817         }
2818         break;
2819     }
2820
2821     if (prev_nf_output_iface == NF_OUT_FLOOD) {
2822         ctx->nf_output_iface = NF_OUT_FLOOD;
2823     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2824         ctx->nf_output_iface = prev_nf_output_iface;
2825     } else if (prev_nf_output_iface != NF_OUT_DROP &&
2826                ctx->nf_output_iface != NF_OUT_FLOOD) {
2827         ctx->nf_output_iface = NF_OUT_MULTI;
2828     }
2829 }
2830
2831 static void
2832 xlate_output_action(struct action_xlate_ctx *ctx,
2833                     const struct ofp_action_output *oao)
2834 {
2835     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2836 }
2837
2838 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2839  * optimization, because we're going to add another action that sets the
2840  * priority immediately after, or because there are no actions following the
2841  * pop.  */
2842 static void
2843 remove_pop_action(struct action_xlate_ctx *ctx)
2844 {
2845     if (ctx->odp_actions->size == ctx->last_pop_priority) {
2846         ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
2847         ctx->last_pop_priority = -1;
2848     }
2849 }
2850
2851 static void
2852 add_pop_action(struct action_xlate_ctx *ctx)
2853 {
2854     if (ctx->odp_actions->size != ctx->last_pop_priority) {
2855         nl_msg_put_flag(ctx->odp_actions, ODPAT_POP_PRIORITY);
2856         ctx->last_pop_priority = ctx->odp_actions->size;
2857     }
2858 }
2859
2860 static void
2861 xlate_enqueue_action(struct action_xlate_ctx *ctx,
2862                      const struct ofp_action_enqueue *oae)
2863 {
2864     uint16_t ofp_port, odp_port;
2865     uint32_t priority;
2866     int error;
2867
2868     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2869                                    &priority);
2870     if (error) {
2871         /* Fall back to ordinary output action. */
2872         xlate_output_action__(ctx, ntohs(oae->port), 0);
2873         return;
2874     }
2875
2876     /* Figure out ODP output port. */
2877     ofp_port = ntohs(oae->port);
2878     if (ofp_port != OFPP_IN_PORT) {
2879         odp_port = ofp_port_to_odp_port(ofp_port);
2880     } else {
2881         odp_port = ctx->flow.in_port;
2882     }
2883
2884     /* Add ODP actions. */
2885     remove_pop_action(ctx);
2886     nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2887     add_output_action(ctx, odp_port);
2888     add_pop_action(ctx);
2889
2890     /* Update NetFlow output port. */
2891     if (ctx->nf_output_iface == NF_OUT_DROP) {
2892         ctx->nf_output_iface = odp_port;
2893     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2894         ctx->nf_output_iface = NF_OUT_MULTI;
2895     }
2896 }
2897
2898 static void
2899 xlate_set_queue_action(struct action_xlate_ctx *ctx,
2900                        const struct nx_action_set_queue *nasq)
2901 {
2902     uint32_t priority;
2903     int error;
2904
2905     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2906                                    &priority);
2907     if (error) {
2908         /* Couldn't translate queue to a priority, so ignore.  A warning
2909          * has already been logged. */
2910         return;
2911     }
2912
2913     remove_pop_action(ctx);
2914     nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2915 }
2916
2917 static void
2918 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2919 {
2920     ovs_be16 tci = ctx->flow.vlan_tci;
2921     if (!(tci & htons(VLAN_CFI))) {
2922         nl_msg_put_flag(ctx->odp_actions, ODPAT_STRIP_VLAN);
2923     } else {
2924         nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_DL_TCI,
2925                         tci & ~htons(VLAN_CFI));
2926     }
2927 }
2928
2929 struct xlate_reg_state {
2930     ovs_be16 vlan_tci;
2931     ovs_be64 tun_id;
2932 };
2933
2934 static void
2935 save_reg_state(const struct action_xlate_ctx *ctx,
2936                struct xlate_reg_state *state)
2937 {
2938     state->vlan_tci = ctx->flow.vlan_tci;
2939     state->tun_id = ctx->flow.tun_id;
2940 }
2941
2942 static void
2943 update_reg_state(struct action_xlate_ctx *ctx,
2944                  const struct xlate_reg_state *state)
2945 {
2946     if (ctx->flow.vlan_tci != state->vlan_tci) {
2947         xlate_set_dl_tci(ctx);
2948     }
2949     if (ctx->flow.tun_id != state->tun_id) {
2950         nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, ctx->flow.tun_id);
2951     }
2952 }
2953
2954 static void
2955 xlate_nicira_action(struct action_xlate_ctx *ctx,
2956                     const struct nx_action_header *nah)
2957 {
2958     const struct nx_action_resubmit *nar;
2959     const struct nx_action_set_tunnel *nast;
2960     const struct nx_action_set_queue *nasq;
2961     const struct nx_action_multipath *nam;
2962     enum nx_action_subtype subtype = ntohs(nah->subtype);
2963     struct xlate_reg_state state;
2964     ovs_be64 tun_id;
2965
2966     assert(nah->vendor == htonl(NX_VENDOR_ID));
2967     switch (subtype) {
2968     case NXAST_RESUBMIT:
2969         nar = (const struct nx_action_resubmit *) nah;
2970         xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2971         break;
2972
2973     case NXAST_SET_TUNNEL:
2974         nast = (const struct nx_action_set_tunnel *) nah;
2975         tun_id = htonll(ntohl(nast->tun_id));
2976         nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
2977         ctx->flow.tun_id = tun_id;
2978         break;
2979
2980     case NXAST_DROP_SPOOFED_ARP:
2981         if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
2982             nl_msg_put_flag(ctx->odp_actions, ODPAT_DROP_SPOOFED_ARP);
2983         }
2984         break;
2985
2986     case NXAST_SET_QUEUE:
2987         nasq = (const struct nx_action_set_queue *) nah;
2988         xlate_set_queue_action(ctx, nasq);
2989         break;
2990
2991     case NXAST_POP_QUEUE:
2992         add_pop_action(ctx);
2993         break;
2994
2995     case NXAST_REG_MOVE:
2996         save_reg_state(ctx, &state);
2997         nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
2998                              &ctx->flow);
2999         update_reg_state(ctx, &state);
3000         break;
3001
3002     case NXAST_REG_LOAD:
3003         save_reg_state(ctx, &state);
3004         nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
3005                              &ctx->flow);
3006         update_reg_state(ctx, &state);
3007         break;
3008
3009     case NXAST_NOTE:
3010         /* Nothing to do. */
3011         break;
3012
3013     case NXAST_SET_TUNNEL64:
3014         tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
3015         nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
3016         ctx->flow.tun_id = tun_id;
3017         break;
3018
3019     case NXAST_MULTIPATH:
3020         nam = (const struct nx_action_multipath *) nah;
3021         multipath_execute(nam, &ctx->flow);
3022         break;
3023
3024     /* If you add a new action here that modifies flow data, don't forget to
3025      * update the flow key in ctx->flow at the same time. */
3026
3027     case NXAST_SNAT__OBSOLETE:
3028     default:
3029         VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
3030         break;
3031     }
3032 }
3033
3034 static void
3035 do_xlate_actions(const union ofp_action *in, size_t n_in,
3036                  struct action_xlate_ctx *ctx)
3037 {
3038     struct actions_iterator iter;
3039     const union ofp_action *ia;
3040     const struct ofport *port;
3041
3042     port = get_port(ctx->ofproto, ctx->flow.in_port);
3043     if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
3044         port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
3045                             ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
3046         /* Drop this flow. */
3047         return;
3048     }
3049
3050     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
3051         enum ofp_action_type type = ntohs(ia->type);
3052         const struct ofp_action_dl_addr *oada;
3053
3054         switch (type) {
3055         case OFPAT_OUTPUT:
3056             xlate_output_action(ctx, &ia->output);
3057             break;
3058
3059         case OFPAT_SET_VLAN_VID:
3060             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3061             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
3062             xlate_set_dl_tci(ctx);
3063             break;
3064
3065         case OFPAT_SET_VLAN_PCP:
3066             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3067             ctx->flow.vlan_tci |= htons(
3068                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
3069             xlate_set_dl_tci(ctx);
3070             break;
3071
3072         case OFPAT_STRIP_VLAN:
3073             ctx->flow.vlan_tci = htons(0);
3074             xlate_set_dl_tci(ctx);
3075             break;
3076
3077         case OFPAT_SET_DL_SRC:
3078             oada = ((struct ofp_action_dl_addr *) ia);
3079             nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_SRC,
3080                               oada->dl_addr, ETH_ADDR_LEN);
3081             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
3082             break;
3083
3084         case OFPAT_SET_DL_DST:
3085             oada = ((struct ofp_action_dl_addr *) ia);
3086             nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_DST,
3087                               oada->dl_addr, ETH_ADDR_LEN);
3088             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
3089             break;
3090
3091         case OFPAT_SET_NW_SRC:
3092             nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_SRC,
3093                             ia->nw_addr.nw_addr);
3094             ctx->flow.nw_src = ia->nw_addr.nw_addr;
3095             break;
3096
3097         case OFPAT_SET_NW_DST:
3098             nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_DST,
3099                             ia->nw_addr.nw_addr);
3100             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
3101             break;
3102
3103         case OFPAT_SET_NW_TOS:
3104             nl_msg_put_u8(ctx->odp_actions, ODPAT_SET_NW_TOS,
3105                           ia->nw_tos.nw_tos);
3106             ctx->flow.nw_tos = ia->nw_tos.nw_tos;
3107             break;
3108
3109         case OFPAT_SET_TP_SRC:
3110             nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_SRC,
3111                             ia->tp_port.tp_port);
3112             ctx->flow.tp_src = ia->tp_port.tp_port;
3113             break;
3114
3115         case OFPAT_SET_TP_DST:
3116             nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_DST,
3117                             ia->tp_port.tp_port);
3118             ctx->flow.tp_dst = ia->tp_port.tp_port;
3119             break;
3120
3121         case OFPAT_VENDOR:
3122             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
3123             break;
3124
3125         case OFPAT_ENQUEUE:
3126             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3127             break;
3128
3129         default:
3130             VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
3131             break;
3132         }
3133     }
3134 }
3135
3136 static void
3137 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3138                       struct ofproto *ofproto, const struct flow *flow,
3139                       const struct ofpbuf *packet)
3140 {
3141     ctx->ofproto = ofproto;
3142     ctx->flow = *flow;
3143     ctx->packet = packet;
3144     ctx->resubmit_hook = NULL;
3145 }
3146
3147 static struct ofpbuf *
3148 xlate_actions(struct action_xlate_ctx *ctx,
3149               const union ofp_action *in, size_t n_in)
3150 {
3151     COVERAGE_INC(ofproto_ofp2odp);
3152
3153     ctx->odp_actions = ofpbuf_new(512);
3154     ctx->tags = 0;
3155     ctx->may_set_up_flow = true;
3156     ctx->nf_output_iface = NF_OUT_DROP;
3157     ctx->recurse = 0;
3158     ctx->last_pop_priority = -1;
3159     do_xlate_actions(in, n_in, ctx);
3160     remove_pop_action(ctx);
3161
3162     /* Check with in-band control to see if we're allowed to set up this
3163      * flow. */
3164     if (!in_band_rule_check(ctx->ofproto->in_band, &ctx->flow,
3165                             ctx->odp_actions->data, ctx->odp_actions->size)) {
3166         ctx->may_set_up_flow = false;
3167     }
3168
3169     return ctx->odp_actions;
3170 }
3171
3172 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
3173  * error message code (composed with ofp_mkerr()) for the caller to propagate
3174  * upward.  Otherwise, returns 0.
3175  *
3176  * The log message mentions 'msg_type'. */
3177 static int
3178 reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
3179 {
3180     if (ofconn->type == OFCONN_PRIMARY && ofconn->role == NX_ROLE_SLAVE) {
3181         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
3182         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
3183                      msg_type);
3184
3185         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3186     } else {
3187         return 0;
3188     }
3189 }
3190
3191 static int
3192 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
3193 {
3194     struct ofproto *p = ofconn->ofproto;
3195     struct ofp_packet_out *opo;
3196     struct ofpbuf payload, *buffer;
3197     union ofp_action *ofp_actions;
3198     struct action_xlate_ctx ctx;
3199     struct ofpbuf *odp_actions;
3200     struct ofpbuf request;
3201     struct flow flow;
3202     size_t n_ofp_actions;
3203     uint16_t in_port;
3204     int error;
3205
3206     COVERAGE_INC(ofproto_packet_out);
3207
3208     error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
3209     if (error) {
3210         return error;
3211     }
3212
3213     /* Get ofp_packet_out. */
3214     ofpbuf_use_const(&request, oh, ntohs(oh->length));
3215     opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
3216
3217     /* Get actions. */
3218     error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
3219                                  &ofp_actions, &n_ofp_actions);
3220     if (error) {
3221         return error;
3222     }
3223
3224     /* Get payload. */
3225     if (opo->buffer_id != htonl(UINT32_MAX)) {
3226         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
3227                                 &buffer, &in_port);
3228         if (error || !buffer) {
3229             return error;
3230         }
3231         payload = *buffer;
3232     } else {
3233         payload = request;
3234         buffer = NULL;
3235     }
3236
3237     /* Extract flow, check actions. */
3238     flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
3239                  &flow);
3240     error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
3241     if (error) {
3242         goto exit;
3243     }
3244
3245     /* Send. */
3246     action_xlate_ctx_init(&ctx, p, &flow, &payload);
3247     odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
3248     dpif_execute(p->dpif, odp_actions->data, odp_actions->size, &payload);
3249     ofpbuf_delete(odp_actions);
3250
3251 exit:
3252     ofpbuf_delete(buffer);
3253     return 0;
3254 }
3255
3256 static void
3257 update_port_config(struct ofproto *p, struct ofport *port,
3258                    uint32_t config, uint32_t mask)
3259 {
3260     mask &= config ^ port->opp.config;
3261     if (mask & OFPPC_PORT_DOWN) {
3262         if (config & OFPPC_PORT_DOWN) {
3263             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
3264         } else {
3265             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
3266         }
3267     }
3268 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP |    \
3269                          OFPPC_NO_FWD | OFPPC_NO_FLOOD)
3270     if (mask & REVALIDATE_BITS) {
3271         COVERAGE_INC(ofproto_costly_flags);
3272         port->opp.config ^= mask & REVALIDATE_BITS;
3273         p->need_revalidate = true;
3274     }
3275 #undef REVALIDATE_BITS
3276     if (mask & OFPPC_NO_PACKET_IN) {
3277         port->opp.config ^= OFPPC_NO_PACKET_IN;
3278     }
3279 }
3280
3281 static int
3282 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3283 {
3284     struct ofproto *p = ofconn->ofproto;
3285     const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
3286     struct ofport *port;
3287     int error;
3288
3289     error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
3290     if (error) {
3291         return error;
3292     }
3293
3294     port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
3295     if (!port) {
3296         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
3297     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
3298         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
3299     } else {
3300         update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
3301         if (opm->advertise) {
3302             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
3303         }
3304     }
3305     return 0;
3306 }
3307
3308 static struct ofpbuf *
3309 make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
3310 {
3311     struct ofp_stats_reply *osr;
3312     struct ofpbuf *msg;
3313
3314     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
3315     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
3316     osr->type = type;
3317     osr->flags = htons(0);
3318     return msg;
3319 }
3320
3321 static struct ofpbuf *
3322 start_ofp_stats_reply(const struct ofp_header *request, size_t body_len)
3323 {
3324     const struct ofp_stats_request *osr
3325         = (const struct ofp_stats_request *) request;
3326     return make_ofp_stats_reply(osr->header.xid, osr->type, body_len);
3327 }
3328
3329 static void *
3330 append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
3331                        struct ofpbuf **msgp)
3332 {
3333     struct ofpbuf *msg = *msgp;
3334     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
3335     if (nbytes + msg->size > UINT16_MAX) {
3336         struct ofp_stats_reply *reply = msg->data;
3337         reply->flags = htons(OFPSF_REPLY_MORE);
3338         *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
3339         queue_tx(msg, ofconn, ofconn->reply_counter);
3340     }
3341     return ofpbuf_put_uninit(*msgp, nbytes);
3342 }
3343
3344 static struct ofpbuf *
3345 make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
3346 {
3347     struct nicira_stats_msg *nsm;
3348     struct ofpbuf *msg;
3349
3350     msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
3351     nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
3352     nsm->type = htons(OFPST_VENDOR);
3353     nsm->flags = htons(0);
3354     nsm->vendor = htonl(NX_VENDOR_ID);
3355     nsm->subtype = subtype;
3356     return msg;
3357 }
3358
3359 static struct ofpbuf *
3360 start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
3361 {
3362     return make_nxstats_reply(request->header.xid, request->subtype, body_len);
3363 }
3364
3365 static void
3366 append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
3367                      struct ofpbuf **msgp)
3368 {
3369     struct ofpbuf *msg = *msgp;
3370     assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
3371     if (nbytes + msg->size > UINT16_MAX) {
3372         struct nicira_stats_msg *reply = msg->data;
3373         reply->flags = htons(OFPSF_REPLY_MORE);
3374         *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
3375         queue_tx(msg, ofconn, ofconn->reply_counter);
3376     }
3377     ofpbuf_prealloc_tailroom(*msgp, nbytes);
3378 }
3379
3380 static int
3381 handle_desc_stats_request(struct ofconn *ofconn,
3382                           const struct ofp_header *request)
3383 {
3384     struct ofproto *p = ofconn->ofproto;
3385     struct ofp_desc_stats *ods;
3386     struct ofpbuf *msg;
3387
3388     msg = start_ofp_stats_reply(request, sizeof *ods);
3389     ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
3390     memset(ods, 0, sizeof *ods);
3391     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
3392     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
3393     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
3394     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
3395     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
3396     queue_tx(msg, ofconn, ofconn->reply_counter);
3397
3398     return 0;
3399 }
3400
3401 static int
3402 handle_table_stats_request(struct ofconn *ofconn,
3403                            const struct ofp_header *request)
3404 {
3405     struct ofproto *p = ofconn->ofproto;
3406     struct ofp_table_stats *ots;
3407     struct ofpbuf *msg;
3408
3409     msg = start_ofp_stats_reply(request, sizeof *ots * 2);
3410
3411     /* Classifier table. */
3412     ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
3413     memset(ots, 0, sizeof *ots);
3414     strcpy(ots->name, "classifier");
3415     ots->wildcards = (ofconn->flow_format == NXFF_OPENFLOW10
3416                       ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
3417     ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
3418     ots->active_count = htonl(classifier_count(&p->cls));
3419     ots->lookup_count = htonll(0);              /* XXX */
3420     ots->matched_count = htonll(0);             /* XXX */
3421
3422     queue_tx(msg, ofconn, ofconn->reply_counter);
3423     return 0;
3424 }
3425
3426 static void
3427 append_port_stat(struct ofport *port, struct ofconn *ofconn,
3428                  struct ofpbuf **msgp)
3429 {
3430     struct netdev_stats stats;
3431     struct ofp_port_stats *ops;
3432
3433     /* Intentionally ignore return value, since errors will set
3434      * 'stats' to all-1s, which is correct for OpenFlow, and
3435      * netdev_get_stats() will log errors. */
3436     netdev_get_stats(port->netdev, &stats);
3437
3438     ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
3439     ops->port_no = htons(port->opp.port_no);
3440     memset(ops->pad, 0, sizeof ops->pad);
3441     ops->rx_packets = htonll(stats.rx_packets);
3442     ops->tx_packets = htonll(stats.tx_packets);
3443     ops->rx_bytes = htonll(stats.rx_bytes);
3444     ops->tx_bytes = htonll(stats.tx_bytes);
3445     ops->rx_dropped = htonll(stats.rx_dropped);
3446     ops->tx_dropped = htonll(stats.tx_dropped);
3447     ops->rx_errors = htonll(stats.rx_errors);
3448     ops->tx_errors = htonll(stats.tx_errors);
3449     ops->rx_frame_err = htonll(stats.rx_frame_errors);
3450     ops->rx_over_err = htonll(stats.rx_over_errors);
3451     ops->rx_crc_err = htonll(stats.rx_crc_errors);
3452     ops->collisions = htonll(stats.collisions);
3453 }
3454
3455 static int
3456 handle_port_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3457 {
3458     struct ofproto *p = ofconn->ofproto;
3459     const struct ofp_port_stats_request *psr = ofputil_stats_body(oh);
3460     struct ofp_port_stats *ops;
3461     struct ofpbuf *msg;
3462     struct ofport *port;
3463
3464     msg = start_ofp_stats_reply(oh, sizeof *ops * 16);
3465     if (psr->port_no != htons(OFPP_NONE)) {
3466         port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
3467         if (port) {
3468             append_port_stat(port, ofconn, &msg);
3469         }
3470     } else {
3471         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3472             append_port_stat(port, ofconn, &msg);
3473         }
3474     }
3475
3476     queue_tx(msg, ofconn, ofconn->reply_counter);
3477     return 0;
3478 }
3479
3480 /* Obtains statistic counters for 'rule' within 'p' and stores them into
3481  * '*packet_countp' and '*byte_countp'.  The returned statistics include
3482  * statistics for all of 'rule''s facets. */
3483 static void
3484 query_stats(struct ofproto *p, struct rule *rule,
3485             uint64_t *packet_countp, uint64_t *byte_countp)
3486 {
3487     uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
3488     uint64_t packet_count, byte_count;
3489     struct facet *facet;
3490     struct ofpbuf key;
3491
3492     /* Start from historical data for 'rule' itself that are no longer tracked
3493      * by the datapath.  This counts, for example, facets that have expired. */
3494     packet_count = rule->packet_count;
3495     byte_count = rule->byte_count;
3496
3497     /* Ask the datapath for statistics on all of the rule's facets.  (We could
3498      * batch up statistics requests using dpif_flow_get_multiple(), but that is
3499      * not yet implemented.)
3500      *
3501      * Also, add any statistics that are not tracked by the datapath for each
3502      * facet.  This includes, for example, statistics for packets that were
3503      * executed "by hand" by ofproto via dpif_execute() but must be accounted
3504      * to a rule. */
3505     ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
3506     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3507         struct odp_flow odp_flow;
3508
3509         ofpbuf_clear(&key);
3510         odp_flow_key_from_flow(&key, &facet->flow);
3511
3512         odp_flow.key = key.data;
3513         odp_flow.key_len = key.size;
3514         odp_flow.actions = NULL;
3515         odp_flow.actions_len = 0;
3516         odp_flow.flags = 0;
3517         if (!dpif_flow_get(p->dpif, &odp_flow)) {
3518             packet_count += odp_flow.stats.n_packets;
3519             byte_count += odp_flow.stats.n_bytes;
3520         }
3521
3522         packet_count += facet->packet_count;
3523         byte_count += facet->byte_count;
3524     }
3525
3526     /* Return the stats to the caller. */
3527     *packet_countp = packet_count;
3528     *byte_countp = byte_count;
3529 }
3530
3531 static void
3532 calc_flow_duration(long long int start, ovs_be32 *sec, ovs_be32 *nsec)
3533 {
3534     long long int msecs = time_msec() - start;
3535     *sec = htonl(msecs / 1000);
3536     *nsec = htonl((msecs % 1000) * (1000 * 1000));
3537 }
3538
3539 static void
3540 put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
3541                    ovs_be16 out_port, struct ofpbuf **replyp)
3542 {
3543     struct ofp_flow_stats *ofs;
3544     uint64_t packet_count, byte_count;
3545     size_t act_len, len;
3546
3547     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3548         return;
3549     }
3550
3551     act_len = sizeof *rule->actions * rule->n_actions;
3552     len = offsetof(struct ofp_flow_stats, actions) + act_len;
3553
3554     query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3555
3556     ofs = append_ofp_stats_reply(len, ofconn, replyp);
3557     ofs->length = htons(len);
3558     ofs->table_id = 0;
3559     ofs->pad = 0;
3560     ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofs->match,
3561                               rule->flow_cookie, &ofs->cookie);
3562     calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
3563     ofs->priority = htons(rule->cr.priority);
3564     ofs->idle_timeout = htons(rule->idle_timeout);
3565     ofs->hard_timeout = htons(rule->hard_timeout);
3566     memset(ofs->pad2, 0, sizeof ofs->pad2);
3567     ofs->packet_count = htonll(packet_count);
3568     ofs->byte_count = htonll(byte_count);
3569     if (rule->n_actions > 0) {
3570         memcpy(ofs->actions, rule->actions, act_len);
3571     }
3572 }
3573
3574 static bool
3575 is_valid_table(uint8_t table_id)
3576 {
3577     return table_id == 0 || table_id == 0xff;
3578 }
3579
3580 static int
3581 handle_flow_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3582 {
3583     const struct ofp_flow_stats_request *fsr = ofputil_stats_body(oh);
3584     struct ofpbuf *reply;
3585
3586     COVERAGE_INC(ofproto_flows_req);
3587     reply = start_ofp_stats_reply(oh, 1024);
3588     if (is_valid_table(fsr->table_id)) {
3589         struct cls_cursor cursor;
3590         struct cls_rule target;
3591         struct rule *rule;
3592
3593         ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
3594                                     &target);
3595         cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3596         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3597             put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
3598         }
3599     }
3600     queue_tx(reply, ofconn, ofconn->reply_counter);
3601
3602     return 0;
3603 }
3604
3605 static void
3606 put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
3607                   ovs_be16 out_port, struct ofpbuf **replyp)
3608 {
3609     struct nx_flow_stats *nfs;
3610     uint64_t packet_count, byte_count;
3611     size_t act_len, start_len;
3612     struct ofpbuf *reply;
3613
3614     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3615         return;
3616     }
3617
3618     query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3619
3620     act_len = sizeof *rule->actions * rule->n_actions;
3621
3622     append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
3623     start_len = (*replyp)->size;
3624     reply = *replyp;
3625
3626     nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
3627     nfs->table_id = 0;
3628     nfs->pad = 0;
3629     calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
3630     nfs->cookie = rule->flow_cookie;
3631     nfs->priority = htons(rule->cr.priority);
3632     nfs->idle_timeout = htons(rule->idle_timeout);
3633     nfs->hard_timeout = htons(rule->hard_timeout);
3634     nfs->match_len = htons(nx_put_match(reply, &rule->cr));
3635     memset(nfs->pad2, 0, sizeof nfs->pad2);
3636     nfs->packet_count = htonll(packet_count);
3637     nfs->byte_count = htonll(byte_count);
3638     if (rule->n_actions > 0) {
3639         ofpbuf_put(reply, rule->actions, act_len);
3640     }
3641     nfs->length = htons(reply->size - start_len);
3642 }
3643
3644 static int
3645 handle_nxst_flow(struct ofconn *ofconn, const struct ofp_header *oh)
3646 {
3647     struct nx_flow_stats_request *nfsr;
3648     struct cls_rule target;
3649     struct ofpbuf *reply;
3650     struct ofpbuf b;
3651     int error;
3652
3653     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3654
3655     /* Dissect the message. */
3656     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
3657     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &target);
3658     if (error) {
3659         return error;
3660     }
3661     if (b.size) {
3662         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3663     }
3664
3665     COVERAGE_INC(ofproto_flows_req);
3666     reply = start_nxstats_reply(&nfsr->nsm, 1024);
3667     if (is_valid_table(nfsr->table_id)) {
3668         struct cls_cursor cursor;
3669         struct rule *rule;
3670
3671         cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3672         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3673             put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
3674         }
3675     }
3676     queue_tx(reply, ofconn, ofconn->reply_counter);
3677
3678     return 0;
3679 }
3680
3681 static void
3682 flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
3683 {
3684     uint64_t packet_count, byte_count;
3685     size_t act_len = sizeof *rule->actions * rule->n_actions;
3686
3687     query_stats(ofproto, rule, &packet_count, &byte_count);
3688
3689     ds_put_format(results, "duration=%llds, ",
3690                   (time_msec() - rule->created) / 1000);
3691     ds_put_format(results, "priority=%u, ", rule->cr.priority);
3692     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3693     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3694     cls_rule_format(&rule->cr, results);
3695     if (act_len > 0) {
3696         ofp_print_actions(results, &rule->actions->header, act_len);
3697     } else {
3698         ds_put_cstr(results, "drop");
3699     }
3700     ds_put_cstr(results, "\n");
3701 }
3702
3703 /* Adds a pretty-printed description of all flows to 'results', including
3704  * those marked hidden by secchan (e.g., by in-band control). */
3705 void
3706 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3707 {
3708     struct cls_cursor cursor;
3709     struct rule *rule;
3710
3711     cls_cursor_init(&cursor, &p->cls, NULL);
3712     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3713         flow_stats_ds(p, rule, results);
3714     }
3715 }
3716
3717 static void
3718 query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
3719                       ovs_be16 out_port, uint8_t table_id,
3720                       struct ofp_aggregate_stats_reply *oasr)
3721 {
3722     uint64_t total_packets = 0;
3723     uint64_t total_bytes = 0;
3724     int n_flows = 0;
3725
3726     COVERAGE_INC(ofproto_agg_request);
3727
3728     if (is_valid_table(table_id)) {
3729         struct cls_cursor cursor;
3730         struct rule *rule;
3731
3732         cls_cursor_init(&cursor, &ofproto->cls, target);
3733         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3734             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
3735                 uint64_t packet_count;
3736                 uint64_t byte_count;
3737
3738                 query_stats(ofproto, rule, &packet_count, &byte_count);
3739
3740                 total_packets += packet_count;
3741                 total_bytes += byte_count;
3742                 n_flows++;
3743             }
3744         }
3745     }
3746
3747     oasr->flow_count = htonl(n_flows);
3748     oasr->packet_count = htonll(total_packets);
3749     oasr->byte_count = htonll(total_bytes);
3750     memset(oasr->pad, 0, sizeof oasr->pad);
3751 }
3752
3753 static int
3754 handle_aggregate_stats_request(struct ofconn *ofconn,
3755                                const struct ofp_header *oh)
3756 {
3757     const struct ofp_aggregate_stats_request *request = ofputil_stats_body(oh);
3758     struct ofp_aggregate_stats_reply *reply;
3759     struct cls_rule target;
3760     struct ofpbuf *msg;
3761
3762     ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
3763                                 &target);
3764
3765     msg = start_ofp_stats_reply(oh, sizeof *reply);
3766     reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
3767     query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3768                           request->table_id, reply);
3769     queue_tx(msg, ofconn, ofconn->reply_counter);
3770     return 0;
3771 }
3772
3773 static int
3774 handle_nxst_aggregate(struct ofconn *ofconn, const struct ofp_header *oh)
3775 {
3776     struct nx_aggregate_stats_request *request;
3777     struct ofp_aggregate_stats_reply *reply;
3778     struct cls_rule target;
3779     struct ofpbuf b;
3780     struct ofpbuf *buf;
3781     int error;
3782
3783     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3784
3785     /* Dissect the message. */
3786     request = ofpbuf_pull(&b, sizeof *request);
3787     error = nx_pull_match(&b, ntohs(request->match_len), 0, &target);
3788     if (error) {
3789         return error;
3790     }
3791     if (b.size) {
3792         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3793     }
3794
3795     /* Reply. */
3796     COVERAGE_INC(ofproto_flows_req);
3797     buf = start_nxstats_reply(&request->nsm, sizeof *reply);
3798     reply = ofpbuf_put_uninit(buf, sizeof *reply);
3799     query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3800                           request->table_id, reply);
3801     queue_tx(buf, ofconn, ofconn->reply_counter);
3802
3803     return 0;
3804 }
3805
3806 struct queue_stats_cbdata {
3807     struct ofconn *ofconn;
3808     struct ofport *ofport;
3809     struct ofpbuf *msg;
3810 };
3811
3812 static void
3813 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3814                 const struct netdev_queue_stats *stats)
3815 {
3816     struct ofp_queue_stats *reply;
3817
3818     reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
3819     reply->port_no = htons(cbdata->ofport->opp.port_no);
3820     memset(reply->pad, 0, sizeof reply->pad);
3821     reply->queue_id = htonl(queue_id);
3822     reply->tx_bytes = htonll(stats->tx_bytes);
3823     reply->tx_packets = htonll(stats->tx_packets);
3824     reply->tx_errors = htonll(stats->tx_errors);
3825 }
3826
3827 static void
3828 handle_queue_stats_dump_cb(uint32_t queue_id,
3829                            struct netdev_queue_stats *stats,
3830                            void *cbdata_)
3831 {
3832     struct queue_stats_cbdata *cbdata = cbdata_;
3833
3834     put_queue_stats(cbdata, queue_id, stats);
3835 }
3836
3837 static void
3838 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3839                             struct queue_stats_cbdata *cbdata)
3840 {
3841     cbdata->ofport = port;
3842     if (queue_id == OFPQ_ALL) {
3843         netdev_dump_queue_stats(port->netdev,
3844                                 handle_queue_stats_dump_cb, cbdata);
3845     } else {
3846         struct netdev_queue_stats stats;
3847
3848         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3849             put_queue_stats(cbdata, queue_id, &stats);
3850         }
3851     }
3852 }
3853
3854 static int
3855 handle_queue_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3856 {
3857     struct ofproto *ofproto = ofconn->ofproto;
3858     const struct ofp_queue_stats_request *qsr;
3859     struct queue_stats_cbdata cbdata;
3860     struct ofport *port;
3861     unsigned int port_no;
3862     uint32_t queue_id;
3863
3864     qsr = ofputil_stats_body(oh);
3865     if (!qsr) {
3866         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3867     }
3868
3869     COVERAGE_INC(ofproto_queue_req);
3870
3871     cbdata.ofconn = ofconn;
3872     cbdata.msg = start_ofp_stats_reply(oh, 128);
3873
3874     port_no = ntohs(qsr->port_no);
3875     queue_id = ntohl(qsr->queue_id);
3876     if (port_no == OFPP_ALL) {
3877         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3878             handle_queue_stats_for_port(port, queue_id, &cbdata);
3879         }
3880     } else if (port_no < ofproto->max_ports) {
3881         port = get_port(ofproto, ofp_port_to_odp_port(port_no));
3882         if (port) {
3883             handle_queue_stats_for_port(port, queue_id, &cbdata);
3884         }
3885     } else {
3886         ofpbuf_delete(cbdata.msg);
3887         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
3888     }
3889     queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
3890
3891     return 0;
3892 }
3893
3894 static long long int
3895 msec_from_nsec(uint64_t sec, uint32_t nsec)
3896 {
3897     return !sec ? 0 : sec * 1000 + nsec / 1000000;
3898 }
3899
3900 static void
3901 facet_update_time(struct ofproto *ofproto, struct facet *facet,
3902                   const struct odp_flow_stats *stats)
3903 {
3904     long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
3905     if (used > facet->used) {
3906         facet->used = used;
3907         if (used > facet->rule->used) {
3908             facet->rule->used = used;
3909         }
3910         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3911     }
3912 }
3913
3914 /* Folds the statistics from 'stats' into the counters in 'facet'.
3915  *
3916  * Because of the meaning of a facet's counters, it only makes sense to do this
3917  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3918  * packet that was sent by hand or if it represents statistics that have been
3919  * cleared out of the datapath. */
3920 static void
3921 facet_update_stats(struct ofproto *ofproto, struct facet *facet,
3922                    const struct odp_flow_stats *stats)
3923 {
3924     if (stats->n_packets) {
3925         facet_update_time(ofproto, facet, stats);
3926         facet->packet_count += stats->n_packets;
3927         facet->byte_count += stats->n_bytes;
3928         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3929     }
3930 }
3931
3932 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3933  * in which no matching flow already exists in the flow table.
3934  *
3935  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3936  * ofp_actions, to ofconn->ofproto's flow table.  Returns 0 on success or an
3937  * OpenFlow error code as encoded by ofp_mkerr() on failure.
3938  *
3939  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3940  * if any. */
3941 static int
3942 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
3943 {
3944     struct ofproto *p = ofconn->ofproto;
3945     struct ofpbuf *packet;
3946     struct rule *rule;
3947     uint16_t in_port;
3948     int error;
3949
3950     if (fm->flags & OFPFF_CHECK_OVERLAP
3951         && classifier_rule_overlaps(&p->cls, &fm->cr)) {
3952         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
3953     }
3954
3955     error = 0;
3956     if (fm->buffer_id != UINT32_MAX) {
3957         error = pktbuf_retrieve(ofconn->pktbuf, fm->buffer_id,
3958                                 &packet, &in_port);
3959     } else {
3960         packet = NULL;
3961         in_port = UINT16_MAX;
3962     }
3963
3964     rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
3965                        fm->idle_timeout, fm->hard_timeout, fm->cookie,
3966                        fm->flags & OFPFF_SEND_FLOW_REM);
3967     rule_insert(p, rule);
3968     if (packet) {
3969         rule_execute(p, rule, in_port, packet);
3970     }
3971     return error;
3972 }
3973
3974 static struct rule *
3975 find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
3976 {
3977     return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
3978 }
3979
3980 static int
3981 send_buffered_packet(struct ofconn *ofconn,
3982                      struct rule *rule, uint32_t buffer_id)
3983 {
3984     struct ofpbuf *packet;
3985     uint16_t in_port;
3986     int error;
3987
3988     if (buffer_id == UINT32_MAX) {
3989         return 0;
3990     }
3991
3992     error = pktbuf_retrieve(ofconn->pktbuf, buffer_id, &packet, &in_port);
3993     if (error) {
3994         return error;
3995     }
3996
3997     rule_execute(ofconn->ofproto, rule, in_port, packet);
3998
3999     return 0;
4000 }
4001 \f
4002 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4003
4004 struct modify_flows_cbdata {
4005     struct ofproto *ofproto;
4006     const struct flow_mod *fm;
4007     struct rule *match;
4008 };
4009
4010 static int modify_flow(struct ofproto *, const struct flow_mod *,
4011                        struct rule *);
4012
4013 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
4014  * encoded by ofp_mkerr() on failure.
4015  *
4016  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4017  * if any. */
4018 static int
4019 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
4020 {
4021     struct ofproto *p = ofconn->ofproto;
4022     struct rule *match = NULL;
4023     struct cls_cursor cursor;
4024     struct rule *rule;
4025
4026     cls_cursor_init(&cursor, &p->cls, &fm->cr);
4027     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4028         if (!rule_is_hidden(rule)) {
4029             match = rule;
4030             modify_flow(p, fm, rule);
4031         }
4032     }
4033
4034     if (match) {
4035         /* This credits the packet to whichever flow happened to match last.
4036          * That's weird.  Maybe we should do a lookup for the flow that
4037          * actually matches the packet?  Who knows. */
4038         send_buffered_packet(ofconn, match, fm->buffer_id);
4039         return 0;
4040     } else {
4041         return add_flow(ofconn, fm);
4042     }
4043 }
4044
4045 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
4046  * code as encoded by ofp_mkerr() on failure.
4047  *
4048  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4049  * if any. */
4050 static int
4051 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
4052 {
4053     struct ofproto *p = ofconn->ofproto;
4054     struct rule *rule = find_flow_strict(p, fm);
4055     if (rule && !rule_is_hidden(rule)) {
4056         modify_flow(p, fm, rule);
4057         return send_buffered_packet(ofconn, rule, fm->buffer_id);
4058     } else {
4059         return add_flow(ofconn, fm);
4060     }
4061 }
4062
4063 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
4064  * been identified as a flow in 'p''s flow table to be modified, by changing
4065  * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
4066  * ofp_action[] structures). */
4067 static int
4068 modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
4069 {
4070     size_t actions_len = fm->n_actions * sizeof *rule->actions;
4071
4072     rule->flow_cookie = fm->cookie;
4073
4074     /* If the actions are the same, do nothing. */
4075     if (fm->n_actions == rule->n_actions
4076         && (!fm->n_actions
4077             || !memcmp(fm->actions, rule->actions, actions_len))) {
4078         return 0;
4079     }
4080
4081     /* Replace actions. */
4082     free(rule->actions);
4083     rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
4084     rule->n_actions = fm->n_actions;
4085
4086     p->need_revalidate = true;
4087
4088     return 0;
4089 }
4090 \f
4091 /* OFPFC_DELETE implementation. */
4092
4093 static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
4094
4095 /* Implements OFPFC_DELETE. */
4096 static void
4097 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
4098 {
4099     struct rule *rule, *next_rule;
4100     struct cls_cursor cursor;
4101
4102     cls_cursor_init(&cursor, &p->cls, &fm->cr);
4103     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4104         delete_flow(p, rule, htons(fm->out_port));
4105     }
4106 }
4107
4108 /* Implements OFPFC_DELETE_STRICT. */
4109 static void
4110 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
4111 {
4112     struct rule *rule = find_flow_strict(p, fm);
4113     if (rule) {
4114         delete_flow(p, rule, htons(fm->out_port));
4115     }
4116 }
4117
4118 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
4119  * been identified as a flow to delete from 'p''s flow table, by deleting the
4120  * flow and sending out a OFPT_FLOW_REMOVED message to any interested
4121  * controller.
4122  *
4123  * Will not delete 'rule' if it is hidden.  Will delete 'rule' only if
4124  * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
4125  * specified 'out_port'. */
4126 static void
4127 delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
4128 {
4129     if (rule_is_hidden(rule)) {
4130         return;
4131     }
4132
4133     if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
4134         return;
4135     }
4136
4137     rule_send_removed(p, rule, OFPRR_DELETE);
4138     rule_remove(p, rule);
4139 }
4140 \f
4141 static int
4142 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4143 {
4144     struct ofproto *p = ofconn->ofproto;
4145     struct flow_mod fm;
4146     int error;
4147
4148     error = reject_slave_controller(ofconn, "flow_mod");
4149     if (error) {
4150         return error;
4151     }
4152
4153     error = ofputil_decode_flow_mod(&fm, oh, ofconn->flow_format);
4154     if (error) {
4155         return error;
4156     }
4157
4158     /* We do not support the emergency flow cache.  It will hopefully get
4159      * dropped from OpenFlow in the near future. */
4160     if (fm.flags & OFPFF_EMERG) {
4161         /* There isn't a good fit for an error code, so just state that the
4162          * flow table is full. */
4163         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
4164     }
4165
4166     error = validate_actions(fm.actions, fm.n_actions,
4167                              &fm.cr.flow, p->max_ports);
4168     if (error) {
4169         return error;
4170     }
4171
4172     switch (fm.command) {
4173     case OFPFC_ADD:
4174         return add_flow(ofconn, &fm);
4175
4176     case OFPFC_MODIFY:
4177         return modify_flows_loose(ofconn, &fm);
4178
4179     case OFPFC_MODIFY_STRICT:
4180         return modify_flow_strict(ofconn, &fm);
4181
4182     case OFPFC_DELETE:
4183         delete_flows_loose(p, &fm);
4184         return 0;
4185
4186     case OFPFC_DELETE_STRICT:
4187         delete_flow_strict(p, &fm);
4188         return 0;
4189
4190     default:
4191         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
4192     }
4193 }
4194
4195 static int
4196 handle_tun_id_from_cookie(struct ofconn *ofconn, const struct ofp_header *oh)
4197 {
4198     const struct nxt_tun_id_cookie *msg
4199         = (const struct nxt_tun_id_cookie *) oh;
4200
4201     ofconn->flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
4202     return 0;
4203 }
4204
4205 static int
4206 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4207 {
4208     struct nx_role_request *nrr = (struct nx_role_request *) oh;
4209     struct nx_role_request *reply;
4210     struct ofpbuf *buf;
4211     uint32_t role;
4212
4213     if (ofconn->type != OFCONN_PRIMARY) {
4214         VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
4215                      "connection");
4216         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4217     }
4218
4219     role = ntohl(nrr->role);
4220     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
4221         && role != NX_ROLE_SLAVE) {
4222         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
4223
4224         /* There's no good error code for this. */
4225         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
4226     }
4227
4228     if (role == NX_ROLE_MASTER) {
4229         struct ofconn *other;
4230
4231         HMAP_FOR_EACH (other, hmap_node, &ofconn->ofproto->controllers) {
4232             if (other->role == NX_ROLE_MASTER) {
4233                 other->role = NX_ROLE_SLAVE;
4234             }
4235         }
4236     }
4237     ofconn->role = role;
4238
4239     reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
4240     reply->role = htonl(role);
4241     queue_tx(buf, ofconn, ofconn->reply_counter);
4242
4243     return 0;
4244 }
4245
4246 static int
4247 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4248 {
4249     const struct nxt_set_flow_format *msg
4250         = (const struct nxt_set_flow_format *) oh;
4251     uint32_t format;
4252
4253     format = ntohl(msg->format);
4254     if (format == NXFF_OPENFLOW10
4255         || format == NXFF_TUN_ID_FROM_COOKIE
4256         || format == NXFF_NXM) {
4257         ofconn->flow_format = format;
4258         return 0;
4259     } else {
4260         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4261     }
4262 }
4263
4264 static int
4265 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4266 {
4267     struct ofp_header *ob;
4268     struct ofpbuf *buf;
4269
4270     /* Currently, everything executes synchronously, so we can just
4271      * immediately send the barrier reply. */
4272     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
4273     queue_tx(buf, ofconn, ofconn->reply_counter);
4274     return 0;
4275 }
4276
4277 static int
4278 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4279 {
4280     const struct ofp_header *oh = msg->data;
4281     const struct ofputil_msg_type *type;
4282     int error;
4283
4284     error = ofputil_decode_msg_type(oh, &type);
4285     if (error) {
4286         return error;
4287     }
4288
4289     switch (ofputil_msg_type_code(type)) {
4290         /* OpenFlow requests. */
4291     case OFPUTIL_OFPT_ECHO_REQUEST:
4292         return handle_echo_request(ofconn, oh);
4293
4294     case OFPUTIL_OFPT_FEATURES_REQUEST:
4295         return handle_features_request(ofconn, oh);
4296
4297     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
4298         return handle_get_config_request(ofconn, oh);
4299
4300     case OFPUTIL_OFPT_SET_CONFIG:
4301         return handle_set_config(ofconn, msg->data);
4302
4303     case OFPUTIL_OFPT_PACKET_OUT:
4304         return handle_packet_out(ofconn, oh);
4305
4306     case OFPUTIL_OFPT_PORT_MOD:
4307         return handle_port_mod(ofconn, oh);
4308
4309     case OFPUTIL_OFPT_FLOW_MOD:
4310         return handle_flow_mod(ofconn, oh);
4311
4312     case OFPUTIL_OFPT_BARRIER_REQUEST:
4313         return handle_barrier_request(ofconn, oh);
4314
4315         /* OpenFlow replies. */
4316     case OFPUTIL_OFPT_ECHO_REPLY:
4317         return 0;
4318
4319         /* Nicira extension requests. */
4320     case OFPUTIL_NXT_STATUS_REQUEST:
4321         return switch_status_handle_request(
4322             ofconn->ofproto->switch_status, ofconn->rconn, oh);
4323
4324     case OFPUTIL_NXT_TUN_ID_FROM_COOKIE:
4325         return handle_tun_id_from_cookie(ofconn, oh);
4326
4327     case OFPUTIL_NXT_ROLE_REQUEST:
4328         return handle_role_request(ofconn, oh);
4329
4330     case OFPUTIL_NXT_SET_FLOW_FORMAT:
4331         return handle_nxt_set_flow_format(ofconn, oh);
4332
4333     case OFPUTIL_NXT_FLOW_MOD:
4334         return handle_flow_mod(ofconn, oh);
4335
4336         /* OpenFlow statistics requests. */
4337     case OFPUTIL_OFPST_DESC_REQUEST:
4338         return handle_desc_stats_request(ofconn, oh);
4339
4340     case OFPUTIL_OFPST_FLOW_REQUEST:
4341         return handle_flow_stats_request(ofconn, oh);
4342
4343     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
4344         return handle_aggregate_stats_request(ofconn, oh);
4345
4346     case OFPUTIL_OFPST_TABLE_REQUEST:
4347         return handle_table_stats_request(ofconn, oh);
4348
4349     case OFPUTIL_OFPST_PORT_REQUEST:
4350         return handle_port_stats_request(ofconn, oh);
4351
4352     case OFPUTIL_OFPST_QUEUE_REQUEST:
4353         return handle_queue_stats_request(ofconn, oh);
4354
4355         /* Nicira extension statistics requests. */
4356     case OFPUTIL_NXST_FLOW_REQUEST:
4357         return handle_nxst_flow(ofconn, oh);
4358
4359     case OFPUTIL_NXST_AGGREGATE_REQUEST:
4360         return handle_nxst_aggregate(ofconn, oh);
4361
4362     case OFPUTIL_INVALID:
4363     case OFPUTIL_OFPT_HELLO:
4364     case OFPUTIL_OFPT_ERROR:
4365     case OFPUTIL_OFPT_FEATURES_REPLY:
4366     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
4367     case OFPUTIL_OFPT_PACKET_IN:
4368     case OFPUTIL_OFPT_FLOW_REMOVED:
4369     case OFPUTIL_OFPT_PORT_STATUS:
4370     case OFPUTIL_OFPT_BARRIER_REPLY:
4371     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
4372     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
4373     case OFPUTIL_OFPST_DESC_REPLY:
4374     case OFPUTIL_OFPST_FLOW_REPLY:
4375     case OFPUTIL_OFPST_QUEUE_REPLY:
4376     case OFPUTIL_OFPST_PORT_REPLY:
4377     case OFPUTIL_OFPST_TABLE_REPLY:
4378     case OFPUTIL_OFPST_AGGREGATE_REPLY:
4379     case OFPUTIL_NXT_STATUS_REPLY:
4380     case OFPUTIL_NXT_ROLE_REPLY:
4381     case OFPUTIL_NXT_FLOW_REMOVED:
4382     case OFPUTIL_NXST_FLOW_REPLY:
4383     case OFPUTIL_NXST_AGGREGATE_REPLY:
4384     default:
4385         if (VLOG_IS_WARN_ENABLED()) {
4386             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
4387             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
4388             free(s);
4389         }
4390         if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
4391             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
4392         } else {
4393             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
4394         }
4395     }
4396 }
4397
4398 static void
4399 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4400 {
4401     int error = handle_openflow__(ofconn, ofp_msg);
4402     if (error) {
4403         send_error_oh(ofconn, ofp_msg->data, error);
4404     }
4405     COVERAGE_INC(ofproto_recv_openflow);
4406 }
4407 \f
4408 static void
4409 handle_miss_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4410 {
4411     struct facet *facet;
4412     struct flow flow;
4413
4414     /* Obtain in_port and tun_id, at least. */
4415     odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4416
4417     /* Set header pointers in 'flow'. */
4418     flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
4419
4420     /* Check with in-band control to see if this packet should be sent
4421      * to the local port regardless of the flow table. */
4422     if (in_band_msg_in_hook(p->in_band, &flow, upcall->packet)) {
4423         struct ofpbuf odp_actions;
4424
4425         ofpbuf_init(&odp_actions, 32);
4426         nl_msg_put_u32(&odp_actions, ODPAT_OUTPUT, ODPP_LOCAL);
4427         dpif_execute(p->dpif, odp_actions.data, odp_actions.size,
4428                      upcall->packet);
4429         ofpbuf_uninit(&odp_actions);
4430     }
4431
4432     facet = facet_lookup_valid(p, &flow);
4433     if (!facet) {
4434         struct rule *rule = rule_lookup(p, &flow);
4435         if (!rule) {
4436             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
4437             struct ofport *port = get_port(p, flow.in_port);
4438             if (port) {
4439                 if (port->opp.config & OFPPC_NO_PACKET_IN) {
4440                     COVERAGE_INC(ofproto_no_packet_in);
4441                     /* XXX install 'drop' flow entry */
4442                     ofpbuf_delete(upcall->packet);
4443                     return;
4444                 }
4445             } else {
4446                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
4447                              flow.in_port);
4448             }
4449
4450             COVERAGE_INC(ofproto_packet_in);
4451             send_packet_in(p, upcall, &flow, false);
4452             return;
4453         }
4454
4455         facet = facet_create(p, rule, &flow, upcall->packet);
4456     } else if (!facet->may_install) {
4457         /* The facet is not installable, that is, we need to process every
4458          * packet, so process the current packet's actions into 'facet'. */
4459         facet_make_actions(p, facet, upcall->packet);
4460     }
4461
4462     if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
4463         /*
4464          * Extra-special case for fail-open mode.
4465          *
4466          * We are in fail-open mode and the packet matched the fail-open rule,
4467          * but we are connected to a controller too.  We should send the packet
4468          * up to the controller in the hope that it will try to set up a flow
4469          * and thereby allow us to exit fail-open.
4470          *
4471          * See the top-level comment in fail-open.c for more information.
4472          */
4473         send_packet_in(p, upcall, &flow, true);
4474     }
4475
4476     facet_execute(p, facet, upcall->packet);
4477     facet_install(p, facet, false);
4478 }
4479
4480 static void
4481 handle_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4482 {
4483     struct flow flow;
4484
4485     switch (upcall->type) {
4486     case _ODPL_ACTION_NR:
4487         COVERAGE_INC(ofproto_ctlr_action);
4488         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4489         send_packet_in(p, upcall, &flow, false);
4490         break;
4491
4492     case _ODPL_SFLOW_NR:
4493         if (p->sflow) {
4494             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4495             ofproto_sflow_received(p->sflow, upcall, &flow);
4496         }
4497         ofpbuf_delete(upcall->packet);
4498         break;
4499
4500     case _ODPL_MISS_NR:
4501         handle_miss_upcall(p, upcall);
4502         break;
4503
4504     default:
4505         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
4506         break;
4507     }
4508 }
4509 \f
4510 /* Flow expiration. */
4511
4512 static int ofproto_dp_max_idle(const struct ofproto *);
4513 static void ofproto_update_used(struct ofproto *);
4514 static void rule_expire(struct ofproto *, struct rule *);
4515 static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
4516
4517 /* This function is called periodically by ofproto_run().  Its job is to
4518  * collect updates for the flows that have been installed into the datapath,
4519  * most importantly when they last were used, and then use that information to
4520  * expire flows that have not been used recently.
4521  *
4522  * Returns the number of milliseconds after which it should be called again. */
4523 static int
4524 ofproto_expire(struct ofproto *ofproto)
4525 {
4526     struct rule *rule, *next_rule;
4527     struct cls_cursor cursor;
4528     int dp_max_idle;
4529
4530     /* Update 'used' for each flow in the datapath. */
4531     ofproto_update_used(ofproto);
4532
4533     /* Expire facets that have been idle too long. */
4534     dp_max_idle = ofproto_dp_max_idle(ofproto);
4535     ofproto_expire_facets(ofproto, dp_max_idle);
4536
4537     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
4538     cls_cursor_init(&cursor, &ofproto->cls, NULL);
4539     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4540         rule_expire(ofproto, rule);
4541     }
4542
4543     /* Let the hook know that we're at a stable point: all outstanding data
4544      * in existing flows has been accounted to the account_cb.  Thus, the
4545      * hook can now reasonably do operations that depend on having accurate
4546      * flow volume accounting (currently, that's just bond rebalancing). */
4547     if (ofproto->ofhooks->account_checkpoint_cb) {
4548         ofproto->ofhooks->account_checkpoint_cb(ofproto->aux);
4549     }
4550
4551     return MIN(dp_max_idle, 1000);
4552 }
4553
4554 /* Update 'used' member of installed facets. */
4555 static void
4556 ofproto_update_used(struct ofproto *p)
4557 {
4558     struct dpif_flow_dump dump;
4559
4560     dpif_flow_dump_start(&dump, p->dpif);
4561     for (;;) {
4562         uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
4563         struct facet *facet;
4564         struct odp_flow f;
4565         struct flow flow;
4566
4567         memset(&f, 0, sizeof f);
4568         f.key = (struct nlattr *) keybuf;
4569         f.key_len = sizeof keybuf;
4570         if (!dpif_flow_dump_next(&dump, &f)) {
4571             break;
4572         }
4573
4574         if (f.key_len > sizeof keybuf) {
4575             VLOG_WARN_RL(&rl, "ODP flow key overflowed buffer");
4576             continue;
4577         }
4578         if (odp_flow_key_to_flow(f.key, f.key_len, &flow)) {
4579             struct ds s;
4580
4581             ds_init(&s);
4582             odp_flow_key_format(f.key, f.key_len, &s);
4583             VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
4584                          ds_cstr(&s));
4585             ds_destroy(&s);
4586
4587             continue;
4588         }
4589         facet = facet_find(p, &flow);
4590
4591         if (facet && facet->installed) {
4592             facet_update_time(p, facet, &f.stats);
4593             facet_account(p, facet, f.stats.n_bytes);
4594         } else {
4595             /* There's a flow in the datapath that we know nothing about.
4596              * Delete it. */
4597             COVERAGE_INC(ofproto_unexpected_rule);
4598             dpif_flow_del(p->dpif, &f);
4599         }
4600     }
4601     dpif_flow_dump_done(&dump);
4602 }
4603
4604 /* Calculates and returns the number of milliseconds of idle time after which
4605  * facets should expire from the datapath and we should fold their statistics
4606  * into their parent rules in userspace. */
4607 static int
4608 ofproto_dp_max_idle(const struct ofproto *ofproto)
4609 {
4610     /*
4611      * Idle time histogram.
4612      *
4613      * Most of the time a switch has a relatively small number of facets.  When
4614      * this is the case we might as well keep statistics for all of them in
4615      * userspace and to cache them in the kernel datapath for performance as
4616      * well.
4617      *
4618      * As the number of facets increases, the memory required to maintain
4619      * statistics about them in userspace and in the kernel becomes
4620      * significant.  However, with a large number of facets it is likely that
4621      * only a few of them are "heavy hitters" that consume a large amount of
4622      * bandwidth.  At this point, only heavy hitters are worth caching in the
4623      * kernel and maintaining in userspaces; other facets we can discard.
4624      *
4625      * The technique used to compute the idle time is to build a histogram with
4626      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each facet
4627      * that is installed in the kernel gets dropped in the appropriate bucket.
4628      * After the histogram has been built, we compute the cutoff so that only
4629      * the most-recently-used 1% of facets (but at least 1000 flows) are kept
4630      * cached.  At least the most-recently-used bucket of facets is kept, so
4631      * actually an arbitrary number of facets can be kept in any given
4632      * expiration run (though the next run will delete most of those unless
4633      * they receive additional data).
4634      *
4635      * This requires a second pass through the facets, in addition to the pass
4636      * made by ofproto_update_used(), because the former function never looks
4637      * at uninstallable facets.
4638      */
4639     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4640     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4641     int buckets[N_BUCKETS] = { 0 };
4642     struct facet *facet;
4643     int total, bucket;
4644     long long int now;
4645     int i;
4646
4647     total = hmap_count(&ofproto->facets);
4648     if (total <= 1000) {
4649         return N_BUCKETS * BUCKET_WIDTH;
4650     }
4651
4652     /* Build histogram. */
4653     now = time_msec();
4654     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
4655         long long int idle = now - facet->used;
4656         int bucket = (idle <= 0 ? 0
4657                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4658                       : (unsigned int) idle / BUCKET_WIDTH);
4659         buckets[bucket]++;
4660     }
4661
4662     /* Find the first bucket whose flows should be expired. */
4663     for (bucket = 0; bucket < N_BUCKETS; bucket++) {
4664         if (buckets[bucket]) {
4665             int subtotal = 0;
4666             do {
4667                 subtotal += buckets[bucket++];
4668             } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
4669             break;
4670         }
4671     }
4672
4673     if (VLOG_IS_DBG_ENABLED()) {
4674         struct ds s;
4675
4676         ds_init(&s);
4677         ds_put_cstr(&s, "keep");
4678         for (i = 0; i < N_BUCKETS; i++) {
4679             if (i == bucket) {
4680                 ds_put_cstr(&s, ", drop");
4681             }
4682             if (buckets[i]) {
4683                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4684             }
4685         }
4686         VLOG_INFO("%s: %s (msec:count)",
4687                   dpif_name(ofproto->dpif), ds_cstr(&s));
4688         ds_destroy(&s);
4689     }
4690
4691     return bucket * BUCKET_WIDTH;
4692 }
4693
4694 static void
4695 facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
4696 {
4697     if (ofproto->netflow && !facet_is_controller_flow(facet) &&
4698         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
4699         struct ofexpired expired;
4700         struct odp_flow odp_flow;
4701
4702         /* Get updated flow stats.
4703          *
4704          * XXX We could avoid this call entirely if (1) ofproto_update_used()
4705          * updated TCP flags and (2) the dpif_flow_list_all() in
4706          * ofproto_update_used() zeroed TCP flags. */
4707         memset(&odp_flow, 0, sizeof odp_flow);
4708         if (facet->installed) {
4709             uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
4710             struct ofpbuf key;
4711
4712             ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
4713             odp_flow_key_from_flow(&key, &facet->flow);
4714
4715             odp_flow.key = key.data;
4716             odp_flow.key_len = key.size;
4717             odp_flow.flags = ODPFF_ZERO_TCP_FLAGS;
4718             dpif_flow_get(ofproto->dpif, &odp_flow);
4719
4720             if (odp_flow.stats.n_packets) {
4721                 facet_update_time(ofproto, facet, &odp_flow.stats);
4722                 netflow_flow_update_flags(&facet->nf_flow,
4723                                           odp_flow.stats.tcp_flags);
4724             }
4725         }
4726
4727         expired.flow = facet->flow;
4728         expired.packet_count = facet->packet_count +
4729                                odp_flow.stats.n_packets;
4730         expired.byte_count = facet->byte_count + odp_flow.stats.n_bytes;
4731         expired.used = facet->used;
4732
4733         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4734     }
4735 }
4736
4737 static void
4738 ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
4739 {
4740     long long int cutoff = time_msec() - dp_max_idle;
4741     struct facet *facet, *next_facet;
4742
4743     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
4744         facet_active_timeout(ofproto, facet);
4745         if (facet->used < cutoff) {
4746             facet_remove(ofproto, facet);
4747         }
4748     }
4749 }
4750
4751 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4752  * then delete it entirely. */
4753 static void
4754 rule_expire(struct ofproto *ofproto, struct rule *rule)
4755 {
4756     struct facet *facet, *next_facet;
4757     long long int now;
4758     uint8_t reason;
4759
4760     /* Has 'rule' expired? */
4761     now = time_msec();
4762     if (rule->hard_timeout
4763         && now > rule->created + rule->hard_timeout * 1000) {
4764         reason = OFPRR_HARD_TIMEOUT;
4765     } else if (rule->idle_timeout && list_is_empty(&rule->facets)
4766                && now >rule->used + rule->idle_timeout * 1000) {
4767         reason = OFPRR_IDLE_TIMEOUT;
4768     } else {
4769         return;
4770     }
4771
4772     COVERAGE_INC(ofproto_expired);
4773
4774     /* Update stats.  (This is a no-op if the rule expired due to an idle
4775      * timeout, because that only happens when the rule has no facets left.) */
4776     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4777         facet_remove(ofproto, facet);
4778     }
4779
4780     /* Get rid of the rule. */
4781     if (!rule_is_hidden(rule)) {
4782         rule_send_removed(ofproto, rule, reason);
4783     }
4784     rule_remove(ofproto, rule);
4785 }
4786 \f
4787 static struct ofpbuf *
4788 compose_ofp_flow_removed(struct ofconn *ofconn, const struct rule *rule,
4789                          uint8_t reason)
4790 {
4791     struct ofp_flow_removed *ofr;
4792     struct ofpbuf *buf;
4793
4794     ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0), &buf);
4795     ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofr->match,
4796                               rule->flow_cookie, &ofr->cookie);
4797     ofr->priority = htons(rule->cr.priority);
4798     ofr->reason = reason;
4799     calc_flow_duration(rule->created, &ofr->duration_sec, &ofr->duration_nsec);
4800     ofr->idle_timeout = htons(rule->idle_timeout);
4801     ofr->packet_count = htonll(rule->packet_count);
4802     ofr->byte_count = htonll(rule->byte_count);
4803
4804     return buf;
4805 }
4806
4807 static struct ofpbuf *
4808 compose_nx_flow_removed(const struct rule *rule, uint8_t reason)
4809 {
4810     struct nx_flow_removed *nfr;
4811     struct ofpbuf *buf;
4812     int match_len;
4813
4814     make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &buf);
4815     match_len = nx_put_match(buf, &rule->cr);
4816
4817     nfr = buf->data;
4818     nfr->cookie = rule->flow_cookie;
4819     nfr->priority = htons(rule->cr.priority);
4820     nfr->reason = reason;
4821     calc_flow_duration(rule->created, &nfr->duration_sec, &nfr->duration_nsec);
4822     nfr->idle_timeout = htons(rule->idle_timeout);
4823     nfr->match_len = htons(match_len);
4824     nfr->packet_count = htonll(rule->packet_count);
4825     nfr->byte_count = htonll(rule->byte_count);
4826
4827     return buf;
4828 }
4829
4830 static void
4831 rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
4832 {
4833     struct ofconn *ofconn;
4834
4835     if (!rule->send_flow_removed) {
4836         return;
4837     }
4838
4839     LIST_FOR_EACH (ofconn, node, &p->all_conns) {
4840         struct ofpbuf *msg;
4841
4842         if (!rconn_is_connected(ofconn->rconn)
4843             || !ofconn_receives_async_msgs(ofconn)) {
4844             continue;
4845         }
4846
4847         msg = (ofconn->flow_format == NXFF_NXM
4848                ? compose_nx_flow_removed(rule, reason)
4849                : compose_ofp_flow_removed(ofconn, rule, reason));
4850
4851         /* Account flow expirations under ofconn->reply_counter, the counter
4852          * for replies to OpenFlow requests.  That works because preventing
4853          * OpenFlow requests from being processed also prevents new flows from
4854          * being added (and expiring).  (It also prevents processing OpenFlow
4855          * requests that would not add new flows, so it is imperfect.) */
4856         queue_tx(msg, ofconn, ofconn->reply_counter);
4857     }
4858 }
4859
4860 /* pinsched callback for sending 'ofp_packet_in' on 'ofconn'. */
4861 static void
4862 do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn_)
4863 {
4864     struct ofconn *ofconn = ofconn_;
4865
4866     rconn_send_with_limit(ofconn->rconn, ofp_packet_in,
4867                           ofconn->packet_in_counter, 100);
4868 }
4869
4870 /* Takes 'upcall', whose packet has the flow specified by 'flow', composes an
4871  * OpenFlow packet-in message from it, and passes it to 'ofconn''s packet
4872  * scheduler for sending.
4873  *
4874  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
4875  * Otherwise, ownership is transferred to this function. */
4876 static void
4877 schedule_packet_in(struct ofconn *ofconn, struct dpif_upcall *upcall,
4878                    const struct flow *flow, bool clone)
4879 {
4880     enum { OPI_SIZE = offsetof(struct ofp_packet_in, data) };
4881     struct ofproto *ofproto = ofconn->ofproto;
4882     struct ofp_packet_in *opi;
4883     int total_len, send_len;
4884     struct ofpbuf *packet;
4885     uint32_t buffer_id;
4886
4887     /* Get OpenFlow buffer_id. */
4888     if (upcall->type == _ODPL_ACTION_NR) {
4889         buffer_id = UINT32_MAX;
4890     } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
4891         buffer_id = pktbuf_get_null();
4892     } else if (!ofconn->pktbuf) {
4893         buffer_id = UINT32_MAX;
4894     } else {
4895         buffer_id = pktbuf_save(ofconn->pktbuf, upcall->packet, flow->in_port);
4896     }
4897
4898     /* Figure out how much of the packet to send. */
4899     total_len = send_len = upcall->packet->size;
4900     if (buffer_id != UINT32_MAX) {
4901         send_len = MIN(send_len, ofconn->miss_send_len);
4902     }
4903     if (upcall->type == _ODPL_ACTION_NR) {
4904         send_len = MIN(send_len, upcall->userdata);
4905     }
4906
4907     /* Copy or steal buffer for OFPT_PACKET_IN. */
4908     if (clone) {
4909         packet = ofpbuf_clone_data_with_headroom(upcall->packet->data,
4910                                                  send_len, OPI_SIZE);
4911     } else {
4912         packet = upcall->packet;
4913         packet->size = send_len;
4914     }
4915
4916     /* Add OFPT_PACKET_IN. */
4917     opi = ofpbuf_push_zeros(packet, OPI_SIZE);
4918     opi->header.version = OFP_VERSION;
4919     opi->header.type = OFPT_PACKET_IN;
4920     opi->total_len = htons(total_len);
4921     opi->in_port = htons(odp_port_to_ofp_port(flow->in_port));
4922     opi->reason = upcall->type == _ODPL_MISS_NR ? OFPR_NO_MATCH : OFPR_ACTION;
4923     opi->buffer_id = htonl(buffer_id);
4924     update_openflow_length(packet);
4925
4926     /* Hand over to packet scheduler.  It might immediately call into
4927      * do_send_packet_in() or it might buffer it for a while (until a later
4928      * call to pinsched_run()). */
4929     pinsched_send(ofconn->schedulers[opi->reason], flow->in_port,
4930                   packet, do_send_packet_in, ofconn);
4931 }
4932
4933 /* Given 'upcall', of type _ODPL_ACTION_NR or _ODPL_MISS_NR, sends an
4934  * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
4935  * their individual configurations.
4936  *
4937  * Takes ownership of 'packet'. */
4938 static void
4939 send_packet_in(struct ofproto *ofproto, struct dpif_upcall *upcall,
4940                const struct flow *flow, bool clone)
4941 {
4942     struct ofconn *ofconn, *prev;
4943
4944     prev = NULL;
4945     LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
4946         if (ofconn_receives_async_msgs(ofconn)) {
4947             if (prev) {
4948                 schedule_packet_in(prev, upcall, flow, true);
4949             }
4950             prev = ofconn;
4951         }
4952     }
4953     if (prev) {
4954         schedule_packet_in(prev, upcall, flow, clone);
4955     } else if (!clone) {
4956         ofpbuf_delete(upcall->packet);
4957     }
4958 }
4959
4960 static uint64_t
4961 pick_datapath_id(const struct ofproto *ofproto)
4962 {
4963     const struct ofport *port;
4964
4965     port = get_port(ofproto, ODPP_LOCAL);
4966     if (port) {
4967         uint8_t ea[ETH_ADDR_LEN];
4968         int error;
4969
4970         error = netdev_get_etheraddr(port->netdev, ea);
4971         if (!error) {
4972             return eth_addr_to_uint64(ea);
4973         }
4974         VLOG_WARN("could not get MAC address for %s (%s)",
4975                   netdev_get_name(port->netdev), strerror(error));
4976     }
4977     return ofproto->fallback_dpid;
4978 }
4979
4980 static uint64_t
4981 pick_fallback_dpid(void)
4982 {
4983     uint8_t ea[ETH_ADDR_LEN];
4984     eth_addr_nicira_random(ea);
4985     return eth_addr_to_uint64(ea);
4986 }
4987 \f
4988 static void
4989 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
4990                      void *aux OVS_UNUSED)
4991 {
4992     const struct shash_node *node;
4993     struct ds results;
4994
4995     ds_init(&results);
4996     SHASH_FOR_EACH (node, &all_ofprotos) {
4997         ds_put_format(&results, "%s\n", node->name);
4998     }
4999     unixctl_command_reply(conn, 200, ds_cstr(&results));
5000     ds_destroy(&results);
5001 }
5002
5003 struct ofproto_trace {
5004     struct action_xlate_ctx ctx;
5005     struct flow flow;
5006     struct ds *result;
5007 };
5008
5009 static void
5010 trace_format_rule(struct ds *result, int level, const struct rule *rule)
5011 {
5012     ds_put_char_multiple(result, '\t', level);
5013     if (!rule) {
5014         ds_put_cstr(result, "No match\n");
5015         return;
5016     }
5017
5018     ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
5019                   ntohll(rule->flow_cookie));
5020     cls_rule_format(&rule->cr, result);
5021     ds_put_char(result, '\n');
5022
5023     ds_put_char_multiple(result, '\t', level);
5024     ds_put_cstr(result, "OpenFlow ");
5025     ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
5026                       rule->n_actions * sizeof *rule->actions);
5027     ds_put_char(result, '\n');
5028 }
5029
5030 static void
5031 trace_format_flow(struct ds *result, int level, const char *title,
5032                  struct ofproto_trace *trace)
5033 {
5034     ds_put_char_multiple(result, '\t', level);
5035     ds_put_format(result, "%s: ", title);
5036     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5037         ds_put_cstr(result, "unchanged");
5038     } else {
5039         flow_format(result, &trace->ctx.flow);
5040         trace->flow = trace->ctx.flow;
5041     }
5042     ds_put_char(result, '\n');
5043 }
5044
5045 static void
5046 trace_resubmit(struct action_xlate_ctx *ctx, const struct rule *rule)
5047 {
5048     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5049     struct ds *result = trace->result;
5050
5051     ds_put_char(result, '\n');
5052     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5053     trace_format_rule(result, ctx->recurse + 1, rule);
5054 }
5055
5056 static void
5057 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5058                       void *aux OVS_UNUSED)
5059 {
5060     char *dpname, *in_port_s, *tun_id_s, *packet_s;
5061     char *args = xstrdup(args_);
5062     char *save_ptr = NULL;
5063     struct ofproto *ofproto;
5064     struct ofpbuf packet;
5065     struct rule *rule;
5066     struct ds result;
5067     struct flow flow;
5068     uint16_t in_port;
5069     ovs_be64 tun_id;
5070     char *s;
5071
5072     ofpbuf_init(&packet, strlen(args) / 2);
5073     ds_init(&result);
5074
5075     dpname = strtok_r(args, " ", &save_ptr);
5076     tun_id_s = strtok_r(NULL, " ", &save_ptr);
5077     in_port_s = strtok_r(NULL, " ", &save_ptr);
5078     packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5079     if (!dpname || !in_port_s || !packet_s) {
5080         unixctl_command_reply(conn, 501, "Bad command syntax");
5081         goto exit;
5082     }
5083
5084     ofproto = shash_find_data(&all_ofprotos, dpname);
5085     if (!ofproto) {
5086         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5087                               "for help)");
5088         goto exit;
5089     }
5090
5091     tun_id = htonll(strtoull(tun_id_s, NULL, 10));
5092     in_port = ofp_port_to_odp_port(atoi(in_port_s));
5093
5094     packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
5095     packet_s += strspn(packet_s, " ");
5096     if (*packet_s != '\0') {
5097         unixctl_command_reply(conn, 501, "Trailing garbage in command");
5098         goto exit;
5099     }
5100     if (packet.size < ETH_HEADER_LEN) {
5101         unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
5102         goto exit;
5103     }
5104
5105     ds_put_cstr(&result, "Packet: ");
5106     s = ofp_packet_to_string(packet.data, packet.size, packet.size);
5107     ds_put_cstr(&result, s);
5108     free(s);
5109
5110     flow_extract(&packet, tun_id, in_port, &flow);
5111     ds_put_cstr(&result, "Flow: ");
5112     flow_format(&result, &flow);
5113     ds_put_char(&result, '\n');
5114
5115     rule = rule_lookup(ofproto, &flow);
5116     trace_format_rule(&result, 0, rule);
5117     if (rule) {
5118         struct ofproto_trace trace;
5119         struct ofpbuf *odp_actions;
5120
5121         trace.result = &result;
5122         trace.flow = flow;
5123         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
5124         trace.ctx.resubmit_hook = trace_resubmit;
5125         odp_actions = xlate_actions(&trace.ctx,
5126                                     rule->actions, rule->n_actions);
5127
5128         ds_put_char(&result, '\n');
5129         trace_format_flow(&result, 0, "Final flow", &trace);
5130         ds_put_cstr(&result, "Datapath actions: ");
5131         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5132         ofpbuf_delete(odp_actions);
5133     }
5134
5135     unixctl_command_reply(conn, 200, ds_cstr(&result));
5136
5137 exit:
5138     ds_destroy(&result);
5139     ofpbuf_uninit(&packet);
5140     free(args);
5141 }
5142
5143 static void
5144 ofproto_unixctl_init(void)
5145 {
5146     static bool registered;
5147     if (registered) {
5148         return;
5149     }
5150     registered = true;
5151
5152     unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
5153     unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
5154 }
5155 \f
5156 static bool
5157 default_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
5158                          struct ofpbuf *odp_actions, tag_type *tags,
5159                          uint16_t *nf_output_iface, void *ofproto_)
5160 {
5161     struct ofproto *ofproto = ofproto_;
5162     int out_port;
5163
5164     /* Drop frames for reserved multicast addresses. */
5165     if (eth_addr_is_reserved(flow->dl_dst)) {
5166         return true;
5167     }
5168
5169     /* Learn source MAC (but don't try to learn from revalidation). */
5170     if (packet != NULL) {
5171         tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
5172                                               0, flow->in_port,
5173                                               GRAT_ARP_LOCK_NONE);
5174         if (rev_tag) {
5175             /* The log messages here could actually be useful in debugging,
5176              * so keep the rate limit relatively high. */
5177             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5178             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
5179                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
5180             ofproto_revalidate(ofproto, rev_tag);
5181         }
5182     }
5183
5184     /* Determine output port. */
5185     out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags,
5186                                        NULL);
5187     if (out_port < 0) {
5188         flood_packets(ofproto, flow->in_port, OFPPC_NO_FLOOD,
5189                       nf_output_iface, odp_actions);
5190     } else if (out_port != flow->in_port) {
5191         nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, out_port);
5192         *nf_output_iface = out_port;
5193     } else {
5194         /* Drop. */
5195     }
5196
5197     return true;
5198 }
5199
5200 static const struct ofhooks default_ofhooks = {
5201     default_normal_ofhook_cb,
5202     NULL,
5203     NULL
5204 };