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