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