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