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