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