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