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