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