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