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