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