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