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