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