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