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