ofproto-dpif: Fix uninitialized struct member in xlate_actions().
[sliver-openvswitch.git] / ofproto / ofproto-dpif.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #include <config.h>
18
19 #include "ofproto/ofproto-provider.h"
20
21 #include <errno.h>
22
23 #include "autopath.h"
24 #include "bond.h"
25 #include "bundle.h"
26 #include "byte-order.h"
27 #include "connmgr.h"
28 #include "coverage.h"
29 #include "cfm.h"
30 #include "dpif.h"
31 #include "dynamic-string.h"
32 #include "fail-open.h"
33 #include "hmapx.h"
34 #include "lacp.h"
35 #include "learn.h"
36 #include "mac-learning.h"
37 #include "multipath.h"
38 #include "netdev.h"
39 #include "netlink.h"
40 #include "nx-match.h"
41 #include "odp-util.h"
42 #include "ofp-util.h"
43 #include "ofpbuf.h"
44 #include "ofp-print.h"
45 #include "ofproto-dpif-sflow.h"
46 #include "poll-loop.h"
47 #include "timer.h"
48 #include "unaligned.h"
49 #include "unixctl.h"
50 #include "vlan-bitmap.h"
51 #include "vlog.h"
52
53 VLOG_DEFINE_THIS_MODULE(ofproto_dpif);
54
55 COVERAGE_DEFINE(ofproto_dpif_ctlr_action);
56 COVERAGE_DEFINE(ofproto_dpif_expired);
57 COVERAGE_DEFINE(ofproto_dpif_no_packet_in);
58 COVERAGE_DEFINE(ofproto_dpif_xlate);
59 COVERAGE_DEFINE(facet_changed_rule);
60 COVERAGE_DEFINE(facet_invalidated);
61 COVERAGE_DEFINE(facet_revalidate);
62 COVERAGE_DEFINE(facet_unexpected);
63
64 /* Maximum depth of flow table recursion (due to resubmit actions) in a
65  * flow translation. */
66 #define MAX_RESUBMIT_RECURSION 32
67
68 /* Number of implemented OpenFlow tables. */
69 enum { N_TABLES = 255 };
70 BUILD_ASSERT_DECL(N_TABLES >= 1 && N_TABLES <= 255);
71
72 struct ofport_dpif;
73 struct ofproto_dpif;
74
75 struct rule_dpif {
76     struct rule up;
77
78     long long int used;         /* Time last used; time created if not used. */
79
80     /* These statistics:
81      *
82      *   - Do include packets and bytes from facets that have been deleted or
83      *     whose own statistics have been folded into the rule.
84      *
85      *   - Do include packets and bytes sent "by hand" that were accounted to
86      *     the rule without any facet being involved (this is a rare corner
87      *     case in rule_execute()).
88      *
89      *   - Do not include packet or bytes that can be obtained from any facet's
90      *     packet_count or byte_count member or that can be obtained from the
91      *     datapath by, e.g., dpif_flow_get() for any facet.
92      */
93     uint64_t packet_count;       /* Number of packets received. */
94     uint64_t byte_count;         /* Number of bytes received. */
95
96     tag_type tag;                /* Caches rule_calculate_tag() result. */
97
98     struct list facets;          /* List of "struct facet"s. */
99 };
100
101 static struct rule_dpif *rule_dpif_cast(const struct rule *rule)
102 {
103     return rule ? CONTAINER_OF(rule, struct rule_dpif, up) : NULL;
104 }
105
106 static struct rule_dpif *rule_dpif_lookup(struct ofproto_dpif *,
107                                           const struct flow *, uint8_t table);
108
109 #define MAX_MIRRORS 32
110 typedef uint32_t mirror_mask_t;
111 #define MIRROR_MASK_C(X) UINT32_C(X)
112 BUILD_ASSERT_DECL(sizeof(mirror_mask_t) * CHAR_BIT >= MAX_MIRRORS);
113 struct ofmirror {
114     struct ofproto_dpif *ofproto; /* Owning ofproto. */
115     size_t idx;                 /* In ofproto's "mirrors" array. */
116     void *aux;                  /* Key supplied by ofproto's client. */
117     char *name;                 /* Identifier for log messages. */
118
119     /* Selection criteria. */
120     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
121     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
122     unsigned long *vlans;       /* Bitmap of chosen VLANs, NULL selects all. */
123
124     /* Output (mutually exclusive). */
125     struct ofbundle *out;       /* Output port or NULL. */
126     int out_vlan;               /* Output VLAN or -1. */
127 };
128
129 static void mirror_destroy(struct ofmirror *);
130
131 /* A group of one or more OpenFlow ports. */
132 #define OFBUNDLE_FLOOD ((struct ofbundle *) 1)
133 struct ofbundle {
134     struct ofproto_dpif *ofproto; /* Owning ofproto. */
135     struct hmap_node hmap_node; /* In struct ofproto's "bundles" hmap. */
136     void *aux;                  /* Key supplied by ofproto's client. */
137     char *name;                 /* Identifier for log messages. */
138
139     /* Configuration. */
140     struct list ports;          /* Contains "struct ofport"s. */
141     enum port_vlan_mode vlan_mode; /* VLAN mode */
142     int vlan;                   /* -1=trunk port, else a 12-bit VLAN ID. */
143     unsigned long *trunks;      /* Bitmap of trunked VLANs, if 'vlan' == -1.
144                                  * NULL if all VLANs are trunked. */
145     struct lacp *lacp;          /* LACP if LACP is enabled, otherwise NULL. */
146     struct bond *bond;          /* Nonnull iff more than one port. */
147
148     /* Status. */
149     bool floodable;             /* True if no port has OFPPC_NO_FLOOD set. */
150
151     /* Port mirroring info. */
152     mirror_mask_t src_mirrors;  /* Mirrors triggered when packet received. */
153     mirror_mask_t dst_mirrors;  /* Mirrors triggered when packet sent. */
154     mirror_mask_t mirror_out;   /* Mirrors that output to this bundle. */
155 };
156
157 static void bundle_remove(struct ofport *);
158 static void bundle_update(struct ofbundle *);
159 static void bundle_destroy(struct ofbundle *);
160 static void bundle_del_port(struct ofport_dpif *);
161 static void bundle_run(struct ofbundle *);
162 static void bundle_wait(struct ofbundle *);
163
164 static void stp_run(struct ofproto_dpif *ofproto);
165 static void stp_wait(struct ofproto_dpif *ofproto);
166
167 struct action_xlate_ctx {
168 /* action_xlate_ctx_init() initializes these members. */
169
170     /* The ofproto. */
171     struct ofproto_dpif *ofproto;
172
173     /* Flow to which the OpenFlow actions apply.  xlate_actions() will modify
174      * this flow when actions change header fields. */
175     struct flow flow;
176
177     /* The packet corresponding to 'flow', or a null pointer if we are
178      * revalidating without a packet to refer to. */
179     const struct ofpbuf *packet;
180
181     /* Should OFPP_NORMAL MAC learning and NXAST_LEARN actions execute?  We
182      * want to execute them if we are actually processing a packet, or if we
183      * are accounting for packets that the datapath has processed, but not if
184      * we are just revalidating. */
185     bool may_learn;
186
187     /* If nonnull, called just before executing a resubmit action.
188      *
189      * This is normally null so the client has to set it manually after
190      * calling action_xlate_ctx_init(). */
191     void (*resubmit_hook)(struct action_xlate_ctx *, struct rule_dpif *);
192
193 /* xlate_actions() initializes and uses these members.  The client might want
194  * to look at them after it returns. */
195
196     struct ofpbuf *odp_actions; /* Datapath actions. */
197     tag_type tags;              /* Tags associated with actions. */
198     bool may_set_up_flow;       /* True ordinarily; false if the actions must
199                                  * be reassessed for every packet. */
200     bool has_learn;             /* Actions include NXAST_LEARN? */
201     bool has_normal;            /* Actions output to OFPP_NORMAL? */
202     uint16_t nf_output_iface;   /* Output interface index for NetFlow. */
203
204 /* xlate_actions() initializes and uses these members, but the client has no
205  * reason to look at them. */
206
207     int recurse;                /* Recursion level, via xlate_table_action. */
208     uint32_t priority;          /* Current flow priority. 0 if none. */
209     struct flow base_flow;      /* Flow at the last commit. */
210     uint32_t base_priority;     /* Priority at the last commit. */
211     uint8_t table_id;           /* OpenFlow table ID where flow was found. */
212     uint32_t sflow_n_outputs;   /* Number of output ports. */
213     uint16_t sflow_odp_port;    /* Output port for composing sFlow action. */
214     uint16_t user_cookie_offset;/* Used for user_action_cookie fixup. */
215 };
216
217 static void action_xlate_ctx_init(struct action_xlate_ctx *,
218                                   struct ofproto_dpif *, const struct flow *,
219                                   const struct ofpbuf *);
220 static struct ofpbuf *xlate_actions(struct action_xlate_ctx *,
221                                     const union ofp_action *in, size_t n_in);
222
223 /* An exact-match instantiation of an OpenFlow flow. */
224 struct facet {
225     long long int used;         /* Time last used; time created if not used. */
226
227     /* These statistics:
228      *
229      *   - Do include packets and bytes sent "by hand", e.g. with
230      *     dpif_execute().
231      *
232      *   - Do include packets and bytes that were obtained from the datapath
233      *     when its statistics were reset (e.g. dpif_flow_put() with
234      *     DPIF_FP_ZERO_STATS).
235      */
236     uint64_t packet_count;       /* Number of packets received. */
237     uint64_t byte_count;         /* Number of bytes received. */
238
239     uint64_t dp_packet_count;    /* Last known packet count in the datapath. */
240     uint64_t dp_byte_count;      /* Last known byte count in the datapath. */
241
242     uint64_t rs_packet_count;    /* Packets pushed to resubmit children. */
243     uint64_t rs_byte_count;      /* Bytes pushed to resubmit children. */
244     long long int rs_used;       /* Used time pushed to resubmit children. */
245
246     uint64_t accounted_bytes;    /* Bytes processed by facet_account(). */
247
248     struct hmap_node hmap_node;  /* In owning ofproto's 'facets' hmap. */
249     struct list list_node;       /* In owning rule's 'facets' list. */
250     struct rule_dpif *rule;      /* Owning rule. */
251     struct flow flow;            /* Exact-match flow. */
252     bool installed;              /* Installed in datapath? */
253     bool may_install;            /* True ordinarily; false if actions must
254                                   * be reassessed for every packet. */
255     bool has_learn;              /* Actions include NXAST_LEARN? */
256     bool has_normal;             /* Actions output to OFPP_NORMAL? */
257     size_t actions_len;          /* Number of bytes in actions[]. */
258     struct nlattr *actions;      /* Datapath actions. */
259     tag_type tags;               /* Tags. */
260     struct netflow_flow nf_flow; /* Per-flow NetFlow tracking data. */
261 };
262
263 static struct facet *facet_create(struct rule_dpif *, const struct flow *);
264 static void facet_remove(struct ofproto_dpif *, struct facet *);
265 static void facet_free(struct facet *);
266
267 static struct facet *facet_find(struct ofproto_dpif *, const struct flow *);
268 static struct facet *facet_lookup_valid(struct ofproto_dpif *,
269                                         const struct flow *);
270 static bool facet_revalidate(struct ofproto_dpif *, struct facet *);
271
272 static bool execute_controller_action(struct ofproto_dpif *,
273                                       const struct flow *,
274                                       const struct nlattr *odp_actions,
275                                       size_t actions_len,
276                                       struct ofpbuf *packet);
277 static void facet_execute(struct ofproto_dpif *, struct facet *,
278                           struct ofpbuf *packet);
279
280 static int facet_put__(struct ofproto_dpif *, struct facet *,
281                        const struct nlattr *actions, size_t actions_len,
282                        struct dpif_flow_stats *);
283 static void facet_install(struct ofproto_dpif *, struct facet *,
284                           bool zero_stats);
285 static void facet_uninstall(struct ofproto_dpif *, struct facet *);
286 static void facet_flush_stats(struct ofproto_dpif *, struct facet *);
287
288 static void facet_make_actions(struct ofproto_dpif *, struct facet *,
289                                const struct ofpbuf *packet);
290 static void facet_update_time(struct ofproto_dpif *, struct facet *,
291                               long long int used);
292 static void facet_update_stats(struct ofproto_dpif *, struct facet *,
293                                const struct dpif_flow_stats *);
294 static void facet_reset_counters(struct facet *);
295 static void facet_reset_dp_stats(struct facet *, struct dpif_flow_stats *);
296 static void facet_push_stats(struct facet *);
297 static void facet_account(struct ofproto_dpif *, struct facet *);
298
299 static bool facet_is_controller_flow(struct facet *);
300
301 static void flow_push_stats(const struct rule_dpif *,
302                             struct flow *, uint64_t packets, uint64_t bytes,
303                             long long int used);
304
305 static uint32_t rule_calculate_tag(const struct flow *,
306                                    const struct flow_wildcards *,
307                                    uint32_t basis);
308 static void rule_invalidate(const struct rule_dpif *);
309
310 struct ofport_dpif {
311     struct ofport up;
312
313     uint32_t odp_port;
314     struct ofbundle *bundle;    /* Bundle that contains this port, if any. */
315     struct list bundle_node;    /* In struct ofbundle's "ports" list. */
316     struct cfm *cfm;            /* Connectivity Fault Management, if any. */
317     tag_type tag;               /* Tag associated with this port. */
318     uint32_t bond_stable_id;    /* stable_id to use as bond slave, or 0. */
319     bool may_enable;            /* May be enabled in bonds. */
320
321     struct stp_port *stp_port;  /* Spanning Tree Protocol, if any. */
322     enum stp_state stp_state;   /* Always STP_DISABLED if STP not in use. */
323     long long int stp_state_entered;
324 };
325
326 static struct ofport_dpif *
327 ofport_dpif_cast(const struct ofport *ofport)
328 {
329     assert(ofport->ofproto->ofproto_class == &ofproto_dpif_class);
330     return ofport ? CONTAINER_OF(ofport, struct ofport_dpif, up) : NULL;
331 }
332
333 static void port_run(struct ofport_dpif *);
334 static void port_wait(struct ofport_dpif *);
335 static int set_cfm(struct ofport *, const struct cfm_settings *);
336
337 struct dpif_completion {
338     struct list list_node;
339     struct ofoperation *op;
340 };
341
342 /* Extra information about a classifier table.
343  * Currently used just for optimized flow revalidation. */
344 struct table_dpif {
345     /* If either of these is nonnull, then this table has a form that allows
346      * flows to be tagged to avoid revalidating most flows for the most common
347      * kinds of flow table changes. */
348     struct cls_table *catchall_table; /* Table that wildcards all fields. */
349     struct cls_table *other_table;    /* Table with any other wildcard set. */
350     uint32_t basis;                   /* Keeps each table's tags separate. */
351 };
352
353 struct ofproto_dpif {
354     struct ofproto up;
355     struct dpif *dpif;
356     int max_ports;
357
358     /* Statistics. */
359     uint64_t n_matches;
360
361     /* Bridging. */
362     struct netflow *netflow;
363     struct dpif_sflow *sflow;
364     struct hmap bundles;        /* Contains "struct ofbundle"s. */
365     struct mac_learning *ml;
366     struct ofmirror *mirrors[MAX_MIRRORS];
367     bool has_bonded_bundles;
368
369     /* Expiration. */
370     struct timer next_expiration;
371
372     /* Facets. */
373     struct hmap facets;
374
375     /* Revalidation. */
376     struct table_dpif tables[N_TABLES];
377     bool need_revalidate;
378     struct tag_set revalidate_set;
379
380     /* Support for debugging async flow mods. */
381     struct list completions;
382
383     bool has_bundle_action; /* True when the first bundle action appears. */
384
385     /* Spanning tree. */
386     struct stp *stp;
387     long long int stp_last_tick;
388 };
389
390 /* Defer flow mod completion until "ovs-appctl ofproto/unclog"?  (Useful only
391  * for debugging the asynchronous flow_mod implementation.) */
392 static bool clogged;
393
394 static void ofproto_dpif_unixctl_init(void);
395
396 static struct ofproto_dpif *
397 ofproto_dpif_cast(const struct ofproto *ofproto)
398 {
399     assert(ofproto->ofproto_class == &ofproto_dpif_class);
400     return CONTAINER_OF(ofproto, struct ofproto_dpif, up);
401 }
402
403 static struct ofport_dpif *get_ofp_port(struct ofproto_dpif *,
404                                         uint16_t ofp_port);
405 static struct ofport_dpif *get_odp_port(struct ofproto_dpif *,
406                                         uint32_t odp_port);
407
408 /* Packet processing. */
409 static void update_learning_table(struct ofproto_dpif *,
410                                   const struct flow *, int vlan,
411                                   struct ofbundle *);
412 static bool is_admissible(struct ofproto_dpif *, const struct flow *,
413                           bool have_packet, tag_type *, int *vlanp,
414                           struct ofbundle **in_bundlep);
415
416 /* Upcalls. */
417 #define FLOW_MISS_MAX_BATCH 50
418 static void handle_upcall(struct ofproto_dpif *, struct dpif_upcall *);
419 static void handle_miss_upcalls(struct ofproto_dpif *,
420                                 struct dpif_upcall *, size_t n);
421
422 /* Flow expiration. */
423 static int expire(struct ofproto_dpif *);
424
425 /* Utilities. */
426 static int send_packet(struct ofproto_dpif *, uint32_t odp_port,
427                        const struct ofpbuf *packet);
428 static size_t
429 compose_sflow_action(const struct ofproto_dpif *, struct ofpbuf *odp_actions,
430                      const struct flow *, uint32_t odp_port);
431 /* Global variables. */
432 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
433 \f
434 /* Factory functions. */
435
436 static void
437 enumerate_types(struct sset *types)
438 {
439     dp_enumerate_types(types);
440 }
441
442 static int
443 enumerate_names(const char *type, struct sset *names)
444 {
445     return dp_enumerate_names(type, names);
446 }
447
448 static int
449 del(const char *type, const char *name)
450 {
451     struct dpif *dpif;
452     int error;
453
454     error = dpif_open(name, type, &dpif);
455     if (!error) {
456         error = dpif_delete(dpif);
457         dpif_close(dpif);
458     }
459     return error;
460 }
461 \f
462 /* Basic life-cycle. */
463
464 static struct ofproto *
465 alloc(void)
466 {
467     struct ofproto_dpif *ofproto = xmalloc(sizeof *ofproto);
468     return &ofproto->up;
469 }
470
471 static void
472 dealloc(struct ofproto *ofproto_)
473 {
474     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
475     free(ofproto);
476 }
477
478 static int
479 construct(struct ofproto *ofproto_, int *n_tablesp)
480 {
481     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
482     const char *name = ofproto->up.name;
483     int error;
484     int i;
485
486     error = dpif_create_and_open(name, ofproto->up.type, &ofproto->dpif);
487     if (error) {
488         VLOG_ERR("failed to open datapath %s: %s", name, strerror(error));
489         return error;
490     }
491
492     ofproto->max_ports = dpif_get_max_ports(ofproto->dpif);
493     ofproto->n_matches = 0;
494
495     dpif_flow_flush(ofproto->dpif);
496     dpif_recv_purge(ofproto->dpif);
497
498     error = dpif_recv_set_mask(ofproto->dpif,
499                                ((1u << DPIF_UC_MISS) |
500                                 (1u << DPIF_UC_ACTION)));
501     if (error) {
502         VLOG_ERR("failed to listen on datapath %s: %s", name, strerror(error));
503         dpif_close(ofproto->dpif);
504         return error;
505     }
506
507     ofproto->netflow = NULL;
508     ofproto->sflow = NULL;
509     ofproto->stp = NULL;
510     hmap_init(&ofproto->bundles);
511     ofproto->ml = mac_learning_create();
512     for (i = 0; i < MAX_MIRRORS; i++) {
513         ofproto->mirrors[i] = NULL;
514     }
515     ofproto->has_bonded_bundles = false;
516
517     timer_set_duration(&ofproto->next_expiration, 1000);
518
519     hmap_init(&ofproto->facets);
520
521     for (i = 0; i < N_TABLES; i++) {
522         struct table_dpif *table = &ofproto->tables[i];
523
524         table->catchall_table = NULL;
525         table->other_table = NULL;
526         table->basis = random_uint32();
527     }
528     ofproto->need_revalidate = false;
529     tag_set_init(&ofproto->revalidate_set);
530
531     list_init(&ofproto->completions);
532
533     ofproto_dpif_unixctl_init();
534
535     ofproto->has_bundle_action = false;
536
537     *n_tablesp = N_TABLES;
538     return 0;
539 }
540
541 static void
542 complete_operations(struct ofproto_dpif *ofproto)
543 {
544     struct dpif_completion *c, *next;
545
546     LIST_FOR_EACH_SAFE (c, next, list_node, &ofproto->completions) {
547         ofoperation_complete(c->op, 0);
548         list_remove(&c->list_node);
549         free(c);
550     }
551 }
552
553 static void
554 destruct(struct ofproto *ofproto_)
555 {
556     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
557     struct rule_dpif *rule, *next_rule;
558     struct classifier *table;
559     int i;
560
561     complete_operations(ofproto);
562
563     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
564         struct cls_cursor cursor;
565
566         cls_cursor_init(&cursor, table, NULL);
567         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
568             ofproto_rule_destroy(&rule->up);
569         }
570     }
571
572     for (i = 0; i < MAX_MIRRORS; i++) {
573         mirror_destroy(ofproto->mirrors[i]);
574     }
575
576     netflow_destroy(ofproto->netflow);
577     dpif_sflow_destroy(ofproto->sflow);
578     hmap_destroy(&ofproto->bundles);
579     mac_learning_destroy(ofproto->ml);
580
581     hmap_destroy(&ofproto->facets);
582
583     dpif_close(ofproto->dpif);
584 }
585
586 static int
587 run(struct ofproto *ofproto_)
588 {
589     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
590     struct dpif_upcall misses[FLOW_MISS_MAX_BATCH];
591     struct ofport_dpif *ofport;
592     struct ofbundle *bundle;
593     size_t n_misses;
594     int i;
595
596     if (!clogged) {
597         complete_operations(ofproto);
598     }
599     dpif_run(ofproto->dpif);
600
601     n_misses = 0;
602     for (i = 0; i < FLOW_MISS_MAX_BATCH; i++) {
603         struct dpif_upcall *upcall = &misses[n_misses];
604         int error;
605
606         error = dpif_recv(ofproto->dpif, upcall);
607         if (error) {
608             if (error == ENODEV && n_misses == 0) {
609                 return error;
610             }
611             break;
612         }
613
614         if (upcall->type == DPIF_UC_MISS) {
615             /* Handle it later. */
616             n_misses++;
617         } else {
618             handle_upcall(ofproto, upcall);
619         }
620     }
621
622     handle_miss_upcalls(ofproto, misses, n_misses);
623
624     if (timer_expired(&ofproto->next_expiration)) {
625         int delay = expire(ofproto);
626         timer_set_duration(&ofproto->next_expiration, delay);
627     }
628
629     if (ofproto->netflow) {
630         netflow_run(ofproto->netflow);
631     }
632     if (ofproto->sflow) {
633         dpif_sflow_run(ofproto->sflow);
634     }
635
636     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
637         port_run(ofport);
638     }
639     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
640         bundle_run(bundle);
641     }
642
643     stp_run(ofproto);
644     mac_learning_run(ofproto->ml, &ofproto->revalidate_set);
645
646     /* Now revalidate if there's anything to do. */
647     if (ofproto->need_revalidate
648         || !tag_set_is_empty(&ofproto->revalidate_set)) {
649         struct tag_set revalidate_set = ofproto->revalidate_set;
650         bool revalidate_all = ofproto->need_revalidate;
651         struct facet *facet, *next;
652
653         /* Clear the revalidation flags. */
654         tag_set_init(&ofproto->revalidate_set);
655         ofproto->need_revalidate = false;
656
657         HMAP_FOR_EACH_SAFE (facet, next, hmap_node, &ofproto->facets) {
658             if (revalidate_all
659                 || tag_set_intersects(&revalidate_set, facet->tags)) {
660                 facet_revalidate(ofproto, facet);
661             }
662         }
663     }
664
665     return 0;
666 }
667
668 static void
669 wait(struct ofproto *ofproto_)
670 {
671     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
672     struct ofport_dpif *ofport;
673     struct ofbundle *bundle;
674
675     if (!clogged && !list_is_empty(&ofproto->completions)) {
676         poll_immediate_wake();
677     }
678
679     dpif_wait(ofproto->dpif);
680     dpif_recv_wait(ofproto->dpif);
681     if (ofproto->sflow) {
682         dpif_sflow_wait(ofproto->sflow);
683     }
684     if (!tag_set_is_empty(&ofproto->revalidate_set)) {
685         poll_immediate_wake();
686     }
687     HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
688         port_wait(ofport);
689     }
690     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
691         bundle_wait(bundle);
692     }
693     mac_learning_wait(ofproto->ml);
694     stp_wait(ofproto);
695     if (ofproto->need_revalidate) {
696         /* Shouldn't happen, but if it does just go around again. */
697         VLOG_DBG_RL(&rl, "need revalidate in ofproto_wait_cb()");
698         poll_immediate_wake();
699     } else {
700         timer_wait(&ofproto->next_expiration);
701     }
702 }
703
704 static void
705 flush(struct ofproto *ofproto_)
706 {
707     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
708     struct facet *facet, *next_facet;
709
710     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
711         /* Mark the facet as not installed so that facet_remove() doesn't
712          * bother trying to uninstall it.  There is no point in uninstalling it
713          * individually since we are about to blow away all the facets with
714          * dpif_flow_flush(). */
715         facet->installed = false;
716         facet->dp_packet_count = 0;
717         facet->dp_byte_count = 0;
718         facet_remove(ofproto, facet);
719     }
720     dpif_flow_flush(ofproto->dpif);
721 }
722
723 static void
724 get_features(struct ofproto *ofproto_ OVS_UNUSED,
725              bool *arp_match_ip, uint32_t *actions)
726 {
727     *arp_match_ip = true;
728     *actions = ((1u << OFPAT_OUTPUT) |
729                 (1u << OFPAT_SET_VLAN_VID) |
730                 (1u << OFPAT_SET_VLAN_PCP) |
731                 (1u << OFPAT_STRIP_VLAN) |
732                 (1u << OFPAT_SET_DL_SRC) |
733                 (1u << OFPAT_SET_DL_DST) |
734                 (1u << OFPAT_SET_NW_SRC) |
735                 (1u << OFPAT_SET_NW_DST) |
736                 (1u << OFPAT_SET_NW_TOS) |
737                 (1u << OFPAT_SET_TP_SRC) |
738                 (1u << OFPAT_SET_TP_DST) |
739                 (1u << OFPAT_ENQUEUE));
740 }
741
742 static void
743 get_tables(struct ofproto *ofproto_, struct ofp_table_stats *ots)
744 {
745     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
746     struct dpif_dp_stats s;
747
748     strcpy(ots->name, "classifier");
749
750     dpif_get_dp_stats(ofproto->dpif, &s);
751     put_32aligned_be64(&ots->lookup_count, htonll(s.n_hit + s.n_missed));
752     put_32aligned_be64(&ots->matched_count,
753                        htonll(s.n_hit + ofproto->n_matches));
754 }
755
756 static int
757 set_netflow(struct ofproto *ofproto_,
758             const struct netflow_options *netflow_options)
759 {
760     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
761
762     if (netflow_options) {
763         if (!ofproto->netflow) {
764             ofproto->netflow = netflow_create();
765         }
766         return netflow_set_options(ofproto->netflow, netflow_options);
767     } else {
768         netflow_destroy(ofproto->netflow);
769         ofproto->netflow = NULL;
770         return 0;
771     }
772 }
773
774 static struct ofport *
775 port_alloc(void)
776 {
777     struct ofport_dpif *port = xmalloc(sizeof *port);
778     return &port->up;
779 }
780
781 static void
782 port_dealloc(struct ofport *port_)
783 {
784     struct ofport_dpif *port = ofport_dpif_cast(port_);
785     free(port);
786 }
787
788 static int
789 port_construct(struct ofport *port_)
790 {
791     struct ofport_dpif *port = ofport_dpif_cast(port_);
792     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
793
794     ofproto->need_revalidate = true;
795     port->odp_port = ofp_port_to_odp_port(port->up.ofp_port);
796     port->bundle = NULL;
797     port->cfm = NULL;
798     port->tag = tag_create_random();
799     port->may_enable = true;
800     port->stp_port = NULL;
801     port->stp_state = STP_DISABLED;
802
803     if (ofproto->sflow) {
804         dpif_sflow_add_port(ofproto->sflow, port->odp_port,
805                             netdev_get_name(port->up.netdev));
806     }
807
808     return 0;
809 }
810
811 static void
812 port_destruct(struct ofport *port_)
813 {
814     struct ofport_dpif *port = ofport_dpif_cast(port_);
815     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
816
817     ofproto->need_revalidate = true;
818     bundle_remove(port_);
819     set_cfm(port_, NULL);
820     if (ofproto->sflow) {
821         dpif_sflow_del_port(ofproto->sflow, port->odp_port);
822     }
823 }
824
825 static void
826 port_modified(struct ofport *port_)
827 {
828     struct ofport_dpif *port = ofport_dpif_cast(port_);
829
830     if (port->bundle && port->bundle->bond) {
831         bond_slave_set_netdev(port->bundle->bond, port, port->up.netdev);
832     }
833 }
834
835 static void
836 port_reconfigured(struct ofport *port_, ovs_be32 old_config)
837 {
838     struct ofport_dpif *port = ofport_dpif_cast(port_);
839     struct ofproto_dpif *ofproto = ofproto_dpif_cast(port->up.ofproto);
840     ovs_be32 changed = old_config ^ port->up.opp.config;
841
842     if (changed & htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
843                         OFPPC_NO_FWD | OFPPC_NO_FLOOD)) {
844         ofproto->need_revalidate = true;
845
846         if (changed & htonl(OFPPC_NO_FLOOD) && port->bundle) {
847             bundle_update(port->bundle);
848         }
849     }
850 }
851
852 static int
853 set_sflow(struct ofproto *ofproto_,
854           const struct ofproto_sflow_options *sflow_options)
855 {
856     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
857     struct dpif_sflow *ds = ofproto->sflow;
858
859     if (sflow_options) {
860         if (!ds) {
861             struct ofport_dpif *ofport;
862
863             ds = ofproto->sflow = dpif_sflow_create(ofproto->dpif);
864             HMAP_FOR_EACH (ofport, up.hmap_node, &ofproto->up.ports) {
865                 dpif_sflow_add_port(ds, ofport->odp_port,
866                                     netdev_get_name(ofport->up.netdev));
867             }
868             ofproto->need_revalidate = true;
869         }
870         dpif_sflow_set_options(ds, sflow_options);
871     } else {
872         if (ds) {
873             dpif_sflow_destroy(ds);
874             ofproto->need_revalidate = true;
875             ofproto->sflow = NULL;
876         }
877     }
878     return 0;
879 }
880
881 static int
882 set_cfm(struct ofport *ofport_, const struct cfm_settings *s)
883 {
884     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
885     int error;
886
887     if (!s) {
888         error = 0;
889     } else {
890         if (!ofport->cfm) {
891             struct ofproto_dpif *ofproto;
892
893             ofproto = ofproto_dpif_cast(ofport->up.ofproto);
894             ofproto->need_revalidate = true;
895             ofport->cfm = cfm_create(netdev_get_name(ofport->up.netdev));
896         }
897
898         if (cfm_configure(ofport->cfm, s)) {
899             return 0;
900         }
901
902         error = EINVAL;
903     }
904     cfm_destroy(ofport->cfm);
905     ofport->cfm = NULL;
906     return error;
907 }
908
909 static int
910 get_cfm_fault(const struct ofport *ofport_)
911 {
912     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
913
914     return ofport->cfm ? cfm_get_fault(ofport->cfm) : -1;
915 }
916
917 static int
918 get_cfm_remote_mpids(const struct ofport *ofport_, const uint64_t **rmps,
919                      size_t *n_rmps)
920 {
921     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
922
923     if (ofport->cfm) {
924         cfm_get_remote_mpids(ofport->cfm, rmps, n_rmps);
925         return 0;
926     } else {
927         return -1;
928     }
929 }
930 \f
931 /* Spanning Tree. */
932
933 static void
934 send_bpdu_cb(struct ofpbuf *pkt, int port_num, void *ofproto_)
935 {
936     struct ofproto_dpif *ofproto = ofproto_;
937     struct stp_port *sp = stp_get_port(ofproto->stp, port_num);
938     struct ofport_dpif *ofport;
939
940     ofport = stp_port_get_aux(sp);
941     if (!ofport) {
942         VLOG_WARN_RL(&rl, "%s: cannot send BPDU on unknown port %d",
943                      ofproto->up.name, port_num);
944     } else {
945         struct eth_header *eth = pkt->l2;
946
947         netdev_get_etheraddr(ofport->up.netdev, eth->eth_src);
948         if (eth_addr_is_zero(eth->eth_src)) {
949             VLOG_WARN_RL(&rl, "%s: cannot send BPDU on port %d "
950                          "with unknown MAC", ofproto->up.name, port_num);
951         } else {
952             int error = netdev_send(ofport->up.netdev, pkt);
953             if (error) {
954                 VLOG_WARN_RL(&rl, "%s: sending BPDU on port %s failed (%s)",
955                              ofproto->up.name,
956                              netdev_get_name(ofport->up.netdev),
957                              strerror(error));
958             }
959         }
960     }
961     ofpbuf_delete(pkt);
962 }
963
964 /* Configures STP on 'ofproto_' using the settings defined in 's'. */
965 static int
966 set_stp(struct ofproto *ofproto_, const struct ofproto_stp_settings *s)
967 {
968     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
969
970     /* Only revalidate flows if the configuration changed. */
971     if (!s != !ofproto->stp) {
972         ofproto->need_revalidate = true;
973     }
974
975     if (s) {
976         if (!ofproto->stp) {
977             ofproto->stp = stp_create(ofproto_->name, s->system_id,
978                                       send_bpdu_cb, ofproto);
979             ofproto->stp_last_tick = time_msec();
980         }
981
982         stp_set_bridge_id(ofproto->stp, s->system_id);
983         stp_set_bridge_priority(ofproto->stp, s->priority);
984         stp_set_hello_time(ofproto->stp, s->hello_time);
985         stp_set_max_age(ofproto->stp, s->max_age);
986         stp_set_forward_delay(ofproto->stp, s->fwd_delay);
987     }  else {
988         stp_destroy(ofproto->stp);
989         ofproto->stp = NULL;
990     }
991
992     return 0;
993 }
994
995 static int
996 get_stp_status(struct ofproto *ofproto_, struct ofproto_stp_status *s)
997 {
998     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
999
1000     if (ofproto->stp) {
1001         s->enabled = true;
1002         s->bridge_id = stp_get_bridge_id(ofproto->stp);
1003         s->designated_root = stp_get_designated_root(ofproto->stp);
1004         s->root_path_cost = stp_get_root_path_cost(ofproto->stp);
1005     } else {
1006         s->enabled = false;
1007     }
1008
1009     return 0;
1010 }
1011
1012 static void
1013 update_stp_port_state(struct ofport_dpif *ofport)
1014 {
1015     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1016     enum stp_state state;
1017
1018     /* Figure out new state. */
1019     state = ofport->stp_port ? stp_port_get_state(ofport->stp_port)
1020                              : STP_DISABLED;
1021
1022     /* Update state. */
1023     if (ofport->stp_state != state) {
1024         ovs_be32 of_state;
1025         bool fwd_change;
1026
1027         VLOG_DBG_RL(&rl, "port %s: STP state changed from %s to %s",
1028                     netdev_get_name(ofport->up.netdev),
1029                     stp_state_name(ofport->stp_state),
1030                     stp_state_name(state));
1031         if (stp_learn_in_state(ofport->stp_state)
1032                 != stp_learn_in_state(state)) {
1033             /* xxx Learning action flows should also be flushed. */
1034             mac_learning_flush(ofproto->ml);
1035         }
1036         fwd_change = stp_forward_in_state(ofport->stp_state)
1037                         != stp_forward_in_state(state);
1038
1039         ofproto->need_revalidate = true;
1040         ofport->stp_state = state;
1041         ofport->stp_state_entered = time_msec();
1042
1043         if (fwd_change) {
1044             bundle_update(ofport->bundle);
1045         }
1046
1047         /* Update the STP state bits in the OpenFlow port description. */
1048         of_state = (ofport->up.opp.state & htonl(~OFPPS_STP_MASK))
1049                          | htonl(state == STP_LISTENING ? OFPPS_STP_LISTEN
1050                                : state == STP_LEARNING ? OFPPS_STP_LEARN
1051                                : state == STP_FORWARDING ? OFPPS_STP_FORWARD
1052                                : state == STP_BLOCKING ?  OFPPS_STP_BLOCK
1053                                : 0);
1054         ofproto_port_set_state(&ofport->up, of_state);
1055     }
1056 }
1057
1058 /* Configures STP on 'ofport_' using the settings defined in 's'.  The
1059  * caller is responsible for assigning STP port numbers and ensuring
1060  * there are no duplicates. */
1061 static int
1062 set_stp_port(struct ofport *ofport_,
1063              const struct ofproto_port_stp_settings *s)
1064 {
1065     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1066     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1067     struct stp_port *sp = ofport->stp_port;
1068
1069     if (!s || !s->enable) {
1070         if (sp) {
1071             ofport->stp_port = NULL;
1072             stp_port_disable(sp);
1073         }
1074         return 0;
1075     } else if (sp && stp_port_no(sp) != s->port_num
1076             && ofport == stp_port_get_aux(sp)) {
1077         /* The port-id changed, so disable the old one if it's not
1078          * already in use by another port. */
1079         stp_port_disable(sp);
1080     }
1081
1082     sp = ofport->stp_port = stp_get_port(ofproto->stp, s->port_num);
1083     stp_port_enable(sp);
1084
1085     stp_port_set_aux(sp, ofport);
1086     stp_port_set_priority(sp, s->priority);
1087     stp_port_set_path_cost(sp, s->path_cost);
1088
1089     update_stp_port_state(ofport);
1090
1091     return 0;
1092 }
1093
1094 static int
1095 get_stp_port_status(struct ofport *ofport_,
1096                     struct ofproto_port_stp_status *s)
1097 {
1098     struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
1099     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1100     struct stp_port *sp = ofport->stp_port;
1101
1102     if (!ofproto->stp || !sp) {
1103         s->enabled = false;
1104         return 0;
1105     }
1106
1107     s->enabled = true;
1108     s->port_id = stp_port_get_id(sp);
1109     s->state = stp_port_get_state(sp);
1110     s->sec_in_state = (time_msec() - ofport->stp_state_entered) / 1000;
1111     s->role = stp_port_get_role(sp);
1112
1113     return 0;
1114 }
1115
1116 static void
1117 stp_run(struct ofproto_dpif *ofproto)
1118 {
1119     if (ofproto->stp) {
1120         long long int now = time_msec();
1121         long long int elapsed = now - ofproto->stp_last_tick;
1122         struct stp_port *sp;
1123
1124         if (elapsed > 0) {
1125             stp_tick(ofproto->stp, MIN(INT_MAX, elapsed));
1126             ofproto->stp_last_tick = now;
1127         }
1128         while (stp_get_changed_port(ofproto->stp, &sp)) {
1129             struct ofport_dpif *ofport = stp_port_get_aux(sp);
1130
1131             if (ofport) {
1132                 update_stp_port_state(ofport);
1133             }
1134         }
1135     }
1136 }
1137
1138 static void
1139 stp_wait(struct ofproto_dpif *ofproto)
1140 {
1141     if (ofproto->stp) {
1142         poll_timer_wait(1000);
1143     }
1144 }
1145
1146 /* Returns true if STP should process 'flow'. */
1147 static bool
1148 stp_should_process_flow(const struct flow *flow)
1149 {
1150     return eth_addr_equals(flow->dl_dst, eth_addr_stp);
1151 }
1152
1153 static void
1154 stp_process_packet(const struct ofport_dpif *ofport,
1155                    const struct ofpbuf *packet)
1156 {
1157     struct ofpbuf payload = *packet;
1158     struct eth_header *eth = payload.data;
1159     struct stp_port *sp = ofport->stp_port;
1160
1161     /* Sink packets on ports that have STP disabled when the bridge has
1162      * STP enabled. */
1163     if (!sp || stp_port_get_state(sp) == STP_DISABLED) {
1164         return;
1165     }
1166
1167     /* Trim off padding on payload. */
1168     if (payload.size > ntohs(eth->eth_type) + ETH_HEADER_LEN) {
1169         payload.size = ntohs(eth->eth_type) + ETH_HEADER_LEN;
1170     }
1171
1172     if (ofpbuf_try_pull(&payload, ETH_HEADER_LEN + LLC_HEADER_LEN)) {
1173         stp_received_bpdu(sp, payload.data, payload.size);
1174     }
1175 }
1176 \f
1177 /* Bundles. */
1178
1179 /* Expires all MAC learning entries associated with 'port' and forces ofproto
1180  * to revalidate every flow. */
1181 static void
1182 bundle_flush_macs(struct ofbundle *bundle)
1183 {
1184     struct ofproto_dpif *ofproto = bundle->ofproto;
1185     struct mac_learning *ml = ofproto->ml;
1186     struct mac_entry *mac, *next_mac;
1187
1188     ofproto->need_revalidate = true;
1189     LIST_FOR_EACH_SAFE (mac, next_mac, lru_node, &ml->lrus) {
1190         if (mac->port.p == bundle) {
1191             mac_learning_expire(ml, mac);
1192         }
1193     }
1194 }
1195
1196 static struct ofbundle *
1197 bundle_lookup(const struct ofproto_dpif *ofproto, void *aux)
1198 {
1199     struct ofbundle *bundle;
1200
1201     HMAP_FOR_EACH_IN_BUCKET (bundle, hmap_node, hash_pointer(aux, 0),
1202                              &ofproto->bundles) {
1203         if (bundle->aux == aux) {
1204             return bundle;
1205         }
1206     }
1207     return NULL;
1208 }
1209
1210 /* Looks up each of the 'n_auxes' pointers in 'auxes' as bundles and adds the
1211  * ones that are found to 'bundles'. */
1212 static void
1213 bundle_lookup_multiple(struct ofproto_dpif *ofproto,
1214                        void **auxes, size_t n_auxes,
1215                        struct hmapx *bundles)
1216 {
1217     size_t i;
1218
1219     hmapx_init(bundles);
1220     for (i = 0; i < n_auxes; i++) {
1221         struct ofbundle *bundle = bundle_lookup(ofproto, auxes[i]);
1222         if (bundle) {
1223             hmapx_add(bundles, bundle);
1224         }
1225     }
1226 }
1227
1228 static void
1229 bundle_update(struct ofbundle *bundle)
1230 {
1231     struct ofport_dpif *port;
1232
1233     bundle->floodable = true;
1234     LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1235         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)
1236                     || !stp_forward_in_state(port->stp_state)) {
1237             bundle->floodable = false;
1238             break;
1239         }
1240     }
1241 }
1242
1243 static void
1244 bundle_del_port(struct ofport_dpif *port)
1245 {
1246     struct ofbundle *bundle = port->bundle;
1247
1248     bundle->ofproto->need_revalidate = true;
1249
1250     list_remove(&port->bundle_node);
1251     port->bundle = NULL;
1252
1253     if (bundle->lacp) {
1254         lacp_slave_unregister(bundle->lacp, port);
1255     }
1256     if (bundle->bond) {
1257         bond_slave_unregister(bundle->bond, port);
1258     }
1259
1260     bundle_update(bundle);
1261 }
1262
1263 static bool
1264 bundle_add_port(struct ofbundle *bundle, uint32_t ofp_port,
1265                 struct lacp_slave_settings *lacp,
1266                 uint32_t bond_stable_id)
1267 {
1268     struct ofport_dpif *port;
1269
1270     port = get_ofp_port(bundle->ofproto, ofp_port);
1271     if (!port) {
1272         return false;
1273     }
1274
1275     if (port->bundle != bundle) {
1276         bundle->ofproto->need_revalidate = true;
1277         if (port->bundle) {
1278             bundle_del_port(port);
1279         }
1280
1281         port->bundle = bundle;
1282         list_push_back(&bundle->ports, &port->bundle_node);
1283         if (port->up.opp.config & htonl(OFPPC_NO_FLOOD)
1284                     || !stp_forward_in_state(port->stp_state)) {
1285             bundle->floodable = false;
1286         }
1287     }
1288     if (lacp) {
1289         port->bundle->ofproto->need_revalidate = true;
1290         lacp_slave_register(bundle->lacp, port, lacp);
1291     }
1292
1293     port->bond_stable_id = bond_stable_id;
1294
1295     return true;
1296 }
1297
1298 static void
1299 bundle_destroy(struct ofbundle *bundle)
1300 {
1301     struct ofproto_dpif *ofproto;
1302     struct ofport_dpif *port, *next_port;
1303     int i;
1304
1305     if (!bundle) {
1306         return;
1307     }
1308
1309     ofproto = bundle->ofproto;
1310     for (i = 0; i < MAX_MIRRORS; i++) {
1311         struct ofmirror *m = ofproto->mirrors[i];
1312         if (m) {
1313             if (m->out == bundle) {
1314                 mirror_destroy(m);
1315             } else if (hmapx_find_and_delete(&m->srcs, bundle)
1316                        || hmapx_find_and_delete(&m->dsts, bundle)) {
1317                 ofproto->need_revalidate = true;
1318             }
1319         }
1320     }
1321
1322     LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1323         bundle_del_port(port);
1324     }
1325
1326     bundle_flush_macs(bundle);
1327     hmap_remove(&ofproto->bundles, &bundle->hmap_node);
1328     free(bundle->name);
1329     free(bundle->trunks);
1330     lacp_destroy(bundle->lacp);
1331     bond_destroy(bundle->bond);
1332     free(bundle);
1333 }
1334
1335 static int
1336 bundle_set(struct ofproto *ofproto_, void *aux,
1337            const struct ofproto_bundle_settings *s)
1338 {
1339     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1340     bool need_flush = false;
1341     struct ofport_dpif *port;
1342     struct ofbundle *bundle;
1343     unsigned long *trunks;
1344     int vlan;
1345     size_t i;
1346     bool ok;
1347
1348     if (!s) {
1349         bundle_destroy(bundle_lookup(ofproto, aux));
1350         return 0;
1351     }
1352
1353     assert(s->n_slaves == 1 || s->bond != NULL);
1354     assert((s->lacp != NULL) == (s->lacp_slaves != NULL));
1355
1356     bundle = bundle_lookup(ofproto, aux);
1357     if (!bundle) {
1358         bundle = xmalloc(sizeof *bundle);
1359
1360         bundle->ofproto = ofproto;
1361         hmap_insert(&ofproto->bundles, &bundle->hmap_node,
1362                     hash_pointer(aux, 0));
1363         bundle->aux = aux;
1364         bundle->name = NULL;
1365
1366         list_init(&bundle->ports);
1367         bundle->vlan_mode = PORT_VLAN_TRUNK;
1368         bundle->vlan = -1;
1369         bundle->trunks = NULL;
1370         bundle->lacp = NULL;
1371         bundle->bond = NULL;
1372
1373         bundle->floodable = true;
1374
1375         bundle->src_mirrors = 0;
1376         bundle->dst_mirrors = 0;
1377         bundle->mirror_out = 0;
1378     }
1379
1380     if (!bundle->name || strcmp(s->name, bundle->name)) {
1381         free(bundle->name);
1382         bundle->name = xstrdup(s->name);
1383     }
1384
1385     /* LACP. */
1386     if (s->lacp) {
1387         if (!bundle->lacp) {
1388             ofproto->need_revalidate = true;
1389             bundle->lacp = lacp_create();
1390         }
1391         lacp_configure(bundle->lacp, s->lacp);
1392     } else {
1393         lacp_destroy(bundle->lacp);
1394         bundle->lacp = NULL;
1395     }
1396
1397     /* Update set of ports. */
1398     ok = true;
1399     for (i = 0; i < s->n_slaves; i++) {
1400         if (!bundle_add_port(bundle, s->slaves[i],
1401                              s->lacp ? &s->lacp_slaves[i] : NULL,
1402                              s->bond_stable_ids ? s->bond_stable_ids[i] : 0)) {
1403             ok = false;
1404         }
1405     }
1406     if (!ok || list_size(&bundle->ports) != s->n_slaves) {
1407         struct ofport_dpif *next_port;
1408
1409         LIST_FOR_EACH_SAFE (port, next_port, bundle_node, &bundle->ports) {
1410             for (i = 0; i < s->n_slaves; i++) {
1411                 if (s->slaves[i] == port->up.ofp_port) {
1412                     goto found;
1413                 }
1414             }
1415
1416             bundle_del_port(port);
1417         found: ;
1418         }
1419     }
1420     assert(list_size(&bundle->ports) <= s->n_slaves);
1421
1422     if (list_is_empty(&bundle->ports)) {
1423         bundle_destroy(bundle);
1424         return EINVAL;
1425     }
1426
1427     /* Set VLAN tagging mode */
1428     if (s->vlan_mode != bundle->vlan_mode) {
1429         bundle->vlan_mode = s->vlan_mode;
1430         need_flush = true;
1431     }
1432
1433     /* Set VLAN tag. */
1434     vlan = (s->vlan_mode == PORT_VLAN_TRUNK ? -1
1435             : s->vlan >= 0 && s->vlan <= 4095 ? s->vlan
1436             : 0);
1437     if (vlan != bundle->vlan) {
1438         bundle->vlan = vlan;
1439         need_flush = true;
1440     }
1441
1442     /* Get trunked VLANs. */
1443     switch (s->vlan_mode) {
1444     case PORT_VLAN_ACCESS:
1445         trunks = NULL;
1446         break;
1447
1448     case PORT_VLAN_TRUNK:
1449         trunks = (unsigned long *) s->trunks;
1450         break;
1451
1452     case PORT_VLAN_NATIVE_UNTAGGED:
1453     case PORT_VLAN_NATIVE_TAGGED:
1454         if (vlan != 0 && (!s->trunks
1455                           || !bitmap_is_set(s->trunks, vlan)
1456                           || bitmap_is_set(s->trunks, 0))) {
1457             /* Force trunking the native VLAN and prohibit trunking VLAN 0. */
1458             if (s->trunks) {
1459                 trunks = bitmap_clone(s->trunks, 4096);
1460             } else {
1461                 trunks = bitmap_allocate1(4096);
1462             }
1463             bitmap_set1(trunks, vlan);
1464             bitmap_set0(trunks, 0);
1465         } else {
1466             trunks = (unsigned long *) s->trunks;
1467         }
1468         break;
1469
1470     default:
1471         NOT_REACHED();
1472     }
1473     if (!vlan_bitmap_equal(trunks, bundle->trunks)) {
1474         free(bundle->trunks);
1475         if (trunks == s->trunks) {
1476             bundle->trunks = vlan_bitmap_clone(trunks);
1477         } else {
1478             bundle->trunks = trunks;
1479             trunks = NULL;
1480         }
1481         need_flush = true;
1482     }
1483     if (trunks != s->trunks) {
1484         free(trunks);
1485     }
1486
1487     /* Bonding. */
1488     if (!list_is_short(&bundle->ports)) {
1489         bundle->ofproto->has_bonded_bundles = true;
1490         if (bundle->bond) {
1491             if (bond_reconfigure(bundle->bond, s->bond)) {
1492                 ofproto->need_revalidate = true;
1493             }
1494         } else {
1495             bundle->bond = bond_create(s->bond);
1496             ofproto->need_revalidate = true;
1497         }
1498
1499         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1500             bond_slave_register(bundle->bond, port, port->bond_stable_id,
1501                                 port->up.netdev);
1502         }
1503     } else {
1504         bond_destroy(bundle->bond);
1505         bundle->bond = NULL;
1506     }
1507
1508     /* If we changed something that would affect MAC learning, un-learn
1509      * everything on this port and force flow revalidation. */
1510     if (need_flush) {
1511         bundle_flush_macs(bundle);
1512     }
1513
1514     return 0;
1515 }
1516
1517 static void
1518 bundle_remove(struct ofport *port_)
1519 {
1520     struct ofport_dpif *port = ofport_dpif_cast(port_);
1521     struct ofbundle *bundle = port->bundle;
1522
1523     if (bundle) {
1524         bundle_del_port(port);
1525         if (list_is_empty(&bundle->ports)) {
1526             bundle_destroy(bundle);
1527         } else if (list_is_short(&bundle->ports)) {
1528             bond_destroy(bundle->bond);
1529             bundle->bond = NULL;
1530         }
1531     }
1532 }
1533
1534 static void
1535 send_pdu_cb(void *port_, const void *pdu, size_t pdu_size)
1536 {
1537     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 10);
1538     struct ofport_dpif *port = port_;
1539     uint8_t ea[ETH_ADDR_LEN];
1540     int error;
1541
1542     error = netdev_get_etheraddr(port->up.netdev, ea);
1543     if (!error) {
1544         struct ofpbuf packet;
1545         void *packet_pdu;
1546
1547         ofpbuf_init(&packet, 0);
1548         packet_pdu = eth_compose(&packet, eth_addr_lacp, ea, ETH_TYPE_LACP,
1549                                  pdu_size);
1550         memcpy(packet_pdu, pdu, pdu_size);
1551
1552         error = netdev_send(port->up.netdev, &packet);
1553         if (error) {
1554             VLOG_WARN_RL(&rl, "port %s: sending LACP PDU on iface %s failed "
1555                          "(%s)", port->bundle->name,
1556                          netdev_get_name(port->up.netdev), strerror(error));
1557         }
1558         ofpbuf_uninit(&packet);
1559     } else {
1560         VLOG_ERR_RL(&rl, "port %s: cannot obtain Ethernet address of iface "
1561                     "%s (%s)", port->bundle->name,
1562                     netdev_get_name(port->up.netdev), strerror(error));
1563     }
1564 }
1565
1566 static void
1567 bundle_send_learning_packets(struct ofbundle *bundle)
1568 {
1569     struct ofproto_dpif *ofproto = bundle->ofproto;
1570     int error, n_packets, n_errors;
1571     struct mac_entry *e;
1572
1573     error = n_packets = n_errors = 0;
1574     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
1575         if (e->port.p != bundle) {
1576             int ret = bond_send_learning_packet(bundle->bond, e->mac, e->vlan);
1577             if (ret) {
1578                 error = ret;
1579                 n_errors++;
1580             }
1581             n_packets++;
1582         }
1583     }
1584
1585     if (n_errors) {
1586         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
1587         VLOG_WARN_RL(&rl, "bond %s: %d errors sending %d gratuitous learning "
1588                      "packets, last error was: %s",
1589                      bundle->name, n_errors, n_packets, strerror(error));
1590     } else {
1591         VLOG_DBG("bond %s: sent %d gratuitous learning packets",
1592                  bundle->name, n_packets);
1593     }
1594 }
1595
1596 static void
1597 bundle_run(struct ofbundle *bundle)
1598 {
1599     if (bundle->lacp) {
1600         lacp_run(bundle->lacp, send_pdu_cb);
1601     }
1602     if (bundle->bond) {
1603         struct ofport_dpif *port;
1604
1605         LIST_FOR_EACH (port, bundle_node, &bundle->ports) {
1606             bond_slave_set_may_enable(bundle->bond, port, port->may_enable);
1607         }
1608
1609         bond_run(bundle->bond, &bundle->ofproto->revalidate_set,
1610                  lacp_negotiated(bundle->lacp));
1611         if (bond_should_send_learning_packets(bundle->bond)) {
1612             bundle_send_learning_packets(bundle);
1613         }
1614     }
1615 }
1616
1617 static void
1618 bundle_wait(struct ofbundle *bundle)
1619 {
1620     if (bundle->lacp) {
1621         lacp_wait(bundle->lacp);
1622     }
1623     if (bundle->bond) {
1624         bond_wait(bundle->bond);
1625     }
1626 }
1627 \f
1628 /* Mirrors. */
1629
1630 static int
1631 mirror_scan(struct ofproto_dpif *ofproto)
1632 {
1633     int idx;
1634
1635     for (idx = 0; idx < MAX_MIRRORS; idx++) {
1636         if (!ofproto->mirrors[idx]) {
1637             return idx;
1638         }
1639     }
1640     return -1;
1641 }
1642
1643 static struct ofmirror *
1644 mirror_lookup(struct ofproto_dpif *ofproto, void *aux)
1645 {
1646     int i;
1647
1648     for (i = 0; i < MAX_MIRRORS; i++) {
1649         struct ofmirror *mirror = ofproto->mirrors[i];
1650         if (mirror && mirror->aux == aux) {
1651             return mirror;
1652         }
1653     }
1654
1655     return NULL;
1656 }
1657
1658 static int
1659 mirror_set(struct ofproto *ofproto_, void *aux,
1660            const struct ofproto_mirror_settings *s)
1661 {
1662     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1663     mirror_mask_t mirror_bit;
1664     struct ofbundle *bundle;
1665     struct ofmirror *mirror;
1666     struct ofbundle *out;
1667     struct hmapx srcs;          /* Contains "struct ofbundle *"s. */
1668     struct hmapx dsts;          /* Contains "struct ofbundle *"s. */
1669     int out_vlan;
1670
1671     mirror = mirror_lookup(ofproto, aux);
1672     if (!s) {
1673         mirror_destroy(mirror);
1674         return 0;
1675     }
1676     if (!mirror) {
1677         int idx;
1678
1679         idx = mirror_scan(ofproto);
1680         if (idx < 0) {
1681             VLOG_WARN("bridge %s: maximum of %d port mirrors reached, "
1682                       "cannot create %s",
1683                       ofproto->up.name, MAX_MIRRORS, s->name);
1684             return EFBIG;
1685         }
1686
1687         mirror = ofproto->mirrors[idx] = xzalloc(sizeof *mirror);
1688         mirror->ofproto = ofproto;
1689         mirror->idx = idx;
1690         mirror->aux = aux;
1691         mirror->out_vlan = -1;
1692         mirror->name = NULL;
1693     }
1694
1695     if (!mirror->name || strcmp(s->name, mirror->name)) {
1696         free(mirror->name);
1697         mirror->name = xstrdup(s->name);
1698     }
1699
1700     /* Get the new configuration. */
1701     if (s->out_bundle) {
1702         out = bundle_lookup(ofproto, s->out_bundle);
1703         if (!out) {
1704             mirror_destroy(mirror);
1705             return EINVAL;
1706         }
1707         out_vlan = -1;
1708     } else {
1709         out = NULL;
1710         out_vlan = s->out_vlan;
1711     }
1712     bundle_lookup_multiple(ofproto, s->srcs, s->n_srcs, &srcs);
1713     bundle_lookup_multiple(ofproto, s->dsts, s->n_dsts, &dsts);
1714
1715     /* If the configuration has not changed, do nothing. */
1716     if (hmapx_equals(&srcs, &mirror->srcs)
1717         && hmapx_equals(&dsts, &mirror->dsts)
1718         && vlan_bitmap_equal(mirror->vlans, s->src_vlans)
1719         && mirror->out == out
1720         && mirror->out_vlan == out_vlan)
1721     {
1722         hmapx_destroy(&srcs);
1723         hmapx_destroy(&dsts);
1724         return 0;
1725     }
1726
1727     hmapx_swap(&srcs, &mirror->srcs);
1728     hmapx_destroy(&srcs);
1729
1730     hmapx_swap(&dsts, &mirror->dsts);
1731     hmapx_destroy(&dsts);
1732
1733     free(mirror->vlans);
1734     mirror->vlans = vlan_bitmap_clone(s->src_vlans);
1735
1736     mirror->out = out;
1737     mirror->out_vlan = out_vlan;
1738
1739     /* Update bundles. */
1740     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1741     HMAP_FOR_EACH (bundle, hmap_node, &mirror->ofproto->bundles) {
1742         if (hmapx_contains(&mirror->srcs, bundle)) {
1743             bundle->src_mirrors |= mirror_bit;
1744         } else {
1745             bundle->src_mirrors &= ~mirror_bit;
1746         }
1747
1748         if (hmapx_contains(&mirror->dsts, bundle)) {
1749             bundle->dst_mirrors |= mirror_bit;
1750         } else {
1751             bundle->dst_mirrors &= ~mirror_bit;
1752         }
1753
1754         if (mirror->out == bundle) {
1755             bundle->mirror_out |= mirror_bit;
1756         } else {
1757             bundle->mirror_out &= ~mirror_bit;
1758         }
1759     }
1760
1761     ofproto->need_revalidate = true;
1762     mac_learning_flush(ofproto->ml);
1763
1764     return 0;
1765 }
1766
1767 static void
1768 mirror_destroy(struct ofmirror *mirror)
1769 {
1770     struct ofproto_dpif *ofproto;
1771     mirror_mask_t mirror_bit;
1772     struct ofbundle *bundle;
1773
1774     if (!mirror) {
1775         return;
1776     }
1777
1778     ofproto = mirror->ofproto;
1779     ofproto->need_revalidate = true;
1780     mac_learning_flush(ofproto->ml);
1781
1782     mirror_bit = MIRROR_MASK_C(1) << mirror->idx;
1783     HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
1784         bundle->src_mirrors &= ~mirror_bit;
1785         bundle->dst_mirrors &= ~mirror_bit;
1786         bundle->mirror_out &= ~mirror_bit;
1787     }
1788
1789     hmapx_destroy(&mirror->srcs);
1790     hmapx_destroy(&mirror->dsts);
1791     free(mirror->vlans);
1792
1793     ofproto->mirrors[mirror->idx] = NULL;
1794     free(mirror->name);
1795     free(mirror);
1796 }
1797
1798 static int
1799 set_flood_vlans(struct ofproto *ofproto_, unsigned long *flood_vlans)
1800 {
1801     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1802     if (mac_learning_set_flood_vlans(ofproto->ml, flood_vlans)) {
1803         ofproto->need_revalidate = true;
1804         mac_learning_flush(ofproto->ml);
1805     }
1806     return 0;
1807 }
1808
1809 static bool
1810 is_mirror_output_bundle(const struct ofproto *ofproto_, void *aux)
1811 {
1812     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1813     struct ofbundle *bundle = bundle_lookup(ofproto, aux);
1814     return bundle && bundle->mirror_out != 0;
1815 }
1816
1817 static void
1818 forward_bpdu_changed(struct ofproto *ofproto_)
1819 {
1820     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1821     /* Revalidate cached flows whenever forward_bpdu option changes. */
1822     ofproto->need_revalidate = true;
1823 }
1824 \f
1825 /* Ports. */
1826
1827 static struct ofport_dpif *
1828 get_ofp_port(struct ofproto_dpif *ofproto, uint16_t ofp_port)
1829 {
1830     struct ofport *ofport = ofproto_get_port(&ofproto->up, ofp_port);
1831     return ofport ? ofport_dpif_cast(ofport) : NULL;
1832 }
1833
1834 static struct ofport_dpif *
1835 get_odp_port(struct ofproto_dpif *ofproto, uint32_t odp_port)
1836 {
1837     return get_ofp_port(ofproto, odp_port_to_ofp_port(odp_port));
1838 }
1839
1840 static void
1841 ofproto_port_from_dpif_port(struct ofproto_port *ofproto_port,
1842                             struct dpif_port *dpif_port)
1843 {
1844     ofproto_port->name = dpif_port->name;
1845     ofproto_port->type = dpif_port->type;
1846     ofproto_port->ofp_port = odp_port_to_ofp_port(dpif_port->port_no);
1847 }
1848
1849 static void
1850 port_run(struct ofport_dpif *ofport)
1851 {
1852     bool enable = netdev_get_carrier(ofport->up.netdev);
1853
1854     if (ofport->cfm) {
1855         cfm_run(ofport->cfm);
1856
1857         if (cfm_should_send_ccm(ofport->cfm)) {
1858             struct ofpbuf packet;
1859
1860             ofpbuf_init(&packet, 0);
1861             cfm_compose_ccm(ofport->cfm, &packet, ofport->up.opp.hw_addr);
1862             send_packet(ofproto_dpif_cast(ofport->up.ofproto),
1863                         ofport->odp_port, &packet);
1864             ofpbuf_uninit(&packet);
1865         }
1866
1867         enable = enable && !cfm_get_fault(ofport->cfm)
1868             && cfm_get_opup(ofport->cfm);
1869     }
1870
1871     if (ofport->bundle) {
1872         enable = enable && lacp_slave_may_enable(ofport->bundle->lacp, ofport);
1873     }
1874
1875     if (ofport->may_enable != enable) {
1876         struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofport->up.ofproto);
1877
1878         if (ofproto->has_bundle_action) {
1879             ofproto->need_revalidate = true;
1880         }
1881     }
1882
1883     ofport->may_enable = enable;
1884 }
1885
1886 static void
1887 port_wait(struct ofport_dpif *ofport)
1888 {
1889     if (ofport->cfm) {
1890         cfm_wait(ofport->cfm);
1891     }
1892 }
1893
1894 static int
1895 port_query_by_name(const struct ofproto *ofproto_, const char *devname,
1896                    struct ofproto_port *ofproto_port)
1897 {
1898     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1899     struct dpif_port dpif_port;
1900     int error;
1901
1902     error = dpif_port_query_by_name(ofproto->dpif, devname, &dpif_port);
1903     if (!error) {
1904         ofproto_port_from_dpif_port(ofproto_port, &dpif_port);
1905     }
1906     return error;
1907 }
1908
1909 static int
1910 port_add(struct ofproto *ofproto_, struct netdev *netdev, uint16_t *ofp_portp)
1911 {
1912     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1913     uint16_t odp_port;
1914     int error;
1915
1916     error = dpif_port_add(ofproto->dpif, netdev, &odp_port);
1917     if (!error) {
1918         *ofp_portp = odp_port_to_ofp_port(odp_port);
1919     }
1920     return error;
1921 }
1922
1923 static int
1924 port_del(struct ofproto *ofproto_, uint16_t ofp_port)
1925 {
1926     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1927     int error;
1928
1929     error = dpif_port_del(ofproto->dpif, ofp_port_to_odp_port(ofp_port));
1930     if (!error) {
1931         struct ofport_dpif *ofport = get_ofp_port(ofproto, ofp_port);
1932         if (ofport) {
1933             /* The caller is going to close ofport->up.netdev.  If this is a
1934              * bonded port, then the bond is using that netdev, so remove it
1935              * from the bond.  The client will need to reconfigure everything
1936              * after deleting ports, so then the slave will get re-added. */
1937             bundle_remove(&ofport->up);
1938         }
1939     }
1940     return error;
1941 }
1942
1943 struct port_dump_state {
1944     struct dpif_port_dump dump;
1945     bool done;
1946 };
1947
1948 static int
1949 port_dump_start(const struct ofproto *ofproto_, void **statep)
1950 {
1951     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1952     struct port_dump_state *state;
1953
1954     *statep = state = xmalloc(sizeof *state);
1955     dpif_port_dump_start(&state->dump, ofproto->dpif);
1956     state->done = false;
1957     return 0;
1958 }
1959
1960 static int
1961 port_dump_next(const struct ofproto *ofproto_ OVS_UNUSED, void *state_,
1962                struct ofproto_port *port)
1963 {
1964     struct port_dump_state *state = state_;
1965     struct dpif_port dpif_port;
1966
1967     if (dpif_port_dump_next(&state->dump, &dpif_port)) {
1968         ofproto_port_from_dpif_port(port, &dpif_port);
1969         return 0;
1970     } else {
1971         int error = dpif_port_dump_done(&state->dump);
1972         state->done = true;
1973         return error ? error : EOF;
1974     }
1975 }
1976
1977 static int
1978 port_dump_done(const struct ofproto *ofproto_ OVS_UNUSED, void *state_)
1979 {
1980     struct port_dump_state *state = state_;
1981
1982     if (!state->done) {
1983         dpif_port_dump_done(&state->dump);
1984     }
1985     free(state);
1986     return 0;
1987 }
1988
1989 static int
1990 port_poll(const struct ofproto *ofproto_, char **devnamep)
1991 {
1992     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
1993     return dpif_port_poll(ofproto->dpif, devnamep);
1994 }
1995
1996 static void
1997 port_poll_wait(const struct ofproto *ofproto_)
1998 {
1999     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
2000     dpif_port_poll_wait(ofproto->dpif);
2001 }
2002
2003 static int
2004 port_is_lacp_current(const struct ofport *ofport_)
2005 {
2006     const struct ofport_dpif *ofport = ofport_dpif_cast(ofport_);
2007     return (ofport->bundle && ofport->bundle->lacp
2008             ? lacp_slave_is_current(ofport->bundle->lacp, ofport)
2009             : -1);
2010 }
2011 \f
2012 /* Upcall handling. */
2013
2014 /* Flow miss batching.
2015  *
2016  * Some dpifs implement operations faster when you hand them off in a batch.
2017  * To allow batching, "struct flow_miss" queues the dpif-related work needed
2018  * for a given flow.  Each "struct flow_miss" corresponds to sending one or
2019  * more packets, plus possibly installing the flow in the dpif.
2020  *
2021  * So far we only batch the operations that affect flow setup time the most.
2022  * It's possible to batch more than that, but the benefit might be minimal. */
2023 struct flow_miss {
2024     struct hmap_node hmap_node;
2025     struct flow flow;
2026     const struct nlattr *key;
2027     size_t key_len;
2028     struct list packets;
2029 };
2030
2031 struct flow_miss_op {
2032     union dpif_op dpif_op;
2033     struct facet *facet;
2034 };
2035
2036 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_NO_MATCH to each
2037  * OpenFlow controller as necessary according to their individual
2038  * configurations.
2039  *
2040  * If 'clone' is true, the caller retains ownership of 'packet'.  Otherwise,
2041  * ownership is transferred to this function. */
2042 static void
2043 send_packet_in_miss(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2044                     const struct flow *flow, bool clone)
2045 {
2046     struct ofputil_packet_in pin;
2047
2048     pin.packet = packet;
2049     pin.in_port = flow->in_port;
2050     pin.reason = OFPR_NO_MATCH;
2051     pin.buffer_id = 0;          /* not yet known */
2052     pin.send_len = 0;           /* not used for flow table misses */
2053     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2054                            clone ? NULL : packet);
2055 }
2056
2057 /* Sends an OFPT_PACKET_IN message for 'packet' of type OFPR_ACTION to each
2058  * OpenFlow controller as necessary according to their individual
2059  * configurations.
2060  *
2061  * 'send_len' should be the number of bytes of 'packet' to send to the
2062  * controller, as specified in the action that caused the packet to be sent.
2063  *
2064  * If 'clone' is true, the caller retains ownership of 'upcall->packet'.
2065  * Otherwise, ownership is transferred to this function. */
2066 static void
2067 send_packet_in_action(struct ofproto_dpif *ofproto, struct ofpbuf *packet,
2068                       uint64_t userdata, const struct flow *flow, bool clone)
2069 {
2070     struct ofputil_packet_in pin;
2071     struct user_action_cookie cookie;
2072
2073     memcpy(&cookie, &userdata, sizeof(cookie));
2074
2075     pin.packet = packet;
2076     pin.in_port = flow->in_port;
2077     pin.reason = OFPR_ACTION;
2078     pin.buffer_id = 0;          /* not yet known */
2079     pin.send_len = cookie.data;
2080     connmgr_send_packet_in(ofproto->up.connmgr, &pin, flow,
2081                            clone ? NULL : packet);
2082 }
2083
2084 static bool
2085 process_special(struct ofproto_dpif *ofproto, const struct flow *flow,
2086                 const struct ofpbuf *packet)
2087 {
2088     struct ofport_dpif *ofport = get_ofp_port(ofproto, flow->in_port);
2089
2090     if (!ofport) {
2091         return false;
2092     }
2093
2094     if (ofport->cfm && cfm_should_process_flow(ofport->cfm, flow)) {
2095         if (packet) {
2096             cfm_process_heartbeat(ofport->cfm, packet);
2097         }
2098         return true;
2099     } else if (ofport->bundle && ofport->bundle->lacp
2100                && flow->dl_type == htons(ETH_TYPE_LACP)) {
2101         if (packet) {
2102             lacp_process_packet(ofport->bundle->lacp, ofport, packet);
2103         }
2104         return true;
2105     } else if (ofproto->stp && stp_should_process_flow(flow)) {
2106         if (packet) {
2107             stp_process_packet(ofport, packet);
2108         }
2109         return true;
2110     }
2111     return false;
2112 }
2113
2114 static struct flow_miss *
2115 flow_miss_create(struct hmap *todo, const struct flow *flow,
2116                  const struct nlattr *key, size_t key_len)
2117 {
2118     uint32_t hash = flow_hash(flow, 0);
2119     struct flow_miss *miss;
2120
2121     HMAP_FOR_EACH_WITH_HASH (miss, hmap_node, hash, todo) {
2122         if (flow_equal(&miss->flow, flow)) {
2123             return miss;
2124         }
2125     }
2126
2127     miss = xmalloc(sizeof *miss);
2128     hmap_insert(todo, &miss->hmap_node, hash);
2129     miss->flow = *flow;
2130     miss->key = key;
2131     miss->key_len = key_len;
2132     list_init(&miss->packets);
2133     return miss;
2134 }
2135
2136 static void
2137 handle_flow_miss(struct ofproto_dpif *ofproto, struct flow_miss *miss,
2138                  struct flow_miss_op *ops, size_t *n_ops)
2139 {
2140     const struct flow *flow = &miss->flow;
2141     struct ofpbuf *packet, *next_packet;
2142     struct facet *facet;
2143
2144     facet = facet_lookup_valid(ofproto, flow);
2145     if (!facet) {
2146         struct rule_dpif *rule;
2147
2148         rule = rule_dpif_lookup(ofproto, flow, 0);
2149         if (!rule) {
2150             /* Don't send a packet-in if OFPPC_NO_PACKET_IN asserted. */
2151             struct ofport_dpif *port = get_ofp_port(ofproto, flow->in_port);
2152             if (port) {
2153                 if (port->up.opp.config & htonl(OFPPC_NO_PACKET_IN)) {
2154                     COVERAGE_INC(ofproto_dpif_no_packet_in);
2155                     /* XXX install 'drop' flow entry */
2156                     return;
2157                 }
2158             } else {
2159                 VLOG_WARN_RL(&rl, "packet-in on unknown port %"PRIu16,
2160                              flow->in_port);
2161             }
2162
2163             LIST_FOR_EACH_SAFE (packet, next_packet, list_node,
2164                                 &miss->packets) {
2165                 list_remove(&packet->list_node);
2166                 send_packet_in_miss(ofproto, packet, flow, false);
2167             }
2168
2169             return;
2170         }
2171
2172         facet = facet_create(rule, flow);
2173     }
2174
2175     LIST_FOR_EACH_SAFE (packet, next_packet, list_node, &miss->packets) {
2176         list_remove(&packet->list_node);
2177         ofproto->n_matches++;
2178
2179         if (facet->rule->up.cr.priority == FAIL_OPEN_PRIORITY) {
2180             /*
2181              * Extra-special case for fail-open mode.
2182              *
2183              * We are in fail-open mode and the packet matched the fail-open
2184              * rule, but we are connected to a controller too.  We should send
2185              * the packet up to the controller in the hope that it will try to
2186              * set up a flow and thereby allow us to exit fail-open.
2187              *
2188              * See the top-level comment in fail-open.c for more information.
2189              */
2190             send_packet_in_miss(ofproto, packet, flow, true);
2191         }
2192
2193         if (!facet->may_install) {
2194             facet_make_actions(ofproto, facet, packet);
2195         }
2196         if (!execute_controller_action(ofproto, &facet->flow,
2197                                        facet->actions, facet->actions_len,
2198                                        packet)) {
2199             struct flow_miss_op *op = &ops[(*n_ops)++];
2200             struct dpif_execute *execute = &op->dpif_op.execute;
2201
2202             op->facet = facet;
2203             execute->type = DPIF_OP_EXECUTE;
2204             execute->key = miss->key;
2205             execute->key_len = miss->key_len;
2206             execute->actions
2207                 = (facet->may_install
2208                    ? facet->actions
2209                    : xmemdup(facet->actions, facet->actions_len));
2210             execute->actions_len = facet->actions_len;
2211             execute->packet = packet;
2212         }
2213     }
2214
2215     if (facet->may_install) {
2216         struct flow_miss_op *op = &ops[(*n_ops)++];
2217         struct dpif_flow_put *put = &op->dpif_op.flow_put;
2218
2219         op->facet = facet;
2220         put->type = DPIF_OP_FLOW_PUT;
2221         put->flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2222         put->key = miss->key;
2223         put->key_len = miss->key_len;
2224         put->actions = facet->actions;
2225         put->actions_len = facet->actions_len;
2226         put->stats = NULL;
2227     }
2228 }
2229
2230 static void
2231 handle_miss_upcalls(struct ofproto_dpif *ofproto, struct dpif_upcall *upcalls,
2232                     size_t n_upcalls)
2233 {
2234     struct dpif_upcall *upcall;
2235     struct flow_miss *miss, *next_miss;
2236     struct flow_miss_op flow_miss_ops[FLOW_MISS_MAX_BATCH * 2];
2237     union dpif_op *dpif_ops[FLOW_MISS_MAX_BATCH * 2];
2238     struct hmap todo;
2239     size_t n_ops;
2240     size_t i;
2241
2242     if (!n_upcalls) {
2243         return;
2244     }
2245
2246     /* Construct the to-do list.
2247      *
2248      * This just amounts to extracting the flow from each packet and sticking
2249      * the packets that have the same flow in the same "flow_miss" structure so
2250      * that we can process them together. */
2251     hmap_init(&todo);
2252     for (upcall = upcalls; upcall < &upcalls[n_upcalls]; upcall++) {
2253         struct flow_miss *miss;
2254         struct flow flow;
2255
2256         /* Obtain in_port and tun_id, at least, then set 'flow''s header
2257          * pointers. */
2258         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2259         flow_extract(upcall->packet, flow.tun_id, flow.in_port, &flow);
2260
2261         /* Handle 802.1ag, LACP, and STP specially. */
2262         if (process_special(ofproto, &flow, upcall->packet)) {
2263             ofpbuf_delete(upcall->packet);
2264             ofproto->n_matches++;
2265             continue;
2266         }
2267
2268         /* Add other packets to a to-do list. */
2269         miss = flow_miss_create(&todo, &flow, upcall->key, upcall->key_len);
2270         list_push_back(&miss->packets, &upcall->packet->list_node);
2271     }
2272
2273     /* Process each element in the to-do list, constructing the set of
2274      * operations to batch. */
2275     n_ops = 0;
2276     HMAP_FOR_EACH_SAFE (miss, next_miss, hmap_node, &todo) {
2277         handle_flow_miss(ofproto, miss, flow_miss_ops, &n_ops);
2278         ofpbuf_list_delete(&miss->packets);
2279         hmap_remove(&todo, &miss->hmap_node);
2280         free(miss);
2281     }
2282     assert(n_ops <= ARRAY_SIZE(flow_miss_ops));
2283     hmap_destroy(&todo);
2284
2285     /* Execute batch. */
2286     for (i = 0; i < n_ops; i++) {
2287         dpif_ops[i] = &flow_miss_ops[i].dpif_op;
2288     }
2289     dpif_operate(ofproto->dpif, dpif_ops, n_ops);
2290
2291     /* Free memory and update facets. */
2292     for (i = 0; i < n_ops; i++) {
2293         struct flow_miss_op *op = &flow_miss_ops[i];
2294         struct dpif_execute *execute;
2295         struct dpif_flow_put *put;
2296
2297         switch (op->dpif_op.type) {
2298         case DPIF_OP_EXECUTE:
2299             execute = &op->dpif_op.execute;
2300             if (op->facet->actions != execute->actions) {
2301                 free((struct nlattr *) execute->actions);
2302             }
2303             ofpbuf_delete((struct ofpbuf *) execute->packet);
2304             break;
2305
2306         case DPIF_OP_FLOW_PUT:
2307             put = &op->dpif_op.flow_put;
2308             if (!put->error) {
2309                 op->facet->installed = true;
2310             }
2311             break;
2312         }
2313     }
2314 }
2315
2316 static void
2317 handle_userspace_upcall(struct ofproto_dpif *ofproto,
2318                         struct dpif_upcall *upcall)
2319 {
2320     struct flow flow;
2321     struct user_action_cookie cookie;
2322
2323     memcpy(&cookie, &upcall->userdata, sizeof(cookie));
2324
2325     if (cookie.type == USER_ACTION_COOKIE_SFLOW) {
2326         if (ofproto->sflow) {
2327             odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2328             dpif_sflow_received(ofproto->sflow, upcall->packet, &flow, &cookie);
2329         }
2330         ofpbuf_delete(upcall->packet);
2331
2332     } else if (cookie.type == USER_ACTION_COOKIE_CONTROLLER) {
2333         COVERAGE_INC(ofproto_dpif_ctlr_action);
2334         odp_flow_key_to_flow(upcall->key, upcall->key_len, &flow);
2335         send_packet_in_action(ofproto, upcall->packet, upcall->userdata,
2336                               &flow, false);
2337     } else {
2338         VLOG_WARN_RL(&rl, "invalid user cookie : 0x%"PRIx64, upcall->userdata);
2339     }
2340 }
2341
2342 static void
2343 handle_upcall(struct ofproto_dpif *ofproto, struct dpif_upcall *upcall)
2344 {
2345     switch (upcall->type) {
2346     case DPIF_UC_ACTION:
2347         handle_userspace_upcall(ofproto, upcall);
2348         break;
2349
2350     case DPIF_UC_MISS:
2351         /* The caller handles these. */
2352         NOT_REACHED();
2353
2354     case DPIF_N_UC_TYPES:
2355     default:
2356         VLOG_WARN_RL(&rl, "upcall has unexpected type %"PRIu32, upcall->type);
2357         break;
2358     }
2359 }
2360 \f
2361 /* Flow expiration. */
2362
2363 static int facet_max_idle(const struct ofproto_dpif *);
2364 static void update_stats(struct ofproto_dpif *);
2365 static void rule_expire(struct rule_dpif *);
2366 static void expire_facets(struct ofproto_dpif *, int dp_max_idle);
2367
2368 /* This function is called periodically by run().  Its job is to collect
2369  * updates for the flows that have been installed into the datapath, most
2370  * importantly when they last were used, and then use that information to
2371  * expire flows that have not been used recently.
2372  *
2373  * Returns the number of milliseconds after which it should be called again. */
2374 static int
2375 expire(struct ofproto_dpif *ofproto)
2376 {
2377     struct rule_dpif *rule, *next_rule;
2378     struct classifier *table;
2379     int dp_max_idle;
2380
2381     /* Update stats for each flow in the datapath. */
2382     update_stats(ofproto);
2383
2384     /* Expire facets that have been idle too long. */
2385     dp_max_idle = facet_max_idle(ofproto);
2386     expire_facets(ofproto, dp_max_idle);
2387
2388     /* Expire OpenFlow flows whose idle_timeout or hard_timeout has passed. */
2389     OFPROTO_FOR_EACH_TABLE (table, &ofproto->up) {
2390         struct cls_cursor cursor;
2391
2392         cls_cursor_init(&cursor, table, NULL);
2393         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, up.cr, &cursor) {
2394             rule_expire(rule);
2395         }
2396     }
2397
2398     /* All outstanding data in existing flows has been accounted, so it's a
2399      * good time to do bond rebalancing. */
2400     if (ofproto->has_bonded_bundles) {
2401         struct ofbundle *bundle;
2402
2403         HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
2404             if (bundle->bond) {
2405                 bond_rebalance(bundle->bond, &ofproto->revalidate_set);
2406             }
2407         }
2408     }
2409
2410     return MIN(dp_max_idle, 1000);
2411 }
2412
2413 /* Update 'packet_count', 'byte_count', and 'used' members of installed facets.
2414  *
2415  * This function also pushes statistics updates to rules which each facet
2416  * resubmits into.  Generally these statistics will be accurate.  However, if a
2417  * facet changes the rule it resubmits into at some time in between
2418  * update_stats() runs, it is possible that statistics accrued to the
2419  * old rule will be incorrectly attributed to the new rule.  This could be
2420  * avoided by calling update_stats() whenever rules are created or
2421  * deleted.  However, the performance impact of making so many calls to the
2422  * datapath do not justify the benefit of having perfectly accurate statistics.
2423  */
2424 static void
2425 update_stats(struct ofproto_dpif *p)
2426 {
2427     const struct dpif_flow_stats *stats;
2428     struct dpif_flow_dump dump;
2429     const struct nlattr *key;
2430     size_t key_len;
2431
2432     dpif_flow_dump_start(&dump, p->dpif);
2433     while (dpif_flow_dump_next(&dump, &key, &key_len, NULL, NULL, &stats)) {
2434         struct facet *facet;
2435         struct flow flow;
2436
2437         if (odp_flow_key_to_flow(key, key_len, &flow)) {
2438             struct ds s;
2439
2440             ds_init(&s);
2441             odp_flow_key_format(key, key_len, &s);
2442             VLOG_WARN_RL(&rl, "failed to convert datapath flow key to flow: %s",
2443                          ds_cstr(&s));
2444             ds_destroy(&s);
2445
2446             continue;
2447         }
2448         facet = facet_find(p, &flow);
2449
2450         if (facet && facet->installed) {
2451
2452             if (stats->n_packets >= facet->dp_packet_count) {
2453                 uint64_t extra = stats->n_packets - facet->dp_packet_count;
2454                 facet->packet_count += extra;
2455             } else {
2456                 VLOG_WARN_RL(&rl, "unexpected packet count from the datapath");
2457             }
2458
2459             if (stats->n_bytes >= facet->dp_byte_count) {
2460                 facet->byte_count += stats->n_bytes - facet->dp_byte_count;
2461             } else {
2462                 VLOG_WARN_RL(&rl, "unexpected byte count from datapath");
2463             }
2464
2465             facet->dp_packet_count = stats->n_packets;
2466             facet->dp_byte_count = stats->n_bytes;
2467
2468             facet_update_time(p, facet, stats->used);
2469             facet_account(p, facet);
2470             facet_push_stats(facet);
2471         } else {
2472             /* There's a flow in the datapath that we know nothing about.
2473              * Delete it. */
2474             COVERAGE_INC(facet_unexpected);
2475             dpif_flow_del(p->dpif, key, key_len, NULL);
2476         }
2477     }
2478     dpif_flow_dump_done(&dump);
2479 }
2480
2481 /* Calculates and returns the number of milliseconds of idle time after which
2482  * facets should expire from the datapath and we should fold their statistics
2483  * into their parent rules in userspace. */
2484 static int
2485 facet_max_idle(const struct ofproto_dpif *ofproto)
2486 {
2487     /*
2488      * Idle time histogram.
2489      *
2490      * Most of the time a switch has a relatively small number of facets.  When
2491      * this is the case we might as well keep statistics for all of them in
2492      * userspace and to cache them in the kernel datapath for performance as
2493      * well.
2494      *
2495      * As the number of facets increases, the memory required to maintain
2496      * statistics about them in userspace and in the kernel becomes
2497      * significant.  However, with a large number of facets it is likely that
2498      * only a few of them are "heavy hitters" that consume a large amount of
2499      * bandwidth.  At this point, only heavy hitters are worth caching in the
2500      * kernel and maintaining in userspaces; other facets we can discard.
2501      *
2502      * The technique used to compute the idle time is to build a histogram with
2503      * N_BUCKETS buckets whose width is BUCKET_WIDTH msecs each.  Each facet
2504      * that is installed in the kernel gets dropped in the appropriate bucket.
2505      * After the histogram has been built, we compute the cutoff so that only
2506      * the most-recently-used 1% of facets (but at least
2507      * ofproto->up.flow_eviction_threshold flows) are kept cached.  At least
2508      * the most-recently-used bucket of facets is kept, so actually an
2509      * arbitrary number of facets can be kept in any given expiration run
2510      * (though the next run will delete most of those unless they receive
2511      * additional data).
2512      *
2513      * This requires a second pass through the facets, in addition to the pass
2514      * made by update_stats(), because the former function never looks
2515      * at uninstallable facets.
2516      */
2517     enum { BUCKET_WIDTH = ROUND_UP(100, TIME_UPDATE_INTERVAL) };
2518     enum { N_BUCKETS = 5000 / BUCKET_WIDTH };
2519     int buckets[N_BUCKETS] = { 0 };
2520     int total, subtotal, bucket;
2521     struct facet *facet;
2522     long long int now;
2523     int i;
2524
2525     total = hmap_count(&ofproto->facets);
2526     if (total <= ofproto->up.flow_eviction_threshold) {
2527         return N_BUCKETS * BUCKET_WIDTH;
2528     }
2529
2530     /* Build histogram. */
2531     now = time_msec();
2532     HMAP_FOR_EACH (facet, hmap_node, &ofproto->facets) {
2533         long long int idle = now - facet->used;
2534         int bucket = (idle <= 0 ? 0
2535                       : idle >= BUCKET_WIDTH * N_BUCKETS ? N_BUCKETS - 1
2536                       : (unsigned int) idle / BUCKET_WIDTH);
2537         buckets[bucket]++;
2538     }
2539
2540     /* Find the first bucket whose flows should be expired. */
2541     subtotal = bucket = 0;
2542     do {
2543         subtotal += buckets[bucket++];
2544     } while (bucket < N_BUCKETS &&
2545              subtotal < MAX(ofproto->up.flow_eviction_threshold, total / 100));
2546
2547     if (VLOG_IS_DBG_ENABLED()) {
2548         struct ds s;
2549
2550         ds_init(&s);
2551         ds_put_cstr(&s, "keep");
2552         for (i = 0; i < N_BUCKETS; i++) {
2553             if (i == bucket) {
2554                 ds_put_cstr(&s, ", drop");
2555             }
2556             if (buckets[i]) {
2557                 ds_put_format(&s, " %d:%d", i * BUCKET_WIDTH, buckets[i]);
2558             }
2559         }
2560         VLOG_INFO("%s: %s (msec:count)", ofproto->up.name, ds_cstr(&s));
2561         ds_destroy(&s);
2562     }
2563
2564     return bucket * BUCKET_WIDTH;
2565 }
2566
2567 static void
2568 facet_active_timeout(struct ofproto_dpif *ofproto, struct facet *facet)
2569 {
2570     if (ofproto->netflow && !facet_is_controller_flow(facet) &&
2571         netflow_active_timeout_expired(ofproto->netflow, &facet->nf_flow)) {
2572         struct ofexpired expired;
2573
2574         if (facet->installed) {
2575             struct dpif_flow_stats stats;
2576
2577             facet_put__(ofproto, facet, facet->actions, facet->actions_len,
2578                         &stats);
2579             facet_update_stats(ofproto, facet, &stats);
2580         }
2581
2582         expired.flow = facet->flow;
2583         expired.packet_count = facet->packet_count;
2584         expired.byte_count = facet->byte_count;
2585         expired.used = facet->used;
2586         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2587     }
2588 }
2589
2590 static void
2591 expire_facets(struct ofproto_dpif *ofproto, int dp_max_idle)
2592 {
2593     long long int cutoff = time_msec() - dp_max_idle;
2594     struct facet *facet, *next_facet;
2595
2596     HMAP_FOR_EACH_SAFE (facet, next_facet, hmap_node, &ofproto->facets) {
2597         facet_active_timeout(ofproto, facet);
2598         if (facet->used < cutoff) {
2599             facet_remove(ofproto, facet);
2600         }
2601     }
2602 }
2603
2604 /* If 'rule' is an OpenFlow rule, that has expired according to OpenFlow rules,
2605  * then delete it entirely. */
2606 static void
2607 rule_expire(struct rule_dpif *rule)
2608 {
2609     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2610     struct facet *facet, *next_facet;
2611     long long int now;
2612     uint8_t reason;
2613
2614     /* Has 'rule' expired? */
2615     now = time_msec();
2616     if (rule->up.hard_timeout
2617         && now > rule->up.modified + rule->up.hard_timeout * 1000) {
2618         reason = OFPRR_HARD_TIMEOUT;
2619     } else if (rule->up.idle_timeout && list_is_empty(&rule->facets)
2620                && now > rule->used + rule->up.idle_timeout * 1000) {
2621         reason = OFPRR_IDLE_TIMEOUT;
2622     } else {
2623         return;
2624     }
2625
2626     COVERAGE_INC(ofproto_dpif_expired);
2627
2628     /* Update stats.  (This is a no-op if the rule expired due to an idle
2629      * timeout, because that only happens when the rule has no facets left.) */
2630     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
2631         facet_remove(ofproto, facet);
2632     }
2633
2634     /* Get rid of the rule. */
2635     ofproto_rule_expire(&rule->up, reason);
2636 }
2637 \f
2638 /* Facets. */
2639
2640 /* Creates and returns a new facet owned by 'rule', given a 'flow'.
2641  *
2642  * The caller must already have determined that no facet with an identical
2643  * 'flow' exists in 'ofproto' and that 'flow' is the best match for 'rule' in
2644  * the ofproto's classifier table.
2645  *
2646  * The facet will initially have no ODP actions.  The caller should fix that
2647  * by calling facet_make_actions(). */
2648 static struct facet *
2649 facet_create(struct rule_dpif *rule, const struct flow *flow)
2650 {
2651     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
2652     struct facet *facet;
2653
2654     facet = xzalloc(sizeof *facet);
2655     facet->used = time_msec();
2656     hmap_insert(&ofproto->facets, &facet->hmap_node, flow_hash(flow, 0));
2657     list_push_back(&rule->facets, &facet->list_node);
2658     facet->rule = rule;
2659     facet->flow = *flow;
2660     netflow_flow_init(&facet->nf_flow);
2661     netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, facet->used);
2662
2663     return facet;
2664 }
2665
2666 static void
2667 facet_free(struct facet *facet)
2668 {
2669     free(facet->actions);
2670     free(facet);
2671 }
2672
2673 static bool
2674 execute_controller_action(struct ofproto_dpif *ofproto,
2675                           const struct flow *flow,
2676                           const struct nlattr *odp_actions, size_t actions_len,
2677                           struct ofpbuf *packet)
2678 {
2679     if (actions_len
2680         && odp_actions->nla_type == OVS_ACTION_ATTR_USERSPACE
2681         && NLA_ALIGN(odp_actions->nla_len) == actions_len) {
2682         /* As an optimization, avoid a round-trip from userspace to kernel to
2683          * userspace.  This also avoids possibly filling up kernel packet
2684          * buffers along the way.
2685          *
2686          * This optimization will not accidentally catch sFlow
2687          * OVS_ACTION_ATTR_USERSPACE actions, since those are encapsulated
2688          * inside OVS_ACTION_ATTR_SAMPLE. */
2689         const struct nlattr *nla;
2690
2691         nla = nl_attr_find_nested(odp_actions, OVS_USERSPACE_ATTR_USERDATA);
2692         send_packet_in_action(ofproto, packet, nl_attr_get_u64(nla), flow,
2693                               false);
2694         return true;
2695     } else {
2696         return false;
2697     }
2698 }
2699
2700 /* Executes, within 'ofproto', the 'n_actions' actions in 'actions' on
2701  * 'packet', which arrived on 'in_port'.
2702  *
2703  * Takes ownership of 'packet'. */
2704 static bool
2705 execute_odp_actions(struct ofproto_dpif *ofproto, const struct flow *flow,
2706                     const struct nlattr *odp_actions, size_t actions_len,
2707                     struct ofpbuf *packet)
2708 {
2709     struct odputil_keybuf keybuf;
2710     struct ofpbuf key;
2711     int error;
2712
2713     if (execute_controller_action(ofproto, flow, odp_actions, actions_len,
2714                                   packet)) {
2715         return true;
2716     }
2717
2718     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2719     odp_flow_key_from_flow(&key, flow);
2720
2721     error = dpif_execute(ofproto->dpif, key.data, key.size,
2722                          odp_actions, actions_len, packet);
2723
2724     ofpbuf_delete(packet);
2725     return !error;
2726 }
2727
2728 /* Executes the actions indicated by 'facet' on 'packet' and credits 'facet''s
2729  * statistics appropriately.  'packet' must have at least sizeof(struct
2730  * ofp_packet_in) bytes of headroom.
2731  *
2732  * For correct results, 'packet' must actually be in 'facet''s flow; that is,
2733  * applying flow_extract() to 'packet' would yield the same flow as
2734  * 'facet->flow'.
2735  *
2736  * 'facet' must have accurately composed datapath actions; that is, it must
2737  * not be in need of revalidation.
2738  *
2739  * Takes ownership of 'packet'. */
2740 static void
2741 facet_execute(struct ofproto_dpif *ofproto, struct facet *facet,
2742               struct ofpbuf *packet)
2743 {
2744     struct dpif_flow_stats stats;
2745
2746     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
2747
2748     dpif_flow_stats_extract(&facet->flow, packet, &stats);
2749     stats.used = time_msec();
2750     if (execute_odp_actions(ofproto, &facet->flow,
2751                             facet->actions, facet->actions_len, packet)) {
2752         facet_update_stats(ofproto, facet, &stats);
2753     }
2754 }
2755
2756 /* Remove 'facet' from 'ofproto' and free up the associated memory:
2757  *
2758  *   - If 'facet' was installed in the datapath, uninstalls it and updates its
2759  *     rule's statistics, via facet_uninstall().
2760  *
2761  *   - Removes 'facet' from its rule and from ofproto->facets.
2762  */
2763 static void
2764 facet_remove(struct ofproto_dpif *ofproto, struct facet *facet)
2765 {
2766     facet_uninstall(ofproto, facet);
2767     facet_flush_stats(ofproto, facet);
2768     hmap_remove(&ofproto->facets, &facet->hmap_node);
2769     list_remove(&facet->list_node);
2770     facet_free(facet);
2771 }
2772
2773 /* Composes the datapath actions for 'facet' based on its rule's actions. */
2774 static void
2775 facet_make_actions(struct ofproto_dpif *p, struct facet *facet,
2776                    const struct ofpbuf *packet)
2777 {
2778     const struct rule_dpif *rule = facet->rule;
2779     struct ofpbuf *odp_actions;
2780     struct action_xlate_ctx ctx;
2781
2782     action_xlate_ctx_init(&ctx, p, &facet->flow, packet);
2783     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
2784     facet->tags = ctx.tags;
2785     facet->may_install = ctx.may_set_up_flow;
2786     facet->has_learn = ctx.has_learn;
2787     facet->has_normal = ctx.has_normal;
2788     facet->nf_flow.output_iface = ctx.nf_output_iface;
2789
2790     if (facet->actions_len != odp_actions->size
2791         || memcmp(facet->actions, odp_actions->data, odp_actions->size)) {
2792         free(facet->actions);
2793         facet->actions_len = odp_actions->size;
2794         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
2795     }
2796
2797     ofpbuf_delete(odp_actions);
2798 }
2799
2800 /* Updates 'facet''s flow in the datapath setting its actions to 'actions_len'
2801  * bytes of actions in 'actions'.  If 'stats' is non-null, statistics counters
2802  * in the datapath will be zeroed and 'stats' will be updated with traffic new
2803  * since 'facet' was last updated.
2804  *
2805  * Returns 0 if successful, otherwise a positive errno value.*/
2806 static int
2807 facet_put__(struct ofproto_dpif *ofproto, struct facet *facet,
2808             const struct nlattr *actions, size_t actions_len,
2809             struct dpif_flow_stats *stats)
2810 {
2811     struct odputil_keybuf keybuf;
2812     enum dpif_flow_put_flags flags;
2813     struct ofpbuf key;
2814     int ret;
2815
2816     flags = DPIF_FP_CREATE | DPIF_FP_MODIFY;
2817     if (stats) {
2818         flags |= DPIF_FP_ZERO_STATS;
2819     }
2820
2821     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2822     odp_flow_key_from_flow(&key, &facet->flow);
2823
2824     ret = dpif_flow_put(ofproto->dpif, flags, key.data, key.size,
2825                         actions, actions_len, stats);
2826
2827     if (stats) {
2828         facet_reset_dp_stats(facet, stats);
2829     }
2830
2831     return ret;
2832 }
2833
2834 /* If 'facet' is installable, inserts or re-inserts it into 'p''s datapath.  If
2835  * 'zero_stats' is true, clears any existing statistics from the datapath for
2836  * 'facet'. */
2837 static void
2838 facet_install(struct ofproto_dpif *p, struct facet *facet, bool zero_stats)
2839 {
2840     struct dpif_flow_stats stats;
2841
2842     if (facet->may_install
2843         && !facet_put__(p, facet, facet->actions, facet->actions_len,
2844                         zero_stats ? &stats : NULL)) {
2845         facet->installed = true;
2846     }
2847 }
2848
2849 static void
2850 facet_account(struct ofproto_dpif *ofproto, struct facet *facet)
2851 {
2852     uint64_t n_bytes;
2853     const struct nlattr *a;
2854     unsigned int left;
2855     ovs_be16 vlan_tci;
2856
2857     if (facet->byte_count <= facet->accounted_bytes) {
2858         return;
2859     }
2860     n_bytes = facet->byte_count - facet->accounted_bytes;
2861     facet->accounted_bytes = facet->byte_count;
2862
2863     /* Feed information from the active flows back into the learning table to
2864      * ensure that table is always in sync with what is actually flowing
2865      * through the datapath. */
2866     if (facet->has_learn || facet->has_normal) {
2867         struct action_xlate_ctx ctx;
2868
2869         action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
2870         ctx.may_learn = true;
2871         ofpbuf_delete(xlate_actions(&ctx, facet->rule->up.actions,
2872                                     facet->rule->up.n_actions));
2873     }
2874
2875     if (!facet->has_normal || !ofproto->has_bonded_bundles) {
2876         return;
2877     }
2878
2879     /* This loop feeds byte counters to bond_account() for rebalancing to use
2880      * as a basis.  We also need to track the actual VLAN on which the packet
2881      * is going to be sent to ensure that it matches the one passed to
2882      * bond_choose_output_slave().  (Otherwise, we will account to the wrong
2883      * hash bucket.) */
2884     vlan_tci = facet->flow.vlan_tci;
2885     NL_ATTR_FOR_EACH_UNSAFE (a, left, facet->actions, facet->actions_len) {
2886         struct ofport_dpif *port;
2887
2888         switch (nl_attr_type(a)) {
2889         const struct nlattr *nested;
2890         case OVS_ACTION_ATTR_OUTPUT:
2891             port = get_odp_port(ofproto, nl_attr_get_u32(a));
2892             if (port && port->bundle && port->bundle->bond) {
2893                 bond_account(port->bundle->bond, &facet->flow,
2894                              vlan_tci_to_vid(vlan_tci), n_bytes);
2895             }
2896             break;
2897
2898         case OVS_ACTION_ATTR_POP:
2899             if (nl_attr_get_u16(a) == OVS_KEY_ATTR_8021Q) {
2900                 vlan_tci = htons(0);
2901             }
2902             break;
2903
2904         case OVS_ACTION_ATTR_PUSH:
2905             nested = nl_attr_get(a);
2906             if (nl_attr_type(nested) == OVS_KEY_ATTR_8021Q) {
2907                 const struct ovs_key_8021q *q_key;
2908
2909                 q_key = nl_attr_get_unspec(nested, sizeof(*q_key));
2910                 vlan_tci = q_key->q_tci;
2911             }
2912             break;
2913         }
2914     }
2915 }
2916
2917 /* If 'rule' is installed in the datapath, uninstalls it. */
2918 static void
2919 facet_uninstall(struct ofproto_dpif *p, struct facet *facet)
2920 {
2921     if (facet->installed) {
2922         struct odputil_keybuf keybuf;
2923         struct dpif_flow_stats stats;
2924         struct ofpbuf key;
2925         int error;
2926
2927         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
2928         odp_flow_key_from_flow(&key, &facet->flow);
2929
2930         error = dpif_flow_del(p->dpif, key.data, key.size, &stats);
2931         facet_reset_dp_stats(facet, &stats);
2932         if (!error) {
2933             facet_update_stats(p, facet, &stats);
2934         }
2935         facet->installed = false;
2936     } else {
2937         assert(facet->dp_packet_count == 0);
2938         assert(facet->dp_byte_count == 0);
2939     }
2940 }
2941
2942 /* Returns true if the only action for 'facet' is to send to the controller.
2943  * (We don't report NetFlow expiration messages for such facets because they
2944  * are just part of the control logic for the network, not real traffic). */
2945 static bool
2946 facet_is_controller_flow(struct facet *facet)
2947 {
2948     return (facet
2949             && facet->rule->up.n_actions == 1
2950             && action_outputs_to_port(&facet->rule->up.actions[0],
2951                                       htons(OFPP_CONTROLLER)));
2952 }
2953
2954 /* Resets 'facet''s datapath statistics counters.  This should be called when
2955  * 'facet''s statistics are cleared in the datapath.  If 'stats' is non-null,
2956  * it should contain the statistics returned by dpif when 'facet' was reset in
2957  * the datapath.  'stats' will be modified to only included statistics new
2958  * since 'facet' was last updated. */
2959 static void
2960 facet_reset_dp_stats(struct facet *facet, struct dpif_flow_stats *stats)
2961 {
2962     if (stats && facet->dp_packet_count <= stats->n_packets
2963         && facet->dp_byte_count <= stats->n_bytes) {
2964         stats->n_packets -= facet->dp_packet_count;
2965         stats->n_bytes -= facet->dp_byte_count;
2966     }
2967
2968     facet->dp_packet_count = 0;
2969     facet->dp_byte_count = 0;
2970 }
2971
2972 /* Folds all of 'facet''s statistics into its rule.  Also updates the
2973  * accounting ofhook and emits a NetFlow expiration if appropriate.  All of
2974  * 'facet''s statistics in the datapath should have been zeroed and folded into
2975  * its packet and byte counts before this function is called. */
2976 static void
2977 facet_flush_stats(struct ofproto_dpif *ofproto, struct facet *facet)
2978 {
2979     assert(!facet->dp_byte_count);
2980     assert(!facet->dp_packet_count);
2981
2982     facet_push_stats(facet);
2983     facet_account(ofproto, facet);
2984
2985     if (ofproto->netflow && !facet_is_controller_flow(facet)) {
2986         struct ofexpired expired;
2987         expired.flow = facet->flow;
2988         expired.packet_count = facet->packet_count;
2989         expired.byte_count = facet->byte_count;
2990         expired.used = facet->used;
2991         netflow_expire(ofproto->netflow, &facet->nf_flow, &expired);
2992     }
2993
2994     facet->rule->packet_count += facet->packet_count;
2995     facet->rule->byte_count += facet->byte_count;
2996
2997     /* Reset counters to prevent double counting if 'facet' ever gets
2998      * reinstalled. */
2999     facet_reset_counters(facet);
3000
3001     netflow_flow_clear(&facet->nf_flow);
3002 }
3003
3004 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3005  * Returns it if found, otherwise a null pointer.
3006  *
3007  * The returned facet might need revalidation; use facet_lookup_valid()
3008  * instead if that is important. */
3009 static struct facet *
3010 facet_find(struct ofproto_dpif *ofproto, const struct flow *flow)
3011 {
3012     struct facet *facet;
3013
3014     HMAP_FOR_EACH_WITH_HASH (facet, hmap_node, flow_hash(flow, 0),
3015                              &ofproto->facets) {
3016         if (flow_equal(flow, &facet->flow)) {
3017             return facet;
3018         }
3019     }
3020
3021     return NULL;
3022 }
3023
3024 /* Searches 'ofproto''s table of facets for one exactly equal to 'flow'.
3025  * Returns it if found, otherwise a null pointer.
3026  *
3027  * The returned facet is guaranteed to be valid. */
3028 static struct facet *
3029 facet_lookup_valid(struct ofproto_dpif *ofproto, const struct flow *flow)
3030 {
3031     struct facet *facet = facet_find(ofproto, flow);
3032
3033     /* The facet we found might not be valid, since we could be in need of
3034      * revalidation.  If it is not valid, don't return it. */
3035     if (facet
3036         && (ofproto->need_revalidate
3037             || tag_set_intersects(&ofproto->revalidate_set, facet->tags))
3038         && !facet_revalidate(ofproto, facet)) {
3039         COVERAGE_INC(facet_invalidated);
3040         return NULL;
3041     }
3042
3043     return facet;
3044 }
3045
3046 /* Re-searches 'ofproto''s classifier for a rule matching 'facet':
3047  *
3048  *   - If the rule found is different from 'facet''s current rule, moves
3049  *     'facet' to the new rule and recompiles its actions.
3050  *
3051  *   - If the rule found is the same as 'facet''s current rule, leaves 'facet'
3052  *     where it is and recompiles its actions anyway.
3053  *
3054  *   - If there is none, destroys 'facet'.
3055  *
3056  * Returns true if 'facet' still exists, false if it has been destroyed. */
3057 static bool
3058 facet_revalidate(struct ofproto_dpif *ofproto, struct facet *facet)
3059 {
3060     struct action_xlate_ctx ctx;
3061     struct ofpbuf *odp_actions;
3062     struct rule_dpif *new_rule;
3063     bool actions_changed;
3064
3065     COVERAGE_INC(facet_revalidate);
3066
3067     /* Determine the new rule. */
3068     new_rule = rule_dpif_lookup(ofproto, &facet->flow, 0);
3069     if (!new_rule) {
3070         /* No new rule, so delete the facet. */
3071         facet_remove(ofproto, facet);
3072         return false;
3073     }
3074
3075     /* Calculate new datapath actions.
3076      *
3077      * We do not modify any 'facet' state yet, because we might need to, e.g.,
3078      * emit a NetFlow expiration and, if so, we need to have the old state
3079      * around to properly compose it. */
3080     action_xlate_ctx_init(&ctx, ofproto, &facet->flow, NULL);
3081     odp_actions = xlate_actions(&ctx,
3082                                 new_rule->up.actions, new_rule->up.n_actions);
3083     actions_changed = (facet->actions_len != odp_actions->size
3084                        || memcmp(facet->actions, odp_actions->data,
3085                                  facet->actions_len));
3086
3087     /* If the datapath actions changed or the installability changed,
3088      * then we need to talk to the datapath. */
3089     if (actions_changed || ctx.may_set_up_flow != facet->installed) {
3090         if (ctx.may_set_up_flow) {
3091             struct dpif_flow_stats stats;
3092
3093             facet_put__(ofproto, facet,
3094                         odp_actions->data, odp_actions->size, &stats);
3095             facet_update_stats(ofproto, facet, &stats);
3096         } else {
3097             facet_uninstall(ofproto, facet);
3098         }
3099
3100         /* The datapath flow is gone or has zeroed stats, so push stats out of
3101          * 'facet' into 'rule'. */
3102         facet_flush_stats(ofproto, facet);
3103     }
3104
3105     /* Update 'facet' now that we've taken care of all the old state. */
3106     facet->tags = ctx.tags;
3107     facet->nf_flow.output_iface = ctx.nf_output_iface;
3108     facet->may_install = ctx.may_set_up_flow;
3109     facet->has_learn = ctx.has_learn;
3110     facet->has_normal = ctx.has_normal;
3111     if (actions_changed) {
3112         free(facet->actions);
3113         facet->actions_len = odp_actions->size;
3114         facet->actions = xmemdup(odp_actions->data, odp_actions->size);
3115     }
3116     if (facet->rule != new_rule) {
3117         COVERAGE_INC(facet_changed_rule);
3118         list_remove(&facet->list_node);
3119         list_push_back(&new_rule->facets, &facet->list_node);
3120         facet->rule = new_rule;
3121         facet->used = new_rule->up.created;
3122         facet->rs_used = facet->used;
3123     }
3124
3125     ofpbuf_delete(odp_actions);
3126
3127     return true;
3128 }
3129
3130 /* Updates 'facet''s used time.  Caller is responsible for calling
3131  * facet_push_stats() to update the flows which 'facet' resubmits into. */
3132 static void
3133 facet_update_time(struct ofproto_dpif *ofproto, struct facet *facet,
3134                   long long int used)
3135 {
3136     if (used > facet->used) {
3137         facet->used = used;
3138         if (used > facet->rule->used) {
3139             facet->rule->used = used;
3140         }
3141         netflow_flow_update_time(ofproto->netflow, &facet->nf_flow, used);
3142     }
3143 }
3144
3145 /* Folds the statistics from 'stats' into the counters in 'facet'.
3146  *
3147  * Because of the meaning of a facet's counters, it only makes sense to do this
3148  * if 'stats' are not tracked in the datapath, that is, if 'stats' represents a
3149  * packet that was sent by hand or if it represents statistics that have been
3150  * cleared out of the datapath. */
3151 static void
3152 facet_update_stats(struct ofproto_dpif *ofproto, struct facet *facet,
3153                    const struct dpif_flow_stats *stats)
3154 {
3155     if (stats->n_packets || stats->used > facet->used) {
3156         facet_update_time(ofproto, facet, stats->used);
3157         facet->packet_count += stats->n_packets;
3158         facet->byte_count += stats->n_bytes;
3159         facet_push_stats(facet);
3160         netflow_flow_update_flags(&facet->nf_flow, stats->tcp_flags);
3161     }
3162 }
3163
3164 static void
3165 facet_reset_counters(struct facet *facet)
3166 {
3167     facet->packet_count = 0;
3168     facet->byte_count = 0;
3169     facet->rs_packet_count = 0;
3170     facet->rs_byte_count = 0;
3171     facet->accounted_bytes = 0;
3172 }
3173
3174 static void
3175 facet_push_stats(struct facet *facet)
3176 {
3177     uint64_t rs_packets, rs_bytes;
3178
3179     assert(facet->packet_count >= facet->rs_packet_count);
3180     assert(facet->byte_count >= facet->rs_byte_count);
3181     assert(facet->used >= facet->rs_used);
3182
3183     rs_packets = facet->packet_count - facet->rs_packet_count;
3184     rs_bytes = facet->byte_count - facet->rs_byte_count;
3185
3186     if (rs_packets || rs_bytes || facet->used > facet->rs_used) {
3187         facet->rs_packet_count = facet->packet_count;
3188         facet->rs_byte_count = facet->byte_count;
3189         facet->rs_used = facet->used;
3190
3191         flow_push_stats(facet->rule, &facet->flow,
3192                         rs_packets, rs_bytes, facet->used);
3193     }
3194 }
3195
3196 struct ofproto_push {
3197     struct action_xlate_ctx ctx;
3198     uint64_t packets;
3199     uint64_t bytes;
3200     long long int used;
3201 };
3202
3203 static void
3204 push_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
3205 {
3206     struct ofproto_push *push = CONTAINER_OF(ctx, struct ofproto_push, ctx);
3207
3208     if (rule) {
3209         rule->packet_count += push->packets;
3210         rule->byte_count += push->bytes;
3211         rule->used = MAX(push->used, rule->used);
3212     }
3213 }
3214
3215 /* Pushes flow statistics to the rules which 'flow' resubmits into given
3216  * 'rule''s actions. */
3217 static void
3218 flow_push_stats(const struct rule_dpif *rule,
3219                 struct flow *flow, uint64_t packets, uint64_t bytes,
3220                 long long int used)
3221 {
3222     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3223     struct ofproto_push push;
3224
3225     push.packets = packets;
3226     push.bytes = bytes;
3227     push.used = used;
3228
3229     action_xlate_ctx_init(&push.ctx, ofproto, flow, NULL);
3230     push.ctx.resubmit_hook = push_resubmit;
3231     ofpbuf_delete(xlate_actions(&push.ctx,
3232                                 rule->up.actions, rule->up.n_actions));
3233 }
3234 \f
3235 /* Rules. */
3236
3237 static struct rule_dpif *
3238 rule_dpif_lookup(struct ofproto_dpif *ofproto, const struct flow *flow,
3239                  uint8_t table_id)
3240 {
3241     struct cls_rule *cls_rule;
3242     struct classifier *cls;
3243
3244     if (table_id >= N_TABLES) {
3245         return NULL;
3246     }
3247
3248     cls = &ofproto->up.tables[table_id];
3249     if (flow->tos_frag & FLOW_FRAG_ANY
3250         && ofproto->up.frag_handling == OFPC_FRAG_NORMAL) {
3251         /* For OFPC_NORMAL frag_handling, we must pretend that transport ports
3252          * are unavailable. */
3253         struct flow ofpc_normal_flow = *flow;
3254         ofpc_normal_flow.tp_src = htons(0);
3255         ofpc_normal_flow.tp_dst = htons(0);
3256         cls_rule = classifier_lookup(cls, &ofpc_normal_flow);
3257     } else {
3258         cls_rule = classifier_lookup(cls, flow);
3259     }
3260     return rule_dpif_cast(rule_from_cls_rule(cls_rule));
3261 }
3262
3263 static void
3264 complete_operation(struct rule_dpif *rule)
3265 {
3266     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3267
3268     rule_invalidate(rule);
3269     if (clogged) {
3270         struct dpif_completion *c = xmalloc(sizeof *c);
3271         c->op = rule->up.pending;
3272         list_push_back(&ofproto->completions, &c->list_node);
3273     } else {
3274         ofoperation_complete(rule->up.pending, 0);
3275     }
3276 }
3277
3278 static struct rule *
3279 rule_alloc(void)
3280 {
3281     struct rule_dpif *rule = xmalloc(sizeof *rule);
3282     return &rule->up;
3283 }
3284
3285 static void
3286 rule_dealloc(struct rule *rule_)
3287 {
3288     struct rule_dpif *rule = rule_dpif_cast(rule_);
3289     free(rule);
3290 }
3291
3292 static int
3293 rule_construct(struct rule *rule_)
3294 {
3295     struct rule_dpif *rule = rule_dpif_cast(rule_);
3296     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3297     struct rule_dpif *victim;
3298     uint8_t table_id;
3299     int error;
3300
3301     error = validate_actions(rule->up.actions, rule->up.n_actions,
3302                              &rule->up.cr.flow, ofproto->max_ports);
3303     if (error) {
3304         return error;
3305     }
3306
3307     rule->used = rule->up.created;
3308     rule->packet_count = 0;
3309     rule->byte_count = 0;
3310
3311     victim = rule_dpif_cast(ofoperation_get_victim(rule->up.pending));
3312     if (victim && !list_is_empty(&victim->facets)) {
3313         struct facet *facet;
3314
3315         rule->facets = victim->facets;
3316         list_moved(&rule->facets);
3317         LIST_FOR_EACH (facet, list_node, &rule->facets) {
3318             /* XXX: We're only clearing our local counters here.  It's possible
3319              * that quite a few packets are unaccounted for in the datapath
3320              * statistics.  These will be accounted to the new rule instead of
3321              * cleared as required.  This could be fixed by clearing out the
3322              * datapath statistics for this facet, but currently it doesn't
3323              * seem worth it. */
3324             facet_reset_counters(facet);
3325             facet->rule = rule;
3326         }
3327     } else {
3328         /* Must avoid list_moved() in this case. */
3329         list_init(&rule->facets);
3330     }
3331
3332     table_id = rule->up.table_id;
3333     rule->tag = (victim ? victim->tag
3334                  : table_id == 0 ? 0
3335                  : rule_calculate_tag(&rule->up.cr.flow, &rule->up.cr.wc,
3336                                       ofproto->tables[table_id].basis));
3337
3338     complete_operation(rule);
3339     return 0;
3340 }
3341
3342 static void
3343 rule_destruct(struct rule *rule_)
3344 {
3345     struct rule_dpif *rule = rule_dpif_cast(rule_);
3346     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3347     struct facet *facet, *next_facet;
3348
3349     LIST_FOR_EACH_SAFE (facet, next_facet, list_node, &rule->facets) {
3350         facet_revalidate(ofproto, facet);
3351     }
3352
3353     complete_operation(rule);
3354 }
3355
3356 static void
3357 rule_get_stats(struct rule *rule_, uint64_t *packets, uint64_t *bytes)
3358 {
3359     struct rule_dpif *rule = rule_dpif_cast(rule_);
3360     struct facet *facet;
3361
3362     /* Start from historical data for 'rule' itself that are no longer tracked
3363      * in facets.  This counts, for example, facets that have expired. */
3364     *packets = rule->packet_count;
3365     *bytes = rule->byte_count;
3366
3367     /* Add any statistics that are tracked by facets.  This includes
3368      * statistical data recently updated by ofproto_update_stats() as well as
3369      * stats for packets that were executed "by hand" via dpif_execute(). */
3370     LIST_FOR_EACH (facet, list_node, &rule->facets) {
3371         *packets += facet->packet_count;
3372         *bytes += facet->byte_count;
3373     }
3374 }
3375
3376 static int
3377 rule_execute(struct rule *rule_, struct flow *flow, struct ofpbuf *packet)
3378 {
3379     struct rule_dpif *rule = rule_dpif_cast(rule_);
3380     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3381     struct action_xlate_ctx ctx;
3382     struct ofpbuf *odp_actions;
3383     struct facet *facet;
3384     size_t size;
3385
3386     /* First look for a related facet.  If we find one, account it to that. */
3387     facet = facet_lookup_valid(ofproto, flow);
3388     if (facet && facet->rule == rule) {
3389         if (!facet->may_install) {
3390             facet_make_actions(ofproto, facet, packet);
3391         }
3392         facet_execute(ofproto, facet, packet);
3393         return 0;
3394     }
3395
3396     /* Otherwise, if 'rule' is in fact the correct rule for 'packet', then
3397      * create a new facet for it and use that. */
3398     if (rule_dpif_lookup(ofproto, flow, 0) == rule) {
3399         facet = facet_create(rule, flow);
3400         facet_make_actions(ofproto, facet, packet);
3401         facet_execute(ofproto, facet, packet);
3402         facet_install(ofproto, facet, true);
3403         return 0;
3404     }
3405
3406     /* We can't account anything to a facet.  If we were to try, then that
3407      * facet would have a non-matching rule, busting our invariants. */
3408     action_xlate_ctx_init(&ctx, ofproto, flow, packet);
3409     odp_actions = xlate_actions(&ctx, rule->up.actions, rule->up.n_actions);
3410     size = packet->size;
3411     if (execute_odp_actions(ofproto, flow, odp_actions->data,
3412                             odp_actions->size, packet)) {
3413         rule->used = time_msec();
3414         rule->packet_count++;
3415         rule->byte_count += size;
3416         flow_push_stats(rule, flow, 1, size, rule->used);
3417     }
3418     ofpbuf_delete(odp_actions);
3419
3420     return 0;
3421 }
3422
3423 static void
3424 rule_modify_actions(struct rule *rule_)
3425 {
3426     struct rule_dpif *rule = rule_dpif_cast(rule_);
3427     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
3428     int error;
3429
3430     error = validate_actions(rule->up.actions, rule->up.n_actions,
3431                              &rule->up.cr.flow, ofproto->max_ports);
3432     if (error) {
3433         ofoperation_complete(rule->up.pending, error);
3434         return;
3435     }
3436
3437     complete_operation(rule);
3438 }
3439 \f
3440 /* Sends 'packet' out of port 'odp_port' within 'ofproto'.
3441  * Returns 0 if successful, otherwise a positive errno value. */
3442 static int
3443 send_packet(struct ofproto_dpif *ofproto, uint32_t odp_port,
3444             const struct ofpbuf *packet)
3445 {
3446     struct ofpbuf key, odp_actions;
3447     struct odputil_keybuf keybuf;
3448     struct flow flow;
3449     int error;
3450
3451     flow_extract((struct ofpbuf *) packet, 0, 0, &flow);
3452     ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
3453     odp_flow_key_from_flow(&key, &flow);
3454
3455     ofpbuf_init(&odp_actions, 32);
3456     compose_sflow_action(ofproto, &odp_actions, &flow, odp_port);
3457
3458     nl_msg_put_u32(&odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3459     error = dpif_execute(ofproto->dpif,
3460                          key.data, key.size,
3461                          odp_actions.data, odp_actions.size,
3462                          packet);
3463     ofpbuf_uninit(&odp_actions);
3464
3465     if (error) {
3466         VLOG_WARN_RL(&rl, "%s: failed to send packet on port %"PRIu32" (%s)",
3467                      ofproto->up.name, odp_port, strerror(error));
3468     }
3469     return error;
3470 }
3471 \f
3472 /* OpenFlow to datapath action translation. */
3473
3474 static void do_xlate_actions(const union ofp_action *in, size_t n_in,
3475                              struct action_xlate_ctx *ctx);
3476 static void xlate_normal(struct action_xlate_ctx *);
3477
3478 static size_t
3479 put_userspace_action(const struct ofproto_dpif *ofproto,
3480                      struct ofpbuf *odp_actions,
3481                      const struct flow *flow,
3482                      const struct user_action_cookie *cookie)
3483 {
3484     size_t offset;
3485     uint32_t pid;
3486
3487     pid = dpif_port_get_pid(ofproto->dpif,
3488                             ofp_port_to_odp_port(flow->in_port));
3489
3490     offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_USERSPACE);
3491     nl_msg_put_u32(odp_actions, OVS_USERSPACE_ATTR_PID, pid);
3492     nl_msg_put_unspec(odp_actions, OVS_USERSPACE_ATTR_USERDATA,
3493                       cookie, sizeof *cookie);
3494     nl_msg_end_nested(odp_actions, offset);
3495
3496     return odp_actions->size - NLA_ALIGN(sizeof *cookie);
3497 }
3498
3499 /* Compose SAMPLE action for sFlow. */
3500 static size_t
3501 compose_sflow_action(const struct ofproto_dpif *ofproto,
3502                      struct ofpbuf *odp_actions,
3503                      const struct flow *flow,
3504                      uint32_t odp_port)
3505 {
3506     uint32_t port_ifindex;
3507     uint32_t probability;
3508     struct user_action_cookie cookie;
3509     size_t sample_offset, actions_offset;
3510     int cookie_offset, n_output;
3511
3512     if (!ofproto->sflow || flow->in_port == OFPP_NONE) {
3513         return 0;
3514     }
3515
3516     if (odp_port == OVSP_NONE) {
3517         port_ifindex = 0;
3518         n_output = 0;
3519     } else {
3520         port_ifindex = dpif_sflow_odp_port_to_ifindex(ofproto->sflow, odp_port);
3521         n_output = 1;
3522     }
3523
3524     sample_offset = nl_msg_start_nested(odp_actions, OVS_ACTION_ATTR_SAMPLE);
3525
3526     /* Number of packets out of UINT_MAX to sample. */
3527     probability = dpif_sflow_get_probability(ofproto->sflow);
3528     nl_msg_put_u32(odp_actions, OVS_SAMPLE_ATTR_PROBABILITY, probability);
3529
3530     actions_offset = nl_msg_start_nested(odp_actions, OVS_SAMPLE_ATTR_ACTIONS);
3531
3532     cookie.type = USER_ACTION_COOKIE_SFLOW;
3533     cookie.data = port_ifindex;
3534     cookie.n_output = n_output;
3535     cookie.vlan_tci = 0;
3536     cookie_offset = put_userspace_action(ofproto, odp_actions, flow, &cookie);
3537
3538     nl_msg_end_nested(odp_actions, actions_offset);
3539     nl_msg_end_nested(odp_actions, sample_offset);
3540     return cookie_offset;
3541 }
3542
3543 /* SAMPLE action must be first action in any given list of actions.
3544  * At this point we do not have all information required to build it. So try to
3545  * build sample action as complete as possible. */
3546 static void
3547 add_sflow_action(struct action_xlate_ctx *ctx)
3548 {
3549     ctx->user_cookie_offset = compose_sflow_action(ctx->ofproto,
3550                                                    ctx->odp_actions,
3551                                                    &ctx->flow, OVSP_NONE);
3552     ctx->sflow_odp_port = 0;
3553     ctx->sflow_n_outputs = 0;
3554 }
3555
3556 /* Fix SAMPLE action according to data collected while composing ODP actions.
3557  * We need to fix SAMPLE actions OVS_SAMPLE_ATTR_ACTIONS attribute, i.e. nested
3558  * USERSPACE action's user-cookie which is required for sflow. */
3559 static void
3560 fix_sflow_action(struct action_xlate_ctx *ctx)
3561 {
3562     const struct flow *base = &ctx->base_flow;
3563     struct user_action_cookie *cookie;
3564
3565     if (!ctx->user_cookie_offset) {
3566         return;
3567     }
3568
3569     cookie = ofpbuf_at(ctx->odp_actions, ctx->user_cookie_offset,
3570                      sizeof(*cookie));
3571     assert(cookie != NULL);
3572     assert(cookie->type == USER_ACTION_COOKIE_SFLOW);
3573
3574     if (ctx->sflow_n_outputs) {
3575         cookie->data = dpif_sflow_odp_port_to_ifindex(ctx->ofproto->sflow,
3576                                                     ctx->sflow_odp_port);
3577     }
3578     if (ctx->sflow_n_outputs >= 255) {
3579         cookie->n_output = 255;
3580     } else {
3581         cookie->n_output = ctx->sflow_n_outputs;
3582     }
3583     cookie->vlan_tci = base->vlan_tci;
3584 }
3585
3586 static void
3587 commit_action__(struct ofpbuf *odp_actions,
3588                 enum ovs_action_attr act_type,
3589                 enum ovs_key_attr key_type,
3590                 const void *key, size_t key_size)
3591 {
3592     size_t offset = nl_msg_start_nested(odp_actions, act_type);
3593
3594     nl_msg_put_unspec(odp_actions, key_type, key, key_size);
3595     nl_msg_end_nested(odp_actions, offset);
3596 }
3597
3598 static void
3599 commit_set_tun_id_action(const struct flow *flow, struct flow *base,
3600                          struct ofpbuf *odp_actions)
3601 {
3602     if (base->tun_id == flow->tun_id) {
3603         return;
3604     }
3605     base->tun_id = flow->tun_id;
3606
3607     commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3608              OVS_KEY_ATTR_TUN_ID, &base->tun_id, sizeof(base->tun_id));
3609 }
3610
3611 static void
3612 commit_set_ether_addr_action(const struct flow *flow, struct flow *base,
3613                              struct ofpbuf *odp_actions)
3614 {
3615     struct ovs_key_ethernet eth_key;
3616
3617     if (eth_addr_equals(base->dl_src, flow->dl_src) &&
3618         eth_addr_equals(base->dl_dst, flow->dl_dst)) {
3619         return;
3620     }
3621
3622     memcpy(base->dl_src, flow->dl_src, ETH_ADDR_LEN);
3623     memcpy(base->dl_dst, flow->dl_dst, ETH_ADDR_LEN);
3624
3625     memcpy(eth_key.eth_src, base->dl_src, ETH_ADDR_LEN);
3626     memcpy(eth_key.eth_dst, base->dl_dst, ETH_ADDR_LEN);
3627
3628     commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3629              OVS_KEY_ATTR_ETHERNET, &eth_key, sizeof(eth_key));
3630 }
3631
3632 static void
3633 commit_vlan_action(struct action_xlate_ctx *ctx, ovs_be16 new_tci)
3634 {
3635     struct flow *base = &ctx->base_flow;
3636
3637     if (base->vlan_tci == new_tci) {
3638         return;
3639     }
3640
3641     if (base->vlan_tci & htons(VLAN_CFI)) {
3642         nl_msg_put_u16(ctx->odp_actions, OVS_ACTION_ATTR_POP,
3643                                        OVS_KEY_ATTR_8021Q);
3644     }
3645
3646     if (new_tci & htons(VLAN_CFI)) {
3647         struct ovs_key_8021q q_key;
3648
3649         q_key.q_tpid = htons(ETH_TYPE_VLAN);
3650         q_key.q_tci = new_tci & ~htons(VLAN_CFI);
3651
3652         commit_action__(ctx->odp_actions, OVS_ACTION_ATTR_PUSH,
3653                             OVS_KEY_ATTR_8021Q, &q_key, sizeof(q_key));
3654     }
3655     base->vlan_tci = new_tci;
3656 }
3657
3658 static void
3659 commit_set_nw_action(const struct flow *flow, struct flow *base,
3660                      struct ofpbuf *odp_actions)
3661 {
3662     int frag = base->tos_frag & FLOW_FRAG_MASK;
3663     struct ovs_key_ipv4 ipv4_key;
3664
3665     if (base->dl_type != htons(ETH_TYPE_IP) ||
3666         !base->nw_src || !base->nw_dst) {
3667         return;
3668     }
3669
3670     if (base->nw_src == flow->nw_src &&
3671         base->nw_dst == flow->nw_dst &&
3672         base->tos_frag == flow->tos_frag) {
3673         return;
3674     }
3675
3676
3677     memset(&ipv4_key, 0, sizeof(ipv4_key));
3678     ipv4_key.ipv4_src = base->nw_src = flow->nw_src;
3679     ipv4_key.ipv4_dst = base->nw_dst = flow->nw_dst;
3680     ipv4_key.ipv4_proto = base->nw_proto;
3681     ipv4_key.ipv4_tos = flow->tos_frag & IP_DSCP_MASK;
3682     ipv4_key.ipv4_frag = (frag == 0 ? OVS_FRAG_TYPE_NONE
3683                           : frag == FLOW_FRAG_ANY ? OVS_FRAG_TYPE_FIRST
3684                           : OVS_FRAG_TYPE_LATER);
3685
3686     commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3687              OVS_KEY_ATTR_IPV4, &ipv4_key, sizeof(ipv4_key));
3688 }
3689
3690 static void
3691 commit_set_port_action(const struct flow *flow, struct flow *base,
3692                        struct ofpbuf *odp_actions)
3693 {
3694     if (!base->tp_src || !base->tp_dst) {
3695         return;
3696     }
3697
3698     if (base->tp_src == flow->tp_src &&
3699         base->tp_dst == flow->tp_dst) {
3700         return;
3701     }
3702
3703     if (flow->nw_proto == IPPROTO_TCP) {
3704         struct ovs_key_tcp port_key;
3705
3706         port_key.tcp_src = base->tp_src = flow->tp_src;
3707         port_key.tcp_dst = base->tp_dst = flow->tp_dst;
3708
3709         commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3710              OVS_KEY_ATTR_TCP, &port_key, sizeof(port_key));
3711
3712     } else if (flow->nw_proto == IPPROTO_UDP) {
3713         struct ovs_key_udp port_key;
3714
3715         port_key.udp_src = base->tp_src = flow->tp_src;
3716         port_key.udp_dst = base->tp_dst = flow->tp_dst;
3717
3718         commit_action__(odp_actions, OVS_ACTION_ATTR_SET,
3719              OVS_KEY_ATTR_UDP, &port_key, sizeof(port_key));
3720     }
3721 }
3722
3723 static void
3724 commit_priority_action(struct action_xlate_ctx *ctx)
3725 {
3726     if (ctx->base_priority == ctx->priority) {
3727         return;
3728     }
3729
3730     if (ctx->priority) {
3731         nl_msg_put_u32(ctx->odp_actions,
3732                         OVS_ACTION_ATTR_SET_PRIORITY, ctx->priority);
3733     } else {
3734         nl_msg_put_flag(ctx->odp_actions, OVS_ACTION_ATTR_POP_PRIORITY);
3735     }
3736     ctx->base_priority = ctx->priority;
3737 }
3738
3739 static void
3740 commit_odp_actions(struct action_xlate_ctx *ctx)
3741 {
3742     const struct flow *flow = &ctx->flow;
3743     struct flow *base = &ctx->base_flow;
3744     struct ofpbuf *odp_actions = ctx->odp_actions;
3745
3746     commit_set_tun_id_action(flow, base, odp_actions);
3747     commit_set_ether_addr_action(flow, base, odp_actions);
3748     commit_vlan_action(ctx, flow->vlan_tci);
3749     commit_set_nw_action(flow, base, odp_actions);
3750     commit_set_port_action(flow, base, odp_actions);
3751     commit_priority_action(ctx);
3752 }
3753
3754 static void
3755 compose_output_action(struct action_xlate_ctx *ctx, uint16_t odp_port)
3756 {
3757     nl_msg_put_u32(ctx->odp_actions, OVS_ACTION_ATTR_OUTPUT, odp_port);
3758     ctx->sflow_odp_port = odp_port;
3759     ctx->sflow_n_outputs++;
3760 }
3761
3762 static void
3763 add_output_action(struct action_xlate_ctx *ctx, uint16_t ofp_port)
3764 {
3765     const struct ofport_dpif *ofport = get_ofp_port(ctx->ofproto, ofp_port);
3766     uint16_t odp_port = ofp_port_to_odp_port(ofp_port);
3767
3768     if (ofport) {
3769         if (ofport->up.opp.config & htonl(OFPPC_NO_FWD)
3770                 || !stp_forward_in_state(ofport->stp_state)) {
3771             /* Forwarding disabled on port. */
3772             return;
3773         }
3774     } else {
3775         /*
3776          * We don't have an ofport record for this port, but it doesn't hurt to
3777          * allow forwarding to it anyhow.  Maybe such a port will appear later
3778          * and we're pre-populating the flow table.
3779          */
3780     }
3781
3782     commit_odp_actions(ctx);
3783     compose_output_action(ctx, odp_port);
3784     ctx->nf_output_iface = ofp_port;
3785 }
3786
3787 static void
3788 xlate_table_action(struct action_xlate_ctx *ctx,
3789                    uint16_t in_port, uint8_t table_id)
3790 {
3791     if (ctx->recurse < MAX_RESUBMIT_RECURSION) {
3792         struct ofproto_dpif *ofproto = ctx->ofproto;
3793         struct rule_dpif *rule;
3794         uint16_t old_in_port;
3795         uint8_t old_table_id;
3796
3797         old_table_id = ctx->table_id;
3798         ctx->table_id = table_id;
3799
3800         /* Look up a flow with 'in_port' as the input port. */
3801         old_in_port = ctx->flow.in_port;
3802         ctx->flow.in_port = in_port;
3803         rule = rule_dpif_lookup(ofproto, &ctx->flow, table_id);
3804
3805         /* Tag the flow. */
3806         if (table_id > 0 && table_id < N_TABLES) {
3807             struct table_dpif *table = &ofproto->tables[table_id];
3808             if (table->other_table) {
3809                 ctx->tags |= (rule
3810                               ? rule->tag
3811                               : rule_calculate_tag(&ctx->flow,
3812                                                    &table->other_table->wc,
3813                                                    table->basis));
3814             }
3815         }
3816
3817         /* Restore the original input port.  Otherwise OFPP_NORMAL and
3818          * OFPP_IN_PORT will have surprising behavior. */
3819         ctx->flow.in_port = old_in_port;
3820
3821         if (ctx->resubmit_hook) {
3822             ctx->resubmit_hook(ctx, rule);
3823         }
3824
3825         if (rule) {
3826             ctx->recurse++;
3827             do_xlate_actions(rule->up.actions, rule->up.n_actions, ctx);
3828             ctx->recurse--;
3829         }
3830
3831         ctx->table_id = old_table_id;
3832     } else {
3833         static struct vlog_rate_limit recurse_rl = VLOG_RATE_LIMIT_INIT(1, 1);
3834
3835         VLOG_ERR_RL(&recurse_rl, "resubmit actions recursed over %d times",
3836                     MAX_RESUBMIT_RECURSION);
3837     }
3838 }
3839
3840 static void
3841 xlate_resubmit_table(struct action_xlate_ctx *ctx,
3842                      const struct nx_action_resubmit *nar)
3843 {
3844     uint16_t in_port;
3845     uint8_t table_id;
3846
3847     in_port = (nar->in_port == htons(OFPP_IN_PORT)
3848                ? ctx->flow.in_port
3849                : ntohs(nar->in_port));
3850     table_id = nar->table == 255 ? ctx->table_id : nar->table;
3851
3852     xlate_table_action(ctx, in_port, table_id);
3853 }
3854
3855 static void
3856 flood_packets(struct action_xlate_ctx *ctx, ovs_be32 mask)
3857 {
3858     struct ofport_dpif *ofport;
3859
3860     commit_odp_actions(ctx);
3861     HMAP_FOR_EACH (ofport, up.hmap_node, &ctx->ofproto->up.ports) {
3862         uint16_t ofp_port = ofport->up.ofp_port;
3863         if (ofp_port != ctx->flow.in_port
3864                 && !(ofport->up.opp.config & mask)
3865                 && stp_forward_in_state(ofport->stp_state)) {
3866             compose_output_action(ctx, ofport->odp_port);
3867         }
3868     }
3869
3870     ctx->nf_output_iface = NF_OUT_FLOOD;
3871 }
3872
3873 static void
3874 compose_controller_action(struct action_xlate_ctx *ctx, int len)
3875 {
3876     struct user_action_cookie cookie;
3877
3878     cookie.type = USER_ACTION_COOKIE_CONTROLLER;
3879     cookie.data = len;
3880     cookie.n_output = 0;
3881     cookie.vlan_tci = 0;
3882     put_userspace_action(ctx->ofproto, ctx->odp_actions, &ctx->flow, &cookie);
3883 }
3884
3885 static void
3886 xlate_output_action__(struct action_xlate_ctx *ctx,
3887                       uint16_t port, uint16_t max_len)
3888 {
3889     uint16_t prev_nf_output_iface = ctx->nf_output_iface;
3890
3891     ctx->nf_output_iface = NF_OUT_DROP;
3892
3893     switch (port) {
3894     case OFPP_IN_PORT:
3895         add_output_action(ctx, ctx->flow.in_port);
3896         break;
3897     case OFPP_TABLE:
3898         xlate_table_action(ctx, ctx->flow.in_port, ctx->table_id);
3899         break;
3900     case OFPP_NORMAL:
3901         xlate_normal(ctx);
3902         break;
3903     case OFPP_FLOOD:
3904         flood_packets(ctx,  htonl(OFPPC_NO_FLOOD));
3905         break;
3906     case OFPP_ALL:
3907         flood_packets(ctx, htonl(0));
3908         break;
3909     case OFPP_CONTROLLER:
3910         commit_odp_actions(ctx);
3911         compose_controller_action(ctx, max_len);
3912         break;
3913     case OFPP_LOCAL:
3914         add_output_action(ctx, OFPP_LOCAL);
3915         break;
3916     case OFPP_NONE:
3917         break;
3918     default:
3919         if (port != ctx->flow.in_port) {
3920             add_output_action(ctx, port);
3921         }
3922         break;
3923     }
3924
3925     if (prev_nf_output_iface == NF_OUT_FLOOD) {
3926         ctx->nf_output_iface = NF_OUT_FLOOD;
3927     } else if (ctx->nf_output_iface == NF_OUT_DROP) {
3928         ctx->nf_output_iface = prev_nf_output_iface;
3929     } else if (prev_nf_output_iface != NF_OUT_DROP &&
3930                ctx->nf_output_iface != NF_OUT_FLOOD) {
3931         ctx->nf_output_iface = NF_OUT_MULTI;
3932     }
3933 }
3934
3935 static void
3936 xlate_output_reg_action(struct action_xlate_ctx *ctx,
3937                         const struct nx_action_output_reg *naor)
3938 {
3939     uint64_t ofp_port;
3940
3941     ofp_port = nxm_read_field_bits(naor->src, naor->ofs_nbits, &ctx->flow);
3942
3943     if (ofp_port <= UINT16_MAX) {
3944         xlate_output_action__(ctx, ofp_port, ntohs(naor->max_len));
3945     }
3946 }
3947
3948 static void
3949 xlate_output_action(struct action_xlate_ctx *ctx,
3950                     const struct ofp_action_output *oao)
3951 {
3952     xlate_output_action__(ctx, ntohs(oao->port), ntohs(oao->max_len));
3953 }
3954
3955 static void
3956 xlate_enqueue_action(struct action_xlate_ctx *ctx,
3957                      const struct ofp_action_enqueue *oae)
3958 {
3959     uint16_t ofp_port, odp_port;
3960     uint32_t ctx_priority, priority;
3961     int error;
3962
3963     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(oae->queue_id),
3964                                    &priority);
3965     if (error) {
3966         /* Fall back to ordinary output action. */
3967         xlate_output_action__(ctx, ntohs(oae->port), 0);
3968         return;
3969     }
3970
3971     /* Figure out datapath output port. */
3972     ofp_port = ntohs(oae->port);
3973     if (ofp_port == OFPP_IN_PORT) {
3974         ofp_port = ctx->flow.in_port;
3975     } else if (ofp_port == ctx->flow.in_port) {
3976         return;
3977     }
3978     odp_port = ofp_port_to_odp_port(ofp_port);
3979
3980     /* Add datapath actions. */
3981     ctx_priority = ctx->priority;
3982     ctx->priority = priority;
3983     add_output_action(ctx, odp_port);
3984     ctx->priority = ctx_priority;
3985
3986     /* Update NetFlow output port. */
3987     if (ctx->nf_output_iface == NF_OUT_DROP) {
3988         ctx->nf_output_iface = odp_port;
3989     } else if (ctx->nf_output_iface != NF_OUT_FLOOD) {
3990         ctx->nf_output_iface = NF_OUT_MULTI;
3991     }
3992 }
3993
3994 static void
3995 xlate_set_queue_action(struct action_xlate_ctx *ctx,
3996                        const struct nx_action_set_queue *nasq)
3997 {
3998     uint32_t priority;
3999     int error;
4000
4001     error = dpif_queue_to_priority(ctx->ofproto->dpif, ntohl(nasq->queue_id),
4002                                    &priority);
4003     if (error) {
4004         /* Couldn't translate queue to a priority, so ignore.  A warning
4005          * has already been logged. */
4006         return;
4007     }
4008
4009     ctx->priority = priority;
4010 }
4011
4012 struct xlate_reg_state {
4013     ovs_be16 vlan_tci;
4014     ovs_be64 tun_id;
4015 };
4016
4017 static void
4018 xlate_autopath(struct action_xlate_ctx *ctx,
4019                const struct nx_action_autopath *naa)
4020 {
4021     uint16_t ofp_port = ntohl(naa->id);
4022     struct ofport_dpif *port = get_ofp_port(ctx->ofproto, ofp_port);
4023
4024     if (!port || !port->bundle) {
4025         ofp_port = OFPP_NONE;
4026     } else if (port->bundle->bond) {
4027         /* Autopath does not support VLAN hashing. */
4028         struct ofport_dpif *slave = bond_choose_output_slave(
4029             port->bundle->bond, &ctx->flow, 0, &ctx->tags);
4030         if (slave) {
4031             ofp_port = slave->up.ofp_port;
4032         }
4033     }
4034     autopath_execute(naa, &ctx->flow, ofp_port);
4035 }
4036
4037 static bool
4038 slave_enabled_cb(uint16_t ofp_port, void *ofproto_)
4039 {
4040     struct ofproto_dpif *ofproto = ofproto_;
4041     struct ofport_dpif *port;
4042
4043     switch (ofp_port) {
4044     case OFPP_IN_PORT:
4045     case OFPP_TABLE:
4046     case OFPP_NORMAL:
4047     case OFPP_FLOOD:
4048     case OFPP_ALL:
4049     case OFPP_LOCAL:
4050         return true;
4051     case OFPP_CONTROLLER: /* Not supported by the bundle action. */
4052         return false;
4053     default:
4054         port = get_ofp_port(ofproto, ofp_port);
4055         return port ? port->may_enable : false;
4056     }
4057 }
4058
4059 static void
4060 xlate_learn_action(struct action_xlate_ctx *ctx,
4061                    const struct nx_action_learn *learn)
4062 {
4063     static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(5, 1);
4064     struct ofputil_flow_mod fm;
4065     int error;
4066
4067     learn_execute(learn, &ctx->flow, &fm);
4068
4069     error = ofproto_flow_mod(&ctx->ofproto->up, &fm);
4070     if (error && !VLOG_DROP_WARN(&rl)) {
4071         char *msg = ofputil_error_to_string(error);
4072         VLOG_WARN("learning action failed to modify flow table (%s)", msg);
4073         free(msg);
4074     }
4075
4076     free(fm.actions);
4077 }
4078
4079 static bool
4080 may_receive(const struct ofport_dpif *port, struct action_xlate_ctx *ctx)
4081 {
4082     if (port->up.opp.config & (eth_addr_equals(ctx->flow.dl_dst, eth_addr_stp)
4083                                ? htonl(OFPPC_NO_RECV_STP)
4084                                : htonl(OFPPC_NO_RECV))) {
4085         return false;
4086     }
4087
4088     /* Only drop packets here if both forwarding and learning are
4089      * disabled.  If just learning is enabled, we need to have
4090      * OFPP_NORMAL and the learning action have a look at the packet
4091      * before we can drop it. */
4092     if (!stp_forward_in_state(port->stp_state)
4093             && !stp_learn_in_state(port->stp_state)) {
4094         return false;
4095     }
4096
4097     return true;
4098 }
4099
4100 static void
4101 do_xlate_actions(const union ofp_action *in, size_t n_in,
4102                  struct action_xlate_ctx *ctx)
4103 {
4104     const struct ofport_dpif *port;
4105     const union ofp_action *ia;
4106     size_t left;
4107
4108     port = get_ofp_port(ctx->ofproto, ctx->flow.in_port);
4109     if (port && !may_receive(port, ctx)) {
4110         /* Drop this flow. */
4111         return;
4112     }
4113
4114     OFPUTIL_ACTION_FOR_EACH_UNSAFE (ia, left, in, n_in) {
4115         const struct ofp_action_dl_addr *oada;
4116         const struct nx_action_resubmit *nar;
4117         const struct nx_action_set_tunnel *nast;
4118         const struct nx_action_set_queue *nasq;
4119         const struct nx_action_multipath *nam;
4120         const struct nx_action_autopath *naa;
4121         const struct nx_action_bundle *nab;
4122         const struct nx_action_output_reg *naor;
4123         enum ofputil_action_code code;
4124         ovs_be64 tun_id;
4125
4126         code = ofputil_decode_action_unsafe(ia);
4127         switch (code) {
4128         case OFPUTIL_OFPAT_OUTPUT:
4129             xlate_output_action(ctx, &ia->output);
4130             break;
4131
4132         case OFPUTIL_OFPAT_SET_VLAN_VID:
4133             ctx->flow.vlan_tci &= ~htons(VLAN_VID_MASK);
4134             ctx->flow.vlan_tci |= ia->vlan_vid.vlan_vid | htons(VLAN_CFI);
4135             break;
4136
4137         case OFPUTIL_OFPAT_SET_VLAN_PCP:
4138             ctx->flow.vlan_tci &= ~htons(VLAN_PCP_MASK);
4139             ctx->flow.vlan_tci |= htons(
4140                 (ia->vlan_pcp.vlan_pcp << VLAN_PCP_SHIFT) | VLAN_CFI);
4141             break;
4142
4143         case OFPUTIL_OFPAT_STRIP_VLAN:
4144             ctx->flow.vlan_tci = htons(0);
4145             break;
4146
4147         case OFPUTIL_OFPAT_SET_DL_SRC:
4148             oada = ((struct ofp_action_dl_addr *) ia);
4149             memcpy(ctx->flow.dl_src, oada->dl_addr, ETH_ADDR_LEN);
4150             break;
4151
4152         case OFPUTIL_OFPAT_SET_DL_DST:
4153             oada = ((struct ofp_action_dl_addr *) ia);
4154             memcpy(ctx->flow.dl_dst, oada->dl_addr, ETH_ADDR_LEN);
4155             break;
4156
4157         case OFPUTIL_OFPAT_SET_NW_SRC:
4158             ctx->flow.nw_src = ia->nw_addr.nw_addr;
4159             break;
4160
4161         case OFPUTIL_OFPAT_SET_NW_DST:
4162             ctx->flow.nw_dst = ia->nw_addr.nw_addr;
4163             break;
4164
4165         case OFPUTIL_OFPAT_SET_NW_TOS:
4166             ctx->flow.tos_frag &= ~IP_DSCP_MASK;
4167             ctx->flow.tos_frag |= ia->nw_tos.nw_tos & IP_DSCP_MASK;
4168             break;
4169
4170         case OFPUTIL_OFPAT_SET_TP_SRC:
4171             ctx->flow.tp_src = ia->tp_port.tp_port;
4172             break;
4173
4174         case OFPUTIL_OFPAT_SET_TP_DST:
4175             ctx->flow.tp_dst = ia->tp_port.tp_port;
4176             break;
4177
4178         case OFPUTIL_OFPAT_ENQUEUE:
4179             xlate_enqueue_action(ctx, (const struct ofp_action_enqueue *) ia);
4180             break;
4181
4182         case OFPUTIL_NXAST_RESUBMIT:
4183             nar = (const struct nx_action_resubmit *) ia;
4184             xlate_table_action(ctx, ntohs(nar->in_port), ctx->table_id);
4185             break;
4186
4187         case OFPUTIL_NXAST_RESUBMIT_TABLE:
4188             xlate_resubmit_table(ctx, (const struct nx_action_resubmit *) ia);
4189             break;
4190
4191         case OFPUTIL_NXAST_SET_TUNNEL:
4192             nast = (const struct nx_action_set_tunnel *) ia;
4193             tun_id = htonll(ntohl(nast->tun_id));
4194             ctx->flow.tun_id = tun_id;
4195             break;
4196
4197         case OFPUTIL_NXAST_SET_QUEUE:
4198             nasq = (const struct nx_action_set_queue *) ia;
4199             xlate_set_queue_action(ctx, nasq);
4200             break;
4201
4202         case OFPUTIL_NXAST_POP_QUEUE:
4203             ctx->priority = 0;
4204             break;
4205
4206         case OFPUTIL_NXAST_REG_MOVE:
4207             nxm_execute_reg_move((const struct nx_action_reg_move *) ia,
4208                                  &ctx->flow);
4209             break;
4210
4211         case OFPUTIL_NXAST_REG_LOAD:
4212             nxm_execute_reg_load((const struct nx_action_reg_load *) ia,
4213                                  &ctx->flow);
4214             break;
4215
4216         case OFPUTIL_NXAST_NOTE:
4217             /* Nothing to do. */
4218             break;
4219
4220         case OFPUTIL_NXAST_SET_TUNNEL64:
4221             tun_id = ((const struct nx_action_set_tunnel64 *) ia)->tun_id;
4222             ctx->flow.tun_id = tun_id;
4223             break;
4224
4225         case OFPUTIL_NXAST_MULTIPATH:
4226             nam = (const struct nx_action_multipath *) ia;
4227             multipath_execute(nam, &ctx->flow);
4228             break;
4229
4230         case OFPUTIL_NXAST_AUTOPATH:
4231             naa = (const struct nx_action_autopath *) ia;
4232             xlate_autopath(ctx, naa);
4233             break;
4234
4235         case OFPUTIL_NXAST_BUNDLE:
4236             ctx->ofproto->has_bundle_action = true;
4237             nab = (const struct nx_action_bundle *) ia;
4238             xlate_output_action__(ctx, bundle_execute(nab, &ctx->flow,
4239                                                       slave_enabled_cb,
4240                                                       ctx->ofproto), 0);
4241             break;
4242
4243         case OFPUTIL_NXAST_BUNDLE_LOAD:
4244             ctx->ofproto->has_bundle_action = true;
4245             nab = (const struct nx_action_bundle *) ia;
4246             bundle_execute_load(nab, &ctx->flow, slave_enabled_cb,
4247                                 ctx->ofproto);
4248             break;
4249
4250         case OFPUTIL_NXAST_OUTPUT_REG:
4251             naor = (const struct nx_action_output_reg *) ia;
4252             xlate_output_reg_action(ctx, naor);
4253             break;
4254
4255         case OFPUTIL_NXAST_LEARN:
4256             ctx->has_learn = true;
4257             if (ctx->may_learn) {
4258                 xlate_learn_action(ctx, (const struct nx_action_learn *) ia);
4259             }
4260             break;
4261         }
4262     }
4263
4264     /* We've let OFPP_NORMAL and the learning action look at the packet,
4265      * so drop it now if forwarding is disabled. */
4266     if (port && !stp_forward_in_state(port->stp_state)) {
4267         ofpbuf_clear(ctx->odp_actions);
4268         add_sflow_action(ctx);
4269     }
4270 }
4271
4272 static void
4273 action_xlate_ctx_init(struct action_xlate_ctx *ctx,
4274                       struct ofproto_dpif *ofproto, const struct flow *flow,
4275                       const struct ofpbuf *packet)
4276 {
4277     ctx->ofproto = ofproto;
4278     ctx->flow = *flow;
4279     ctx->packet = packet;
4280     ctx->may_learn = packet != NULL;
4281     ctx->resubmit_hook = NULL;
4282 }
4283
4284 static struct ofpbuf *
4285 xlate_actions(struct action_xlate_ctx *ctx,
4286               const union ofp_action *in, size_t n_in)
4287 {
4288     COVERAGE_INC(ofproto_dpif_xlate);
4289
4290     ctx->odp_actions = ofpbuf_new(512);
4291     ofpbuf_reserve(ctx->odp_actions, NL_A_U32_SIZE);
4292     ctx->tags = 0;
4293     ctx->may_set_up_flow = true;
4294     ctx->has_learn = false;
4295     ctx->has_normal = false;
4296     ctx->nf_output_iface = NF_OUT_DROP;
4297     ctx->recurse = 0;
4298     ctx->priority = 0;
4299     ctx->base_priority = 0;
4300     ctx->base_flow = ctx->flow;
4301     ctx->base_flow.tun_id = 0;
4302     ctx->table_id = 0;
4303
4304     if (ctx->flow.tos_frag & FLOW_FRAG_ANY) {
4305         switch (ctx->ofproto->up.frag_handling) {
4306         case OFPC_FRAG_NORMAL:
4307             /* We must pretend that transport ports are unavailable. */
4308             ctx->flow.tp_src = ctx->base_flow.tp_src = htons(0);
4309             ctx->flow.tp_dst = ctx->base_flow.tp_dst = htons(0);
4310             break;
4311
4312         case OFPC_FRAG_DROP:
4313             return ctx->odp_actions;
4314
4315         case OFPC_FRAG_REASM:
4316             NOT_REACHED();
4317
4318         case OFPC_FRAG_NX_MATCH:
4319             /* Nothing to do. */
4320             break;
4321         }
4322     }
4323
4324     if (process_special(ctx->ofproto, &ctx->flow, ctx->packet)) {
4325         ctx->may_set_up_flow = false;
4326         return ctx->odp_actions;
4327     } else {
4328         add_sflow_action(ctx);
4329         do_xlate_actions(in, n_in, ctx);
4330
4331         if (!connmgr_may_set_up_flow(ctx->ofproto->up.connmgr, &ctx->flow,
4332                                      ctx->odp_actions->data,
4333                                      ctx->odp_actions->size)) {
4334             ctx->may_set_up_flow = false;
4335             if (ctx->packet
4336                 && connmgr_msg_in_hook(ctx->ofproto->up.connmgr, &ctx->flow,
4337                                        ctx->packet)) {
4338                 compose_output_action(ctx, OVSP_LOCAL);
4339             }
4340         }
4341         fix_sflow_action(ctx);
4342     }
4343
4344     return ctx->odp_actions;
4345 }
4346 \f
4347 /* OFPP_NORMAL implementation. */
4348
4349 struct dst {
4350     struct ofport_dpif *port;
4351     uint16_t vid;
4352 };
4353
4354 struct dst_set {
4355     struct dst builtin[32];
4356     struct dst *dsts;
4357     size_t n, allocated;
4358 };
4359
4360 static void dst_set_init(struct dst_set *);
4361 static void dst_set_add(struct dst_set *, const struct dst *);
4362 static void dst_set_free(struct dst_set *);
4363
4364 static struct ofport_dpif *ofbundle_get_a_port(const struct ofbundle *);
4365
4366 /* Given 'vid', the VID obtained from the 802.1Q header that was received as
4367  * part of a packet (specify 0 if there was no 802.1Q header), and 'in_bundle',
4368  * the bundle on which the packet was received, returns the VLAN to which the
4369  * packet belongs.
4370  *
4371  * Both 'vid' and the return value are in the range 0...4095. */
4372 static uint16_t
4373 input_vid_to_vlan(const struct ofbundle *in_bundle, uint16_t vid)
4374 {
4375     switch (in_bundle->vlan_mode) {
4376     case PORT_VLAN_ACCESS:
4377         return in_bundle->vlan;
4378         break;
4379
4380     case PORT_VLAN_TRUNK:
4381         return vid;
4382
4383     case PORT_VLAN_NATIVE_UNTAGGED:
4384     case PORT_VLAN_NATIVE_TAGGED:
4385         return vid ? vid : in_bundle->vlan;
4386
4387     default:
4388         NOT_REACHED();
4389     }
4390 }
4391
4392 /* Given 'vlan', the VLAN that a packet belongs to, and
4393  * 'out_bundle', a bundle on which the packet is to be output, returns the VID
4394  * that should be included in the 802.1Q header.  (If the return value is 0,
4395  * then the 802.1Q header should only be included in the packet if there is a
4396  * nonzero PCP.)
4397  *
4398  * Both 'vlan' and the return value are in the range 0...4095. */
4399 static uint16_t
4400 output_vlan_to_vid(const struct ofbundle *out_bundle, uint16_t vlan)
4401 {
4402     switch (out_bundle->vlan_mode) {
4403     case PORT_VLAN_ACCESS:
4404         return 0;
4405
4406     case PORT_VLAN_TRUNK:
4407     case PORT_VLAN_NATIVE_TAGGED:
4408         return vlan;
4409
4410     case PORT_VLAN_NATIVE_UNTAGGED:
4411         return vlan == out_bundle->vlan ? 0 : vlan;
4412
4413     default:
4414         NOT_REACHED();
4415     }
4416 }
4417
4418 static bool
4419 set_dst(struct action_xlate_ctx *ctx, struct dst *dst,
4420         const struct ofbundle *in_bundle, const struct ofbundle *out_bundle)
4421 {
4422     uint16_t vlan;
4423
4424     vlan = input_vid_to_vlan(in_bundle, vlan_tci_to_vid(ctx->flow.vlan_tci));
4425     dst->vid = output_vlan_to_vid(out_bundle, vlan);
4426
4427     dst->port = (!out_bundle->bond
4428                  ? ofbundle_get_a_port(out_bundle)
4429                  : bond_choose_output_slave(out_bundle->bond, &ctx->flow,
4430                                             dst->vid, &ctx->tags));
4431     return dst->port != NULL;
4432 }
4433
4434 static int
4435 mirror_mask_ffs(mirror_mask_t mask)
4436 {
4437     BUILD_ASSERT_DECL(sizeof(unsigned int) >= sizeof(mask));
4438     return ffs(mask);
4439 }
4440
4441 static void
4442 dst_set_init(struct dst_set *set)
4443 {
4444     set->dsts = set->builtin;
4445     set->n = 0;
4446     set->allocated = ARRAY_SIZE(set->builtin);
4447 }
4448
4449 static void
4450 dst_set_add(struct dst_set *set, const struct dst *dst)
4451 {
4452     if (set->n >= set->allocated) {
4453         size_t new_allocated;
4454         struct dst *new_dsts;
4455
4456         new_allocated = set->allocated * 2;
4457         new_dsts = xmalloc(new_allocated * sizeof *new_dsts);
4458         memcpy(new_dsts, set->dsts, set->n * sizeof *new_dsts);
4459
4460         dst_set_free(set);
4461
4462         set->dsts = new_dsts;
4463         set->allocated = new_allocated;
4464     }
4465     set->dsts[set->n++] = *dst;
4466 }
4467
4468 static void
4469 dst_set_free(struct dst_set *set)
4470 {
4471     if (set->dsts != set->builtin) {
4472         free(set->dsts);
4473     }
4474 }
4475
4476 static bool
4477 dst_is_duplicate(const struct dst_set *set, const struct dst *test)
4478 {
4479     size_t i;
4480     for (i = 0; i < set->n; i++) {
4481         if (set->dsts[i].vid == test->vid
4482             && set->dsts[i].port == test->port) {
4483             return true;
4484         }
4485     }
4486     return false;
4487 }
4488
4489 static bool
4490 ofbundle_trunks_vlan(const struct ofbundle *bundle, uint16_t vlan)
4491 {
4492     return (bundle->vlan_mode != PORT_VLAN_ACCESS
4493             && (!bundle->trunks || bitmap_is_set(bundle->trunks, vlan)));
4494 }
4495
4496 static bool
4497 ofbundle_includes_vlan(const struct ofbundle *bundle, uint16_t vlan)
4498 {
4499     return vlan == bundle->vlan || ofbundle_trunks_vlan(bundle, vlan);
4500 }
4501
4502 /* Returns an arbitrary interface within 'bundle'. */
4503 static struct ofport_dpif *
4504 ofbundle_get_a_port(const struct ofbundle *bundle)
4505 {
4506     return CONTAINER_OF(list_front(&bundle->ports),
4507                         struct ofport_dpif, bundle_node);
4508 }
4509
4510 static void
4511 compose_dsts(struct action_xlate_ctx *ctx, uint16_t vlan,
4512              const struct ofbundle *in_bundle,
4513              const struct ofbundle *out_bundle, struct dst_set *set)
4514 {
4515     struct dst dst;
4516
4517     if (out_bundle == OFBUNDLE_FLOOD) {
4518         struct ofbundle *bundle;
4519
4520         HMAP_FOR_EACH (bundle, hmap_node, &ctx->ofproto->bundles) {
4521             if (bundle != in_bundle
4522                 && ofbundle_includes_vlan(bundle, vlan)
4523                 && bundle->floodable
4524                 && !bundle->mirror_out
4525                 && set_dst(ctx, &dst, in_bundle, bundle)) {
4526                 dst_set_add(set, &dst);
4527             }
4528         }
4529         ctx->nf_output_iface = NF_OUT_FLOOD;
4530     } else if (out_bundle && set_dst(ctx, &dst, in_bundle, out_bundle)) {
4531         dst_set_add(set, &dst);
4532         ctx->nf_output_iface = dst.port->odp_port;
4533     }
4534 }
4535
4536 static bool
4537 vlan_is_mirrored(const struct ofmirror *m, int vlan)
4538 {
4539     return !m->vlans || bitmap_is_set(m->vlans, vlan);
4540 }
4541
4542 /* Returns true if a packet with Ethernet destination MAC 'dst' may be mirrored
4543  * to a VLAN.  In general most packets may be mirrored but we want to drop
4544  * protocols that may confuse switches. */
4545 static bool
4546 eth_dst_may_rspan(const uint8_t dst[ETH_ADDR_LEN])
4547 {
4548     /* If you change this function's behavior, please update corresponding
4549      * documentation in vswitch.xml at the same time. */
4550     if (dst[0] != 0x01) {
4551         /* All the currently banned MACs happen to start with 01 currently, so
4552          * this is a quick way to eliminate most of the good ones. */
4553     } else {
4554         if (eth_addr_is_reserved(dst)) {
4555             /* Drop STP, IEEE pause frames, and other reserved protocols
4556              * (01-80-c2-00-00-0x). */
4557             return false;
4558         }
4559
4560         if (dst[0] == 0x01 && dst[1] == 0x00 && dst[2] == 0x0c) {
4561             /* Cisco OUI. */
4562             if ((dst[3] & 0xfe) == 0xcc &&
4563                 (dst[4] & 0xfe) == 0xcc &&
4564                 (dst[5] & 0xfe) == 0xcc) {
4565                 /* Drop the following protocols plus others following the same
4566                    pattern:
4567
4568                    CDP, VTP, DTP, PAgP  (01-00-0c-cc-cc-cc)
4569                    Spanning Tree PVSTP+ (01-00-0c-cc-cc-cd)
4570                    STP Uplink Fast      (01-00-0c-cd-cd-cd) */
4571                 return false;
4572             }
4573
4574             if (!(dst[3] | dst[4] | dst[5])) {
4575                 /* Drop Inter Switch Link packets (01-00-0c-00-00-00). */
4576                 return false;
4577             }
4578         }
4579     }
4580     return true;
4581 }
4582
4583 static void
4584 compose_mirror_dsts(struct action_xlate_ctx *ctx,
4585                     uint16_t vlan, const struct ofbundle *in_bundle,
4586                     struct dst_set *set)
4587 {
4588     struct ofproto_dpif *ofproto = ctx->ofproto;
4589     mirror_mask_t mirrors;
4590     uint16_t flow_vid;
4591     size_t i;
4592
4593     mirrors = in_bundle->src_mirrors;
4594     for (i = 0; i < set->n; i++) {
4595         mirrors |= set->dsts[i].port->bundle->dst_mirrors;
4596     }
4597
4598     if (!mirrors) {
4599         return;
4600     }
4601
4602     flow_vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
4603     while (mirrors) {
4604         struct ofmirror *m = ofproto->mirrors[mirror_mask_ffs(mirrors) - 1];
4605         if (vlan_is_mirrored(m, vlan)) {
4606             struct dst dst;
4607
4608             if (m->out) {
4609                 if (set_dst(ctx, &dst, in_bundle, m->out)
4610                     && !dst_is_duplicate(set, &dst)) {
4611                     dst_set_add(set, &dst);
4612                 }
4613             } else if (eth_dst_may_rspan(ctx->flow.dl_dst)) {
4614                 struct ofbundle *bundle;
4615
4616                 HMAP_FOR_EACH (bundle, hmap_node, &ofproto->bundles) {
4617                     if (ofbundle_includes_vlan(bundle, m->out_vlan)
4618                         && set_dst(ctx, &dst, in_bundle, bundle))
4619                     {
4620                         /* set_dst() got dst->vid from the input packet's VLAN,
4621                          * not from m->out_vlan, so recompute it. */
4622                         dst.vid = output_vlan_to_vid(bundle, m->out_vlan);
4623
4624                         if (dst_is_duplicate(set, &dst)) {
4625                             continue;
4626                         }
4627
4628                         if (bundle == in_bundle && dst.vid == flow_vid) {
4629                             /* Don't send out input port on same VLAN. */
4630                             continue;
4631                         }
4632                         dst_set_add(set, &dst);
4633                     }
4634                 }
4635             }
4636         }
4637         mirrors &= mirrors - 1;
4638     }
4639 }
4640
4641 static void
4642 compose_actions(struct action_xlate_ctx *ctx, uint16_t vlan,
4643                 const struct ofbundle *in_bundle,
4644                 const struct ofbundle *out_bundle)
4645 {
4646     uint16_t initial_vid, cur_vid;
4647     const struct dst *dst;
4648     struct dst_set set;
4649
4650     dst_set_init(&set);
4651     compose_dsts(ctx, vlan, in_bundle, out_bundle, &set);
4652     compose_mirror_dsts(ctx, vlan, in_bundle, &set);
4653     if (!set.n) {
4654         dst_set_free(&set);
4655         return;
4656     }
4657
4658     /* Output all the packets we can without having to change the VLAN. */
4659     commit_odp_actions(ctx);
4660     initial_vid = vlan_tci_to_vid(ctx->flow.vlan_tci);
4661     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
4662         if (dst->vid != initial_vid) {
4663             continue;
4664         }
4665         compose_output_action(ctx, dst->port->odp_port);
4666     }
4667
4668     /* Then output the rest. */
4669     cur_vid = initial_vid;
4670     for (dst = set.dsts; dst < &set.dsts[set.n]; dst++) {
4671         if (dst->vid == initial_vid) {
4672             continue;
4673         }
4674         if (dst->vid != cur_vid) {
4675             ovs_be16 tci;
4676
4677             tci = htons(dst->vid);
4678             tci |= ctx->flow.vlan_tci & htons(VLAN_PCP_MASK);
4679             if (tci) {
4680                 tci |= htons(VLAN_CFI);
4681             }
4682             commit_vlan_action(ctx, tci);
4683
4684             cur_vid = dst->vid;
4685         }
4686         compose_output_action(ctx, dst->port->odp_port);
4687     }
4688
4689     dst_set_free(&set);
4690 }
4691
4692 /* Returns the effective vlan of a packet, taking into account both the
4693  * 802.1Q header and implicitly tagged ports.  A value of 0 indicates that
4694  * the packet is untagged and -1 indicates it has an invalid header and
4695  * should be dropped. */
4696 static int
4697 flow_get_vlan(struct ofproto_dpif *ofproto, const struct flow *flow,
4698               struct ofbundle *in_bundle, bool have_packet)
4699 {
4700     int vlan = vlan_tci_to_vid(flow->vlan_tci);
4701     if (vlan) {
4702         if (in_bundle->vlan_mode == PORT_VLAN_ACCESS) {
4703             /* Drop tagged packet on access port */
4704             if (have_packet) {
4705                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4706                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
4707                              "packet received on port %s configured with "
4708                              "implicit VLAN %"PRIu16,
4709                              ofproto->up.name, vlan,
4710                              in_bundle->name, in_bundle->vlan);
4711             }
4712             return -1;
4713         } else if (ofbundle_includes_vlan(in_bundle, vlan)) {
4714             return vlan;
4715         } else {
4716             /* Drop packets from a VLAN not member of the trunk */
4717             if (have_packet) {
4718                 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4719                 VLOG_WARN_RL(&rl, "bridge %s: dropping VLAN %d tagged "
4720                              "packet received on port %s not configured for "
4721                              "trunking VLAN %d",
4722                              ofproto->up.name, vlan, in_bundle->name, vlan);
4723             }
4724             return -1;
4725         }
4726     } else {
4727         if (in_bundle->vlan_mode != PORT_VLAN_TRUNK) {
4728             return in_bundle->vlan;
4729         } else {
4730             return ofbundle_includes_vlan(in_bundle, 0) ? 0 : -1;
4731         }
4732     }
4733 }
4734
4735 /* A VM broadcasts a gratuitous ARP to indicate that it has resumed after
4736  * migration.  Older Citrix-patched Linux DomU used gratuitous ARP replies to
4737  * indicate this; newer upstream kernels use gratuitous ARP requests. */
4738 static bool
4739 is_gratuitous_arp(const struct flow *flow)
4740 {
4741     return (flow->dl_type == htons(ETH_TYPE_ARP)
4742             && eth_addr_is_broadcast(flow->dl_dst)
4743             && (flow->nw_proto == ARP_OP_REPLY
4744                 || (flow->nw_proto == ARP_OP_REQUEST
4745                     && flow->nw_src == flow->nw_dst)));
4746 }
4747
4748 static void
4749 update_learning_table(struct ofproto_dpif *ofproto,
4750                       const struct flow *flow, int vlan,
4751                       struct ofbundle *in_bundle)
4752 {
4753     struct mac_entry *mac;
4754
4755     if (!mac_learning_may_learn(ofproto->ml, flow->dl_src, vlan)) {
4756         return;
4757     }
4758
4759     mac = mac_learning_insert(ofproto->ml, flow->dl_src, vlan);
4760     if (is_gratuitous_arp(flow)) {
4761         /* We don't want to learn from gratuitous ARP packets that are
4762          * reflected back over bond slaves so we lock the learning table. */
4763         if (!in_bundle->bond) {
4764             mac_entry_set_grat_arp_lock(mac);
4765         } else if (mac_entry_is_grat_arp_locked(mac)) {
4766             return;
4767         }
4768     }
4769
4770     if (mac_entry_is_new(mac) || mac->port.p != in_bundle) {
4771         /* The log messages here could actually be useful in debugging,
4772          * so keep the rate limit relatively high. */
4773         static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(30, 300);
4774         VLOG_DBG_RL(&rl, "bridge %s: learned that "ETH_ADDR_FMT" is "
4775                     "on port %s in VLAN %d",
4776                     ofproto->up.name, ETH_ADDR_ARGS(flow->dl_src),
4777                     in_bundle->name, vlan);
4778
4779         mac->port.p = in_bundle;
4780         tag_set_add(&ofproto->revalidate_set,
4781                     mac_learning_changed(ofproto->ml, mac));
4782     }
4783 }
4784
4785 /* Determines whether packets in 'flow' within 'br' should be forwarded or
4786  * dropped.  Returns true if they may be forwarded, false if they should be
4787  * dropped.
4788  *
4789  * If 'have_packet' is true, it indicates that the caller is processing a
4790  * received packet.  If 'have_packet' is false, then the caller is just
4791  * revalidating an existing flow because configuration has changed.  Either
4792  * way, 'have_packet' only affects logging (there is no point in logging errors
4793  * during revalidation).
4794  *
4795  * Sets '*in_portp' to the input port.  This will be a null pointer if
4796  * flow->in_port does not designate a known input port (in which case
4797  * is_admissible() returns false).
4798  *
4799  * When returning true, sets '*vlanp' to the effective VLAN of the input
4800  * packet, as returned by flow_get_vlan().
4801  *
4802  * May also add tags to '*tags', although the current implementation only does
4803  * so in one special case.
4804  */
4805 static bool
4806 is_admissible(struct ofproto_dpif *ofproto, const struct flow *flow,
4807               bool have_packet,
4808               tag_type *tags, int *vlanp, struct ofbundle **in_bundlep)
4809 {
4810     struct ofport_dpif *in_port;
4811     struct ofbundle *in_bundle;
4812     int vlan;
4813
4814     /* Find the port and bundle for the received packet. */
4815     in_port = get_ofp_port(ofproto, flow->in_port);
4816     *in_bundlep = in_bundle = in_port ? in_port->bundle : NULL;
4817     if (!in_port || !in_bundle) {
4818         /* No interface?  Something fishy... */
4819         if (have_packet) {
4820             /* Odd.  A few possible reasons here:
4821              *
4822              * - We deleted a port but there are still a few packets queued up
4823              *   from it.
4824              *
4825              * - Someone externally added a port (e.g. "ovs-dpctl add-if") that
4826              *   we don't know about.
4827              *
4828              * - Packet arrived on the local port but the local port is not
4829              *   part of a bundle.
4830              */
4831             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4832
4833             VLOG_WARN_RL(&rl, "bridge %s: received packet on unknown "
4834                          "port %"PRIu16,
4835                          ofproto->up.name, flow->in_port);
4836         }
4837         *vlanp = -1;
4838         return false;
4839     }
4840     *vlanp = vlan = flow_get_vlan(ofproto, flow, in_bundle, have_packet);
4841     if (vlan < 0) {
4842         return false;
4843     }
4844
4845     /* Drop frames for reserved multicast addresses only if forward_bpdu
4846      * option is absent. */
4847     if (eth_addr_is_reserved(flow->dl_dst) && !ofproto->up.forward_bpdu) {
4848         return false;
4849     }
4850
4851     /* Drop frames on bundles reserved for mirroring. */
4852     if (in_bundle->mirror_out) {
4853         if (have_packet) {
4854             static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
4855             VLOG_WARN_RL(&rl, "bridge %s: dropping packet received on port "
4856                          "%s, which is reserved exclusively for mirroring",
4857                          ofproto->up.name, in_bundle->name);
4858         }
4859         return false;
4860     }
4861
4862     if (in_bundle->bond) {
4863         struct mac_entry *mac;
4864
4865         switch (bond_check_admissibility(in_bundle->bond, in_port,
4866                                          flow->dl_dst, tags)) {
4867         case BV_ACCEPT:
4868             break;
4869
4870         case BV_DROP:
4871             return false;
4872
4873         case BV_DROP_IF_MOVED:
4874             mac = mac_learning_lookup(ofproto->ml, flow->dl_src, vlan, NULL);
4875             if (mac && mac->port.p != in_bundle &&
4876                 (!is_gratuitous_arp(flow)
4877                  || mac_entry_is_grat_arp_locked(mac))) {
4878                 return false;
4879             }
4880             break;
4881         }
4882     }
4883
4884     return true;
4885 }
4886
4887 static void
4888 xlate_normal(struct action_xlate_ctx *ctx)
4889 {
4890     struct ofbundle *in_bundle;
4891     struct ofbundle *out_bundle;
4892     struct mac_entry *mac;
4893     int vlan;
4894
4895     ctx->has_normal = true;
4896
4897     /* Check whether we should drop packets in this flow. */
4898     if (!is_admissible(ctx->ofproto, &ctx->flow, ctx->packet != NULL,
4899                        &ctx->tags, &vlan, &in_bundle)) {
4900         out_bundle = NULL;
4901         goto done;
4902     }
4903
4904     /* Learn source MAC. */
4905     if (ctx->may_learn) {
4906         update_learning_table(ctx->ofproto, &ctx->flow, vlan, in_bundle);
4907     }
4908
4909     /* Determine output bundle. */
4910     mac = mac_learning_lookup(ctx->ofproto->ml, ctx->flow.dl_dst, vlan,
4911                               &ctx->tags);
4912     if (mac) {
4913         out_bundle = mac->port.p;
4914     } else if (!ctx->packet && !eth_addr_is_multicast(ctx->flow.dl_dst)) {
4915         /* If we are revalidating but don't have a learning entry then eject
4916          * the flow.  Installing a flow that floods packets opens up a window
4917          * of time where we could learn from a packet reflected on a bond and
4918          * blackhole packets before the learning table is updated to reflect
4919          * the correct port. */
4920         ctx->may_set_up_flow = false;
4921         return;
4922     } else {
4923         out_bundle = OFBUNDLE_FLOOD;
4924     }
4925
4926     /* Don't send packets out their input bundles. */
4927     if (in_bundle == out_bundle) {
4928         out_bundle = NULL;
4929     }
4930
4931 done:
4932     if (in_bundle) {
4933         compose_actions(ctx, vlan, in_bundle, out_bundle);
4934     }
4935 }
4936 \f
4937 /* Optimized flow revalidation.
4938  *
4939  * It's a difficult problem, in general, to tell which facets need to have
4940  * their actions recalculated whenever the OpenFlow flow table changes.  We
4941  * don't try to solve that general problem: for most kinds of OpenFlow flow
4942  * table changes, we recalculate the actions for every facet.  This is
4943  * relatively expensive, but it's good enough if the OpenFlow flow table
4944  * doesn't change very often.
4945  *
4946  * However, we can expect one particular kind of OpenFlow flow table change to
4947  * happen frequently: changes caused by MAC learning.  To avoid wasting a lot
4948  * of CPU on revalidating every facet whenever MAC learning modifies the flow
4949  * table, we add a special case that applies to flow tables in which every rule
4950  * has the same form (that is, the same wildcards), except that the table is
4951  * also allowed to have a single "catch-all" flow that matches all packets.  We
4952  * optimize this case by tagging all of the facets that resubmit into the table
4953  * and invalidating the same tag whenever a flow changes in that table.  The
4954  * end result is that we revalidate just the facets that need it (and sometimes
4955  * a few more, but not all of the facets or even all of the facets that
4956  * resubmit to the table modified by MAC learning). */
4957
4958 /* Calculates the tag to use for 'flow' and wildcards 'wc' when it is inserted
4959  * into an OpenFlow table with the given 'basis'. */
4960 static uint32_t
4961 rule_calculate_tag(const struct flow *flow, const struct flow_wildcards *wc,
4962                    uint32_t secret)
4963 {
4964     if (flow_wildcards_is_catchall(wc)) {
4965         return 0;
4966     } else {
4967         struct flow tag_flow = *flow;
4968         flow_zero_wildcards(&tag_flow, wc);
4969         return tag_create_deterministic(flow_hash(&tag_flow, secret));
4970     }
4971 }
4972
4973 /* Following a change to OpenFlow table 'table_id' in 'ofproto', update the
4974  * taggability of that table.
4975  *
4976  * This function must be called after *each* change to a flow table.  If you
4977  * skip calling it on some changes then the pointer comparisons at the end can
4978  * be invalid if you get unlucky.  For example, if a flow removal causes a
4979  * cls_table to be destroyed and then a flow insertion causes a cls_table with
4980  * different wildcards to be created with the same address, then this function
4981  * will incorrectly skip revalidation. */
4982 static void
4983 table_update_taggable(struct ofproto_dpif *ofproto, uint8_t table_id)
4984 {
4985     struct table_dpif *table = &ofproto->tables[table_id];
4986     const struct classifier *cls = &ofproto->up.tables[table_id];
4987     struct cls_table *catchall, *other;
4988     struct cls_table *t;
4989
4990     catchall = other = NULL;
4991
4992     switch (hmap_count(&cls->tables)) {
4993     case 0:
4994         /* We could tag this OpenFlow table but it would make the logic a
4995          * little harder and it's a corner case that doesn't seem worth it
4996          * yet. */
4997         break;
4998
4999     case 1:
5000     case 2:
5001         HMAP_FOR_EACH (t, hmap_node, &cls->tables) {
5002             if (cls_table_is_catchall(t)) {
5003                 catchall = t;
5004             } else if (!other) {
5005                 other = t;
5006             } else {
5007                 /* Indicate that we can't tag this by setting both tables to
5008                  * NULL.  (We know that 'catchall' is already NULL.) */
5009                 other = NULL;
5010             }
5011         }
5012         break;
5013
5014     default:
5015         /* Can't tag this table. */
5016         break;
5017     }
5018
5019     if (table->catchall_table != catchall || table->other_table != other) {
5020         table->catchall_table = catchall;
5021         table->other_table = other;
5022         ofproto->need_revalidate = true;
5023     }
5024 }
5025
5026 /* Given 'rule' that has changed in some way (either it is a rule being
5027  * inserted, a rule being deleted, or a rule whose actions are being
5028  * modified), marks facets for revalidation to ensure that packets will be
5029  * forwarded correctly according to the new state of the flow table.
5030  *
5031  * This function must be called after *each* change to a flow table.  See
5032  * the comment on table_update_taggable() for more information. */
5033 static void
5034 rule_invalidate(const struct rule_dpif *rule)
5035 {
5036     struct ofproto_dpif *ofproto = ofproto_dpif_cast(rule->up.ofproto);
5037
5038     table_update_taggable(ofproto, rule->up.table_id);
5039
5040     if (!ofproto->need_revalidate) {
5041         struct table_dpif *table = &ofproto->tables[rule->up.table_id];
5042
5043         if (table->other_table && rule->tag) {
5044             tag_set_add(&ofproto->revalidate_set, rule->tag);
5045         } else {
5046             ofproto->need_revalidate = true;
5047         }
5048     }
5049 }
5050 \f
5051 static bool
5052 set_frag_handling(struct ofproto *ofproto_,
5053                   enum ofp_config_flags frag_handling)
5054 {
5055     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5056
5057     if (frag_handling != OFPC_FRAG_REASM) {
5058         ofproto->need_revalidate = true;
5059         return true;
5060     } else {
5061         return false;
5062     }
5063 }
5064
5065 static int
5066 packet_out(struct ofproto *ofproto_, struct ofpbuf *packet,
5067            const struct flow *flow,
5068            const union ofp_action *ofp_actions, size_t n_ofp_actions)
5069 {
5070     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5071     int error;
5072
5073     error = validate_actions(ofp_actions, n_ofp_actions, flow,
5074                              ofproto->max_ports);
5075     if (!error) {
5076         struct odputil_keybuf keybuf;
5077         struct action_xlate_ctx ctx;
5078         struct ofpbuf *odp_actions;
5079         struct ofpbuf key;
5080
5081         ofpbuf_use_stack(&key, &keybuf, sizeof keybuf);
5082         odp_flow_key_from_flow(&key, flow);
5083
5084         action_xlate_ctx_init(&ctx, ofproto, flow, packet);
5085         odp_actions = xlate_actions(&ctx, ofp_actions, n_ofp_actions);
5086         dpif_execute(ofproto->dpif, key.data, key.size,
5087                      odp_actions->data, odp_actions->size, packet);
5088         ofpbuf_delete(odp_actions);
5089     }
5090     return error;
5091 }
5092
5093 static void
5094 get_netflow_ids(const struct ofproto *ofproto_,
5095                 uint8_t *engine_type, uint8_t *engine_id)
5096 {
5097     struct ofproto_dpif *ofproto = ofproto_dpif_cast(ofproto_);
5098
5099     dpif_get_netflow_ids(ofproto->dpif, engine_type, engine_id);
5100 }
5101 \f
5102 static struct ofproto_dpif *
5103 ofproto_dpif_lookup(const char *name)
5104 {
5105     struct ofproto *ofproto = ofproto_lookup(name);
5106     return (ofproto && ofproto->ofproto_class == &ofproto_dpif_class
5107             ? ofproto_dpif_cast(ofproto)
5108             : NULL);
5109 }
5110
5111 static void
5112 ofproto_unixctl_fdb_show(struct unixctl_conn *conn,
5113                          const char *args, void *aux OVS_UNUSED)
5114 {
5115     struct ds ds = DS_EMPTY_INITIALIZER;
5116     const struct ofproto_dpif *ofproto;
5117     const struct mac_entry *e;
5118
5119     ofproto = ofproto_dpif_lookup(args);
5120     if (!ofproto) {
5121         unixctl_command_reply(conn, 501, "no such bridge");
5122         return;
5123     }
5124
5125     ds_put_cstr(&ds, " port  VLAN  MAC                Age\n");
5126     LIST_FOR_EACH (e, lru_node, &ofproto->ml->lrus) {
5127         struct ofbundle *bundle = e->port.p;
5128         ds_put_format(&ds, "%5d  %4d  "ETH_ADDR_FMT"  %3d\n",
5129                       ofbundle_get_a_port(bundle)->odp_port,
5130                       e->vlan, ETH_ADDR_ARGS(e->mac), mac_entry_age(e));
5131     }
5132     unixctl_command_reply(conn, 200, ds_cstr(&ds));
5133     ds_destroy(&ds);
5134 }
5135
5136 struct ofproto_trace {
5137     struct action_xlate_ctx ctx;
5138     struct flow flow;
5139     struct ds *result;
5140 };
5141
5142 static void
5143 trace_format_rule(struct ds *result, uint8_t table_id, int level,
5144                   const struct rule_dpif *rule)
5145 {
5146     ds_put_char_multiple(result, '\t', level);
5147     if (!rule) {
5148         ds_put_cstr(result, "No match\n");
5149         return;
5150     }
5151
5152     ds_put_format(result, "Rule: table=%"PRIu8" cookie=%#"PRIx64" ",
5153                   table_id, ntohll(rule->up.flow_cookie));
5154     cls_rule_format(&rule->up.cr, result);
5155     ds_put_char(result, '\n');
5156
5157     ds_put_char_multiple(result, '\t', level);
5158     ds_put_cstr(result, "OpenFlow ");
5159     ofp_print_actions(result, rule->up.actions, rule->up.n_actions);
5160     ds_put_char(result, '\n');
5161 }
5162
5163 static void
5164 trace_format_flow(struct ds *result, int level, const char *title,
5165                  struct ofproto_trace *trace)
5166 {
5167     ds_put_char_multiple(result, '\t', level);
5168     ds_put_format(result, "%s: ", title);
5169     if (flow_equal(&trace->ctx.flow, &trace->flow)) {
5170         ds_put_cstr(result, "unchanged");
5171     } else {
5172         flow_format(result, &trace->ctx.flow);
5173         trace->flow = trace->ctx.flow;
5174     }
5175     ds_put_char(result, '\n');
5176 }
5177
5178 static void
5179 trace_format_regs(struct ds *result, int level, const char *title,
5180                   struct ofproto_trace *trace)
5181 {
5182     size_t i;
5183
5184     ds_put_char_multiple(result, '\t', level);
5185     ds_put_format(result, "%s:", title);
5186     for (i = 0; i < FLOW_N_REGS; i++) {
5187         ds_put_format(result, " reg%zu=0x%"PRIx32, i, trace->flow.regs[i]);
5188     }
5189     ds_put_char(result, '\n');
5190 }
5191
5192 static void
5193 trace_resubmit(struct action_xlate_ctx *ctx, struct rule_dpif *rule)
5194 {
5195     struct ofproto_trace *trace = CONTAINER_OF(ctx, struct ofproto_trace, ctx);
5196     struct ds *result = trace->result;
5197
5198     ds_put_char(result, '\n');
5199     trace_format_flow(result, ctx->recurse + 1, "Resubmitted flow", trace);
5200     trace_format_regs(result, ctx->recurse + 1, "Resubmitted regs", trace);
5201     trace_format_rule(result, ctx->table_id, ctx->recurse + 1, rule);
5202 }
5203
5204 static void
5205 ofproto_unixctl_trace(struct unixctl_conn *conn, const char *args_,
5206                       void *aux OVS_UNUSED)
5207 {
5208     char *dpname, *arg1, *arg2, *arg3;
5209     char *args = xstrdup(args_);
5210     char *save_ptr = NULL;
5211     struct ofproto_dpif *ofproto;
5212     struct ofpbuf odp_key;
5213     struct ofpbuf *packet;
5214     struct rule_dpif *rule;
5215     struct ds result;
5216     struct flow flow;
5217     char *s;
5218
5219     packet = NULL;
5220     ofpbuf_init(&odp_key, 0);
5221     ds_init(&result);
5222
5223     dpname = strtok_r(args, " ", &save_ptr);
5224     arg1 = strtok_r(NULL, " ", &save_ptr);
5225     arg2 = strtok_r(NULL, " ", &save_ptr);
5226     arg3 = strtok_r(NULL, "", &save_ptr); /* Get entire rest of line. */
5227     if (dpname && arg1 && (!arg2 || !strcmp(arg2, "-generate")) && !arg3) {
5228         /* ofproto/trace dpname flow [-generate] */
5229         int error;
5230
5231         /* Convert string to datapath key. */
5232         ofpbuf_init(&odp_key, 0);
5233         error = odp_flow_key_from_string(arg1, &odp_key);
5234         if (error) {
5235             unixctl_command_reply(conn, 501, "Bad flow syntax");
5236             goto exit;
5237         }
5238
5239         /* Convert odp_key to flow. */
5240         error = odp_flow_key_to_flow(odp_key.data, odp_key.size, &flow);
5241         if (error) {
5242             unixctl_command_reply(conn, 501, "Invalid flow");
5243             goto exit;
5244         }
5245
5246         /* Generate a packet, if requested. */
5247         if (arg2) {
5248             packet = ofpbuf_new(0);
5249             flow_compose(packet, &flow);
5250         }
5251     } else if (dpname && arg1 && arg2 && arg3) {
5252         /* ofproto/trace dpname tun_id in_port packet */
5253         uint16_t in_port;
5254         ovs_be64 tun_id;
5255
5256         tun_id = htonll(strtoull(arg1, NULL, 0));
5257         in_port = ofp_port_to_odp_port(atoi(arg2));
5258
5259         packet = ofpbuf_new(strlen(args) / 2);
5260         arg3 = ofpbuf_put_hex(packet, arg3, NULL);
5261         arg3 += strspn(arg3, " ");
5262         if (*arg3 != '\0') {
5263             unixctl_command_reply(conn, 501, "Trailing garbage in command");
5264             goto exit;
5265         }
5266         if (packet->size < ETH_HEADER_LEN) {
5267             unixctl_command_reply(conn, 501,
5268                                   "Packet data too short for Ethernet");
5269             goto exit;
5270         }
5271
5272         ds_put_cstr(&result, "Packet: ");
5273         s = ofp_packet_to_string(packet->data, packet->size, packet->size);
5274         ds_put_cstr(&result, s);
5275         free(s);
5276
5277         flow_extract(packet, tun_id, in_port, &flow);
5278     } else {
5279         unixctl_command_reply(conn, 501, "Bad command syntax");
5280         goto exit;
5281     }
5282
5283     ofproto = ofproto_dpif_lookup(dpname);
5284     if (!ofproto) {
5285         unixctl_command_reply(conn, 501, "Unknown ofproto (use ofproto/list "
5286                               "for help)");
5287         goto exit;
5288     }
5289
5290     ds_put_cstr(&result, "Flow: ");
5291     flow_format(&result, &flow);
5292     ds_put_char(&result, '\n');
5293
5294     rule = rule_dpif_lookup(ofproto, &flow, 0);
5295     trace_format_rule(&result, 0, 0, rule);
5296     if (rule) {
5297         struct ofproto_trace trace;
5298         struct ofpbuf *odp_actions;
5299
5300         trace.result = &result;
5301         trace.flow = flow;
5302         action_xlate_ctx_init(&trace.ctx, ofproto, &flow, packet);
5303         trace.ctx.resubmit_hook = trace_resubmit;
5304         odp_actions = xlate_actions(&trace.ctx,
5305                                     rule->up.actions, rule->up.n_actions);
5306
5307         ds_put_char(&result, '\n');
5308         trace_format_flow(&result, 0, "Final flow", &trace);
5309         ds_put_cstr(&result, "Datapath actions: ");
5310         format_odp_actions(&result, odp_actions->data, odp_actions->size);
5311         ofpbuf_delete(odp_actions);
5312
5313         if (!trace.ctx.may_set_up_flow) {
5314             if (packet) {
5315                 ds_put_cstr(&result, "\nThis flow is not cachable.");
5316             } else {
5317                 ds_put_cstr(&result, "\nThe datapath actions are incomplete--"
5318                             "for complete actions, please supply a packet.");
5319             }
5320         }
5321     }
5322
5323     unixctl_command_reply(conn, 200, ds_cstr(&result));
5324
5325 exit:
5326     ds_destroy(&result);
5327     ofpbuf_delete(packet);
5328     ofpbuf_uninit(&odp_key);
5329     free(args);
5330 }
5331
5332 static void
5333 ofproto_dpif_clog(struct unixctl_conn *conn OVS_UNUSED,
5334                   const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5335 {
5336     clogged = true;
5337     unixctl_command_reply(conn, 200, NULL);
5338 }
5339
5340 static void
5341 ofproto_dpif_unclog(struct unixctl_conn *conn OVS_UNUSED,
5342                     const char *args_ OVS_UNUSED, void *aux OVS_UNUSED)
5343 {
5344     clogged = false;
5345     unixctl_command_reply(conn, 200, NULL);
5346 }
5347
5348 static void
5349 ofproto_dpif_unixctl_init(void)
5350 {
5351     static bool registered;
5352     if (registered) {
5353         return;
5354     }
5355     registered = true;
5356
5357     unixctl_command_register("ofproto/trace",
5358                       "bridge {tun_id in_port packet | odp_flow [-generate]}",
5359                       ofproto_unixctl_trace, NULL);
5360     unixctl_command_register("fdb/show", "bridge", ofproto_unixctl_fdb_show,
5361                              NULL); 
5362     unixctl_command_register("ofproto/clog", "", ofproto_dpif_clog, NULL);
5363     unixctl_command_register("ofproto/unclog", "", ofproto_dpif_unclog, NULL);
5364 }
5365 \f
5366 const struct ofproto_class ofproto_dpif_class = {
5367     enumerate_types,
5368     enumerate_names,
5369     del,
5370     alloc,
5371     construct,
5372     destruct,
5373     dealloc,
5374     run,
5375     wait,
5376     flush,
5377     get_features,
5378     get_tables,
5379     port_alloc,
5380     port_construct,
5381     port_destruct,
5382     port_dealloc,
5383     port_modified,
5384     port_reconfigured,
5385     port_query_by_name,
5386     port_add,
5387     port_del,
5388     port_dump_start,
5389     port_dump_next,
5390     port_dump_done,
5391     port_poll,
5392     port_poll_wait,
5393     port_is_lacp_current,
5394     NULL,                       /* rule_choose_table */
5395     rule_alloc,
5396     rule_construct,
5397     rule_destruct,
5398     rule_dealloc,
5399     rule_get_stats,
5400     rule_execute,
5401     rule_modify_actions,
5402     set_frag_handling,
5403     packet_out,
5404     set_netflow,
5405     get_netflow_ids,
5406     set_sflow,
5407     set_cfm,
5408     get_cfm_fault,
5409     get_cfm_remote_mpids,
5410     set_stp,
5411     get_stp_status,
5412     set_stp_port,
5413     get_stp_port_status,
5414     bundle_set,
5415     bundle_remove,
5416     mirror_set,
5417     set_flood_vlans,
5418     is_mirror_output_bundle,
5419     forward_bpdu_changed,
5420 };