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