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