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