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