dpif: Eliminate "struct odp_flow" from client-visible interface.
[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 {
2311     uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2312     struct ofpbuf key;
2313
2314     ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2315     odp_flow_key_from_flow(&key, &facet->flow);
2316     assert(key.base == keybuf);
2317
2318     return dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
2319                          facet->actions, facet->actions_len, NULL);
2320 }
2321
2322 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
2323  * 'zero_stats' is true, clears any existing statistics from the datapath for
2324  * 'facet'. */
2325 static void
2326 facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
2327 {
2328     if (facet->may_install) {
2329         int flags = ODPPF_CREATE | ODPPF_MODIFY;
2330         if (zero_stats) {
2331             flags |= ODPPF_ZERO_STATS;
2332         }
2333         if (!facet_put__(p, facet, flags)) {
2334             facet->installed = true;
2335         }
2336     }
2337 }
2338
2339 /* Ensures that the bytes in 'facet', plus 'extra_bytes', have been passed up
2340  * to the accounting hook function in the ofhooks structure. */
2341 static void
2342 facet_account(struct ofproto *ofproto,
2343               struct facet *facet, uint64_t extra_bytes)
2344 {
2345     uint64_t total_bytes = facet->byte_count + extra_bytes;
2346
2347     if (ofproto->ofhooks->account_flow_cb
2348         && total_bytes > facet->accounted_bytes)
2349     {
2350         ofproto->ofhooks->account_flow_cb(
2351             &facet->flow, facet->tags, facet->actions, facet->actions_len,
2352             total_bytes - facet->accounted_bytes, ofproto->aux);
2353         facet->accounted_bytes = total_bytes;
2354     }
2355 }
2356
2357 /* If 'rule' is installed in the datapath, uninstalls it. */
2358 static void
2359 facet_uninstall(struct ofproto *p, struct facet *facet)
2360 {
2361     if (facet->installed) {
2362         uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2363         struct odp_flow_stats stats;
2364         struct ofpbuf key;
2365
2366         ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2367         odp_flow_key_from_flow(&key, &facet->flow);
2368         assert(key.base == keybuf);
2369
2370         if (!dpif_flow_del(p->dpif, key.data, key.size, &stats)) {
2371             facet_update_stats(p, facet, &stats);
2372         }
2373         facet->installed = false;
2374     }
2375 }
2376
2377 /* Returns true if the only action for 'facet' is to send to the controller.
2378  * (We don't report NetFlow expiration messages for such facets because they
2379  * are just part of the control logic for the network, not real traffic). */
2380 static bool
2381 facet_is_controller_flow(struct facet *facet)
2382 {
2383     return (facet
2384             && facet->rule->n_actions == 1
2385             && action_outputs_to_port(&facet->rule->actions[0],
2386                                       htons(OFPP_CONTROLLER)));
2387 }
2388
2389 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2390  * accounting ofhook and emits a NetFlow expiration if appropriate.  */
2391 static void
2392 facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
2393 {
2394     facet_account(ofproto, facet, 0);
2395
2396     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2397         struct ofexpired expired;
2398         expired.flow = facet->flow;
2399         expired.packet_count = facet->packet_count;
2400         expired.byte_count = facet->byte_count;
2401         expired.used = facet->used;
2402         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2403     }
2404
2405     facet->rule->packet_count += facet->packet_count;
2406     facet->rule->byte_count += facet->byte_count;
2407
2408     /* Reset counters to prevent double counting if 'facet' ever gets
2409      * reinstalled. */
2410     facet->packet_count = 0;
2411     facet->byte_count = 0;
2412     facet->accounted_bytes = 0;
2413
2414     netflow_flow_clear(&facet->nf_flow);
2415 }
2416
2417 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2418  * Returns it if found, otherwise a null pointer.
2419  *
2420  * The returned facet might need revalidation; use facet_lookup_valid()
2421  * instead if that is important. */
2422 static struct facet *
2423 facet_find(struct ofproto *ofproto, const struct flow *flow)
2424 {
2425     struct facet *facet;
2426
2427     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2428                              &ofproto->facets) {
2429         if (flow_equal(flow, &facet->flow)) {
2430             return facet;
2431         }
2432     }
2433
2434     return NULL;
2435 }
2436
2437 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2438  * Returns it if found, otherwise a null pointer.
2439  *
2440  * The returned facet is guaranteed to be valid. */
2441 static struct facet *
2442 facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
2443 {
2444     struct facet *facet = facet_find(ofproto, flow);
2445
2446     /* The facet we found might not be valid, since we could be in need of
2447      * revalidation.  If it is not valid, don't return it. */
2448     if (facet
2449         && ofproto->need_revalidate
2450         && !facet_revalidate(ofproto, facet)) {
2451         COVERAGE_INC(ofproto_invalidated);
2452         return NULL;
2453     }
2454
2455     return facet;
2456 }
2457
2458 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2459  *
2460  *   - If the rule found is different from 'facet''s current rule, moves
2461  *     'facet' to the new rule and recompiles its actions.
2462  *
2463  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2464  *     where it is and recompiles its actions anyway.
2465  *
2466  *   - If there is none, destroys 'facet'.
2467  *
2468  * Returns true if 'facet' still exists, false if it has been destroyed. */
2469 static bool
2470 facet_revalidate(struct ofproto *ofproto, struct facet *facet)
2471 {
2472     struct action_xlate_ctx ctx;
2473     struct ofpbuf *odp_actions;
2474     struct rule *new_rule;
2475     bool actions_changed;
2476
2477     COVERAGE_INC(facet_revalidate);
2478
2479     /* Determine the new rule. */
2480     new_rule = rule_lookup(ofproto, &facet->flow);
2481     if (!new_rule) {
2482         /* No new rule, so delete the facet. */
2483         facet_remove(ofproto, facet);
2484         return false;
2485     }
2486
2487     /* Calculate new ODP actions.
2488      *
2489      * We do not modify any 'facet' state yet, because we might need to, e.g.,
2490      * emit a NetFlow expiration and, if so, we need to have the old state
2491      * around to properly compose it. */
2492     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2493     odp_actions = xlate_actions(&ctx, new_rule->actions, new_rule->n_actions);
2494     actions_changed = (facet->actions_len != odp_actions->size
2495                        || memcmp(facet->actions, odp_actions->data,
2496                                  facet->actions_len));
2497
2498     /* If the ODP actions changed or the installability changed, then we need
2499      * to talk to the datapath. */
2500     if (actions_changed || facet->may_install != facet->installed) {
2501         if (facet->may_install) {
2502             uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
2503             struct odp_flow_stats stats;
2504             struct ofpbuf key;
2505
2506             ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
2507             odp_flow_key_from_flow(&key, &facet->flow);
2508
2509             dpif_flow_put(ofproto->dpif,
2510                           ODPPF_CREATE | ODPPF_MODIFY | ODPPF_ZERO_STATS,
2511                           key.data, key.size,
2512                           odp_actions->data, odp_actions->size, &stats);
2513
2514             facet_update_stats(ofproto, facet, &stats);
2515         } else {
2516             facet_uninstall(ofproto, facet);
2517         }
2518
2519         /* The datapath flow is gone or has zeroed stats, so push stats out of
2520          * 'facet' into 'rule'. */
2521         facet_flush_stats(ofproto, facet);
2522     }
2523
2524     /* Update 'facet' now that we've taken care of all the old state. */
2525     facet->tags = ctx.tags;
2526     facet->nf_flow.output_iface = ctx.nf_output_iface;
2527     facet->may_install = ctx.may_set_up_flow;
2528     if (actions_changed) {
2529         free(facet->actions);
2530         facet->actions_len = odp_actions->size;
2531         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2532     }
2533     if (facet->rule != new_rule) {
2534         COVERAGE_INC(facet_changed_rule);
2535         list_remove(&facet->list_node);
2536         list_push_back(&new_rule->facets, &facet->list_node);
2537         facet->rule = new_rule;
2538         facet->used = new_rule->created;
2539     }
2540
2541     ofpbuf_delete(odp_actions);
2542
2543     return true;
2544 }
2545 \f
2546 static void
2547 queue_tx(struct ofpbuf *msg, const struct ofconn *ofconn,
2548          struct rconn_packet_counter *counter)
2549 {
2550     update_openflow_length(msg);
2551     if (rconn_send(ofconn->rconn, msg, counter)) {
2552         ofpbuf_delete(msg);
2553     }
2554 }
2555
2556 static void
2557 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
2558               int error)
2559 {
2560     struct ofpbuf *buf = ofputil_encode_error_msg(error, oh);
2561     if (buf) {
2562         COVERAGE_INC(ofproto_error);
2563         queue_tx(buf, ofconn, ofconn->reply_counter);
2564     }
2565 }
2566
2567 static void
2568 hton_ofp_phy_port(struct ofp_phy_port *opp)
2569 {
2570     opp->port_no = htons(opp->port_no);
2571     opp->config = htonl(opp->config);
2572     opp->state = htonl(opp->state);
2573     opp->curr = htonl(opp->curr);
2574     opp->advertised = htonl(opp->advertised);
2575     opp->supported = htonl(opp->supported);
2576     opp->peer = htonl(opp->peer);
2577 }
2578
2579 static int
2580 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2581 {
2582     queue_tx(make_echo_reply(oh), ofconn, ofconn->reply_counter);
2583     return 0;
2584 }
2585
2586 static int
2587 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2588 {
2589     struct ofp_switch_features *osf;
2590     struct ofpbuf *buf;
2591     struct ofport *port;
2592
2593     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
2594     osf->datapath_id = htonll(ofconn->ofproto->datapath_id);
2595     osf->n_buffers = htonl(pktbuf_capacity());
2596     osf->n_tables = 2;
2597     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
2598                               OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
2599     osf->actions = htonl((1u << OFPAT_OUTPUT) |
2600                          (1u << OFPAT_SET_VLAN_VID) |
2601                          (1u << OFPAT_SET_VLAN_PCP) |
2602                          (1u << OFPAT_STRIP_VLAN) |
2603                          (1u << OFPAT_SET_DL_SRC) |
2604                          (1u << OFPAT_SET_DL_DST) |
2605                          (1u << OFPAT_SET_NW_SRC) |
2606                          (1u << OFPAT_SET_NW_DST) |
2607                          (1u << OFPAT_SET_NW_TOS) |
2608                          (1u << OFPAT_SET_TP_SRC) |
2609                          (1u << OFPAT_SET_TP_DST) |
2610                          (1u << OFPAT_ENQUEUE));
2611
2612     HMAP_FOR_EACH (port, hmap_node, &ofconn->ofproto->ports) {
2613         hton_ofp_phy_port(ofpbuf_put(buf, &port->opp, sizeof port->opp));
2614     }
2615
2616     queue_tx(buf, ofconn, ofconn->reply_counter);
2617     return 0;
2618 }
2619
2620 static int
2621 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2622 {
2623     struct ofpbuf *buf;
2624     struct ofp_switch_config *osc;
2625     uint16_t flags;
2626     bool drop_frags;
2627
2628     /* Figure out flags. */
2629     dpif_get_drop_frags(ofconn->ofproto->dpif, &drop_frags);
2630     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
2631
2632     /* Send reply. */
2633     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
2634     osc->flags = htons(flags);
2635     osc->miss_send_len = htons(ofconn->miss_send_len);
2636     queue_tx(buf, ofconn, ofconn->reply_counter);
2637
2638     return 0;
2639 }
2640
2641 static int
2642 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
2643 {
2644     uint16_t flags = ntohs(osc->flags);
2645
2646     if (ofconn->type == OFCONN_PRIMARY && ofconn->role != NX_ROLE_SLAVE) {
2647         switch (flags & OFPC_FRAG_MASK) {
2648         case OFPC_FRAG_NORMAL:
2649             dpif_set_drop_frags(ofconn->ofproto->dpif, false);
2650             break;
2651         case OFPC_FRAG_DROP:
2652             dpif_set_drop_frags(ofconn->ofproto->dpif, true);
2653             break;
2654         default:
2655             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
2656                          osc->flags);
2657             break;
2658         }
2659     }
2660
2661     ofconn->miss_send_len = ntohs(osc->miss_send_len);
2662
2663     return 0;
2664 }
2665
2666 /* Maximum depth of flow table recursion (due to NXAST_RESUBMIT actions) in a
2667  * flow translation. */
2668 #define MAX_RESUBMIT_RECURSION 16
2669
2670 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
2671                              struct action_xlate_ctx *ctx);
2672
2673 static void
2674 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
2675 {
2676     const struct ofport *ofport = get_port(ctx->ofproto, port);
2677
2678     if (ofport) {
2679         if (ofport->opp.config & OFPPC_NO_FWD) {
2680             /* Forwarding disabled on port. */
2681             return;
2682         }
2683     } else {
2684         /*
2685          * We don't have an ofport record for this port, but it doesn't hurt to
2686          * allow forwarding to it anyhow.  Maybe such a port will appear later
2687          * and we're pre-populating the flow table.
2688          */
2689     }
2690
2691     nl_msg_put_u32(ctx->odp_actions, ODPAT_OUTPUT, port);
2692     ctx->nf_output_iface = port;
2693 }
2694
2695 static struct rule *
2696 rule_lookup(struct ofproto *ofproto, const struct flow *flow)
2697 {
2698     return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
2699 }
2700
2701 static void
2702 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
2703 {
2704     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
2705         uint16_t old_in_port;
2706         struct rule *rule;
2707
2708         /* Look up a flow with 'in_port' as the input port.  Then restore the
2709          * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
2710          * have surprising behavior). */
2711         old_in_port = ctx->flow.in_port;
2712         ctx->flow.in_port = in_port;
2713         rule = rule_lookup(ctx->ofproto, &ctx->flow);
2714         ctx->flow.in_port = old_in_port;
2715
2716         if (ctx->resubmit_hook) {
2717             ctx->resubmit_hook(ctx, rule);
2718         }
2719
2720         if (rule) {
2721             ctx->recurse++;
2722             do_xlate_actions(rule->actions, rule->n_actions, ctx);
2723             ctx->recurse--;
2724         }
2725     } else {
2726         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
2727
2728         VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
2729                     MAX_RESUBMIT_RECURSION);
2730     }
2731 }
2732
2733 static void
2734 flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, uint32_t mask,
2735               uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
2736 {
2737     struct ofport *ofport;
2738
2739     HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
2740         uint16_t odp_port = ofport->odp_port;
2741         if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
2742             nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, odp_port);
2743         }
2744     }
2745     *nf_output_iface = NF_OUT_FLOOD;
2746 }
2747
2748 static void
2749 xlate_output_action__(struct action_xlate_ctx *ctx,
2750                       uint16_t port, uint16_t max_len)
2751 {
2752     uint16_t odp_port;
2753     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
2754
2755     ctx->nf_output_iface = NF_OUT_DROP;
2756
2757     switch (port) {
2758     case OFPP_IN_PORT:
2759         add_output_action(ctx, ctx->flow.in_port);
2760         break;
2761     case OFPP_TABLE:
2762         xlate_table_action(ctx, ctx->flow.in_port);
2763         break;
2764     case OFPP_NORMAL:
2765         if (!ctx->ofproto->ofhooks->normal_cb(&ctx->flow, ctx->packet,
2766                                               ctx->odp_actions, &ctx->tags,
2767                                               &ctx->nf_output_iface,
2768                                               ctx->ofproto->aux)) {
2769             COVERAGE_INC(ofproto_uninstallable);
2770             ctx->may_set_up_flow = false;
2771         }
2772         break;
2773     case OFPP_FLOOD:
2774         flood_packets(ctx->ofproto, ctx->flow.in_port, OFPPC_NO_FLOOD,
2775                       &ctx->nf_output_iface, ctx->odp_actions);
2776         break;
2777     case OFPP_ALL:
2778         flood_packets(ctx->ofproto, ctx->flow.in_port, 0,
2779                       &ctx->nf_output_iface, ctx->odp_actions);
2780         break;
2781     case OFPP_CONTROLLER:
2782         nl_msg_put_u64(ctx->odp_actions, ODPAT_CONTROLLER, max_len);
2783         break;
2784     case OFPP_LOCAL:
2785         add_output_action(ctx, ODPP_LOCAL);
2786         break;
2787     default:
2788         odp_port = ofp_port_to_odp_port(port);
2789         if (odp_port != ctx->flow.in_port) {
2790             add_output_action(ctx, odp_port);
2791         }
2792         break;
2793     }
2794
2795     if (prev_nf_output_iface == NF_OUT_FLOOD) {
2796         ctx->nf_output_iface = NF_OUT_FLOOD;
2797     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
2798         ctx->nf_output_iface = prev_nf_output_iface;
2799     } else if (prev_nf_output_iface != NF_OUT_DROP &&
2800                ctx->nf_output_iface != NF_OUT_FLOOD) {
2801         ctx->nf_output_iface = NF_OUT_MULTI;
2802     }
2803 }
2804
2805 static void
2806 xlate_output_action(struct action_xlate_ctx *ctx,
2807                     const struct ofp_action_output *oao)
2808 {
2809     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
2810 }
2811
2812 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
2813  * optimization, because we're going to add another action that sets the
2814  * priority immediately after, or because there are no actions following the
2815  * pop.  */
2816 static void
2817 remove_pop_action(struct action_xlate_ctx *ctx)
2818 {
2819     if (ctx->odp_actions->size == ctx->last_pop_priority) {
2820         ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
2821         ctx->last_pop_priority = -1;
2822     }
2823 }
2824
2825 static void
2826 add_pop_action(struct action_xlate_ctx *ctx)
2827 {
2828     if (ctx->odp_actions->size != ctx->last_pop_priority) {
2829         nl_msg_put_flag(ctx->odp_actions, ODPAT_POP_PRIORITY);
2830         ctx->last_pop_priority = ctx->odp_actions->size;
2831     }
2832 }
2833
2834 static void
2835 xlate_enqueue_action(struct action_xlate_ctx *ctx,
2836                      const struct ofp_action_enqueue *oae)
2837 {
2838     uint16_t ofp_port, odp_port;
2839     uint32_t priority;
2840     int error;
2841
2842     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
2843                                    &priority);
2844     if (error) {
2845         /* Fall back to ordinary output action. */
2846         xlate_output_action__(ctx, ntohs(oae->port), 0);
2847         return;
2848     }
2849
2850     /* Figure out ODP output port. */
2851     ofp_port = ntohs(oae->port);
2852     if (ofp_port != OFPP_IN_PORT) {
2853         odp_port = ofp_port_to_odp_port(ofp_port);
2854     } else {
2855         odp_port = ctx->flow.in_port;
2856     }
2857
2858     /* Add ODP actions. */
2859     remove_pop_action(ctx);
2860     nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2861     add_output_action(ctx, odp_port);
2862     add_pop_action(ctx);
2863
2864     /* Update NetFlow output port. */
2865     if (ctx->nf_output_iface == NF_OUT_DROP) {
2866         ctx->nf_output_iface = odp_port;
2867     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
2868         ctx->nf_output_iface = NF_OUT_MULTI;
2869     }
2870 }
2871
2872 static void
2873 xlate_set_queue_action(struct action_xlate_ctx *ctx,
2874                        const struct nx_action_set_queue *nasq)
2875 {
2876     uint32_t priority;
2877     int error;
2878
2879     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
2880                                    &priority);
2881     if (error) {
2882         /* Couldn't translate queue to a priority, so ignore.  A warning
2883          * has already been logged. */
2884         return;
2885     }
2886
2887     remove_pop_action(ctx);
2888     nl_msg_put_u32(ctx->odp_actions, ODPAT_SET_PRIORITY, priority);
2889 }
2890
2891 static void
2892 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
2893 {
2894     ovs_be16 tci = ctx->flow.vlan_tci;
2895     if (!(tci & htons(VLAN_CFI))) {
2896         nl_msg_put_flag(ctx->odp_actions, ODPAT_STRIP_VLAN);
2897     } else {
2898         nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_DL_TCI,
2899                         tci & ~htons(VLAN_CFI));
2900     }
2901 }
2902
2903 struct xlate_reg_state {
2904     ovs_be16 vlan_tci;
2905     ovs_be64 tun_id;
2906 };
2907
2908 static void
2909 save_reg_state(const struct action_xlate_ctx *ctx,
2910                struct xlate_reg_state *state)
2911 {
2912     state->vlan_tci = ctx->flow.vlan_tci;
2913     state->tun_id = ctx->flow.tun_id;
2914 }
2915
2916 static void
2917 update_reg_state(struct action_xlate_ctx *ctx,
2918                  const struct xlate_reg_state *state)
2919 {
2920     if (ctx->flow.vlan_tci != state->vlan_tci) {
2921         xlate_set_dl_tci(ctx);
2922     }
2923     if (ctx->flow.tun_id != state->tun_id) {
2924         nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, ctx->flow.tun_id);
2925     }
2926 }
2927
2928 static void
2929 xlate_nicira_action(struct action_xlate_ctx *ctx,
2930                     const struct nx_action_header *nah)
2931 {
2932     const struct nx_action_resubmit *nar;
2933     const struct nx_action_set_tunnel *nast;
2934     const struct nx_action_set_queue *nasq;
2935     const struct nx_action_multipath *nam;
2936     enum nx_action_subtype subtype = ntohs(nah->subtype);
2937     struct xlate_reg_state state;
2938     ovs_be64 tun_id;
2939
2940     assert(nah->vendor == htonl(NX_VENDOR_ID));
2941     switch (subtype) {
2942     case NXAST_RESUBMIT:
2943         nar = (const struct nx_action_resubmit *) nah;
2944         xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
2945         break;
2946
2947     case NXAST_SET_TUNNEL:
2948         nast = (const struct nx_action_set_tunnel *) nah;
2949         tun_id = htonll(ntohl(nast->tun_id));
2950         nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
2951         ctx->flow.tun_id = tun_id;
2952         break;
2953
2954     case NXAST_DROP_SPOOFED_ARP:
2955         if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
2956             nl_msg_put_flag(ctx->odp_actions, ODPAT_DROP_SPOOFED_ARP);
2957         }
2958         break;
2959
2960     case NXAST_SET_QUEUE:
2961         nasq = (const struct nx_action_set_queue *) nah;
2962         xlate_set_queue_action(ctx, nasq);
2963         break;
2964
2965     case NXAST_POP_QUEUE:
2966         add_pop_action(ctx);
2967         break;
2968
2969     case NXAST_REG_MOVE:
2970         save_reg_state(ctx, &state);
2971         nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
2972                              &ctx->flow);
2973         update_reg_state(ctx, &state);
2974         break;
2975
2976     case NXAST_REG_LOAD:
2977         save_reg_state(ctx, &state);
2978         nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
2979                              &ctx->flow);
2980         update_reg_state(ctx, &state);
2981         break;
2982
2983     case NXAST_NOTE:
2984         /* Nothing to do. */
2985         break;
2986
2987     case NXAST_SET_TUNNEL64:
2988         tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
2989         nl_msg_put_be64(ctx->odp_actions, ODPAT_SET_TUNNEL, tun_id);
2990         ctx->flow.tun_id = tun_id;
2991         break;
2992
2993     case NXAST_MULTIPATH:
2994         nam = (const struct nx_action_multipath *) nah;
2995         multipath_execute(nam, &ctx->flow);
2996         break;
2997
2998     /* If you add a new action here that modifies flow data, don't forget to
2999      * update the flow key in ctx->flow at the same time. */
3000
3001     case NXAST_SNAT__OBSOLETE:
3002     default:
3003         VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
3004         break;
3005     }
3006 }
3007
3008 static void
3009 do_xlate_actions(const union ofp_action *in, size_t n_in,
3010                  struct action_xlate_ctx *ctx)
3011 {
3012     struct actions_iterator iter;
3013     const union ofp_action *ia;
3014     const struct ofport *port;
3015
3016     port = get_port(ctx->ofproto, ctx->flow.in_port);
3017     if (port && port->opp.config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
3018         port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
3019                             ? OFPPC_NO_RECV_STP : OFPPC_NO_RECV)) {
3020         /* Drop this flow. */
3021         return;
3022     }
3023
3024     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
3025         enum ofp_action_type type = ntohs(ia->type);
3026         const struct ofp_action_dl_addr *oada;
3027
3028         switch (type) {
3029         case OFPAT_OUTPUT:
3030             xlate_output_action(ctx, &ia->output);
3031             break;
3032
3033         case OFPAT_SET_VLAN_VID:
3034             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3035             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
3036             xlate_set_dl_tci(ctx);
3037             break;
3038
3039         case OFPAT_SET_VLAN_PCP:
3040             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3041             ctx->flow.vlan_tci |= htons(
3042                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
3043             xlate_set_dl_tci(ctx);
3044             break;
3045
3046         case OFPAT_STRIP_VLAN:
3047             ctx->flow.vlan_tci = htons(0);
3048             xlate_set_dl_tci(ctx);
3049             break;
3050
3051         case OFPAT_SET_DL_SRC:
3052             oada = ((struct ofp_action_dl_addr *) ia);
3053             nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_SRC,
3054                               oada->dl_addr, ETH_ADDR_LEN);
3055             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
3056             break;
3057
3058         case OFPAT_SET_DL_DST:
3059             oada = ((struct ofp_action_dl_addr *) ia);
3060             nl_msg_put_unspec(ctx->odp_actions, ODPAT_SET_DL_DST,
3061                               oada->dl_addr, ETH_ADDR_LEN);
3062             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
3063             break;
3064
3065         case OFPAT_SET_NW_SRC:
3066             nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_SRC,
3067                             ia->nw_addr.nw_addr);
3068             ctx->flow.nw_src = ia->nw_addr.nw_addr;
3069             break;
3070
3071         case OFPAT_SET_NW_DST:
3072             nl_msg_put_be32(ctx->odp_actions, ODPAT_SET_NW_DST,
3073                             ia->nw_addr.nw_addr);
3074             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
3075             break;
3076
3077         case OFPAT_SET_NW_TOS:
3078             nl_msg_put_u8(ctx->odp_actions, ODPAT_SET_NW_TOS,
3079                           ia->nw_tos.nw_tos);
3080             ctx->flow.nw_tos = ia->nw_tos.nw_tos;
3081             break;
3082
3083         case OFPAT_SET_TP_SRC:
3084             nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_SRC,
3085                             ia->tp_port.tp_port);
3086             ctx->flow.tp_src = ia->tp_port.tp_port;
3087             break;
3088
3089         case OFPAT_SET_TP_DST:
3090             nl_msg_put_be16(ctx->odp_actions, ODPAT_SET_TP_DST,
3091                             ia->tp_port.tp_port);
3092             ctx->flow.tp_dst = ia->tp_port.tp_port;
3093             break;
3094
3095         case OFPAT_VENDOR:
3096             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
3097             break;
3098
3099         case OFPAT_ENQUEUE:
3100             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3101             break;
3102
3103         default:
3104             VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
3105             break;
3106         }
3107     }
3108 }
3109
3110 static void
3111 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3112                       struct ofproto *ofproto, const struct flow *flow,
3113                       const struct ofpbuf *packet)
3114 {
3115     ctx->ofproto = ofproto;
3116     ctx->flow = *flow;
3117     ctx->packet = packet;
3118     ctx->resubmit_hook = NULL;
3119 }
3120
3121 static struct ofpbuf *
3122 xlate_actions(struct action_xlate_ctx *ctx,
3123               const union ofp_action *in, size_t n_in)
3124 {
3125     COVERAGE_INC(ofproto_ofp2odp);
3126
3127     ctx->odp_actions = ofpbuf_new(512);
3128     ctx->tags = 0;
3129     ctx->may_set_up_flow = true;
3130     ctx->nf_output_iface = NF_OUT_DROP;
3131     ctx->recurse = 0;
3132     ctx->last_pop_priority = -1;
3133     do_xlate_actions(in, n_in, ctx);
3134     remove_pop_action(ctx);
3135
3136     /* Check with in-band control to see if we're allowed to set up this
3137      * flow. */
3138     if (!in_band_rule_check(ctx->ofproto->in_band, &ctx->flow,
3139                             ctx->odp_actions->data, ctx->odp_actions->size)) {
3140         ctx->may_set_up_flow = false;
3141     }
3142
3143     return ctx->odp_actions;
3144 }
3145
3146 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
3147  * error message code (composed with ofp_mkerr()) for the caller to propagate
3148  * upward.  Otherwise, returns 0.
3149  *
3150  * The log message mentions 'msg_type'. */
3151 static int
3152 reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
3153 {
3154     if (ofconn->type == OFCONN_PRIMARY && ofconn->role == NX_ROLE_SLAVE) {
3155         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
3156         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
3157                      msg_type);
3158
3159         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3160     } else {
3161         return 0;
3162     }
3163 }
3164
3165 static int
3166 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
3167 {
3168     struct ofproto *p = ofconn->ofproto;
3169     struct ofp_packet_out *opo;
3170     struct ofpbuf payload, *buffer;
3171     union ofp_action *ofp_actions;
3172     struct action_xlate_ctx ctx;
3173     struct ofpbuf *odp_actions;
3174     struct ofpbuf request;
3175     struct flow flow;
3176     size_t n_ofp_actions;
3177     uint16_t in_port;
3178     int error;
3179
3180     COVERAGE_INC(ofproto_packet_out);
3181
3182     error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
3183     if (error) {
3184         return error;
3185     }
3186
3187     /* Get ofp_packet_out. */
3188     ofpbuf_use_const(&request, oh, ntohs(oh->length));
3189     opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
3190
3191     /* Get actions. */
3192     error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
3193                                  &ofp_actions, &n_ofp_actions);
3194     if (error) {
3195         return error;
3196     }
3197
3198     /* Get payload. */
3199     if (opo->buffer_id != htonl(UINT32_MAX)) {
3200         error = pktbuf_retrieve(ofconn->pktbuf, ntohl(opo->buffer_id),
3201                                 &buffer, &in_port);
3202         if (error || !buffer) {
3203             return error;
3204         }
3205         payload = *buffer;
3206     } else {
3207         payload = request;
3208         buffer = NULL;
3209     }
3210
3211     /* Extract flow, check actions. */
3212     flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
3213                  &flow);
3214     error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
3215     if (error) {
3216         goto exit;
3217     }
3218
3219     /* Send. */
3220     action_xlate_ctx_init(&ctx, p, &flow, &payload);
3221     odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
3222     dpif_execute(p->dpif, odp_actions->data, odp_actions->size, &payload);
3223     ofpbuf_delete(odp_actions);
3224
3225 exit:
3226     ofpbuf_delete(buffer);
3227     return 0;
3228 }
3229
3230 static void
3231 update_port_config(struct ofproto *p, struct ofport *port,
3232                    uint32_t config, uint32_t mask)
3233 {
3234     mask &= config ^ port->opp.config;
3235     if (mask & OFPPC_PORT_DOWN) {
3236         if (config & OFPPC_PORT_DOWN) {
3237             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
3238         } else {
3239             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
3240         }
3241     }
3242 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP |    \
3243                          OFPPC_NO_FWD | OFPPC_NO_FLOOD)
3244     if (mask & REVALIDATE_BITS) {
3245         COVERAGE_INC(ofproto_costly_flags);
3246         port->opp.config ^= mask & REVALIDATE_BITS;
3247         p->need_revalidate = true;
3248     }
3249 #undef REVALIDATE_BITS
3250     if (mask & OFPPC_NO_PACKET_IN) {
3251         port->opp.config ^= OFPPC_NO_PACKET_IN;
3252     }
3253 }
3254
3255 static int
3256 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3257 {
3258     struct ofproto *p = ofconn->ofproto;
3259     const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
3260     struct ofport *port;
3261     int error;
3262
3263     error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
3264     if (error) {
3265         return error;
3266     }
3267
3268     port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
3269     if (!port) {
3270         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
3271     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
3272         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
3273     } else {
3274         update_port_config(p, port, ntohl(opm->config), ntohl(opm->mask));
3275         if (opm->advertise) {
3276             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
3277         }
3278     }
3279     return 0;
3280 }
3281
3282 static struct ofpbuf *
3283 make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
3284 {
3285     struct ofp_stats_reply *osr;
3286     struct ofpbuf *msg;
3287
3288     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
3289     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
3290     osr->type = type;
3291     osr->flags = htons(0);
3292     return msg;
3293 }
3294
3295 static struct ofpbuf *
3296 start_ofp_stats_reply(const struct ofp_header *request, size_t body_len)
3297 {
3298     const struct ofp_stats_request *osr
3299         = (const struct ofp_stats_request *) request;
3300     return make_ofp_stats_reply(osr->header.xid, osr->type, body_len);
3301 }
3302
3303 static void *
3304 append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
3305                        struct ofpbuf **msgp)
3306 {
3307     struct ofpbuf *msg = *msgp;
3308     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
3309     if (nbytes + msg->size > UINT16_MAX) {
3310         struct ofp_stats_reply *reply = msg->data;
3311         reply->flags = htons(OFPSF_REPLY_MORE);
3312         *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
3313         queue_tx(msg, ofconn, ofconn->reply_counter);
3314     }
3315     return ofpbuf_put_uninit(*msgp, nbytes);
3316 }
3317
3318 static struct ofpbuf *
3319 make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
3320 {
3321     struct nicira_stats_msg *nsm;
3322     struct ofpbuf *msg;
3323
3324     msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
3325     nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
3326     nsm->type = htons(OFPST_VENDOR);
3327     nsm->flags = htons(0);
3328     nsm->vendor = htonl(NX_VENDOR_ID);
3329     nsm->subtype = subtype;
3330     return msg;
3331 }
3332
3333 static struct ofpbuf *
3334 start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
3335 {
3336     return make_nxstats_reply(request->header.xid, request->subtype, body_len);
3337 }
3338
3339 static void
3340 append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
3341                      struct ofpbuf **msgp)
3342 {
3343     struct ofpbuf *msg = *msgp;
3344     assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
3345     if (nbytes + msg->size > UINT16_MAX) {
3346         struct nicira_stats_msg *reply = msg->data;
3347         reply->flags = htons(OFPSF_REPLY_MORE);
3348         *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
3349         queue_tx(msg, ofconn, ofconn->reply_counter);
3350     }
3351     ofpbuf_prealloc_tailroom(*msgp, nbytes);
3352 }
3353
3354 static int
3355 handle_desc_stats_request(struct ofconn *ofconn,
3356                           const struct ofp_header *request)
3357 {
3358     struct ofproto *p = ofconn->ofproto;
3359     struct ofp_desc_stats *ods;
3360     struct ofpbuf *msg;
3361
3362     msg = start_ofp_stats_reply(request, sizeof *ods);
3363     ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
3364     memset(ods, 0, sizeof *ods);
3365     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
3366     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
3367     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
3368     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
3369     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
3370     queue_tx(msg, ofconn, ofconn->reply_counter);
3371
3372     return 0;
3373 }
3374
3375 static int
3376 handle_table_stats_request(struct ofconn *ofconn,
3377                            const struct ofp_header *request)
3378 {
3379     struct ofproto *p = ofconn->ofproto;
3380     struct ofp_table_stats *ots;
3381     struct ofpbuf *msg;
3382
3383     msg = start_ofp_stats_reply(request, sizeof *ots * 2);
3384
3385     /* Classifier table. */
3386     ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
3387     memset(ots, 0, sizeof *ots);
3388     strcpy(ots->name, "classifier");
3389     ots->wildcards = (ofconn->flow_format == NXFF_OPENFLOW10
3390                       ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
3391     ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
3392     ots->active_count = htonl(classifier_count(&p->cls));
3393     ots->lookup_count = htonll(0);              /* XXX */
3394     ots->matched_count = htonll(0);             /* XXX */
3395
3396     queue_tx(msg, ofconn, ofconn->reply_counter);
3397     return 0;
3398 }
3399
3400 static void
3401 append_port_stat(struct ofport *port, struct ofconn *ofconn,
3402                  struct ofpbuf **msgp)
3403 {
3404     struct netdev_stats stats;
3405     struct ofp_port_stats *ops;
3406
3407     /* Intentionally ignore return value, since errors will set
3408      * 'stats' to all-1s, which is correct for OpenFlow, and
3409      * netdev_get_stats() will log errors. */
3410     netdev_get_stats(port->netdev, &stats);
3411
3412     ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
3413     ops->port_no = htons(port->opp.port_no);
3414     memset(ops->pad, 0, sizeof ops->pad);
3415     ops->rx_packets = htonll(stats.rx_packets);
3416     ops->tx_packets = htonll(stats.tx_packets);
3417     ops->rx_bytes = htonll(stats.rx_bytes);
3418     ops->tx_bytes = htonll(stats.tx_bytes);
3419     ops->rx_dropped = htonll(stats.rx_dropped);
3420     ops->tx_dropped = htonll(stats.tx_dropped);
3421     ops->rx_errors = htonll(stats.rx_errors);
3422     ops->tx_errors = htonll(stats.tx_errors);
3423     ops->rx_frame_err = htonll(stats.rx_frame_errors);
3424     ops->rx_over_err = htonll(stats.rx_over_errors);
3425     ops->rx_crc_err = htonll(stats.rx_crc_errors);
3426     ops->collisions = htonll(stats.collisions);
3427 }
3428
3429 static int
3430 handle_port_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3431 {
3432     struct ofproto *p = ofconn->ofproto;
3433     const struct ofp_port_stats_request *psr = ofputil_stats_body(oh);
3434     struct ofp_port_stats *ops;
3435     struct ofpbuf *msg;
3436     struct ofport *port;
3437
3438     msg = start_ofp_stats_reply(oh, sizeof *ops * 16);
3439     if (psr->port_no != htons(OFPP_NONE)) {
3440         port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
3441         if (port) {
3442             append_port_stat(port, ofconn, &msg);
3443         }
3444     } else {
3445         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
3446             append_port_stat(port, ofconn, &msg);
3447         }
3448     }
3449
3450     queue_tx(msg, ofconn, ofconn->reply_counter);
3451     return 0;
3452 }
3453
3454 /* Obtains statistic counters for 'rule' within 'p' and stores them into
3455  * '*packet_countp' and '*byte_countp'.  The returned statistics include
3456  * statistics for all of 'rule''s facets. */
3457 static void
3458 query_stats(struct ofproto *p, struct rule *rule,
3459             uint64_t *packet_countp, uint64_t *byte_countp)
3460 {
3461     uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
3462     uint64_t packet_count, byte_count;
3463     struct facet *facet;
3464     struct ofpbuf key;
3465
3466     /* Start from historical data for 'rule' itself that are no longer tracked
3467      * by the datapath.  This counts, for example, facets that have expired. */
3468     packet_count = rule->packet_count;
3469     byte_count = rule->byte_count;
3470
3471     /* Ask the datapath for statistics on all of the rule's facets.
3472      *
3473      * Also, add any statistics that are not tracked by the datapath for each
3474      * facet.  This includes, for example, statistics for packets that were
3475      * executed "by hand" by ofproto via dpif_execute() but must be accounted
3476      * to a rule. */
3477     ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
3478     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3479         struct odp_flow_stats stats;
3480
3481         ofpbuf_clear(&key);
3482         odp_flow_key_from_flow(&key, &facet->flow);
3483         dpif_flow_get(p->dpif, 0, key.data, key.size, NULL, &stats);
3484
3485         packet_count += stats.n_packets + facet->packet_count;
3486         byte_count += stats.n_bytes + facet->byte_count;
3487     }
3488
3489     /* Return the stats to the caller. */
3490     *packet_countp = packet_count;
3491     *byte_countp = byte_count;
3492 }
3493
3494 static void
3495 calc_flow_duration(long long int start, ovs_be32 *sec, ovs_be32 *nsec)
3496 {
3497     long long int msecs = time_msec() - start;
3498     *sec = htonl(msecs / 1000);
3499     *nsec = htonl((msecs % 1000) * (1000 * 1000));
3500 }
3501
3502 static void
3503 put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
3504                    ovs_be16 out_port, struct ofpbuf **replyp)
3505 {
3506     struct ofp_flow_stats *ofs;
3507     uint64_t packet_count, byte_count;
3508     size_t act_len, len;
3509
3510     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3511         return;
3512     }
3513
3514     act_len = sizeof *rule->actions * rule->n_actions;
3515     len = offsetof(struct ofp_flow_stats, actions) + act_len;
3516
3517     query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3518
3519     ofs = append_ofp_stats_reply(len, ofconn, replyp);
3520     ofs->length = htons(len);
3521     ofs->table_id = 0;
3522     ofs->pad = 0;
3523     ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofs->match,
3524                               rule->flow_cookie, &ofs->cookie);
3525     calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
3526     ofs->priority = htons(rule->cr.priority);
3527     ofs->idle_timeout = htons(rule->idle_timeout);
3528     ofs->hard_timeout = htons(rule->hard_timeout);
3529     memset(ofs->pad2, 0, sizeof ofs->pad2);
3530     ofs->packet_count = htonll(packet_count);
3531     ofs->byte_count = htonll(byte_count);
3532     if (rule->n_actions > 0) {
3533         memcpy(ofs->actions, rule->actions, act_len);
3534     }
3535 }
3536
3537 static bool
3538 is_valid_table(uint8_t table_id)
3539 {
3540     return table_id == 0 || table_id == 0xff;
3541 }
3542
3543 static int
3544 handle_flow_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3545 {
3546     const struct ofp_flow_stats_request *fsr = ofputil_stats_body(oh);
3547     struct ofpbuf *reply;
3548
3549     COVERAGE_INC(ofproto_flows_req);
3550     reply = start_ofp_stats_reply(oh, 1024);
3551     if (is_valid_table(fsr->table_id)) {
3552         struct cls_cursor cursor;
3553         struct cls_rule target;
3554         struct rule *rule;
3555
3556         ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
3557                                     &target);
3558         cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3559         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3560             put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
3561         }
3562     }
3563     queue_tx(reply, ofconn, ofconn->reply_counter);
3564
3565     return 0;
3566 }
3567
3568 static void
3569 put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
3570                   ovs_be16 out_port, struct ofpbuf **replyp)
3571 {
3572     struct nx_flow_stats *nfs;
3573     uint64_t packet_count, byte_count;
3574     size_t act_len, start_len;
3575     struct ofpbuf *reply;
3576
3577     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
3578         return;
3579     }
3580
3581     query_stats(ofconn->ofproto, rule, &packet_count, &byte_count);
3582
3583     act_len = sizeof *rule->actions * rule->n_actions;
3584
3585     append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
3586     start_len = (*replyp)->size;
3587     reply = *replyp;
3588
3589     nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
3590     nfs->table_id = 0;
3591     nfs->pad = 0;
3592     calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
3593     nfs->cookie = rule->flow_cookie;
3594     nfs->priority = htons(rule->cr.priority);
3595     nfs->idle_timeout = htons(rule->idle_timeout);
3596     nfs->hard_timeout = htons(rule->hard_timeout);
3597     nfs->match_len = htons(nx_put_match(reply, &rule->cr));
3598     memset(nfs->pad2, 0, sizeof nfs->pad2);
3599     nfs->packet_count = htonll(packet_count);
3600     nfs->byte_count = htonll(byte_count);
3601     if (rule->n_actions > 0) {
3602         ofpbuf_put(reply, rule->actions, act_len);
3603     }
3604     nfs->length = htons(reply->size - start_len);
3605 }
3606
3607 static int
3608 handle_nxst_flow(struct ofconn *ofconn, const struct ofp_header *oh)
3609 {
3610     struct nx_flow_stats_request *nfsr;
3611     struct cls_rule target;
3612     struct ofpbuf *reply;
3613     struct ofpbuf b;
3614     int error;
3615
3616     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3617
3618     /* Dissect the message. */
3619     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
3620     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &target);
3621     if (error) {
3622         return error;
3623     }
3624     if (b.size) {
3625         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3626     }
3627
3628     COVERAGE_INC(ofproto_flows_req);
3629     reply = start_nxstats_reply(&nfsr->nsm, 1024);
3630     if (is_valid_table(nfsr->table_id)) {
3631         struct cls_cursor cursor;
3632         struct rule *rule;
3633
3634         cls_cursor_init(&cursor, &ofconn->ofproto->cls, &target);
3635         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3636             put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
3637         }
3638     }
3639     queue_tx(reply, ofconn, ofconn->reply_counter);
3640
3641     return 0;
3642 }
3643
3644 static void
3645 flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
3646 {
3647     uint64_t packet_count, byte_count;
3648     size_t act_len = sizeof *rule->actions * rule->n_actions;
3649
3650     query_stats(ofproto, rule, &packet_count, &byte_count);
3651
3652     ds_put_format(results, "duration=%llds, ",
3653                   (time_msec() - rule->created) / 1000);
3654     ds_put_format(results, "priority=%u, ", rule->cr.priority);
3655     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3656     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3657     cls_rule_format(&rule->cr, results);
3658     if (act_len > 0) {
3659         ofp_print_actions(results, &rule->actions->header, act_len);
3660     } else {
3661         ds_put_cstr(results, "drop");
3662     }
3663     ds_put_cstr(results, "\n");
3664 }
3665
3666 /* Adds a pretty-printed description of all flows to 'results', including
3667  * those marked hidden by secchan (e.g., by in-band control). */
3668 void
3669 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3670 {
3671     struct cls_cursor cursor;
3672     struct rule *rule;
3673
3674     cls_cursor_init(&cursor, &p->cls, NULL);
3675     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3676         flow_stats_ds(p, rule, results);
3677     }
3678 }
3679
3680 static void
3681 query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
3682                       ovs_be16 out_port, uint8_t table_id,
3683                       struct ofp_aggregate_stats_reply *oasr)
3684 {
3685     uint64_t total_packets = 0;
3686     uint64_t total_bytes = 0;
3687     int n_flows = 0;
3688
3689     COVERAGE_INC(ofproto_agg_request);
3690
3691     if (is_valid_table(table_id)) {
3692         struct cls_cursor cursor;
3693         struct rule *rule;
3694
3695         cls_cursor_init(&cursor, &ofproto->cls, target);
3696         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3697             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
3698                 uint64_t packet_count;
3699                 uint64_t byte_count;
3700
3701                 query_stats(ofproto, rule, &packet_count, &byte_count);
3702
3703                 total_packets += packet_count;
3704                 total_bytes += byte_count;
3705                 n_flows++;
3706             }
3707         }
3708     }
3709
3710     oasr->flow_count = htonl(n_flows);
3711     oasr->packet_count = htonll(total_packets);
3712     oasr->byte_count = htonll(total_bytes);
3713     memset(oasr->pad, 0, sizeof oasr->pad);
3714 }
3715
3716 static int
3717 handle_aggregate_stats_request(struct ofconn *ofconn,
3718                                const struct ofp_header *oh)
3719 {
3720     const struct ofp_aggregate_stats_request *request = ofputil_stats_body(oh);
3721     struct ofp_aggregate_stats_reply *reply;
3722     struct cls_rule target;
3723     struct ofpbuf *msg;
3724
3725     ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
3726                                 &target);
3727
3728     msg = start_ofp_stats_reply(oh, sizeof *reply);
3729     reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
3730     query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3731                           request->table_id, reply);
3732     queue_tx(msg, ofconn, ofconn->reply_counter);
3733     return 0;
3734 }
3735
3736 static int
3737 handle_nxst_aggregate(struct ofconn *ofconn, const struct ofp_header *oh)
3738 {
3739     struct nx_aggregate_stats_request *request;
3740     struct ofp_aggregate_stats_reply *reply;
3741     struct cls_rule target;
3742     struct ofpbuf b;
3743     struct ofpbuf *buf;
3744     int error;
3745
3746     ofpbuf_use_const(&b, oh, ntohs(oh->length));
3747
3748     /* Dissect the message. */
3749     request = ofpbuf_pull(&b, sizeof *request);
3750     error = nx_pull_match(&b, ntohs(request->match_len), 0, &target);
3751     if (error) {
3752         return error;
3753     }
3754     if (b.size) {
3755         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3756     }
3757
3758     /* Reply. */
3759     COVERAGE_INC(ofproto_flows_req);
3760     buf = start_nxstats_reply(&request->nsm, sizeof *reply);
3761     reply = ofpbuf_put_uninit(buf, sizeof *reply);
3762     query_aggregate_stats(ofconn->ofproto, &target, request->out_port,
3763                           request->table_id, reply);
3764     queue_tx(buf, ofconn, ofconn->reply_counter);
3765
3766     return 0;
3767 }
3768
3769 struct queue_stats_cbdata {
3770     struct ofconn *ofconn;
3771     struct ofport *ofport;
3772     struct ofpbuf *msg;
3773 };
3774
3775 static void
3776 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3777                 const struct netdev_queue_stats *stats)
3778 {
3779     struct ofp_queue_stats *reply;
3780
3781     reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
3782     reply->port_no = htons(cbdata->ofport->opp.port_no);
3783     memset(reply->pad, 0, sizeof reply->pad);
3784     reply->queue_id = htonl(queue_id);
3785     reply->tx_bytes = htonll(stats->tx_bytes);
3786     reply->tx_packets = htonll(stats->tx_packets);
3787     reply->tx_errors = htonll(stats->tx_errors);
3788 }
3789
3790 static void
3791 handle_queue_stats_dump_cb(uint32_t queue_id,
3792                            struct netdev_queue_stats *stats,
3793                            void *cbdata_)
3794 {
3795     struct queue_stats_cbdata *cbdata = cbdata_;
3796
3797     put_queue_stats(cbdata, queue_id, stats);
3798 }
3799
3800 static void
3801 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3802                             struct queue_stats_cbdata *cbdata)
3803 {
3804     cbdata->ofport = port;
3805     if (queue_id == OFPQ_ALL) {
3806         netdev_dump_queue_stats(port->netdev,
3807                                 handle_queue_stats_dump_cb, cbdata);
3808     } else {
3809         struct netdev_queue_stats stats;
3810
3811         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3812             put_queue_stats(cbdata, queue_id, &stats);
3813         }
3814     }
3815 }
3816
3817 static int
3818 handle_queue_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
3819 {
3820     struct ofproto *ofproto = ofconn->ofproto;
3821     const struct ofp_queue_stats_request *qsr;
3822     struct queue_stats_cbdata cbdata;
3823     struct ofport *port;
3824     unsigned int port_no;
3825     uint32_t queue_id;
3826
3827     qsr = ofputil_stats_body(oh);
3828     if (!qsr) {
3829         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
3830     }
3831
3832     COVERAGE_INC(ofproto_queue_req);
3833
3834     cbdata.ofconn = ofconn;
3835     cbdata.msg = start_ofp_stats_reply(oh, 128);
3836
3837     port_no = ntohs(qsr->port_no);
3838     queue_id = ntohl(qsr->queue_id);
3839     if (port_no == OFPP_ALL) {
3840         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3841             handle_queue_stats_for_port(port, queue_id, &cbdata);
3842         }
3843     } else if (port_no < ofproto->max_ports) {
3844         port = get_port(ofproto, ofp_port_to_odp_port(port_no));
3845         if (port) {
3846             handle_queue_stats_for_port(port, queue_id, &cbdata);
3847         }
3848     } else {
3849         ofpbuf_delete(cbdata.msg);
3850         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
3851     }
3852     queue_tx(cbdata.msg, ofconn, ofconn->reply_counter);
3853
3854     return 0;
3855 }
3856
3857 static long long int
3858 msec_from_nsec(uint64_t sec, uint32_t nsec)
3859 {
3860     return !sec ? 0 : sec * 1000 + nsec / 1000000;
3861 }
3862
3863 static void
3864 facet_update_time(struct ofproto *ofproto, struct facet *facet,
3865                   const struct odp_flow_stats *stats)
3866 {
3867     long long int used = msec_from_nsec(stats->used_sec, stats->used_nsec);
3868     if (used > facet->used) {
3869         facet->used = used;
3870         if (used > facet->rule->used) {
3871             facet->rule->used = used;
3872         }
3873         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3874     }
3875 }
3876
3877 /* Folds the statistics from 'stats' into the counters in 'facet'.
3878  *
3879  * Because of the meaning of a facet's counters, it only makes sense to do this
3880  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3881  * packet that was sent by hand or if it represents statistics that have been
3882  * cleared out of the datapath. */
3883 static void
3884 facet_update_stats(struct ofproto *ofproto, struct facet *facet,
3885                    const struct odp_flow_stats *stats)
3886 {
3887     if (stats->n_packets) {
3888         facet_update_time(ofproto, facet, stats);
3889         facet->packet_count += stats->n_packets;
3890         facet->byte_count += stats->n_bytes;
3891         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3892     }
3893 }
3894
3895 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3896  * in which no matching flow already exists in the flow table.
3897  *
3898  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3899  * ofp_actions, to ofconn->ofproto's flow table.  Returns 0 on success or an
3900  * OpenFlow error code as encoded by ofp_mkerr() on failure.
3901  *
3902  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3903  * if any. */
3904 static int
3905 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
3906 {
3907     struct ofproto *p = ofconn->ofproto;
3908     struct ofpbuf *packet;
3909     struct rule *rule;
3910     uint16_t in_port;
3911     int error;
3912
3913     if (fm->flags & OFPFF_CHECK_OVERLAP
3914         && classifier_rule_overlaps(&p->cls, &fm->cr)) {
3915         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
3916     }
3917
3918     error = 0;
3919     if (fm->buffer_id != UINT32_MAX) {
3920         error = pktbuf_retrieve(ofconn->pktbuf, fm->buffer_id,
3921                                 &packet, &in_port);
3922     } else {
3923         packet = NULL;
3924         in_port = UINT16_MAX;
3925     }
3926
3927     rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
3928                        fm->idle_timeout, fm->hard_timeout, fm->cookie,
3929                        fm->flags & OFPFF_SEND_FLOW_REM);
3930     rule_insert(p, rule);
3931     if (packet) {
3932         rule_execute(p, rule, in_port, packet);
3933     }
3934     return error;
3935 }
3936
3937 static struct rule *
3938 find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
3939 {
3940     return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
3941 }
3942
3943 static int
3944 send_buffered_packet(struct ofconn *ofconn,
3945                      struct rule *rule, uint32_t buffer_id)
3946 {
3947     struct ofpbuf *packet;
3948     uint16_t in_port;
3949     int error;
3950
3951     if (buffer_id == UINT32_MAX) {
3952         return 0;
3953     }
3954
3955     error = pktbuf_retrieve(ofconn->pktbuf, buffer_id, &packet, &in_port);
3956     if (error) {
3957         return error;
3958     }
3959
3960     rule_execute(ofconn->ofproto, rule, in_port, packet);
3961
3962     return 0;
3963 }
3964 \f
3965 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
3966
3967 struct modify_flows_cbdata {
3968     struct ofproto *ofproto;
3969     const struct flow_mod *fm;
3970     struct rule *match;
3971 };
3972
3973 static int modify_flow(struct ofproto *, const struct flow_mod *,
3974                        struct rule *);
3975
3976 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
3977  * encoded by ofp_mkerr() on failure.
3978  *
3979  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3980  * if any. */
3981 static int
3982 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
3983 {
3984     struct ofproto *p = ofconn->ofproto;
3985     struct rule *match = NULL;
3986     struct cls_cursor cursor;
3987     struct rule *rule;
3988
3989     cls_cursor_init(&cursor, &p->cls, &fm->cr);
3990     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3991         if (!rule_is_hidden(rule)) {
3992             match = rule;
3993             modify_flow(p, fm, rule);
3994         }
3995     }
3996
3997     if (match) {
3998         /* This credits the packet to whichever flow happened to match last.
3999          * That's weird.  Maybe we should do a lookup for the flow that
4000          * actually matches the packet?  Who knows. */
4001         send_buffered_packet(ofconn, match, fm->buffer_id);
4002         return 0;
4003     } else {
4004         return add_flow(ofconn, fm);
4005     }
4006 }
4007
4008 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
4009  * code as encoded by ofp_mkerr() on failure.
4010  *
4011  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4012  * if any. */
4013 static int
4014 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
4015 {
4016     struct ofproto *p = ofconn->ofproto;
4017     struct rule *rule = find_flow_strict(p, fm);
4018     if (rule && !rule_is_hidden(rule)) {
4019         modify_flow(p, fm, rule);
4020         return send_buffered_packet(ofconn, rule, fm->buffer_id);
4021     } else {
4022         return add_flow(ofconn, fm);
4023     }
4024 }
4025
4026 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
4027  * been identified as a flow in 'p''s flow table to be modified, by changing
4028  * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
4029  * ofp_action[] structures). */
4030 static int
4031 modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
4032 {
4033     size_t actions_len = fm->n_actions * sizeof *rule->actions;
4034
4035     rule->flow_cookie = fm->cookie;
4036
4037     /* If the actions are the same, do nothing. */
4038     if (fm->n_actions == rule->n_actions
4039         && (!fm->n_actions
4040             || !memcmp(fm->actions, rule->actions, actions_len))) {
4041         return 0;
4042     }
4043
4044     /* Replace actions. */
4045     free(rule->actions);
4046     rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
4047     rule->n_actions = fm->n_actions;
4048
4049     p->need_revalidate = true;
4050
4051     return 0;
4052 }
4053 \f
4054 /* OFPFC_DELETE implementation. */
4055
4056 static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
4057
4058 /* Implements OFPFC_DELETE. */
4059 static void
4060 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
4061 {
4062     struct rule *rule, *next_rule;
4063     struct cls_cursor cursor;
4064
4065     cls_cursor_init(&cursor, &p->cls, &fm->cr);
4066     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4067         delete_flow(p, rule, htons(fm->out_port));
4068     }
4069 }
4070
4071 /* Implements OFPFC_DELETE_STRICT. */
4072 static void
4073 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
4074 {
4075     struct rule *rule = find_flow_strict(p, fm);
4076     if (rule) {
4077         delete_flow(p, rule, htons(fm->out_port));
4078     }
4079 }
4080
4081 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
4082  * been identified as a flow to delete from 'p''s flow table, by deleting the
4083  * flow and sending out a OFPT_FLOW_REMOVED message to any interested
4084  * controller.
4085  *
4086  * Will not delete 'rule' if it is hidden.  Will delete 'rule' only if
4087  * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
4088  * specified 'out_port'. */
4089 static void
4090 delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
4091 {
4092     if (rule_is_hidden(rule)) {
4093         return;
4094     }
4095
4096     if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
4097         return;
4098     }
4099
4100     rule_send_removed(p, rule, OFPRR_DELETE);
4101     rule_remove(p, rule);
4102 }
4103 \f
4104 static int
4105 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4106 {
4107     struct ofproto *p = ofconn->ofproto;
4108     struct flow_mod fm;
4109     int error;
4110
4111     error = reject_slave_controller(ofconn, "flow_mod");
4112     if (error) {
4113         return error;
4114     }
4115
4116     error = ofputil_decode_flow_mod(&fm, oh, ofconn->flow_format);
4117     if (error) {
4118         return error;
4119     }
4120
4121     /* We do not support the emergency flow cache.  It will hopefully get
4122      * dropped from OpenFlow in the near future. */
4123     if (fm.flags & OFPFF_EMERG) {
4124         /* There isn't a good fit for an error code, so just state that the
4125          * flow table is full. */
4126         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
4127     }
4128
4129     error = validate_actions(fm.actions, fm.n_actions,
4130                              &fm.cr.flow, p->max_ports);
4131     if (error) {
4132         return error;
4133     }
4134
4135     switch (fm.command) {
4136     case OFPFC_ADD:
4137         return add_flow(ofconn, &fm);
4138
4139     case OFPFC_MODIFY:
4140         return modify_flows_loose(ofconn, &fm);
4141
4142     case OFPFC_MODIFY_STRICT:
4143         return modify_flow_strict(ofconn, &fm);
4144
4145     case OFPFC_DELETE:
4146         delete_flows_loose(p, &fm);
4147         return 0;
4148
4149     case OFPFC_DELETE_STRICT:
4150         delete_flow_strict(p, &fm);
4151         return 0;
4152
4153     default:
4154         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
4155     }
4156 }
4157
4158 static int
4159 handle_tun_id_from_cookie(struct ofconn *ofconn, const struct ofp_header *oh)
4160 {
4161     const struct nxt_tun_id_cookie *msg
4162         = (const struct nxt_tun_id_cookie *) oh;
4163
4164     ofconn->flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
4165     return 0;
4166 }
4167
4168 static int
4169 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4170 {
4171     struct nx_role_request *nrr = (struct nx_role_request *) oh;
4172     struct nx_role_request *reply;
4173     struct ofpbuf *buf;
4174     uint32_t role;
4175
4176     if (ofconn->type != OFCONN_PRIMARY) {
4177         VLOG_WARN_RL(&rl, "ignoring role request on non-controller "
4178                      "connection");
4179         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4180     }
4181
4182     role = ntohl(nrr->role);
4183     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
4184         && role != NX_ROLE_SLAVE) {
4185         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
4186
4187         /* There's no good error code for this. */
4188         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
4189     }
4190
4191     if (role == NX_ROLE_MASTER) {
4192         struct ofconn *other;
4193
4194         HMAP_FOR_EACH (other, hmap_node, &ofconn->ofproto->controllers) {
4195             if (other->role == NX_ROLE_MASTER) {
4196                 other->role = NX_ROLE_SLAVE;
4197             }
4198         }
4199     }
4200     ofconn->role = role;
4201
4202     reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
4203     reply->role = htonl(role);
4204     queue_tx(buf, ofconn, ofconn->reply_counter);
4205
4206     return 0;
4207 }
4208
4209 static int
4210 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4211 {
4212     const struct nxt_set_flow_format *msg
4213         = (const struct nxt_set_flow_format *) oh;
4214     uint32_t format;
4215
4216     format = ntohl(msg->format);
4217     if (format == NXFF_OPENFLOW10
4218         || format == NXFF_TUN_ID_FROM_COOKIE
4219         || format == NXFF_NXM) {
4220         ofconn->flow_format = format;
4221         return 0;
4222     } else {
4223         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4224     }
4225 }
4226
4227 static int
4228 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4229 {
4230     struct ofp_header *ob;
4231     struct ofpbuf *buf;
4232
4233     /* Currently, everything executes synchronously, so we can just
4234      * immediately send the barrier reply. */
4235     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
4236     queue_tx(buf, ofconn, ofconn->reply_counter);
4237     return 0;
4238 }
4239
4240 static int
4241 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4242 {
4243     const struct ofp_header *oh = msg->data;
4244     const struct ofputil_msg_type *type;
4245     int error;
4246
4247     error = ofputil_decode_msg_type(oh, &type);
4248     if (error) {
4249         return error;
4250     }
4251
4252     switch (ofputil_msg_type_code(type)) {
4253         /* OpenFlow requests. */
4254     case OFPUTIL_OFPT_ECHO_REQUEST:
4255         return handle_echo_request(ofconn, oh);
4256
4257     case OFPUTIL_OFPT_FEATURES_REQUEST:
4258         return handle_features_request(ofconn, oh);
4259
4260     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
4261         return handle_get_config_request(ofconn, oh);
4262
4263     case OFPUTIL_OFPT_SET_CONFIG:
4264         return handle_set_config(ofconn, msg->data);
4265
4266     case OFPUTIL_OFPT_PACKET_OUT:
4267         return handle_packet_out(ofconn, oh);
4268
4269     case OFPUTIL_OFPT_PORT_MOD:
4270         return handle_port_mod(ofconn, oh);
4271
4272     case OFPUTIL_OFPT_FLOW_MOD:
4273         return handle_flow_mod(ofconn, oh);
4274
4275     case OFPUTIL_OFPT_BARRIER_REQUEST:
4276         return handle_barrier_request(ofconn, oh);
4277
4278         /* OpenFlow replies. */
4279     case OFPUTIL_OFPT_ECHO_REPLY:
4280         return 0;
4281
4282         /* Nicira extension requests. */
4283     case OFPUTIL_NXT_STATUS_REQUEST:
4284         return switch_status_handle_request(
4285             ofconn->ofproto->switch_status, ofconn->rconn, oh);
4286
4287     case OFPUTIL_NXT_TUN_ID_FROM_COOKIE:
4288         return handle_tun_id_from_cookie(ofconn, oh);
4289
4290     case OFPUTIL_NXT_ROLE_REQUEST:
4291         return handle_role_request(ofconn, oh);
4292
4293     case OFPUTIL_NXT_SET_FLOW_FORMAT:
4294         return handle_nxt_set_flow_format(ofconn, oh);
4295
4296     case OFPUTIL_NXT_FLOW_MOD:
4297         return handle_flow_mod(ofconn, oh);
4298
4299         /* OpenFlow statistics requests. */
4300     case OFPUTIL_OFPST_DESC_REQUEST:
4301         return handle_desc_stats_request(ofconn, oh);
4302
4303     case OFPUTIL_OFPST_FLOW_REQUEST:
4304         return handle_flow_stats_request(ofconn, oh);
4305
4306     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
4307         return handle_aggregate_stats_request(ofconn, oh);
4308
4309     case OFPUTIL_OFPST_TABLE_REQUEST:
4310         return handle_table_stats_request(ofconn, oh);
4311
4312     case OFPUTIL_OFPST_PORT_REQUEST:
4313         return handle_port_stats_request(ofconn, oh);
4314
4315     case OFPUTIL_OFPST_QUEUE_REQUEST:
4316         return handle_queue_stats_request(ofconn, oh);
4317
4318         /* Nicira extension statistics requests. */
4319     case OFPUTIL_NXST_FLOW_REQUEST:
4320         return handle_nxst_flow(ofconn, oh);
4321
4322     case OFPUTIL_NXST_AGGREGATE_REQUEST:
4323         return handle_nxst_aggregate(ofconn, oh);
4324
4325     case OFPUTIL_INVALID:
4326     case OFPUTIL_OFPT_HELLO:
4327     case OFPUTIL_OFPT_ERROR:
4328     case OFPUTIL_OFPT_FEATURES_REPLY:
4329     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
4330     case OFPUTIL_OFPT_PACKET_IN:
4331     case OFPUTIL_OFPT_FLOW_REMOVED:
4332     case OFPUTIL_OFPT_PORT_STATUS:
4333     case OFPUTIL_OFPT_BARRIER_REPLY:
4334     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
4335     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
4336     case OFPUTIL_OFPST_DESC_REPLY:
4337     case OFPUTIL_OFPST_FLOW_REPLY:
4338     case OFPUTIL_OFPST_QUEUE_REPLY:
4339     case OFPUTIL_OFPST_PORT_REPLY:
4340     case OFPUTIL_OFPST_TABLE_REPLY:
4341     case OFPUTIL_OFPST_AGGREGATE_REPLY:
4342     case OFPUTIL_NXT_STATUS_REPLY:
4343     case OFPUTIL_NXT_ROLE_REPLY:
4344     case OFPUTIL_NXT_FLOW_REMOVED:
4345     case OFPUTIL_NXST_FLOW_REPLY:
4346     case OFPUTIL_NXST_AGGREGATE_REPLY:
4347     default:
4348         if (VLOG_IS_WARN_ENABLED()) {
4349             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
4350             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
4351             free(s);
4352         }
4353         if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
4354             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
4355         } else {
4356             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
4357         }
4358     }
4359 }
4360
4361 static void
4362 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
4363 {
4364     int error = handle_openflow__(ofconn, ofp_msg);
4365     if (error) {
4366         send_error_oh(ofconn, ofp_msg->data, error);
4367     }
4368     COVERAGE_INC(ofproto_recv_openflow);
4369 }
4370 \f
4371 static void
4372 handle_miss_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4373 {
4374     struct facet *facet;
4375     struct flow flow;
4376
4377     /* Obtain in_port and tun_id, at least. */
4378     odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4379
4380     /* Set header pointers in 'flow'. */
4381     flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
4382
4383     /* Check with in-band control to see if this packet should be sent
4384      * to the local port regardless of the flow table. */
4385     if (in_band_msg_in_hook(p->in_band, &flow, upcall->packet)) {
4386         struct ofpbuf odp_actions;
4387
4388         ofpbuf_init(&odp_actions, 32);
4389         nl_msg_put_u32(&odp_actions, ODPAT_OUTPUT, ODPP_LOCAL);
4390         dpif_execute(p->dpif, odp_actions.data, odp_actions.size,
4391                      upcall->packet);
4392         ofpbuf_uninit(&odp_actions);
4393     }
4394
4395     facet = facet_lookup_valid(p, &flow);
4396     if (!facet) {
4397         struct rule *rule = rule_lookup(p, &flow);
4398         if (!rule) {
4399             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
4400             struct ofport *port = get_port(p, flow.in_port);
4401             if (port) {
4402                 if (port->opp.config & OFPPC_NO_PACKET_IN) {
4403                     COVERAGE_INC(ofproto_no_packet_in);
4404                     /* XXX install 'drop' flow entry */
4405                     ofpbuf_delete(upcall->packet);
4406                     return;
4407                 }
4408             } else {
4409                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
4410                              flow.in_port);
4411             }
4412
4413             COVERAGE_INC(ofproto_packet_in);
4414             send_packet_in(p, upcall, &flow, false);
4415             return;
4416         }
4417
4418         facet = facet_create(p, rule, &flow, upcall->packet);
4419     } else if (!facet->may_install) {
4420         /* The facet is not installable, that is, we need to process every
4421          * packet, so process the current packet's actions into 'facet'. */
4422         facet_make_actions(p, facet, upcall->packet);
4423     }
4424
4425     if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
4426         /*
4427          * Extra-special case for fail-open mode.
4428          *
4429          * We are in fail-open mode and the packet matched the fail-open rule,
4430          * but we are connected to a controller too.  We should send the packet
4431          * up to the controller in the hope that it will try to set up a flow
4432          * and thereby allow us to exit fail-open.
4433          *
4434          * See the top-level comment in fail-open.c for more information.
4435          */
4436         send_packet_in(p, upcall, &flow, true);
4437     }
4438
4439     facet_execute(p, facet, upcall->packet);
4440     facet_install(p, facet, false);
4441 }
4442
4443 static void
4444 handle_upcall(struct ofproto *p, struct dpif_upcall *upcall)
4445 {
4446     struct flow flow;
4447
4448     switch (upcall->type) {
4449     case _ODPL_ACTION_NR:
4450         COVERAGE_INC(ofproto_ctlr_action);
4451         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4452         send_packet_in(p, upcall, &flow, false);
4453         break;
4454
4455     case _ODPL_SFLOW_NR:
4456         if (p->sflow) {
4457             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
4458             ofproto_sflow_received(p->sflow, upcall, &flow);
4459         }
4460         ofpbuf_delete(upcall->packet);
4461         break;
4462
4463     case _ODPL_MISS_NR:
4464         handle_miss_upcall(p, upcall);
4465         break;
4466
4467     default:
4468         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
4469         break;
4470     }
4471 }
4472 \f
4473 /* Flow expiration. */
4474
4475 static int ofproto_dp_max_idle(const struct ofproto *);
4476 static void ofproto_update_used(struct ofproto *);
4477 static void rule_expire(struct ofproto *, struct rule *);
4478 static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
4479
4480 /* This function is called periodically by ofproto_run().  Its job is to
4481  * collect updates for the flows that have been installed into the datapath,
4482  * most importantly when they last were used, and then use that information to
4483  * expire flows that have not been used recently.
4484  *
4485  * Returns the number of milliseconds after which it should be called again. */
4486 static int
4487 ofproto_expire(struct ofproto *ofproto)
4488 {
4489     struct rule *rule, *next_rule;
4490     struct cls_cursor cursor;
4491     int dp_max_idle;
4492
4493     /* Update 'used' for each flow in the datapath. */
4494     ofproto_update_used(ofproto);
4495
4496     /* Expire facets that have been idle too long. */
4497     dp_max_idle = ofproto_dp_max_idle(ofproto);
4498     ofproto_expire_facets(ofproto, dp_max_idle);
4499
4500     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
4501     cls_cursor_init(&cursor, &ofproto->cls, NULL);
4502     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4503         rule_expire(ofproto, rule);
4504     }
4505
4506     /* Let the hook know that we're at a stable point: all outstanding data
4507      * in existing flows has been accounted to the account_cb.  Thus, the
4508      * hook can now reasonably do operations that depend on having accurate
4509      * flow volume accounting (currently, that's just bond rebalancing). */
4510     if (ofproto->ofhooks->account_checkpoint_cb) {
4511         ofproto->ofhooks->account_checkpoint_cb(ofproto->aux);
4512     }
4513
4514     return MIN(dp_max_idle, 1000);
4515 }
4516
4517 /* Update 'used' member of installed facets. */
4518 static void
4519 ofproto_update_used(struct ofproto *p)
4520 {
4521     const struct odp_flow_stats *stats;
4522     struct dpif_flow_dump dump;
4523     const struct nlattr *key;
4524     size_t key_len;
4525
4526     dpif_flow_dump_start(&dump, p->dpif);
4527     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
4528         struct facet *facet;
4529         struct flow flow;
4530
4531         if (odp_flow_key_to_flow(key, key_len, &flow)) {
4532             struct ds s;
4533
4534             ds_init(&s);
4535             odp_flow_key_format(key, key_len, &s);
4536             VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
4537                          ds_cstr(&s));
4538             ds_destroy(&s);
4539
4540             continue;
4541         }
4542         facet = facet_find(p, &flow);
4543
4544         if (facet && facet->installed) {
4545             facet_update_time(p, facet, stats);
4546             facet_account(p, facet, stats->n_bytes);
4547         } else {
4548             /* There's a flow in the datapath that we know nothing about.
4549              * Delete it. */
4550             COVERAGE_INC(ofproto_unexpected_rule);
4551             dpif_flow_del(p->dpif, key, key_len, NULL);
4552         }
4553     }
4554     dpif_flow_dump_done(&dump);
4555 }
4556
4557 /* Calculates and returns the number of milliseconds of idle time after which
4558  * facets should expire from the datapath and we should fold their statistics
4559  * into their parent rules in userspace. */
4560 static int
4561 ofproto_dp_max_idle(const struct ofproto *ofproto)
4562 {
4563     /*
4564      * Idle time histogram.
4565      *
4566      * Most of the time a switch has a relatively small number of facets.  When
4567      * this is the case we might as well keep statistics for all of them in
4568      * userspace and to cache them in the kernel datapath for performance as
4569      * well.
4570      *
4571      * As the number of facets increases, the memory required to maintain
4572      * statistics about them in userspace and in the kernel becomes
4573      * significant.  However, with a large number of facets it is likely that
4574      * only a few of them are "heavy hitters" that consume a large amount of
4575      * bandwidth.  At this point, only heavy hitters are worth caching in the
4576      * kernel and maintaining in userspaces; other facets we can discard.
4577      *
4578      * The technique used to compute the idle time is to build a histogram with
4579      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each facet
4580      * that is installed in the kernel gets dropped in the appropriate bucket.
4581      * After the histogram has been built, we compute the cutoff so that only
4582      * the most-recently-used 1% of facets (but at least 1000 flows) are kept
4583      * cached.  At least the most-recently-used bucket of facets is kept, so
4584      * actually an arbitrary number of facets can be kept in any given
4585      * expiration run (though the next run will delete most of those unless
4586      * they receive additional data).
4587      *
4588      * This requires a second pass through the facets, in addition to the pass
4589      * made by ofproto_update_used(), because the former function never looks
4590      * at uninstallable facets.
4591      */
4592     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4593     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4594     int buckets[N_BUCKETS] = { 0 };
4595     struct facet *facet;
4596     int total, bucket;
4597     long long int now;
4598     int i;
4599
4600     total = hmap_count(&ofproto->facets);
4601     if (total <= 1000) {
4602         return N_BUCKETS * BUCKET_WIDTH;
4603     }
4604
4605     /* Build histogram. */
4606     now = time_msec();
4607     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
4608         long long int idle = now - facet->used;
4609         int bucket = (idle <= 0 ? 0
4610                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4611                       : (unsigned int) idle / BUCKET_WIDTH);
4612         buckets[bucket]++;
4613     }
4614
4615     /* Find the first bucket whose flows should be expired. */
4616     for (bucket = 0; bucket < N_BUCKETS; bucket++) {
4617         if (buckets[bucket]) {
4618             int subtotal = 0;
4619             do {
4620                 subtotal += buckets[bucket++];
4621             } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
4622             break;
4623         }
4624     }
4625
4626     if (VLOG_IS_DBG_ENABLED()) {
4627         struct ds s;
4628
4629         ds_init(&s);
4630         ds_put_cstr(&s, "keep");
4631         for (i = 0; i < N_BUCKETS; i++) {
4632             if (i == bucket) {
4633                 ds_put_cstr(&s, ", drop");
4634             }
4635             if (buckets[i]) {
4636                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4637             }
4638         }
4639         VLOG_INFO("%s: %s (msec:count)",
4640                   dpif_name(ofproto->dpif), ds_cstr(&s));
4641         ds_destroy(&s);
4642     }
4643
4644     return bucket * BUCKET_WIDTH;
4645 }
4646
4647 static void
4648 facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
4649 {
4650     if (ofproto->netflow && !facet_is_controller_flow(facet) &&
4651         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
4652         struct ofexpired expired;
4653
4654         expired.flow = facet->flow;
4655         expired.packet_count = facet->packet_count;
4656         expired.byte_count = facet->byte_count;
4657         expired.used = facet->used;
4658
4659         /* Get updated flow stats.
4660          *
4661          * XXX We could avoid this call entirely if (1) ofproto_update_used()
4662          * updated TCP flags and (2) the dpif_flow_list_all() in
4663          * ofproto_update_used() zeroed TCP flags. */
4664         if (facet->installed) {
4665             uint32_t keybuf[ODPUTIL_FLOW_KEY_U32S];
4666             struct odp_flow_stats stats;
4667             struct ofpbuf key;
4668
4669             ofpbuf_use_stack(&key, keybuf, sizeof keybuf);
4670             odp_flow_key_from_flow(&key, &facet->flow);
4671
4672             if (!dpif_flow_get(ofproto->dpif, ODPFF_ZERO_TCP_FLAGS,
4673                                key.data, key.size, NULL, &stats)) {
4674                 expired.packet_count += stats.n_packets;
4675                 expired.byte_count += stats.n_bytes;
4676                 if (stats.n_packets) {
4677                     facet_update_time(ofproto, facet, &stats);
4678                     netflow_flow_update_flags(&facet->nf_flow,
4679                                               stats.tcp_flags);
4680                 }
4681             }
4682         }
4683
4684         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4685     }
4686 }
4687
4688 static void
4689 ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
4690 {
4691     long long int cutoff = time_msec() - dp_max_idle;
4692     struct facet *facet, *next_facet;
4693
4694     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
4695         facet_active_timeout(ofproto, facet);
4696         if (facet->used < cutoff) {
4697             facet_remove(ofproto, facet);
4698         }
4699     }
4700 }
4701
4702 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4703  * then delete it entirely. */
4704 static void
4705 rule_expire(struct ofproto *ofproto, struct rule *rule)
4706 {
4707     struct facet *facet, *next_facet;
4708     long long int now;
4709     uint8_t reason;
4710
4711     /* Has 'rule' expired? */
4712     now = time_msec();
4713     if (rule->hard_timeout
4714         && now > rule->created + rule->hard_timeout * 1000) {
4715         reason = OFPRR_HARD_TIMEOUT;
4716     } else if (rule->idle_timeout && list_is_empty(&rule->facets)
4717                && now >rule->used + rule->idle_timeout * 1000) {
4718         reason = OFPRR_IDLE_TIMEOUT;
4719     } else {
4720         return;
4721     }
4722
4723     COVERAGE_INC(ofproto_expired);
4724
4725     /* Update stats.  (This is a no-op if the rule expired due to an idle
4726      * timeout, because that only happens when the rule has no facets left.) */
4727     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4728         facet_remove(ofproto, facet);
4729     }
4730
4731     /* Get rid of the rule. */
4732     if (!rule_is_hidden(rule)) {
4733         rule_send_removed(ofproto, rule, reason);
4734     }
4735     rule_remove(ofproto, rule);
4736 }
4737 \f
4738 static struct ofpbuf *
4739 compose_ofp_flow_removed(struct ofconn *ofconn, const struct rule *rule,
4740                          uint8_t reason)
4741 {
4742     struct ofp_flow_removed *ofr;
4743     struct ofpbuf *buf;
4744
4745     ofr = make_openflow_xid(sizeof *ofr, OFPT_FLOW_REMOVED, htonl(0), &buf);
4746     ofputil_cls_rule_to_match(&rule->cr, ofconn->flow_format, &ofr->match,
4747                               rule->flow_cookie, &ofr->cookie);
4748     ofr->priority = htons(rule->cr.priority);
4749     ofr->reason = reason;
4750     calc_flow_duration(rule->created, &ofr->duration_sec, &ofr->duration_nsec);
4751     ofr->idle_timeout = htons(rule->idle_timeout);
4752     ofr->packet_count = htonll(rule->packet_count);
4753     ofr->byte_count = htonll(rule->byte_count);
4754
4755     return buf;
4756 }
4757
4758 static struct ofpbuf *
4759 compose_nx_flow_removed(const struct rule *rule, uint8_t reason)
4760 {
4761     struct nx_flow_removed *nfr;
4762     struct ofpbuf *buf;
4763     int match_len;
4764
4765     make_nxmsg_xid(sizeof *nfr, NXT_FLOW_REMOVED, htonl(0), &buf);
4766     match_len = nx_put_match(buf, &rule->cr);
4767
4768     nfr = buf->data;
4769     nfr->cookie = rule->flow_cookie;
4770     nfr->priority = htons(rule->cr.priority);
4771     nfr->reason = reason;
4772     calc_flow_duration(rule->created, &nfr->duration_sec, &nfr->duration_nsec);
4773     nfr->idle_timeout = htons(rule->idle_timeout);
4774     nfr->match_len = htons(match_len);
4775     nfr->packet_count = htonll(rule->packet_count);
4776     nfr->byte_count = htonll(rule->byte_count);
4777
4778     return buf;
4779 }
4780
4781 static void
4782 rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
4783 {
4784     struct ofconn *ofconn;
4785
4786     if (!rule->send_flow_removed) {
4787         return;
4788     }
4789
4790     LIST_FOR_EACH (ofconn, node, &p->all_conns) {
4791         struct ofpbuf *msg;
4792
4793         if (!rconn_is_connected(ofconn->rconn)
4794             || !ofconn_receives_async_msgs(ofconn)) {
4795             continue;
4796         }
4797
4798         msg = (ofconn->flow_format == NXFF_NXM
4799                ? compose_nx_flow_removed(rule, reason)
4800                : compose_ofp_flow_removed(ofconn, rule, reason));
4801
4802         /* Account flow expirations under ofconn->reply_counter, the counter
4803          * for replies to OpenFlow requests.  That works because preventing
4804          * OpenFlow requests from being processed also prevents new flows from
4805          * being added (and expiring).  (It also prevents processing OpenFlow
4806          * requests that would not add new flows, so it is imperfect.) */
4807         queue_tx(msg, ofconn, ofconn->reply_counter);
4808     }
4809 }
4810
4811 /* pinsched callback for sending 'ofp_packet_in' on 'ofconn'. */
4812 static void
4813 do_send_packet_in(struct ofpbuf *ofp_packet_in, void *ofconn_)
4814 {
4815     struct ofconn *ofconn = ofconn_;
4816
4817     rconn_send_with_limit(ofconn->rconn, ofp_packet_in,
4818                           ofconn->packet_in_counter, 100);
4819 }
4820
4821 /* Takes 'upcall', whose packet has the flow specified by 'flow', composes an
4822  * OpenFlow packet-in message from it, and passes it to 'ofconn''s packet
4823  * scheduler for sending.
4824  *
4825  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
4826  * Otherwise, ownership is transferred to this function. */
4827 static void
4828 schedule_packet_in(struct ofconn *ofconn, struct dpif_upcall *upcall,
4829                    const struct flow *flow, bool clone)
4830 {
4831     enum { OPI_SIZE = offsetof(struct ofp_packet_in, data) };
4832     struct ofproto *ofproto = ofconn->ofproto;
4833     struct ofp_packet_in *opi;
4834     int total_len, send_len;
4835     struct ofpbuf *packet;
4836     uint32_t buffer_id;
4837
4838     /* Get OpenFlow buffer_id. */
4839     if (upcall->type == _ODPL_ACTION_NR) {
4840         buffer_id = UINT32_MAX;
4841     } else if (ofproto->fail_open && fail_open_is_active(ofproto->fail_open)) {
4842         buffer_id = pktbuf_get_null();
4843     } else if (!ofconn->pktbuf) {
4844         buffer_id = UINT32_MAX;
4845     } else {
4846         buffer_id = pktbuf_save(ofconn->pktbuf, upcall->packet, flow->in_port);
4847     }
4848
4849     /* Figure out how much of the packet to send. */
4850     total_len = send_len = upcall->packet->size;
4851     if (buffer_id != UINT32_MAX) {
4852         send_len = MIN(send_len, ofconn->miss_send_len);
4853     }
4854     if (upcall->type == _ODPL_ACTION_NR) {
4855         send_len = MIN(send_len, upcall->userdata);
4856     }
4857
4858     /* Copy or steal buffer for OFPT_PACKET_IN. */
4859     if (clone) {
4860         packet = ofpbuf_clone_data_with_headroom(upcall->packet->data,
4861                                                  send_len, OPI_SIZE);
4862     } else {
4863         packet = upcall->packet;
4864         packet->size = send_len;
4865     }
4866
4867     /* Add OFPT_PACKET_IN. */
4868     opi = ofpbuf_push_zeros(packet, OPI_SIZE);
4869     opi->header.version = OFP_VERSION;
4870     opi->header.type = OFPT_PACKET_IN;
4871     opi->total_len = htons(total_len);
4872     opi->in_port = htons(odp_port_to_ofp_port(flow->in_port));
4873     opi->reason = upcall->type == _ODPL_MISS_NR ? OFPR_NO_MATCH : OFPR_ACTION;
4874     opi->buffer_id = htonl(buffer_id);
4875     update_openflow_length(packet);
4876
4877     /* Hand over to packet scheduler.  It might immediately call into
4878      * do_send_packet_in() or it might buffer it for a while (until a later
4879      * call to pinsched_run()). */
4880     pinsched_send(ofconn->schedulers[opi->reason], flow->in_port,
4881                   packet, do_send_packet_in, ofconn);
4882 }
4883
4884 /* Given 'upcall', of type _ODPL_ACTION_NR or _ODPL_MISS_NR, sends an
4885  * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
4886  * their individual configurations.
4887  *
4888  * Takes ownership of 'packet'. */
4889 static void
4890 send_packet_in(struct ofproto *ofproto, struct dpif_upcall *upcall,
4891                const struct flow *flow, bool clone)
4892 {
4893     struct ofconn *ofconn, *prev;
4894
4895     prev = NULL;
4896     LIST_FOR_EACH (ofconn, node, &ofproto->all_conns) {
4897         if (ofconn_receives_async_msgs(ofconn)) {
4898             if (prev) {
4899                 schedule_packet_in(prev, upcall, flow, true);
4900             }
4901             prev = ofconn;
4902         }
4903     }
4904     if (prev) {
4905         schedule_packet_in(prev, upcall, flow, clone);
4906     } else if (!clone) {
4907         ofpbuf_delete(upcall->packet);
4908     }
4909 }
4910
4911 static uint64_t
4912 pick_datapath_id(const struct ofproto *ofproto)
4913 {
4914     const struct ofport *port;
4915
4916     port = get_port(ofproto, ODPP_LOCAL);
4917     if (port) {
4918         uint8_t ea[ETH_ADDR_LEN];
4919         int error;
4920
4921         error = netdev_get_etheraddr(port->netdev, ea);
4922         if (!error) {
4923             return eth_addr_to_uint64(ea);
4924         }
4925         VLOG_WARN("could not get MAC address for %s (%s)",
4926                   netdev_get_name(port->netdev), strerror(error));
4927     }
4928     return ofproto->fallback_dpid;
4929 }
4930
4931 static uint64_t
4932 pick_fallback_dpid(void)
4933 {
4934     uint8_t ea[ETH_ADDR_LEN];
4935     eth_addr_nicira_random(ea);
4936     return eth_addr_to_uint64(ea);
4937 }
4938 \f
4939 static void
4940 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
4941                      void *aux OVS_UNUSED)
4942 {
4943     const struct shash_node *node;
4944     struct ds results;
4945
4946     ds_init(&results);
4947     SHASH_FOR_EACH (node, &all_ofprotos) {
4948         ds_put_format(&results, "%s\n", node->name);
4949     }
4950     unixctl_command_reply(conn, 200, ds_cstr(&results));
4951     ds_destroy(&results);
4952 }
4953
4954 struct ofproto_trace {
4955     struct action_xlate_ctx ctx;
4956     struct flow flow;
4957     struct ds *result;
4958 };
4959
4960 static void
4961 trace_format_rule(struct ds *result, int level, const struct rule *rule)
4962 {
4963     ds_put_char_multiple(result, '\t', level);
4964     if (!rule) {
4965         ds_put_cstr(result, "No match\n");
4966         return;
4967     }
4968
4969     ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
4970                   ntohll(rule->flow_cookie));
4971     cls_rule_format(&rule->cr, result);
4972     ds_put_char(result, '\n');
4973
4974     ds_put_char_multiple(result, '\t', level);
4975     ds_put_cstr(result, "OpenFlow ");
4976     ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
4977                       rule->n_actions * sizeof *rule->actions);
4978     ds_put_char(result, '\n');
4979 }
4980
4981 static void
4982 trace_format_flow(struct ds *result, int level, const char *title,
4983                  struct ofproto_trace *trace)
4984 {
4985     ds_put_char_multiple(result, '\t', level);
4986     ds_put_format(result, "%s: ", title);
4987     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
4988         ds_put_cstr(result, "unchanged");
4989     } else {
4990         flow_format(result, &trace->ctx.flow);
4991         trace->flow = trace->ctx.flow;
4992     }
4993     ds_put_char(result, '\n');
4994 }
4995
4996 static void
4997 trace_resubmit(struct action_xlate_ctx *ctx, const struct rule *rule)
4998 {
4999     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5000     struct ds *result = trace->result;
5001
5002     ds_put_char(result, '\n');
5003     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5004     trace_format_rule(result, ctx->recurse + 1, rule);
5005 }
5006
5007 static void
5008 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5009                       void *aux OVS_UNUSED)
5010 {
5011     char *dpname, *in_port_s, *tun_id_s, *packet_s;
5012     char *args = xstrdup(args_);
5013     char *save_ptr = NULL;
5014     struct ofproto *ofproto;
5015     struct ofpbuf packet;
5016     struct rule *rule;
5017     struct ds result;
5018     struct flow flow;
5019     uint16_t in_port;
5020     ovs_be64 tun_id;
5021     char *s;
5022
5023     ofpbuf_init(&packet, strlen(args) / 2);
5024     ds_init(&result);
5025
5026     dpname = strtok_r(args, " ", &save_ptr);
5027     tun_id_s = strtok_r(NULL, " ", &save_ptr);
5028     in_port_s = strtok_r(NULL, " ", &save_ptr);
5029     packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5030     if (!dpname || !in_port_s || !packet_s) {
5031         unixctl_command_reply(conn, 501, "Bad command syntax");
5032         goto exit;
5033     }
5034
5035     ofproto = shash_find_data(&all_ofprotos, dpname);
5036     if (!ofproto) {
5037         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5038                               "for help)");
5039         goto exit;
5040     }
5041
5042     tun_id = htonll(strtoull(tun_id_s, NULL, 10));
5043     in_port = ofp_port_to_odp_port(atoi(in_port_s));
5044
5045     packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
5046     packet_s += strspn(packet_s, " ");
5047     if (*packet_s != '\0') {
5048         unixctl_command_reply(conn, 501, "Trailing garbage in command");
5049         goto exit;
5050     }
5051     if (packet.size < ETH_HEADER_LEN) {
5052         unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
5053         goto exit;
5054     }
5055
5056     ds_put_cstr(&result, "Packet: ");
5057     s = ofp_packet_to_string(packet.data, packet.size, packet.size);
5058     ds_put_cstr(&result, s);
5059     free(s);
5060
5061     flow_extract(&packet, tun_id, in_port, &flow);
5062     ds_put_cstr(&result, "Flow: ");
5063     flow_format(&result, &flow);
5064     ds_put_char(&result, '\n');
5065
5066     rule = rule_lookup(ofproto, &flow);
5067     trace_format_rule(&result, 0, rule);
5068     if (rule) {
5069         struct ofproto_trace trace;
5070         struct ofpbuf *odp_actions;
5071
5072         trace.result = &result;
5073         trace.flow = flow;
5074         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
5075         trace.ctx.resubmit_hook = trace_resubmit;
5076         odp_actions = xlate_actions(&trace.ctx,
5077                                     rule->actions, rule->n_actions);
5078
5079         ds_put_char(&result, '\n');
5080         trace_format_flow(&result, 0, "Final flow", &trace);
5081         ds_put_cstr(&result, "Datapath actions: ");
5082         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5083         ofpbuf_delete(odp_actions);
5084     }
5085
5086     unixctl_command_reply(conn, 200, ds_cstr(&result));
5087
5088 exit:
5089     ds_destroy(&result);
5090     ofpbuf_uninit(&packet);
5091     free(args);
5092 }
5093
5094 static void
5095 ofproto_unixctl_init(void)
5096 {
5097     static bool registered;
5098     if (registered) {
5099         return;
5100     }
5101     registered = true;
5102
5103     unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
5104     unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
5105 }
5106 \f
5107 static bool
5108 default_normal_ofhook_cb(const struct flow *flow, const struct ofpbuf *packet,
5109                          struct ofpbuf *odp_actions, tag_type *tags,
5110                          uint16_t *nf_output_iface, void *ofproto_)
5111 {
5112     struct ofproto *ofproto = ofproto_;
5113     int out_port;
5114
5115     /* Drop frames for reserved multicast addresses. */
5116     if (eth_addr_is_reserved(flow->dl_dst)) {
5117         return true;
5118     }
5119
5120     /* Learn source MAC (but don't try to learn from revalidation). */
5121     if (packet != NULL) {
5122         tag_type rev_tag = mac_learning_learn(ofproto->ml, flow->dl_src,
5123                                               0, flow->in_port,
5124                                               GRAT_ARP_LOCK_NONE);
5125         if (rev_tag) {
5126             /* The log messages here could actually be useful in debugging,
5127              * so keep the rate limit relatively high. */
5128             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
5129             VLOG_DBG_RL(&rl, "learned that "ETH_ADDR_FMT" is on port %"PRIu16,
5130                         ETH_ADDR_ARGS(flow->dl_src), flow->in_port);
5131             ofproto_revalidate(ofproto, rev_tag);
5132         }
5133     }
5134
5135     /* Determine output port. */
5136     out_port = mac_learning_lookup_tag(ofproto->ml, flow->dl_dst, 0, tags,
5137                                        NULL);
5138     if (out_port < 0) {
5139         flood_packets(ofproto, flow->in_port, OFPPC_NO_FLOOD,
5140                       nf_output_iface, odp_actions);
5141     } else if (out_port != flow->in_port) {
5142         nl_msg_put_u32(odp_actions, ODPAT_OUTPUT, out_port);
5143         *nf_output_iface = out_port;
5144     } else {
5145         /* Drop. */
5146     }
5147
5148     return true;
5149 }
5150
5151 static const struct ofhooks default_ofhooks = {
5152     default_normal_ofhook_cb,
5153     NULL,
5154     NULL
5155 };