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