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