d2cc36f91816e72d35879dfec027e8d03b6c066f
[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 static void facet_remove(struct ofproto_dpif *, struct facet *);
261 static void facet_free(struct facet *);
262
263 static struct facet *facet_find(struct ofproto_dpif *, const struct flow *);
264 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
265                                         const struct flow *);
266 static bool facet_revalidate(struct ofproto_dpif *, struct facet *);
267
268 static bool execute_controller_action(struct ofproto_dpif *,
269                                       const struct flow *,
270                                       const struct nlattr *odp_actions,
271                                       size_t actions_len,
272                                       struct ofpbuf *packet);
273 static void facet_execute(struct ofproto_dpif *, struct facet *,
274                           struct ofpbuf *packet);
275
276 static int facet_put__(struct ofproto_dpif *, struct facet *,
277                        const struct nlattr *actions, size_t actions_len,
278                        struct dpif_flow_stats *);
279 static void facet_install(struct ofproto_dpif *, struct facet *,
280                           bool zero_stats);
281 static void facet_uninstall(struct ofproto_dpif *, struct facet *);
282 static void facet_flush_stats(struct ofproto_dpif *, struct facet *);
283
284 static void facet_make_actions(struct ofproto_dpif *, struct facet *,
285                                const struct ofpbuf *packet);
286 static void facet_update_time(struct ofproto_dpif *, struct facet *,
287                               long long int used);
288 static void facet_update_stats(struct ofproto_dpif *, struct facet *,
289                                const struct dpif_flow_stats *);
290 static void facet_reset_counters(struct facet *);
291 static void facet_reset_dp_stats(struct facet *, struct dpif_flow_stats *);
292 static void facet_push_stats(struct facet *);
293 static void facet_account(struct ofproto_dpif *, struct facet *);
294
295 static bool facet_is_controller_flow(struct facet *);
296
297 static void flow_push_stats(const struct rule_dpif *,
298                             struct flow *, uint64_t packets, uint64_t bytes,
299                             long long int used);
300
301 static uint32_t rule_calculate_tag(const struct flow *,
302                                    const struct flow_wildcards *,
303                                    uint32_t basis);
304 static void rule_invalidate(const struct rule_dpif *);
305
306 struct ofport_dpif {
307     struct ofport up;
308
309     uint32_t odp_port;
310     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
311     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
312     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
313     tag_type tag;               /* Tag associated with this port. */
314     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
315     bool may_enable;            /* May be enabled in bonds. */
316 };
317
318 static struct ofport_dpif *
319 ofport_dpif_cast(const struct ofport *ofport)
320 {
321     assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
322     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
323 }
324
325 static void port_run(struct ofport_dpif *);
326 static void port_wait(struct ofport_dpif *);
327 static int set_cfm(struct ofport *, const struct cfm_settings *);
328
329 struct dpif_completion {
330     struct list list_node;
331     struct ofoperation *op;
332 };
333
334 /* Extra information about a classifier table.
335  * Currently used just for optimized flow revalidation. */
336 struct table_dpif {
337     /* If either of these is nonnull, then this table has a form that allows
338      * flows to be tagged to avoid revalidating most flows for the most common
339      * kinds of flow table changes. */
340     struct cls_table *catchall_table; /* Table that wildcards all fields. */
341     struct cls_table *other_table;    /* Table with any other wildcard set. */
342     uint32_t basis;                   /* Keeps each table's tags separate. */
343 };
344
345 struct ofproto_dpif {
346     struct ofproto up;
347     struct dpif *dpif;
348     int max_ports;
349
350     /* Statistics. */
351     uint64_t n_matches;
352
353     /* Bridging. */
354     struct netflow *netflow;
355     struct dpif_sflow *sflow;
356     struct hmap bundles;        /* Contains "struct ofbundle"s. */
357     struct mac_learning *ml;
358     struct ofmirror *mirrors[MAX_MIRRORS];
359     bool has_bonded_bundles;
360
361     /* Expiration. */
362     struct timer next_expiration;
363
364     /* Facets. */
365     struct hmap facets;
366
367     /* Revalidation. */
368     struct table_dpif tables[N_TABLES];
369     bool need_revalidate;
370     struct tag_set revalidate_set;
371
372     /* Support for debugging async flow mods. */
373     struct list completions;
374
375     bool has_bundle_action; /* True when the first bundle action appears. */
376 };
377
378 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
379  * for debugging the asynchronous flow_mod implementation.) */
380 static bool clogged;
381
382 static void ofproto_dpif_unixctl_init(void);
383
384 static struct ofproto_dpif *
385 ofproto_dpif_cast(const struct ofproto *ofproto)
386 {
387     assert(ofproto->ofproto_class == &ofproto_dpif_class);
388     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
389 }
390
391 static struct ofport_dpif *get_ofp_port(struct ofproto_dpif *,
392                                         uint16_t ofp_port);
393 static struct ofport_dpif *get_odp_port(struct ofproto_dpif *,
394                                         uint32_t odp_port);
395
396 /* Packet processing. */
397 static void update_learning_table(struct ofproto_dpif *,
398                                   const struct flow *, int vlan,
399                                   struct ofbundle *);
400 static bool is_admissible(struct ofproto_dpif *, const struct flow *,
401                           bool have_packet, tag_type *, int *vlanp,
402                           struct ofbundle **in_bundlep);
403 static void handle_upcall(struct ofproto_dpif *, struct dpif_upcall *);
404
405 /* Flow expiration. */
406 static int expire(struct ofproto_dpif *);
407
408 /* Utilities. */
409 static int send_packet(struct ofproto_dpif *, uint32_t odp_port,
410                        const struct ofpbuf *packet);
411 static size_t
412 compose_sflow_action(const struct ofproto_dpif *, struct ofpbuf *odp_actions,
413                      const struct flow *, uint32_t odp_port);
414 /* Global variables. */
415 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
416 \f
417 /* Factory functions. */
418
419 static void
420 enumerate_types(struct sset *types)
421 {
422     dp_enumerate_types(types);
423 }
424
425 static int
426 enumerate_names(const char *type, struct sset *names)
427 {
428     return dp_enumerate_names(type, names);
429 }
430
431 static int
432 del(const char *type, const char *name)
433 {
434     struct dpif *dpif;
435     int error;
436
437     error = dpif_open(name, type, &dpif);
438     if (!error) {
439         error = dpif_delete(dpif);
440         dpif_close(dpif);
441     }
442     return error;
443 }
444 \f
445 /* Basic life-cycle. */
446
447 static struct ofproto *
448 alloc(void)
449 {
450     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
451     return &ofproto->up;
452 }
453
454 static void
455 dealloc(struct ofproto *ofproto_)
456 {
457     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
458     free(ofproto);
459 }
460
461 static int
462 construct(struct ofproto *ofproto_, int *n_tablesp)
463 {
464     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
465     const char *name = ofproto->up.name;
466     int error;
467     int i;
468
469     error = dpif_create_and_open(name, ofproto->up.type, &ofproto->dpif);
470     if (error) {
471         VLOG_ERR("failed to open datapath %s: %s", name, strerror(error));
472         return error;
473     }
474
475     ofproto->max_ports = dpif_get_max_ports(ofproto->dpif);
476     ofproto->n_matches = 0;
477
478     dpif_flow_flush(ofproto->dpif);
479     dpif_recv_purge(ofproto->dpif);
480
481     error = dpif_recv_set_mask(ofproto->dpif,
482                                ((1u << DPIF_UC_MISS) |
483                                 (1u << DPIF_UC_ACTION)));
484     if (error) {
485         VLOG_ERR("failed to listen on datapath %s: %s", name, strerror(error));
486         dpif_close(ofproto->dpif);
487         return error;
488     }
489
490     ofproto->netflow = NULL;
491     ofproto->sflow = NULL;
492     hmap_init(&ofproto->bundles);
493     ofproto->ml = mac_learning_create();
494     for (i = 0; i < MAX_MIRRORS; i++) {
495         ofproto->mirrors[i] = NULL;
496     }
497     ofproto->has_bonded_bundles = false;
498
499     timer_set_duration(&ofproto->next_expiration, 1000);
500
501     hmap_init(&ofproto->facets);
502
503     for (i = 0; i < N_TABLES; i++) {
504         struct table_dpif *table = &ofproto->tables[i];
505
506         table->catchall_table = NULL;
507         table->other_table = NULL;
508         table->basis = random_uint32();
509     }
510     ofproto->need_revalidate = false;
511     tag_set_init(&ofproto->revalidate_set);
512
513     list_init(&ofproto->completions);
514
515     ofproto_dpif_unixctl_init();
516
517     ofproto->has_bundle_action = false;
518
519     *n_tablesp = N_TABLES;
520     return 0;
521 }
522
523 static void
524 complete_operations(struct ofproto_dpif *ofproto)
525 {
526     struct dpif_completion *c, *next;
527
528     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
529         ofoperation_complete(c->op, 0);
530         list_remove(&c->list_node);
531         free(c);
532     }
533 }
534
535 static void
536 destruct(struct ofproto *ofproto_)
537 {
538     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
539     struct rule_dpif *rule, *next_rule;
540     struct classifier *table;
541     int i;
542
543     complete_operations(ofproto);
544
545     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
546         struct cls_cursor cursor;
547
548         cls_cursor_init(&cursor, table, NULL);
549         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
550             ofproto_rule_destroy(&rule->up);
551         }
552     }
553
554     for (i = 0; i < MAX_MIRRORS; i++) {
555         mirror_destroy(ofproto->mirrors[i]);
556     }
557
558     netflow_destroy(ofproto->netflow);
559     dpif_sflow_destroy(ofproto->sflow);
560     hmap_destroy(&ofproto->bundles);
561     mac_learning_destroy(ofproto->ml);
562
563     hmap_destroy(&ofproto->facets);
564
565     dpif_close(ofproto->dpif);
566 }
567
568 static int
569 run(struct ofproto *ofproto_)
570 {
571     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
572     struct ofport_dpif *ofport;
573     struct ofbundle *bundle;
574     int i;
575
576     if (!clogged) {
577         complete_operations(ofproto);
578     }
579     dpif_run(ofproto->dpif);
580
581     for (i = 0; i < 50; i++) {
582         struct dpif_upcall packet;
583         int error;
584
585         error = dpif_recv(ofproto->dpif, &packet);
586         if (error) {
587             if (error == ENODEV) {
588                 /* Datapath destroyed. */
589                 return error;
590             }
591             break;
592         }
593
594         handle_upcall(ofproto, &packet);
595     }
596
597     if (timer_expired(&ofproto->next_expiration)) {
598         int delay = expire(ofproto);
599         timer_set_duration(&ofproto->next_expiration, delay);
600     }
601
602     if (ofproto->netflow) {
603         netflow_run(ofproto->netflow);
604     }
605     if (ofproto->sflow) {
606         dpif_sflow_run(ofproto->sflow);
607     }
608
609     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
610         port_run(ofport);
611     }
612     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
613         bundle_run(bundle);
614     }
615
616     mac_learning_run(ofproto->ml, &ofproto->revalidate_set);
617
618     /* Now revalidate if there's anything to do. */
619     if (ofproto->need_revalidate
620         || !tag_set_is_empty(&ofproto->revalidate_set)) {
621         struct tag_set revalidate_set = ofproto->revalidate_set;
622         bool revalidate_all = ofproto->need_revalidate;
623         struct facet *facet, *next;
624
625         /* Clear the revalidation flags. */
626         tag_set_init(&ofproto->revalidate_set);
627         ofproto->need_revalidate = false;
628
629         HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &ofproto->facets) {
630             if (revalidate_all
631                 || tag_set_intersects(&revalidate_set, facet->tags)) {
632                 facet_revalidate(ofproto, facet);
633             }
634         }
635     }
636
637     return 0;
638 }
639
640 static void
641 wait(struct ofproto *ofproto_)
642 {
643     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
644     struct ofport_dpif *ofport;
645     struct ofbundle *bundle;
646
647     if (!clogged && !list_is_empty(&ofproto->completions)) {
648         poll_immediate_wake();
649     }
650
651     dpif_wait(ofproto->dpif);
652     dpif_recv_wait(ofproto->dpif);
653     if (ofproto->sflow) {
654         dpif_sflow_wait(ofproto->sflow);
655     }
656     if (!tag_set_is_empty(&ofproto->revalidate_set)) {
657         poll_immediate_wake();
658     }
659     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
660         port_wait(ofport);
661     }
662     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
663         bundle_wait(bundle);
664     }
665     mac_learning_wait(ofproto->ml);
666     if (ofproto->need_revalidate) {
667         /* Shouldn't happen, but if it does just go around again. */
668         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
669         poll_immediate_wake();
670     } else {
671         timer_wait(&ofproto->next_expiration);
672     }
673 }
674
675 static void
676 flush(struct ofproto *ofproto_)
677 {
678     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
679     struct facet *facet, *next_facet;
680
681     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
682         /* Mark the facet as not installed so that facet_remove() doesn't
683          * bother trying to uninstall it.  There is no point in uninstalling it
684          * individually since we are about to blow away all the facets with
685          * dpif_flow_flush(). */
686         facet->installed = false;
687         facet->dp_packet_count = 0;
688         facet->dp_byte_count = 0;
689         facet_remove(ofproto, facet);
690     }
691     dpif_flow_flush(ofproto->dpif);
692 }
693
694 static void
695 get_features(struct ofproto *ofproto_ OVS_UNUSED,
696              bool *arp_match_ip, uint32_t *actions)
697 {
698     *arp_match_ip = true;
699     *actions = ((1u << OFPAT_OUTPUT) |
700                 (1u << OFPAT_SET_VLAN_VID) |
701                 (1u << OFPAT_SET_VLAN_PCP) |
702                 (1u << OFPAT_STRIP_VLAN) |
703                 (1u << OFPAT_SET_DL_SRC) |
704                 (1u << OFPAT_SET_DL_DST) |
705                 (1u << OFPAT_SET_NW_SRC) |
706                 (1u << OFPAT_SET_NW_DST) |
707                 (1u << OFPAT_SET_NW_TOS) |
708                 (1u << OFPAT_SET_TP_SRC) |
709                 (1u << OFPAT_SET_TP_DST) |
710                 (1u << OFPAT_ENQUEUE));
711 }
712
713 static void
714 get_tables(struct ofproto *ofproto_, struct ofp_table_stats *ots)
715 {
716     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
717     struct dpif_dp_stats s;
718
719     strcpy(ots->name, "classifier");
720
721     dpif_get_dp_stats(ofproto->dpif, &s);
722     put_32aligned_be64(&ots->lookup_count, htonll(s.n_hit + s.n_missed));
723     put_32aligned_be64(&ots->matched_count,
724                        htonll(s.n_hit + ofproto->n_matches));
725 }
726
727 static int
728 set_netflow(struct ofproto *ofproto_,
729             const struct netflow_options *netflow_options)
730 {
731     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
732
733     if (netflow_options) {
734         if (!ofproto->netflow) {
735             ofproto->netflow = netflow_create();
736         }
737         return netflow_set_options(ofproto->netflow, netflow_options);
738     } else {
739         netflow_destroy(ofproto->netflow);
740         ofproto->netflow = NULL;
741         return 0;
742     }
743 }
744
745 static struct ofport *
746 port_alloc(void)
747 {
748     struct ofport_dpif *port = xmalloc(sizeof *port);
749     return &port->up;
750 }
751
752 static void
753 port_dealloc(struct ofport *port_)
754 {
755     struct ofport_dpif *port = ofport_dpif_cast(port_);
756     free(port);
757 }
758
759 static int
760 port_construct(struct ofport *port_)
761 {
762     struct ofport_dpif *port = ofport_dpif_cast(port_);
763     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
764
765     ofproto->need_revalidate = true;
766     port->odp_port = ofp_port_to_odp_port(port->up.ofp_port);
767     port->bundle = NULL;
768     port->cfm = NULL;
769     port->tag = tag_create_random();
770     port->may_enable = true;
771
772     if (ofproto->sflow) {
773         dpif_sflow_add_port(ofproto->sflow, port->odp_port,
774                             netdev_get_name(port->up.netdev));
775     }
776
777     return 0;
778 }
779
780 static void
781 port_destruct(struct ofport *port_)
782 {
783     struct ofport_dpif *port = ofport_dpif_cast(port_);
784     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
785
786     ofproto->need_revalidate = true;
787     bundle_remove(port_);
788     set_cfm(port_, NULL);
789     if (ofproto->sflow) {
790         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
791     }
792 }
793
794 static void
795 port_modified(struct ofport *port_)
796 {
797     struct ofport_dpif *port = ofport_dpif_cast(port_);
798
799     if (port->bundle && port->bundle->bond) {
800         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
801     }
802 }
803
804 static void
805 port_reconfigured(struct ofport *port_, ovs_be32 old_config)
806 {
807     struct ofport_dpif *port = ofport_dpif_cast(port_);
808     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
809     ovs_be32 changed = old_config ^ port->up.opp.config;
810
811     if (changed & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
812                         OFPPC_NO_FWD | OFPPC_NO_FLOOD)) {
813         ofproto->need_revalidate = true;
814     }
815 }
816
817 static int
818 set_sflow(struct ofproto *ofproto_,
819           const struct ofproto_sflow_options *sflow_options)
820 {
821     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
822     struct dpif_sflow *ds = ofproto->sflow;
823
824     if (sflow_options) {
825         if (!ds) {
826             struct ofport_dpif *ofport;
827
828             ds = ofproto->sflow = dpif_sflow_create(ofproto->dpif);
829             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
830                 dpif_sflow_add_port(ds, ofport->odp_port,
831                                     netdev_get_name(ofport->up.netdev));
832             }
833             ofproto->need_revalidate = true;
834         }
835         dpif_sflow_set_options(ds, sflow_options);
836     } else {
837         if (ds) {
838             dpif_sflow_destroy(ds);
839             ofproto->need_revalidate = true;
840             ofproto->sflow = NULL;
841         }
842     }
843     return 0;
844 }
845
846 static int
847 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
848 {
849     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
850     int error;
851
852     if (!s) {
853         error = 0;
854     } else {
855         if (!ofport->cfm) {
856             struct ofproto_dpif *ofproto;
857
858             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
859             ofproto->need_revalidate = true;
860             ofport->cfm = cfm_create(netdev_get_name(ofport->up.netdev));
861         }
862
863         if (cfm_configure(ofport->cfm, s)) {
864             return 0;
865         }
866
867         error = EINVAL;
868     }
869     cfm_destroy(ofport->cfm);
870     ofport->cfm = NULL;
871     return error;
872 }
873
874 static int
875 get_cfm_fault(const struct ofport *ofport_)
876 {
877     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
878
879     return ofport->cfm ? cfm_get_fault(ofport->cfm) : -1;
880 }
881
882 static int
883 get_cfm_remote_mpids(const struct ofport *ofport_, const uint64_t **rmps,
884                      size_t *n_rmps)
885 {
886     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
887
888     if (ofport->cfm) {
889         cfm_get_remote_mpids(ofport->cfm, rmps, n_rmps);
890         return 0;
891     } else {
892         return -1;
893     }
894 }
895 \f
896 /* Bundles. */
897
898 /* Expires all MAC learning entries associated with 'port' and forces ofproto
899  * to revalidate every flow. */
900 static void
901 bundle_flush_macs(struct ofbundle *bundle)
902 {
903     struct ofproto_dpif *ofproto = bundle->ofproto;
904     struct mac_learning *ml = ofproto->ml;
905     struct mac_entry *mac, *next_mac;
906
907     ofproto->need_revalidate = true;
908     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
909         if (mac->port.p == bundle) {
910             mac_learning_expire(ml, mac);
911         }
912     }
913 }
914
915 static struct ofbundle *
916 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
917 {
918     struct ofbundle *bundle;
919
920     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
921                              &ofproto->bundles) {
922         if (bundle->aux == aux) {
923             return bundle;
924         }
925     }
926     return NULL;
927 }
928
929 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
930  * ones that are found to 'bundles'. */
931 static void
932 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
933                        void **auxes, size_t n_auxes,
934                        struct hmapx *bundles)
935 {
936     size_t i;
937
938     hmapx_init(bundles);
939     for (i = 0; i < n_auxes; i++) {
940         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
941         if (bundle) {
942             hmapx_add(bundles, bundle);
943         }
944     }
945 }
946
947 static void
948 bundle_del_port(struct ofport_dpif *port)
949 {
950     struct ofbundle *bundle = port->bundle;
951
952     bundle->ofproto->need_revalidate = true;
953
954     list_remove(&port->bundle_node);
955     port->bundle = NULL;
956
957     if (bundle->lacp) {
958         lacp_slave_unregister(bundle->lacp, port);
959     }
960     if (bundle->bond) {
961         bond_slave_unregister(bundle->bond, port);
962     }
963
964     bundle->floodable = true;
965     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
966         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)) {
967             bundle->floodable = false;
968         }
969     }
970 }
971
972 static bool
973 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
974                 struct lacp_slave_settings *lacp,
975                 uint32_t bond_stable_id)
976 {
977     struct ofport_dpif *port;
978
979     port = get_ofp_port(bundle->ofproto, ofp_port);
980     if (!port) {
981         return false;
982     }
983
984     if (port->bundle != bundle) {
985         bundle->ofproto->need_revalidate = true;
986         if (port->bundle) {
987             bundle_del_port(port);
988         }
989
990         port->bundle = bundle;
991         list_push_back(&bundle->ports, &port->bundle_node);
992         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)) {
993             bundle->floodable = false;
994         }
995     }
996     if (lacp) {
997         port->bundle->ofproto->need_revalidate = true;
998         lacp_slave_register(bundle->lacp, port, lacp);
999     }
1000
1001     port->bond_stable_id = bond_stable_id;
1002
1003     return true;
1004 }
1005
1006 static void
1007 bundle_destroy(struct ofbundle *bundle)
1008 {
1009     struct ofproto_dpif *ofproto;
1010     struct ofport_dpif *port, *next_port;
1011     int i;
1012
1013     if (!bundle) {
1014         return;
1015     }
1016
1017     ofproto = bundle->ofproto;
1018     for (i = 0; i < MAX_MIRRORS; i++) {
1019         struct ofmirror *m = ofproto->mirrors[i];
1020         if (m) {
1021             if (m->out == bundle) {
1022                 mirror_destroy(m);
1023             } else if (hmapx_find_and_delete(&m->srcs, bundle)
1024                        || hmapx_find_and_delete(&m->dsts, bundle)) {
1025                 ofproto->need_revalidate = true;
1026             }
1027         }
1028     }
1029
1030     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1031         bundle_del_port(port);
1032     }
1033
1034     bundle_flush_macs(bundle);
1035     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
1036     free(bundle->name);
1037     free(bundle->trunks);
1038     lacp_destroy(bundle->lacp);
1039     bond_destroy(bundle->bond);
1040     free(bundle);
1041 }
1042
1043 static int
1044 bundle_set(struct ofproto *ofproto_, void *aux,
1045            const struct ofproto_bundle_settings *s)
1046 {
1047     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1048     bool need_flush = false;
1049     struct ofport_dpif *port;
1050     struct ofbundle *bundle;
1051     unsigned long *trunks;
1052     int vlan;
1053     size_t i;
1054     bool ok;
1055
1056     if (!s) {
1057         bundle_destroy(bundle_lookup(ofproto, aux));
1058         return 0;
1059     }
1060
1061     assert(s->n_slaves == 1 || s->bond != NULL);
1062     assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
1063
1064     bundle = bundle_lookup(ofproto, aux);
1065     if (!bundle) {
1066         bundle = xmalloc(sizeof *bundle);
1067
1068         bundle->ofproto = ofproto;
1069         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
1070                     hash_pointer(aux, 0));
1071         bundle->aux = aux;
1072         bundle->name = NULL;
1073
1074         list_init(&bundle->ports);
1075         bundle->vlan_mode = PORT_VLAN_TRUNK;
1076         bundle->vlan = -1;
1077         bundle->trunks = NULL;
1078         bundle->lacp = NULL;
1079         bundle->bond = NULL;
1080
1081         bundle->floodable = true;
1082
1083         bundle->src_mirrors = 0;
1084         bundle->dst_mirrors = 0;
1085         bundle->mirror_out = 0;
1086     }
1087
1088     if (!bundle->name || strcmp(s->name, bundle->name)) {
1089         free(bundle->name);
1090         bundle->name = xstrdup(s->name);
1091     }
1092
1093     /* LACP. */
1094     if (s->lacp) {
1095         if (!bundle->lacp) {
1096             ofproto->need_revalidate = true;
1097             bundle->lacp = lacp_create();
1098         }
1099         lacp_configure(bundle->lacp, s->lacp);
1100     } else {
1101         lacp_destroy(bundle->lacp);
1102         bundle->lacp = NULL;
1103     }
1104
1105     /* Update set of ports. */
1106     ok = true;
1107     for (i = 0; i < s->n_slaves; i++) {
1108         if (!bundle_add_port(bundle, s->slaves[i],
1109                              s->lacp ? &s->lacp_slaves[i] : NULL,
1110                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
1111             ok = false;
1112         }
1113     }
1114     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
1115         struct ofport_dpif *next_port;
1116
1117         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1118             for (i = 0; i < s->n_slaves; i++) {
1119                 if (s->slaves[i] == port->up.ofp_port) {
1120                     goto found;
1121                 }
1122             }
1123
1124             bundle_del_port(port);
1125         found: ;
1126         }
1127     }
1128     assert(list_size(&bundle->ports) <= s->n_slaves);
1129
1130     if (list_is_empty(&bundle->ports)) {
1131         bundle_destroy(bundle);
1132         return EINVAL;
1133     }
1134
1135     /* Set VLAN tagging mode */
1136     if (s->vlan_mode != bundle->vlan_mode) {
1137         bundle->vlan_mode = s->vlan_mode;
1138         need_flush = true;
1139     }
1140
1141     /* Set VLAN tag. */
1142     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
1143             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
1144             : 0);
1145     if (vlan != bundle->vlan) {
1146         bundle->vlan = vlan;
1147         need_flush = true;
1148     }
1149
1150     /* Get trunked VLANs. */
1151     switch (s->vlan_mode) {
1152     case PORT_VLAN_ACCESS:
1153         trunks = NULL;
1154         break;
1155
1156     case PORT_VLAN_TRUNK:
1157         trunks = (unsigned long *) s->trunks;
1158         break;
1159
1160     case PORT_VLAN_NATIVE_UNTAGGED:
1161     case PORT_VLAN_NATIVE_TAGGED:
1162         if (vlan != 0 && (!s->trunks
1163                           || !bitmap_is_set(s->trunks, vlan)
1164                           || bitmap_is_set(s->trunks, 0))) {
1165             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
1166             if (s->trunks) {
1167                 trunks = bitmap_clone(s->trunks, 4096);
1168             } else {
1169                 trunks = bitmap_allocate1(4096);
1170             }
1171             bitmap_set1(trunks, vlan);
1172             bitmap_set0(trunks, 0);
1173         } else {
1174             trunks = (unsigned long *) s->trunks;
1175         }
1176         break;
1177
1178     default:
1179         NOT_REACHED();
1180     }
1181     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
1182         free(bundle->trunks);
1183         if (trunks == s->trunks) {
1184             bundle->trunks = vlan_bitmap_clone(trunks);
1185         } else {
1186             bundle->trunks = trunks;
1187             trunks = NULL;
1188         }
1189         need_flush = true;
1190     }
1191     if (trunks != s->trunks) {
1192         free(trunks);
1193     }
1194
1195     /* Bonding. */
1196     if (!list_is_short(&bundle->ports)) {
1197         bundle->ofproto->has_bonded_bundles = true;
1198         if (bundle->bond) {
1199             if (bond_reconfigure(bundle->bond, s->bond)) {
1200                 ofproto->need_revalidate = true;
1201             }
1202         } else {
1203             bundle->bond = bond_create(s->bond);
1204             ofproto->need_revalidate = true;
1205         }
1206
1207         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1208             bond_slave_register(bundle->bond, port, port->bond_stable_id,
1209                                 port->up.netdev);
1210         }
1211     } else {
1212         bond_destroy(bundle->bond);
1213         bundle->bond = NULL;
1214     }
1215
1216     /* If we changed something that would affect MAC learning, un-learn
1217      * everything on this port and force flow revalidation. */
1218     if (need_flush) {
1219         bundle_flush_macs(bundle);
1220     }
1221
1222     return 0;
1223 }
1224
1225 static void
1226 bundle_remove(struct ofport *port_)
1227 {
1228     struct ofport_dpif *port = ofport_dpif_cast(port_);
1229     struct ofbundle *bundle = port->bundle;
1230
1231     if (bundle) {
1232         bundle_del_port(port);
1233         if (list_is_empty(&bundle->ports)) {
1234             bundle_destroy(bundle);
1235         } else if (list_is_short(&bundle->ports)) {
1236             bond_destroy(bundle->bond);
1237             bundle->bond = NULL;
1238         }
1239     }
1240 }
1241
1242 static void
1243 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
1244 {
1245     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
1246     struct ofport_dpif *port = port_;
1247     uint8_t ea[ETH_ADDR_LEN];
1248     int error;
1249
1250     error = netdev_get_etheraddr(port->up.netdev, ea);
1251     if (!error) {
1252         struct ofpbuf packet;
1253         void *packet_pdu;
1254
1255         ofpbuf_init(&packet, 0);
1256         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
1257                                  pdu_size);
1258         memcpy(packet_pdu, pdu, pdu_size);
1259
1260         error = netdev_send(port->up.netdev, &packet);
1261         if (error) {
1262             VLOG_WARN_RL(&rl, "port %s: sending LACP PDU on iface %s failed "
1263                          "(%s)", port->bundle->name,
1264                          netdev_get_name(port->up.netdev), strerror(error));
1265         }
1266         ofpbuf_uninit(&packet);
1267     } else {
1268         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
1269                     "%s (%s)", port->bundle->name,
1270                     netdev_get_name(port->up.netdev), strerror(error));
1271     }
1272 }
1273
1274 static void
1275 bundle_send_learning_packets(struct ofbundle *bundle)
1276 {
1277     struct ofproto_dpif *ofproto = bundle->ofproto;
1278     int error, n_packets, n_errors;
1279     struct mac_entry *e;
1280
1281     error = n_packets = n_errors = 0;
1282     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
1283         if (e->port.p != bundle) {
1284             int ret = bond_send_learning_packet(bundle->bond, e->mac, e->vlan);
1285             if (ret) {
1286                 error = ret;
1287                 n_errors++;
1288             }
1289             n_packets++;
1290         }
1291     }
1292
1293     if (n_errors) {
1294         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1295         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
1296                      "packets, last error was: %s",
1297                      bundle->name, n_errors, n_packets, strerror(error));
1298     } else {
1299         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
1300                  bundle->name, n_packets);
1301     }
1302 }
1303
1304 static void
1305 bundle_run(struct ofbundle *bundle)
1306 {
1307     if (bundle->lacp) {
1308         lacp_run(bundle->lacp, send_pdu_cb);
1309     }
1310     if (bundle->bond) {
1311         struct ofport_dpif *port;
1312
1313         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1314             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
1315         }
1316
1317         bond_run(bundle->bond, &bundle->ofproto->revalidate_set,
1318                  lacp_negotiated(bundle->lacp));
1319         if (bond_should_send_learning_packets(bundle->bond)) {
1320             bundle_send_learning_packets(bundle);
1321         }
1322     }
1323 }
1324
1325 static void
1326 bundle_wait(struct ofbundle *bundle)
1327 {
1328     if (bundle->lacp) {
1329         lacp_wait(bundle->lacp);
1330     }
1331     if (bundle->bond) {
1332         bond_wait(bundle->bond);
1333     }
1334 }
1335 \f
1336 /* Mirrors. */
1337
1338 static int
1339 mirror_scan(struct ofproto_dpif *ofproto)
1340 {
1341     int idx;
1342
1343     for (idx = 0; idx < MAX_MIRRORS; idx++) {
1344         if (!ofproto->mirrors[idx]) {
1345             return idx;
1346         }
1347     }
1348     return -1;
1349 }
1350
1351 static struct ofmirror *
1352 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
1353 {
1354     int i;
1355
1356     for (i = 0; i < MAX_MIRRORS; i++) {
1357         struct ofmirror *mirror = ofproto->mirrors[i];
1358         if (mirror && mirror->aux == aux) {
1359             return mirror;
1360         }
1361     }
1362
1363     return NULL;
1364 }
1365
1366 static int
1367 mirror_set(struct ofproto *ofproto_, void *aux,
1368            const struct ofproto_mirror_settings *s)
1369 {
1370     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1371     mirror_mask_t mirror_bit;
1372     struct ofbundle *bundle;
1373     struct ofmirror *mirror;
1374     struct ofbundle *out;
1375     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
1376     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
1377     int out_vlan;
1378
1379     mirror = mirror_lookup(ofproto, aux);
1380     if (!s) {
1381         mirror_destroy(mirror);
1382         return 0;
1383     }
1384     if (!mirror) {
1385         int idx;
1386
1387         idx = mirror_scan(ofproto);
1388         if (idx < 0) {
1389             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
1390                       "cannot create %s",
1391                       ofproto->up.name, MAX_MIRRORS, s->name);
1392             return EFBIG;
1393         }
1394
1395         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
1396         mirror->ofproto = ofproto;
1397         mirror->idx = idx;
1398         mirror->aux = aux;
1399         mirror->out_vlan = -1;
1400         mirror->name = NULL;
1401     }
1402
1403     if (!mirror->name || strcmp(s->name, mirror->name)) {
1404         free(mirror->name);
1405         mirror->name = xstrdup(s->name);
1406     }
1407
1408     /* Get the new configuration. */
1409     if (s->out_bundle) {
1410         out = bundle_lookup(ofproto, s->out_bundle);
1411         if (!out) {
1412             mirror_destroy(mirror);
1413             return EINVAL;
1414         }
1415         out_vlan = -1;
1416     } else {
1417         out = NULL;
1418         out_vlan = s->out_vlan;
1419     }
1420     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
1421     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
1422
1423     /* If the configuration has not changed, do nothing. */
1424     if (hmapx_equals(&srcs, &mirror->srcs)
1425         && hmapx_equals(&dsts, &mirror->dsts)
1426         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
1427         && mirror->out == out
1428         && mirror->out_vlan == out_vlan)
1429     {
1430         hmapx_destroy(&srcs);
1431         hmapx_destroy(&dsts);
1432         return 0;
1433     }
1434
1435     hmapx_swap(&srcs, &mirror->srcs);
1436     hmapx_destroy(&srcs);
1437
1438     hmapx_swap(&dsts, &mirror->dsts);
1439     hmapx_destroy(&dsts);
1440
1441     free(mirror->vlans);
1442     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
1443
1444     mirror->out = out;
1445     mirror->out_vlan = out_vlan;
1446
1447     /* Update bundles. */
1448     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1449     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
1450         if (hmapx_contains(&mirror->srcs, bundle)) {
1451             bundle->src_mirrors |= mirror_bit;
1452         } else {
1453             bundle->src_mirrors &= ~mirror_bit;
1454         }
1455
1456         if (hmapx_contains(&mirror->dsts, bundle)) {
1457             bundle->dst_mirrors |= mirror_bit;
1458         } else {
1459             bundle->dst_mirrors &= ~mirror_bit;
1460         }
1461
1462         if (mirror->out == bundle) {
1463             bundle->mirror_out |= mirror_bit;
1464         } else {
1465             bundle->mirror_out &= ~mirror_bit;
1466         }
1467     }
1468
1469     ofproto->need_revalidate = true;
1470     mac_learning_flush(ofproto->ml);
1471
1472     return 0;
1473 }
1474
1475 static void
1476 mirror_destroy(struct ofmirror *mirror)
1477 {
1478     struct ofproto_dpif *ofproto;
1479     mirror_mask_t mirror_bit;
1480     struct ofbundle *bundle;
1481
1482     if (!mirror) {
1483         return;
1484     }
1485
1486     ofproto = mirror->ofproto;
1487     ofproto->need_revalidate = true;
1488     mac_learning_flush(ofproto->ml);
1489
1490     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1491     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1492         bundle->src_mirrors &= ~mirror_bit;
1493         bundle->dst_mirrors &= ~mirror_bit;
1494         bundle->mirror_out &= ~mirror_bit;
1495     }
1496
1497     hmapx_destroy(&mirror->srcs);
1498     hmapx_destroy(&mirror->dsts);
1499     free(mirror->vlans);
1500
1501     ofproto->mirrors[mirror->idx] = NULL;
1502     free(mirror->name);
1503     free(mirror);
1504 }
1505
1506 static int
1507 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
1508 {
1509     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1510     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
1511         ofproto->need_revalidate = true;
1512         mac_learning_flush(ofproto->ml);
1513     }
1514     return 0;
1515 }
1516
1517 static bool
1518 is_mirror_output_bundle(struct ofproto *ofproto_, void *aux)
1519 {
1520     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1521     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
1522     return bundle && bundle->mirror_out != 0;
1523 }
1524
1525 static void
1526 forward_bpdu_changed(struct ofproto *ofproto_)
1527 {
1528     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1529     /* Revalidate cached flows whenever forward_bpdu option changes. */
1530     ofproto->need_revalidate = true;
1531 }
1532 \f
1533 /* Ports. */
1534
1535 static struct ofport_dpif *
1536 get_ofp_port(struct ofproto_dpif *ofproto, uint16_t ofp_port)
1537 {
1538     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
1539     return ofport ? ofport_dpif_cast(ofport) : NULL;
1540 }
1541
1542 static struct ofport_dpif *
1543 get_odp_port(struct ofproto_dpif *ofproto, uint32_t odp_port)
1544 {
1545     return get_ofp_port(ofproto, odp_port_to_ofp_port(odp_port));
1546 }
1547
1548 static void
1549 ofproto_port_from_dpif_port(struct ofproto_port *ofproto_port,
1550                             struct dpif_port *dpif_port)
1551 {
1552     ofproto_port->name = dpif_port->name;
1553     ofproto_port->type = dpif_port->type;
1554     ofproto_port->ofp_port = odp_port_to_ofp_port(dpif_port->port_no);
1555 }
1556
1557 static void
1558 port_run(struct ofport_dpif *ofport)
1559 {
1560     bool enable = netdev_get_carrier(ofport->up.netdev);
1561
1562     if (ofport->cfm) {
1563         cfm_run(ofport->cfm);
1564
1565         if (cfm_should_send_ccm(ofport->cfm)) {
1566             struct ofpbuf packet;
1567
1568             ofpbuf_init(&packet, 0);
1569             cfm_compose_ccm(ofport->cfm, &packet, ofport->up.opp.hw_addr);
1570             send_packet(ofproto_dpif_cast(ofport->up.ofproto),
1571                         ofport->odp_port, &packet);
1572             ofpbuf_uninit(&packet);
1573         }
1574
1575         enable = enable && !cfm_get_fault(ofport->cfm)
1576             && cfm_get_opup(ofport->cfm);
1577     }
1578
1579     if (ofport->bundle) {
1580         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
1581     }
1582
1583     if (ofport->may_enable != enable) {
1584         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1585
1586         if (ofproto->has_bundle_action) {
1587             ofproto->need_revalidate = true;
1588         }
1589     }
1590
1591     ofport->may_enable = enable;
1592 }
1593
1594 static void
1595 port_wait(struct ofport_dpif *ofport)
1596 {
1597     if (ofport->cfm) {
1598         cfm_wait(ofport->cfm);
1599     }
1600 }
1601
1602 static int
1603 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
1604                    struct ofproto_port *ofproto_port)
1605 {
1606     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1607     struct dpif_port dpif_port;
1608     int error;
1609
1610     error = dpif_port_query_by_name(ofproto->dpif, devname, &dpif_port);
1611     if (!error) {
1612         ofproto_port_from_dpif_port(ofproto_port, &dpif_port);
1613     }
1614     return error;
1615 }
1616
1617 static int
1618 port_add(struct ofproto *ofproto_, struct netdev *netdev, uint16_t *ofp_portp)
1619 {
1620     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1621     uint16_t odp_port;
1622     int error;
1623
1624     error = dpif_port_add(ofproto->dpif, netdev, &odp_port);
1625     if (!error) {
1626         *ofp_portp = odp_port_to_ofp_port(odp_port);
1627     }
1628     return error;
1629 }
1630
1631 static int
1632 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
1633 {
1634     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1635     int error;
1636
1637     error = dpif_port_del(ofproto->dpif, ofp_port_to_odp_port(ofp_port));
1638     if (!error) {
1639         struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
1640         if (ofport) {
1641             /* The caller is going to close ofport->up.netdev.  If this is a
1642              * bonded port, then the bond is using that netdev, so remove it
1643              * from the bond.  The client will need to reconfigure everything
1644              * after deleting ports, so then the slave will get re-added. */
1645             bundle_remove(&ofport->up);
1646         }
1647     }
1648     return error;
1649 }
1650
1651 struct port_dump_state {
1652     struct dpif_port_dump dump;
1653     bool done;
1654 };
1655
1656 static int
1657 port_dump_start(const struct ofproto *ofproto_, void **statep)
1658 {
1659     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1660     struct port_dump_state *state;
1661
1662     *statep = state = xmalloc(sizeof *state);
1663     dpif_port_dump_start(&state->dump, ofproto->dpif);
1664     state->done = false;
1665     return 0;
1666 }
1667
1668 static int
1669 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
1670                struct ofproto_port *port)
1671 {
1672     struct port_dump_state *state = state_;
1673     struct dpif_port dpif_port;
1674
1675     if (dpif_port_dump_next(&state->dump, &dpif_port)) {
1676         ofproto_port_from_dpif_port(port, &dpif_port);
1677         return 0;
1678     } else {
1679         int error = dpif_port_dump_done(&state->dump);
1680         state->done = true;
1681         return error ? error : EOF;
1682     }
1683 }
1684
1685 static int
1686 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
1687 {
1688     struct port_dump_state *state = state_;
1689
1690     if (!state->done) {
1691         dpif_port_dump_done(&state->dump);
1692     }
1693     free(state);
1694     return 0;
1695 }
1696
1697 static int
1698 port_poll(const struct ofproto *ofproto_, char **devnamep)
1699 {
1700     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1701     return dpif_port_poll(ofproto->dpif, devnamep);
1702 }
1703
1704 static void
1705 port_poll_wait(const struct ofproto *ofproto_)
1706 {
1707     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1708     dpif_port_poll_wait(ofproto->dpif);
1709 }
1710
1711 static int
1712 port_is_lacp_current(const struct ofport *ofport_)
1713 {
1714     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1715     return (ofport->bundle && ofport->bundle->lacp
1716             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
1717             : -1);
1718 }
1719 \f
1720 /* Upcall handling. */
1721
1722 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
1723  * OpenFlow controller as necessary according to their individual
1724  * configurations.
1725  *
1726  * If 'clone' is true, the caller retains ownership of 'packet'.  Otherwise,
1727  * ownership is transferred to this function. */
1728 static void
1729 send_packet_in_miss(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
1730                     const struct flow *flow, bool clone)
1731 {
1732     struct ofputil_packet_in pin;
1733
1734     pin.packet = packet;
1735     pin.in_port = flow->in_port;
1736     pin.reason = OFPR_NO_MATCH;
1737     pin.buffer_id = 0;          /* not yet known */
1738     pin.send_len = 0;           /* not used for flow table misses */
1739     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
1740                            clone ? NULL : packet);
1741 }
1742
1743 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_ACTION to each
1744  * OpenFlow controller as necessary according to their individual
1745  * configurations.
1746  *
1747  * 'send_len' should be the number of bytes of 'packet' to send to the
1748  * controller, as specified in the action that caused the packet to be sent.
1749  *
1750  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
1751  * Otherwise, ownership is transferred to this function. */
1752 static void
1753 send_packet_in_action(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
1754                       uint64_t userdata, const struct flow *flow, bool clone)
1755 {
1756     struct ofputil_packet_in pin;
1757     struct user_action_cookie cookie;
1758
1759     memcpy(&cookie, &userdata, sizeof(cookie));
1760
1761     pin.packet = packet;
1762     pin.in_port = flow->in_port;
1763     pin.reason = OFPR_ACTION;
1764     pin.buffer_id = 0;          /* not yet known */
1765     pin.send_len = cookie.data;
1766     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
1767                            clone ? NULL : packet);
1768 }
1769
1770 static bool
1771 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
1772                 const struct ofpbuf *packet)
1773 {
1774     struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
1775
1776     if (!ofport) {
1777         return false;
1778     }
1779
1780     if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
1781         if (packet) {
1782             cfm_process_heartbeat(ofport->cfm, packet);
1783         }
1784         return true;
1785     } else if (ofport->bundle && ofport->bundle->lacp
1786                && flow->dl_type == htons(ETH_TYPE_LACP)) {
1787         if (packet) {
1788             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
1789         }
1790         return true;
1791     }
1792     return false;
1793 }
1794
1795 static void
1796 handle_miss_upcall(struct ofproto_dpif *ofproto, struct dpif_upcall *upcall)
1797 {
1798     struct facet *facet;
1799     struct flow flow;
1800
1801     /* Obtain in_port and tun_id, at least. */
1802     odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
1803
1804     /* Set header pointers in 'flow'. */
1805     flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
1806
1807     /* Handle 802.1ag and LACP. */
1808     if (process_special(ofproto, &flow, upcall->packet)) {
1809         ofpbuf_delete(upcall->packet);
1810         ofproto->n_matches++;
1811         return;
1812     }
1813
1814     facet = facet_lookup_valid(ofproto, &flow);
1815     if (!facet) {
1816         struct rule_dpif *rule = rule_dpif_lookup(ofproto, &flow, 0);
1817         if (!rule) {
1818             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
1819             struct ofport_dpif *port = get_ofp_port(ofproto, flow.in_port);
1820             if (port) {
1821                 if (port->up.opp.config & htonl(OFPPC_NO_PACKET_IN)) {
1822                     COVERAGE_INC(ofproto_dpif_no_packet_in);
1823                     /* XXX install 'drop' flow entry */
1824                     ofpbuf_delete(upcall->packet);
1825                     return;
1826                 }
1827             } else {
1828                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
1829                              flow.in_port);
1830             }
1831
1832             send_packet_in_miss(ofproto, upcall->packet, &flow, false);
1833             return;
1834         }
1835
1836         facet = facet_create(rule, &flow);
1837         facet_make_actions(ofproto, facet, 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'.
2188  *
2189  * The caller must already have determined that no facet with an identical
2190  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2191  * the ofproto's classifier table.
2192  *
2193  * The facet will initially have no ODP actions.  The caller should fix that
2194  * by calling facet_make_actions(). */
2195 static struct facet *
2196 facet_create(struct rule_dpif *rule, const struct flow *flow)
2197 {
2198     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2199     struct facet *facet;
2200
2201     facet = xzalloc(sizeof *facet);
2202     facet->used = time_msec();
2203     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2204     list_push_back(&rule->facets, &facet->list_node);
2205     facet->rule = rule;
2206     facet->flow = *flow;
2207     netflow_flow_init(&facet->nf_flow);
2208     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2209
2210     return facet;
2211 }
2212
2213 static void
2214 facet_free(struct facet *facet)
2215 {
2216     free(facet->actions);
2217     free(facet);
2218 }
2219
2220 static bool
2221 execute_controller_action(struct ofproto_dpif *ofproto,
2222                           const struct flow *flow,
2223                           const struct nlattr *odp_actions, size_t actions_len,
2224                           struct ofpbuf *packet)
2225 {
2226     if (actions_len
2227         && odp_actions->nla_type == OVS_ACTION_ATTR_USERSPACE
2228         && NLA_ALIGN(odp_actions->nla_len) == actions_len) {
2229         /* As an optimization, avoid a round-trip from userspace to kernel to
2230          * userspace.  This also avoids possibly filling up kernel packet
2231          * buffers along the way.
2232          *
2233          * This optimization will not accidentally catch sFlow
2234          * OVS_ACTION_ATTR_USERSPACE actions, since those are encapsulated
2235          * inside OVS_ACTION_ATTR_SAMPLE. */
2236         const struct nlattr *nla;
2237
2238         nla = nl_attr_find_nested(odp_actions, OVS_USERSPACE_ATTR_USERDATA);
2239         send_packet_in_action(ofproto, packet, nl_attr_get_u64(nla), flow,
2240                               false);
2241         return true;
2242     } else {
2243         return false;
2244     }
2245 }
2246
2247 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2248  * 'packet', which arrived on 'in_port'.
2249  *
2250  * Takes ownership of 'packet'. */
2251 static bool
2252 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
2253                     const struct nlattr *odp_actions, size_t actions_len,
2254                     struct ofpbuf *packet)
2255 {
2256     struct odputil_keybuf keybuf;
2257     struct ofpbuf key;
2258     int error;
2259
2260     if (execute_controller_action(ofproto, flow, odp_actions, actions_len,
2261                                   packet)) {
2262         return true;
2263     }
2264
2265     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2266     odp_flow_key_from_flow(&key, flow);
2267
2268     error = dpif_execute(ofproto->dpif, key.data, key.size,
2269                          odp_actions, actions_len, packet);
2270
2271     ofpbuf_delete(packet);
2272     return !error;
2273 }
2274
2275 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2276  * statistics appropriately.  'packet' must have at least sizeof(struct
2277  * ofp_packet_in) bytes of headroom.
2278  *
2279  * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2280  * applying flow_extract() to 'packet' would yield the same flow as
2281  * 'facet->flow'.
2282  *
2283  * 'facet' must have accurately composed datapath actions; that is, it must
2284  * not be in need of revalidation.
2285  *
2286  * Takes ownership of 'packet'. */
2287 static void
2288 facet_execute(struct ofproto_dpif *ofproto, struct facet *facet,
2289               struct ofpbuf *packet)
2290 {
2291     struct dpif_flow_stats stats;
2292
2293     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2294
2295     dpif_flow_stats_extract(&facet->flow, packet, &stats);
2296     stats.used = time_msec();
2297     if (execute_odp_actions(ofproto, &facet->flow,
2298                             facet->actions, facet->actions_len, packet)) {
2299         facet_update_stats(ofproto, facet, &stats);
2300     }
2301 }
2302
2303 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2304  *
2305  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
2306  *     rule's statistics, via facet_uninstall().
2307  *
2308  *   - Removes 'facet' from its rule and from ofproto->facets.
2309  */
2310 static void
2311 facet_remove(struct ofproto_dpif *ofproto, struct facet *facet)
2312 {
2313     facet_uninstall(ofproto, facet);
2314     facet_flush_stats(ofproto, facet);
2315     hmap_remove(&ofproto->facets, &facet->hmap_node);
2316     list_remove(&facet->list_node);
2317     facet_free(facet);
2318 }
2319
2320 /* Composes the datapath actions for 'facet' based on its rule's actions. */
2321 static void
2322 facet_make_actions(struct ofproto_dpif *p, struct facet *facet,
2323                    const struct ofpbuf *packet)
2324 {
2325     const struct rule_dpif *rule = facet->rule;
2326     struct ofpbuf *odp_actions;
2327     struct action_xlate_ctx ctx;
2328
2329     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2330     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
2331     facet->tags = ctx.tags;
2332     facet->may_install = ctx.may_set_up_flow;
2333     facet->has_learn = ctx.has_learn;
2334     facet->has_normal = ctx.has_normal;
2335     facet->nf_flow.output_iface = ctx.nf_output_iface;
2336
2337     if (facet->actions_len != odp_actions->size
2338         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2339         free(facet->actions);
2340         facet->actions_len = odp_actions->size;
2341         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2342     }
2343
2344     ofpbuf_delete(odp_actions);
2345 }
2346
2347 /* Updates 'facet''s flow in the datapath setting its actions to 'actions_len'
2348  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
2349  * in the datapath will be zeroed and 'stats' will be updated with traffic new
2350  * since 'facet' was last updated.
2351  *
2352  * Returns 0 if successful, otherwise a positive errno value.*/
2353 static int
2354 facet_put__(struct ofproto_dpif *ofproto, struct facet *facet,
2355             const struct nlattr *actions, size_t actions_len,
2356             struct dpif_flow_stats *stats)
2357 {
2358     struct odputil_keybuf keybuf;
2359     enum dpif_flow_put_flags flags;
2360     struct ofpbuf key;
2361     int ret;
2362
2363     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2364     if (stats) {
2365         flags |= DPIF_FP_ZERO_STATS;
2366     }
2367
2368     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2369     odp_flow_key_from_flow(&key, &facet->flow);
2370
2371     ret = dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
2372                         actions, actions_len, stats);
2373
2374     if (stats) {
2375         facet_reset_dp_stats(facet, stats);
2376     }
2377
2378     return ret;
2379 }
2380
2381 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
2382  * 'zero_stats' is true, clears any existing statistics from the datapath for
2383  * 'facet'. */
2384 static void
2385 facet_install(struct ofproto_dpif *p, struct facet *facet, bool zero_stats)
2386 {
2387     struct dpif_flow_stats stats;
2388
2389     if (facet->may_install
2390         && !facet_put__(p, facet, facet->actions, facet->actions_len,
2391                         zero_stats ? &stats : NULL)) {
2392         facet->installed = true;
2393     }
2394 }
2395
2396 static void
2397 facet_account(struct ofproto_dpif *ofproto, struct facet *facet)
2398 {
2399     uint64_t n_bytes;
2400     const struct nlattr *a;
2401     unsigned int left;
2402     ovs_be16 vlan_tci;
2403
2404     if (facet->byte_count <= facet->accounted_bytes) {
2405         return;
2406     }
2407     n_bytes = facet->byte_count - facet->accounted_bytes;
2408     facet->accounted_bytes = facet->byte_count;
2409
2410     /* Feed information from the active flows back into the learning table to
2411      * ensure that table is always in sync with what is actually flowing
2412      * through the datapath. */
2413     if (facet->has_learn || facet->has_normal) {
2414         struct action_xlate_ctx ctx;
2415
2416         action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2417         ctx.may_learn = true;
2418         ofpbuf_delete(xlate_actions(&ctx, facet->rule->up.actions,
2419                                     facet->rule->up.n_actions));
2420     }
2421
2422     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
2423         return;
2424     }
2425
2426     /* This loop feeds byte counters to bond_account() for rebalancing to use
2427      * as a basis.  We also need to track the actual VLAN on which the packet
2428      * is going to be sent to ensure that it matches the one passed to
2429      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
2430      * hash bucket.) */
2431     vlan_tci = facet->flow.vlan_tci;
2432     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->actions, facet->actions_len) {
2433         struct ofport_dpif *port;
2434
2435         switch (nl_attr_type(a)) {
2436         case OVS_ACTION_ATTR_OUTPUT:
2437             port = get_odp_port(ofproto, nl_attr_get_u32(a));
2438             if (port && port->bundle && port->bundle->bond) {
2439                 bond_account(port->bundle->bond, &facet->flow,
2440                              vlan_tci_to_vid(vlan_tci), n_bytes);
2441             }
2442             break;
2443
2444         case OVS_ACTION_ATTR_POP_VLAN:
2445             vlan_tci = htons(0);
2446             break;
2447
2448         case OVS_ACTION_ATTR_PUSH_VLAN:
2449             vlan_tci = nl_attr_get_be16(a);
2450             break;
2451         }
2452     }
2453 }
2454
2455 /* If 'rule' is installed in the datapath, uninstalls it. */
2456 static void
2457 facet_uninstall(struct ofproto_dpif *p, struct facet *facet)
2458 {
2459     if (facet->installed) {
2460         struct odputil_keybuf keybuf;
2461         struct dpif_flow_stats stats;
2462         struct ofpbuf key;
2463         int error;
2464
2465         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2466         odp_flow_key_from_flow(&key, &facet->flow);
2467
2468         error = dpif_flow_del(p->dpif, key.data, key.size, &stats);
2469         facet_reset_dp_stats(facet, &stats);
2470         if (!error) {
2471             facet_update_stats(p, facet, &stats);
2472         }
2473         facet->installed = false;
2474     } else {
2475         assert(facet->dp_packet_count == 0);
2476         assert(facet->dp_byte_count == 0);
2477     }
2478 }
2479
2480 /* Returns true if the only action for 'facet' is to send to the controller.
2481  * (We don't report NetFlow expiration messages for such facets because they
2482  * are just part of the control logic for the network, not real traffic). */
2483 static bool
2484 facet_is_controller_flow(struct facet *facet)
2485 {
2486     return (facet
2487             && facet->rule->up.n_actions == 1
2488             && action_outputs_to_port(&facet->rule->up.actions[0],
2489                                       htons(OFPP_CONTROLLER)));
2490 }
2491
2492 /* Resets 'facet''s datapath statistics counters.  This should be called when
2493  * 'facet''s statistics are cleared in the datapath.  If 'stats' is non-null,
2494  * it should contain the statistics returned by dpif when 'facet' was reset in
2495  * the datapath.  'stats' will be modified to only included statistics new
2496  * since 'facet' was last updated. */
2497 static void
2498 facet_reset_dp_stats(struct facet *facet, struct dpif_flow_stats *stats)
2499 {
2500     if (stats && facet->dp_packet_count <= stats->n_packets
2501         && facet->dp_byte_count <= stats->n_bytes) {
2502         stats->n_packets -= facet->dp_packet_count;
2503         stats->n_bytes -= facet->dp_byte_count;
2504     }
2505
2506     facet->dp_packet_count = 0;
2507     facet->dp_byte_count = 0;
2508 }
2509
2510 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2511  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
2512  * 'facet''s statistics in the datapath should have been zeroed and folded into
2513  * its packet and byte counts before this function is called. */
2514 static void
2515 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
2516 {
2517     assert(!facet->dp_byte_count);
2518     assert(!facet->dp_packet_count);
2519
2520     facet_push_stats(facet);
2521     facet_account(ofproto, facet);
2522
2523     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2524         struct ofexpired expired;
2525         expired.flow = facet->flow;
2526         expired.packet_count = facet->packet_count;
2527         expired.byte_count = facet->byte_count;
2528         expired.used = facet->used;
2529         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2530     }
2531
2532     facet->rule->packet_count += facet->packet_count;
2533     facet->rule->byte_count += facet->byte_count;
2534
2535     /* Reset counters to prevent double counting if 'facet' ever gets
2536      * reinstalled. */
2537     facet_reset_counters(facet);
2538
2539     netflow_flow_clear(&facet->nf_flow);
2540 }
2541
2542 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2543  * Returns it if found, otherwise a null pointer.
2544  *
2545  * The returned facet might need revalidation; use facet_lookup_valid()
2546  * instead if that is important. */
2547 static struct facet *
2548 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
2549 {
2550     struct facet *facet;
2551
2552     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
2553                              &ofproto->facets) {
2554         if (flow_equal(flow, &facet->flow)) {
2555             return facet;
2556         }
2557     }
2558
2559     return NULL;
2560 }
2561
2562 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
2563  * Returns it if found, otherwise a null pointer.
2564  *
2565  * The returned facet is guaranteed to be valid. */
2566 static struct facet *
2567 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
2568 {
2569     struct facet *facet = facet_find(ofproto, flow);
2570
2571     /* The facet we found might not be valid, since we could be in need of
2572      * revalidation.  If it is not valid, don't return it. */
2573     if (facet
2574         && (ofproto->need_revalidate
2575             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))
2576         && !facet_revalidate(ofproto, facet)) {
2577         COVERAGE_INC(facet_invalidated);
2578         return NULL;
2579     }
2580
2581     return facet;
2582 }
2583
2584 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
2585  *
2586  *   - If the rule found is different from 'facet''s current rule, moves
2587  *     'facet' to the new rule and recompiles its actions.
2588  *
2589  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
2590  *     where it is and recompiles its actions anyway.
2591  *
2592  *   - If there is none, destroys 'facet'.
2593  *
2594  * Returns true if 'facet' still exists, false if it has been destroyed. */
2595 static bool
2596 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
2597 {
2598     struct action_xlate_ctx ctx;
2599     struct ofpbuf *odp_actions;
2600     struct rule_dpif *new_rule;
2601     bool actions_changed;
2602
2603     COVERAGE_INC(facet_revalidate);
2604
2605     /* Determine the new rule. */
2606     new_rule = rule_dpif_lookup(ofproto, &facet->flow, 0);
2607     if (!new_rule) {
2608         /* No new rule, so delete the facet. */
2609         facet_remove(ofproto, facet);
2610         return false;
2611     }
2612
2613     /* Calculate new datapath actions.
2614      *
2615      * We do not modify any 'facet' state yet, because we might need to, e.g.,
2616      * emit a NetFlow expiration and, if so, we need to have the old state
2617      * around to properly compose it. */
2618     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2619     odp_actions = xlate_actions(&ctx,
2620                                 new_rule->up.actions, new_rule->up.n_actions);
2621     actions_changed = (facet->actions_len != odp_actions->size
2622                        || memcmp(facet->actions, odp_actions->data,
2623                                  facet->actions_len));
2624
2625     /* If the datapath actions changed or the installability changed,
2626      * then we need to talk to the datapath. */
2627     if (actions_changed || ctx.may_set_up_flow != facet->installed) {
2628         if (ctx.may_set_up_flow) {
2629             struct dpif_flow_stats stats;
2630
2631             facet_put__(ofproto, facet,
2632                         odp_actions->data, odp_actions->size, &stats);
2633             facet_update_stats(ofproto, facet, &stats);
2634         } else {
2635             facet_uninstall(ofproto, facet);
2636         }
2637
2638         /* The datapath flow is gone or has zeroed stats, so push stats out of
2639          * 'facet' into 'rule'. */
2640         facet_flush_stats(ofproto, facet);
2641     }
2642
2643     /* Update 'facet' now that we've taken care of all the old state. */
2644     facet->tags = ctx.tags;
2645     facet->nf_flow.output_iface = ctx.nf_output_iface;
2646     facet->may_install = ctx.may_set_up_flow;
2647     facet->has_learn = ctx.has_learn;
2648     facet->has_normal = ctx.has_normal;
2649     if (actions_changed) {
2650         free(facet->actions);
2651         facet->actions_len = odp_actions->size;
2652         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2653     }
2654     if (facet->rule != new_rule) {
2655         COVERAGE_INC(facet_changed_rule);
2656         list_remove(&facet->list_node);
2657         list_push_back(&new_rule->facets, &facet->list_node);
2658         facet->rule = new_rule;
2659         facet->used = new_rule->up.created;
2660         facet->rs_used = facet->used;
2661     }
2662
2663     ofpbuf_delete(odp_actions);
2664
2665     return true;
2666 }
2667
2668 /* Updates 'facet''s used time.  Caller is responsible for calling
2669  * facet_push_stats() to update the flows which 'facet' resubmits into. */
2670 static void
2671 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
2672                   long long int used)
2673 {
2674     if (used > facet->used) {
2675         facet->used = used;
2676         if (used > facet->rule->used) {
2677             facet->rule->used = used;
2678         }
2679         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
2680     }
2681 }
2682
2683 /* Folds the statistics from 'stats' into the counters in 'facet'.
2684  *
2685  * Because of the meaning of a facet's counters, it only makes sense to do this
2686  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
2687  * packet that was sent by hand or if it represents statistics that have been
2688  * cleared out of the datapath. */
2689 static void
2690 facet_update_stats(struct ofproto_dpif *ofproto, struct facet *facet,
2691                    const struct dpif_flow_stats *stats)
2692 {
2693     if (stats->n_packets || stats->used > facet->used) {
2694         facet_update_time(ofproto, facet, stats->used);
2695         facet->packet_count += stats->n_packets;
2696         facet->byte_count += stats->n_bytes;
2697         facet_push_stats(facet);
2698         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
2699     }
2700 }
2701
2702 static void
2703 facet_reset_counters(struct facet *facet)
2704 {
2705     facet->packet_count = 0;
2706     facet->byte_count = 0;
2707     facet->rs_packet_count = 0;
2708     facet->rs_byte_count = 0;
2709     facet->accounted_bytes = 0;
2710 }
2711
2712 static void
2713 facet_push_stats(struct facet *facet)
2714 {
2715     uint64_t rs_packets, rs_bytes;
2716
2717     assert(facet->packet_count >= facet->rs_packet_count);
2718     assert(facet->byte_count >= facet->rs_byte_count);
2719     assert(facet->used >= facet->rs_used);
2720
2721     rs_packets = facet->packet_count - facet->rs_packet_count;
2722     rs_bytes = facet->byte_count - facet->rs_byte_count;
2723
2724     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
2725         facet->rs_packet_count = facet->packet_count;
2726         facet->rs_byte_count = facet->byte_count;
2727         facet->rs_used = facet->used;
2728
2729         flow_push_stats(facet->rule, &facet->flow,
2730                         rs_packets, rs_bytes, facet->used);
2731     }
2732 }
2733
2734 struct ofproto_push {
2735     struct action_xlate_ctx ctx;
2736     uint64_t packets;
2737     uint64_t bytes;
2738     long long int used;
2739 };
2740
2741 static void
2742 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
2743 {
2744     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
2745
2746     if (rule) {
2747         rule->packet_count += push->packets;
2748         rule->byte_count += push->bytes;
2749         rule->used = MAX(push->used, rule->used);
2750     }
2751 }
2752
2753 /* Pushes flow statistics to the rules which 'flow' resubmits into given
2754  * 'rule''s actions. */
2755 static void
2756 flow_push_stats(const struct rule_dpif *rule,
2757                 struct flow *flow, uint64_t packets, uint64_t bytes,
2758                 long long int used)
2759 {
2760     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2761     struct ofproto_push push;
2762
2763     push.packets = packets;
2764     push.bytes = bytes;
2765     push.used = used;
2766
2767     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
2768     push.ctx.resubmit_hook = push_resubmit;
2769     ofpbuf_delete(xlate_actions(&push.ctx,
2770                                 rule->up.actions, rule->up.n_actions));
2771 }
2772 \f
2773 /* Rules. */
2774
2775 static struct rule_dpif *
2776 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
2777                  uint8_t table_id)
2778 {
2779     if (table_id >= N_TABLES) {
2780         return NULL;
2781     }
2782
2783     return rule_dpif_cast(rule_from_cls_rule(
2784                               classifier_lookup(&ofproto->up.tables[table_id],
2785                                                 flow)));
2786 }
2787
2788 static void
2789 complete_operation(struct rule_dpif *rule)
2790 {
2791     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2792
2793     rule_invalidate(rule);
2794     if (clogged) {
2795         struct dpif_completion *c = xmalloc(sizeof *c);
2796         c->op = rule->up.pending;
2797         list_push_back(&ofproto->completions, &c->list_node);
2798     } else {
2799         ofoperation_complete(rule->up.pending, 0);
2800     }
2801 }
2802
2803 static struct rule *
2804 rule_alloc(void)
2805 {
2806     struct rule_dpif *rule = xmalloc(sizeof *rule);
2807     return &rule->up;
2808 }
2809
2810 static void
2811 rule_dealloc(struct rule *rule_)
2812 {
2813     struct rule_dpif *rule = rule_dpif_cast(rule_);
2814     free(rule);
2815 }
2816
2817 static int
2818 rule_construct(struct rule *rule_)
2819 {
2820     struct rule_dpif *rule = rule_dpif_cast(rule_);
2821     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2822     struct rule_dpif *victim;
2823     uint8_t table_id;
2824     int error;
2825
2826     error = validate_actions(rule->up.actions, rule->up.n_actions,
2827                              &rule->up.cr.flow, ofproto->max_ports);
2828     if (error) {
2829         return error;
2830     }
2831
2832     rule->used = rule->up.created;
2833     rule->packet_count = 0;
2834     rule->byte_count = 0;
2835
2836     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
2837     if (victim && !list_is_empty(&victim->facets)) {
2838         struct facet *facet;
2839
2840         rule->facets = victim->facets;
2841         list_moved(&rule->facets);
2842         LIST_FOR_EACH (facet, list_node, &rule->facets) {
2843             /* XXX: We're only clearing our local counters here.  It's possible
2844              * that quite a few packets are unaccounted for in the datapath
2845              * statistics.  These will be accounted to the new rule instead of
2846              * cleared as required.  This could be fixed by clearing out the
2847              * datapath statistics for this facet, but currently it doesn't
2848              * seem worth it. */
2849             facet_reset_counters(facet);
2850             facet->rule = rule;
2851         }
2852     } else {
2853         /* Must avoid list_moved() in this case. */
2854         list_init(&rule->facets);
2855     }
2856
2857     table_id = rule->up.table_id;
2858     rule->tag = (victim ? victim->tag
2859                  : table_id == 0 ? 0
2860                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
2861                                       ofproto->tables[table_id].basis));
2862
2863     complete_operation(rule);
2864     return 0;
2865 }
2866
2867 static void
2868 rule_destruct(struct rule *rule_)
2869 {
2870     struct rule_dpif *rule = rule_dpif_cast(rule_);
2871     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2872     struct facet *facet, *next_facet;
2873
2874     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2875         facet_revalidate(ofproto, facet);
2876     }
2877
2878     complete_operation(rule);
2879 }
2880
2881 static void
2882 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
2883 {
2884     struct rule_dpif *rule = rule_dpif_cast(rule_);
2885     struct facet *facet;
2886
2887     /* Start from historical data for 'rule' itself that are no longer tracked
2888      * in facets.  This counts, for example, facets that have expired. */
2889     *packets = rule->packet_count;
2890     *bytes = rule->byte_count;
2891
2892     /* Add any statistics that are tracked by facets.  This includes
2893      * statistical data recently updated by ofproto_update_stats() as well as
2894      * stats for packets that were executed "by hand" via dpif_execute(). */
2895     LIST_FOR_EACH (facet, list_node, &rule->facets) {
2896         *packets += facet->packet_count;
2897         *bytes += facet->byte_count;
2898     }
2899 }
2900
2901 static int
2902 rule_execute(struct rule *rule_, struct flow *flow, struct ofpbuf *packet)
2903 {
2904     struct rule_dpif *rule = rule_dpif_cast(rule_);
2905     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2906     struct action_xlate_ctx ctx;
2907     struct ofpbuf *odp_actions;
2908     struct facet *facet;
2909     size_t size;
2910
2911     /* First look for a related facet.  If we find one, account it to that. */
2912     facet = facet_lookup_valid(ofproto, flow);
2913     if (facet && facet->rule == rule) {
2914         if (!facet->may_install) {
2915             facet_make_actions(ofproto, facet, packet);
2916         }
2917         facet_execute(ofproto, facet, packet);
2918         return 0;
2919     }
2920
2921     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
2922      * create a new facet for it and use that. */
2923     if (rule_dpif_lookup(ofproto, flow, 0) == rule) {
2924         facet = facet_create(rule, flow);
2925         facet_make_actions(ofproto, facet, 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 };