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