dpif: Improve abstraction by making 'run' and 'wait' functions per-dpif.
[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 'port_no' on 'ofproto'. */
657 void
658 ofproto_port_clear_cfm(struct ofproto *ofproto, uint32_t port_no)
659 {
660     struct ofport *ofport = get_port(ofproto, port_no);
661     if (ofport && ofport->cfm){
662         cfm_destroy(ofport->cfm);
663         ofport->cfm = NULL;
664     }
665 }
666
667 /* Configures connectivity fault management on 'port_no' 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 'port_no'. */
673 void
674 ofproto_port_set_cfm(struct ofproto *ofproto, uint32_t port_no,
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, port_no);
681     if (!ofport) {
682         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu32,
683                   ofproto->name, port_no);
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 %"PRIu32" (%s) failed",
699                   ofproto->name, port_no,
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 'port_no'
707  * within 'ofproto', or a null pointer if 'ofproto' does not have a port
708  * 'port_no' or if that port does not have CFM configured.  The caller must not
709  * modify or destroy the returned object. */
710 const struct cfm *
711 ofproto_port_get_cfm(struct ofproto *ofproto, uint32_t port_no)
712 {
713     struct ofport *ofport = get_port(ofproto, port_no);
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 port OpenFlow 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  *
1620  * This is almost the same as calling dpif_port_del() directly on the
1621  * datapath, but it also makes 'ofproto' close its open netdev for the port
1622  * (if any).  This makes it possible to create a new netdev of a different
1623  * type under the same name, which otherwise the netdev library would refuse
1624  * to do because of the conflict.  (The netdev would eventually get closed on
1625  * the next trip through ofproto_run(), but this interface is more direct.)
1626  *
1627  * Returns 0 if successful, otherwise a positive errno. */
1628 int
1629 ofproto_port_del(struct ofproto *ofproto, uint16_t ofp_port)
1630 {
1631     uint32_t odp_port = ofp_port_to_odp_port(ofp_port);
1632     struct ofport *ofport = get_port(ofproto, odp_port);
1633     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1634     int error;
1635
1636     error = dpif_port_del(ofproto->dpif, odp_port);
1637     if (error) {
1638         VLOG_ERR("%s: failed to remove port %"PRIu16" (%s) interface (%s)",
1639                  ofproto->name, odp_port, name, strerror(error));
1640     } else if (ofport) {
1641         /* 'name' is the netdev's name and update_port() is going to close the
1642          * netdev.  Just in case update_port() refers to 'name' after it
1643          * destroys 'ofport', make a copy of it around the update_port()
1644          * call. */
1645         char *devname = xstrdup(name);
1646         update_port(ofproto, devname);
1647         free(devname);
1648     }
1649     return error;
1650 }
1651
1652 /* Sends 'packet' out of port 'port_no' within 'p'.  If 'vlan_tci' is zero the
1653  * packet will not have any 802.1Q hader; if it is nonzero, then the packet
1654  * will be sent with the VLAN TCI specified by 'vlan_tci & ~VLAN_CFI'.
1655  *
1656  * Returns 0 if successful, otherwise a positive errno value. */
1657 static int
1658 ofproto_send_packet(struct ofproto *ofproto,
1659                     uint32_t port_no, uint16_t vlan_tci,
1660                     const struct ofpbuf *packet)
1661 {
1662     struct ofpbuf odp_actions;
1663     int error;
1664
1665     ofpbuf_init(&odp_actions, 32);
1666     if (vlan_tci != 0) {
1667         nl_msg_put_u32(&odp_actions, ODP_ACTION_ATTR_SET_DL_TCI,
1668                        ntohs(vlan_tci & ~VLAN_CFI));
1669     }
1670     nl_msg_put_u32(&odp_actions, ODP_ACTION_ATTR_OUTPUT, port_no);
1671     error = dpif_execute(ofproto->dpif, odp_actions.data, odp_actions.size,
1672                          packet);
1673     ofpbuf_uninit(&odp_actions);
1674
1675     if (error) {
1676         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
1677                      ofproto->name, port_no, strerror(error));
1678     }
1679     return error;
1680 }
1681
1682 /* Adds a flow to the OpenFlow flow table in 'p' that matches 'cls_rule' and
1683  * performs the 'n_actions' actions in 'actions'.  The new flow will not
1684  * timeout.
1685  *
1686  * If cls_rule->priority is in the range of priorities supported by OpenFlow
1687  * (0...65535, inclusive) then the flow will be visible to OpenFlow
1688  * controllers; otherwise, it will be hidden.
1689  *
1690  * The caller retains ownership of 'cls_rule' and 'actions'. */
1691 void
1692 ofproto_add_flow(struct ofproto *p, const struct cls_rule *cls_rule,
1693                  const union ofp_action *actions, size_t n_actions)
1694 {
1695     struct rule *rule;
1696     rule = rule_create(cls_rule, actions, n_actions, 0, 0, 0, false);
1697     rule_insert(p, rule);
1698 }
1699
1700 void
1701 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
1702 {
1703     struct rule *rule;
1704
1705     rule = rule_from_cls_rule(classifier_find_rule_exactly(&ofproto->cls,
1706                                                            target));
1707     if (rule) {
1708         rule_remove(ofproto, rule);
1709     }
1710 }
1711
1712 static void
1713 ofproto_flush_flows__(struct ofproto *ofproto)
1714 {
1715     struct facet *facet, *next_facet;
1716     struct rule *rule, *next_rule;
1717     struct cls_cursor cursor;
1718
1719     COVERAGE_INC(ofproto_flush);
1720
1721     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
1722         /* Mark the facet as not installed so that facet_remove() doesn't
1723          * bother trying to uninstall it.  There is no point in uninstalling it
1724          * individually since we are about to blow away all the facets with
1725          * dpif_flow_flush(). */
1726         facet->installed = false;
1727         facet->dp_packet_count = 0;
1728         facet->dp_byte_count = 0;
1729         facet_remove(ofproto, facet);
1730     }
1731
1732     cls_cursor_init(&cursor, &ofproto->cls, NULL);
1733     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1734         rule_remove(ofproto, rule);
1735     }
1736
1737     dpif_flow_flush(ofproto->dpif);
1738 }
1739
1740 void
1741 ofproto_flush_flows(struct ofproto *ofproto)
1742 {
1743     ofproto_flush_flows__(ofproto);
1744     connmgr_flushed(ofproto->connmgr);
1745 }
1746 \f
1747 static void
1748 reinit_ports(struct ofproto *p)
1749 {
1750     struct dpif_port_dump dump;
1751     struct sset devnames;
1752     struct ofport *ofport;
1753     struct dpif_port dpif_port;
1754     const char *devname;
1755
1756     COVERAGE_INC(ofproto_reinit_ports);
1757
1758     sset_init(&devnames);
1759     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1760         sset_add(&devnames, netdev_get_name(ofport->netdev));
1761     }
1762     DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
1763         sset_add(&devnames, dpif_port.name);
1764     }
1765
1766     SSET_FOR_EACH (devname, &devnames) {
1767         update_port(p, devname);
1768     }
1769     sset_destroy(&devnames);
1770 }
1771
1772 /* Opens and returns a netdev for 'dpif_port', or a null pointer if the netdev
1773  * cannot be opened.  On success, also fills in 'opp'. */
1774 static struct netdev *
1775 ofport_open(const struct dpif_port *dpif_port, struct ofp_phy_port *opp)
1776 {
1777     uint32_t curr, advertised, supported, peer;
1778     struct netdev_options netdev_options;
1779     enum netdev_flags flags;
1780     struct netdev *netdev;
1781     int error;
1782
1783     memset(&netdev_options, 0, sizeof netdev_options);
1784     netdev_options.name = dpif_port->name;
1785     netdev_options.type = dpif_port->type;
1786     netdev_options.ethertype = NETDEV_ETH_TYPE_NONE;
1787
1788     error = netdev_open(&netdev_options, &netdev);
1789     if (error) {
1790         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1791                      "cannot be opened (%s)",
1792                      dpif_port->name, dpif_port->port_no,
1793                      dpif_port->name, strerror(error));
1794         return NULL;
1795     }
1796
1797     netdev_get_flags(netdev, &flags);
1798     netdev_get_features(netdev, &curr, &advertised, &supported, &peer);
1799
1800     opp->port_no = htons(odp_port_to_ofp_port(dpif_port->port_no));
1801     netdev_get_etheraddr(netdev, opp->hw_addr);
1802     ovs_strzcpy(opp->name, dpif_port->name, sizeof opp->name);
1803     opp->config = flags & NETDEV_UP ? 0 : htonl(OFPPC_PORT_DOWN);
1804     opp->state = netdev_get_carrier(netdev) ? 0 : htonl(OFPPS_LINK_DOWN);
1805     opp->curr = htonl(curr);
1806     opp->advertised = htonl(advertised);
1807     opp->supported = htonl(supported);
1808     opp->peer = htonl(peer);
1809
1810     return netdev;
1811 }
1812
1813 static bool
1814 ofport_conflicts(const struct ofproto *p, const struct dpif_port *dpif_port)
1815 {
1816     if (get_port(p, dpif_port->port_no)) {
1817         VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1818                      dpif_port->port_no);
1819         return true;
1820     } else if (shash_find(&p->port_by_name, dpif_port->name)) {
1821         VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1822                      dpif_port->name);
1823         return true;
1824     } else {
1825         return false;
1826     }
1827 }
1828
1829 /* Returns true if most fields of 'a' and 'b' are equal.  Differences in name,
1830  * port number, and 'config' bits other than OFPPC_PORT_DOWN are
1831  * disregarded. */
1832 static bool
1833 ofport_equal(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
1834 {
1835     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1836     return (!memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1837             && a->state == b->state
1838             && !((a->config ^ b->config) & htonl(OFPPC_PORT_DOWN))
1839             && a->curr == b->curr
1840             && a->advertised == b->advertised
1841             && a->supported == b->supported
1842             && a->peer == b->peer);
1843 }
1844
1845 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1846  * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1847  * one with the same name or port number). */
1848 static void
1849 ofport_install(struct ofproto *p,
1850                struct netdev *netdev, const struct ofp_phy_port *opp)
1851 {
1852     const char *netdev_name = netdev_get_name(netdev);
1853     struct ofport *ofport;
1854
1855     connmgr_send_port_status(p->connmgr, opp, OFPPR_ADD);
1856
1857     /* Create ofport. */
1858     ofport = xmalloc(sizeof *ofport);
1859     ofport->ofproto = p;
1860     ofport->netdev = netdev;
1861     ofport->opp = *opp;
1862     ofport->odp_port = ofp_port_to_odp_port(ntohs(opp->port_no));
1863     ofport->bundle = NULL;
1864     ofport->cfm = NULL;
1865     ofport->tag = tag_create_random();
1866
1867     /* Add port to 'p'. */
1868     netdev_monitor_add(p->netdev_monitor, ofport->netdev);
1869     hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->odp_port, 0));
1870     shash_add(&p->port_by_name, netdev_name, ofport);
1871     if (p->sflow) {
1872         ofproto_sflow_add_port(p->sflow, ofport->odp_port, netdev_name);
1873     }
1874 }
1875
1876 /* Removes 'ofport' from 'p' and destroys it. */
1877 static void
1878 ofport_remove(struct ofport *ofport)
1879 {
1880     connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->opp,
1881                              OFPPR_DELETE);
1882     ofport_free(ofport);
1883 }
1884
1885 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1886  * destroys it. */
1887 static void
1888 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1889 {
1890     struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1891     if (port) {
1892         ofport_remove(port);
1893     }
1894 }
1895
1896 /* Updates 'port' within 'ofproto' with the new 'netdev' and 'opp'.
1897  *
1898  * Does not handle a name or port number change.  The caller must implement
1899  * such a change as a delete followed by an add.  */
1900 static void
1901 ofport_modified(struct ofport *port,
1902                 struct netdev *netdev, struct ofp_phy_port *opp)
1903 {
1904     struct ofproto *ofproto = port->ofproto;
1905
1906     if (port->bundle && port->bundle->bond) {
1907         bond_slave_set_netdev(port->bundle->bond, port, netdev);
1908     }
1909
1910     memcpy(port->opp.hw_addr, opp->hw_addr, ETH_ADDR_LEN);
1911     port->opp.config = ((port->opp.config & ~htonl(OFPPC_PORT_DOWN))
1912                         | (opp->config & htonl(OFPPC_PORT_DOWN)));
1913     port->opp.state = opp->state;
1914     port->opp.curr = opp->curr;
1915     port->opp.advertised = opp->advertised;
1916     port->opp.supported = opp->supported;
1917     port->opp.peer = opp->peer;
1918
1919     netdev_monitor_remove(ofproto->netdev_monitor, port->netdev);
1920     netdev_monitor_add(ofproto->netdev_monitor, netdev);
1921
1922     netdev_close(port->netdev);
1923     port->netdev = netdev;
1924
1925     connmgr_send_port_status(ofproto->connmgr, &port->opp, OFPPR_MODIFY);
1926 }
1927
1928 static void
1929 ofport_run(struct ofport *ofport)
1930 {
1931     if (ofport->cfm) {
1932         cfm_run(ofport->cfm);
1933
1934         if (cfm_should_send_ccm(ofport->cfm)) {
1935             struct ofpbuf packet;
1936             struct ccm *ccm;
1937
1938             ofpbuf_init(&packet, 0);
1939             ccm = eth_compose(&packet, eth_addr_ccm, ofport->opp.hw_addr,
1940                               ETH_TYPE_CFM,  sizeof *ccm);
1941             cfm_compose_ccm(ofport->cfm, ccm);
1942             ofproto_send_packet(ofport->ofproto, ofport->odp_port, 0, &packet);
1943             ofpbuf_uninit(&packet);
1944         }
1945     }
1946 }
1947
1948 static void
1949 ofport_wait(struct ofport *ofport)
1950 {
1951     if (ofport->cfm) {
1952         cfm_wait(ofport->cfm);
1953     }
1954 }
1955
1956 static void
1957 ofport_unregister(struct ofport *port)
1958 {
1959     struct ofbundle *bundle = port->bundle;
1960
1961     if (bundle) {
1962         ofproto_bundle_del_port(port);
1963         if (list_is_empty(&bundle->ports)) {
1964             ofproto_bundle_destroy(bundle);
1965         } else if (list_is_short(&bundle->ports)) {
1966             bond_destroy(bundle->bond);
1967             bundle->bond = NULL;
1968         }
1969     }
1970
1971     cfm_destroy(port->cfm);
1972     port->cfm = NULL;
1973 }
1974
1975 void
1976 ofproto_port_unregister(struct ofproto *ofproto, uint32_t ofp_port)
1977 {
1978     struct ofport *port = get_port(ofproto, ofp_port_to_odp_port(ofp_port));
1979     if (port) {
1980         ofport_unregister(port);
1981     }
1982 }
1983
1984 static void
1985 ofport_free(struct ofport *port)
1986 {
1987     if (port) {
1988         struct ofproto *ofproto = port->ofproto;
1989         const char *name = netdev_get_name(port->netdev);
1990
1991         ofport_unregister(port);
1992
1993         netdev_monitor_remove(ofproto->netdev_monitor, port->netdev);
1994         hmap_remove(&ofproto->ports, &port->hmap_node);
1995         shash_delete(&ofproto->port_by_name,
1996                      shash_find(&ofproto->port_by_name, name));
1997         if (ofproto->sflow) {
1998             ofproto_sflow_del_port(ofproto->sflow, port->odp_port);
1999         }
2000
2001         netdev_close(port->netdev);
2002         free(port);
2003     }
2004 }
2005
2006 static struct ofport *
2007 get_port(const struct ofproto *ofproto, uint16_t odp_port)
2008 {
2009     struct ofport *port;
2010
2011     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
2012                              hash_int(odp_port, 0), &ofproto->ports) {
2013         if (port->odp_port == odp_port) {
2014             return port;
2015         }
2016     }
2017     return NULL;
2018 }
2019
2020 static void
2021 update_port(struct ofproto *ofproto, const char *name)
2022 {
2023     struct dpif_port dpif_port;
2024     struct ofp_phy_port opp;
2025     struct netdev *netdev;
2026     struct ofport *port;
2027
2028     COVERAGE_INC(ofproto_update_port);
2029
2030     /* Fetch 'name''s location and properties from the datapath. */
2031     netdev = (!dpif_port_query_by_name(ofproto->dpif, name, &dpif_port)
2032               ? ofport_open(&dpif_port, &opp)
2033               : NULL);
2034     if (netdev) {
2035         port = get_port(ofproto, dpif_port.port_no);
2036         if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2037             /* 'name' hasn't changed location.  Any properties changed? */
2038             if (!ofport_equal(&port->opp, &opp)) {
2039                 ofport_modified(port, netdev, &opp);
2040             } else {
2041                 netdev_close(netdev);
2042             }
2043         } else {
2044             /* If 'port' is nonnull then its name differs from 'name' and thus
2045              * we should delete it.  If we think there's a port named 'name'
2046              * then its port number must be wrong now so delete it too. */
2047             if (port) {
2048                 ofport_remove(port);
2049             }
2050             ofport_remove_with_name(ofproto, name);
2051             ofport_install(ofproto, netdev, &opp);
2052         }
2053     } else {
2054         /* Any port named 'name' is gone now. */
2055         ofport_remove_with_name(ofproto, name);
2056     }
2057     dpif_port_destroy(&dpif_port);
2058 }
2059
2060 static int
2061 init_ports(struct ofproto *p)
2062 {
2063     struct dpif_port_dump dump;
2064     struct dpif_port dpif_port;
2065
2066     DPIF_PORT_FOR_EACH (&dpif_port, &dump, p->dpif) {
2067         if (!ofport_conflicts(p, &dpif_port)) {
2068             struct ofp_phy_port opp;
2069             struct netdev *netdev;
2070
2071             netdev = ofport_open(&dpif_port, &opp);
2072             if (netdev) {
2073                 ofport_install(p, netdev, &opp);
2074             }
2075         }
2076     }
2077
2078     return 0;
2079 }
2080 \f
2081 /* Returns true if 'rule' should be hidden from the controller.
2082  *
2083  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2084  * (e.g. by in-band control) and are intentionally hidden from the
2085  * controller. */
2086 static bool
2087 rule_is_hidden(const struct rule *rule)
2088 {
2089     return rule->cr.priority > UINT16_MAX;
2090 }
2091
2092 /* Creates and returns a new rule initialized as specified.
2093  *
2094  * The caller is responsible for inserting the rule into the classifier (with
2095  * rule_insert()). */
2096 static struct rule *
2097 rule_create(const struct cls_rule *cls_rule,
2098             const union ofp_action *actions, size_t n_actions,
2099             uint16_t idle_timeout, uint16_t hard_timeout,
2100             ovs_be64 flow_cookie, bool send_flow_removed)
2101 {
2102     struct rule *rule = xzalloc(sizeof *rule);
2103     rule->cr = *cls_rule;
2104     rule->idle_timeout = idle_timeout;
2105     rule->hard_timeout = hard_timeout;
2106     rule->flow_cookie = flow_cookie;
2107     rule->used = rule->created = time_msec();
2108     rule->send_flow_removed = send_flow_removed;
2109     list_init(&rule->facets);
2110     if (n_actions > 0) {
2111         rule->n_actions = n_actions;
2112         rule->actions = xmemdup(actions, n_actions * sizeof *actions);
2113     }
2114
2115     return rule;
2116 }
2117
2118 static struct rule *
2119 rule_from_cls_rule(const struct cls_rule *cls_rule)
2120 {
2121     return cls_rule ? CONTAINER_OF(cls_rule, struct rule, cr) : NULL;
2122 }
2123
2124 static void
2125 rule_free(struct rule *rule)
2126 {
2127     free(rule->actions);
2128     free(rule);
2129 }
2130
2131 /* Destroys 'rule' and iterates through all of its facets and revalidates them,
2132  * destroying any that no longer has a rule (which is probably all of them).
2133  *
2134  * The caller must have already removed 'rule' from the classifier. */
2135 static void
2136 rule_destroy(struct ofproto *ofproto, struct rule *rule)
2137 {
2138     struct facet *facet, *next_facet;
2139     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2140         facet_revalidate(ofproto, facet);
2141     }
2142     rule_free(rule);
2143 }
2144
2145 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2146  * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
2147  * count). */
2148 static bool
2149 rule_has_out_port(const struct rule *rule, ovs_be16 out_port)
2150 {
2151     const union ofp_action *oa;
2152     struct actions_iterator i;
2153
2154     if (out_port == htons(OFPP_NONE)) {
2155         return true;
2156     }
2157     for (oa = actions_first(&i, rule->actions, rule->n_actions); oa;
2158          oa = actions_next(&i)) {
2159         if (action_outputs_to_port(oa, out_port)) {
2160             return true;
2161         }
2162     }
2163     return false;
2164 }
2165
2166 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2167  * 'packet', which arrived on 'in_port'.
2168  *
2169  * Takes ownership of 'packet'. */
2170 static bool
2171 execute_odp_actions(struct ofproto *ofproto, const struct flow *flow,
2172                     const struct nlattr *odp_actions, size_t actions_len,
2173                     struct ofpbuf *packet)
2174 {
2175     if (actions_len == NLA_ALIGN(NLA_HDRLEN + sizeof(uint64_t))
2176         && odp_actions->nla_type == ODP_ACTION_ATTR_CONTROLLER) {
2177         /* As an optimization, avoid a round-trip from userspace to kernel to
2178          * userspace.  This also avoids possibly filling up kernel packet
2179          * buffers along the way. */
2180         struct dpif_upcall upcall;
2181
2182         upcall.type = DPIF_UC_ACTION;
2183         upcall.packet = packet;
2184         upcall.key = NULL;
2185         upcall.key_len = 0;
2186         upcall.userdata = nl_attr_get_u64(odp_actions);
2187         upcall.sample_pool = 0;
2188         upcall.actions = NULL;
2189         upcall.actions_len = 0;
2190
2191         send_packet_in(ofproto, &upcall, flow, false);
2192
2193         return true;
2194     } else {
2195         int error;
2196
2197         error = dpif_execute(ofproto->dpif, odp_actions, actions_len, packet);
2198         ofpbuf_delete(packet);
2199         return !error;
2200     }
2201 }
2202
2203 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2204  * statistics appropriately.  'packet' must have at least sizeof(struct
2205  * ofp_packet_in) bytes of headroom.
2206  *
2207  * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2208  * applying flow_extract() to 'packet' would yield the same flow as
2209  * 'facet->flow'.
2210  *
2211  * 'facet' must have accurately composed ODP actions; that is, it must not be
2212  * in need of revalidation.
2213  *
2214  * Takes ownership of 'packet'. */
2215 static void
2216 facet_execute(struct ofproto *ofproto, struct facet *facet,
2217               struct ofpbuf *packet)
2218 {
2219     struct dpif_flow_stats stats;
2220
2221     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2222
2223     flow_extract_stats(&facet->flow, packet, &stats);
2224     stats.used = time_msec();
2225     if (execute_odp_actions(ofproto, &facet->flow,
2226                             facet->actions, facet->actions_len, packet)) {
2227         facet_update_stats(ofproto, facet, &stats);
2228     }
2229 }
2230
2231 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
2232  * statistics (or the statistics for one of its facets) appropriately.
2233  * 'packet' must have at least sizeof(struct ofp_packet_in) bytes of headroom.
2234  *
2235  * 'packet' doesn't necessarily have to match 'rule'.  'rule' will be credited
2236  * with statistics for 'packet' either way.
2237  *
2238  * Takes ownership of 'packet'. */
2239 static void
2240 rule_execute(struct ofproto *ofproto, struct rule *rule, uint16_t in_port,
2241              struct ofpbuf *packet)
2242 {
2243     struct action_xlate_ctx ctx;
2244     struct ofpbuf *odp_actions;
2245     struct facet *facet;
2246     struct flow flow;
2247     size_t size;
2248
2249     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2250
2251     flow_extract(packet, 0, in_port, &flow);
2252
2253     /* First look for a related facet.  If we find one, account it to that. */
2254     facet = facet_lookup_valid(ofproto, &flow);
2255     if (facet && facet->rule == rule) {
2256         facet_execute(ofproto, facet, packet);
2257         return;
2258     }
2259
2260     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
2261      * create a new facet for it and use that. */
2262     if (rule_lookup(ofproto, &flow) == rule) {
2263         facet = facet_create(ofproto, rule, &flow, packet);
2264         facet_execute(ofproto, facet, packet);
2265         facet_install(ofproto, facet, true);
2266         return;
2267     }
2268
2269     /* We can't account anything to a facet.  If we were to try, then that
2270      * facet would have a non-matching rule, busting our invariants. */
2271     action_xlate_ctx_init(&ctx, ofproto, &flow, packet);
2272     odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
2273     size = packet->size;
2274     if (execute_odp_actions(ofproto, &flow, odp_actions->data,
2275                             odp_actions->size, packet)) {
2276         rule->used = time_msec();
2277         rule->packet_count++;
2278         rule->byte_count += size;
2279         flow_push_stats(ofproto, rule, &flow, 1, size, rule->used);
2280     }
2281     ofpbuf_delete(odp_actions);
2282 }
2283
2284 /* Inserts 'rule' into 'p''s flow table. */
2285 static void
2286 rule_insert(struct ofproto *p, struct rule *rule)
2287 {
2288     struct rule *displaced_rule;
2289
2290     displaced_rule = rule_from_cls_rule(classifier_insert(&p->cls, &rule->cr));
2291     if (displaced_rule) {
2292         rule_destroy(p, displaced_rule);
2293     }
2294     p->need_revalidate = true;
2295 }
2296
2297 /* Creates and returns a new facet within 'ofproto' owned by 'rule', given a
2298  * 'flow' and an example 'packet' within that flow.
2299  *
2300  * The caller must already have determined that no facet with an identical
2301  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2302  * 'ofproto''s classifier table. */
2303 static struct facet *
2304 facet_create(struct ofproto *ofproto, struct rule *rule,
2305              const struct flow *flow, const struct ofpbuf *packet)
2306 {
2307     struct facet *facet;
2308
2309     facet = xzalloc(sizeof *facet);
2310     facet->used = time_msec();
2311     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2312     list_push_back(&rule->facets, &facet->list_node);
2313     facet->rule = rule;
2314     facet->flow = *flow;
2315     netflow_flow_init(&facet->nf_flow);
2316     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2317
2318     facet_make_actions(ofproto, facet, packet);
2319
2320     return facet;
2321 }
2322
2323 static void
2324 facet_free(struct facet *facet)
2325 {
2326     free(facet->actions);
2327     free(facet);
2328 }
2329
2330 /* Remove 'rule' from 'ofproto' and free up the associated memory:
2331  *
2332  *   - Removes 'rule' from the classifier.
2333  *
2334  *   - If 'rule' has facets, revalidates them (and possibly uninstalls and
2335  *     destroys them), via rule_destroy().
2336  */
2337 static void
2338 rule_remove(struct ofproto *ofproto, struct rule *rule)
2339 {
2340     COVERAGE_INC(ofproto_del_rule);
2341     ofproto->need_revalidate = true;
2342     classifier_remove(&ofproto->cls, &rule->cr);
2343     rule_destroy(ofproto, rule);
2344 }
2345
2346 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2347  *
2348  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
2349  *     rule's statistics, via facet_uninstall().
2350  *
2351  *   - Removes 'facet' from its rule and from ofproto->facets.
2352  */
2353 static void
2354 facet_remove(struct ofproto *ofproto, struct facet *facet)
2355 {
2356     facet_uninstall(ofproto, facet);
2357     facet_flush_stats(ofproto, facet);
2358     hmap_remove(&ofproto->facets, &facet->hmap_node);
2359     list_remove(&facet->list_node);
2360     facet_free(facet);
2361 }
2362
2363 /* Composes the ODP actions for 'facet' based on its rule's actions. */
2364 static void
2365 facet_make_actions(struct ofproto *p, struct facet *facet,
2366                    const struct ofpbuf *packet)
2367 {
2368     const struct rule *rule = facet->rule;
2369     struct ofpbuf *odp_actions;
2370     struct action_xlate_ctx ctx;
2371
2372     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2373     odp_actions = xlate_actions(&ctx, rule->actions, rule->n_actions);
2374     facet->tags = ctx.tags;
2375     facet->may_install = ctx.may_set_up_flow;
2376     facet->nf_flow.output_iface = ctx.nf_output_iface;
2377
2378     if (facet->actions_len != odp_actions->size
2379         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2380         free(facet->actions);
2381         facet->actions_len = odp_actions->size;
2382         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2383     }
2384
2385     ofpbuf_delete(odp_actions);
2386 }
2387
2388 static int
2389 facet_put__(struct ofproto *ofproto, struct facet *facet,
2390             const struct nlattr *actions, size_t actions_len,
2391             struct dpif_flow_stats *stats)
2392 {
2393     struct odputil_keybuf keybuf;
2394     enum dpif_flow_put_flags flags;
2395     struct ofpbuf key;
2396
2397     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2398     if (stats) {
2399         flags |= DPIF_FP_ZERO_STATS;
2400         facet->dp_packet_count = 0;
2401         facet->dp_byte_count = 0;
2402     }
2403
2404     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2405     odp_flow_key_from_flow(&key, &facet->flow);
2406
2407     return dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
2408                          actions, actions_len, stats);
2409 }
2410
2411 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
2412  * 'zero_stats' is true, clears any existing statistics from the datapath for
2413  * 'facet'. */
2414 static void
2415 facet_install(struct ofproto *p, struct facet *facet, bool zero_stats)
2416 {
2417     struct dpif_flow_stats stats;
2418
2419     if (facet->may_install
2420         && !facet_put__(p, facet, facet->actions, facet->actions_len,
2421                         zero_stats ? &stats : NULL)) {
2422         facet->installed = true;
2423     }
2424 }
2425
2426 static void
2427 facet_account(struct ofproto *ofproto,
2428               struct facet *facet, uint64_t extra_bytes)
2429 {
2430     uint64_t total_bytes, n_bytes;
2431     struct ofbundle *in_bundle;
2432     const struct nlattr *a;
2433     tag_type dummy = 0;
2434     unsigned int left;
2435     int vlan;
2436
2437     total_bytes = facet->byte_count + extra_bytes;
2438     if (total_bytes <= facet->accounted_bytes) {
2439         return;
2440     }
2441     n_bytes = total_bytes - facet->accounted_bytes;
2442     facet->accounted_bytes = total_bytes;
2443
2444     /* Test that 'tags' is nonzero to ensure that only flows that include an
2445      * OFPP_NORMAL action are used for learning and bond slave rebalancing.
2446      * This works because OFPP_NORMAL always sets a nonzero tag value.
2447      *
2448      * Feed information from the active flows back into the learning table to
2449      * ensure that table is always in sync with what is actually flowing
2450      * through the datapath. */
2451     if (!facet->tags
2452         || !is_admissible(ofproto, &facet->flow, false, &dummy,
2453                           &vlan, &in_bundle)) {
2454         return;
2455     }
2456
2457     update_learning_table(ofproto, &facet->flow, vlan, in_bundle);
2458
2459     if (!ofproto->has_bonded_bundles) {
2460         return;
2461     }
2462     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->actions, facet->actions_len) {
2463         if (nl_attr_type(a) == ODP_ACTION_ATTR_OUTPUT) {
2464             struct ofport *port = get_port(ofproto, nl_attr_get_u32(a));
2465             if (port && port->bundle && port->bundle->bond) {
2466                 bond_account(port->bundle->bond, &facet->flow, vlan, n_bytes);
2467             }
2468         }
2469     }
2470 }
2471
2472 /* If 'rule' is installed in the datapath, uninstalls it. */
2473 static void
2474 facet_uninstall(struct ofproto *p, struct facet *facet)
2475 {
2476     if (facet->installed) {
2477         struct odputil_keybuf keybuf;
2478         struct dpif_flow_stats stats;
2479         struct ofpbuf key;
2480
2481         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2482         odp_flow_key_from_flow(&key, &facet->flow);
2483
2484         if (!dpif_flow_del(p->dpif, key.data, key.size, &stats)) {
2485             facet_update_stats(p, facet, &stats);
2486         }
2487         facet->installed = false;
2488         facet->dp_packet_count = 0;
2489         facet->dp_byte_count = 0;
2490     } else {
2491         assert(facet->dp_packet_count == 0);
2492         assert(facet->dp_byte_count == 0);
2493     }
2494 }
2495
2496 /* Returns true if the only action for 'facet' is to send to the controller.
2497  * (We don't report NetFlow expiration messages for such facets because they
2498  * are just part of the control logic for the network, not real traffic). */
2499 static bool
2500 facet_is_controller_flow(struct facet *facet)
2501 {
2502     return (facet
2503             && facet->rule->n_actions == 1
2504             && action_outputs_to_port(&facet->rule->actions[0],
2505                                       htons(OFPP_CONTROLLER)));
2506 }
2507
2508 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2509  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
2510  * 'facet''s statistics in the datapath should have been zeroed and folded into
2511  * its packet and byte counts before this function is called. */
2512 static void
2513 facet_flush_stats(struct ofproto *ofproto, struct facet *facet)
2514 {
2515     assert(!facet->dp_byte_count);
2516     assert(!facet->dp_packet_count);
2517
2518     facet_push_stats(ofproto, facet);
2519     facet_account(ofproto, facet, 0);
2520
2521     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2522         struct ofexpired expired;
2523         expired.flow = facet->flow;
2524         expired.packet_count = facet->packet_count;
2525         expired.byte_count = facet->byte_count;
2526         expired.used = facet->used;
2527         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2528     }
2529
2530     facet->rule->packet_count += facet->packet_count;
2531     facet->rule->byte_count += facet->byte_count;
2532
2533     /* Reset counters to prevent double counting if 'facet' ever gets
2534      * reinstalled. */
2535     facet->packet_count = 0;
2536     facet->byte_count = 0;
2537     facet->rs_packet_count = 0;
2538     facet->rs_byte_count = 0;
2539     facet->accounted_bytes = 0;
2540
2541     netflow_flow_clear(&facet->nf_flow);
2542 }
2543
2544 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2545  * Returns it if found, otherwise a null pointer.
2546  *
2547  * The returned facet might need revalidation; use facet_lookup_valid()
2548  * instead if that is important. */
2549 static struct facet *
2550 facet_find(struct ofproto *ofproto, const struct flow *flow)
2551 {
2552     struct facet *facet;
2553
2554     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2555                              &ofproto->facets) {
2556         if (flow_equal(flow, &facet->flow)) {
2557             return facet;
2558         }
2559     }
2560
2561     return NULL;
2562 }
2563
2564 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2565  * Returns it if found, otherwise a null pointer.
2566  *
2567  * The returned facet is guaranteed to be valid. */
2568 static struct facet *
2569 facet_lookup_valid(struct ofproto *ofproto, const struct flow *flow)
2570 {
2571     struct facet *facet = facet_find(ofproto, flow);
2572
2573     /* The facet we found might not be valid, since we could be in need of
2574      * revalidation.  If it is not valid, don't return it. */
2575     if (facet
2576         && ofproto->need_revalidate
2577         && !facet_revalidate(ofproto, facet)) {
2578         COVERAGE_INC(ofproto_invalidated);
2579         return NULL;
2580     }
2581
2582     return facet;
2583 }
2584
2585 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2586  *
2587  *   - If the rule found is different from 'facet''s current rule, moves
2588  *     'facet' to the new rule and recompiles its actions.
2589  *
2590  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2591  *     where it is and recompiles its actions anyway.
2592  *
2593  *   - If there is none, destroys 'facet'.
2594  *
2595  * Returns true if 'facet' still exists, false if it has been destroyed. */
2596 static bool
2597 facet_revalidate(struct ofproto *ofproto, struct facet *facet)
2598 {
2599     struct action_xlate_ctx ctx;
2600     struct ofpbuf *odp_actions;
2601     struct rule *new_rule;
2602     bool actions_changed;
2603
2604     COVERAGE_INC(facet_revalidate);
2605
2606     /* Determine the new rule. */
2607     new_rule = rule_lookup(ofproto, &facet->flow);
2608     if (!new_rule) {
2609         /* No new rule, so delete the facet. */
2610         facet_remove(ofproto, facet);
2611         return false;
2612     }
2613
2614     /* Calculate new ODP actions.
2615      *
2616      * We do not modify any 'facet' state yet, because we might need to, e.g.,
2617      * emit a NetFlow expiration and, if so, we need to have the old state
2618      * around to properly compose it. */
2619     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2620     odp_actions = xlate_actions(&ctx, new_rule->actions, new_rule->n_actions);
2621     actions_changed = (facet->actions_len != odp_actions->size
2622                        || memcmp(facet->actions, odp_actions->data,
2623                                  facet->actions_len));
2624
2625     /* If the ODP actions changed or the installability changed, then we need
2626      * to talk to the datapath. */
2627     if (actions_changed || ctx.may_set_up_flow != facet->installed) {
2628         if (ctx.may_set_up_flow) {
2629             struct dpif_flow_stats stats;
2630
2631             facet_put__(ofproto, facet,
2632                         odp_actions->data, odp_actions->size, &stats);
2633             facet_update_stats(ofproto, facet, &stats);
2634         } else {
2635             facet_uninstall(ofproto, facet);
2636         }
2637
2638         /* The datapath flow is gone or has zeroed stats, so push stats out of
2639          * 'facet' into 'rule'. */
2640         facet_flush_stats(ofproto, facet);
2641     }
2642
2643     /* Update 'facet' now that we've taken care of all the old state. */
2644     facet->tags = ctx.tags;
2645     facet->nf_flow.output_iface = ctx.nf_output_iface;
2646     facet->may_install = ctx.may_set_up_flow;
2647     if (actions_changed) {
2648         free(facet->actions);
2649         facet->actions_len = odp_actions->size;
2650         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2651     }
2652     if (facet->rule != new_rule) {
2653         COVERAGE_INC(facet_changed_rule);
2654         list_remove(&facet->list_node);
2655         list_push_back(&new_rule->facets, &facet->list_node);
2656         facet->rule = new_rule;
2657         facet->used = new_rule->created;
2658         facet->rs_used = facet->used;
2659     }
2660
2661     ofpbuf_delete(odp_actions);
2662
2663     return true;
2664 }
2665 \f
2666 /* Bridge packet processing functions. */
2667
2668 struct dst {
2669     struct ofport *port;
2670     uint16_t vlan;
2671 };
2672
2673 struct dst_set {
2674     struct dst builtin[32];
2675     struct dst *dsts;
2676     size_t n, allocated;
2677 };
2678
2679 static void dst_set_init(struct dst_set *);
2680 static void dst_set_add(struct dst_set *, const struct dst *);
2681 static void dst_set_free(struct dst_set *);
2682
2683 static struct ofport *ofbundle_get_a_port(const struct ofbundle *);
2684
2685 static bool
2686 set_dst(struct action_xlate_ctx *ctx, struct dst *dst,
2687         const struct ofbundle *in_bundle, const struct ofbundle *out_bundle)
2688 {
2689     dst->vlan = (out_bundle->vlan >= 0 ? OFP_VLAN_NONE
2690                  : in_bundle->vlan >= 0 ? in_bundle->vlan
2691                  : ctx->flow.vlan_tci == 0 ? OFP_VLAN_NONE
2692                  : vlan_tci_to_vid(ctx->flow.vlan_tci));
2693
2694     dst->port = (!out_bundle->bond
2695                  ? ofbundle_get_a_port(out_bundle)
2696                  : bond_choose_output_slave(out_bundle->bond, &ctx->flow,
2697                                             dst->vlan, &ctx->tags));
2698
2699     return dst->port != NULL;
2700 }
2701
2702 static int
2703 mirror_mask_ffs(mirror_mask_t mask)
2704 {
2705     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
2706     return ffs(mask);
2707 }
2708
2709 static void
2710 dst_set_init(struct dst_set *set)
2711 {
2712     set->dsts = set->builtin;
2713     set->n = 0;
2714     set->allocated = ARRAY_SIZE(set->builtin);
2715 }
2716
2717 static void
2718 dst_set_add(struct dst_set *set, const struct dst *dst)
2719 {
2720     if (set->n >= set->allocated) {
2721         size_t new_allocated;
2722         struct dst *new_dsts;
2723
2724         new_allocated = set->allocated * 2;
2725         new_dsts = xmalloc(new_allocated * sizeof *new_dsts);
2726         memcpy(new_dsts, set->dsts, set->n * sizeof *new_dsts);
2727
2728         dst_set_free(set);
2729
2730         set->dsts = new_dsts;
2731         set->allocated = new_allocated;
2732     }
2733     set->dsts[set->n++] = *dst;
2734 }
2735
2736 static void
2737 dst_set_free(struct dst_set *set)
2738 {
2739     if (set->dsts != set->builtin) {
2740         free(set->dsts);
2741     }
2742 }
2743
2744 static bool
2745 dst_is_duplicate(const struct dst_set *set, const struct dst *test)
2746 {
2747     size_t i;
2748     for (i = 0; i < set->n; i++) {
2749         if (set->dsts[i].vlan == test->vlan
2750             && set->dsts[i].port == test->port) {
2751             return true;
2752         }
2753     }
2754     return false;
2755 }
2756
2757 static bool
2758 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
2759 {
2760     return bundle->vlan < 0 && vlan_bitmap_contains(bundle->trunks, vlan);
2761 }
2762
2763 static bool
2764 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
2765 {
2766     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
2767 }
2768
2769 /* Returns an arbitrary interface within 'bundle'. */
2770 static struct ofport *
2771 ofbundle_get_a_port(const struct ofbundle *bundle)
2772 {
2773     return CONTAINER_OF(list_front(&bundle->ports),
2774                         struct ofport, bundle_node);
2775 }
2776
2777 static void
2778 compose_dsts(struct action_xlate_ctx *ctx, uint16_t vlan,
2779              const struct ofbundle *in_bundle,
2780              const struct ofbundle *out_bundle, struct dst_set *set)
2781 {
2782     struct dst dst;
2783
2784     if (out_bundle == OFBUNDLE_FLOOD) {
2785         struct ofbundle *bundle;
2786
2787         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
2788             if (bundle != in_bundle
2789                 && ofbundle_includes_vlan(bundle, vlan)
2790                 && bundle->floodable
2791                 && !bundle->mirror_out
2792                 && set_dst(ctx, &dst, in_bundle, bundle)) {
2793                 dst_set_add(set, &dst);
2794             }
2795         }
2796         ctx->nf_output_iface = NF_OUT_FLOOD;
2797     } else if (out_bundle && set_dst(ctx, &dst, in_bundle, out_bundle)) {
2798         dst_set_add(set, &dst);
2799         ctx->nf_output_iface = dst.port->odp_port;
2800     }
2801 }
2802
2803 static bool
2804 vlan_is_mirrored(const struct ofmirror *m, int vlan)
2805 {
2806     return vlan_bitmap_contains(m->vlans, vlan);
2807 }
2808
2809 static void
2810 compose_mirror_dsts(struct action_xlate_ctx *ctx,
2811                     uint16_t vlan, const struct ofbundle *in_bundle,
2812                     struct dst_set *set)
2813 {
2814     struct ofproto *ofproto = ctx->ofproto;
2815     mirror_mask_t mirrors;
2816     int flow_vlan;
2817     size_t i;
2818
2819     mirrors = in_bundle->src_mirrors;
2820     for (i = 0; i < set->n; i++) {
2821         mirrors |= set->dsts[i].port->bundle->dst_mirrors;
2822     }
2823
2824     if (!mirrors) {
2825         return;
2826     }
2827
2828     flow_vlan = vlan_tci_to_vid(ctx->flow.vlan_tci);
2829     if (flow_vlan == 0) {
2830         flow_vlan = OFP_VLAN_NONE;
2831     }
2832
2833     while (mirrors) {
2834         struct ofmirror *m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
2835         if (vlan_is_mirrored(m, vlan)) {
2836             struct dst dst;
2837
2838             if (m->out) {
2839                 if (set_dst(ctx, &dst, in_bundle, m->out)
2840                     && !dst_is_duplicate(set, &dst)) {
2841                     dst_set_add(set, &dst);
2842                 }
2843             } else {
2844                 struct ofbundle *bundle;
2845
2846                 HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2847                     if (ofbundle_includes_vlan(bundle, m->out_vlan)
2848                         && set_dst(ctx, &dst, in_bundle, bundle))
2849                     {
2850                         if (bundle->vlan < 0) {
2851                             dst.vlan = m->out_vlan;
2852                         }
2853                         if (dst_is_duplicate(set, &dst)) {
2854                             continue;
2855                         }
2856
2857                         /* Use the vlan tag on the original flow instead of
2858                          * the one passed in the vlan parameter.  This ensures
2859                          * that we compare the vlan from before any implicit
2860                          * tagging tags place. This is necessary because
2861                          * dst->vlan is the final vlan, after removing implicit
2862                          * tags. */
2863                         if (bundle == in_bundle && dst.vlan == flow_vlan) {
2864                             /* Don't send out input port on same VLAN. */
2865                             continue;
2866                         }
2867                         dst_set_add(set, &dst);
2868                     }
2869                 }
2870             }
2871         }
2872         mirrors &= mirrors - 1;
2873     }
2874 }
2875
2876 static void
2877 compose_actions(struct action_xlate_ctx *ctx, uint16_t vlan,
2878                 const struct ofbundle *in_bundle,
2879                 const struct ofbundle *out_bundle)
2880 {
2881     uint16_t initial_vlan, cur_vlan;
2882     const struct dst *dst;
2883     struct dst_set set;
2884
2885     dst_set_init(&set);
2886     compose_dsts(ctx, vlan, in_bundle, out_bundle, &set);
2887     compose_mirror_dsts(ctx, vlan, in_bundle, &set);
2888
2889     /* Output all the packets we can without having to change the VLAN. */
2890     initial_vlan = vlan_tci_to_vid(ctx->flow.vlan_tci);
2891     if (initial_vlan == 0) {
2892         initial_vlan = OFP_VLAN_NONE;
2893     }
2894     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
2895         if (dst->vlan != initial_vlan) {
2896             continue;
2897         }
2898         nl_msg_put_u32(ctx->odp_actions,
2899                        ODP_ACTION_ATTR_OUTPUT, dst->port->odp_port);
2900     }
2901
2902     /* Then output the rest. */
2903     cur_vlan = initial_vlan;
2904     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
2905         if (dst->vlan == initial_vlan) {
2906             continue;
2907         }
2908         if (dst->vlan != cur_vlan) {
2909             if (dst->vlan == OFP_VLAN_NONE) {
2910                 nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_STRIP_VLAN);
2911             } else {
2912                 ovs_be16 tci;
2913                 tci = htons(dst->vlan & VLAN_VID_MASK);
2914                 tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
2915                 nl_msg_put_be16(ctx->odp_actions,
2916                                 ODP_ACTION_ATTR_SET_DL_TCI, tci);
2917             }
2918             cur_vlan = dst->vlan;
2919         }
2920         nl_msg_put_u32(ctx->odp_actions,
2921                        ODP_ACTION_ATTR_OUTPUT, dst->port->odp_port);
2922     }
2923
2924     dst_set_free(&set);
2925 }
2926
2927 /* Returns the effective vlan of a packet, taking into account both the
2928  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
2929  * the packet is untagged and -1 indicates it has an invalid header and
2930  * should be dropped. */
2931 static int
2932 flow_get_vlan(struct ofproto *ofproto, const struct flow *flow,
2933               struct ofbundle *in_bundle, bool have_packet)
2934 {
2935     int vlan = vlan_tci_to_vid(flow->vlan_tci);
2936     if (in_bundle->vlan >= 0) {
2937         if (vlan) {
2938             if (have_packet) {
2939                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2940                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
2941                              "packet received on port %s configured with "
2942                              "implicit VLAN %"PRIu16,
2943                              ofproto->name, vlan,
2944                              in_bundle->name, in_bundle->vlan);
2945             }
2946             return -1;
2947         }
2948         vlan = in_bundle->vlan;
2949     } else {
2950         if (!ofbundle_includes_vlan(in_bundle, vlan)) {
2951             if (have_packet) {
2952                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2953                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
2954                              "packet received on port %s not configured for "
2955                              "trunking VLAN %d",
2956                              ofproto->name, vlan, in_bundle->name, vlan);
2957             }
2958             return -1;
2959         }
2960     }
2961
2962     return vlan;
2963 }
2964
2965 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
2966  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
2967  * indicate this; newer upstream kernels use gratuitous ARP requests. */
2968 static bool
2969 is_gratuitous_arp(const struct flow *flow)
2970 {
2971     return (flow->dl_type == htons(ETH_TYPE_ARP)
2972             && eth_addr_is_broadcast(flow->dl_dst)
2973             && (flow->nw_proto == ARP_OP_REPLY
2974                 || (flow->nw_proto == ARP_OP_REQUEST
2975                     && flow->nw_src == flow->nw_dst)));
2976 }
2977
2978 static void
2979 update_learning_table(struct ofproto *ofproto,
2980                       const struct flow *flow, int vlan,
2981                       struct ofbundle *in_bundle)
2982 {
2983     struct mac_entry *mac;
2984
2985     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
2986         return;
2987     }
2988
2989     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
2990     if (is_gratuitous_arp(flow)) {
2991         /* We don't want to learn from gratuitous ARP packets that are
2992          * reflected back over bond slaves so we lock the learning table. */
2993         if (!in_bundle->bond) {
2994             mac_entry_set_grat_arp_lock(mac);
2995         } else if (mac_entry_is_grat_arp_locked(mac)) {
2996             return;
2997         }
2998     }
2999
3000     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
3001         /* The log messages here could actually be useful in debugging,
3002          * so keep the rate limit relatively high. */
3003         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
3004         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
3005                     "on port %s in VLAN %d",
3006                     ofproto->name, ETH_ADDR_ARGS(flow->dl_src),
3007                     in_bundle->name, vlan);
3008
3009         mac->port.p = in_bundle;
3010         tag_set_add(&ofproto->revalidate_set,
3011                     mac_learning_changed(ofproto->ml, mac));
3012     }
3013 }
3014
3015 /* Determines whether packets in 'flow' within 'br' should be forwarded or
3016  * dropped.  Returns true if they may be forwarded, false if they should be
3017  * dropped.
3018  *
3019  * If 'have_packet' is true, it indicates that the caller is processing a
3020  * received packet.  If 'have_packet' is false, then the caller is just
3021  * revalidating an existing flow because configuration has changed.  Either
3022  * way, 'have_packet' only affects logging (there is no point in logging errors
3023  * during revalidation).
3024  *
3025  * Sets '*in_portp' to the input port.  This will be a null pointer if
3026  * flow->in_port does not designate a known input port (in which case
3027  * is_admissible() returns false).
3028  *
3029  * When returning true, sets '*vlanp' to the effective VLAN of the input
3030  * packet, as returned by flow_get_vlan().
3031  *
3032  * May also add tags to '*tags', although the current implementation only does
3033  * so in one special case.
3034  */
3035 static bool
3036 is_admissible(struct ofproto *ofproto, const struct flow *flow,
3037               bool have_packet,
3038               tag_type *tags, int *vlanp, struct ofbundle **in_bundlep)
3039 {
3040     struct ofport *in_port;
3041     struct ofbundle *in_bundle;
3042     int vlan;
3043
3044     /* Find the port and bundle for the received packet. */
3045     in_port = get_port(ofproto, flow->in_port);
3046     *in_bundlep = in_bundle = in_port->bundle;
3047     if (!in_port || !in_bundle) {
3048         /* No interface?  Something fishy... */
3049         if (have_packet) {
3050             /* Odd.  A few possible reasons here:
3051              *
3052              * - We deleted a port but there are still a few packets queued up
3053              *   from it.
3054              *
3055              * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
3056              *   we don't know about.
3057              *
3058              * - Packet arrived on the local port but the local port is not
3059              *   part of a bundle.
3060              */
3061             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3062
3063             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
3064                          "port %"PRIu16,
3065                          ofproto->name, flow->in_port);
3066         }
3067         return false;
3068     }
3069     *vlanp = vlan = flow_get_vlan(ofproto, flow, in_bundle, have_packet);
3070     if (vlan < 0) {
3071         return false;
3072     }
3073
3074     /* Drop frames for reserved multicast addresses. */
3075     if (eth_addr_is_reserved(flow->dl_dst)) {
3076         return false;
3077     }
3078
3079     /* Drop frames on bundles reserved for mirroring. */
3080     if (in_bundle->mirror_out) {
3081         if (have_packet) {
3082             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
3083             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
3084                          "%s, which is reserved exclusively for mirroring",
3085                          ofproto->name, in_bundle->name);
3086         }
3087         return false;
3088     }
3089
3090     if (in_bundle->bond) {
3091         struct mac_entry *mac;
3092
3093         switch (bond_check_admissibility(in_bundle->bond, in_port,
3094                                          flow->dl_dst, tags)) {
3095         case BV_ACCEPT:
3096             break;
3097
3098         case BV_DROP:
3099             return false;
3100
3101         case BV_DROP_IF_MOVED:
3102             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
3103             if (mac && mac->port.p != in_bundle &&
3104                 (!is_gratuitous_arp(flow)
3105                  || mac_entry_is_grat_arp_locked(mac))) {
3106                 return false;
3107             }
3108             break;
3109         }
3110     }
3111
3112     return true;
3113 }
3114
3115 /* If the composed actions may be applied to any packet in the given 'flow',
3116  * returns true.  Otherwise, the actions should only be applied to 'packet', or
3117  * not at all, if 'packet' was NULL. */
3118 static bool
3119 xlate_normal(struct action_xlate_ctx *ctx)
3120 {
3121     struct ofbundle *in_bundle;
3122     struct ofbundle *out_bundle;
3123     struct mac_entry *mac;
3124     int vlan;
3125
3126     /* Check whether we should drop packets in this flow. */
3127     if (!is_admissible(ctx->ofproto, &ctx->flow, ctx->packet != NULL,
3128                        &ctx->tags, &vlan, &in_bundle)) {
3129         out_bundle = NULL;
3130         goto done;
3131     }
3132
3133     /* Learn source MAC (but don't try to learn from revalidation). */
3134     if (ctx->packet) {
3135         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
3136     }
3137
3138     /* Determine output bundle. */
3139     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
3140                               &ctx->tags);
3141     if (mac) {
3142         out_bundle = mac->port.p;
3143     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
3144         /* If we are revalidating but don't have a learning entry then eject
3145          * the flow.  Installing a flow that floods packets opens up a window
3146          * of time where we could learn from a packet reflected on a bond and
3147          * blackhole packets before the learning table is updated to reflect
3148          * the correct port. */
3149         return false;
3150     } else {
3151         out_bundle = OFBUNDLE_FLOOD;
3152     }
3153
3154     /* Don't send packets out their input bundles. */
3155     if (in_bundle == out_bundle) {
3156         out_bundle = NULL;
3157     }
3158
3159 done:
3160     if (in_bundle) {
3161         compose_actions(ctx, vlan, in_bundle, out_bundle);
3162     }
3163
3164     return true;
3165 }
3166 \f
3167 static void
3168 send_error_oh(const struct ofconn *ofconn, const struct ofp_header *oh,
3169               int error)
3170 {
3171     struct ofpbuf *buf = ofputil_encode_error_msg(error, oh);
3172     if (buf) {
3173         COVERAGE_INC(ofproto_error);
3174         ofconn_send_reply(ofconn, buf);
3175     }
3176 }
3177
3178 static int
3179 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
3180 {
3181     ofconn_send_reply(ofconn, make_echo_reply(oh));
3182     return 0;
3183 }
3184
3185 static int
3186 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
3187 {
3188     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3189     struct ofp_switch_features *osf;
3190     struct ofpbuf *buf;
3191     struct ofport *port;
3192
3193     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
3194     osf->datapath_id = htonll(ofproto->datapath_id);
3195     osf->n_buffers = htonl(pktbuf_capacity());
3196     osf->n_tables = 2;
3197     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
3198                               OFPC_PORT_STATS | OFPC_ARP_MATCH_IP);
3199     osf->actions = htonl((1u << OFPAT_OUTPUT) |
3200                          (1u << OFPAT_SET_VLAN_VID) |
3201                          (1u << OFPAT_SET_VLAN_PCP) |
3202                          (1u << OFPAT_STRIP_VLAN) |
3203                          (1u << OFPAT_SET_DL_SRC) |
3204                          (1u << OFPAT_SET_DL_DST) |
3205                          (1u << OFPAT_SET_NW_SRC) |
3206                          (1u << OFPAT_SET_NW_DST) |
3207                          (1u << OFPAT_SET_NW_TOS) |
3208                          (1u << OFPAT_SET_TP_SRC) |
3209                          (1u << OFPAT_SET_TP_DST) |
3210                          (1u << OFPAT_ENQUEUE));
3211
3212     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3213         ofpbuf_put(buf, &port->opp, sizeof port->opp);
3214     }
3215
3216     ofconn_send_reply(ofconn, buf);
3217     return 0;
3218 }
3219
3220 static int
3221 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
3222 {
3223     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3224     struct ofpbuf *buf;
3225     struct ofp_switch_config *osc;
3226     uint16_t flags;
3227     bool drop_frags;
3228
3229     /* Figure out flags. */
3230     dpif_get_drop_frags(ofproto->dpif, &drop_frags);
3231     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
3232
3233     /* Send reply. */
3234     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
3235     osc->flags = htons(flags);
3236     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
3237     ofconn_send_reply(ofconn, buf);
3238
3239     return 0;
3240 }
3241
3242 static int
3243 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
3244 {
3245     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3246     uint16_t flags = ntohs(osc->flags);
3247
3248     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
3249         && ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
3250         switch (flags & OFPC_FRAG_MASK) {
3251         case OFPC_FRAG_NORMAL:
3252             dpif_set_drop_frags(ofproto->dpif, false);
3253             break;
3254         case OFPC_FRAG_DROP:
3255             dpif_set_drop_frags(ofproto->dpif, true);
3256             break;
3257         default:
3258             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
3259                          osc->flags);
3260             break;
3261         }
3262     }
3263
3264     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
3265
3266     return 0;
3267 }
3268
3269 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
3270                              struct action_xlate_ctx *ctx);
3271
3272 static void
3273 add_output_action(struct action_xlate_ctx *ctx, uint16_t port)
3274 {
3275     const struct ofport *ofport = get_port(ctx->ofproto, port);
3276
3277     if (ofport) {
3278         if (ofport->opp.config & htonl(OFPPC_NO_FWD)) {
3279             /* Forwarding disabled on port. */
3280             return;
3281         }
3282     } else {
3283         /*
3284          * We don't have an ofport record for this port, but it doesn't hurt to
3285          * allow forwarding to it anyhow.  Maybe such a port will appear later
3286          * and we're pre-populating the flow table.
3287          */
3288     }
3289
3290     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_OUTPUT, port);
3291     ctx->nf_output_iface = port;
3292 }
3293
3294 static struct rule *
3295 rule_lookup(struct ofproto *ofproto, const struct flow *flow)
3296 {
3297     return rule_from_cls_rule(classifier_lookup(&ofproto->cls, flow));
3298 }
3299
3300 static void
3301 xlate_table_action(struct action_xlate_ctx *ctx, uint16_t in_port)
3302 {
3303     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
3304         uint16_t old_in_port;
3305         struct rule *rule;
3306
3307         /* Look up a flow with 'in_port' as the input port.  Then restore the
3308          * original input port (otherwise OFPP_NORMAL and OFPP_IN_PORT will
3309          * have surprising behavior). */
3310         old_in_port = ctx->flow.in_port;
3311         ctx->flow.in_port = in_port;
3312         rule = rule_lookup(ctx->ofproto, &ctx->flow);
3313         ctx->flow.in_port = old_in_port;
3314
3315         if (ctx->resubmit_hook) {
3316             ctx->resubmit_hook(ctx, rule);
3317         }
3318
3319         if (rule) {
3320             ctx->recurse++;
3321             do_xlate_actions(rule->actions, rule->n_actions, ctx);
3322             ctx->recurse--;
3323         }
3324     } else {
3325         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
3326
3327         VLOG_ERR_RL(&recurse_rl, "NXAST_RESUBMIT recursed over %d times",
3328                     MAX_RESUBMIT_RECURSION);
3329     }
3330 }
3331
3332 static void
3333 flood_packets(struct ofproto *ofproto, uint16_t odp_in_port, ovs_be32 mask,
3334               uint16_t *nf_output_iface, struct ofpbuf *odp_actions)
3335 {
3336     struct ofport *ofport;
3337
3338     HMAP_FOR_EACH (ofport, hmap_node, &ofproto->ports) {
3339         uint16_t odp_port = ofport->odp_port;
3340         if (odp_port != odp_in_port && !(ofport->opp.config & mask)) {
3341             nl_msg_put_u32(odp_actions, ODP_ACTION_ATTR_OUTPUT, odp_port);
3342         }
3343     }
3344     *nf_output_iface = NF_OUT_FLOOD;
3345 }
3346
3347 static void
3348 xlate_output_action__(struct action_xlate_ctx *ctx,
3349                       uint16_t port, uint16_t max_len)
3350 {
3351     uint16_t odp_port;
3352     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
3353
3354     ctx->nf_output_iface = NF_OUT_DROP;
3355
3356     switch (port) {
3357     case OFPP_IN_PORT:
3358         add_output_action(ctx, ctx->flow.in_port);
3359         break;
3360     case OFPP_TABLE:
3361         xlate_table_action(ctx, ctx->flow.in_port);
3362         break;
3363     case OFPP_NORMAL:
3364         xlate_normal(ctx);
3365         break;
3366     case OFPP_FLOOD:
3367         flood_packets(ctx->ofproto, ctx->flow.in_port, htonl(OFPPC_NO_FLOOD),
3368                       &ctx->nf_output_iface, ctx->odp_actions);
3369         break;
3370     case OFPP_ALL:
3371         flood_packets(ctx->ofproto, ctx->flow.in_port, htonl(0),
3372                       &ctx->nf_output_iface, ctx->odp_actions);
3373         break;
3374     case OFPP_CONTROLLER:
3375         nl_msg_put_u64(ctx->odp_actions, ODP_ACTION_ATTR_CONTROLLER, max_len);
3376         break;
3377     case OFPP_LOCAL:
3378         add_output_action(ctx, ODPP_LOCAL);
3379         break;
3380     default:
3381         odp_port = ofp_port_to_odp_port(port);
3382         if (odp_port != ctx->flow.in_port) {
3383             add_output_action(ctx, odp_port);
3384         }
3385         break;
3386     }
3387
3388     if (prev_nf_output_iface == NF_OUT_FLOOD) {
3389         ctx->nf_output_iface = NF_OUT_FLOOD;
3390     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
3391         ctx->nf_output_iface = prev_nf_output_iface;
3392     } else if (prev_nf_output_iface != NF_OUT_DROP &&
3393                ctx->nf_output_iface != NF_OUT_FLOOD) {
3394         ctx->nf_output_iface = NF_OUT_MULTI;
3395     }
3396 }
3397
3398 static void
3399 xlate_output_action(struct action_xlate_ctx *ctx,
3400                     const struct ofp_action_output *oao)
3401 {
3402     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
3403 }
3404
3405 /* If the final ODP action in 'ctx' is "pop priority", drop it, as an
3406  * optimization, because we're going to add another action that sets the
3407  * priority immediately after, or because there are no actions following the
3408  * pop.  */
3409 static void
3410 remove_pop_action(struct action_xlate_ctx *ctx)
3411 {
3412     if (ctx->odp_actions->size == ctx->last_pop_priority) {
3413         ctx->odp_actions->size -= NLA_ALIGN(NLA_HDRLEN);
3414         ctx->last_pop_priority = -1;
3415     }
3416 }
3417
3418 static void
3419 add_pop_action(struct action_xlate_ctx *ctx)
3420 {
3421     if (ctx->odp_actions->size != ctx->last_pop_priority) {
3422         nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_POP_PRIORITY);
3423         ctx->last_pop_priority = ctx->odp_actions->size;
3424     }
3425 }
3426
3427 static void
3428 xlate_enqueue_action(struct action_xlate_ctx *ctx,
3429                      const struct ofp_action_enqueue *oae)
3430 {
3431     uint16_t ofp_port, odp_port;
3432     uint32_t priority;
3433     int error;
3434
3435     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
3436                                    &priority);
3437     if (error) {
3438         /* Fall back to ordinary output action. */
3439         xlate_output_action__(ctx, ntohs(oae->port), 0);
3440         return;
3441     }
3442
3443     /* Figure out ODP output port. */
3444     ofp_port = ntohs(oae->port);
3445     if (ofp_port != OFPP_IN_PORT) {
3446         odp_port = ofp_port_to_odp_port(ofp_port);
3447     } else {
3448         odp_port = ctx->flow.in_port;
3449     }
3450
3451     /* Add ODP actions. */
3452     remove_pop_action(ctx);
3453     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_SET_PRIORITY, priority);
3454     add_output_action(ctx, odp_port);
3455     add_pop_action(ctx);
3456
3457     /* Update NetFlow output port. */
3458     if (ctx->nf_output_iface == NF_OUT_DROP) {
3459         ctx->nf_output_iface = odp_port;
3460     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
3461         ctx->nf_output_iface = NF_OUT_MULTI;
3462     }
3463 }
3464
3465 static void
3466 xlate_set_queue_action(struct action_xlate_ctx *ctx,
3467                        const struct nx_action_set_queue *nasq)
3468 {
3469     uint32_t priority;
3470     int error;
3471
3472     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
3473                                    &priority);
3474     if (error) {
3475         /* Couldn't translate queue to a priority, so ignore.  A warning
3476          * has already been logged. */
3477         return;
3478     }
3479
3480     remove_pop_action(ctx);
3481     nl_msg_put_u32(ctx->odp_actions, ODP_ACTION_ATTR_SET_PRIORITY, priority);
3482 }
3483
3484 static void
3485 xlate_set_dl_tci(struct action_xlate_ctx *ctx)
3486 {
3487     ovs_be16 tci = ctx->flow.vlan_tci;
3488     if (!(tci & htons(VLAN_CFI))) {
3489         nl_msg_put_flag(ctx->odp_actions, ODP_ACTION_ATTR_STRIP_VLAN);
3490     } else {
3491         nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_TCI,
3492                         tci & ~htons(VLAN_CFI));
3493     }
3494 }
3495
3496 struct xlate_reg_state {
3497     ovs_be16 vlan_tci;
3498     ovs_be64 tun_id;
3499 };
3500
3501 static void
3502 save_reg_state(const struct action_xlate_ctx *ctx,
3503                struct xlate_reg_state *state)
3504 {
3505     state->vlan_tci = ctx->flow.vlan_tci;
3506     state->tun_id = ctx->flow.tun_id;
3507 }
3508
3509 static void
3510 update_reg_state(struct action_xlate_ctx *ctx,
3511                  const struct xlate_reg_state *state)
3512 {
3513     if (ctx->flow.vlan_tci != state->vlan_tci) {
3514         xlate_set_dl_tci(ctx);
3515     }
3516     if (ctx->flow.tun_id != state->tun_id) {
3517         nl_msg_put_be64(ctx->odp_actions,
3518                         ODP_ACTION_ATTR_SET_TUNNEL, ctx->flow.tun_id);
3519     }
3520 }
3521
3522 static void
3523 xlate_autopath(struct action_xlate_ctx *ctx,
3524                const struct nx_action_autopath *naa)
3525 {
3526     uint16_t ofp_port = ntohl(naa->id);
3527     struct ofport *port;
3528
3529     port = get_port(ctx->ofproto, ofp_port_to_odp_port(ofp_port));
3530     if (!port || !port->bundle) {
3531         ofp_port = OFPP_NONE;
3532     } else if (port->bundle->bond) {
3533         /* Autopath does not support VLAN hashing. */
3534         struct ofport *slave = bond_choose_output_slave(
3535             port->bundle->bond, &ctx->flow, OFP_VLAN_NONE, &ctx->tags);
3536         if (slave) {
3537             ofp_port = odp_port_to_ofp_port(slave->odp_port);
3538         }
3539     }
3540     autopath_execute(naa, &ctx->flow, ofp_port);
3541 }
3542
3543 static void
3544 xlate_nicira_action(struct action_xlate_ctx *ctx,
3545                     const struct nx_action_header *nah)
3546 {
3547     const struct nx_action_resubmit *nar;
3548     const struct nx_action_set_tunnel *nast;
3549     const struct nx_action_set_queue *nasq;
3550     const struct nx_action_multipath *nam;
3551     const struct nx_action_autopath *naa;
3552     enum nx_action_subtype subtype = ntohs(nah->subtype);
3553     struct xlate_reg_state state;
3554     ovs_be64 tun_id;
3555
3556     assert(nah->vendor == htonl(NX_VENDOR_ID));
3557     switch (subtype) {
3558     case NXAST_RESUBMIT:
3559         nar = (const struct nx_action_resubmit *) nah;
3560         xlate_table_action(ctx, ofp_port_to_odp_port(ntohs(nar->in_port)));
3561         break;
3562
3563     case NXAST_SET_TUNNEL:
3564         nast = (const struct nx_action_set_tunnel *) nah;
3565         tun_id = htonll(ntohl(nast->tun_id));
3566         nl_msg_put_be64(ctx->odp_actions, ODP_ACTION_ATTR_SET_TUNNEL, tun_id);
3567         ctx->flow.tun_id = tun_id;
3568         break;
3569
3570     case NXAST_DROP_SPOOFED_ARP:
3571         if (ctx->flow.dl_type == htons(ETH_TYPE_ARP)) {
3572             nl_msg_put_flag(ctx->odp_actions,
3573                             ODP_ACTION_ATTR_DROP_SPOOFED_ARP);
3574         }
3575         break;
3576
3577     case NXAST_SET_QUEUE:
3578         nasq = (const struct nx_action_set_queue *) nah;
3579         xlate_set_queue_action(ctx, nasq);
3580         break;
3581
3582     case NXAST_POP_QUEUE:
3583         add_pop_action(ctx);
3584         break;
3585
3586     case NXAST_REG_MOVE:
3587         save_reg_state(ctx, &state);
3588         nxm_execute_reg_move((const struct nx_action_reg_move *) nah,
3589                              &ctx->flow);
3590         update_reg_state(ctx, &state);
3591         break;
3592
3593     case NXAST_REG_LOAD:
3594         save_reg_state(ctx, &state);
3595         nxm_execute_reg_load((const struct nx_action_reg_load *) nah,
3596                              &ctx->flow);
3597         update_reg_state(ctx, &state);
3598         break;
3599
3600     case NXAST_NOTE:
3601         /* Nothing to do. */
3602         break;
3603
3604     case NXAST_SET_TUNNEL64:
3605         tun_id = ((const struct nx_action_set_tunnel64 *) nah)->tun_id;
3606         nl_msg_put_be64(ctx->odp_actions, ODP_ACTION_ATTR_SET_TUNNEL, tun_id);
3607         ctx->flow.tun_id = tun_id;
3608         break;
3609
3610     case NXAST_MULTIPATH:
3611         nam = (const struct nx_action_multipath *) nah;
3612         multipath_execute(nam, &ctx->flow);
3613         break;
3614
3615     case NXAST_AUTOPATH:
3616         naa = (const struct nx_action_autopath *) nah;
3617         xlate_autopath(ctx, naa);
3618         break;
3619
3620     /* If you add a new action here that modifies flow data, don't forget to
3621      * update the flow key in ctx->flow at the same time. */
3622
3623     case NXAST_SNAT__OBSOLETE:
3624     default:
3625         VLOG_DBG_RL(&rl, "unknown Nicira action type %d", (int) subtype);
3626         break;
3627     }
3628 }
3629
3630 static void
3631 do_xlate_actions(const union ofp_action *in, size_t n_in,
3632                  struct action_xlate_ctx *ctx)
3633 {
3634     struct actions_iterator iter;
3635     const union ofp_action *ia;
3636     const struct ofport *port;
3637
3638     port = get_port(ctx->ofproto, ctx->flow.in_port);
3639     if (port && port->opp.config & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP) &&
3640         port->opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
3641                             ? htonl(OFPPC_NO_RECV_STP)
3642                             : htonl(OFPPC_NO_RECV))) {
3643         /* Drop this flow. */
3644         return;
3645     }
3646
3647     for (ia = actions_first(&iter, in, n_in); ia; ia = actions_next(&iter)) {
3648         enum ofp_action_type type = ntohs(ia->type);
3649         const struct ofp_action_dl_addr *oada;
3650
3651         switch (type) {
3652         case OFPAT_OUTPUT:
3653             xlate_output_action(ctx, &ia->output);
3654             break;
3655
3656         case OFPAT_SET_VLAN_VID:
3657             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
3658             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
3659             xlate_set_dl_tci(ctx);
3660             break;
3661
3662         case OFPAT_SET_VLAN_PCP:
3663             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
3664             ctx->flow.vlan_tci |= htons(
3665                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
3666             xlate_set_dl_tci(ctx);
3667             break;
3668
3669         case OFPAT_STRIP_VLAN:
3670             ctx->flow.vlan_tci = htons(0);
3671             xlate_set_dl_tci(ctx);
3672             break;
3673
3674         case OFPAT_SET_DL_SRC:
3675             oada = ((struct ofp_action_dl_addr *) ia);
3676             nl_msg_put_unspec(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_SRC,
3677                               oada->dl_addr, ETH_ADDR_LEN);
3678             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
3679             break;
3680
3681         case OFPAT_SET_DL_DST:
3682             oada = ((struct ofp_action_dl_addr *) ia);
3683             nl_msg_put_unspec(ctx->odp_actions, ODP_ACTION_ATTR_SET_DL_DST,
3684                               oada->dl_addr, ETH_ADDR_LEN);
3685             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
3686             break;
3687
3688         case OFPAT_SET_NW_SRC:
3689             nl_msg_put_be32(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_SRC,
3690                             ia->nw_addr.nw_addr);
3691             ctx->flow.nw_src = ia->nw_addr.nw_addr;
3692             break;
3693
3694         case OFPAT_SET_NW_DST:
3695             nl_msg_put_be32(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_DST,
3696                             ia->nw_addr.nw_addr);
3697             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
3698             break;
3699
3700         case OFPAT_SET_NW_TOS:
3701             nl_msg_put_u8(ctx->odp_actions, ODP_ACTION_ATTR_SET_NW_TOS,
3702                           ia->nw_tos.nw_tos);
3703             ctx->flow.nw_tos = ia->nw_tos.nw_tos;
3704             break;
3705
3706         case OFPAT_SET_TP_SRC:
3707             nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_TP_SRC,
3708                             ia->tp_port.tp_port);
3709             ctx->flow.tp_src = ia->tp_port.tp_port;
3710             break;
3711
3712         case OFPAT_SET_TP_DST:
3713             nl_msg_put_be16(ctx->odp_actions, ODP_ACTION_ATTR_SET_TP_DST,
3714                             ia->tp_port.tp_port);
3715             ctx->flow.tp_dst = ia->tp_port.tp_port;
3716             break;
3717
3718         case OFPAT_VENDOR:
3719             xlate_nicira_action(ctx, (const struct nx_action_header *) ia);
3720             break;
3721
3722         case OFPAT_ENQUEUE:
3723             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
3724             break;
3725
3726         default:
3727             VLOG_DBG_RL(&rl, "unknown action type %d", (int) type);
3728             break;
3729         }
3730     }
3731 }
3732
3733 static void
3734 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
3735                       struct ofproto *ofproto, const struct flow *flow,
3736                       const struct ofpbuf *packet)
3737 {
3738     ctx->ofproto = ofproto;
3739     ctx->flow = *flow;
3740     ctx->packet = packet;
3741     ctx->resubmit_hook = NULL;
3742     ctx->check_special = true;
3743 }
3744
3745 static bool
3746 ofproto_process_special(struct ofproto *ofproto, const struct flow *flow,
3747                         const struct ofpbuf *packet)
3748 {
3749     if (cfm_should_process_flow(flow)) {
3750         struct ofport *ofport = get_port(ofproto, flow->in_port);
3751         if (ofport && ofport->cfm) {
3752             cfm_process_heartbeat(ofport->cfm, packet);
3753         }
3754         return true;
3755     } else if (flow->dl_type == htons(ETH_TYPE_LACP)) {
3756         struct ofport *port = get_port(ofproto, flow->in_port);
3757         if (port && port->bundle && port->bundle->lacp) {
3758             const struct lacp_pdu *pdu = parse_lacp_packet(packet);
3759             if (pdu) {
3760                 lacp_process_pdu(port->bundle->lacp, port, pdu);
3761             }
3762             return true;
3763         }
3764     }
3765     return false;
3766 }
3767
3768 static struct ofpbuf *
3769 xlate_actions(struct action_xlate_ctx *ctx,
3770               const union ofp_action *in, size_t n_in)
3771 {
3772     COVERAGE_INC(ofproto_ofp2odp);
3773
3774     ctx->odp_actions = ofpbuf_new(512);
3775     ctx->tags = 0;
3776     ctx->may_set_up_flow = true;
3777     ctx->nf_output_iface = NF_OUT_DROP;
3778     ctx->recurse = 0;
3779     ctx->last_pop_priority = -1;
3780
3781     if (ctx->check_special
3782         && ofproto_process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
3783         ctx->may_set_up_flow = false;
3784     } else {
3785         do_xlate_actions(in, n_in, ctx);
3786     }
3787
3788     remove_pop_action(ctx);
3789
3790     /* Check with in-band control to see if we're allowed to set up this
3791      * flow. */
3792     if (!connmgr_may_set_up_flow(ctx->ofproto->connmgr, &ctx->flow,
3793                                  ctx->odp_actions->data,
3794                                  ctx->odp_actions->size)) {
3795         ctx->may_set_up_flow = false;
3796     }
3797
3798     return ctx->odp_actions;
3799 }
3800
3801 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
3802  * error message code (composed with ofp_mkerr()) for the caller to propagate
3803  * upward.  Otherwise, returns 0.
3804  *
3805  * The log message mentions 'msg_type'. */
3806 static int
3807 reject_slave_controller(struct ofconn *ofconn, const const char *msg_type)
3808 {
3809     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
3810         && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
3811         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
3812         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
3813                      msg_type);
3814
3815         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
3816     } else {
3817         return 0;
3818     }
3819 }
3820
3821 static int
3822 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
3823 {
3824     struct ofproto *p = ofconn_get_ofproto(ofconn);
3825     struct ofp_packet_out *opo;
3826     struct ofpbuf payload, *buffer;
3827     union ofp_action *ofp_actions;
3828     struct action_xlate_ctx ctx;
3829     struct ofpbuf *odp_actions;
3830     struct ofpbuf request;
3831     struct flow flow;
3832     size_t n_ofp_actions;
3833     uint16_t in_port;
3834     int error;
3835
3836     COVERAGE_INC(ofproto_packet_out);
3837
3838     error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
3839     if (error) {
3840         return error;
3841     }
3842
3843     /* Get ofp_packet_out. */
3844     ofpbuf_use_const(&request, oh, ntohs(oh->length));
3845     opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
3846
3847     /* Get actions. */
3848     error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
3849                                  &ofp_actions, &n_ofp_actions);
3850     if (error) {
3851         return error;
3852     }
3853
3854     /* Get payload. */
3855     if (opo->buffer_id != htonl(UINT32_MAX)) {
3856         error = ofconn_pktbuf_retrieve(ofconn, ntohl(opo->buffer_id),
3857                                        &buffer, &in_port);
3858         if (error || !buffer) {
3859             return error;
3860         }
3861         payload = *buffer;
3862     } else {
3863         payload = request;
3864         buffer = NULL;
3865     }
3866
3867     /* Extract flow, check actions. */
3868     flow_extract(&payload, 0, ofp_port_to_odp_port(ntohs(opo->in_port)),
3869                  &flow);
3870     error = validate_actions(ofp_actions, n_ofp_actions, &flow, p->max_ports);
3871     if (error) {
3872         goto exit;
3873     }
3874
3875     /* Send. */
3876     action_xlate_ctx_init(&ctx, p, &flow, &payload);
3877     odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
3878     dpif_execute(p->dpif, odp_actions->data, odp_actions->size, &payload);
3879     ofpbuf_delete(odp_actions);
3880
3881 exit:
3882     ofpbuf_delete(buffer);
3883     return 0;
3884 }
3885
3886 static void
3887 update_port_config(struct ofproto *p, struct ofport *port,
3888                    ovs_be32 config, ovs_be32 mask)
3889 {
3890     mask &= config ^ port->opp.config;
3891     if (mask & htonl(OFPPC_PORT_DOWN)) {
3892         if (config & htonl(OFPPC_PORT_DOWN)) {
3893             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
3894         } else {
3895             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
3896         }
3897     }
3898 #define REVALIDATE_BITS (OFPPC_NO_RECV | OFPPC_NO_RECV_STP |    \
3899                          OFPPC_NO_FWD | OFPPC_NO_FLOOD)
3900     if (mask & htonl(REVALIDATE_BITS)) {
3901         COVERAGE_INC(ofproto_costly_flags);
3902         port->opp.config ^= mask & htonl(REVALIDATE_BITS);
3903         p->need_revalidate = true;
3904     }
3905 #undef REVALIDATE_BITS
3906     if (mask & htonl(OFPPC_NO_PACKET_IN)) {
3907         port->opp.config ^= htonl(OFPPC_NO_PACKET_IN);
3908     }
3909 }
3910
3911 static int
3912 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3913 {
3914     struct ofproto *p = ofconn_get_ofproto(ofconn);
3915     const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
3916     struct ofport *port;
3917     int error;
3918
3919     error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
3920     if (error) {
3921         return error;
3922     }
3923
3924     port = get_port(p, ofp_port_to_odp_port(ntohs(opm->port_no)));
3925     if (!port) {
3926         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
3927     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
3928         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
3929     } else {
3930         update_port_config(p, port, opm->config, opm->mask);
3931         if (opm->advertise) {
3932             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
3933         }
3934     }
3935     return 0;
3936 }
3937
3938 static struct ofpbuf *
3939 make_ofp_stats_reply(ovs_be32 xid, ovs_be16 type, size_t body_len)
3940 {
3941     struct ofp_stats_reply *osr;
3942     struct ofpbuf *msg;
3943
3944     msg = ofpbuf_new(MIN(sizeof *osr + body_len, UINT16_MAX));
3945     osr = put_openflow_xid(sizeof *osr, OFPT_STATS_REPLY, xid, msg);
3946     osr->type = type;
3947     osr->flags = htons(0);
3948     return msg;
3949 }
3950
3951 static struct ofpbuf *
3952 start_ofp_stats_reply(const struct ofp_header *request, size_t body_len)
3953 {
3954     const struct ofp_stats_request *osr
3955         = (const struct ofp_stats_request *) request;
3956     return make_ofp_stats_reply(osr->header.xid, osr->type, body_len);
3957 }
3958
3959 static void *
3960 append_ofp_stats_reply(size_t nbytes, struct ofconn *ofconn,
3961                        struct ofpbuf **msgp)
3962 {
3963     struct ofpbuf *msg = *msgp;
3964     assert(nbytes <= UINT16_MAX - sizeof(struct ofp_stats_reply));
3965     if (nbytes + msg->size > UINT16_MAX) {
3966         struct ofp_stats_reply *reply = msg->data;
3967         reply->flags = htons(OFPSF_REPLY_MORE);
3968         *msgp = make_ofp_stats_reply(reply->header.xid, reply->type, nbytes);
3969         ofconn_send_reply(ofconn, msg);
3970     }
3971     return ofpbuf_put_uninit(*msgp, nbytes);
3972 }
3973
3974 static struct ofpbuf *
3975 make_nxstats_reply(ovs_be32 xid, ovs_be32 subtype, size_t body_len)
3976 {
3977     struct nicira_stats_msg *nsm;
3978     struct ofpbuf *msg;
3979
3980     msg = ofpbuf_new(MIN(sizeof *nsm + body_len, UINT16_MAX));
3981     nsm = put_openflow_xid(sizeof *nsm, OFPT_STATS_REPLY, xid, msg);
3982     nsm->type = htons(OFPST_VENDOR);
3983     nsm->flags = htons(0);
3984     nsm->vendor = htonl(NX_VENDOR_ID);
3985     nsm->subtype = subtype;
3986     return msg;
3987 }
3988
3989 static struct ofpbuf *
3990 start_nxstats_reply(const struct nicira_stats_msg *request, size_t body_len)
3991 {
3992     return make_nxstats_reply(request->header.xid, request->subtype, body_len);
3993 }
3994
3995 static void
3996 append_nxstats_reply(size_t nbytes, struct ofconn *ofconn,
3997                      struct ofpbuf **msgp)
3998 {
3999     struct ofpbuf *msg = *msgp;
4000     assert(nbytes <= UINT16_MAX - sizeof(struct nicira_stats_msg));
4001     if (nbytes + msg->size > UINT16_MAX) {
4002         struct nicira_stats_msg *reply = msg->data;
4003         reply->flags = htons(OFPSF_REPLY_MORE);
4004         *msgp = make_nxstats_reply(reply->header.xid, reply->subtype, nbytes);
4005         ofconn_send_reply(ofconn, msg);
4006     }
4007     ofpbuf_prealloc_tailroom(*msgp, nbytes);
4008 }
4009
4010 static int
4011 handle_desc_stats_request(struct ofconn *ofconn,
4012                           const struct ofp_header *request)
4013 {
4014     struct ofproto *p = ofconn_get_ofproto(ofconn);
4015     struct ofp_desc_stats *ods;
4016     struct ofpbuf *msg;
4017
4018     msg = start_ofp_stats_reply(request, sizeof *ods);
4019     ods = append_ofp_stats_reply(sizeof *ods, ofconn, &msg);
4020     memset(ods, 0, sizeof *ods);
4021     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
4022     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
4023     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
4024     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
4025     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
4026     ofconn_send_reply(ofconn, msg);
4027
4028     return 0;
4029 }
4030
4031 static int
4032 handle_table_stats_request(struct ofconn *ofconn,
4033                            const struct ofp_header *request)
4034 {
4035     struct ofproto *p = ofconn_get_ofproto(ofconn);
4036     struct ofp_table_stats *ots;
4037     struct ofpbuf *msg;
4038
4039     msg = start_ofp_stats_reply(request, sizeof *ots * 2);
4040
4041     /* Classifier table. */
4042     ots = append_ofp_stats_reply(sizeof *ots, ofconn, &msg);
4043     memset(ots, 0, sizeof *ots);
4044     strcpy(ots->name, "classifier");
4045     ots->wildcards = (ofconn_get_flow_format(ofconn) == NXFF_OPENFLOW10
4046                       ? htonl(OFPFW_ALL) : htonl(OVSFW_ALL));
4047     ots->max_entries = htonl(1024 * 1024); /* An arbitrary big number. */
4048     ots->active_count = htonl(classifier_count(&p->cls));
4049     put_32aligned_be64(&ots->lookup_count, htonll(0));  /* XXX */
4050     put_32aligned_be64(&ots->matched_count, htonll(0)); /* XXX */
4051
4052     ofconn_send_reply(ofconn, msg);
4053     return 0;
4054 }
4055
4056 static void
4057 append_port_stat(struct ofport *port, struct ofconn *ofconn,
4058                  struct ofpbuf **msgp)
4059 {
4060     struct netdev_stats stats;
4061     struct ofp_port_stats *ops;
4062
4063     /* Intentionally ignore return value, since errors will set
4064      * 'stats' to all-1s, which is correct for OpenFlow, and
4065      * netdev_get_stats() will log errors. */
4066     netdev_get_stats(port->netdev, &stats);
4067
4068     ops = append_ofp_stats_reply(sizeof *ops, ofconn, msgp);
4069     ops->port_no = port->opp.port_no;
4070     memset(ops->pad, 0, sizeof ops->pad);
4071     put_32aligned_be64(&ops->rx_packets, htonll(stats.rx_packets));
4072     put_32aligned_be64(&ops->tx_packets, htonll(stats.tx_packets));
4073     put_32aligned_be64(&ops->rx_bytes, htonll(stats.rx_bytes));
4074     put_32aligned_be64(&ops->tx_bytes, htonll(stats.tx_bytes));
4075     put_32aligned_be64(&ops->rx_dropped, htonll(stats.rx_dropped));
4076     put_32aligned_be64(&ops->tx_dropped, htonll(stats.tx_dropped));
4077     put_32aligned_be64(&ops->rx_errors, htonll(stats.rx_errors));
4078     put_32aligned_be64(&ops->tx_errors, htonll(stats.tx_errors));
4079     put_32aligned_be64(&ops->rx_frame_err, htonll(stats.rx_frame_errors));
4080     put_32aligned_be64(&ops->rx_over_err, htonll(stats.rx_over_errors));
4081     put_32aligned_be64(&ops->rx_crc_err, htonll(stats.rx_crc_errors));
4082     put_32aligned_be64(&ops->collisions, htonll(stats.collisions));
4083 }
4084
4085 static int
4086 handle_port_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
4087 {
4088     struct ofproto *p = ofconn_get_ofproto(ofconn);
4089     const struct ofp_port_stats_request *psr = ofputil_stats_body(oh);
4090     struct ofp_port_stats *ops;
4091     struct ofpbuf *msg;
4092     struct ofport *port;
4093
4094     msg = start_ofp_stats_reply(oh, sizeof *ops * 16);
4095     if (psr->port_no != htons(OFPP_NONE)) {
4096         port = get_port(p, ofp_port_to_odp_port(ntohs(psr->port_no)));
4097         if (port) {
4098             append_port_stat(port, ofconn, &msg);
4099         }
4100     } else {
4101         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
4102             append_port_stat(port, ofconn, &msg);
4103         }
4104     }
4105
4106     ofconn_send_reply(ofconn, msg);
4107     return 0;
4108 }
4109
4110 static void
4111 calc_flow_duration__(long long int start, uint32_t *sec, uint32_t *nsec)
4112 {
4113     long long int msecs = time_msec() - start;
4114     *sec = msecs / 1000;
4115     *nsec = (msecs % 1000) * (1000 * 1000);
4116 }
4117
4118 static void
4119 calc_flow_duration(long long int start, ovs_be32 *sec_be, ovs_be32 *nsec_be)
4120 {
4121     uint32_t sec, nsec;
4122
4123     calc_flow_duration__(start, &sec, &nsec);
4124     *sec_be = htonl(sec);
4125     *nsec_be = htonl(nsec);
4126 }
4127
4128 static void
4129 put_ofp_flow_stats(struct ofconn *ofconn, struct rule *rule,
4130                    ovs_be16 out_port, struct ofpbuf **replyp)
4131 {
4132     struct ofp_flow_stats *ofs;
4133     uint64_t packet_count, byte_count;
4134     ovs_be64 cookie;
4135     size_t act_len, len;
4136
4137     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
4138         return;
4139     }
4140
4141     act_len = sizeof *rule->actions * rule->n_actions;
4142     len = offsetof(struct ofp_flow_stats, actions) + act_len;
4143
4144     rule_get_stats(rule, &packet_count, &byte_count);
4145
4146     ofs = append_ofp_stats_reply(len, ofconn, replyp);
4147     ofs->length = htons(len);
4148     ofs->table_id = 0;
4149     ofs->pad = 0;
4150     ofputil_cls_rule_to_match(&rule->cr, ofconn_get_flow_format(ofconn),
4151                               &ofs->match, rule->flow_cookie, &cookie);
4152     put_32aligned_be64(&ofs->cookie, cookie);
4153     calc_flow_duration(rule->created, &ofs->duration_sec, &ofs->duration_nsec);
4154     ofs->priority = htons(rule->cr.priority);
4155     ofs->idle_timeout = htons(rule->idle_timeout);
4156     ofs->hard_timeout = htons(rule->hard_timeout);
4157     memset(ofs->pad2, 0, sizeof ofs->pad2);
4158     put_32aligned_be64(&ofs->packet_count, htonll(packet_count));
4159     put_32aligned_be64(&ofs->byte_count, htonll(byte_count));
4160     if (rule->n_actions > 0) {
4161         memcpy(ofs->actions, rule->actions, act_len);
4162     }
4163 }
4164
4165 static bool
4166 is_valid_table(uint8_t table_id)
4167 {
4168     if (table_id == 0 || table_id == 0xff) {
4169         return true;
4170     } else {
4171         /* It would probably be better to reply with an error but there doesn't
4172          * seem to be any appropriate value, so that might just be
4173          * confusing. */
4174         VLOG_WARN_RL(&rl, "controller asked for invalid table %"PRIu8,
4175                      table_id);
4176         return false;
4177     }
4178 }
4179
4180 static int
4181 handle_flow_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
4182 {
4183     const struct ofp_flow_stats_request *fsr = ofputil_stats_body(oh);
4184     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4185     struct ofpbuf *reply;
4186
4187     COVERAGE_INC(ofproto_flows_req);
4188     reply = start_ofp_stats_reply(oh, 1024);
4189     if (is_valid_table(fsr->table_id)) {
4190         struct cls_cursor cursor;
4191         struct cls_rule target;
4192         struct rule *rule;
4193
4194         ofputil_cls_rule_from_match(&fsr->match, 0, NXFF_OPENFLOW10, 0,
4195                                     &target);
4196         cls_cursor_init(&cursor, &ofproto->cls, &target);
4197         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4198             put_ofp_flow_stats(ofconn, rule, fsr->out_port, &reply);
4199         }
4200     }
4201     ofconn_send_reply(ofconn, reply);
4202
4203     return 0;
4204 }
4205
4206 static void
4207 put_nx_flow_stats(struct ofconn *ofconn, struct rule *rule,
4208                   ovs_be16 out_port, struct ofpbuf **replyp)
4209 {
4210     struct nx_flow_stats *nfs;
4211     uint64_t packet_count, byte_count;
4212     size_t act_len, start_len;
4213     struct ofpbuf *reply;
4214
4215     if (rule_is_hidden(rule) || !rule_has_out_port(rule, out_port)) {
4216         return;
4217     }
4218
4219     rule_get_stats(rule, &packet_count, &byte_count);
4220
4221     act_len = sizeof *rule->actions * rule->n_actions;
4222
4223     append_nxstats_reply(sizeof *nfs + NXM_MAX_LEN + act_len, ofconn, replyp);
4224     start_len = (*replyp)->size;
4225     reply = *replyp;
4226
4227     nfs = ofpbuf_put_uninit(reply, sizeof *nfs);
4228     nfs->table_id = 0;
4229     nfs->pad = 0;
4230     calc_flow_duration(rule->created, &nfs->duration_sec, &nfs->duration_nsec);
4231     nfs->cookie = rule->flow_cookie;
4232     nfs->priority = htons(rule->cr.priority);
4233     nfs->idle_timeout = htons(rule->idle_timeout);
4234     nfs->hard_timeout = htons(rule->hard_timeout);
4235     nfs->match_len = htons(nx_put_match(reply, &rule->cr));
4236     memset(nfs->pad2, 0, sizeof nfs->pad2);
4237     nfs->packet_count = htonll(packet_count);
4238     nfs->byte_count = htonll(byte_count);
4239     if (rule->n_actions > 0) {
4240         ofpbuf_put(reply, rule->actions, act_len);
4241     }
4242     nfs->length = htons(reply->size - start_len);
4243 }
4244
4245 static int
4246 handle_nxst_flow(struct ofconn *ofconn, const struct ofp_header *oh)
4247 {
4248     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4249     struct nx_flow_stats_request *nfsr;
4250     struct cls_rule target;
4251     struct ofpbuf *reply;
4252     struct ofpbuf b;
4253     int error;
4254
4255     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4256
4257     /* Dissect the message. */
4258     nfsr = ofpbuf_pull(&b, sizeof *nfsr);
4259     error = nx_pull_match(&b, ntohs(nfsr->match_len), 0, &target);
4260     if (error) {
4261         return error;
4262     }
4263     if (b.size) {
4264         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4265     }
4266
4267     COVERAGE_INC(ofproto_flows_req);
4268     reply = start_nxstats_reply(&nfsr->nsm, 1024);
4269     if (is_valid_table(nfsr->table_id)) {
4270         struct cls_cursor cursor;
4271         struct rule *rule;
4272
4273         cls_cursor_init(&cursor, &ofproto->cls, &target);
4274         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4275             put_nx_flow_stats(ofconn, rule, nfsr->out_port, &reply);
4276         }
4277     }
4278     ofconn_send_reply(ofconn, reply);
4279
4280     return 0;
4281 }
4282
4283 static void
4284 flow_stats_ds(struct rule *rule, struct ds *results)
4285 {
4286     uint64_t packet_count, byte_count;
4287     size_t act_len = sizeof *rule->actions * rule->n_actions;
4288
4289     rule_get_stats(rule, &packet_count, &byte_count);
4290
4291     ds_put_format(results, "duration=%llds, ",
4292                   (time_msec() - rule->created) / 1000);
4293     ds_put_format(results, "idle=%.3fs, ", (time_msec() - rule->used) / 1000.0);
4294     ds_put_format(results, "priority=%u, ", rule->cr.priority);
4295     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
4296     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
4297     cls_rule_format(&rule->cr, results);
4298     ds_put_char(results, ',');
4299     if (act_len > 0) {
4300         ofp_print_actions(results, &rule->actions->header, act_len);
4301     } else {
4302         ds_put_cstr(results, "drop");
4303     }
4304     ds_put_cstr(results, "\n");
4305 }
4306
4307 /* Adds a pretty-printed description of all flows to 'results', including
4308  * hidden flows (e.g., set up by in-band control). */
4309 void
4310 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
4311 {
4312     struct cls_cursor cursor;
4313     struct rule *rule;
4314
4315     cls_cursor_init(&cursor, &p->cls, NULL);
4316     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4317         flow_stats_ds(rule, results);
4318     }
4319 }
4320
4321 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
4322  * '*engine_type' and '*engine_id', respectively. */
4323 void
4324 ofproto_get_netflow_ids(const struct ofproto *ofproto,
4325                         uint8_t *engine_type, uint8_t *engine_id)
4326 {
4327     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
4328 }
4329
4330 static void
4331 query_aggregate_stats(struct ofproto *ofproto, struct cls_rule *target,
4332                       ovs_be16 out_port, uint8_t table_id,
4333                       struct ofp_aggregate_stats_reply *oasr)
4334 {
4335     uint64_t total_packets = 0;
4336     uint64_t total_bytes = 0;
4337     int n_flows = 0;
4338
4339     COVERAGE_INC(ofproto_agg_request);
4340
4341     if (is_valid_table(table_id)) {
4342         struct cls_cursor cursor;
4343         struct rule *rule;
4344
4345         cls_cursor_init(&cursor, &ofproto->cls, target);
4346         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4347             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
4348                 uint64_t packet_count;
4349                 uint64_t byte_count;
4350
4351                 rule_get_stats(rule, &packet_count, &byte_count);
4352
4353                 total_packets += packet_count;
4354                 total_bytes += byte_count;
4355                 n_flows++;
4356             }
4357         }
4358     }
4359
4360     oasr->flow_count = htonl(n_flows);
4361     put_32aligned_be64(&oasr->packet_count, htonll(total_packets));
4362     put_32aligned_be64(&oasr->byte_count, htonll(total_bytes));
4363     memset(oasr->pad, 0, sizeof oasr->pad);
4364 }
4365
4366 static int
4367 handle_aggregate_stats_request(struct ofconn *ofconn,
4368                                const struct ofp_header *oh)
4369 {
4370     const struct ofp_aggregate_stats_request *request = ofputil_stats_body(oh);
4371     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4372     struct ofp_aggregate_stats_reply *reply;
4373     struct cls_rule target;
4374     struct ofpbuf *msg;
4375
4376     ofputil_cls_rule_from_match(&request->match, 0, NXFF_OPENFLOW10, 0,
4377                                 &target);
4378
4379     msg = start_ofp_stats_reply(oh, sizeof *reply);
4380     reply = append_ofp_stats_reply(sizeof *reply, ofconn, &msg);
4381     query_aggregate_stats(ofproto, &target, request->out_port,
4382                           request->table_id, reply);
4383     ofconn_send_reply(ofconn, msg);
4384     return 0;
4385 }
4386
4387 static int
4388 handle_nxst_aggregate(struct ofconn *ofconn, const struct ofp_header *oh)
4389 {
4390     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4391     struct nx_aggregate_stats_request *request;
4392     struct ofp_aggregate_stats_reply *reply;
4393     struct cls_rule target;
4394     struct ofpbuf b;
4395     struct ofpbuf *buf;
4396     int error;
4397
4398     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4399
4400     /* Dissect the message. */
4401     request = ofpbuf_pull(&b, sizeof *request);
4402     error = nx_pull_match(&b, ntohs(request->match_len), 0, &target);
4403     if (error) {
4404         return error;
4405     }
4406     if (b.size) {
4407         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4408     }
4409
4410     /* Reply. */
4411     COVERAGE_INC(ofproto_flows_req);
4412     buf = start_nxstats_reply(&request->nsm, sizeof *reply);
4413     reply = ofpbuf_put_uninit(buf, sizeof *reply);
4414     query_aggregate_stats(ofproto, &target, request->out_port,
4415                           request->table_id, reply);
4416     ofconn_send_reply(ofconn, buf);
4417
4418     return 0;
4419 }
4420
4421 struct queue_stats_cbdata {
4422     struct ofconn *ofconn;
4423     struct ofport *ofport;
4424     struct ofpbuf *msg;
4425 };
4426
4427 static void
4428 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
4429                 const struct netdev_queue_stats *stats)
4430 {
4431     struct ofp_queue_stats *reply;
4432
4433     reply = append_ofp_stats_reply(sizeof *reply, cbdata->ofconn, &cbdata->msg);
4434     reply->port_no = cbdata->ofport->opp.port_no;
4435     memset(reply->pad, 0, sizeof reply->pad);
4436     reply->queue_id = htonl(queue_id);
4437     put_32aligned_be64(&reply->tx_bytes, htonll(stats->tx_bytes));
4438     put_32aligned_be64(&reply->tx_packets, htonll(stats->tx_packets));
4439     put_32aligned_be64(&reply->tx_errors, htonll(stats->tx_errors));
4440 }
4441
4442 static void
4443 handle_queue_stats_dump_cb(uint32_t queue_id,
4444                            struct netdev_queue_stats *stats,
4445                            void *cbdata_)
4446 {
4447     struct queue_stats_cbdata *cbdata = cbdata_;
4448
4449     put_queue_stats(cbdata, queue_id, stats);
4450 }
4451
4452 static void
4453 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
4454                             struct queue_stats_cbdata *cbdata)
4455 {
4456     cbdata->ofport = port;
4457     if (queue_id == OFPQ_ALL) {
4458         netdev_dump_queue_stats(port->netdev,
4459                                 handle_queue_stats_dump_cb, cbdata);
4460     } else {
4461         struct netdev_queue_stats stats;
4462
4463         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
4464             put_queue_stats(cbdata, queue_id, &stats);
4465         }
4466     }
4467 }
4468
4469 static int
4470 handle_queue_stats_request(struct ofconn *ofconn, const struct ofp_header *oh)
4471 {
4472     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4473     const struct ofp_queue_stats_request *qsr;
4474     struct queue_stats_cbdata cbdata;
4475     struct ofport *port;
4476     unsigned int port_no;
4477     uint32_t queue_id;
4478
4479     qsr = ofputil_stats_body(oh);
4480     if (!qsr) {
4481         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_LEN);
4482     }
4483
4484     COVERAGE_INC(ofproto_queue_req);
4485
4486     cbdata.ofconn = ofconn;
4487     cbdata.msg = start_ofp_stats_reply(oh, 128);
4488
4489     port_no = ntohs(qsr->port_no);
4490     queue_id = ntohl(qsr->queue_id);
4491     if (port_no == OFPP_ALL) {
4492         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
4493             handle_queue_stats_for_port(port, queue_id, &cbdata);
4494         }
4495     } else if (port_no < ofproto->max_ports) {
4496         port = get_port(ofproto, ofp_port_to_odp_port(port_no));
4497         if (port) {
4498             handle_queue_stats_for_port(port, queue_id, &cbdata);
4499         }
4500     } else {
4501         ofpbuf_delete(cbdata.msg);
4502         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
4503     }
4504     ofconn_send_reply(ofconn, cbdata.msg);
4505
4506     return 0;
4507 }
4508
4509 /* Updates 'facet''s used time.  Caller is responsible for calling
4510  * facet_push_stats() to update the flows which 'facet' resubmits into. */
4511 static void
4512 facet_update_time(struct ofproto *ofproto, struct facet *facet,
4513                   long long int used)
4514 {
4515     if (used > facet->used) {
4516         facet->used = used;
4517         if (used > facet->rule->used) {
4518             facet->rule->used = used;
4519         }
4520         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
4521     }
4522 }
4523
4524 /* Folds the statistics from 'stats' into the counters in 'facet'.
4525  *
4526  * Because of the meaning of a facet's counters, it only makes sense to do this
4527  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
4528  * packet that was sent by hand or if it represents statistics that have been
4529  * cleared out of the datapath. */
4530 static void
4531 facet_update_stats(struct ofproto *ofproto, struct facet *facet,
4532                    const struct dpif_flow_stats *stats)
4533 {
4534     if (stats->n_packets || stats->used > facet->used) {
4535         facet_update_time(ofproto, facet, stats->used);
4536         facet->packet_count += stats->n_packets;
4537         facet->byte_count += stats->n_bytes;
4538         facet_push_stats(ofproto, facet);
4539         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
4540     }
4541 }
4542
4543 static void
4544 facet_push_stats(struct ofproto *ofproto, struct facet *facet)
4545 {
4546     uint64_t rs_packets, rs_bytes;
4547
4548     assert(facet->packet_count >= facet->rs_packet_count);
4549     assert(facet->byte_count >= facet->rs_byte_count);
4550     assert(facet->used >= facet->rs_used);
4551
4552     rs_packets = facet->packet_count - facet->rs_packet_count;
4553     rs_bytes = facet->byte_count - facet->rs_byte_count;
4554
4555     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
4556         facet->rs_packet_count = facet->packet_count;
4557         facet->rs_byte_count = facet->byte_count;
4558         facet->rs_used = facet->used;
4559
4560         flow_push_stats(ofproto, facet->rule, &facet->flow,
4561                         rs_packets, rs_bytes, facet->used);
4562     }
4563 }
4564
4565 struct ofproto_push {
4566     struct action_xlate_ctx ctx;
4567     uint64_t packets;
4568     uint64_t bytes;
4569     long long int used;
4570 };
4571
4572 static void
4573 push_resubmit(struct action_xlate_ctx *ctx, struct rule *rule)
4574 {
4575     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
4576
4577     if (rule) {
4578         rule->packet_count += push->packets;
4579         rule->byte_count += push->bytes;
4580         rule->used = MAX(push->used, rule->used);
4581     }
4582 }
4583
4584 /* Pushes flow statistics to the rules which 'flow' resubmits into given
4585  * 'rule''s actions. */
4586 static void
4587 flow_push_stats(struct ofproto *ofproto, const struct rule *rule,
4588                 struct flow *flow, uint64_t packets, uint64_t bytes,
4589                 long long int used)
4590 {
4591     struct ofproto_push push;
4592
4593     push.packets = packets;
4594     push.bytes = bytes;
4595     push.used = used;
4596
4597     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
4598     push.ctx.resubmit_hook = push_resubmit;
4599     ofpbuf_delete(xlate_actions(&push.ctx, rule->actions, rule->n_actions));
4600 }
4601
4602 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
4603  * in which no matching flow already exists in the flow table.
4604  *
4605  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
4606  * ofp_actions, to the ofproto's flow table.  Returns 0 on success or an
4607  * OpenFlow error code as encoded by ofp_mkerr() on failure.
4608  *
4609  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4610  * if any. */
4611 static int
4612 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
4613 {
4614     struct ofproto *p = ofconn_get_ofproto(ofconn);
4615     struct ofpbuf *packet;
4616     struct rule *rule;
4617     uint16_t in_port;
4618     int error;
4619
4620     if (fm->flags & OFPFF_CHECK_OVERLAP
4621         && classifier_rule_overlaps(&p->cls, &fm->cr)) {
4622         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
4623     }
4624
4625     error = 0;
4626     if (fm->buffer_id != UINT32_MAX) {
4627         error = ofconn_pktbuf_retrieve(ofconn, fm->buffer_id,
4628                                        &packet, &in_port);
4629     } else {
4630         packet = NULL;
4631         in_port = UINT16_MAX;
4632     }
4633
4634     rule = rule_create(&fm->cr, fm->actions, fm->n_actions,
4635                        fm->idle_timeout, fm->hard_timeout, fm->cookie,
4636                        fm->flags & OFPFF_SEND_FLOW_REM);
4637     rule_insert(p, rule);
4638     if (packet) {
4639         rule_execute(p, rule, in_port, packet);
4640     }
4641     return error;
4642 }
4643
4644 static struct rule *
4645 find_flow_strict(struct ofproto *p, const struct flow_mod *fm)
4646 {
4647     return rule_from_cls_rule(classifier_find_rule_exactly(&p->cls, &fm->cr));
4648 }
4649
4650 static int
4651 send_buffered_packet(struct ofconn *ofconn,
4652                      struct rule *rule, uint32_t buffer_id)
4653 {
4654     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4655     struct ofpbuf *packet;
4656     uint16_t in_port;
4657     int error;
4658
4659     if (buffer_id == UINT32_MAX) {
4660         return 0;
4661     }
4662
4663     error = ofconn_pktbuf_retrieve(ofconn, buffer_id, &packet, &in_port);
4664     if (error) {
4665         return error;
4666     }
4667
4668     rule_execute(ofproto, rule, in_port, packet);
4669
4670     return 0;
4671 }
4672 \f
4673 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4674
4675 struct modify_flows_cbdata {
4676     struct ofproto *ofproto;
4677     const struct flow_mod *fm;
4678     struct rule *match;
4679 };
4680
4681 static int modify_flow(struct ofproto *, const struct flow_mod *,
4682                        struct rule *);
4683
4684 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
4685  * encoded by ofp_mkerr() on failure.
4686  *
4687  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4688  * if any. */
4689 static int
4690 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
4691 {
4692     struct ofproto *p = ofconn_get_ofproto(ofconn);
4693     struct rule *match = NULL;
4694     struct cls_cursor cursor;
4695     struct rule *rule;
4696
4697     cls_cursor_init(&cursor, &p->cls, &fm->cr);
4698     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4699         if (!rule_is_hidden(rule)) {
4700             match = rule;
4701             modify_flow(p, fm, rule);
4702         }
4703     }
4704
4705     if (match) {
4706         /* This credits the packet to whichever flow happened to match last.
4707          * That's weird.  Maybe we should do a lookup for the flow that
4708          * actually matches the packet?  Who knows. */
4709         send_buffered_packet(ofconn, match, fm->buffer_id);
4710         return 0;
4711     } else {
4712         return add_flow(ofconn, fm);
4713     }
4714 }
4715
4716 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
4717  * code as encoded by ofp_mkerr() on failure.
4718  *
4719  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
4720  * if any. */
4721 static int
4722 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
4723 {
4724     struct ofproto *p = ofconn_get_ofproto(ofconn);
4725     struct rule *rule = find_flow_strict(p, fm);
4726     if (rule && !rule_is_hidden(rule)) {
4727         modify_flow(p, fm, rule);
4728         return send_buffered_packet(ofconn, rule, fm->buffer_id);
4729     } else {
4730         return add_flow(ofconn, fm);
4731     }
4732 }
4733
4734 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
4735  * been identified as a flow in 'p''s flow table to be modified, by changing
4736  * the rule's actions to match those in 'ofm' (which is followed by 'n_actions'
4737  * ofp_action[] structures). */
4738 static int
4739 modify_flow(struct ofproto *p, const struct flow_mod *fm, struct rule *rule)
4740 {
4741     size_t actions_len = fm->n_actions * sizeof *rule->actions;
4742
4743     rule->flow_cookie = fm->cookie;
4744
4745     /* If the actions are the same, do nothing. */
4746     if (fm->n_actions == rule->n_actions
4747         && (!fm->n_actions
4748             || !memcmp(fm->actions, rule->actions, actions_len))) {
4749         return 0;
4750     }
4751
4752     /* Replace actions. */
4753     free(rule->actions);
4754     rule->actions = fm->n_actions ? xmemdup(fm->actions, actions_len) : NULL;
4755     rule->n_actions = fm->n_actions;
4756
4757     p->need_revalidate = true;
4758
4759     return 0;
4760 }
4761 \f
4762 /* OFPFC_DELETE implementation. */
4763
4764 static void delete_flow(struct ofproto *, struct rule *, ovs_be16 out_port);
4765
4766 /* Implements OFPFC_DELETE. */
4767 static void
4768 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
4769 {
4770     struct rule *rule, *next_rule;
4771     struct cls_cursor cursor;
4772
4773     cls_cursor_init(&cursor, &p->cls, &fm->cr);
4774     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
4775         delete_flow(p, rule, htons(fm->out_port));
4776     }
4777 }
4778
4779 /* Implements OFPFC_DELETE_STRICT. */
4780 static void
4781 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
4782 {
4783     struct rule *rule = find_flow_strict(p, fm);
4784     if (rule) {
4785         delete_flow(p, rule, htons(fm->out_port));
4786     }
4787 }
4788
4789 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
4790  * been identified as a flow to delete from 'p''s flow table, by deleting the
4791  * flow and sending out a OFPT_FLOW_REMOVED message to any interested
4792  * controller.
4793  *
4794  * Will not delete 'rule' if it is hidden.  Will delete 'rule' only if
4795  * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
4796  * specified 'out_port'. */
4797 static void
4798 delete_flow(struct ofproto *p, struct rule *rule, ovs_be16 out_port)
4799 {
4800     if (rule_is_hidden(rule)) {
4801         return;
4802     }
4803
4804     if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
4805         return;
4806     }
4807
4808     rule_send_removed(p, rule, OFPRR_DELETE);
4809     rule_remove(p, rule);
4810 }
4811 \f
4812 static int
4813 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4814 {
4815     struct ofproto *p = ofconn_get_ofproto(ofconn);
4816     struct flow_mod fm;
4817     int error;
4818
4819     error = reject_slave_controller(ofconn, "flow_mod");
4820     if (error) {
4821         return error;
4822     }
4823
4824     error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_flow_format(ofconn));
4825     if (error) {
4826         return error;
4827     }
4828
4829     /* We do not support the emergency flow cache.  It will hopefully get
4830      * dropped from OpenFlow in the near future. */
4831     if (fm.flags & OFPFF_EMERG) {
4832         /* There isn't a good fit for an error code, so just state that the
4833          * flow table is full. */
4834         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
4835     }
4836
4837     error = validate_actions(fm.actions, fm.n_actions,
4838                              &fm.cr.flow, p->max_ports);
4839     if (error) {
4840         return error;
4841     }
4842
4843     switch (fm.command) {
4844     case OFPFC_ADD:
4845         return add_flow(ofconn, &fm);
4846
4847     case OFPFC_MODIFY:
4848         return modify_flows_loose(ofconn, &fm);
4849
4850     case OFPFC_MODIFY_STRICT:
4851         return modify_flow_strict(ofconn, &fm);
4852
4853     case OFPFC_DELETE:
4854         delete_flows_loose(p, &fm);
4855         return 0;
4856
4857     case OFPFC_DELETE_STRICT:
4858         delete_flow_strict(p, &fm);
4859         return 0;
4860
4861     default:
4862         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
4863     }
4864 }
4865
4866 static int
4867 handle_tun_id_from_cookie(struct ofconn *ofconn, const struct ofp_header *oh)
4868 {
4869     const struct nxt_tun_id_cookie *msg
4870         = (const struct nxt_tun_id_cookie *) oh;
4871     enum nx_flow_format flow_format;
4872
4873     flow_format = msg->set ? NXFF_TUN_ID_FROM_COOKIE : NXFF_OPENFLOW10;
4874     ofconn_set_flow_format(ofconn, flow_format);
4875
4876     return 0;
4877 }
4878
4879 static int
4880 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4881 {
4882     struct nx_role_request *nrr = (struct nx_role_request *) oh;
4883     struct nx_role_request *reply;
4884     struct ofpbuf *buf;
4885     uint32_t role;
4886
4887     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY) {
4888         VLOG_WARN_RL(&rl, "ignoring role request on service connection");
4889         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4890     }
4891
4892     role = ntohl(nrr->role);
4893     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
4894         && role != NX_ROLE_SLAVE) {
4895         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
4896
4897         /* There's no good error code for this. */
4898         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
4899     }
4900
4901     ofconn_set_role(ofconn, role);
4902
4903     reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
4904     reply->role = htonl(role);
4905     ofconn_send_reply(ofconn, buf);
4906
4907     return 0;
4908 }
4909
4910 static int
4911 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4912 {
4913     const struct nxt_set_flow_format *msg
4914         = (const struct nxt_set_flow_format *) oh;
4915     uint32_t format;
4916
4917     format = ntohl(msg->format);
4918     if (format == NXFF_OPENFLOW10
4919         || format == NXFF_TUN_ID_FROM_COOKIE
4920         || format == NXFF_NXM) {
4921         ofconn_set_flow_format(ofconn, format);
4922         return 0;
4923     } else {
4924         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
4925     }
4926 }
4927
4928 static int
4929 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4930 {
4931     struct ofp_header *ob;
4932     struct ofpbuf *buf;
4933
4934     /* Currently, everything executes synchronously, so we can just
4935      * immediately send the barrier reply. */
4936     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
4937     ofconn_send_reply(ofconn, buf);
4938     return 0;
4939 }
4940
4941 static int
4942 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
4943 {
4944     const struct ofp_header *oh = msg->data;
4945     const struct ofputil_msg_type *type;
4946     int error;
4947
4948     error = ofputil_decode_msg_type(oh, &type);
4949     if (error) {
4950         return error;
4951     }
4952
4953     switch (ofputil_msg_type_code(type)) {
4954         /* OpenFlow requests. */
4955     case OFPUTIL_OFPT_ECHO_REQUEST:
4956         return handle_echo_request(ofconn, oh);
4957
4958     case OFPUTIL_OFPT_FEATURES_REQUEST:
4959         return handle_features_request(ofconn, oh);
4960
4961     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
4962         return handle_get_config_request(ofconn, oh);
4963
4964     case OFPUTIL_OFPT_SET_CONFIG:
4965         return handle_set_config(ofconn, msg->data);
4966
4967     case OFPUTIL_OFPT_PACKET_OUT:
4968         return handle_packet_out(ofconn, oh);
4969
4970     case OFPUTIL_OFPT_PORT_MOD:
4971         return handle_port_mod(ofconn, oh);
4972
4973     case OFPUTIL_OFPT_FLOW_MOD:
4974         return handle_flow_mod(ofconn, oh);
4975
4976     case OFPUTIL_OFPT_BARRIER_REQUEST:
4977         return handle_barrier_request(ofconn, oh);
4978
4979         /* OpenFlow replies. */
4980     case OFPUTIL_OFPT_ECHO_REPLY:
4981         return 0;
4982
4983         /* Nicira extension requests. */
4984     case OFPUTIL_NXT_TUN_ID_FROM_COOKIE:
4985         return handle_tun_id_from_cookie(ofconn, oh);
4986
4987     case OFPUTIL_NXT_ROLE_REQUEST:
4988         return handle_role_request(ofconn, oh);
4989
4990     case OFPUTIL_NXT_SET_FLOW_FORMAT:
4991         return handle_nxt_set_flow_format(ofconn, oh);
4992
4993     case OFPUTIL_NXT_FLOW_MOD:
4994         return handle_flow_mod(ofconn, oh);
4995
4996         /* OpenFlow statistics requests. */
4997     case OFPUTIL_OFPST_DESC_REQUEST:
4998         return handle_desc_stats_request(ofconn, oh);
4999
5000     case OFPUTIL_OFPST_FLOW_REQUEST:
5001         return handle_flow_stats_request(ofconn, oh);
5002
5003     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
5004         return handle_aggregate_stats_request(ofconn, oh);
5005
5006     case OFPUTIL_OFPST_TABLE_REQUEST:
5007         return handle_table_stats_request(ofconn, oh);
5008
5009     case OFPUTIL_OFPST_PORT_REQUEST:
5010         return handle_port_stats_request(ofconn, oh);
5011
5012     case OFPUTIL_OFPST_QUEUE_REQUEST:
5013         return handle_queue_stats_request(ofconn, oh);
5014
5015         /* Nicira extension statistics requests. */
5016     case OFPUTIL_NXST_FLOW_REQUEST:
5017         return handle_nxst_flow(ofconn, oh);
5018
5019     case OFPUTIL_NXST_AGGREGATE_REQUEST:
5020         return handle_nxst_aggregate(ofconn, oh);
5021
5022     case OFPUTIL_INVALID:
5023     case OFPUTIL_OFPT_HELLO:
5024     case OFPUTIL_OFPT_ERROR:
5025     case OFPUTIL_OFPT_FEATURES_REPLY:
5026     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
5027     case OFPUTIL_OFPT_PACKET_IN:
5028     case OFPUTIL_OFPT_FLOW_REMOVED:
5029     case OFPUTIL_OFPT_PORT_STATUS:
5030     case OFPUTIL_OFPT_BARRIER_REPLY:
5031     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
5032     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
5033     case OFPUTIL_OFPST_DESC_REPLY:
5034     case OFPUTIL_OFPST_FLOW_REPLY:
5035     case OFPUTIL_OFPST_QUEUE_REPLY:
5036     case OFPUTIL_OFPST_PORT_REPLY:
5037     case OFPUTIL_OFPST_TABLE_REPLY:
5038     case OFPUTIL_OFPST_AGGREGATE_REPLY:
5039     case OFPUTIL_NXT_ROLE_REPLY:
5040     case OFPUTIL_NXT_FLOW_REMOVED:
5041     case OFPUTIL_NXST_FLOW_REPLY:
5042     case OFPUTIL_NXST_AGGREGATE_REPLY:
5043     default:
5044         if (VLOG_IS_WARN_ENABLED()) {
5045             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
5046             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
5047             free(s);
5048         }
5049         if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
5050             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
5051         } else {
5052             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
5053         }
5054     }
5055 }
5056
5057 static void
5058 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
5059 {
5060     int error = handle_openflow__(ofconn, ofp_msg);
5061     if (error) {
5062         send_error_oh(ofconn, ofp_msg->data, error);
5063     }
5064     COVERAGE_INC(ofproto_recv_openflow);
5065 }
5066 \f
5067 static void
5068 handle_miss_upcall(struct ofproto *p, struct dpif_upcall *upcall)
5069 {
5070     struct facet *facet;
5071     struct flow flow;
5072
5073     /* Obtain in_port and tun_id, at least. */
5074     odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
5075
5076     /* Set header pointers in 'flow'. */
5077     flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
5078
5079     /* Handle 802.1ag and LACP. */
5080     if (ofproto_process_special(p, &flow, upcall->packet)) {
5081         ofpbuf_delete(upcall->packet);
5082         return;
5083     }
5084
5085     /* Check with in-band control to see if this packet should be sent
5086      * to the local port regardless of the flow table. */
5087     if (connmgr_msg_in_hook(p->connmgr, &flow, upcall->packet)) {
5088         ofproto_send_packet(p, ODPP_LOCAL, 0, upcall->packet);
5089     }
5090
5091     facet = facet_lookup_valid(p, &flow);
5092     if (!facet) {
5093         struct rule *rule = rule_lookup(p, &flow);
5094         if (!rule) {
5095             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
5096             struct ofport *port = get_port(p, flow.in_port);
5097             if (port) {
5098                 if (port->opp.config & htonl(OFPPC_NO_PACKET_IN)) {
5099                     COVERAGE_INC(ofproto_no_packet_in);
5100                     /* XXX install 'drop' flow entry */
5101                     ofpbuf_delete(upcall->packet);
5102                     return;
5103                 }
5104             } else {
5105                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
5106                              flow.in_port);
5107             }
5108
5109             COVERAGE_INC(ofproto_packet_in);
5110             send_packet_in(p, upcall, &flow, false);
5111             return;
5112         }
5113
5114         facet = facet_create(p, rule, &flow, upcall->packet);
5115     } else if (!facet->may_install) {
5116         /* The facet is not installable, that is, we need to process every
5117          * packet, so process the current packet's actions into 'facet'. */
5118         facet_make_actions(p, facet, upcall->packet);
5119     }
5120
5121     if (facet->rule->cr.priority == FAIL_OPEN_PRIORITY) {
5122         /*
5123          * Extra-special case for fail-open mode.
5124          *
5125          * We are in fail-open mode and the packet matched the fail-open rule,
5126          * but we are connected to a controller too.  We should send the packet
5127          * up to the controller in the hope that it will try to set up a flow
5128          * and thereby allow us to exit fail-open.
5129          *
5130          * See the top-level comment in fail-open.c for more information.
5131          */
5132         send_packet_in(p, upcall, &flow, true);
5133     }
5134
5135     facet_execute(p, facet, upcall->packet);
5136     facet_install(p, facet, false);
5137 }
5138
5139 static void
5140 handle_upcall(struct ofproto *p, struct dpif_upcall *upcall)
5141 {
5142     struct flow flow;
5143
5144     switch (upcall->type) {
5145     case DPIF_UC_ACTION:
5146         COVERAGE_INC(ofproto_ctlr_action);
5147         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
5148         send_packet_in(p, upcall, &flow, false);
5149         break;
5150
5151     case DPIF_UC_SAMPLE:
5152         if (p->sflow) {
5153             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
5154             ofproto_sflow_received(p->sflow, upcall, &flow);
5155         }
5156         ofpbuf_delete(upcall->packet);
5157         break;
5158
5159     case DPIF_UC_MISS:
5160         handle_miss_upcall(p, upcall);
5161         break;
5162
5163     case DPIF_N_UC_TYPES:
5164     default:
5165         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
5166         break;
5167     }
5168 }
5169 \f
5170 /* Flow expiration. */
5171
5172 static int ofproto_dp_max_idle(const struct ofproto *);
5173 static void ofproto_update_stats(struct ofproto *);
5174 static void rule_expire(struct ofproto *, struct rule *);
5175 static void ofproto_expire_facets(struct ofproto *, int dp_max_idle);
5176
5177 /* This function is called periodically by ofproto_run().  Its job is to
5178  * collect updates for the flows that have been installed into the datapath,
5179  * most importantly when they last were used, and then use that information to
5180  * expire flows that have not been used recently.
5181  *
5182  * Returns the number of milliseconds after which it should be called again. */
5183 static int
5184 ofproto_expire(struct ofproto *ofproto)
5185 {
5186     struct rule *rule, *next_rule;
5187     struct cls_cursor cursor;
5188     int dp_max_idle;
5189
5190     /* Update stats for each flow in the datapath. */
5191     ofproto_update_stats(ofproto);
5192
5193     /* Expire facets that have been idle too long. */
5194     dp_max_idle = ofproto_dp_max_idle(ofproto);
5195     ofproto_expire_facets(ofproto, dp_max_idle);
5196
5197     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
5198     cls_cursor_init(&cursor, &ofproto->cls, NULL);
5199     CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
5200         rule_expire(ofproto, rule);
5201     }
5202
5203     /* All outstanding data in existing flows has been accounted, so it's a
5204      * good time to do bond rebalancing. */
5205     if (ofproto->has_bonded_bundles) {
5206         struct ofbundle *bundle;
5207
5208         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
5209             if (bundle->bond) {
5210                 bond_rebalance(bundle->bond, &ofproto->revalidate_set);
5211             }
5212         }
5213     }
5214
5215     return MIN(dp_max_idle, 1000);
5216 }
5217
5218 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
5219  *
5220  * This function also pushes statistics updates to rules which each facet
5221  * resubmits into.  Generally these statistics will be accurate.  However, if a
5222  * facet changes the rule it resubmits into at some time in between
5223  * ofproto_update_stats() runs, it is possible that statistics accrued to the
5224  * old rule will be incorrectly attributed to the new rule.  This could be
5225  * avoided by calling ofproto_update_stats() whenever rules are created or
5226  * deleted.  However, the performance impact of making so many calls to the
5227  * datapath do not justify the benefit of having perfectly accurate statistics.
5228  */
5229 static void
5230 ofproto_update_stats(struct ofproto *p)
5231 {
5232     const struct dpif_flow_stats *stats;
5233     struct dpif_flow_dump dump;
5234     const struct nlattr *key;
5235     size_t key_len;
5236
5237     dpif_flow_dump_start(&dump, p->dpif);
5238     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
5239         struct facet *facet;
5240         struct flow flow;
5241
5242         if (odp_flow_key_to_flow(key, key_len, &flow)) {
5243             struct ds s;
5244
5245             ds_init(&s);
5246             odp_flow_key_format(key, key_len, &s);
5247             VLOG_WARN_RL(&rl, "failed to convert ODP flow key to flow: %s",
5248                          ds_cstr(&s));
5249             ds_destroy(&s);
5250
5251             continue;
5252         }
5253         facet = facet_find(p, &flow);
5254
5255         if (facet && facet->installed) {
5256
5257             if (stats->n_packets >= facet->dp_packet_count) {
5258                 facet->packet_count += stats->n_packets - facet->dp_packet_count;
5259             } else {
5260                 VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
5261             }
5262
5263             if (stats->n_bytes >= facet->dp_byte_count) {
5264                 facet->byte_count += stats->n_bytes - facet->dp_byte_count;
5265             } else {
5266                 VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
5267             }
5268
5269             facet->dp_packet_count = stats->n_packets;
5270             facet->dp_byte_count = stats->n_bytes;
5271
5272             facet_update_time(p, facet, stats->used);
5273             facet_account(p, facet, stats->n_bytes);
5274             facet_push_stats(p, facet);
5275         } else {
5276             /* There's a flow in the datapath that we know nothing about.
5277              * Delete it. */
5278             COVERAGE_INC(ofproto_unexpected_rule);
5279             dpif_flow_del(p->dpif, key, key_len, NULL);
5280         }
5281     }
5282     dpif_flow_dump_done(&dump);
5283 }
5284
5285 /* Calculates and returns the number of milliseconds of idle time after which
5286  * facets should expire from the datapath and we should fold their statistics
5287  * into their parent rules in userspace. */
5288 static int
5289 ofproto_dp_max_idle(const struct ofproto *ofproto)
5290 {
5291     /*
5292      * Idle time histogram.
5293      *
5294      * Most of the time a switch has a relatively small number of facets.  When
5295      * this is the case we might as well keep statistics for all of them in
5296      * userspace and to cache them in the kernel datapath for performance as
5297      * well.
5298      *
5299      * As the number of facets increases, the memory required to maintain
5300      * statistics about them in userspace and in the kernel becomes
5301      * significant.  However, with a large number of facets it is likely that
5302      * only a few of them are "heavy hitters" that consume a large amount of
5303      * bandwidth.  At this point, only heavy hitters are worth caching in the
5304      * kernel and maintaining in userspaces; other facets we can discard.
5305      *
5306      * The technique used to compute the idle time is to build a histogram with
5307      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each facet
5308      * that is installed in the kernel gets dropped in the appropriate bucket.
5309      * After the histogram has been built, we compute the cutoff so that only
5310      * the most-recently-used 1% of facets (but at least 1000 flows) are kept
5311      * cached.  At least the most-recently-used bucket of facets is kept, so
5312      * actually an arbitrary number of facets can be kept in any given
5313      * expiration run (though the next run will delete most of those unless
5314      * they receive additional data).
5315      *
5316      * This requires a second pass through the facets, in addition to the pass
5317      * made by ofproto_update_stats(), because the former function never looks
5318      * at uninstallable facets.
5319      */
5320     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
5321     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
5322     int buckets[N_BUCKETS] = { 0 };
5323     struct facet *facet;
5324     int total, bucket;
5325     long long int now;
5326     int i;
5327
5328     total = hmap_count(&ofproto->facets);
5329     if (total <= 1000) {
5330         return N_BUCKETS * BUCKET_WIDTH;
5331     }
5332
5333     /* Build histogram. */
5334     now = time_msec();
5335     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
5336         long long int idle = now - facet->used;
5337         int bucket = (idle <= 0 ? 0
5338                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
5339                       : (unsigned int) idle / BUCKET_WIDTH);
5340         buckets[bucket]++;
5341     }
5342
5343     /* Find the first bucket whose flows should be expired. */
5344     for (bucket = 0; bucket < N_BUCKETS; bucket++) {
5345         if (buckets[bucket]) {
5346             int subtotal = 0;
5347             do {
5348                 subtotal += buckets[bucket++];
5349             } while (bucket < N_BUCKETS && subtotal < MAX(1000, total / 100));
5350             break;
5351         }
5352     }
5353
5354     if (VLOG_IS_DBG_ENABLED()) {
5355         struct ds s;
5356
5357         ds_init(&s);
5358         ds_put_cstr(&s, "keep");
5359         for (i = 0; i < N_BUCKETS; i++) {
5360             if (i == bucket) {
5361                 ds_put_cstr(&s, ", drop");
5362             }
5363             if (buckets[i]) {
5364                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
5365             }
5366         }
5367         VLOG_INFO("%s: %s (msec:count)", ofproto->name, ds_cstr(&s));
5368         ds_destroy(&s);
5369     }
5370
5371     return bucket * BUCKET_WIDTH;
5372 }
5373
5374 static void
5375 facet_active_timeout(struct ofproto *ofproto, struct facet *facet)
5376 {
5377     if (ofproto->netflow && !facet_is_controller_flow(facet) &&
5378         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
5379         struct ofexpired expired;
5380
5381         if (facet->installed) {
5382             struct dpif_flow_stats stats;
5383
5384             facet_put__(ofproto, facet, facet->actions, facet->actions_len,
5385                         &stats);
5386             facet_update_stats(ofproto, facet, &stats);
5387         }
5388
5389         expired.flow = facet->flow;
5390         expired.packet_count = facet->packet_count;
5391         expired.byte_count = facet->byte_count;
5392         expired.used = facet->used;
5393         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
5394     }
5395 }
5396
5397 static void
5398 ofproto_expire_facets(struct ofproto *ofproto, int dp_max_idle)
5399 {
5400     long long int cutoff = time_msec() - dp_max_idle;
5401     struct facet *facet, *next_facet;
5402
5403     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
5404         facet_active_timeout(ofproto, facet);
5405         if (facet->used < cutoff) {
5406             facet_remove(ofproto, facet);
5407         }
5408     }
5409 }
5410
5411 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
5412  * then delete it entirely. */
5413 static void
5414 rule_expire(struct ofproto *ofproto, struct rule *rule)
5415 {
5416     struct facet *facet, *next_facet;
5417     long long int now;
5418     uint8_t reason;
5419
5420     /* Has 'rule' expired? */
5421     now = time_msec();
5422     if (rule->hard_timeout
5423         && now > rule->created + rule->hard_timeout * 1000) {
5424         reason = OFPRR_HARD_TIMEOUT;
5425     } else if (rule->idle_timeout && list_is_empty(&rule->facets)
5426                && now >rule->used + rule->idle_timeout * 1000) {
5427         reason = OFPRR_IDLE_TIMEOUT;
5428     } else {
5429         return;
5430     }
5431
5432     COVERAGE_INC(ofproto_expired);
5433
5434     /* Update stats.  (This is a no-op if the rule expired due to an idle
5435      * timeout, because that only happens when the rule has no facets left.) */
5436     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
5437         facet_remove(ofproto, facet);
5438     }
5439
5440     /* Get rid of the rule. */
5441     if (!rule_is_hidden(rule)) {
5442         rule_send_removed(ofproto, rule, reason);
5443     }
5444     rule_remove(ofproto, rule);
5445 }
5446 \f
5447 static void
5448 rule_send_removed(struct ofproto *p, struct rule *rule, uint8_t reason)
5449 {
5450     struct ofputil_flow_removed fr;
5451
5452     if (!rule->send_flow_removed) {
5453         return;
5454     }
5455
5456     fr.rule = rule->cr;
5457     fr.cookie = rule->flow_cookie;
5458     fr.reason = reason;
5459     calc_flow_duration__(rule->created, &fr.duration_sec, &fr.duration_nsec);
5460     fr.idle_timeout = rule->idle_timeout;
5461     fr.packet_count = rule->packet_count;
5462     fr.byte_count = rule->byte_count;
5463
5464     connmgr_send_flow_removed(p->connmgr, &fr);
5465 }
5466
5467 /* Obtains statistics for 'rule' and stores them in '*packets' and '*bytes'.
5468  * The returned statistics include statistics for all of 'rule''s facets. */
5469 static void
5470 rule_get_stats(const struct rule *rule, uint64_t *packets, uint64_t *bytes)
5471 {
5472     uint64_t p, b;
5473     struct facet *facet;
5474
5475     /* Start from historical data for 'rule' itself that are no longer tracked
5476      * in facets.  This counts, for example, facets that have expired. */
5477     p = rule->packet_count;
5478     b = rule->byte_count;
5479
5480     /* Add any statistics that are tracked by facets.  This includes
5481      * statistical data recently updated by ofproto_update_stats() as well as
5482      * stats for packets that were executed "by hand" via dpif_execute(). */
5483     LIST_FOR_EACH (facet, list_node, &rule->facets) {
5484         p += facet->packet_count;
5485         b += facet->byte_count;
5486     }
5487
5488     *packets = p;
5489     *bytes = b;
5490 }
5491
5492 /* Given 'upcall', of type DPIF_UC_ACTION or DPIF_UC_MISS, sends an
5493  * OFPT_PACKET_IN message to each OpenFlow controller as necessary according to
5494  * their individual configurations.
5495  *
5496  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
5497  * Otherwise, ownership is transferred to this function. */
5498 static void
5499 send_packet_in(struct ofproto *ofproto, struct dpif_upcall *upcall,
5500                const struct flow *flow, bool clone)
5501 {
5502     struct ofputil_packet_in pin;
5503
5504     pin.packet = upcall->packet;
5505     pin.in_port = odp_port_to_ofp_port(flow->in_port);
5506     pin.reason = upcall->type == DPIF_UC_MISS ? OFPR_NO_MATCH : OFPR_ACTION;
5507     pin.buffer_id = 0;          /* not yet known */
5508     pin.send_len = upcall->userdata;
5509     connmgr_send_packet_in(ofproto->connmgr, upcall, flow,
5510                            clone ? NULL : upcall->packet);
5511 }
5512
5513 static uint64_t
5514 pick_datapath_id(const struct ofproto *ofproto)
5515 {
5516     const struct ofport *port;
5517
5518     port = get_port(ofproto, ODPP_LOCAL);
5519     if (port) {
5520         uint8_t ea[ETH_ADDR_LEN];
5521         int error;
5522
5523         error = netdev_get_etheraddr(port->netdev, ea);
5524         if (!error) {
5525             return eth_addr_to_uint64(ea);
5526         }
5527         VLOG_WARN("could not get MAC address for %s (%s)",
5528                   netdev_get_name(port->netdev), strerror(error));
5529     }
5530     return ofproto->fallback_dpid;
5531 }
5532
5533 static uint64_t
5534 pick_fallback_dpid(void)
5535 {
5536     uint8_t ea[ETH_ADDR_LEN];
5537     eth_addr_nicira_random(ea);
5538     return eth_addr_to_uint64(ea);
5539 }
5540 \f
5541 static struct ofproto *
5542 ofproto_lookup(const char *name)
5543 {
5544     struct ofproto *ofproto;
5545
5546     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
5547                              &all_ofprotos) {
5548         if (!strcmp(ofproto->name, name)) {
5549             return ofproto;
5550         }
5551     }
5552     return NULL;
5553 }
5554
5555 static void
5556 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
5557                      void *aux OVS_UNUSED)
5558 {
5559     struct ofproto *ofproto;
5560     struct ds results;
5561
5562     ds_init(&results);
5563     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
5564         ds_put_format(&results, "%s\n", ofproto->name);
5565     }
5566     unixctl_command_reply(conn, 200, ds_cstr(&results));
5567     ds_destroy(&results);
5568 }
5569
5570 struct ofproto_trace {
5571     struct action_xlate_ctx ctx;
5572     struct flow flow;
5573     struct ds *result;
5574 };
5575
5576 static void
5577 trace_format_rule(struct ds *result, int level, const struct rule *rule)
5578 {
5579     ds_put_char_multiple(result, '\t', level);
5580     if (!rule) {
5581         ds_put_cstr(result, "No match\n");
5582         return;
5583     }
5584
5585     ds_put_format(result, "Rule: cookie=%#"PRIx64" ",
5586                   ntohll(rule->flow_cookie));
5587     cls_rule_format(&rule->cr, result);
5588     ds_put_char(result, '\n');
5589
5590     ds_put_char_multiple(result, '\t', level);
5591     ds_put_cstr(result, "OpenFlow ");
5592     ofp_print_actions(result, (const struct ofp_action_header *) rule->actions,
5593                       rule->n_actions * sizeof *rule->actions);
5594     ds_put_char(result, '\n');
5595 }
5596
5597 static void
5598 trace_format_flow(struct ds *result, int level, const char *title,
5599                  struct ofproto_trace *trace)
5600 {
5601     ds_put_char_multiple(result, '\t', level);
5602     ds_put_format(result, "%s: ", title);
5603     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5604         ds_put_cstr(result, "unchanged");
5605     } else {
5606         flow_format(result, &trace->ctx.flow);
5607         trace->flow = trace->ctx.flow;
5608     }
5609     ds_put_char(result, '\n');
5610 }
5611
5612 static void
5613 trace_resubmit(struct action_xlate_ctx *ctx, struct rule *rule)
5614 {
5615     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5616     struct ds *result = trace->result;
5617
5618     ds_put_char(result, '\n');
5619     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5620     trace_format_rule(result, ctx->recurse + 1, rule);
5621 }
5622
5623 static void
5624 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5625                       void *aux OVS_UNUSED)
5626 {
5627     char *dpname, *in_port_s, *tun_id_s, *packet_s;
5628     char *args = xstrdup(args_);
5629     char *save_ptr = NULL;
5630     struct ofproto *ofproto;
5631     struct ofpbuf packet;
5632     struct rule *rule;
5633     struct ds result;
5634     struct flow flow;
5635     uint16_t in_port;
5636     ovs_be64 tun_id;
5637     char *s;
5638
5639     ofpbuf_init(&packet, strlen(args) / 2);
5640     ds_init(&result);
5641
5642     dpname = strtok_r(args, " ", &save_ptr);
5643     tun_id_s = strtok_r(NULL, " ", &save_ptr);
5644     in_port_s = strtok_r(NULL, " ", &save_ptr);
5645     packet_s = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5646     if (!dpname || !in_port_s || !packet_s) {
5647         unixctl_command_reply(conn, 501, "Bad command syntax");
5648         goto exit;
5649     }
5650
5651     ofproto = ofproto_lookup(dpname);
5652     if (!ofproto) {
5653         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5654                               "for help)");
5655         goto exit;
5656     }
5657
5658     tun_id = htonll(strtoull(tun_id_s, NULL, 0));
5659     in_port = ofp_port_to_odp_port(atoi(in_port_s));
5660
5661     packet_s = ofpbuf_put_hex(&packet, packet_s, NULL);
5662     packet_s += strspn(packet_s, " ");
5663     if (*packet_s != '\0') {
5664         unixctl_command_reply(conn, 501, "Trailing garbage in command");
5665         goto exit;
5666     }
5667     if (packet.size < ETH_HEADER_LEN) {
5668         unixctl_command_reply(conn, 501, "Packet data too short for Ethernet");
5669         goto exit;
5670     }
5671
5672     ds_put_cstr(&result, "Packet: ");
5673     s = ofp_packet_to_string(packet.data, packet.size, packet.size);
5674     ds_put_cstr(&result, s);
5675     free(s);
5676
5677     flow_extract(&packet, tun_id, in_port, &flow);
5678     ds_put_cstr(&result, "Flow: ");
5679     flow_format(&result, &flow);
5680     ds_put_char(&result, '\n');
5681
5682     rule = rule_lookup(ofproto, &flow);
5683     trace_format_rule(&result, 0, rule);
5684     if (rule) {
5685         struct ofproto_trace trace;
5686         struct ofpbuf *odp_actions;
5687
5688         trace.result = &result;
5689         trace.flow = flow;
5690         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, &packet);
5691         trace.ctx.resubmit_hook = trace_resubmit;
5692         odp_actions = xlate_actions(&trace.ctx,
5693                                     rule->actions, rule->n_actions);
5694
5695         ds_put_char(&result, '\n');
5696         trace_format_flow(&result, 0, "Final flow", &trace);
5697         ds_put_cstr(&result, "Datapath actions: ");
5698         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5699         ofpbuf_delete(odp_actions);
5700     }
5701
5702     unixctl_command_reply(conn, 200, ds_cstr(&result));
5703
5704 exit:
5705     ds_destroy(&result);
5706     ofpbuf_uninit(&packet);
5707     free(args);
5708 }
5709
5710 static void
5711 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
5712                          const char *args, void *aux OVS_UNUSED)
5713 {
5714     struct ds ds = DS_EMPTY_INITIALIZER;
5715     const struct ofproto *ofproto;
5716     const struct mac_entry *e;
5717
5718     ofproto = ofproto_lookup(args);
5719     if (!ofproto) {
5720         unixctl_command_reply(conn, 501, "no such bridge");
5721         return;
5722     }
5723
5724     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5725     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5726         struct ofbundle *bundle = e->port.p;
5727         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
5728                       ofbundle_get_a_port(bundle)->odp_port,
5729                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
5730     }
5731     unixctl_command_reply(conn, 200, ds_cstr(&ds));
5732     ds_destroy(&ds);
5733 }
5734
5735 static void
5736 ofproto_unixctl_init(void)
5737 {
5738     static bool registered;
5739     if (registered) {
5740         return;
5741     }
5742     registered = true;
5743
5744     unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
5745     unixctl_command_register("ofproto/trace", ofproto_unixctl_trace, NULL);
5746     unixctl_command_register("fdb/show", ofproto_unixctl_fdb_show, NULL);
5747 }