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