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