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