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