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