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