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