ofproto: Add missing lock annotations on prototypes.
[cascardo/ovs.git] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010, 2011, 2012, 2013, 2014 Nicira, Inc.
3  * Copyright (c) 2010 Jean Tourrilhes - HP-Labs.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at:
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17
18 #include <config.h>
19 #include "ofproto.h"
20 #include <errno.h>
21 #include <inttypes.h>
22 #include <stdbool.h>
23 #include <stdlib.h>
24 #include <unistd.h>
25 #include "bitmap.h"
26 #include "byte-order.h"
27 #include "classifier.h"
28 #include "connectivity.h"
29 #include "connmgr.h"
30 #include "coverage.h"
31 #include "dynamic-string.h"
32 #include "hash.h"
33 #include "hmap.h"
34 #include "meta-flow.h"
35 #include "netdev.h"
36 #include "nx-match.h"
37 #include "ofp-actions.h"
38 #include "ofp-errors.h"
39 #include "ofp-msgs.h"
40 #include "ofp-print.h"
41 #include "ofp-util.h"
42 #include "ofpbuf.h"
43 #include "ofproto-provider.h"
44 #include "openflow/nicira-ext.h"
45 #include "openflow/openflow.h"
46 #include "ovs-rcu.h"
47 #include "packets.h"
48 #include "pinsched.h"
49 #include "pktbuf.h"
50 #include "poll-loop.h"
51 #include "random.h"
52 #include "seq.h"
53 #include "shash.h"
54 #include "simap.h"
55 #include "smap.h"
56 #include "sset.h"
57 #include "timeval.h"
58 #include "unaligned.h"
59 #include "unixctl.h"
60 #include "vlog.h"
61 #include "bundles.h"
62
63 VLOG_DEFINE_THIS_MODULE(ofproto);
64
65 COVERAGE_DEFINE(ofproto_flush);
66 COVERAGE_DEFINE(ofproto_packet_out);
67 COVERAGE_DEFINE(ofproto_queue_req);
68 COVERAGE_DEFINE(ofproto_recv_openflow);
69 COVERAGE_DEFINE(ofproto_reinit_ports);
70 COVERAGE_DEFINE(ofproto_update_port);
71
72 /* Default fields to use for prefix tries in each flow table, unless something
73  * else is configured. */
74 const enum mf_field_id default_prefix_fields[2] =
75     { MFF_IPV4_DST, MFF_IPV4_SRC };
76
77 enum ofproto_state {
78     S_OPENFLOW,                 /* Processing OpenFlow commands. */
79     S_EVICT,                    /* Evicting flows from over-limit tables. */
80     S_FLUSH,                    /* Deleting all flow table rules. */
81 };
82
83 enum ofoperation_type {
84     OFOPERATION_ADD,
85     OFOPERATION_DELETE,
86     OFOPERATION_MODIFY,
87     OFOPERATION_REPLACE
88 };
89
90 /* A single OpenFlow request can execute any number of operations.  The
91  * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
92  * ofconn to which an error reply should be sent if necessary.
93  *
94  * ofproto initiates some operations internally.  These operations are still
95  * assigned to groups but will not have an associated ofconn. */
96 struct ofopgroup {
97     struct ofproto *ofproto;    /* Owning ofproto. */
98     struct list ofproto_node;   /* In ofproto's "pending" list. */
99     struct list ops;            /* List of "struct ofoperation"s. */
100     int n_running;              /* Number of ops still pending. */
101
102     /* Data needed to send OpenFlow reply on failure or to send a buffered
103      * packet on success.
104      *
105      * If list_is_empty(ofconn_node) then this ofopgroup never had an
106      * associated ofconn or its ofconn's connection dropped after it initiated
107      * the operation.  In the latter case 'ofconn' is a wild pointer that
108      * refers to freed memory, so the 'ofconn' member must be used only if
109      * !list_is_empty(ofconn_node).
110      */
111     struct list ofconn_node;    /* In ofconn's list of pending opgroups. */
112     struct ofconn *ofconn;      /* ofconn for reply (but see note above). */
113     struct ofp_header *request; /* Original request (truncated at 64 bytes). */
114     uint32_t buffer_id;         /* Buffer id from original request. */
115 };
116
117 static struct ofopgroup *ofopgroup_create_unattached(struct ofproto *);
118 static struct ofopgroup *ofopgroup_create(struct ofproto *, struct ofconn *,
119                                           const struct ofp_header *,
120                                           uint32_t buffer_id);
121 static void ofopgroup_submit(struct ofopgroup *);
122 static void ofopgroup_complete(struct ofopgroup *);
123
124 /* A single flow table operation. */
125 struct ofoperation {
126     struct ofopgroup *group;    /* Owning group. */
127     struct list group_node;     /* In ofopgroup's "ops" list. */
128     struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
129     struct rule *rule;          /* Rule being operated upon. */
130     enum ofoperation_type type; /* Type of operation. */
131
132     /* OFOPERATION_MODIFY, OFOPERATION_REPLACE: The old actions, if the actions
133      * are changing. */
134     const struct rule_actions *actions;
135
136     /* OFOPERATION_DELETE. */
137     enum ofp_flow_removed_reason reason; /* Reason flow was removed. */
138
139     ovs_be64 flow_cookie;               /* Rule's old flow cookie. */
140     uint16_t idle_timeout;              /* Rule's old idle timeout. */
141     uint16_t hard_timeout;              /* Rule's old hard timeout. */
142     enum ofputil_flow_mod_flags flags;  /* Rule's old flags. */
143     enum ofperr error;                  /* 0 if no error. */
144 };
145
146 static struct ofoperation *ofoperation_create(struct ofopgroup *,
147                                               struct rule *,
148                                               enum ofoperation_type,
149                                               enum ofp_flow_removed_reason);
150 static void ofoperation_destroy(struct ofoperation *);
151
152 /* oftable. */
153 static void oftable_init(struct oftable *);
154 static void oftable_destroy(struct oftable *);
155
156 static void oftable_set_name(struct oftable *, const char *name);
157
158 static void oftable_disable_eviction(struct oftable *);
159 static void oftable_enable_eviction(struct oftable *,
160                                     const struct mf_subfield *fields,
161                                     size_t n_fields);
162
163 static void oftable_remove_rule(struct rule *rule) OVS_REQUIRES(ofproto_mutex);
164 static void oftable_remove_rule__(struct ofproto *, struct rule *)
165     OVS_REQUIRES(ofproto_mutex);
166
167 /* A set of rules within a single OpenFlow table (oftable) that have the same
168  * values for the oftable's eviction_fields.  A rule to be evicted, when one is
169  * needed, is taken from the eviction group that contains the greatest number
170  * of rules.
171  *
172  * An oftable owns any number of eviction groups, each of which contains any
173  * number of rules.
174  *
175  * Membership in an eviction group is imprecise, based on the hash of the
176  * oftable's eviction_fields (in the eviction_group's id_node.hash member).
177  * That is, if two rules have different eviction_fields, but those
178  * eviction_fields hash to the same value, then they will belong to the same
179  * eviction_group anyway.
180  *
181  * (When eviction is not enabled on an oftable, we don't track any eviction
182  * groups, to save time and space.) */
183 struct eviction_group {
184     struct hmap_node id_node;   /* In oftable's "eviction_groups_by_id". */
185     struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
186     struct heap rules;          /* Contains "struct rule"s. */
187 };
188
189 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep)
190     OVS_REQUIRES(ofproto_mutex);
191 static void ofproto_evict(struct ofproto *)
192     OVS_EXCLUDED(ofproto_mutex);
193 static uint32_t rule_eviction_priority(struct ofproto *ofproto, struct rule *)
194     OVS_REQUIRES(ofproto_mutex);;
195 static void eviction_group_add_rule(struct rule *)
196     OVS_REQUIRES(ofproto_mutex);
197 static void eviction_group_remove_rule(struct rule *)
198     OVS_REQUIRES(ofproto_mutex);
199
200 /* Criteria that flow_mod and other operations use for selecting rules on
201  * which to operate. */
202 struct rule_criteria {
203     /* An OpenFlow table or 255 for all tables. */
204     uint8_t table_id;
205
206     /* OpenFlow matching criteria.  Interpreted different in "loose" way by
207      * collect_rules_loose() and "strict" way by collect_rules_strict(), as
208      * defined in the OpenFlow spec. */
209     struct cls_rule cr;
210
211     /* Matching criteria for the OpenFlow cookie.  Consider a bit B in a rule's
212      * cookie and the corresponding bits C in 'cookie' and M in 'cookie_mask'.
213      * The rule will not be selected if M is 1 and B != C.  */
214     ovs_be64 cookie;
215     ovs_be64 cookie_mask;
216
217     /* Selection based on actions within a rule:
218      *
219      * If out_port != OFPP_ANY, selects only rules that output to out_port.
220      * If out_group != OFPG_ALL, select only rules that output to out_group. */
221     ofp_port_t out_port;
222     uint32_t out_group;
223 };
224
225 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
226                                const struct match *match,
227                                unsigned int priority,
228                                ovs_be64 cookie, ovs_be64 cookie_mask,
229                                ofp_port_t out_port, uint32_t out_group);
230 static void rule_criteria_destroy(struct rule_criteria *);
231
232 /* A packet that needs to be passed to rule_execute().
233  *
234  * (We can't do this immediately from ofopgroup_complete() because that holds
235  * ofproto_mutex, which rule_execute() needs released.) */
236 struct rule_execute {
237     struct list list_node;      /* In struct ofproto's "rule_executes" list. */
238     struct rule *rule;          /* Owns a reference to the rule. */
239     ofp_port_t in_port;
240     struct ofpbuf *packet;      /* Owns the packet. */
241 };
242
243 static void run_rule_executes(struct ofproto *) OVS_EXCLUDED(ofproto_mutex);
244 static void destroy_rule_executes(struct ofproto *);
245
246 /* ofport. */
247 static void ofport_destroy__(struct ofport *) OVS_EXCLUDED(ofproto_mutex);
248 static void ofport_destroy(struct ofport *);
249
250 static void update_port(struct ofproto *, const char *devname);
251 static int init_ports(struct ofproto *);
252 static void reinit_ports(struct ofproto *);
253
254 static long long int ofport_get_usage(const struct ofproto *,
255                                       ofp_port_t ofp_port);
256 static void ofport_set_usage(struct ofproto *, ofp_port_t ofp_port,
257                              long long int last_used);
258 static void ofport_remove_usage(struct ofproto *, ofp_port_t ofp_port);
259
260 /* Ofport usage.
261  *
262  * Keeps track of the currently used and recently used ofport values and is
263  * used to prevent immediate recycling of ofport values. */
264 struct ofport_usage {
265     struct hmap_node hmap_node; /* In struct ofproto's "ofport_usage" hmap. */
266     ofp_port_t ofp_port;        /* OpenFlow port number. */
267     long long int last_used;    /* Last time the 'ofp_port' was used. LLONG_MAX
268                                    represents in-use ofports. */
269 };
270
271 /* rule. */
272 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
273 static bool rule_is_modifiable(const struct rule *rule,
274                                enum ofputil_flow_mod_flags flag);
275
276 /* OpenFlow. */
277 static enum ofperr add_flow(struct ofproto *, struct ofconn *,
278                             struct ofputil_flow_mod *,
279                             const struct ofp_header *);
280 static enum ofperr modify_flows__(struct ofproto *, struct ofconn *,
281                                   struct ofputil_flow_mod *,
282                                   const struct ofp_header *,
283                                   const struct rule_collection *);
284 static void delete_flow__(struct rule *rule, struct ofopgroup *,
285                           enum ofp_flow_removed_reason)
286     OVS_REQUIRES(ofproto_mutex);
287 static bool ofproto_group_exists__(const struct ofproto *ofproto,
288                                    uint32_t group_id)
289     OVS_REQ_RDLOCK(ofproto->groups_rwlock);
290 static bool ofproto_group_exists(const struct ofproto *ofproto,
291                                  uint32_t group_id)
292     OVS_EXCLUDED(ofproto->groups_rwlock);
293 static enum ofperr add_group(struct ofproto *, struct ofputil_group_mod *);
294 static bool handle_openflow(struct ofconn *, const struct ofpbuf *);
295 static enum ofperr handle_flow_mod__(struct ofproto *, struct ofconn *,
296                                      struct ofputil_flow_mod *,
297                                      const struct ofp_header *)
298     OVS_EXCLUDED(ofproto_mutex);
299 static void calc_duration(long long int start, long long int now,
300                           uint32_t *sec, uint32_t *nsec);
301
302 /* ofproto. */
303 static uint64_t pick_datapath_id(const struct ofproto *);
304 static uint64_t pick_fallback_dpid(void);
305 static void ofproto_destroy__(struct ofproto *);
306 static void update_mtu(struct ofproto *, struct ofport *);
307 static void meter_delete(struct ofproto *, uint32_t first, uint32_t last);
308 static void meter_insert_rule(struct rule *);
309
310 /* unixctl. */
311 static void ofproto_unixctl_init(void);
312
313 /* All registered ofproto classes, in probe order. */
314 static const struct ofproto_class **ofproto_classes;
315 static size_t n_ofproto_classes;
316 static size_t allocated_ofproto_classes;
317
318 /* Global lock that protects all flow table operations. */
319 struct ovs_mutex ofproto_mutex = OVS_MUTEX_INITIALIZER;
320
321 unsigned ofproto_flow_limit = OFPROTO_FLOW_LIMIT_DEFAULT;
322 unsigned ofproto_max_idle = OFPROTO_MAX_IDLE_DEFAULT;
323
324 size_t n_handlers, n_revalidators;
325
326 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
327 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
328
329 /* Initial mappings of port to OpenFlow number mappings. */
330 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
331
332 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
333
334 /* The default value of true waits for flow restore. */
335 static bool flow_restore_wait = true;
336
337 /* Must be called to initialize the ofproto library.
338  *
339  * The caller may pass in 'iface_hints', which contains an shash of
340  * "iface_hint" elements indexed by the interface's name.  The provider
341  * may use these hints to describe the startup configuration in order to
342  * reinitialize its state.  The caller owns the provided data, so a
343  * provider will make copies of anything required.  An ofproto provider
344  * will remove any existing state that is not described by the hint, and
345  * may choose to remove it all. */
346 void
347 ofproto_init(const struct shash *iface_hints)
348 {
349     struct shash_node *node;
350     size_t i;
351
352     ofproto_class_register(&ofproto_dpif_class);
353
354     /* Make a local copy, since we don't own 'iface_hints' elements. */
355     SHASH_FOR_EACH(node, iface_hints) {
356         const struct iface_hint *orig_hint = node->data;
357         struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
358         const char *br_type = ofproto_normalize_type(orig_hint->br_type);
359
360         new_hint->br_name = xstrdup(orig_hint->br_name);
361         new_hint->br_type = xstrdup(br_type);
362         new_hint->ofp_port = orig_hint->ofp_port;
363
364         shash_add(&init_ofp_ports, node->name, new_hint);
365     }
366
367     for (i = 0; i < n_ofproto_classes; i++) {
368         ofproto_classes[i]->init(&init_ofp_ports);
369     }
370 }
371
372 /* 'type' should be a normalized datapath type, as returned by
373  * ofproto_normalize_type().  Returns the corresponding ofproto_class
374  * structure, or a null pointer if there is none registered for 'type'. */
375 static const struct ofproto_class *
376 ofproto_class_find__(const char *type)
377 {
378     size_t i;
379
380     for (i = 0; i < n_ofproto_classes; i++) {
381         const struct ofproto_class *class = ofproto_classes[i];
382         struct sset types;
383         bool found;
384
385         sset_init(&types);
386         class->enumerate_types(&types);
387         found = sset_contains(&types, type);
388         sset_destroy(&types);
389
390         if (found) {
391             return class;
392         }
393     }
394     VLOG_WARN("unknown datapath type %s", type);
395     return NULL;
396 }
397
398 /* Registers a new ofproto class.  After successful registration, new ofprotos
399  * of that type can be created using ofproto_create(). */
400 int
401 ofproto_class_register(const struct ofproto_class *new_class)
402 {
403     size_t i;
404
405     for (i = 0; i < n_ofproto_classes; i++) {
406         if (ofproto_classes[i] == new_class) {
407             return EEXIST;
408         }
409     }
410
411     if (n_ofproto_classes >= allocated_ofproto_classes) {
412         ofproto_classes = x2nrealloc(ofproto_classes,
413                                      &allocated_ofproto_classes,
414                                      sizeof *ofproto_classes);
415     }
416     ofproto_classes[n_ofproto_classes++] = new_class;
417     return 0;
418 }
419
420 /* Unregisters a datapath provider.  'type' must have been previously
421  * registered and not currently be in use by any ofprotos.  After
422  * unregistration new datapaths of that type cannot be opened using
423  * ofproto_create(). */
424 int
425 ofproto_class_unregister(const struct ofproto_class *class)
426 {
427     size_t i;
428
429     for (i = 0; i < n_ofproto_classes; i++) {
430         if (ofproto_classes[i] == class) {
431             for (i++; i < n_ofproto_classes; i++) {
432                 ofproto_classes[i - 1] = ofproto_classes[i];
433             }
434             n_ofproto_classes--;
435             return 0;
436         }
437     }
438     VLOG_WARN("attempted to unregister an ofproto class that is not "
439               "registered");
440     return EAFNOSUPPORT;
441 }
442
443 /* Clears 'types' and enumerates all registered ofproto types into it.  The
444  * caller must first initialize the sset. */
445 void
446 ofproto_enumerate_types(struct sset *types)
447 {
448     size_t i;
449
450     sset_clear(types);
451     for (i = 0; i < n_ofproto_classes; i++) {
452         ofproto_classes[i]->enumerate_types(types);
453     }
454 }
455
456 /* Returns the fully spelled out name for the given ofproto 'type'.
457  *
458  * Normalized type string can be compared with strcmp().  Unnormalized type
459  * string might be the same even if they have different spellings. */
460 const char *
461 ofproto_normalize_type(const char *type)
462 {
463     return type && type[0] ? type : "system";
464 }
465
466 /* Clears 'names' and enumerates the names of all known created ofprotos with
467  * the given 'type'.  The caller must first initialize the sset.  Returns 0 if
468  * successful, otherwise a positive errno value.
469  *
470  * Some kinds of datapaths might not be practically enumerable.  This is not
471  * considered an error. */
472 int
473 ofproto_enumerate_names(const char *type, struct sset *names)
474 {
475     const struct ofproto_class *class = ofproto_class_find__(type);
476     return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
477 }
478
479 int
480 ofproto_create(const char *datapath_name, const char *datapath_type,
481                struct ofproto **ofprotop)
482 {
483     const struct ofproto_class *class;
484     struct ofproto *ofproto;
485     int error;
486     int i;
487
488     *ofprotop = NULL;
489
490     ofproto_unixctl_init();
491
492     datapath_type = ofproto_normalize_type(datapath_type);
493     class = ofproto_class_find__(datapath_type);
494     if (!class) {
495         VLOG_WARN("could not create datapath %s of unknown type %s",
496                   datapath_name, datapath_type);
497         return EAFNOSUPPORT;
498     }
499
500     ofproto = class->alloc();
501     if (!ofproto) {
502         VLOG_ERR("failed to allocate datapath %s of type %s",
503                  datapath_name, datapath_type);
504         return ENOMEM;
505     }
506
507     /* Initialize. */
508     ovs_mutex_lock(&ofproto_mutex);
509     memset(ofproto, 0, sizeof *ofproto);
510     ofproto->ofproto_class = class;
511     ofproto->name = xstrdup(datapath_name);
512     ofproto->type = xstrdup(datapath_type);
513     hmap_insert(&all_ofprotos, &ofproto->hmap_node,
514                 hash_string(ofproto->name, 0));
515     ofproto->datapath_id = 0;
516     ofproto->forward_bpdu = false;
517     ofproto->fallback_dpid = pick_fallback_dpid();
518     ofproto->mfr_desc = NULL;
519     ofproto->hw_desc = NULL;
520     ofproto->sw_desc = NULL;
521     ofproto->serial_desc = NULL;
522     ofproto->dp_desc = NULL;
523     ofproto->frag_handling = OFPC_FRAG_NORMAL;
524     hmap_init(&ofproto->ports);
525     hmap_init(&ofproto->ofport_usage);
526     shash_init(&ofproto->port_by_name);
527     simap_init(&ofproto->ofp_requests);
528     ofproto->max_ports = ofp_to_u16(OFPP_MAX);
529     ofproto->eviction_group_timer = LLONG_MIN;
530     ofproto->tables = NULL;
531     ofproto->n_tables = 0;
532     hindex_init(&ofproto->cookies);
533     list_init(&ofproto->expirable);
534     ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
535     ofproto->state = S_OPENFLOW;
536     list_init(&ofproto->pending);
537     ofproto->n_pending = 0;
538     hmap_init(&ofproto->deletions);
539     guarded_list_init(&ofproto->rule_executes);
540     ofproto->vlan_bitmap = NULL;
541     ofproto->vlans_changed = false;
542     ofproto->min_mtu = INT_MAX;
543     ovs_rwlock_init(&ofproto->groups_rwlock);
544     hmap_init(&ofproto->groups);
545     ovs_mutex_unlock(&ofproto_mutex);
546     ofproto->ogf.capabilities = OFPGFC_CHAINING | OFPGFC_SELECT_LIVENESS |
547                                 OFPGFC_SELECT_WEIGHT;
548     ofproto->ogf.max_groups[OFPGT11_ALL] = OFPG_MAX;
549     ofproto->ogf.max_groups[OFPGT11_SELECT] = OFPG_MAX;
550     ofproto->ogf.max_groups[OFPGT11_INDIRECT] = OFPG_MAX;
551     ofproto->ogf.max_groups[OFPGT11_FF] = OFPG_MAX;
552     ofproto->ogf.actions[0] =
553         (1 << OFPAT11_OUTPUT) |
554         (1 << OFPAT11_COPY_TTL_OUT) |
555         (1 << OFPAT11_COPY_TTL_IN) |
556         (1 << OFPAT11_SET_MPLS_TTL) |
557         (1 << OFPAT11_DEC_MPLS_TTL) |
558         (1 << OFPAT11_PUSH_VLAN) |
559         (1 << OFPAT11_POP_VLAN) |
560         (1 << OFPAT11_PUSH_MPLS) |
561         (1 << OFPAT11_POP_MPLS) |
562         (1 << OFPAT11_SET_QUEUE) |
563         (1 << OFPAT11_GROUP) |
564         (1 << OFPAT11_SET_NW_TTL) |
565         (1 << OFPAT11_DEC_NW_TTL) |
566         (1 << OFPAT12_SET_FIELD);
567 /* not supported:
568  *      (1 << OFPAT13_PUSH_PBB) |
569  *      (1 << OFPAT13_POP_PBB) */
570
571     error = ofproto->ofproto_class->construct(ofproto);
572     if (error) {
573         VLOG_ERR("failed to open datapath %s: %s",
574                  datapath_name, ovs_strerror(error));
575         ofproto_destroy__(ofproto);
576         return error;
577     }
578
579     /* Check that hidden tables, if any, are at the end. */
580     ovs_assert(ofproto->n_tables);
581     for (i = 0; i + 1 < ofproto->n_tables; i++) {
582         enum oftable_flags flags = ofproto->tables[i].flags;
583         enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
584
585         ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
586     }
587
588     ofproto->datapath_id = pick_datapath_id(ofproto);
589     init_ports(ofproto);
590
591     /* Initialize meters table. */
592     if (ofproto->ofproto_class->meter_get_features) {
593         ofproto->ofproto_class->meter_get_features(ofproto,
594                                                    &ofproto->meter_features);
595     } else {
596         memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
597     }
598     ofproto->meters = xzalloc((ofproto->meter_features.max_meters + 1)
599                               * sizeof(struct meter *));
600
601     *ofprotop = ofproto;
602     return 0;
603 }
604
605 /* Must be called (only) by an ofproto implementation in its constructor
606  * function.  See the large comment on 'construct' in struct ofproto_class for
607  * details. */
608 void
609 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
610 {
611     struct oftable *table;
612
613     ovs_assert(!ofproto->n_tables);
614     ovs_assert(n_tables >= 1 && n_tables <= 255);
615
616     ofproto->n_tables = n_tables;
617     ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
618     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
619         oftable_init(table);
620     }
621 }
622
623 /* To be optionally called (only) by an ofproto implementation in its
624  * constructor function.  See the large comment on 'construct' in struct
625  * ofproto_class for details.
626  *
627  * Sets the maximum number of ports to 'max_ports'.  The ofproto generic layer
628  * will then ensure that actions passed into the ofproto implementation will
629  * not refer to OpenFlow ports numbered 'max_ports' or higher.  If this
630  * function is not called, there will be no such restriction.
631  *
632  * Reserved ports numbered OFPP_MAX and higher are special and not subject to
633  * the 'max_ports' restriction. */
634 void
635 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
636 {
637     ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
638     ofproto->max_ports = max_ports;
639 }
640
641 uint64_t
642 ofproto_get_datapath_id(const struct ofproto *ofproto)
643 {
644     return ofproto->datapath_id;
645 }
646
647 void
648 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
649 {
650     uint64_t old_dpid = p->datapath_id;
651     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
652     if (p->datapath_id != old_dpid) {
653         /* Force all active connections to reconnect, since there is no way to
654          * notify a controller that the datapath ID has changed. */
655         ofproto_reconnect_controllers(p);
656     }
657 }
658
659 void
660 ofproto_set_controllers(struct ofproto *p,
661                         const struct ofproto_controller *controllers,
662                         size_t n_controllers, uint32_t allowed_versions)
663 {
664     connmgr_set_controllers(p->connmgr, controllers, n_controllers,
665                             allowed_versions);
666 }
667
668 void
669 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
670 {
671     connmgr_set_fail_mode(p->connmgr, fail_mode);
672 }
673
674 /* Drops the connections between 'ofproto' and all of its controllers, forcing
675  * them to reconnect. */
676 void
677 ofproto_reconnect_controllers(struct ofproto *ofproto)
678 {
679     connmgr_reconnect(ofproto->connmgr);
680 }
681
682 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
683  * in-band control should guarantee access, in the same way that in-band
684  * control guarantees access to OpenFlow controllers. */
685 void
686 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
687                                   const struct sockaddr_in *extras, size_t n)
688 {
689     connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
690 }
691
692 /* Sets the OpenFlow queue used by flows set up by in-band control on
693  * 'ofproto' to 'queue_id'.  If 'queue_id' is negative, then in-band control
694  * flows will use the default queue. */
695 void
696 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
697 {
698     connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
699 }
700
701 /* Sets the number of flows at which eviction from the kernel flow table
702  * will occur. */
703 void
704 ofproto_set_flow_limit(unsigned limit)
705 {
706     ofproto_flow_limit = limit;
707 }
708
709 /* Sets the maximum idle time for flows in the datapath before they are
710  * expired. */
711 void
712 ofproto_set_max_idle(unsigned max_idle)
713 {
714     ofproto_max_idle = max_idle;
715 }
716
717 /* If forward_bpdu is true, the NORMAL action will forward frames with
718  * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
719  * the NORMAL action will drop these frames. */
720 void
721 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
722 {
723     bool old_val = ofproto->forward_bpdu;
724     ofproto->forward_bpdu = forward_bpdu;
725     if (old_val != ofproto->forward_bpdu) {
726         if (ofproto->ofproto_class->forward_bpdu_changed) {
727             ofproto->ofproto_class->forward_bpdu_changed(ofproto);
728         }
729     }
730 }
731
732 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
733  * 'idle_time', in seconds, and the maximum number of MAC table entries to
734  * 'max_entries'. */
735 void
736 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
737                              size_t max_entries)
738 {
739     if (ofproto->ofproto_class->set_mac_table_config) {
740         ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
741                                                      max_entries);
742     }
743 }
744
745 void
746 ofproto_set_threads(int n_handlers_, int n_revalidators_)
747 {
748     int threads = MAX(count_cpu_cores(), 2);
749
750     n_revalidators = MAX(n_revalidators_, 0);
751     n_handlers = MAX(n_handlers_, 0);
752
753     if (!n_revalidators) {
754         n_revalidators = n_handlers
755             ? MAX(threads - (int) n_handlers, 1)
756             : threads / 4 + 1;
757     }
758
759     if (!n_handlers) {
760         n_handlers = MAX(threads - (int) n_revalidators, 1);
761     }
762 }
763
764 void
765 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
766 {
767     free(p->dp_desc);
768     p->dp_desc = dp_desc ? xstrdup(dp_desc) : NULL;
769 }
770
771 int
772 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
773 {
774     return connmgr_set_snoops(ofproto->connmgr, snoops);
775 }
776
777 int
778 ofproto_set_netflow(struct ofproto *ofproto,
779                     const struct netflow_options *nf_options)
780 {
781     if (nf_options && sset_is_empty(&nf_options->collectors)) {
782         nf_options = NULL;
783     }
784
785     if (ofproto->ofproto_class->set_netflow) {
786         return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
787     } else {
788         return nf_options ? EOPNOTSUPP : 0;
789     }
790 }
791
792 int
793 ofproto_set_sflow(struct ofproto *ofproto,
794                   const struct ofproto_sflow_options *oso)
795 {
796     if (oso && sset_is_empty(&oso->targets)) {
797         oso = NULL;
798     }
799
800     if (ofproto->ofproto_class->set_sflow) {
801         return ofproto->ofproto_class->set_sflow(ofproto, oso);
802     } else {
803         return oso ? EOPNOTSUPP : 0;
804     }
805 }
806
807 int
808 ofproto_set_ipfix(struct ofproto *ofproto,
809                   const struct ofproto_ipfix_bridge_exporter_options *bo,
810                   const struct ofproto_ipfix_flow_exporter_options *fo,
811                   size_t n_fo)
812 {
813     if (ofproto->ofproto_class->set_ipfix) {
814         return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
815     } else {
816         return (bo || fo) ? EOPNOTSUPP : 0;
817     }
818 }
819
820 void
821 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
822 {
823     flow_restore_wait = flow_restore_wait_db;
824 }
825
826 bool
827 ofproto_get_flow_restore_wait(void)
828 {
829     return flow_restore_wait;
830 }
831
832 \f
833 /* Spanning Tree Protocol (STP) configuration. */
834
835 /* Configures STP on 'ofproto' using the settings defined in 's'.  If
836  * 's' is NULL, disables STP.
837  *
838  * Returns 0 if successful, otherwise a positive errno value. */
839 int
840 ofproto_set_stp(struct ofproto *ofproto,
841                 const struct ofproto_stp_settings *s)
842 {
843     return (ofproto->ofproto_class->set_stp
844             ? ofproto->ofproto_class->set_stp(ofproto, s)
845             : EOPNOTSUPP);
846 }
847
848 /* Retrieves STP status of 'ofproto' and stores it in 's'.  If the
849  * 'enabled' member of 's' is false, then the other members are not
850  * meaningful.
851  *
852  * Returns 0 if successful, otherwise a positive errno value. */
853 int
854 ofproto_get_stp_status(struct ofproto *ofproto,
855                        struct ofproto_stp_status *s)
856 {
857     return (ofproto->ofproto_class->get_stp_status
858             ? ofproto->ofproto_class->get_stp_status(ofproto, s)
859             : EOPNOTSUPP);
860 }
861
862 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
863  * in 's'.  The caller is responsible for assigning STP port numbers
864  * (using the 'port_num' member in the range of 1 through 255, inclusive)
865  * and ensuring there are no duplicates.  If the 's' is NULL, then STP
866  * is disabled on the port.
867  *
868  * Returns 0 if successful, otherwise a positive errno value.*/
869 int
870 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
871                      const struct ofproto_port_stp_settings *s)
872 {
873     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
874     if (!ofport) {
875         VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu16,
876                   ofproto->name, ofp_port);
877         return ENODEV;
878     }
879
880     return (ofproto->ofproto_class->set_stp_port
881             ? ofproto->ofproto_class->set_stp_port(ofport, s)
882             : EOPNOTSUPP);
883 }
884
885 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
886  * 's'.  If the 'enabled' member in 's' is false, then the other members
887  * are not meaningful.
888  *
889  * Returns 0 if successful, otherwise a positive errno value.*/
890 int
891 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
892                             struct ofproto_port_stp_status *s)
893 {
894     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
895     if (!ofport) {
896         VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
897                      "port %"PRIu16, ofproto->name, ofp_port);
898         return ENODEV;
899     }
900
901     return (ofproto->ofproto_class->get_stp_port_status
902             ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
903             : EOPNOTSUPP);
904 }
905
906 /* Retrieves STP port statistics of 'ofp_port' on 'ofproto' and stores it in
907  * 's'.  If the 'enabled' member in 's' is false, then the other members
908  * are not meaningful.
909  *
910  * Returns 0 if successful, otherwise a positive errno value.*/
911 int
912 ofproto_port_get_stp_stats(struct ofproto *ofproto, ofp_port_t ofp_port,
913                            struct ofproto_port_stp_stats *s)
914 {
915     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
916     if (!ofport) {
917         VLOG_WARN_RL(&rl, "%s: cannot get STP stats on nonexistent "
918                      "port %"PRIu16, ofproto->name, ofp_port);
919         return ENODEV;
920     }
921
922     return (ofproto->ofproto_class->get_stp_port_stats
923             ? ofproto->ofproto_class->get_stp_port_stats(ofport, s)
924             : EOPNOTSUPP);
925 }
926 \f
927 /* Queue DSCP configuration. */
928
929 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
930  * 'queues' attached to 'ofport'.  This data is not intended to be sufficient
931  * to implement QoS.  Instead, it is used to implement features which require
932  * knowledge of what queues exist on a port, and some basic information about
933  * them.
934  *
935  * Returns 0 if successful, otherwise a positive errno value. */
936 int
937 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
938                         const struct ofproto_port_queue *queues,
939                         size_t n_queues)
940 {
941     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
942
943     if (!ofport) {
944         VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu16,
945                   ofproto->name, ofp_port);
946         return ENODEV;
947     }
948
949     return (ofproto->ofproto_class->set_queues
950             ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
951             : EOPNOTSUPP);
952 }
953 \f
954 /* Connectivity Fault Management configuration. */
955
956 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
957 void
958 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
959 {
960     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
961     if (ofport && ofproto->ofproto_class->set_cfm) {
962         ofproto->ofproto_class->set_cfm(ofport, NULL);
963     }
964 }
965
966 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'.  Takes
967  * basic configuration from the configuration members in 'cfm', and the remote
968  * maintenance point ID from  remote_mpid.  Ignores the statistics members of
969  * 'cfm'.
970  *
971  * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
972 void
973 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
974                      const struct cfm_settings *s)
975 {
976     struct ofport *ofport;
977     int error;
978
979     ofport = ofproto_get_port(ofproto, ofp_port);
980     if (!ofport) {
981         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
982                   ofproto->name, ofp_port);
983         return;
984     }
985
986     /* XXX: For configuration simplicity, we only support one remote_mpid
987      * outside of the CFM module.  It's not clear if this is the correct long
988      * term solution or not. */
989     error = (ofproto->ofproto_class->set_cfm
990              ? ofproto->ofproto_class->set_cfm(ofport, s)
991              : EOPNOTSUPP);
992     if (error) {
993         VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
994                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
995                   ovs_strerror(error));
996     }
997 }
998
999 /* Configures BFD on 'ofp_port' in 'ofproto'.  This function has no effect if
1000  * 'ofproto' does not have a port 'ofp_port'. */
1001 void
1002 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
1003                      const struct smap *cfg)
1004 {
1005     struct ofport *ofport;
1006     int error;
1007
1008     ofport = ofproto_get_port(ofproto, ofp_port);
1009     if (!ofport) {
1010         VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu16,
1011                   ofproto->name, ofp_port);
1012         return;
1013     }
1014
1015     error = (ofproto->ofproto_class->set_bfd
1016              ? ofproto->ofproto_class->set_bfd(ofport, cfg)
1017              : EOPNOTSUPP);
1018     if (error) {
1019         VLOG_WARN("%s: bfd configuration on port %"PRIu16" (%s) failed (%s)",
1020                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1021                   ovs_strerror(error));
1022     }
1023 }
1024
1025 /* Populates 'status' with the status of BFD on 'ofport'.  Returns 0 on
1026  * success.  Returns a negative number if there is no status change since
1027  * last update.  Returns a positive errno otherwise.  Has no effect if
1028  * 'ofp_port' is not an OpenFlow port in 'ofproto'.
1029  *
1030  * The caller must provide and own '*status'. */
1031 int
1032 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
1033                             struct smap *status)
1034 {
1035     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1036     return (ofport && ofproto->ofproto_class->get_bfd_status
1037             ? ofproto->ofproto_class->get_bfd_status(ofport, status)
1038             : EOPNOTSUPP);
1039 }
1040
1041 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
1042  * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
1043  * 0 if LACP partner information is not current (generally indicating a
1044  * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
1045 int
1046 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
1047 {
1048     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1049     return (ofport && ofproto->ofproto_class->port_is_lacp_current
1050             ? ofproto->ofproto_class->port_is_lacp_current(ofport)
1051             : -1);
1052 }
1053 \f
1054 /* Bundles. */
1055
1056 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
1057  * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
1058  * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
1059  * configuration plus, if there is more than one slave, a bonding
1060  * configuration.
1061  *
1062  * If 'aux' is already registered then this function updates its configuration
1063  * to 's'.  Otherwise, this function registers a new bundle.
1064  *
1065  * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
1066  * port. */
1067 int
1068 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
1069                         const struct ofproto_bundle_settings *s)
1070 {
1071     return (ofproto->ofproto_class->bundle_set
1072             ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1073             : EOPNOTSUPP);
1074 }
1075
1076 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1077  * If no such bundle has been registered, this has no effect. */
1078 int
1079 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1080 {
1081     return ofproto_bundle_register(ofproto, aux, NULL);
1082 }
1083
1084 \f
1085 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1086  * If 'aux' is already registered then this function updates its configuration
1087  * to 's'.  Otherwise, this function registers a new mirror. */
1088 int
1089 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1090                         const struct ofproto_mirror_settings *s)
1091 {
1092     return (ofproto->ofproto_class->mirror_set
1093             ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1094             : EOPNOTSUPP);
1095 }
1096
1097 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1098  * If no mirror has been registered, this has no effect. */
1099 int
1100 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1101 {
1102     return ofproto_mirror_register(ofproto, aux, NULL);
1103 }
1104
1105 /* Retrieves statistics from mirror associated with client data pointer
1106  * 'aux' in 'ofproto'.  Stores packet and byte counts in 'packets' and
1107  * 'bytes', respectively.  If a particular counters is not supported,
1108  * the appropriate argument is set to UINT64_MAX. */
1109 int
1110 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1111                          uint64_t *packets, uint64_t *bytes)
1112 {
1113     if (!ofproto->ofproto_class->mirror_get_stats) {
1114         *packets = *bytes = UINT64_MAX;
1115         return EOPNOTSUPP;
1116     }
1117
1118     return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1119                                                     packets, bytes);
1120 }
1121
1122 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1123  * which all packets are flooded, instead of using MAC learning.  If
1124  * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1125  *
1126  * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1127  * port. */
1128 int
1129 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1130 {
1131     return (ofproto->ofproto_class->set_flood_vlans
1132             ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1133             : EOPNOTSUPP);
1134 }
1135
1136 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1137  * output for a mirror. */
1138 bool
1139 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1140 {
1141     return (ofproto->ofproto_class->is_mirror_output_bundle
1142             ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1143             : false);
1144 }
1145 \f
1146 /* Configuration of OpenFlow tables. */
1147
1148 /* Returns the number of OpenFlow tables in 'ofproto'. */
1149 int
1150 ofproto_get_n_tables(const struct ofproto *ofproto)
1151 {
1152     return ofproto->n_tables;
1153 }
1154
1155 /* Returns the number of Controller visible OpenFlow tables
1156  * in 'ofproto'. This number will exclude Hidden tables.
1157  * This funtion's return value should be less or equal to that of
1158  * ofproto_get_n_tables() . */
1159 uint8_t
1160 ofproto_get_n_visible_tables(const struct ofproto *ofproto)
1161 {
1162     uint8_t n = ofproto->n_tables;
1163
1164     /* Count only non-hidden tables in the number of tables.  (Hidden tables,
1165      * if present, are always at the end.) */
1166     while(n && (ofproto->tables[n - 1].flags & OFTABLE_HIDDEN)) {
1167         n--;
1168     }
1169
1170     return n;
1171 }
1172
1173 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1174  * settings from 's'.  'table_id' must be in the range 0 through the number of
1175  * OpenFlow tables in 'ofproto' minus 1, inclusive.
1176  *
1177  * For read-only tables, only the name may be configured. */
1178 void
1179 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1180                         const struct ofproto_table_settings *s)
1181 {
1182     struct oftable *table;
1183
1184     ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1185     table = &ofproto->tables[table_id];
1186
1187     oftable_set_name(table, s->name);
1188
1189     if (table->flags & OFTABLE_READONLY) {
1190         return;
1191     }
1192
1193     if (s->groups) {
1194         oftable_enable_eviction(table, s->groups, s->n_groups);
1195     } else {
1196         oftable_disable_eviction(table);
1197     }
1198
1199     table->max_flows = s->max_flows;
1200     fat_rwlock_wrlock(&table->cls.rwlock);
1201     if (classifier_count(&table->cls) > table->max_flows
1202         && table->eviction_fields) {
1203         /* 'table' contains more flows than allowed.  We might not be able to
1204          * evict them right away because of the asynchronous nature of flow
1205          * table changes.  Schedule eviction for later. */
1206         switch (ofproto->state) {
1207         case S_OPENFLOW:
1208             ofproto->state = S_EVICT;
1209             break;
1210         case S_EVICT:
1211         case S_FLUSH:
1212             /* We're already deleting flows, nothing more to do. */
1213             break;
1214         }
1215     }
1216
1217     classifier_set_prefix_fields(&table->cls,
1218                                  s->prefix_fields, s->n_prefix_fields);
1219
1220     fat_rwlock_unlock(&table->cls.rwlock);
1221 }
1222 \f
1223 bool
1224 ofproto_has_snoops(const struct ofproto *ofproto)
1225 {
1226     return connmgr_has_snoops(ofproto->connmgr);
1227 }
1228
1229 void
1230 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1231 {
1232     connmgr_get_snoops(ofproto->connmgr, snoops);
1233 }
1234
1235 static void
1236 ofproto_rule_delete__(struct ofproto *ofproto, struct rule *rule,
1237                       uint8_t reason)
1238     OVS_REQUIRES(ofproto_mutex)
1239 {
1240     struct ofopgroup *group;
1241
1242     ovs_assert(!rule->pending);
1243
1244     group = ofopgroup_create_unattached(ofproto);
1245     delete_flow__(rule, group, reason);
1246     ofopgroup_submit(group);
1247 }
1248
1249 /* Deletes 'rule' from 'ofproto'.
1250  *
1251  * Within an ofproto implementation, this function allows an ofproto
1252  * implementation to destroy any rules that remain when its ->destruct()
1253  * function is called.  This function is not suitable for use elsewhere in an
1254  * ofproto implementation.
1255  *
1256  * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1257  * Cycle" in ofproto-provider.h. */
1258 void
1259 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1260     OVS_EXCLUDED(ofproto_mutex)
1261 {
1262     struct ofopgroup *group;
1263
1264     ovs_mutex_lock(&ofproto_mutex);
1265     ovs_assert(!rule->pending);
1266
1267     group = ofopgroup_create_unattached(ofproto);
1268     ofoperation_create(group, rule, OFOPERATION_DELETE, OFPRR_DELETE);
1269     oftable_remove_rule__(ofproto, rule);
1270     ofproto->ofproto_class->rule_delete(rule);
1271     ofopgroup_submit(group);
1272
1273     ovs_mutex_unlock(&ofproto_mutex);
1274 }
1275
1276 static void
1277 ofproto_flush__(struct ofproto *ofproto)
1278     OVS_EXCLUDED(ofproto_mutex)
1279 {
1280     struct oftable *table;
1281
1282     if (ofproto->ofproto_class->flush) {
1283         ofproto->ofproto_class->flush(ofproto);
1284     }
1285
1286     ovs_mutex_lock(&ofproto_mutex);
1287     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1288         struct rule *rule, *next_rule;
1289         struct cls_cursor cursor;
1290
1291         if (table->flags & OFTABLE_HIDDEN) {
1292             continue;
1293         }
1294
1295         fat_rwlock_rdlock(&table->cls.rwlock);
1296         cls_cursor_init(&cursor, &table->cls, NULL);
1297         fat_rwlock_unlock(&table->cls.rwlock);
1298         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
1299             if (!rule->pending) {
1300                 ofproto_rule_delete__(ofproto, rule, OFPRR_DELETE);
1301             }
1302         }
1303     }
1304     ovs_mutex_unlock(&ofproto_mutex);
1305 }
1306
1307 static void delete_group(struct ofproto *ofproto, uint32_t group_id);
1308
1309 static void
1310 ofproto_destroy__(struct ofproto *ofproto)
1311     OVS_EXCLUDED(ofproto_mutex)
1312 {
1313     struct oftable *table;
1314
1315     ovs_assert(list_is_empty(&ofproto->pending));
1316
1317     destroy_rule_executes(ofproto);
1318     delete_group(ofproto, OFPG_ALL);
1319
1320     guarded_list_destroy(&ofproto->rule_executes);
1321     ovs_rwlock_destroy(&ofproto->groups_rwlock);
1322     hmap_destroy(&ofproto->groups);
1323
1324     connmgr_destroy(ofproto->connmgr);
1325
1326     hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1327     free(ofproto->name);
1328     free(ofproto->type);
1329     free(ofproto->mfr_desc);
1330     free(ofproto->hw_desc);
1331     free(ofproto->sw_desc);
1332     free(ofproto->serial_desc);
1333     free(ofproto->dp_desc);
1334     hmap_destroy(&ofproto->ports);
1335     hmap_destroy(&ofproto->ofport_usage);
1336     shash_destroy(&ofproto->port_by_name);
1337     simap_destroy(&ofproto->ofp_requests);
1338
1339     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1340         oftable_destroy(table);
1341     }
1342     free(ofproto->tables);
1343
1344     hmap_destroy(&ofproto->deletions);
1345
1346     ovs_assert(hindex_is_empty(&ofproto->cookies));
1347     hindex_destroy(&ofproto->cookies);
1348
1349     free(ofproto->vlan_bitmap);
1350
1351     ofproto->ofproto_class->dealloc(ofproto);
1352 }
1353
1354 void
1355 ofproto_destroy(struct ofproto *p)
1356     OVS_EXCLUDED(ofproto_mutex)
1357 {
1358     struct ofport *ofport, *next_ofport;
1359     struct ofport_usage *usage, *next_usage;
1360
1361     if (!p) {
1362         return;
1363     }
1364
1365     if (p->meters) {
1366         meter_delete(p, 1, p->meter_features.max_meters);
1367         p->meter_features.max_meters = 0;
1368         free(p->meters);
1369         p->meters = NULL;
1370     }
1371
1372     ofproto_flush__(p);
1373     HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1374         ofport_destroy(ofport);
1375     }
1376
1377     HMAP_FOR_EACH_SAFE (usage, next_usage, hmap_node, &p->ofport_usage) {
1378         hmap_remove(&p->ofport_usage, &usage->hmap_node);
1379         free(usage);
1380     }
1381
1382     p->ofproto_class->destruct(p);
1383     /* Destroying rules is deferred, must have 'ofproto' around for them. */
1384     ovsrcu_postpone(ofproto_destroy__, p);
1385 }
1386
1387 /* Destroys the datapath with the respective 'name' and 'type'.  With the Linux
1388  * kernel datapath, for example, this destroys the datapath in the kernel, and
1389  * with the netdev-based datapath, it tears down the data structures that
1390  * represent the datapath.
1391  *
1392  * The datapath should not be currently open as an ofproto. */
1393 int
1394 ofproto_delete(const char *name, const char *type)
1395 {
1396     const struct ofproto_class *class = ofproto_class_find__(type);
1397     return (!class ? EAFNOSUPPORT
1398             : !class->del ? EACCES
1399             : class->del(type, name));
1400 }
1401
1402 static void
1403 process_port_change(struct ofproto *ofproto, int error, char *devname)
1404 {
1405     if (error == ENOBUFS) {
1406         reinit_ports(ofproto);
1407     } else if (!error) {
1408         update_port(ofproto, devname);
1409         free(devname);
1410     }
1411 }
1412
1413 int
1414 ofproto_type_run(const char *datapath_type)
1415 {
1416     const struct ofproto_class *class;
1417     int error;
1418
1419     datapath_type = ofproto_normalize_type(datapath_type);
1420     class = ofproto_class_find__(datapath_type);
1421
1422     error = class->type_run ? class->type_run(datapath_type) : 0;
1423     if (error && error != EAGAIN) {
1424         VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1425                     datapath_type, ovs_strerror(error));
1426     }
1427     return error;
1428 }
1429
1430 void
1431 ofproto_type_wait(const char *datapath_type)
1432 {
1433     const struct ofproto_class *class;
1434
1435     datapath_type = ofproto_normalize_type(datapath_type);
1436     class = ofproto_class_find__(datapath_type);
1437
1438     if (class->type_wait) {
1439         class->type_wait(datapath_type);
1440     }
1441 }
1442
1443 static bool
1444 any_pending_ops(const struct ofproto *p)
1445     OVS_EXCLUDED(ofproto_mutex)
1446 {
1447     bool b;
1448
1449     ovs_mutex_lock(&ofproto_mutex);
1450     b = !list_is_empty(&p->pending);
1451     ovs_mutex_unlock(&ofproto_mutex);
1452
1453     return b;
1454 }
1455
1456 int
1457 ofproto_run(struct ofproto *p)
1458 {
1459     int error;
1460     uint64_t new_seq;
1461
1462     error = p->ofproto_class->run(p);
1463     if (error && error != EAGAIN) {
1464         VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1465     }
1466
1467     run_rule_executes(p);
1468
1469     /* Restore the eviction group heap invariant occasionally. */
1470     if (p->eviction_group_timer < time_msec()) {
1471         size_t i;
1472
1473         p->eviction_group_timer = time_msec() + 1000;
1474
1475         for (i = 0; i < p->n_tables; i++) {
1476             struct oftable *table = &p->tables[i];
1477             struct eviction_group *evg;
1478             struct cls_cursor cursor;
1479             struct rule *rule;
1480
1481             if (!table->eviction_fields) {
1482                 continue;
1483             }
1484
1485             ovs_mutex_lock(&ofproto_mutex);
1486             fat_rwlock_rdlock(&table->cls.rwlock);
1487             cls_cursor_init(&cursor, &table->cls, NULL);
1488             CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1489                 if (rule->idle_timeout || rule->hard_timeout) {
1490                     if (!rule->eviction_group) {
1491                         eviction_group_add_rule(rule);
1492                     } else {
1493                         heap_raw_change(&rule->evg_node,
1494                                         rule_eviction_priority(p, rule));
1495                     }
1496                 }
1497             }
1498             fat_rwlock_unlock(&table->cls.rwlock);
1499
1500             HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1501                 heap_rebuild(&evg->rules);
1502             }
1503             ovs_mutex_unlock(&ofproto_mutex);
1504         }
1505     }
1506
1507     if (p->ofproto_class->port_poll) {
1508         char *devname;
1509
1510         while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1511             process_port_change(p, error, devname);
1512         }
1513     }
1514
1515     new_seq = seq_read(connectivity_seq_get());
1516     if (new_seq != p->change_seq) {
1517         struct sset devnames;
1518         const char *devname;
1519         struct ofport *ofport;
1520
1521         /* Update OpenFlow port status for any port whose netdev has changed.
1522          *
1523          * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1524          * destroyed, so it's not safe to update ports directly from the
1525          * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE.  Instead, we
1526          * need this two-phase approach. */
1527         sset_init(&devnames);
1528         HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1529             uint64_t port_change_seq;
1530
1531             port_change_seq = netdev_get_change_seq(ofport->netdev);
1532             if (ofport->change_seq != port_change_seq) {
1533                 ofport->change_seq = port_change_seq;
1534                 sset_add(&devnames, netdev_get_name(ofport->netdev));
1535             }
1536         }
1537         SSET_FOR_EACH (devname, &devnames) {
1538             update_port(p, devname);
1539         }
1540         sset_destroy(&devnames);
1541
1542         p->change_seq = new_seq;
1543     }
1544
1545     switch (p->state) {
1546     case S_OPENFLOW:
1547         connmgr_run(p->connmgr, handle_openflow);
1548         break;
1549
1550     case S_EVICT:
1551         connmgr_run(p->connmgr, NULL);
1552         ofproto_evict(p);
1553         if (!any_pending_ops(p)) {
1554             p->state = S_OPENFLOW;
1555         }
1556         break;
1557
1558     case S_FLUSH:
1559         connmgr_run(p->connmgr, NULL);
1560         ofproto_flush__(p);
1561         if (!any_pending_ops(p)) {
1562             connmgr_flushed(p->connmgr);
1563             p->state = S_OPENFLOW;
1564         }
1565         break;
1566
1567     default:
1568         OVS_NOT_REACHED();
1569     }
1570
1571     return error;
1572 }
1573
1574 void
1575 ofproto_wait(struct ofproto *p)
1576 {
1577     p->ofproto_class->wait(p);
1578     if (p->ofproto_class->port_poll_wait) {
1579         p->ofproto_class->port_poll_wait(p);
1580     }
1581     seq_wait(connectivity_seq_get(), p->change_seq);
1582
1583     switch (p->state) {
1584     case S_OPENFLOW:
1585         connmgr_wait(p->connmgr, true);
1586         break;
1587
1588     case S_EVICT:
1589     case S_FLUSH:
1590         connmgr_wait(p->connmgr, false);
1591         if (!any_pending_ops(p)) {
1592             poll_immediate_wake();
1593         }
1594         break;
1595     }
1596 }
1597
1598 bool
1599 ofproto_is_alive(const struct ofproto *p)
1600 {
1601     return connmgr_has_controllers(p->connmgr);
1602 }
1603
1604 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1605  * memory_report(). */
1606 void
1607 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1608 {
1609     const struct oftable *table;
1610     unsigned int n_rules;
1611
1612     simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1613
1614     ovs_mutex_lock(&ofproto_mutex);
1615     simap_increase(usage, "ops",
1616                    ofproto->n_pending + hmap_count(&ofproto->deletions));
1617     ovs_mutex_unlock(&ofproto_mutex);
1618
1619     n_rules = 0;
1620     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1621         fat_rwlock_rdlock(&table->cls.rwlock);
1622         n_rules += classifier_count(&table->cls);
1623         fat_rwlock_unlock(&table->cls.rwlock);
1624     }
1625     simap_increase(usage, "rules", n_rules);
1626
1627     if (ofproto->ofproto_class->get_memory_usage) {
1628         ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1629     }
1630
1631     connmgr_get_memory_usage(ofproto->connmgr, usage);
1632 }
1633
1634 void
1635 ofproto_type_get_memory_usage(const char *datapath_type, struct simap *usage)
1636 {
1637     const struct ofproto_class *class;
1638
1639     datapath_type = ofproto_normalize_type(datapath_type);
1640     class = ofproto_class_find__(datapath_type);
1641
1642     if (class && class->type_get_memory_usage) {
1643         class->type_get_memory_usage(datapath_type, usage);
1644     }
1645 }
1646
1647 void
1648 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1649                                     struct shash *info)
1650 {
1651     connmgr_get_controller_info(ofproto->connmgr, info);
1652 }
1653
1654 void
1655 ofproto_free_ofproto_controller_info(struct shash *info)
1656 {
1657     connmgr_free_controller_info(info);
1658 }
1659
1660 /* Makes a deep copy of 'old' into 'port'. */
1661 void
1662 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1663 {
1664     port->name = xstrdup(old->name);
1665     port->type = xstrdup(old->type);
1666     port->ofp_port = old->ofp_port;
1667 }
1668
1669 /* Frees memory allocated to members of 'ofproto_port'.
1670  *
1671  * Do not call this function on an ofproto_port obtained from
1672  * ofproto_port_dump_next(): that function retains ownership of the data in the
1673  * ofproto_port. */
1674 void
1675 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1676 {
1677     free(ofproto_port->name);
1678     free(ofproto_port->type);
1679 }
1680
1681 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1682  *
1683  * This function provides no status indication.  An error status for the entire
1684  * dump operation is provided when it is completed by calling
1685  * ofproto_port_dump_done().
1686  */
1687 void
1688 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1689                         const struct ofproto *ofproto)
1690 {
1691     dump->ofproto = ofproto;
1692     dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1693                                                           &dump->state);
1694 }
1695
1696 /* Attempts to retrieve another port from 'dump', which must have been created
1697  * with ofproto_port_dump_start().  On success, stores a new ofproto_port into
1698  * 'port' and returns true.  On failure, returns false.
1699  *
1700  * Failure might indicate an actual error or merely that the last port has been
1701  * dumped.  An error status for the entire dump operation is provided when it
1702  * is completed by calling ofproto_port_dump_done().
1703  *
1704  * The ofproto owns the data stored in 'port'.  It will remain valid until at
1705  * least the next time 'dump' is passed to ofproto_port_dump_next() or
1706  * ofproto_port_dump_done(). */
1707 bool
1708 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1709                        struct ofproto_port *port)
1710 {
1711     const struct ofproto *ofproto = dump->ofproto;
1712
1713     if (dump->error) {
1714         return false;
1715     }
1716
1717     dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1718                                                          port);
1719     if (dump->error) {
1720         ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1721         return false;
1722     }
1723     return true;
1724 }
1725
1726 /* Completes port table dump operation 'dump', which must have been created
1727  * with ofproto_port_dump_start().  Returns 0 if the dump operation was
1728  * error-free, otherwise a positive errno value describing the problem. */
1729 int
1730 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1731 {
1732     const struct ofproto *ofproto = dump->ofproto;
1733     if (!dump->error) {
1734         dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1735                                                              dump->state);
1736     }
1737     return dump->error == EOF ? 0 : dump->error;
1738 }
1739
1740 /* Returns the type to pass to netdev_open() when a datapath of type
1741  * 'datapath_type' has a port of type 'port_type', for a few special
1742  * cases when a netdev type differs from a port type.  For example, when
1743  * using the userspace datapath, a port of type "internal" needs to be
1744  * opened as "tap".
1745  *
1746  * Returns either 'type' itself or a string literal, which must not be
1747  * freed. */
1748 const char *
1749 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1750 {
1751     const struct ofproto_class *class;
1752
1753     datapath_type = ofproto_normalize_type(datapath_type);
1754     class = ofproto_class_find__(datapath_type);
1755     if (!class) {
1756         return port_type;
1757     }
1758
1759     return (class->port_open_type
1760             ? class->port_open_type(datapath_type, port_type)
1761             : port_type);
1762 }
1763
1764 /* Attempts to add 'netdev' as a port on 'ofproto'.  If 'ofp_portp' is
1765  * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1766  * the port's OpenFlow port number.
1767  *
1768  * If successful, returns 0 and sets '*ofp_portp' to the new port's
1769  * OpenFlow port number (if 'ofp_portp' is non-null).  On failure,
1770  * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1771  * 'ofp_portp' is non-null). */
1772 int
1773 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1774                  ofp_port_t *ofp_portp)
1775 {
1776     ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
1777     int error;
1778
1779     error = ofproto->ofproto_class->port_add(ofproto, netdev);
1780     if (!error) {
1781         const char *netdev_name = netdev_get_name(netdev);
1782
1783         simap_put(&ofproto->ofp_requests, netdev_name,
1784                   ofp_to_u16(ofp_port));
1785         update_port(ofproto, netdev_name);
1786     }
1787     if (ofp_portp) {
1788         *ofp_portp = OFPP_NONE;
1789         if (!error) {
1790             struct ofproto_port ofproto_port;
1791
1792             error = ofproto_port_query_by_name(ofproto,
1793                                                netdev_get_name(netdev),
1794                                                &ofproto_port);
1795             if (!error) {
1796                 *ofp_portp = ofproto_port.ofp_port;
1797                 ofproto_port_destroy(&ofproto_port);
1798             }
1799         }
1800     }
1801     return error;
1802 }
1803
1804 /* Looks up a port named 'devname' in 'ofproto'.  On success, returns 0 and
1805  * initializes '*port' appropriately; on failure, returns a positive errno
1806  * value.
1807  *
1808  * The caller owns the data in 'ofproto_port' and must free it with
1809  * ofproto_port_destroy() when it is no longer needed. */
1810 int
1811 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
1812                            struct ofproto_port *port)
1813 {
1814     int error;
1815
1816     error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
1817     if (error) {
1818         memset(port, 0, sizeof *port);
1819     }
1820     return error;
1821 }
1822
1823 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
1824  * Returns 0 if successful, otherwise a positive errno. */
1825 int
1826 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
1827 {
1828     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1829     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1830     struct simap_node *ofp_request_node;
1831     int error;
1832
1833     ofp_request_node = simap_find(&ofproto->ofp_requests, name);
1834     if (ofp_request_node) {
1835         simap_delete(&ofproto->ofp_requests, ofp_request_node);
1836     }
1837
1838     error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1839     if (!error && ofport) {
1840         /* 'name' is the netdev's name and update_port() is going to close the
1841          * netdev.  Just in case update_port() refers to 'name' after it
1842          * destroys 'ofport', make a copy of it around the update_port()
1843          * call. */
1844         char *devname = xstrdup(name);
1845         update_port(ofproto, devname);
1846         free(devname);
1847     }
1848     return error;
1849 }
1850
1851 static void
1852 flow_mod_init(struct ofputil_flow_mod *fm,
1853               const struct match *match, unsigned int priority,
1854               const struct ofpact *ofpacts, size_t ofpacts_len,
1855               enum ofp_flow_mod_command command)
1856 {
1857     memset(fm, 0, sizeof *fm);
1858     fm->match = *match;
1859     fm->priority = priority;
1860     fm->cookie = 0;
1861     fm->new_cookie = 0;
1862     fm->modify_cookie = false;
1863     fm->table_id = 0;
1864     fm->command = command;
1865     fm->idle_timeout = 0;
1866     fm->hard_timeout = 0;
1867     fm->buffer_id = UINT32_MAX;
1868     fm->out_port = OFPP_ANY;
1869     fm->out_group = OFPG_ANY;
1870     fm->flags = 0;
1871     fm->ofpacts = CONST_CAST(struct ofpact *, ofpacts);
1872     fm->ofpacts_len = ofpacts_len;
1873     fm->delete_reason = OFPRR_DELETE;
1874 }
1875
1876 static int
1877 simple_flow_mod(struct ofproto *ofproto,
1878                 const struct match *match, unsigned int priority,
1879                 const struct ofpact *ofpacts, size_t ofpacts_len,
1880                 enum ofp_flow_mod_command command)
1881 {
1882     struct ofputil_flow_mod fm;
1883
1884     flow_mod_init(&fm, match, priority, ofpacts, ofpacts_len, command);
1885
1886     return handle_flow_mod__(ofproto, NULL, &fm, NULL);
1887 }
1888
1889 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1890  * performs the 'n_actions' actions in 'actions'.  The new flow will not
1891  * timeout.
1892  *
1893  * If cls_rule->priority is in the range of priorities supported by OpenFlow
1894  * (0...65535, inclusive) then the flow will be visible to OpenFlow
1895  * controllers; otherwise, it will be hidden.
1896  *
1897  * The caller retains ownership of 'cls_rule' and 'ofpacts'.
1898  *
1899  * This is a helper function for in-band control and fail-open. */
1900 void
1901 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
1902                  unsigned int priority,
1903                  const struct ofpact *ofpacts, size_t ofpacts_len)
1904     OVS_EXCLUDED(ofproto_mutex)
1905 {
1906     const struct rule *rule;
1907     bool must_add;
1908
1909     /* First do a cheap check whether the rule we're looking for already exists
1910      * with the actions that we want.  If it does, then we're done. */
1911     fat_rwlock_rdlock(&ofproto->tables[0].cls.rwlock);
1912     rule = rule_from_cls_rule(classifier_find_match_exactly(
1913                                   &ofproto->tables[0].cls, match, priority));
1914     if (rule) {
1915         const struct rule_actions *actions = rule_get_actions(rule);
1916         must_add = !ofpacts_equal(actions->ofpacts, actions->ofpacts_len,
1917                                   ofpacts, ofpacts_len);
1918     } else {
1919         must_add = true;
1920     }
1921     fat_rwlock_unlock(&ofproto->tables[0].cls.rwlock);
1922
1923     /* If there's no such rule or the rule doesn't have the actions we want,
1924      * fall back to a executing a full flow mod.  We can't optimize this at
1925      * all because we didn't take enough locks above to ensure that the flow
1926      * table didn't already change beneath us.  */
1927     if (must_add) {
1928         simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
1929                         OFPFC_MODIFY_STRICT);
1930     }
1931 }
1932
1933 /* Executes the flow modification specified in 'fm'.  Returns 0 on success, an
1934  * OFPERR_* OpenFlow error code on failure, or OFPROTO_POSTPONE if the
1935  * operation cannot be initiated now but may be retried later.
1936  *
1937  * This is a helper function for in-band control and fail-open and the "learn"
1938  * action. */
1939 int
1940 ofproto_flow_mod(struct ofproto *ofproto, struct ofputil_flow_mod *fm)
1941     OVS_EXCLUDED(ofproto_mutex)
1942 {
1943     /* Optimize for the most common case of a repeated learn action.
1944      * If an identical flow already exists we only need to update its
1945      * 'modified' time. */
1946     if (fm->command == OFPFC_MODIFY_STRICT && fm->table_id != OFPTT_ALL
1947         && !(fm->flags & OFPUTIL_FF_RESET_COUNTS)) {
1948         struct oftable *table = &ofproto->tables[fm->table_id];
1949         struct rule *rule;
1950         bool done = false;
1951
1952         fat_rwlock_rdlock(&table->cls.rwlock);
1953         rule = rule_from_cls_rule(classifier_find_match_exactly(&table->cls,
1954                                                                 &fm->match,
1955                                                                 fm->priority));
1956         if (rule) {
1957             /* Reading many of the rule fields and writing on 'modified'
1958              * requires the rule->mutex.  Also, rule->actions may change
1959              * if rule->mutex is not held. */
1960             const struct rule_actions *actions;
1961
1962             ovs_mutex_lock(&rule->mutex);
1963             actions = rule_get_actions(rule);
1964             if (rule->idle_timeout == fm->idle_timeout
1965                 && rule->hard_timeout == fm->hard_timeout
1966                 && rule->flags == (fm->flags & OFPUTIL_FF_STATE)
1967                 && (!fm->modify_cookie || (fm->new_cookie == rule->flow_cookie))
1968                 && ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
1969                                  actions->ofpacts, actions->ofpacts_len)) {
1970                 /* Rule already exists and need not change, only update the
1971                    modified timestamp. */
1972                 rule->modified = time_msec();
1973                 done = true;
1974             }
1975             ovs_mutex_unlock(&rule->mutex);
1976         }
1977         fat_rwlock_unlock(&table->cls.rwlock);
1978
1979         if (done) {
1980             return 0;
1981         }
1982     }
1983
1984     return handle_flow_mod__(ofproto, NULL, fm, NULL);
1985 }
1986
1987 /* Searches for a rule with matching criteria exactly equal to 'target' in
1988  * ofproto's table 0 and, if it finds one, deletes it.
1989  *
1990  * This is a helper function for in-band control and fail-open. */
1991 bool
1992 ofproto_delete_flow(struct ofproto *ofproto,
1993                     const struct match *target, unsigned int priority)
1994     OVS_EXCLUDED(ofproto_mutex)
1995 {
1996     struct classifier *cls = &ofproto->tables[0].cls;
1997     struct rule *rule;
1998
1999     /* First do a cheap check whether the rule we're looking for has already
2000      * been deleted.  If so, then we're done. */
2001     fat_rwlock_rdlock(&cls->rwlock);
2002     rule = rule_from_cls_rule(classifier_find_match_exactly(cls, target,
2003                                                             priority));
2004     fat_rwlock_unlock(&cls->rwlock);
2005     if (!rule) {
2006         return true;
2007     }
2008
2009     /* Fall back to a executing a full flow mod.  We can't optimize this at all
2010      * because we didn't take enough locks above to ensure that the flow table
2011      * didn't already change beneath us.  */
2012     return simple_flow_mod(ofproto, target, priority, NULL, 0,
2013                            OFPFC_DELETE_STRICT) != OFPROTO_POSTPONE;
2014 }
2015
2016 /* Starts the process of deleting all of the flows from all of ofproto's flow
2017  * tables and then reintroducing the flows required by in-band control and
2018  * fail-open.  The process will complete in a later call to ofproto_run(). */
2019 void
2020 ofproto_flush_flows(struct ofproto *ofproto)
2021 {
2022     COVERAGE_INC(ofproto_flush);
2023     ofproto->state = S_FLUSH;
2024 }
2025 \f
2026 static void
2027 reinit_ports(struct ofproto *p)
2028 {
2029     struct ofproto_port_dump dump;
2030     struct sset devnames;
2031     struct ofport *ofport;
2032     struct ofproto_port ofproto_port;
2033     const char *devname;
2034
2035     COVERAGE_INC(ofproto_reinit_ports);
2036
2037     sset_init(&devnames);
2038     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2039         sset_add(&devnames, netdev_get_name(ofport->netdev));
2040     }
2041     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2042         sset_add(&devnames, ofproto_port.name);
2043     }
2044
2045     SSET_FOR_EACH (devname, &devnames) {
2046         update_port(p, devname);
2047     }
2048     sset_destroy(&devnames);
2049 }
2050
2051 static ofp_port_t
2052 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
2053 {
2054     uint16_t port_idx;
2055
2056     port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
2057     port_idx = port_idx ? port_idx : UINT16_MAX;
2058
2059     if (port_idx >= ofproto->max_ports
2060         || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
2061         uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
2062         long long int last_used_at, lru = LLONG_MAX;
2063
2064         /* Search for a free OpenFlow port number.  We try not to
2065          * immediately reuse them to prevent problems due to old
2066          * flows.
2067          *
2068          * We limit the automatically assigned port numbers to the lower half
2069          * of the port range, to reserve the upper half for assignment by
2070          * controllers. */
2071         for (;;) {
2072             if (++ofproto->alloc_port_no >= MIN(ofproto->max_ports, 32768)) {
2073                 ofproto->alloc_port_no = 1;
2074             }
2075             last_used_at = ofport_get_usage(ofproto,
2076                                          u16_to_ofp(ofproto->alloc_port_no));
2077             if (!last_used_at) {
2078                 port_idx = ofproto->alloc_port_no;
2079                 break;
2080             } else if ( last_used_at < time_msec() - 60*60*1000) {
2081                 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
2082                  * more than an hour ago, consider it usable. */
2083                 ofport_remove_usage(ofproto,
2084                     u16_to_ofp(ofproto->alloc_port_no));
2085                 port_idx = ofproto->alloc_port_no;
2086                 break;
2087             } else if (last_used_at < lru) {
2088                 lru = last_used_at;
2089                 lru_ofport = ofproto->alloc_port_no;
2090             }
2091
2092             if (ofproto->alloc_port_no == end_port_no) {
2093                 if (lru_ofport) {
2094                     port_idx = lru_ofport;
2095                     break;
2096                 }
2097                 return OFPP_NONE;
2098             }
2099         }
2100     }
2101     ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
2102     return u16_to_ofp(port_idx);
2103 }
2104
2105 static void
2106 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2107 {
2108     if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2109         ofport_set_usage(ofproto, ofp_port, time_msec());
2110     }
2111 }
2112
2113 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2114  * pointer if the netdev cannot be opened.  On success, also fills in
2115  * '*pp'.  */
2116 static struct netdev *
2117 ofport_open(struct ofproto *ofproto,
2118             struct ofproto_port *ofproto_port,
2119             struct ofputil_phy_port *pp)
2120 {
2121     enum netdev_flags flags;
2122     struct netdev *netdev;
2123     int error;
2124
2125     error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2126     if (error) {
2127         VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu16") because netdev %s "
2128                      "cannot be opened (%s)",
2129                      ofproto->name,
2130                      ofproto_port->name, ofproto_port->ofp_port,
2131                      ofproto_port->name, ovs_strerror(error));
2132         return NULL;
2133     }
2134
2135     if (ofproto_port->ofp_port == OFPP_NONE) {
2136         if (!strcmp(ofproto->name, ofproto_port->name)) {
2137             ofproto_port->ofp_port = OFPP_LOCAL;
2138         } else {
2139             ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2140                                                     ofproto_port->name);
2141         }
2142     }
2143     pp->port_no = ofproto_port->ofp_port;
2144     netdev_get_etheraddr(netdev, pp->hw_addr);
2145     ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2146     netdev_get_flags(netdev, &flags);
2147     pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2148     pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2149     netdev_get_features(netdev, &pp->curr, &pp->advertised,
2150                         &pp->supported, &pp->peer);
2151     pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2152     pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2153
2154     return netdev;
2155 }
2156
2157 /* Returns true if most fields of 'a' and 'b' are equal.  Differences in name,
2158  * port number, and 'config' bits other than OFPUTIL_PC_PORT_DOWN are
2159  * disregarded. */
2160 static bool
2161 ofport_equal(const struct ofputil_phy_port *a,
2162              const struct ofputil_phy_port *b)
2163 {
2164     return (eth_addr_equals(a->hw_addr, b->hw_addr)
2165             && a->state == b->state
2166             && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2167             && a->curr == b->curr
2168             && a->advertised == b->advertised
2169             && a->supported == b->supported
2170             && a->peer == b->peer
2171             && a->curr_speed == b->curr_speed
2172             && a->max_speed == b->max_speed);
2173 }
2174
2175 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2176  * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2177  * one with the same name or port number). */
2178 static void
2179 ofport_install(struct ofproto *p,
2180                struct netdev *netdev, const struct ofputil_phy_port *pp)
2181 {
2182     const char *netdev_name = netdev_get_name(netdev);
2183     struct ofport *ofport;
2184     int error;
2185
2186     /* Create ofport. */
2187     ofport = p->ofproto_class->port_alloc();
2188     if (!ofport) {
2189         error = ENOMEM;
2190         goto error;
2191     }
2192     ofport->ofproto = p;
2193     ofport->netdev = netdev;
2194     ofport->change_seq = netdev_get_change_seq(netdev);
2195     ofport->pp = *pp;
2196     ofport->ofp_port = pp->port_no;
2197     ofport->created = time_msec();
2198
2199     /* Add port to 'p'. */
2200     hmap_insert(&p->ports, &ofport->hmap_node,
2201                 hash_ofp_port(ofport->ofp_port));
2202     shash_add(&p->port_by_name, netdev_name, ofport);
2203
2204     update_mtu(p, ofport);
2205
2206     /* Let the ofproto_class initialize its private data. */
2207     error = p->ofproto_class->port_construct(ofport);
2208     if (error) {
2209         goto error;
2210     }
2211     connmgr_send_port_status(p->connmgr, NULL, pp, OFPPR_ADD);
2212     return;
2213
2214 error:
2215     VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2216                  p->name, netdev_name, ovs_strerror(error));
2217     if (ofport) {
2218         ofport_destroy__(ofport);
2219     } else {
2220         netdev_close(netdev);
2221     }
2222 }
2223
2224 /* Removes 'ofport' from 'p' and destroys it. */
2225 static void
2226 ofport_remove(struct ofport *ofport)
2227 {
2228     connmgr_send_port_status(ofport->ofproto->connmgr, NULL, &ofport->pp,
2229                              OFPPR_DELETE);
2230     ofport_destroy(ofport);
2231 }
2232
2233 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2234  * destroys it. */
2235 static void
2236 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2237 {
2238     struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2239     if (port) {
2240         ofport_remove(port);
2241     }
2242 }
2243
2244 /* Updates 'port' with new 'pp' description.
2245  *
2246  * Does not handle a name or port number change.  The caller must implement
2247  * such a change as a delete followed by an add.  */
2248 static void
2249 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2250 {
2251     memcpy(port->pp.hw_addr, pp->hw_addr, ETH_ADDR_LEN);
2252     port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2253                         | (pp->config & OFPUTIL_PC_PORT_DOWN));
2254     port->pp.state = ((port->pp.state & ~OFPUTIL_PS_LINK_DOWN)
2255                       | (pp->state & OFPUTIL_PS_LINK_DOWN));
2256     port->pp.curr = pp->curr;
2257     port->pp.advertised = pp->advertised;
2258     port->pp.supported = pp->supported;
2259     port->pp.peer = pp->peer;
2260     port->pp.curr_speed = pp->curr_speed;
2261     port->pp.max_speed = pp->max_speed;
2262
2263     connmgr_send_port_status(port->ofproto->connmgr, NULL,
2264                              &port->pp, OFPPR_MODIFY);
2265 }
2266
2267 /* Update OpenFlow 'state' in 'port' and notify controller. */
2268 void
2269 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2270 {
2271     if (port->pp.state != state) {
2272         port->pp.state = state;
2273         connmgr_send_port_status(port->ofproto->connmgr, NULL,
2274                                  &port->pp, OFPPR_MODIFY);
2275     }
2276 }
2277
2278 void
2279 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2280 {
2281     struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2282     if (port) {
2283         if (port->ofproto->ofproto_class->set_realdev) {
2284             port->ofproto->ofproto_class->set_realdev(port, 0, 0);
2285         }
2286         if (port->ofproto->ofproto_class->set_stp_port) {
2287             port->ofproto->ofproto_class->set_stp_port(port, NULL);
2288         }
2289         if (port->ofproto->ofproto_class->set_cfm) {
2290             port->ofproto->ofproto_class->set_cfm(port, NULL);
2291         }
2292         if (port->ofproto->ofproto_class->bundle_remove) {
2293             port->ofproto->ofproto_class->bundle_remove(port);
2294         }
2295     }
2296 }
2297
2298 static void
2299 ofport_destroy__(struct ofport *port)
2300 {
2301     struct ofproto *ofproto = port->ofproto;
2302     const char *name = netdev_get_name(port->netdev);
2303
2304     hmap_remove(&ofproto->ports, &port->hmap_node);
2305     shash_delete(&ofproto->port_by_name,
2306                  shash_find(&ofproto->port_by_name, name));
2307
2308     netdev_close(port->netdev);
2309     ofproto->ofproto_class->port_dealloc(port);
2310 }
2311
2312 static void
2313 ofport_destroy(struct ofport *port)
2314 {
2315     if (port) {
2316         dealloc_ofp_port(port->ofproto, port->ofp_port);
2317         port->ofproto->ofproto_class->port_destruct(port);
2318         ofport_destroy__(port);
2319      }
2320 }
2321
2322 struct ofport *
2323 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2324 {
2325     struct ofport *port;
2326
2327     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2328                              &ofproto->ports) {
2329         if (port->ofp_port == ofp_port) {
2330             return port;
2331         }
2332     }
2333     return NULL;
2334 }
2335
2336 static long long int
2337 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2338 {
2339     struct ofport_usage *usage;
2340
2341     HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2342                              &ofproto->ofport_usage) {
2343         if (usage->ofp_port == ofp_port) {
2344             return usage->last_used;
2345         }
2346     }
2347     return 0;
2348 }
2349
2350 static void
2351 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2352                  long long int last_used)
2353 {
2354     struct ofport_usage *usage;
2355     HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2356                              &ofproto->ofport_usage) {
2357         if (usage->ofp_port == ofp_port) {
2358             usage->last_used = last_used;
2359             return;
2360         }
2361     }
2362     ovs_assert(last_used == LLONG_MAX);
2363
2364     usage = xmalloc(sizeof *usage);
2365     usage->ofp_port = ofp_port;
2366     usage->last_used = last_used;
2367     hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2368                 hash_ofp_port(ofp_port));
2369 }
2370
2371 static void
2372 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2373 {
2374     struct ofport_usage *usage;
2375     HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2376                              &ofproto->ofport_usage) {
2377         if (usage->ofp_port == ofp_port) {
2378             hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2379             free(usage);
2380             break;
2381         }
2382     }
2383 }
2384
2385 int
2386 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2387 {
2388     struct ofproto *ofproto = port->ofproto;
2389     int error;
2390
2391     if (ofproto->ofproto_class->port_get_stats) {
2392         error = ofproto->ofproto_class->port_get_stats(port, stats);
2393     } else {
2394         error = EOPNOTSUPP;
2395     }
2396
2397     return error;
2398 }
2399
2400 static void
2401 update_port(struct ofproto *ofproto, const char *name)
2402 {
2403     struct ofproto_port ofproto_port;
2404     struct ofputil_phy_port pp;
2405     struct netdev *netdev;
2406     struct ofport *port;
2407
2408     COVERAGE_INC(ofproto_update_port);
2409
2410     /* Fetch 'name''s location and properties from the datapath. */
2411     netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2412               ? ofport_open(ofproto, &ofproto_port, &pp)
2413               : NULL);
2414
2415     if (netdev) {
2416         port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2417         if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2418             struct netdev *old_netdev = port->netdev;
2419
2420             /* 'name' hasn't changed location.  Any properties changed? */
2421             if (!ofport_equal(&port->pp, &pp)) {
2422                 ofport_modified(port, &pp);
2423             }
2424
2425             update_mtu(ofproto, port);
2426
2427             /* Install the newly opened netdev in case it has changed.
2428              * Don't close the old netdev yet in case port_modified has to
2429              * remove a retained reference to it.*/
2430             port->netdev = netdev;
2431             port->change_seq = netdev_get_change_seq(netdev);
2432
2433             if (port->ofproto->ofproto_class->port_modified) {
2434                 port->ofproto->ofproto_class->port_modified(port);
2435             }
2436
2437             netdev_close(old_netdev);
2438         } else {
2439             /* If 'port' is nonnull then its name differs from 'name' and thus
2440              * we should delete it.  If we think there's a port named 'name'
2441              * then its port number must be wrong now so delete it too. */
2442             if (port) {
2443                 ofport_remove(port);
2444             }
2445             ofport_remove_with_name(ofproto, name);
2446             ofport_install(ofproto, netdev, &pp);
2447         }
2448     } else {
2449         /* Any port named 'name' is gone now. */
2450         ofport_remove_with_name(ofproto, name);
2451     }
2452     ofproto_port_destroy(&ofproto_port);
2453 }
2454
2455 static int
2456 init_ports(struct ofproto *p)
2457 {
2458     struct ofproto_port_dump dump;
2459     struct ofproto_port ofproto_port;
2460     struct shash_node *node, *next;
2461
2462     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2463         const char *name = ofproto_port.name;
2464
2465         if (shash_find(&p->port_by_name, name)) {
2466             VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2467                          p->name, name);
2468         } else {
2469             struct ofputil_phy_port pp;
2470             struct netdev *netdev;
2471
2472             /* Check if an OpenFlow port number had been requested. */
2473             node = shash_find(&init_ofp_ports, name);
2474             if (node) {
2475                 const struct iface_hint *iface_hint = node->data;
2476                 simap_put(&p->ofp_requests, name,
2477                           ofp_to_u16(iface_hint->ofp_port));
2478             }
2479
2480             netdev = ofport_open(p, &ofproto_port, &pp);
2481             if (netdev) {
2482                 ofport_install(p, netdev, &pp);
2483                 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2484                     p->alloc_port_no = MAX(p->alloc_port_no,
2485                                            ofp_to_u16(ofproto_port.ofp_port));
2486                 }
2487             }
2488         }
2489     }
2490
2491     SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2492         struct iface_hint *iface_hint = node->data;
2493
2494         if (!strcmp(iface_hint->br_name, p->name)) {
2495             free(iface_hint->br_name);
2496             free(iface_hint->br_type);
2497             free(iface_hint);
2498             shash_delete(&init_ofp_ports, node);
2499         }
2500     }
2501
2502     return 0;
2503 }
2504
2505 /* Find the minimum MTU of all non-datapath devices attached to 'p'.
2506  * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2507 static int
2508 find_min_mtu(struct ofproto *p)
2509 {
2510     struct ofport *ofport;
2511     int mtu = 0;
2512
2513     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2514         struct netdev *netdev = ofport->netdev;
2515         int dev_mtu;
2516
2517         /* Skip any internal ports, since that's what we're trying to
2518          * set. */
2519         if (!strcmp(netdev_get_type(netdev), "internal")) {
2520             continue;
2521         }
2522
2523         if (netdev_get_mtu(netdev, &dev_mtu)) {
2524             continue;
2525         }
2526         if (!mtu || dev_mtu < mtu) {
2527             mtu = dev_mtu;
2528         }
2529     }
2530
2531     return mtu ? mtu: ETH_PAYLOAD_MAX;
2532 }
2533
2534 /* Update MTU of all datapath devices on 'p' to the minimum of the
2535  * non-datapath ports in event of 'port' added or changed. */
2536 static void
2537 update_mtu(struct ofproto *p, struct ofport *port)
2538 {
2539     struct ofport *ofport;
2540     struct netdev *netdev = port->netdev;
2541     int dev_mtu, old_min;
2542
2543     if (netdev_get_mtu(netdev, &dev_mtu)) {
2544         port->mtu = 0;
2545         return;
2546     }
2547     if (!strcmp(netdev_get_type(port->netdev), "internal")) {
2548         if (dev_mtu > p->min_mtu) {
2549            if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2550                dev_mtu = p->min_mtu;
2551            }
2552         }
2553         port->mtu = dev_mtu;
2554         return;
2555     }
2556
2557     /* For non-internal port find new min mtu. */
2558     old_min = p->min_mtu;
2559     port->mtu = dev_mtu;
2560     p->min_mtu = find_min_mtu(p);
2561     if (p->min_mtu == old_min) {
2562         return;
2563     }
2564
2565     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2566         struct netdev *netdev = ofport->netdev;
2567
2568         if (!strcmp(netdev_get_type(netdev), "internal")) {
2569             if (!netdev_set_mtu(netdev, p->min_mtu)) {
2570                 ofport->mtu = p->min_mtu;
2571             }
2572         }
2573     }
2574 }
2575 \f
2576 static void
2577 ofproto_rule_destroy__(struct rule *rule)
2578     OVS_NO_THREAD_SAFETY_ANALYSIS
2579 {
2580     cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2581     rule_actions_destroy(rule_get_actions(rule));
2582     ovs_mutex_destroy(&rule->mutex);
2583     rule->ofproto->ofproto_class->rule_dealloc(rule);
2584 }
2585
2586 static void
2587 rule_destroy_cb(struct rule *rule)
2588 {
2589     rule->ofproto->ofproto_class->rule_destruct(rule);
2590     ofproto_rule_destroy__(rule);
2591 }
2592
2593 void
2594 ofproto_rule_ref(struct rule *rule)
2595 {
2596     if (rule) {
2597         ovs_refcount_ref(&rule->ref_count);
2598     }
2599 }
2600
2601 /* Decrements 'rule''s ref_count and schedules 'rule' to be destroyed if the
2602  * ref_count reaches 0.
2603  *
2604  * Use of RCU allows short term use (between RCU quiescent periods) without
2605  * keeping a reference.  A reference must be taken if the rule needs to
2606  * stay around accross the RCU quiescent periods. */
2607 void
2608 ofproto_rule_unref(struct rule *rule)
2609 {
2610     if (rule && ovs_refcount_unref(&rule->ref_count) == 1) {
2611         ovsrcu_postpone(rule_destroy_cb, rule);
2612     }
2613 }
2614
2615 void
2616 ofproto_group_ref(struct ofgroup *group)
2617 {
2618     if (group) {
2619         ovs_refcount_ref(&group->ref_count);
2620     }
2621 }
2622
2623 void
2624 ofproto_group_unref(struct ofgroup *group)
2625 {
2626     if (group && ovs_refcount_unref(&group->ref_count) == 1) {
2627         group->ofproto->ofproto_class->group_destruct(group);
2628         ofputil_bucket_list_destroy(&group->buckets);
2629         group->ofproto->ofproto_class->group_dealloc(group);
2630     }
2631 }
2632
2633 static uint32_t get_provider_meter_id(const struct ofproto *,
2634                                       uint32_t of_meter_id);
2635
2636 /* Creates and returns a new 'struct rule_actions', whose actions are a copy
2637  * of from the 'ofpacts_len' bytes of 'ofpacts'. */
2638 const struct rule_actions *
2639 rule_actions_create(const struct ofproto *ofproto,
2640                     const struct ofpact *ofpacts, size_t ofpacts_len)
2641 {
2642     struct rule_actions *actions;
2643
2644     actions = xmalloc(sizeof *actions + ofpacts_len);
2645     actions->ofpacts_len = ofpacts_len;
2646     actions->provider_meter_id
2647         = get_provider_meter_id(ofproto,
2648                                 ofpacts_get_meter(ofpacts, ofpacts_len));
2649     memcpy(actions->ofpacts, ofpacts, ofpacts_len);
2650
2651     return actions;
2652 }
2653
2654 /* Free the actions after the RCU quiescent period is reached. */
2655 void
2656 rule_actions_destroy(const struct rule_actions *actions)
2657 {
2658     if (actions) {
2659         ovsrcu_postpone(free, CONST_CAST(struct rule_actions *, actions));
2660     }
2661 }
2662
2663 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
2664  * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
2665 static bool
2666 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
2667     OVS_REQUIRES(ofproto_mutex)
2668 {
2669     if (port == OFPP_ANY) {
2670         return true;
2671     } else {
2672         const struct rule_actions *actions = rule_get_actions(rule);
2673         return ofpacts_output_to_port(actions->ofpacts,
2674                                       actions->ofpacts_len, port);
2675     }
2676 }
2677
2678 /* Returns true if 'rule' has group and equals group_id. */
2679 static bool
2680 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
2681     OVS_REQUIRES(ofproto_mutex)
2682 {
2683     if (group_id == OFPG_ANY) {
2684         return true;
2685     } else {
2686         const struct rule_actions *actions = rule_get_actions(rule);
2687         return ofpacts_output_to_group(actions->ofpacts,
2688                                        actions->ofpacts_len, group_id);
2689     }
2690 }
2691
2692 /* Returns true if a rule related to 'op' has an OpenFlow OFPAT_OUTPUT or
2693  * OFPAT_ENQUEUE action that outputs to 'out_port'. */
2694 bool
2695 ofoperation_has_out_port(const struct ofoperation *op, ofp_port_t out_port)
2696     OVS_REQUIRES(ofproto_mutex)
2697 {
2698     if (ofproto_rule_has_out_port(op->rule, out_port)) {
2699         return true;
2700     }
2701
2702     switch (op->type) {
2703     case OFOPERATION_ADD:
2704     case OFOPERATION_DELETE:
2705         return false;
2706
2707     case OFOPERATION_MODIFY:
2708     case OFOPERATION_REPLACE:
2709         return ofpacts_output_to_port(op->actions->ofpacts,
2710                                       op->actions->ofpacts_len, out_port);
2711     }
2712
2713     OVS_NOT_REACHED();
2714 }
2715
2716 static void
2717 rule_execute_destroy(struct rule_execute *e)
2718 {
2719     ofproto_rule_unref(e->rule);
2720     list_remove(&e->list_node);
2721     free(e);
2722 }
2723
2724 /* Executes all "rule_execute" operations queued up in ofproto->rule_executes,
2725  * by passing them to the ofproto provider. */
2726 static void
2727 run_rule_executes(struct ofproto *ofproto)
2728     OVS_EXCLUDED(ofproto_mutex)
2729 {
2730     struct rule_execute *e, *next;
2731     struct list executes;
2732
2733     guarded_list_pop_all(&ofproto->rule_executes, &executes);
2734     LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2735         struct flow flow;
2736
2737         flow_extract(e->packet, NULL, &flow);
2738         flow.in_port.ofp_port = e->in_port;
2739         ofproto->ofproto_class->rule_execute(e->rule, &flow, e->packet);
2740
2741         rule_execute_destroy(e);
2742     }
2743 }
2744
2745 /* Destroys and discards all "rule_execute" operations queued up in
2746  * ofproto->rule_executes. */
2747 static void
2748 destroy_rule_executes(struct ofproto *ofproto)
2749 {
2750     struct rule_execute *e, *next;
2751     struct list executes;
2752
2753     guarded_list_pop_all(&ofproto->rule_executes, &executes);
2754     LIST_FOR_EACH_SAFE (e, next, list_node, &executes) {
2755         ofpbuf_delete(e->packet);
2756         rule_execute_destroy(e);
2757     }
2758 }
2759
2760 /* Returns true if 'rule' should be hidden from the controller.
2761  *
2762  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
2763  * (e.g. by in-band control) and are intentionally hidden from the
2764  * controller. */
2765 static bool
2766 ofproto_rule_is_hidden(const struct rule *rule)
2767 {
2768     return (rule->cr.priority > UINT16_MAX);
2769 }
2770
2771 static bool
2772 oftable_is_modifiable(const struct oftable *table,
2773                       enum ofputil_flow_mod_flags flags)
2774 {
2775     if (flags & OFPUTIL_FF_NO_READONLY) {
2776         return true;
2777     }
2778
2779     return !(table->flags & OFTABLE_READONLY);
2780 }
2781
2782 static bool
2783 rule_is_modifiable(const struct rule *rule, enum ofputil_flow_mod_flags flags)
2784 {
2785     const struct oftable *rule_table;
2786
2787     rule_table = &rule->ofproto->tables[rule->table_id];
2788     return oftable_is_modifiable(rule_table, flags);
2789 }
2790 \f
2791 static enum ofperr
2792 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
2793 {
2794     ofconn_send_reply(ofconn, make_echo_reply(oh));
2795     return 0;
2796 }
2797
2798 static enum ofperr
2799 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
2800 {
2801     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2802     struct ofputil_switch_features features;
2803     struct ofport *port;
2804     bool arp_match_ip;
2805     struct ofpbuf *b;
2806
2807     ofproto->ofproto_class->get_features(ofproto, &arp_match_ip,
2808                                          &features.actions);
2809     ovs_assert(features.actions & OFPUTIL_A_OUTPUT); /* sanity check */
2810
2811     features.datapath_id = ofproto->datapath_id;
2812     features.n_buffers = pktbuf_capacity();
2813     features.n_tables = ofproto_get_n_visible_tables(ofproto);
2814     features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
2815                              OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS);
2816     if (arp_match_ip) {
2817         features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
2818     }
2819     /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
2820     features.auxiliary_id = 0;
2821     b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
2822                                        oh->xid);
2823     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2824         ofputil_put_switch_features_port(&port->pp, b);
2825     }
2826
2827     ofconn_send_reply(ofconn, b);
2828     return 0;
2829 }
2830
2831 static enum ofperr
2832 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
2833 {
2834     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2835     struct ofp_switch_config *osc;
2836     enum ofp_config_flags flags;
2837     struct ofpbuf *buf;
2838
2839     /* Send reply. */
2840     buf = ofpraw_alloc_reply(OFPRAW_OFPT_GET_CONFIG_REPLY, oh, 0);
2841     osc = ofpbuf_put_uninit(buf, sizeof *osc);
2842     flags = ofproto->frag_handling;
2843     /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2844     if (oh->version < OFP13_VERSION
2845         && ofconn_get_invalid_ttl_to_controller(ofconn)) {
2846         flags |= OFPC_INVALID_TTL_TO_CONTROLLER;
2847     }
2848     osc->flags = htons(flags);
2849     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
2850     ofconn_send_reply(ofconn, buf);
2851
2852     return 0;
2853 }
2854
2855 static enum ofperr
2856 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
2857 {
2858     const struct ofp_switch_config *osc = ofpmsg_body(oh);
2859     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2860     uint16_t flags = ntohs(osc->flags);
2861
2862     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
2863         || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
2864         enum ofp_config_flags cur = ofproto->frag_handling;
2865         enum ofp_config_flags next = flags & OFPC_FRAG_MASK;
2866
2867         ovs_assert((cur & OFPC_FRAG_MASK) == cur);
2868         if (cur != next) {
2869             if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
2870                 ofproto->frag_handling = next;
2871             } else {
2872                 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
2873                              ofproto->name,
2874                              ofputil_frag_handling_to_string(next));
2875             }
2876         }
2877     }
2878     /* OFPC_INVALID_TTL_TO_CONTROLLER is deprecated in OF 1.3 */
2879     ofconn_set_invalid_ttl_to_controller(ofconn,
2880              (oh->version < OFP13_VERSION
2881               && flags & OFPC_INVALID_TTL_TO_CONTROLLER));
2882
2883     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
2884
2885     return 0;
2886 }
2887
2888 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
2889  * error message code for the caller to propagate upward.  Otherwise, returns
2890  * 0.
2891  *
2892  * The log message mentions 'msg_type'. */
2893 static enum ofperr
2894 reject_slave_controller(struct ofconn *ofconn)
2895 {
2896     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
2897         && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
2898         return OFPERR_OFPBRC_EPERM;
2899     } else {
2900         return 0;
2901     }
2902 }
2903
2904 /* Checks that the 'ofpacts_len' bytes of action in 'ofpacts' are appropriate
2905  * for 'ofproto':
2906  *
2907  *    - If they use a meter, then 'ofproto' has that meter configured.
2908  *
2909  *    - If they use any groups, then 'ofproto' has that group configured.
2910  *
2911  * Returns 0 if successful, otherwise an OpenFlow error. */
2912 static enum ofperr
2913 ofproto_check_ofpacts(struct ofproto *ofproto,
2914                       const struct ofpact ofpacts[], size_t ofpacts_len)
2915 {
2916     const struct ofpact *a;
2917     uint32_t mid;
2918
2919     mid = ofpacts_get_meter(ofpacts, ofpacts_len);
2920     if (mid && get_provider_meter_id(ofproto, mid) == UINT32_MAX) {
2921         return OFPERR_OFPMMFC_INVALID_METER;
2922     }
2923
2924     OFPACT_FOR_EACH (a, ofpacts, ofpacts_len) {
2925         if (a->type == OFPACT_GROUP
2926             && !ofproto_group_exists(ofproto, ofpact_get_GROUP(a)->group_id)) {
2927             return OFPERR_OFPBAC_BAD_OUT_GROUP;
2928         }
2929     }
2930
2931     return 0;
2932 }
2933
2934 static enum ofperr
2935 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
2936 {
2937     struct ofproto *p = ofconn_get_ofproto(ofconn);
2938     struct ofputil_packet_out po;
2939     struct ofpbuf *payload;
2940     uint64_t ofpacts_stub[1024 / 8];
2941     struct ofpbuf ofpacts;
2942     struct flow flow;
2943     enum ofperr error;
2944
2945     COVERAGE_INC(ofproto_packet_out);
2946
2947     error = reject_slave_controller(ofconn);
2948     if (error) {
2949         goto exit;
2950     }
2951
2952     /* Decode message. */
2953     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
2954     error = ofputil_decode_packet_out(&po, oh, &ofpacts);
2955     if (error) {
2956         goto exit_free_ofpacts;
2957     }
2958     if (ofp_to_u16(po.in_port) >= p->max_ports
2959         && ofp_to_u16(po.in_port) < ofp_to_u16(OFPP_MAX)) {
2960         error = OFPERR_OFPBRC_BAD_PORT;
2961         goto exit_free_ofpacts;
2962     }
2963
2964     /* Get payload. */
2965     if (po.buffer_id != UINT32_MAX) {
2966         error = ofconn_pktbuf_retrieve(ofconn, po.buffer_id, &payload, NULL);
2967         if (error || !payload) {
2968             goto exit_free_ofpacts;
2969         }
2970     } else {
2971         /* Ensure that the L3 header is 32-bit aligned. */
2972         payload = ofpbuf_clone_data_with_headroom(po.packet, po.packet_len, 2);
2973     }
2974
2975     /* Verify actions against packet, then send packet if successful. */
2976     flow_extract(payload, NULL, &flow);
2977     flow.in_port.ofp_port = po.in_port;
2978     error = ofproto_check_ofpacts(p, po.ofpacts, po.ofpacts_len);
2979     if (!error) {
2980         error = p->ofproto_class->packet_out(p, payload, &flow,
2981                                              po.ofpacts, po.ofpacts_len);
2982     }
2983     ofpbuf_delete(payload);
2984
2985 exit_free_ofpacts:
2986     ofpbuf_uninit(&ofpacts);
2987 exit:
2988     return error;
2989 }
2990
2991 static void
2992 update_port_config(struct ofconn *ofconn, struct ofport *port,
2993                    enum ofputil_port_config config,
2994                    enum ofputil_port_config mask)
2995 {
2996     enum ofputil_port_config toggle = (config ^ port->pp.config) & mask;
2997
2998     if (toggle & OFPUTIL_PC_PORT_DOWN
2999         && (config & OFPUTIL_PC_PORT_DOWN
3000             ? netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL)
3001             : netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL))) {
3002         /* We tried to bring the port up or down, but it failed, so don't
3003          * update the "down" bit. */
3004         toggle &= ~OFPUTIL_PC_PORT_DOWN;
3005     }
3006
3007     if (toggle) {
3008         enum ofputil_port_config old_config = port->pp.config;
3009         port->pp.config ^= toggle;
3010         port->ofproto->ofproto_class->port_reconfigured(port, old_config);
3011         connmgr_send_port_status(port->ofproto->connmgr, ofconn, &port->pp,
3012                                  OFPPR_MODIFY);
3013     }
3014 }
3015
3016 static enum ofperr
3017 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3018 {
3019     struct ofproto *p = ofconn_get_ofproto(ofconn);
3020     struct ofputil_port_mod pm;
3021     struct ofport *port;
3022     enum ofperr error;
3023
3024     error = reject_slave_controller(ofconn);
3025     if (error) {
3026         return error;
3027     }
3028
3029     error = ofputil_decode_port_mod(oh, &pm, false);
3030     if (error) {
3031         return error;
3032     }
3033
3034     port = ofproto_get_port(p, pm.port_no);
3035     if (!port) {
3036         return OFPERR_OFPPMFC_BAD_PORT;
3037     } else if (!eth_addr_equals(port->pp.hw_addr, pm.hw_addr)) {
3038         return OFPERR_OFPPMFC_BAD_HW_ADDR;
3039     } else {
3040         update_port_config(ofconn, port, pm.config, pm.mask);
3041         if (pm.advertise) {
3042             netdev_set_advertisements(port->netdev, pm.advertise);
3043         }
3044     }
3045     return 0;
3046 }
3047
3048 static enum ofperr
3049 handle_desc_stats_request(struct ofconn *ofconn,
3050                           const struct ofp_header *request)
3051 {
3052     static const char *default_mfr_desc = "Nicira, Inc.";
3053     static const char *default_hw_desc = "Open vSwitch";
3054     static const char *default_sw_desc = VERSION;
3055     static const char *default_serial_desc = "None";
3056     static const char *default_dp_desc = "None";
3057
3058     struct ofproto *p = ofconn_get_ofproto(ofconn);
3059     struct ofp_desc_stats *ods;
3060     struct ofpbuf *msg;
3061
3062     msg = ofpraw_alloc_stats_reply(request, 0);
3063     ods = ofpbuf_put_zeros(msg, sizeof *ods);
3064     ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
3065                 sizeof ods->mfr_desc);
3066     ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
3067                 sizeof ods->hw_desc);
3068     ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
3069                 sizeof ods->sw_desc);
3070     ovs_strlcpy(ods->serial_num,
3071                 p->serial_desc ? p->serial_desc : default_serial_desc,
3072                 sizeof ods->serial_num);
3073     ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
3074                 sizeof ods->dp_desc);
3075     ofconn_send_reply(ofconn, msg);
3076
3077     return 0;
3078 }
3079
3080 static enum ofperr
3081 handle_table_stats_request(struct ofconn *ofconn,
3082                            const struct ofp_header *request)
3083 {
3084     struct ofproto *p = ofconn_get_ofproto(ofconn);
3085     struct ofp12_table_stats *ots;
3086     struct ofpbuf *msg;
3087     int n_tables;
3088     size_t i;
3089
3090     /* Set up default values.
3091      *
3092      * ofp12_table_stats is used as a generic structure as
3093      * it is able to hold all the fields for ofp10_table_stats
3094      * and ofp11_table_stats (and of course itself).
3095      */
3096     ots = xcalloc(p->n_tables, sizeof *ots);
3097     for (i = 0; i < p->n_tables; i++) {
3098         ots[i].table_id = i;
3099         sprintf(ots[i].name, "table%"PRIuSIZE, i);
3100         ots[i].match = htonll(OFPXMT13_MASK);
3101         ots[i].wildcards = htonll(OFPXMT13_MASK);
3102         ots[i].write_actions = htonl(OFPAT11_OUTPUT);
3103         ots[i].apply_actions = htonl(OFPAT11_OUTPUT);
3104         ots[i].write_setfields = htonll(OFPXMT13_MASK);
3105         ots[i].apply_setfields = htonll(OFPXMT13_MASK);
3106         ots[i].metadata_match = OVS_BE64_MAX;
3107         ots[i].metadata_write = OVS_BE64_MAX;
3108         ots[i].instructions = htonl(OFPIT11_ALL);
3109         ots[i].config = htonl(OFPTC11_TABLE_MISS_MASK);
3110         ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
3111         fat_rwlock_rdlock(&p->tables[i].cls.rwlock);
3112         ots[i].active_count = htonl(classifier_count(&p->tables[i].cls));
3113         fat_rwlock_unlock(&p->tables[i].cls.rwlock);
3114     }
3115
3116     p->ofproto_class->get_tables(p, ots);
3117
3118     /* Post-process the tables, dropping hidden tables. */
3119     n_tables = p->n_tables;
3120     for (i = 0; i < p->n_tables; i++) {
3121         const struct oftable *table = &p->tables[i];
3122
3123         if (table->flags & OFTABLE_HIDDEN) {
3124             n_tables = i;
3125             break;
3126         }
3127
3128         if (table->name) {
3129             ovs_strzcpy(ots[i].name, table->name, sizeof ots[i].name);
3130         }
3131
3132         if (table->max_flows < ntohl(ots[i].max_entries)) {
3133             ots[i].max_entries = htonl(table->max_flows);
3134         }
3135     }
3136
3137     msg = ofputil_encode_table_stats_reply(ots, n_tables, request);
3138     ofconn_send_reply(ofconn, msg);
3139
3140     free(ots);
3141
3142     return 0;
3143 }
3144
3145 static void
3146 append_port_stat(struct ofport *port, struct list *replies)
3147 {
3148     struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3149
3150     calc_duration(port->created, time_msec(),
3151                   &ops.duration_sec, &ops.duration_nsec);
3152
3153     /* Intentionally ignore return value, since errors will set
3154      * 'stats' to all-1s, which is correct for OpenFlow, and
3155      * netdev_get_stats() will log errors. */
3156     ofproto_port_get_stats(port, &ops.stats);
3157
3158     ofputil_append_port_stat(replies, &ops);
3159 }
3160
3161 static void
3162 handle_port_request(struct ofconn *ofconn,
3163                     const struct ofp_header *request, ofp_port_t port_no,
3164                     void (*cb)(struct ofport *, struct list *replies))
3165 {
3166     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3167     struct ofport *port;
3168     struct list replies;
3169
3170     ofpmp_init(&replies, request);
3171     if (port_no != OFPP_ANY) {
3172         port = ofproto_get_port(ofproto, port_no);
3173         if (port) {
3174             cb(port, &replies);
3175         }
3176     } else {
3177         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3178             cb(port, &replies);
3179         }
3180     }
3181
3182     ofconn_send_replies(ofconn, &replies);
3183 }
3184
3185 static enum ofperr
3186 handle_port_stats_request(struct ofconn *ofconn,
3187                           const struct ofp_header *request)
3188 {
3189     ofp_port_t port_no;
3190     enum ofperr error;
3191
3192     error = ofputil_decode_port_stats_request(request, &port_no);
3193     if (!error) {
3194         handle_port_request(ofconn, request, port_no, append_port_stat);
3195     }
3196     return error;
3197 }
3198
3199 static void
3200 append_port_desc(struct ofport *port, struct list *replies)
3201 {
3202     ofputil_append_port_desc_stats_reply(&port->pp, replies);
3203 }
3204
3205 static enum ofperr
3206 handle_port_desc_stats_request(struct ofconn *ofconn,
3207                                const struct ofp_header *request)
3208 {
3209     ofp_port_t port_no;
3210     enum ofperr error;
3211
3212     error = ofputil_decode_port_desc_stats_request(request, &port_no);
3213     if (!error) {
3214         handle_port_request(ofconn, request, port_no, append_port_desc);
3215     }
3216     return error;
3217 }
3218
3219 static uint32_t
3220 hash_cookie(ovs_be64 cookie)
3221 {
3222     return hash_uint64((OVS_FORCE uint64_t)cookie);
3223 }
3224
3225 static void
3226 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3227     OVS_REQUIRES(ofproto_mutex)
3228 {
3229     hindex_insert(&ofproto->cookies, &rule->cookie_node,
3230                   hash_cookie(rule->flow_cookie));
3231 }
3232
3233 static void
3234 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3235     OVS_REQUIRES(ofproto_mutex)
3236 {
3237     hindex_remove(&ofproto->cookies, &rule->cookie_node);
3238 }
3239
3240 static void
3241 ofproto_rule_change_cookie(struct ofproto *ofproto, struct rule *rule,
3242                            ovs_be64 new_cookie)
3243     OVS_REQUIRES(ofproto_mutex)
3244 {
3245     if (new_cookie != rule->flow_cookie) {
3246         cookies_remove(ofproto, rule);
3247
3248         ovs_mutex_lock(&rule->mutex);
3249         rule->flow_cookie = new_cookie;
3250         ovs_mutex_unlock(&rule->mutex);
3251
3252         cookies_insert(ofproto, rule);
3253     }
3254 }
3255
3256 static void
3257 calc_duration(long long int start, long long int now,
3258               uint32_t *sec, uint32_t *nsec)
3259 {
3260     long long int msecs = now - start;
3261     *sec = msecs / 1000;
3262     *nsec = (msecs % 1000) * (1000 * 1000);
3263 }
3264
3265 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'.  Returns
3266  * true if 'table_id' is OK, false otherwise.  */
3267 static bool
3268 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3269 {
3270     return table_id == OFPTT_ALL || table_id < ofproto->n_tables;
3271 }
3272
3273 static struct oftable *
3274 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3275 {
3276     struct oftable *table;
3277
3278     for (table = &ofproto->tables[table_id];
3279          table < &ofproto->tables[ofproto->n_tables];
3280          table++) {
3281         if (!(table->flags & OFTABLE_HIDDEN)) {
3282             return table;
3283         }
3284     }
3285
3286     return NULL;
3287 }
3288
3289 static struct oftable *
3290 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
3291 {
3292     if (table_id == 0xff) {
3293         return next_visible_table(ofproto, 0);
3294     } else if (table_id < ofproto->n_tables) {
3295         return &ofproto->tables[table_id];
3296     } else {
3297         return NULL;
3298     }
3299 }
3300
3301 static struct oftable *
3302 next_matching_table(const struct ofproto *ofproto,
3303                     const struct oftable *table, uint8_t table_id)
3304 {
3305     return (table_id == 0xff
3306             ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
3307             : NULL);
3308 }
3309
3310 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
3311  *
3312  *   - If TABLE_ID is 0xff, this iterates over every classifier table in
3313  *     OFPROTO, skipping tables marked OFTABLE_HIDDEN.
3314  *
3315  *   - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
3316  *     only once, for that table.  (This can be used to access tables marked
3317  *     OFTABLE_HIDDEN.)
3318  *
3319  *   - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
3320  *     entered at all.  (Perhaps you should have validated TABLE_ID with
3321  *     check_table_id().)
3322  *
3323  * All parameters are evaluated multiple times.
3324  */
3325 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO)         \
3326     for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID);       \
3327          (TABLE) != NULL;                                         \
3328          (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
3329
3330 /* Initializes 'criteria' in a straightforward way based on the other
3331  * parameters.
3332  *
3333  * For "loose" matching, the 'priority' parameter is unimportant and may be
3334  * supplied as 0. */
3335 static void
3336 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
3337                    const struct match *match, unsigned int priority,
3338                    ovs_be64 cookie, ovs_be64 cookie_mask,
3339                    ofp_port_t out_port, uint32_t out_group)
3340 {
3341     criteria->table_id = table_id;
3342     cls_rule_init(&criteria->cr, match, priority);
3343     criteria->cookie = cookie;
3344     criteria->cookie_mask = cookie_mask;
3345     criteria->out_port = out_port;
3346     criteria->out_group = out_group;
3347 }
3348
3349 static void
3350 rule_criteria_destroy(struct rule_criteria *criteria)
3351 {
3352     cls_rule_destroy(&criteria->cr);
3353 }
3354
3355 void
3356 rule_collection_init(struct rule_collection *rules)
3357 {
3358     rules->rules = rules->stub;
3359     rules->n = 0;
3360     rules->capacity = ARRAY_SIZE(rules->stub);
3361 }
3362
3363 void
3364 rule_collection_add(struct rule_collection *rules, struct rule *rule)
3365 {
3366     if (rules->n >= rules->capacity) {
3367         size_t old_size, new_size;
3368
3369         old_size = rules->capacity * sizeof *rules->rules;
3370         rules->capacity *= 2;
3371         new_size = rules->capacity * sizeof *rules->rules;
3372
3373         if (rules->rules == rules->stub) {
3374             rules->rules = xmalloc(new_size);
3375             memcpy(rules->rules, rules->stub, old_size);
3376         } else {
3377             rules->rules = xrealloc(rules->rules, new_size);
3378         }
3379     }
3380
3381     rules->rules[rules->n++] = rule;
3382 }
3383
3384 void
3385 rule_collection_ref(struct rule_collection *rules)
3386     OVS_REQUIRES(ofproto_mutex)
3387 {
3388     size_t i;
3389
3390     for (i = 0; i < rules->n; i++) {
3391         ofproto_rule_ref(rules->rules[i]);
3392     }
3393 }
3394
3395 void
3396 rule_collection_unref(struct rule_collection *rules)
3397 {
3398     size_t i;
3399
3400     for (i = 0; i < rules->n; i++) {
3401         ofproto_rule_unref(rules->rules[i]);
3402     }
3403 }
3404
3405 void
3406 rule_collection_destroy(struct rule_collection *rules)
3407 {
3408     if (rules->rules != rules->stub) {
3409         free(rules->rules);
3410     }
3411 }
3412
3413 static enum ofperr
3414 collect_rule(struct rule *rule, const struct rule_criteria *c,
3415              struct rule_collection *rules)
3416     OVS_REQUIRES(ofproto_mutex)
3417 {
3418     /* We ordinarily want to skip hidden rules, but there has to be a way for
3419      * code internal to OVS to modify and delete them, so if the criteria
3420      * specify a priority that can only be for a hidden flow, then allow hidden
3421      * rules to be selected.  (This doesn't allow OpenFlow clients to meddle
3422      * with hidden flows because OpenFlow uses only a 16-bit field to specify
3423      * priority.) */
3424     if (ofproto_rule_is_hidden(rule) && c->cr.priority <= UINT16_MAX) {
3425         return 0;
3426     } else if (rule->pending) {
3427         return OFPROTO_POSTPONE;
3428     } else {
3429         if ((c->table_id == rule->table_id || c->table_id == 0xff)
3430             && ofproto_rule_has_out_port(rule, c->out_port)
3431             && ofproto_rule_has_out_group(rule, c->out_group)
3432             && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)) {
3433             rule_collection_add(rules, rule);
3434         }
3435         return 0;
3436     }
3437 }
3438
3439 /* Searches 'ofproto' for rules that match the criteria in 'criteria'.  Matches
3440  * on classifiers rules are done in the "loose" way required for OpenFlow
3441  * OFPFC_MODIFY and OFPFC_DELETE requests.  Puts the selected rules on list
3442  * 'rules'.
3443  *
3444  * Hidden rules are always omitted.
3445  *
3446  * Returns 0 on success, otherwise an OpenFlow error code. */
3447 static enum ofperr
3448 collect_rules_loose(struct ofproto *ofproto,
3449                     const struct rule_criteria *criteria,
3450                     struct rule_collection *rules)
3451     OVS_REQUIRES(ofproto_mutex)
3452 {
3453     struct oftable *table;
3454     enum ofperr error = 0;
3455
3456     rule_collection_init(rules);
3457
3458     if (!check_table_id(ofproto, criteria->table_id)) {
3459         error = OFPERR_OFPBRC_BAD_TABLE_ID;
3460         goto exit;
3461     }
3462
3463     if (criteria->cookie_mask == OVS_BE64_MAX) {
3464         struct rule *rule;
3465
3466         HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3467                                    hash_cookie(criteria->cookie),
3468                                    &ofproto->cookies) {
3469             if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
3470                 error = collect_rule(rule, criteria, rules);
3471                 if (error) {
3472                     break;
3473                 }
3474             }
3475         }
3476     } else {
3477         FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3478             struct cls_cursor cursor;
3479             struct rule *rule;
3480
3481             fat_rwlock_rdlock(&table->cls.rwlock);
3482             cls_cursor_init(&cursor, &table->cls, &criteria->cr);
3483             CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3484                 error = collect_rule(rule, criteria, rules);
3485                 if (error) {
3486                     break;
3487                 }
3488             }
3489             fat_rwlock_unlock(&table->cls.rwlock);
3490         }
3491     }
3492
3493 exit:
3494     if (error) {
3495         rule_collection_destroy(rules);
3496     }
3497     return error;
3498 }
3499
3500 /* Searches 'ofproto' for rules that match the criteria in 'criteria'.  Matches
3501  * on classifiers rules are done in the "strict" way required for OpenFlow
3502  * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests.  Puts the selected
3503  * rules on list 'rules'.
3504  *
3505  * Hidden rules are always omitted.
3506  *
3507  * Returns 0 on success, otherwise an OpenFlow error code. */
3508 static enum ofperr
3509 collect_rules_strict(struct ofproto *ofproto,
3510                      const struct rule_criteria *criteria,
3511                      struct rule_collection *rules)
3512     OVS_REQUIRES(ofproto_mutex)
3513 {
3514     struct oftable *table;
3515     int error = 0;
3516
3517     rule_collection_init(rules);
3518
3519     if (!check_table_id(ofproto, criteria->table_id)) {
3520         error = OFPERR_OFPBRC_BAD_TABLE_ID;
3521         goto exit;
3522     }
3523
3524     if (criteria->cookie_mask == OVS_BE64_MAX) {
3525         struct rule *rule;
3526
3527         HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
3528                                    hash_cookie(criteria->cookie),
3529                                    &ofproto->cookies) {
3530             if (cls_rule_equal(&rule->cr, &criteria->cr)) {
3531                 error = collect_rule(rule, criteria, rules);
3532                 if (error) {
3533                     break;
3534                 }
3535             }
3536         }
3537     } else {
3538         FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
3539             struct rule *rule;
3540
3541             fat_rwlock_rdlock(&table->cls.rwlock);
3542             rule = rule_from_cls_rule(classifier_find_rule_exactly(
3543                                           &table->cls, &criteria->cr));
3544             fat_rwlock_unlock(&table->cls.rwlock);
3545             if (rule) {
3546                 error = collect_rule(rule, criteria, rules);
3547                 if (error) {
3548                     break;
3549                 }
3550             }
3551         }
3552     }
3553
3554 exit:
3555     if (error) {
3556         rule_collection_destroy(rules);
3557     }
3558     return error;
3559 }
3560
3561 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
3562  * forced into the range of a uint16_t. */
3563 static int
3564 age_secs(long long int age_ms)
3565 {
3566     return (age_ms < 0 ? 0
3567             : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
3568             : (unsigned int) age_ms / 1000);
3569 }
3570
3571 static enum ofperr
3572 handle_flow_stats_request(struct ofconn *ofconn,
3573                           const struct ofp_header *request)
3574     OVS_EXCLUDED(ofproto_mutex)
3575 {
3576     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3577     struct ofputil_flow_stats_request fsr;
3578     struct rule_criteria criteria;
3579     struct rule_collection rules;
3580     struct list replies;
3581     enum ofperr error;
3582     size_t i;
3583
3584     error = ofputil_decode_flow_stats_request(&fsr, request);
3585     if (error) {
3586         return error;
3587     }
3588
3589     rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, fsr.cookie,
3590                        fsr.cookie_mask, fsr.out_port, fsr.out_group);
3591
3592     ovs_mutex_lock(&ofproto_mutex);
3593     error = collect_rules_loose(ofproto, &criteria, &rules);
3594     rule_criteria_destroy(&criteria);
3595     if (!error) {
3596         rule_collection_ref(&rules);
3597     }
3598     ovs_mutex_unlock(&ofproto_mutex);
3599
3600     if (error) {
3601         return error;
3602     }
3603
3604     ofpmp_init(&replies, request);
3605     for (i = 0; i < rules.n; i++) {
3606         struct rule *rule = rules.rules[i];
3607         long long int now = time_msec();
3608         struct ofputil_flow_stats fs;
3609         long long int created, used, modified;
3610         const struct rule_actions *actions;
3611         enum ofputil_flow_mod_flags flags;
3612
3613         ovs_mutex_lock(&rule->mutex);
3614         fs.cookie = rule->flow_cookie;
3615         fs.idle_timeout = rule->idle_timeout;
3616         fs.hard_timeout = rule->hard_timeout;
3617         created = rule->created;
3618         modified = rule->modified;
3619         actions = rule_get_actions(rule);
3620         flags = rule->flags;
3621         ovs_mutex_unlock(&rule->mutex);
3622
3623         ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
3624                                                &fs.byte_count, &used);
3625
3626         minimatch_expand(&rule->cr.match, &fs.match);
3627         fs.table_id = rule->table_id;
3628         calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
3629         fs.priority = rule->cr.priority;
3630         fs.idle_age = age_secs(now - used);
3631         fs.hard_age = age_secs(now - modified);
3632         fs.ofpacts = actions->ofpacts;
3633         fs.ofpacts_len = actions->ofpacts_len;
3634
3635         fs.flags = flags;
3636         ofputil_append_flow_stats_reply(&fs, &replies);
3637     }
3638
3639     rule_collection_unref(&rules);
3640     rule_collection_destroy(&rules);
3641
3642     ofconn_send_replies(ofconn, &replies);
3643
3644     return 0;
3645 }
3646
3647 static void
3648 flow_stats_ds(struct rule *rule, struct ds *results)
3649 {
3650     uint64_t packet_count, byte_count;
3651     const struct rule_actions *actions;
3652     long long int created, used;
3653
3654     rule->ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3655                                                  &byte_count, &used);
3656
3657     ovs_mutex_lock(&rule->mutex);
3658     actions = rule_get_actions(rule);
3659     created = rule->created;
3660     ovs_mutex_unlock(&rule->mutex);
3661
3662     if (rule->table_id != 0) {
3663         ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
3664     }
3665     ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
3666     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
3667     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
3668     cls_rule_format(&rule->cr, results);
3669     ds_put_char(results, ',');
3670
3671     ds_put_cstr(results, "actions=");
3672     ofpacts_format(actions->ofpacts, actions->ofpacts_len, results);
3673
3674     ds_put_cstr(results, "\n");
3675 }
3676
3677 /* Adds a pretty-printed description of all flows to 'results', including
3678  * hidden flows (e.g., set up by in-band control). */
3679 void
3680 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
3681 {
3682     struct oftable *table;
3683
3684     OFPROTO_FOR_EACH_TABLE (table, p) {
3685         struct cls_cursor cursor;
3686         struct rule *rule;
3687
3688         fat_rwlock_rdlock(&table->cls.rwlock);
3689         cls_cursor_init(&cursor, &table->cls, NULL);
3690         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
3691             flow_stats_ds(rule, results);
3692         }
3693         fat_rwlock_unlock(&table->cls.rwlock);
3694     }
3695 }
3696
3697 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
3698  * '*engine_type' and '*engine_id', respectively. */
3699 void
3700 ofproto_get_netflow_ids(const struct ofproto *ofproto,
3701                         uint8_t *engine_type, uint8_t *engine_id)
3702 {
3703     ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
3704 }
3705
3706 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'.
3707  * Returns 0 if the port's CFM status was successfully stored into
3708  * '*status'.  Returns positive errno if the port did not have CFM
3709  * configured.  Returns negative number if there is no status change
3710  * since last update.
3711  *
3712  * The caller must provide and own '*status', and must free 'status->rmps'.
3713  * '*status' is indeterminate if the return value is non-zero. */
3714 int
3715 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
3716                             struct ofproto_cfm_status *status)
3717 {
3718     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
3719     return (ofport && ofproto->ofproto_class->get_cfm_status
3720             ? ofproto->ofproto_class->get_cfm_status(ofport, status)
3721             : EOPNOTSUPP);
3722 }
3723
3724 static enum ofperr
3725 handle_aggregate_stats_request(struct ofconn *ofconn,
3726                                const struct ofp_header *oh)
3727     OVS_EXCLUDED(ofproto_mutex)
3728 {
3729     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3730     struct ofputil_flow_stats_request request;
3731     struct ofputil_aggregate_stats stats;
3732     bool unknown_packets, unknown_bytes;
3733     struct rule_criteria criteria;
3734     struct rule_collection rules;
3735     struct ofpbuf *reply;
3736     enum ofperr error;
3737     size_t i;
3738
3739     error = ofputil_decode_flow_stats_request(&request, oh);
3740     if (error) {
3741         return error;
3742     }
3743
3744     rule_criteria_init(&criteria, request.table_id, &request.match, 0,
3745                        request.cookie, request.cookie_mask,
3746                        request.out_port, request.out_group);
3747
3748     ovs_mutex_lock(&ofproto_mutex);
3749     error = collect_rules_loose(ofproto, &criteria, &rules);
3750     rule_criteria_destroy(&criteria);
3751     if (!error) {
3752         rule_collection_ref(&rules);
3753     }
3754     ovs_mutex_unlock(&ofproto_mutex);
3755
3756     if (error) {
3757         return error;
3758     }
3759
3760     memset(&stats, 0, sizeof stats);
3761     unknown_packets = unknown_bytes = false;
3762     for (i = 0; i < rules.n; i++) {
3763         struct rule *rule = rules.rules[i];
3764         uint64_t packet_count;
3765         uint64_t byte_count;
3766         long long int used;
3767
3768         ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
3769                                                &byte_count, &used);
3770
3771         if (packet_count == UINT64_MAX) {
3772             unknown_packets = true;
3773         } else {
3774             stats.packet_count += packet_count;
3775         }
3776
3777         if (byte_count == UINT64_MAX) {
3778             unknown_bytes = true;
3779         } else {
3780             stats.byte_count += byte_count;
3781         }
3782
3783         stats.flow_count++;
3784     }
3785     if (unknown_packets) {
3786         stats.packet_count = UINT64_MAX;
3787     }
3788     if (unknown_bytes) {
3789         stats.byte_count = UINT64_MAX;
3790     }
3791
3792     rule_collection_unref(&rules);
3793     rule_collection_destroy(&rules);
3794
3795     reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
3796     ofconn_send_reply(ofconn, reply);
3797
3798     return 0;
3799 }
3800
3801 struct queue_stats_cbdata {
3802     struct ofport *ofport;
3803     struct list replies;
3804     long long int now;
3805 };
3806
3807 static void
3808 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
3809                 const struct netdev_queue_stats *stats)
3810 {
3811     struct ofputil_queue_stats oqs;
3812
3813     oqs.port_no = cbdata->ofport->pp.port_no;
3814     oqs.queue_id = queue_id;
3815     oqs.tx_bytes = stats->tx_bytes;
3816     oqs.tx_packets = stats->tx_packets;
3817     oqs.tx_errors = stats->tx_errors;
3818     if (stats->created != LLONG_MIN) {
3819         calc_duration(stats->created, cbdata->now,
3820                       &oqs.duration_sec, &oqs.duration_nsec);
3821     } else {
3822         oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
3823     }
3824     ofputil_append_queue_stat(&cbdata->replies, &oqs);
3825 }
3826
3827 static void
3828 handle_queue_stats_dump_cb(uint32_t queue_id,
3829                            struct netdev_queue_stats *stats,
3830                            void *cbdata_)
3831 {
3832     struct queue_stats_cbdata *cbdata = cbdata_;
3833
3834     put_queue_stats(cbdata, queue_id, stats);
3835 }
3836
3837 static enum ofperr
3838 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
3839                             struct queue_stats_cbdata *cbdata)
3840 {
3841     cbdata->ofport = port;
3842     if (queue_id == OFPQ_ALL) {
3843         netdev_dump_queue_stats(port->netdev,
3844                                 handle_queue_stats_dump_cb, cbdata);
3845     } else {
3846         struct netdev_queue_stats stats;
3847
3848         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
3849             put_queue_stats(cbdata, queue_id, &stats);
3850         } else {
3851             return OFPERR_OFPQOFC_BAD_QUEUE;
3852         }
3853     }
3854     return 0;
3855 }
3856
3857 static enum ofperr
3858 handle_queue_stats_request(struct ofconn *ofconn,
3859                            const struct ofp_header *rq)
3860 {
3861     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3862     struct queue_stats_cbdata cbdata;
3863     struct ofport *port;
3864     enum ofperr error;
3865     struct ofputil_queue_stats_request oqsr;
3866
3867     COVERAGE_INC(ofproto_queue_req);
3868
3869     ofpmp_init(&cbdata.replies, rq);
3870     cbdata.now = time_msec();
3871
3872     error = ofputil_decode_queue_stats_request(rq, &oqsr);
3873     if (error) {
3874         return error;
3875     }
3876
3877     if (oqsr.port_no == OFPP_ANY) {
3878         error = OFPERR_OFPQOFC_BAD_QUEUE;
3879         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3880             if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
3881                 error = 0;
3882             }
3883         }
3884     } else {
3885         port = ofproto_get_port(ofproto, oqsr.port_no);
3886         error = (port
3887                  ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
3888                  : OFPERR_OFPQOFC_BAD_PORT);
3889     }
3890     if (!error) {
3891         ofconn_send_replies(ofconn, &cbdata.replies);
3892     } else {
3893         ofpbuf_list_delete(&cbdata.replies);
3894     }
3895
3896     return error;
3897 }
3898
3899 static bool
3900 is_flow_deletion_pending(const struct ofproto *ofproto,
3901                          const struct cls_rule *cls_rule,
3902                          uint8_t table_id)
3903     OVS_REQUIRES(ofproto_mutex)
3904 {
3905     if (!hmap_is_empty(&ofproto->deletions)) {
3906         struct ofoperation *op;
3907
3908         HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
3909                                  cls_rule_hash(cls_rule, table_id),
3910                                  &ofproto->deletions) {
3911             if (op->rule->table_id == table_id
3912                 && cls_rule_equal(cls_rule, &op->rule->cr)) {
3913                 return true;
3914             }
3915         }
3916     }
3917
3918     return false;
3919 }
3920
3921 static bool
3922 should_evict_a_rule(struct oftable *table, unsigned int extra_space)
3923     OVS_REQUIRES(ofproto_mutex)
3924     OVS_NO_THREAD_SAFETY_ANALYSIS
3925 {
3926     return classifier_count(&table->cls) + extra_space > table->max_flows;
3927 }
3928
3929 static enum ofperr
3930 evict_rules_from_table(struct ofproto *ofproto, struct oftable *table,
3931                        unsigned int extra_space)
3932     OVS_REQUIRES(ofproto_mutex)
3933 {
3934     while (should_evict_a_rule(table, extra_space)) {
3935         struct rule *rule;
3936
3937         if (!choose_rule_to_evict(table, &rule)) {
3938             return OFPERR_OFPFMFC_TABLE_FULL;
3939         } else if (rule->pending) {
3940             return OFPROTO_POSTPONE;
3941         } else {
3942             struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
3943             delete_flow__(rule, group, OFPRR_EVICTION);
3944             ofopgroup_submit(group);
3945         }
3946     }
3947
3948     return 0;
3949 }
3950
3951 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
3952  * in which no matching flow already exists in the flow table.
3953  *
3954  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
3955  * ofp_actions, to the ofproto's flow table.  Returns 0 on success, an OpenFlow
3956  * error code on failure, or OFPROTO_POSTPONE if the operation cannot be
3957  * initiated now but may be retried later.
3958  *
3959  * The caller retains ownership of 'fm->ofpacts'.
3960  *
3961  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
3962  * if any. */
3963 static enum ofperr
3964 add_flow(struct ofproto *ofproto, struct ofconn *ofconn,
3965          struct ofputil_flow_mod *fm, const struct ofp_header *request)
3966     OVS_REQUIRES(ofproto_mutex)
3967 {
3968     const struct rule_actions *actions;
3969     struct ofopgroup *group;
3970     struct oftable *table;
3971     struct cls_rule cr;
3972     struct rule *rule;
3973     uint8_t table_id;
3974     int error = 0;
3975
3976     if (!check_table_id(ofproto, fm->table_id)) {
3977         error = OFPERR_OFPBRC_BAD_TABLE_ID;
3978         return error;
3979     }
3980
3981     /* Pick table. */
3982     if (fm->table_id == 0xff) {
3983         if (ofproto->ofproto_class->rule_choose_table) {
3984             error = ofproto->ofproto_class->rule_choose_table(ofproto,
3985                                                               &fm->match,
3986                                                               &table_id);
3987             if (error) {
3988                 return error;
3989             }
3990             ovs_assert(table_id < ofproto->n_tables);
3991         } else {
3992             table_id = 0;
3993         }
3994     } else if (fm->table_id < ofproto->n_tables) {
3995         table_id = fm->table_id;
3996     } else {
3997         return OFPERR_OFPBRC_BAD_TABLE_ID;
3998     }
3999
4000     table = &ofproto->tables[table_id];
4001
4002     if (!oftable_is_modifiable(table, fm->flags)) {
4003         return OFPERR_OFPBRC_EPERM;
4004     }
4005
4006     if (!(fm->flags & OFPUTIL_FF_HIDDEN_FIELDS)) {
4007         if (!match_has_default_hidden_fields(&fm->match)) {
4008             VLOG_WARN_RL(&rl, "%s: (add_flow) only internal flows can set "
4009                          "non-default values to hidden fields", ofproto->name);
4010             return OFPERR_OFPBRC_EPERM;
4011         }
4012     }
4013
4014     cls_rule_init(&cr, &fm->match, fm->priority);
4015
4016     /* Transform "add" into "modify" if there's an existing identical flow. */
4017     fat_rwlock_rdlock(&table->cls.rwlock);
4018     rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls, &cr));
4019     fat_rwlock_unlock(&table->cls.rwlock);
4020     if (rule) {
4021         cls_rule_destroy(&cr);
4022         if (!rule_is_modifiable(rule, fm->flags)) {
4023             return OFPERR_OFPBRC_EPERM;
4024         } else if (rule->pending) {
4025             return OFPROTO_POSTPONE;
4026         } else {
4027             struct rule_collection rules;
4028
4029             rule_collection_init(&rules);
4030             rule_collection_add(&rules, rule);
4031             fm->modify_cookie = true;
4032             error = modify_flows__(ofproto, ofconn, fm, request, &rules);
4033             rule_collection_destroy(&rules);
4034
4035             return error;
4036         }
4037     }
4038
4039     /* Serialize against pending deletion. */
4040     if (is_flow_deletion_pending(ofproto, &cr, table_id)) {
4041         cls_rule_destroy(&cr);
4042         return OFPROTO_POSTPONE;
4043     }
4044
4045     /* Check for overlap, if requested. */
4046     if (fm->flags & OFPUTIL_FF_CHECK_OVERLAP) {
4047         bool overlaps;
4048
4049         fat_rwlock_rdlock(&table->cls.rwlock);
4050         overlaps = classifier_rule_overlaps(&table->cls, &cr);
4051         fat_rwlock_unlock(&table->cls.rwlock);
4052
4053         if (overlaps) {
4054             cls_rule_destroy(&cr);
4055             return OFPERR_OFPFMFC_OVERLAP;
4056         }
4057     }
4058
4059     /* If necessary, evict an existing rule to clear out space. */
4060     error = evict_rules_from_table(ofproto, table, 1);
4061     if (error) {
4062         cls_rule_destroy(&cr);
4063         return error;
4064     }
4065
4066     /* Allocate new rule. */
4067     rule = ofproto->ofproto_class->rule_alloc();
4068     if (!rule) {
4069         cls_rule_destroy(&cr);
4070         VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
4071                      ofproto->name, ovs_strerror(error));
4072         return ENOMEM;
4073     }
4074
4075     /* Initialize base state. */
4076     *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
4077     cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), &cr);
4078     ovs_refcount_init(&rule->ref_count);
4079     rule->pending = NULL;
4080     rule->flow_cookie = fm->new_cookie;
4081     rule->created = rule->modified = time_msec();
4082
4083     ovs_mutex_init(&rule->mutex);
4084     ovs_mutex_lock(&rule->mutex);
4085     rule->idle_timeout = fm->idle_timeout;
4086     rule->hard_timeout = fm->hard_timeout;
4087     ovs_mutex_unlock(&rule->mutex);
4088
4089     *CONST_CAST(uint8_t *, &rule->table_id) = table - ofproto->tables;
4090     rule->flags = fm->flags & OFPUTIL_FF_STATE;
4091     actions = rule_actions_create(ofproto, fm->ofpacts, fm->ofpacts_len);
4092     ovsrcu_set(&rule->actions, actions);
4093     list_init(&rule->meter_list_node);
4094     rule->eviction_group = NULL;
4095     list_init(&rule->expirable);
4096     rule->monitor_flags = 0;
4097     rule->add_seqno = 0;
4098     rule->modify_seqno = 0;
4099
4100     /* Construct rule, initializing derived state. */
4101     error = ofproto->ofproto_class->rule_construct(rule);
4102     if (error) {
4103         ofproto_rule_destroy__(rule);
4104         return error;
4105     }
4106
4107     if (fm->hard_timeout || fm->idle_timeout) {
4108         list_insert(&ofproto->expirable, &rule->expirable);
4109     }
4110     cookies_insert(ofproto, rule);
4111     eviction_group_add_rule(rule);
4112     if (actions->provider_meter_id != UINT32_MAX) {
4113         meter_insert_rule(rule);
4114     }
4115
4116     fat_rwlock_wrlock(&table->cls.rwlock);
4117     classifier_insert(&table->cls, CONST_CAST(struct cls_rule *, &rule->cr));
4118     fat_rwlock_unlock(&table->cls.rwlock);
4119
4120     group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4121     ofoperation_create(group, rule, OFOPERATION_ADD, 0);
4122     ofproto->ofproto_class->rule_insert(rule);
4123     ofopgroup_submit(group);
4124
4125     return error;
4126 }
4127 \f
4128 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4129
4130 /* Modifies the rules listed in 'rules', changing their actions to match those
4131  * in 'fm'.
4132  *
4133  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4134  * if any.
4135  *
4136  * Returns 0 on success, otherwise an OpenFlow error code. */
4137 static enum ofperr
4138 modify_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4139                struct ofputil_flow_mod *fm, const struct ofp_header *request,
4140                const struct rule_collection *rules)
4141     OVS_REQUIRES(ofproto_mutex)
4142 {
4143     enum ofoperation_type type;
4144     struct ofopgroup *group;
4145     enum ofperr error;
4146     size_t i;
4147
4148     type = fm->command == OFPFC_ADD ? OFOPERATION_REPLACE : OFOPERATION_MODIFY;
4149     group = ofopgroup_create(ofproto, ofconn, request, fm->buffer_id);
4150     error = OFPERR_OFPBRC_EPERM;
4151     for (i = 0; i < rules->n; i++) {
4152         struct rule *rule = rules->rules[i];
4153         const struct rule_actions *actions;
4154         struct ofoperation *op;
4155         bool actions_changed;
4156         bool reset_counters;
4157
4158         /* FIXME: Implement OFPFUTIL_FF_RESET_COUNTS */
4159
4160         if (rule_is_modifiable(rule, fm->flags)) {
4161             /* At least one rule is modifiable, don't report EPERM error. */
4162             error = 0;
4163         } else {
4164             continue;
4165         }
4166
4167         actions = rule_get_actions(rule);
4168         actions_changed = !ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4169                                          actions->ofpacts,
4170                                          actions->ofpacts_len);
4171
4172         op = ofoperation_create(group, rule, type, 0);
4173
4174         if (fm->modify_cookie && fm->new_cookie != OVS_BE64_MAX) {
4175             ofproto_rule_change_cookie(ofproto, rule, fm->new_cookie);
4176         }
4177         if (type == OFOPERATION_REPLACE) {
4178             ovs_mutex_lock(&rule->mutex);
4179             rule->idle_timeout = fm->idle_timeout;
4180             rule->hard_timeout = fm->hard_timeout;
4181             ovs_mutex_unlock(&rule->mutex);
4182
4183             rule->flags = fm->flags & OFPUTIL_FF_STATE;
4184             if (fm->idle_timeout || fm->hard_timeout) {
4185                 if (!rule->eviction_group) {
4186                     eviction_group_add_rule(rule);
4187                 }
4188             } else {
4189                 eviction_group_remove_rule(rule);
4190             }
4191         }
4192
4193         reset_counters = (fm->flags & OFPUTIL_FF_RESET_COUNTS) != 0;
4194         if (actions_changed || reset_counters) {
4195             const struct rule_actions *new_actions;
4196
4197             op->actions = rule_get_actions(rule);
4198             new_actions = rule_actions_create(ofproto,
4199                                               fm->ofpacts, fm->ofpacts_len);
4200
4201             ovsrcu_set(&rule->actions, new_actions);
4202
4203             rule->ofproto->ofproto_class->rule_modify_actions(rule,
4204                                                               reset_counters);
4205         } else {
4206             ofoperation_complete(op, 0);
4207         }
4208     }
4209     ofopgroup_submit(group);
4210
4211     return error;
4212 }
4213
4214 static enum ofperr
4215 modify_flows_add(struct ofproto *ofproto, struct ofconn *ofconn,
4216                  struct ofputil_flow_mod *fm, const struct ofp_header *request)
4217     OVS_REQUIRES(ofproto_mutex)
4218 {
4219     if (fm->cookie_mask != htonll(0) || fm->new_cookie == OVS_BE64_MAX) {
4220         return 0;
4221     }
4222     return add_flow(ofproto, ofconn, fm, request);
4223 }
4224
4225 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code on
4226  * failure.
4227  *
4228  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4229  * if any. */
4230 static enum ofperr
4231 modify_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4232                    struct ofputil_flow_mod *fm,
4233                    const struct ofp_header *request)
4234     OVS_REQUIRES(ofproto_mutex)
4235 {
4236     struct rule_criteria criteria;
4237     struct rule_collection rules;
4238     int error;
4239
4240     rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4241                        fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4242     error = collect_rules_loose(ofproto, &criteria, &rules);
4243     rule_criteria_destroy(&criteria);
4244
4245     if (!error) {
4246         error = (rules.n > 0
4247                  ? modify_flows__(ofproto, ofconn, fm, request, &rules)
4248                  : modify_flows_add(ofproto, ofconn, fm, request));
4249     }
4250
4251     rule_collection_destroy(&rules);
4252
4253     return error;
4254 }
4255
4256 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
4257  * code on failure.
4258  *
4259  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
4260  * if any. */
4261 static enum ofperr
4262 modify_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4263                    struct ofputil_flow_mod *fm,
4264                    const struct ofp_header *request)
4265     OVS_REQUIRES(ofproto_mutex)
4266 {
4267     struct rule_criteria criteria;
4268     struct rule_collection rules;
4269     int error;
4270
4271     rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4272                        fm->cookie, fm->cookie_mask, OFPP_ANY, OFPG11_ANY);
4273     error = collect_rules_strict(ofproto, &criteria, &rules);
4274     rule_criteria_destroy(&criteria);
4275
4276     if (!error) {
4277         if (rules.n == 0) {
4278             error =  modify_flows_add(ofproto, ofconn, fm, request);
4279         } else if (rules.n == 1) {
4280             error = modify_flows__(ofproto, ofconn, fm, request, &rules);
4281         }
4282     }
4283
4284     rule_collection_destroy(&rules);
4285
4286     return error;
4287 }
4288 \f
4289 /* OFPFC_DELETE implementation. */
4290
4291 static void
4292 delete_flow__(struct rule *rule, struct ofopgroup *group,
4293               enum ofp_flow_removed_reason reason)
4294     OVS_REQUIRES(ofproto_mutex)
4295 {
4296     struct ofproto *ofproto = rule->ofproto;
4297
4298     ofproto_rule_send_removed(rule, reason);
4299
4300     ofoperation_create(group, rule, OFOPERATION_DELETE, reason);
4301     oftable_remove_rule(rule);
4302     ofproto->ofproto_class->rule_delete(rule);
4303 }
4304
4305 /* Deletes the rules listed in 'rules'.
4306  *
4307  * Returns 0 on success, otherwise an OpenFlow error code. */
4308 static enum ofperr
4309 delete_flows__(struct ofproto *ofproto, struct ofconn *ofconn,
4310                const struct ofp_header *request,
4311                const struct rule_collection *rules,
4312                enum ofp_flow_removed_reason reason)
4313     OVS_REQUIRES(ofproto_mutex)
4314 {
4315     struct ofopgroup *group;
4316     size_t i;
4317
4318     group = ofopgroup_create(ofproto, ofconn, request, UINT32_MAX);
4319     for (i = 0; i < rules->n; i++) {
4320         delete_flow__(rules->rules[i], group, reason);
4321     }
4322     ofopgroup_submit(group);
4323
4324     return 0;
4325 }
4326
4327 /* Implements OFPFC_DELETE. */
4328 static enum ofperr
4329 delete_flows_loose(struct ofproto *ofproto, struct ofconn *ofconn,
4330                    const struct ofputil_flow_mod *fm,
4331                    const struct ofp_header *request)
4332     OVS_REQUIRES(ofproto_mutex)
4333 {
4334     struct rule_criteria criteria;
4335     struct rule_collection rules;
4336     enum ofperr error;
4337
4338     rule_criteria_init(&criteria, fm->table_id, &fm->match, 0,
4339                        fm->cookie, fm->cookie_mask,
4340                        fm->out_port, fm->out_group);
4341     error = collect_rules_loose(ofproto, &criteria, &rules);
4342     rule_criteria_destroy(&criteria);
4343
4344     if (!error && rules.n > 0) {
4345         error = delete_flows__(ofproto, ofconn, request, &rules,
4346                                fm->delete_reason);
4347     }
4348     rule_collection_destroy(&rules);
4349
4350     return error;
4351 }
4352
4353 /* Implements OFPFC_DELETE_STRICT. */
4354 static enum ofperr
4355 delete_flow_strict(struct ofproto *ofproto, struct ofconn *ofconn,
4356                    const struct ofputil_flow_mod *fm,
4357                    const struct ofp_header *request)
4358     OVS_REQUIRES(ofproto_mutex)
4359 {
4360     struct rule_criteria criteria;
4361     struct rule_collection rules;
4362     enum ofperr error;
4363
4364     rule_criteria_init(&criteria, fm->table_id, &fm->match, fm->priority,
4365                        fm->cookie, fm->cookie_mask,
4366                        fm->out_port, fm->out_group);
4367     error = collect_rules_strict(ofproto, &criteria, &rules);
4368     rule_criteria_destroy(&criteria);
4369
4370     if (!error && rules.n > 0) {
4371         error = delete_flows__(ofproto, ofconn, request, &rules,
4372                                fm->delete_reason);
4373     }
4374     rule_collection_destroy(&rules);
4375
4376     return error;
4377 }
4378
4379 static void
4380 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
4381     OVS_REQUIRES(ofproto_mutex)
4382 {
4383     struct ofputil_flow_removed fr;
4384     long long int used;
4385
4386     if (ofproto_rule_is_hidden(rule) ||
4387         !(rule->flags & OFPUTIL_FF_SEND_FLOW_REM)) {
4388         return;
4389     }
4390
4391     minimatch_expand(&rule->cr.match, &fr.match);
4392     fr.priority = rule->cr.priority;
4393     fr.cookie = rule->flow_cookie;
4394     fr.reason = reason;
4395     fr.table_id = rule->table_id;
4396     calc_duration(rule->created, time_msec(),
4397                   &fr.duration_sec, &fr.duration_nsec);
4398     ovs_mutex_lock(&rule->mutex);
4399     fr.idle_timeout = rule->idle_timeout;
4400     fr.hard_timeout = rule->hard_timeout;
4401     ovs_mutex_unlock(&rule->mutex);
4402     rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
4403                                                  &fr.byte_count, &used);
4404
4405     connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
4406 }
4407
4408 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
4409  * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
4410  * ofproto.
4411  *
4412  * 'rule' must not have a pending operation (that is, 'rule->pending' must be
4413  * NULL).
4414  *
4415  * ofproto implementation ->run() functions should use this function to expire
4416  * OpenFlow flows. */
4417 void
4418 ofproto_rule_expire(struct rule *rule, uint8_t reason)
4419     OVS_REQUIRES(ofproto_mutex)
4420 {
4421     struct ofproto *ofproto = rule->ofproto;
4422
4423     ovs_assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT
4424                || reason == OFPRR_DELETE || reason == OFPRR_GROUP_DELETE);
4425
4426     ofproto_rule_delete__(ofproto, rule, reason);
4427 }
4428
4429 /* Reduces '*timeout' to no more than 'max'.  A value of zero in either case
4430  * means "infinite". */
4431 static void
4432 reduce_timeout(uint16_t max, uint16_t *timeout)
4433 {
4434     if (max && (!*timeout || *timeout > max)) {
4435         *timeout = max;
4436     }
4437 }
4438
4439 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
4440  * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
4441  * 'idle_timeout' seconds.  Similarly for 'hard_timeout'.
4442  *
4443  * Suitable for implementing OFPACT_FIN_TIMEOUT. */
4444 void
4445 ofproto_rule_reduce_timeouts(struct rule *rule,
4446                              uint16_t idle_timeout, uint16_t hard_timeout)
4447     OVS_EXCLUDED(ofproto_mutex, rule->mutex)
4448 {
4449     if (!idle_timeout && !hard_timeout) {
4450         return;
4451     }
4452
4453     ovs_mutex_lock(&ofproto_mutex);
4454     if (list_is_empty(&rule->expirable)) {
4455         list_insert(&rule->ofproto->expirable, &rule->expirable);
4456     }
4457     ovs_mutex_unlock(&ofproto_mutex);
4458
4459     ovs_mutex_lock(&rule->mutex);
4460     reduce_timeout(idle_timeout, &rule->idle_timeout);
4461     reduce_timeout(hard_timeout, &rule->hard_timeout);
4462     ovs_mutex_unlock(&rule->mutex);
4463 }
4464 \f
4465 static enum ofperr
4466 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
4467     OVS_EXCLUDED(ofproto_mutex)
4468 {
4469     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4470     struct ofputil_flow_mod fm;
4471     uint64_t ofpacts_stub[1024 / 8];
4472     struct ofpbuf ofpacts;
4473     enum ofperr error;
4474
4475     error = reject_slave_controller(ofconn);
4476     if (error) {
4477         goto exit;
4478     }
4479
4480     ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
4481     error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
4482                                     &ofpacts,
4483                                     u16_to_ofp(ofproto->max_ports),
4484                                     ofproto->n_tables);
4485     if (!error) {
4486         error = ofproto_check_ofpacts(ofproto, fm.ofpacts, fm.ofpacts_len);
4487     }
4488     if (!error) {
4489         error = handle_flow_mod__(ofproto, ofconn, &fm, oh);
4490     }
4491     if (error) {
4492         goto exit_free_ofpacts;
4493     }
4494
4495     ofconn_report_flow_mod(ofconn, fm.command);
4496
4497 exit_free_ofpacts:
4498     ofpbuf_uninit(&ofpacts);
4499 exit:
4500     return error;
4501 }
4502
4503 static enum ofperr
4504 handle_flow_mod__(struct ofproto *ofproto, struct ofconn *ofconn,
4505                   struct ofputil_flow_mod *fm, const struct ofp_header *oh)
4506     OVS_EXCLUDED(ofproto_mutex)
4507 {
4508     enum ofperr error;
4509
4510     ovs_mutex_lock(&ofproto_mutex);
4511     if (ofproto->n_pending < 50) {
4512         switch (fm->command) {
4513         case OFPFC_ADD:
4514             error = add_flow(ofproto, ofconn, fm, oh);
4515             break;
4516
4517         case OFPFC_MODIFY:
4518             error = modify_flows_loose(ofproto, ofconn, fm, oh);
4519             break;
4520
4521         case OFPFC_MODIFY_STRICT:
4522             error = modify_flow_strict(ofproto, ofconn, fm, oh);
4523             break;
4524
4525         case OFPFC_DELETE:
4526             error = delete_flows_loose(ofproto, ofconn, fm, oh);
4527             break;
4528
4529         case OFPFC_DELETE_STRICT:
4530             error = delete_flow_strict(ofproto, ofconn, fm, oh);
4531             break;
4532
4533         default:
4534             if (fm->command > 0xff) {
4535                 VLOG_WARN_RL(&rl, "%s: flow_mod has explicit table_id but "
4536                              "flow_mod_table_id extension is not enabled",
4537                              ofproto->name);
4538             }
4539             error = OFPERR_OFPFMFC_BAD_COMMAND;
4540             break;
4541         }
4542     } else {
4543         ovs_assert(!list_is_empty(&ofproto->pending));
4544         error = OFPROTO_POSTPONE;
4545     }
4546     ovs_mutex_unlock(&ofproto_mutex);
4547
4548     run_rule_executes(ofproto);
4549     return error;
4550 }
4551
4552 static enum ofperr
4553 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
4554 {
4555     struct ofputil_role_request request;
4556     struct ofputil_role_request reply;
4557     struct ofpbuf *buf;
4558     enum ofperr error;
4559
4560     error = ofputil_decode_role_message(oh, &request);
4561     if (error) {
4562         return error;
4563     }
4564
4565     if (request.role != OFPCR12_ROLE_NOCHANGE) {
4566         if (ofconn_get_role(ofconn) != request.role
4567             && ofconn_has_pending_opgroups(ofconn)) {
4568             return OFPROTO_POSTPONE;
4569         }
4570
4571         if (request.have_generation_id
4572             && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
4573                 return OFPERR_OFPRRFC_STALE;
4574         }
4575
4576         ofconn_set_role(ofconn, request.role);
4577     }
4578
4579     reply.role = ofconn_get_role(ofconn);
4580     reply.have_generation_id = ofconn_get_master_election_id(
4581         ofconn, &reply.generation_id);
4582     buf = ofputil_encode_role_reply(oh, &reply);
4583     ofconn_send_reply(ofconn, buf);
4584
4585     return 0;
4586 }
4587
4588 static enum ofperr
4589 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
4590                              const struct ofp_header *oh)
4591 {
4592     const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
4593     enum ofputil_protocol cur, next;
4594
4595     cur = ofconn_get_protocol(ofconn);
4596     next = ofputil_protocol_set_tid(cur, msg->set != 0);
4597     ofconn_set_protocol(ofconn, next);
4598
4599     return 0;
4600 }
4601
4602 static enum ofperr
4603 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
4604 {
4605     const struct nx_set_flow_format *msg = ofpmsg_body(oh);
4606     enum ofputil_protocol cur, next;
4607     enum ofputil_protocol next_base;
4608
4609     next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
4610     if (!next_base) {
4611         return OFPERR_OFPBRC_EPERM;
4612     }
4613
4614     cur = ofconn_get_protocol(ofconn);
4615     next = ofputil_protocol_set_base(cur, next_base);
4616     if (cur != next && ofconn_has_pending_opgroups(ofconn)) {
4617         /* Avoid sending async messages in surprising protocol. */
4618         return OFPROTO_POSTPONE;
4619     }
4620
4621     ofconn_set_protocol(ofconn, next);
4622     return 0;
4623 }
4624
4625 static enum ofperr
4626 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
4627                                 const struct ofp_header *oh)
4628 {
4629     const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
4630     uint32_t format;
4631
4632     format = ntohl(msg->format);
4633     if (format != NXPIF_OPENFLOW10 && format != NXPIF_NXM) {
4634         return OFPERR_OFPBRC_EPERM;
4635     }
4636
4637     if (format != ofconn_get_packet_in_format(ofconn)
4638         && ofconn_has_pending_opgroups(ofconn)) {
4639         /* Avoid sending async message in surprsing packet in format. */
4640         return OFPROTO_POSTPONE;
4641     }
4642
4643     ofconn_set_packet_in_format(ofconn, format);
4644     return 0;
4645 }
4646
4647 static enum ofperr
4648 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
4649 {
4650     const struct nx_async_config *msg = ofpmsg_body(oh);
4651     uint32_t master[OAM_N_TYPES];
4652     uint32_t slave[OAM_N_TYPES];
4653
4654     master[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[0]);
4655     master[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[0]);
4656     master[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[0]);
4657
4658     slave[OAM_PACKET_IN] = ntohl(msg->packet_in_mask[1]);
4659     slave[OAM_PORT_STATUS] = ntohl(msg->port_status_mask[1]);
4660     slave[OAM_FLOW_REMOVED] = ntohl(msg->flow_removed_mask[1]);
4661
4662     ofconn_set_async_config(ofconn, master, slave);
4663     if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
4664         !ofconn_get_miss_send_len(ofconn)) {
4665         ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
4666     }
4667
4668     return 0;
4669 }
4670
4671 static enum ofperr
4672 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
4673 {
4674     struct ofpbuf *buf;
4675     uint32_t master[OAM_N_TYPES];
4676     uint32_t slave[OAM_N_TYPES];
4677     struct nx_async_config *msg;
4678
4679     ofconn_get_async_config(ofconn, master, slave);
4680     buf = ofpraw_alloc_reply(OFPRAW_OFPT13_GET_ASYNC_REPLY, oh, 0);
4681     msg = ofpbuf_put_zeros(buf, sizeof *msg);
4682
4683     msg->packet_in_mask[0] = htonl(master[OAM_PACKET_IN]);
4684     msg->port_status_mask[0] = htonl(master[OAM_PORT_STATUS]);
4685     msg->flow_removed_mask[0] = htonl(master[OAM_FLOW_REMOVED]);
4686
4687     msg->packet_in_mask[1] = htonl(slave[OAM_PACKET_IN]);
4688     msg->port_status_mask[1] = htonl(slave[OAM_PORT_STATUS]);
4689     msg->flow_removed_mask[1] = htonl(slave[OAM_FLOW_REMOVED]);
4690
4691     ofconn_send_reply(ofconn, buf);
4692
4693     return 0;
4694 }
4695
4696 static enum ofperr
4697 handle_nxt_set_controller_id(struct ofconn *ofconn,
4698                              const struct ofp_header *oh)
4699 {
4700     const struct nx_controller_id *nci = ofpmsg_body(oh);
4701
4702     if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
4703         return OFPERR_NXBRC_MUST_BE_ZERO;
4704     }
4705
4706     ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
4707     return 0;
4708 }
4709
4710 static enum ofperr
4711 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
4712 {
4713     struct ofpbuf *buf;
4714
4715     if (ofconn_has_pending_opgroups(ofconn)) {
4716         return OFPROTO_POSTPONE;
4717     }
4718
4719     buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
4720                               ? OFPRAW_OFPT10_BARRIER_REPLY
4721                               : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
4722     ofconn_send_reply(ofconn, buf);
4723     return 0;
4724 }
4725
4726 static void
4727 ofproto_compose_flow_refresh_update(const struct rule *rule,
4728                                     enum nx_flow_monitor_flags flags,
4729                                     struct list *msgs)
4730     OVS_REQUIRES(ofproto_mutex)
4731 {
4732     struct ofoperation *op = rule->pending;
4733     const struct rule_actions *actions;
4734     struct ofputil_flow_update fu;
4735     struct match match;
4736
4737     if (op && op->type == OFOPERATION_ADD) {
4738         /* We'll report the final flow when the operation completes.  Reporting
4739          * it now would cause a duplicate report later. */
4740         return;
4741     }
4742
4743     fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
4744                 ? NXFME_ADDED : NXFME_MODIFIED);
4745     fu.reason = 0;
4746     ovs_mutex_lock(&rule->mutex);
4747     fu.idle_timeout = rule->idle_timeout;
4748     fu.hard_timeout = rule->hard_timeout;
4749     ovs_mutex_unlock(&rule->mutex);
4750     fu.table_id = rule->table_id;
4751     fu.cookie = rule->flow_cookie;
4752     minimatch_expand(&rule->cr.match, &match);
4753     fu.match = &match;
4754     fu.priority = rule->cr.priority;
4755
4756     if (!(flags & NXFMF_ACTIONS)) {
4757         actions = NULL;
4758     } else if (!op) {
4759         actions = rule_get_actions(rule);
4760     } else {
4761         /* An operation is in progress.  Use the previous version of the flow's
4762          * actions, so that when the operation commits we report the change. */
4763         switch (op->type) {
4764         case OFOPERATION_ADD:
4765             OVS_NOT_REACHED();
4766
4767         case OFOPERATION_MODIFY:
4768         case OFOPERATION_REPLACE:
4769             actions = op->actions ? op->actions : rule_get_actions(rule);
4770             break;
4771
4772         case OFOPERATION_DELETE:
4773             actions = rule_get_actions(rule);
4774             break;
4775
4776         default:
4777             OVS_NOT_REACHED();
4778         }
4779     }
4780     fu.ofpacts = actions ? actions->ofpacts : NULL;
4781     fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
4782
4783     if (list_is_empty(msgs)) {
4784         ofputil_start_flow_update(msgs);
4785     }
4786     ofputil_append_flow_update(&fu, msgs);
4787 }
4788
4789 void
4790 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
4791                                   struct list *msgs)
4792     OVS_REQUIRES(ofproto_mutex)
4793 {
4794     size_t i;
4795
4796     for (i = 0; i < rules->n; i++) {
4797         struct rule *rule = rules->rules[i];
4798         enum nx_flow_monitor_flags flags = rule->monitor_flags;
4799         rule->monitor_flags = 0;
4800
4801         ofproto_compose_flow_refresh_update(rule, flags, msgs);
4802     }
4803 }
4804
4805 static void
4806 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
4807                                        struct rule *rule, uint64_t seqno,
4808                                        struct rule_collection *rules)
4809     OVS_REQUIRES(ofproto_mutex)
4810 {
4811     enum nx_flow_monitor_flags update;
4812
4813     if (ofproto_rule_is_hidden(rule)) {
4814         return;
4815     }
4816
4817     if (!(rule->pending
4818           ? ofoperation_has_out_port(rule->pending, m->out_port)
4819           : ofproto_rule_has_out_port(rule, m->out_port))) {
4820         return;
4821     }
4822
4823     if (seqno) {
4824         if (rule->add_seqno > seqno) {
4825             update = NXFMF_ADD | NXFMF_MODIFY;
4826         } else if (rule->modify_seqno > seqno) {
4827             update = NXFMF_MODIFY;
4828         } else {
4829             return;
4830         }
4831
4832         if (!(m->flags & update)) {
4833             return;
4834         }
4835     } else {
4836         update = NXFMF_INITIAL;
4837     }
4838
4839     if (!rule->monitor_flags) {
4840         rule_collection_add(rules, rule);
4841     }
4842     rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
4843 }
4844
4845 static void
4846 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
4847                                         uint64_t seqno,
4848                                         struct rule_collection *rules)
4849     OVS_REQUIRES(ofproto_mutex)
4850 {
4851     const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
4852     const struct ofoperation *op;
4853     const struct oftable *table;
4854     struct cls_rule target;
4855
4856     cls_rule_init_from_minimatch(&target, &m->match, 0);
4857     FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
4858         struct cls_cursor cursor;
4859         struct rule *rule;
4860
4861         fat_rwlock_rdlock(&table->cls.rwlock);
4862         cls_cursor_init(&cursor, &table->cls, &target);
4863         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
4864             ovs_assert(!rule->pending); /* XXX */
4865             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4866         }
4867         fat_rwlock_unlock(&table->cls.rwlock);
4868     }
4869
4870     HMAP_FOR_EACH (op, hmap_node, &ofproto->deletions) {
4871         struct rule *rule = op->rule;
4872
4873         if (((m->table_id == 0xff
4874               ? !(ofproto->tables[rule->table_id].flags & OFTABLE_HIDDEN)
4875               : m->table_id == rule->table_id))
4876             && cls_rule_is_loose_match(&rule->cr, &target.match)) {
4877             ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
4878         }
4879     }
4880     cls_rule_destroy(&target);
4881 }
4882
4883 static void
4884 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
4885                                         struct rule_collection *rules)
4886     OVS_REQUIRES(ofproto_mutex)
4887 {
4888     if (m->flags & NXFMF_INITIAL) {
4889         ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
4890     }
4891 }
4892
4893 void
4894 ofmonitor_collect_resume_rules(struct ofmonitor *m,
4895                                uint64_t seqno, struct rule_collection *rules)
4896     OVS_REQUIRES(ofproto_mutex)
4897 {
4898     ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
4899 }
4900
4901 static enum ofperr
4902 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
4903     OVS_EXCLUDED(ofproto_mutex)
4904 {
4905     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4906     struct ofmonitor **monitors;
4907     size_t n_monitors, allocated_monitors;
4908     struct rule_collection rules;
4909     struct list replies;
4910     enum ofperr error;
4911     struct ofpbuf b;
4912     size_t i;
4913
4914     error = 0;
4915     ofpbuf_use_const(&b, oh, ntohs(oh->length));
4916     monitors = NULL;
4917     n_monitors = allocated_monitors = 0;
4918
4919     ovs_mutex_lock(&ofproto_mutex);
4920     for (;;) {
4921         struct ofputil_flow_monitor_request request;
4922         struct ofmonitor *m;
4923         int retval;
4924
4925         retval = ofputil_decode_flow_monitor_request(&request, &b);
4926         if (retval == EOF) {
4927             break;
4928         } else if (retval) {
4929             error = retval;
4930             goto error;
4931         }
4932
4933         if (request.table_id != 0xff
4934             && request.table_id >= ofproto->n_tables) {
4935             error = OFPERR_OFPBRC_BAD_TABLE_ID;
4936             goto error;
4937         }
4938
4939         error = ofmonitor_create(&request, ofconn, &m);
4940         if (error) {
4941             goto error;
4942         }
4943
4944         if (n_monitors >= allocated_monitors) {
4945             monitors = x2nrealloc(monitors, &allocated_monitors,
4946                                   sizeof *monitors);
4947         }
4948         monitors[n_monitors++] = m;
4949     }
4950
4951     rule_collection_init(&rules);
4952     for (i = 0; i < n_monitors; i++) {
4953         ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
4954     }
4955
4956     ofpmp_init(&replies, oh);
4957     ofmonitor_compose_refresh_updates(&rules, &replies);
4958     ovs_mutex_unlock(&ofproto_mutex);
4959
4960     rule_collection_destroy(&rules);
4961
4962     ofconn_send_replies(ofconn, &replies);
4963     free(monitors);
4964
4965     return 0;
4966
4967 error:
4968     for (i = 0; i < n_monitors; i++) {
4969         ofmonitor_destroy(monitors[i]);
4970     }
4971     free(monitors);
4972     ovs_mutex_unlock(&ofproto_mutex);
4973
4974     return error;
4975 }
4976
4977 static enum ofperr
4978 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
4979     OVS_EXCLUDED(ofproto_mutex)
4980 {
4981     struct ofmonitor *m;
4982     enum ofperr error;
4983     uint32_t id;
4984
4985     id = ofputil_decode_flow_monitor_cancel(oh);
4986
4987     ovs_mutex_lock(&ofproto_mutex);
4988     m = ofmonitor_lookup(ofconn, id);
4989     if (m) {
4990         ofmonitor_destroy(m);
4991         error = 0;
4992     } else {
4993         error = OFPERR_NXBRC_FM_BAD_ID;
4994     }
4995     ovs_mutex_unlock(&ofproto_mutex);
4996
4997     return error;
4998 }
4999
5000 /* Meters implementation.
5001  *
5002  * Meter table entry, indexed by the OpenFlow meter_id.
5003  * 'created' is used to compute the duration for meter stats.
5004  * 'list rules' is needed so that we can delete the dependent rules when the
5005  * meter table entry is deleted.
5006  * 'provider_meter_id' is for the provider's private use.
5007  */
5008 struct meter {
5009     long long int created;      /* Time created. */
5010     struct list rules;          /* List of "struct rule_dpif"s. */
5011     ofproto_meter_id provider_meter_id;
5012     uint16_t flags;             /* Meter flags. */
5013     uint16_t n_bands;           /* Number of meter bands. */
5014     struct ofputil_meter_band *bands;
5015 };
5016
5017 /*
5018  * This is used in instruction validation at flow set-up time,
5019  * as flows may not use non-existing meters.
5020  * Return value of UINT32_MAX signifies an invalid meter.
5021  */
5022 static uint32_t
5023 get_provider_meter_id(const struct ofproto *ofproto, uint32_t of_meter_id)
5024 {
5025     if (of_meter_id && of_meter_id <= ofproto->meter_features.max_meters) {
5026         const struct meter *meter = ofproto->meters[of_meter_id];
5027         if (meter) {
5028             return meter->provider_meter_id.uint32;
5029         }
5030     }
5031     return UINT32_MAX;
5032 }
5033
5034 /* Finds the meter invoked by 'rule''s actions and adds 'rule' to the meter's
5035  * list of rules. */
5036 static void
5037 meter_insert_rule(struct rule *rule)
5038 {
5039     const struct rule_actions *a = rule_get_actions(rule);
5040     uint32_t meter_id = ofpacts_get_meter(a->ofpacts, a->ofpacts_len);
5041     struct meter *meter = rule->ofproto->meters[meter_id];
5042
5043     list_insert(&meter->rules, &rule->meter_list_node);
5044 }
5045
5046 static void
5047 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
5048 {
5049     free(meter->bands);
5050
5051     meter->flags = config->flags;
5052     meter->n_bands = config->n_bands;
5053     meter->bands = xmemdup(config->bands,
5054                            config->n_bands * sizeof *meter->bands);
5055 }
5056
5057 static struct meter *
5058 meter_create(const struct ofputil_meter_config *config,
5059              ofproto_meter_id provider_meter_id)
5060 {
5061     struct meter *meter;
5062
5063     meter = xzalloc(sizeof *meter);
5064     meter->provider_meter_id = provider_meter_id;
5065     meter->created = time_msec();
5066     list_init(&meter->rules);
5067
5068     meter_update(meter, config);
5069
5070     return meter;
5071 }
5072
5073 static void
5074 meter_delete(struct ofproto *ofproto, uint32_t first, uint32_t last)
5075     OVS_REQUIRES(ofproto_mutex)
5076 {
5077     uint32_t mid;
5078     for (mid = first; mid <= last; ++mid) {
5079         struct meter *meter = ofproto->meters[mid];
5080         if (meter) {
5081             ofproto->meters[mid] = NULL;
5082             ofproto->ofproto_class->meter_del(ofproto,
5083                                               meter->provider_meter_id);
5084             free(meter->bands);
5085             free(meter);
5086         }
5087     }
5088 }
5089
5090 static enum ofperr
5091 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5092 {
5093     ofproto_meter_id provider_meter_id = { UINT32_MAX };
5094     struct meter **meterp = &ofproto->meters[mm->meter.meter_id];
5095     enum ofperr error;
5096
5097     if (*meterp) {
5098         return OFPERR_OFPMMFC_METER_EXISTS;
5099     }
5100
5101     error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
5102                                               &mm->meter);
5103     if (!error) {
5104         ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
5105         *meterp = meter_create(&mm->meter, provider_meter_id);
5106     }
5107     return error;
5108 }
5109
5110 static enum ofperr
5111 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
5112 {
5113     struct meter *meter = ofproto->meters[mm->meter.meter_id];
5114     enum ofperr error;
5115     uint32_t provider_meter_id;
5116
5117     if (!meter) {
5118         return OFPERR_OFPMMFC_UNKNOWN_METER;
5119     }
5120
5121     provider_meter_id = meter->provider_meter_id.uint32;
5122     error = ofproto->ofproto_class->meter_set(ofproto,
5123                                               &meter->provider_meter_id,
5124                                               &mm->meter);
5125     ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
5126     if (!error) {
5127         meter_update(meter, &mm->meter);
5128     }
5129     return error;
5130 }
5131
5132 static enum ofperr
5133 handle_delete_meter(struct ofconn *ofconn, const struct ofp_header *oh,
5134                     struct ofputil_meter_mod *mm)
5135     OVS_EXCLUDED(ofproto_mutex)
5136 {
5137     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5138     uint32_t meter_id = mm->meter.meter_id;
5139     struct rule_collection rules;
5140     enum ofperr error = 0;
5141     uint32_t first, last;
5142
5143     if (meter_id == OFPM13_ALL) {
5144         first = 1;
5145         last = ofproto->meter_features.max_meters;
5146     } else {
5147         if (!meter_id || meter_id > ofproto->meter_features.max_meters) {
5148             return 0;
5149         }
5150         first = last = meter_id;
5151     }
5152
5153     /* First delete the rules that use this meter.  If any of those rules are
5154      * currently being modified, postpone the whole operation until later. */
5155     rule_collection_init(&rules);
5156     ovs_mutex_lock(&ofproto_mutex);
5157     for (meter_id = first; meter_id <= last; ++meter_id) {
5158         struct meter *meter = ofproto->meters[meter_id];
5159         if (meter && !list_is_empty(&meter->rules)) {
5160             struct rule *rule;
5161
5162             LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
5163                 if (rule->pending) {
5164                     error = OFPROTO_POSTPONE;
5165                     goto exit;
5166                 }
5167                 rule_collection_add(&rules, rule);
5168             }
5169         }
5170     }
5171     if (rules.n > 0) {
5172         delete_flows__(ofproto, ofconn, oh, &rules, OFPRR_METER_DELETE);
5173     }
5174
5175     /* Delete the meters. */
5176     meter_delete(ofproto, first, last);
5177
5178 exit:
5179     ovs_mutex_unlock(&ofproto_mutex);
5180     rule_collection_destroy(&rules);
5181
5182     return error;
5183 }
5184
5185 static enum ofperr
5186 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5187 {
5188     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5189     struct ofputil_meter_mod mm;
5190     uint64_t bands_stub[256 / 8];
5191     struct ofpbuf bands;
5192     uint32_t meter_id;
5193     enum ofperr error;
5194
5195     error = reject_slave_controller(ofconn);
5196     if (error) {
5197         return error;
5198     }
5199
5200     ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5201
5202     error = ofputil_decode_meter_mod(oh, &mm, &bands);
5203     if (error) {
5204         goto exit_free_bands;
5205     }
5206
5207     meter_id = mm.meter.meter_id;
5208
5209     if (mm.command != OFPMC13_DELETE) {
5210         /* Fails also when meters are not implemented by the provider. */
5211         if (meter_id == 0 || meter_id > OFPM13_MAX) {
5212             error = OFPERR_OFPMMFC_INVALID_METER;
5213             goto exit_free_bands;
5214         } else if (meter_id > ofproto->meter_features.max_meters) {
5215             error = OFPERR_OFPMMFC_OUT_OF_METERS;
5216             goto exit_free_bands;
5217         }
5218         if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
5219             error = OFPERR_OFPMMFC_OUT_OF_BANDS;
5220             goto exit_free_bands;
5221         }
5222     }
5223
5224     switch (mm.command) {
5225     case OFPMC13_ADD:
5226         error = handle_add_meter(ofproto, &mm);
5227         break;
5228
5229     case OFPMC13_MODIFY:
5230         error = handle_modify_meter(ofproto, &mm);
5231         break;
5232
5233     case OFPMC13_DELETE:
5234         error = handle_delete_meter(ofconn, oh, &mm);
5235         break;
5236
5237     default:
5238         error = OFPERR_OFPMMFC_BAD_COMMAND;
5239         break;
5240     }
5241
5242 exit_free_bands:
5243     ofpbuf_uninit(&bands);
5244     return error;
5245 }
5246
5247 static enum ofperr
5248 handle_meter_features_request(struct ofconn *ofconn,
5249                               const struct ofp_header *request)
5250 {
5251     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5252     struct ofputil_meter_features features;
5253     struct ofpbuf *b;
5254
5255     if (ofproto->ofproto_class->meter_get_features) {
5256         ofproto->ofproto_class->meter_get_features(ofproto, &features);
5257     } else {
5258         memset(&features, 0, sizeof features);
5259     }
5260     b = ofputil_encode_meter_features_reply(&features, request);
5261
5262     ofconn_send_reply(ofconn, b);
5263     return 0;
5264 }
5265
5266 static enum ofperr
5267 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
5268                      enum ofptype type)
5269 {
5270     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5271     struct list replies;
5272     uint64_t bands_stub[256 / 8];
5273     struct ofpbuf bands;
5274     uint32_t meter_id, first, last;
5275
5276     ofputil_decode_meter_request(request, &meter_id);
5277
5278     if (meter_id == OFPM13_ALL) {
5279         first = 1;
5280         last = ofproto->meter_features.max_meters;
5281     } else {
5282         if (!meter_id || meter_id > ofproto->meter_features.max_meters ||
5283             !ofproto->meters[meter_id]) {
5284             return OFPERR_OFPMMFC_UNKNOWN_METER;
5285         }
5286         first = last = meter_id;
5287     }
5288
5289     ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
5290     ofpmp_init(&replies, request);
5291
5292     for (meter_id = first; meter_id <= last; ++meter_id) {
5293         struct meter *meter = ofproto->meters[meter_id];
5294         if (!meter) {
5295             continue; /* Skip non-existing meters. */
5296         }
5297         if (type == OFPTYPE_METER_STATS_REQUEST) {
5298             struct ofputil_meter_stats stats;
5299
5300             stats.meter_id = meter_id;
5301
5302             /* Provider sets the packet and byte counts, we do the rest. */
5303             stats.flow_count = list_size(&meter->rules);
5304             calc_duration(meter->created, time_msec(),
5305                           &stats.duration_sec, &stats.duration_nsec);
5306             stats.n_bands = meter->n_bands;
5307             ofpbuf_clear(&bands);
5308             stats.bands
5309                 = ofpbuf_put_uninit(&bands,
5310                                     meter->n_bands * sizeof *stats.bands);
5311
5312             if (!ofproto->ofproto_class->meter_get(ofproto,
5313                                                    meter->provider_meter_id,
5314                                                    &stats)) {
5315                 ofputil_append_meter_stats(&replies, &stats);
5316             }
5317         } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
5318             struct ofputil_meter_config config;
5319
5320             config.meter_id = meter_id;
5321             config.flags = meter->flags;
5322             config.n_bands = meter->n_bands;
5323             config.bands = meter->bands;
5324             ofputil_append_meter_config(&replies, &config);
5325         }
5326     }
5327
5328     ofconn_send_replies(ofconn, &replies);
5329     ofpbuf_uninit(&bands);
5330     return 0;
5331 }
5332
5333 static bool
5334 ofproto_group_lookup__(const struct ofproto *ofproto, uint32_t group_id,
5335                        struct ofgroup **group)
5336     OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5337 {
5338     HMAP_FOR_EACH_IN_BUCKET (*group, hmap_node,
5339                              hash_int(group_id, 0), &ofproto->groups) {
5340         if ((*group)->group_id == group_id) {
5341             return true;
5342         }
5343     }
5344
5345     return false;
5346 }
5347
5348 /* If the group exists, this function increments the groups's reference count.
5349  *
5350  * Make sure to call ofproto_group_unref() after no longer needing to maintain
5351  * a reference to the group. */
5352 bool
5353 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
5354                      struct ofgroup **group)
5355 {
5356     bool found;
5357
5358     ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5359     found = ofproto_group_lookup__(ofproto, group_id, group);
5360     if (found) {
5361         ofproto_group_ref(*group);
5362     }
5363     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5364     return found;
5365 }
5366
5367 static bool
5368 ofproto_group_exists__(const struct ofproto *ofproto, uint32_t group_id)
5369     OVS_REQ_RDLOCK(ofproto->groups_rwlock)
5370 {
5371     struct ofgroup *grp;
5372
5373     HMAP_FOR_EACH_IN_BUCKET (grp, hmap_node,
5374                              hash_int(group_id, 0), &ofproto->groups) {
5375         if (grp->group_id == group_id) {
5376             return true;
5377         }
5378     }
5379     return false;
5380 }
5381
5382 static bool
5383 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
5384     OVS_EXCLUDED(ofproto->groups_rwlock)
5385 {
5386     bool exists;
5387
5388     ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5389     exists = ofproto_group_exists__(ofproto, group_id);
5390     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5391
5392     return exists;
5393 }
5394
5395 static uint32_t
5396 group_get_ref_count(struct ofgroup *group)
5397     OVS_EXCLUDED(ofproto_mutex)
5398 {
5399     struct ofproto *ofproto = CONST_CAST(struct ofproto *, group->ofproto);
5400     struct rule_criteria criteria;
5401     struct rule_collection rules;
5402     struct match match;
5403     enum ofperr error;
5404     uint32_t count;
5405
5406     match_init_catchall(&match);
5407     rule_criteria_init(&criteria, 0xff, &match, 0, htonll(0), htonll(0),
5408                        OFPP_ANY, group->group_id);
5409     ovs_mutex_lock(&ofproto_mutex);
5410     error = collect_rules_loose(ofproto, &criteria, &rules);
5411     ovs_mutex_unlock(&ofproto_mutex);
5412     rule_criteria_destroy(&criteria);
5413
5414     count = !error && rules.n < UINT32_MAX ? rules.n : UINT32_MAX;
5415
5416     rule_collection_destroy(&rules);
5417     return count;
5418 }
5419
5420 static void
5421 append_group_stats(struct ofgroup *group, struct list *replies)
5422 {
5423     struct ofputil_group_stats ogs;
5424     const struct ofproto *ofproto = group->ofproto;
5425     long long int now = time_msec();
5426     int error;
5427
5428     ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
5429
5430     /* Provider sets the packet and byte counts, we do the rest. */
5431     ogs.ref_count = group_get_ref_count(group);
5432     ogs.n_buckets = group->n_buckets;
5433
5434     error = (ofproto->ofproto_class->group_get_stats
5435              ? ofproto->ofproto_class->group_get_stats(group, &ogs)
5436              : EOPNOTSUPP);
5437     if (error) {
5438         ogs.packet_count = UINT64_MAX;
5439         ogs.byte_count = UINT64_MAX;
5440         memset(ogs.bucket_stats, 0xff,
5441                ogs.n_buckets * sizeof *ogs.bucket_stats);
5442     }
5443
5444     ogs.group_id = group->group_id;
5445     calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
5446
5447     ofputil_append_group_stats(replies, &ogs);
5448
5449     free(ogs.bucket_stats);
5450 }
5451
5452 static void
5453 handle_group_request(struct ofconn *ofconn,
5454                      const struct ofp_header *request, uint32_t group_id,
5455                      void (*cb)(struct ofgroup *, struct list *replies))
5456 {
5457     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5458     struct ofgroup *group;
5459     struct list replies;
5460
5461     ofpmp_init(&replies, request);
5462     if (group_id == OFPG_ALL) {
5463         ovs_rwlock_rdlock(&ofproto->groups_rwlock);
5464         HMAP_FOR_EACH (group, hmap_node, &ofproto->groups) {
5465             cb(group, &replies);
5466         }
5467         ovs_rwlock_unlock(&ofproto->groups_rwlock);
5468     } else {
5469         if (ofproto_group_lookup(ofproto, group_id, &group)) {
5470             cb(group, &replies);
5471             ofproto_group_unref(group);
5472         }
5473     }
5474     ofconn_send_replies(ofconn, &replies);
5475 }
5476
5477 static enum ofperr
5478 handle_group_stats_request(struct ofconn *ofconn,
5479                            const struct ofp_header *request)
5480 {
5481     uint32_t group_id;
5482     enum ofperr error;
5483
5484     error = ofputil_decode_group_stats_request(request, &group_id);
5485     if (error) {
5486         return error;
5487     }
5488
5489     handle_group_request(ofconn, request, group_id, append_group_stats);
5490     return 0;
5491 }
5492
5493 static void
5494 append_group_desc(struct ofgroup *group, struct list *replies)
5495 {
5496     struct ofputil_group_desc gds;
5497
5498     gds.group_id = group->group_id;
5499     gds.type = group->type;
5500     ofputil_append_group_desc_reply(&gds, &group->buckets, replies);
5501 }
5502
5503 static enum ofperr
5504 handle_group_desc_stats_request(struct ofconn *ofconn,
5505                                 const struct ofp_header *request)
5506 {
5507     handle_group_request(ofconn, request,
5508                          ofputil_decode_group_desc_request(request),
5509                          append_group_desc);
5510     return 0;
5511 }
5512
5513 static enum ofperr
5514 handle_group_features_stats_request(struct ofconn *ofconn,
5515                                     const struct ofp_header *request)
5516 {
5517     struct ofproto *p = ofconn_get_ofproto(ofconn);
5518     struct ofpbuf *msg;
5519
5520     msg = ofputil_encode_group_features_reply(&p->ogf, request);
5521     if (msg) {
5522         ofconn_send_reply(ofconn, msg);
5523     }
5524
5525     return 0;
5526 }
5527
5528 static enum ofperr
5529 handle_queue_get_config_request(struct ofconn *ofconn,
5530                                 const struct ofp_header *oh)
5531 {
5532    struct ofproto *p = ofconn_get_ofproto(ofconn);
5533    struct netdev_queue_dump queue_dump;
5534    struct ofport *ofport;
5535    unsigned int queue_id;
5536    struct ofpbuf *reply;
5537    struct smap details;
5538    ofp_port_t request;
5539    enum ofperr error;
5540
5541    error = ofputil_decode_queue_get_config_request(oh, &request);
5542    if (error) {
5543        return error;
5544    }
5545
5546    ofport = ofproto_get_port(p, request);
5547    if (!ofport) {
5548       return OFPERR_OFPQOFC_BAD_PORT;
5549    }
5550
5551    reply = ofputil_encode_queue_get_config_reply(oh);
5552
5553    smap_init(&details);
5554    NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &queue_dump, ofport->netdev) {
5555        struct ofputil_queue_config queue;
5556
5557        /* None of the existing queues have compatible properties, so we
5558         * hard-code omitting min_rate and max_rate. */
5559        queue.queue_id = queue_id;
5560        queue.min_rate = UINT16_MAX;
5561        queue.max_rate = UINT16_MAX;
5562        ofputil_append_queue_get_config_reply(reply, &queue);
5563    }
5564    smap_destroy(&details);
5565
5566    ofconn_send_reply(ofconn, reply);
5567
5568    return 0;
5569 }
5570
5571 static enum ofperr
5572 init_group(struct ofproto *ofproto, struct ofputil_group_mod *gm,
5573            struct ofgroup **ofgroup)
5574 {
5575     enum ofperr error;
5576     const long long int now = time_msec();
5577
5578     if (gm->group_id > OFPG_MAX) {
5579         return OFPERR_OFPGMFC_INVALID_GROUP;
5580     }
5581     if (gm->type > OFPGT11_FF) {
5582         return OFPERR_OFPGMFC_BAD_TYPE;
5583     }
5584
5585     *ofgroup = ofproto->ofproto_class->group_alloc();
5586     if (!*ofgroup) {
5587         VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
5588         return OFPERR_OFPGMFC_OUT_OF_GROUPS;
5589     }
5590
5591     (*ofgroup)->ofproto = ofproto;
5592     *CONST_CAST(uint32_t *, &((*ofgroup)->group_id)) = gm->group_id;
5593     *CONST_CAST(enum ofp11_group_type *, &(*ofgroup)->type) = gm->type;
5594     *CONST_CAST(long long int *, &((*ofgroup)->created)) = now;
5595     *CONST_CAST(long long int *, &((*ofgroup)->modified)) = now;
5596     ovs_refcount_init(&(*ofgroup)->ref_count);
5597
5598     list_move(&(*ofgroup)->buckets, &gm->buckets);
5599     *CONST_CAST(uint32_t *, &(*ofgroup)->n_buckets) =
5600         list_size(&(*ofgroup)->buckets);
5601
5602     /* Construct called BEFORE any locks are held. */
5603     error = ofproto->ofproto_class->group_construct(*ofgroup);
5604     if (error) {
5605         ofputil_bucket_list_destroy(&(*ofgroup)->buckets);
5606         ofproto->ofproto_class->group_dealloc(*ofgroup);
5607     }
5608     return error;
5609 }
5610
5611 /* Implements the OFPGC11_ADD operation specified by 'gm', adding a group to
5612  * 'ofproto''s group table.  Returns 0 on success or an OpenFlow error code on
5613  * failure. */
5614 static enum ofperr
5615 add_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5616 {
5617     struct ofgroup *ofgroup;
5618     enum ofperr error;
5619
5620     /* Allocate new group and initialize it. */
5621     error = init_group(ofproto, gm, &ofgroup);
5622     if (error) {
5623         return error;
5624     }
5625
5626     /* We wrlock as late as possible to minimize the time we jam any other
5627      * threads: No visible state changes before acquiring the lock. */
5628     ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5629
5630     if (ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5631         error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5632         goto unlock_out;
5633     }
5634
5635     if (ofproto_group_exists__(ofproto, gm->group_id)) {
5636         error = OFPERR_OFPGMFC_GROUP_EXISTS;
5637         goto unlock_out;
5638     }
5639
5640     if (!error) {
5641         /* Insert new group. */
5642         hmap_insert(&ofproto->groups, &ofgroup->hmap_node,
5643                     hash_int(ofgroup->group_id, 0));
5644         ofproto->n_groups[ofgroup->type]++;
5645
5646         ovs_rwlock_unlock(&ofproto->groups_rwlock);
5647         return error;
5648     }
5649
5650  unlock_out:
5651     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5652     ofproto->ofproto_class->group_destruct(ofgroup);
5653     ofputil_bucket_list_destroy(&ofgroup->buckets);
5654     ofproto->ofproto_class->group_dealloc(ofgroup);
5655
5656     return error;
5657 }
5658
5659 /* Implements OFPGC11_MODIFY.  Returns 0 on success or an OpenFlow error code
5660  * on failure.
5661  *
5662  * Note that the group is re-created and then replaces the old group in
5663  * ofproto's ofgroup hash map. Thus, the group is never altered while users of
5664  * the xlate module hold a pointer to the group. */
5665 static enum ofperr
5666 modify_group(struct ofproto *ofproto, struct ofputil_group_mod *gm)
5667 {
5668     struct ofgroup *ofgroup, *new_ofgroup, *retiring;
5669     enum ofperr error;
5670
5671     error = init_group(ofproto, gm, &new_ofgroup);
5672     if (error) {
5673         return error;
5674     }
5675
5676     retiring = new_ofgroup;
5677
5678     ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5679     if (!ofproto_group_lookup__(ofproto, gm->group_id, &ofgroup)) {
5680         error = OFPERR_OFPGMFC_UNKNOWN_GROUP;
5681         goto out;
5682     }
5683
5684     /* Ofproto's group write lock is held now. */
5685     if (ofgroup->type != gm->type
5686         && ofproto->n_groups[gm->type] >= ofproto->ogf.max_groups[gm->type]) {
5687         error = OFPERR_OFPGMFC_OUT_OF_GROUPS;
5688         goto out;
5689     }
5690
5691     /* The group creation time does not change during modification. */
5692     *CONST_CAST(long long int *, &(new_ofgroup->created)) = ofgroup->created;
5693     *CONST_CAST(long long int *, &(new_ofgroup->modified)) = time_msec();
5694
5695     error = ofproto->ofproto_class->group_modify(new_ofgroup);
5696     if (error) {
5697         goto out;
5698     }
5699
5700     retiring = ofgroup;
5701     /* Replace ofgroup in ofproto's groups hash map with new_ofgroup. */
5702     hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5703     hmap_insert(&ofproto->groups, &new_ofgroup->hmap_node,
5704                 hash_int(new_ofgroup->group_id, 0));
5705     if (ofgroup->type != new_ofgroup->type) {
5706         ofproto->n_groups[ofgroup->type]--;
5707         ofproto->n_groups[new_ofgroup->type]++;
5708     }
5709
5710 out:
5711     ofproto_group_unref(retiring);
5712     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5713     return error;
5714 }
5715
5716 static void
5717 delete_group__(struct ofproto *ofproto, struct ofgroup *ofgroup)
5718     OVS_RELEASES(ofproto->groups_rwlock)
5719 {
5720     struct match match;
5721     struct ofputil_flow_mod fm;
5722
5723     /* Delete all flow entries containing this group in a group action */
5724     match_init_catchall(&match);
5725     flow_mod_init(&fm, &match, 0, NULL, 0, OFPFC_DELETE);
5726     fm.delete_reason = OFPRR_GROUP_DELETE;
5727     fm.out_group = ofgroup->group_id;
5728     handle_flow_mod__(ofproto, NULL, &fm, NULL);
5729
5730     hmap_remove(&ofproto->groups, &ofgroup->hmap_node);
5731     /* No-one can find this group any more. */
5732     ofproto->n_groups[ofgroup->type]--;
5733     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5734     ofproto_group_unref(ofgroup);
5735 }
5736
5737 /* Implements OFPGC11_DELETE. */
5738 static void
5739 delete_group(struct ofproto *ofproto, uint32_t group_id)
5740 {
5741     struct ofgroup *ofgroup;
5742
5743     ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5744     if (group_id == OFPG_ALL) {
5745         for (;;) {
5746             struct hmap_node *node = hmap_first(&ofproto->groups);
5747             if (!node) {
5748                 break;
5749             }
5750             ofgroup = CONTAINER_OF(node, struct ofgroup, hmap_node);
5751             delete_group__(ofproto, ofgroup);
5752             /* Lock for each node separately, so that we will not jam the
5753              * other threads for too long time. */
5754             ovs_rwlock_wrlock(&ofproto->groups_rwlock);
5755         }
5756     } else {
5757         HMAP_FOR_EACH_IN_BUCKET (ofgroup, hmap_node,
5758                                  hash_int(group_id, 0), &ofproto->groups) {
5759             if (ofgroup->group_id == group_id) {
5760                 delete_group__(ofproto, ofgroup);
5761                 return;
5762             }
5763         }
5764     }
5765     ovs_rwlock_unlock(&ofproto->groups_rwlock);
5766 }
5767
5768 static enum ofperr
5769 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5770 {
5771     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5772     struct ofputil_group_mod gm;
5773     enum ofperr error;
5774
5775     error = reject_slave_controller(ofconn);
5776     if (error) {
5777         return error;
5778     }
5779
5780     error = ofputil_decode_group_mod(oh, &gm);
5781     if (error) {
5782         return error;
5783     }
5784
5785     switch (gm.command) {
5786     case OFPGC11_ADD:
5787         return add_group(ofproto, &gm);
5788
5789     case OFPGC11_MODIFY:
5790         return modify_group(ofproto, &gm);
5791
5792     case OFPGC11_DELETE:
5793         delete_group(ofproto, gm.group_id);
5794         return 0;
5795
5796     default:
5797         if (gm.command > OFPGC11_DELETE) {
5798             VLOG_WARN_RL(&rl, "%s: Invalid group_mod command type %d",
5799                          ofproto->name, gm.command);
5800         }
5801         return OFPERR_OFPGMFC_BAD_COMMAND;
5802     }
5803 }
5804
5805 enum ofproto_table_config
5806 ofproto_table_get_config(const struct ofproto *ofproto, uint8_t table_id)
5807 {
5808     unsigned int value;
5809     atomic_read(&ofproto->tables[table_id].config, &value);
5810     return (enum ofproto_table_config)value;
5811 }
5812
5813 static enum ofperr
5814 table_mod(struct ofproto *ofproto, const struct ofputil_table_mod *tm)
5815 {
5816     /* Only accept currently supported configurations */
5817     if (tm->config & ~OFPTC11_TABLE_MISS_MASK) {
5818         return OFPERR_OFPTMFC_BAD_CONFIG;
5819     }
5820
5821     if (tm->table_id == OFPTT_ALL) {
5822         int i;
5823         for (i = 0; i < ofproto->n_tables; i++) {
5824             atomic_store(&ofproto->tables[i].config,
5825                          (unsigned int)tm->config);
5826         }
5827     } else if (!check_table_id(ofproto, tm->table_id)) {
5828         return OFPERR_OFPTMFC_BAD_TABLE;
5829     } else {
5830         atomic_store(&ofproto->tables[tm->table_id].config,
5831                      (unsigned int)tm->config);
5832     }
5833
5834     return 0;
5835 }
5836
5837 static enum ofperr
5838 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5839 {
5840     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5841     struct ofputil_table_mod tm;
5842     enum ofperr error;
5843
5844     error = reject_slave_controller(ofconn);
5845     if (error) {
5846         return error;
5847     }
5848
5849     error = ofputil_decode_table_mod(oh, &tm);
5850     if (error) {
5851         return error;
5852     }
5853
5854     return table_mod(ofproto, &tm);
5855 }
5856
5857 static enum ofperr
5858 handle_bundle_control(struct ofconn *ofconn, const struct ofp_header *oh)
5859 {
5860     enum ofperr error;
5861     struct ofputil_bundle_ctrl_msg bctrl;
5862     struct ofpbuf *buf;
5863     struct ofputil_bundle_ctrl_msg reply;
5864
5865     error = ofputil_decode_bundle_ctrl(oh, &bctrl);
5866     if (error) {
5867         return error;
5868     }
5869     reply.flags = 0;
5870     reply.bundle_id = bctrl.bundle_id;
5871
5872     switch (bctrl.type) {
5873         case OFPBCT_OPEN_REQUEST:
5874         error = ofp_bundle_open(ofconn, bctrl.bundle_id, bctrl.flags);
5875         reply.type = OFPBCT_OPEN_REPLY;
5876         break;
5877     case OFPBCT_CLOSE_REQUEST:
5878         error = ofp_bundle_close(ofconn, bctrl.bundle_id, bctrl.flags);
5879         reply.type = OFPBCT_CLOSE_REPLY;;
5880         break;
5881     case OFPBCT_COMMIT_REQUEST:
5882         error = ofp_bundle_commit(ofconn, bctrl.bundle_id, bctrl.flags);
5883         reply.type = OFPBCT_COMMIT_REPLY;
5884         break;
5885     case OFPBCT_DISCARD_REQUEST:
5886         error = ofp_bundle_discard(ofconn, bctrl.bundle_id);
5887         reply.type = OFPBCT_DISCARD_REPLY;
5888         break;
5889
5890     case OFPBCT_OPEN_REPLY:
5891     case OFPBCT_CLOSE_REPLY:
5892     case OFPBCT_COMMIT_REPLY:
5893     case OFPBCT_DISCARD_REPLY:
5894         return OFPERR_OFPBFC_BAD_TYPE;
5895         break;
5896     }
5897
5898     if (!error) {
5899         buf = ofputil_encode_bundle_ctrl_reply(oh, &reply);
5900         ofconn_send_reply(ofconn, buf);
5901     }
5902     return error;
5903 }
5904
5905
5906 static enum ofperr
5907 handle_bundle_add(struct ofconn *ofconn, const struct ofp_header *oh)
5908 {
5909     enum ofperr error;
5910     struct ofputil_bundle_add_msg badd;
5911
5912     error = ofputil_decode_bundle_add(oh, &badd);
5913     if (error) {
5914         return error;
5915     }
5916
5917     return ofp_bundle_add_message(ofconn, &badd);
5918 }
5919
5920 static enum ofperr
5921 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
5922     OVS_EXCLUDED(ofproto_mutex)
5923 {
5924     const struct ofp_header *oh = ofpbuf_data(msg);
5925     enum ofptype type;
5926     enum ofperr error;
5927
5928     error = ofptype_decode(&type, oh);
5929     if (error) {
5930         return error;
5931     }
5932     if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
5933         && ofpmp_more(oh)) {
5934         /* We have no buffer implementation for multipart requests.
5935          * Report overflow for requests which consists of multiple
5936          * messages. */
5937         return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
5938     }
5939
5940     switch (type) {
5941         /* OpenFlow requests. */
5942     case OFPTYPE_ECHO_REQUEST:
5943         return handle_echo_request(ofconn, oh);
5944
5945     case OFPTYPE_FEATURES_REQUEST:
5946         return handle_features_request(ofconn, oh);
5947
5948     case OFPTYPE_GET_CONFIG_REQUEST:
5949         return handle_get_config_request(ofconn, oh);
5950
5951     case OFPTYPE_SET_CONFIG:
5952         return handle_set_config(ofconn, oh);
5953
5954     case OFPTYPE_PACKET_OUT:
5955         return handle_packet_out(ofconn, oh);
5956
5957     case OFPTYPE_PORT_MOD:
5958         return handle_port_mod(ofconn, oh);
5959
5960     case OFPTYPE_FLOW_MOD:
5961         return handle_flow_mod(ofconn, oh);
5962
5963     case OFPTYPE_GROUP_MOD:
5964         return handle_group_mod(ofconn, oh);
5965
5966     case OFPTYPE_TABLE_MOD:
5967         return handle_table_mod(ofconn, oh);
5968
5969     case OFPTYPE_METER_MOD:
5970         return handle_meter_mod(ofconn, oh);
5971
5972     case OFPTYPE_BARRIER_REQUEST:
5973         return handle_barrier_request(ofconn, oh);
5974
5975     case OFPTYPE_ROLE_REQUEST:
5976         return handle_role_request(ofconn, oh);
5977
5978         /* OpenFlow replies. */
5979     case OFPTYPE_ECHO_REPLY:
5980         return 0;
5981
5982         /* Nicira extension requests. */
5983     case OFPTYPE_FLOW_MOD_TABLE_ID:
5984         return handle_nxt_flow_mod_table_id(ofconn, oh);
5985
5986     case OFPTYPE_SET_FLOW_FORMAT:
5987         return handle_nxt_set_flow_format(ofconn, oh);
5988
5989     case OFPTYPE_SET_PACKET_IN_FORMAT:
5990         return handle_nxt_set_packet_in_format(ofconn, oh);
5991
5992     case OFPTYPE_SET_CONTROLLER_ID:
5993         return handle_nxt_set_controller_id(ofconn, oh);
5994
5995     case OFPTYPE_FLOW_AGE:
5996         /* Nothing to do. */
5997         return 0;
5998
5999     case OFPTYPE_FLOW_MONITOR_CANCEL:
6000         return handle_flow_monitor_cancel(ofconn, oh);
6001
6002     case OFPTYPE_SET_ASYNC_CONFIG:
6003         return handle_nxt_set_async_config(ofconn, oh);
6004
6005     case OFPTYPE_GET_ASYNC_REQUEST:
6006         return handle_nxt_get_async_request(ofconn, oh);
6007
6008         /* Statistics requests. */
6009     case OFPTYPE_DESC_STATS_REQUEST:
6010         return handle_desc_stats_request(ofconn, oh);
6011
6012     case OFPTYPE_FLOW_STATS_REQUEST:
6013         return handle_flow_stats_request(ofconn, oh);
6014
6015     case OFPTYPE_AGGREGATE_STATS_REQUEST:
6016         return handle_aggregate_stats_request(ofconn, oh);
6017
6018     case OFPTYPE_TABLE_STATS_REQUEST:
6019         return handle_table_stats_request(ofconn, oh);
6020
6021     case OFPTYPE_PORT_STATS_REQUEST:
6022         return handle_port_stats_request(ofconn, oh);
6023
6024     case OFPTYPE_QUEUE_STATS_REQUEST:
6025         return handle_queue_stats_request(ofconn, oh);
6026
6027     case OFPTYPE_PORT_DESC_STATS_REQUEST:
6028         return handle_port_desc_stats_request(ofconn, oh);
6029
6030     case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
6031         return handle_flow_monitor_request(ofconn, oh);
6032
6033     case OFPTYPE_METER_STATS_REQUEST:
6034     case OFPTYPE_METER_CONFIG_STATS_REQUEST:
6035         return handle_meter_request(ofconn, oh, type);
6036
6037     case OFPTYPE_METER_FEATURES_STATS_REQUEST:
6038         return handle_meter_features_request(ofconn, oh);
6039
6040     case OFPTYPE_GROUP_STATS_REQUEST:
6041         return handle_group_stats_request(ofconn, oh);
6042
6043     case OFPTYPE_GROUP_DESC_STATS_REQUEST:
6044         return handle_group_desc_stats_request(ofconn, oh);
6045
6046     case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
6047         return handle_group_features_stats_request(ofconn, oh);
6048
6049     case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
6050         return handle_queue_get_config_request(ofconn, oh);
6051
6052     case OFPTYPE_BUNDLE_CONTROL:
6053         return handle_bundle_control(ofconn, oh);
6054
6055     case OFPTYPE_BUNDLE_ADD_MESSAGE:
6056         return handle_bundle_add(ofconn, oh);
6057
6058     case OFPTYPE_HELLO:
6059     case OFPTYPE_ERROR:
6060     case OFPTYPE_FEATURES_REPLY:
6061     case OFPTYPE_GET_CONFIG_REPLY:
6062     case OFPTYPE_PACKET_IN:
6063     case OFPTYPE_FLOW_REMOVED:
6064     case OFPTYPE_PORT_STATUS:
6065     case OFPTYPE_BARRIER_REPLY:
6066     case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
6067     case OFPTYPE_DESC_STATS_REPLY:
6068     case OFPTYPE_FLOW_STATS_REPLY:
6069     case OFPTYPE_QUEUE_STATS_REPLY:
6070     case OFPTYPE_PORT_STATS_REPLY:
6071     case OFPTYPE_TABLE_STATS_REPLY:
6072     case OFPTYPE_AGGREGATE_STATS_REPLY:
6073     case OFPTYPE_PORT_DESC_STATS_REPLY:
6074     case OFPTYPE_ROLE_REPLY:
6075     case OFPTYPE_FLOW_MONITOR_PAUSED:
6076     case OFPTYPE_FLOW_MONITOR_RESUMED:
6077     case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
6078     case OFPTYPE_GET_ASYNC_REPLY:
6079     case OFPTYPE_GROUP_STATS_REPLY:
6080     case OFPTYPE_GROUP_DESC_STATS_REPLY:
6081     case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
6082     case OFPTYPE_METER_STATS_REPLY:
6083     case OFPTYPE_METER_CONFIG_STATS_REPLY:
6084     case OFPTYPE_METER_FEATURES_STATS_REPLY:
6085     case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
6086     case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
6087     case OFPTYPE_ROLE_STATUS:
6088     default:
6089         if (ofpmsg_is_stat_request(oh)) {
6090             return OFPERR_OFPBRC_BAD_STAT;
6091         } else {
6092             return OFPERR_OFPBRC_BAD_TYPE;
6093         }
6094     }
6095 }
6096
6097 static bool
6098 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
6099     OVS_EXCLUDED(ofproto_mutex)
6100 {
6101     int error = handle_openflow__(ofconn, ofp_msg);
6102     if (error && error != OFPROTO_POSTPONE) {
6103         ofconn_send_error(ofconn, ofpbuf_data(ofp_msg), error);
6104     }
6105     COVERAGE_INC(ofproto_recv_openflow);
6106     return error != OFPROTO_POSTPONE;
6107 }
6108 \f
6109 /* Asynchronous operations. */
6110
6111 /* Creates and returns a new ofopgroup that is not associated with any
6112  * OpenFlow connection.
6113  *
6114  * The caller should add operations to the returned group with
6115  * ofoperation_create() and then submit it with ofopgroup_submit(). */
6116 static struct ofopgroup *
6117 ofopgroup_create_unattached(struct ofproto *ofproto)
6118     OVS_REQUIRES(ofproto_mutex)
6119 {
6120     struct ofopgroup *group = xzalloc(sizeof *group);
6121     group->ofproto = ofproto;
6122     list_init(&group->ofproto_node);
6123     list_init(&group->ops);
6124     list_init(&group->ofconn_node);
6125     return group;
6126 }
6127
6128 /* Creates and returns a new ofopgroup for 'ofproto'.
6129  *
6130  * If 'ofconn' is NULL, the new ofopgroup is not associated with any OpenFlow
6131  * connection.  The 'request' and 'buffer_id' arguments are ignored.
6132  *
6133  * If 'ofconn' is nonnull, then the new ofopgroup is associated with 'ofconn'.
6134  * If the ofopgroup eventually fails, then the error reply will include
6135  * 'request'.  If the ofopgroup eventually succeeds, then the packet with
6136  * buffer id 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
6137  *
6138  * The caller should add operations to the returned group with
6139  * ofoperation_create() and then submit it with ofopgroup_submit(). */
6140 static struct ofopgroup *
6141 ofopgroup_create(struct ofproto *ofproto, struct ofconn *ofconn,
6142                  const struct ofp_header *request, uint32_t buffer_id)
6143     OVS_REQUIRES(ofproto_mutex)
6144 {
6145     struct ofopgroup *group = ofopgroup_create_unattached(ofproto);
6146     if (ofconn) {
6147         size_t request_len = ntohs(request->length);
6148
6149         ovs_assert(ofconn_get_ofproto(ofconn) == ofproto);
6150
6151         ofconn_add_opgroup(ofconn, &group->ofconn_node);
6152         group->ofconn = ofconn;
6153         group->request = xmemdup(request, MIN(request_len, 64));
6154         group->buffer_id = buffer_id;
6155     }
6156     return group;
6157 }
6158
6159 /* Submits 'group' for processing.
6160  *
6161  * If 'group' contains no operations (e.g. none were ever added, or all of the
6162  * ones that were added completed synchronously), then it is destroyed
6163  * immediately.  Otherwise it is added to the ofproto's list of pending
6164  * groups. */
6165 static void
6166 ofopgroup_submit(struct ofopgroup *group)
6167     OVS_REQUIRES(ofproto_mutex)
6168 {
6169     if (!group->n_running) {
6170         ofopgroup_complete(group);
6171     } else {
6172         list_push_back(&group->ofproto->pending, &group->ofproto_node);
6173         group->ofproto->n_pending++;
6174     }
6175 }
6176
6177 static void
6178 ofopgroup_complete(struct ofopgroup *group)
6179     OVS_REQUIRES(ofproto_mutex)
6180 {
6181     struct ofproto *ofproto = group->ofproto;
6182
6183     struct ofconn *abbrev_ofconn;
6184     ovs_be32 abbrev_xid;
6185
6186     struct ofoperation *op, *next_op;
6187     int error;
6188
6189     ovs_assert(!group->n_running);
6190
6191     error = 0;
6192     LIST_FOR_EACH (op, group_node, &group->ops) {
6193         if (op->error) {
6194             error = op->error;
6195             break;
6196         }
6197     }
6198
6199     if (!error && group->ofconn && group->buffer_id != UINT32_MAX) {
6200         LIST_FOR_EACH (op, group_node, &group->ops) {
6201             if (op->type != OFOPERATION_DELETE) {
6202                 struct ofpbuf *packet;
6203                 ofp_port_t in_port;
6204
6205                 error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
6206                                                &packet, &in_port);
6207                 if (packet) {
6208                     struct rule_execute *re;
6209
6210                     ovs_assert(!error);
6211
6212                     ofproto_rule_ref(op->rule);
6213
6214                     re = xmalloc(sizeof *re);
6215                     re->rule = op->rule;
6216                     re->in_port = in_port;
6217                     re->packet = packet;
6218
6219                     if (!guarded_list_push_back(&ofproto->rule_executes,
6220                                                 &re->list_node, 1024)) {
6221                         ofproto_rule_unref(op->rule);
6222                         ofpbuf_delete(re->packet);
6223                         free(re);
6224                     }
6225                 }
6226                 break;
6227             }
6228         }
6229     }
6230
6231     if (!error && !list_is_empty(&group->ofconn_node)) {
6232         abbrev_ofconn = group->ofconn;
6233         abbrev_xid = group->request->xid;
6234     } else {
6235         abbrev_ofconn = NULL;
6236         abbrev_xid = htonl(0);
6237     }
6238     LIST_FOR_EACH_SAFE (op, next_op, group_node, &group->ops) {
6239         struct rule *rule = op->rule;
6240
6241         /* We generally want to report the change to active OpenFlow flow
6242            monitors (e.g. NXST_FLOW_MONITOR).  There are three exceptions:
6243
6244               - The operation failed.
6245
6246               - The affected rule is not visible to controllers.
6247
6248               - The operation's only effect was to update rule->modified. */
6249         if (!(op->error
6250               || ofproto_rule_is_hidden(rule)
6251               || (op->type == OFOPERATION_MODIFY
6252                   && !op->actions
6253                   && rule->flow_cookie == op->flow_cookie))) {
6254             enum nx_flow_update_event event_type;
6255
6256             switch (op->type) {
6257             case OFOPERATION_ADD:
6258             case OFOPERATION_REPLACE:
6259                 event_type = NXFME_ADDED;
6260                 break;
6261
6262             case OFOPERATION_DELETE:
6263                 event_type = NXFME_DELETED;
6264                 break;
6265
6266             case OFOPERATION_MODIFY:
6267                 event_type = NXFME_MODIFIED;
6268                 break;
6269
6270             default:
6271                 OVS_NOT_REACHED();
6272             }
6273
6274             ofmonitor_report(ofproto->connmgr, rule, event_type,
6275                              op->reason, abbrev_ofconn, abbrev_xid);
6276         }
6277
6278         rule->pending = NULL;
6279
6280         switch (op->type) {
6281         case OFOPERATION_ADD:
6282             if (!op->error) {
6283                 uint16_t vid_mask;
6284
6285                 vid_mask = minimask_get_vid_mask(&rule->cr.match.mask);
6286                 if (vid_mask == VLAN_VID_MASK) {
6287                     if (ofproto->vlan_bitmap) {
6288                         uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
6289                         if (!bitmap_is_set(ofproto->vlan_bitmap, vid)) {
6290                             bitmap_set1(ofproto->vlan_bitmap, vid);
6291                             ofproto->vlans_changed = true;
6292                         }
6293                     } else {
6294                         ofproto->vlans_changed = true;
6295                     }
6296                 }
6297             } else {
6298                 oftable_remove_rule(rule);
6299                 ofproto_rule_unref(rule);
6300             }
6301             break;
6302
6303         case OFOPERATION_DELETE:
6304             ovs_assert(!op->error);
6305             ofproto_rule_unref(rule);
6306             op->rule = NULL;
6307             break;
6308
6309         case OFOPERATION_MODIFY:
6310         case OFOPERATION_REPLACE:
6311             if (!op->error) {
6312                 long long int now = time_msec();
6313
6314                 ovs_mutex_lock(&rule->mutex);
6315                 rule->modified = now;
6316                 if (op->type == OFOPERATION_REPLACE) {
6317                     rule->created = now;
6318                 }
6319                 ovs_mutex_unlock(&rule->mutex);
6320             } else {
6321                 ofproto_rule_change_cookie(ofproto, rule, op->flow_cookie);
6322                 ovs_mutex_lock(&rule->mutex);
6323                 rule->idle_timeout = op->idle_timeout;
6324                 rule->hard_timeout = op->hard_timeout;
6325                 ovs_mutex_unlock(&rule->mutex);
6326                 if (op->actions) {
6327                     const struct rule_actions *old_actions;
6328
6329                     ovs_mutex_lock(&rule->mutex);
6330                     old_actions = rule_get_actions(rule);
6331                     ovsrcu_set(&rule->actions, op->actions);
6332                     ovs_mutex_unlock(&rule->mutex);
6333
6334                     op->actions = NULL;
6335                     rule_actions_destroy(old_actions);
6336                 }
6337                 rule->flags = op->flags;
6338             }
6339             break;
6340
6341         default:
6342             OVS_NOT_REACHED();
6343         }
6344
6345         ofoperation_destroy(op);
6346     }
6347
6348     ofmonitor_flush(ofproto->connmgr);
6349
6350     if (!list_is_empty(&group->ofproto_node)) {
6351         ovs_assert(ofproto->n_pending > 0);
6352         ofproto->n_pending--;
6353         list_remove(&group->ofproto_node);
6354     }
6355     if (!list_is_empty(&group->ofconn_node)) {
6356         list_remove(&group->ofconn_node);
6357         if (error) {
6358             ofconn_send_error(group->ofconn, group->request, error);
6359         }
6360         connmgr_retry(ofproto->connmgr);
6361     }
6362     free(group->request);
6363     free(group);
6364 }
6365
6366 /* Initiates a new operation on 'rule', of the specified 'type', within
6367  * 'group'.  Prior to calling, 'rule' must not have any pending operation.
6368  *
6369  * For a 'type' of OFOPERATION_DELETE, 'reason' should specify the reason that
6370  * the flow is being deleted.  For other 'type's, 'reason' is ignored (use 0).
6371  *
6372  * Returns the newly created ofoperation (which is also available as
6373  * rule->pending). */
6374 static struct ofoperation *
6375 ofoperation_create(struct ofopgroup *group, struct rule *rule,
6376                    enum ofoperation_type type,
6377                    enum ofp_flow_removed_reason reason)
6378     OVS_REQUIRES(ofproto_mutex)
6379 {
6380     struct ofproto *ofproto = group->ofproto;
6381     struct ofoperation *op;
6382
6383     ovs_assert(!rule->pending);
6384
6385     op = rule->pending = xzalloc(sizeof *op);
6386     op->group = group;
6387     list_push_back(&group->ops, &op->group_node);
6388     op->rule = rule;
6389     op->type = type;
6390     op->reason = reason;
6391     op->flow_cookie = rule->flow_cookie;
6392     ovs_mutex_lock(&rule->mutex);
6393     op->idle_timeout = rule->idle_timeout;
6394     op->hard_timeout = rule->hard_timeout;
6395     ovs_mutex_unlock(&rule->mutex);
6396     op->flags = rule->flags;
6397
6398     group->n_running++;
6399
6400     if (type == OFOPERATION_DELETE) {
6401         hmap_insert(&ofproto->deletions, &op->hmap_node,
6402                     cls_rule_hash(&rule->cr, rule->table_id));
6403     }
6404
6405     return op;
6406 }
6407
6408 static void
6409 ofoperation_destroy(struct ofoperation *op)
6410     OVS_REQUIRES(ofproto_mutex)
6411 {
6412     struct ofopgroup *group = op->group;
6413
6414     if (op->rule) {
6415         op->rule->pending = NULL;
6416     }
6417     if (op->type == OFOPERATION_DELETE) {
6418         hmap_remove(&group->ofproto->deletions, &op->hmap_node);
6419     }
6420     list_remove(&op->group_node);
6421     rule_actions_destroy(op->actions);
6422     free(op);
6423 }
6424
6425 /* Indicates that 'op' completed with status 'error', which is either 0 to
6426  * indicate success or an OpenFlow error code on failure.
6427  *
6428  * If 'error' is 0, indicating success, the operation will be committed
6429  * permanently to the flow table.
6430  *
6431  * If 'error' is nonzero, then generally the operation will be rolled back:
6432  *
6433  *   - If 'op' is an "add flow" operation, ofproto removes the new rule or
6434  *     restores the original rule.  The caller must have uninitialized any
6435  *     derived state in the new rule, as in step 5 of in the "Life Cycle" in
6436  *     ofproto/ofproto-provider.h.  ofoperation_complete() performs steps 6 and
6437  *     and 7 for the new rule, calling its ->rule_dealloc() function.
6438  *
6439  *   - If 'op' is a "modify flow" operation, ofproto restores the original
6440  *     actions.
6441  *
6442  *   - 'op' must not be a "delete flow" operation.  Removing a rule is not
6443  *     allowed to fail.  It must always succeed.
6444  *
6445  * Please see the large comment in ofproto/ofproto-provider.h titled
6446  * "Asynchronous Operation Support" for more information. */
6447 void
6448 ofoperation_complete(struct ofoperation *op, enum ofperr error)
6449 {
6450     struct ofopgroup *group = op->group;
6451
6452     ovs_assert(group->n_running > 0);
6453     ovs_assert(!error || op->type != OFOPERATION_DELETE);
6454
6455     op->error = error;
6456     if (!--group->n_running && !list_is_empty(&group->ofproto_node)) {
6457         /* This function can be called from ->rule_construct(), in which case
6458          * ofproto_mutex is held, or it can be called from ->run(), in which
6459          * case ofproto_mutex is not held.  But only in the latter case can we
6460          * arrive here, so we can safely take ofproto_mutex now. */
6461         ovs_mutex_lock(&ofproto_mutex);
6462         ovs_assert(op->rule->pending == op);
6463         ofopgroup_complete(group);
6464         ovs_mutex_unlock(&ofproto_mutex);
6465     }
6466 }
6467 \f
6468 static uint64_t
6469 pick_datapath_id(const struct ofproto *ofproto)
6470 {
6471     const struct ofport *port;
6472
6473     port = ofproto_get_port(ofproto, OFPP_LOCAL);
6474     if (port) {
6475         uint8_t ea[ETH_ADDR_LEN];
6476         int error;
6477
6478         error = netdev_get_etheraddr(port->netdev, ea);
6479         if (!error) {
6480             return eth_addr_to_uint64(ea);
6481         }
6482         VLOG_WARN("%s: could not get MAC address for %s (%s)",
6483                   ofproto->name, netdev_get_name(port->netdev),
6484                   ovs_strerror(error));
6485     }
6486     return ofproto->fallback_dpid;
6487 }
6488
6489 static uint64_t
6490 pick_fallback_dpid(void)
6491 {
6492     uint8_t ea[ETH_ADDR_LEN];
6493     eth_addr_nicira_random(ea);
6494     return eth_addr_to_uint64(ea);
6495 }
6496 \f
6497 /* Table overflow policy. */
6498
6499 /* Chooses and updates 'rulep' with a rule to evict from 'table'.  Sets 'rulep'
6500  * to NULL if the table is not configured to evict rules or if the table
6501  * contains no evictable rules.  (Rules with a readlock on their evict rwlock,
6502  * or with no timeouts are not evictable.) */
6503 static bool
6504 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
6505     OVS_REQUIRES(ofproto_mutex)
6506 {
6507     struct eviction_group *evg;
6508
6509     *rulep = NULL;
6510     if (!table->eviction_fields) {
6511         return false;
6512     }
6513
6514     /* In the common case, the outer and inner loops here will each be entered
6515      * exactly once:
6516      *
6517      *   - The inner loop normally "return"s in its first iteration.  If the
6518      *     eviction group has any evictable rules, then it always returns in
6519      *     some iteration.
6520      *
6521      *   - The outer loop only iterates more than once if the largest eviction
6522      *     group has no evictable rules.
6523      *
6524      *   - The outer loop can exit only if table's 'max_flows' is all filled up
6525      *     by unevictable rules. */
6526     HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
6527         struct rule *rule;
6528
6529         HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
6530             *rulep = rule;
6531             return true;
6532         }
6533     }
6534
6535     return false;
6536 }
6537
6538 /* Searches 'ofproto' for tables that have more flows than their configured
6539  * maximum and that have flow eviction enabled, and evicts as many flows as
6540  * necessary and currently feasible from them.
6541  *
6542  * This triggers only when an OpenFlow table has N flows in it and then the
6543  * client configures a maximum number of flows less than N. */
6544 static void
6545 ofproto_evict(struct ofproto *ofproto)
6546 {
6547     struct oftable *table;
6548
6549     ovs_mutex_lock(&ofproto_mutex);
6550     OFPROTO_FOR_EACH_TABLE (table, ofproto) {
6551         evict_rules_from_table(ofproto, table, 0);
6552     }
6553     ovs_mutex_unlock(&ofproto_mutex);
6554 }
6555 \f
6556 /* Eviction groups. */
6557
6558 /* Returns the priority to use for an eviction_group that contains 'n_rules'
6559  * rules.  The priority contains low-order random bits to ensure that eviction
6560  * groups with the same number of rules are prioritized randomly. */
6561 static uint32_t
6562 eviction_group_priority(size_t n_rules)
6563 {
6564     uint16_t size = MIN(UINT16_MAX, n_rules);
6565     return (size << 16) | random_uint16();
6566 }
6567
6568 /* Updates 'evg', an eviction_group within 'table', following a change that
6569  * adds or removes rules in 'evg'. */
6570 static void
6571 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
6572     OVS_REQUIRES(ofproto_mutex)
6573 {
6574     heap_change(&table->eviction_groups_by_size, &evg->size_node,
6575                 eviction_group_priority(heap_count(&evg->rules)));
6576 }
6577
6578 /* Destroys 'evg', an eviction_group within 'table':
6579  *
6580  *   - Removes all the rules, if any, from 'evg'.  (It doesn't destroy the
6581  *     rules themselves, just removes them from the eviction group.)
6582  *
6583  *   - Removes 'evg' from 'table'.
6584  *
6585  *   - Frees 'evg'. */
6586 static void
6587 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
6588     OVS_REQUIRES(ofproto_mutex)
6589 {
6590     while (!heap_is_empty(&evg->rules)) {
6591         struct rule *rule;
6592
6593         rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
6594         rule->eviction_group = NULL;
6595     }
6596     hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
6597     heap_remove(&table->eviction_groups_by_size, &evg->size_node);
6598     heap_destroy(&evg->rules);
6599     free(evg);
6600 }
6601
6602 /* Removes 'rule' from its eviction group, if any. */
6603 static void
6604 eviction_group_remove_rule(struct rule *rule)
6605     OVS_REQUIRES(ofproto_mutex)
6606 {
6607     if (rule->eviction_group) {
6608         struct oftable *table = &rule->ofproto->tables[rule->table_id];
6609         struct eviction_group *evg = rule->eviction_group;
6610
6611         rule->eviction_group = NULL;
6612         heap_remove(&evg->rules, &rule->evg_node);
6613         if (heap_is_empty(&evg->rules)) {
6614             eviction_group_destroy(table, evg);
6615         } else {
6616             eviction_group_resized(table, evg);
6617         }
6618     }
6619 }
6620
6621 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
6622  * returns the hash value. */
6623 static uint32_t
6624 eviction_group_hash_rule(struct rule *rule)
6625     OVS_REQUIRES(ofproto_mutex)
6626 {
6627     struct oftable *table = &rule->ofproto->tables[rule->table_id];
6628     const struct mf_subfield *sf;
6629     struct flow flow;
6630     uint32_t hash;
6631
6632     hash = table->eviction_group_id_basis;
6633     miniflow_expand(&rule->cr.match.flow, &flow);
6634     for (sf = table->eviction_fields;
6635          sf < &table->eviction_fields[table->n_eviction_fields];
6636          sf++)
6637     {
6638         if (mf_are_prereqs_ok(sf->field, &flow)) {
6639             union mf_value value;
6640
6641             mf_get_value(sf->field, &flow, &value);
6642             if (sf->ofs) {
6643                 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
6644             }
6645             if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
6646                 unsigned int start = sf->ofs + sf->n_bits;
6647                 bitwise_zero(&value, sf->field->n_bytes, start,
6648                              sf->field->n_bytes * 8 - start);
6649             }
6650             hash = hash_bytes(&value, sf->field->n_bytes, hash);
6651         } else {
6652             hash = hash_int(hash, 0);
6653         }
6654     }
6655
6656     return hash;
6657 }
6658
6659 /* Returns an eviction group within 'table' with the given 'id', creating one
6660  * if necessary. */
6661 static struct eviction_group *
6662 eviction_group_find(struct oftable *table, uint32_t id)
6663     OVS_REQUIRES(ofproto_mutex)
6664 {
6665     struct eviction_group *evg;
6666
6667     HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
6668         return evg;
6669     }
6670
6671     evg = xmalloc(sizeof *evg);
6672     hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
6673     heap_insert(&table->eviction_groups_by_size, &evg->size_node,
6674                 eviction_group_priority(0));
6675     heap_init(&evg->rules);
6676
6677     return evg;
6678 }
6679
6680 /* Returns an eviction priority for 'rule'.  The return value should be
6681  * interpreted so that higher priorities make a rule more attractive candidates
6682  * for eviction.
6683  * Called only if have a timeout. */
6684 static uint32_t
6685 rule_eviction_priority(struct ofproto *ofproto, struct rule *rule)
6686     OVS_REQUIRES(ofproto_mutex)
6687 {
6688     long long int expiration = LLONG_MAX;
6689     long long int modified;
6690     uint32_t expiration_offset;
6691
6692     /* 'modified' needs protection even when we hold 'ofproto_mutex'. */
6693     ovs_mutex_lock(&rule->mutex);
6694     modified = rule->modified;
6695     ovs_mutex_unlock(&rule->mutex);
6696
6697     if (rule->hard_timeout) {
6698         expiration = modified + rule->hard_timeout * 1000;
6699     }
6700     if (rule->idle_timeout) {
6701         uint64_t packets, bytes;
6702         long long int used;
6703         long long int idle_expiration;
6704
6705         ofproto->ofproto_class->rule_get_stats(rule, &packets, &bytes, &used);
6706         idle_expiration = used + rule->idle_timeout * 1000;
6707         expiration = MIN(expiration, idle_expiration);
6708     }
6709
6710     if (expiration == LLONG_MAX) {
6711         return 0;
6712     }
6713
6714     /* Calculate the time of expiration as a number of (approximate) seconds
6715      * after program startup.
6716      *
6717      * This should work OK for program runs that last UINT32_MAX seconds or
6718      * less.  Therefore, please restart OVS at least once every 136 years. */
6719     expiration_offset = (expiration >> 10) - (time_boot_msec() >> 10);
6720
6721     /* Invert the expiration offset because we're using a max-heap. */
6722     return UINT32_MAX - expiration_offset;
6723 }
6724
6725 /* Adds 'rule' to an appropriate eviction group for its oftable's
6726  * configuration.  Does nothing if 'rule''s oftable doesn't have eviction
6727  * enabled, or if 'rule' is a permanent rule (one that will never expire on its
6728  * own).
6729  *
6730  * The caller must ensure that 'rule' is not already in an eviction group. */
6731 static void
6732 eviction_group_add_rule(struct rule *rule)
6733     OVS_REQUIRES(ofproto_mutex)
6734 {
6735     struct ofproto *ofproto = rule->ofproto;
6736     struct oftable *table = &ofproto->tables[rule->table_id];
6737     bool has_timeout;
6738
6739     /* Timeouts may be modified only when holding 'ofproto_mutex'.  We have it
6740      * so no additional protection is needed. */
6741     has_timeout = rule->hard_timeout || rule->idle_timeout;
6742
6743     if (table->eviction_fields && has_timeout) {
6744         struct eviction_group *evg;
6745
6746         evg = eviction_group_find(table, eviction_group_hash_rule(rule));
6747
6748         rule->eviction_group = evg;
6749         heap_insert(&evg->rules, &rule->evg_node,
6750                     rule_eviction_priority(ofproto, rule));
6751         eviction_group_resized(table, evg);
6752     }
6753 }
6754 \f
6755 /* oftables. */
6756
6757 /* Initializes 'table'. */
6758 static void
6759 oftable_init(struct oftable *table)
6760 {
6761     memset(table, 0, sizeof *table);
6762     classifier_init(&table->cls, flow_segment_u32s);
6763     table->max_flows = UINT_MAX;
6764     atomic_init(&table->config, (unsigned int)OFPROTO_TABLE_MISS_DEFAULT);
6765
6766     fat_rwlock_wrlock(&table->cls.rwlock);
6767     classifier_set_prefix_fields(&table->cls, default_prefix_fields,
6768                                  ARRAY_SIZE(default_prefix_fields));
6769     fat_rwlock_unlock(&table->cls.rwlock);
6770
6771     atomic_init(&table->n_matched, 0);
6772     atomic_init(&table->n_missed, 0);
6773 }
6774
6775 /* Destroys 'table', including its classifier and eviction groups.
6776  *
6777  * The caller is responsible for freeing 'table' itself. */
6778 static void
6779 oftable_destroy(struct oftable *table)
6780 {
6781     fat_rwlock_rdlock(&table->cls.rwlock);
6782     ovs_assert(classifier_is_empty(&table->cls));
6783     fat_rwlock_unlock(&table->cls.rwlock);
6784     oftable_disable_eviction(table);
6785     classifier_destroy(&table->cls);
6786     free(table->name);
6787 }
6788
6789 /* Changes the name of 'table' to 'name'.  If 'name' is NULL or the empty
6790  * string, then 'table' will use its default name.
6791  *
6792  * This only affects the name exposed for a table exposed through the OpenFlow
6793  * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
6794 static void
6795 oftable_set_name(struct oftable *table, const char *name)
6796 {
6797     if (name && name[0]) {
6798         int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
6799         if (!table->name || strncmp(name, table->name, len)) {
6800             free(table->name);
6801             table->name = xmemdup0(name, len);
6802         }
6803     } else {
6804         free(table->name);
6805         table->name = NULL;
6806     }
6807 }
6808
6809 /* oftables support a choice of two policies when adding a rule would cause the
6810  * number of flows in the table to exceed the configured maximum number: either
6811  * they can refuse to add the new flow or they can evict some existing flow.
6812  * This function configures the former policy on 'table'. */
6813 static void
6814 oftable_disable_eviction(struct oftable *table)
6815     OVS_REQUIRES(ofproto_mutex)
6816 {
6817     if (table->eviction_fields) {
6818         struct eviction_group *evg, *next;
6819
6820         HMAP_FOR_EACH_SAFE (evg, next, id_node,
6821                             &table->eviction_groups_by_id) {
6822             eviction_group_destroy(table, evg);
6823         }
6824         hmap_destroy(&table->eviction_groups_by_id);
6825         heap_destroy(&table->eviction_groups_by_size);
6826
6827         free(table->eviction_fields);
6828         table->eviction_fields = NULL;
6829         table->n_eviction_fields = 0;
6830     }
6831 }
6832
6833 /* oftables support a choice of two policies when adding a rule would cause the
6834  * number of flows in the table to exceed the configured maximum number: either
6835  * they can refuse to add the new flow or they can evict some existing flow.
6836  * This function configures the latter policy on 'table', with fairness based
6837  * on the values of the 'n_fields' fields specified in 'fields'.  (Specifying
6838  * 'n_fields' as 0 disables fairness.) */
6839 static void
6840 oftable_enable_eviction(struct oftable *table,
6841                         const struct mf_subfield *fields, size_t n_fields)
6842     OVS_REQUIRES(ofproto_mutex)
6843 {
6844     struct cls_cursor cursor;
6845     struct rule *rule;
6846
6847     if (table->eviction_fields
6848         && n_fields == table->n_eviction_fields
6849         && (!n_fields
6850             || !memcmp(fields, table->eviction_fields,
6851                        n_fields * sizeof *fields))) {
6852         /* No change. */
6853         return;
6854     }
6855
6856     oftable_disable_eviction(table);
6857
6858     table->n_eviction_fields = n_fields;
6859     table->eviction_fields = xmemdup(fields, n_fields * sizeof *fields);
6860
6861     table->eviction_group_id_basis = random_uint32();
6862     hmap_init(&table->eviction_groups_by_id);
6863     heap_init(&table->eviction_groups_by_size);
6864
6865     fat_rwlock_rdlock(&table->cls.rwlock);
6866     cls_cursor_init(&cursor, &table->cls, NULL);
6867     CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6868         eviction_group_add_rule(rule);
6869     }
6870     fat_rwlock_unlock(&table->cls.rwlock);
6871 }
6872
6873 /* Removes 'rule' from the oftable that contains it. */
6874 static void
6875 oftable_remove_rule__(struct ofproto *ofproto, struct rule *rule)
6876     OVS_REQUIRES(ofproto_mutex)
6877 {
6878     struct classifier *cls = &ofproto->tables[rule->table_id].cls;
6879
6880     fat_rwlock_wrlock(&cls->rwlock);
6881     classifier_remove(cls, CONST_CAST(struct cls_rule *, &rule->cr));
6882     fat_rwlock_unlock(&cls->rwlock);
6883
6884     cookies_remove(ofproto, rule);
6885
6886     eviction_group_remove_rule(rule);
6887     if (!list_is_empty(&rule->expirable)) {
6888         list_remove(&rule->expirable);
6889     }
6890     if (!list_is_empty(&rule->meter_list_node)) {
6891         list_remove(&rule->meter_list_node);
6892         list_init(&rule->meter_list_node);
6893     }
6894 }
6895
6896 static void
6897 oftable_remove_rule(struct rule *rule)
6898     OVS_REQUIRES(ofproto_mutex)
6899 {
6900     oftable_remove_rule__(rule->ofproto, rule);
6901 }
6902 \f
6903 /* unixctl commands. */
6904
6905 struct ofproto *
6906 ofproto_lookup(const char *name)
6907 {
6908     struct ofproto *ofproto;
6909
6910     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
6911                              &all_ofprotos) {
6912         if (!strcmp(ofproto->name, name)) {
6913             return ofproto;
6914         }
6915     }
6916     return NULL;
6917 }
6918
6919 static void
6920 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
6921                      const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
6922 {
6923     struct ofproto *ofproto;
6924     struct ds results;
6925
6926     ds_init(&results);
6927     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
6928         ds_put_format(&results, "%s\n", ofproto->name);
6929     }
6930     unixctl_command_reply(conn, ds_cstr(&results));
6931     ds_destroy(&results);
6932 }
6933
6934 static void
6935 ofproto_unixctl_init(void)
6936 {
6937     static bool registered;
6938     if (registered) {
6939         return;
6940     }
6941     registered = true;
6942
6943     unixctl_command_register("ofproto/list", "", 0, 0,
6944                              ofproto_unixctl_list, NULL);
6945 }
6946 \f
6947 /* Linux VLAN device support (e.g. "eth0.10" for VLAN 10.)
6948  *
6949  * This is deprecated.  It is only for compatibility with broken device drivers
6950  * in old versions of Linux that do not properly support VLANs when VLAN
6951  * devices are not used.  When broken device drivers are no longer in
6952  * widespread use, we will delete these interfaces. */
6953
6954 /* Sets a 1-bit in the 4096-bit 'vlan_bitmap' for each VLAN ID that is matched
6955  * (exactly) by an OpenFlow rule in 'ofproto'. */
6956 void
6957 ofproto_get_vlan_usage(struct ofproto *ofproto, unsigned long int *vlan_bitmap)
6958 {
6959     struct match match;
6960     struct cls_rule target;
6961     const struct oftable *oftable;
6962
6963     match_init_catchall(&match);
6964     match_set_vlan_vid_masked(&match, htons(VLAN_CFI), htons(VLAN_CFI));
6965     cls_rule_init(&target, &match, 0);
6966
6967     free(ofproto->vlan_bitmap);
6968     ofproto->vlan_bitmap = bitmap_allocate(4096);
6969     ofproto->vlans_changed = false;
6970
6971     OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
6972         struct cls_cursor cursor;
6973         struct rule *rule;
6974
6975         fat_rwlock_rdlock(&oftable->cls.rwlock);
6976         cls_cursor_init(&cursor, &oftable->cls, &target);
6977         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
6978             if (minimask_get_vid_mask(&rule->cr.match.mask) == VLAN_VID_MASK) {
6979                 uint16_t vid = miniflow_get_vid(&rule->cr.match.flow);
6980
6981                 bitmap_set1(vlan_bitmap, vid);
6982                 bitmap_set1(ofproto->vlan_bitmap, vid);
6983             }
6984         }
6985         fat_rwlock_unlock(&oftable->cls.rwlock);
6986     }
6987
6988     cls_rule_destroy(&target);
6989 }
6990
6991 /* Returns true if new VLANs have come into use by the flow table since the
6992  * last call to ofproto_get_vlan_usage().
6993  *
6994  * We don't track when old VLANs stop being used. */
6995 bool
6996 ofproto_has_vlan_usage_changed(const struct ofproto *ofproto)
6997 {
6998     return ofproto->vlans_changed;
6999 }
7000
7001 /* Configures a VLAN splinter binding between the ports identified by OpenFlow
7002  * port numbers 'vlandev_ofp_port' and 'realdev_ofp_port'.  If
7003  * 'realdev_ofp_port' is nonzero, then the VLAN device is enslaved to the real
7004  * device as a VLAN splinter for VLAN ID 'vid'.  If 'realdev_ofp_port' is zero,
7005  * then the VLAN device is un-enslaved. */
7006 int
7007 ofproto_port_set_realdev(struct ofproto *ofproto, ofp_port_t vlandev_ofp_port,
7008                          ofp_port_t realdev_ofp_port, int vid)
7009 {
7010     struct ofport *ofport;
7011     int error;
7012
7013     ovs_assert(vlandev_ofp_port != realdev_ofp_port);
7014
7015     ofport = ofproto_get_port(ofproto, vlandev_ofp_port);
7016     if (!ofport) {
7017         VLOG_WARN("%s: cannot set realdev on nonexistent port %"PRIu16,
7018                   ofproto->name, vlandev_ofp_port);
7019         return EINVAL;
7020     }
7021
7022     if (!ofproto->ofproto_class->set_realdev) {
7023         if (!vlandev_ofp_port) {
7024             return 0;
7025         }
7026         VLOG_WARN("%s: vlan splinters not supported", ofproto->name);
7027         return EOPNOTSUPP;
7028     }
7029
7030     error = ofproto->ofproto_class->set_realdev(ofport, realdev_ofp_port, vid);
7031     if (error) {
7032         VLOG_WARN("%s: setting realdev on port %"PRIu16" (%s) failed (%s)",
7033                   ofproto->name, vlandev_ofp_port,
7034                   netdev_get_name(ofport->netdev), ovs_strerror(error));
7035     }
7036     return error;
7037 }