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