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