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