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