ofproto-dpif: Simplify invocation of send_packet().
[openvswitch] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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 "multipath.h"
38 #include "netdev.h"
39 #include "netlink.h"
40 #include "nx-match.h"
41 #include "odp-util.h"
42 #include "ofp-util.h"
43 #include "ofpbuf.h"
44 #include "ofp-print.h"
45 #include "ofproto-dpif-sflow.h"
46 #include "poll-loop.h"
47 #include "timer.h"
48 #include "unaligned.h"
49 #include "unixctl.h"
50 #include "vlan-bitmap.h"
51 #include "vlog.h"
52
53 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
54
55 COVERAGE_DEFINE(ofproto_dpif_ctlr_action);
56 COVERAGE_DEFINE(ofproto_dpif_expired);
57 COVERAGE_DEFINE(ofproto_dpif_no_packet_in);
58 COVERAGE_DEFINE(ofproto_dpif_xlate);
59 COVERAGE_DEFINE(facet_changed_rule);
60 COVERAGE_DEFINE(facet_invalidated);
61 COVERAGE_DEFINE(facet_revalidate);
62 COVERAGE_DEFINE(facet_unexpected);
63
64 /* Maximum depth of flow table recursion (due to resubmit actions) in a
65  * flow translation. */
66 #define MAX_RESUBMIT_RECURSION 32
67
68 /* Number of implemented OpenFlow tables. */
69 enum { N_TABLES = 255 };
70 BUILD_ASSERT_DECL(N_TABLES >= 1 && N_TABLES <= 255);
71
72 struct ofport_dpif;
73 struct ofproto_dpif;
74
75 struct rule_dpif {
76     struct rule up;
77
78     long long int used;         /* Time last used; time created if not used. */
79
80     /* These statistics:
81      *
82      *   - Do include packets and bytes from facets that have been deleted or
83      *     whose own statistics have been folded into the rule.
84      *
85      *   - Do include packets and bytes sent "by hand" that were accounted to
86      *     the rule without any facet being involved (this is a rare corner
87      *     case in rule_execute()).
88      *
89      *   - Do not include packet or bytes that can be obtained from any facet's
90      *     packet_count or byte_count member or that can be obtained from the
91      *     datapath by, e.g., dpif_flow_get() for any subfacet.
92      */
93     uint64_t packet_count;       /* Number of packets received. */
94     uint64_t byte_count;         /* Number of bytes received. */
95
96     tag_type tag;                /* Caches rule_calculate_tag() result. */
97
98     struct list facets;          /* List of "struct facet"s. */
99 };
100
101 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
102 {
103     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
104 }
105
106 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
107                                           const struct flow *, uint8_t table);
108
109 static void flow_push_stats(const struct rule_dpif *, const struct flow *,
110                             uint64_t packets, uint64_t bytes,
111                             long long int used);
112
113 static uint32_t rule_calculate_tag(const struct flow *,
114                                    const struct flow_wildcards *,
115                                    uint32_t basis);
116 static void rule_invalidate(const struct rule_dpif *);
117
118 #define MAX_MIRRORS 32
119 typedef uint32_t mirror_mask_t;
120 #define MIRROR_MASK_C(X) UINT32_C(X)
121 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
122 struct ofmirror {
123     struct ofproto_dpif *ofproto; /* Owning ofproto. */
124     size_t idx;                 /* In ofproto's "mirrors" array. */
125     void *aux;                  /* Key supplied by ofproto's client. */
126     char *name;                 /* Identifier for log messages. */
127
128     /* Selection criteria. */
129     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
130     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
131     unsigned long *vlans;       /* Bitmap of chosen VLANs, NULL selects all. */
132
133     /* Output (exactly one of out == NULL and out_vlan == -1 is true). */
134     struct ofbundle *out;       /* Output port or NULL. */
135     int out_vlan;               /* Output VLAN or -1. */
136     mirror_mask_t dup_mirrors;  /* Bitmap of mirrors with the same output. */
137 };
138
139 static void mirror_destroy(struct ofmirror *);
140
141 /* A group of one or more OpenFlow ports. */
142 #define OFBUNDLE_FLOOD ((struct ofbundle *) 1)
143 struct ofbundle {
144     struct ofproto_dpif *ofproto; /* Owning ofproto. */
145     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
146     void *aux;                  /* Key supplied by ofproto's client. */
147     char *name;                 /* Identifier for log messages. */
148
149     /* Configuration. */
150     struct list ports;          /* Contains "struct ofport"s. */
151     enum port_vlan_mode vlan_mode; /* VLAN mode */
152     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
153     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
154                                  * NULL if all VLANs are trunked. */
155     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
156     struct bond *bond;          /* Nonnull iff more than one port. */
157     bool use_priority_tags;     /* Use 802.1p tag for frames in VLAN 0? */
158
159     /* Status. */
160     bool floodable;             /* True if no port has OFPPC_NO_FLOOD set. */
161
162     /* Port mirroring info. */
163     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
164     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
165     mirror_mask_t mirror_out;   /* Mirrors that output to this bundle. */
166 };
167
168 static void bundle_remove(struct ofport *);
169 static void bundle_update(struct ofbundle *);
170 static void bundle_destroy(struct ofbundle *);
171 static void bundle_del_port(struct ofport_dpif *);
172 static void bundle_run(struct ofbundle *);
173 static void bundle_wait(struct ofbundle *);
174
175 static void stp_run(struct ofproto_dpif *ofproto);
176 static void stp_wait(struct ofproto_dpif *ofproto);
177
178 static bool ofbundle_includes_vlan(const struct ofbundle *, uint16_t vlan);
179
180 struct action_xlate_ctx {
181 /* action_xlate_ctx_init() initializes these members. */
182
183     /* The ofproto. */
184     struct ofproto_dpif *ofproto;
185
186     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
187      * this flow when actions change header fields. */
188     struct flow flow;
189
190     /* The packet corresponding to 'flow', or a null pointer if we are
191      * revalidating without a packet to refer to. */
192     const struct ofpbuf *packet;
193
194     /* Should OFPP_NORMAL MAC learning and NXAST_LEARN actions execute?  We
195      * want to execute them if we are actually processing a packet, or if we
196      * are accounting for packets that the datapath has processed, but not if
197      * we are just revalidating. */
198     bool may_learn;
199
200     /* If nonnull, called just before executing a resubmit action.
201      *
202      * This is normally null so the client has to set it manually after
203      * calling action_xlate_ctx_init(). */
204     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule_dpif *);
205
206 /* xlate_actions() initializes and uses these members.  The client might want
207  * to look at them after it returns. */
208
209     struct ofpbuf *odp_actions; /* Datapath actions. */
210     tag_type tags;              /* Tags associated with actions. */
211     bool may_set_up_flow;       /* True ordinarily; false if the actions must
212                                  * be reassessed for every packet. */
213     bool has_learn;             /* Actions include NXAST_LEARN? */
214     bool has_normal;            /* Actions output to OFPP_NORMAL? */
215     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
216
217 /* xlate_actions() initializes and uses these members, but the client has no
218  * reason to look at them. */
219
220     int recurse;                /* Recursion level, via xlate_table_action. */
221     struct flow base_flow;      /* Flow at the last commit. */
222     uint32_t original_priority; /* Priority when packet arrived. */
223     uint8_t table_id;           /* OpenFlow table ID where flow was found. */
224     uint32_t sflow_n_outputs;   /* Number of output ports. */
225     uint16_t sflow_odp_port;    /* Output port for composing sFlow action. */
226     uint16_t user_cookie_offset;/* Used for user_action_cookie fixup. */
227     bool exit;                  /* No further actions should be processed. */
228 };
229
230 static void action_xlate_ctx_init(struct action_xlate_ctx *,
231                                   struct ofproto_dpif *, const struct flow *,
232                                   const struct ofpbuf *);
233 static struct ofpbuf *xlate_actions(struct action_xlate_ctx *,
234                                     const union ofp_action *in, size_t n_in);
235
236 /* An exact-match instantiation of an OpenFlow flow.
237  *
238  * A facet associates a "struct flow", which represents the Open vSwitch
239  * userspace idea of an exact-match flow, with a set of datapath actions.
240  *
241  * A facet contains one or more subfacets.  Each subfacet tracks the datapath's
242  * idea of the exact-match flow equivalent to the facet.  When the kernel
243  * module (or other dpif implementation) and Open vSwitch userspace agree on
244  * the definition of a flow key, there is exactly one subfacet per facet.  If
245  * the dpif implementation supports more-specific flow matching than userspace,
246  * however, a facet can have more than one subfacet, each of which corresponds
247  * to some distinction in flow that userspace simply doesn't understand.
248  *
249  * Flow expiration works in terms of subfacets, so a facet must have at least
250  * one subfacet or it will never expire, leaking memory. */
251 struct facet {
252     /* Owners. */
253     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
254     struct list list_node;       /* In owning rule's 'facets' list. */
255     struct rule_dpif *rule;      /* Owning rule. */
256
257     /* Owned data. */
258     struct list subfacets;
259     long long int used;         /* Time last used; time created if not used. */
260
261     /* Key. */
262     struct flow flow;
263
264     /* These statistics:
265      *
266      *   - Do include packets and bytes sent "by hand", e.g. with
267      *     dpif_execute().
268      *
269      *   - Do include packets and bytes that were obtained from the datapath
270      *     when a subfacet's statistics were reset (e.g. dpif_flow_put() with
271      *     DPIF_FP_ZERO_STATS).
272      *
273      *   - Do not include packets or bytes that can be obtained from the
274      *     datapath for any existing subfacet.
275      */
276     uint64_t packet_count;       /* Number of packets received. */
277     uint64_t byte_count;         /* Number of bytes received. */
278
279     /* Resubmit statistics. */
280     uint64_t rs_packet_count;    /* Packets pushed to resubmit children. */
281     uint64_t rs_byte_count;      /* Bytes pushed to resubmit children. */
282     long long int rs_used;       /* Used time pushed to resubmit children. */
283
284     /* Accounting. */
285     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
286     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
287
288     /* Datapath actions. */
289     bool may_install;            /* Reassess actions for every packet? */
290     bool has_learn;              /* Actions include NXAST_LEARN? */
291     bool has_normal;             /* Actions output to OFPP_NORMAL? */
292     size_t actions_len;          /* Number of bytes in actions[]. */
293     struct nlattr *actions;      /* Datapath actions. */
294     tag_type tags;               /* Tags that would require revalidation. */
295 };
296
297 static struct facet *facet_create(struct rule_dpif *, const struct flow *);
298 static void facet_remove(struct ofproto_dpif *, struct facet *);
299 static void facet_free(struct facet *);
300
301 static struct facet *facet_find(struct ofproto_dpif *, const struct flow *);
302 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
303                                         const struct flow *);
304 static bool facet_revalidate(struct ofproto_dpif *, struct facet *);
305
306 static bool execute_controller_action(struct ofproto_dpif *,
307                                       const struct flow *,
308                                       const struct nlattr *odp_actions,
309                                       size_t actions_len,
310                                       struct ofpbuf *packet);
311
312 static void facet_flush_stats(struct ofproto_dpif *, struct facet *);
313
314 static void facet_make_actions(struct ofproto_dpif *, struct facet *,
315                                const struct ofpbuf *packet);
316 static void facet_update_time(struct ofproto_dpif *, struct facet *,
317                               long long int used);
318 static void facet_reset_counters(struct facet *);
319 static void facet_push_stats(struct facet *);
320 static void facet_account(struct ofproto_dpif *, struct facet *);
321
322 static bool facet_is_controller_flow(struct facet *);
323
324 /* A dpif flow associated with a facet.
325  *
326  * See also the large comment on struct facet. */
327 struct subfacet {
328     /* Owners. */
329     struct hmap_node hmap_node; /* In struct ofproto_dpif 'subfacets' list. */
330     struct list list_node;      /* In struct facet's 'facets' list. */
331     struct facet *facet;        /* Owning facet. */
332
333     /* Key.
334      *
335      * To save memory in the common case, 'key' is NULL if 'key_fitness' is
336      * ODP_FIT_PERFECT, that is, odp_flow_key_from_flow() can accurately
337      * regenerate the ODP flow key from ->facet->flow. */
338     enum odp_key_fitness key_fitness;
339     struct nlattr *key;
340     int key_len;
341
342     long long int used;         /* Time last used; time created if not used. */
343
344     uint64_t dp_packet_count;   /* Last known packet count in the datapath. */
345     uint64_t dp_byte_count;     /* Last known byte count in the datapath. */
346
347     bool installed;             /* Installed in datapath? */
348 };
349
350 static struct subfacet *subfacet_create(struct ofproto_dpif *, struct facet *,
351                                         enum odp_key_fitness,
352                                         const struct nlattr *key,
353                                         size_t key_len);
354 static struct subfacet *subfacet_find(struct ofproto_dpif *,
355                                       const struct nlattr *key, size_t key_len,
356                                       const struct flow *);
357 static void subfacet_destroy(struct ofproto_dpif *, struct subfacet *);
358 static void subfacet_destroy__(struct ofproto_dpif *, struct subfacet *);
359 static void subfacet_reset_dp_stats(struct subfacet *,
360                                     struct dpif_flow_stats *);
361 static void subfacet_update_time(struct ofproto_dpif *, struct subfacet *,
362                                  long long int used);
363 static void subfacet_update_stats(struct ofproto_dpif *, struct subfacet *,
364                                   const struct dpif_flow_stats *);
365 static int subfacet_install(struct ofproto_dpif *, struct subfacet *,
366                             const struct nlattr *actions, size_t actions_len,
367                             struct dpif_flow_stats *);
368 static void subfacet_uninstall(struct ofproto_dpif *, struct subfacet *);
369
370 struct ofport_dpif {
371     struct ofport up;
372
373     uint32_t odp_port;
374     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
375     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
376     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
377     tag_type tag;               /* Tag associated with this port. */
378     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
379     bool may_enable;            /* May be enabled in bonds. */
380
381     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
382     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
383     long long int stp_state_entered;
384
385     struct hmap priorities;     /* Map of attached 'priority_to_dscp's. */
386 };
387
388 /* Node in 'ofport_dpif''s 'priorities' map.  Used to maintain a map from
389  * 'priority' (the datapath's term for QoS queue) to the dscp bits which all
390  * traffic egressing the 'ofport' with that priority should be marked with. */
391 struct priority_to_dscp {
392     struct hmap_node hmap_node; /* Node in 'ofport_dpif''s 'priorities' map. */
393     uint32_t priority;          /* Priority of this queue (see struct flow). */
394
395     uint8_t dscp;               /* DSCP bits to mark outgoing traffic with. */
396 };
397
398 static struct ofport_dpif *
399 ofport_dpif_cast(const struct ofport *ofport)
400 {
401     assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
402     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
403 }
404
405 static void port_run(struct ofport_dpif *);
406 static void port_wait(struct ofport_dpif *);
407 static int set_cfm(struct ofport *, const struct cfm_settings *);
408 static void ofport_clear_priorities(struct ofport_dpif *);
409
410 struct dpif_completion {
411     struct list list_node;
412     struct ofoperation *op;
413 };
414
415 /* Extra information about a classifier table.
416  * Currently used just for optimized flow revalidation. */
417 struct table_dpif {
418     /* If either of these is nonnull, then this table has a form that allows
419      * flows to be tagged to avoid revalidating most flows for the most common
420      * kinds of flow table changes. */
421     struct cls_table *catchall_table; /* Table that wildcards all fields. */
422     struct cls_table *other_table;    /* Table with any other wildcard set. */
423     uint32_t basis;                   /* Keeps each table's tags separate. */
424 };
425
426 struct ofproto_dpif {
427     struct ofproto up;
428     struct dpif *dpif;
429     int max_ports;
430
431     /* Statistics. */
432     uint64_t n_matches;
433
434     /* Bridging. */
435     struct netflow *netflow;
436     struct dpif_sflow *sflow;
437     struct hmap bundles;        /* Contains "struct ofbundle"s. */
438     struct mac_learning *ml;
439     struct ofmirror *mirrors[MAX_MIRRORS];
440     bool has_bonded_bundles;
441
442     /* Expiration. */
443     struct timer next_expiration;
444
445     /* Facets. */
446     struct hmap facets;
447     struct hmap subfacets;
448
449     /* Revalidation. */
450     struct table_dpif tables[N_TABLES];
451     bool need_revalidate;
452     struct tag_set revalidate_set;
453
454     /* Support for debugging async flow mods. */
455     struct list completions;
456
457     bool has_bundle_action; /* True when the first bundle action appears. */
458
459     /* Spanning tree. */
460     struct stp *stp;
461     long long int stp_last_tick;
462 };
463
464 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
465  * for debugging the asynchronous flow_mod implementation.) */
466 static bool clogged;
467
468 static void ofproto_dpif_unixctl_init(void);
469
470 static struct ofproto_dpif *
471 ofproto_dpif_cast(const struct ofproto *ofproto)
472 {
473     assert(ofproto->ofproto_class == &ofproto_dpif_class);
474     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
475 }
476
477 static struct ofport_dpif *get_ofp_port(struct ofproto_dpif *,
478                                         uint16_t ofp_port);
479 static struct ofport_dpif *get_odp_port(struct ofproto_dpif *,
480                                         uint32_t odp_port);
481
482 /* Packet processing. */
483 static void update_learning_table(struct ofproto_dpif *,
484                                   const struct flow *, int vlan,
485                                   struct ofbundle *);
486 /* Upcalls. */
487 #define FLOW_MISS_MAX_BATCH 50
488
489 static void handle_upcall(struct ofproto_dpif *, struct dpif_upcall *);
490 static void handle_miss_upcalls(struct ofproto_dpif *,
491                                 struct dpif_upcall *, size_t n);
492
493 /* Flow expiration. */
494 static int expire(struct ofproto_dpif *);
495
496 /* NetFlow. */
497 static void send_netflow_active_timeouts(struct ofproto_dpif *);
498
499 /* Utilities. */
500 static int send_packet(const struct ofport_dpif *,
501                        const struct ofpbuf *packet);
502 static size_t
503 compose_sflow_action(const struct ofproto_dpif *, struct ofpbuf *odp_actions,
504                      const struct flow *, uint32_t odp_port);
505 /* Global variables. */
506 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
507 \f
508 /* Factory functions. */
509
510 static void
511 enumerate_types(struct sset *types)
512 {
513     dp_enumerate_types(types);
514 }
515
516 static int
517 enumerate_names(const char *type, struct sset *names)
518 {
519     return dp_enumerate_names(type, names);
520 }
521
522 static int
523 del(const char *type, const char *name)
524 {
525     struct dpif *dpif;
526     int error;
527
528     error = dpif_open(name, type, &dpif);
529     if (!error) {
530         error = dpif_delete(dpif);
531         dpif_close(dpif);
532     }
533     return error;
534 }
535 \f
536 /* Basic life-cycle. */
537
538 static struct ofproto *
539 alloc(void)
540 {
541     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
542     return &ofproto->up;
543 }
544
545 static void
546 dealloc(struct ofproto *ofproto_)
547 {
548     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
549     free(ofproto);
550 }
551
552 static int
553 construct(struct ofproto *ofproto_, int *n_tablesp)
554 {
555     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
556     const char *name = ofproto->up.name;
557     int error;
558     int i;
559
560     error = dpif_create_and_open(name, ofproto->up.type, &ofproto->dpif);
561     if (error) {
562         VLOG_ERR("failed to open datapath %s: %s", name, strerror(error));
563         return error;
564     }
565
566     ofproto->max_ports = dpif_get_max_ports(ofproto->dpif);
567     ofproto->n_matches = 0;
568
569     dpif_flow_flush(ofproto->dpif);
570     dpif_recv_purge(ofproto->dpif);
571
572     error = dpif_recv_set_mask(ofproto->dpif,
573                                ((1u << DPIF_UC_MISS) |
574                                 (1u << DPIF_UC_ACTION)));
575     if (error) {
576         VLOG_ERR("failed to listen on datapath %s: %s", name, strerror(error));
577         dpif_close(ofproto->dpif);
578         return error;
579     }
580
581     ofproto->netflow = NULL;
582     ofproto->sflow = NULL;
583     ofproto->stp = NULL;
584     hmap_init(&ofproto->bundles);
585     ofproto->ml = mac_learning_create();
586     for (i = 0; i < MAX_MIRRORS; i++) {
587         ofproto->mirrors[i] = NULL;
588     }
589     ofproto->has_bonded_bundles = false;
590
591     timer_set_duration(&ofproto->next_expiration, 1000);
592
593     hmap_init(&ofproto->facets);
594     hmap_init(&ofproto->subfacets);
595
596     for (i = 0; i < N_TABLES; i++) {
597         struct table_dpif *table = &ofproto->tables[i];
598
599         table->catchall_table = NULL;
600         table->other_table = NULL;
601         table->basis = random_uint32();
602     }
603     ofproto->need_revalidate = false;
604     tag_set_init(&ofproto->revalidate_set);
605
606     list_init(&ofproto->completions);
607
608     ofproto_dpif_unixctl_init();
609
610     ofproto->has_bundle_action = false;
611
612     *n_tablesp = N_TABLES;
613     return 0;
614 }
615
616 static void
617 complete_operations(struct ofproto_dpif *ofproto)
618 {
619     struct dpif_completion *c, *next;
620
621     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
622         ofoperation_complete(c->op, 0);
623         list_remove(&c->list_node);
624         free(c);
625     }
626 }
627
628 static void
629 destruct(struct ofproto *ofproto_)
630 {
631     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
632     struct rule_dpif *rule, *next_rule;
633     struct classifier *table;
634     int i;
635
636     complete_operations(ofproto);
637
638     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
639         struct cls_cursor cursor;
640
641         cls_cursor_init(&cursor, table, NULL);
642         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
643             ofproto_rule_destroy(&rule->up);
644         }
645     }
646
647     for (i = 0; i < MAX_MIRRORS; i++) {
648         mirror_destroy(ofproto->mirrors[i]);
649     }
650
651     netflow_destroy(ofproto->netflow);
652     dpif_sflow_destroy(ofproto->sflow);
653     hmap_destroy(&ofproto->bundles);
654     mac_learning_destroy(ofproto->ml);
655
656     hmap_destroy(&ofproto->facets);
657     hmap_destroy(&ofproto->subfacets);
658
659     dpif_close(ofproto->dpif);
660 }
661
662 static int
663 run(struct ofproto *ofproto_)
664 {
665     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
666     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
667     struct ofport_dpif *ofport;
668     struct ofbundle *bundle;
669     size_t n_misses;
670     int i;
671
672     if (!clogged) {
673         complete_operations(ofproto);
674     }
675     dpif_run(ofproto->dpif);
676
677     n_misses = 0;
678     for (i = 0; i < FLOW_MISS_MAX_BATCH; i++) {
679         struct dpif_upcall *upcall = &misses[n_misses];
680         int error;
681
682         error = dpif_recv(ofproto->dpif, upcall);
683         if (error) {
684             if (error == ENODEV && n_misses == 0) {
685                 return error;
686             }
687             break;
688         }
689
690         if (upcall->type == DPIF_UC_MISS) {
691             /* Handle it later. */
692             n_misses++;
693         } else {
694             handle_upcall(ofproto, upcall);
695         }
696     }
697
698     handle_miss_upcalls(ofproto, misses, n_misses);
699
700     if (timer_expired(&ofproto->next_expiration)) {
701         int delay = expire(ofproto);
702         timer_set_duration(&ofproto->next_expiration, delay);
703     }
704
705     if (ofproto->netflow) {
706         if (netflow_run(ofproto->netflow)) {
707             send_netflow_active_timeouts(ofproto);
708         }
709     }
710     if (ofproto->sflow) {
711         dpif_sflow_run(ofproto->sflow);
712     }
713
714     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
715         port_run(ofport);
716     }
717     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
718         bundle_run(bundle);
719     }
720
721     stp_run(ofproto);
722     mac_learning_run(ofproto->ml, &ofproto->revalidate_set);
723
724     /* Now revalidate if there's anything to do. */
725     if (ofproto->need_revalidate
726         || !tag_set_is_empty(&ofproto->revalidate_set)) {
727         struct tag_set revalidate_set = ofproto->revalidate_set;
728         bool revalidate_all = ofproto->need_revalidate;
729         struct facet *facet, *next;
730
731         /* Clear the revalidation flags. */
732         tag_set_init(&ofproto->revalidate_set);
733         ofproto->need_revalidate = false;
734
735         HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &ofproto->facets) {
736             if (revalidate_all
737                 || tag_set_intersects(&revalidate_set, facet->tags)) {
738                 facet_revalidate(ofproto, facet);
739             }
740         }
741     }
742
743     return 0;
744 }
745
746 static void
747 wait(struct ofproto *ofproto_)
748 {
749     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
750     struct ofport_dpif *ofport;
751     struct ofbundle *bundle;
752
753     if (!clogged && !list_is_empty(&ofproto->completions)) {
754         poll_immediate_wake();
755     }
756
757     dpif_wait(ofproto->dpif);
758     dpif_recv_wait(ofproto->dpif);
759     if (ofproto->sflow) {
760         dpif_sflow_wait(ofproto->sflow);
761     }
762     if (!tag_set_is_empty(&ofproto->revalidate_set)) {
763         poll_immediate_wake();
764     }
765     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
766         port_wait(ofport);
767     }
768     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
769         bundle_wait(bundle);
770     }
771     if (ofproto->netflow) {
772         netflow_wait(ofproto->netflow);
773     }
774     mac_learning_wait(ofproto->ml);
775     stp_wait(ofproto);
776     if (ofproto->need_revalidate) {
777         /* Shouldn't happen, but if it does just go around again. */
778         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
779         poll_immediate_wake();
780     } else {
781         timer_wait(&ofproto->next_expiration);
782     }
783 }
784
785 static void
786 flush(struct ofproto *ofproto_)
787 {
788     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
789     struct facet *facet, *next_facet;
790
791     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
792         /* Mark the facet as not installed so that facet_remove() doesn't
793          * bother trying to uninstall it.  There is no point in uninstalling it
794          * individually since we are about to blow away all the facets with
795          * dpif_flow_flush(). */
796         struct subfacet *subfacet;
797
798         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
799             subfacet->installed = false;
800             subfacet->dp_packet_count = 0;
801             subfacet->dp_byte_count = 0;
802         }
803         facet_remove(ofproto, facet);
804     }
805     dpif_flow_flush(ofproto->dpif);
806 }
807
808 static void
809 get_features(struct ofproto *ofproto_ OVS_UNUSED,
810              bool *arp_match_ip, uint32_t *actions)
811 {
812     *arp_match_ip = true;
813     *actions = ((1u << OFPAT_OUTPUT) |
814                 (1u << OFPAT_SET_VLAN_VID) |
815                 (1u << OFPAT_SET_VLAN_PCP) |
816                 (1u << OFPAT_STRIP_VLAN) |
817                 (1u << OFPAT_SET_DL_SRC) |
818                 (1u << OFPAT_SET_DL_DST) |
819                 (1u << OFPAT_SET_NW_SRC) |
820                 (1u << OFPAT_SET_NW_DST) |
821                 (1u << OFPAT_SET_NW_TOS) |
822                 (1u << OFPAT_SET_TP_SRC) |
823                 (1u << OFPAT_SET_TP_DST) |
824                 (1u << OFPAT_ENQUEUE));
825 }
826
827 static void
828 get_tables(struct ofproto *ofproto_, struct ofp_table_stats *ots)
829 {
830     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
831     struct dpif_dp_stats s;
832
833     strcpy(ots->name, "classifier");
834
835     dpif_get_dp_stats(ofproto->dpif, &s);
836     put_32aligned_be64(&ots->lookup_count, htonll(s.n_hit + s.n_missed));
837     put_32aligned_be64(&ots->matched_count,
838                        htonll(s.n_hit + ofproto->n_matches));
839 }
840
841 static struct ofport *
842 port_alloc(void)
843 {
844     struct ofport_dpif *port = xmalloc(sizeof *port);
845     return &port->up;
846 }
847
848 static void
849 port_dealloc(struct ofport *port_)
850 {
851     struct ofport_dpif *port = ofport_dpif_cast(port_);
852     free(port);
853 }
854
855 static int
856 port_construct(struct ofport *port_)
857 {
858     struct ofport_dpif *port = ofport_dpif_cast(port_);
859     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
860
861     ofproto->need_revalidate = true;
862     port->odp_port = ofp_port_to_odp_port(port->up.ofp_port);
863     port->bundle = NULL;
864     port->cfm = NULL;
865     port->tag = tag_create_random();
866     port->may_enable = true;
867     port->stp_port = NULL;
868     port->stp_state = STP_DISABLED;
869     hmap_init(&port->priorities);
870
871     if (ofproto->sflow) {
872         dpif_sflow_add_port(ofproto->sflow, port->odp_port,
873                             netdev_get_name(port->up.netdev));
874     }
875
876     return 0;
877 }
878
879 static void
880 port_destruct(struct ofport *port_)
881 {
882     struct ofport_dpif *port = ofport_dpif_cast(port_);
883     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
884
885     ofproto->need_revalidate = true;
886     bundle_remove(port_);
887     set_cfm(port_, NULL);
888     if (ofproto->sflow) {
889         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
890     }
891
892     ofport_clear_priorities(port);
893     hmap_destroy(&port->priorities);
894 }
895
896 static void
897 port_modified(struct ofport *port_)
898 {
899     struct ofport_dpif *port = ofport_dpif_cast(port_);
900
901     if (port->bundle && port->bundle->bond) {
902         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
903     }
904 }
905
906 static void
907 port_reconfigured(struct ofport *port_, ovs_be32 old_config)
908 {
909     struct ofport_dpif *port = ofport_dpif_cast(port_);
910     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
911     ovs_be32 changed = old_config ^ port->up.opp.config;
912
913     if (changed & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
914                         OFPPC_NO_FWD | OFPPC_NO_FLOOD)) {
915         ofproto->need_revalidate = true;
916
917         if (changed & htonl(OFPPC_NO_FLOOD) && port->bundle) {
918             bundle_update(port->bundle);
919         }
920     }
921 }
922
923 static int
924 set_sflow(struct ofproto *ofproto_,
925           const struct ofproto_sflow_options *sflow_options)
926 {
927     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
928     struct dpif_sflow *ds = ofproto->sflow;
929
930     if (sflow_options) {
931         if (!ds) {
932             struct ofport_dpif *ofport;
933
934             ds = ofproto->sflow = dpif_sflow_create(ofproto->dpif);
935             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
936                 dpif_sflow_add_port(ds, ofport->odp_port,
937                                     netdev_get_name(ofport->up.netdev));
938             }
939             ofproto->need_revalidate = true;
940         }
941         dpif_sflow_set_options(ds, sflow_options);
942     } else {
943         if (ds) {
944             dpif_sflow_destroy(ds);
945             ofproto->need_revalidate = true;
946             ofproto->sflow = NULL;
947         }
948     }
949     return 0;
950 }
951
952 static int
953 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
954 {
955     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
956     int error;
957
958     if (!s) {
959         error = 0;
960     } else {
961         if (!ofport->cfm) {
962             struct ofproto_dpif *ofproto;
963
964             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
965             ofproto->need_revalidate = true;
966             ofport->cfm = cfm_create(netdev_get_name(ofport->up.netdev));
967         }
968
969         if (cfm_configure(ofport->cfm, s)) {
970             return 0;
971         }
972
973         error = EINVAL;
974     }
975     cfm_destroy(ofport->cfm);
976     ofport->cfm = NULL;
977     return error;
978 }
979
980 static int
981 get_cfm_fault(const struct ofport *ofport_)
982 {
983     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
984
985     return ofport->cfm ? cfm_get_fault(ofport->cfm) : -1;
986 }
987
988 static int
989 get_cfm_remote_mpids(const struct ofport *ofport_, const uint64_t **rmps,
990                      size_t *n_rmps)
991 {
992     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
993
994     if (ofport->cfm) {
995         cfm_get_remote_mpids(ofport->cfm, rmps, n_rmps);
996         return 0;
997     } else {
998         return -1;
999     }
1000 }
1001 \f
1002 /* Spanning Tree. */
1003
1004 static void
1005 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
1006 {
1007     struct ofproto_dpif *ofproto = ofproto_;
1008     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
1009     struct ofport_dpif *ofport;
1010
1011     ofport = stp_port_get_aux(sp);
1012     if (!ofport) {
1013         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
1014                      ofproto->up.name, port_num);
1015     } else {
1016         struct eth_header *eth = pkt->l2;
1017
1018         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
1019         if (eth_addr_is_zero(eth->eth_src)) {
1020             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
1021                          "with unknown MAC", ofproto->up.name, port_num);
1022         } else {
1023             send_packet(ofport, pkt);
1024         }
1025     }
1026     ofpbuf_delete(pkt);
1027 }
1028
1029 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
1030 static int
1031 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
1032 {
1033     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1034
1035     /* Only revalidate flows if the configuration changed. */
1036     if (!s != !ofproto->stp) {
1037         ofproto->need_revalidate = true;
1038     }
1039
1040     if (s) {
1041         if (!ofproto->stp) {
1042             ofproto->stp = stp_create(ofproto_->name, s->system_id,
1043                                       send_bpdu_cb, ofproto);
1044             ofproto->stp_last_tick = time_msec();
1045         }
1046
1047         stp_set_bridge_id(ofproto->stp, s->system_id);
1048         stp_set_bridge_priority(ofproto->stp, s->priority);
1049         stp_set_hello_time(ofproto->stp, s->hello_time);
1050         stp_set_max_age(ofproto->stp, s->max_age);
1051         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
1052     }  else {
1053         stp_destroy(ofproto->stp);
1054         ofproto->stp = NULL;
1055     }
1056
1057     return 0;
1058 }
1059
1060 static int
1061 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
1062 {
1063     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1064
1065     if (ofproto->stp) {
1066         s->enabled = true;
1067         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1068         s->designated_root = stp_get_designated_root(ofproto->stp);
1069         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1070     } else {
1071         s->enabled = false;
1072     }
1073
1074     return 0;
1075 }
1076
1077 static void
1078 update_stp_port_state(struct ofport_dpif *ofport)
1079 {
1080     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1081     enum stp_state state;
1082
1083     /* Figure out new state. */
1084     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1085                              : STP_DISABLED;
1086
1087     /* Update state. */
1088     if (ofport->stp_state != state) {
1089         ovs_be32 of_state;
1090         bool fwd_change;
1091
1092         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1093                     netdev_get_name(ofport->up.netdev),
1094                     stp_state_name(ofport->stp_state),
1095                     stp_state_name(state));
1096         if (stp_learn_in_state(ofport->stp_state)
1097                 != stp_learn_in_state(state)) {
1098             /* xxx Learning action flows should also be flushed. */
1099             mac_learning_flush(ofproto->ml);
1100         }
1101         fwd_change = stp_forward_in_state(ofport->stp_state)
1102                         != stp_forward_in_state(state);
1103
1104         ofproto->need_revalidate = true;
1105         ofport->stp_state = state;
1106         ofport->stp_state_entered = time_msec();
1107
1108         if (fwd_change && ofport->bundle) {
1109             bundle_update(ofport->bundle);
1110         }
1111
1112         /* Update the STP state bits in the OpenFlow port description. */
1113         of_state = (ofport->up.opp.state & htonl(~OFPPS_STP_MASK))
1114                          | htonl(state == STP_LISTENING ? OFPPS_STP_LISTEN
1115                                : state == STP_LEARNING ? OFPPS_STP_LEARN
1116                                : state == STP_FORWARDING ? OFPPS_STP_FORWARD
1117                                : state == STP_BLOCKING ?  OFPPS_STP_BLOCK
1118                                : 0);
1119         ofproto_port_set_state(&ofport->up, of_state);
1120     }
1121 }
1122
1123 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1124  * caller is responsible for assigning STP port numbers and ensuring
1125  * there are no duplicates. */
1126 static int
1127 set_stp_port(struct ofport *ofport_,
1128              const struct ofproto_port_stp_settings *s)
1129 {
1130     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1131     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1132     struct stp_port *sp = ofport->stp_port;
1133
1134     if (!s || !s->enable) {
1135         if (sp) {
1136             ofport->stp_port = NULL;
1137             stp_port_disable(sp);
1138             update_stp_port_state(ofport);
1139         }
1140         return 0;
1141     } else if (sp && stp_port_no(sp) != s->port_num
1142             && ofport == stp_port_get_aux(sp)) {
1143         /* The port-id changed, so disable the old one if it's not
1144          * already in use by another port. */
1145         stp_port_disable(sp);
1146     }
1147
1148     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1149     stp_port_enable(sp);
1150
1151     stp_port_set_aux(sp, ofport);
1152     stp_port_set_priority(sp, s->priority);
1153     stp_port_set_path_cost(sp, s->path_cost);
1154
1155     update_stp_port_state(ofport);
1156
1157     return 0;
1158 }
1159
1160 static int
1161 get_stp_port_status(struct ofport *ofport_,
1162                     struct ofproto_port_stp_status *s)
1163 {
1164     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1165     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1166     struct stp_port *sp = ofport->stp_port;
1167
1168     if (!ofproto->stp || !sp) {
1169         s->enabled = false;
1170         return 0;
1171     }
1172
1173     s->enabled = true;
1174     s->port_id = stp_port_get_id(sp);
1175     s->state = stp_port_get_state(sp);
1176     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1177     s->role = stp_port_get_role(sp);
1178     stp_port_get_counts(sp, &s->tx_count, &s->rx_count, &s->error_count);
1179
1180     return 0;
1181 }
1182
1183 static void
1184 stp_run(struct ofproto_dpif *ofproto)
1185 {
1186     if (ofproto->stp) {
1187         long long int now = time_msec();
1188         long long int elapsed = now - ofproto->stp_last_tick;
1189         struct stp_port *sp;
1190
1191         if (elapsed > 0) {
1192             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1193             ofproto->stp_last_tick = now;
1194         }
1195         while (stp_get_changed_port(ofproto->stp, &sp)) {
1196             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1197
1198             if (ofport) {
1199                 update_stp_port_state(ofport);
1200             }
1201         }
1202     }
1203 }
1204
1205 static void
1206 stp_wait(struct ofproto_dpif *ofproto)
1207 {
1208     if (ofproto->stp) {
1209         poll_timer_wait(1000);
1210     }
1211 }
1212
1213 /* Returns true if STP should process 'flow'. */
1214 static bool
1215 stp_should_process_flow(const struct flow *flow)
1216 {
1217     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
1218 }
1219
1220 static void
1221 stp_process_packet(const struct ofport_dpif *ofport,
1222                    const struct ofpbuf *packet)
1223 {
1224     struct ofpbuf payload = *packet;
1225     struct eth_header *eth = payload.data;
1226     struct stp_port *sp = ofport->stp_port;
1227
1228     /* Sink packets on ports that have STP disabled when the bridge has
1229      * STP enabled. */
1230     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1231         return;
1232     }
1233
1234     /* Trim off padding on payload. */
1235     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1236         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1237     }
1238
1239     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1240         stp_received_bpdu(sp, payload.data, payload.size);
1241     }
1242 }
1243 \f
1244 static struct priority_to_dscp *
1245 get_priority(const struct ofport_dpif *ofport, uint32_t priority)
1246 {
1247     struct priority_to_dscp *pdscp;
1248     uint32_t hash;
1249
1250     hash = hash_int(priority, 0);
1251     HMAP_FOR_EACH_IN_BUCKET (pdscp, hmap_node, hash, &ofport->priorities) {
1252         if (pdscp->priority == priority) {
1253             return pdscp;
1254         }
1255     }
1256     return NULL;
1257 }
1258
1259 static void
1260 ofport_clear_priorities(struct ofport_dpif *ofport)
1261 {
1262     struct priority_to_dscp *pdscp, *next;
1263
1264     HMAP_FOR_EACH_SAFE (pdscp, next, hmap_node, &ofport->priorities) {
1265         hmap_remove(&ofport->priorities, &pdscp->hmap_node);
1266         free(pdscp);
1267     }
1268 }
1269
1270 static int
1271 set_queues(struct ofport *ofport_,
1272            const struct ofproto_port_queue *qdscp_list,
1273            size_t n_qdscp)
1274 {
1275     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1276     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1277     struct hmap new = HMAP_INITIALIZER(&new);
1278     size_t i;
1279
1280     for (i = 0; i < n_qdscp; i++) {
1281         struct priority_to_dscp *pdscp;
1282         uint32_t priority;
1283         uint8_t dscp;
1284
1285         dscp = (qdscp_list[i].dscp << 2) & IP_DSCP_MASK;
1286         if (dpif_queue_to_priority(ofproto->dpif, qdscp_list[i].queue,
1287                                    &priority)) {
1288             continue;
1289         }
1290
1291         pdscp = get_priority(ofport, priority);
1292         if (pdscp) {
1293             hmap_remove(&ofport->priorities, &pdscp->hmap_node);
1294         } else {
1295             pdscp = xmalloc(sizeof *pdscp);
1296             pdscp->priority = priority;
1297             pdscp->dscp = dscp;
1298             ofproto->need_revalidate = true;
1299         }
1300
1301         if (pdscp->dscp != dscp) {
1302             pdscp->dscp = dscp;
1303             ofproto->need_revalidate = true;
1304         }
1305
1306         hmap_insert(&new, &pdscp->hmap_node, hash_int(pdscp->priority, 0));
1307     }
1308
1309     if (!hmap_is_empty(&ofport->priorities)) {
1310         ofport_clear_priorities(ofport);
1311         ofproto->need_revalidate = true;
1312     }
1313
1314     hmap_swap(&new, &ofport->priorities);
1315     hmap_destroy(&new);
1316
1317     return 0;
1318 }
1319 \f
1320 /* Bundles. */
1321
1322 /* Expires all MAC learning entries associated with 'port' and forces ofproto
1323  * to revalidate every flow. */
1324 static void
1325 bundle_flush_macs(struct ofbundle *bundle)
1326 {
1327     struct ofproto_dpif *ofproto = bundle->ofproto;
1328     struct mac_learning *ml = ofproto->ml;
1329     struct mac_entry *mac, *next_mac;
1330
1331     ofproto->need_revalidate = true;
1332     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
1333         if (mac->port.p == bundle) {
1334             mac_learning_expire(ml, mac);
1335         }
1336     }
1337 }
1338
1339 static struct ofbundle *
1340 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
1341 {
1342     struct ofbundle *bundle;
1343
1344     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
1345                              &ofproto->bundles) {
1346         if (bundle->aux == aux) {
1347             return bundle;
1348         }
1349     }
1350     return NULL;
1351 }
1352
1353 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
1354  * ones that are found to 'bundles'. */
1355 static void
1356 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
1357                        void **auxes, size_t n_auxes,
1358                        struct hmapx *bundles)
1359 {
1360     size_t i;
1361
1362     hmapx_init(bundles);
1363     for (i = 0; i < n_auxes; i++) {
1364         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
1365         if (bundle) {
1366             hmapx_add(bundles, bundle);
1367         }
1368     }
1369 }
1370
1371 static void
1372 bundle_update(struct ofbundle *bundle)
1373 {
1374     struct ofport_dpif *port;
1375
1376     bundle->floodable = true;
1377     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1378         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)) {
1379             bundle->floodable = false;
1380             break;
1381         }
1382     }
1383 }
1384
1385 static void
1386 bundle_del_port(struct ofport_dpif *port)
1387 {
1388     struct ofbundle *bundle = port->bundle;
1389
1390     bundle->ofproto->need_revalidate = true;
1391
1392     list_remove(&port->bundle_node);
1393     port->bundle = NULL;
1394
1395     if (bundle->lacp) {
1396         lacp_slave_unregister(bundle->lacp, port);
1397     }
1398     if (bundle->bond) {
1399         bond_slave_unregister(bundle->bond, port);
1400     }
1401
1402     bundle_update(bundle);
1403 }
1404
1405 static bool
1406 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
1407                 struct lacp_slave_settings *lacp,
1408                 uint32_t bond_stable_id)
1409 {
1410     struct ofport_dpif *port;
1411
1412     port = get_ofp_port(bundle->ofproto, ofp_port);
1413     if (!port) {
1414         return false;
1415     }
1416
1417     if (port->bundle != bundle) {
1418         bundle->ofproto->need_revalidate = true;
1419         if (port->bundle) {
1420             bundle_del_port(port);
1421         }
1422
1423         port->bundle = bundle;
1424         list_push_back(&bundle->ports, &port->bundle_node);
1425         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)) {
1426             bundle->floodable = false;
1427         }
1428     }
1429     if (lacp) {
1430         port->bundle->ofproto->need_revalidate = true;
1431         lacp_slave_register(bundle->lacp, port, lacp);
1432     }
1433
1434     port->bond_stable_id = bond_stable_id;
1435
1436     return true;
1437 }
1438
1439 static void
1440 bundle_destroy(struct ofbundle *bundle)
1441 {
1442     struct ofproto_dpif *ofproto;
1443     struct ofport_dpif *port, *next_port;
1444     int i;
1445
1446     if (!bundle) {
1447         return;
1448     }
1449
1450     ofproto = bundle->ofproto;
1451     for (i = 0; i < MAX_MIRRORS; i++) {
1452         struct ofmirror *m = ofproto->mirrors[i];
1453         if (m) {
1454             if (m->out == bundle) {
1455                 mirror_destroy(m);
1456             } else if (hmapx_find_and_delete(&m->srcs, bundle)
1457                        || hmapx_find_and_delete(&m->dsts, bundle)) {
1458                 ofproto->need_revalidate = true;
1459             }
1460         }
1461     }
1462
1463     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1464         bundle_del_port(port);
1465     }
1466
1467     bundle_flush_macs(bundle);
1468     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
1469     free(bundle->name);
1470     free(bundle->trunks);
1471     lacp_destroy(bundle->lacp);
1472     bond_destroy(bundle->bond);
1473     free(bundle);
1474 }
1475
1476 static int
1477 bundle_set(struct ofproto *ofproto_, void *aux,
1478            const struct ofproto_bundle_settings *s)
1479 {
1480     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1481     bool need_flush = false;
1482     struct ofport_dpif *port;
1483     struct ofbundle *bundle;
1484     unsigned long *trunks;
1485     int vlan;
1486     size_t i;
1487     bool ok;
1488
1489     if (!s) {
1490         bundle_destroy(bundle_lookup(ofproto, aux));
1491         return 0;
1492     }
1493
1494     assert(s->n_slaves == 1 || s->bond != NULL);
1495     assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
1496
1497     bundle = bundle_lookup(ofproto, aux);
1498     if (!bundle) {
1499         bundle = xmalloc(sizeof *bundle);
1500
1501         bundle->ofproto = ofproto;
1502         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
1503                     hash_pointer(aux, 0));
1504         bundle->aux = aux;
1505         bundle->name = NULL;
1506
1507         list_init(&bundle->ports);
1508         bundle->vlan_mode = PORT_VLAN_TRUNK;
1509         bundle->vlan = -1;
1510         bundle->trunks = NULL;
1511         bundle->use_priority_tags = s->use_priority_tags;
1512         bundle->lacp = NULL;
1513         bundle->bond = NULL;
1514
1515         bundle->floodable = true;
1516
1517         bundle->src_mirrors = 0;
1518         bundle->dst_mirrors = 0;
1519         bundle->mirror_out = 0;
1520     }
1521
1522     if (!bundle->name || strcmp(s->name, bundle->name)) {
1523         free(bundle->name);
1524         bundle->name = xstrdup(s->name);
1525     }
1526
1527     /* LACP. */
1528     if (s->lacp) {
1529         if (!bundle->lacp) {
1530             ofproto->need_revalidate = true;
1531             bundle->lacp = lacp_create();
1532         }
1533         lacp_configure(bundle->lacp, s->lacp);
1534     } else {
1535         lacp_destroy(bundle->lacp);
1536         bundle->lacp = NULL;
1537     }
1538
1539     /* Update set of ports. */
1540     ok = true;
1541     for (i = 0; i < s->n_slaves; i++) {
1542         if (!bundle_add_port(bundle, s->slaves[i],
1543                              s->lacp ? &s->lacp_slaves[i] : NULL,
1544                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
1545             ok = false;
1546         }
1547     }
1548     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
1549         struct ofport_dpif *next_port;
1550
1551         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1552             for (i = 0; i < s->n_slaves; i++) {
1553                 if (s->slaves[i] == port->up.ofp_port) {
1554                     goto found;
1555                 }
1556             }
1557
1558             bundle_del_port(port);
1559         found: ;
1560         }
1561     }
1562     assert(list_size(&bundle->ports) <= s->n_slaves);
1563
1564     if (list_is_empty(&bundle->ports)) {
1565         bundle_destroy(bundle);
1566         return EINVAL;
1567     }
1568
1569     /* Set VLAN tagging mode */
1570     if (s->vlan_mode != bundle->vlan_mode
1571         || s->use_priority_tags != bundle->use_priority_tags) {
1572         bundle->vlan_mode = s->vlan_mode;
1573         bundle->use_priority_tags = s->use_priority_tags;
1574         need_flush = true;
1575     }
1576
1577     /* Set VLAN tag. */
1578     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
1579             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
1580             : 0);
1581     if (vlan != bundle->vlan) {
1582         bundle->vlan = vlan;
1583         need_flush = true;
1584     }
1585
1586     /* Get trunked VLANs. */
1587     switch (s->vlan_mode) {
1588     case PORT_VLAN_ACCESS:
1589         trunks = NULL;
1590         break;
1591
1592     case PORT_VLAN_TRUNK:
1593         trunks = (unsigned long *) s->trunks;
1594         break;
1595
1596     case PORT_VLAN_NATIVE_UNTAGGED:
1597     case PORT_VLAN_NATIVE_TAGGED:
1598         if (vlan != 0 && (!s->trunks
1599                           || !bitmap_is_set(s->trunks, vlan)
1600                           || bitmap_is_set(s->trunks, 0))) {
1601             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
1602             if (s->trunks) {
1603                 trunks = bitmap_clone(s->trunks, 4096);
1604             } else {
1605                 trunks = bitmap_allocate1(4096);
1606             }
1607             bitmap_set1(trunks, vlan);
1608             bitmap_set0(trunks, 0);
1609         } else {
1610             trunks = (unsigned long *) s->trunks;
1611         }
1612         break;
1613
1614     default:
1615         NOT_REACHED();
1616     }
1617     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
1618         free(bundle->trunks);
1619         if (trunks == s->trunks) {
1620             bundle->trunks = vlan_bitmap_clone(trunks);
1621         } else {
1622             bundle->trunks = trunks;
1623             trunks = NULL;
1624         }
1625         need_flush = true;
1626     }
1627     if (trunks != s->trunks) {
1628         free(trunks);
1629     }
1630
1631     /* Bonding. */
1632     if (!list_is_short(&bundle->ports)) {
1633         bundle->ofproto->has_bonded_bundles = true;
1634         if (bundle->bond) {
1635             if (bond_reconfigure(bundle->bond, s->bond)) {
1636                 ofproto->need_revalidate = true;
1637             }
1638         } else {
1639             bundle->bond = bond_create(s->bond);
1640             ofproto->need_revalidate = true;
1641         }
1642
1643         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1644             bond_slave_register(bundle->bond, port, port->bond_stable_id,
1645                                 port->up.netdev);
1646         }
1647     } else {
1648         bond_destroy(bundle->bond);
1649         bundle->bond = NULL;
1650     }
1651
1652     /* If we changed something that would affect MAC learning, un-learn
1653      * everything on this port and force flow revalidation. */
1654     if (need_flush) {
1655         bundle_flush_macs(bundle);
1656     }
1657
1658     return 0;
1659 }
1660
1661 static void
1662 bundle_remove(struct ofport *port_)
1663 {
1664     struct ofport_dpif *port = ofport_dpif_cast(port_);
1665     struct ofbundle *bundle = port->bundle;
1666
1667     if (bundle) {
1668         bundle_del_port(port);
1669         if (list_is_empty(&bundle->ports)) {
1670             bundle_destroy(bundle);
1671         } else if (list_is_short(&bundle->ports)) {
1672             bond_destroy(bundle->bond);
1673             bundle->bond = NULL;
1674         }
1675     }
1676 }
1677
1678 static void
1679 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
1680 {
1681     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
1682     struct ofport_dpif *port = port_;
1683     uint8_t ea[ETH_ADDR_LEN];
1684     int error;
1685
1686     error = netdev_get_etheraddr(port->up.netdev, ea);
1687     if (!error) {
1688         struct ofpbuf packet;
1689         void *packet_pdu;
1690
1691         ofpbuf_init(&packet, 0);
1692         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
1693                                  pdu_size);
1694         memcpy(packet_pdu, pdu, pdu_size);
1695
1696         send_packet(port, &packet);
1697         ofpbuf_uninit(&packet);
1698     } else {
1699         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
1700                     "%s (%s)", port->bundle->name,
1701                     netdev_get_name(port->up.netdev), strerror(error));
1702     }
1703 }
1704
1705 static void
1706 bundle_send_learning_packets(struct ofbundle *bundle)
1707 {
1708     struct ofproto_dpif *ofproto = bundle->ofproto;
1709     int error, n_packets, n_errors;
1710     struct mac_entry *e;
1711
1712     error = n_packets = n_errors = 0;
1713     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
1714         if (e->port.p != bundle) {
1715             struct ofpbuf *learning_packet;
1716             struct ofport_dpif *port;
1717             int ret;
1718
1719             learning_packet = bond_compose_learning_packet(bundle->bond, e->mac,
1720                                                            e->vlan,
1721                                                            (void **)&port);
1722             ret = send_packet(port, learning_packet);
1723             ofpbuf_delete(learning_packet);
1724             if (ret) {
1725                 error = ret;
1726                 n_errors++;
1727             }
1728             n_packets++;
1729         }
1730     }
1731
1732     if (n_errors) {
1733         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1734         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
1735                      "packets, last error was: %s",
1736                      bundle->name, n_errors, n_packets, strerror(error));
1737     } else {
1738         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
1739                  bundle->name, n_packets);
1740     }
1741 }
1742
1743 static void
1744 bundle_run(struct ofbundle *bundle)
1745 {
1746     if (bundle->lacp) {
1747         lacp_run(bundle->lacp, send_pdu_cb);
1748     }
1749     if (bundle->bond) {
1750         struct ofport_dpif *port;
1751
1752         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1753             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
1754         }
1755
1756         bond_run(bundle->bond, &bundle->ofproto->revalidate_set,
1757                  lacp_negotiated(bundle->lacp));
1758         if (bond_should_send_learning_packets(bundle->bond)) {
1759             bundle_send_learning_packets(bundle);
1760         }
1761     }
1762 }
1763
1764 static void
1765 bundle_wait(struct ofbundle *bundle)
1766 {
1767     if (bundle->lacp) {
1768         lacp_wait(bundle->lacp);
1769     }
1770     if (bundle->bond) {
1771         bond_wait(bundle->bond);
1772     }
1773 }
1774 \f
1775 /* Mirrors. */
1776
1777 static int
1778 mirror_scan(struct ofproto_dpif *ofproto)
1779 {
1780     int idx;
1781
1782     for (idx = 0; idx < MAX_MIRRORS; idx++) {
1783         if (!ofproto->mirrors[idx]) {
1784             return idx;
1785         }
1786     }
1787     return -1;
1788 }
1789
1790 static struct ofmirror *
1791 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
1792 {
1793     int i;
1794
1795     for (i = 0; i < MAX_MIRRORS; i++) {
1796         struct ofmirror *mirror = ofproto->mirrors[i];
1797         if (mirror && mirror->aux == aux) {
1798             return mirror;
1799         }
1800     }
1801
1802     return NULL;
1803 }
1804
1805 /* Update the 'dup_mirrors' member of each of the ofmirrors in 'ofproto'. */
1806 static void
1807 mirror_update_dups(struct ofproto_dpif *ofproto)
1808 {
1809     int i;
1810
1811     for (i = 0; i < MAX_MIRRORS; i++) {
1812         struct ofmirror *m = ofproto->mirrors[i];
1813
1814         if (m) {
1815             m->dup_mirrors = MIRROR_MASK_C(1) << i;
1816         }
1817     }
1818
1819     for (i = 0; i < MAX_MIRRORS; i++) {
1820         struct ofmirror *m1 = ofproto->mirrors[i];
1821         int j;
1822
1823         if (!m1) {
1824             continue;
1825         }
1826
1827         for (j = i + 1; j < MAX_MIRRORS; j++) {
1828             struct ofmirror *m2 = ofproto->mirrors[j];
1829
1830             if (m2 && m1->out == m2->out && m1->out_vlan == m2->out_vlan) {
1831                 m1->dup_mirrors |= MIRROR_MASK_C(1) << j;
1832                 m2->dup_mirrors |= m1->dup_mirrors;
1833             }
1834         }
1835     }
1836 }
1837
1838 static int
1839 mirror_set(struct ofproto *ofproto_, void *aux,
1840            const struct ofproto_mirror_settings *s)
1841 {
1842     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1843     mirror_mask_t mirror_bit;
1844     struct ofbundle *bundle;
1845     struct ofmirror *mirror;
1846     struct ofbundle *out;
1847     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
1848     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
1849     int out_vlan;
1850
1851     mirror = mirror_lookup(ofproto, aux);
1852     if (!s) {
1853         mirror_destroy(mirror);
1854         return 0;
1855     }
1856     if (!mirror) {
1857         int idx;
1858
1859         idx = mirror_scan(ofproto);
1860         if (idx < 0) {
1861             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
1862                       "cannot create %s",
1863                       ofproto->up.name, MAX_MIRRORS, s->name);
1864             return EFBIG;
1865         }
1866
1867         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
1868         mirror->ofproto = ofproto;
1869         mirror->idx = idx;
1870         mirror->aux = aux;
1871         mirror->out_vlan = -1;
1872         mirror->name = NULL;
1873     }
1874
1875     if (!mirror->name || strcmp(s->name, mirror->name)) {
1876         free(mirror->name);
1877         mirror->name = xstrdup(s->name);
1878     }
1879
1880     /* Get the new configuration. */
1881     if (s->out_bundle) {
1882         out = bundle_lookup(ofproto, s->out_bundle);
1883         if (!out) {
1884             mirror_destroy(mirror);
1885             return EINVAL;
1886         }
1887         out_vlan = -1;
1888     } else {
1889         out = NULL;
1890         out_vlan = s->out_vlan;
1891     }
1892     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
1893     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
1894
1895     /* If the configuration has not changed, do nothing. */
1896     if (hmapx_equals(&srcs, &mirror->srcs)
1897         && hmapx_equals(&dsts, &mirror->dsts)
1898         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
1899         && mirror->out == out
1900         && mirror->out_vlan == out_vlan)
1901     {
1902         hmapx_destroy(&srcs);
1903         hmapx_destroy(&dsts);
1904         return 0;
1905     }
1906
1907     hmapx_swap(&srcs, &mirror->srcs);
1908     hmapx_destroy(&srcs);
1909
1910     hmapx_swap(&dsts, &mirror->dsts);
1911     hmapx_destroy(&dsts);
1912
1913     free(mirror->vlans);
1914     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
1915
1916     mirror->out = out;
1917     mirror->out_vlan = out_vlan;
1918
1919     /* Update bundles. */
1920     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1921     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
1922         if (hmapx_contains(&mirror->srcs, bundle)) {
1923             bundle->src_mirrors |= mirror_bit;
1924         } else {
1925             bundle->src_mirrors &= ~mirror_bit;
1926         }
1927
1928         if (hmapx_contains(&mirror->dsts, bundle)) {
1929             bundle->dst_mirrors |= mirror_bit;
1930         } else {
1931             bundle->dst_mirrors &= ~mirror_bit;
1932         }
1933
1934         if (mirror->out == bundle) {
1935             bundle->mirror_out |= mirror_bit;
1936         } else {
1937             bundle->mirror_out &= ~mirror_bit;
1938         }
1939     }
1940
1941     ofproto->need_revalidate = true;
1942     mac_learning_flush(ofproto->ml);
1943     mirror_update_dups(ofproto);
1944
1945     return 0;
1946 }
1947
1948 static void
1949 mirror_destroy(struct ofmirror *mirror)
1950 {
1951     struct ofproto_dpif *ofproto;
1952     mirror_mask_t mirror_bit;
1953     struct ofbundle *bundle;
1954
1955     if (!mirror) {
1956         return;
1957     }
1958
1959     ofproto = mirror->ofproto;
1960     ofproto->need_revalidate = true;
1961     mac_learning_flush(ofproto->ml);
1962
1963     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1964     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1965         bundle->src_mirrors &= ~mirror_bit;
1966         bundle->dst_mirrors &= ~mirror_bit;
1967         bundle->mirror_out &= ~mirror_bit;
1968     }
1969
1970     hmapx_destroy(&mirror->srcs);
1971     hmapx_destroy(&mirror->dsts);
1972     free(mirror->vlans);
1973
1974     ofproto->mirrors[mirror->idx] = NULL;
1975     free(mirror->name);
1976     free(mirror);
1977
1978     mirror_update_dups(ofproto);
1979 }
1980
1981 static int
1982 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
1983 {
1984     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1985     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
1986         ofproto->need_revalidate = true;
1987         mac_learning_flush(ofproto->ml);
1988     }
1989     return 0;
1990 }
1991
1992 static bool
1993 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
1994 {
1995     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1996     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
1997     return bundle && bundle->mirror_out != 0;
1998 }
1999
2000 static void
2001 forward_bpdu_changed(struct ofproto *ofproto_)
2002 {
2003     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2004     /* Revalidate cached flows whenever forward_bpdu option changes. */
2005     ofproto->need_revalidate = true;
2006 }
2007 \f
2008 /* Ports. */
2009
2010 static struct ofport_dpif *
2011 get_ofp_port(struct ofproto_dpif *ofproto, uint16_t ofp_port)
2012 {
2013     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
2014     return ofport ? ofport_dpif_cast(ofport) : NULL;
2015 }
2016
2017 static struct ofport_dpif *
2018 get_odp_port(struct ofproto_dpif *ofproto, uint32_t odp_port)
2019 {
2020     return get_ofp_port(ofproto, odp_port_to_ofp_port(odp_port));
2021 }
2022
2023 static void
2024 ofproto_port_from_dpif_port(struct ofproto_port *ofproto_port,
2025                             struct dpif_port *dpif_port)
2026 {
2027     ofproto_port->name = dpif_port->name;
2028     ofproto_port->type = dpif_port->type;
2029     ofproto_port->ofp_port = odp_port_to_ofp_port(dpif_port->port_no);
2030 }
2031
2032 static void
2033 port_run(struct ofport_dpif *ofport)
2034 {
2035     bool enable = netdev_get_carrier(ofport->up.netdev);
2036
2037     if (ofport->cfm) {
2038         cfm_run(ofport->cfm);
2039
2040         if (cfm_should_send_ccm(ofport->cfm)) {
2041             struct ofpbuf packet;
2042
2043             ofpbuf_init(&packet, 0);
2044             cfm_compose_ccm(ofport->cfm, &packet, ofport->up.opp.hw_addr);
2045             send_packet(ofport, &packet);
2046             ofpbuf_uninit(&packet);
2047         }
2048
2049         enable = enable && !cfm_get_fault(ofport->cfm)
2050             && cfm_get_opup(ofport->cfm);
2051     }
2052
2053     if (ofport->bundle) {
2054         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
2055     }
2056
2057     if (ofport->may_enable != enable) {
2058         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
2059
2060         if (ofproto->has_bundle_action) {
2061             ofproto->need_revalidate = true;
2062         }
2063     }
2064
2065     ofport->may_enable = enable;
2066 }
2067
2068 static void
2069 port_wait(struct ofport_dpif *ofport)
2070 {
2071     if (ofport->cfm) {
2072         cfm_wait(ofport->cfm);
2073     }
2074 }
2075
2076 static int
2077 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
2078                    struct ofproto_port *ofproto_port)
2079 {
2080     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2081     struct dpif_port dpif_port;
2082     int error;
2083
2084     error = dpif_port_query_by_name(ofproto->dpif, devname, &dpif_port);
2085     if (!error) {
2086         ofproto_port_from_dpif_port(ofproto_port, &dpif_port);
2087     }
2088     return error;
2089 }
2090
2091 static int
2092 port_add(struct ofproto *ofproto_, struct netdev *netdev, uint16_t *ofp_portp)
2093 {
2094     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2095     uint16_t odp_port;
2096     int error;
2097
2098     error = dpif_port_add(ofproto->dpif, netdev, &odp_port);
2099     if (!error) {
2100         *ofp_portp = odp_port_to_ofp_port(odp_port);
2101     }
2102     return error;
2103 }
2104
2105 static int
2106 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
2107 {
2108     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2109     int error;
2110
2111     error = dpif_port_del(ofproto->dpif, ofp_port_to_odp_port(ofp_port));
2112     if (!error) {
2113         struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
2114         if (ofport) {
2115             /* The caller is going to close ofport->up.netdev.  If this is a
2116              * bonded port, then the bond is using that netdev, so remove it
2117              * from the bond.  The client will need to reconfigure everything
2118              * after deleting ports, so then the slave will get re-added. */
2119             bundle_remove(&ofport->up);
2120         }
2121     }
2122     return error;
2123 }
2124
2125 struct port_dump_state {
2126     struct dpif_port_dump dump;
2127     bool done;
2128 };
2129
2130 static int
2131 port_dump_start(const struct ofproto *ofproto_, void **statep)
2132 {
2133     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2134     struct port_dump_state *state;
2135
2136     *statep = state = xmalloc(sizeof *state);
2137     dpif_port_dump_start(&state->dump, ofproto->dpif);
2138     state->done = false;
2139     return 0;
2140 }
2141
2142 static int
2143 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
2144                struct ofproto_port *port)
2145 {
2146     struct port_dump_state *state = state_;
2147     struct dpif_port dpif_port;
2148
2149     if (dpif_port_dump_next(&state->dump, &dpif_port)) {
2150         ofproto_port_from_dpif_port(port, &dpif_port);
2151         return 0;
2152     } else {
2153         int error = dpif_port_dump_done(&state->dump);
2154         state->done = true;
2155         return error ? error : EOF;
2156     }
2157 }
2158
2159 static int
2160 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
2161 {
2162     struct port_dump_state *state = state_;
2163
2164     if (!state->done) {
2165         dpif_port_dump_done(&state->dump);
2166     }
2167     free(state);
2168     return 0;
2169 }
2170
2171 static int
2172 port_poll(const struct ofproto *ofproto_, char **devnamep)
2173 {
2174     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2175     return dpif_port_poll(ofproto->dpif, devnamep);
2176 }
2177
2178 static void
2179 port_poll_wait(const struct ofproto *ofproto_)
2180 {
2181     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2182     dpif_port_poll_wait(ofproto->dpif);
2183 }
2184
2185 static int
2186 port_is_lacp_current(const struct ofport *ofport_)
2187 {
2188     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2189     return (ofport->bundle && ofport->bundle->lacp
2190             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
2191             : -1);
2192 }
2193 \f
2194 /* Upcall handling. */
2195
2196 /* Flow miss batching.
2197  *
2198  * Some dpifs implement operations faster when you hand them off in a batch.
2199  * To allow batching, "struct flow_miss" queues the dpif-related work needed
2200  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
2201  * more packets, plus possibly installing the flow in the dpif.
2202  *
2203  * So far we only batch the operations that affect flow setup time the most.
2204  * It's possible to batch more than that, but the benefit might be minimal. */
2205 struct flow_miss {
2206     struct hmap_node hmap_node;
2207     struct flow flow;
2208     enum odp_key_fitness key_fitness;
2209     const struct nlattr *key;
2210     size_t key_len;
2211     struct list packets;
2212 };
2213
2214 struct flow_miss_op {
2215     union dpif_op dpif_op;
2216     struct subfacet *subfacet;
2217 };
2218
2219 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
2220  * OpenFlow controller as necessary according to their individual
2221  * configurations.
2222  *
2223  * If 'clone' is true, the caller retains ownership of 'packet'.  Otherwise,
2224  * ownership is transferred to this function. */
2225 static void
2226 send_packet_in_miss(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2227                     const struct flow *flow, bool clone)
2228 {
2229     struct ofputil_packet_in pin;
2230
2231     pin.packet = packet;
2232     pin.in_port = flow->in_port;
2233     pin.reason = OFPR_NO_MATCH;
2234     pin.buffer_id = 0;          /* not yet known */
2235     pin.send_len = 0;           /* not used for flow table misses */
2236     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2237                            clone ? NULL : packet);
2238 }
2239
2240 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_ACTION to each
2241  * OpenFlow controller as necessary according to their individual
2242  * configurations.
2243  *
2244  * 'send_len' should be the number of bytes of 'packet' to send to the
2245  * controller, as specified in the action that caused the packet to be sent.
2246  *
2247  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
2248  * Otherwise, ownership is transferred to this function. */
2249 static void
2250 send_packet_in_action(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2251                       uint64_t userdata, const struct flow *flow, bool clone)
2252 {
2253     struct ofputil_packet_in pin;
2254     struct user_action_cookie cookie;
2255
2256     memcpy(&cookie, &userdata, sizeof(cookie));
2257
2258     pin.packet = packet;
2259     pin.in_port = flow->in_port;
2260     pin.reason = OFPR_ACTION;
2261     pin.buffer_id = 0;          /* not yet known */
2262     pin.send_len = cookie.data;
2263     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2264                            clone ? NULL : packet);
2265 }
2266
2267 static bool
2268 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
2269                 const struct ofpbuf *packet)
2270 {
2271     struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
2272
2273     if (!ofport) {
2274         return false;
2275     }
2276
2277     if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
2278         if (packet) {
2279             cfm_process_heartbeat(ofport->cfm, packet);
2280         }
2281         return true;
2282     } else if (ofport->bundle && ofport->bundle->lacp
2283                && flow->dl_type == htons(ETH_TYPE_LACP)) {
2284         if (packet) {
2285             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
2286         }
2287         return true;
2288     } else if (ofproto->stp && stp_should_process_flow(flow)) {
2289         if (packet) {
2290             stp_process_packet(ofport, packet);
2291         }
2292         return true;
2293     }
2294     return false;
2295 }
2296
2297 static struct flow_miss *
2298 flow_miss_create(struct hmap *todo, const struct flow *flow,
2299                  enum odp_key_fitness key_fitness,
2300                  const struct nlattr *key, size_t key_len)
2301 {
2302     uint32_t hash = flow_hash(flow, 0);
2303     struct flow_miss *miss;
2304
2305     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
2306         if (flow_equal(&miss->flow, flow)) {
2307             return miss;
2308         }
2309     }
2310
2311     miss = xmalloc(sizeof *miss);
2312     hmap_insert(todo, &miss->hmap_node, hash);
2313     miss->flow = *flow;
2314     miss->key_fitness = key_fitness;
2315     miss->key = key;
2316     miss->key_len = key_len;
2317     list_init(&miss->packets);
2318     return miss;
2319 }
2320
2321 static void
2322 handle_flow_miss(struct ofproto_dpif *ofproto, struct flow_miss *miss,
2323                  struct flow_miss_op *ops, size_t *n_ops)
2324 {
2325     const struct flow *flow = &miss->flow;
2326     struct ofpbuf *packet, *next_packet;
2327     struct subfacet *subfacet;
2328     struct facet *facet;
2329
2330     facet = facet_lookup_valid(ofproto, flow);
2331     if (!facet) {
2332         struct rule_dpif *rule;
2333
2334         rule = rule_dpif_lookup(ofproto, flow, 0);
2335         if (!rule) {
2336             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
2337             struct ofport_dpif *port = get_ofp_port(ofproto, flow->in_port);
2338             if (port) {
2339                 if (port->up.opp.config & htonl(OFPPC_NO_PACKET_IN)) {
2340                     COVERAGE_INC(ofproto_dpif_no_packet_in);
2341                     /* XXX install 'drop' flow entry */
2342                     return;
2343                 }
2344             } else {
2345                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
2346                              flow->in_port);
2347             }
2348
2349             LIST_FOR_EACH_SAFE (packet, next_packet, list_node,
2350                                 &miss->packets) {
2351                 list_remove(&packet->list_node);
2352                 send_packet_in_miss(ofproto, packet, flow, false);
2353             }
2354
2355             return;
2356         }
2357
2358         facet = facet_create(rule, flow);
2359     }
2360
2361     subfacet = subfacet_create(ofproto, facet,
2362                                miss->key_fitness, miss->key, miss->key_len);
2363
2364     LIST_FOR_EACH_SAFE (packet, next_packet, list_node, &miss->packets) {
2365         list_remove(&packet->list_node);
2366         ofproto->n_matches++;
2367
2368         if (facet->rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
2369             /*
2370              * Extra-special case for fail-open mode.
2371              *
2372              * We are in fail-open mode and the packet matched the fail-open
2373              * rule, but we are connected to a controller too.  We should send
2374              * the packet up to the controller in the hope that it will try to
2375              * set up a flow and thereby allow us to exit fail-open.
2376              *
2377              * See the top-level comment in fail-open.c for more information.
2378              */
2379             send_packet_in_miss(ofproto, packet, flow, true);
2380         }
2381
2382         if (!facet->may_install) {
2383             facet_make_actions(ofproto, facet, packet);
2384         }
2385         if (!execute_controller_action(ofproto, &facet->flow,
2386                                        facet->actions, facet->actions_len,
2387                                        packet)) {
2388             struct flow_miss_op *op = &ops[(*n_ops)++];
2389             struct dpif_execute *execute = &op->dpif_op.execute;
2390
2391             op->subfacet = subfacet;
2392             execute->type = DPIF_OP_EXECUTE;
2393             execute->key = miss->key;
2394             execute->key_len = miss->key_len;
2395             execute->actions
2396                 = (facet->may_install
2397                    ? facet->actions
2398                    : xmemdup(facet->actions, facet->actions_len));
2399             execute->actions_len = facet->actions_len;
2400             execute->packet = packet;
2401         }
2402     }
2403
2404     if (facet->may_install && subfacet->key_fitness != ODP_FIT_TOO_LITTLE) {
2405         struct flow_miss_op *op = &ops[(*n_ops)++];
2406         struct dpif_flow_put *put = &op->dpif_op.flow_put;
2407
2408         op->subfacet = subfacet;
2409         put->type = DPIF_OP_FLOW_PUT;
2410         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2411         put->key = miss->key;
2412         put->key_len = miss->key_len;
2413         put->actions = facet->actions;
2414         put->actions_len = facet->actions_len;
2415         put->stats = NULL;
2416     }
2417 }
2418
2419 static void
2420 handle_miss_upcalls(struct ofproto_dpif *ofproto, struct dpif_upcall *upcalls,
2421                     size_t n_upcalls)
2422 {
2423     struct dpif_upcall *upcall;
2424     struct flow_miss *miss, *next_miss;
2425     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
2426     union dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
2427     struct hmap todo;
2428     size_t n_ops;
2429     size_t i;
2430
2431     if (!n_upcalls) {
2432         return;
2433     }
2434
2435     /* Construct the to-do list.
2436      *
2437      * This just amounts to extracting the flow from each packet and sticking
2438      * the packets that have the same flow in the same "flow_miss" structure so
2439      * that we can process them together. */
2440     hmap_init(&todo);
2441     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
2442         enum odp_key_fitness fitness;
2443         struct flow_miss *miss;
2444         struct flow flow;
2445
2446         /* Obtain metadata and check userspace/kernel agreement on flow match,
2447          * then set 'flow''s header pointers. */
2448         fitness = odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2449         if (fitness == ODP_FIT_ERROR) {
2450             continue;
2451         }
2452         flow_extract(upcall->packet, flow.priority, flow.tun_id,
2453                      flow.in_port, &flow);
2454
2455         /* Handle 802.1ag, LACP, and STP specially. */
2456         if (process_special(ofproto, &flow, upcall->packet)) {
2457             ofpbuf_delete(upcall->packet);
2458             ofproto->n_matches++;
2459             continue;
2460         }
2461
2462         /* Add other packets to a to-do list. */
2463         miss = flow_miss_create(&todo, &flow, fitness,
2464                                 upcall->key, upcall->key_len);
2465         list_push_back(&miss->packets, &upcall->packet->list_node);
2466     }
2467
2468     /* Process each element in the to-do list, constructing the set of
2469      * operations to batch. */
2470     n_ops = 0;
2471     HMAP_FOR_EACH_SAFE (miss, next_miss, hmap_node, &todo) {
2472         handle_flow_miss(ofproto, miss, flow_miss_ops, &n_ops);
2473         ofpbuf_list_delete(&miss->packets);
2474         hmap_remove(&todo, &miss->hmap_node);
2475         free(miss);
2476     }
2477     assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
2478     hmap_destroy(&todo);
2479
2480     /* Execute batch. */
2481     for (i = 0; i < n_ops; i++) {
2482         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
2483     }
2484     dpif_operate(ofproto->dpif, dpif_ops, n_ops);
2485
2486     /* Free memory and update facets. */
2487     for (i = 0; i < n_ops; i++) {
2488         struct flow_miss_op *op = &flow_miss_ops[i];
2489         struct dpif_execute *execute;
2490         struct dpif_flow_put *put;
2491
2492         switch (op->dpif_op.type) {
2493         case DPIF_OP_EXECUTE:
2494             execute = &op->dpif_op.execute;
2495             if (op->subfacet->facet->actions != execute->actions) {
2496                 free((struct nlattr *) execute->actions);
2497             }
2498             ofpbuf_delete((struct ofpbuf *) execute->packet);
2499             break;
2500
2501         case DPIF_OP_FLOW_PUT:
2502             put = &op->dpif_op.flow_put;
2503             if (!put->error) {
2504                 op->subfacet->installed = true;
2505             }
2506             break;
2507         }
2508     }
2509 }
2510
2511 static void
2512 handle_userspace_upcall(struct ofproto_dpif *ofproto,
2513                         struct dpif_upcall *upcall)
2514 {
2515     struct flow flow;
2516     struct user_action_cookie cookie;
2517
2518     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
2519
2520     if (cookie.type == USER_ACTION_COOKIE_SFLOW) {
2521         if (ofproto->sflow) {
2522             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2523             dpif_sflow_received(ofproto->sflow, upcall->packet, &flow, &cookie);
2524         }
2525         ofpbuf_delete(upcall->packet);
2526
2527     } else if (cookie.type == USER_ACTION_COOKIE_CONTROLLER) {
2528         COVERAGE_INC(ofproto_dpif_ctlr_action);
2529         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2530         send_packet_in_action(ofproto, upcall->packet, upcall->userdata,
2531                               &flow, false);
2532     } else {
2533         VLOG_WARN_RL(&rl, "invalid user cookie : 0x%"PRIx64, upcall->userdata);
2534     }
2535 }
2536
2537 static void
2538 handle_upcall(struct ofproto_dpif *ofproto, struct dpif_upcall *upcall)
2539 {
2540     switch (upcall->type) {
2541     case DPIF_UC_ACTION:
2542         handle_userspace_upcall(ofproto, upcall);
2543         break;
2544
2545     case DPIF_UC_MISS:
2546         /* The caller handles these. */
2547         NOT_REACHED();
2548
2549     case DPIF_N_UC_TYPES:
2550     default:
2551         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
2552         break;
2553     }
2554 }
2555 \f
2556 /* Flow expiration. */
2557
2558 static int subfacet_max_idle(const struct ofproto_dpif *);
2559 static void update_stats(struct ofproto_dpif *);
2560 static void rule_expire(struct rule_dpif *);
2561 static void expire_subfacets(struct ofproto_dpif *, int dp_max_idle);
2562
2563 /* This function is called periodically by run().  Its job is to collect
2564  * updates for the flows that have been installed into the datapath, most
2565  * importantly when they last were used, and then use that information to
2566  * expire flows that have not been used recently.
2567  *
2568  * Returns the number of milliseconds after which it should be called again. */
2569 static int
2570 expire(struct ofproto_dpif *ofproto)
2571 {
2572     struct rule_dpif *rule, *next_rule;
2573     struct classifier *table;
2574     int dp_max_idle;
2575
2576     /* Update stats for each flow in the datapath. */
2577     update_stats(ofproto);
2578
2579     /* Expire subfacets that have been idle too long. */
2580     dp_max_idle = subfacet_max_idle(ofproto);
2581     expire_subfacets(ofproto, dp_max_idle);
2582
2583     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
2584     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
2585         struct cls_cursor cursor;
2586
2587         cls_cursor_init(&cursor, table, NULL);
2588         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
2589             rule_expire(rule);
2590         }
2591     }
2592
2593     /* All outstanding data in existing flows has been accounted, so it's a
2594      * good time to do bond rebalancing. */
2595     if (ofproto->has_bonded_bundles) {
2596         struct ofbundle *bundle;
2597
2598         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2599             if (bundle->bond) {
2600                 bond_rebalance(bundle->bond, &ofproto->revalidate_set);
2601             }
2602         }
2603     }
2604
2605     return MIN(dp_max_idle, 1000);
2606 }
2607
2608 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
2609  *
2610  * This function also pushes statistics updates to rules which each facet
2611  * resubmits into.  Generally these statistics will be accurate.  However, if a
2612  * facet changes the rule it resubmits into at some time in between
2613  * update_stats() runs, it is possible that statistics accrued to the
2614  * old rule will be incorrectly attributed to the new rule.  This could be
2615  * avoided by calling update_stats() whenever rules are created or
2616  * deleted.  However, the performance impact of making so many calls to the
2617  * datapath do not justify the benefit of having perfectly accurate statistics.
2618  */
2619 static void
2620 update_stats(struct ofproto_dpif *p)
2621 {
2622     const struct dpif_flow_stats *stats;
2623     struct dpif_flow_dump dump;
2624     const struct nlattr *key;
2625     size_t key_len;
2626
2627     dpif_flow_dump_start(&dump, p->dpif);
2628     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
2629         enum odp_key_fitness fitness;
2630         struct subfacet *subfacet;
2631         struct flow flow;
2632
2633         fitness = odp_flow_key_to_flow(key, key_len, &flow);
2634         if (fitness == ODP_FIT_ERROR) {
2635             continue;
2636         }
2637
2638         subfacet = subfacet_find(p, key, key_len, &flow);
2639         if (subfacet && subfacet->installed) {
2640             struct facet *facet = subfacet->facet;
2641
2642             if (stats->n_packets >= subfacet->dp_packet_count) {
2643                 uint64_t extra = stats->n_packets - subfacet->dp_packet_count;
2644                 facet->packet_count += extra;
2645             } else {
2646                 VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
2647             }
2648
2649             if (stats->n_bytes >= subfacet->dp_byte_count) {
2650                 facet->byte_count += stats->n_bytes - subfacet->dp_byte_count;
2651             } else {
2652                 VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
2653             }
2654
2655             subfacet->dp_packet_count = stats->n_packets;
2656             subfacet->dp_byte_count = stats->n_bytes;
2657
2658             subfacet_update_time(p, subfacet, stats->used);
2659             facet_account(p, facet);
2660             facet_push_stats(facet);
2661         } else {
2662             /* There's a flow in the datapath that we know nothing about, or a
2663              * flow that shouldn't be installed but was anyway.  Delete it. */
2664             COVERAGE_INC(facet_unexpected);
2665             dpif_flow_del(p->dpif, key, key_len, NULL);
2666         }
2667     }
2668     dpif_flow_dump_done(&dump);
2669 }
2670
2671 /* Calculates and returns the number of milliseconds of idle time after which
2672  * subfacets should expire from the datapath.  When a subfacet expires, we fold
2673  * its statistics into its facet, and when a facet's last subfacet expires, we
2674  * fold its statistic into its rule. */
2675 static int
2676 subfacet_max_idle(const struct ofproto_dpif *ofproto)
2677 {
2678     /*
2679      * Idle time histogram.
2680      *
2681      * Most of the time a switch has a relatively small number of subfacets.
2682      * When this is the case we might as well keep statistics for all of them
2683      * in userspace and to cache them in the kernel datapath for performance as
2684      * well.
2685      *
2686      * As the number of subfacets increases, the memory required to maintain
2687      * statistics about them in userspace and in the kernel becomes
2688      * significant.  However, with a large number of subfacets it is likely
2689      * that only a few of them are "heavy hitters" that consume a large amount
2690      * of bandwidth.  At this point, only heavy hitters are worth caching in
2691      * the kernel and maintaining in userspaces; other subfacets we can
2692      * discard.
2693      *
2694      * The technique used to compute the idle time is to build a histogram with
2695      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each subfacet
2696      * that is installed in the kernel gets dropped in the appropriate bucket.
2697      * After the histogram has been built, we compute the cutoff so that only
2698      * the most-recently-used 1% of subfacets (but at least
2699      * ofproto->up.flow_eviction_threshold flows) are kept cached.  At least
2700      * the most-recently-used bucket of subfacets is kept, so actually an
2701      * arbitrary number of subfacets can be kept in any given expiration run
2702      * (though the next run will delete most of those unless they receive
2703      * additional data).
2704      *
2705      * This requires a second pass through the subfacets, in addition to the
2706      * pass made by update_stats(), because the former function never looks at
2707      * uninstallable subfacets.
2708      */
2709     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
2710     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
2711     int buckets[N_BUCKETS] = { 0 };
2712     int total, subtotal, bucket;
2713     struct subfacet *subfacet;
2714     long long int now;
2715     int i;
2716
2717     total = hmap_count(&ofproto->subfacets);
2718     if (total <= ofproto->up.flow_eviction_threshold) {
2719         return N_BUCKETS * BUCKET_WIDTH;
2720     }
2721
2722     /* Build histogram. */
2723     now = time_msec();
2724     HMAP_FOR_EACH (subfacet, hmap_node, &ofproto->subfacets) {
2725         long long int idle = now - subfacet->used;
2726         int bucket = (idle <= 0 ? 0
2727                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
2728                       : (unsigned int) idle / BUCKET_WIDTH);
2729         buckets[bucket]++;
2730     }
2731
2732     /* Find the first bucket whose flows should be expired. */
2733     subtotal = bucket = 0;
2734     do {
2735         subtotal += buckets[bucket++];
2736     } while (bucket < N_BUCKETS &&
2737              subtotal < MAX(ofproto->up.flow_eviction_threshold, total / 100));
2738
2739     if (VLOG_IS_DBG_ENABLED()) {
2740         struct ds s;
2741
2742         ds_init(&s);
2743         ds_put_cstr(&s, "keep");
2744         for (i = 0; i < N_BUCKETS; i++) {
2745             if (i == bucket) {
2746                 ds_put_cstr(&s, ", drop");
2747             }
2748             if (buckets[i]) {
2749                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
2750             }
2751         }
2752         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
2753         ds_destroy(&s);
2754     }
2755
2756     return bucket * BUCKET_WIDTH;
2757 }
2758
2759 static void
2760 expire_subfacets(struct ofproto_dpif *ofproto, int dp_max_idle)
2761 {
2762     long long int cutoff = time_msec() - dp_max_idle;
2763     struct subfacet *subfacet, *next_subfacet;
2764
2765     HMAP_FOR_EACH_SAFE (subfacet, next_subfacet, hmap_node,
2766                         &ofproto->subfacets) {
2767         if (subfacet->used < cutoff) {
2768             subfacet_destroy(ofproto, subfacet);
2769         }
2770     }
2771 }
2772
2773 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
2774  * then delete it entirely. */
2775 static void
2776 rule_expire(struct rule_dpif *rule)
2777 {
2778     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2779     struct facet *facet, *next_facet;
2780     long long int now;
2781     uint8_t reason;
2782
2783     /* Has 'rule' expired? */
2784     now = time_msec();
2785     if (rule->up.hard_timeout
2786         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
2787         reason = OFPRR_HARD_TIMEOUT;
2788     } else if (rule->up.idle_timeout && list_is_empty(&rule->facets)
2789                && now > rule->used + rule->up.idle_timeout * 1000) {
2790         reason = OFPRR_IDLE_TIMEOUT;
2791     } else {
2792         return;
2793     }
2794
2795     COVERAGE_INC(ofproto_dpif_expired);
2796
2797     /* Update stats.  (This is a no-op if the rule expired due to an idle
2798      * timeout, because that only happens when the rule has no facets left.) */
2799     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2800         facet_remove(ofproto, facet);
2801     }
2802
2803     /* Get rid of the rule. */
2804     ofproto_rule_expire(&rule->up, reason);
2805 }
2806 \f
2807 /* Facets. */
2808
2809 /* Creates and returns a new facet owned by 'rule', given a 'flow'.
2810  *
2811  * The caller must already have determined that no facet with an identical
2812  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2813  * the ofproto's classifier table.
2814  *
2815  * The facet will initially have no ODP actions.  The caller should fix that
2816  * by calling facet_make_actions().
2817  *
2818  * The facet will initially have no subfacets.  The caller should create (at
2819  * least) one subfacet with subfacet_create(). */
2820 static struct facet *
2821 facet_create(struct rule_dpif *rule, const struct flow *flow)
2822 {
2823     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2824     struct facet *facet;
2825
2826     facet = xzalloc(sizeof *facet);
2827     facet->used = time_msec();
2828     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2829     list_push_back(&rule->facets, &facet->list_node);
2830     facet->rule = rule;
2831     facet->flow = *flow;
2832     list_init(&facet->subfacets);
2833     netflow_flow_init(&facet->nf_flow);
2834     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2835
2836     return facet;
2837 }
2838
2839 static void
2840 facet_free(struct facet *facet)
2841 {
2842     free(facet->actions);
2843     free(facet);
2844 }
2845
2846 static bool
2847 execute_controller_action(struct ofproto_dpif *ofproto,
2848                           const struct flow *flow,
2849                           const struct nlattr *odp_actions, size_t actions_len,
2850                           struct ofpbuf *packet)
2851 {
2852     if (actions_len
2853         && odp_actions->nla_type == OVS_ACTION_ATTR_USERSPACE
2854         && NLA_ALIGN(odp_actions->nla_len) == actions_len) {
2855         /* As an optimization, avoid a round-trip from userspace to kernel to
2856          * userspace.  This also avoids possibly filling up kernel packet
2857          * buffers along the way.
2858          *
2859          * This optimization will not accidentally catch sFlow
2860          * OVS_ACTION_ATTR_USERSPACE actions, since those are encapsulated
2861          * inside OVS_ACTION_ATTR_SAMPLE. */
2862         const struct nlattr *nla;
2863
2864         nla = nl_attr_find_nested(odp_actions, OVS_USERSPACE_ATTR_USERDATA);
2865         send_packet_in_action(ofproto, packet, nl_attr_get_u64(nla), flow,
2866                               false);
2867         return true;
2868     } else {
2869         return false;
2870     }
2871 }
2872
2873 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2874  * 'packet', which arrived on 'in_port'.
2875  *
2876  * Takes ownership of 'packet'. */
2877 static bool
2878 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
2879                     const struct nlattr *odp_actions, size_t actions_len,
2880                     struct ofpbuf *packet)
2881 {
2882     struct odputil_keybuf keybuf;
2883     struct ofpbuf key;
2884     int error;
2885
2886     if (execute_controller_action(ofproto, flow, odp_actions, actions_len,
2887                                   packet)) {
2888         return true;
2889     }
2890
2891     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2892     odp_flow_key_from_flow(&key, flow);
2893
2894     error = dpif_execute(ofproto->dpif, key.data, key.size,
2895                          odp_actions, actions_len, packet);
2896
2897     ofpbuf_delete(packet);
2898     return !error;
2899 }
2900
2901 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2902  *
2903  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
2904  *     rule's statistics, via subfacet_uninstall().
2905  *
2906  *   - Removes 'facet' from its rule and from ofproto->facets.
2907  */
2908 static void
2909 facet_remove(struct ofproto_dpif *ofproto, struct facet *facet)
2910 {
2911     struct subfacet *subfacet, *next_subfacet;
2912
2913     LIST_FOR_EACH_SAFE (subfacet, next_subfacet, list_node,
2914                         &facet->subfacets) {
2915         subfacet_destroy__(ofproto, subfacet);
2916     }
2917
2918     facet_flush_stats(ofproto, facet);
2919     hmap_remove(&ofproto->facets, &facet->hmap_node);
2920     list_remove(&facet->list_node);
2921     facet_free(facet);
2922 }
2923
2924 /* Composes the datapath actions for 'facet' based on its rule's actions. */
2925 static void
2926 facet_make_actions(struct ofproto_dpif *p, struct facet *facet,
2927                    const struct ofpbuf *packet)
2928 {
2929     const struct rule_dpif *rule = facet->rule;
2930     struct ofpbuf *odp_actions;
2931     struct action_xlate_ctx ctx;
2932
2933     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2934     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
2935     facet->tags = ctx.tags;
2936     facet->may_install = ctx.may_set_up_flow;
2937     facet->has_learn = ctx.has_learn;
2938     facet->has_normal = ctx.has_normal;
2939     facet->nf_flow.output_iface = ctx.nf_output_iface;
2940
2941     if (facet->actions_len != odp_actions->size
2942         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2943         free(facet->actions);
2944         facet->actions_len = odp_actions->size;
2945         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2946     }
2947
2948     ofpbuf_delete(odp_actions);
2949 }
2950
2951 static void
2952 facet_account(struct ofproto_dpif *ofproto, struct facet *facet)
2953 {
2954     uint64_t n_bytes;
2955     const struct nlattr *a;
2956     unsigned int left;
2957     ovs_be16 vlan_tci;
2958
2959     if (facet->byte_count <= facet->accounted_bytes) {
2960         return;
2961     }
2962     n_bytes = facet->byte_count - facet->accounted_bytes;
2963     facet->accounted_bytes = facet->byte_count;
2964
2965     /* Feed information from the active flows back into the learning table to
2966      * ensure that table is always in sync with what is actually flowing
2967      * through the datapath. */
2968     if (facet->has_learn || facet->has_normal) {
2969         struct action_xlate_ctx ctx;
2970
2971         action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2972         ctx.may_learn = true;
2973         ofpbuf_delete(xlate_actions(&ctx, facet->rule->up.actions,
2974                                     facet->rule->up.n_actions));
2975     }
2976
2977     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
2978         return;
2979     }
2980
2981     /* This loop feeds byte counters to bond_account() for rebalancing to use
2982      * as a basis.  We also need to track the actual VLAN on which the packet
2983      * is going to be sent to ensure that it matches the one passed to
2984      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
2985      * hash bucket.) */
2986     vlan_tci = facet->flow.vlan_tci;
2987     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->actions, facet->actions_len) {
2988         const struct ovs_action_push_vlan *vlan;
2989         struct ofport_dpif *port;
2990
2991         switch (nl_attr_type(a)) {
2992         case OVS_ACTION_ATTR_OUTPUT:
2993             port = get_odp_port(ofproto, nl_attr_get_u32(a));
2994             if (port && port->bundle && port->bundle->bond) {
2995                 bond_account(port->bundle->bond, &facet->flow,
2996                              vlan_tci_to_vid(vlan_tci), n_bytes);
2997             }
2998             break;
2999
3000         case OVS_ACTION_ATTR_POP_VLAN:
3001             vlan_tci = htons(0);
3002             break;
3003
3004         case OVS_ACTION_ATTR_PUSH_VLAN:
3005             vlan = nl_attr_get(a);
3006             vlan_tci = vlan->vlan_tci;
3007             break;
3008         }
3009     }
3010 }
3011
3012 /* Returns true if the only action for 'facet' is to send to the controller.
3013  * (We don't report NetFlow expiration messages for such facets because they
3014  * are just part of the control logic for the network, not real traffic). */
3015 static bool
3016 facet_is_controller_flow(struct facet *facet)
3017 {
3018     return (facet
3019             && facet->rule->up.n_actions == 1
3020             && action_outputs_to_port(&facet->rule->up.actions[0],
3021                                       htons(OFPP_CONTROLLER)));
3022 }
3023
3024 /* Folds all of 'facet''s statistics into its rule.  Also updates the
3025  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
3026  * 'facet''s statistics in the datapath should have been zeroed and folded into
3027  * its packet and byte counts before this function is called. */
3028 static void
3029 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
3030 {
3031     struct subfacet *subfacet;
3032
3033     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3034         assert(!subfacet->dp_byte_count);
3035         assert(!subfacet->dp_packet_count);
3036     }
3037
3038     facet_push_stats(facet);
3039     facet_account(ofproto, facet);
3040
3041     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
3042         struct ofexpired expired;
3043         expired.flow = facet->flow;
3044         expired.packet_count = facet->packet_count;
3045         expired.byte_count = facet->byte_count;
3046         expired.used = facet->used;
3047         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
3048     }
3049
3050     facet->rule->packet_count += facet->packet_count;
3051     facet->rule->byte_count += facet->byte_count;
3052
3053     /* Reset counters to prevent double counting if 'facet' ever gets
3054      * reinstalled. */
3055     facet_reset_counters(facet);
3056
3057     netflow_flow_clear(&facet->nf_flow);
3058 }
3059
3060 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3061  * Returns it if found, otherwise a null pointer.
3062  *
3063  * The returned facet might need revalidation; use facet_lookup_valid()
3064  * instead if that is important. */
3065 static struct facet *
3066 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
3067 {
3068     struct facet *facet;
3069
3070     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
3071                              &ofproto->facets) {
3072         if (flow_equal(flow, &facet->flow)) {
3073             return facet;
3074         }
3075     }
3076
3077     return NULL;
3078 }
3079
3080 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3081  * Returns it if found, otherwise a null pointer.
3082  *
3083  * The returned facet is guaranteed to be valid. */
3084 static struct facet *
3085 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
3086 {
3087     struct facet *facet = facet_find(ofproto, flow);
3088
3089     /* The facet we found might not be valid, since we could be in need of
3090      * revalidation.  If it is not valid, don't return it. */
3091     if (facet
3092         && (ofproto->need_revalidate
3093             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))
3094         && !facet_revalidate(ofproto, facet)) {
3095         COVERAGE_INC(facet_invalidated);
3096         return NULL;
3097     }
3098
3099     return facet;
3100 }
3101
3102 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
3103  *
3104  *   - If the rule found is different from 'facet''s current rule, moves
3105  *     'facet' to the new rule and recompiles its actions.
3106  *
3107  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
3108  *     where it is and recompiles its actions anyway.
3109  *
3110  *   - If there is none, destroys 'facet'.
3111  *
3112  * Returns true if 'facet' still exists, false if it has been destroyed. */
3113 static bool
3114 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
3115 {
3116     struct action_xlate_ctx ctx;
3117     struct ofpbuf *odp_actions;
3118     struct rule_dpif *new_rule;
3119     struct subfacet *subfacet;
3120     bool actions_changed;
3121     bool flush_stats;
3122
3123     COVERAGE_INC(facet_revalidate);
3124
3125     /* Determine the new rule. */
3126     new_rule = rule_dpif_lookup(ofproto, &facet->flow, 0);
3127     if (!new_rule) {
3128         /* No new rule, so delete the facet. */
3129         facet_remove(ofproto, facet);
3130         return false;
3131     }
3132
3133     /* Calculate new datapath actions.
3134      *
3135      * We do not modify any 'facet' state yet, because we might need to, e.g.,
3136      * emit a NetFlow expiration and, if so, we need to have the old state
3137      * around to properly compose it. */
3138     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
3139     odp_actions = xlate_actions(&ctx,
3140                                 new_rule->up.actions, new_rule->up.n_actions);
3141     actions_changed = (facet->actions_len != odp_actions->size
3142                        || memcmp(facet->actions, odp_actions->data,
3143                                  facet->actions_len));
3144
3145     /* If the datapath actions changed or the installability changed,
3146      * then we need to talk to the datapath. */
3147     flush_stats = false;
3148     LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
3149         bool should_install = (ctx.may_set_up_flow
3150                                && subfacet->key_fitness != ODP_FIT_TOO_LITTLE);
3151         if (actions_changed || should_install != subfacet->installed) {
3152             if (should_install) {
3153                 struct dpif_flow_stats stats;
3154
3155                 subfacet_install(ofproto, subfacet,
3156                                  odp_actions->data, odp_actions->size, &stats);
3157                 subfacet_update_stats(ofproto, subfacet, &stats);
3158             } else {
3159                 subfacet_uninstall(ofproto, subfacet);
3160             }
3161             flush_stats = true;
3162         }
3163     }
3164     if (flush_stats) {
3165         facet_flush_stats(ofproto, facet);
3166     }
3167
3168     /* Update 'facet' now that we've taken care of all the old state. */
3169     facet->tags = ctx.tags;
3170     facet->nf_flow.output_iface = ctx.nf_output_iface;
3171     facet->may_install = ctx.may_set_up_flow;
3172     facet->has_learn = ctx.has_learn;
3173     facet->has_normal = ctx.has_normal;
3174     if (actions_changed) {
3175         free(facet->actions);
3176         facet->actions_len = odp_actions->size;
3177         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
3178     }
3179     if (facet->rule != new_rule) {
3180         COVERAGE_INC(facet_changed_rule);
3181         list_remove(&facet->list_node);
3182         list_push_back(&new_rule->facets, &facet->list_node);
3183         facet->rule = new_rule;
3184         facet->used = new_rule->up.created;
3185         facet->rs_used = facet->used;
3186     }
3187
3188     ofpbuf_delete(odp_actions);
3189
3190     return true;
3191 }
3192
3193 /* Updates 'facet''s used time.  Caller is responsible for calling
3194  * facet_push_stats() to update the flows which 'facet' resubmits into. */
3195 static void
3196 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
3197                   long long int used)
3198 {
3199     if (used > facet->used) {
3200         facet->used = used;
3201         if (used > facet->rule->used) {
3202             facet->rule->used = used;
3203         }
3204         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3205     }
3206 }
3207
3208 static void
3209 facet_reset_counters(struct facet *facet)
3210 {
3211     facet->packet_count = 0;
3212     facet->byte_count = 0;
3213     facet->rs_packet_count = 0;
3214     facet->rs_byte_count = 0;
3215     facet->accounted_bytes = 0;
3216 }
3217
3218 static void
3219 facet_push_stats(struct facet *facet)
3220 {
3221     uint64_t rs_packets, rs_bytes;
3222
3223     assert(facet->packet_count >= facet->rs_packet_count);
3224     assert(facet->byte_count >= facet->rs_byte_count);
3225     assert(facet->used >= facet->rs_used);
3226
3227     rs_packets = facet->packet_count - facet->rs_packet_count;
3228     rs_bytes = facet->byte_count - facet->rs_byte_count;
3229
3230     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
3231         facet->rs_packet_count = facet->packet_count;
3232         facet->rs_byte_count = facet->byte_count;
3233         facet->rs_used = facet->used;
3234
3235         flow_push_stats(facet->rule, &facet->flow,
3236                         rs_packets, rs_bytes, facet->used);
3237     }
3238 }
3239
3240 struct ofproto_push {
3241     struct action_xlate_ctx ctx;
3242     uint64_t packets;
3243     uint64_t bytes;
3244     long long int used;
3245 };
3246
3247 static void
3248 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
3249 {
3250     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
3251
3252     if (rule) {
3253         rule->packet_count += push->packets;
3254         rule->byte_count += push->bytes;
3255         rule->used = MAX(push->used, rule->used);
3256     }
3257 }
3258
3259 /* Pushes flow statistics to the rules which 'flow' resubmits into given
3260  * 'rule''s actions. */
3261 static void
3262 flow_push_stats(const struct rule_dpif *rule,
3263                 const struct flow *flow, uint64_t packets, uint64_t bytes,
3264                 long long int used)
3265 {
3266     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3267     struct ofproto_push push;
3268
3269     push.packets = packets;
3270     push.bytes = bytes;
3271     push.used = used;
3272
3273     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
3274     push.ctx.resubmit_hook = push_resubmit;
3275     ofpbuf_delete(xlate_actions(&push.ctx,
3276                                 rule->up.actions, rule->up.n_actions));
3277 }
3278 \f
3279 /* Subfacets. */
3280
3281 static struct subfacet *
3282 subfacet_find__(struct ofproto_dpif *ofproto,
3283                 const struct nlattr *key, size_t key_len, uint32_t key_hash,
3284                 const struct flow *flow)
3285 {
3286     struct subfacet *subfacet;
3287
3288     HMAP_FOR_EACH_WITH_HASH (subfacet, hmap_node, key_hash,
3289                              &ofproto->subfacets) {
3290         if (subfacet->key
3291             ? (subfacet->key_len == key_len
3292                && !memcmp(key, subfacet->key, key_len))
3293             : flow_equal(flow, &subfacet->facet->flow)) {
3294             return subfacet;
3295         }
3296     }
3297
3298     return NULL;
3299 }
3300
3301 /* Searches 'facet' (within 'ofproto') for a subfacet with the specified
3302  * 'key_fitness', 'key', and 'key_len'.  Returns the existing subfacet if
3303  * there is one, otherwise creates and returns a new subfacet.  */
3304 static struct subfacet *
3305 subfacet_create(struct ofproto_dpif *ofproto, struct facet *facet,
3306                 enum odp_key_fitness key_fitness,
3307                 const struct nlattr *key, size_t key_len)
3308 {
3309     uint32_t key_hash = odp_flow_key_hash(key, key_len);
3310     struct subfacet *subfacet;
3311
3312     subfacet = subfacet_find__(ofproto, key, key_len, key_hash, &facet->flow);
3313     if (subfacet) {
3314         if (subfacet->facet == facet) {
3315             return subfacet;
3316         }
3317
3318         /* This shouldn't happen. */
3319         VLOG_ERR_RL(&rl, "subfacet with wrong facet");
3320         subfacet_destroy(ofproto, subfacet);
3321     }
3322
3323     subfacet = xzalloc(sizeof *subfacet);
3324     hmap_insert(&ofproto->subfacets, &subfacet->hmap_node, key_hash);
3325     list_push_back(&facet->subfacets, &subfacet->list_node);
3326     subfacet->facet = facet;
3327     subfacet->used = time_msec();
3328     subfacet->key_fitness = key_fitness;
3329     if (key_fitness != ODP_FIT_PERFECT) {
3330         subfacet->key = xmemdup(key, key_len);
3331         subfacet->key_len = key_len;
3332     }
3333     subfacet->installed = false;
3334
3335     return subfacet;
3336 }
3337
3338 /* Searches 'ofproto' for a subfacet with the given 'key', 'key_len', and
3339  * 'flow'.  Returns the subfacet if one exists, otherwise NULL. */
3340 static struct subfacet *
3341 subfacet_find(struct ofproto_dpif *ofproto,
3342               const struct nlattr *key, size_t key_len,
3343               const struct flow *flow)
3344 {
3345     uint32_t key_hash = odp_flow_key_hash(key, key_len);
3346
3347     return subfacet_find__(ofproto, key, key_len, key_hash, flow);
3348 }
3349
3350 /* Uninstalls 'subfacet' from the datapath, if it is installed, removes it from
3351  * its facet within 'ofproto', and frees it. */
3352 static void
3353 subfacet_destroy__(struct ofproto_dpif *ofproto, struct subfacet *subfacet)
3354 {
3355     subfacet_uninstall(ofproto, subfacet);
3356     hmap_remove(&ofproto->subfacets, &subfacet->hmap_node);
3357     list_remove(&subfacet->list_node);
3358     free(subfacet->key);
3359     free(subfacet);
3360 }
3361
3362 /* Destroys 'subfacet', as with subfacet_destroy__(), and then if this was the
3363  * last remaining subfacet in its facet destroys the facet too. */
3364 static void
3365 subfacet_destroy(struct ofproto_dpif *ofproto, struct subfacet *subfacet)
3366 {
3367     struct facet *facet = subfacet->facet;
3368
3369     subfacet_destroy__(ofproto, subfacet);
3370     if (list_is_empty(&facet->subfacets)) {
3371         facet_remove(ofproto, facet);
3372     }
3373 }
3374
3375 /* Initializes 'key' with the sequence of OVS_KEY_ATTR_* Netlink attributes
3376  * that can be used to refer to 'subfacet'.  The caller must provide 'keybuf'
3377  * for use as temporary storage. */
3378 static void
3379 subfacet_get_key(struct subfacet *subfacet, struct odputil_keybuf *keybuf,
3380                  struct ofpbuf *key)
3381 {
3382     if (!subfacet->key) {
3383         ofpbuf_use_stack(key, keybuf, sizeof *keybuf);
3384         odp_flow_key_from_flow(key, &subfacet->facet->flow);
3385     } else {
3386         ofpbuf_use_const(key, subfacet->key, subfacet->key_len);
3387     }
3388 }
3389
3390 /* Updates 'subfacet''s datapath flow, setting its actions to 'actions_len'
3391  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
3392  * in the datapath will be zeroed and 'stats' will be updated with traffic new
3393  * since 'subfacet' was last updated.
3394  *
3395  * Returns 0 if successful, otherwise a positive errno value. */
3396 static int
3397 subfacet_install(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3398                  const struct nlattr *actions, size_t actions_len,
3399                  struct dpif_flow_stats *stats)
3400 {
3401     struct odputil_keybuf keybuf;
3402     enum dpif_flow_put_flags flags;
3403     struct ofpbuf key;
3404     int ret;
3405
3406     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
3407     if (stats) {
3408         flags |= DPIF_FP_ZERO_STATS;
3409     }
3410
3411     subfacet_get_key(subfacet, &keybuf, &key);
3412     ret = dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
3413                         actions, actions_len, stats);
3414
3415     if (stats) {
3416         subfacet_reset_dp_stats(subfacet, stats);
3417     }
3418
3419     return ret;
3420 }
3421
3422 /* If 'subfacet' is installed in the datapath, uninstalls it. */
3423 static void
3424 subfacet_uninstall(struct ofproto_dpif *p, struct subfacet *subfacet)
3425 {
3426     if (subfacet->installed) {
3427         struct odputil_keybuf keybuf;
3428         struct dpif_flow_stats stats;
3429         struct ofpbuf key;
3430         int error;
3431
3432         subfacet_get_key(subfacet, &keybuf, &key);
3433         error = dpif_flow_del(p->dpif, key.data, key.size, &stats);
3434         subfacet_reset_dp_stats(subfacet, &stats);
3435         if (!error) {
3436             subfacet_update_stats(p, subfacet, &stats);
3437         }
3438         subfacet->installed = false;
3439     } else {
3440         assert(subfacet->dp_packet_count == 0);
3441         assert(subfacet->dp_byte_count == 0);
3442     }
3443 }
3444
3445 /* Resets 'subfacet''s datapath statistics counters.  This should be called
3446  * when 'subfacet''s statistics are cleared in the datapath.  If 'stats' is
3447  * non-null, it should contain the statistics returned by dpif when 'subfacet'
3448  * was reset in the datapath.  'stats' will be modified to include only
3449  * statistics new since 'subfacet' was last updated. */
3450 static void
3451 subfacet_reset_dp_stats(struct subfacet *subfacet,
3452                         struct dpif_flow_stats *stats)
3453 {
3454     if (stats
3455         && subfacet->dp_packet_count <= stats->n_packets
3456         && subfacet->dp_byte_count <= stats->n_bytes) {
3457         stats->n_packets -= subfacet->dp_packet_count;
3458         stats->n_bytes -= subfacet->dp_byte_count;
3459     }
3460
3461     subfacet->dp_packet_count = 0;
3462     subfacet->dp_byte_count = 0;
3463 }
3464
3465 /* Updates 'subfacet''s used time.  The caller is responsible for calling
3466  * facet_push_stats() to update the flows which 'subfacet' resubmits into. */
3467 static void
3468 subfacet_update_time(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3469                      long long int used)
3470 {
3471     if (used > subfacet->used) {
3472         subfacet->used = used;
3473         facet_update_time(ofproto, subfacet->facet, used);
3474     }
3475 }
3476
3477 /* Folds the statistics from 'stats' into the counters in 'subfacet'.
3478  *
3479  * Because of the meaning of a subfacet's counters, it only makes sense to do
3480  * this if 'stats' are not tracked in the datapath, that is, if 'stats'
3481  * represents a packet that was sent by hand or if it represents statistics
3482  * that have been cleared out of the datapath. */
3483 static void
3484 subfacet_update_stats(struct ofproto_dpif *ofproto, struct subfacet *subfacet,
3485                       const struct dpif_flow_stats *stats)
3486 {
3487     if (stats->n_packets || stats->used > subfacet->used) {
3488         struct facet *facet = subfacet->facet;
3489
3490         subfacet_update_time(ofproto, subfacet, stats->used);
3491         facet->packet_count += stats->n_packets;
3492         facet->byte_count += stats->n_bytes;
3493         facet_push_stats(facet);
3494         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3495     }
3496 }
3497 \f
3498 /* Rules. */
3499
3500 static struct rule_dpif *
3501 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
3502                  uint8_t table_id)
3503 {
3504     struct cls_rule *cls_rule;
3505     struct classifier *cls;
3506
3507     if (table_id >= N_TABLES) {
3508         return NULL;
3509     }
3510
3511     cls = &ofproto->up.tables[table_id];
3512     if (flow->nw_frag & FLOW_NW_FRAG_ANY
3513         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
3514         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
3515          * are unavailable. */
3516         struct flow ofpc_normal_flow = *flow;
3517         ofpc_normal_flow.tp_src = htons(0);
3518         ofpc_normal_flow.tp_dst = htons(0);
3519         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
3520     } else {
3521         cls_rule = classifier_lookup(cls, flow);
3522     }
3523     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
3524 }
3525
3526 static void
3527 complete_operation(struct rule_dpif *rule)
3528 {
3529     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3530
3531     rule_invalidate(rule);
3532     if (clogged) {
3533         struct dpif_completion *c = xmalloc(sizeof *c);
3534         c->op = rule->up.pending;
3535         list_push_back(&ofproto->completions, &c->list_node);
3536     } else {
3537         ofoperation_complete(rule->up.pending, 0);
3538     }
3539 }
3540
3541 static struct rule *
3542 rule_alloc(void)
3543 {
3544     struct rule_dpif *rule = xmalloc(sizeof *rule);
3545     return &rule->up;
3546 }
3547
3548 static void
3549 rule_dealloc(struct rule *rule_)
3550 {
3551     struct rule_dpif *rule = rule_dpif_cast(rule_);
3552     free(rule);
3553 }
3554
3555 static int
3556 rule_construct(struct rule *rule_)
3557 {
3558     struct rule_dpif *rule = rule_dpif_cast(rule_);
3559     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3560     struct rule_dpif *victim;
3561     uint8_t table_id;
3562     int error;
3563
3564     error = validate_actions(rule->up.actions, rule->up.n_actions,
3565                              &rule->up.cr.flow, ofproto->max_ports);
3566     if (error) {
3567         return error;
3568     }
3569
3570     rule->used = rule->up.created;
3571     rule->packet_count = 0;
3572     rule->byte_count = 0;
3573
3574     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
3575     if (victim && !list_is_empty(&victim->facets)) {
3576         struct facet *facet;
3577
3578         rule->facets = victim->facets;
3579         list_moved(&rule->facets);
3580         LIST_FOR_EACH (facet, list_node, &rule->facets) {
3581             /* XXX: We're only clearing our local counters here.  It's possible
3582              * that quite a few packets are unaccounted for in the datapath
3583              * statistics.  These will be accounted to the new rule instead of
3584              * cleared as required.  This could be fixed by clearing out the
3585              * datapath statistics for this facet, but currently it doesn't
3586              * seem worth it. */
3587             facet_reset_counters(facet);
3588             facet->rule = rule;
3589         }
3590     } else {
3591         /* Must avoid list_moved() in this case. */
3592         list_init(&rule->facets);
3593     }
3594
3595     table_id = rule->up.table_id;
3596     rule->tag = (victim ? victim->tag
3597                  : table_id == 0 ? 0
3598                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
3599                                       ofproto->tables[table_id].basis));
3600
3601     complete_operation(rule);
3602     return 0;
3603 }
3604
3605 static void
3606 rule_destruct(struct rule *rule_)
3607 {
3608     struct rule_dpif *rule = rule_dpif_cast(rule_);
3609     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3610     struct facet *facet, *next_facet;
3611
3612     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3613         facet_revalidate(ofproto, facet);
3614     }
3615
3616     complete_operation(rule);
3617 }
3618
3619 static void
3620 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
3621 {
3622     struct rule_dpif *rule = rule_dpif_cast(rule_);
3623     struct facet *facet;
3624
3625     /* Start from historical data for 'rule' itself that are no longer tracked
3626      * in facets.  This counts, for example, facets that have expired. */
3627     *packets = rule->packet_count;
3628     *bytes = rule->byte_count;
3629
3630     /* Add any statistics that are tracked by facets.  This includes
3631      * statistical data recently updated by ofproto_update_stats() as well as
3632      * stats for packets that were executed "by hand" via dpif_execute(). */
3633     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3634         *packets += facet->packet_count;
3635         *bytes += facet->byte_count;
3636     }
3637 }
3638
3639 static int
3640 rule_execute(struct rule *rule_, const struct flow *flow,
3641              struct ofpbuf *packet)
3642 {
3643     struct rule_dpif *rule = rule_dpif_cast(rule_);
3644     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3645     struct action_xlate_ctx ctx;
3646     struct ofpbuf *odp_actions;
3647     size_t size;
3648
3649     action_xlate_ctx_init(&ctx, ofproto, flow, packet);
3650     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3651     size = packet->size;
3652     if (execute_odp_actions(ofproto, flow, odp_actions->data,
3653                             odp_actions->size, packet)) {
3654         rule->used = time_msec();
3655         rule->packet_count++;
3656         rule->byte_count += size;
3657         flow_push_stats(rule, flow, 1, size, rule->used);
3658     }
3659     ofpbuf_delete(odp_actions);
3660
3661     return 0;
3662 }
3663
3664 static void
3665 rule_modify_actions(struct rule *rule_)
3666 {
3667     struct rule_dpif *rule = rule_dpif_cast(rule_);
3668     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3669     int error;
3670
3671     error = validate_actions(rule->up.actions, rule->up.n_actions,
3672                              &rule->up.cr.flow, ofproto->max_ports);
3673     if (error) {
3674         ofoperation_complete(rule->up.pending, error);
3675         return;
3676     }
3677
3678     complete_operation(rule);
3679 }
3680 \f
3681 /* Sends 'packet' out 'ofport'.
3682  * Returns 0 if successful, otherwise a positive errno value. */
3683 static int
3684 send_packet(const struct ofport_dpif *ofport, const struct ofpbuf *packet)
3685 {
3686     const struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
3687     uint16_t odp_port = ofport->odp_port;
3688     struct ofpbuf key, odp_actions;
3689     struct odputil_keybuf keybuf;
3690     struct flow flow;
3691     int error;
3692
3693     flow_extract((struct ofpbuf *) packet, 0, 0, 0, &flow);
3694     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3695     odp_flow_key_from_flow(&key, &flow);
3696
3697     ofpbuf_init(&odp_actions, 32);
3698     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
3699
3700     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3701     error = dpif_execute(ofproto->dpif,
3702                          key.data, key.size,
3703                          odp_actions.data, odp_actions.size,
3704                          packet);
3705     ofpbuf_uninit(&odp_actions);
3706
3707     if (error) {
3708         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
3709                      ofproto->up.name, odp_port, strerror(error));
3710     }
3711     return error;
3712 }
3713 \f
3714 /* OpenFlow to datapath action translation. */
3715
3716 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
3717                              struct action_xlate_ctx *ctx);
3718 static void xlate_normal(struct action_xlate_ctx *);
3719
3720 static size_t
3721 put_userspace_action(const struct ofproto_dpif *ofproto,
3722                      struct ofpbuf *odp_actions,
3723                      const struct flow *flow,
3724                      const struct user_action_cookie *cookie)
3725 {
3726     uint32_t pid;
3727
3728     pid = dpif_port_get_pid(ofproto->dpif,
3729                             ofp_port_to_odp_port(flow->in_port));
3730
3731     return odp_put_userspace_action(pid, cookie, odp_actions);
3732 }
3733
3734 /* Compose SAMPLE action for sFlow. */
3735 static size_t
3736 compose_sflow_action(const struct ofproto_dpif *ofproto,
3737                      struct ofpbuf *odp_actions,
3738                      const struct flow *flow,
3739                      uint32_t odp_port)
3740 {
3741     uint32_t port_ifindex;
3742     uint32_t probability;
3743     struct user_action_cookie cookie;
3744     size_t sample_offset, actions_offset;
3745     int cookie_offset, n_output;
3746
3747     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
3748         return 0;
3749     }
3750
3751     if (odp_port == OVSP_NONE) {
3752         port_ifindex = 0;
3753         n_output = 0;
3754     } else {
3755         port_ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
3756         n_output = 1;
3757     }
3758
3759     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
3760
3761     /* Number of packets out of UINT_MAX to sample. */
3762     probability = dpif_sflow_get_probability(ofproto->sflow);
3763     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
3764
3765     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
3766
3767     cookie.type = USER_ACTION_COOKIE_SFLOW;
3768     cookie.data = port_ifindex;
3769     cookie.n_output = n_output;
3770     cookie.vlan_tci = 0;
3771     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
3772
3773     nl_msg_end_nested(odp_actions, actions_offset);
3774     nl_msg_end_nested(odp_actions, sample_offset);
3775     return cookie_offset;
3776 }
3777
3778 /* SAMPLE action must be first action in any given list of actions.
3779  * At this point we do not have all information required to build it. So try to
3780  * build sample action as complete as possible. */
3781 static void
3782 add_sflow_action(struct action_xlate_ctx *ctx)
3783 {
3784     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
3785                                                    ctx->odp_actions,
3786                                                    &ctx->flow, OVSP_NONE);
3787     ctx->sflow_odp_port = 0;
3788     ctx->sflow_n_outputs = 0;
3789 }
3790
3791 /* Fix SAMPLE action according to data collected while composing ODP actions.
3792  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
3793  * USERSPACE action's user-cookie which is required for sflow. */
3794 static void
3795 fix_sflow_action(struct action_xlate_ctx *ctx)
3796 {
3797     const struct flow *base = &ctx->base_flow;
3798     struct user_action_cookie *cookie;
3799
3800     if (!ctx->user_cookie_offset) {
3801         return;
3802     }
3803
3804     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
3805                      sizeof(*cookie));
3806     assert(cookie != NULL);
3807     assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
3808
3809     if (ctx->sflow_n_outputs) {
3810         cookie->data = dpif_sflow_odp_port_to_ifindex(ctx->ofproto->sflow,
3811                                                     ctx->sflow_odp_port);
3812     }
3813     if (ctx->sflow_n_outputs >= 255) {
3814         cookie->n_output = 255;
3815     } else {
3816         cookie->n_output = ctx->sflow_n_outputs;
3817     }
3818     cookie->vlan_tci = base->vlan_tci;
3819 }
3820
3821 static void
3822 commit_set_action(struct ofpbuf *odp_actions, enum ovs_key_attr key_type,
3823                   const void *key, size_t key_size)
3824 {
3825     size_t offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SET);
3826     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
3827     nl_msg_end_nested(odp_actions, offset);
3828 }
3829
3830 static void
3831 commit_set_tun_id_action(const struct flow *flow, struct flow *base,
3832                          struct ofpbuf *odp_actions)
3833 {
3834     if (base->tun_id == flow->tun_id) {
3835         return;
3836     }
3837     base->tun_id = flow->tun_id;
3838
3839     commit_set_action(odp_actions, OVS_KEY_ATTR_TUN_ID,
3840                       &base->tun_id, sizeof(base->tun_id));
3841 }
3842
3843 static void
3844 commit_set_ether_addr_action(const struct flow *flow, struct flow *base,
3845                              struct ofpbuf *odp_actions)
3846 {
3847     struct ovs_key_ethernet eth_key;
3848
3849     if (eth_addr_equals(base->dl_src, flow->dl_src) &&
3850         eth_addr_equals(base->dl_dst, flow->dl_dst)) {
3851         return;
3852     }
3853
3854     memcpy(base->dl_src, flow->dl_src, ETH_ADDR_LEN);
3855     memcpy(base->dl_dst, flow->dl_dst, ETH_ADDR_LEN);
3856
3857     memcpy(eth_key.eth_src, base->dl_src, ETH_ADDR_LEN);
3858     memcpy(eth_key.eth_dst, base->dl_dst, ETH_ADDR_LEN);
3859
3860     commit_set_action(odp_actions, OVS_KEY_ATTR_ETHERNET,
3861                       &eth_key, sizeof(eth_key));
3862 }
3863
3864 static void
3865 commit_vlan_action(const struct flow *flow, struct flow *base,
3866                    struct ofpbuf *odp_actions)
3867 {
3868     if (base->vlan_tci == flow->vlan_tci) {
3869         return;
3870     }
3871
3872     if (base->vlan_tci & htons(VLAN_CFI)) {
3873         nl_msg_put_flag(odp_actions, OVS_ACTION_ATTR_POP_VLAN);
3874     }
3875
3876     if (flow->vlan_tci & htons(VLAN_CFI)) {
3877         struct ovs_action_push_vlan vlan;
3878
3879         vlan.vlan_tpid = htons(ETH_TYPE_VLAN);
3880         vlan.vlan_tci = flow->vlan_tci;
3881         nl_msg_put_unspec(odp_actions, OVS_ACTION_ATTR_PUSH_VLAN,
3882                           &vlan, sizeof vlan);
3883     }
3884     base->vlan_tci = flow->vlan_tci;
3885 }
3886
3887 static void
3888 commit_set_nw_action(const struct flow *flow, struct flow *base,
3889                      struct ofpbuf *odp_actions)
3890 {
3891     struct ovs_key_ipv4 ipv4_key;
3892
3893     if (base->dl_type != htons(ETH_TYPE_IP) ||
3894         !base->nw_src || !base->nw_dst) {
3895         return;
3896     }
3897
3898     if (base->nw_src == flow->nw_src &&
3899         base->nw_dst == flow->nw_dst &&
3900         base->nw_tos == flow->nw_tos &&
3901         base->nw_ttl == flow->nw_ttl &&
3902         base->nw_frag == flow->nw_frag) {
3903         return;
3904     }
3905
3906     ipv4_key.ipv4_src = base->nw_src = flow->nw_src;
3907     ipv4_key.ipv4_dst = base->nw_dst = flow->nw_dst;
3908     ipv4_key.ipv4_tos = base->nw_tos = flow->nw_tos;
3909     ipv4_key.ipv4_ttl = base->nw_ttl = flow->nw_ttl;
3910     ipv4_key.ipv4_proto = base->nw_proto;
3911     ipv4_key.ipv4_frag = (base->nw_frag == 0 ? OVS_FRAG_TYPE_NONE
3912                           : base->nw_frag == FLOW_NW_FRAG_ANY
3913                           ? OVS_FRAG_TYPE_FIRST : OVS_FRAG_TYPE_LATER);
3914
3915     commit_set_action(odp_actions, OVS_KEY_ATTR_IPV4,
3916                       &ipv4_key, sizeof(ipv4_key));
3917 }
3918
3919 static void
3920 commit_set_port_action(const struct flow *flow, struct flow *base,
3921                        struct ofpbuf *odp_actions)
3922 {
3923     if (!base->tp_src || !base->tp_dst) {
3924         return;
3925     }
3926
3927     if (base->tp_src == flow->tp_src &&
3928         base->tp_dst == flow->tp_dst) {
3929         return;
3930     }
3931
3932     if (flow->nw_proto == IPPROTO_TCP) {
3933         struct ovs_key_tcp port_key;
3934
3935         port_key.tcp_src = base->tp_src = flow->tp_src;
3936         port_key.tcp_dst = base->tp_dst = flow->tp_dst;
3937
3938         commit_set_action(odp_actions, OVS_KEY_ATTR_TCP,
3939                           &port_key, sizeof(port_key));
3940
3941     } else if (flow->nw_proto == IPPROTO_UDP) {
3942         struct ovs_key_udp port_key;
3943
3944         port_key.udp_src = base->tp_src = flow->tp_src;
3945         port_key.udp_dst = base->tp_dst = flow->tp_dst;
3946
3947         commit_set_action(odp_actions, OVS_KEY_ATTR_UDP,
3948                           &port_key, sizeof(port_key));
3949     }
3950 }
3951
3952 static void
3953 commit_set_priority_action(const struct flow *flow, struct flow *base,
3954                            struct ofpbuf *odp_actions)
3955 {
3956     if (base->priority == flow->priority) {
3957         return;
3958     }
3959     base->priority = flow->priority;
3960
3961     commit_set_action(odp_actions, OVS_KEY_ATTR_PRIORITY,
3962                       &base->priority, sizeof(base->priority));
3963 }
3964
3965 static void
3966 commit_odp_actions(struct action_xlate_ctx *ctx)
3967 {
3968     const struct flow *flow = &ctx->flow;
3969     struct flow *base = &ctx->base_flow;
3970     struct ofpbuf *odp_actions = ctx->odp_actions;
3971
3972     commit_set_tun_id_action(flow, base, odp_actions);
3973     commit_set_ether_addr_action(flow, base, odp_actions);
3974     commit_vlan_action(flow, base, odp_actions);
3975     commit_set_nw_action(flow, base, odp_actions);
3976     commit_set_port_action(flow, base, odp_actions);
3977     commit_set_priority_action(flow, base, odp_actions);
3978 }
3979
3980 static void
3981 compose_output_action__(struct action_xlate_ctx *ctx, uint16_t ofp_port,
3982                         bool check_stp)
3983 {
3984     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
3985     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
3986     uint8_t flow_nw_tos = ctx->flow.nw_tos;
3987
3988     if (ofport) {
3989         struct priority_to_dscp *pdscp;
3990
3991         if (ofport->up.opp.config & htonl(OFPPC_NO_FWD)
3992             || (check_stp && !stp_forward_in_state(ofport->stp_state))) {
3993             return;
3994         }
3995
3996         pdscp = get_priority(ofport, ctx->flow.priority);
3997         if (pdscp) {
3998             ctx->flow.nw_tos &= ~IP_DSCP_MASK;
3999             ctx->flow.nw_tos |= pdscp->dscp;
4000         }
4001     } else {
4002         /* We may not have an ofport record for this port, but it doesn't hurt
4003          * to allow forwarding to it anyhow.  Maybe such a port will appear
4004          * later and we're pre-populating the flow table.  */
4005     }
4006
4007     commit_odp_actions(ctx);
4008     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
4009     ctx->sflow_odp_port = odp_port;
4010     ctx->sflow_n_outputs++;
4011     ctx->nf_output_iface = ofp_port;
4012     ctx->flow.nw_tos = flow_nw_tos;
4013 }
4014
4015 static void
4016 compose_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
4017 {
4018     compose_output_action__(ctx, ofp_port, true);
4019 }
4020
4021 static void
4022 xlate_table_action(struct action_xlate_ctx *ctx,
4023                    uint16_t in_port, uint8_t table_id)
4024 {
4025     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
4026         struct ofproto_dpif *ofproto = ctx->ofproto;
4027         struct rule_dpif *rule;
4028         uint16_t old_in_port;
4029         uint8_t old_table_id;
4030
4031         old_table_id = ctx->table_id;
4032         ctx->table_id = table_id;
4033
4034         /* Look up a flow with 'in_port' as the input port. */
4035         old_in_port = ctx->flow.in_port;
4036         ctx->flow.in_port = in_port;
4037         rule = rule_dpif_lookup(ofproto, &ctx->flow, table_id);
4038
4039         /* Tag the flow. */
4040         if (table_id > 0 && table_id < N_TABLES) {
4041             struct table_dpif *table = &ofproto->tables[table_id];
4042             if (table->other_table) {
4043                 ctx->tags |= (rule
4044                               ? rule->tag
4045                               : rule_calculate_tag(&ctx->flow,
4046                                                    &table->other_table->wc,
4047                                                    table->basis));
4048             }
4049         }
4050
4051         /* Restore the original input port.  Otherwise OFPP_NORMAL and
4052          * OFPP_IN_PORT will have surprising behavior. */
4053         ctx->flow.in_port = old_in_port;
4054
4055         if (ctx->resubmit_hook) {
4056             ctx->resubmit_hook(ctx, rule);
4057         }
4058
4059         if (rule) {
4060             ctx->recurse++;
4061             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
4062             ctx->recurse--;
4063         }
4064
4065         ctx->table_id = old_table_id;
4066     } else {
4067         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
4068
4069         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
4070                     MAX_RESUBMIT_RECURSION);
4071     }
4072 }
4073
4074 static void
4075 xlate_resubmit_table(struct action_xlate_ctx *ctx,
4076                      const struct nx_action_resubmit *nar)
4077 {
4078     uint16_t in_port;
4079     uint8_t table_id;
4080
4081     in_port = (nar->in_port == htons(OFPP_IN_PORT)
4082                ? ctx->flow.in_port
4083                : ntohs(nar->in_port));
4084     table_id = nar->table == 255 ? ctx->table_id : nar->table;
4085
4086     xlate_table_action(ctx, in_port, table_id);
4087 }
4088
4089 static void
4090 flood_packets(struct action_xlate_ctx *ctx, bool all)
4091 {
4092     struct ofport_dpif *ofport;
4093
4094     commit_odp_actions(ctx);
4095     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
4096         uint16_t ofp_port = ofport->up.ofp_port;
4097
4098         if (ofp_port == ctx->flow.in_port) {
4099             continue;
4100         }
4101
4102         if (all) {
4103             compose_output_action__(ctx, ofp_port, false);
4104         } else if (!(ofport->up.opp.config & htonl(OFPPC_NO_FLOOD))) {
4105             compose_output_action(ctx, ofp_port);
4106         }
4107     }
4108
4109     ctx->nf_output_iface = NF_OUT_FLOOD;
4110 }
4111
4112 static void
4113 compose_controller_action(struct action_xlate_ctx *ctx, int len)
4114 {
4115     struct user_action_cookie cookie;
4116
4117     commit_odp_actions(ctx);
4118     cookie.type = USER_ACTION_COOKIE_CONTROLLER;
4119     cookie.data = len;
4120     cookie.n_output = 0;
4121     cookie.vlan_tci = 0;
4122     put_userspace_action(ctx->ofproto, ctx->odp_actions, &ctx->flow, &cookie);
4123 }
4124
4125 static void
4126 xlate_output_action__(struct action_xlate_ctx *ctx,
4127                       uint16_t port, uint16_t max_len)
4128 {
4129     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
4130
4131     ctx->nf_output_iface = NF_OUT_DROP;
4132
4133     switch (port) {
4134     case OFPP_IN_PORT:
4135         compose_output_action(ctx, ctx->flow.in_port);
4136         break;
4137     case OFPP_TABLE:
4138         xlate_table_action(ctx, ctx->flow.in_port, ctx->table_id);
4139         break;
4140     case OFPP_NORMAL:
4141         xlate_normal(ctx);
4142         break;
4143     case OFPP_FLOOD:
4144         flood_packets(ctx,  false);
4145         break;
4146     case OFPP_ALL:
4147         flood_packets(ctx, true);
4148         break;
4149     case OFPP_CONTROLLER:
4150         compose_controller_action(ctx, max_len);
4151         break;
4152     case OFPP_LOCAL:
4153         compose_output_action(ctx, OFPP_LOCAL);
4154         break;
4155     case OFPP_NONE:
4156         break;
4157     default:
4158         if (port != ctx->flow.in_port) {
4159             compose_output_action(ctx, port);
4160         }
4161         break;
4162     }
4163
4164     if (prev_nf_output_iface == NF_OUT_FLOOD) {
4165         ctx->nf_output_iface = NF_OUT_FLOOD;
4166     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
4167         ctx->nf_output_iface = prev_nf_output_iface;
4168     } else if (prev_nf_output_iface != NF_OUT_DROP &&
4169                ctx->nf_output_iface != NF_OUT_FLOOD) {
4170         ctx->nf_output_iface = NF_OUT_MULTI;
4171     }
4172 }
4173
4174 static void
4175 xlate_output_reg_action(struct action_xlate_ctx *ctx,
4176                         const struct nx_action_output_reg *naor)
4177 {
4178     uint64_t ofp_port;
4179
4180     ofp_port = nxm_read_field_bits(naor->src, naor->ofs_nbits, &ctx->flow);
4181
4182     if (ofp_port <= UINT16_MAX) {
4183         xlate_output_action__(ctx, ofp_port, ntohs(naor->max_len));
4184     }
4185 }
4186
4187 static void
4188 xlate_output_action(struct action_xlate_ctx *ctx,
4189                     const struct ofp_action_output *oao)
4190 {
4191     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
4192 }
4193
4194 static void
4195 xlate_enqueue_action(struct action_xlate_ctx *ctx,
4196                      const struct ofp_action_enqueue *oae)
4197 {
4198     uint16_t ofp_port;
4199     uint32_t flow_priority, priority;
4200     int error;
4201
4202     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
4203                                    &priority);
4204     if (error) {
4205         /* Fall back to ordinary output action. */
4206         xlate_output_action__(ctx, ntohs(oae->port), 0);
4207         return;
4208     }
4209
4210     /* Figure out datapath output port. */
4211     ofp_port = ntohs(oae->port);
4212     if (ofp_port == OFPP_IN_PORT) {
4213         ofp_port = ctx->flow.in_port;
4214     } else if (ofp_port == ctx->flow.in_port) {
4215         return;
4216     }
4217
4218     /* Add datapath actions. */
4219     flow_priority = ctx->flow.priority;
4220     ctx->flow.priority = priority;
4221     compose_output_action(ctx, ofp_port);
4222     ctx->flow.priority = flow_priority;
4223
4224     /* Update NetFlow output port. */
4225     if (ctx->nf_output_iface == NF_OUT_DROP) {
4226         ctx->nf_output_iface = ofp_port;
4227     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
4228         ctx->nf_output_iface = NF_OUT_MULTI;
4229     }
4230 }
4231
4232 static void
4233 xlate_set_queue_action(struct action_xlate_ctx *ctx,
4234                        const struct nx_action_set_queue *nasq)
4235 {
4236     uint32_t priority;
4237     int error;
4238
4239     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
4240                                    &priority);
4241     if (error) {
4242         /* Couldn't translate queue to a priority, so ignore.  A warning
4243          * has already been logged. */
4244         return;
4245     }
4246
4247     ctx->flow.priority = priority;
4248 }
4249
4250 struct xlate_reg_state {
4251     ovs_be16 vlan_tci;
4252     ovs_be64 tun_id;
4253 };
4254
4255 static void
4256 xlate_autopath(struct action_xlate_ctx *ctx,
4257                const struct nx_action_autopath *naa)
4258 {
4259     uint16_t ofp_port = ntohl(naa->id);
4260     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
4261
4262     if (!port || !port->bundle) {
4263         ofp_port = OFPP_NONE;
4264     } else if (port->bundle->bond) {
4265         /* Autopath does not support VLAN hashing. */
4266         struct ofport_dpif *slave = bond_choose_output_slave(
4267             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
4268         if (slave) {
4269             ofp_port = slave->up.ofp_port;
4270         }
4271     }
4272     autopath_execute(naa, &ctx->flow, ofp_port);
4273 }
4274
4275 static bool
4276 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
4277 {
4278     struct ofproto_dpif *ofproto = ofproto_;
4279     struct ofport_dpif *port;
4280
4281     switch (ofp_port) {
4282     case OFPP_IN_PORT:
4283     case OFPP_TABLE:
4284     case OFPP_NORMAL:
4285     case OFPP_FLOOD:
4286     case OFPP_ALL:
4287     case OFPP_NONE:
4288         return true;
4289     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
4290         return false;
4291     default:
4292         port = get_ofp_port(ofproto, ofp_port);
4293         return port ? port->may_enable : false;
4294     }
4295 }
4296
4297 static void
4298 xlate_learn_action(struct action_xlate_ctx *ctx,
4299                    const struct nx_action_learn *learn)
4300 {
4301     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
4302     struct ofputil_flow_mod fm;
4303     int error;
4304
4305     learn_execute(learn, &ctx->flow, &fm);
4306
4307     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
4308     if (error && !VLOG_DROP_WARN(&rl)) {
4309         char *msg = ofputil_error_to_string(error);
4310         VLOG_WARN("learning action failed to modify flow table (%s)", msg);
4311         free(msg);
4312     }
4313
4314     free(fm.actions);
4315 }
4316
4317 static bool
4318 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
4319 {
4320     if (port->up.opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
4321                                ? htonl(OFPPC_NO_RECV_STP)
4322                                : htonl(OFPPC_NO_RECV))) {
4323         return false;
4324     }
4325
4326     /* Only drop packets here if both forwarding and learning are
4327      * disabled.  If just learning is enabled, we need to have
4328      * OFPP_NORMAL and the learning action have a look at the packet
4329      * before we can drop it. */
4330     if (!stp_forward_in_state(port->stp_state)
4331             && !stp_learn_in_state(port->stp_state)) {
4332         return false;
4333     }
4334
4335     return true;
4336 }
4337
4338 static void
4339 do_xlate_actions(const union ofp_action *in, size_t n_in,
4340                  struct action_xlate_ctx *ctx)
4341 {
4342     const struct ofport_dpif *port;
4343     const union ofp_action *ia;
4344     size_t left;
4345
4346     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
4347     if (port && !may_receive(port, ctx)) {
4348         /* Drop this flow. */
4349         return;
4350     }
4351
4352     OFPUTIL_ACTION_FOR_EACH_UNSAFE (ia, left, in, n_in) {
4353         const struct ofp_action_dl_addr *oada;
4354         const struct nx_action_resubmit *nar;
4355         const struct nx_action_set_tunnel *nast;
4356         const struct nx_action_set_queue *nasq;
4357         const struct nx_action_multipath *nam;
4358         const struct nx_action_autopath *naa;
4359         const struct nx_action_bundle *nab;
4360         const struct nx_action_output_reg *naor;
4361         enum ofputil_action_code code;
4362         ovs_be64 tun_id;
4363
4364         if (ctx->exit) {
4365             break;
4366         }
4367
4368         code = ofputil_decode_action_unsafe(ia);
4369         switch (code) {
4370         case OFPUTIL_OFPAT_OUTPUT:
4371             xlate_output_action(ctx, &ia->output);
4372             break;
4373
4374         case OFPUTIL_OFPAT_SET_VLAN_VID:
4375             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
4376             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
4377             break;
4378
4379         case OFPUTIL_OFPAT_SET_VLAN_PCP:
4380             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
4381             ctx->flow.vlan_tci |= htons(
4382                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
4383             break;
4384
4385         case OFPUTIL_OFPAT_STRIP_VLAN:
4386             ctx->flow.vlan_tci = htons(0);
4387             break;
4388
4389         case OFPUTIL_OFPAT_SET_DL_SRC:
4390             oada = ((struct ofp_action_dl_addr *) ia);
4391             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
4392             break;
4393
4394         case OFPUTIL_OFPAT_SET_DL_DST:
4395             oada = ((struct ofp_action_dl_addr *) ia);
4396             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
4397             break;
4398
4399         case OFPUTIL_OFPAT_SET_NW_SRC:
4400             ctx->flow.nw_src = ia->nw_addr.nw_addr;
4401             break;
4402
4403         case OFPUTIL_OFPAT_SET_NW_DST:
4404             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
4405             break;
4406
4407         case OFPUTIL_OFPAT_SET_NW_TOS:
4408             ctx->flow.nw_tos &= ~IP_DSCP_MASK;
4409             ctx->flow.nw_tos |= ia->nw_tos.nw_tos & IP_DSCP_MASK;
4410             break;
4411
4412         case OFPUTIL_OFPAT_SET_TP_SRC:
4413             ctx->flow.tp_src = ia->tp_port.tp_port;
4414             break;
4415
4416         case OFPUTIL_OFPAT_SET_TP_DST:
4417             ctx->flow.tp_dst = ia->tp_port.tp_port;
4418             break;
4419
4420         case OFPUTIL_OFPAT_ENQUEUE:
4421             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
4422             break;
4423
4424         case OFPUTIL_NXAST_RESUBMIT:
4425             nar = (const struct nx_action_resubmit *) ia;
4426             xlate_table_action(ctx, ntohs(nar->in_port), ctx->table_id);
4427             break;
4428
4429         case OFPUTIL_NXAST_RESUBMIT_TABLE:
4430             xlate_resubmit_table(ctx, (const struct nx_action_resubmit *) ia);
4431             break;
4432
4433         case OFPUTIL_NXAST_SET_TUNNEL:
4434             nast = (const struct nx_action_set_tunnel *) ia;
4435             tun_id = htonll(ntohl(nast->tun_id));
4436             ctx->flow.tun_id = tun_id;
4437             break;
4438
4439         case OFPUTIL_NXAST_SET_QUEUE:
4440             nasq = (const struct nx_action_set_queue *) ia;
4441             xlate_set_queue_action(ctx, nasq);
4442             break;
4443
4444         case OFPUTIL_NXAST_POP_QUEUE:
4445             ctx->flow.priority = ctx->original_priority;
4446             break;
4447
4448         case OFPUTIL_NXAST_REG_MOVE:
4449             nxm_execute_reg_move((const struct nx_action_reg_move *) ia,
4450                                  &ctx->flow);
4451             break;
4452
4453         case OFPUTIL_NXAST_REG_LOAD:
4454             nxm_execute_reg_load((const struct nx_action_reg_load *) ia,
4455                                  &ctx->flow);
4456             break;
4457
4458         case OFPUTIL_NXAST_NOTE:
4459             /* Nothing to do. */
4460             break;
4461
4462         case OFPUTIL_NXAST_SET_TUNNEL64:
4463             tun_id = ((const struct nx_action_set_tunnel64 *) ia)->tun_id;
4464             ctx->flow.tun_id = tun_id;
4465             break;
4466
4467         case OFPUTIL_NXAST_MULTIPATH:
4468             nam = (const struct nx_action_multipath *) ia;
4469             multipath_execute(nam, &ctx->flow);
4470             break;
4471
4472         case OFPUTIL_NXAST_AUTOPATH:
4473             naa = (const struct nx_action_autopath *) ia;
4474             xlate_autopath(ctx, naa);
4475             break;
4476
4477         case OFPUTIL_NXAST_BUNDLE:
4478             ctx->ofproto->has_bundle_action = true;
4479             nab = (const struct nx_action_bundle *) ia;
4480             xlate_output_action__(ctx, bundle_execute(nab, &ctx->flow,
4481                                                       slave_enabled_cb,
4482                                                       ctx->ofproto), 0);
4483             break;
4484
4485         case OFPUTIL_NXAST_BUNDLE_LOAD:
4486             ctx->ofproto->has_bundle_action = true;
4487             nab = (const struct nx_action_bundle *) ia;
4488             bundle_execute_load(nab, &ctx->flow, slave_enabled_cb,
4489                                 ctx->ofproto);
4490             break;
4491
4492         case OFPUTIL_NXAST_OUTPUT_REG:
4493             naor = (const struct nx_action_output_reg *) ia;
4494             xlate_output_reg_action(ctx, naor);
4495             break;
4496
4497         case OFPUTIL_NXAST_LEARN:
4498             ctx->has_learn = true;
4499             if (ctx->may_learn) {
4500                 xlate_learn_action(ctx, (const struct nx_action_learn *) ia);
4501             }
4502             break;
4503
4504         case OFPUTIL_NXAST_EXIT:
4505             ctx->exit = true;
4506             break;
4507         }
4508     }
4509
4510     /* We've let OFPP_NORMAL and the learning action look at the packet,
4511      * so drop it now if forwarding is disabled. */
4512     if (port && !stp_forward_in_state(port->stp_state)) {
4513         ofpbuf_clear(ctx->odp_actions);
4514         add_sflow_action(ctx);
4515     }
4516 }
4517
4518 static void
4519 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
4520                       struct ofproto_dpif *ofproto, const struct flow *flow,
4521                       const struct ofpbuf *packet)
4522 {
4523     ctx->ofproto = ofproto;
4524     ctx->flow = *flow;
4525     ctx->packet = packet;
4526     ctx->may_learn = packet != NULL;
4527     ctx->resubmit_hook = NULL;
4528 }
4529
4530 static struct ofpbuf *
4531 xlate_actions(struct action_xlate_ctx *ctx,
4532               const union ofp_action *in, size_t n_in)
4533 {
4534     COVERAGE_INC(ofproto_dpif_xlate);
4535
4536     ctx->odp_actions = ofpbuf_new(512);
4537     ofpbuf_reserve(ctx->odp_actions, NL_A_U32_SIZE);
4538     ctx->tags = 0;
4539     ctx->may_set_up_flow = true;
4540     ctx->has_learn = false;
4541     ctx->has_normal = false;
4542     ctx->nf_output_iface = NF_OUT_DROP;
4543     ctx->recurse = 0;
4544     ctx->original_priority = ctx->flow.priority;
4545     ctx->base_flow = ctx->flow;
4546     ctx->base_flow.tun_id = 0;
4547     ctx->table_id = 0;
4548     ctx->exit = false;
4549
4550     if (ctx->flow.nw_frag & FLOW_NW_FRAG_ANY) {
4551         switch (ctx->ofproto->up.frag_handling) {
4552         case OFPC_FRAG_NORMAL:
4553             /* We must pretend that transport ports are unavailable. */
4554             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
4555             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
4556             break;
4557
4558         case OFPC_FRAG_DROP:
4559             return ctx->odp_actions;
4560
4561         case OFPC_FRAG_REASM:
4562             NOT_REACHED();
4563
4564         case OFPC_FRAG_NX_MATCH:
4565             /* Nothing to do. */
4566             break;
4567         }
4568     }
4569
4570     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
4571         ctx->may_set_up_flow = false;
4572         return ctx->odp_actions;
4573     } else {
4574         add_sflow_action(ctx);
4575         do_xlate_actions(in, n_in, ctx);
4576
4577         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
4578                                      ctx->odp_actions->data,
4579                                      ctx->odp_actions->size)) {
4580             ctx->may_set_up_flow = false;
4581             if (ctx->packet
4582                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
4583                                        ctx->packet)) {
4584                 compose_output_action(ctx, OFPP_LOCAL);
4585             }
4586         }
4587         fix_sflow_action(ctx);
4588     }
4589
4590     return ctx->odp_actions;
4591 }
4592 \f
4593 /* OFPP_NORMAL implementation. */
4594
4595 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
4596
4597 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
4598  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
4599  * the bundle on which the packet was received, returns the VLAN to which the
4600  * packet belongs.
4601  *
4602  * Both 'vid' and the return value are in the range 0...4095. */
4603 static uint16_t
4604 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
4605 {
4606     switch (in_bundle->vlan_mode) {
4607     case PORT_VLAN_ACCESS:
4608         return in_bundle->vlan;
4609         break;
4610
4611     case PORT_VLAN_TRUNK:
4612         return vid;
4613
4614     case PORT_VLAN_NATIVE_UNTAGGED:
4615     case PORT_VLAN_NATIVE_TAGGED:
4616         return vid ? vid : in_bundle->vlan;
4617
4618     default:
4619         NOT_REACHED();
4620     }
4621 }
4622
4623 /* Checks whether a packet with the given 'vid' may ingress on 'in_bundle'.
4624  * If so, returns true.  Otherwise, returns false and, if 'warn' is true, logs
4625  * a warning.
4626  *
4627  * 'vid' should be the VID obtained from the 802.1Q header that was received as
4628  * part of a packet (specify 0 if there was no 802.1Q header), in the range
4629  * 0...4095. */
4630 static bool
4631 input_vid_is_valid(uint16_t vid, struct ofbundle *in_bundle, bool warn)
4632 {
4633     switch (in_bundle->vlan_mode) {
4634     case PORT_VLAN_ACCESS:
4635         if (vid) {
4636             if (warn) {
4637                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4638                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" tagged "
4639                              "packet received on port %s configured as VLAN "
4640                              "%"PRIu16" access port",
4641                              in_bundle->ofproto->up.name, vid,
4642                              in_bundle->name, in_bundle->vlan);
4643             }
4644             return false;
4645         }
4646         return true;
4647
4648     case PORT_VLAN_NATIVE_UNTAGGED:
4649     case PORT_VLAN_NATIVE_TAGGED:
4650         if (!vid) {
4651             /* Port must always carry its native VLAN. */
4652             return true;
4653         }
4654         /* Fall through. */
4655     case PORT_VLAN_TRUNK:
4656         if (!ofbundle_includes_vlan(in_bundle, vid)) {
4657             if (warn) {
4658                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4659                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %"PRIu16" packet "
4660                              "received on port %s not configured for trunking "
4661                              "VLAN %"PRIu16,
4662                              in_bundle->ofproto->up.name, vid,
4663                              in_bundle->name, vid);
4664             }
4665             return false;
4666         }
4667         return true;
4668
4669     default:
4670         NOT_REACHED();
4671     }
4672
4673 }
4674
4675 /* Given 'vlan', the VLAN that a packet belongs to, and
4676  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
4677  * that should be included in the 802.1Q header.  (If the return value is 0,
4678  * then the 802.1Q header should only be included in the packet if there is a
4679  * nonzero PCP.)
4680  *
4681  * Both 'vlan' and the return value are in the range 0...4095. */
4682 static uint16_t
4683 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
4684 {
4685     switch (out_bundle->vlan_mode) {
4686     case PORT_VLAN_ACCESS:
4687         return 0;
4688
4689     case PORT_VLAN_TRUNK:
4690     case PORT_VLAN_NATIVE_TAGGED:
4691         return vlan;
4692
4693     case PORT_VLAN_NATIVE_UNTAGGED:
4694         return vlan == out_bundle->vlan ? 0 : vlan;
4695
4696     default:
4697         NOT_REACHED();
4698     }
4699 }
4700
4701 static void
4702 output_normal(struct action_xlate_ctx *ctx, const struct ofbundle *out_bundle,
4703               uint16_t vlan)
4704 {
4705     struct ofport_dpif *port;
4706     uint16_t vid;
4707     ovs_be16 tci, old_tci;
4708
4709     vid = output_vlan_to_vid(out_bundle, vlan);
4710     if (!out_bundle->bond) {
4711         port = ofbundle_get_a_port(out_bundle);
4712     } else {
4713         port = bond_choose_output_slave(out_bundle->bond, &ctx->flow,
4714                                         vid, &ctx->tags);
4715         if (!port) {
4716             /* No slaves enabled, so drop packet. */
4717             return;
4718         }
4719     }
4720
4721     old_tci = ctx->flow.vlan_tci;
4722     tci = htons(vid);
4723     if (tci || out_bundle->use_priority_tags) {
4724         tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
4725         if (tci) {
4726             tci |= htons(VLAN_CFI);
4727         }
4728     }
4729     ctx->flow.vlan_tci = tci;
4730
4731     compose_output_action(ctx, port->up.ofp_port);
4732     ctx->flow.vlan_tci = old_tci;
4733 }
4734
4735 static int
4736 mirror_mask_ffs(mirror_mask_t mask)
4737 {
4738     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
4739     return ffs(mask);
4740 }
4741
4742 static bool
4743 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
4744 {
4745     return (bundle->vlan_mode != PORT_VLAN_ACCESS
4746             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
4747 }
4748
4749 static bool
4750 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
4751 {
4752     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
4753 }
4754
4755 /* Returns an arbitrary interface within 'bundle'. */
4756 static struct ofport_dpif *
4757 ofbundle_get_a_port(const struct ofbundle *bundle)
4758 {
4759     return CONTAINER_OF(list_front(&bundle->ports),
4760                         struct ofport_dpif, bundle_node);
4761 }
4762
4763 static mirror_mask_t
4764 compose_dsts(struct action_xlate_ctx *ctx, uint16_t vlan,
4765              const struct ofbundle *in_bundle,
4766              const struct ofbundle *out_bundle)
4767 {
4768     mirror_mask_t dst_mirrors = 0;
4769
4770     if (out_bundle == OFBUNDLE_FLOOD) {
4771         struct ofbundle *bundle;
4772
4773         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
4774             if (bundle != in_bundle
4775                 && ofbundle_includes_vlan(bundle, vlan)
4776                 && bundle->floodable
4777                 && !bundle->mirror_out) {
4778                 output_normal(ctx, bundle, vlan);
4779                 dst_mirrors |= bundle->dst_mirrors;
4780             }
4781         }
4782         ctx->nf_output_iface = NF_OUT_FLOOD;
4783     } else if (out_bundle) {
4784         output_normal(ctx, out_bundle, vlan);
4785         dst_mirrors = out_bundle->dst_mirrors;
4786     }
4787
4788     return dst_mirrors;
4789 }
4790
4791 static bool
4792 vlan_is_mirrored(const struct ofmirror *m, int vlan)
4793 {
4794     return !m->vlans || bitmap_is_set(m->vlans, vlan);
4795 }
4796
4797 /* Returns true if a packet with Ethernet destination MAC 'dst' may be mirrored
4798  * to a VLAN.  In general most packets may be mirrored but we want to drop
4799  * protocols that may confuse switches. */
4800 static bool
4801 eth_dst_may_rspan(const uint8_t dst[ETH_ADDR_LEN])
4802 {
4803     /* If you change this function's behavior, please update corresponding
4804      * documentation in vswitch.xml at the same time. */
4805     if (dst[0] != 0x01) {
4806         /* All the currently banned MACs happen to start with 01 currently, so
4807          * this is a quick way to eliminate most of the good ones. */
4808     } else {
4809         if (eth_addr_is_reserved(dst)) {
4810             /* Drop STP, IEEE pause frames, and other reserved protocols
4811              * (01-80-c2-00-00-0x). */
4812             return false;
4813         }
4814
4815         if (dst[0] == 0x01 && dst[1] == 0x00 && dst[2] == 0x0c) {
4816             /* Cisco OUI. */
4817             if ((dst[3] & 0xfe) == 0xcc &&
4818                 (dst[4] & 0xfe) == 0xcc &&
4819                 (dst[5] & 0xfe) == 0xcc) {
4820                 /* Drop the following protocols plus others following the same
4821                    pattern:
4822
4823                    CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
4824                    Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
4825                    STP Uplink Fast      (01-00-0c-cd-cd-cd) */
4826                 return false;
4827             }
4828
4829             if (!(dst[3] | dst[4] | dst[5])) {
4830                 /* Drop Inter Switch Link packets (01-00-0c-00-00-00). */
4831                 return false;
4832             }
4833         }
4834     }
4835     return true;
4836 }
4837
4838 static void
4839 output_mirrors(struct action_xlate_ctx *ctx,
4840                uint16_t vlan, const struct ofbundle *in_bundle,
4841                mirror_mask_t dst_mirrors)
4842 {
4843     struct ofproto_dpif *ofproto = ctx->ofproto;
4844     mirror_mask_t mirrors;
4845
4846     mirrors = in_bundle->src_mirrors | dst_mirrors;
4847     if (!mirrors) {
4848         return;
4849     }
4850
4851     while (mirrors) {
4852         struct ofmirror *m;
4853
4854         m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
4855
4856         if (!vlan_is_mirrored(m, vlan)) {
4857             mirrors &= mirrors - 1;
4858             continue;
4859         }
4860
4861         mirrors &= ~m->dup_mirrors;
4862         if (m->out) {
4863             output_normal(ctx, m->out, vlan);
4864         } else if (eth_dst_may_rspan(ctx->flow.dl_dst)
4865                    && vlan != m->out_vlan) {
4866             struct ofbundle *bundle;
4867
4868             HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4869                 if (ofbundle_includes_vlan(bundle, m->out_vlan)
4870                     && !bundle->mirror_out) {
4871                     output_normal(ctx, bundle, m->out_vlan);
4872                 }
4873             }
4874         }
4875     }
4876 }
4877
4878 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
4879  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
4880  * indicate this; newer upstream kernels use gratuitous ARP requests. */
4881 static bool
4882 is_gratuitous_arp(const struct flow *flow)
4883 {
4884     return (flow->dl_type == htons(ETH_TYPE_ARP)
4885             && eth_addr_is_broadcast(flow->dl_dst)
4886             && (flow->nw_proto == ARP_OP_REPLY
4887                 || (flow->nw_proto == ARP_OP_REQUEST
4888                     && flow->nw_src == flow->nw_dst)));
4889 }
4890
4891 static void
4892 update_learning_table(struct ofproto_dpif *ofproto,
4893                       const struct flow *flow, int vlan,
4894                       struct ofbundle *in_bundle)
4895 {
4896     struct mac_entry *mac;
4897
4898     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
4899         return;
4900     }
4901
4902     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
4903     if (is_gratuitous_arp(flow)) {
4904         /* We don't want to learn from gratuitous ARP packets that are
4905          * reflected back over bond slaves so we lock the learning table. */
4906         if (!in_bundle->bond) {
4907             mac_entry_set_grat_arp_lock(mac);
4908         } else if (mac_entry_is_grat_arp_locked(mac)) {
4909             return;
4910         }
4911     }
4912
4913     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
4914         /* The log messages here could actually be useful in debugging,
4915          * so keep the rate limit relatively high. */
4916         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
4917         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
4918                     "on port %s in VLAN %d",
4919                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
4920                     in_bundle->name, vlan);
4921
4922         mac->port.p = in_bundle;
4923         tag_set_add(&ofproto->revalidate_set,
4924                     mac_learning_changed(ofproto->ml, mac));
4925     }
4926 }
4927
4928 static struct ofport_dpif *
4929 lookup_input_bundle(struct ofproto_dpif *ofproto, uint16_t in_port, bool warn)
4930 {
4931     struct ofport_dpif *ofport;
4932
4933     /* Find the port and bundle for the received packet. */
4934     ofport = get_ofp_port(ofproto, in_port);
4935     if (ofport && ofport->bundle) {
4936         return ofport;
4937     }
4938
4939     /* Odd.  A few possible reasons here:
4940      *
4941      * - We deleted a port but there are still a few packets queued up
4942      *   from it.
4943      *
4944      * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
4945      *   we don't know about.
4946      *
4947      * - The ofproto client didn't configure the port as part of a bundle.
4948      */
4949     if (warn) {
4950         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4951
4952         VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
4953                      "port %"PRIu16, ofproto->up.name, in_port);
4954     }
4955     return NULL;
4956 }
4957
4958 /* Determines whether packets in 'flow' within 'ofproto' should be forwarded or
4959  * dropped.  Returns true if they may be forwarded, false if they should be
4960  * dropped.
4961  *
4962  * 'in_port' must be the ofport_dpif that corresponds to flow->in_port.
4963  * 'in_port' must be part of a bundle (e.g. in_port->bundle must be nonnull).
4964  *
4965  * 'vlan' must be the VLAN that corresponds to flow->vlan_tci on 'in_port', as
4966  * returned by input_vid_to_vlan().  It must be a valid VLAN for 'in_port', as
4967  * checked by input_vid_is_valid().
4968  *
4969  * May also add tags to '*tags', although the current implementation only does
4970  * so in one special case.
4971  */
4972 static bool
4973 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
4974               struct ofport_dpif *in_port, uint16_t vlan, tag_type *tags)
4975 {
4976     struct ofbundle *in_bundle = in_port->bundle;
4977
4978     /* Drop frames for reserved multicast addresses
4979      * only if forward_bpdu option is absent. */
4980     if (eth_addr_is_reserved(flow->dl_dst) && !ofproto->up.forward_bpdu) {
4981         return false;
4982     }
4983
4984     if (in_bundle->bond) {
4985         struct mac_entry *mac;
4986
4987         switch (bond_check_admissibility(in_bundle->bond, in_port,
4988                                          flow->dl_dst, tags)) {
4989         case BV_ACCEPT:
4990             break;
4991
4992         case BV_DROP:
4993             return false;
4994
4995         case BV_DROP_IF_MOVED:
4996             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
4997             if (mac && mac->port.p != in_bundle &&
4998                 (!is_gratuitous_arp(flow)
4999                  || mac_entry_is_grat_arp_locked(mac))) {
5000                 return false;
5001             }
5002             break;
5003         }
5004     }
5005
5006     return true;
5007 }
5008
5009 static void
5010 xlate_normal(struct action_xlate_ctx *ctx)
5011 {
5012     mirror_mask_t dst_mirrors = 0;
5013     struct ofport_dpif *in_port;
5014     struct ofbundle *in_bundle;
5015     struct ofbundle *out_bundle;
5016     struct mac_entry *mac;
5017     uint16_t vlan;
5018     uint16_t vid;
5019
5020     ctx->has_normal = true;
5021
5022     /* Obtain in_port from ctx->flow.in_port.
5023      *
5024      * lookup_input_bundle() also ensures that in_port belongs to a bundle. */
5025     in_port = lookup_input_bundle(ctx->ofproto, ctx->flow.in_port,
5026                                   ctx->packet != NULL);
5027     if (!in_port) {
5028         return;
5029     }
5030     in_bundle = in_port->bundle;
5031
5032     /* Drop malformed frames. */
5033     if (ctx->flow.dl_type == htons(ETH_TYPE_VLAN) &&
5034         !(ctx->flow.vlan_tci & htons(VLAN_CFI))) {
5035         if (ctx->packet != NULL) {
5036             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5037             VLOG_WARN_RL(&rl, "bridge %s: dropping packet with partial "
5038                          "VLAN tag received on port %s",
5039                          ctx->ofproto->up.name, in_bundle->name);
5040         }
5041         return;
5042     }
5043
5044     /* Drop frames on bundles reserved for mirroring. */
5045     if (in_bundle->mirror_out) {
5046         if (ctx->packet != NULL) {
5047             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
5048             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
5049                          "%s, which is reserved exclusively for mirroring",
5050                          ctx->ofproto->up.name, in_bundle->name);
5051         }
5052         return;
5053     }
5054
5055     /* Check VLAN. */
5056     vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
5057     if (!input_vid_is_valid(vid, in_bundle, ctx->packet != NULL)) {
5058         return;
5059     }
5060     vlan = input_vid_to_vlan(in_bundle, vid);
5061
5062     /* Check other admissibility requirements. */
5063     if (!is_admissible(ctx->ofproto, &ctx->flow, in_port, vlan, &ctx->tags)) {
5064         output_mirrors(ctx, vlan, in_bundle, 0);
5065         return;
5066     }
5067
5068     /* Learn source MAC. */
5069     if (ctx->may_learn) {
5070         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
5071     }
5072
5073     /* Determine output bundle. */
5074     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
5075                               &ctx->tags);
5076     if (mac) {
5077         out_bundle = mac->port.p;
5078     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
5079         /* If we are revalidating but don't have a learning entry then eject
5080          * the flow.  Installing a flow that floods packets opens up a window
5081          * of time where we could learn from a packet reflected on a bond and
5082          * blackhole packets before the learning table is updated to reflect
5083          * the correct port. */
5084         ctx->may_set_up_flow = false;
5085         return;
5086     } else {
5087         out_bundle = OFBUNDLE_FLOOD;
5088     }
5089
5090     /* Don't send packets out their input bundles. */
5091     if (in_bundle != out_bundle) {
5092         dst_mirrors = compose_dsts(ctx, vlan, in_bundle, out_bundle);
5093     }
5094     output_mirrors(ctx, vlan, in_bundle, dst_mirrors);
5095 }
5096 \f
5097 /* Optimized flow revalidation.
5098  *
5099  * It's a difficult problem, in general, to tell which facets need to have
5100  * their actions recalculated whenever the OpenFlow flow table changes.  We
5101  * don't try to solve that general problem: for most kinds of OpenFlow flow
5102  * table changes, we recalculate the actions for every facet.  This is
5103  * relatively expensive, but it's good enough if the OpenFlow flow table
5104  * doesn't change very often.
5105  *
5106  * However, we can expect one particular kind of OpenFlow flow table change to
5107  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
5108  * of CPU on revalidating every facet whenever MAC learning modifies the flow
5109  * table, we add a special case that applies to flow tables in which every rule
5110  * has the same form (that is, the same wildcards), except that the table is
5111  * also allowed to have a single "catch-all" flow that matches all packets.  We
5112  * optimize this case by tagging all of the facets that resubmit into the table
5113  * and invalidating the same tag whenever a flow changes in that table.  The
5114  * end result is that we revalidate just the facets that need it (and sometimes
5115  * a few more, but not all of the facets or even all of the facets that
5116  * resubmit to the table modified by MAC learning). */
5117
5118 /* Calculates the tag to use for 'flow' and wildcards 'wc' when it is inserted
5119  * into an OpenFlow table with the given 'basis'. */
5120 static uint32_t
5121 rule_calculate_tag(const struct flow *flow, const struct flow_wildcards *wc,
5122                    uint32_t secret)
5123 {
5124     if (flow_wildcards_is_catchall(wc)) {
5125         return 0;
5126     } else {
5127         struct flow tag_flow = *flow;
5128         flow_zero_wildcards(&tag_flow, wc);
5129         return tag_create_deterministic(flow_hash(&tag_flow, secret));
5130     }
5131 }
5132
5133 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
5134  * taggability of that table.
5135  *
5136  * This function must be called after *each* change to a flow table.  If you
5137  * skip calling it on some changes then the pointer comparisons at the end can
5138  * be invalid if you get unlucky.  For example, if a flow removal causes a
5139  * cls_table to be destroyed and then a flow insertion causes a cls_table with
5140  * different wildcards to be created with the same address, then this function
5141  * will incorrectly skip revalidation. */
5142 static void
5143 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
5144 {
5145     struct table_dpif *table = &ofproto->tables[table_id];
5146     const struct classifier *cls = &ofproto->up.tables[table_id];
5147     struct cls_table *catchall, *other;
5148     struct cls_table *t;
5149
5150     catchall = other = NULL;
5151
5152     switch (hmap_count(&cls->tables)) {
5153     case 0:
5154         /* We could tag this OpenFlow table but it would make the logic a
5155          * little harder and it's a corner case that doesn't seem worth it
5156          * yet. */
5157         break;
5158
5159     case 1:
5160     case 2:
5161         HMAP_FOR_EACH (t, hmap_node, &cls->tables) {
5162             if (cls_table_is_catchall(t)) {
5163                 catchall = t;
5164             } else if (!other) {
5165                 other = t;
5166             } else {
5167                 /* Indicate that we can't tag this by setting both tables to
5168                  * NULL.  (We know that 'catchall' is already NULL.) */
5169                 other = NULL;
5170             }
5171         }
5172         break;
5173
5174     default:
5175         /* Can't tag this table. */
5176         break;
5177     }
5178
5179     if (table->catchall_table != catchall || table->other_table != other) {
5180         table->catchall_table = catchall;
5181         table->other_table = other;
5182         ofproto->need_revalidate = true;
5183     }
5184 }
5185
5186 /* Given 'rule' that has changed in some way (either it is a rule being
5187  * inserted, a rule being deleted, or a rule whose actions are being
5188  * modified), marks facets for revalidation to ensure that packets will be
5189  * forwarded correctly according to the new state of the flow table.
5190  *
5191  * This function must be called after *each* change to a flow table.  See
5192  * the comment on table_update_taggable() for more information. */
5193 static void
5194 rule_invalidate(const struct rule_dpif *rule)
5195 {
5196     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5197
5198     table_update_taggable(ofproto, rule->up.table_id);
5199
5200     if (!ofproto->need_revalidate) {
5201         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
5202
5203         if (table->other_table && rule->tag) {
5204             tag_set_add(&ofproto->revalidate_set, rule->tag);
5205         } else {
5206             ofproto->need_revalidate = true;
5207         }
5208     }
5209 }
5210 \f
5211 static bool
5212 set_frag_handling(struct ofproto *ofproto_,
5213                   enum ofp_config_flags frag_handling)
5214 {
5215     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5216
5217     if (frag_handling != OFPC_FRAG_REASM) {
5218         ofproto->need_revalidate = true;
5219         return true;
5220     } else {
5221         return false;
5222     }
5223 }
5224
5225 static int
5226 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5227            const struct flow *flow,
5228            const union ofp_action *ofp_actions, size_t n_ofp_actions)
5229 {
5230     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5231     int error;
5232
5233     if (flow->in_port >= ofproto->max_ports && flow->in_port < OFPP_MAX) {
5234         return ofp_mkerr_nicira(OFPET_BAD_REQUEST, NXBRC_BAD_IN_PORT);
5235     }
5236
5237     error = validate_actions(ofp_actions, n_ofp_actions, flow,
5238                              ofproto->max_ports);
5239     if (!error) {
5240         struct odputil_keybuf keybuf;
5241         struct action_xlate_ctx ctx;
5242         struct ofpbuf *odp_actions;
5243         struct ofpbuf key;
5244
5245         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5246         odp_flow_key_from_flow(&key, flow);
5247
5248         action_xlate_ctx_init(&ctx, ofproto, flow, packet);
5249         odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
5250         dpif_execute(ofproto->dpif, key.data, key.size,
5251                      odp_actions->data, odp_actions->size, packet);
5252         ofpbuf_delete(odp_actions);
5253     }
5254     return error;
5255 }
5256 \f
5257 /* NetFlow. */
5258
5259 static int
5260 set_netflow(struct ofproto *ofproto_,
5261             const struct netflow_options *netflow_options)
5262 {
5263     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5264
5265     if (netflow_options) {
5266         if (!ofproto->netflow) {
5267             ofproto->netflow = netflow_create();
5268         }
5269         return netflow_set_options(ofproto->netflow, netflow_options);
5270     } else {
5271         netflow_destroy(ofproto->netflow);
5272         ofproto->netflow = NULL;
5273         return 0;
5274     }
5275 }
5276
5277 static void
5278 get_netflow_ids(const struct ofproto *ofproto_,
5279                 uint8_t *engine_type, uint8_t *engine_id)
5280 {
5281     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5282
5283     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
5284 }
5285
5286 static void
5287 send_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
5288 {
5289     if (!facet_is_controller_flow(facet) &&
5290         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
5291         struct subfacet *subfacet;
5292         struct ofexpired expired;
5293
5294         LIST_FOR_EACH (subfacet, list_node, &facet->subfacets) {
5295             if (subfacet->installed) {
5296                 struct dpif_flow_stats stats;
5297
5298                 subfacet_install(ofproto, subfacet, facet->actions,
5299                                  facet->actions_len, &stats);
5300                 subfacet_update_stats(ofproto, subfacet, &stats);
5301             }
5302         }
5303
5304         expired.flow = facet->flow;
5305         expired.packet_count = facet->packet_count;
5306         expired.byte_count = facet->byte_count;
5307         expired.used = facet->used;
5308         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
5309     }
5310 }
5311
5312 static void
5313 send_netflow_active_timeouts(struct ofproto_dpif *ofproto)
5314 {
5315     struct facet *facet;
5316
5317     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
5318         send_active_timeout(ofproto, facet);
5319     }
5320 }
5321 \f
5322 static struct ofproto_dpif *
5323 ofproto_dpif_lookup(const char *name)
5324 {
5325     struct ofproto *ofproto = ofproto_lookup(name);
5326     return (ofproto && ofproto->ofproto_class == &ofproto_dpif_class
5327             ? ofproto_dpif_cast(ofproto)
5328             : NULL);
5329 }
5330
5331 static void
5332 ofproto_unixctl_fdb_flush(struct unixctl_conn *conn,
5333                          const char *args, void *aux OVS_UNUSED)
5334 {
5335     const struct ofproto_dpif *ofproto;
5336
5337     ofproto = ofproto_dpif_lookup(args);
5338     if (!ofproto) {
5339         unixctl_command_reply(conn, 501, "no such bridge");
5340         return;
5341     }
5342     mac_learning_flush(ofproto->ml);
5343
5344     unixctl_command_reply(conn, 200, "table successfully flushed");
5345 }
5346
5347 static void
5348 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
5349                          const char *args, void *aux OVS_UNUSED)
5350 {
5351     struct ds ds = DS_EMPTY_INITIALIZER;
5352     const struct ofproto_dpif *ofproto;
5353     const struct mac_entry *e;
5354
5355     ofproto = ofproto_dpif_lookup(args);
5356     if (!ofproto) {
5357         unixctl_command_reply(conn, 501, "no such bridge");
5358         return;
5359     }
5360
5361     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5362     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5363         struct ofbundle *bundle = e->port.p;
5364         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
5365                       ofbundle_get_a_port(bundle)->odp_port,
5366                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
5367     }
5368     unixctl_command_reply(conn, 200, ds_cstr(&ds));
5369     ds_destroy(&ds);
5370 }
5371
5372 struct ofproto_trace {
5373     struct action_xlate_ctx ctx;
5374     struct flow flow;
5375     struct ds *result;
5376 };
5377
5378 static void
5379 trace_format_rule(struct ds *result, uint8_t table_id, int level,
5380                   const struct rule_dpif *rule)
5381 {
5382     ds_put_char_multiple(result, '\t', level);
5383     if (!rule) {
5384         ds_put_cstr(result, "No match\n");
5385         return;
5386     }
5387
5388     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5389                   table_id, ntohll(rule->up.flow_cookie));
5390     cls_rule_format(&rule->up.cr, result);
5391     ds_put_char(result, '\n');
5392
5393     ds_put_char_multiple(result, '\t', level);
5394     ds_put_cstr(result, "OpenFlow ");
5395     ofp_print_actions(result, rule->up.actions, rule->up.n_actions);
5396     ds_put_char(result, '\n');
5397 }
5398
5399 static void
5400 trace_format_flow(struct ds *result, int level, const char *title,
5401                  struct ofproto_trace *trace)
5402 {
5403     ds_put_char_multiple(result, '\t', level);
5404     ds_put_format(result, "%s: ", title);
5405     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5406         ds_put_cstr(result, "unchanged");
5407     } else {
5408         flow_format(result, &trace->ctx.flow);
5409         trace->flow = trace->ctx.flow;
5410     }
5411     ds_put_char(result, '\n');
5412 }
5413
5414 static void
5415 trace_format_regs(struct ds *result, int level, const char *title,
5416                   struct ofproto_trace *trace)
5417 {
5418     size_t i;
5419
5420     ds_put_char_multiple(result, '\t', level);
5421     ds_put_format(result, "%s:", title);
5422     for (i = 0; i < FLOW_N_REGS; i++) {
5423         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5424     }
5425     ds_put_char(result, '\n');
5426 }
5427
5428 static void
5429 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
5430 {
5431     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5432     struct ds *result = trace->result;
5433
5434     ds_put_char(result, '\n');
5435     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5436     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
5437     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
5438 }
5439
5440 static void
5441 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5442                       void *aux OVS_UNUSED)
5443 {
5444     char *dpname, *arg1, *arg2, *arg3, *arg4;
5445     char *args = xstrdup(args_);
5446     char *save_ptr = NULL;
5447     struct ofproto_dpif *ofproto;
5448     struct ofpbuf odp_key;
5449     struct ofpbuf *packet;
5450     struct rule_dpif *rule;
5451     struct ds result;
5452     struct flow flow;
5453     char *s;
5454
5455     packet = NULL;
5456     ofpbuf_init(&odp_key, 0);
5457     ds_init(&result);
5458
5459     dpname = strtok_r(args, " ", &save_ptr);
5460     arg1 = strtok_r(NULL, " ", &save_ptr);
5461     arg2 = strtok_r(NULL, " ", &save_ptr);
5462     arg3 = strtok_r(NULL, " ", &save_ptr);
5463     arg4 = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5464     if (dpname && arg1 && (!arg2 || !strcmp(arg2, "-generate")) && !arg3) {
5465         /* ofproto/trace dpname flow [-generate] */
5466         int error;
5467
5468         /* Convert string to datapath key. */
5469         ofpbuf_init(&odp_key, 0);
5470         error = odp_flow_key_from_string(arg1, NULL, &odp_key);
5471         if (error) {
5472             unixctl_command_reply(conn, 501, "Bad flow syntax");
5473             goto exit;
5474         }
5475
5476         /* Convert odp_key to flow. */
5477         error = odp_flow_key_to_flow(odp_key.data, odp_key.size, &flow);
5478         if (error) {
5479             unixctl_command_reply(conn, 501, "Invalid flow");
5480             goto exit;
5481         }
5482
5483         /* Generate a packet, if requested. */
5484         if (arg2) {
5485             packet = ofpbuf_new(0);
5486             flow_compose(packet, &flow);
5487         }
5488     } else if (dpname && arg1 && arg2 && arg3 && arg4) {
5489         /* ofproto/trace dpname priority tun_id in_port packet */
5490         uint16_t in_port;
5491         ovs_be64 tun_id;
5492         uint32_t priority;
5493
5494         priority = atoi(arg1);
5495         tun_id = htonll(strtoull(arg2, NULL, 0));
5496         in_port = ofp_port_to_odp_port(atoi(arg3));
5497
5498         packet = ofpbuf_new(strlen(args) / 2);
5499         arg4 = ofpbuf_put_hex(packet, arg4, NULL);
5500         arg4 += strspn(arg4, " ");
5501         if (*arg4 != '\0') {
5502             unixctl_command_reply(conn, 501, "Trailing garbage in command");
5503             goto exit;
5504         }
5505         if (packet->size < ETH_HEADER_LEN) {
5506             unixctl_command_reply(conn, 501,
5507                                   "Packet data too short for Ethernet");
5508             goto exit;
5509         }
5510
5511         ds_put_cstr(&result, "Packet: ");
5512         s = ofp_packet_to_string(packet->data, packet->size, packet->size);
5513         ds_put_cstr(&result, s);
5514         free(s);
5515
5516         flow_extract(packet, priority, tun_id, in_port, &flow);
5517     } else {
5518         unixctl_command_reply(conn, 501, "Bad command syntax");
5519         goto exit;
5520     }
5521
5522     ofproto = ofproto_dpif_lookup(dpname);
5523     if (!ofproto) {
5524         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5525                               "for help)");
5526         goto exit;
5527     }
5528
5529     ds_put_cstr(&result, "Flow: ");
5530     flow_format(&result, &flow);
5531     ds_put_char(&result, '\n');
5532
5533     rule = rule_dpif_lookup(ofproto, &flow, 0);
5534     trace_format_rule(&result, 0, 0, rule);
5535     if (rule) {
5536         struct ofproto_trace trace;
5537         struct ofpbuf *odp_actions;
5538
5539         trace.result = &result;
5540         trace.flow = flow;
5541         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, packet);
5542         trace.ctx.resubmit_hook = trace_resubmit;
5543         odp_actions = xlate_actions(&trace.ctx,
5544                                     rule->up.actions, rule->up.n_actions);
5545
5546         ds_put_char(&result, '\n');
5547         trace_format_flow(&result, 0, "Final flow", &trace);
5548         ds_put_cstr(&result, "Datapath actions: ");
5549         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5550         ofpbuf_delete(odp_actions);
5551
5552         if (!trace.ctx.may_set_up_flow) {
5553             if (packet) {
5554                 ds_put_cstr(&result, "\nThis flow is not cachable.");
5555             } else {
5556                 ds_put_cstr(&result, "\nThe datapath actions are incomplete--"
5557                             "for complete actions, please supply a packet.");
5558             }
5559         }
5560     }
5561
5562     unixctl_command_reply(conn, 200, ds_cstr(&result));
5563
5564 exit:
5565     ds_destroy(&result);
5566     ofpbuf_delete(packet);
5567     ofpbuf_uninit(&odp_key);
5568     free(args);
5569 }
5570
5571 static void
5572 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED,
5573                   const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5574 {
5575     clogged = true;
5576     unixctl_command_reply(conn, 200, NULL);
5577 }
5578
5579 static void
5580 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED,
5581                     const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5582 {
5583     clogged = false;
5584     unixctl_command_reply(conn, 200, NULL);
5585 }
5586
5587 static void
5588 ofproto_dpif_unixctl_init(void)
5589 {
5590     static bool registered;
5591     if (registered) {
5592         return;
5593     }
5594     registered = true;
5595
5596     unixctl_command_register("ofproto/trace",
5597                       "bridge {tun_id in_port packet | odp_flow [-generate]}",
5598                       ofproto_unixctl_trace, NULL);
5599     unixctl_command_register("fdb/flush", "bridge", ofproto_unixctl_fdb_flush,
5600                              NULL);
5601     unixctl_command_register("fdb/show", "bridge", ofproto_unixctl_fdb_show,
5602                              NULL);
5603     unixctl_command_register("ofproto/clog", "", ofproto_dpif_clog, NULL);
5604     unixctl_command_register("ofproto/unclog", "", ofproto_dpif_unclog, NULL);
5605 }
5606 \f
5607 const struct ofproto_class ofproto_dpif_class = {
5608     enumerate_types,
5609     enumerate_names,
5610     del,
5611     alloc,
5612     construct,
5613     destruct,
5614     dealloc,
5615     run,
5616     wait,
5617     flush,
5618     get_features,
5619     get_tables,
5620     port_alloc,
5621     port_construct,
5622     port_destruct,
5623     port_dealloc,
5624     port_modified,
5625     port_reconfigured,
5626     port_query_by_name,
5627     port_add,
5628     port_del,
5629     port_dump_start,
5630     port_dump_next,
5631     port_dump_done,
5632     port_poll,
5633     port_poll_wait,
5634     port_is_lacp_current,
5635     NULL,                       /* rule_choose_table */
5636     rule_alloc,
5637     rule_construct,
5638     rule_destruct,
5639     rule_dealloc,
5640     rule_get_stats,
5641     rule_execute,
5642     rule_modify_actions,
5643     set_frag_handling,
5644     packet_out,
5645     set_netflow,
5646     get_netflow_ids,
5647     set_sflow,
5648     set_cfm,
5649     get_cfm_fault,
5650     get_cfm_remote_mpids,
5651     set_stp,
5652     get_stp_status,
5653     set_stp_port,
5654     get_stp_port_status,
5655     set_queues,
5656     bundle_set,
5657     bundle_remove,
5658     mirror_set,
5659     set_flood_vlans,
5660     is_mirror_output_bundle,
5661     forward_bpdu_changed,
5662 };