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