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