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