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