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