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