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