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