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