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