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