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