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