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