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