ofproto-dpif: Install drops for flows from invalid in_ports.
[sliver-openvswitch.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013 Nicira, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "ofproto/ofproto-provider.h"
20
21 #include <errno.h>
22
23 #include "autopath.h"
24 #include "bond.h"
25 #include "bundle.h"
26 #include "byte-order.h"
27 #include "connmgr.h"
28 #include "coverage.h"
29 #include "cfm.h"
30 #include "dpif.h"
31 #include "dynamic-string.h"
32 #include "fail-open.h"
33 #include "hmapx.h"
34 #include "lacp.h"
35 #include "learn.h"
36 #include "mac-learning.h"
37 #include "meta-flow.h"
38 #include "multipath.h"
39 #include "netdev-vport.h"
40 #include "netdev.h"
41 #include "netlink.h"
42 #include "nx-match.h"
43 #include "odp-util.h"
44 #include "ofp-util.h"
45 #include "ofpbuf.h"
46 #include "ofp-actions.h"
47 #include "ofp-parse.h"
48 #include "ofp-print.h"
49 #include "ofproto-dpif-governor.h"
50 #include "ofproto-dpif-sflow.h"
51 #include "poll-loop.h"
52 #include "simap.h"
53 #include "smap.h"
54 #include "timer.h"
55 #include "unaligned.h"
56 #include "unixctl.h"
57 #include "vlan-bitmap.h"
58 #include "vlog.h"
59
60 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
61
62 COVERAGE_DEFINE(ofproto_dpif_expired);
63 COVERAGE_DEFINE(ofproto_dpif_xlate);
64 COVERAGE_DEFINE(facet_changed_rule);
65 COVERAGE_DEFINE(facet_revalidate);
66 COVERAGE_DEFINE(facet_unexpected);
67 COVERAGE_DEFINE(facet_suppress);
68
69 /* Maximum depth of flow table recursion (due to resubmit actions) in a
70  * flow translation. */
71 #define MAX_RESUBMIT_RECURSION 64
72
73 /* Number of implemented OpenFlow tables. */
74 enum { N_TABLES = 255 };
75 enum { TBL_INTERNAL = N_TABLES - 1 };    /* Used for internal hidden rules. */
76 BUILD_ASSERT_DECL(N_TABLES >= 2 && N_TABLES <= 255);
77
78 struct ofport_dpif;
79 struct ofproto_dpif;
80 struct flow_miss;
81
82 struct rule_dpif {
83     struct rule up;
84
85     /* These statistics:
86      *
87      *   - Do include packets and bytes from facets that have been deleted or
88      *     whose own statistics have been folded into the rule.
89      *
90      *   - Do include packets and bytes sent "by hand" that were accounted to
91      *     the rule without any facet being involved (this is a rare corner
92      *     case in rule_execute()).
93      *
94      *   - Do not include packet or bytes that can be obtained from any facet's
95      *     packet_count or byte_count member or that can be obtained from the
96      *     datapath by, e.g., dpif_flow_get() for any subfacet.
97      */
98     uint64_t packet_count;       /* Number of packets received. */
99     uint64_t byte_count;         /* Number of bytes received. */
100
101     tag_type tag;                /* Caches rule_calculate_tag() result. */
102
103     struct list facets;          /* List of "struct facet"s. */
104 };
105
106 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
107 {
108     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
109 }
110
111 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
112                                           const struct flow *);
113 static struct rule_dpif *rule_dpif_lookup__(struct ofproto_dpif *,
114                                             const struct flow *,
115                                             uint8_t table);
116 static struct rule_dpif *rule_dpif_miss_rule(struct ofproto_dpif *ofproto,
117                                              const struct flow *flow);
118
119 static void rule_credit_stats(struct rule_dpif *,
120                               const struct dpif_flow_stats *);
121 static void flow_push_stats(struct rule_dpif *, const struct flow *,
122                             const struct dpif_flow_stats *);
123 static tag_type rule_calculate_tag(const struct flow *,
124                                    const struct minimask *, uint32_t basis);
125 static void rule_invalidate(const struct rule_dpif *);
126
127 #define MAX_MIRRORS 32
128 typedef uint32_t mirror_mask_t;
129 #define MIRROR_MASK_C(X) UINT32_C(X)
130 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
131 struct ofmirror {
132     struct ofproto_dpif *ofproto; /* Owning ofproto. */
133     size_t idx;                 /* In ofproto's "mirrors" array. */
134     void *aux;                  /* Key supplied by ofproto's client. */
135     char *name;                 /* Identifier for log messages. */
136
137     /* Selection criteria. */
138     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
139     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
140     unsigned long *vlans;       /* Bitmap of chosen VLANs, NULL selects all. */
141
142     /* Output (exactly one of out == NULL and out_vlan == -1 is true). */
143     struct ofbundle *out;       /* Output port or NULL. */
144     int out_vlan;               /* Output VLAN or -1. */
145     mirror_mask_t dup_mirrors;  /* Bitmap of mirrors with the same output. */
146
147     /* Counters. */
148     int64_t packet_count;       /* Number of packets sent. */
149     int64_t byte_count;         /* Number of bytes sent. */
150 };
151
152 static void mirror_destroy(struct ofmirror *);
153 static void update_mirror_stats(struct ofproto_dpif *ofproto,
154                                 mirror_mask_t mirrors,
155                                 uint64_t packets, uint64_t bytes);
156
157 struct ofbundle {
158     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
159     struct ofproto_dpif *ofproto; /* Owning ofproto. */
160     void *aux;                  /* Key supplied by ofproto's client. */
161     char *name;                 /* Identifier for log messages. */
162
163     /* Configuration. */
164     struct list ports;          /* Contains "struct ofport"s. */
165     enum port_vlan_mode vlan_mode; /* VLAN mode */
166     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
167     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
168                                  * NULL if all VLANs are trunked. */
169     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
170     struct bond *bond;          /* Nonnull iff more than one port. */
171     bool use_priority_tags;     /* Use 802.1p tag for frames in VLAN 0? */
172
173     /* Status. */
174     bool floodable;          /* True if no port has OFPUTIL_PC_NO_FLOOD set. */
175
176     /* Port mirroring info. */
177     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
178     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
179     mirror_mask_t mirror_out;   /* Mirrors that output to this bundle. */
180 };
181
182 static void bundle_remove(struct ofport *);
183 static void bundle_update(struct ofbundle *);
184 static void bundle_destroy(struct ofbundle *);
185 static void bundle_del_port(struct ofport_dpif *);
186 static void bundle_run(struct ofbundle *);
187 static void bundle_wait(struct ofbundle *);
188 static struct ofbundle *lookup_input_bundle(const struct ofproto_dpif *,
189                                             uint16_t in_port, bool warn,
190                                             struct ofport_dpif **in_ofportp);
191
192 /* A controller may use OFPP_NONE as the ingress port to indicate that
193  * it did not arrive on a "real" port.  'ofpp_none_bundle' exists for
194  * when an input bundle is needed for validation (e.g., mirroring or
195  * OFPP_NORMAL processing).  It is not connected to an 'ofproto' or have
196  * any 'port' structs, so care must be taken when dealing with it. */
197 static struct ofbundle ofpp_none_bundle = {
198     .name      = "OFPP_NONE",
199     .vlan_mode = PORT_VLAN_TRUNK
200 };
201
202 static void stp_run(struct ofproto_dpif *ofproto);
203 static void stp_wait(struct ofproto_dpif *ofproto);
204 static int set_stp_port(struct ofport *,
205                         const struct ofproto_port_stp_settings *);
206
207 static bool ofbundle_includes_vlan(const struct ofbundle *, uint16_t vlan);
208
209 struct action_xlate_ctx {
210 /* action_xlate_ctx_init() initializes these members. */
211
212     /* The ofproto. */
213     struct ofproto_dpif *ofproto;
214
215     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
216      * this flow when actions change header fields. */
217     struct flow flow;
218
219     /* The packet corresponding to 'flow', or a null pointer if we are
220      * revalidating without a packet to refer to. */
221     const struct ofpbuf *packet;
222
223     /* Should OFPP_NORMAL update the MAC learning table?  Should "learn"
224      * actions update the flow table?
225      *
226      * We want to update these tables if we are actually processing a packet,
227      * or if we are accounting for packets that the datapath has processed, but
228      * not if we are just revalidating. */
229     bool may_learn;
230
231     /* The rule that we are currently translating, or NULL. */
232     struct rule_dpif *rule;
233
234     /* Union of the set of TCP flags seen so far in this flow.  (Used only by
235      * NXAST_FIN_TIMEOUT.  Set to zero to avoid updating updating rules'
236      * timeouts.) */
237     uint8_t tcp_flags;
238
239     /* If nonnull, flow translation calls this function just before executing a
240      * resubmit or OFPP_TABLE action.  In addition, disables logging of traces
241      * when the recursion depth is exceeded.
242      *
243      * 'rule' is the rule being submitted into.  It will be null if the
244      * resubmit or OFPP_TABLE action didn't find a matching rule.
245      *
246      * This is normally null so the client has to set it manually after
247      * calling action_xlate_ctx_init(). */
248     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule_dpif *rule);
249
250     /* If nonnull, flow translation calls this function to report some
251      * significant decision, e.g. to explain why OFPP_NORMAL translation
252      * dropped a packet. */
253     void (*report_hook)(struct action_xlate_ctx *, const char *s);
254
255     /* If nonnull, flow translation credits the specified statistics to each
256      * rule reached through a resubmit or OFPP_TABLE action.
257      *
258      * This is normally null so the client has to set it manually after
259      * calling action_xlate_ctx_init(). */
260     const struct dpif_flow_stats *resubmit_stats;
261
262 /* xlate_actions() initializes and uses these members.  The client might want
263  * to look at them after it returns. */
264
265     struct ofpbuf *odp_actions; /* Datapath actions. */
266     tag_type tags;              /* Tags associated with actions. */
267     enum slow_path_reason slow; /* 0 if fast path may be used. */
268     bool has_learn;             /* Actions include NXAST_LEARN? */
269     bool has_normal;            /* Actions output to OFPP_NORMAL? */
270     bool has_fin_timeout;       /* Actions include NXAST_FIN_TIMEOUT? */
271     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
272     mirror_mask_t mirrors;      /* Bitmap of associated mirrors. */
273
274 /* xlate_actions() initializes and uses these members, but the client has no
275  * reason to look at them. */
276
277     int recurse;                /* Recursion level, via xlate_table_action. */
278     bool max_resubmit_trigger;  /* Recursed too deeply during translation. */
279     struct flow base_flow;      /* Flow at the last commit. */
280     uint32_t orig_skb_priority; /* Priority when packet arrived. */
281     uint8_t table_id;           /* OpenFlow table ID where flow was found. */
282     uint32_t sflow_n_outputs;   /* Number of output ports. */
283     uint32_t sflow_odp_port;    /* Output port for composing sFlow action. */
284     uint16_t user_cookie_offset;/* Used for user_action_cookie fixup. */
285     bool exit;                  /* No further actions should be processed. */
286     struct flow orig_flow;      /* Copy of original flow. */
287 };
288
289 static void action_xlate_ctx_init(struct action_xlate_ctx *,
290                                   struct ofproto_dpif *, const struct flow *,
291                                   ovs_be16 initial_tci, struct rule_dpif *,
292                                   uint8_t tcp_flags, const struct ofpbuf *);
293 static void xlate_actions(struct action_xlate_ctx *,
294                           const struct ofpact *ofpacts, size_t ofpacts_len,
295                           struct ofpbuf *odp_actions);
296 static void xlate_actions_for_side_effects(struct action_xlate_ctx *,
297                                            const struct ofpact *ofpacts,
298                                            size_t ofpacts_len);
299 static void xlate_table_action(struct action_xlate_ctx *, uint16_t in_port,
300                                uint8_t table_id, bool may_packet_in);
301
302 static size_t put_userspace_action(const struct ofproto_dpif *,
303                                    struct ofpbuf *odp_actions,
304                                    const struct flow *,
305                                    const union user_action_cookie *);
306
307 static void compose_slow_path(const struct ofproto_dpif *, const struct flow *,
308                               enum slow_path_reason,
309                               uint64_t *stub, size_t stub_size,
310                               const struct nlattr **actionsp,
311                               size_t *actions_lenp);
312
313 static void xlate_report(struct action_xlate_ctx *ctx, const char *s);
314
315 /* A subfacet (see "struct subfacet" below) has three possible installation
316  * states:
317  *
318  *   - SF_NOT_INSTALLED: Not installed in the datapath.  This will only be the
319  *     case just after the subfacet is created, just before the subfacet is
320  *     destroyed, or if the datapath returns an error when we try to install a
321  *     subfacet.
322  *
323  *   - SF_FAST_PATH: The subfacet's actions are installed in the datapath.
324  *
325  *   - SF_SLOW_PATH: An action that sends every packet for the subfacet through
326  *     ofproto_dpif is installed in the datapath.
327  */
328 enum subfacet_path {
329     SF_NOT_INSTALLED,           /* No datapath flow for this subfacet. */
330     SF_FAST_PATH,               /* Full actions are installed. */
331     SF_SLOW_PATH,               /* Send-to-userspace action is installed. */
332 };
333
334 static const char *subfacet_path_to_string(enum subfacet_path);
335
336 /* A dpif flow and actions associated with a facet.
337  *
338  * See also the large comment on struct facet. */
339 struct subfacet {
340     /* Owners. */
341     struct hmap_node hmap_node; /* In struct ofproto_dpif 'subfacets' list. */
342     struct list list_node;      /* In struct facet's 'facets' list. */
343     struct facet *facet;        /* Owning facet. */
344
345     /* Key.
346      *
347      * To save memory in the common case, 'key' is NULL if 'key_fitness' is
348      * ODP_FIT_PERFECT, that is, odp_flow_key_from_flow() can accurately
349      * regenerate the ODP flow key from ->facet->flow. */
350     enum odp_key_fitness key_fitness;
351     struct nlattr *key;
352     int key_len;
353
354     long long int used;         /* Time last used; time created if not used. */
355
356     uint64_t dp_packet_count;   /* Last known packet count in the datapath. */
357     uint64_t dp_byte_count;     /* Last known byte count in the datapath. */
358
359     /* Datapath actions.
360      *
361      * These should be essentially identical for every subfacet in a facet, but
362      * may differ in trivial ways due to VLAN splinters. */
363     size_t actions_len;         /* Number of bytes in actions[]. */
364     struct nlattr *actions;     /* Datapath actions. */
365
366     enum slow_path_reason slow; /* 0 if fast path may be used. */
367     enum subfacet_path path;    /* Installed in datapath? */
368
369     /* This value is normally the same as ->facet->flow.vlan_tci.  Only VLAN
370      * splinters can cause it to differ.  This value should be removed when
371      * the VLAN splinters feature is no longer needed.  */
372     ovs_be16 initial_tci;       /* Initial VLAN TCI value. */
373
374     /* Datapath port the packet arrived on.  This is needed to remove
375      * flows for ports that are no longer part of the bridge.  Since the
376      * flow definition only has the OpenFlow port number and the port is
377      * no longer part of the bridge, we can't determine the datapath port
378      * number needed to delete the flow from the datapath. */
379     uint32_t odp_in_port;
380 };
381
382 #define SUBFACET_DESTROY_MAX_BATCH 50
383
384 static struct subfacet *subfacet_create(struct facet *, struct flow_miss *miss,
385                                         long long int now);
386 static struct subfacet *subfacet_find(struct ofproto_dpif *,
387                                       const struct nlattr *key, size_t key_len,
388                                       uint32_t key_hash,
389                                       const struct flow *flow);
390 static void subfacet_destroy(struct subfacet *);
391 static void subfacet_destroy__(struct subfacet *);
392 static void subfacet_destroy_batch(struct ofproto_dpif *,
393                                    struct subfacet **, int n);
394 static void subfacet_get_key(struct subfacet *, struct odputil_keybuf *,
395                              struct ofpbuf *key);
396 static void subfacet_reset_dp_stats(struct subfacet *,
397                                     struct dpif_flow_stats *);
398 static void subfacet_update_time(struct subfacet *, long long int used);
399 static void subfacet_update_stats(struct subfacet *,
400                                   const struct dpif_flow_stats *);
401 static void subfacet_make_actions(struct subfacet *,
402                                   const struct ofpbuf *packet,
403                                   struct ofpbuf *odp_actions);
404 static int subfacet_install(struct subfacet *,
405                             const struct nlattr *actions, size_t actions_len,
406                             struct dpif_flow_stats *, enum slow_path_reason);
407 static void subfacet_uninstall(struct subfacet *);
408
409 static enum subfacet_path subfacet_want_path(enum slow_path_reason);
410
411 /* An exact-match instantiation of an OpenFlow flow.
412  *
413  * A facet associates a "struct flow", which represents the Open vSwitch
414  * userspace idea of an exact-match flow, with one or more subfacets.  Each
415  * subfacet tracks the datapath's idea of the exact-match flow equivalent to
416  * the facet.  When the kernel module (or other dpif implementation) and Open
417  * vSwitch userspace agree on the definition of a flow key, there is exactly
418  * one subfacet per facet.  If the dpif implementation supports more-specific
419  * flow matching than userspace, however, a facet can have more than one
420  * subfacet, each of which corresponds to some distinction in flow that
421  * userspace simply doesn't understand.
422  *
423  * Flow expiration works in terms of subfacets, so a facet must have at least
424  * one subfacet or it will never expire, leaking memory. */
425 struct facet {
426     /* Owners. */
427     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
428     struct list list_node;       /* In owning rule's 'facets' list. */
429     struct rule_dpif *rule;      /* Owning rule. */
430
431     /* Owned data. */
432     struct list subfacets;
433     long long int used;         /* Time last used; time created if not used. */
434
435     /* Key. */
436     struct flow flow;
437
438     /* These statistics:
439      *
440      *   - Do include packets and bytes sent "by hand", e.g. with
441      *     dpif_execute().
442      *
443      *   - Do include packets and bytes that were obtained from the datapath
444      *     when a subfacet's statistics were reset (e.g. dpif_flow_put() with
445      *     DPIF_FP_ZERO_STATS).
446      *
447      *   - Do not include packets or bytes that can be obtained from the
448      *     datapath for any existing subfacet.
449      */
450     uint64_t packet_count;       /* Number of packets received. */
451     uint64_t byte_count;         /* Number of bytes received. */
452
453     /* Resubmit statistics. */
454     uint64_t prev_packet_count;  /* Number of packets from last stats push. */
455     uint64_t prev_byte_count;    /* Number of bytes from last stats push. */
456     long long int prev_used;     /* Used time from last stats push. */
457
458     /* Accounting. */
459     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
460     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
461     uint8_t tcp_flags;           /* TCP flags seen for this 'rule'. */
462
463     /* Properties of datapath actions.
464      *
465      * Every subfacet has its own actions because actions can differ slightly
466      * between splintered and non-splintered subfacets due to the VLAN tag
467      * being initially different (present vs. absent).  All of them have these
468      * properties in common so we just store one copy of them here. */
469     bool has_learn;              /* Actions include NXAST_LEARN? */
470     bool has_normal;             /* Actions output to OFPP_NORMAL? */
471     bool has_fin_timeout;        /* Actions include NXAST_FIN_TIMEOUT? */
472     tag_type tags;               /* Tags that would require revalidation. */
473     mirror_mask_t mirrors;       /* Bitmap of dependent mirrors. */
474
475     /* Storage for a single subfacet, to reduce malloc() time and space
476      * overhead.  (A facet always has at least one subfacet and in the common
477      * case has exactly one subfacet.) */
478     struct subfacet one_subfacet;
479 };
480
481 static struct facet *facet_create(struct rule_dpif *,
482                                   const struct flow *, uint32_t hash);
483 static void facet_remove(struct facet *);
484 static void facet_free(struct facet *);
485
486 static struct facet *facet_find(struct ofproto_dpif *,
487                                 const struct flow *, uint32_t hash);
488 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
489                                         const struct flow *, uint32_t hash);
490 static void facet_revalidate(struct facet *);
491 static bool facet_check_consistency(struct facet *);
492
493 static void facet_flush_stats(struct facet *);
494
495 static void facet_update_time(struct facet *, long long int used);
496 static void facet_reset_counters(struct facet *);
497 static void facet_push_stats(struct facet *);
498 static void facet_learn(struct facet *);
499 static void facet_account(struct facet *);
500
501 static bool facet_is_controller_flow(struct facet *);
502
503 struct ofport_dpif {
504     struct hmap_node odp_port_node; /* In dpif_backer's "odp_to_ofport_map". */
505     struct ofport up;
506
507     uint32_t odp_port;
508     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
509     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
510     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
511     tag_type tag;               /* Tag associated with this port. */
512     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
513     bool may_enable;            /* May be enabled in bonds. */
514     long long int carrier_seq;  /* Carrier status changes. */
515
516     /* Spanning tree. */
517     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
518     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
519     long long int stp_state_entered;
520
521     struct hmap priorities;     /* Map of attached 'priority_to_dscp's. */
522
523     /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
524      *
525      * This is deprecated.  It is only for compatibility with broken device
526      * drivers in old versions of Linux that do not properly support VLANs when
527      * VLAN devices are not used.  When broken device drivers are no longer in
528      * widespread use, we will delete these interfaces. */
529     uint16_t realdev_ofp_port;
530     int vlandev_vid;
531 };
532
533 /* Node in 'ofport_dpif''s 'priorities' map.  Used to maintain a map from
534  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
535  * traffic egressing the 'ofport' with that priority should be marked with. */
536 struct priority_to_dscp {
537     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'priorities' map. */
538     uint32_t priority;          /* Priority of this queue (see struct flow). */
539
540     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
541 };
542
543 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
544  *
545  * This is deprecated.  It is only for compatibility with broken device drivers
546  * in old versions of Linux that do not properly support VLANs when VLAN
547  * devices are not used.  When broken device drivers are no longer in
548  * widespread use, we will delete these interfaces. */
549 struct vlan_splinter {
550     struct hmap_node realdev_vid_node;
551     struct hmap_node vlandev_node;
552     uint16_t realdev_ofp_port;
553     uint16_t vlandev_ofp_port;
554     int vid;
555 };
556
557 static uint32_t vsp_realdev_to_vlandev(const struct ofproto_dpif *,
558                                        uint32_t realdev, ovs_be16 vlan_tci);
559 static bool vsp_adjust_flow(const struct ofproto_dpif *, struct flow *);
560 static void vsp_remove(struct ofport_dpif *);
561 static void vsp_add(struct ofport_dpif *, uint16_t realdev_ofp_port, int vid);
562
563 static uint32_t ofp_port_to_odp_port(const struct ofproto_dpif *,
564                                      uint16_t ofp_port);
565 static uint16_t odp_port_to_ofp_port(const struct ofproto_dpif *,
566                                      uint32_t odp_port);
567
568 static struct ofport_dpif *
569 ofport_dpif_cast(const struct ofport *ofport)
570 {
571     ovs_assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
572     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
573 }
574
575 static void port_run(struct ofport_dpif *);
576 static void port_run_fast(struct ofport_dpif *);
577 static void port_wait(struct ofport_dpif *);
578 static int set_cfm(struct ofport *, const struct cfm_settings *);
579 static void ofport_clear_priorities(struct ofport_dpif *);
580
581 struct dpif_completion {
582     struct list list_node;
583     struct ofoperation *op;
584 };
585
586 /* Extra information about a classifier table.
587  * Currently used just for optimized flow revalidation. */
588 struct table_dpif {
589     /* If either of these is nonnull, then this table has a form that allows
590      * flows to be tagged to avoid revalidating most flows for the most common
591      * kinds of flow table changes. */
592     struct cls_table *catchall_table; /* Table that wildcards all fields. */
593     struct cls_table *other_table;    /* Table with any other wildcard set. */
594     uint32_t basis;                   /* Keeps each table's tags separate. */
595 };
596
597 /* Reasons that we might need to revalidate every facet, and corresponding
598  * coverage counters.
599  *
600  * A value of 0 means that there is no need to revalidate.
601  *
602  * It would be nice to have some cleaner way to integrate with coverage
603  * counters, but with only a few reasons I guess this is good enough for
604  * now. */
605 enum revalidate_reason {
606     REV_RECONFIGURE = 1,       /* Switch configuration changed. */
607     REV_STP,                   /* Spanning tree protocol port status change. */
608     REV_PORT_TOGGLED,          /* Port enabled or disabled by CFM, LACP, ...*/
609     REV_FLOW_TABLE,            /* Flow table changed. */
610     REV_INCONSISTENCY          /* Facet self-check failed. */
611 };
612 COVERAGE_DEFINE(rev_reconfigure);
613 COVERAGE_DEFINE(rev_stp);
614 COVERAGE_DEFINE(rev_port_toggled);
615 COVERAGE_DEFINE(rev_flow_table);
616 COVERAGE_DEFINE(rev_inconsistency);
617
618 /* Drop keys are odp flow keys which have drop flows installed in the kernel.
619  * These are datapath flows which have no associated ofproto, if they did we
620  * would use facets. */
621 struct drop_key {
622     struct hmap_node hmap_node;
623     struct nlattr *key;
624     size_t key_len;
625 };
626
627 /* All datapaths of a given type share a single dpif backer instance. */
628 struct dpif_backer {
629     char *type;
630     int refcount;
631     struct dpif *dpif;
632     struct timer next_expiration;
633     struct hmap odp_to_ofport_map; /* ODP port to ofport mapping. */
634
635     /* Facet revalidation flags applying to facets which use this backer. */
636     enum revalidate_reason need_revalidate; /* Revalidate every facet. */
637     struct tag_set revalidate_set; /* Revalidate only matching facets. */
638
639     struct hmap drop_keys; /* Set of dropped odp keys. */
640 };
641
642 /* All existing ofproto_backer instances, indexed by ofproto->up.type. */
643 static struct shash all_dpif_backers = SHASH_INITIALIZER(&all_dpif_backers);
644
645 static void drop_key_clear(struct dpif_backer *);
646 static struct ofport_dpif *
647 odp_port_to_ofport(const struct dpif_backer *, uint32_t odp_port);
648
649 struct ofproto_dpif {
650     struct hmap_node all_ofproto_dpifs_node; /* In 'all_ofproto_dpifs'. */
651     struct ofproto up;
652     struct dpif_backer *backer;
653
654     /* Special OpenFlow rules. */
655     struct rule_dpif *miss_rule; /* Sends flow table misses to controller. */
656     struct rule_dpif *no_packet_in_rule; /* Drops flow table misses. */
657
658     /* Statistics. */
659     uint64_t n_matches;
660
661     /* Bridging. */
662     struct netflow *netflow;
663     struct dpif_sflow *sflow;
664     struct hmap bundles;        /* Contains "struct ofbundle"s. */
665     struct mac_learning *ml;
666     struct ofmirror *mirrors[MAX_MIRRORS];
667     bool has_mirrors;
668     bool has_bonded_bundles;
669
670     /* Facets. */
671     struct hmap facets;
672     struct hmap subfacets;
673     struct governor *governor;
674
675     /* Revalidation. */
676     struct table_dpif tables[N_TABLES];
677
678     /* Support for debugging async flow mods. */
679     struct list completions;
680
681     bool has_bundle_action; /* True when the first bundle action appears. */
682     struct netdev_stats stats; /* To account packets generated and consumed in
683                                 * userspace. */
684
685     /* Spanning tree. */
686     struct stp *stp;
687     long long int stp_last_tick;
688
689     /* VLAN splinters. */
690     struct hmap realdev_vid_map; /* (realdev,vid) -> vlandev. */
691     struct hmap vlandev_map;     /* vlandev -> (realdev,vid). */
692
693     /* Ports. */
694     struct sset ports;             /* Set of standard port names. */
695     struct sset ghost_ports;       /* Ports with no datapath port. */
696     struct sset port_poll_set;     /* Queued names for port_poll() reply. */
697     int port_poll_errno;           /* Last errno for port_poll() reply. */
698 };
699
700 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
701  * for debugging the asynchronous flow_mod implementation.) */
702 static bool clogged;
703
704 /* All existing ofproto_dpif instances, indexed by ->up.name. */
705 static struct hmap all_ofproto_dpifs = HMAP_INITIALIZER(&all_ofproto_dpifs);
706
707 static void ofproto_dpif_unixctl_init(void);
708
709 static struct ofproto_dpif *
710 ofproto_dpif_cast(const struct ofproto *ofproto)
711 {
712     ovs_assert(ofproto->ofproto_class == &ofproto_dpif_class);
713     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
714 }
715
716 static struct ofport_dpif *get_ofp_port(const struct ofproto_dpif *,
717                                         uint16_t ofp_port);
718 static struct ofport_dpif *get_odp_port(const struct ofproto_dpif *,
719                                         uint32_t odp_port);
720 static void ofproto_trace(struct ofproto_dpif *, const struct flow *,
721                           const struct ofpbuf *, ovs_be16 initial_tci,
722                           struct ds *);
723
724 /* Packet processing. */
725 static void update_learning_table(struct ofproto_dpif *,
726                                   const struct flow *, int vlan,
727                                   struct ofbundle *);
728 /* Upcalls. */
729 #define FLOW_MISS_MAX_BATCH 50
730 static int handle_upcalls(struct dpif_backer *, unsigned int max_batch);
731
732 /* Flow expiration. */
733 static int expire(struct dpif_backer *);
734
735 /* NetFlow. */
736 static void send_netflow_active_timeouts(struct ofproto_dpif *);
737
738 /* Utilities. */
739 static int send_packet(const struct ofport_dpif *, struct ofpbuf *packet);
740 static size_t compose_sflow_action(const struct ofproto_dpif *,
741                                    struct ofpbuf *odp_actions,
742                                    const struct flow *, uint32_t odp_port);
743 static void add_mirror_actions(struct action_xlate_ctx *ctx,
744                                const struct flow *flow);
745 /* Global variables. */
746 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
747
748 /* Initial mappings of port to bridge mappings. */
749 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
750 \f
751 /* Factory functions. */
752
753 static void
754 init(const struct shash *iface_hints)
755 {
756     struct shash_node *node;
757
758     /* Make a local copy, since we don't own 'iface_hints' elements. */
759     SHASH_FOR_EACH(node, iface_hints) {
760         const struct iface_hint *orig_hint = node->data;
761         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
762
763         new_hint->br_name = xstrdup(orig_hint->br_name);
764         new_hint->br_type = xstrdup(orig_hint->br_type);
765         new_hint->ofp_port = orig_hint->ofp_port;
766
767         shash_add(&init_ofp_ports, node->name, new_hint);
768     }
769 }
770
771 static void
772 enumerate_types(struct sset *types)
773 {
774     dp_enumerate_types(types);
775 }
776
777 static int
778 enumerate_names(const char *type, struct sset *names)
779 {
780     struct ofproto_dpif *ofproto;
781
782     sset_clear(names);
783     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
784         if (strcmp(type, ofproto->up.type)) {
785             continue;
786         }
787         sset_add(names, ofproto->up.name);
788     }
789
790     return 0;
791 }
792
793 static int
794 del(const char *type, const char *name)
795 {
796     struct dpif *dpif;
797     int error;
798
799     error = dpif_open(name, type, &dpif);
800     if (!error) {
801         error = dpif_delete(dpif);
802         dpif_close(dpif);
803     }
804     return error;
805 }
806 \f
807 static const char *
808 port_open_type(const char *datapath_type, const char *port_type)
809 {
810     return dpif_port_open_type(datapath_type, port_type);
811 }
812
813 /* Type functions. */
814
815 static struct ofproto_dpif *
816 lookup_ofproto_dpif_by_port_name(const char *name)
817 {
818     struct ofproto_dpif *ofproto;
819
820     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
821         if (sset_contains(&ofproto->ports, name)) {
822             return ofproto;
823         }
824     }
825
826     return NULL;
827 }
828
829 static int
830 type_run(const char *type)
831 {
832     struct dpif_backer *backer;
833     char *devname;
834     int error;
835
836     backer = shash_find_data(&all_dpif_backers, type);
837     if (!backer) {
838         /* This is not necessarily a problem, since backers are only
839          * created on demand. */
840         return 0;
841     }
842
843     dpif_run(backer->dpif);
844
845     if (backer->need_revalidate
846         || !tag_set_is_empty(&backer->revalidate_set)) {
847         struct tag_set revalidate_set = backer->revalidate_set;
848         bool need_revalidate = backer->need_revalidate;
849         struct ofproto_dpif *ofproto;
850
851         switch (backer->need_revalidate) {
852         case REV_RECONFIGURE:   COVERAGE_INC(rev_reconfigure);   break;
853         case REV_STP:           COVERAGE_INC(rev_stp);           break;
854         case REV_PORT_TOGGLED:  COVERAGE_INC(rev_port_toggled);  break;
855         case REV_FLOW_TABLE:    COVERAGE_INC(rev_flow_table);    break;
856         case REV_INCONSISTENCY: COVERAGE_INC(rev_inconsistency); break;
857         }
858
859         if (backer->need_revalidate) {
860             /* Clear the drop_keys in case we should now be accepting some
861              * formerly dropped flows. */
862             drop_key_clear(backer);
863         }
864
865         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
866             struct facet *facet;
867
868             if (ofproto->backer != backer) {
869                 continue;
870             }
871
872             /* Clear the revalidation flags. */
873             tag_set_init(&backer->revalidate_set);
874             backer->need_revalidate = 0;
875
876             HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
877                 if (need_revalidate
878                     || tag_set_intersects(&revalidate_set, facet->tags)) {
879                     facet_revalidate(facet);
880                 }
881             }
882         }
883     }
884
885     if (timer_expired(&backer->next_expiration)) {
886         int delay = expire(backer);
887         timer_set_duration(&backer->next_expiration, delay);
888     }
889
890     /* Check for port changes in the dpif. */
891     while ((error = dpif_port_poll(backer->dpif, &devname)) == 0) {
892         struct ofproto_dpif *ofproto;
893         struct dpif_port port;
894
895         /* Don't report on the datapath's device. */
896         if (!strcmp(devname, dpif_base_name(backer->dpif))) {
897             goto next;
898         }
899
900         ofproto = lookup_ofproto_dpif_by_port_name(devname);
901         if (dpif_port_query_by_name(backer->dpif, devname, &port)) {
902             /* The port was removed.  If we know the datapath,
903              * report it through poll_set().  If we don't, it may be
904              * notifying us of a removal we initiated, so ignore it.
905              * If there's a pending ENOBUFS, let it stand, since
906              * everything will be reevaluated. */
907             if (ofproto && ofproto->port_poll_errno != ENOBUFS) {
908                 sset_add(&ofproto->port_poll_set, devname);
909                 ofproto->port_poll_errno = 0;
910             }
911         } else if (!ofproto) {
912             /* The port was added, but we don't know with which
913              * ofproto we should associate it.  Delete it. */
914             dpif_port_del(backer->dpif, port.port_no);
915         }
916         dpif_port_destroy(&port);
917
918     next:
919         free(devname);
920     }
921
922     if (error != EAGAIN) {
923         struct ofproto_dpif *ofproto;
924
925         /* There was some sort of error, so propagate it to all
926          * ofprotos that use this backer. */
927         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node,
928                        &all_ofproto_dpifs) {
929             if (ofproto->backer == backer) {
930                 sset_clear(&ofproto->port_poll_set);
931                 ofproto->port_poll_errno = error;
932             }
933         }
934     }
935
936     return 0;
937 }
938
939 static int
940 type_run_fast(const char *type)
941 {
942     struct dpif_backer *backer;
943     unsigned int work;
944
945     backer = shash_find_data(&all_dpif_backers, type);
946     if (!backer) {
947         /* This is not necessarily a problem, since backers are only
948          * created on demand. */
949         return 0;
950     }
951
952     /* Handle one or more batches of upcalls, until there's nothing left to do
953      * or until we do a fixed total amount of work.
954      *
955      * We do work in batches because it can be much cheaper to set up a number
956      * of flows and fire off their patches all at once.  We do multiple batches
957      * because in some cases handling a packet can cause another packet to be
958      * queued almost immediately as part of the return flow.  Both
959      * optimizations can make major improvements on some benchmarks and
960      * presumably for real traffic as well. */
961     work = 0;
962     while (work < FLOW_MISS_MAX_BATCH) {
963         int retval = handle_upcalls(backer, FLOW_MISS_MAX_BATCH - work);
964         if (retval <= 0) {
965             return -retval;
966         }
967         work += retval;
968     }
969
970     return 0;
971 }
972
973 static void
974 type_wait(const char *type)
975 {
976     struct dpif_backer *backer;
977
978     backer = shash_find_data(&all_dpif_backers, type);
979     if (!backer) {
980         /* This is not necessarily a problem, since backers are only
981          * created on demand. */
982         return;
983     }
984
985     timer_wait(&backer->next_expiration);
986 }
987 \f
988 /* Basic life-cycle. */
989
990 static int add_internal_flows(struct ofproto_dpif *);
991
992 static struct ofproto *
993 alloc(void)
994 {
995     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
996     return &ofproto->up;
997 }
998
999 static void
1000 dealloc(struct ofproto *ofproto_)
1001 {
1002     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1003     free(ofproto);
1004 }
1005
1006 static void
1007 close_dpif_backer(struct dpif_backer *backer)
1008 {
1009     struct shash_node *node;
1010
1011     ovs_assert(backer->refcount > 0);
1012
1013     if (--backer->refcount) {
1014         return;
1015     }
1016
1017     drop_key_clear(backer);
1018     hmap_destroy(&backer->drop_keys);
1019
1020     hmap_destroy(&backer->odp_to_ofport_map);
1021     node = shash_find(&all_dpif_backers, backer->type);
1022     free(backer->type);
1023     shash_delete(&all_dpif_backers, node);
1024     dpif_close(backer->dpif);
1025
1026     free(backer);
1027 }
1028
1029 /* Datapath port slated for removal from datapath. */
1030 struct odp_garbage {
1031     struct list list_node;
1032     uint32_t odp_port;
1033 };
1034
1035 static int
1036 open_dpif_backer(const char *type, struct dpif_backer **backerp)
1037 {
1038     struct dpif_backer *backer;
1039     struct dpif_port_dump port_dump;
1040     struct dpif_port port;
1041     struct shash_node *node;
1042     struct list garbage_list;
1043     struct odp_garbage *garbage, *next;
1044     struct sset names;
1045     char *backer_name;
1046     const char *name;
1047     int error;
1048
1049     backer = shash_find_data(&all_dpif_backers, type);
1050     if (backer) {
1051         backer->refcount++;
1052         *backerp = backer;
1053         return 0;
1054     }
1055
1056     backer_name = xasprintf("ovs-%s", type);
1057
1058     /* Remove any existing datapaths, since we assume we're the only
1059      * userspace controlling the datapath. */
1060     sset_init(&names);
1061     dp_enumerate_names(type, &names);
1062     SSET_FOR_EACH(name, &names) {
1063         struct dpif *old_dpif;
1064
1065         /* Don't remove our backer if it exists. */
1066         if (!strcmp(name, backer_name)) {
1067             continue;
1068         }
1069
1070         if (dpif_open(name, type, &old_dpif)) {
1071             VLOG_WARN("couldn't open old datapath %s to remove it", name);
1072         } else {
1073             dpif_delete(old_dpif);
1074             dpif_close(old_dpif);
1075         }
1076     }
1077     sset_destroy(&names);
1078
1079     backer = xmalloc(sizeof *backer);
1080
1081     error = dpif_create_and_open(backer_name, type, &backer->dpif);
1082     free(backer_name);
1083     if (error) {
1084         VLOG_ERR("failed to open datapath of type %s: %s", type,
1085                  strerror(error));
1086         free(backer);
1087         return error;
1088     }
1089
1090     backer->type = xstrdup(type);
1091     backer->refcount = 1;
1092     hmap_init(&backer->odp_to_ofport_map);
1093     hmap_init(&backer->drop_keys);
1094     timer_set_duration(&backer->next_expiration, 1000);
1095     backer->need_revalidate = 0;
1096     tag_set_init(&backer->revalidate_set);
1097     *backerp = backer;
1098
1099     dpif_flow_flush(backer->dpif);
1100
1101     /* Loop through the ports already on the datapath and remove any
1102      * that we don't need anymore. */
1103     list_init(&garbage_list);
1104     dpif_port_dump_start(&port_dump, backer->dpif);
1105     while (dpif_port_dump_next(&port_dump, &port)) {
1106         node = shash_find(&init_ofp_ports, port.name);
1107         if (!node && strcmp(port.name, dpif_base_name(backer->dpif))) {
1108             garbage = xmalloc(sizeof *garbage);
1109             garbage->odp_port = port.port_no;
1110             list_push_front(&garbage_list, &garbage->list_node);
1111         }
1112     }
1113     dpif_port_dump_done(&port_dump);
1114
1115     LIST_FOR_EACH_SAFE (garbage, next, list_node, &garbage_list) {
1116         dpif_port_del(backer->dpif, garbage->odp_port);
1117         list_remove(&garbage->list_node);
1118         free(garbage);
1119     }
1120
1121     shash_add(&all_dpif_backers, type, backer);
1122
1123     error = dpif_recv_set(backer->dpif, true);
1124     if (error) {
1125         VLOG_ERR("failed to listen on datapath of type %s: %s",
1126                  type, strerror(error));
1127         close_dpif_backer(backer);
1128         return error;
1129     }
1130
1131     return error;
1132 }
1133
1134 static int
1135 construct(struct ofproto *ofproto_)
1136 {
1137     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1138     struct shash_node *node, *next;
1139     int max_ports;
1140     int error;
1141     int i;
1142
1143     error = open_dpif_backer(ofproto->up.type, &ofproto->backer);
1144     if (error) {
1145         return error;
1146     }
1147
1148     max_ports = dpif_get_max_ports(ofproto->backer->dpif);
1149     ofproto_init_max_ports(ofproto_, MIN(max_ports, OFPP_MAX));
1150
1151     ofproto->n_matches = 0;
1152
1153     ofproto->netflow = NULL;
1154     ofproto->sflow = NULL;
1155     ofproto->stp = NULL;
1156     hmap_init(&ofproto->bundles);
1157     ofproto->ml = mac_learning_create(MAC_ENTRY_DEFAULT_IDLE_TIME);
1158     for (i = 0; i < MAX_MIRRORS; i++) {
1159         ofproto->mirrors[i] = NULL;
1160     }
1161     ofproto->has_bonded_bundles = false;
1162
1163     hmap_init(&ofproto->facets);
1164     hmap_init(&ofproto->subfacets);
1165     ofproto->governor = NULL;
1166
1167     for (i = 0; i < N_TABLES; i++) {
1168         struct table_dpif *table = &ofproto->tables[i];
1169
1170         table->catchall_table = NULL;
1171         table->other_table = NULL;
1172         table->basis = random_uint32();
1173     }
1174
1175     list_init(&ofproto->completions);
1176
1177     ofproto_dpif_unixctl_init();
1178
1179     ofproto->has_mirrors = false;
1180     ofproto->has_bundle_action = false;
1181
1182     hmap_init(&ofproto->vlandev_map);
1183     hmap_init(&ofproto->realdev_vid_map);
1184
1185     sset_init(&ofproto->ports);
1186     sset_init(&ofproto->ghost_ports);
1187     sset_init(&ofproto->port_poll_set);
1188     ofproto->port_poll_errno = 0;
1189
1190     SHASH_FOR_EACH_SAFE (node, next, &init_ofp_ports) {
1191         struct iface_hint *iface_hint = node->data;
1192
1193         if (!strcmp(iface_hint->br_name, ofproto->up.name)) {
1194             /* Check if the datapath already has this port. */
1195             if (dpif_port_exists(ofproto->backer->dpif, node->name)) {
1196                 sset_add(&ofproto->ports, node->name);
1197             }
1198
1199             free(iface_hint->br_name);
1200             free(iface_hint->br_type);
1201             free(iface_hint);
1202             shash_delete(&init_ofp_ports, node);
1203         }
1204     }
1205
1206     hmap_insert(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node,
1207                 hash_string(ofproto->up.name, 0));
1208     memset(&ofproto->stats, 0, sizeof ofproto->stats);
1209
1210     ofproto_init_tables(ofproto_, N_TABLES);
1211     error = add_internal_flows(ofproto);
1212     ofproto->up.tables[TBL_INTERNAL].flags = OFTABLE_HIDDEN | OFTABLE_READONLY;
1213
1214     return error;
1215 }
1216
1217 static int
1218 add_internal_flow(struct ofproto_dpif *ofproto, int id,
1219                   const struct ofpbuf *ofpacts, struct rule_dpif **rulep)
1220 {
1221     struct ofputil_flow_mod fm;
1222     int error;
1223
1224     match_init_catchall(&fm.match);
1225     fm.priority = 0;
1226     match_set_reg(&fm.match, 0, id);
1227     fm.new_cookie = htonll(0);
1228     fm.cookie = htonll(0);
1229     fm.cookie_mask = htonll(0);
1230     fm.table_id = TBL_INTERNAL;
1231     fm.command = OFPFC_ADD;
1232     fm.idle_timeout = 0;
1233     fm.hard_timeout = 0;
1234     fm.buffer_id = 0;
1235     fm.out_port = 0;
1236     fm.flags = 0;
1237     fm.ofpacts = ofpacts->data;
1238     fm.ofpacts_len = ofpacts->size;
1239
1240     error = ofproto_flow_mod(&ofproto->up, &fm);
1241     if (error) {
1242         VLOG_ERR_RL(&rl, "failed to add internal flow %d (%s)",
1243                     id, ofperr_to_string(error));
1244         return error;
1245     }
1246
1247     *rulep = rule_dpif_lookup__(ofproto, &fm.match.flow, TBL_INTERNAL);
1248     ovs_assert(*rulep != NULL);
1249
1250     return 0;
1251 }
1252
1253 static int
1254 add_internal_flows(struct ofproto_dpif *ofproto)
1255 {
1256     struct ofpact_controller *controller;
1257     uint64_t ofpacts_stub[128 / 8];
1258     struct ofpbuf ofpacts;
1259     int error;
1260     int id;
1261
1262     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
1263     id = 1;
1264
1265     controller = ofpact_put_CONTROLLER(&ofpacts);
1266     controller->max_len = UINT16_MAX;
1267     controller->controller_id = 0;
1268     controller->reason = OFPR_NO_MATCH;
1269     ofpact_pad(&ofpacts);
1270
1271     error = add_internal_flow(ofproto, id++, &ofpacts, &ofproto->miss_rule);
1272     if (error) {
1273         return error;
1274     }
1275
1276     ofpbuf_clear(&ofpacts);
1277     error = add_internal_flow(ofproto, id++, &ofpacts,
1278                               &ofproto->no_packet_in_rule);
1279     return error;
1280 }
1281
1282 static void
1283 complete_operations(struct ofproto_dpif *ofproto)
1284 {
1285     struct dpif_completion *c, *next;
1286
1287     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
1288         ofoperation_complete(c->op, 0);
1289         list_remove(&c->list_node);
1290         free(c);
1291     }
1292 }
1293
1294 static void
1295 destruct(struct ofproto *ofproto_)
1296 {
1297     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1298     struct rule_dpif *rule, *next_rule;
1299     struct oftable *table;
1300     int i;
1301
1302     hmap_remove(&all_ofproto_dpifs, &ofproto->all_ofproto_dpifs_node);
1303     complete_operations(ofproto);
1304
1305     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
1306         struct cls_cursor cursor;
1307
1308         cls_cursor_init(&cursor, &table->cls, NULL);
1309         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
1310             ofproto_rule_destroy(&rule->up);
1311         }
1312     }
1313
1314     for (i = 0; i < MAX_MIRRORS; i++) {
1315         mirror_destroy(ofproto->mirrors[i]);
1316     }
1317
1318     netflow_destroy(ofproto->netflow);
1319     dpif_sflow_destroy(ofproto->sflow);
1320     hmap_destroy(&ofproto->bundles);
1321     mac_learning_destroy(ofproto->ml);
1322
1323     hmap_destroy(&ofproto->facets);
1324     hmap_destroy(&ofproto->subfacets);
1325     governor_destroy(ofproto->governor);
1326
1327     hmap_destroy(&ofproto->vlandev_map);
1328     hmap_destroy(&ofproto->realdev_vid_map);
1329
1330     sset_destroy(&ofproto->ports);
1331     sset_destroy(&ofproto->ghost_ports);
1332     sset_destroy(&ofproto->port_poll_set);
1333
1334     close_dpif_backer(ofproto->backer);
1335 }
1336
1337 static int
1338 run_fast(struct ofproto *ofproto_)
1339 {
1340     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1341     struct ofport_dpif *ofport;
1342
1343     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1344         port_run_fast(ofport);
1345     }
1346
1347     return 0;
1348 }
1349
1350 static int
1351 run(struct ofproto *ofproto_)
1352 {
1353     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1354     struct ofport_dpif *ofport;
1355     struct ofbundle *bundle;
1356     int error;
1357
1358     if (!clogged) {
1359         complete_operations(ofproto);
1360     }
1361
1362     error = run_fast(ofproto_);
1363     if (error) {
1364         return error;
1365     }
1366
1367     if (ofproto->netflow) {
1368         if (netflow_run(ofproto->netflow)) {
1369             send_netflow_active_timeouts(ofproto);
1370         }
1371     }
1372     if (ofproto->sflow) {
1373         dpif_sflow_run(ofproto->sflow);
1374     }
1375
1376     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1377         port_run(ofport);
1378     }
1379     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1380         bundle_run(bundle);
1381     }
1382
1383     stp_run(ofproto);
1384     mac_learning_run(ofproto->ml, &ofproto->backer->revalidate_set);
1385
1386     /* Check the consistency of a random facet, to aid debugging. */
1387     if (!hmap_is_empty(&ofproto->facets)
1388         && !ofproto->backer->need_revalidate) {
1389         struct facet *facet;
1390
1391         facet = CONTAINER_OF(hmap_random_node(&ofproto->facets),
1392                              struct facet, hmap_node);
1393         if (!tag_set_intersects(&ofproto->backer->revalidate_set,
1394                                 facet->tags)) {
1395             if (!facet_check_consistency(facet)) {
1396                 ofproto->backer->need_revalidate = REV_INCONSISTENCY;
1397             }
1398         }
1399     }
1400
1401     if (ofproto->governor) {
1402         size_t n_subfacets;
1403
1404         governor_run(ofproto->governor);
1405
1406         /* If the governor has shrunk to its minimum size and the number of
1407          * subfacets has dwindled, then drop the governor entirely.
1408          *
1409          * For hysteresis, the number of subfacets to drop the governor is
1410          * smaller than the number needed to trigger its creation. */
1411         n_subfacets = hmap_count(&ofproto->subfacets);
1412         if (n_subfacets * 4 < ofproto->up.flow_eviction_threshold
1413             && governor_is_idle(ofproto->governor)) {
1414             governor_destroy(ofproto->governor);
1415             ofproto->governor = NULL;
1416         }
1417     }
1418
1419     return 0;
1420 }
1421
1422 static void
1423 wait(struct ofproto *ofproto_)
1424 {
1425     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1426     struct ofport_dpif *ofport;
1427     struct ofbundle *bundle;
1428
1429     if (!clogged && !list_is_empty(&ofproto->completions)) {
1430         poll_immediate_wake();
1431     }
1432
1433     dpif_wait(ofproto->backer->dpif);
1434     dpif_recv_wait(ofproto->backer->dpif);
1435     if (ofproto->sflow) {
1436         dpif_sflow_wait(ofproto->sflow);
1437     }
1438     if (!tag_set_is_empty(&ofproto->backer->revalidate_set)) {
1439         poll_immediate_wake();
1440     }
1441     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1442         port_wait(ofport);
1443     }
1444     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1445         bundle_wait(bundle);
1446     }
1447     if (ofproto->netflow) {
1448         netflow_wait(ofproto->netflow);
1449     }
1450     mac_learning_wait(ofproto->ml);
1451     stp_wait(ofproto);
1452     if (ofproto->backer->need_revalidate) {
1453         /* Shouldn't happen, but if it does just go around again. */
1454         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
1455         poll_immediate_wake();
1456     }
1457     if (ofproto->governor) {
1458         governor_wait(ofproto->governor);
1459     }
1460 }
1461
1462 static void
1463 get_memory_usage(const struct ofproto *ofproto_, struct simap *usage)
1464 {
1465     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1466
1467     simap_increase(usage, "facets", hmap_count(&ofproto->facets));
1468     simap_increase(usage, "subfacets", hmap_count(&ofproto->subfacets));
1469 }
1470
1471 static void
1472 flush(struct ofproto *ofproto_)
1473 {
1474     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1475     struct subfacet *subfacet, *next_subfacet;
1476     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
1477     int n_batch;
1478
1479     n_batch = 0;
1480     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
1481                         &ofproto->subfacets) {
1482         if (subfacet->path != SF_NOT_INSTALLED) {
1483             batch[n_batch++] = subfacet;
1484             if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
1485                 subfacet_destroy_batch(ofproto, batch, n_batch);
1486                 n_batch = 0;
1487             }
1488         } else {
1489             subfacet_destroy(subfacet);
1490         }
1491     }
1492
1493     if (n_batch > 0) {
1494         subfacet_destroy_batch(ofproto, batch, n_batch);
1495     }
1496 }
1497
1498 static void
1499 get_features(struct ofproto *ofproto_ OVS_UNUSED,
1500              bool *arp_match_ip, enum ofputil_action_bitmap *actions)
1501 {
1502     *arp_match_ip = true;
1503     *actions = (OFPUTIL_A_OUTPUT |
1504                 OFPUTIL_A_SET_VLAN_VID |
1505                 OFPUTIL_A_SET_VLAN_PCP |
1506                 OFPUTIL_A_STRIP_VLAN |
1507                 OFPUTIL_A_SET_DL_SRC |
1508                 OFPUTIL_A_SET_DL_DST |
1509                 OFPUTIL_A_SET_NW_SRC |
1510                 OFPUTIL_A_SET_NW_DST |
1511                 OFPUTIL_A_SET_NW_TOS |
1512                 OFPUTIL_A_SET_TP_SRC |
1513                 OFPUTIL_A_SET_TP_DST |
1514                 OFPUTIL_A_ENQUEUE);
1515 }
1516
1517 static void
1518 get_tables(struct ofproto *ofproto_, struct ofp12_table_stats *ots)
1519 {
1520     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1521     struct dpif_dp_stats s;
1522
1523     strcpy(ots->name, "classifier");
1524
1525     dpif_get_dp_stats(ofproto->backer->dpif, &s);
1526
1527     ots->lookup_count = htonll(s.n_hit + s.n_missed);
1528     ots->matched_count = htonll(s.n_hit + ofproto->n_matches);
1529 }
1530
1531 static struct ofport *
1532 port_alloc(void)
1533 {
1534     struct ofport_dpif *port = xmalloc(sizeof *port);
1535     return &port->up;
1536 }
1537
1538 static void
1539 port_dealloc(struct ofport *port_)
1540 {
1541     struct ofport_dpif *port = ofport_dpif_cast(port_);
1542     free(port);
1543 }
1544
1545 static int
1546 port_construct(struct ofport *port_)
1547 {
1548     struct ofport_dpif *port = ofport_dpif_cast(port_);
1549     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1550     struct dpif_port dpif_port;
1551     int error;
1552
1553     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1554     port->bundle = NULL;
1555     port->cfm = NULL;
1556     port->tag = tag_create_random();
1557     port->may_enable = true;
1558     port->stp_port = NULL;
1559     port->stp_state = STP_DISABLED;
1560     hmap_init(&port->priorities);
1561     port->realdev_ofp_port = 0;
1562     port->vlandev_vid = 0;
1563     port->carrier_seq = netdev_get_carrier_resets(port->up.netdev);
1564
1565     if (netdev_vport_is_patch(port->up.netdev)) {
1566         /* XXX By bailing out here, we don't do required sFlow work. */
1567         port->odp_port = OVSP_NONE;
1568         return 0;
1569     }
1570
1571     error = dpif_port_query_by_name(ofproto->backer->dpif,
1572                                     netdev_get_name(port->up.netdev),
1573                                     &dpif_port);
1574     if (error) {
1575         return error;
1576     }
1577
1578     port->odp_port = dpif_port.port_no;
1579
1580     /* Sanity-check that a mapping doesn't already exist.  This
1581      * shouldn't happen. */
1582     if (odp_port_to_ofp_port(ofproto, port->odp_port) != OFPP_NONE) {
1583         VLOG_ERR("port %s already has an OpenFlow port number\n",
1584                  dpif_port.name);
1585         return EBUSY;
1586     }
1587
1588     hmap_insert(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node,
1589                 hash_int(port->odp_port, 0));
1590
1591     if (ofproto->sflow) {
1592         dpif_sflow_add_port(ofproto->sflow, port_, port->odp_port);
1593     }
1594
1595     return 0;
1596 }
1597
1598 static void
1599 port_destruct(struct ofport *port_)
1600 {
1601     struct ofport_dpif *port = ofport_dpif_cast(port_);
1602     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1603     const char *devname = netdev_get_name(port->up.netdev);
1604
1605     if (dpif_port_exists(ofproto->backer->dpif, devname)) {
1606         /* The underlying device is still there, so delete it.  This
1607          * happens when the ofproto is being destroyed, since the caller
1608          * assumes that removal of attached ports will happen as part of
1609          * destruction. */
1610         dpif_port_del(ofproto->backer->dpif, port->odp_port);
1611     }
1612
1613     if (port->odp_port != OVSP_NONE) {
1614         hmap_remove(&ofproto->backer->odp_to_ofport_map, &port->odp_port_node);
1615     }
1616
1617     sset_find_and_delete(&ofproto->ports, devname);
1618     sset_find_and_delete(&ofproto->ghost_ports, devname);
1619     ofproto->backer->need_revalidate = REV_RECONFIGURE;
1620     bundle_remove(port_);
1621     set_cfm(port_, NULL);
1622     if (ofproto->sflow) {
1623         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
1624     }
1625
1626     ofport_clear_priorities(port);
1627     hmap_destroy(&port->priorities);
1628 }
1629
1630 static void
1631 port_modified(struct ofport *port_)
1632 {
1633     struct ofport_dpif *port = ofport_dpif_cast(port_);
1634
1635     if (port->bundle && port->bundle->bond) {
1636         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
1637     }
1638 }
1639
1640 static void
1641 port_reconfigured(struct ofport *port_, enum ofputil_port_config old_config)
1642 {
1643     struct ofport_dpif *port = ofport_dpif_cast(port_);
1644     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
1645     enum ofputil_port_config changed = old_config ^ port->up.pp.config;
1646
1647     if (changed & (OFPUTIL_PC_NO_RECV | OFPUTIL_PC_NO_RECV_STP |
1648                    OFPUTIL_PC_NO_FWD | OFPUTIL_PC_NO_FLOOD |
1649                    OFPUTIL_PC_NO_PACKET_IN)) {
1650         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1651
1652         if (changed & OFPUTIL_PC_NO_FLOOD && port->bundle) {
1653             bundle_update(port->bundle);
1654         }
1655     }
1656 }
1657
1658 static int
1659 set_sflow(struct ofproto *ofproto_,
1660           const struct ofproto_sflow_options *sflow_options)
1661 {
1662     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1663     struct dpif_sflow *ds = ofproto->sflow;
1664
1665     if (sflow_options) {
1666         if (!ds) {
1667             struct ofport_dpif *ofport;
1668
1669             ds = ofproto->sflow = dpif_sflow_create();
1670             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
1671                 dpif_sflow_add_port(ds, &ofport->up, ofport->odp_port);
1672             }
1673             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1674         }
1675         dpif_sflow_set_options(ds, sflow_options);
1676     } else {
1677         if (ds) {
1678             dpif_sflow_destroy(ds);
1679             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1680             ofproto->sflow = NULL;
1681         }
1682     }
1683     return 0;
1684 }
1685
1686 static int
1687 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
1688 {
1689     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1690     int error;
1691
1692     if (!s) {
1693         error = 0;
1694     } else {
1695         if (!ofport->cfm) {
1696             struct ofproto_dpif *ofproto;
1697
1698             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1699             ofproto->backer->need_revalidate = REV_RECONFIGURE;
1700             ofport->cfm = cfm_create(netdev_get_name(ofport->up.netdev));
1701         }
1702
1703         if (cfm_configure(ofport->cfm, s)) {
1704             return 0;
1705         }
1706
1707         error = EINVAL;
1708     }
1709     cfm_destroy(ofport->cfm);
1710     ofport->cfm = NULL;
1711     return error;
1712 }
1713
1714 static int
1715 get_cfm_fault(const struct ofport *ofport_)
1716 {
1717     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1718
1719     return ofport->cfm ? cfm_get_fault(ofport->cfm) : -1;
1720 }
1721
1722 static int
1723 get_cfm_opup(const struct ofport *ofport_)
1724 {
1725     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1726
1727     return ofport->cfm ? cfm_get_opup(ofport->cfm) : -1;
1728 }
1729
1730 static int
1731 get_cfm_remote_mpids(const struct ofport *ofport_, const uint64_t **rmps,
1732                      size_t *n_rmps)
1733 {
1734     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1735
1736     if (ofport->cfm) {
1737         cfm_get_remote_mpids(ofport->cfm, rmps, n_rmps);
1738         return 0;
1739     } else {
1740         return -1;
1741     }
1742 }
1743
1744 static int
1745 get_cfm_health(const struct ofport *ofport_)
1746 {
1747     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1748
1749     return ofport->cfm ? cfm_get_health(ofport->cfm) : -1;
1750 }
1751 \f
1752 /* Spanning Tree. */
1753
1754 static void
1755 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1756 {
1757     struct ofproto_dpif *ofproto = ofproto_;
1758     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1759     struct ofport_dpif *ofport;
1760
1761     ofport = stp_port_get_aux(sp);
1762     if (!ofport) {
1763         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1764                      ofproto->up.name, port_num);
1765     } else {
1766         struct eth_header *eth = pkt->l2;
1767
1768         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1769         if (eth_addr_is_zero(eth->eth_src)) {
1770             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1771                          "with unknown MAC", ofproto->up.name, port_num);
1772         } else {
1773             send_packet(ofport, pkt);
1774         }
1775     }
1776     ofpbuf_delete(pkt);
1777 }
1778
1779 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1780 static int
1781 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1782 {
1783     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1784
1785     /* Only revalidate flows if the configuration changed. */
1786     if (!s != !ofproto->stp) {
1787         ofproto->backer->need_revalidate = REV_RECONFIGURE;
1788     }
1789
1790     if (s) {
1791         if (!ofproto->stp) {
1792             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1793                                       send_bpdu_cb, ofproto);
1794             ofproto->stp_last_tick = time_msec();
1795         }
1796
1797         stp_set_bridge_id(ofproto->stp, s->system_id);
1798         stp_set_bridge_priority(ofproto->stp, s->priority);
1799         stp_set_hello_time(ofproto->stp, s->hello_time);
1800         stp_set_max_age(ofproto->stp, s->max_age);
1801         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1802     }  else {
1803         struct ofport *ofport;
1804
1805         HMAP_FOR_EACH (ofport, hmap_node, &ofproto->up.ports) {
1806             set_stp_port(ofport, NULL);
1807         }
1808
1809         stp_destroy(ofproto->stp);
1810         ofproto->stp = NULL;
1811     }
1812
1813     return 0;
1814 }
1815
1816 static int
1817 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1818 {
1819     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1820
1821     if (ofproto->stp) {
1822         s->enabled = true;
1823         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1824         s->designated_root = stp_get_designated_root(ofproto->stp);
1825         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1826     } else {
1827         s->enabled = false;
1828     }
1829
1830     return 0;
1831 }
1832
1833 static void
1834 update_stp_port_state(struct ofport_dpif *ofport)
1835 {
1836     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1837     enum stp_state state;
1838
1839     /* Figure out new state. */
1840     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1841                              : STP_DISABLED;
1842
1843     /* Update state. */
1844     if (ofport->stp_state != state) {
1845         enum ofputil_port_state of_state;
1846         bool fwd_change;
1847
1848         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1849                     netdev_get_name(ofport->up.netdev),
1850                     stp_state_name(ofport->stp_state),
1851                     stp_state_name(state));
1852         if (stp_learn_in_state(ofport->stp_state)
1853                 != stp_learn_in_state(state)) {
1854             /* xxx Learning action flows should also be flushed. */
1855             mac_learning_flush(ofproto->ml,
1856                                &ofproto->backer->revalidate_set);
1857         }
1858         fwd_change = stp_forward_in_state(ofport->stp_state)
1859                         != stp_forward_in_state(state);
1860
1861         ofproto->backer->need_revalidate = REV_STP;
1862         ofport->stp_state = state;
1863         ofport->stp_state_entered = time_msec();
1864
1865         if (fwd_change && ofport->bundle) {
1866             bundle_update(ofport->bundle);
1867         }
1868
1869         /* Update the STP state bits in the OpenFlow port description. */
1870         of_state = ofport->up.pp.state & ~OFPUTIL_PS_STP_MASK;
1871         of_state |= (state == STP_LISTENING ? OFPUTIL_PS_STP_LISTEN
1872                      : state == STP_LEARNING ? OFPUTIL_PS_STP_LEARN
1873                      : state == STP_FORWARDING ? OFPUTIL_PS_STP_FORWARD
1874                      : state == STP_BLOCKING ?  OFPUTIL_PS_STP_BLOCK
1875                      : 0);
1876         ofproto_port_set_state(&ofport->up, of_state);
1877     }
1878 }
1879
1880 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1881  * caller is responsible for assigning STP port numbers and ensuring
1882  * there are no duplicates. */
1883 static int
1884 set_stp_port(struct ofport *ofport_,
1885              const struct ofproto_port_stp_settings *s)
1886 {
1887     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1888     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1889     struct stp_port *sp = ofport->stp_port;
1890
1891     if (!s || !s->enable) {
1892         if (sp) {
1893             ofport->stp_port = NULL;
1894             stp_port_disable(sp);
1895             update_stp_port_state(ofport);
1896         }
1897         return 0;
1898     } else if (sp && stp_port_no(sp) != s->port_num
1899             && ofport == stp_port_get_aux(sp)) {
1900         /* The port-id changed, so disable the old one if it's not
1901          * already in use by another port. */
1902         stp_port_disable(sp);
1903     }
1904
1905     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1906     stp_port_enable(sp);
1907
1908     stp_port_set_aux(sp, ofport);
1909     stp_port_set_priority(sp, s->priority);
1910     stp_port_set_path_cost(sp, s->path_cost);
1911
1912     update_stp_port_state(ofport);
1913
1914     return 0;
1915 }
1916
1917 static int
1918 get_stp_port_status(struct ofport *ofport_,
1919                     struct ofproto_port_stp_status *s)
1920 {
1921     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1922     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1923     struct stp_port *sp = ofport->stp_port;
1924
1925     if (!ofproto->stp || !sp) {
1926         s->enabled = false;
1927         return 0;
1928     }
1929
1930     s->enabled = true;
1931     s->port_id = stp_port_get_id(sp);
1932     s->state = stp_port_get_state(sp);
1933     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1934     s->role = stp_port_get_role(sp);
1935     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1936
1937     return 0;
1938 }
1939
1940 static void
1941 stp_run(struct ofproto_dpif *ofproto)
1942 {
1943     if (ofproto->stp) {
1944         long long int now = time_msec();
1945         long long int elapsed = now - ofproto->stp_last_tick;
1946         struct stp_port *sp;
1947
1948         if (elapsed > 0) {
1949             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1950             ofproto->stp_last_tick = now;
1951         }
1952         while (stp_get_changed_port(ofproto->stp, &sp)) {
1953             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1954
1955             if (ofport) {
1956                 update_stp_port_state(ofport);
1957             }
1958         }
1959
1960         if (stp_check_and_reset_fdb_flush(ofproto->stp)) {
1961             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
1962         }
1963     }
1964 }
1965
1966 static void
1967 stp_wait(struct ofproto_dpif *ofproto)
1968 {
1969     if (ofproto->stp) {
1970         poll_timer_wait(1000);
1971     }
1972 }
1973
1974 /* Returns true if STP should process 'flow'. */
1975 static bool
1976 stp_should_process_flow(const struct flow *flow)
1977 {
1978     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
1979 }
1980
1981 static void
1982 stp_process_packet(const struct ofport_dpif *ofport,
1983                    const struct ofpbuf *packet)
1984 {
1985     struct ofpbuf payload = *packet;
1986     struct eth_header *eth = payload.data;
1987     struct stp_port *sp = ofport->stp_port;
1988
1989     /* Sink packets on ports that have STP disabled when the bridge has
1990      * STP enabled. */
1991     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1992         return;
1993     }
1994
1995     /* Trim off padding on payload. */
1996     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1997         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1998     }
1999
2000     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
2001         stp_received_bpdu(sp, payload.data, payload.size);
2002     }
2003 }
2004 \f
2005 static struct priority_to_dscp *
2006 get_priority(const struct ofport_dpif *ofport, uint32_t priority)
2007 {
2008     struct priority_to_dscp *pdscp;
2009     uint32_t hash;
2010
2011     hash = hash_int(priority, 0);
2012     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &ofport->priorities) {
2013         if (pdscp->priority == priority) {
2014             return pdscp;
2015         }
2016     }
2017     return NULL;
2018 }
2019
2020 static void
2021 ofport_clear_priorities(struct ofport_dpif *ofport)
2022 {
2023     struct priority_to_dscp *pdscp, *next;
2024
2025     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &ofport->priorities) {
2026         hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2027         free(pdscp);
2028     }
2029 }
2030
2031 static int
2032 set_queues(struct ofport *ofport_,
2033            const struct ofproto_port_queue *qdscp_list,
2034            size_t n_qdscp)
2035 {
2036     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2037     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2038     struct hmap new = HMAP_INITIALIZER(&new);
2039     size_t i;
2040
2041     for (i = 0; i < n_qdscp; i++) {
2042         struct priority_to_dscp *pdscp;
2043         uint32_t priority;
2044         uint8_t dscp;
2045
2046         dscp = (qdscp_list[i].dscp << 2) & IP_DSCP_MASK;
2047         if (dpif_queue_to_priority(ofproto->backer->dpif, qdscp_list[i].queue,
2048                                    &priority)) {
2049             continue;
2050         }
2051
2052         pdscp = get_priority(ofport, priority);
2053         if (pdscp) {
2054             hmap_remove(&ofport->priorities, &pdscp->hmap_node);
2055         } else {
2056             pdscp = xmalloc(sizeof *pdscp);
2057             pdscp->priority = priority;
2058             pdscp->dscp = dscp;
2059             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2060         }
2061
2062         if (pdscp->dscp != dscp) {
2063             pdscp->dscp = dscp;
2064             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2065         }
2066
2067         hmap_insert(&new, &pdscp->hmap_node, hash_int(pdscp->priority, 0));
2068     }
2069
2070     if (!hmap_is_empty(&ofport->priorities)) {
2071         ofport_clear_priorities(ofport);
2072         ofproto->backer->need_revalidate = REV_RECONFIGURE;
2073     }
2074
2075     hmap_swap(&new, &ofport->priorities);
2076     hmap_destroy(&new);
2077
2078     return 0;
2079 }
2080 \f
2081 /* Bundles. */
2082
2083 /* Expires all MAC learning entries associated with 'bundle' and forces its
2084  * ofproto to revalidate every flow.
2085  *
2086  * Normally MAC learning entries are removed only from the ofproto associated
2087  * with 'bundle', but if 'all_ofprotos' is true, then the MAC learning entries
2088  * are removed from every ofproto.  When patch ports and SLB bonds are in use
2089  * and a VM migration happens and the gratuitous ARPs are somehow lost, this
2090  * avoids a MAC_ENTRY_IDLE_TIME delay before the migrated VM can communicate
2091  * with the host from which it migrated. */
2092 static void
2093 bundle_flush_macs(struct ofbundle *bundle, bool all_ofprotos)
2094 {
2095     struct ofproto_dpif *ofproto = bundle->ofproto;
2096     struct mac_learning *ml = ofproto->ml;
2097     struct mac_entry *mac, *next_mac;
2098
2099     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2100     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
2101         if (mac->port.p == bundle) {
2102             if (all_ofprotos) {
2103                 struct ofproto_dpif *o;
2104
2105                 HMAP_FOR_EACH (o, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2106                     if (o != ofproto) {
2107                         struct mac_entry *e;
2108
2109                         e = mac_learning_lookup(o->ml, mac->mac, mac->vlan,
2110                                                 NULL);
2111                         if (e) {
2112                             mac_learning_expire(o->ml, e);
2113                         }
2114                     }
2115                 }
2116             }
2117
2118             mac_learning_expire(ml, mac);
2119         }
2120     }
2121 }
2122
2123 static struct ofbundle *
2124 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
2125 {
2126     struct ofbundle *bundle;
2127
2128     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
2129                              &ofproto->bundles) {
2130         if (bundle->aux == aux) {
2131             return bundle;
2132         }
2133     }
2134     return NULL;
2135 }
2136
2137 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
2138  * ones that are found to 'bundles'. */
2139 static void
2140 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
2141                        void **auxes, size_t n_auxes,
2142                        struct hmapx *bundles)
2143 {
2144     size_t i;
2145
2146     hmapx_init(bundles);
2147     for (i = 0; i < n_auxes; i++) {
2148         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
2149         if (bundle) {
2150             hmapx_add(bundles, bundle);
2151         }
2152     }
2153 }
2154
2155 static void
2156 bundle_update(struct ofbundle *bundle)
2157 {
2158     struct ofport_dpif *port;
2159
2160     bundle->floodable = true;
2161     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2162         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2163             || !stp_forward_in_state(port->stp_state)) {
2164             bundle->floodable = false;
2165             break;
2166         }
2167     }
2168 }
2169
2170 static void
2171 bundle_del_port(struct ofport_dpif *port)
2172 {
2173     struct ofbundle *bundle = port->bundle;
2174
2175     bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2176
2177     list_remove(&port->bundle_node);
2178     port->bundle = NULL;
2179
2180     if (bundle->lacp) {
2181         lacp_slave_unregister(bundle->lacp, port);
2182     }
2183     if (bundle->bond) {
2184         bond_slave_unregister(bundle->bond, port);
2185     }
2186
2187     bundle_update(bundle);
2188 }
2189
2190 static bool
2191 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
2192                 struct lacp_slave_settings *lacp,
2193                 uint32_t bond_stable_id)
2194 {
2195     struct ofport_dpif *port;
2196
2197     port = get_ofp_port(bundle->ofproto, ofp_port);
2198     if (!port) {
2199         return false;
2200     }
2201
2202     if (port->bundle != bundle) {
2203         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2204         if (port->bundle) {
2205             bundle_del_port(port);
2206         }
2207
2208         port->bundle = bundle;
2209         list_push_back(&bundle->ports, &port->bundle_node);
2210         if (port->up.pp.config & OFPUTIL_PC_NO_FLOOD
2211             || !stp_forward_in_state(port->stp_state)) {
2212             bundle->floodable = false;
2213         }
2214     }
2215     if (lacp) {
2216         bundle->ofproto->backer->need_revalidate = REV_RECONFIGURE;
2217         lacp_slave_register(bundle->lacp, port, lacp);
2218     }
2219
2220     port->bond_stable_id = bond_stable_id;
2221
2222     return true;
2223 }
2224
2225 static void
2226 bundle_destroy(struct ofbundle *bundle)
2227 {
2228     struct ofproto_dpif *ofproto;
2229     struct ofport_dpif *port, *next_port;
2230     int i;
2231
2232     if (!bundle) {
2233         return;
2234     }
2235
2236     ofproto = bundle->ofproto;
2237     for (i = 0; i < MAX_MIRRORS; i++) {
2238         struct ofmirror *m = ofproto->mirrors[i];
2239         if (m) {
2240             if (m->out == bundle) {
2241                 mirror_destroy(m);
2242             } else if (hmapx_find_and_delete(&m->srcs, bundle)
2243                        || hmapx_find_and_delete(&m->dsts, bundle)) {
2244                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2245             }
2246         }
2247     }
2248
2249     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2250         bundle_del_port(port);
2251     }
2252
2253     bundle_flush_macs(bundle, true);
2254     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
2255     free(bundle->name);
2256     free(bundle->trunks);
2257     lacp_destroy(bundle->lacp);
2258     bond_destroy(bundle->bond);
2259     free(bundle);
2260 }
2261
2262 static int
2263 bundle_set(struct ofproto *ofproto_, void *aux,
2264            const struct ofproto_bundle_settings *s)
2265 {
2266     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2267     bool need_flush = false;
2268     struct ofport_dpif *port;
2269     struct ofbundle *bundle;
2270     unsigned long *trunks;
2271     int vlan;
2272     size_t i;
2273     bool ok;
2274
2275     if (!s) {
2276         bundle_destroy(bundle_lookup(ofproto, aux));
2277         return 0;
2278     }
2279
2280     ovs_assert(s->n_slaves == 1 || s->bond != NULL);
2281     ovs_assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
2282
2283     bundle = bundle_lookup(ofproto, aux);
2284     if (!bundle) {
2285         bundle = xmalloc(sizeof *bundle);
2286
2287         bundle->ofproto = ofproto;
2288         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
2289                     hash_pointer(aux, 0));
2290         bundle->aux = aux;
2291         bundle->name = NULL;
2292
2293         list_init(&bundle->ports);
2294         bundle->vlan_mode = PORT_VLAN_TRUNK;
2295         bundle->vlan = -1;
2296         bundle->trunks = NULL;
2297         bundle->use_priority_tags = s->use_priority_tags;
2298         bundle->lacp = NULL;
2299         bundle->bond = NULL;
2300
2301         bundle->floodable = true;
2302
2303         bundle->src_mirrors = 0;
2304         bundle->dst_mirrors = 0;
2305         bundle->mirror_out = 0;
2306     }
2307
2308     if (!bundle->name || strcmp(s->name, bundle->name)) {
2309         free(bundle->name);
2310         bundle->name = xstrdup(s->name);
2311     }
2312
2313     /* LACP. */
2314     if (s->lacp) {
2315         if (!bundle->lacp) {
2316             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2317             bundle->lacp = lacp_create();
2318         }
2319         lacp_configure(bundle->lacp, s->lacp);
2320     } else {
2321         lacp_destroy(bundle->lacp);
2322         bundle->lacp = NULL;
2323     }
2324
2325     /* Update set of ports. */
2326     ok = true;
2327     for (i = 0; i < s->n_slaves; i++) {
2328         if (!bundle_add_port(bundle, s->slaves[i],
2329                              s->lacp ? &s->lacp_slaves[i] : NULL,
2330                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
2331             ok = false;
2332         }
2333     }
2334     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
2335         struct ofport_dpif *next_port;
2336
2337         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
2338             for (i = 0; i < s->n_slaves; i++) {
2339                 if (s->slaves[i] == port->up.ofp_port) {
2340                     goto found;
2341                 }
2342             }
2343
2344             bundle_del_port(port);
2345         found: ;
2346         }
2347     }
2348     ovs_assert(list_size(&bundle->ports) <= s->n_slaves);
2349
2350     if (list_is_empty(&bundle->ports)) {
2351         bundle_destroy(bundle);
2352         return EINVAL;
2353     }
2354
2355     /* Set VLAN tagging mode */
2356     if (s->vlan_mode != bundle->vlan_mode
2357         || s->use_priority_tags != bundle->use_priority_tags) {
2358         bundle->vlan_mode = s->vlan_mode;
2359         bundle->use_priority_tags = s->use_priority_tags;
2360         need_flush = true;
2361     }
2362
2363     /* Set VLAN tag. */
2364     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
2365             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
2366             : 0);
2367     if (vlan != bundle->vlan) {
2368         bundle->vlan = vlan;
2369         need_flush = true;
2370     }
2371
2372     /* Get trunked VLANs. */
2373     switch (s->vlan_mode) {
2374     case PORT_VLAN_ACCESS:
2375         trunks = NULL;
2376         break;
2377
2378     case PORT_VLAN_TRUNK:
2379         trunks = CONST_CAST(unsigned long *, s->trunks);
2380         break;
2381
2382     case PORT_VLAN_NATIVE_UNTAGGED:
2383     case PORT_VLAN_NATIVE_TAGGED:
2384         if (vlan != 0 && (!s->trunks
2385                           || !bitmap_is_set(s->trunks, vlan)
2386                           || bitmap_is_set(s->trunks, 0))) {
2387             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
2388             if (s->trunks) {
2389                 trunks = bitmap_clone(s->trunks, 4096);
2390             } else {
2391                 trunks = bitmap_allocate1(4096);
2392             }
2393             bitmap_set1(trunks, vlan);
2394             bitmap_set0(trunks, 0);
2395         } else {
2396             trunks = CONST_CAST(unsigned long *, s->trunks);
2397         }
2398         break;
2399
2400     default:
2401         NOT_REACHED();
2402     }
2403     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
2404         free(bundle->trunks);
2405         if (trunks == s->trunks) {
2406             bundle->trunks = vlan_bitmap_clone(trunks);
2407         } else {
2408             bundle->trunks = trunks;
2409             trunks = NULL;
2410         }
2411         need_flush = true;
2412     }
2413     if (trunks != s->trunks) {
2414         free(trunks);
2415     }
2416
2417     /* Bonding. */
2418     if (!list_is_short(&bundle->ports)) {
2419         bundle->ofproto->has_bonded_bundles = true;
2420         if (bundle->bond) {
2421             if (bond_reconfigure(bundle->bond, s->bond)) {
2422                 ofproto->backer->need_revalidate = REV_RECONFIGURE;
2423             }
2424         } else {
2425             bundle->bond = bond_create(s->bond);
2426             ofproto->backer->need_revalidate = REV_RECONFIGURE;
2427         }
2428
2429         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2430             bond_slave_register(bundle->bond, port, port->bond_stable_id,
2431                                 port->up.netdev);
2432         }
2433     } else {
2434         bond_destroy(bundle->bond);
2435         bundle->bond = NULL;
2436     }
2437
2438     /* If we changed something that would affect MAC learning, un-learn
2439      * everything on this port and force flow revalidation. */
2440     if (need_flush) {
2441         bundle_flush_macs(bundle, false);
2442     }
2443
2444     return 0;
2445 }
2446
2447 static void
2448 bundle_remove(struct ofport *port_)
2449 {
2450     struct ofport_dpif *port = ofport_dpif_cast(port_);
2451     struct ofbundle *bundle = port->bundle;
2452
2453     if (bundle) {
2454         bundle_del_port(port);
2455         if (list_is_empty(&bundle->ports)) {
2456             bundle_destroy(bundle);
2457         } else if (list_is_short(&bundle->ports)) {
2458             bond_destroy(bundle->bond);
2459             bundle->bond = NULL;
2460         }
2461     }
2462 }
2463
2464 static void
2465 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
2466 {
2467     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
2468     struct ofport_dpif *port = port_;
2469     uint8_t ea[ETH_ADDR_LEN];
2470     int error;
2471
2472     error = netdev_get_etheraddr(port->up.netdev, ea);
2473     if (!error) {
2474         struct ofpbuf packet;
2475         void *packet_pdu;
2476
2477         ofpbuf_init(&packet, 0);
2478         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
2479                                  pdu_size);
2480         memcpy(packet_pdu, pdu, pdu_size);
2481
2482         send_packet(port, &packet);
2483         ofpbuf_uninit(&packet);
2484     } else {
2485         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
2486                     "%s (%s)", port->bundle->name,
2487                     netdev_get_name(port->up.netdev), strerror(error));
2488     }
2489 }
2490
2491 static void
2492 bundle_send_learning_packets(struct ofbundle *bundle)
2493 {
2494     struct ofproto_dpif *ofproto = bundle->ofproto;
2495     int error, n_packets, n_errors;
2496     struct mac_entry *e;
2497
2498     error = n_packets = n_errors = 0;
2499     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
2500         if (e->port.p != bundle) {
2501             struct ofpbuf *learning_packet;
2502             struct ofport_dpif *port;
2503             void *port_void;
2504             int ret;
2505
2506             /* The assignment to "port" is unnecessary but makes "grep"ing for
2507              * struct ofport_dpif more effective. */
2508             learning_packet = bond_compose_learning_packet(bundle->bond,
2509                                                            e->mac, e->vlan,
2510                                                            &port_void);
2511             port = port_void;
2512             ret = send_packet(port, learning_packet);
2513             ofpbuf_delete(learning_packet);
2514             if (ret) {
2515                 error = ret;
2516                 n_errors++;
2517             }
2518             n_packets++;
2519         }
2520     }
2521
2522     if (n_errors) {
2523         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
2524         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
2525                      "packets, last error was: %s",
2526                      bundle->name, n_errors, n_packets, strerror(error));
2527     } else {
2528         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
2529                  bundle->name, n_packets);
2530     }
2531 }
2532
2533 static void
2534 bundle_run(struct ofbundle *bundle)
2535 {
2536     if (bundle->lacp) {
2537         lacp_run(bundle->lacp, send_pdu_cb);
2538     }
2539     if (bundle->bond) {
2540         struct ofport_dpif *port;
2541
2542         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
2543             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
2544         }
2545
2546         bond_run(bundle->bond, &bundle->ofproto->backer->revalidate_set,
2547                  lacp_status(bundle->lacp));
2548         if (bond_should_send_learning_packets(bundle->bond)) {
2549             bundle_send_learning_packets(bundle);
2550         }
2551     }
2552 }
2553
2554 static void
2555 bundle_wait(struct ofbundle *bundle)
2556 {
2557     if (bundle->lacp) {
2558         lacp_wait(bundle->lacp);
2559     }
2560     if (bundle->bond) {
2561         bond_wait(bundle->bond);
2562     }
2563 }
2564 \f
2565 /* Mirrors. */
2566
2567 static int
2568 mirror_scan(struct ofproto_dpif *ofproto)
2569 {
2570     int idx;
2571
2572     for (idx = 0; idx < MAX_MIRRORS; idx++) {
2573         if (!ofproto->mirrors[idx]) {
2574             return idx;
2575         }
2576     }
2577     return -1;
2578 }
2579
2580 static struct ofmirror *
2581 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
2582 {
2583     int i;
2584
2585     for (i = 0; i < MAX_MIRRORS; i++) {
2586         struct ofmirror *mirror = ofproto->mirrors[i];
2587         if (mirror && mirror->aux == aux) {
2588             return mirror;
2589         }
2590     }
2591
2592     return NULL;
2593 }
2594
2595 /* Update the 'dup_mirrors' member of each of the ofmirrors in 'ofproto'. */
2596 static void
2597 mirror_update_dups(struct ofproto_dpif *ofproto)
2598 {
2599     int i;
2600
2601     for (i = 0; i < MAX_MIRRORS; i++) {
2602         struct ofmirror *m = ofproto->mirrors[i];
2603
2604         if (m) {
2605             m->dup_mirrors = MIRROR_MASK_C(1) << i;
2606         }
2607     }
2608
2609     for (i = 0; i < MAX_MIRRORS; i++) {
2610         struct ofmirror *m1 = ofproto->mirrors[i];
2611         int j;
2612
2613         if (!m1) {
2614             continue;
2615         }
2616
2617         for (j = i + 1; j < MAX_MIRRORS; j++) {
2618             struct ofmirror *m2 = ofproto->mirrors[j];
2619
2620             if (m2 && m1->out == m2->out && m1->out_vlan == m2->out_vlan) {
2621                 m1->dup_mirrors |= MIRROR_MASK_C(1) << j;
2622                 m2->dup_mirrors |= m1->dup_mirrors;
2623             }
2624         }
2625     }
2626 }
2627
2628 static int
2629 mirror_set(struct ofproto *ofproto_, void *aux,
2630            const struct ofproto_mirror_settings *s)
2631 {
2632     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2633     mirror_mask_t mirror_bit;
2634     struct ofbundle *bundle;
2635     struct ofmirror *mirror;
2636     struct ofbundle *out;
2637     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
2638     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
2639     int out_vlan;
2640
2641     mirror = mirror_lookup(ofproto, aux);
2642     if (!s) {
2643         mirror_destroy(mirror);
2644         return 0;
2645     }
2646     if (!mirror) {
2647         int idx;
2648
2649         idx = mirror_scan(ofproto);
2650         if (idx < 0) {
2651             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
2652                       "cannot create %s",
2653                       ofproto->up.name, MAX_MIRRORS, s->name);
2654             return EFBIG;
2655         }
2656
2657         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
2658         mirror->ofproto = ofproto;
2659         mirror->idx = idx;
2660         mirror->aux = aux;
2661         mirror->out_vlan = -1;
2662         mirror->name = NULL;
2663     }
2664
2665     if (!mirror->name || strcmp(s->name, mirror->name)) {
2666         free(mirror->name);
2667         mirror->name = xstrdup(s->name);
2668     }
2669
2670     /* Get the new configuration. */
2671     if (s->out_bundle) {
2672         out = bundle_lookup(ofproto, s->out_bundle);
2673         if (!out) {
2674             mirror_destroy(mirror);
2675             return EINVAL;
2676         }
2677         out_vlan = -1;
2678     } else {
2679         out = NULL;
2680         out_vlan = s->out_vlan;
2681     }
2682     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
2683     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
2684
2685     /* If the configuration has not changed, do nothing. */
2686     if (hmapx_equals(&srcs, &mirror->srcs)
2687         && hmapx_equals(&dsts, &mirror->dsts)
2688         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
2689         && mirror->out == out
2690         && mirror->out_vlan == out_vlan)
2691     {
2692         hmapx_destroy(&srcs);
2693         hmapx_destroy(&dsts);
2694         return 0;
2695     }
2696
2697     hmapx_swap(&srcs, &mirror->srcs);
2698     hmapx_destroy(&srcs);
2699
2700     hmapx_swap(&dsts, &mirror->dsts);
2701     hmapx_destroy(&dsts);
2702
2703     free(mirror->vlans);
2704     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
2705
2706     mirror->out = out;
2707     mirror->out_vlan = out_vlan;
2708
2709     /* Update bundles. */
2710     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2711     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
2712         if (hmapx_contains(&mirror->srcs, bundle)) {
2713             bundle->src_mirrors |= mirror_bit;
2714         } else {
2715             bundle->src_mirrors &= ~mirror_bit;
2716         }
2717
2718         if (hmapx_contains(&mirror->dsts, bundle)) {
2719             bundle->dst_mirrors |= mirror_bit;
2720         } else {
2721             bundle->dst_mirrors &= ~mirror_bit;
2722         }
2723
2724         if (mirror->out == bundle) {
2725             bundle->mirror_out |= mirror_bit;
2726         } else {
2727             bundle->mirror_out &= ~mirror_bit;
2728         }
2729     }
2730
2731     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2732     ofproto->has_mirrors = true;
2733     mac_learning_flush(ofproto->ml,
2734                        &ofproto->backer->revalidate_set);
2735     mirror_update_dups(ofproto);
2736
2737     return 0;
2738 }
2739
2740 static void
2741 mirror_destroy(struct ofmirror *mirror)
2742 {
2743     struct ofproto_dpif *ofproto;
2744     mirror_mask_t mirror_bit;
2745     struct ofbundle *bundle;
2746     int i;
2747
2748     if (!mirror) {
2749         return;
2750     }
2751
2752     ofproto = mirror->ofproto;
2753     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2754     mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2755
2756     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
2757     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2758         bundle->src_mirrors &= ~mirror_bit;
2759         bundle->dst_mirrors &= ~mirror_bit;
2760         bundle->mirror_out &= ~mirror_bit;
2761     }
2762
2763     hmapx_destroy(&mirror->srcs);
2764     hmapx_destroy(&mirror->dsts);
2765     free(mirror->vlans);
2766
2767     ofproto->mirrors[mirror->idx] = NULL;
2768     free(mirror->name);
2769     free(mirror);
2770
2771     mirror_update_dups(ofproto);
2772
2773     ofproto->has_mirrors = false;
2774     for (i = 0; i < MAX_MIRRORS; i++) {
2775         if (ofproto->mirrors[i]) {
2776             ofproto->has_mirrors = true;
2777             break;
2778         }
2779     }
2780 }
2781
2782 static int
2783 mirror_get_stats(struct ofproto *ofproto_, void *aux,
2784                  uint64_t *packets, uint64_t *bytes)
2785 {
2786     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2787     struct ofmirror *mirror = mirror_lookup(ofproto, aux);
2788
2789     if (!mirror) {
2790         *packets = *bytes = UINT64_MAX;
2791         return 0;
2792     }
2793
2794     *packets = mirror->packet_count;
2795     *bytes = mirror->byte_count;
2796
2797     return 0;
2798 }
2799
2800 static int
2801 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
2802 {
2803     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2804     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
2805         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
2806     }
2807     return 0;
2808 }
2809
2810 static bool
2811 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
2812 {
2813     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2814     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
2815     return bundle && bundle->mirror_out != 0;
2816 }
2817
2818 static void
2819 forward_bpdu_changed(struct ofproto *ofproto_)
2820 {
2821     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2822     ofproto->backer->need_revalidate = REV_RECONFIGURE;
2823 }
2824
2825 static void
2826 set_mac_table_config(struct ofproto *ofproto_, unsigned int idle_time,
2827                      size_t max_entries)
2828 {
2829     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2830     mac_learning_set_idle_time(ofproto->ml, idle_time);
2831     mac_learning_set_max_entries(ofproto->ml, max_entries);
2832 }
2833 \f
2834 /* Ports. */
2835
2836 static struct ofport_dpif *
2837 get_ofp_port(const struct ofproto_dpif *ofproto, uint16_t ofp_port)
2838 {
2839     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2840     return ofport ? ofport_dpif_cast(ofport) : NULL;
2841 }
2842
2843 static struct ofport_dpif *
2844 get_odp_port(const struct ofproto_dpif *ofproto, uint32_t odp_port)
2845 {
2846     struct ofport_dpif *port = odp_port_to_ofport(ofproto->backer, odp_port);
2847     return port && &ofproto->up == port->up.ofproto ? port : NULL;
2848 }
2849
2850 static void
2851 ofproto_port_from_dpif_port(struct ofproto_dpif *ofproto,
2852                             struct ofproto_port *ofproto_port,
2853                             struct dpif_port *dpif_port)
2854 {
2855     ofproto_port->name = dpif_port->name;
2856     ofproto_port->type = dpif_port->type;
2857     ofproto_port->ofp_port = odp_port_to_ofp_port(ofproto, dpif_port->port_no);
2858 }
2859
2860 static struct ofport_dpif *
2861 ofport_get_peer(const struct ofport_dpif *ofport_dpif)
2862 {
2863     const struct ofproto_dpif *ofproto;
2864     const char *peer;
2865
2866     peer = netdev_vport_patch_peer(ofport_dpif->up.netdev);
2867     if (!peer) {
2868         return NULL;
2869     }
2870
2871     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
2872         struct ofport *ofport;
2873
2874         ofport = shash_find_data(&ofproto->up.port_by_name, peer);
2875         if (ofport && ofport->ofproto->ofproto_class == &ofproto_dpif_class) {
2876             return ofport_dpif_cast(ofport);
2877         }
2878     }
2879     return NULL;
2880 }
2881
2882 static void
2883 port_run_fast(struct ofport_dpif *ofport)
2884 {
2885     if (ofport->cfm && cfm_should_send_ccm(ofport->cfm)) {
2886         struct ofpbuf packet;
2887
2888         ofpbuf_init(&packet, 0);
2889         cfm_compose_ccm(ofport->cfm, &packet, ofport->up.pp.hw_addr);
2890         send_packet(ofport, &packet);
2891         ofpbuf_uninit(&packet);
2892     }
2893 }
2894
2895 static void
2896 port_run(struct ofport_dpif *ofport)
2897 {
2898     long long int carrier_seq = netdev_get_carrier_resets(ofport->up.netdev);
2899     bool carrier_changed = carrier_seq != ofport->carrier_seq;
2900     bool enable = netdev_get_carrier(ofport->up.netdev);
2901
2902     ofport->carrier_seq = carrier_seq;
2903
2904     port_run_fast(ofport);
2905     if (ofport->cfm) {
2906         int cfm_opup = cfm_get_opup(ofport->cfm);
2907
2908         cfm_run(ofport->cfm);
2909         enable = enable && !cfm_get_fault(ofport->cfm);
2910
2911         if (cfm_opup >= 0) {
2912             enable = enable && cfm_opup;
2913         }
2914     }
2915
2916     if (ofport->bundle) {
2917         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2918         if (carrier_changed) {
2919             lacp_slave_carrier_changed(ofport->bundle->lacp, ofport);
2920         }
2921     }
2922
2923     if (ofport->may_enable != enable) {
2924         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2925
2926         if (ofproto->has_bundle_action) {
2927             ofproto->backer->need_revalidate = REV_PORT_TOGGLED;
2928         }
2929     }
2930
2931     ofport->may_enable = enable;
2932 }
2933
2934 static void
2935 port_wait(struct ofport_dpif *ofport)
2936 {
2937     if (ofport->cfm) {
2938         cfm_wait(ofport->cfm);
2939     }
2940 }
2941
2942 static int
2943 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
2944                    struct ofproto_port *ofproto_port)
2945 {
2946     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2947     struct dpif_port dpif_port;
2948     int error;
2949
2950     if (sset_contains(&ofproto->ghost_ports, devname)) {
2951         const char *type = netdev_get_type_from_name(devname);
2952
2953         /* We may be called before ofproto->up.port_by_name is populated with
2954          * the appropriate ofport.  For this reason, we must get the name and
2955          * type from the netdev layer directly. */
2956         if (type) {
2957             const struct ofport *ofport;
2958
2959             ofport = shash_find_data(&ofproto->up.port_by_name, devname);
2960             ofproto_port->ofp_port = ofport ? ofport->ofp_port : OFPP_NONE;
2961             ofproto_port->name = xstrdup(devname);
2962             ofproto_port->type = xstrdup(type);
2963             return 0;
2964         }
2965         return ENODEV;
2966     }
2967
2968     if (!sset_contains(&ofproto->ports, devname)) {
2969         return ENODEV;
2970     }
2971     error = dpif_port_query_by_name(ofproto->backer->dpif,
2972                                     devname, &dpif_port);
2973     if (!error) {
2974         ofproto_port_from_dpif_port(ofproto, ofproto_port, &dpif_port);
2975     }
2976     return error;
2977 }
2978
2979 static int
2980 port_add(struct ofproto *ofproto_, struct netdev *netdev)
2981 {
2982     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2983     uint32_t odp_port = UINT32_MAX;
2984     int error;
2985
2986     if (netdev_vport_is_patch(netdev)) {
2987         sset_add(&ofproto->ghost_ports, netdev_get_name(netdev));
2988         return 0;
2989     }
2990
2991     error = dpif_port_add(ofproto->backer->dpif, netdev, &odp_port);
2992     if (!error) {
2993         sset_add(&ofproto->ports, netdev_get_name(netdev));
2994     }
2995     return error;
2996 }
2997
2998 static int
2999 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
3000 {
3001     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3002     uint32_t odp_port = ofp_port_to_odp_port(ofproto, ofp_port);
3003     int error = 0;
3004
3005     if (odp_port != OFPP_NONE) {
3006         error = dpif_port_del(ofproto->backer->dpif, odp_port);
3007     }
3008     if (!error) {
3009         struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
3010         if (ofport) {
3011             /* The caller is going to close ofport->up.netdev.  If this is a
3012              * bonded port, then the bond is using that netdev, so remove it
3013              * from the bond.  The client will need to reconfigure everything
3014              * after deleting ports, so then the slave will get re-added. */
3015             bundle_remove(&ofport->up);
3016         }
3017     }
3018     return error;
3019 }
3020
3021 static int
3022 port_get_stats(const struct ofport *ofport_, struct netdev_stats *stats)
3023 {
3024     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3025     int error;
3026
3027     error = netdev_get_stats(ofport->up.netdev, stats);
3028
3029     if (!error && ofport_->ofp_port == OFPP_LOCAL) {
3030         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3031
3032         /* ofproto->stats.tx_packets represents packets that we created
3033          * internally and sent to some port (e.g. packets sent with
3034          * send_packet()).  Account for them as if they had come from
3035          * OFPP_LOCAL and got forwarded. */
3036
3037         if (stats->rx_packets != UINT64_MAX) {
3038             stats->rx_packets += ofproto->stats.tx_packets;
3039         }
3040
3041         if (stats->rx_bytes != UINT64_MAX) {
3042             stats->rx_bytes += ofproto->stats.tx_bytes;
3043         }
3044
3045         /* ofproto->stats.rx_packets represents packets that were received on
3046          * some port and we processed internally and dropped (e.g. STP).
3047          * Account for them as if they had been forwarded to OFPP_LOCAL. */
3048
3049         if (stats->tx_packets != UINT64_MAX) {
3050             stats->tx_packets += ofproto->stats.rx_packets;
3051         }
3052
3053         if (stats->tx_bytes != UINT64_MAX) {
3054             stats->tx_bytes += ofproto->stats.rx_bytes;
3055         }
3056     }
3057
3058     return error;
3059 }
3060
3061 /* Account packets for LOCAL port. */
3062 static void
3063 ofproto_update_local_port_stats(const struct ofproto *ofproto_,
3064                                 size_t tx_size, size_t rx_size)
3065 {
3066     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3067
3068     if (rx_size) {
3069         ofproto->stats.rx_packets++;
3070         ofproto->stats.rx_bytes += rx_size;
3071     }
3072     if (tx_size) {
3073         ofproto->stats.tx_packets++;
3074         ofproto->stats.tx_bytes += tx_size;
3075     }
3076 }
3077
3078 struct port_dump_state {
3079     uint32_t bucket;
3080     uint32_t offset;
3081     bool ghost;
3082 };
3083
3084 static int
3085 port_dump_start(const struct ofproto *ofproto_ OVS_UNUSED, void **statep)
3086 {
3087     *statep = xzalloc(sizeof(struct port_dump_state));
3088     return 0;
3089 }
3090
3091 static int
3092 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
3093                struct ofproto_port *port)
3094 {
3095     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3096     struct port_dump_state *state = state_;
3097     const struct sset *sset;
3098     struct sset_node *node;
3099
3100     sset = state->ghost ? &ofproto->ghost_ports : &ofproto->ports;
3101     while ((node = sset_at_position(sset, &state->bucket, &state->offset))) {
3102         int error;
3103
3104         error = port_query_by_name(ofproto_, node->name, port);
3105         if (error != ENODEV) {
3106             return error;
3107         }
3108     }
3109
3110     if (!state->ghost) {
3111         state->ghost = true;
3112         state->bucket = 0;
3113         state->offset = 0;
3114         return port_dump_next(ofproto_, state_, port);
3115     }
3116
3117     return EOF;
3118 }
3119
3120 static int
3121 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
3122 {
3123     struct port_dump_state *state = state_;
3124
3125     free(state);
3126     return 0;
3127 }
3128
3129 static int
3130 port_poll(const struct ofproto *ofproto_, char **devnamep)
3131 {
3132     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3133
3134     if (ofproto->port_poll_errno) {
3135         int error = ofproto->port_poll_errno;
3136         ofproto->port_poll_errno = 0;
3137         return error;
3138     }
3139
3140     if (sset_is_empty(&ofproto->port_poll_set)) {
3141         return EAGAIN;
3142     }
3143
3144     *devnamep = sset_pop(&ofproto->port_poll_set);
3145     return 0;
3146 }
3147
3148 static void
3149 port_poll_wait(const struct ofproto *ofproto_)
3150 {
3151     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
3152     dpif_port_poll_wait(ofproto->backer->dpif);
3153 }
3154
3155 static int
3156 port_is_lacp_current(const struct ofport *ofport_)
3157 {
3158     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
3159     return (ofport->bundle && ofport->bundle->lacp
3160             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
3161             : -1);
3162 }
3163 \f
3164 /* Upcall handling. */
3165
3166 /* Flow miss batching.
3167  *
3168  * Some dpifs implement operations faster when you hand them off in a batch.
3169  * To allow batching, "struct flow_miss" queues the dpif-related work needed
3170  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
3171  * more packets, plus possibly installing the flow in the dpif.
3172  *
3173  * So far we only batch the operations that affect flow setup time the most.
3174  * It's possible to batch more than that, but the benefit might be minimal. */
3175 struct flow_miss {
3176     struct hmap_node hmap_node;
3177     struct ofproto_dpif *ofproto;
3178     struct flow flow;
3179     enum odp_key_fitness key_fitness;
3180     const struct nlattr *key;
3181     size_t key_len;
3182     ovs_be16 initial_tci;
3183     struct list packets;
3184     enum dpif_upcall_type upcall_type;
3185     uint32_t odp_in_port;
3186 };
3187
3188 struct flow_miss_op {
3189     struct dpif_op dpif_op;
3190     struct subfacet *subfacet;  /* Subfacet  */
3191     void *garbage;              /* Pointer to pass to free(), NULL if none. */
3192     uint64_t stub[1024 / 8];    /* Temporary buffer. */
3193 };
3194
3195 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
3196  * OpenFlow controller as necessary according to their individual
3197  * configurations. */
3198 static void
3199 send_packet_in_miss(struct ofproto_dpif *ofproto, const struct ofpbuf *packet,
3200                     const struct flow *flow)
3201 {
3202     struct ofputil_packet_in pin;
3203
3204     pin.packet = packet->data;
3205     pin.packet_len = packet->size;
3206     pin.reason = OFPR_NO_MATCH;
3207     pin.controller_id = 0;
3208
3209     pin.table_id = 0;
3210     pin.cookie = 0;
3211
3212     pin.send_len = 0;           /* not used for flow table misses */
3213
3214     flow_get_metadata(flow, &pin.fmd);
3215
3216     connmgr_send_packet_in(ofproto->up.connmgr, &pin);
3217 }
3218
3219 static enum slow_path_reason
3220 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
3221                 const struct ofpbuf *packet)
3222 {
3223     struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
3224
3225     if (!ofport) {
3226         return 0;
3227     }
3228
3229     if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
3230         if (packet) {
3231             cfm_process_heartbeat(ofport->cfm, packet);
3232         }
3233         return SLOW_CFM;
3234     } else if (ofport->bundle && ofport->bundle->lacp
3235                && flow->dl_type == htons(ETH_TYPE_LACP)) {
3236         if (packet) {
3237             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
3238         }
3239         return SLOW_LACP;
3240     } else if (ofproto->stp && stp_should_process_flow(flow)) {
3241         if (packet) {
3242             stp_process_packet(ofport, packet);
3243         }
3244         return SLOW_STP;
3245     }
3246     return 0;
3247 }
3248
3249 static struct flow_miss *
3250 flow_miss_find(struct hmap *todo, const struct flow *flow, uint32_t hash)
3251 {
3252     struct flow_miss *miss;
3253
3254     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
3255         if (flow_equal(&miss->flow, flow)) {
3256             return miss;
3257         }
3258     }
3259
3260     return NULL;
3261 }
3262
3263 /* Partially Initializes 'op' as an "execute" operation for 'miss' and
3264  * 'packet'.  The caller must initialize op->actions and op->actions_len.  If
3265  * 'miss' is associated with a subfacet the caller must also initialize the
3266  * returned op->subfacet, and if anything needs to be freed after processing
3267  * the op, the caller must initialize op->garbage also. */
3268 static void
3269 init_flow_miss_execute_op(struct flow_miss *miss, struct ofpbuf *packet,
3270                           struct flow_miss_op *op)
3271 {
3272     if (miss->flow.vlan_tci != miss->initial_tci) {
3273         /* This packet was received on a VLAN splinter port.  We
3274          * added a VLAN to the packet to make the packet resemble
3275          * the flow, but the actions were composed assuming that
3276          * the packet contained no VLAN.  So, we must remove the
3277          * VLAN header from the packet before trying to execute the
3278          * actions. */
3279         eth_pop_vlan(packet);
3280     }
3281
3282     op->subfacet = NULL;
3283     op->garbage = NULL;
3284     op->dpif_op.type = DPIF_OP_EXECUTE;
3285     op->dpif_op.u.execute.key = miss->key;
3286     op->dpif_op.u.execute.key_len = miss->key_len;
3287     op->dpif_op.u.execute.packet = packet;
3288 }
3289
3290 /* Helper for handle_flow_miss_without_facet() and
3291  * handle_flow_miss_with_facet(). */
3292 static void
3293 handle_flow_miss_common(struct rule_dpif *rule,
3294                         struct ofpbuf *packet, const struct flow *flow)
3295 {
3296     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3297
3298     ofproto->n_matches++;
3299
3300     if (rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
3301         /*
3302          * Extra-special case for fail-open mode.
3303          *
3304          * We are in fail-open mode and the packet matched the fail-open
3305          * rule, but we are connected to a controller too.  We should send
3306          * the packet up to the controller in the hope that it will try to
3307          * set up a flow and thereby allow us to exit fail-open.
3308          *
3309          * See the top-level comment in fail-open.c for more information.
3310          */
3311         send_packet_in_miss(ofproto, packet, flow);
3312     }
3313 }
3314
3315 /* Figures out whether a flow that missed in 'ofproto', whose details are in
3316  * 'miss', is likely to be worth tracking in detail in userspace and (usually)
3317  * installing a datapath flow.  The answer is usually "yes" (a return value of
3318  * true).  However, for short flows the cost of bookkeeping is much higher than
3319  * the benefits, so when the datapath holds a large number of flows we impose
3320  * some heuristics to decide which flows are likely to be worth tracking. */
3321 static bool
3322 flow_miss_should_make_facet(struct ofproto_dpif *ofproto,
3323                             struct flow_miss *miss, uint32_t hash)
3324 {
3325     if (!ofproto->governor) {
3326         size_t n_subfacets;
3327
3328         n_subfacets = hmap_count(&ofproto->subfacets);
3329         if (n_subfacets * 2 <= ofproto->up.flow_eviction_threshold) {
3330             return true;
3331         }
3332
3333         ofproto->governor = governor_create(ofproto->up.name);
3334     }
3335
3336     return governor_should_install_flow(ofproto->governor, hash,
3337                                         list_size(&miss->packets));
3338 }
3339
3340 /* Handles 'miss', which matches 'rule', without creating a facet or subfacet
3341  * or creating any datapath flow.  May add an "execute" operation to 'ops' and
3342  * increment '*n_ops'. */
3343 static void
3344 handle_flow_miss_without_facet(struct flow_miss *miss,
3345                                struct rule_dpif *rule,
3346                                struct flow_miss_op *ops, size_t *n_ops)
3347 {
3348     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3349     long long int now = time_msec();
3350     struct action_xlate_ctx ctx;
3351     struct ofpbuf *packet;
3352
3353     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3354         struct flow_miss_op *op = &ops[*n_ops];
3355         struct dpif_flow_stats stats;
3356         struct ofpbuf odp_actions;
3357
3358         COVERAGE_INC(facet_suppress);
3359
3360         ofpbuf_use_stub(&odp_actions, op->stub, sizeof op->stub);
3361
3362         dpif_flow_stats_extract(&miss->flow, packet, now, &stats);
3363         rule_credit_stats(rule, &stats);
3364
3365         action_xlate_ctx_init(&ctx, ofproto, &miss->flow, miss->initial_tci,
3366                               rule, 0, packet);
3367         ctx.resubmit_stats = &stats;
3368         xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len,
3369                       &odp_actions);
3370
3371         if (odp_actions.size) {
3372             struct dpif_execute *execute = &op->dpif_op.u.execute;
3373
3374             init_flow_miss_execute_op(miss, packet, op);
3375             execute->actions = odp_actions.data;
3376             execute->actions_len = odp_actions.size;
3377             op->garbage = ofpbuf_get_uninit_pointer(&odp_actions);
3378
3379             (*n_ops)++;
3380         } else {
3381             ofpbuf_uninit(&odp_actions);
3382         }
3383     }
3384 }
3385
3386 /* Handles 'miss', which matches 'facet'.  May add any required datapath
3387  * operations to 'ops', incrementing '*n_ops' for each new op.
3388  *
3389  * All of the packets in 'miss' are considered to have arrived at time 'now'.
3390  * This is really important only for new facets: if we just called time_msec()
3391  * here, then the new subfacet or its packets could look (occasionally) as
3392  * though it was used some time after the facet was used.  That can make a
3393  * one-packet flow look like it has a nonzero duration, which looks odd in
3394  * e.g. NetFlow statistics. */
3395 static void
3396 handle_flow_miss_with_facet(struct flow_miss *miss, struct facet *facet,
3397                             long long int now,
3398                             struct flow_miss_op *ops, size_t *n_ops)
3399 {
3400     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
3401     enum subfacet_path want_path;
3402     struct subfacet *subfacet;
3403     struct ofpbuf *packet;
3404
3405     subfacet = subfacet_create(facet, miss, now);
3406
3407     LIST_FOR_EACH (packet, list_node, &miss->packets) {
3408         struct flow_miss_op *op = &ops[*n_ops];
3409         struct dpif_flow_stats stats;
3410         struct ofpbuf odp_actions;
3411
3412         handle_flow_miss_common(facet->rule, packet, &miss->flow);
3413
3414         ofpbuf_use_stub(&odp_actions, op->stub, sizeof op->stub);
3415         if (!subfacet->actions || subfacet->slow) {
3416             subfacet_make_actions(subfacet, packet, &odp_actions);
3417         }
3418
3419         dpif_flow_stats_extract(&facet->flow, packet, now, &stats);
3420         subfacet_update_stats(subfacet, &stats);
3421
3422         if (subfacet->actions_len) {
3423             struct dpif_execute *execute = &op->dpif_op.u.execute;
3424
3425             init_flow_miss_execute_op(miss, packet, op);
3426             op->subfacet = subfacet;
3427             if (!subfacet->slow) {
3428                 execute->actions = subfacet->actions;
3429                 execute->actions_len = subfacet->actions_len;
3430                 ofpbuf_uninit(&odp_actions);
3431             } else {
3432                 execute->actions = odp_actions.data;
3433                 execute->actions_len = odp_actions.size;
3434                 op->garbage = ofpbuf_get_uninit_pointer(&odp_actions);
3435             }
3436
3437             (*n_ops)++;
3438         } else {
3439             ofpbuf_uninit(&odp_actions);
3440         }
3441     }
3442
3443     want_path = subfacet_want_path(subfacet->slow);
3444     if (miss->upcall_type == DPIF_UC_MISS || subfacet->path != want_path) {
3445         struct flow_miss_op *op = &ops[(*n_ops)++];
3446         struct dpif_flow_put *put = &op->dpif_op.u.flow_put;
3447
3448         op->subfacet = subfacet;
3449         op->garbage = NULL;
3450         op->dpif_op.type = DPIF_OP_FLOW_PUT;
3451         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
3452         put->key = miss->key;
3453         put->key_len = miss->key_len;
3454         if (want_path == SF_FAST_PATH) {
3455             put->actions = subfacet->actions;
3456             put->actions_len = subfacet->actions_len;
3457         } else {
3458             compose_slow_path(ofproto, &facet->flow, subfacet->slow,
3459                               op->stub, sizeof op->stub,
3460                               &put->actions, &put->actions_len);
3461         }
3462         put->stats = NULL;
3463     }
3464 }
3465
3466 /* Handles flow miss 'miss'.  May add any required datapath operations
3467  * to 'ops', incrementing '*n_ops' for each new op. */
3468 static void
3469 handle_flow_miss(struct flow_miss *miss, struct flow_miss_op *ops,
3470                  size_t *n_ops)
3471 {
3472     struct ofproto_dpif *ofproto = miss->ofproto;
3473     struct facet *facet;
3474     long long int now;
3475     uint32_t hash;
3476
3477     /* The caller must ensure that miss->hmap_node.hash contains
3478      * flow_hash(miss->flow, 0). */
3479     hash = miss->hmap_node.hash;
3480
3481     facet = facet_lookup_valid(ofproto, &miss->flow, hash);
3482     if (!facet) {
3483         struct rule_dpif *rule = rule_dpif_lookup(ofproto, &miss->flow);
3484
3485         if (!flow_miss_should_make_facet(ofproto, miss, hash)) {
3486             handle_flow_miss_without_facet(miss, rule, ops, n_ops);
3487             return;
3488         }
3489
3490         facet = facet_create(rule, &miss->flow, hash);
3491         now = facet->used;
3492     } else {
3493         now = time_msec();
3494     }
3495     handle_flow_miss_with_facet(miss, facet, now, ops, n_ops);
3496 }
3497
3498 static struct drop_key *
3499 drop_key_lookup(const struct dpif_backer *backer, const struct nlattr *key,
3500                 size_t key_len)
3501 {
3502     struct drop_key *drop_key;
3503
3504     HMAP_FOR_EACH_WITH_HASH (drop_key, hmap_node, hash_bytes(key, key_len, 0),
3505                              &backer->drop_keys) {
3506         if (drop_key->key_len == key_len
3507             && !memcmp(drop_key->key, key, key_len)) {
3508             return drop_key;
3509         }
3510     }
3511     return NULL;
3512 }
3513
3514 static void
3515 drop_key_clear(struct dpif_backer *backer)
3516 {
3517     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
3518     struct drop_key *drop_key, *next;
3519
3520     HMAP_FOR_EACH_SAFE (drop_key, next, hmap_node, &backer->drop_keys) {
3521         int error;
3522
3523         error = dpif_flow_del(backer->dpif, drop_key->key, drop_key->key_len,
3524                               NULL);
3525         if (error && !VLOG_DROP_WARN(&rl)) {
3526             struct ds ds = DS_EMPTY_INITIALIZER;
3527             odp_flow_key_format(drop_key->key, drop_key->key_len, &ds);
3528             VLOG_WARN("Failed to delete drop key (%s) (%s)", strerror(error),
3529                       ds_cstr(&ds));
3530             ds_destroy(&ds);
3531         }
3532
3533         hmap_remove(&backer->drop_keys, &drop_key->hmap_node);
3534         free(drop_key->key);
3535         free(drop_key);
3536     }
3537 }
3538
3539 /* Given a datpath, packet, and flow metadata ('backer', 'packet', and 'key'
3540  * respectively), populates 'flow' with the result of odp_flow_key_to_flow().
3541  * Optionally, if nonnull, populates 'fitnessp' with the fitness of 'flow' as
3542  * returned by odp_flow_key_to_flow().  Also, optionally populates 'ofproto'
3543  * with the ofproto_dpif, and 'odp_in_port' with the datapath in_port, that
3544  * 'packet' ingressed.
3545  *
3546  * If 'ofproto' is nonnull, requires 'flow''s in_port to exist.  Otherwise sets
3547  * 'flow''s in_port to OFPP_NONE.
3548  *
3549  * This function does post-processing on data returned from
3550  * odp_flow_key_to_flow() to help make VLAN splinters transparent to the rest
3551  * of the upcall processing logic.  In particular, if the extracted in_port is
3552  * a VLAN splinter port, it replaces flow->in_port by the "real" port, sets
3553  * flow->vlan_tci correctly for the VLAN of the VLAN splinter port, and pushes
3554  * a VLAN header onto 'packet' (if it is nonnull).
3555  *
3556  * Optionally, if nonnull, sets '*initial_tci' to the VLAN TCI with which the
3557  * packet was really received, that is, the actual VLAN TCI extracted by
3558  * odp_flow_key_to_flow().  (This differs from the value returned in
3559  * flow->vlan_tci only for packets received on VLAN splinters.)
3560  *
3561  * Returns 0 if successful, ENODEV if the parsed flow has no associated ofport,
3562  * or some other positive errno if there are other problems. */
3563 static int
3564 ofproto_receive(const struct dpif_backer *backer, struct ofpbuf *packet,
3565                 const struct nlattr *key, size_t key_len,
3566                 struct flow *flow, enum odp_key_fitness *fitnessp,
3567                 struct ofproto_dpif **ofproto, uint32_t *odp_in_port,
3568                 ovs_be16 *initial_tci)
3569 {
3570     const struct ofport_dpif *port;
3571     enum odp_key_fitness fitness;
3572     int error;
3573
3574     fitness = odp_flow_key_to_flow(key, key_len, flow);
3575     if (fitness == ODP_FIT_ERROR) {
3576         error = EINVAL;
3577         goto exit;
3578     }
3579
3580     if (initial_tci) {
3581         *initial_tci = flow->vlan_tci;
3582     }
3583
3584     if (odp_in_port) {
3585         *odp_in_port = flow->in_port;
3586     }
3587
3588     port = odp_port_to_ofport(backer, flow->in_port);
3589     if (!port) {
3590         flow->in_port = OFPP_NONE;
3591         error = ENODEV;
3592         goto exit;
3593     }
3594
3595     if (ofproto) {
3596         *ofproto = ofproto_dpif_cast(port->up.ofproto);
3597     }
3598
3599     flow->in_port = port->up.ofp_port;
3600     if (vsp_adjust_flow(ofproto_dpif_cast(port->up.ofproto), flow)) {
3601         if (packet) {
3602             /* Make the packet resemble the flow, so that it gets sent to an
3603              * OpenFlow controller properly, so that it looks correct for
3604              * sFlow, and so that flow_extract() will get the correct vlan_tci
3605              * if it is called on 'packet'.
3606              *
3607              * The allocated space inside 'packet' probably also contains
3608              * 'key', that is, both 'packet' and 'key' are probably part of a
3609              * struct dpif_upcall (see the large comment on that structure
3610              * definition), so pushing data on 'packet' is in general not a
3611              * good idea since it could overwrite 'key' or free it as a side
3612              * effect.  However, it's OK in this special case because we know
3613              * that 'packet' is inside a Netlink attribute: pushing 4 bytes
3614              * will just overwrite the 4-byte "struct nlattr", which is fine
3615              * since we don't need that header anymore. */
3616             eth_push_vlan(packet, flow->vlan_tci);
3617         }
3618
3619         /* Let the caller know that we can't reproduce 'key' from 'flow'. */
3620         if (fitness == ODP_FIT_PERFECT) {
3621             fitness = ODP_FIT_TOO_MUCH;
3622         }
3623     }
3624     error = 0;
3625
3626 exit:
3627     if (fitnessp) {
3628         *fitnessp = fitness;
3629     }
3630     return error;
3631 }
3632
3633 static void
3634 handle_miss_upcalls(struct dpif_backer *backer, struct dpif_upcall *upcalls,
3635                     size_t n_upcalls)
3636 {
3637     struct dpif_upcall *upcall;
3638     struct flow_miss *miss;
3639     struct flow_miss misses[FLOW_MISS_MAX_BATCH];
3640     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
3641     struct dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
3642     struct hmap todo;
3643     int n_misses;
3644     size_t n_ops;
3645     size_t i;
3646
3647     if (!n_upcalls) {
3648         return;
3649     }
3650
3651     /* Construct the to-do list.
3652      *
3653      * This just amounts to extracting the flow from each packet and sticking
3654      * the packets that have the same flow in the same "flow_miss" structure so
3655      * that we can process them together. */
3656     hmap_init(&todo);
3657     n_misses = 0;
3658     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
3659         struct flow_miss *miss = &misses[n_misses];
3660         struct flow_miss *existing_miss;
3661         struct ofproto_dpif *ofproto;
3662         uint32_t odp_in_port;
3663         struct flow flow;
3664         uint32_t hash;
3665         int error;
3666
3667         error = ofproto_receive(backer, upcall->packet, upcall->key,
3668                                 upcall->key_len, &flow, &miss->key_fitness,
3669                                 &ofproto, &odp_in_port, &miss->initial_tci);
3670         if (error == ENODEV) {
3671             struct drop_key *drop_key;
3672
3673             /* Received packet on port for which we couldn't associate
3674              * an ofproto.  This can happen if a port is removed while
3675              * traffic is being received.  Print a rate-limited message
3676              * in case it happens frequently.  Install a drop flow so
3677              * that future packets of the flow are inexpensively dropped
3678              * in the kernel. */
3679             VLOG_INFO_RL(&rl, "received packet on unassociated port %"PRIu32,
3680                          flow.in_port);
3681
3682             drop_key = drop_key_lookup(backer, upcall->key, upcall->key_len);
3683             if (!drop_key) {
3684                 drop_key = xmalloc(sizeof *drop_key);
3685                 drop_key->key = xmemdup(upcall->key, upcall->key_len);
3686                 drop_key->key_len = upcall->key_len;
3687
3688                 hmap_insert(&backer->drop_keys, &drop_key->hmap_node,
3689                             hash_bytes(drop_key->key, drop_key->key_len, 0));
3690                 dpif_flow_put(backer->dpif, DPIF_FP_CREATE | DPIF_FP_MODIFY,
3691                               drop_key->key, drop_key->key_len, NULL, 0, NULL);
3692             }
3693             continue;
3694         }
3695         if (error) {
3696             continue;
3697         }
3698         flow_extract(upcall->packet, flow.skb_priority, flow.skb_mark,
3699                      &flow.tunnel, flow.in_port, &miss->flow);
3700
3701         /* Add other packets to a to-do list. */
3702         hash = flow_hash(&miss->flow, 0);
3703         existing_miss = flow_miss_find(&todo, &miss->flow, hash);
3704         if (!existing_miss) {
3705             hmap_insert(&todo, &miss->hmap_node, hash);
3706             miss->ofproto = ofproto;
3707             miss->key = upcall->key;
3708             miss->key_len = upcall->key_len;
3709             miss->upcall_type = upcall->type;
3710             miss->odp_in_port = odp_in_port;
3711             list_init(&miss->packets);
3712
3713             n_misses++;
3714         } else {
3715             miss = existing_miss;
3716         }
3717         list_push_back(&miss->packets, &upcall->packet->list_node);
3718     }
3719
3720     /* Process each element in the to-do list, constructing the set of
3721      * operations to batch. */
3722     n_ops = 0;
3723     HMAP_FOR_EACH (miss, hmap_node, &todo) {
3724         handle_flow_miss(miss, flow_miss_ops, &n_ops);
3725     }
3726     ovs_assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
3727
3728     /* Execute batch. */
3729     for (i = 0; i < n_ops; i++) {
3730         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
3731     }
3732     dpif_operate(backer->dpif, dpif_ops, n_ops);
3733
3734     /* Free memory and update facets. */
3735     for (i = 0; i < n_ops; i++) {
3736         struct flow_miss_op *op = &flow_miss_ops[i];
3737
3738         switch (op->dpif_op.type) {
3739         case DPIF_OP_EXECUTE:
3740             break;
3741
3742         case DPIF_OP_FLOW_PUT:
3743             if (!op->dpif_op.error) {
3744                 op->subfacet->path = subfacet_want_path(op->subfacet->slow);
3745             }
3746             break;
3747
3748         case DPIF_OP_FLOW_DEL:
3749             NOT_REACHED();
3750         }
3751
3752         free(op->garbage);
3753     }
3754     hmap_destroy(&todo);
3755 }
3756
3757 static enum { SFLOW_UPCALL, MISS_UPCALL, BAD_UPCALL }
3758 classify_upcall(const struct dpif_upcall *upcall)
3759 {
3760     union user_action_cookie cookie;
3761
3762     /* First look at the upcall type. */
3763     switch (upcall->type) {
3764     case DPIF_UC_ACTION:
3765         break;
3766
3767     case DPIF_UC_MISS:
3768         return MISS_UPCALL;
3769
3770     case DPIF_N_UC_TYPES:
3771     default:
3772         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
3773         return BAD_UPCALL;
3774     }
3775
3776     /* "action" upcalls need a closer look. */
3777     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
3778     switch (cookie.type) {
3779     case USER_ACTION_COOKIE_SFLOW:
3780         return SFLOW_UPCALL;
3781
3782     case USER_ACTION_COOKIE_SLOW_PATH:
3783         return MISS_UPCALL;
3784
3785     case USER_ACTION_COOKIE_UNSPEC:
3786     default:
3787         VLOG_WARN_RL(&rl, "invalid user cookie : 0x%"PRIx64, upcall->userdata);
3788         return BAD_UPCALL;
3789     }
3790 }
3791
3792 static void
3793 handle_sflow_upcall(struct dpif_backer *backer,
3794                     const struct dpif_upcall *upcall)
3795 {
3796     struct ofproto_dpif *ofproto;
3797     union user_action_cookie cookie;
3798     struct flow flow;
3799     uint32_t odp_in_port;
3800
3801     if (ofproto_receive(backer, upcall->packet, upcall->key, upcall->key_len,
3802                         &flow, NULL, &ofproto, &odp_in_port, NULL)
3803         || !ofproto->sflow) {
3804         return;
3805     }
3806
3807     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
3808     dpif_sflow_received(ofproto->sflow, upcall->packet, &flow,
3809                         odp_in_port, &cookie);
3810 }
3811
3812 static int
3813 handle_upcalls(struct dpif_backer *backer, unsigned int max_batch)
3814 {
3815     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
3816     struct ofpbuf miss_bufs[FLOW_MISS_MAX_BATCH];
3817     uint64_t miss_buf_stubs[FLOW_MISS_MAX_BATCH][4096 / 8];
3818     int n_processed;
3819     int n_misses;
3820     int i;
3821
3822     ovs_assert(max_batch <= FLOW_MISS_MAX_BATCH);
3823
3824     n_misses = 0;
3825     for (n_processed = 0; n_processed < max_batch; n_processed++) {
3826         struct dpif_upcall *upcall = &misses[n_misses];
3827         struct ofpbuf *buf = &miss_bufs[n_misses];
3828         int error;
3829
3830         ofpbuf_use_stub(buf, miss_buf_stubs[n_misses],
3831                         sizeof miss_buf_stubs[n_misses]);
3832         error = dpif_recv(backer->dpif, upcall, buf);
3833         if (error) {
3834             ofpbuf_uninit(buf);
3835             break;
3836         }
3837
3838         switch (classify_upcall(upcall)) {
3839         case MISS_UPCALL:
3840             /* Handle it later. */
3841             n_misses++;
3842             break;
3843
3844         case SFLOW_UPCALL:
3845             handle_sflow_upcall(backer, upcall);
3846             ofpbuf_uninit(buf);
3847             break;
3848
3849         case BAD_UPCALL:
3850             ofpbuf_uninit(buf);
3851             break;
3852         }
3853     }
3854
3855     /* Handle deferred MISS_UPCALL processing. */
3856     handle_miss_upcalls(backer, misses, n_misses);
3857     for (i = 0; i < n_misses; i++) {
3858         ofpbuf_uninit(&miss_bufs[i]);
3859     }
3860
3861     return n_processed;
3862 }
3863 \f
3864 /* Flow expiration. */
3865
3866 static int subfacet_max_idle(const struct ofproto_dpif *);
3867 static void update_stats(struct dpif_backer *);
3868 static void rule_expire(struct rule_dpif *);
3869 static void expire_subfacets(struct ofproto_dpif *, int dp_max_idle);
3870
3871 /* This function is called periodically by run().  Its job is to collect
3872  * updates for the flows that have been installed into the datapath, most
3873  * importantly when they last were used, and then use that information to
3874  * expire flows that have not been used recently.
3875  *
3876  * Returns the number of milliseconds after which it should be called again. */
3877 static int
3878 expire(struct dpif_backer *backer)
3879 {
3880     struct ofproto_dpif *ofproto;
3881     int max_idle = INT32_MAX;
3882
3883     /* Periodically clear out the drop keys in an effort to keep them
3884      * relatively few. */
3885     drop_key_clear(backer);
3886
3887     /* Update stats for each flow in the backer. */
3888     update_stats(backer);
3889
3890     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
3891         struct rule *rule, *next_rule;
3892         int dp_max_idle;
3893
3894         if (ofproto->backer != backer) {
3895             continue;
3896         }
3897
3898         /* Expire subfacets that have been idle too long. */
3899         dp_max_idle = subfacet_max_idle(ofproto);
3900         expire_subfacets(ofproto, dp_max_idle);
3901
3902         max_idle = MIN(max_idle, dp_max_idle);
3903
3904         /* Expire OpenFlow flows whose idle_timeout or hard_timeout
3905          * has passed. */
3906         LIST_FOR_EACH_SAFE (rule, next_rule, expirable,
3907                             &ofproto->up.expirable) {
3908             rule_expire(rule_dpif_cast(rule));
3909         }
3910
3911         /* All outstanding data in existing flows has been accounted, so it's a
3912          * good time to do bond rebalancing. */
3913         if (ofproto->has_bonded_bundles) {
3914             struct ofbundle *bundle;
3915
3916             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
3917                 if (bundle->bond) {
3918                     bond_rebalance(bundle->bond, &backer->revalidate_set);
3919                 }
3920             }
3921         }
3922     }
3923
3924     return MIN(max_idle, 1000);
3925 }
3926
3927 /* Updates flow table statistics given that the datapath just reported 'stats'
3928  * as 'subfacet''s statistics. */
3929 static void
3930 update_subfacet_stats(struct subfacet *subfacet,
3931                       const struct dpif_flow_stats *stats)
3932 {
3933     struct facet *facet = subfacet->facet;
3934
3935     if (stats->n_packets >= subfacet->dp_packet_count) {
3936         uint64_t extra = stats->n_packets - subfacet->dp_packet_count;
3937         facet->packet_count += extra;
3938     } else {
3939         VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
3940     }
3941
3942     if (stats->n_bytes >= subfacet->dp_byte_count) {
3943         facet->byte_count += stats->n_bytes - subfacet->dp_byte_count;
3944     } else {
3945         VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
3946     }
3947
3948     subfacet->dp_packet_count = stats->n_packets;
3949     subfacet->dp_byte_count = stats->n_bytes;
3950
3951     facet->tcp_flags |= stats->tcp_flags;
3952
3953     subfacet_update_time(subfacet, stats->used);
3954     if (facet->accounted_bytes < facet->byte_count) {
3955         facet_learn(facet);
3956         facet_account(facet);
3957         facet->accounted_bytes = facet->byte_count;
3958     }
3959     facet_push_stats(facet);
3960 }
3961
3962 /* 'key' with length 'key_len' bytes is a flow in 'dpif' that we know nothing
3963  * about, or a flow that shouldn't be installed but was anyway.  Delete it. */
3964 static void
3965 delete_unexpected_flow(struct ofproto_dpif *ofproto,
3966                        const struct nlattr *key, size_t key_len)
3967 {
3968     if (!VLOG_DROP_WARN(&rl)) {
3969         struct ds s;
3970
3971         ds_init(&s);
3972         odp_flow_key_format(key, key_len, &s);
3973         VLOG_WARN("unexpected flow on %s: %s", ofproto->up.name, ds_cstr(&s));
3974         ds_destroy(&s);
3975     }
3976
3977     COVERAGE_INC(facet_unexpected);
3978     dpif_flow_del(ofproto->backer->dpif, key, key_len, NULL);
3979 }
3980
3981 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
3982  *
3983  * This function also pushes statistics updates to rules which each facet
3984  * resubmits into.  Generally these statistics will be accurate.  However, if a
3985  * facet changes the rule it resubmits into at some time in between
3986  * update_stats() runs, it is possible that statistics accrued to the
3987  * old rule will be incorrectly attributed to the new rule.  This could be
3988  * avoided by calling update_stats() whenever rules are created or
3989  * deleted.  However, the performance impact of making so many calls to the
3990  * datapath do not justify the benefit of having perfectly accurate statistics.
3991  */
3992 static void
3993 update_stats(struct dpif_backer *backer)
3994 {
3995     const struct dpif_flow_stats *stats;
3996     struct dpif_flow_dump dump;
3997     const struct nlattr *key;
3998     size_t key_len;
3999
4000     dpif_flow_dump_start(&dump, backer->dpif);
4001     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
4002         struct flow flow;
4003         struct subfacet *subfacet;
4004         struct ofproto_dpif *ofproto;
4005         uint32_t key_hash;
4006
4007         if (ofproto_receive(backer, NULL, key, key_len, &flow, NULL, &ofproto,
4008                             NULL, NULL)) {
4009             continue;
4010         }
4011
4012         key_hash = odp_flow_key_hash(key, key_len);
4013         subfacet = subfacet_find(ofproto, key, key_len, key_hash, &flow);
4014         switch (subfacet ? subfacet->path : SF_NOT_INSTALLED) {
4015         case SF_FAST_PATH:
4016             update_subfacet_stats(subfacet, stats);
4017             break;
4018
4019         case SF_SLOW_PATH:
4020             /* Stats are updated per-packet. */
4021             break;
4022
4023         case SF_NOT_INSTALLED:
4024         default:
4025             delete_unexpected_flow(ofproto, key, key_len);
4026             break;
4027         }
4028     }
4029     dpif_flow_dump_done(&dump);
4030 }
4031
4032 /* Calculates and returns the number of milliseconds of idle time after which
4033  * subfacets should expire from the datapath.  When a subfacet expires, we fold
4034  * its statistics into its facet, and when a facet's last subfacet expires, we
4035  * fold its statistic into its rule. */
4036 static int
4037 subfacet_max_idle(const struct ofproto_dpif *ofproto)
4038 {
4039     /*
4040      * Idle time histogram.
4041      *
4042      * Most of the time a switch has a relatively small number of subfacets.
4043      * When this is the case we might as well keep statistics for all of them
4044      * in userspace and to cache them in the kernel datapath for performance as
4045      * well.
4046      *
4047      * As the number of subfacets increases, the memory required to maintain
4048      * statistics about them in userspace and in the kernel becomes
4049      * significant.  However, with a large number of subfacets it is likely
4050      * that only a few of them are "heavy hitters" that consume a large amount
4051      * of bandwidth.  At this point, only heavy hitters are worth caching in
4052      * the kernel and maintaining in userspaces; other subfacets we can
4053      * discard.
4054      *
4055      * The technique used to compute the idle time is to build a histogram with
4056      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each subfacet
4057      * that is installed in the kernel gets dropped in the appropriate bucket.
4058      * After the histogram has been built, we compute the cutoff so that only
4059      * the most-recently-used 1% of subfacets (but at least
4060      * ofproto->up.flow_eviction_threshold flows) are kept cached.  At least
4061      * the most-recently-used bucket of subfacets is kept, so actually an
4062      * arbitrary number of subfacets can be kept in any given expiration run
4063      * (though the next run will delete most of those unless they receive
4064      * additional data).
4065      *
4066      * This requires a second pass through the subfacets, in addition to the
4067      * pass made by update_stats(), because the former function never looks at
4068      * uninstallable subfacets.
4069      */
4070     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
4071     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
4072     int buckets[N_BUCKETS] = { 0 };
4073     int total, subtotal, bucket;
4074     struct subfacet *subfacet;
4075     long long int now;
4076     int i;
4077
4078     total = hmap_count(&ofproto->subfacets);
4079     if (total <= ofproto->up.flow_eviction_threshold) {
4080         return N_BUCKETS * BUCKET_WIDTH;
4081     }
4082
4083     /* Build histogram. */
4084     now = time_msec();
4085     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
4086         long long int idle = now - subfacet->used;
4087         int bucket = (idle <= 0 ? 0
4088                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
4089                       : (unsigned int) idle / BUCKET_WIDTH);
4090         buckets[bucket]++;
4091     }
4092
4093     /* Find the first bucket whose flows should be expired. */
4094     subtotal = bucket = 0;
4095     do {
4096         subtotal += buckets[bucket++];
4097     } while (bucket < N_BUCKETS &&
4098              subtotal < MAX(ofproto->up.flow_eviction_threshold, total / 100));
4099
4100     if (VLOG_IS_DBG_ENABLED()) {
4101         struct ds s;
4102
4103         ds_init(&s);
4104         ds_put_cstr(&s, "keep");
4105         for (i = 0; i < N_BUCKETS; i++) {
4106             if (i == bucket) {
4107                 ds_put_cstr(&s, ", drop");
4108             }
4109             if (buckets[i]) {
4110                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
4111             }
4112         }
4113         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
4114         ds_destroy(&s);
4115     }
4116
4117     return bucket * BUCKET_WIDTH;
4118 }
4119
4120 static void
4121 expire_subfacets(struct ofproto_dpif *ofproto, int dp_max_idle)
4122 {
4123     /* Cutoff time for most flows. */
4124     long long int normal_cutoff = time_msec() - dp_max_idle;
4125
4126     /* We really want to keep flows for special protocols around, so use a more
4127      * conservative cutoff. */
4128     long long int special_cutoff = time_msec() - 10000;
4129
4130     struct subfacet *subfacet, *next_subfacet;
4131     struct subfacet *batch[SUBFACET_DESTROY_MAX_BATCH];
4132     int n_batch;
4133
4134     n_batch = 0;
4135     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
4136                         &ofproto->subfacets) {
4137         long long int cutoff;
4138
4139         cutoff = (subfacet->slow & (SLOW_CFM | SLOW_LACP | SLOW_STP)
4140                   ? special_cutoff
4141                   : normal_cutoff);
4142         if (subfacet->used < cutoff) {
4143             if (subfacet->path != SF_NOT_INSTALLED) {
4144                 batch[n_batch++] = subfacet;
4145                 if (n_batch >= SUBFACET_DESTROY_MAX_BATCH) {
4146                     subfacet_destroy_batch(ofproto, batch, n_batch);
4147                     n_batch = 0;
4148                 }
4149             } else {
4150                 subfacet_destroy(subfacet);
4151             }
4152         }
4153     }
4154
4155     if (n_batch > 0) {
4156         subfacet_destroy_batch(ofproto, batch, n_batch);
4157     }
4158 }
4159
4160 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
4161  * then delete it entirely. */
4162 static void
4163 rule_expire(struct rule_dpif *rule)
4164 {
4165     struct facet *facet, *next_facet;
4166     long long int now;
4167     uint8_t reason;
4168
4169     if (rule->up.pending) {
4170         /* We'll have to expire it later. */
4171         return;
4172     }
4173
4174     /* Has 'rule' expired? */
4175     now = time_msec();
4176     if (rule->up.hard_timeout
4177         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
4178         reason = OFPRR_HARD_TIMEOUT;
4179     } else if (rule->up.idle_timeout
4180                && now > rule->up.used + rule->up.idle_timeout * 1000) {
4181         reason = OFPRR_IDLE_TIMEOUT;
4182     } else {
4183         return;
4184     }
4185
4186     COVERAGE_INC(ofproto_dpif_expired);
4187
4188     /* Update stats.  (This is a no-op if the rule expired due to an idle
4189      * timeout, because that only happens when the rule has no facets left.) */
4190     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
4191         facet_remove(facet);
4192     }
4193
4194     /* Get rid of the rule. */
4195     ofproto_rule_expire(&rule->up, reason);
4196 }
4197 \f
4198 /* Facets. */
4199
4200 /* Creates and returns a new facet owned by 'rule', given a 'flow'.
4201  *
4202  * The caller must already have determined that no facet with an identical
4203  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
4204  * the ofproto's classifier table.
4205  *
4206  * 'hash' must be the return value of flow_hash(flow, 0).
4207  *
4208  * The facet will initially have no subfacets.  The caller should create (at
4209  * least) one subfacet with subfacet_create(). */
4210 static struct facet *
4211 facet_create(struct rule_dpif *rule, const struct flow *flow, uint32_t hash)
4212 {
4213     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4214     struct facet *facet;
4215
4216     facet = xzalloc(sizeof *facet);
4217     facet->used = time_msec();
4218     hmap_insert(&ofproto->facets, &facet->hmap_node, hash);
4219     list_push_back(&rule->facets, &facet->list_node);
4220     facet->rule = rule;
4221     facet->flow = *flow;
4222     list_init(&facet->subfacets);
4223     netflow_flow_init(&facet->nf_flow);
4224     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
4225
4226     return facet;
4227 }
4228
4229 static void
4230 facet_free(struct facet *facet)
4231 {
4232     free(facet);
4233 }
4234
4235 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
4236  * 'packet', which arrived on 'in_port'. */
4237 static bool
4238 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
4239                     const struct nlattr *odp_actions, size_t actions_len,
4240                     struct ofpbuf *packet)
4241 {
4242     struct odputil_keybuf keybuf;
4243     struct ofpbuf key;
4244     int error;
4245
4246     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
4247     odp_flow_key_from_flow(&key, flow,
4248                            ofp_port_to_odp_port(ofproto, flow->in_port));
4249
4250     error = dpif_execute(ofproto->backer->dpif, key.data, key.size,
4251                          odp_actions, actions_len, packet);
4252     return !error;
4253 }
4254
4255 /* Remove 'facet' from 'ofproto' and free up the associated memory:
4256  *
4257  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
4258  *     rule's statistics, via subfacet_uninstall().
4259  *
4260  *   - Removes 'facet' from its rule and from ofproto->facets.
4261  */
4262 static void
4263 facet_remove(struct facet *facet)
4264 {
4265     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4266     struct subfacet *subfacet, *next_subfacet;
4267
4268     ovs_assert(!list_is_empty(&facet->subfacets));
4269
4270     /* First uninstall all of the subfacets to get final statistics. */
4271     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4272         subfacet_uninstall(subfacet);
4273     }
4274
4275     /* Flush the final stats to the rule.
4276      *
4277      * This might require us to have at least one subfacet around so that we
4278      * can use its actions for accounting in facet_account(), which is why we
4279      * have uninstalled but not yet destroyed the subfacets. */
4280     facet_flush_stats(facet);
4281
4282     /* Now we're really all done so destroy everything. */
4283     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
4284                         &facet->subfacets) {
4285         subfacet_destroy__(subfacet);
4286     }
4287     hmap_remove(&ofproto->facets, &facet->hmap_node);
4288     list_remove(&facet->list_node);
4289     facet_free(facet);
4290 }
4291
4292 /* Feed information from 'facet' back into the learning table to keep it in
4293  * sync with what is actually flowing through the datapath. */
4294 static void
4295 facet_learn(struct facet *facet)
4296 {
4297     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4298     struct action_xlate_ctx ctx;
4299
4300     if (!facet->has_learn
4301         && !facet->has_normal
4302         && (!facet->has_fin_timeout
4303             || !(facet->tcp_flags & (TCP_FIN | TCP_RST)))) {
4304         return;
4305     }
4306
4307     action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
4308                           facet->flow.vlan_tci,
4309                           facet->rule, facet->tcp_flags, NULL);
4310     ctx.may_learn = true;
4311     xlate_actions_for_side_effects(&ctx, facet->rule->up.ofpacts,
4312                                    facet->rule->up.ofpacts_len);
4313 }
4314
4315 static void
4316 facet_account(struct facet *facet)
4317 {
4318     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4319     struct subfacet *subfacet;
4320     const struct nlattr *a;
4321     unsigned int left;
4322     ovs_be16 vlan_tci;
4323     uint64_t n_bytes;
4324
4325     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
4326         return;
4327     }
4328     n_bytes = facet->byte_count - facet->accounted_bytes;
4329
4330     /* This loop feeds byte counters to bond_account() for rebalancing to use
4331      * as a basis.  We also need to track the actual VLAN on which the packet
4332      * is going to be sent to ensure that it matches the one passed to
4333      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
4334      * hash bucket.)
4335      *
4336      * We use the actions from an arbitrary subfacet because they should all
4337      * be equally valid for our purpose. */
4338     subfacet = CONTAINER_OF(list_front(&facet->subfacets),
4339                             struct subfacet, list_node);
4340     vlan_tci = facet->flow.vlan_tci;
4341     NL_ATTR_FOR_EACH_UNSAFE (a, left,
4342                              subfacet->actions, subfacet->actions_len) {
4343         const struct ovs_action_push_vlan *vlan;
4344         struct ofport_dpif *port;
4345
4346         switch (nl_attr_type(a)) {
4347         case OVS_ACTION_ATTR_OUTPUT:
4348             port = get_odp_port(ofproto, nl_attr_get_u32(a));
4349             if (port && port->bundle && port->bundle->bond) {
4350                 bond_account(port->bundle->bond, &facet->flow,
4351                              vlan_tci_to_vid(vlan_tci), n_bytes);
4352             }
4353             break;
4354
4355         case OVS_ACTION_ATTR_POP_VLAN:
4356             vlan_tci = htons(0);
4357             break;
4358
4359         case OVS_ACTION_ATTR_PUSH_VLAN:
4360             vlan = nl_attr_get(a);
4361             vlan_tci = vlan->vlan_tci;
4362             break;
4363         }
4364     }
4365 }
4366
4367 /* Returns true if the only action for 'facet' is to send to the controller.
4368  * (We don't report NetFlow expiration messages for such facets because they
4369  * are just part of the control logic for the network, not real traffic). */
4370 static bool
4371 facet_is_controller_flow(struct facet *facet)
4372 {
4373     if (facet) {
4374         const struct rule *rule = &facet->rule->up;
4375         const struct ofpact *ofpacts = rule->ofpacts;
4376         size_t ofpacts_len = rule->ofpacts_len;
4377
4378         if (ofpacts_len > 0 &&
4379             ofpacts->type == OFPACT_CONTROLLER &&
4380             ofpact_next(ofpacts) >= ofpact_end(ofpacts, ofpacts_len)) {
4381             return true;
4382         }
4383     }
4384     return false;
4385 }
4386
4387 /* Folds all of 'facet''s statistics into its rule.  Also updates the
4388  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
4389  * 'facet''s statistics in the datapath should have been zeroed and folded into
4390  * its packet and byte counts before this function is called. */
4391 static void
4392 facet_flush_stats(struct facet *facet)
4393 {
4394     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4395     struct subfacet *subfacet;
4396
4397     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4398         ovs_assert(!subfacet->dp_byte_count);
4399         ovs_assert(!subfacet->dp_packet_count);
4400     }
4401
4402     facet_push_stats(facet);
4403     if (facet->accounted_bytes < facet->byte_count) {
4404         facet_account(facet);
4405         facet->accounted_bytes = facet->byte_count;
4406     }
4407
4408     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
4409         struct ofexpired expired;
4410         expired.flow = facet->flow;
4411         expired.packet_count = facet->packet_count;
4412         expired.byte_count = facet->byte_count;
4413         expired.used = facet->used;
4414         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
4415     }
4416
4417     facet->rule->packet_count += facet->packet_count;
4418     facet->rule->byte_count += facet->byte_count;
4419
4420     /* Reset counters to prevent double counting if 'facet' ever gets
4421      * reinstalled. */
4422     facet_reset_counters(facet);
4423
4424     netflow_flow_clear(&facet->nf_flow);
4425     facet->tcp_flags = 0;
4426 }
4427
4428 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
4429  * Returns it if found, otherwise a null pointer.
4430  *
4431  * 'hash' must be the return value of flow_hash(flow, 0).
4432  *
4433  * The returned facet might need revalidation; use facet_lookup_valid()
4434  * instead if that is important. */
4435 static struct facet *
4436 facet_find(struct ofproto_dpif *ofproto,
4437            const struct flow *flow, uint32_t hash)
4438 {
4439     struct facet *facet;
4440
4441     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, hash, &ofproto->facets) {
4442         if (flow_equal(flow, &facet->flow)) {
4443             return facet;
4444         }
4445     }
4446
4447     return NULL;
4448 }
4449
4450 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
4451  * Returns it if found, otherwise a null pointer.
4452  *
4453  * 'hash' must be the return value of flow_hash(flow, 0).
4454  *
4455  * The returned facet is guaranteed to be valid. */
4456 static struct facet *
4457 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow,
4458                    uint32_t hash)
4459 {
4460     struct facet *facet;
4461
4462     facet = facet_find(ofproto, flow, hash);
4463     if (facet
4464         && (ofproto->backer->need_revalidate
4465             || tag_set_intersects(&ofproto->backer->revalidate_set,
4466                                   facet->tags))) {
4467         facet_revalidate(facet);
4468     }
4469
4470     return facet;
4471 }
4472
4473 static const char *
4474 subfacet_path_to_string(enum subfacet_path path)
4475 {
4476     switch (path) {
4477     case SF_NOT_INSTALLED:
4478         return "not installed";
4479     case SF_FAST_PATH:
4480         return "in fast path";
4481     case SF_SLOW_PATH:
4482         return "in slow path";
4483     default:
4484         return "<error>";
4485     }
4486 }
4487
4488 /* Returns the path in which a subfacet should be installed if its 'slow'
4489  * member has the specified value. */
4490 static enum subfacet_path
4491 subfacet_want_path(enum slow_path_reason slow)
4492 {
4493     return slow ? SF_SLOW_PATH : SF_FAST_PATH;
4494 }
4495
4496 /* Returns true if 'subfacet' needs to have its datapath flow updated,
4497  * supposing that its actions have been recalculated as 'want_actions' and that
4498  * 'slow' is nonzero iff 'subfacet' should be in the slow path. */
4499 static bool
4500 subfacet_should_install(struct subfacet *subfacet, enum slow_path_reason slow,
4501                         const struct ofpbuf *want_actions)
4502 {
4503     enum subfacet_path want_path = subfacet_want_path(slow);
4504     return (want_path != subfacet->path
4505             || (want_path == SF_FAST_PATH
4506                 && (subfacet->actions_len != want_actions->size
4507                     || memcmp(subfacet->actions, want_actions->data,
4508                               subfacet->actions_len))));
4509 }
4510
4511 static bool
4512 facet_check_consistency(struct facet *facet)
4513 {
4514     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 15);
4515
4516     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4517
4518     uint64_t odp_actions_stub[1024 / 8];
4519     struct ofpbuf odp_actions;
4520
4521     struct rule_dpif *rule;
4522     struct subfacet *subfacet;
4523     bool may_log = false;
4524     bool ok;
4525
4526     /* Check the rule for consistency. */
4527     rule = rule_dpif_lookup(ofproto, &facet->flow);
4528     ok = rule == facet->rule;
4529     if (!ok) {
4530         may_log = !VLOG_DROP_WARN(&rl);
4531         if (may_log) {
4532             struct ds s;
4533
4534             ds_init(&s);
4535             flow_format(&s, &facet->flow);
4536             ds_put_format(&s, ": facet associated with wrong rule (was "
4537                           "table=%"PRIu8",", facet->rule->up.table_id);
4538             cls_rule_format(&facet->rule->up.cr, &s);
4539             ds_put_format(&s, ") (should have been table=%"PRIu8",",
4540                           rule->up.table_id);
4541             cls_rule_format(&rule->up.cr, &s);
4542             ds_put_char(&s, ')');
4543
4544             VLOG_WARN("%s", ds_cstr(&s));
4545             ds_destroy(&s);
4546         }
4547     }
4548
4549     /* Check the datapath actions for consistency. */
4550     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
4551     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4552         enum subfacet_path want_path;
4553         struct odputil_keybuf keybuf;
4554         struct action_xlate_ctx ctx;
4555         struct ofpbuf key;
4556         struct ds s;
4557
4558         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
4559                               subfacet->initial_tci, rule, 0, NULL);
4560         xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len,
4561                       &odp_actions);
4562
4563         if (subfacet->path == SF_NOT_INSTALLED) {
4564             /* This only happens if the datapath reported an error when we
4565              * tried to install the flow.  Don't flag another error here. */
4566             continue;
4567         }
4568
4569         want_path = subfacet_want_path(subfacet->slow);
4570         if (want_path == SF_SLOW_PATH && subfacet->path == SF_SLOW_PATH) {
4571             /* The actions for slow-path flows may legitimately vary from one
4572              * packet to the next.  We're done. */
4573             continue;
4574         }
4575
4576         if (!subfacet_should_install(subfacet, subfacet->slow, &odp_actions)) {
4577             continue;
4578         }
4579
4580         /* Inconsistency! */
4581         if (ok) {
4582             may_log = !VLOG_DROP_WARN(&rl);
4583             ok = false;
4584         }
4585         if (!may_log) {
4586             /* Rate-limited, skip reporting. */
4587             continue;
4588         }
4589
4590         ds_init(&s);
4591         subfacet_get_key(subfacet, &keybuf, &key);
4592         odp_flow_key_format(key.data, key.size, &s);
4593
4594         ds_put_cstr(&s, ": inconsistency in subfacet");
4595         if (want_path != subfacet->path) {
4596             enum odp_key_fitness fitness = subfacet->key_fitness;
4597
4598             ds_put_format(&s, " (%s, fitness=%s)",
4599                           subfacet_path_to_string(subfacet->path),
4600                           odp_key_fitness_to_string(fitness));
4601             ds_put_format(&s, " (should have been %s)",
4602                           subfacet_path_to_string(want_path));
4603         } else if (want_path == SF_FAST_PATH) {
4604             ds_put_cstr(&s, " (actions were: ");
4605             format_odp_actions(&s, subfacet->actions,
4606                                subfacet->actions_len);
4607             ds_put_cstr(&s, ") (correct actions: ");
4608             format_odp_actions(&s, odp_actions.data, odp_actions.size);
4609             ds_put_char(&s, ')');
4610         } else {
4611             ds_put_cstr(&s, " (actions: ");
4612             format_odp_actions(&s, subfacet->actions,
4613                                subfacet->actions_len);
4614             ds_put_char(&s, ')');
4615         }
4616         VLOG_WARN("%s", ds_cstr(&s));
4617         ds_destroy(&s);
4618     }
4619     ofpbuf_uninit(&odp_actions);
4620
4621     return ok;
4622 }
4623
4624 /* Re-searches the classifier for 'facet':
4625  *
4626  *   - If the rule found is different from 'facet''s current rule, moves
4627  *     'facet' to the new rule and recompiles its actions.
4628  *
4629  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
4630  *     where it is and recompiles its actions anyway. */
4631 static void
4632 facet_revalidate(struct facet *facet)
4633 {
4634     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4635     struct actions {
4636         struct nlattr *odp_actions;
4637         size_t actions_len;
4638     };
4639     struct actions *new_actions;
4640
4641     struct action_xlate_ctx ctx;
4642     uint64_t odp_actions_stub[1024 / 8];
4643     struct ofpbuf odp_actions;
4644
4645     struct rule_dpif *new_rule;
4646     struct subfacet *subfacet;
4647     int i;
4648
4649     COVERAGE_INC(facet_revalidate);
4650
4651     new_rule = rule_dpif_lookup(ofproto, &facet->flow);
4652
4653     /* Calculate new datapath actions.
4654      *
4655      * We do not modify any 'facet' state yet, because we might need to, e.g.,
4656      * emit a NetFlow expiration and, if so, we need to have the old state
4657      * around to properly compose it. */
4658
4659     /* If the datapath actions changed or the installability changed,
4660      * then we need to talk to the datapath. */
4661     i = 0;
4662     new_actions = NULL;
4663     memset(&ctx, 0, sizeof ctx);
4664     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
4665     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4666         enum slow_path_reason slow;
4667
4668         action_xlate_ctx_init(&ctx, ofproto, &facet->flow,
4669                               subfacet->initial_tci, new_rule, 0, NULL);
4670         xlate_actions(&ctx, new_rule->up.ofpacts, new_rule->up.ofpacts_len,
4671                       &odp_actions);
4672
4673         slow = (subfacet->slow & SLOW_MATCH) | ctx.slow;
4674         if (subfacet_should_install(subfacet, slow, &odp_actions)) {
4675             struct dpif_flow_stats stats;
4676
4677             subfacet_install(subfacet,
4678                              odp_actions.data, odp_actions.size, &stats, slow);
4679             subfacet_update_stats(subfacet, &stats);
4680
4681             if (!new_actions) {
4682                 new_actions = xcalloc(list_size(&facet->subfacets),
4683                                       sizeof *new_actions);
4684             }
4685             new_actions[i].odp_actions = xmemdup(odp_actions.data,
4686                                                  odp_actions.size);
4687             new_actions[i].actions_len = odp_actions.size;
4688         }
4689
4690         i++;
4691     }
4692     ofpbuf_uninit(&odp_actions);
4693
4694     if (new_actions) {
4695         facet_flush_stats(facet);
4696     }
4697
4698     /* Update 'facet' now that we've taken care of all the old state. */
4699     facet->tags = ctx.tags;
4700     facet->nf_flow.output_iface = ctx.nf_output_iface;
4701     facet->has_learn = ctx.has_learn;
4702     facet->has_normal = ctx.has_normal;
4703     facet->has_fin_timeout = ctx.has_fin_timeout;
4704     facet->mirrors = ctx.mirrors;
4705
4706     i = 0;
4707     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
4708         subfacet->slow = (subfacet->slow & SLOW_MATCH) | ctx.slow;
4709
4710         if (new_actions && new_actions[i].odp_actions) {
4711             free(subfacet->actions);
4712             subfacet->actions = new_actions[i].odp_actions;
4713             subfacet->actions_len = new_actions[i].actions_len;
4714         }
4715         i++;
4716     }
4717     free(new_actions);
4718
4719     if (facet->rule != new_rule) {
4720         COVERAGE_INC(facet_changed_rule);
4721         list_remove(&facet->list_node);
4722         list_push_back(&new_rule->facets, &facet->list_node);
4723         facet->rule = new_rule;
4724         facet->used = new_rule->up.created;
4725         facet->prev_used = facet->used;
4726     }
4727 }
4728
4729 /* Updates 'facet''s used time.  Caller is responsible for calling
4730  * facet_push_stats() to update the flows which 'facet' resubmits into. */
4731 static void
4732 facet_update_time(struct facet *facet, long long int used)
4733 {
4734     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4735     if (used > facet->used) {
4736         facet->used = used;
4737         ofproto_rule_update_used(&facet->rule->up, used);
4738         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
4739     }
4740 }
4741
4742 static void
4743 facet_reset_counters(struct facet *facet)
4744 {
4745     facet->packet_count = 0;
4746     facet->byte_count = 0;
4747     facet->prev_packet_count = 0;
4748     facet->prev_byte_count = 0;
4749     facet->accounted_bytes = 0;
4750 }
4751
4752 static void
4753 facet_push_stats(struct facet *facet)
4754 {
4755     struct dpif_flow_stats stats;
4756
4757     ovs_assert(facet->packet_count >= facet->prev_packet_count);
4758     ovs_assert(facet->byte_count >= facet->prev_byte_count);
4759     ovs_assert(facet->used >= facet->prev_used);
4760
4761     stats.n_packets = facet->packet_count - facet->prev_packet_count;
4762     stats.n_bytes = facet->byte_count - facet->prev_byte_count;
4763     stats.used = facet->used;
4764     stats.tcp_flags = 0;
4765
4766     if (stats.n_packets || stats.n_bytes || facet->used > facet->prev_used) {
4767         facet->prev_packet_count = facet->packet_count;
4768         facet->prev_byte_count = facet->byte_count;
4769         facet->prev_used = facet->used;
4770
4771         flow_push_stats(facet->rule, &facet->flow, &stats);
4772
4773         update_mirror_stats(ofproto_dpif_cast(facet->rule->up.ofproto),
4774                             facet->mirrors, stats.n_packets, stats.n_bytes);
4775     }
4776 }
4777
4778 static void
4779 rule_credit_stats(struct rule_dpif *rule, const struct dpif_flow_stats *stats)
4780 {
4781     rule->packet_count += stats->n_packets;
4782     rule->byte_count += stats->n_bytes;
4783     ofproto_rule_update_used(&rule->up, stats->used);
4784 }
4785
4786 /* Pushes flow statistics to the rules which 'flow' resubmits into given
4787  * 'rule''s actions and mirrors. */
4788 static void
4789 flow_push_stats(struct rule_dpif *rule,
4790                 const struct flow *flow, const struct dpif_flow_stats *stats)
4791 {
4792     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4793     struct action_xlate_ctx ctx;
4794
4795     ofproto_rule_update_used(&rule->up, stats->used);
4796
4797     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, rule,
4798                           0, NULL);
4799     ctx.resubmit_stats = stats;
4800     xlate_actions_for_side_effects(&ctx, rule->up.ofpacts,
4801                                    rule->up.ofpacts_len);
4802 }
4803 \f
4804 /* Subfacets. */
4805
4806 static struct subfacet *
4807 subfacet_find(struct ofproto_dpif *ofproto,
4808               const struct nlattr *key, size_t key_len, uint32_t key_hash,
4809               const struct flow *flow)
4810 {
4811     struct subfacet *subfacet;
4812
4813     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
4814                              &ofproto->subfacets) {
4815         if (subfacet->key
4816             ? (subfacet->key_len == key_len
4817                && !memcmp(key, subfacet->key, key_len))
4818             : flow_equal(flow, &subfacet->facet->flow)) {
4819             return subfacet;
4820         }
4821     }
4822
4823     return NULL;
4824 }
4825
4826 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
4827  * 'key_fitness', 'key', and 'key_len' members in 'miss'.  Returns the
4828  * existing subfacet if there is one, otherwise creates and returns a
4829  * new subfacet.
4830  *
4831  * If the returned subfacet is new, then subfacet->actions will be NULL, in
4832  * which case the caller must populate the actions with
4833  * subfacet_make_actions(). */
4834 static struct subfacet *
4835 subfacet_create(struct facet *facet, struct flow_miss *miss,
4836                 long long int now)
4837 {
4838     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4839     enum odp_key_fitness key_fitness = miss->key_fitness;
4840     const struct nlattr *key = miss->key;
4841     size_t key_len = miss->key_len;
4842     uint32_t key_hash;
4843     struct subfacet *subfacet;
4844
4845     key_hash = odp_flow_key_hash(key, key_len);
4846
4847     if (list_is_empty(&facet->subfacets)) {
4848         subfacet = &facet->one_subfacet;
4849     } else {
4850         subfacet = subfacet_find(ofproto, key, key_len, key_hash,
4851                                  &facet->flow);
4852         if (subfacet) {
4853             if (subfacet->facet == facet) {
4854                 return subfacet;
4855             }
4856
4857             /* This shouldn't happen. */
4858             VLOG_ERR_RL(&rl, "subfacet with wrong facet");
4859             subfacet_destroy(subfacet);
4860         }
4861
4862         subfacet = xmalloc(sizeof *subfacet);
4863     }
4864
4865     hmap_insert(&ofproto->subfacets, &subfacet->hmap_node, key_hash);
4866     list_push_back(&facet->subfacets, &subfacet->list_node);
4867     subfacet->facet = facet;
4868     subfacet->key_fitness = key_fitness;
4869     if (key_fitness != ODP_FIT_PERFECT) {
4870         subfacet->key = xmemdup(key, key_len);
4871         subfacet->key_len = key_len;
4872     } else {
4873         subfacet->key = NULL;
4874         subfacet->key_len = 0;
4875     }
4876     subfacet->used = now;
4877     subfacet->dp_packet_count = 0;
4878     subfacet->dp_byte_count = 0;
4879     subfacet->actions_len = 0;
4880     subfacet->actions = NULL;
4881     subfacet->slow = (subfacet->key_fitness == ODP_FIT_TOO_LITTLE
4882                       ? SLOW_MATCH
4883                       : 0);
4884     subfacet->path = SF_NOT_INSTALLED;
4885     subfacet->initial_tci = miss->initial_tci;
4886     subfacet->odp_in_port = miss->odp_in_port;
4887
4888     return subfacet;
4889 }
4890
4891 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
4892  * its facet within 'ofproto', and frees it. */
4893 static void
4894 subfacet_destroy__(struct subfacet *subfacet)
4895 {
4896     struct facet *facet = subfacet->facet;
4897     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
4898
4899     subfacet_uninstall(subfacet);
4900     hmap_remove(&ofproto->subfacets, &subfacet->hmap_node);
4901     list_remove(&subfacet->list_node);
4902     free(subfacet->key);
4903     free(subfacet->actions);
4904     if (subfacet != &facet->one_subfacet) {
4905         free(subfacet);
4906     }
4907 }
4908
4909 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
4910  * last remaining subfacet in its facet destroys the facet too. */
4911 static void
4912 subfacet_destroy(struct subfacet *subfacet)
4913 {
4914     struct facet *facet = subfacet->facet;
4915
4916     if (list_is_singleton(&facet->subfacets)) {
4917         /* facet_remove() needs at least one subfacet (it will remove it). */
4918         facet_remove(facet);
4919     } else {
4920         subfacet_destroy__(subfacet);
4921     }
4922 }
4923
4924 static void
4925 subfacet_destroy_batch(struct ofproto_dpif *ofproto,
4926                        struct subfacet **subfacets, int n)
4927 {
4928     struct odputil_keybuf keybufs[SUBFACET_DESTROY_MAX_BATCH];
4929     struct dpif_op ops[SUBFACET_DESTROY_MAX_BATCH];
4930     struct dpif_op *opsp[SUBFACET_DESTROY_MAX_BATCH];
4931     struct ofpbuf keys[SUBFACET_DESTROY_MAX_BATCH];
4932     struct dpif_flow_stats stats[SUBFACET_DESTROY_MAX_BATCH];
4933     int i;
4934
4935     for (i = 0; i < n; i++) {
4936         ops[i].type = DPIF_OP_FLOW_DEL;
4937         subfacet_get_key(subfacets[i], &keybufs[i], &keys[i]);
4938         ops[i].u.flow_del.key = keys[i].data;
4939         ops[i].u.flow_del.key_len = keys[i].size;
4940         ops[i].u.flow_del.stats = &stats[i];
4941         opsp[i] = &ops[i];
4942     }
4943
4944     dpif_operate(ofproto->backer->dpif, opsp, n);
4945     for (i = 0; i < n; i++) {
4946         subfacet_reset_dp_stats(subfacets[i], &stats[i]);
4947         subfacets[i]->path = SF_NOT_INSTALLED;
4948         subfacet_destroy(subfacets[i]);
4949     }
4950 }
4951
4952 /* Initializes 'key' with the sequence of OVS_KEY_ATTR_* Netlink attributes
4953  * that can be used to refer to 'subfacet'.  The caller must provide 'keybuf'
4954  * for use as temporary storage. */
4955 static void
4956 subfacet_get_key(struct subfacet *subfacet, struct odputil_keybuf *keybuf,
4957                  struct ofpbuf *key)
4958 {
4959
4960     if (!subfacet->key) {
4961         struct flow *flow = &subfacet->facet->flow;
4962
4963         ofpbuf_use_stack(key, keybuf, sizeof *keybuf);
4964         odp_flow_key_from_flow(key, flow, subfacet->odp_in_port);
4965     } else {
4966         ofpbuf_use_const(key, subfacet->key, subfacet->key_len);
4967     }
4968 }
4969
4970 /* Composes the datapath actions for 'subfacet' based on its rule's actions.
4971  * Translates the actions into 'odp_actions', which the caller must have
4972  * initialized and is responsible for uninitializing. */
4973 static void
4974 subfacet_make_actions(struct subfacet *subfacet, const struct ofpbuf *packet,
4975                       struct ofpbuf *odp_actions)
4976 {
4977     struct facet *facet = subfacet->facet;
4978     struct rule_dpif *rule = facet->rule;
4979     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
4980
4981     struct action_xlate_ctx ctx;
4982
4983     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, subfacet->initial_tci,
4984                           rule, 0, packet);
4985     xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len, odp_actions);
4986     facet->tags = ctx.tags;
4987     facet->has_learn = ctx.has_learn;
4988     facet->has_normal = ctx.has_normal;
4989     facet->has_fin_timeout = ctx.has_fin_timeout;
4990     facet->nf_flow.output_iface = ctx.nf_output_iface;
4991     facet->mirrors = ctx.mirrors;
4992
4993     subfacet->slow = (subfacet->slow & SLOW_MATCH) | ctx.slow;
4994     if (subfacet->actions_len != odp_actions->size
4995         || memcmp(subfacet->actions, odp_actions->data, odp_actions->size)) {
4996         free(subfacet->actions);
4997         subfacet->actions_len = odp_actions->size;
4998         subfacet->actions = xmemdup(odp_actions->data, odp_actions->size);
4999     }
5000 }
5001
5002 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
5003  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
5004  * in the datapath will be zeroed and 'stats' will be updated with traffic new
5005  * since 'subfacet' was last updated.
5006  *
5007  * Returns 0 if successful, otherwise a positive errno value. */
5008 static int
5009 subfacet_install(struct subfacet *subfacet,
5010                  const struct nlattr *actions, size_t actions_len,
5011                  struct dpif_flow_stats *stats,
5012                  enum slow_path_reason slow)
5013 {
5014     struct facet *facet = subfacet->facet;
5015     struct ofproto_dpif *ofproto = ofproto_dpif_cast(facet->rule->up.ofproto);
5016     enum subfacet_path path = subfacet_want_path(slow);
5017     uint64_t slow_path_stub[128 / 8];
5018     struct odputil_keybuf keybuf;
5019     enum dpif_flow_put_flags flags;
5020     struct ofpbuf key;
5021     int ret;
5022
5023     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
5024     if (stats) {
5025         flags |= DPIF_FP_ZERO_STATS;
5026     }
5027
5028     if (path == SF_SLOW_PATH) {
5029         compose_slow_path(ofproto, &facet->flow, slow,
5030                           slow_path_stub, sizeof slow_path_stub,
5031                           &actions, &actions_len);
5032     }
5033
5034     subfacet_get_key(subfacet, &keybuf, &key);
5035     ret = dpif_flow_put(ofproto->backer->dpif, flags, key.data, key.size,
5036                         actions, actions_len, stats);
5037
5038     if (stats) {
5039         subfacet_reset_dp_stats(subfacet, stats);
5040     }
5041
5042     if (!ret) {
5043         subfacet->path = path;
5044     }
5045     return ret;
5046 }
5047
5048 static int
5049 subfacet_reinstall(struct subfacet *subfacet, struct dpif_flow_stats *stats)
5050 {
5051     return subfacet_install(subfacet, subfacet->actions, subfacet->actions_len,
5052                             stats, subfacet->slow);
5053 }
5054
5055 /* If 'subfacet' is installed in the datapath, uninstalls it. */
5056 static void
5057 subfacet_uninstall(struct subfacet *subfacet)
5058 {
5059     if (subfacet->path != SF_NOT_INSTALLED) {
5060         struct rule_dpif *rule = subfacet->facet->rule;
5061         struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5062         struct odputil_keybuf keybuf;
5063         struct dpif_flow_stats stats;
5064         struct ofpbuf key;
5065         int error;
5066
5067         subfacet_get_key(subfacet, &keybuf, &key);
5068         error = dpif_flow_del(ofproto->backer->dpif,
5069                               key.data, key.size, &stats);
5070         subfacet_reset_dp_stats(subfacet, &stats);
5071         if (!error) {
5072             subfacet_update_stats(subfacet, &stats);
5073         }
5074         subfacet->path = SF_NOT_INSTALLED;
5075     } else {
5076         ovs_assert(subfacet->dp_packet_count == 0);
5077         ovs_assert(subfacet->dp_byte_count == 0);
5078     }
5079 }
5080
5081 /* Resets 'subfacet''s datapath statistics counters.  This should be called
5082  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
5083  * non-null, it should contain the statistics returned by dpif when 'subfacet'
5084  * was reset in the datapath.  'stats' will be modified to include only
5085  * statistics new since 'subfacet' was last updated. */
5086 static void
5087 subfacet_reset_dp_stats(struct subfacet *subfacet,
5088                         struct dpif_flow_stats *stats)
5089 {
5090     if (stats
5091         && subfacet->dp_packet_count <= stats->n_packets
5092         && subfacet->dp_byte_count <= stats->n_bytes) {
5093         stats->n_packets -= subfacet->dp_packet_count;
5094         stats->n_bytes -= subfacet->dp_byte_count;
5095     }
5096
5097     subfacet->dp_packet_count = 0;
5098     subfacet->dp_byte_count = 0;
5099 }
5100
5101 /* Updates 'subfacet''s used time.  The caller is responsible for calling
5102  * facet_push_stats() to update the flows which 'subfacet' resubmits into. */
5103 static void
5104 subfacet_update_time(struct subfacet *subfacet, long long int used)
5105 {
5106     if (used > subfacet->used) {
5107         subfacet->used = used;
5108         facet_update_time(subfacet->facet, used);
5109     }
5110 }
5111
5112 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
5113  *
5114  * Because of the meaning of a subfacet's counters, it only makes sense to do
5115  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
5116  * represents a packet that was sent by hand or if it represents statistics
5117  * that have been cleared out of the datapath. */
5118 static void
5119 subfacet_update_stats(struct subfacet *subfacet,
5120                       const struct dpif_flow_stats *stats)
5121 {
5122     if (stats->n_packets || stats->used > subfacet->used) {
5123         struct facet *facet = subfacet->facet;
5124
5125         subfacet_update_time(subfacet, stats->used);
5126         facet->packet_count += stats->n_packets;
5127         facet->byte_count += stats->n_bytes;
5128         facet->tcp_flags |= stats->tcp_flags;
5129         facet_push_stats(facet);
5130         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
5131     }
5132 }
5133 \f
5134 /* Rules. */
5135
5136 static struct rule_dpif *
5137 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow)
5138 {
5139     struct rule_dpif *rule;
5140
5141     rule = rule_dpif_lookup__(ofproto, flow, 0);
5142     if (rule) {
5143         return rule;
5144     }
5145
5146     return rule_dpif_miss_rule(ofproto, flow);
5147 }
5148
5149 static struct rule_dpif *
5150 rule_dpif_lookup__(struct ofproto_dpif *ofproto, const struct flow *flow,
5151                    uint8_t table_id)
5152 {
5153     struct cls_rule *cls_rule;
5154     struct classifier *cls;
5155
5156     if (table_id >= N_TABLES) {
5157         return NULL;
5158     }
5159
5160     cls = &ofproto->up.tables[table_id].cls;
5161     if (flow->nw_frag & FLOW_NW_FRAG_ANY
5162         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
5163         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
5164          * are unavailable. */
5165         struct flow ofpc_normal_flow = *flow;
5166         ofpc_normal_flow.tp_src = htons(0);
5167         ofpc_normal_flow.tp_dst = htons(0);
5168         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
5169     } else {
5170         cls_rule = classifier_lookup(cls, flow);
5171     }
5172     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
5173 }
5174
5175 static struct rule_dpif *
5176 rule_dpif_miss_rule(struct ofproto_dpif *ofproto, const struct flow *flow)
5177 {
5178     struct ofport_dpif *port;
5179
5180     port = get_ofp_port(ofproto, flow->in_port);
5181     if (!port) {
5182         VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16, flow->in_port);
5183         return ofproto->miss_rule;
5184     }
5185
5186     if (port->up.pp.config & OFPUTIL_PC_NO_PACKET_IN) {
5187         return ofproto->no_packet_in_rule;
5188     }
5189     return ofproto->miss_rule;
5190 }
5191
5192 static void
5193 complete_operation(struct rule_dpif *rule)
5194 {
5195     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5196
5197     rule_invalidate(rule);
5198     if (clogged) {
5199         struct dpif_completion *c = xmalloc(sizeof *c);
5200         c->op = rule->up.pending;
5201         list_push_back(&ofproto->completions, &c->list_node);
5202     } else {
5203         ofoperation_complete(rule->up.pending, 0);
5204     }
5205 }
5206
5207 static struct rule *
5208 rule_alloc(void)
5209 {
5210     struct rule_dpif *rule = xmalloc(sizeof *rule);
5211     return &rule->up;
5212 }
5213
5214 static void
5215 rule_dealloc(struct rule *rule_)
5216 {
5217     struct rule_dpif *rule = rule_dpif_cast(rule_);
5218     free(rule);
5219 }
5220
5221 static enum ofperr
5222 rule_construct(struct rule *rule_)
5223 {
5224     struct rule_dpif *rule = rule_dpif_cast(rule_);
5225     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5226     struct rule_dpif *victim;
5227     uint8_t table_id;
5228
5229     rule->packet_count = 0;
5230     rule->byte_count = 0;
5231
5232     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
5233     if (victim && !list_is_empty(&victim->facets)) {
5234         struct facet *facet;
5235
5236         rule->facets = victim->facets;
5237         list_moved(&rule->facets);
5238         LIST_FOR_EACH (facet, list_node, &rule->facets) {
5239             /* XXX: We're only clearing our local counters here.  It's possible
5240              * that quite a few packets are unaccounted for in the datapath
5241              * statistics.  These will be accounted to the new rule instead of
5242              * cleared as required.  This could be fixed by clearing out the
5243              * datapath statistics for this facet, but currently it doesn't
5244              * seem worth it. */
5245             facet_reset_counters(facet);
5246             facet->rule = rule;
5247         }
5248     } else {
5249         /* Must avoid list_moved() in this case. */
5250         list_init(&rule->facets);
5251     }
5252
5253     table_id = rule->up.table_id;
5254     if (victim) {
5255         rule->tag = victim->tag;
5256     } else if (table_id == 0) {
5257         rule->tag = 0;
5258     } else {
5259         struct flow flow;
5260
5261         miniflow_expand(&rule->up.cr.match.flow, &flow);
5262         rule->tag = rule_calculate_tag(&flow, &rule->up.cr.match.mask,
5263                                        ofproto->tables[table_id].basis);
5264     }
5265
5266     complete_operation(rule);
5267     return 0;
5268 }
5269
5270 static void
5271 rule_destruct(struct rule *rule_)
5272 {
5273     struct rule_dpif *rule = rule_dpif_cast(rule_);
5274     struct facet *facet, *next_facet;
5275
5276     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
5277         facet_revalidate(facet);
5278     }
5279
5280     complete_operation(rule);
5281 }
5282
5283 static void
5284 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
5285 {
5286     struct rule_dpif *rule = rule_dpif_cast(rule_);
5287     struct facet *facet;
5288
5289     /* Start from historical data for 'rule' itself that are no longer tracked
5290      * in facets.  This counts, for example, facets that have expired. */
5291     *packets = rule->packet_count;
5292     *bytes = rule->byte_count;
5293
5294     /* Add any statistics that are tracked by facets.  This includes
5295      * statistical data recently updated by ofproto_update_stats() as well as
5296      * stats for packets that were executed "by hand" via dpif_execute(). */
5297     LIST_FOR_EACH (facet, list_node, &rule->facets) {
5298         *packets += facet->packet_count;
5299         *bytes += facet->byte_count;
5300     }
5301 }
5302
5303 static void
5304 rule_dpif_execute(struct rule_dpif *rule, const struct flow *flow,
5305                   struct ofpbuf *packet)
5306 {
5307     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5308
5309     struct dpif_flow_stats stats;
5310
5311     struct action_xlate_ctx ctx;
5312     uint64_t odp_actions_stub[1024 / 8];
5313     struct ofpbuf odp_actions;
5314
5315     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
5316     rule_credit_stats(rule, &stats);
5317
5318     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
5319     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci,
5320                           rule, stats.tcp_flags, packet);
5321     ctx.resubmit_stats = &stats;
5322     xlate_actions(&ctx, rule->up.ofpacts, rule->up.ofpacts_len, &odp_actions);
5323
5324     execute_odp_actions(ofproto, flow, odp_actions.data,
5325                         odp_actions.size, packet);
5326
5327     ofpbuf_uninit(&odp_actions);
5328 }
5329
5330 static enum ofperr
5331 rule_execute(struct rule *rule, const struct flow *flow,
5332              struct ofpbuf *packet)
5333 {
5334     rule_dpif_execute(rule_dpif_cast(rule), flow, packet);
5335     ofpbuf_delete(packet);
5336     return 0;
5337 }
5338
5339 static void
5340 rule_modify_actions(struct rule *rule_)
5341 {
5342     struct rule_dpif *rule = rule_dpif_cast(rule_);
5343
5344     complete_operation(rule);
5345 }
5346 \f
5347 /* Sends 'packet' out 'ofport'.
5348  * May modify 'packet'.
5349  * Returns 0 if successful, otherwise a positive errno value. */
5350 static int
5351 send_packet(const struct ofport_dpif *ofport, struct ofpbuf *packet)
5352 {
5353     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5354     struct ofpbuf key, odp_actions;
5355     struct odputil_keybuf keybuf;
5356     uint32_t odp_port;
5357     struct flow flow;
5358     int error;
5359
5360     flow_extract(packet, 0, 0, NULL, OFPP_LOCAL, &flow);
5361     if (netdev_vport_is_patch(ofport->up.netdev)) {
5362         struct ofproto_dpif *peer_ofproto;
5363         struct dpif_flow_stats stats;
5364         struct ofport_dpif *peer;
5365         struct rule_dpif *rule;
5366
5367         peer = ofport_get_peer(ofport);
5368         if (!peer) {
5369             return ENODEV;
5370         }
5371
5372         dpif_flow_stats_extract(&flow, packet, time_msec(), &stats);
5373         netdev_vport_patch_inc_tx(ofport->up.netdev, &stats);
5374         netdev_vport_patch_inc_rx(peer->up.netdev, &stats);
5375
5376         flow.in_port = peer->up.ofp_port;
5377         peer_ofproto = ofproto_dpif_cast(peer->up.ofproto);
5378         rule = rule_dpif_lookup(peer_ofproto, &flow);
5379         rule_dpif_execute(rule, &flow, packet);
5380
5381         return 0;
5382     }
5383
5384     odp_port = vsp_realdev_to_vlandev(ofproto, ofport->odp_port,
5385                                       flow.vlan_tci);
5386     if (odp_port != ofport->odp_port) {
5387         eth_pop_vlan(packet);
5388         flow.vlan_tci = htons(0);
5389     }
5390
5391     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5392     odp_flow_key_from_flow(&key, &flow,
5393                            ofp_port_to_odp_port(ofproto, flow.in_port));
5394
5395     ofpbuf_init(&odp_actions, 32);
5396     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
5397
5398     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
5399     error = dpif_execute(ofproto->backer->dpif,
5400                          key.data, key.size,
5401                          odp_actions.data, odp_actions.size,
5402                          packet);
5403     ofpbuf_uninit(&odp_actions);
5404
5405     if (error) {
5406         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
5407                      ofproto->up.name, odp_port, strerror(error));
5408     }
5409     ofproto_update_local_port_stats(ofport->up.ofproto, packet->size, 0);
5410     return error;
5411 }
5412 \f
5413 /* OpenFlow to datapath action translation. */
5414
5415 static void do_xlate_actions(const struct ofpact *, size_t ofpacts_len,
5416                              struct action_xlate_ctx *);
5417 static void xlate_normal(struct action_xlate_ctx *);
5418
5419 /* Composes an ODP action for a "slow path" action for 'flow' within 'ofproto'.
5420  * The action will state 'slow' as the reason that the action is in the slow
5421  * path.  (This is purely informational: it allows a human viewing "ovs-dpctl
5422  * dump-flows" output to see why a flow is in the slow path.)
5423  *
5424  * The 'stub_size' bytes in 'stub' will be used to store the action.
5425  * 'stub_size' must be large enough for the action.
5426  *
5427  * The action and its size will be stored in '*actionsp' and '*actions_lenp',
5428  * respectively. */
5429 static void
5430 compose_slow_path(const struct ofproto_dpif *ofproto, const struct flow *flow,
5431                   enum slow_path_reason slow,
5432                   uint64_t *stub, size_t stub_size,
5433                   const struct nlattr **actionsp, size_t *actions_lenp)
5434 {
5435     union user_action_cookie cookie;
5436     struct ofpbuf buf;
5437
5438     cookie.type = USER_ACTION_COOKIE_SLOW_PATH;
5439     cookie.slow_path.unused = 0;
5440     cookie.slow_path.reason = slow;
5441
5442     ofpbuf_use_stack(&buf, stub, stub_size);
5443     if (slow & (SLOW_CFM | SLOW_LACP | SLOW_STP)) {
5444         uint32_t pid = dpif_port_get_pid(ofproto->backer->dpif, UINT32_MAX);
5445         odp_put_userspace_action(pid, &cookie, &buf);
5446     } else {
5447         put_userspace_action(ofproto, &buf, flow, &cookie);
5448     }
5449     *actionsp = buf.data;
5450     *actions_lenp = buf.size;
5451 }
5452
5453 static size_t
5454 put_userspace_action(const struct ofproto_dpif *ofproto,
5455                      struct ofpbuf *odp_actions,
5456                      const struct flow *flow,
5457                      const union user_action_cookie *cookie)
5458 {
5459     uint32_t pid;
5460
5461     pid = dpif_port_get_pid(ofproto->backer->dpif,
5462                             ofp_port_to_odp_port(ofproto, flow->in_port));
5463
5464     return odp_put_userspace_action(pid, cookie, odp_actions);
5465 }
5466
5467 static void
5468 compose_sflow_cookie(const struct ofproto_dpif *ofproto,
5469                      ovs_be16 vlan_tci, uint32_t odp_port,
5470                      unsigned int n_outputs, union user_action_cookie *cookie)
5471 {
5472     int ifindex;
5473
5474     cookie->type = USER_ACTION_COOKIE_SFLOW;
5475     cookie->sflow.vlan_tci = vlan_tci;
5476
5477     /* See http://www.sflow.org/sflow_version_5.txt (search for "Input/output
5478      * port information") for the interpretation of cookie->output. */
5479     switch (n_outputs) {
5480     case 0:
5481         /* 0x40000000 | 256 means "packet dropped for unknown reason". */
5482         cookie->sflow.output = 0x40000000 | 256;
5483         break;
5484
5485     case 1:
5486         ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
5487         if (ifindex) {
5488             cookie->sflow.output = ifindex;
5489             break;
5490         }
5491         /* Fall through. */
5492     default:
5493         /* 0x80000000 means "multiple output ports. */
5494         cookie->sflow.output = 0x80000000 | n_outputs;
5495         break;
5496     }
5497 }
5498
5499 /* Compose SAMPLE action for sFlow. */
5500 static size_t
5501 compose_sflow_action(const struct ofproto_dpif *ofproto,
5502                      struct ofpbuf *odp_actions,
5503                      const struct flow *flow,
5504                      uint32_t odp_port)
5505 {
5506     uint32_t probability;
5507     union user_action_cookie cookie;
5508     size_t sample_offset, actions_offset;
5509     int cookie_offset;
5510
5511     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
5512         return 0;
5513     }
5514
5515     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
5516
5517     /* Number of packets out of UINT_MAX to sample. */
5518     probability = dpif_sflow_get_probability(ofproto->sflow);
5519     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
5520
5521     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
5522     compose_sflow_cookie(ofproto, htons(0), odp_port,
5523                          odp_port == OVSP_NONE ? 0 : 1, &cookie);
5524     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
5525
5526     nl_msg_end_nested(odp_actions, actions_offset);
5527     nl_msg_end_nested(odp_actions, sample_offset);
5528     return cookie_offset;
5529 }
5530
5531 /* SAMPLE action must be first action in any given list of actions.
5532  * At this point we do not have all information required to build it. So try to
5533  * build sample action as complete as possible. */
5534 static void
5535 add_sflow_action(struct action_xlate_ctx *ctx)
5536 {
5537     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
5538                                                    ctx->odp_actions,
5539                                                    &ctx->flow, OVSP_NONE);
5540     ctx->sflow_odp_port = 0;
5541     ctx->sflow_n_outputs = 0;
5542 }
5543
5544 /* Fix SAMPLE action according to data collected while composing ODP actions.
5545  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
5546  * USERSPACE action's user-cookie which is required for sflow. */
5547 static void
5548 fix_sflow_action(struct action_xlate_ctx *ctx)
5549 {
5550     const struct flow *base = &ctx->base_flow;
5551     union user_action_cookie *cookie;
5552
5553     if (!ctx->user_cookie_offset) {
5554         return;
5555     }
5556
5557     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
5558                        sizeof(*cookie));
5559     ovs_assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
5560
5561     compose_sflow_cookie(ctx->ofproto, base->vlan_tci,
5562                          ctx->sflow_odp_port, ctx->sflow_n_outputs, cookie);
5563 }
5564
5565 static void
5566 compose_output_action__(struct action_xlate_ctx *ctx, uint16_t ofp_port,
5567                         bool check_stp)
5568 {
5569     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
5570     ovs_be16 flow_vlan_tci = ctx->flow.vlan_tci;
5571     uint8_t flow_nw_tos = ctx->flow.nw_tos;
5572     struct priority_to_dscp *pdscp;
5573     uint32_t out_port, odp_port;
5574
5575     /* If 'struct flow' gets additional metadata, we'll need to zero it out
5576      * before traversing a patch port. */
5577     BUILD_ASSERT_DECL(FLOW_WC_SEQ == 18);
5578
5579     if (!ofport) {
5580         xlate_report(ctx, "Nonexistent output port");
5581         return;
5582     } else if (ofport->up.pp.config & OFPUTIL_PC_NO_FWD) {
5583         xlate_report(ctx, "OFPPC_NO_FWD set, skipping output");
5584         return;
5585     } else if (check_stp && !stp_forward_in_state(ofport->stp_state)) {
5586         xlate_report(ctx, "STP not in forwarding state, skipping output");
5587         return;
5588     }
5589
5590     if (netdev_vport_is_patch(ofport->up.netdev)) {
5591         struct ofport_dpif *peer = ofport_get_peer(ofport);
5592         struct flow old_flow = ctx->flow;
5593         const struct ofproto_dpif *peer_ofproto;
5594
5595         if (!peer) {
5596             xlate_report(ctx, "Nonexistent patch port peer");
5597             return;
5598         }
5599
5600         peer_ofproto = ofproto_dpif_cast(peer->up.ofproto);
5601         if (peer_ofproto->backer != ctx->ofproto->backer) {
5602             xlate_report(ctx, "Patch port peer on a different datapath");
5603             return;
5604         }
5605
5606         ctx->ofproto = ofproto_dpif_cast(peer->up.ofproto);
5607         ctx->flow.in_port = peer->up.ofp_port;
5608         ctx->flow.metadata = htonll(0);
5609         memset(&ctx->flow.tunnel, 0, sizeof ctx->flow.tunnel);
5610         memset(ctx->flow.regs, 0, sizeof ctx->flow.regs);
5611         xlate_table_action(ctx, ctx->flow.in_port, 0, true);
5612         ctx->flow = old_flow;
5613         ctx->ofproto = ofproto_dpif_cast(ofport->up.ofproto);
5614
5615         if (ctx->resubmit_stats) {
5616             netdev_vport_patch_inc_tx(ofport->up.netdev, ctx->resubmit_stats);
5617             netdev_vport_patch_inc_rx(peer->up.netdev, ctx->resubmit_stats);
5618         }
5619
5620         return;
5621     }
5622
5623     pdscp = get_priority(ofport, ctx->flow.skb_priority);
5624     if (pdscp) {
5625         ctx->flow.nw_tos &= ~IP_DSCP_MASK;
5626         ctx->flow.nw_tos |= pdscp->dscp;
5627     }
5628
5629     odp_port = ofp_port_to_odp_port(ctx->ofproto, ofp_port);
5630     out_port = vsp_realdev_to_vlandev(ctx->ofproto, odp_port,
5631                                       ctx->flow.vlan_tci);
5632     if (out_port != odp_port) {
5633         ctx->flow.vlan_tci = htons(0);
5634     }
5635     commit_odp_actions(&ctx->flow, &ctx->base_flow, ctx->odp_actions);
5636     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, out_port);
5637
5638     ctx->sflow_odp_port = odp_port;
5639     ctx->sflow_n_outputs++;
5640     ctx->nf_output_iface = ofp_port;
5641     ctx->flow.vlan_tci = flow_vlan_tci;
5642     ctx->flow.nw_tos = flow_nw_tos;
5643 }
5644
5645 static void
5646 compose_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
5647 {
5648     compose_output_action__(ctx, ofp_port, true);
5649 }
5650
5651 static void
5652 xlate_table_action(struct action_xlate_ctx *ctx,
5653                    uint16_t in_port, uint8_t table_id, bool may_packet_in)
5654 {
5655     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
5656         struct ofproto_dpif *ofproto = ctx->ofproto;
5657         struct rule_dpif *rule;
5658         uint16_t old_in_port;
5659         uint8_t old_table_id;
5660
5661         old_table_id = ctx->table_id;
5662         ctx->table_id = table_id;
5663
5664         /* Look up a flow with 'in_port' as the input port. */
5665         old_in_port = ctx->flow.in_port;
5666         ctx->flow.in_port = in_port;
5667         rule = rule_dpif_lookup__(ofproto, &ctx->flow, table_id);
5668
5669         /* Tag the flow. */
5670         if (table_id > 0 && table_id < N_TABLES) {
5671             struct table_dpif *table = &ofproto->tables[table_id];
5672             if (table->other_table) {
5673                 ctx->tags |= (rule && rule->tag
5674                               ? rule->tag
5675                               : rule_calculate_tag(&ctx->flow,
5676                                                    &table->other_table->mask,
5677                                                    table->basis));
5678             }
5679         }
5680
5681         /* Restore the original input port.  Otherwise OFPP_NORMAL and
5682          * OFPP_IN_PORT will have surprising behavior. */
5683         ctx->flow.in_port = old_in_port;
5684
5685         if (ctx->resubmit_hook) {
5686             ctx->resubmit_hook(ctx, rule);
5687         }
5688
5689         if (rule == NULL && may_packet_in) {
5690             /* XXX
5691              * check if table configuration flags
5692              * OFPTC_TABLE_MISS_CONTROLLER, default.
5693              * OFPTC_TABLE_MISS_CONTINUE,
5694              * OFPTC_TABLE_MISS_DROP
5695              * When OF1.0, OFPTC_TABLE_MISS_CONTINUE is used. What to do?
5696              */
5697             rule = rule_dpif_miss_rule(ofproto, &ctx->flow);
5698         }
5699
5700         if (rule) {
5701             struct rule_dpif *old_rule = ctx->rule;
5702
5703             if (ctx->resubmit_stats) {
5704                 rule_credit_stats(rule, ctx->resubmit_stats);
5705             }
5706
5707             ctx->recurse++;
5708             ctx->rule = rule;
5709             do_xlate_actions(rule->up.ofpacts, rule->up.ofpacts_len, ctx);
5710             ctx->rule = old_rule;
5711             ctx->recurse--;
5712         }
5713
5714         ctx->table_id = old_table_id;
5715     } else {
5716         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
5717
5718         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
5719                     MAX_RESUBMIT_RECURSION);
5720         ctx->max_resubmit_trigger = true;
5721     }
5722 }
5723
5724 static void
5725 xlate_ofpact_resubmit(struct action_xlate_ctx *ctx,
5726                       const struct ofpact_resubmit *resubmit)
5727 {
5728     uint16_t in_port;
5729     uint8_t table_id;
5730
5731     in_port = resubmit->in_port;
5732     if (in_port == OFPP_IN_PORT) {
5733         in_port = ctx->flow.in_port;
5734     }
5735
5736     table_id = resubmit->table_id;
5737     if (table_id == 255) {
5738         table_id = ctx->table_id;
5739     }
5740
5741     xlate_table_action(ctx, in_port, table_id, false);
5742 }
5743
5744 static void
5745 flood_packets(struct action_xlate_ctx *ctx, bool all)
5746 {
5747     struct ofport_dpif *ofport;
5748
5749     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
5750         uint16_t ofp_port = ofport->up.ofp_port;
5751
5752         if (ofp_port == ctx->flow.in_port) {
5753             continue;
5754         }
5755
5756         if (all) {
5757             compose_output_action__(ctx, ofp_port, false);
5758         } else if (!(ofport->up.pp.config & OFPUTIL_PC_NO_FLOOD)) {
5759             compose_output_action(ctx, ofp_port);
5760         }
5761     }
5762
5763     ctx->nf_output_iface = NF_OUT_FLOOD;
5764 }
5765
5766 static void
5767 execute_controller_action(struct action_xlate_ctx *ctx, int len,
5768                           enum ofp_packet_in_reason reason,
5769                           uint16_t controller_id)
5770 {
5771     struct ofputil_packet_in pin;
5772     struct ofpbuf *packet;
5773
5774     ctx->slow |= SLOW_CONTROLLER;
5775     if (!ctx->packet) {
5776         return;
5777     }
5778
5779     packet = ofpbuf_clone(ctx->packet);
5780
5781     if (packet->l2 && packet->l3) {
5782         struct eth_header *eh;
5783
5784         eth_pop_vlan(packet);
5785         eh = packet->l2;
5786
5787         /* If the Ethernet type is less than ETH_TYPE_MIN, it's likely an 802.2
5788          * LLC frame.  Calculating the Ethernet type of these frames is more
5789          * trouble than seems appropriate for a simple assertion. */
5790         ovs_assert(ntohs(eh->eth_type) < ETH_TYPE_MIN
5791                    || eh->eth_type == ctx->flow.dl_type);
5792
5793         memcpy(eh->eth_src, ctx->flow.dl_src, sizeof eh->eth_src);
5794         memcpy(eh->eth_dst, ctx->flow.dl_dst, sizeof eh->eth_dst);
5795
5796         if (ctx->flow.vlan_tci & htons(VLAN_CFI)) {
5797             eth_push_vlan(packet, ctx->flow.vlan_tci);
5798         }
5799
5800         if (packet->l4) {
5801             if (ctx->flow.dl_type == htons(ETH_TYPE_IP)) {
5802                 packet_set_ipv4(packet, ctx->flow.nw_src, ctx->flow.nw_dst,
5803                                 ctx->flow.nw_tos, ctx->flow.nw_ttl);
5804             }
5805
5806             if (packet->l7) {
5807                 if (ctx->flow.nw_proto == IPPROTO_TCP) {
5808                     packet_set_tcp_port(packet, ctx->flow.tp_src,
5809                                         ctx->flow.tp_dst);
5810                 } else if (ctx->flow.nw_proto == IPPROTO_UDP) {
5811                     packet_set_udp_port(packet, ctx->flow.tp_src,
5812                                         ctx->flow.tp_dst);
5813                 }
5814             }
5815         }
5816     }
5817
5818     pin.packet = packet->data;
5819     pin.packet_len = packet->size;
5820     pin.reason = reason;
5821     pin.controller_id = controller_id;
5822     pin.table_id = ctx->table_id;
5823     pin.cookie = ctx->rule ? ctx->rule->up.flow_cookie : 0;
5824
5825     pin.send_len = len;
5826     flow_get_metadata(&ctx->flow, &pin.fmd);
5827
5828     connmgr_send_packet_in(ctx->ofproto->up.connmgr, &pin);
5829     ofpbuf_delete(packet);
5830 }
5831
5832 static bool
5833 compose_dec_ttl(struct action_xlate_ctx *ctx, struct ofpact_cnt_ids *ids)
5834 {
5835     if (ctx->flow.dl_type != htons(ETH_TYPE_IP) &&
5836         ctx->flow.dl_type != htons(ETH_TYPE_IPV6)) {
5837         return false;
5838     }
5839
5840     if (ctx->flow.nw_ttl > 1) {
5841         ctx->flow.nw_ttl--;
5842         return false;
5843     } else {
5844         size_t i;
5845
5846         for (i = 0; i < ids->n_controllers; i++) {
5847             execute_controller_action(ctx, UINT16_MAX, OFPR_INVALID_TTL,
5848                                       ids->cnt_ids[i]);
5849         }
5850
5851         /* Stop processing for current table. */
5852         return true;
5853     }
5854 }
5855
5856 static void
5857 xlate_output_action(struct action_xlate_ctx *ctx,
5858                     uint16_t port, uint16_t max_len, bool may_packet_in)
5859 {
5860     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
5861
5862     ctx->nf_output_iface = NF_OUT_DROP;
5863
5864     switch (port) {
5865     case OFPP_IN_PORT:
5866         compose_output_action(ctx, ctx->flow.in_port);
5867         break;
5868     case OFPP_TABLE:
5869         xlate_table_action(ctx, ctx->flow.in_port, 0, may_packet_in);
5870         break;
5871     case OFPP_NORMAL:
5872         xlate_normal(ctx);
5873         break;
5874     case OFPP_FLOOD:
5875         flood_packets(ctx,  false);
5876         break;
5877     case OFPP_ALL:
5878         flood_packets(ctx, true);
5879         break;
5880     case OFPP_CONTROLLER:
5881         execute_controller_action(ctx, max_len, OFPR_ACTION, 0);
5882         break;
5883     case OFPP_NONE:
5884         break;
5885     case OFPP_LOCAL:
5886     default:
5887         if (port != ctx->flow.in_port) {
5888             compose_output_action(ctx, port);
5889         } else {
5890             xlate_report(ctx, "skipping output to input port");
5891         }
5892         break;
5893     }
5894
5895     if (prev_nf_output_iface == NF_OUT_FLOOD) {
5896         ctx->nf_output_iface = NF_OUT_FLOOD;
5897     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
5898         ctx->nf_output_iface = prev_nf_output_iface;
5899     } else if (prev_nf_output_iface != NF_OUT_DROP &&
5900                ctx->nf_output_iface != NF_OUT_FLOOD) {
5901         ctx->nf_output_iface = NF_OUT_MULTI;
5902     }
5903 }
5904
5905 static void
5906 xlate_output_reg_action(struct action_xlate_ctx *ctx,
5907                         const struct ofpact_output_reg *or)
5908 {
5909     uint64_t port = mf_get_subfield(&or->src, &ctx->flow);
5910     if (port <= UINT16_MAX) {
5911         xlate_output_action(ctx, port, or->max_len, false);
5912     }
5913 }
5914
5915 static void
5916 xlate_enqueue_action(struct action_xlate_ctx *ctx,
5917                      const struct ofpact_enqueue *enqueue)
5918 {
5919     uint16_t ofp_port = enqueue->port;
5920     uint32_t queue_id = enqueue->queue;
5921     uint32_t flow_priority, priority;
5922     int error;
5923
5924     /* Translate queue to priority. */
5925     error = dpif_queue_to_priority(ctx->ofproto->backer->dpif,
5926                                    queue_id, &priority);
5927     if (error) {
5928         /* Fall back to ordinary output action. */
5929         xlate_output_action(ctx, enqueue->port, 0, false);
5930         return;
5931     }
5932
5933     /* Check output port. */
5934     if (ofp_port == OFPP_IN_PORT) {
5935         ofp_port = ctx->flow.in_port;
5936     } else if (ofp_port == ctx->flow.in_port) {
5937         return;
5938     }
5939
5940     /* Add datapath actions. */
5941     flow_priority = ctx->flow.skb_priority;
5942     ctx->flow.skb_priority = priority;
5943     compose_output_action(ctx, ofp_port);
5944     ctx->flow.skb_priority = flow_priority;
5945
5946     /* Update NetFlow output port. */
5947     if (ctx->nf_output_iface == NF_OUT_DROP) {
5948         ctx->nf_output_iface = ofp_port;
5949     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
5950         ctx->nf_output_iface = NF_OUT_MULTI;
5951     }
5952 }
5953
5954 static void
5955 xlate_set_queue_action(struct action_xlate_ctx *ctx, uint32_t queue_id)
5956 {
5957     uint32_t skb_priority;
5958
5959     if (!dpif_queue_to_priority(ctx->ofproto->backer->dpif,
5960                                 queue_id, &skb_priority)) {
5961         ctx->flow.skb_priority = skb_priority;
5962     } else {
5963         /* Couldn't translate queue to a priority.  Nothing to do.  A warning
5964          * has already been logged. */
5965     }
5966 }
5967
5968 struct xlate_reg_state {
5969     ovs_be16 vlan_tci;
5970     ovs_be64 tun_id;
5971 };
5972
5973 static void
5974 xlate_autopath(struct action_xlate_ctx *ctx,
5975                const struct ofpact_autopath *ap)
5976 {
5977     uint16_t ofp_port = ap->port;
5978     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
5979
5980     if (!port || !port->bundle) {
5981         ofp_port = OFPP_NONE;
5982     } else if (port->bundle->bond) {
5983         /* Autopath does not support VLAN hashing. */
5984         struct ofport_dpif *slave = bond_choose_output_slave(
5985             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
5986         if (slave) {
5987             ofp_port = slave->up.ofp_port;
5988         }
5989     }
5990     nxm_reg_load(&ap->dst, ofp_port, &ctx->flow);
5991 }
5992
5993 static bool
5994 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
5995 {
5996     struct ofproto_dpif *ofproto = ofproto_;
5997     struct ofport_dpif *port;
5998
5999     switch (ofp_port) {
6000     case OFPP_IN_PORT:
6001     case OFPP_TABLE:
6002     case OFPP_NORMAL:
6003     case OFPP_FLOOD:
6004     case OFPP_ALL:
6005     case OFPP_NONE:
6006         return true;
6007     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
6008         return false;
6009     default:
6010         port = get_ofp_port(ofproto, ofp_port);
6011         return port ? port->may_enable : false;
6012     }
6013 }
6014
6015 static void
6016 xlate_bundle_action(struct action_xlate_ctx *ctx,
6017                     const struct ofpact_bundle *bundle)
6018 {
6019     uint16_t port;
6020
6021     port = bundle_execute(bundle, &ctx->flow, slave_enabled_cb, ctx->ofproto);
6022     if (bundle->dst.field) {
6023         nxm_reg_load(&bundle->dst, port, &ctx->flow);
6024     } else {
6025         xlate_output_action(ctx, port, 0, false);
6026     }
6027 }
6028
6029 static void
6030 xlate_learn_action(struct action_xlate_ctx *ctx,
6031                    const struct ofpact_learn *learn)
6032 {
6033     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
6034     struct ofputil_flow_mod fm;
6035     uint64_t ofpacts_stub[1024 / 8];
6036     struct ofpbuf ofpacts;
6037     int error;
6038
6039     ofpbuf_use_stack(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
6040     learn_execute(learn, &ctx->flow, &fm, &ofpacts);
6041
6042     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
6043     if (error && !VLOG_DROP_WARN(&rl)) {
6044         VLOG_WARN("learning action failed to modify flow table (%s)",
6045                   ofperr_get_name(error));
6046     }
6047
6048     ofpbuf_uninit(&ofpacts);
6049 }
6050
6051 /* Reduces '*timeout' to no more than 'max'.  A value of zero in either case
6052  * means "infinite". */
6053 static void
6054 reduce_timeout(uint16_t max, uint16_t *timeout)
6055 {
6056     if (max && (!*timeout || *timeout > max)) {
6057         *timeout = max;
6058     }
6059 }
6060
6061 static void
6062 xlate_fin_timeout(struct action_xlate_ctx *ctx,
6063                   const struct ofpact_fin_timeout *oft)
6064 {
6065     if (ctx->tcp_flags & (TCP_FIN | TCP_RST) && ctx->rule) {
6066         struct rule_dpif *rule = ctx->rule;
6067
6068         reduce_timeout(oft->fin_idle_timeout, &rule->up.idle_timeout);
6069         reduce_timeout(oft->fin_hard_timeout, &rule->up.hard_timeout);
6070     }
6071 }
6072
6073 static bool
6074 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
6075 {
6076     if (port->up.pp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
6077                               ? OFPUTIL_PC_NO_RECV_STP
6078                               : OFPUTIL_PC_NO_RECV)) {
6079         return false;
6080     }
6081
6082     /* Only drop packets here if both forwarding and learning are
6083      * disabled.  If just learning is enabled, we need to have
6084      * OFPP_NORMAL and the learning action have a look at the packet
6085      * before we can drop it. */
6086     if (!stp_forward_in_state(port->stp_state)
6087             && !stp_learn_in_state(port->stp_state)) {
6088         return false;
6089     }
6090
6091     return true;
6092 }
6093
6094 static void
6095 do_xlate_actions(const struct ofpact *ofpacts, size_t ofpacts_len,
6096                  struct action_xlate_ctx *ctx)
6097 {
6098     const struct ofport_dpif *port;
6099     bool was_evictable = true;
6100     const struct ofpact *a;
6101
6102     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
6103     if (port && !may_receive(port, ctx)) {
6104         /* Drop this flow. */
6105         return;
6106     }
6107
6108     if (ctx->rule) {
6109         /* Don't let the rule we're working on get evicted underneath us. */
6110         was_evictable = ctx->rule->up.evictable;
6111         ctx->rule->up.evictable = false;
6112     }
6113     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
6114         struct ofpact_controller *controller;
6115         const struct ofpact_metadata *metadata;
6116
6117         if (ctx->exit) {
6118             break;
6119         }
6120
6121         switch (a->type) {
6122         case OFPACT_OUTPUT:
6123             xlate_output_action(ctx, ofpact_get_OUTPUT(a)->port,
6124                                 ofpact_get_OUTPUT(a)->max_len, true);
6125             break;
6126
6127         case OFPACT_CONTROLLER:
6128             controller = ofpact_get_CONTROLLER(a);
6129             execute_controller_action(ctx, controller->max_len,
6130                                       controller->reason,
6131                                       controller->controller_id);
6132             break;
6133
6134         case OFPACT_ENQUEUE:
6135             xlate_enqueue_action(ctx, ofpact_get_ENQUEUE(a));
6136             break;
6137
6138         case OFPACT_SET_VLAN_VID:
6139             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
6140             ctx->flow.vlan_tci |= (htons(ofpact_get_SET_VLAN_VID(a)->vlan_vid)
6141                                    | htons(VLAN_CFI));
6142             break;
6143
6144         case OFPACT_SET_VLAN_PCP:
6145             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
6146             ctx->flow.vlan_tci |= htons((ofpact_get_SET_VLAN_PCP(a)->vlan_pcp
6147                                          << VLAN_PCP_SHIFT)
6148                                         | VLAN_CFI);
6149             break;
6150
6151         case OFPACT_STRIP_VLAN:
6152             ctx->flow.vlan_tci = htons(0);
6153             break;
6154
6155         case OFPACT_PUSH_VLAN:
6156             /* XXX 802.1AD(QinQ) */
6157             ctx->flow.vlan_tci = htons(VLAN_CFI);
6158             break;
6159
6160         case OFPACT_SET_ETH_SRC:
6161             memcpy(ctx->flow.dl_src, ofpact_get_SET_ETH_SRC(a)->mac,
6162                    ETH_ADDR_LEN);
6163             break;
6164
6165         case OFPACT_SET_ETH_DST:
6166             memcpy(ctx->flow.dl_dst, ofpact_get_SET_ETH_DST(a)->mac,
6167                    ETH_ADDR_LEN);
6168             break;
6169
6170         case OFPACT_SET_IPV4_SRC:
6171             ctx->flow.nw_src = ofpact_get_SET_IPV4_SRC(a)->ipv4;
6172             break;
6173
6174         case OFPACT_SET_IPV4_DST:
6175             ctx->flow.nw_dst = ofpact_get_SET_IPV4_DST(a)->ipv4;
6176             break;
6177
6178         case OFPACT_SET_IPV4_DSCP:
6179             /* OpenFlow 1.0 only supports IPv4. */
6180             if (ctx->flow.dl_type == htons(ETH_TYPE_IP)) {
6181                 ctx->flow.nw_tos &= ~IP_DSCP_MASK;
6182                 ctx->flow.nw_tos |= ofpact_get_SET_IPV4_DSCP(a)->dscp;
6183             }
6184             break;
6185
6186         case OFPACT_SET_L4_SRC_PORT:
6187             ctx->flow.tp_src = htons(ofpact_get_SET_L4_SRC_PORT(a)->port);
6188             break;
6189
6190         case OFPACT_SET_L4_DST_PORT:
6191             ctx->flow.tp_dst = htons(ofpact_get_SET_L4_DST_PORT(a)->port);
6192             break;
6193
6194         case OFPACT_RESUBMIT:
6195             xlate_ofpact_resubmit(ctx, ofpact_get_RESUBMIT(a));
6196             break;
6197
6198         case OFPACT_SET_TUNNEL:
6199             ctx->flow.tunnel.tun_id = htonll(ofpact_get_SET_TUNNEL(a)->tun_id);
6200             break;
6201
6202         case OFPACT_SET_QUEUE:
6203             xlate_set_queue_action(ctx, ofpact_get_SET_QUEUE(a)->queue_id);
6204             break;
6205
6206         case OFPACT_POP_QUEUE:
6207             ctx->flow.skb_priority = ctx->orig_skb_priority;
6208             break;
6209
6210         case OFPACT_REG_MOVE:
6211             nxm_execute_reg_move(ofpact_get_REG_MOVE(a), &ctx->flow);
6212             break;
6213
6214         case OFPACT_REG_LOAD:
6215             nxm_execute_reg_load(ofpact_get_REG_LOAD(a), &ctx->flow);
6216             break;
6217
6218         case OFPACT_DEC_TTL:
6219             if (compose_dec_ttl(ctx, ofpact_get_DEC_TTL(a))) {
6220                 goto out;
6221             }
6222             break;
6223
6224         case OFPACT_NOTE:
6225             /* Nothing to do. */
6226             break;
6227
6228         case OFPACT_MULTIPATH:
6229             multipath_execute(ofpact_get_MULTIPATH(a), &ctx->flow);
6230             break;
6231
6232         case OFPACT_AUTOPATH:
6233             xlate_autopath(ctx, ofpact_get_AUTOPATH(a));
6234             break;
6235
6236         case OFPACT_BUNDLE:
6237             ctx->ofproto->has_bundle_action = true;
6238             xlate_bundle_action(ctx, ofpact_get_BUNDLE(a));
6239             break;
6240
6241         case OFPACT_OUTPUT_REG:
6242             xlate_output_reg_action(ctx, ofpact_get_OUTPUT_REG(a));
6243             break;
6244
6245         case OFPACT_LEARN:
6246             ctx->has_learn = true;
6247             if (ctx->may_learn) {
6248                 xlate_learn_action(ctx, ofpact_get_LEARN(a));
6249             }
6250             break;
6251
6252         case OFPACT_EXIT:
6253             ctx->exit = true;
6254             break;
6255
6256         case OFPACT_FIN_TIMEOUT:
6257             ctx->has_fin_timeout = true;
6258             xlate_fin_timeout(ctx, ofpact_get_FIN_TIMEOUT(a));
6259             break;
6260
6261         case OFPACT_CLEAR_ACTIONS:
6262             /* XXX
6263              * Nothing to do because writa-actions is not supported for now.
6264              * When writa-actions is supported, clear-actions also must
6265              * be supported at the same time.
6266              */
6267             break;
6268
6269         case OFPACT_WRITE_METADATA:
6270             metadata = ofpact_get_WRITE_METADATA(a);
6271             ctx->flow.metadata &= ~metadata->mask;
6272             ctx->flow.metadata |= metadata->metadata & metadata->mask;
6273             break;
6274
6275         case OFPACT_GOTO_TABLE: {
6276             /* XXX remove recursion */
6277             /* It is assumed that goto-table is last action */
6278             struct ofpact_goto_table *ogt = ofpact_get_GOTO_TABLE(a);
6279             ovs_assert(ctx->table_id < ogt->table_id);
6280             xlate_table_action(ctx, ctx->flow.in_port, ogt->table_id, true);
6281             break;
6282         }
6283         }
6284     }
6285
6286 out:
6287     /* We've let OFPP_NORMAL and the learning action look at the packet,
6288      * so drop it now if forwarding is disabled. */
6289     if (port && !stp_forward_in_state(port->stp_state)) {
6290         ofpbuf_clear(ctx->odp_actions);
6291         add_sflow_action(ctx);
6292     }
6293     if (ctx->rule) {
6294         ctx->rule->up.evictable = was_evictable;
6295     }
6296 }
6297
6298 static void
6299 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
6300                       struct ofproto_dpif *ofproto, const struct flow *flow,
6301                       ovs_be16 initial_tci, struct rule_dpif *rule,
6302                       uint8_t tcp_flags, const struct ofpbuf *packet)
6303 {
6304     ovs_be64 initial_tun_id = flow->tunnel.tun_id;
6305
6306     /* Flow initialization rules:
6307      * - 'base_flow' must match the kernel's view of the packet at the
6308      *   time that action processing starts.  'flow' represents any
6309      *   transformations we wish to make through actions.
6310      * - By default 'base_flow' and 'flow' are the same since the input
6311      *   packet matches the output before any actions are applied.
6312      * - When using VLAN splinters, 'base_flow''s VLAN is set to the value
6313      *   of the received packet as seen by the kernel.  If we later output
6314      *   to another device without any modifications this will cause us to
6315      *   insert a new tag since the original one was stripped off by the
6316      *   VLAN device.
6317      * - Tunnel 'flow' is largely cleared when transitioning between
6318      *   the input and output stages since it does not make sense to output
6319      *   a packet with the exact headers that it was received with (i.e.
6320      *   the destination IP is us).  The one exception is the tun_id, which
6321      *   is preserved to allow use in later resubmit lookups and loads into
6322      *   registers.
6323      * - Tunnel 'base_flow' is completely cleared since that is what the
6324      *   kernel does.  If we wish to maintain the original values an action
6325      *   needs to be generated. */
6326
6327     ctx->ofproto = ofproto;
6328     ctx->flow = *flow;
6329     memset(&ctx->flow.tunnel, 0, sizeof ctx->flow.tunnel);
6330     ctx->base_flow = ctx->flow;
6331     ctx->base_flow.vlan_tci = initial_tci;
6332     ctx->flow.tunnel.tun_id = initial_tun_id;
6333     ctx->rule = rule;
6334     ctx->packet = packet;
6335     ctx->may_learn = packet != NULL;
6336     ctx->tcp_flags = tcp_flags;
6337     ctx->resubmit_hook = NULL;
6338     ctx->report_hook = NULL;
6339     ctx->resubmit_stats = NULL;
6340 }
6341
6342 /* Translates the 'ofpacts_len' bytes of "struct ofpacts" starting at 'ofpacts'
6343  * into datapath actions in 'odp_actions', using 'ctx'. */
6344 static void
6345 xlate_actions(struct action_xlate_ctx *ctx,
6346               const struct ofpact *ofpacts, size_t ofpacts_len,
6347               struct ofpbuf *odp_actions)
6348 {
6349     /* Normally false.  Set to true if we ever hit MAX_RESUBMIT_RECURSION, so
6350      * that in the future we always keep a copy of the original flow for
6351      * tracing purposes. */
6352     static bool hit_resubmit_limit;
6353
6354     enum slow_path_reason special;
6355
6356     COVERAGE_INC(ofproto_dpif_xlate);
6357
6358     ofpbuf_clear(odp_actions);
6359     ofpbuf_reserve(odp_actions, NL_A_U32_SIZE);
6360
6361     ctx->odp_actions = odp_actions;
6362     ctx->tags = 0;
6363     ctx->slow = 0;
6364     ctx->has_learn = false;
6365     ctx->has_normal = false;
6366     ctx->has_fin_timeout = false;
6367     ctx->nf_output_iface = NF_OUT_DROP;
6368     ctx->mirrors = 0;
6369     ctx->recurse = 0;
6370     ctx->max_resubmit_trigger = false;
6371     ctx->orig_skb_priority = ctx->flow.skb_priority;
6372     ctx->table_id = 0;
6373     ctx->exit = false;
6374
6375     if (ctx->ofproto->has_mirrors || hit_resubmit_limit) {
6376         /* Do this conditionally because the copy is expensive enough that it
6377          * shows up in profiles.
6378          *
6379          * We keep orig_flow in 'ctx' only because I couldn't make GCC 4.4
6380          * believe that I wasn't using it without initializing it if I kept it
6381          * in a local variable. */
6382         ctx->orig_flow = ctx->flow;
6383     }
6384
6385     if (ctx->flow.nw_frag & FLOW_NW_FRAG_ANY) {
6386         switch (ctx->ofproto->up.frag_handling) {
6387         case OFPC_FRAG_NORMAL:
6388             /* We must pretend that transport ports are unavailable. */
6389             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
6390             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
6391             break;
6392
6393         case OFPC_FRAG_DROP:
6394             return;
6395
6396         case OFPC_FRAG_REASM:
6397             NOT_REACHED();
6398
6399         case OFPC_FRAG_NX_MATCH:
6400             /* Nothing to do. */
6401             break;
6402
6403         case OFPC_INVALID_TTL_TO_CONTROLLER:
6404             NOT_REACHED();
6405         }
6406     }
6407
6408     special = process_special(ctx->ofproto, &ctx->flow, ctx->packet);
6409     if (special) {
6410         ctx->slow |= special;
6411     } else {
6412         static struct vlog_rate_limit trace_rl = VLOG_RATE_LIMIT_INIT(1, 1);
6413         ovs_be16 initial_tci = ctx->base_flow.vlan_tci;
6414         uint32_t local_odp_port;
6415
6416         add_sflow_action(ctx);
6417         do_xlate_actions(ofpacts, ofpacts_len, ctx);
6418
6419         if (ctx->max_resubmit_trigger && !ctx->resubmit_hook) {
6420             if (!hit_resubmit_limit) {
6421                 /* We didn't record the original flow.  Make sure we do from
6422                  * now on. */
6423                 hit_resubmit_limit = true;
6424             } else if (!VLOG_DROP_ERR(&trace_rl)) {
6425                 struct ds ds = DS_EMPTY_INITIALIZER;
6426
6427                 ofproto_trace(ctx->ofproto, &ctx->orig_flow, ctx->packet,
6428                               initial_tci, &ds);
6429                 VLOG_ERR("Trace triggered by excessive resubmit "
6430                          "recursion:\n%s", ds_cstr(&ds));
6431                 ds_destroy(&ds);
6432             }
6433         }
6434
6435         local_odp_port = ofp_port_to_odp_port(ctx->ofproto, OFPP_LOCAL);
6436         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
6437                                      local_odp_port,
6438                                      ctx->odp_actions->data,
6439                                      ctx->odp_actions->size)) {
6440             ctx->slow |= SLOW_IN_BAND;
6441             if (ctx->packet
6442                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
6443                                        ctx->packet)) {
6444                 compose_output_action(ctx, OFPP_LOCAL);
6445             }
6446         }
6447         if (ctx->ofproto->has_mirrors) {
6448             add_mirror_actions(ctx, &ctx->orig_flow);
6449         }
6450         fix_sflow_action(ctx);
6451     }
6452 }
6453
6454 /* Translates the 'ofpacts_len' bytes of "struct ofpact"s starting at 'ofpacts'
6455  * into datapath actions, using 'ctx', and discards the datapath actions. */
6456 static void
6457 xlate_actions_for_side_effects(struct action_xlate_ctx *ctx,
6458                                const struct ofpact *ofpacts,
6459                                size_t ofpacts_len)
6460 {
6461     uint64_t odp_actions_stub[1024 / 8];
6462     struct ofpbuf odp_actions;
6463
6464     ofpbuf_use_stub(&odp_actions, odp_actions_stub, sizeof odp_actions_stub);
6465     xlate_actions(ctx, ofpacts, ofpacts_len, &odp_actions);
6466     ofpbuf_uninit(&odp_actions);
6467 }
6468
6469 static void
6470 xlate_report(struct action_xlate_ctx *ctx, const char *s)
6471 {
6472     if (ctx->report_hook) {
6473         ctx->report_hook(ctx, s);
6474     }
6475 }
6476 \f
6477 /* OFPP_NORMAL implementation. */
6478
6479 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
6480
6481 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
6482  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
6483  * the bundle on which the packet was received, returns the VLAN to which the
6484  * packet belongs.
6485  *
6486  * Both 'vid' and the return value are in the range 0...4095. */
6487 static uint16_t
6488 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
6489 {
6490     switch (in_bundle->vlan_mode) {
6491     case PORT_VLAN_ACCESS:
6492         return in_bundle->vlan;
6493         break;
6494
6495     case PORT_VLAN_TRUNK:
6496         return vid;
6497
6498     case PORT_VLAN_NATIVE_UNTAGGED:
6499     case PORT_VLAN_NATIVE_TAGGED:
6500         return vid ? vid : in_bundle->vlan;
6501
6502     default:
6503         NOT_REACHED();
6504     }
6505 }
6506
6507 /* Checks whether a packet with the given 'vid' may ingress on 'in_bundle'.
6508  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
6509  * a warning.
6510  *
6511  * 'vid' should be the VID obtained from the 802.1Q header that was received as
6512  * part of a packet (specify 0 if there was no 802.1Q header), in the range
6513  * 0...4095. */
6514 static bool
6515 input_vid_is_valid(uint16_t vid, struct ofbundle *in_bundle, bool warn)
6516 {
6517     /* Allow any VID on the OFPP_NONE port. */
6518     if (in_bundle == &ofpp_none_bundle) {
6519         return true;
6520     }
6521
6522     switch (in_bundle->vlan_mode) {
6523     case PORT_VLAN_ACCESS:
6524         if (vid) {
6525             if (warn) {
6526                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6527                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
6528                              "packet received on port %s configured as VLAN "
6529                              "%"PRIu16" access port",
6530                              in_bundle->ofproto->up.name, vid,
6531                              in_bundle->name, in_bundle->vlan);
6532             }
6533             return false;
6534         }
6535         return true;
6536
6537     case PORT_VLAN_NATIVE_UNTAGGED:
6538     case PORT_VLAN_NATIVE_TAGGED:
6539         if (!vid) {
6540             /* Port must always carry its native VLAN. */
6541             return true;
6542         }
6543         /* Fall through. */
6544     case PORT_VLAN_TRUNK:
6545         if (!ofbundle_includes_vlan(in_bundle, vid)) {
6546             if (warn) {
6547                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6548                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" packet "
6549                              "received on port %s not configured for trunking "
6550                              "VLAN %"PRIu16,
6551                              in_bundle->ofproto->up.name, vid,
6552                              in_bundle->name, vid);
6553             }
6554             return false;
6555         }
6556         return true;
6557
6558     default:
6559         NOT_REACHED();
6560     }
6561
6562 }
6563
6564 /* Given 'vlan', the VLAN that a packet belongs to, and
6565  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
6566  * that should be included in the 802.1Q header.  (If the return value is 0,
6567  * then the 802.1Q header should only be included in the packet if there is a
6568  * nonzero PCP.)
6569  *
6570  * Both 'vlan' and the return value are in the range 0...4095. */
6571 static uint16_t
6572 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
6573 {
6574     switch (out_bundle->vlan_mode) {
6575     case PORT_VLAN_ACCESS:
6576         return 0;
6577
6578     case PORT_VLAN_TRUNK:
6579     case PORT_VLAN_NATIVE_TAGGED:
6580         return vlan;
6581
6582     case PORT_VLAN_NATIVE_UNTAGGED:
6583         return vlan == out_bundle->vlan ? 0 : vlan;
6584
6585     default:
6586         NOT_REACHED();
6587     }
6588 }
6589
6590 static void
6591 output_normal(struct action_xlate_ctx *ctx, const struct ofbundle *out_bundle,
6592               uint16_t vlan)
6593 {
6594     struct ofport_dpif *port;
6595     uint16_t vid;
6596     ovs_be16 tci, old_tci;
6597
6598     vid = output_vlan_to_vid(out_bundle, vlan);
6599     if (!out_bundle->bond) {
6600         port = ofbundle_get_a_port(out_bundle);
6601     } else {
6602         port = bond_choose_output_slave(out_bundle->bond, &ctx->flow,
6603                                         vid, &ctx->tags);
6604         if (!port) {
6605             /* No slaves enabled, so drop packet. */
6606             return;
6607         }
6608     }
6609
6610     old_tci = ctx->flow.vlan_tci;
6611     tci = htons(vid);
6612     if (tci || out_bundle->use_priority_tags) {
6613         tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
6614         if (tci) {
6615             tci |= htons(VLAN_CFI);
6616         }
6617     }
6618     ctx->flow.vlan_tci = tci;
6619
6620     compose_output_action(ctx, port->up.ofp_port);
6621     ctx->flow.vlan_tci = old_tci;
6622 }
6623
6624 static int
6625 mirror_mask_ffs(mirror_mask_t mask)
6626 {
6627     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
6628     return ffs(mask);
6629 }
6630
6631 static bool
6632 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
6633 {
6634     return (bundle->vlan_mode != PORT_VLAN_ACCESS
6635             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
6636 }
6637
6638 static bool
6639 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
6640 {
6641     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
6642 }
6643
6644 /* Returns an arbitrary interface within 'bundle'. */
6645 static struct ofport_dpif *
6646 ofbundle_get_a_port(const struct ofbundle *bundle)
6647 {
6648     return CONTAINER_OF(list_front(&bundle->ports),
6649                         struct ofport_dpif, bundle_node);
6650 }
6651
6652 static bool
6653 vlan_is_mirrored(const struct ofmirror *m, int vlan)
6654 {
6655     return !m->vlans || bitmap_is_set(m->vlans, vlan);
6656 }
6657
6658 static void
6659 add_mirror_actions(struct action_xlate_ctx *ctx, const struct flow *orig_flow)
6660 {
6661     struct ofproto_dpif *ofproto = ctx->ofproto;
6662     mirror_mask_t mirrors;
6663     struct ofbundle *in_bundle;
6664     uint16_t vlan;
6665     uint16_t vid;
6666     const struct nlattr *a;
6667     size_t left;
6668
6669     in_bundle = lookup_input_bundle(ctx->ofproto, orig_flow->in_port,
6670                                     ctx->packet != NULL, NULL);
6671     if (!in_bundle) {
6672         return;
6673     }
6674     mirrors = in_bundle->src_mirrors;
6675
6676     /* Drop frames on bundles reserved for mirroring. */
6677     if (in_bundle->mirror_out) {
6678         if (ctx->packet != NULL) {
6679             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6680             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
6681                          "%s, which is reserved exclusively for mirroring",
6682                          ctx->ofproto->up.name, in_bundle->name);
6683         }
6684         return;
6685     }
6686
6687     /* Check VLAN. */
6688     vid = vlan_tci_to_vid(orig_flow->vlan_tci);
6689     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
6690         return;
6691     }
6692     vlan = input_vid_to_vlan(in_bundle, vid);
6693
6694     /* Look at the output ports to check for destination selections. */
6695
6696     NL_ATTR_FOR_EACH (a, left, ctx->odp_actions->data,
6697                       ctx->odp_actions->size) {
6698         enum ovs_action_attr type = nl_attr_type(a);
6699         struct ofport_dpif *ofport;
6700
6701         if (type != OVS_ACTION_ATTR_OUTPUT) {
6702             continue;
6703         }
6704
6705         ofport = get_odp_port(ofproto, nl_attr_get_u32(a));
6706         if (ofport && ofport->bundle) {
6707             mirrors |= ofport->bundle->dst_mirrors;
6708         }
6709     }
6710
6711     if (!mirrors) {
6712         return;
6713     }
6714
6715     /* Restore the original packet before adding the mirror actions. */
6716     ctx->flow = *orig_flow;
6717
6718     while (mirrors) {
6719         struct ofmirror *m;
6720
6721         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
6722
6723         if (!vlan_is_mirrored(m, vlan)) {
6724             mirrors = zero_rightmost_1bit(mirrors);
6725             continue;
6726         }
6727
6728         mirrors &= ~m->dup_mirrors;
6729         ctx->mirrors |= m->dup_mirrors;
6730         if (m->out) {
6731             output_normal(ctx, m->out, vlan);
6732         } else if (vlan != m->out_vlan
6733                    && !eth_addr_is_reserved(orig_flow->dl_dst)) {
6734             struct ofbundle *bundle;
6735
6736             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
6737                 if (ofbundle_includes_vlan(bundle, m->out_vlan)
6738                     && !bundle->mirror_out) {
6739                     output_normal(ctx, bundle, m->out_vlan);
6740                 }
6741             }
6742         }
6743     }
6744 }
6745
6746 static void
6747 update_mirror_stats(struct ofproto_dpif *ofproto, mirror_mask_t mirrors,
6748                     uint64_t packets, uint64_t bytes)
6749 {
6750     if (!mirrors) {
6751         return;
6752     }
6753
6754     for (; mirrors; mirrors = zero_rightmost_1bit(mirrors)) {
6755         struct ofmirror *m;
6756
6757         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
6758
6759         if (!m) {
6760             /* In normal circumstances 'm' will not be NULL.  However,
6761              * if mirrors are reconfigured, we can temporarily get out
6762              * of sync in facet_revalidate().  We could "correct" the
6763              * mirror list before reaching here, but doing that would
6764              * not properly account the traffic stats we've currently
6765              * accumulated for previous mirror configuration. */
6766             continue;
6767         }
6768
6769         m->packet_count += packets;
6770         m->byte_count += bytes;
6771     }
6772 }
6773
6774 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
6775  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
6776  * indicate this; newer upstream kernels use gratuitous ARP requests. */
6777 static bool
6778 is_gratuitous_arp(const struct flow *flow)
6779 {
6780     return (flow->dl_type == htons(ETH_TYPE_ARP)
6781             && eth_addr_is_broadcast(flow->dl_dst)
6782             && (flow->nw_proto == ARP_OP_REPLY
6783                 || (flow->nw_proto == ARP_OP_REQUEST
6784                     && flow->nw_src == flow->nw_dst)));
6785 }
6786
6787 static void
6788 update_learning_table(struct ofproto_dpif *ofproto,
6789                       const struct flow *flow, int vlan,
6790                       struct ofbundle *in_bundle)
6791 {
6792     struct mac_entry *mac;
6793
6794     /* Don't learn the OFPP_NONE port. */
6795     if (in_bundle == &ofpp_none_bundle) {
6796         return;
6797     }
6798
6799     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
6800         return;
6801     }
6802
6803     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
6804     if (is_gratuitous_arp(flow)) {
6805         /* We don't want to learn from gratuitous ARP packets that are
6806          * reflected back over bond slaves so we lock the learning table. */
6807         if (!in_bundle->bond) {
6808             mac_entry_set_grat_arp_lock(mac);
6809         } else if (mac_entry_is_grat_arp_locked(mac)) {
6810             return;
6811         }
6812     }
6813
6814     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
6815         /* The log messages here could actually be useful in debugging,
6816          * so keep the rate limit relatively high. */
6817         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
6818         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
6819                     "on port %s in VLAN %d",
6820                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
6821                     in_bundle->name, vlan);
6822
6823         mac->port.p = in_bundle;
6824         tag_set_add(&ofproto->backer->revalidate_set,
6825                     mac_learning_changed(ofproto->ml, mac));
6826     }
6827 }
6828
6829 static struct ofbundle *
6830 lookup_input_bundle(const struct ofproto_dpif *ofproto, uint16_t in_port,
6831                     bool warn, struct ofport_dpif **in_ofportp)
6832 {
6833     struct ofport_dpif *ofport;
6834
6835     /* Find the port and bundle for the received packet. */
6836     ofport = get_ofp_port(ofproto, in_port);
6837     if (in_ofportp) {
6838         *in_ofportp = ofport;
6839     }
6840     if (ofport && ofport->bundle) {
6841         return ofport->bundle;
6842     }
6843
6844     /* Special-case OFPP_NONE, which a controller may use as the ingress
6845      * port for traffic that it is sourcing. */
6846     if (in_port == OFPP_NONE) {
6847         return &ofpp_none_bundle;
6848     }
6849
6850     /* Odd.  A few possible reasons here:
6851      *
6852      * - We deleted a port but there are still a few packets queued up
6853      *   from it.
6854      *
6855      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
6856      *   we don't know about.
6857      *
6858      * - The ofproto client didn't configure the port as part of a bundle.
6859      *   This is particularly likely to happen if a packet was received on the
6860      *   port after it was created, but before the client had a chance to
6861      *   configure its bundle.
6862      */
6863     if (warn) {
6864         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6865
6866         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
6867                      "port %"PRIu16, ofproto->up.name, in_port);
6868     }
6869     return NULL;
6870 }
6871
6872 /* Determines whether packets in 'flow' within 'ofproto' should be forwarded or
6873  * dropped.  Returns true if they may be forwarded, false if they should be
6874  * dropped.
6875  *
6876  * 'in_port' must be the ofport_dpif that corresponds to flow->in_port.
6877  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
6878  *
6879  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
6880  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
6881  * checked by input_vid_is_valid().
6882  *
6883  * May also add tags to '*tags', although the current implementation only does
6884  * so in one special case.
6885  */
6886 static bool
6887 is_admissible(struct action_xlate_ctx *ctx, struct ofport_dpif *in_port,
6888               uint16_t vlan)
6889 {
6890     struct ofproto_dpif *ofproto = ctx->ofproto;
6891     struct flow *flow = &ctx->flow;
6892     struct ofbundle *in_bundle = in_port->bundle;
6893
6894     /* Drop frames for reserved multicast addresses
6895      * only if forward_bpdu option is absent. */
6896     if (!ofproto->up.forward_bpdu && eth_addr_is_reserved(flow->dl_dst)) {
6897         xlate_report(ctx, "packet has reserved destination MAC, dropping");
6898         return false;
6899     }
6900
6901     if (in_bundle->bond) {
6902         struct mac_entry *mac;
6903
6904         switch (bond_check_admissibility(in_bundle->bond, in_port,
6905                                          flow->dl_dst, &ctx->tags)) {
6906         case BV_ACCEPT:
6907             break;
6908
6909         case BV_DROP:
6910             xlate_report(ctx, "bonding refused admissibility, dropping");
6911             return false;
6912
6913         case BV_DROP_IF_MOVED:
6914             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
6915             if (mac && mac->port.p != in_bundle &&
6916                 (!is_gratuitous_arp(flow)
6917                  || mac_entry_is_grat_arp_locked(mac))) {
6918                 xlate_report(ctx, "SLB bond thinks this packet looped back, "
6919                             "dropping");
6920                 return false;
6921             }
6922             break;
6923         }
6924     }
6925
6926     return true;
6927 }
6928
6929 static void
6930 xlate_normal(struct action_xlate_ctx *ctx)
6931 {
6932     struct ofport_dpif *in_port;
6933     struct ofbundle *in_bundle;
6934     struct mac_entry *mac;
6935     uint16_t vlan;
6936     uint16_t vid;
6937
6938     ctx->has_normal = true;
6939
6940     in_bundle = lookup_input_bundle(ctx->ofproto, ctx->flow.in_port,
6941                                     ctx->packet != NULL, &in_port);
6942     if (!in_bundle) {
6943         xlate_report(ctx, "no input bundle, dropping");
6944         return;
6945     }
6946
6947     /* Drop malformed frames. */
6948     if (ctx->flow.dl_type == htons(ETH_TYPE_VLAN) &&
6949         !(ctx->flow.vlan_tci & htons(VLAN_CFI))) {
6950         if (ctx->packet != NULL) {
6951             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6952             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
6953                          "VLAN tag received on port %s",
6954                          ctx->ofproto->up.name, in_bundle->name);
6955         }
6956         xlate_report(ctx, "partial VLAN tag, dropping");
6957         return;
6958     }
6959
6960     /* Drop frames on bundles reserved for mirroring. */
6961     if (in_bundle->mirror_out) {
6962         if (ctx->packet != NULL) {
6963             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
6964             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
6965                          "%s, which is reserved exclusively for mirroring",
6966                          ctx->ofproto->up.name, in_bundle->name);
6967         }
6968         xlate_report(ctx, "input port is mirror output port, dropping");
6969         return;
6970     }
6971
6972     /* Check VLAN. */
6973     vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
6974     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
6975         xlate_report(ctx, "disallowed VLAN VID for this input port, dropping");
6976         return;
6977     }
6978     vlan = input_vid_to_vlan(in_bundle, vid);
6979
6980     /* Check other admissibility requirements. */
6981     if (in_port && !is_admissible(ctx, in_port, vlan)) {
6982         return;
6983     }
6984
6985     /* Learn source MAC. */
6986     if (ctx->may_learn) {
6987         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
6988     }
6989
6990     /* Determine output bundle. */
6991     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
6992                               &ctx->tags);
6993     if (mac) {
6994         if (mac->port.p != in_bundle) {
6995             xlate_report(ctx, "forwarding to learned port");
6996             output_normal(ctx, mac->port.p, vlan);
6997         } else {
6998             xlate_report(ctx, "learned port is input port, dropping");
6999         }
7000     } else {
7001         struct ofbundle *bundle;
7002
7003         xlate_report(ctx, "no learned MAC for destination, flooding");
7004         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
7005             if (bundle != in_bundle
7006                 && ofbundle_includes_vlan(bundle, vlan)
7007                 && bundle->floodable
7008                 && !bundle->mirror_out) {
7009                 output_normal(ctx, bundle, vlan);
7010             }
7011         }
7012         ctx->nf_output_iface = NF_OUT_FLOOD;
7013     }
7014 }
7015 \f
7016 /* Optimized flow revalidation.
7017  *
7018  * It's a difficult problem, in general, to tell which facets need to have
7019  * their actions recalculated whenever the OpenFlow flow table changes.  We
7020  * don't try to solve that general problem: for most kinds of OpenFlow flow
7021  * table changes, we recalculate the actions for every facet.  This is
7022  * relatively expensive, but it's good enough if the OpenFlow flow table
7023  * doesn't change very often.
7024  *
7025  * However, we can expect one particular kind of OpenFlow flow table change to
7026  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
7027  * of CPU on revalidating every facet whenever MAC learning modifies the flow
7028  * table, we add a special case that applies to flow tables in which every rule
7029  * has the same form (that is, the same wildcards), except that the table is
7030  * also allowed to have a single "catch-all" flow that matches all packets.  We
7031  * optimize this case by tagging all of the facets that resubmit into the table
7032  * and invalidating the same tag whenever a flow changes in that table.  The
7033  * end result is that we revalidate just the facets that need it (and sometimes
7034  * a few more, but not all of the facets or even all of the facets that
7035  * resubmit to the table modified by MAC learning). */
7036
7037 /* Calculates the tag to use for 'flow' and mask 'mask' when it is inserted
7038  * into an OpenFlow table with the given 'basis'. */
7039 static tag_type
7040 rule_calculate_tag(const struct flow *flow, const struct minimask *mask,
7041                    uint32_t secret)
7042 {
7043     if (minimask_is_catchall(mask)) {
7044         return 0;
7045     } else {
7046         uint32_t hash = flow_hash_in_minimask(flow, mask, secret);
7047         return tag_create_deterministic(hash);
7048     }
7049 }
7050
7051 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
7052  * taggability of that table.
7053  *
7054  * This function must be called after *each* change to a flow table.  If you
7055  * skip calling it on some changes then the pointer comparisons at the end can
7056  * be invalid if you get unlucky.  For example, if a flow removal causes a
7057  * cls_table to be destroyed and then a flow insertion causes a cls_table with
7058  * different wildcards to be created with the same address, then this function
7059  * will incorrectly skip revalidation. */
7060 static void
7061 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
7062 {
7063     struct table_dpif *table = &ofproto->tables[table_id];
7064     const struct oftable *oftable = &ofproto->up.tables[table_id];
7065     struct cls_table *catchall, *other;
7066     struct cls_table *t;
7067
7068     catchall = other = NULL;
7069
7070     switch (hmap_count(&oftable->cls.tables)) {
7071     case 0:
7072         /* We could tag this OpenFlow table but it would make the logic a
7073          * little harder and it's a corner case that doesn't seem worth it
7074          * yet. */
7075         break;
7076
7077     case 1:
7078     case 2:
7079         HMAP_FOR_EACH (t, hmap_node, &oftable->cls.tables) {
7080             if (cls_table_is_catchall(t)) {
7081                 catchall = t;
7082             } else if (!other) {
7083                 other = t;
7084             } else {
7085                 /* Indicate that we can't tag this by setting both tables to
7086                  * NULL.  (We know that 'catchall' is already NULL.) */
7087                 other = NULL;
7088             }
7089         }
7090         break;
7091
7092     default:
7093         /* Can't tag this table. */
7094         break;
7095     }
7096
7097     if (table->catchall_table != catchall || table->other_table != other) {
7098         table->catchall_table = catchall;
7099         table->other_table = other;
7100         ofproto->backer->need_revalidate = REV_FLOW_TABLE;
7101     }
7102 }
7103
7104 /* Given 'rule' that has changed in some way (either it is a rule being
7105  * inserted, a rule being deleted, or a rule whose actions are being
7106  * modified), marks facets for revalidation to ensure that packets will be
7107  * forwarded correctly according to the new state of the flow table.
7108  *
7109  * This function must be called after *each* change to a flow table.  See
7110  * the comment on table_update_taggable() for more information. */
7111 static void
7112 rule_invalidate(const struct rule_dpif *rule)
7113 {
7114     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
7115
7116     table_update_taggable(ofproto, rule->up.table_id);
7117
7118     if (!ofproto->backer->need_revalidate) {
7119         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
7120
7121         if (table->other_table && rule->tag) {
7122             tag_set_add(&ofproto->backer->revalidate_set, rule->tag);
7123         } else {
7124             ofproto->backer->need_revalidate = REV_FLOW_TABLE;
7125         }
7126     }
7127 }
7128 \f
7129 static bool
7130 set_frag_handling(struct ofproto *ofproto_,
7131                   enum ofp_config_flags frag_handling)
7132 {
7133     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7134     if (frag_handling != OFPC_FRAG_REASM) {
7135         ofproto->backer->need_revalidate = REV_RECONFIGURE;
7136         return true;
7137     } else {
7138         return false;
7139     }
7140 }
7141
7142 static enum ofperr
7143 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
7144            const struct flow *flow,
7145            const struct ofpact *ofpacts, size_t ofpacts_len)
7146 {
7147     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7148     struct odputil_keybuf keybuf;
7149     struct dpif_flow_stats stats;
7150
7151     struct ofpbuf key;
7152
7153     struct action_xlate_ctx ctx;
7154     uint64_t odp_actions_stub[1024 / 8];
7155     struct ofpbuf odp_actions;
7156
7157     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
7158     odp_flow_key_from_flow(&key, flow,
7159                            ofp_port_to_odp_port(ofproto, flow->in_port));
7160
7161     dpif_flow_stats_extract(flow, packet, time_msec(), &stats);
7162
7163     action_xlate_ctx_init(&ctx, ofproto, flow, flow->vlan_tci, NULL,
7164                           packet_get_tcp_flags(packet, flow), packet);
7165     ctx.resubmit_stats = &stats;
7166
7167     ofpbuf_use_stub(&odp_actions,
7168                     odp_actions_stub, sizeof odp_actions_stub);
7169     xlate_actions(&ctx, ofpacts, ofpacts_len, &odp_actions);
7170     dpif_execute(ofproto->backer->dpif, key.data, key.size,
7171                  odp_actions.data, odp_actions.size, packet);
7172     ofpbuf_uninit(&odp_actions);
7173
7174     return 0;
7175 }
7176 \f
7177 /* NetFlow. */
7178
7179 static int
7180 set_netflow(struct ofproto *ofproto_,
7181             const struct netflow_options *netflow_options)
7182 {
7183     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7184
7185     if (netflow_options) {
7186         if (!ofproto->netflow) {
7187             ofproto->netflow = netflow_create();
7188         }
7189         return netflow_set_options(ofproto->netflow, netflow_options);
7190     } else {
7191         netflow_destroy(ofproto->netflow);
7192         ofproto->netflow = NULL;
7193         return 0;
7194     }
7195 }
7196
7197 static void
7198 get_netflow_ids(const struct ofproto *ofproto_,
7199                 uint8_t *engine_type, uint8_t *engine_id)
7200 {
7201     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
7202
7203     dpif_get_netflow_ids(ofproto->backer->dpif, engine_type, engine_id);
7204 }
7205
7206 static void
7207 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
7208 {
7209     if (!facet_is_controller_flow(facet) &&
7210         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
7211         struct subfacet *subfacet;
7212         struct ofexpired expired;
7213
7214         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
7215             if (subfacet->path == SF_FAST_PATH) {
7216                 struct dpif_flow_stats stats;
7217
7218                 subfacet_reinstall(subfacet, &stats);
7219                 subfacet_update_stats(subfacet, &stats);
7220             }
7221         }
7222
7223         expired.flow = facet->flow;
7224         expired.packet_count = facet->packet_count;
7225         expired.byte_count = facet->byte_count;
7226         expired.used = facet->used;
7227         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
7228     }
7229 }
7230
7231 static void
7232 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
7233 {
7234     struct facet *facet;
7235
7236     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
7237         send_active_timeout(ofproto, facet);
7238     }
7239 }
7240 \f
7241 static struct ofproto_dpif *
7242 ofproto_dpif_lookup(const char *name)
7243 {
7244     struct ofproto_dpif *ofproto;
7245
7246     HMAP_FOR_EACH_WITH_HASH (ofproto, all_ofproto_dpifs_node,
7247                              hash_string(name, 0), &all_ofproto_dpifs) {
7248         if (!strcmp(ofproto->up.name, name)) {
7249             return ofproto;
7250         }
7251     }
7252     return NULL;
7253 }
7254
7255 static void
7256 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn, int argc,
7257                           const char *argv[], void *aux OVS_UNUSED)
7258 {
7259     struct ofproto_dpif *ofproto;
7260
7261     if (argc > 1) {
7262         ofproto = ofproto_dpif_lookup(argv[1]);
7263         if (!ofproto) {
7264             unixctl_command_reply_error(conn, "no such bridge");
7265             return;
7266         }
7267         mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
7268     } else {
7269         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
7270             mac_learning_flush(ofproto->ml, &ofproto->backer->revalidate_set);
7271         }
7272     }
7273
7274     unixctl_command_reply(conn, "table successfully flushed");
7275 }
7276
7277 static void
7278 ofproto_unixctl_fdb_show(struct unixctl_conn *conn, int argc OVS_UNUSED,
7279                          const char *argv[], void *aux OVS_UNUSED)
7280 {
7281     struct ds ds = DS_EMPTY_INITIALIZER;
7282     const struct ofproto_dpif *ofproto;
7283     const struct mac_entry *e;
7284
7285     ofproto = ofproto_dpif_lookup(argv[1]);
7286     if (!ofproto) {
7287         unixctl_command_reply_error(conn, "no such bridge");
7288         return;
7289     }
7290
7291     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
7292     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
7293         struct ofbundle *bundle = e->port.p;
7294         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
7295                       ofbundle_get_a_port(bundle)->odp_port,
7296                       e->vlan, ETH_ADDR_ARGS(e->mac),
7297                       mac_entry_age(ofproto->ml, e));
7298     }
7299     unixctl_command_reply(conn, ds_cstr(&ds));
7300     ds_destroy(&ds);
7301 }
7302
7303 struct trace_ctx {
7304     struct action_xlate_ctx ctx;
7305     struct flow flow;
7306     struct ds *result;
7307 };
7308
7309 static void
7310 trace_format_rule(struct ds *result, uint8_t table_id, int level,
7311                   const struct rule_dpif *rule)
7312 {
7313     ds_put_char_multiple(result, '\t', level);
7314     if (!rule) {
7315         ds_put_cstr(result, "No match\n");
7316         return;
7317     }
7318
7319     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
7320                   table_id, ntohll(rule->up.flow_cookie));
7321     cls_rule_format(&rule->up.cr, result);
7322     ds_put_char(result, '\n');
7323
7324     ds_put_char_multiple(result, '\t', level);
7325     ds_put_cstr(result, "OpenFlow ");
7326     ofpacts_format(rule->up.ofpacts, rule->up.ofpacts_len, result);
7327     ds_put_char(result, '\n');
7328 }
7329
7330 static void
7331 trace_format_flow(struct ds *result, int level, const char *title,
7332                  struct trace_ctx *trace)
7333 {
7334     ds_put_char_multiple(result, '\t', level);
7335     ds_put_format(result, "%s: ", title);
7336     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
7337         ds_put_cstr(result, "unchanged");
7338     } else {
7339         flow_format(result, &trace->ctx.flow);
7340         trace->flow = trace->ctx.flow;
7341     }
7342     ds_put_char(result, '\n');
7343 }
7344
7345 static void
7346 trace_format_regs(struct ds *result, int level, const char *title,
7347                   struct trace_ctx *trace)
7348 {
7349     size_t i;
7350
7351     ds_put_char_multiple(result, '\t', level);
7352     ds_put_format(result, "%s:", title);
7353     for (i = 0; i < FLOW_N_REGS; i++) {
7354         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
7355     }
7356     ds_put_char(result, '\n');
7357 }
7358
7359 static void
7360 trace_format_odp(struct ds *result, int level, const char *title,
7361                  struct trace_ctx *trace)
7362 {
7363     struct ofpbuf *odp_actions = trace->ctx.odp_actions;
7364
7365     ds_put_char_multiple(result, '\t', level);
7366     ds_put_format(result, "%s: ", title);
7367     format_odp_actions(result, odp_actions->data, odp_actions->size);
7368     ds_put_char(result, '\n');
7369 }
7370
7371 static void
7372 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
7373 {
7374     struct trace_ctx *trace = CONTAINER_OF(ctx, struct trace_ctx, ctx);
7375     struct ds *result = trace->result;
7376
7377     ds_put_char(result, '\n');
7378     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
7379     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
7380     trace_format_odp(result,  ctx->recurse + 1, "Resubmitted  odp", trace);
7381     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
7382 }
7383
7384 static void
7385 trace_report(struct action_xlate_ctx *ctx, const char *s)
7386 {
7387     struct trace_ctx *trace = CONTAINER_OF(ctx, struct trace_ctx, ctx);
7388     struct ds *result = trace->result;
7389
7390     ds_put_char_multiple(result, '\t', ctx->recurse);
7391     ds_put_cstr(result, s);
7392     ds_put_char(result, '\n');
7393 }
7394
7395 static void
7396 ofproto_unixctl_trace(struct unixctl_conn *conn, int argc, const char *argv[],
7397                       void *aux OVS_UNUSED)
7398 {
7399     const char *dpname = argv[1];
7400     struct ofproto_dpif *ofproto;
7401     struct ofpbuf odp_key;
7402     struct ofpbuf *packet;
7403     ovs_be16 initial_tci;
7404     struct ds result;
7405     struct flow flow;
7406     char *s;
7407
7408     packet = NULL;
7409     ofpbuf_init(&odp_key, 0);
7410     ds_init(&result);
7411
7412     ofproto = ofproto_dpif_lookup(dpname);
7413     if (!ofproto) {
7414         unixctl_command_reply_error(conn, "Unknown ofproto (use ofproto/list "
7415                                     "for help)");
7416         goto exit;
7417     }
7418     if (argc == 3 || (argc == 4 && !strcmp(argv[3], "-generate"))) {
7419         /* ofproto/trace dpname flow [-generate] */
7420         const char *flow_s = argv[2];
7421         const char *generate_s = argv[3];
7422
7423         /* Allow 'flow_s' to be either a datapath flow or an OpenFlow-like
7424          * flow.  We guess which type it is based on whether 'flow_s' contains
7425          * an '(', since a datapath flow always contains '(') but an
7426          * OpenFlow-like flow should not (in fact it's allowed but I believe
7427          * that's not documented anywhere).
7428          *
7429          * An alternative would be to try to parse 'flow_s' both ways, but then
7430          * it would be tricky giving a sensible error message.  After all, do
7431          * you just say "syntax error" or do you present both error messages?
7432          * Both choices seem lousy. */
7433         if (strchr(flow_s, '(')) {
7434             int error;
7435
7436             /* Convert string to datapath key. */
7437             ofpbuf_init(&odp_key, 0);
7438             error = odp_flow_key_from_string(flow_s, NULL, &odp_key);
7439             if (error) {
7440                 unixctl_command_reply_error(conn, "Bad flow syntax");
7441                 goto exit;
7442             }
7443
7444             /* XXX: Since we allow the user to specify an ofproto, it's
7445              * possible they will specify a different ofproto than the one the
7446              * port actually belongs too.  Ideally we should simply remove the
7447              * ability to specify the ofproto. */
7448             if (ofproto_receive(ofproto->backer, NULL, odp_key.data,
7449                                 odp_key.size, &flow, NULL, NULL, NULL,
7450                                 &initial_tci)) {
7451                 unixctl_command_reply_error(conn, "Invalid flow");
7452                 goto exit;
7453             }
7454         } else {
7455             char *error_s;
7456
7457             error_s = parse_ofp_exact_flow(&flow, argv[2]);
7458             if (error_s) {
7459                 unixctl_command_reply_error(conn, error_s);
7460                 free(error_s);
7461                 goto exit;
7462             }
7463
7464             initial_tci = flow.vlan_tci;
7465         }
7466
7467         /* Generate a packet, if requested. */
7468         if (generate_s) {
7469             packet = ofpbuf_new(0);
7470             flow_compose(packet, &flow);
7471         }
7472     } else if (argc == 7) {
7473         /* ofproto/trace dpname priority tun_id in_port mark packet */
7474         const char *priority_s = argv[2];
7475         const char *tun_id_s = argv[3];
7476         const char *in_port_s = argv[4];
7477         const char *mark_s = argv[5];
7478         const char *packet_s = argv[6];
7479         uint32_t in_port = atoi(in_port_s);
7480         ovs_be64 tun_id = htonll(strtoull(tun_id_s, NULL, 0));
7481         uint32_t priority = atoi(priority_s);
7482         uint32_t mark = atoi(mark_s);
7483         const char *msg;
7484
7485         msg = eth_from_hex(packet_s, &packet);
7486         if (msg) {
7487             unixctl_command_reply_error(conn, msg);
7488             goto exit;
7489         }
7490
7491         ds_put_cstr(&result, "Packet: ");
7492         s = ofp_packet_to_string(packet->data, packet->size);
7493         ds_put_cstr(&result, s);
7494         free(s);
7495
7496         flow_extract(packet, priority, mark, NULL, in_port, &flow);
7497         flow.tunnel.tun_id = tun_id;
7498         initial_tci = flow.vlan_tci;
7499     } else {
7500         unixctl_command_reply_error(conn, "Bad command syntax");
7501         goto exit;
7502     }
7503
7504     ofproto_trace(ofproto, &flow, packet, initial_tci, &result);
7505     unixctl_command_reply(conn, ds_cstr(&result));
7506
7507 exit:
7508     ds_destroy(&result);
7509     ofpbuf_delete(packet);
7510     ofpbuf_uninit(&odp_key);
7511 }
7512
7513 static void
7514 ofproto_trace(struct ofproto_dpif *ofproto, const struct flow *flow,
7515               const struct ofpbuf *packet, ovs_be16 initial_tci,
7516               struct ds *ds)
7517 {
7518     struct rule_dpif *rule;
7519
7520     ds_put_cstr(ds, "Flow: ");
7521     flow_format(ds, flow);
7522     ds_put_char(ds, '\n');
7523
7524     rule = rule_dpif_lookup(ofproto, flow);
7525
7526     trace_format_rule(ds, 0, 0, rule);
7527     if (rule == ofproto->miss_rule) {
7528         ds_put_cstr(ds, "\nNo match, flow generates \"packet in\"s.\n");
7529     } else if (rule == ofproto->no_packet_in_rule) {
7530         ds_put_cstr(ds, "\nNo match, packets dropped because "
7531                     "OFPPC_NO_PACKET_IN is set on in_port.\n");
7532     }
7533
7534     if (rule) {
7535         uint64_t odp_actions_stub[1024 / 8];
7536         struct ofpbuf odp_actions;
7537
7538         struct trace_ctx trace;
7539         uint8_t tcp_flags;
7540
7541         tcp_flags = packet ? packet_get_tcp_flags(packet, flow) : 0;
7542         trace.result = ds;
7543         trace.flow = *flow;
7544         ofpbuf_use_stub(&odp_actions,
7545                         odp_actions_stub, sizeof odp_actions_stub);
7546         action_xlate_ctx_init(&trace.ctx, ofproto, flow, initial_tci,
7547                               rule, tcp_flags, packet);
7548         trace.ctx.resubmit_hook = trace_resubmit;
7549         trace.ctx.report_hook = trace_report;
7550         xlate_actions(&trace.ctx, rule->up.ofpacts, rule->up.ofpacts_len,
7551                       &odp_actions);
7552
7553         ds_put_char(ds, '\n');
7554         trace_format_flow(ds, 0, "Final flow", &trace);
7555         ds_put_cstr(ds, "Datapath actions: ");
7556         format_odp_actions(ds, odp_actions.data, odp_actions.size);
7557         ofpbuf_uninit(&odp_actions);
7558
7559         if (trace.ctx.slow) {
7560             enum slow_path_reason slow;
7561
7562             ds_put_cstr(ds, "\nThis flow is handled by the userspace "
7563                         "slow path because it:");
7564             for (slow = trace.ctx.slow; slow; ) {
7565                 enum slow_path_reason bit = rightmost_1bit(slow);
7566
7567                 switch (bit) {
7568                 case SLOW_CFM:
7569                     ds_put_cstr(ds, "\n\t- Consists of CFM packets.");
7570                     break;
7571                 case SLOW_LACP:
7572                     ds_put_cstr(ds, "\n\t- Consists of LACP packets.");
7573                     break;
7574                 case SLOW_STP:
7575                     ds_put_cstr(ds, "\n\t- Consists of STP packets.");
7576                     break;
7577                 case SLOW_IN_BAND:
7578                     ds_put_cstr(ds, "\n\t- Needs in-band special case "
7579                                 "processing.");
7580                     if (!packet) {
7581                         ds_put_cstr(ds, "\n\t  (The datapath actions are "
7582                                     "incomplete--for complete actions, "
7583                                     "please supply a packet.)");
7584                     }
7585                     break;
7586                 case SLOW_CONTROLLER:
7587                     ds_put_cstr(ds, "\n\t- Sends \"packet-in\" messages "
7588                                 "to the OpenFlow controller.");
7589                     break;
7590                 case SLOW_MATCH:
7591                     ds_put_cstr(ds, "\n\t- Needs more specific matching "
7592                                 "than the datapath supports.");
7593                     break;
7594                 }
7595
7596                 slow &= ~bit;
7597             }
7598
7599             if (slow & ~SLOW_MATCH) {
7600                 ds_put_cstr(ds, "\nThe datapath actions above do not reflect "
7601                             "the special slow-path processing.");
7602             }
7603         }
7604     }
7605 }
7606
7607 static void
7608 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
7609                   const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
7610 {
7611     clogged = true;
7612     unixctl_command_reply(conn, NULL);
7613 }
7614
7615 static void
7616 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED, int argc OVS_UNUSED,
7617                     const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
7618 {
7619     clogged = false;
7620     unixctl_command_reply(conn, NULL);
7621 }
7622
7623 /* Runs a self-check of flow translations in 'ofproto'.  Appends a message to
7624  * 'reply' describing the results. */
7625 static void
7626 ofproto_dpif_self_check__(struct ofproto_dpif *ofproto, struct ds *reply)
7627 {
7628     struct facet *facet;
7629     int errors;
7630
7631     errors = 0;
7632     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
7633         if (!facet_check_consistency(facet)) {
7634             errors++;
7635         }
7636     }
7637     if (errors) {
7638         ofproto->backer->need_revalidate = REV_INCONSISTENCY;
7639     }
7640
7641     if (errors) {
7642         ds_put_format(reply, "%s: self-check failed (%d errors)\n",
7643                       ofproto->up.name, errors);
7644     } else {
7645         ds_put_format(reply, "%s: self-check passed\n", ofproto->up.name);
7646     }
7647 }
7648
7649 static void
7650 ofproto_dpif_self_check(struct unixctl_conn *conn,
7651                         int argc, const char *argv[], void *aux OVS_UNUSED)
7652 {
7653     struct ds reply = DS_EMPTY_INITIALIZER;
7654     struct ofproto_dpif *ofproto;
7655
7656     if (argc > 1) {
7657         ofproto = ofproto_dpif_lookup(argv[1]);
7658         if (!ofproto) {
7659             unixctl_command_reply_error(conn, "Unknown ofproto (use "
7660                                         "ofproto/list for help)");
7661             return;
7662         }
7663         ofproto_dpif_self_check__(ofproto, &reply);
7664     } else {
7665         HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
7666             ofproto_dpif_self_check__(ofproto, &reply);
7667         }
7668     }
7669
7670     unixctl_command_reply(conn, ds_cstr(&reply));
7671     ds_destroy(&reply);
7672 }
7673
7674 /* Store the current ofprotos in 'ofproto_shash'.  Returns a sorted list
7675  * of the 'ofproto_shash' nodes.  It is the responsibility of the caller
7676  * to destroy 'ofproto_shash' and free the returned value. */
7677 static const struct shash_node **
7678 get_ofprotos(struct shash *ofproto_shash)
7679 {
7680     const struct ofproto_dpif *ofproto;
7681
7682     HMAP_FOR_EACH (ofproto, all_ofproto_dpifs_node, &all_ofproto_dpifs) {
7683         char *name = xasprintf("%s@%s", ofproto->up.type, ofproto->up.name);
7684         shash_add_nocopy(ofproto_shash, name, ofproto);
7685     }
7686
7687     return shash_sort(ofproto_shash);
7688 }
7689
7690 static void
7691 ofproto_unixctl_dpif_dump_dps(struct unixctl_conn *conn, int argc OVS_UNUSED,
7692                               const char *argv[] OVS_UNUSED,
7693                               void *aux OVS_UNUSED)
7694 {
7695     struct ds ds = DS_EMPTY_INITIALIZER;
7696     struct shash ofproto_shash;
7697     const struct shash_node **sorted_ofprotos;
7698     int i;
7699
7700     shash_init(&ofproto_shash);
7701     sorted_ofprotos = get_ofprotos(&ofproto_shash);
7702     for (i = 0; i < shash_count(&ofproto_shash); i++) {
7703         const struct shash_node *node = sorted_ofprotos[i];
7704         ds_put_format(&ds, "%s\n", node->name);
7705     }
7706
7707     shash_destroy(&ofproto_shash);
7708     free(sorted_ofprotos);
7709
7710     unixctl_command_reply(conn, ds_cstr(&ds));
7711     ds_destroy(&ds);
7712 }
7713
7714 static void
7715 show_dp_format(const struct ofproto_dpif *ofproto, struct ds *ds)
7716 {
7717     struct dpif_dp_stats s;
7718     const struct shash_node **ports;
7719     int i;
7720
7721     dpif_get_dp_stats(ofproto->backer->dpif, &s);
7722
7723     ds_put_format(ds, "%s (%s):\n", ofproto->up.name,
7724                   dpif_name(ofproto->backer->dpif));
7725     /* xxx It would be better to show bridge-specific stats instead
7726      * xxx of dp ones. */
7727     ds_put_format(ds,
7728                   "\tlookups: hit:%"PRIu64" missed:%"PRIu64" lost:%"PRIu64"\n",
7729                   s.n_hit, s.n_missed, s.n_lost);
7730     ds_put_format(ds, "\tflows: %zu\n",
7731                   hmap_count(&ofproto->subfacets));
7732
7733     ports = shash_sort(&ofproto->up.port_by_name);
7734     for (i = 0; i < shash_count(&ofproto->up.port_by_name); i++) {
7735         const struct shash_node *node = ports[i];
7736         struct ofport *ofport = node->data;
7737         const char *name = netdev_get_name(ofport->netdev);
7738         const char *type = netdev_get_type(ofport->netdev);
7739         uint32_t odp_port;
7740
7741         ds_put_format(ds, "\t%s %u/", name, ofport->ofp_port);
7742
7743         odp_port = ofp_port_to_odp_port(ofproto, ofport->ofp_port);
7744         if (odp_port != OVSP_NONE) {
7745             ds_put_format(ds, "%"PRIu32":", odp_port);
7746         } else {
7747             ds_put_cstr(ds, "none:");
7748         }
7749
7750         if (strcmp(type, "system")) {
7751             struct netdev *netdev;
7752             int error;
7753
7754             ds_put_format(ds, " (%s", type);
7755
7756             error = netdev_open(name, type, &netdev);
7757             if (!error) {
7758                 struct smap config;
7759
7760                 smap_init(&config);
7761                 error = netdev_get_config(netdev, &config);
7762                 if (!error) {
7763                     const struct smap_node **nodes;
7764                     size_t i;
7765
7766                     nodes = smap_sort(&config);
7767                     for (i = 0; i < smap_count(&config); i++) {
7768                         const struct smap_node *node = nodes[i];
7769                         ds_put_format(ds, "%c %s=%s", i ? ',' : ':',
7770                                       node->key, node->value);
7771                     }
7772                     free(nodes);
7773                 }
7774                 smap_destroy(&config);
7775
7776                 netdev_close(netdev);
7777             }
7778             ds_put_char(ds, ')');
7779         }
7780         ds_put_char(ds, '\n');
7781     }
7782     free(ports);
7783 }
7784
7785 static void
7786 ofproto_unixctl_dpif_show(struct unixctl_conn *conn, int argc,
7787                           const char *argv[], void *aux OVS_UNUSED)
7788 {
7789     struct ds ds = DS_EMPTY_INITIALIZER;
7790     const struct ofproto_dpif *ofproto;
7791
7792     if (argc > 1) {
7793         int i;
7794         for (i = 1; i < argc; i++) {
7795             ofproto = ofproto_dpif_lookup(argv[i]);
7796             if (!ofproto) {
7797                 ds_put_format(&ds, "Unknown bridge %s (use dpif/dump-dps "
7798                                    "for help)", argv[i]);
7799                 unixctl_command_reply_error(conn, ds_cstr(&ds));
7800                 return;
7801             }
7802             show_dp_format(ofproto, &ds);
7803         }
7804     } else {
7805         struct shash ofproto_shash;
7806         const struct shash_node **sorted_ofprotos;
7807         int i;
7808
7809         shash_init(&ofproto_shash);
7810         sorted_ofprotos = get_ofprotos(&ofproto_shash);
7811         for (i = 0; i < shash_count(&ofproto_shash); i++) {
7812             const struct shash_node *node = sorted_ofprotos[i];
7813             show_dp_format(node->data, &ds);
7814         }
7815
7816         shash_destroy(&ofproto_shash);
7817         free(sorted_ofprotos);
7818     }
7819
7820     unixctl_command_reply(conn, ds_cstr(&ds));
7821     ds_destroy(&ds);
7822 }
7823
7824 static void
7825 ofproto_unixctl_dpif_dump_flows(struct unixctl_conn *conn,
7826                                 int argc OVS_UNUSED, const char *argv[],
7827                                 void *aux OVS_UNUSED)
7828 {
7829     struct ds ds = DS_EMPTY_INITIALIZER;
7830     const struct ofproto_dpif *ofproto;
7831     struct subfacet *subfacet;
7832
7833     ofproto = ofproto_dpif_lookup(argv[1]);
7834     if (!ofproto) {
7835         unixctl_command_reply_error(conn, "no such bridge");
7836         return;
7837     }
7838
7839     update_stats(ofproto->backer);
7840
7841     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
7842         struct odputil_keybuf keybuf;
7843         struct ofpbuf key;
7844
7845         subfacet_get_key(subfacet, &keybuf, &key);
7846         odp_flow_key_format(key.data, key.size, &ds);
7847
7848         ds_put_format(&ds, ", packets:%"PRIu64", bytes:%"PRIu64", used:",
7849                       subfacet->dp_packet_count, subfacet->dp_byte_count);
7850         if (subfacet->used) {
7851             ds_put_format(&ds, "%.3fs",
7852                           (time_msec() - subfacet->used) / 1000.0);
7853         } else {
7854             ds_put_format(&ds, "never");
7855         }
7856         if (subfacet->facet->tcp_flags) {
7857             ds_put_cstr(&ds, ", flags:");
7858             packet_format_tcp_flags(&ds, subfacet->facet->tcp_flags);
7859         }
7860
7861         ds_put_cstr(&ds, ", actions:");
7862         format_odp_actions(&ds, subfacet->actions, subfacet->actions_len);
7863         ds_put_char(&ds, '\n');
7864     }
7865
7866     unixctl_command_reply(conn, ds_cstr(&ds));
7867     ds_destroy(&ds);
7868 }
7869
7870 static void
7871 ofproto_unixctl_dpif_del_flows(struct unixctl_conn *conn,
7872                                int argc OVS_UNUSED, const char *argv[],
7873                                void *aux OVS_UNUSED)
7874 {
7875     struct ds ds = DS_EMPTY_INITIALIZER;
7876     struct ofproto_dpif *ofproto;
7877
7878     ofproto = ofproto_dpif_lookup(argv[1]);
7879     if (!ofproto) {
7880         unixctl_command_reply_error(conn, "no such bridge");
7881         return;
7882     }
7883
7884     flush(&ofproto->up);
7885
7886     unixctl_command_reply(conn, ds_cstr(&ds));
7887     ds_destroy(&ds);
7888 }
7889
7890 static void
7891 ofproto_dpif_unixctl_init(void)
7892 {
7893     static bool registered;
7894     if (registered) {
7895         return;
7896     }
7897     registered = true;
7898
7899     unixctl_command_register(
7900         "ofproto/trace",
7901         "bridge {priority tun_id in_port mark packet | odp_flow [-generate]}",
7902         2, 6, ofproto_unixctl_trace, NULL);
7903     unixctl_command_register("fdb/flush", "[bridge]", 0, 1,
7904                              ofproto_unixctl_fdb_flush, NULL);
7905     unixctl_command_register("fdb/show", "bridge", 1, 1,
7906                              ofproto_unixctl_fdb_show, NULL);
7907     unixctl_command_register("ofproto/clog", "", 0, 0,
7908                              ofproto_dpif_clog, NULL);
7909     unixctl_command_register("ofproto/unclog", "", 0, 0,
7910                              ofproto_dpif_unclog, NULL);
7911     unixctl_command_register("ofproto/self-check", "[bridge]", 0, 1,
7912                              ofproto_dpif_self_check, NULL);
7913     unixctl_command_register("dpif/dump-dps", "", 0, 0,
7914                              ofproto_unixctl_dpif_dump_dps, NULL);
7915     unixctl_command_register("dpif/show", "[bridge]", 0, INT_MAX,
7916                              ofproto_unixctl_dpif_show, NULL);
7917     unixctl_command_register("dpif/dump-flows", "bridge", 1, 1,
7918                              ofproto_unixctl_dpif_dump_flows, NULL);
7919     unixctl_command_register("dpif/del-flows", "bridge", 1, 1,
7920                              ofproto_unixctl_dpif_del_flows, NULL);
7921 }
7922 \f
7923 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
7924  *
7925  * This is deprecated.  It is only for compatibility with broken device drivers
7926  * in old versions of Linux that do not properly support VLANs when VLAN
7927  * devices are not used.  When broken device drivers are no longer in
7928  * widespread use, we will delete these interfaces. */
7929
7930 static int
7931 set_realdev(struct ofport *ofport_, uint16_t realdev_ofp_port, int vid)
7932 {
7933     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport_->ofproto);
7934     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
7935
7936     if (realdev_ofp_port == ofport->realdev_ofp_port
7937         && vid == ofport->vlandev_vid) {
7938         return 0;
7939     }
7940
7941     ofproto->backer->need_revalidate = REV_RECONFIGURE;
7942
7943     if (ofport->realdev_ofp_port) {
7944         vsp_remove(ofport);
7945     }
7946     if (realdev_ofp_port && ofport->bundle) {
7947         /* vlandevs are enslaved to their realdevs, so they are not allowed to
7948          * themselves be part of a bundle. */
7949         bundle_set(ofport->up.ofproto, ofport->bundle, NULL);
7950     }
7951
7952     ofport->realdev_ofp_port = realdev_ofp_port;
7953     ofport->vlandev_vid = vid;
7954
7955     if (realdev_ofp_port) {
7956         vsp_add(ofport, realdev_ofp_port, vid);
7957     }
7958
7959     return 0;
7960 }
7961
7962 static uint32_t
7963 hash_realdev_vid(uint16_t realdev_ofp_port, int vid)
7964 {
7965     return hash_2words(realdev_ofp_port, vid);
7966 }
7967
7968 /* Returns the ODP port number of the Linux VLAN device that corresponds to
7969  * 'vlan_tci' on the network device with port number 'realdev_odp_port' in
7970  * 'ofproto'.  For example, given 'realdev_odp_port' of eth0 and 'vlan_tci' 9,
7971  * it would return the port number of eth0.9.
7972  *
7973  * Unless VLAN splinters are enabled for port 'realdev_odp_port', this
7974  * function just returns its 'realdev_odp_port' argument. */
7975 static uint32_t
7976 vsp_realdev_to_vlandev(const struct ofproto_dpif *ofproto,
7977                        uint32_t realdev_odp_port, ovs_be16 vlan_tci)
7978 {
7979     if (!hmap_is_empty(&ofproto->realdev_vid_map)) {
7980         uint16_t realdev_ofp_port;
7981         int vid = vlan_tci_to_vid(vlan_tci);
7982         const struct vlan_splinter *vsp;
7983
7984         realdev_ofp_port = odp_port_to_ofp_port(ofproto, realdev_odp_port);
7985         HMAP_FOR_EACH_WITH_HASH (vsp, realdev_vid_node,
7986                                  hash_realdev_vid(realdev_ofp_port, vid),
7987                                  &ofproto->realdev_vid_map) {
7988             if (vsp->realdev_ofp_port == realdev_ofp_port
7989                 && vsp->vid == vid) {
7990                 return ofp_port_to_odp_port(ofproto, vsp->vlandev_ofp_port);
7991             }
7992         }
7993     }
7994     return realdev_odp_port;
7995 }
7996
7997 static struct vlan_splinter *
7998 vlandev_find(const struct ofproto_dpif *ofproto, uint16_t vlandev_ofp_port)
7999 {
8000     struct vlan_splinter *vsp;
8001
8002     HMAP_FOR_EACH_WITH_HASH (vsp, vlandev_node, hash_int(vlandev_ofp_port, 0),
8003                              &ofproto->vlandev_map) {
8004         if (vsp->vlandev_ofp_port == vlandev_ofp_port) {
8005             return vsp;
8006         }
8007     }
8008
8009     return NULL;
8010 }
8011
8012 /* Returns the OpenFlow port number of the "real" device underlying the Linux
8013  * VLAN device with OpenFlow port number 'vlandev_ofp_port' and stores the
8014  * VLAN VID of the Linux VLAN device in '*vid'.  For example, given
8015  * 'vlandev_ofp_port' of eth0.9, it would return the OpenFlow port number of
8016  * eth0 and store 9 in '*vid'.
8017  *
8018  * Returns 0 and does not modify '*vid' if 'vlandev_ofp_port' is not a Linux
8019  * VLAN device.  Unless VLAN splinters are enabled, this is what this function
8020  * always does.*/
8021 static uint16_t
8022 vsp_vlandev_to_realdev(const struct ofproto_dpif *ofproto,
8023                        uint16_t vlandev_ofp_port, int *vid)
8024 {
8025     if (!hmap_is_empty(&ofproto->vlandev_map)) {
8026         const struct vlan_splinter *vsp;
8027
8028         vsp = vlandev_find(ofproto, vlandev_ofp_port);
8029         if (vsp) {
8030             if (vid) {
8031                 *vid = vsp->vid;
8032             }
8033             return vsp->realdev_ofp_port;
8034         }
8035     }
8036     return 0;
8037 }
8038
8039 /* Given 'flow', a flow representing a packet received on 'ofproto', checks
8040  * whether 'flow->in_port' represents a Linux VLAN device.  If so, changes
8041  * 'flow->in_port' to the "real" device backing the VLAN device, sets
8042  * 'flow->vlan_tci' to the VLAN VID, and returns true.  Otherwise (which is
8043  * always the case unless VLAN splinters are enabled), returns false without
8044  * making any changes. */
8045 static bool
8046 vsp_adjust_flow(const struct ofproto_dpif *ofproto, struct flow *flow)
8047 {
8048     uint16_t realdev;
8049     int vid;
8050
8051     realdev = vsp_vlandev_to_realdev(ofproto, flow->in_port, &vid);
8052     if (!realdev) {
8053         return false;
8054     }
8055
8056     /* Cause the flow to be processed as if it came in on the real device with
8057      * the VLAN device's VLAN ID. */
8058     flow->in_port = realdev;
8059     flow->vlan_tci = htons((vid & VLAN_VID_MASK) | VLAN_CFI);
8060     return true;
8061 }
8062
8063 static void
8064 vsp_remove(struct ofport_dpif *port)
8065 {
8066     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
8067     struct vlan_splinter *vsp;
8068
8069     vsp = vlandev_find(ofproto, port->up.ofp_port);
8070     if (vsp) {
8071         hmap_remove(&ofproto->vlandev_map, &vsp->vlandev_node);
8072         hmap_remove(&ofproto->realdev_vid_map, &vsp->realdev_vid_node);
8073         free(vsp);
8074
8075         port->realdev_ofp_port = 0;
8076     } else {
8077         VLOG_ERR("missing vlan device record");
8078     }
8079 }
8080
8081 static void
8082 vsp_add(struct ofport_dpif *port, uint16_t realdev_ofp_port, int vid)
8083 {
8084     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
8085
8086     if (!vsp_vlandev_to_realdev(ofproto, port->up.ofp_port, NULL)
8087         && (vsp_realdev_to_vlandev(ofproto, realdev_ofp_port, htons(vid))
8088             == realdev_ofp_port)) {
8089         struct vlan_splinter *vsp;
8090
8091         vsp = xmalloc(sizeof *vsp);
8092         hmap_insert(&ofproto->vlandev_map, &vsp->vlandev_node,
8093                     hash_int(port->up.ofp_port, 0));
8094         hmap_insert(&ofproto->realdev_vid_map, &vsp->realdev_vid_node,
8095                     hash_realdev_vid(realdev_ofp_port, vid));
8096         vsp->realdev_ofp_port = realdev_ofp_port;
8097         vsp->vlandev_ofp_port = port->up.ofp_port;
8098         vsp->vid = vid;
8099
8100         port->realdev_ofp_port = realdev_ofp_port;
8101     } else {
8102         VLOG_ERR("duplicate vlan device record");
8103     }
8104 }
8105
8106 static uint32_t
8107 ofp_port_to_odp_port(const struct ofproto_dpif *ofproto, uint16_t ofp_port)
8108 {
8109     const struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
8110     return ofport ? ofport->odp_port : OVSP_NONE;
8111 }
8112
8113 static struct ofport_dpif *
8114 odp_port_to_ofport(const struct dpif_backer *backer, uint32_t odp_port)
8115 {
8116     struct ofport_dpif *port;
8117
8118     HMAP_FOR_EACH_IN_BUCKET (port, odp_port_node,
8119                              hash_int(odp_port, 0),
8120                              &backer->odp_to_ofport_map) {
8121         if (port->odp_port == odp_port) {
8122             return port;
8123         }
8124     }
8125
8126     return NULL;
8127 }
8128
8129 static uint16_t
8130 odp_port_to_ofp_port(const struct ofproto_dpif *ofproto, uint32_t odp_port)
8131 {
8132     struct ofport_dpif *port;
8133
8134     port = odp_port_to_ofport(ofproto->backer, odp_port);
8135     if (port && &ofproto->up == port->up.ofproto) {
8136         return port->up.ofp_port;
8137     } else {
8138         return OFPP_NONE;
8139     }
8140 }
8141
8142 const struct ofproto_class ofproto_dpif_class = {
8143     init,
8144     enumerate_types,
8145     enumerate_names,
8146     del,
8147     port_open_type,
8148     type_run,
8149     type_run_fast,
8150     type_wait,
8151     alloc,
8152     construct,
8153     destruct,
8154     dealloc,
8155     run,
8156     run_fast,
8157     wait,
8158     get_memory_usage,
8159     flush,
8160     get_features,
8161     get_tables,
8162     port_alloc,
8163     port_construct,
8164     port_destruct,
8165     port_dealloc,
8166     port_modified,
8167     port_reconfigured,
8168     port_query_by_name,
8169     port_add,
8170     port_del,
8171     port_get_stats,
8172     port_dump_start,
8173     port_dump_next,
8174     port_dump_done,
8175     port_poll,
8176     port_poll_wait,
8177     port_is_lacp_current,
8178     NULL,                       /* rule_choose_table */
8179     rule_alloc,
8180     rule_construct,
8181     rule_destruct,
8182     rule_dealloc,
8183     rule_get_stats,
8184     rule_execute,
8185     rule_modify_actions,
8186     set_frag_handling,
8187     packet_out,
8188     set_netflow,
8189     get_netflow_ids,
8190     set_sflow,
8191     set_cfm,
8192     get_cfm_fault,
8193     get_cfm_opup,
8194     get_cfm_remote_mpids,
8195     get_cfm_health,
8196     set_stp,
8197     get_stp_status,
8198     set_stp_port,
8199     get_stp_port_status,
8200     set_queues,
8201     bundle_set,
8202     bundle_remove,
8203     mirror_set,
8204     mirror_get_stats,
8205     set_flood_vlans,
8206     is_mirror_output_bundle,
8207     forward_bpdu_changed,
8208     set_mac_table_config,
8209     set_realdev,
8210 };