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