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