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