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