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