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