]> git.proxmox.com Git - mirror_ovs.git/blob - ofproto/ofproto.c
dpif-netdev: Calculate rxq cycles prior to compare_rxq_cycles calls.
[mirror_ovs.git] / ofproto / ofproto.c
1 /*
2 * Copyright (c) 2009-2017 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 <errno.h>
20 #include <inttypes.h>
21 #include <stdbool.h>
22 #include <stdlib.h>
23 #include <unistd.h>
24
25 #include "bitmap.h"
26 #include "bundles.h"
27 #include "byte-order.h"
28 #include "classifier.h"
29 #include "connectivity.h"
30 #include "connmgr.h"
31 #include "coverage.h"
32 #include "dp-packet.h"
33 #include "hash.h"
34 #include "openvswitch/hmap.h"
35 #include "netdev.h"
36 #include "nx-match.h"
37 #include "ofproto.h"
38 #include "ofproto-provider.h"
39 #include "openflow/nicira-ext.h"
40 #include "openflow/openflow.h"
41 #include "openvswitch/dynamic-string.h"
42 #include "openvswitch/meta-flow.h"
43 #include "openvswitch/ofp-actions.h"
44 #include "openvswitch/ofp-errors.h"
45 #include "openvswitch/ofp-msgs.h"
46 #include "openvswitch/ofp-print.h"
47 #include "openvswitch/ofp-util.h"
48 #include "openvswitch/ofpbuf.h"
49 #include "openvswitch/vlog.h"
50 #include "ovs-rcu.h"
51 #include "packets.h"
52 #include "pinsched.h"
53 #include "openvswitch/poll-loop.h"
54 #include "random.h"
55 #include "seq.h"
56 #include "openvswitch/shash.h"
57 #include "simap.h"
58 #include "smap.h"
59 #include "sset.h"
60 #include "timeval.h"
61 #include "tun-metadata.h"
62 #include "unaligned.h"
63 #include "unixctl.h"
64 #include "util.h"
65
66 VLOG_DEFINE_THIS_MODULE(ofproto);
67
68 COVERAGE_DEFINE(ofproto_flush);
69 COVERAGE_DEFINE(ofproto_packet_out);
70 COVERAGE_DEFINE(ofproto_queue_req);
71 COVERAGE_DEFINE(ofproto_recv_openflow);
72 COVERAGE_DEFINE(ofproto_reinit_ports);
73 COVERAGE_DEFINE(ofproto_update_port);
74
75 /* Default fields to use for prefix tries in each flow table, unless something
76 * else is configured. */
77 const enum mf_field_id default_prefix_fields[2] =
78 { MFF_IPV4_DST, MFF_IPV4_SRC };
79
80 /* oftable. */
81 static void oftable_init(struct oftable *);
82 static void oftable_destroy(struct oftable *);
83
84 static void oftable_set_name(struct oftable *, const char *name);
85
86 static enum ofperr evict_rules_from_table(struct oftable *)
87 OVS_REQUIRES(ofproto_mutex);
88 static void oftable_configure_eviction(struct oftable *,
89 unsigned int eviction,
90 const struct mf_subfield *fields,
91 size_t n_fields)
92 OVS_REQUIRES(ofproto_mutex);
93
94 /* This is the only combination of OpenFlow eviction flags that OVS supports: a
95 * combination of OF1.4+ importance, the remaining lifetime of the flow, and
96 * fairness based on user-specified fields. */
97 #define OFPROTO_EVICTION_FLAGS \
98 (OFPTMPEF14_OTHER | OFPTMPEF14_IMPORTANCE | OFPTMPEF14_LIFETIME)
99
100 /* A set of rules within a single OpenFlow table (oftable) that have the same
101 * values for the oftable's eviction_fields. A rule to be evicted, when one is
102 * needed, is taken from the eviction group that contains the greatest number
103 * of rules.
104 *
105 * An oftable owns any number of eviction groups, each of which contains any
106 * number of rules.
107 *
108 * Membership in an eviction group is imprecise, based on the hash of the
109 * oftable's eviction_fields (in the eviction_group's id_node.hash member).
110 * That is, if two rules have different eviction_fields, but those
111 * eviction_fields hash to the same value, then they will belong to the same
112 * eviction_group anyway.
113 *
114 * (When eviction is not enabled on an oftable, we don't track any eviction
115 * groups, to save time and space.) */
116 struct eviction_group {
117 struct hmap_node id_node; /* In oftable's "eviction_groups_by_id". */
118 struct heap_node size_node; /* In oftable's "eviction_groups_by_size". */
119 struct heap rules; /* Contains "struct rule"s. */
120 };
121
122 static bool choose_rule_to_evict(struct oftable *table, struct rule **rulep)
123 OVS_REQUIRES(ofproto_mutex);
124 static uint64_t rule_eviction_priority(struct ofproto *ofproto, struct rule *)
125 OVS_REQUIRES(ofproto_mutex);
126 static void eviction_group_add_rule(struct rule *)
127 OVS_REQUIRES(ofproto_mutex);
128 static void eviction_group_remove_rule(struct rule *)
129 OVS_REQUIRES(ofproto_mutex);
130
131 static void rule_criteria_init(struct rule_criteria *, uint8_t table_id,
132 const struct match *match, int priority,
133 ovs_version_t version,
134 ovs_be64 cookie, ovs_be64 cookie_mask,
135 ofp_port_t out_port, uint32_t out_group);
136 static void rule_criteria_require_rw(struct rule_criteria *,
137 bool can_write_readonly);
138 static void rule_criteria_destroy(struct rule_criteria *);
139
140 static enum ofperr collect_rules_loose(struct ofproto *,
141 const struct rule_criteria *,
142 struct rule_collection *);
143
144 struct learned_cookie {
145 union {
146 /* In struct ofproto's 'learned_cookies' hmap. */
147 struct hmap_node hmap_node OVS_GUARDED_BY(ofproto_mutex);
148
149 /* In 'dead_cookies' list when removed from hmap. */
150 struct ovs_list list_node;
151 } u;
152
153 /* Key. */
154 ovs_be64 cookie OVS_GUARDED_BY(ofproto_mutex);
155 uint8_t table_id OVS_GUARDED_BY(ofproto_mutex);
156
157 /* Number of references from "learn" actions.
158 *
159 * When this drops to 0, all of the flows in 'table_id' with the specified
160 * 'cookie' are deleted. */
161 int n OVS_GUARDED_BY(ofproto_mutex);
162 };
163
164 static const struct ofpact_learn *next_learn_with_delete(
165 const struct rule_actions *, const struct ofpact_learn *start);
166
167 static void learned_cookies_inc(struct ofproto *, const struct rule_actions *)
168 OVS_REQUIRES(ofproto_mutex);
169 static void learned_cookies_dec(struct ofproto *, const struct rule_actions *,
170 struct ovs_list *dead_cookies)
171 OVS_REQUIRES(ofproto_mutex);
172 static void learned_cookies_flush(struct ofproto *, struct ovs_list *dead_cookies)
173 OVS_REQUIRES(ofproto_mutex);
174
175 /* ofport. */
176 static void ofport_destroy__(struct ofport *) OVS_EXCLUDED(ofproto_mutex);
177 static void ofport_destroy(struct ofport *, bool del);
178 static bool ofport_is_mtu_overridden(const struct ofproto *,
179 const struct ofport *);
180
181 static int update_port(struct ofproto *, const char *devname);
182 static int init_ports(struct ofproto *);
183 static void reinit_ports(struct ofproto *);
184
185 static long long int ofport_get_usage(const struct ofproto *,
186 ofp_port_t ofp_port);
187 static void ofport_set_usage(struct ofproto *, ofp_port_t ofp_port,
188 long long int last_used);
189 static void ofport_remove_usage(struct ofproto *, ofp_port_t ofp_port);
190
191 /* Ofport usage.
192 *
193 * Keeps track of the currently used and recently used ofport values and is
194 * used to prevent immediate recycling of ofport values. */
195 struct ofport_usage {
196 struct hmap_node hmap_node; /* In struct ofproto's "ofport_usage" hmap. */
197 ofp_port_t ofp_port; /* OpenFlow port number. */
198 long long int last_used; /* Last time the 'ofp_port' was used. LLONG_MAX
199 represents in-use ofports. */
200 };
201
202 /* rule. */
203 static void ofproto_rule_send_removed(struct rule *)
204 OVS_EXCLUDED(ofproto_mutex);
205 static bool rule_is_readonly(const struct rule *);
206 static void ofproto_rule_insert__(struct ofproto *, struct rule *)
207 OVS_REQUIRES(ofproto_mutex);
208 static void ofproto_rule_remove__(struct ofproto *, struct rule *)
209 OVS_REQUIRES(ofproto_mutex);
210
211 /* The source of an OpenFlow request.
212 *
213 * A table modification request can be generated externally, via OpenFlow, or
214 * internally through a function call. This structure indicates the source of
215 * an OpenFlow-generated table modification. For an internal flow_mod, it
216 * isn't meaningful and thus supplied as NULL. */
217 struct openflow_mod_requester {
218 struct ofconn *ofconn; /* Connection on which flow_mod arrived. */
219 const struct ofp_header *request;
220 };
221
222 /* OpenFlow. */
223 static enum ofperr ofproto_rule_create(struct ofproto *, struct cls_rule *,
224 uint8_t table_id, ovs_be64 new_cookie,
225 uint16_t idle_timeout,
226 uint16_t hard_timeout,
227 enum ofputil_flow_mod_flags flags,
228 uint16_t importance,
229 const struct ofpact *ofpacts,
230 size_t ofpacts_len,
231 uint64_t match_tlv_bitmap,
232 uint64_t ofpacts_tlv_bitmap,
233 struct rule **new_rule)
234 OVS_NO_THREAD_SAFETY_ANALYSIS;
235
236 static void replace_rule_start(struct ofproto *, struct ofproto_flow_mod *,
237 struct rule *old_rule, struct rule *new_rule)
238 OVS_REQUIRES(ofproto_mutex);
239
240 static void replace_rule_revert(struct ofproto *, struct rule *old_rule,
241 struct rule *new_rule)
242 OVS_REQUIRES(ofproto_mutex);
243
244 static void replace_rule_finish(struct ofproto *, struct ofproto_flow_mod *,
245 const struct openflow_mod_requester *,
246 struct rule *old_rule, struct rule *new_rule,
247 struct ovs_list *dead_cookies)
248 OVS_REQUIRES(ofproto_mutex);
249 static void delete_flows__(struct rule_collection *,
250 enum ofp_flow_removed_reason,
251 const struct openflow_mod_requester *)
252 OVS_REQUIRES(ofproto_mutex);
253
254 static bool ofproto_group_exists(const struct ofproto *, uint32_t group_id);
255 static void handle_openflow(struct ofconn *, const struct ofpbuf *);
256 static enum ofperr ofproto_flow_mod_init(struct ofproto *,
257 struct ofproto_flow_mod *,
258 const struct ofputil_flow_mod *fm,
259 struct rule *)
260 OVS_EXCLUDED(ofproto_mutex);
261 static enum ofperr ofproto_flow_mod_start(struct ofproto *,
262 struct ofproto_flow_mod *)
263 OVS_REQUIRES(ofproto_mutex);
264 static void ofproto_flow_mod_revert(struct ofproto *,
265 struct ofproto_flow_mod *)
266 OVS_REQUIRES(ofproto_mutex);
267 static void ofproto_flow_mod_finish(struct ofproto *,
268 struct ofproto_flow_mod *,
269 const struct openflow_mod_requester *)
270 OVS_REQUIRES(ofproto_mutex);
271 static enum ofperr handle_flow_mod__(struct ofproto *,
272 const struct ofputil_flow_mod *,
273 const struct openflow_mod_requester *)
274 OVS_EXCLUDED(ofproto_mutex);
275 static void calc_duration(long long int start, long long int now,
276 uint32_t *sec, uint32_t *nsec);
277
278 /* ofproto. */
279 static uint64_t pick_datapath_id(const struct ofproto *);
280 static uint64_t pick_fallback_dpid(void);
281 static void ofproto_destroy__(struct ofproto *);
282 static void update_mtu(struct ofproto *, struct ofport *);
283 static void update_mtu_ofproto(struct ofproto *);
284 static void meter_delete(struct ofproto *, uint32_t);
285 static void meter_delete_all(struct ofproto *);
286 static void meter_insert_rule(struct rule *);
287
288 /* unixctl. */
289 static void ofproto_unixctl_init(void);
290
291 /* All registered ofproto classes, in probe order. */
292 static const struct ofproto_class **ofproto_classes;
293 static size_t n_ofproto_classes;
294 static size_t allocated_ofproto_classes;
295
296 /* Global lock that protects all flow table operations. */
297 struct ovs_mutex ofproto_mutex = OVS_MUTEX_INITIALIZER;
298
299 unsigned ofproto_flow_limit = OFPROTO_FLOW_LIMIT_DEFAULT;
300 unsigned ofproto_max_idle = OFPROTO_MAX_IDLE_DEFAULT;
301
302 size_t n_handlers, n_revalidators;
303
304 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
305 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
306
307 /* Initial mappings of port to OpenFlow number mappings. */
308 static struct shash init_ofp_ports = SHASH_INITIALIZER(&init_ofp_ports);
309
310 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
311
312 /* The default value of true waits for flow restore. */
313 static bool flow_restore_wait = true;
314
315 /* Must be called to initialize the ofproto library.
316 *
317 * The caller may pass in 'iface_hints', which contains an shash of
318 * "iface_hint" elements indexed by the interface's name. The provider
319 * may use these hints to describe the startup configuration in order to
320 * reinitialize its state. The caller owns the provided data, so a
321 * provider will make copies of anything required. An ofproto provider
322 * will remove any existing state that is not described by the hint, and
323 * may choose to remove it all. */
324 void
325 ofproto_init(const struct shash *iface_hints)
326 {
327 struct shash_node *node;
328 size_t i;
329
330 ofproto_class_register(&ofproto_dpif_class);
331
332 /* Make a local copy, since we don't own 'iface_hints' elements. */
333 SHASH_FOR_EACH(node, iface_hints) {
334 const struct iface_hint *orig_hint = node->data;
335 struct iface_hint *new_hint = xmalloc(sizeof *new_hint);
336 const char *br_type = ofproto_normalize_type(orig_hint->br_type);
337
338 new_hint->br_name = xstrdup(orig_hint->br_name);
339 new_hint->br_type = xstrdup(br_type);
340 new_hint->ofp_port = orig_hint->ofp_port;
341
342 shash_add(&init_ofp_ports, node->name, new_hint);
343 }
344
345 for (i = 0; i < n_ofproto_classes; i++) {
346 ofproto_classes[i]->init(&init_ofp_ports);
347 }
348
349 ofproto_unixctl_init();
350 }
351
352 /* 'type' should be a normalized datapath type, as returned by
353 * ofproto_normalize_type(). Returns the corresponding ofproto_class
354 * structure, or a null pointer if there is none registered for 'type'. */
355 static const struct ofproto_class *
356 ofproto_class_find__(const char *type)
357 {
358 size_t i;
359
360 for (i = 0; i < n_ofproto_classes; i++) {
361 const struct ofproto_class *class = ofproto_classes[i];
362 struct sset types;
363 bool found;
364
365 sset_init(&types);
366 class->enumerate_types(&types);
367 found = sset_contains(&types, type);
368 sset_destroy(&types);
369
370 if (found) {
371 return class;
372 }
373 }
374 VLOG_WARN("unknown datapath type %s", type);
375 return NULL;
376 }
377
378 /* Registers a new ofproto class. After successful registration, new ofprotos
379 * of that type can be created using ofproto_create(). */
380 int
381 ofproto_class_register(const struct ofproto_class *new_class)
382 {
383 size_t i;
384
385 for (i = 0; i < n_ofproto_classes; i++) {
386 if (ofproto_classes[i] == new_class) {
387 return EEXIST;
388 }
389 }
390
391 if (n_ofproto_classes >= allocated_ofproto_classes) {
392 ofproto_classes = x2nrealloc(ofproto_classes,
393 &allocated_ofproto_classes,
394 sizeof *ofproto_classes);
395 }
396 ofproto_classes[n_ofproto_classes++] = new_class;
397 return 0;
398 }
399
400 /* Unregisters a datapath provider. 'type' must have been previously
401 * registered and not currently be in use by any ofprotos. After
402 * unregistration new datapaths of that type cannot be opened using
403 * ofproto_create(). */
404 int
405 ofproto_class_unregister(const struct ofproto_class *class)
406 {
407 size_t i;
408
409 for (i = 0; i < n_ofproto_classes; i++) {
410 if (ofproto_classes[i] == class) {
411 for (i++; i < n_ofproto_classes; i++) {
412 ofproto_classes[i - 1] = ofproto_classes[i];
413 }
414 n_ofproto_classes--;
415 return 0;
416 }
417 }
418 VLOG_WARN("attempted to unregister an ofproto class that is not "
419 "registered");
420 return EAFNOSUPPORT;
421 }
422
423 /* Clears 'types' and enumerates all registered ofproto types into it. The
424 * caller must first initialize the sset. */
425 void
426 ofproto_enumerate_types(struct sset *types)
427 {
428 size_t i;
429
430 sset_clear(types);
431 for (i = 0; i < n_ofproto_classes; i++) {
432 ofproto_classes[i]->enumerate_types(types);
433 }
434 }
435
436 /* Returns the fully spelled out name for the given ofproto 'type'.
437 *
438 * Normalized type string can be compared with strcmp(). Unnormalized type
439 * string might be the same even if they have different spellings. */
440 const char *
441 ofproto_normalize_type(const char *type)
442 {
443 return type && type[0] ? type : "system";
444 }
445
446 /* Clears 'names' and enumerates the names of all known created ofprotos with
447 * the given 'type'. The caller must first initialize the sset. Returns 0 if
448 * successful, otherwise a positive errno value.
449 *
450 * Some kinds of datapaths might not be practically enumerable. This is not
451 * considered an error. */
452 int
453 ofproto_enumerate_names(const char *type, struct sset *names)
454 {
455 const struct ofproto_class *class = ofproto_class_find__(type);
456 return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
457 }
458
459 static void
460 ofproto_bump_tables_version(struct ofproto *ofproto)
461 {
462 ++ofproto->tables_version;
463 ofproto->ofproto_class->set_tables_version(ofproto,
464 ofproto->tables_version);
465 }
466
467 int
468 ofproto_create(const char *datapath_name, const char *datapath_type,
469 struct ofproto **ofprotop)
470 OVS_EXCLUDED(ofproto_mutex)
471 {
472 const struct ofproto_class *class;
473 struct ofproto *ofproto;
474 int error;
475 int i;
476
477 *ofprotop = NULL;
478
479 datapath_type = ofproto_normalize_type(datapath_type);
480 class = ofproto_class_find__(datapath_type);
481 if (!class) {
482 VLOG_WARN("could not create datapath %s of unknown type %s",
483 datapath_name, datapath_type);
484 return EAFNOSUPPORT;
485 }
486
487 ofproto = class->alloc();
488 if (!ofproto) {
489 VLOG_ERR("failed to allocate datapath %s of type %s",
490 datapath_name, datapath_type);
491 return ENOMEM;
492 }
493
494 /* Initialize. */
495 ovs_mutex_lock(&ofproto_mutex);
496 memset(ofproto, 0, sizeof *ofproto);
497 ofproto->ofproto_class = class;
498 ofproto->name = xstrdup(datapath_name);
499 ofproto->type = xstrdup(datapath_type);
500 hmap_insert(&all_ofprotos, &ofproto->hmap_node,
501 hash_string(ofproto->name, 0));
502 ofproto->datapath_id = 0;
503 ofproto->forward_bpdu = false;
504 ofproto->fallback_dpid = pick_fallback_dpid();
505 ofproto->mfr_desc = NULL;
506 ofproto->hw_desc = NULL;
507 ofproto->sw_desc = NULL;
508 ofproto->serial_desc = NULL;
509 ofproto->dp_desc = NULL;
510 ofproto->frag_handling = OFPUTIL_FRAG_NORMAL;
511 hmap_init(&ofproto->ports);
512 hmap_init(&ofproto->ofport_usage);
513 shash_init(&ofproto->port_by_name);
514 simap_init(&ofproto->ofp_requests);
515 ofproto->max_ports = ofp_to_u16(OFPP_MAX);
516 ofproto->eviction_group_timer = LLONG_MIN;
517 ofproto->tables = NULL;
518 ofproto->n_tables = 0;
519 ofproto->tables_version = OVS_VERSION_MIN;
520 hindex_init(&ofproto->cookies);
521 hmap_init(&ofproto->learned_cookies);
522 ovs_list_init(&ofproto->expirable);
523 ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
524 ofproto->min_mtu = INT_MAX;
525 cmap_init(&ofproto->groups);
526 ovs_mutex_unlock(&ofproto_mutex);
527 ofproto->ogf.types = 0xf;
528 ofproto->ogf.capabilities = OFPGFC_CHAINING | OFPGFC_SELECT_LIVENESS |
529 OFPGFC_SELECT_WEIGHT;
530 for (i = 0; i < 4; i++) {
531 ofproto->ogf.max_groups[i] = OFPG_MAX;
532 ofproto->ogf.ofpacts[i] = (UINT64_C(1) << N_OFPACTS) - 1;
533 }
534 ovsrcu_set(&ofproto->metadata_tab, tun_metadata_alloc(NULL));
535
536 ovs_mutex_init(&ofproto->vl_mff_map.mutex);
537 cmap_init(&ofproto->vl_mff_map.cmap);
538
539 error = ofproto->ofproto_class->construct(ofproto);
540 if (error) {
541 VLOG_ERR("failed to open datapath %s: %s",
542 datapath_name, ovs_strerror(error));
543 ovs_mutex_lock(&ofproto_mutex);
544 connmgr_destroy(ofproto->connmgr);
545 ofproto->connmgr = NULL;
546 ovs_mutex_unlock(&ofproto_mutex);
547 ofproto_destroy__(ofproto);
548 return error;
549 }
550
551 /* Check that hidden tables, if any, are at the end. */
552 ovs_assert(ofproto->n_tables);
553 for (i = 0; i + 1 < ofproto->n_tables; i++) {
554 enum oftable_flags flags = ofproto->tables[i].flags;
555 enum oftable_flags next_flags = ofproto->tables[i + 1].flags;
556
557 ovs_assert(!(flags & OFTABLE_HIDDEN) || next_flags & OFTABLE_HIDDEN);
558 }
559
560 ofproto->datapath_id = pick_datapath_id(ofproto);
561 init_ports(ofproto);
562
563 /* Initialize meters table. */
564 if (ofproto->ofproto_class->meter_get_features) {
565 ofproto->ofproto_class->meter_get_features(ofproto,
566 &ofproto->meter_features);
567 } else {
568 memset(&ofproto->meter_features, 0, sizeof ofproto->meter_features);
569 }
570 hmap_init(&ofproto->meters);
571 ofproto->slowpath_meter_id = UINT32_MAX;
572 ofproto->controller_meter_id = UINT32_MAX;
573
574 /* Set the initial tables version. */
575 ofproto_bump_tables_version(ofproto);
576
577 *ofprotop = ofproto;
578 return 0;
579 }
580
581 /* Must be called (only) by an ofproto implementation in its constructor
582 * function. See the large comment on 'construct' in struct ofproto_class for
583 * details. */
584 void
585 ofproto_init_tables(struct ofproto *ofproto, int n_tables)
586 {
587 struct oftable *table;
588
589 ovs_assert(!ofproto->n_tables);
590 ovs_assert(n_tables >= 1 && n_tables <= 255);
591
592 ofproto->n_tables = n_tables;
593 ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
594 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
595 oftable_init(table);
596 }
597 }
598
599 /* To be optionally called (only) by an ofproto implementation in its
600 * constructor function. See the large comment on 'construct' in struct
601 * ofproto_class for details.
602 *
603 * Sets the maximum number of ports to 'max_ports'. The ofproto generic layer
604 * will then ensure that actions passed into the ofproto implementation will
605 * not refer to OpenFlow ports numbered 'max_ports' or higher. If this
606 * function is not called, there will be no such restriction.
607 *
608 * Reserved ports numbered OFPP_MAX and higher are special and not subject to
609 * the 'max_ports' restriction. */
610 void
611 ofproto_init_max_ports(struct ofproto *ofproto, uint16_t max_ports)
612 {
613 ovs_assert(max_ports <= ofp_to_u16(OFPP_MAX));
614 ofproto->max_ports = max_ports;
615 }
616
617 uint64_t
618 ofproto_get_datapath_id(const struct ofproto *ofproto)
619 {
620 return ofproto->datapath_id;
621 }
622
623 void
624 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
625 {
626 uint64_t old_dpid = p->datapath_id;
627 p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
628 if (p->datapath_id != old_dpid) {
629 /* Force all active connections to reconnect, since there is no way to
630 * notify a controller that the datapath ID has changed. */
631 ofproto_reconnect_controllers(p);
632 }
633 }
634
635 void
636 ofproto_set_controllers(struct ofproto *p,
637 const struct ofproto_controller *controllers,
638 size_t n_controllers, uint32_t allowed_versions)
639 {
640 connmgr_set_controllers(p->connmgr, controllers, n_controllers,
641 allowed_versions);
642 }
643
644 void
645 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
646 {
647 connmgr_set_fail_mode(p->connmgr, fail_mode);
648 }
649
650 /* Drops the connections between 'ofproto' and all of its controllers, forcing
651 * them to reconnect. */
652 void
653 ofproto_reconnect_controllers(struct ofproto *ofproto)
654 {
655 connmgr_reconnect(ofproto->connmgr);
656 }
657
658 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
659 * in-band control should guarantee access, in the same way that in-band
660 * control guarantees access to OpenFlow controllers. */
661 void
662 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
663 const struct sockaddr_in *extras, size_t n)
664 {
665 connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
666 }
667
668 /* Sets the OpenFlow queue used by flows set up by in-band control on
669 * 'ofproto' to 'queue_id'. If 'queue_id' is negative, then in-band control
670 * flows will use the default queue. */
671 void
672 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
673 {
674 connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
675 }
676
677 /* Sets the number of flows at which eviction from the kernel flow table
678 * will occur. */
679 void
680 ofproto_set_flow_limit(unsigned limit)
681 {
682 ofproto_flow_limit = limit;
683 }
684
685 /* Sets the maximum idle time for flows in the datapath before they are
686 * expired. */
687 void
688 ofproto_set_max_idle(unsigned max_idle)
689 {
690 ofproto_max_idle = max_idle;
691 }
692
693 /* If forward_bpdu is true, the NORMAL action will forward frames with
694 * reserved (e.g. STP) destination Ethernet addresses. if forward_bpdu is false,
695 * the NORMAL action will drop these frames. */
696 void
697 ofproto_set_forward_bpdu(struct ofproto *ofproto, bool forward_bpdu)
698 {
699 bool old_val = ofproto->forward_bpdu;
700 ofproto->forward_bpdu = forward_bpdu;
701 if (old_val != ofproto->forward_bpdu) {
702 if (ofproto->ofproto_class->forward_bpdu_changed) {
703 ofproto->ofproto_class->forward_bpdu_changed(ofproto);
704 }
705 }
706 }
707
708 /* Sets the MAC aging timeout for the OFPP_NORMAL action on 'ofproto' to
709 * 'idle_time', in seconds, and the maximum number of MAC table entries to
710 * 'max_entries'. */
711 void
712 ofproto_set_mac_table_config(struct ofproto *ofproto, unsigned idle_time,
713 size_t max_entries)
714 {
715 if (ofproto->ofproto_class->set_mac_table_config) {
716 ofproto->ofproto_class->set_mac_table_config(ofproto, idle_time,
717 max_entries);
718 }
719 }
720
721 /* Multicast snooping configuration. */
722
723 /* Configures multicast snooping on 'ofproto' using the settings
724 * defined in 's'. If 's' is NULL, disables multicast snooping.
725 *
726 * Returns 0 if successful, otherwise a positive errno value. */
727 int
728 ofproto_set_mcast_snooping(struct ofproto *ofproto,
729 const struct ofproto_mcast_snooping_settings *s)
730 {
731 return (ofproto->ofproto_class->set_mcast_snooping
732 ? ofproto->ofproto_class->set_mcast_snooping(ofproto, s)
733 : EOPNOTSUPP);
734 }
735
736 /* Configures multicast snooping flood settings on 'ofp_port' of 'ofproto'.
737 *
738 * Returns 0 if successful, otherwise a positive errno value.*/
739 int
740 ofproto_port_set_mcast_snooping(struct ofproto *ofproto, void *aux,
741 const struct ofproto_mcast_snooping_port_settings *s)
742 {
743 return (ofproto->ofproto_class->set_mcast_snooping_port
744 ? ofproto->ofproto_class->set_mcast_snooping_port(ofproto, aux, s)
745 : EOPNOTSUPP);
746 }
747
748 void
749 ofproto_type_set_config(const char *datapath_type, const struct smap *cfg)
750 {
751 const struct ofproto_class *class;
752
753 datapath_type = ofproto_normalize_type(datapath_type);
754 class = ofproto_class_find__(datapath_type);
755
756 if (class->type_set_config) {
757 class->type_set_config(datapath_type, cfg);
758 }
759 }
760
761 void
762 ofproto_set_threads(int n_handlers_, int n_revalidators_)
763 {
764 int threads = MAX(count_cpu_cores(), 2);
765
766 n_revalidators = MAX(n_revalidators_, 0);
767 n_handlers = MAX(n_handlers_, 0);
768
769 if (!n_revalidators) {
770 n_revalidators = n_handlers
771 ? MAX(threads - (int) n_handlers, 1)
772 : threads / 4 + 1;
773 }
774
775 if (!n_handlers) {
776 n_handlers = MAX(threads - (int) n_revalidators, 1);
777 }
778 }
779
780 void
781 ofproto_set_dp_desc(struct ofproto *p, const char *dp_desc)
782 {
783 free(p->dp_desc);
784 p->dp_desc = nullable_xstrdup(dp_desc);
785 }
786
787 int
788 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
789 {
790 return connmgr_set_snoops(ofproto->connmgr, snoops);
791 }
792
793 int
794 ofproto_set_netflow(struct ofproto *ofproto,
795 const struct netflow_options *nf_options)
796 {
797 if (nf_options && sset_is_empty(&nf_options->collectors)) {
798 nf_options = NULL;
799 }
800
801 if (ofproto->ofproto_class->set_netflow) {
802 return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
803 } else {
804 return nf_options ? EOPNOTSUPP : 0;
805 }
806 }
807
808 int
809 ofproto_set_sflow(struct ofproto *ofproto,
810 const struct ofproto_sflow_options *oso)
811 {
812 if (oso && sset_is_empty(&oso->targets)) {
813 oso = NULL;
814 }
815
816 if (ofproto->ofproto_class->set_sflow) {
817 return ofproto->ofproto_class->set_sflow(ofproto, oso);
818 } else {
819 return oso ? EOPNOTSUPP : 0;
820 }
821 }
822
823 int
824 ofproto_set_ipfix(struct ofproto *ofproto,
825 const struct ofproto_ipfix_bridge_exporter_options *bo,
826 const struct ofproto_ipfix_flow_exporter_options *fo,
827 size_t n_fo)
828 {
829 if (ofproto->ofproto_class->set_ipfix) {
830 return ofproto->ofproto_class->set_ipfix(ofproto, bo, fo, n_fo);
831 } else {
832 return (bo || fo) ? EOPNOTSUPP : 0;
833 }
834 }
835
836 static int
837 ofproto_get_ipfix_stats(struct ofproto *ofproto,
838 bool bridge_ipfix,
839 struct ovs_list *replies)
840 {
841 int error;
842
843 if (ofproto->ofproto_class->get_ipfix_stats) {
844 error = ofproto->ofproto_class->get_ipfix_stats(ofproto,
845 bridge_ipfix,
846 replies);
847 } else {
848 error = EOPNOTSUPP;
849 }
850
851 return error;
852 }
853
854 static enum ofperr
855 handle_ipfix_bridge_stats_request(struct ofconn *ofconn,
856 const struct ofp_header *request)
857 {
858 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
859 struct ovs_list replies;
860 enum ofperr error;
861
862 ofpmp_init(&replies, request);
863 error = ofproto_get_ipfix_stats(ofproto, true, &replies);
864
865 if (!error) {
866 ofconn_send_replies(ofconn, &replies);
867 } else {
868 ofpbuf_list_delete(&replies);
869 }
870
871 return error;
872 }
873
874 static enum ofperr
875 handle_ipfix_flow_stats_request(struct ofconn *ofconn,
876 const struct ofp_header *request)
877 {
878 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
879 struct ovs_list replies;
880 enum ofperr error;
881
882 ofpmp_init(&replies, request);
883 error = ofproto_get_ipfix_stats(ofproto, false, &replies);
884
885 if (!error) {
886 ofconn_send_replies(ofconn, &replies);
887 } else {
888 ofpbuf_list_delete(&replies);
889 }
890
891 return error;
892 }
893
894 static enum ofperr
895 handle_nxt_ct_flush_zone(struct ofconn *ofconn, const struct ofp_header *oh)
896 {
897 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
898 const struct nx_zone_id *nzi = ofpmsg_body(oh);
899
900 if (!is_all_zeros(nzi->zero, sizeof nzi->zero)) {
901 return OFPERR_NXBRC_MUST_BE_ZERO;
902 }
903
904 uint16_t zone = ntohs(nzi->zone_id);
905 if (ofproto->ofproto_class->ct_flush) {
906 ofproto->ofproto_class->ct_flush(ofproto, &zone);
907 } else {
908 return EOPNOTSUPP;
909 }
910
911 return 0;
912 }
913
914 void
915 ofproto_set_flow_restore_wait(bool flow_restore_wait_db)
916 {
917 flow_restore_wait = flow_restore_wait_db;
918 }
919
920 bool
921 ofproto_get_flow_restore_wait(void)
922 {
923 return flow_restore_wait;
924 }
925
926 \f
927 /* Spanning Tree Protocol (STP) configuration. */
928
929 /* Configures STP on 'ofproto' using the settings defined in 's'. If
930 * 's' is NULL, disables STP.
931 *
932 * Returns 0 if successful, otherwise a positive errno value. */
933 int
934 ofproto_set_stp(struct ofproto *ofproto,
935 const struct ofproto_stp_settings *s)
936 {
937 return (ofproto->ofproto_class->set_stp
938 ? ofproto->ofproto_class->set_stp(ofproto, s)
939 : EOPNOTSUPP);
940 }
941
942 /* Retrieves STP status of 'ofproto' and stores it in 's'. If the
943 * 'enabled' member of 's' is false, then the other members are not
944 * meaningful.
945 *
946 * Returns 0 if successful, otherwise a positive errno value. */
947 int
948 ofproto_get_stp_status(struct ofproto *ofproto,
949 struct ofproto_stp_status *s)
950 {
951 return (ofproto->ofproto_class->get_stp_status
952 ? ofproto->ofproto_class->get_stp_status(ofproto, s)
953 : EOPNOTSUPP);
954 }
955
956 /* Configures STP on 'ofp_port' of 'ofproto' using the settings defined
957 * in 's'. The caller is responsible for assigning STP port numbers
958 * (using the 'port_num' member in the range of 1 through 255, inclusive)
959 * and ensuring there are no duplicates. If the 's' is NULL, then STP
960 * is disabled on the port.
961 *
962 * Returns 0 if successful, otherwise a positive errno value.*/
963 int
964 ofproto_port_set_stp(struct ofproto *ofproto, ofp_port_t ofp_port,
965 const struct ofproto_port_stp_settings *s)
966 {
967 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
968 if (!ofport) {
969 VLOG_WARN("%s: cannot configure STP on nonexistent port %"PRIu32,
970 ofproto->name, ofp_port);
971 return ENODEV;
972 }
973
974 return (ofproto->ofproto_class->set_stp_port
975 ? ofproto->ofproto_class->set_stp_port(ofport, s)
976 : EOPNOTSUPP);
977 }
978
979 /* Retrieves STP port status of 'ofp_port' on 'ofproto' and stores it in
980 * 's'. If the 'enabled' member in 's' is false, then the other members
981 * are not meaningful.
982 *
983 * Returns 0 if successful, otherwise a positive errno value.*/
984 int
985 ofproto_port_get_stp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
986 struct ofproto_port_stp_status *s)
987 {
988 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
989 if (!ofport) {
990 VLOG_WARN_RL(&rl, "%s: cannot get STP status on nonexistent "
991 "port %"PRIu32, ofproto->name, ofp_port);
992 return ENODEV;
993 }
994
995 return (ofproto->ofproto_class->get_stp_port_status
996 ? ofproto->ofproto_class->get_stp_port_status(ofport, s)
997 : EOPNOTSUPP);
998 }
999
1000 /* Retrieves STP port statistics of 'ofp_port' on 'ofproto' and stores it in
1001 * 's'. If the 'enabled' member in 's' is false, then the other members
1002 * are not meaningful.
1003 *
1004 * Returns 0 if successful, otherwise a positive errno value.*/
1005 int
1006 ofproto_port_get_stp_stats(struct ofproto *ofproto, ofp_port_t ofp_port,
1007 struct ofproto_port_stp_stats *s)
1008 {
1009 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1010 if (!ofport) {
1011 VLOG_WARN_RL(&rl, "%s: cannot get STP stats on nonexistent "
1012 "port %"PRIu32, ofproto->name, ofp_port);
1013 return ENODEV;
1014 }
1015
1016 return (ofproto->ofproto_class->get_stp_port_stats
1017 ? ofproto->ofproto_class->get_stp_port_stats(ofport, s)
1018 : EOPNOTSUPP);
1019 }
1020
1021 /* Rapid Spanning Tree Protocol (RSTP) configuration. */
1022
1023 /* Configures RSTP on 'ofproto' using the settings defined in 's'. If
1024 * 's' is NULL, disables RSTP.
1025 *
1026 * Returns 0 if successful, otherwise a positive errno value. */
1027 int
1028 ofproto_set_rstp(struct ofproto *ofproto,
1029 const struct ofproto_rstp_settings *s)
1030 {
1031 if (!ofproto->ofproto_class->set_rstp) {
1032 return EOPNOTSUPP;
1033 }
1034 ofproto->ofproto_class->set_rstp(ofproto, s);
1035 return 0;
1036 }
1037
1038 /* Retrieves RSTP status of 'ofproto' and stores it in 's'. If the
1039 * 'enabled' member of 's' is false, then the other members are not
1040 * meaningful.
1041 *
1042 * Returns 0 if successful, otherwise a positive errno value. */
1043 int
1044 ofproto_get_rstp_status(struct ofproto *ofproto,
1045 struct ofproto_rstp_status *s)
1046 {
1047 if (!ofproto->ofproto_class->get_rstp_status) {
1048 return EOPNOTSUPP;
1049 }
1050 ofproto->ofproto_class->get_rstp_status(ofproto, s);
1051 return 0;
1052 }
1053
1054 /* Configures RSTP on 'ofp_port' of 'ofproto' using the settings defined
1055 * in 's'. The caller is responsible for assigning RSTP port numbers
1056 * (using the 'port_num' member in the range of 1 through 255, inclusive)
1057 * and ensuring there are no duplicates. If the 's' is NULL, then RSTP
1058 * is disabled on the port.
1059 *
1060 * Returns 0 if successful, otherwise a positive errno value.*/
1061 int
1062 ofproto_port_set_rstp(struct ofproto *ofproto, ofp_port_t ofp_port,
1063 const struct ofproto_port_rstp_settings *s)
1064 {
1065 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1066 if (!ofport) {
1067 VLOG_WARN("%s: cannot configure RSTP on nonexistent port %"PRIu32,
1068 ofproto->name, ofp_port);
1069 return ENODEV;
1070 }
1071
1072 if (!ofproto->ofproto_class->set_rstp_port) {
1073 return EOPNOTSUPP;
1074 }
1075 ofproto->ofproto_class->set_rstp_port(ofport, s);
1076 return 0;
1077 }
1078
1079 /* Retrieves RSTP port status of 'ofp_port' on 'ofproto' and stores it in
1080 * 's'. If the 'enabled' member in 's' is false, then the other members
1081 * are not meaningful.
1082 *
1083 * Returns 0 if successful, otherwise a positive errno value.*/
1084 int
1085 ofproto_port_get_rstp_status(struct ofproto *ofproto, ofp_port_t ofp_port,
1086 struct ofproto_port_rstp_status *s)
1087 {
1088 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1089 if (!ofport) {
1090 VLOG_WARN_RL(&rl, "%s: cannot get RSTP status on nonexistent "
1091 "port %"PRIu32, ofproto->name, ofp_port);
1092 return ENODEV;
1093 }
1094
1095 if (!ofproto->ofproto_class->get_rstp_port_status) {
1096 return EOPNOTSUPP;
1097 }
1098 ofproto->ofproto_class->get_rstp_port_status(ofport, s);
1099 return 0;
1100 }
1101 \f
1102 /* Queue DSCP configuration. */
1103
1104 /* Registers meta-data associated with the 'n_qdscp' Qualities of Service
1105 * 'queues' attached to 'ofport'. This data is not intended to be sufficient
1106 * to implement QoS. Instead, it is used to implement features which require
1107 * knowledge of what queues exist on a port, and some basic information about
1108 * them.
1109 *
1110 * Returns 0 if successful, otherwise a positive errno value. */
1111 int
1112 ofproto_port_set_queues(struct ofproto *ofproto, ofp_port_t ofp_port,
1113 const struct ofproto_port_queue *queues,
1114 size_t n_queues)
1115 {
1116 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1117
1118 if (!ofport) {
1119 VLOG_WARN("%s: cannot set queues on nonexistent port %"PRIu32,
1120 ofproto->name, ofp_port);
1121 return ENODEV;
1122 }
1123
1124 return (ofproto->ofproto_class->set_queues
1125 ? ofproto->ofproto_class->set_queues(ofport, queues, n_queues)
1126 : EOPNOTSUPP);
1127 }
1128 \f
1129 /* LLDP configuration. */
1130 void
1131 ofproto_port_set_lldp(struct ofproto *ofproto,
1132 ofp_port_t ofp_port,
1133 const struct smap *cfg)
1134 {
1135 struct ofport *ofport;
1136 int error;
1137
1138 ofport = ofproto_get_port(ofproto, ofp_port);
1139 if (!ofport) {
1140 VLOG_WARN("%s: cannot configure LLDP on nonexistent port %"PRIu32,
1141 ofproto->name, ofp_port);
1142 return;
1143 }
1144 error = (ofproto->ofproto_class->set_lldp
1145 ? ofproto->ofproto_class->set_lldp(ofport, cfg)
1146 : EOPNOTSUPP);
1147 if (error) {
1148 VLOG_WARN("%s: lldp configuration on port %"PRIu32" (%s) failed (%s)",
1149 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1150 ovs_strerror(error));
1151 }
1152 }
1153
1154 int
1155 ofproto_set_aa(struct ofproto *ofproto, void *aux OVS_UNUSED,
1156 const struct aa_settings *s)
1157 {
1158 if (!ofproto->ofproto_class->set_aa) {
1159 return EOPNOTSUPP;
1160 }
1161 ofproto->ofproto_class->set_aa(ofproto, s);
1162 return 0;
1163 }
1164
1165 int
1166 ofproto_aa_mapping_register(struct ofproto *ofproto, void *aux,
1167 const struct aa_mapping_settings *s)
1168 {
1169 if (!ofproto->ofproto_class->aa_mapping_set) {
1170 return EOPNOTSUPP;
1171 }
1172 ofproto->ofproto_class->aa_mapping_set(ofproto, aux, s);
1173 return 0;
1174 }
1175
1176 int
1177 ofproto_aa_mapping_unregister(struct ofproto *ofproto, void *aux)
1178 {
1179 if (!ofproto->ofproto_class->aa_mapping_unset) {
1180 return EOPNOTSUPP;
1181 }
1182 ofproto->ofproto_class->aa_mapping_unset(ofproto, aux);
1183 return 0;
1184 }
1185
1186 int
1187 ofproto_aa_vlan_get_queued(struct ofproto *ofproto,
1188 struct ovs_list *list)
1189 {
1190 if (!ofproto->ofproto_class->aa_vlan_get_queued) {
1191 return EOPNOTSUPP;
1192 }
1193 ofproto->ofproto_class->aa_vlan_get_queued(ofproto, list);
1194 return 0;
1195 }
1196
1197 unsigned int
1198 ofproto_aa_vlan_get_queue_size(struct ofproto *ofproto)
1199 {
1200 if (!ofproto->ofproto_class->aa_vlan_get_queue_size) {
1201 return EOPNOTSUPP;
1202 }
1203 return ofproto->ofproto_class->aa_vlan_get_queue_size(ofproto);
1204 }
1205
1206 /* Connectivity Fault Management configuration. */
1207
1208 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
1209 void
1210 ofproto_port_clear_cfm(struct ofproto *ofproto, ofp_port_t ofp_port)
1211 {
1212 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1213 if (ofport && ofproto->ofproto_class->set_cfm) {
1214 ofproto->ofproto_class->set_cfm(ofport, NULL);
1215 }
1216 }
1217
1218 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'. Takes
1219 * basic configuration from the configuration members in 'cfm', and the remote
1220 * maintenance point ID from remote_mpid. Ignores the statistics members of
1221 * 'cfm'.
1222 *
1223 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
1224 void
1225 ofproto_port_set_cfm(struct ofproto *ofproto, ofp_port_t ofp_port,
1226 const struct cfm_settings *s)
1227 {
1228 struct ofport *ofport;
1229 int error;
1230
1231 ofport = ofproto_get_port(ofproto, ofp_port);
1232 if (!ofport) {
1233 VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu32,
1234 ofproto->name, ofp_port);
1235 return;
1236 }
1237
1238 /* XXX: For configuration simplicity, we only support one remote_mpid
1239 * outside of the CFM module. It's not clear if this is the correct long
1240 * term solution or not. */
1241 error = (ofproto->ofproto_class->set_cfm
1242 ? ofproto->ofproto_class->set_cfm(ofport, s)
1243 : EOPNOTSUPP);
1244 if (error) {
1245 VLOG_WARN("%s: CFM configuration on port %"PRIu32" (%s) failed (%s)",
1246 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1247 ovs_strerror(error));
1248 }
1249 }
1250
1251 /* Configures BFD on 'ofp_port' in 'ofproto'. This function has no effect if
1252 * 'ofproto' does not have a port 'ofp_port'. */
1253 void
1254 ofproto_port_set_bfd(struct ofproto *ofproto, ofp_port_t ofp_port,
1255 const struct smap *cfg)
1256 {
1257 struct ofport *ofport;
1258 int error;
1259
1260 ofport = ofproto_get_port(ofproto, ofp_port);
1261 if (!ofport) {
1262 VLOG_WARN("%s: cannot configure bfd on nonexistent port %"PRIu32,
1263 ofproto->name, ofp_port);
1264 return;
1265 }
1266
1267 error = (ofproto->ofproto_class->set_bfd
1268 ? ofproto->ofproto_class->set_bfd(ofport, cfg)
1269 : EOPNOTSUPP);
1270 if (error) {
1271 VLOG_WARN("%s: bfd configuration on port %"PRIu32" (%s) failed (%s)",
1272 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
1273 ovs_strerror(error));
1274 }
1275 }
1276
1277 /* Checks the status change of BFD on 'ofport'.
1278 *
1279 * Returns true if 'ofproto_class' does not support 'bfd_status_changed'. */
1280 bool
1281 ofproto_port_bfd_status_changed(struct ofproto *ofproto, ofp_port_t ofp_port)
1282 {
1283 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1284 return (ofport && ofproto->ofproto_class->bfd_status_changed
1285 ? ofproto->ofproto_class->bfd_status_changed(ofport)
1286 : true);
1287 }
1288
1289 /* Populates 'status' with the status of BFD on 'ofport'. Returns 0 on
1290 * success. Returns a positive errno otherwise. Has no effect if 'ofp_port'
1291 * is not an OpenFlow port in 'ofproto'.
1292 *
1293 * The caller must provide and own '*status'. */
1294 int
1295 ofproto_port_get_bfd_status(struct ofproto *ofproto, ofp_port_t ofp_port,
1296 struct smap *status)
1297 {
1298 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1299 return (ofport && ofproto->ofproto_class->get_bfd_status
1300 ? ofproto->ofproto_class->get_bfd_status(ofport, status)
1301 : EOPNOTSUPP);
1302 }
1303
1304 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
1305 * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
1306 * 0 if LACP partner information is not current (generally indicating a
1307 * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
1308 int
1309 ofproto_port_is_lacp_current(struct ofproto *ofproto, ofp_port_t ofp_port)
1310 {
1311 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1312 return (ofport && ofproto->ofproto_class->port_is_lacp_current
1313 ? ofproto->ofproto_class->port_is_lacp_current(ofport)
1314 : -1);
1315 }
1316
1317 int
1318 ofproto_port_get_lacp_stats(const struct ofport *port, struct lacp_slave_stats *stats)
1319 {
1320 struct ofproto *ofproto = port->ofproto;
1321 int error;
1322
1323 if (ofproto->ofproto_class->port_get_lacp_stats) {
1324 error = ofproto->ofproto_class->port_get_lacp_stats(port, stats);
1325 } else {
1326 error = EOPNOTSUPP;
1327 }
1328
1329 return error;
1330 }
1331 \f
1332 /* Bundles. */
1333
1334 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
1335 * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
1336 * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
1337 * configuration plus, if there is more than one slave, a bonding
1338 * configuration.
1339 *
1340 * If 'aux' is already registered then this function updates its configuration
1341 * to 's'. Otherwise, this function registers a new bundle.
1342 *
1343 * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
1344 * port. */
1345 int
1346 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
1347 const struct ofproto_bundle_settings *s)
1348 {
1349 return (ofproto->ofproto_class->bundle_set
1350 ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
1351 : EOPNOTSUPP);
1352 }
1353
1354 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
1355 * If no such bundle has been registered, this has no effect. */
1356 int
1357 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
1358 {
1359 return ofproto_bundle_register(ofproto, aux, NULL);
1360 }
1361
1362 \f
1363 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
1364 * If 'aux' is already registered then this function updates its configuration
1365 * to 's'. Otherwise, this function registers a new mirror. */
1366 int
1367 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
1368 const struct ofproto_mirror_settings *s)
1369 {
1370 return (ofproto->ofproto_class->mirror_set
1371 ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
1372 : EOPNOTSUPP);
1373 }
1374
1375 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
1376 * If no mirror has been registered, this has no effect. */
1377 int
1378 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
1379 {
1380 return ofproto_mirror_register(ofproto, aux, NULL);
1381 }
1382
1383 /* Retrieves statistics from mirror associated with client data pointer
1384 * 'aux' in 'ofproto'. Stores packet and byte counts in 'packets' and
1385 * 'bytes', respectively. If a particular counters is not supported,
1386 * the appropriate argument is set to UINT64_MAX.
1387 */
1388 int
1389 ofproto_mirror_get_stats(struct ofproto *ofproto, void *aux,
1390 uint64_t *packets, uint64_t *bytes)
1391 {
1392 if (!ofproto->ofproto_class->mirror_get_stats) {
1393 *packets = *bytes = UINT64_MAX;
1394 return EOPNOTSUPP;
1395 }
1396
1397 return ofproto->ofproto_class->mirror_get_stats(ofproto, aux,
1398 packets, bytes);
1399 }
1400
1401 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
1402 * which all packets are flooded, instead of using MAC learning. If
1403 * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
1404 *
1405 * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
1406 * port. */
1407 int
1408 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
1409 {
1410 return (ofproto->ofproto_class->set_flood_vlans
1411 ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
1412 : EOPNOTSUPP);
1413 }
1414
1415 /* Returns true if 'aux' is a registered bundle that is currently in use as the
1416 * output for a mirror. */
1417 bool
1418 ofproto_is_mirror_output_bundle(const struct ofproto *ofproto, void *aux)
1419 {
1420 return (ofproto->ofproto_class->is_mirror_output_bundle
1421 ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
1422 : false);
1423 }
1424 \f
1425 /* Configuration of OpenFlow tables. */
1426
1427 /* Returns the number of OpenFlow tables in 'ofproto'. */
1428 int
1429 ofproto_get_n_tables(const struct ofproto *ofproto)
1430 {
1431 return ofproto->n_tables;
1432 }
1433
1434 /* Returns the number of Controller visible OpenFlow tables
1435 * in 'ofproto'. This number will exclude Hidden tables.
1436 * This funtion's return value should be less or equal to that of
1437 * ofproto_get_n_tables() . */
1438 uint8_t
1439 ofproto_get_n_visible_tables(const struct ofproto *ofproto)
1440 {
1441 uint8_t n = ofproto->n_tables;
1442
1443 /* Count only non-hidden tables in the number of tables. (Hidden tables,
1444 * if present, are always at the end.) */
1445 while(n && (ofproto->tables[n - 1].flags & OFTABLE_HIDDEN)) {
1446 n--;
1447 }
1448
1449 return n;
1450 }
1451
1452 /* Configures the OpenFlow table in 'ofproto' with id 'table_id' with the
1453 * settings from 's'. 'table_id' must be in the range 0 through the number of
1454 * OpenFlow tables in 'ofproto' minus 1, inclusive.
1455 *
1456 * For read-only tables, only the name may be configured. */
1457 void
1458 ofproto_configure_table(struct ofproto *ofproto, int table_id,
1459 const struct ofproto_table_settings *s)
1460 {
1461 struct oftable *table;
1462
1463 ovs_assert(table_id >= 0 && table_id < ofproto->n_tables);
1464 table = &ofproto->tables[table_id];
1465
1466 oftable_set_name(table, s->name);
1467
1468 if (table->flags & OFTABLE_READONLY) {
1469 return;
1470 }
1471
1472 if (classifier_set_prefix_fields(&table->cls,
1473 s->prefix_fields, s->n_prefix_fields)) {
1474 /* XXX: Trigger revalidation. */
1475 }
1476
1477 ovs_mutex_lock(&ofproto_mutex);
1478 unsigned int new_eviction = (s->enable_eviction
1479 ? table->eviction | EVICTION_CLIENT
1480 : table->eviction & ~EVICTION_CLIENT);
1481 oftable_configure_eviction(table, new_eviction, s->groups, s->n_groups);
1482 table->max_flows = s->max_flows;
1483 evict_rules_from_table(table);
1484 ovs_mutex_unlock(&ofproto_mutex);
1485 }
1486 \f
1487 bool
1488 ofproto_has_snoops(const struct ofproto *ofproto)
1489 {
1490 return connmgr_has_snoops(ofproto->connmgr);
1491 }
1492
1493 void
1494 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
1495 {
1496 connmgr_get_snoops(ofproto->connmgr, snoops);
1497 }
1498
1499 /* Deletes 'rule' from 'ofproto'.
1500 *
1501 * Within an ofproto implementation, this function allows an ofproto
1502 * implementation to destroy any rules that remain when its ->destruct()
1503 * function is called. This function is not suitable for use elsewhere in an
1504 * ofproto implementation.
1505 *
1506 * This function implements steps 4.4 and 4.5 in the section titled "Rule Life
1507 * Cycle" in ofproto-provider.h. */
1508 void
1509 ofproto_rule_delete(struct ofproto *ofproto, struct rule *rule)
1510 OVS_EXCLUDED(ofproto_mutex)
1511 {
1512 /* This skips the ofmonitor and flow-removed notifications because the
1513 * switch is being deleted and any OpenFlow channels have been or soon will
1514 * be killed. */
1515 ovs_mutex_lock(&ofproto_mutex);
1516
1517 if (rule->state == RULE_INSERTED) {
1518 /* Make sure there is no postponed removal of the rule. */
1519 ovs_assert(cls_rule_visible_in_version(&rule->cr, OVS_VERSION_MAX));
1520
1521 if (!classifier_remove(&rule->ofproto->tables[rule->table_id].cls,
1522 &rule->cr)) {
1523 OVS_NOT_REACHED();
1524 }
1525 ofproto_rule_remove__(rule->ofproto, rule);
1526 if (ofproto->ofproto_class->rule_delete) {
1527 ofproto->ofproto_class->rule_delete(rule);
1528 }
1529
1530 /* This may not be the last reference to the rule. */
1531 ofproto_rule_unref(rule);
1532 }
1533 ovs_mutex_unlock(&ofproto_mutex);
1534 }
1535
1536 static void
1537 ofproto_flush__(struct ofproto *ofproto)
1538 OVS_EXCLUDED(ofproto_mutex)
1539 {
1540 struct oftable *table;
1541
1542 /* This will flush all datapath flows. */
1543 if (ofproto->ofproto_class->flush) {
1544 ofproto->ofproto_class->flush(ofproto);
1545 }
1546
1547 /* XXX: There is a small race window here, where new datapath flows can be
1548 * created by upcall handlers based on the existing flow table. We can not
1549 * call ofproto class flush while holding 'ofproto_mutex' to prevent this,
1550 * as then we could deadlock on syncing with the handler threads waiting on
1551 * the same mutex. */
1552
1553 ovs_mutex_lock(&ofproto_mutex);
1554 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1555 struct rule_collection rules;
1556 struct rule *rule;
1557
1558 if (table->flags & OFTABLE_HIDDEN) {
1559 continue;
1560 }
1561
1562 rule_collection_init(&rules);
1563
1564 CLS_FOR_EACH (rule, cr, &table->cls) {
1565 rule_collection_add(&rules, rule);
1566 }
1567 delete_flows__(&rules, OFPRR_DELETE, NULL);
1568 }
1569 /* XXX: Concurrent handler threads may insert new learned flows based on
1570 * learn actions of the now deleted flows right after we release
1571 * 'ofproto_mutex'. */
1572 ovs_mutex_unlock(&ofproto_mutex);
1573 }
1574
1575 static void
1576 ofproto_destroy__(struct ofproto *ofproto)
1577 OVS_EXCLUDED(ofproto_mutex)
1578 {
1579 struct oftable *table;
1580
1581 cmap_destroy(&ofproto->groups);
1582
1583 hmap_remove(&all_ofprotos, &ofproto->hmap_node);
1584
1585 free(ofproto->name);
1586 free(ofproto->type);
1587 free(ofproto->mfr_desc);
1588 free(ofproto->hw_desc);
1589 free(ofproto->sw_desc);
1590 free(ofproto->serial_desc);
1591 free(ofproto->dp_desc);
1592 hmap_destroy(&ofproto->ports);
1593 hmap_destroy(&ofproto->ofport_usage);
1594 shash_destroy(&ofproto->port_by_name);
1595 simap_destroy(&ofproto->ofp_requests);
1596
1597 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1598 oftable_destroy(table);
1599 }
1600 free(ofproto->tables);
1601
1602 ovs_mutex_lock(&ofproto->vl_mff_map.mutex);
1603 mf_vl_mff_map_clear(&ofproto->vl_mff_map, true);
1604 ovs_mutex_unlock(&ofproto->vl_mff_map.mutex);
1605 cmap_destroy(&ofproto->vl_mff_map.cmap);
1606 ovs_mutex_destroy(&ofproto->vl_mff_map.mutex);
1607 tun_metadata_free(ovsrcu_get_protected(struct tun_table *,
1608 &ofproto->metadata_tab));
1609
1610 ovs_assert(hindex_is_empty(&ofproto->cookies));
1611 hindex_destroy(&ofproto->cookies);
1612
1613 ovs_assert(hmap_is_empty(&ofproto->learned_cookies));
1614 hmap_destroy(&ofproto->learned_cookies);
1615
1616 ofproto->ofproto_class->dealloc(ofproto);
1617 }
1618
1619 /* Destroying rules is doubly deferred, must have 'ofproto' around for them.
1620 * - 1st we defer the removal of the rules from the classifier
1621 * - 2nd we defer the actual destruction of the rules. */
1622 static void
1623 ofproto_destroy_defer__(struct ofproto *ofproto)
1624 OVS_EXCLUDED(ofproto_mutex)
1625 {
1626 ovsrcu_postpone(ofproto_destroy__, ofproto);
1627 }
1628
1629 void
1630 ofproto_destroy(struct ofproto *p, bool del)
1631 OVS_EXCLUDED(ofproto_mutex)
1632 {
1633 struct ofport *ofport, *next_ofport;
1634 struct ofport_usage *usage;
1635
1636 if (!p) {
1637 return;
1638 }
1639
1640 meter_delete_all(p);
1641 hmap_destroy(&p->meters);
1642
1643 ofproto_flush__(p);
1644 HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
1645 ofport_destroy(ofport, del);
1646 }
1647
1648 HMAP_FOR_EACH_POP (usage, hmap_node, &p->ofport_usage) {
1649 free(usage);
1650 }
1651
1652 p->ofproto_class->destruct(p, del);
1653
1654 /* We should not postpone this because it involves deleting a listening
1655 * socket which we may want to reopen soon. 'connmgr' may be used by other
1656 * threads only if they take the ofproto_mutex and read a non-NULL
1657 * 'ofproto->connmgr'. */
1658 ovs_mutex_lock(&ofproto_mutex);
1659 connmgr_destroy(p->connmgr);
1660 p->connmgr = NULL;
1661 ovs_mutex_unlock(&ofproto_mutex);
1662
1663 /* Destroying rules is deferred, must have 'ofproto' around for them. */
1664 ovsrcu_postpone(ofproto_destroy_defer__, p);
1665 }
1666
1667 /* Destroys the datapath with the respective 'name' and 'type'. With the Linux
1668 * kernel datapath, for example, this destroys the datapath in the kernel, and
1669 * with the netdev-based datapath, it tears down the data structures that
1670 * represent the datapath.
1671 *
1672 * The datapath should not be currently open as an ofproto. */
1673 int
1674 ofproto_delete(const char *name, const char *type)
1675 {
1676 const struct ofproto_class *class = ofproto_class_find__(type);
1677 return (!class ? EAFNOSUPPORT
1678 : !class->del ? EACCES
1679 : class->del(type, name));
1680 }
1681
1682 static void
1683 process_port_change(struct ofproto *ofproto, int error, char *devname)
1684 {
1685 if (error == ENOBUFS) {
1686 reinit_ports(ofproto);
1687 } else if (!error) {
1688 update_port(ofproto, devname);
1689 free(devname);
1690 }
1691 }
1692
1693 int
1694 ofproto_type_run(const char *datapath_type)
1695 {
1696 const struct ofproto_class *class;
1697 int error;
1698
1699 datapath_type = ofproto_normalize_type(datapath_type);
1700 class = ofproto_class_find__(datapath_type);
1701
1702 error = class->type_run ? class->type_run(datapath_type) : 0;
1703 if (error && error != EAGAIN) {
1704 VLOG_ERR_RL(&rl, "%s: type_run failed (%s)",
1705 datapath_type, ovs_strerror(error));
1706 }
1707 return error;
1708 }
1709
1710 void
1711 ofproto_type_wait(const char *datapath_type)
1712 {
1713 const struct ofproto_class *class;
1714
1715 datapath_type = ofproto_normalize_type(datapath_type);
1716 class = ofproto_class_find__(datapath_type);
1717
1718 if (class->type_wait) {
1719 class->type_wait(datapath_type);
1720 }
1721 }
1722
1723 int
1724 ofproto_run(struct ofproto *p)
1725 {
1726 int error;
1727 uint64_t new_seq;
1728
1729 error = p->ofproto_class->run(p);
1730 if (error && error != EAGAIN) {
1731 VLOG_ERR_RL(&rl, "%s: run failed (%s)", p->name, ovs_strerror(error));
1732 }
1733
1734 /* Restore the eviction group heap invariant occasionally. */
1735 if (p->eviction_group_timer < time_msec()) {
1736 size_t i;
1737
1738 p->eviction_group_timer = time_msec() + 1000;
1739
1740 for (i = 0; i < p->n_tables; i++) {
1741 struct oftable *table = &p->tables[i];
1742 struct eviction_group *evg;
1743 struct rule *rule;
1744
1745 if (!table->eviction) {
1746 continue;
1747 }
1748
1749 if (table->n_flows > 100000) {
1750 static struct vlog_rate_limit count_rl =
1751 VLOG_RATE_LIMIT_INIT(1, 1);
1752 VLOG_WARN_RL(&count_rl, "Table %"PRIuSIZE" has an excessive"
1753 " number of rules: %d", i, table->n_flows);
1754 }
1755
1756 ovs_mutex_lock(&ofproto_mutex);
1757 CLS_FOR_EACH (rule, cr, &table->cls) {
1758 if (rule->idle_timeout || rule->hard_timeout) {
1759 if (!rule->eviction_group) {
1760 eviction_group_add_rule(rule);
1761 } else {
1762 heap_raw_change(&rule->evg_node,
1763 rule_eviction_priority(p, rule));
1764 }
1765 }
1766 }
1767
1768 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
1769 heap_rebuild(&evg->rules);
1770 }
1771 ovs_mutex_unlock(&ofproto_mutex);
1772 }
1773 }
1774
1775 if (p->ofproto_class->port_poll) {
1776 char *devname;
1777
1778 while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
1779 process_port_change(p, error, devname);
1780 }
1781 }
1782
1783 new_seq = seq_read(connectivity_seq_get());
1784 if (new_seq != p->change_seq) {
1785 struct sset devnames;
1786 const char *devname;
1787 struct ofport *ofport;
1788
1789 /* Update OpenFlow port status for any port whose netdev has changed.
1790 *
1791 * Refreshing a given 'ofport' can cause an arbitrary ofport to be
1792 * destroyed, so it's not safe to update ports directly from the
1793 * HMAP_FOR_EACH loop, or even to use HMAP_FOR_EACH_SAFE. Instead, we
1794 * need this two-phase approach. */
1795 sset_init(&devnames);
1796 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1797 uint64_t port_change_seq;
1798
1799 port_change_seq = netdev_get_change_seq(ofport->netdev);
1800 if (ofport->change_seq != port_change_seq) {
1801 ofport->change_seq = port_change_seq;
1802 sset_add(&devnames, netdev_get_name(ofport->netdev));
1803 }
1804 }
1805 SSET_FOR_EACH (devname, &devnames) {
1806 update_port(p, devname);
1807 }
1808 sset_destroy(&devnames);
1809
1810 p->change_seq = new_seq;
1811 }
1812
1813 connmgr_run(p->connmgr, handle_openflow);
1814
1815 return error;
1816 }
1817
1818 void
1819 ofproto_wait(struct ofproto *p)
1820 {
1821 p->ofproto_class->wait(p);
1822 if (p->ofproto_class->port_poll_wait) {
1823 p->ofproto_class->port_poll_wait(p);
1824 }
1825 seq_wait(connectivity_seq_get(), p->change_seq);
1826 connmgr_wait(p->connmgr);
1827 }
1828
1829 bool
1830 ofproto_is_alive(const struct ofproto *p)
1831 {
1832 return connmgr_has_controllers(p->connmgr);
1833 }
1834
1835 /* Adds some memory usage statistics for 'ofproto' into 'usage', for use with
1836 * memory_report(). */
1837 void
1838 ofproto_get_memory_usage(const struct ofproto *ofproto, struct simap *usage)
1839 {
1840 const struct oftable *table;
1841 unsigned int n_rules;
1842
1843 simap_increase(usage, "ports", hmap_count(&ofproto->ports));
1844
1845 n_rules = 0;
1846 OFPROTO_FOR_EACH_TABLE (table, ofproto) {
1847 n_rules += table->n_flows;
1848 }
1849 simap_increase(usage, "rules", n_rules);
1850
1851 if (ofproto->ofproto_class->get_memory_usage) {
1852 ofproto->ofproto_class->get_memory_usage(ofproto, usage);
1853 }
1854
1855 connmgr_get_memory_usage(ofproto->connmgr, usage);
1856 }
1857
1858 void
1859 ofproto_type_get_memory_usage(const char *datapath_type, struct simap *usage)
1860 {
1861 const struct ofproto_class *class;
1862
1863 datapath_type = ofproto_normalize_type(datapath_type);
1864 class = ofproto_class_find__(datapath_type);
1865
1866 if (class && class->type_get_memory_usage) {
1867 class->type_get_memory_usage(datapath_type, usage);
1868 }
1869 }
1870
1871 void
1872 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
1873 struct shash *info)
1874 {
1875 connmgr_get_controller_info(ofproto->connmgr, info);
1876 }
1877
1878 void
1879 ofproto_free_ofproto_controller_info(struct shash *info)
1880 {
1881 connmgr_free_controller_info(info);
1882 }
1883
1884 /* Makes a deep copy of 'old' into 'port'. */
1885 void
1886 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
1887 {
1888 port->name = xstrdup(old->name);
1889 port->type = xstrdup(old->type);
1890 port->ofp_port = old->ofp_port;
1891 }
1892
1893 /* Frees memory allocated to members of 'ofproto_port'.
1894 *
1895 * Do not call this function on an ofproto_port obtained from
1896 * ofproto_port_dump_next(): that function retains ownership of the data in the
1897 * ofproto_port. */
1898 void
1899 ofproto_port_destroy(struct ofproto_port *ofproto_port)
1900 {
1901 free(ofproto_port->name);
1902 free(ofproto_port->type);
1903 }
1904
1905 /* Initializes 'dump' to begin dumping the ports in an ofproto.
1906 *
1907 * This function provides no status indication. An error status for the entire
1908 * dump operation is provided when it is completed by calling
1909 * ofproto_port_dump_done().
1910 */
1911 void
1912 ofproto_port_dump_start(struct ofproto_port_dump *dump,
1913 const struct ofproto *ofproto)
1914 {
1915 dump->ofproto = ofproto;
1916 dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
1917 &dump->state);
1918 }
1919
1920 /* Attempts to retrieve another port from 'dump', which must have been created
1921 * with ofproto_port_dump_start(). On success, stores a new ofproto_port into
1922 * 'port' and returns true. On failure, returns false.
1923 *
1924 * Failure might indicate an actual error or merely that the last port has been
1925 * dumped. An error status for the entire dump operation is provided when it
1926 * is completed by calling ofproto_port_dump_done().
1927 *
1928 * The ofproto owns the data stored in 'port'. It will remain valid until at
1929 * least the next time 'dump' is passed to ofproto_port_dump_next() or
1930 * ofproto_port_dump_done(). */
1931 bool
1932 ofproto_port_dump_next(struct ofproto_port_dump *dump,
1933 struct ofproto_port *port)
1934 {
1935 const struct ofproto *ofproto = dump->ofproto;
1936
1937 if (dump->error) {
1938 return false;
1939 }
1940
1941 dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
1942 port);
1943 if (dump->error) {
1944 ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
1945 return false;
1946 }
1947 return true;
1948 }
1949
1950 /* Completes port table dump operation 'dump', which must have been created
1951 * with ofproto_port_dump_start(). Returns 0 if the dump operation was
1952 * error-free, otherwise a positive errno value describing the problem. */
1953 int
1954 ofproto_port_dump_done(struct ofproto_port_dump *dump)
1955 {
1956 const struct ofproto *ofproto = dump->ofproto;
1957 if (!dump->error) {
1958 dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
1959 dump->state);
1960 }
1961 return dump->error == EOF ? 0 : dump->error;
1962 }
1963
1964 /* Returns the type to pass to netdev_open() when a datapath of type
1965 * 'datapath_type' has a port of type 'port_type', for a few special
1966 * cases when a netdev type differs from a port type. For example, when
1967 * using the userspace datapath, a port of type "internal" needs to be
1968 * opened as "tap".
1969 *
1970 * Returns either 'type' itself or a string literal, which must not be
1971 * freed. */
1972 const char *
1973 ofproto_port_open_type(const char *datapath_type, const char *port_type)
1974 {
1975 const struct ofproto_class *class;
1976
1977 datapath_type = ofproto_normalize_type(datapath_type);
1978 class = ofproto_class_find__(datapath_type);
1979 if (!class) {
1980 return port_type;
1981 }
1982
1983 return (class->port_open_type
1984 ? class->port_open_type(datapath_type, port_type)
1985 : port_type);
1986 }
1987
1988 /* Attempts to add 'netdev' as a port on 'ofproto'. If 'ofp_portp' is
1989 * non-null and '*ofp_portp' is not OFPP_NONE, attempts to use that as
1990 * the port's OpenFlow port number.
1991 *
1992 * If successful, returns 0 and sets '*ofp_portp' to the new port's
1993 * OpenFlow port number (if 'ofp_portp' is non-null). On failure,
1994 * returns a positive errno value and sets '*ofp_portp' to OFPP_NONE (if
1995 * 'ofp_portp' is non-null). */
1996 int
1997 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
1998 ofp_port_t *ofp_portp)
1999 {
2000 ofp_port_t ofp_port = ofp_portp ? *ofp_portp : OFPP_NONE;
2001 int error;
2002
2003 error = ofproto->ofproto_class->port_add(ofproto, netdev);
2004 if (!error) {
2005 const char *netdev_name = netdev_get_name(netdev);
2006
2007 simap_put(&ofproto->ofp_requests, netdev_name,
2008 ofp_to_u16(ofp_port));
2009 error = update_port(ofproto, netdev_name);
2010 }
2011 if (ofp_portp) {
2012 *ofp_portp = OFPP_NONE;
2013 if (!error) {
2014 struct ofproto_port ofproto_port;
2015
2016 error = ofproto_port_query_by_name(ofproto,
2017 netdev_get_name(netdev),
2018 &ofproto_port);
2019 if (!error) {
2020 *ofp_portp = ofproto_port.ofp_port;
2021 ofproto_port_destroy(&ofproto_port);
2022 }
2023 }
2024 }
2025 return error;
2026 }
2027
2028 /* Looks up a port named 'devname' in 'ofproto'. On success, returns 0 and
2029 * initializes '*port' appropriately; on failure, returns a positive errno
2030 * value.
2031 *
2032 * The caller owns the data in 'ofproto_port' and must free it with
2033 * ofproto_port_destroy() when it is no longer needed. */
2034 int
2035 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
2036 struct ofproto_port *port)
2037 {
2038 int error;
2039
2040 error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
2041 if (error) {
2042 memset(port, 0, sizeof *port);
2043 }
2044 return error;
2045 }
2046
2047 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
2048 * Returns 0 if successful, otherwise a positive errno. */
2049 int
2050 ofproto_port_del(struct ofproto *ofproto, ofp_port_t ofp_port)
2051 {
2052 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
2053 const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
2054 struct simap_node *ofp_request_node;
2055 int error;
2056
2057 ofp_request_node = simap_find(&ofproto->ofp_requests, name);
2058 if (ofp_request_node) {
2059 simap_delete(&ofproto->ofp_requests, ofp_request_node);
2060 }
2061
2062 error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
2063 if (!error && ofport) {
2064 /* 'name' is the netdev's name and update_port() is going to close the
2065 * netdev. Just in case update_port() refers to 'name' after it
2066 * destroys 'ofport', make a copy of it around the update_port()
2067 * call. */
2068 char *devname = xstrdup(name);
2069 update_port(ofproto, devname);
2070 free(devname);
2071 }
2072 return error;
2073 }
2074
2075 /* Refreshes datapath configuration of port number 'ofp_port' in 'ofproto'.
2076 *
2077 * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
2078 void
2079 ofproto_port_set_config(struct ofproto *ofproto, ofp_port_t ofp_port,
2080 const struct smap *cfg)
2081 {
2082 struct ofport *ofport;
2083 int error;
2084
2085 ofport = ofproto_get_port(ofproto, ofp_port);
2086 if (!ofport) {
2087 VLOG_WARN("%s: cannot configure datapath on nonexistent port %"PRIu32,
2088 ofproto->name, ofp_port);
2089 return;
2090 }
2091
2092 error = (ofproto->ofproto_class->port_set_config
2093 ? ofproto->ofproto_class->port_set_config(ofport, cfg)
2094 : EOPNOTSUPP);
2095 if (error) {
2096 VLOG_WARN("%s: datapath configuration on port %"PRIu32
2097 " (%s) failed (%s)",
2098 ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
2099 ovs_strerror(error));
2100 }
2101 }
2102
2103
2104 static void
2105 flow_mod_init(struct ofputil_flow_mod *fm,
2106 const struct match *match, int priority,
2107 const struct ofpact *ofpacts, size_t ofpacts_len,
2108 enum ofp_flow_mod_command command)
2109 {
2110 *fm = (struct ofputil_flow_mod) {
2111 .match = *match,
2112 .priority = priority,
2113 .table_id = 0,
2114 .command = command,
2115 .buffer_id = UINT32_MAX,
2116 .out_port = OFPP_ANY,
2117 .out_group = OFPG_ANY,
2118 .ofpacts = CONST_CAST(struct ofpact *, ofpacts),
2119 .ofpacts_len = ofpacts_len,
2120 };
2121 }
2122
2123 static int
2124 simple_flow_mod(struct ofproto *ofproto,
2125 const struct match *match, int priority,
2126 const struct ofpact *ofpacts, size_t ofpacts_len,
2127 enum ofp_flow_mod_command command)
2128 {
2129 struct ofputil_flow_mod fm;
2130
2131 flow_mod_init(&fm, match, priority, ofpacts, ofpacts_len, command);
2132
2133 return handle_flow_mod__(ofproto, &fm, NULL);
2134 }
2135
2136 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
2137 * performs the 'n_actions' actions in 'actions'. The new flow will not
2138 * timeout.
2139 *
2140 * If cls_rule->priority is in the range of priorities supported by OpenFlow
2141 * (0...65535, inclusive) then the flow will be visible to OpenFlow
2142 * controllers; otherwise, it will be hidden.
2143 *
2144 * The caller retains ownership of 'cls_rule' and 'ofpacts'.
2145 *
2146 * This is a helper function for in-band control and fail-open. */
2147 void
2148 ofproto_add_flow(struct ofproto *ofproto, const struct match *match,
2149 int priority,
2150 const struct ofpact *ofpacts, size_t ofpacts_len)
2151 OVS_EXCLUDED(ofproto_mutex)
2152 {
2153 const struct rule *rule;
2154 bool must_add;
2155
2156 /* First do a cheap check whether the rule we're looking for already exists
2157 * with the actions that we want. If it does, then we're done. */
2158 rule = rule_from_cls_rule(classifier_find_match_exactly(
2159 &ofproto->tables[0].cls, match, priority,
2160 OVS_VERSION_MAX));
2161 if (rule) {
2162 const struct rule_actions *actions = rule_get_actions(rule);
2163 must_add = !ofpacts_equal(actions->ofpacts, actions->ofpacts_len,
2164 ofpacts, ofpacts_len);
2165 } else {
2166 must_add = true;
2167 }
2168
2169 /* If there's no such rule or the rule doesn't have the actions we want,
2170 * fall back to a executing a full flow mod. We can't optimize this at
2171 * all because we didn't take enough locks above to ensure that the flow
2172 * table didn't already change beneath us. */
2173 if (must_add) {
2174 simple_flow_mod(ofproto, match, priority, ofpacts, ofpacts_len,
2175 OFPFC_MODIFY_STRICT);
2176 }
2177 }
2178
2179 /* Executes the flow modification specified in 'fm'. Returns 0 on success, or
2180 * an OFPERR_* OpenFlow error code on failure.
2181 *
2182 * This is a helper function for in-band control and fail-open. */
2183 enum ofperr
2184 ofproto_flow_mod(struct ofproto *ofproto, const struct ofputil_flow_mod *fm)
2185 OVS_EXCLUDED(ofproto_mutex)
2186 {
2187 return handle_flow_mod__(ofproto, fm, NULL);
2188 }
2189
2190 /* Searches for a rule with matching criteria exactly equal to 'target' in
2191 * ofproto's table 0 and, if it finds one, deletes it.
2192 *
2193 * This is a helper function for in-band control and fail-open. */
2194 void
2195 ofproto_delete_flow(struct ofproto *ofproto,
2196 const struct match *target, int priority)
2197 OVS_REQUIRES(ofproto_mutex)
2198 {
2199 struct classifier *cls = &ofproto->tables[0].cls;
2200 struct rule *rule;
2201
2202 /* First do a cheap check whether the rule we're looking for has already
2203 * been deleted. If so, then we're done. */
2204 rule = rule_from_cls_rule(classifier_find_match_exactly(
2205 cls, target, priority, OVS_VERSION_MAX));
2206 if (!rule) {
2207 return;
2208 }
2209
2210 struct rule_collection rules;
2211
2212 rule_collection_init(&rules);
2213 rule_collection_add(&rules, rule);
2214 delete_flows__(&rules, OFPRR_DELETE, NULL);
2215 rule_collection_destroy(&rules);
2216 }
2217
2218 /* Delete all of the flows from all of ofproto's flow tables, then reintroduce
2219 * the flows required by in-band control and fail-open. */
2220 void
2221 ofproto_flush_flows(struct ofproto *ofproto)
2222 {
2223 COVERAGE_INC(ofproto_flush);
2224 ofproto_flush__(ofproto);
2225 connmgr_flushed(ofproto->connmgr);
2226 }
2227 \f
2228 static void
2229 reinit_ports(struct ofproto *p)
2230 {
2231 struct ofproto_port_dump dump;
2232 struct sset devnames;
2233 struct ofport *ofport;
2234 struct ofproto_port ofproto_port;
2235 const char *devname;
2236
2237 COVERAGE_INC(ofproto_reinit_ports);
2238
2239 sset_init(&devnames);
2240 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2241 sset_add(&devnames, netdev_get_name(ofport->netdev));
2242 }
2243 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2244 sset_add(&devnames, ofproto_port.name);
2245 }
2246
2247 SSET_FOR_EACH (devname, &devnames) {
2248 update_port(p, devname);
2249 }
2250 sset_destroy(&devnames);
2251 }
2252
2253 static ofp_port_t
2254 alloc_ofp_port(struct ofproto *ofproto, const char *netdev_name)
2255 {
2256 uint16_t port_idx;
2257
2258 port_idx = simap_get(&ofproto->ofp_requests, netdev_name);
2259 port_idx = port_idx ? port_idx : UINT16_MAX;
2260
2261 if (port_idx >= ofproto->max_ports
2262 || ofport_get_usage(ofproto, u16_to_ofp(port_idx)) == LLONG_MAX) {
2263 uint16_t lru_ofport = 0, end_port_no = ofproto->alloc_port_no;
2264 long long int last_used_at, lru = LLONG_MAX;
2265
2266 /* Search for a free OpenFlow port number. We try not to
2267 * immediately reuse them to prevent problems due to old
2268 * flows.
2269 *
2270 * We limit the automatically assigned port numbers to the lower half
2271 * of the port range, to reserve the upper half for assignment by
2272 * controllers. */
2273 for (;;) {
2274 if (++ofproto->alloc_port_no >= MIN(ofproto->max_ports, 32768)) {
2275 ofproto->alloc_port_no = 1;
2276 }
2277 last_used_at = ofport_get_usage(ofproto,
2278 u16_to_ofp(ofproto->alloc_port_no));
2279 if (!last_used_at) {
2280 port_idx = ofproto->alloc_port_no;
2281 break;
2282 } else if ( last_used_at < time_msec() - 60*60*1000) {
2283 /* If the port with ofport 'ofproto->alloc_port_no' was deleted
2284 * more than an hour ago, consider it usable. */
2285 ofport_remove_usage(ofproto,
2286 u16_to_ofp(ofproto->alloc_port_no));
2287 port_idx = ofproto->alloc_port_no;
2288 break;
2289 } else if (last_used_at < lru) {
2290 lru = last_used_at;
2291 lru_ofport = ofproto->alloc_port_no;
2292 }
2293
2294 if (ofproto->alloc_port_no == end_port_no) {
2295 if (lru_ofport) {
2296 port_idx = lru_ofport;
2297 break;
2298 }
2299 return OFPP_NONE;
2300 }
2301 }
2302 }
2303 ofport_set_usage(ofproto, u16_to_ofp(port_idx), LLONG_MAX);
2304 return u16_to_ofp(port_idx);
2305 }
2306
2307 static void
2308 dealloc_ofp_port(struct ofproto *ofproto, ofp_port_t ofp_port)
2309 {
2310 if (ofp_to_u16(ofp_port) < ofproto->max_ports) {
2311 ofport_set_usage(ofproto, ofp_port, time_msec());
2312 }
2313 }
2314
2315 /* Opens and returns a netdev for 'ofproto_port' in 'ofproto', or a null
2316 * pointer if the netdev cannot be opened. On success, also fills in
2317 * '*pp'. */
2318 static struct netdev *
2319 ofport_open(struct ofproto *ofproto,
2320 struct ofproto_port *ofproto_port,
2321 struct ofputil_phy_port *pp)
2322 {
2323 enum netdev_flags flags;
2324 struct netdev *netdev;
2325 int error;
2326
2327 error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
2328 if (error) {
2329 VLOG_WARN_RL(&rl, "%s: ignoring port %s (%"PRIu32") because netdev %s "
2330 "cannot be opened (%s)",
2331 ofproto->name,
2332 ofproto_port->name, ofproto_port->ofp_port,
2333 ofproto_port->name, ovs_strerror(error));
2334 return NULL;
2335 }
2336
2337 if (ofproto_port->ofp_port == OFPP_NONE) {
2338 if (!strcmp(ofproto->name, ofproto_port->name)) {
2339 ofproto_port->ofp_port = OFPP_LOCAL;
2340 } else {
2341 ofproto_port->ofp_port = alloc_ofp_port(ofproto,
2342 ofproto_port->name);
2343 }
2344 }
2345 pp->port_no = ofproto_port->ofp_port;
2346 netdev_get_etheraddr(netdev, &pp->hw_addr);
2347 pp->hw_addr64 = eth_addr64_zero;
2348 ovs_strlcpy(pp->name, ofproto_port->name, sizeof pp->name);
2349 netdev_get_flags(netdev, &flags);
2350 pp->config = flags & NETDEV_UP ? 0 : OFPUTIL_PC_PORT_DOWN;
2351 pp->state = netdev_get_carrier(netdev) ? 0 : OFPUTIL_PS_LINK_DOWN;
2352 netdev_get_features(netdev, &pp->curr, &pp->advertised,
2353 &pp->supported, &pp->peer);
2354 pp->curr_speed = netdev_features_to_bps(pp->curr, 0) / 1000;
2355 pp->max_speed = netdev_features_to_bps(pp->supported, 0) / 1000;
2356
2357 return netdev;
2358 }
2359
2360 /* Returns true if most fields of 'a' and 'b' are equal. Differences in name,
2361 * port number, and 'config' bits other than OFPUTIL_PC_PORT_DOWN are
2362 * disregarded. */
2363 static bool
2364 ofport_equal(const struct ofputil_phy_port *a,
2365 const struct ofputil_phy_port *b)
2366 {
2367 return (eth_addr_equals(a->hw_addr, b->hw_addr)
2368 && eth_addr64_equals(a->hw_addr64, b->hw_addr64)
2369 && a->state == b->state
2370 && !((a->config ^ b->config) & OFPUTIL_PC_PORT_DOWN)
2371 && a->curr == b->curr
2372 && a->advertised == b->advertised
2373 && a->supported == b->supported
2374 && a->peer == b->peer
2375 && a->curr_speed == b->curr_speed
2376 && a->max_speed == b->max_speed);
2377 }
2378
2379 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
2380 * The caller must ensure that 'p' does not have a conflicting ofport (that is,
2381 * one with the same name or port number). */
2382 static int
2383 ofport_install(struct ofproto *p,
2384 struct netdev *netdev, const struct ofputil_phy_port *pp)
2385 {
2386 const char *netdev_name = netdev_get_name(netdev);
2387 struct ofport *ofport;
2388 int error;
2389
2390 /* Create ofport. */
2391 ofport = p->ofproto_class->port_alloc();
2392 if (!ofport) {
2393 error = ENOMEM;
2394 goto error;
2395 }
2396 ofport->ofproto = p;
2397 ofport->netdev = netdev;
2398 ofport->change_seq = netdev_get_change_seq(netdev);
2399 ofport->pp = *pp;
2400 ofport->ofp_port = pp->port_no;
2401 ofport->created = time_msec();
2402
2403 /* Add port to 'p'. */
2404 hmap_insert(&p->ports, &ofport->hmap_node,
2405 hash_ofp_port(ofport->ofp_port));
2406 shash_add(&p->port_by_name, netdev_name, ofport);
2407
2408 update_mtu(p, ofport);
2409
2410 /* Let the ofproto_class initialize its private data. */
2411 error = p->ofproto_class->port_construct(ofport);
2412 if (error) {
2413 goto error;
2414 }
2415 connmgr_send_port_status(p->connmgr, NULL, pp, OFPPR_ADD);
2416 return 0;
2417
2418 error:
2419 VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
2420 p->name, netdev_name, ovs_strerror(error));
2421 if (ofport) {
2422 ofport_destroy__(ofport);
2423 } else {
2424 netdev_close(netdev);
2425 }
2426 return error;
2427 }
2428
2429 /* Removes 'ofport' from 'p' and destroys it. */
2430 static void
2431 ofport_remove(struct ofport *ofport)
2432 {
2433 struct ofproto *p = ofport->ofproto;
2434 bool is_mtu_overridden = ofport_is_mtu_overridden(p, ofport);
2435
2436 connmgr_send_port_status(ofport->ofproto->connmgr, NULL, &ofport->pp,
2437 OFPPR_DELETE);
2438 ofport_destroy(ofport, true);
2439 if (!is_mtu_overridden) {
2440 update_mtu_ofproto(p);
2441 }
2442 }
2443
2444 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
2445 * destroys it. */
2446 static void
2447 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
2448 {
2449 struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
2450 if (port) {
2451 ofport_remove(port);
2452 }
2453 }
2454
2455 /* Updates 'port' with new 'pp' description.
2456 *
2457 * Does not handle a name or port number change. The caller must implement
2458 * such a change as a delete followed by an add. */
2459 static void
2460 ofport_modified(struct ofport *port, struct ofputil_phy_port *pp)
2461 {
2462 port->pp.hw_addr = pp->hw_addr;
2463 port->pp.hw_addr64 = pp->hw_addr64;
2464 port->pp.config = ((port->pp.config & ~OFPUTIL_PC_PORT_DOWN)
2465 | (pp->config & OFPUTIL_PC_PORT_DOWN));
2466 port->pp.state = ((port->pp.state & ~OFPUTIL_PS_LINK_DOWN)
2467 | (pp->state & OFPUTIL_PS_LINK_DOWN));
2468 port->pp.curr = pp->curr;
2469 port->pp.advertised = pp->advertised;
2470 port->pp.supported = pp->supported;
2471 port->pp.peer = pp->peer;
2472 port->pp.curr_speed = pp->curr_speed;
2473 port->pp.max_speed = pp->max_speed;
2474 }
2475
2476 /* Update OpenFlow 'state' in 'port' and notify controller. */
2477 void
2478 ofproto_port_set_state(struct ofport *port, enum ofputil_port_state state)
2479 {
2480 if (port->pp.state != state) {
2481 port->pp.state = state;
2482 connmgr_send_port_status(port->ofproto->connmgr, NULL,
2483 &port->pp, OFPPR_MODIFY);
2484 }
2485 }
2486
2487 void
2488 ofproto_port_unregister(struct ofproto *ofproto, ofp_port_t ofp_port)
2489 {
2490 struct ofport *port = ofproto_get_port(ofproto, ofp_port);
2491 if (port) {
2492 if (port->ofproto->ofproto_class->set_stp_port) {
2493 port->ofproto->ofproto_class->set_stp_port(port, NULL);
2494 }
2495 if (port->ofproto->ofproto_class->set_rstp_port) {
2496 port->ofproto->ofproto_class->set_rstp_port(port, NULL);
2497 }
2498 if (port->ofproto->ofproto_class->set_cfm) {
2499 port->ofproto->ofproto_class->set_cfm(port, NULL);
2500 }
2501 if (port->ofproto->ofproto_class->bundle_remove) {
2502 port->ofproto->ofproto_class->bundle_remove(port);
2503 }
2504 }
2505 }
2506
2507 static void
2508 ofport_destroy__(struct ofport *port)
2509 {
2510 struct ofproto *ofproto = port->ofproto;
2511 const char *name = netdev_get_name(port->netdev);
2512
2513 hmap_remove(&ofproto->ports, &port->hmap_node);
2514 shash_find_and_delete(&ofproto->port_by_name, name);
2515
2516 netdev_close(port->netdev);
2517 ofproto->ofproto_class->port_dealloc(port);
2518 }
2519
2520 static void
2521 ofport_destroy(struct ofport *port, bool del)
2522 {
2523 if (port) {
2524 dealloc_ofp_port(port->ofproto, port->ofp_port);
2525 port->ofproto->ofproto_class->port_destruct(port, del);
2526 ofport_destroy__(port);
2527 }
2528 }
2529
2530 struct ofport *
2531 ofproto_get_port(const struct ofproto *ofproto, ofp_port_t ofp_port)
2532 {
2533 struct ofport *port;
2534
2535 HMAP_FOR_EACH_IN_BUCKET (port, hmap_node, hash_ofp_port(ofp_port),
2536 &ofproto->ports) {
2537 if (port->ofp_port == ofp_port) {
2538 return port;
2539 }
2540 }
2541 return NULL;
2542 }
2543
2544 static long long int
2545 ofport_get_usage(const struct ofproto *ofproto, ofp_port_t ofp_port)
2546 {
2547 struct ofport_usage *usage;
2548
2549 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2550 &ofproto->ofport_usage) {
2551 if (usage->ofp_port == ofp_port) {
2552 return usage->last_used;
2553 }
2554 }
2555 return 0;
2556 }
2557
2558 static void
2559 ofport_set_usage(struct ofproto *ofproto, ofp_port_t ofp_port,
2560 long long int last_used)
2561 {
2562 struct ofport_usage *usage;
2563 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2564 &ofproto->ofport_usage) {
2565 if (usage->ofp_port == ofp_port) {
2566 usage->last_used = last_used;
2567 return;
2568 }
2569 }
2570 ovs_assert(last_used == LLONG_MAX);
2571
2572 usage = xmalloc(sizeof *usage);
2573 usage->ofp_port = ofp_port;
2574 usage->last_used = last_used;
2575 hmap_insert(&ofproto->ofport_usage, &usage->hmap_node,
2576 hash_ofp_port(ofp_port));
2577 }
2578
2579 static void
2580 ofport_remove_usage(struct ofproto *ofproto, ofp_port_t ofp_port)
2581 {
2582 struct ofport_usage *usage;
2583 HMAP_FOR_EACH_IN_BUCKET (usage, hmap_node, hash_ofp_port(ofp_port),
2584 &ofproto->ofport_usage) {
2585 if (usage->ofp_port == ofp_port) {
2586 hmap_remove(&ofproto->ofport_usage, &usage->hmap_node);
2587 free(usage);
2588 break;
2589 }
2590 }
2591 }
2592
2593 int
2594 ofproto_port_get_stats(const struct ofport *port, struct netdev_stats *stats)
2595 {
2596 struct ofproto *ofproto = port->ofproto;
2597 int error;
2598
2599 if (ofproto->ofproto_class->port_get_stats) {
2600 error = ofproto->ofproto_class->port_get_stats(port, stats);
2601 } else {
2602 error = EOPNOTSUPP;
2603 }
2604
2605 return error;
2606 }
2607
2608 static int
2609 update_port(struct ofproto *ofproto, const char *name)
2610 {
2611 struct ofproto_port ofproto_port;
2612 struct ofputil_phy_port pp;
2613 struct netdev *netdev;
2614 struct ofport *port;
2615 int error = 0;
2616
2617 COVERAGE_INC(ofproto_update_port);
2618
2619 /* Fetch 'name''s location and properties from the datapath. */
2620 netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
2621 ? ofport_open(ofproto, &ofproto_port, &pp)
2622 : NULL);
2623
2624 if (netdev) {
2625 port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
2626 if (port && !strcmp(netdev_get_name(port->netdev), name)) {
2627 struct netdev *old_netdev = port->netdev;
2628
2629 /* 'name' hasn't changed location. Any properties changed? */
2630 bool port_changed = !ofport_equal(&port->pp, &pp);
2631 if (port_changed) {
2632 ofport_modified(port, &pp);
2633 }
2634
2635 update_mtu(ofproto, port);
2636
2637 /* Install the newly opened netdev in case it has changed.
2638 * Don't close the old netdev yet in case port_modified has to
2639 * remove a retained reference to it.*/
2640 port->netdev = netdev;
2641 port->change_seq = netdev_get_change_seq(netdev);
2642
2643 if (port->ofproto->ofproto_class->port_modified) {
2644 port->ofproto->ofproto_class->port_modified(port);
2645 }
2646
2647 /* Send status update, if any port property changed */
2648 if (port_changed) {
2649 connmgr_send_port_status(port->ofproto->connmgr, NULL,
2650 &port->pp, OFPPR_MODIFY);
2651 }
2652
2653 netdev_close(old_netdev);
2654 } else {
2655 /* If 'port' is nonnull then its name differs from 'name' and thus
2656 * we should delete it. If we think there's a port named 'name'
2657 * then its port number must be wrong now so delete it too. */
2658 if (port) {
2659 ofport_remove(port);
2660 }
2661 ofport_remove_with_name(ofproto, name);
2662 error = ofport_install(ofproto, netdev, &pp);
2663 }
2664 } else {
2665 /* Any port named 'name' is gone now. */
2666 ofport_remove_with_name(ofproto, name);
2667 }
2668 ofproto_port_destroy(&ofproto_port);
2669
2670 return error;
2671 }
2672
2673 static int
2674 init_ports(struct ofproto *p)
2675 {
2676 struct ofproto_port_dump dump;
2677 struct ofproto_port ofproto_port;
2678 struct shash_node *node, *next;
2679
2680 OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
2681 const char *name = ofproto_port.name;
2682
2683 if (shash_find(&p->port_by_name, name)) {
2684 VLOG_WARN_RL(&rl, "%s: ignoring duplicate device %s in datapath",
2685 p->name, name);
2686 } else {
2687 struct ofputil_phy_port pp;
2688 struct netdev *netdev;
2689
2690 /* Check if an OpenFlow port number had been requested. */
2691 node = shash_find(&init_ofp_ports, name);
2692 if (node) {
2693 const struct iface_hint *iface_hint = node->data;
2694 simap_put(&p->ofp_requests, name,
2695 ofp_to_u16(iface_hint->ofp_port));
2696 }
2697
2698 netdev = ofport_open(p, &ofproto_port, &pp);
2699 if (netdev) {
2700 ofport_install(p, netdev, &pp);
2701 if (ofp_to_u16(ofproto_port.ofp_port) < p->max_ports) {
2702 p->alloc_port_no = MAX(p->alloc_port_no,
2703 ofp_to_u16(ofproto_port.ofp_port));
2704 }
2705 }
2706 }
2707 }
2708
2709 SHASH_FOR_EACH_SAFE(node, next, &init_ofp_ports) {
2710 struct iface_hint *iface_hint = node->data;
2711
2712 if (!strcmp(iface_hint->br_name, p->name)) {
2713 free(iface_hint->br_name);
2714 free(iface_hint->br_type);
2715 free(iface_hint);
2716 shash_delete(&init_ofp_ports, node);
2717 }
2718 }
2719
2720 return 0;
2721 }
2722
2723 static bool
2724 ofport_is_internal_or_patch(const struct ofproto *p, const struct ofport *port)
2725 {
2726 return !strcmp(netdev_get_type(port->netdev),
2727 ofproto_port_open_type(p->type, "internal")) ||
2728 !strcmp(netdev_get_type(port->netdev),
2729 ofproto_port_open_type(p->type, "patch"));
2730 }
2731
2732 /* If 'port' is internal or patch and if the user didn't explicitly specify an
2733 * mtu through the database, we have to override it. */
2734 static bool
2735 ofport_is_mtu_overridden(const struct ofproto *p, const struct ofport *port)
2736 {
2737 return ofport_is_internal_or_patch(p, port)
2738 && !netdev_mtu_is_user_config(port->netdev);
2739 }
2740
2741 /* Find the minimum MTU of all non-overridden devices attached to 'p'.
2742 * Returns ETH_PAYLOAD_MAX or the minimum of the ports. */
2743 static int
2744 find_min_mtu(struct ofproto *p)
2745 {
2746 struct ofport *ofport;
2747 int mtu = 0;
2748
2749 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2750 struct netdev *netdev = ofport->netdev;
2751 int dev_mtu;
2752
2753 /* Skip any overridden port, since that's what we're trying to set. */
2754 if (ofport_is_mtu_overridden(p, ofport)) {
2755 continue;
2756 }
2757
2758 if (netdev_get_mtu(netdev, &dev_mtu)) {
2759 continue;
2760 }
2761 if (!mtu || dev_mtu < mtu) {
2762 mtu = dev_mtu;
2763 }
2764 }
2765
2766 return mtu ? mtu: ETH_PAYLOAD_MAX;
2767 }
2768
2769 /* Update MTU of all overridden devices on 'p' to the minimum of the
2770 * non-overridden ports in event of 'port' added or changed. */
2771 static void
2772 update_mtu(struct ofproto *p, struct ofport *port)
2773 {
2774 struct netdev *netdev = port->netdev;
2775 int dev_mtu;
2776
2777 if (netdev_get_mtu(netdev, &dev_mtu)) {
2778 port->mtu = 0;
2779 return;
2780 }
2781 if (ofport_is_mtu_overridden(p, port)) {
2782 if (dev_mtu > p->min_mtu) {
2783 if (!netdev_set_mtu(port->netdev, p->min_mtu)) {
2784 dev_mtu = p->min_mtu;
2785 }
2786 }
2787 port->mtu = dev_mtu;
2788 return;
2789 }
2790
2791 port->mtu = dev_mtu;
2792 /* For non-overridden port find new min mtu. */
2793
2794 update_mtu_ofproto(p);
2795 }
2796
2797 static void
2798 update_mtu_ofproto(struct ofproto *p)
2799 {
2800 struct ofport *ofport;
2801 int old_min = p->min_mtu;
2802
2803 p->min_mtu = find_min_mtu(p);
2804 if (p->min_mtu == old_min) {
2805 return;
2806 }
2807
2808 HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
2809 struct netdev *netdev = ofport->netdev;
2810
2811 if (ofport_is_mtu_overridden(p, ofport)) {
2812 if (!netdev_set_mtu(netdev, p->min_mtu)) {
2813 ofport->mtu = p->min_mtu;
2814 }
2815 }
2816 }
2817 }
2818 \f
2819 static void
2820 ofproto_rule_destroy__(struct rule *rule)
2821 OVS_NO_THREAD_SAFETY_ANALYSIS
2822 {
2823 cls_rule_destroy(CONST_CAST(struct cls_rule *, &rule->cr));
2824 rule_actions_destroy(rule_get_actions(rule));
2825 ovs_mutex_destroy(&rule->mutex);
2826 rule->ofproto->ofproto_class->rule_dealloc(rule);
2827 }
2828
2829 static void
2830 rule_destroy_cb(struct rule *rule)
2831 OVS_NO_THREAD_SAFETY_ANALYSIS
2832 {
2833 /* Send rule removed if needed. */
2834 if (rule->flags & OFPUTIL_FF_SEND_FLOW_REM
2835 && rule->removed_reason != OVS_OFPRR_NONE
2836 && !rule_is_hidden(rule)) {
2837 ofproto_rule_send_removed(rule);
2838 }
2839 rule->ofproto->ofproto_class->rule_destruct(rule);
2840 mf_vl_mff_unref(&rule->ofproto->vl_mff_map, rule->match_tlv_bitmap);
2841 mf_vl_mff_unref(&rule->ofproto->vl_mff_map, rule->ofpacts_tlv_bitmap);
2842 ofproto_rule_destroy__(rule);
2843 }
2844
2845 void
2846 ofproto_rule_ref(struct rule *rule)
2847 {
2848 if (rule) {
2849 ovs_refcount_ref(&rule->ref_count);
2850 }
2851 }
2852
2853 bool
2854 ofproto_rule_try_ref(struct rule *rule)
2855 {
2856 if (rule) {
2857 return ovs_refcount_try_ref_rcu(&rule->ref_count);
2858 }
2859 return false;
2860 }
2861
2862 /* Decrements 'rule''s ref_count and schedules 'rule' to be destroyed if the
2863 * ref_count reaches 0.
2864 *
2865 * Use of RCU allows short term use (between RCU quiescent periods) without
2866 * keeping a reference. A reference must be taken if the rule needs to
2867 * stay around accross the RCU quiescent periods. */
2868 void
2869 ofproto_rule_unref(struct rule *rule)
2870 {
2871 if (rule && ovs_refcount_unref_relaxed(&rule->ref_count) == 1) {
2872 ovs_assert(rule->state != RULE_INSERTED);
2873 ovsrcu_postpone(rule_destroy_cb, rule);
2874 }
2875 }
2876
2877 static void
2878 remove_rule_rcu__(struct rule *rule)
2879 OVS_REQUIRES(ofproto_mutex)
2880 {
2881 struct ofproto *ofproto = rule->ofproto;
2882 struct oftable *table = &ofproto->tables[rule->table_id];
2883
2884 ovs_assert(!cls_rule_visible_in_version(&rule->cr, OVS_VERSION_MAX));
2885 if (!classifier_remove(&table->cls, &rule->cr)) {
2886 OVS_NOT_REACHED();
2887 }
2888 if (ofproto->ofproto_class->rule_delete) {
2889 ofproto->ofproto_class->rule_delete(rule);
2890 }
2891 ofproto_rule_unref(rule);
2892 }
2893
2894 static void
2895 remove_rule_rcu(struct rule *rule)
2896 OVS_EXCLUDED(ofproto_mutex)
2897 {
2898 ovs_mutex_lock(&ofproto_mutex);
2899 remove_rule_rcu__(rule);
2900 ovs_mutex_unlock(&ofproto_mutex);
2901 }
2902
2903 /* Removes and deletes rules from a NULL-terminated array of rule pointers. */
2904 static void
2905 remove_rules_rcu(struct rule **rules)
2906 OVS_EXCLUDED(ofproto_mutex)
2907 {
2908 struct rule **orig_rules = rules;
2909
2910 if (*rules) {
2911 struct ofproto *ofproto = rules[0]->ofproto;
2912 unsigned long tables[BITMAP_N_LONGS(256)];
2913 struct rule *rule;
2914 size_t table_id;
2915
2916 memset(tables, 0, sizeof tables);
2917
2918 ovs_mutex_lock(&ofproto_mutex);
2919 while ((rule = *rules++)) {
2920 /* Defer once for each new table. This defers the subtable cleanup
2921 * until later, so that when removing large number of flows the
2922 * operation is faster. */
2923 if (!bitmap_is_set(tables, rule->table_id)) {
2924 struct classifier *cls = &ofproto->tables[rule->table_id].cls;
2925
2926 bitmap_set1(tables, rule->table_id);
2927 classifier_defer(cls);
2928 }
2929 remove_rule_rcu__(rule);
2930 }
2931
2932 BITMAP_FOR_EACH_1(table_id, 256, tables) {
2933 struct classifier *cls = &ofproto->tables[table_id].cls;
2934
2935 classifier_publish(cls);
2936 }
2937 ovs_mutex_unlock(&ofproto_mutex);
2938 }
2939
2940 free(orig_rules);
2941 }
2942
2943 void
2944 ofproto_group_ref(struct ofgroup *group)
2945 {
2946 if (group) {
2947 ovs_refcount_ref(&group->ref_count);
2948 }
2949 }
2950
2951 bool
2952 ofproto_group_try_ref(struct ofgroup *group)
2953 {
2954 if (group) {
2955 return ovs_refcount_try_ref_rcu(&group->ref_count);
2956 }
2957 return false;
2958 }
2959
2960 static void
2961 group_destroy_cb(struct ofgroup *group)
2962 {
2963 group->ofproto->ofproto_class->group_destruct(group);
2964 ofputil_group_properties_destroy(CONST_CAST(struct ofputil_group_props *,
2965 &group->props));
2966 ofputil_bucket_list_destroy(CONST_CAST(struct ovs_list *,
2967 &group->buckets));
2968 group->ofproto->ofproto_class->group_dealloc(group);
2969 }
2970
2971 void
2972 ofproto_group_unref(struct ofgroup *group)
2973 OVS_NO_THREAD_SAFETY_ANALYSIS
2974 {
2975 if (group && ovs_refcount_unref_relaxed(&group->ref_count) == 1) {
2976 ovs_assert(rule_collection_n(&group->rules) == 0);
2977 ovsrcu_postpone(group_destroy_cb, group);
2978 }
2979 }
2980
2981 static void
2982 remove_group_rcu__(struct ofgroup *group)
2983 OVS_REQUIRES(ofproto_mutex)
2984 {
2985 struct ofproto *ofproto = group->ofproto;
2986
2987 ovs_assert(!versions_visible_in_version(&group->versions, OVS_VERSION_MAX));
2988
2989 cmap_remove(&ofproto->groups, &group->cmap_node,
2990 hash_int(group->group_id, 0));
2991 ofproto_group_unref(group);
2992 }
2993
2994 static void
2995 remove_group_rcu(struct ofgroup *group)
2996 OVS_EXCLUDED(ofproto_mutex)
2997 {
2998 ovs_mutex_lock(&ofproto_mutex);
2999 remove_group_rcu__(group);
3000 ovs_mutex_unlock(&ofproto_mutex);
3001 }
3002
3003 /* Removes and deletes groups from a NULL-terminated array of group
3004 * pointers. */
3005 static void
3006 remove_groups_rcu(struct ofgroup **groups)
3007 OVS_EXCLUDED(ofproto_mutex)
3008 {
3009 ovs_mutex_lock(&ofproto_mutex);
3010 for (struct ofgroup **g = groups; *g; g++) {
3011 remove_group_rcu__(*g);
3012 }
3013 ovs_mutex_unlock(&ofproto_mutex);
3014 free(groups);
3015 }
3016
3017 static bool ofproto_fix_meter_action(const struct ofproto *,
3018 struct ofpact_meter *);
3019
3020 /* Creates and returns a new 'struct rule_actions', whose actions are a copy
3021 * of from the 'ofpacts_len' bytes of 'ofpacts'. */
3022 const struct rule_actions *
3023 rule_actions_create(const struct ofpact *ofpacts, size_t ofpacts_len)
3024 {
3025 struct rule_actions *actions;
3026
3027 actions = xmalloc(sizeof *actions + ofpacts_len);
3028 actions->ofpacts_len = ofpacts_len;
3029 memcpy(actions->ofpacts, ofpacts, ofpacts_len);
3030 actions->has_meter = ofpacts_get_meter(ofpacts, ofpacts_len) != 0;
3031 actions->has_groups =
3032 (ofpact_find_type_flattened(ofpacts, OFPACT_GROUP,
3033 ofpact_end(ofpacts, ofpacts_len))
3034 != NULL);
3035 actions->has_learn_with_delete = (next_learn_with_delete(actions, NULL)
3036 != NULL);
3037
3038 return actions;
3039 }
3040
3041 /* Free the actions after the RCU quiescent period is reached. */
3042 void
3043 rule_actions_destroy(const struct rule_actions *actions)
3044 {
3045 if (actions) {
3046 ovsrcu_postpone(free, CONST_CAST(struct rule_actions *, actions));
3047 }
3048 }
3049
3050 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
3051 * that outputs to 'port' (output to OFPP_FLOOD and OFPP_ALL doesn't count). */
3052 bool
3053 ofproto_rule_has_out_port(const struct rule *rule, ofp_port_t port)
3054 OVS_REQUIRES(ofproto_mutex)
3055 {
3056 if (port == OFPP_ANY) {
3057 return true;
3058 } else {
3059 const struct rule_actions *actions = rule_get_actions(rule);
3060 return ofpacts_output_to_port(actions->ofpacts,
3061 actions->ofpacts_len, port);
3062 }
3063 }
3064
3065 /* Returns true if 'rule' has group and equals group_id. */
3066 static bool
3067 ofproto_rule_has_out_group(const struct rule *rule, uint32_t group_id)
3068 OVS_REQUIRES(ofproto_mutex)
3069 {
3070 if (group_id == OFPG_ANY) {
3071 return true;
3072 } else {
3073 const struct rule_actions *actions = rule_get_actions(rule);
3074 return ofpacts_output_to_group(actions->ofpacts,
3075 actions->ofpacts_len, group_id);
3076 }
3077 }
3078
3079 static bool
3080 rule_is_readonly(const struct rule *rule)
3081 {
3082 const struct oftable *table = &rule->ofproto->tables[rule->table_id];
3083 return (table->flags & OFTABLE_READONLY) != 0;
3084 }
3085 \f
3086 static uint32_t
3087 hash_learned_cookie(ovs_be64 cookie_, uint8_t table_id)
3088 {
3089 uint64_t cookie = (OVS_FORCE uint64_t) cookie_;
3090 return hash_3words(cookie, cookie >> 32, table_id);
3091 }
3092
3093 static void
3094 learned_cookies_update_one__(struct ofproto *ofproto,
3095 const struct ofpact_learn *learn,
3096 int delta, struct ovs_list *dead_cookies)
3097 OVS_REQUIRES(ofproto_mutex)
3098 {
3099 uint32_t hash = hash_learned_cookie(learn->cookie, learn->table_id);
3100 struct learned_cookie *c;
3101
3102 HMAP_FOR_EACH_WITH_HASH (c, u.hmap_node, hash, &ofproto->learned_cookies) {
3103 if (c->cookie == learn->cookie && c->table_id == learn->table_id) {
3104 c->n += delta;
3105 ovs_assert(c->n >= 0);
3106
3107 if (!c->n) {
3108 hmap_remove(&ofproto->learned_cookies, &c->u.hmap_node);
3109 ovs_list_push_back(dead_cookies, &c->u.list_node);
3110 }
3111
3112 return;
3113 }
3114 }
3115
3116 ovs_assert(delta > 0);
3117 c = xmalloc(sizeof *c);
3118 hmap_insert(&ofproto->learned_cookies, &c->u.hmap_node, hash);
3119 c->cookie = learn->cookie;
3120 c->table_id = learn->table_id;
3121 c->n = delta;
3122 }
3123
3124 static const struct ofpact_learn *
3125 next_learn_with_delete(const struct rule_actions *actions,
3126 const struct ofpact_learn *start)
3127 {
3128 const struct ofpact *pos;
3129
3130 for (pos = start ? ofpact_next(&start->ofpact) : actions->ofpacts;
3131 pos < ofpact_end(actions->ofpacts, actions->ofpacts_len);
3132 pos = ofpact_next(pos)) {
3133 if (pos->type == OFPACT_LEARN) {
3134 const struct ofpact_learn *learn = ofpact_get_LEARN(pos);
3135 if (learn->flags & NX_LEARN_F_DELETE_LEARNED) {
3136 return learn;
3137 }
3138 }
3139 }
3140
3141 return NULL;
3142 }
3143
3144 static void
3145 learned_cookies_update__(struct ofproto *ofproto,
3146 const struct rule_actions *actions,
3147 int delta, struct ovs_list *dead_cookies)
3148 OVS_REQUIRES(ofproto_mutex)
3149 {
3150 if (actions->has_learn_with_delete) {
3151 const struct ofpact_learn *learn;
3152
3153 for (learn = next_learn_with_delete(actions, NULL); learn;
3154 learn = next_learn_with_delete(actions, learn)) {
3155 learned_cookies_update_one__(ofproto, learn, delta, dead_cookies);
3156 }
3157 }
3158 }
3159
3160 static void
3161 learned_cookies_inc(struct ofproto *ofproto,
3162 const struct rule_actions *actions)
3163 OVS_REQUIRES(ofproto_mutex)
3164 {
3165 learned_cookies_update__(ofproto, actions, +1, NULL);
3166 }
3167
3168 static void
3169 learned_cookies_dec(struct ofproto *ofproto,
3170 const struct rule_actions *actions,
3171 struct ovs_list *dead_cookies)
3172 OVS_REQUIRES(ofproto_mutex)
3173 {
3174 learned_cookies_update__(ofproto, actions, -1, dead_cookies);
3175 }
3176
3177 static void
3178 learned_cookies_flush(struct ofproto *ofproto, struct ovs_list *dead_cookies)
3179 OVS_REQUIRES(ofproto_mutex)
3180 {
3181 struct learned_cookie *c;
3182
3183 LIST_FOR_EACH_POP (c, u.list_node, dead_cookies) {
3184 struct rule_criteria criteria;
3185 struct rule_collection rules;
3186 struct match match;
3187
3188 match_init_catchall(&match);
3189 rule_criteria_init(&criteria, c->table_id, &match, 0, OVS_VERSION_MAX,
3190 c->cookie, OVS_BE64_MAX, OFPP_ANY, OFPG_ANY);
3191 rule_criteria_require_rw(&criteria, false);
3192 collect_rules_loose(ofproto, &criteria, &rules);
3193 rule_criteria_destroy(&criteria);
3194 delete_flows__(&rules, OFPRR_DELETE, NULL);
3195
3196 free(c);
3197 }
3198 }
3199 \f
3200 static enum ofperr
3201 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
3202 {
3203 ofconn_send_reply(ofconn, make_echo_reply(oh));
3204 return 0;
3205 }
3206
3207 static void
3208 query_tables(struct ofproto *ofproto,
3209 struct ofputil_table_features **featuresp,
3210 struct ofputil_table_stats **statsp)
3211 {
3212 struct mf_bitmap rw_fields = oxm_writable_fields();
3213 struct mf_bitmap match = oxm_matchable_fields();
3214 struct mf_bitmap mask = oxm_maskable_fields();
3215
3216 struct ofputil_table_features *features;
3217 struct ofputil_table_stats *stats;
3218 int i;
3219
3220 features = *featuresp = xcalloc(ofproto->n_tables, sizeof *features);
3221 for (i = 0; i < ofproto->n_tables; i++) {
3222 struct ofputil_table_features *f = &features[i];
3223
3224 f->table_id = i;
3225 sprintf(f->name, "table%d", i);
3226 f->metadata_match = OVS_BE64_MAX;
3227 f->metadata_write = OVS_BE64_MAX;
3228 atomic_read_relaxed(&ofproto->tables[i].miss_config, &f->miss_config);
3229 f->max_entries = 1000000;
3230
3231 bool more_tables = false;
3232 for (int j = i + 1; j < ofproto->n_tables; j++) {
3233 if (!(ofproto->tables[j].flags & OFTABLE_HIDDEN)) {
3234 bitmap_set1(f->nonmiss.next, j);
3235 more_tables = true;
3236 }
3237 }
3238 f->nonmiss.instructions = (1u << N_OVS_INSTRUCTIONS) - 1;
3239 if (!more_tables) {
3240 f->nonmiss.instructions &= ~(1u << OVSINST_OFPIT11_GOTO_TABLE);
3241 }
3242 f->nonmiss.write.ofpacts = (UINT64_C(1) << N_OFPACTS) - 1;
3243 f->nonmiss.write.set_fields = rw_fields;
3244 f->nonmiss.apply = f->nonmiss.write;
3245 f->miss = f->nonmiss;
3246
3247 f->match = match;
3248 f->mask = mask;
3249 f->wildcard = match;
3250 }
3251
3252 if (statsp) {
3253 stats = *statsp = xcalloc(ofproto->n_tables, sizeof *stats);
3254 for (i = 0; i < ofproto->n_tables; i++) {
3255 struct ofputil_table_stats *s = &stats[i];
3256
3257 s->table_id = i;
3258 s->active_count = ofproto->tables[i].n_flows;
3259 if (i == 0) {
3260 s->active_count -= connmgr_count_hidden_rules(
3261 ofproto->connmgr);
3262 }
3263 }
3264 } else {
3265 stats = NULL;
3266 }
3267
3268 ofproto->ofproto_class->query_tables(ofproto, features, stats);
3269
3270 for (i = 0; i < ofproto->n_tables; i++) {
3271 const struct oftable *table = &ofproto->tables[i];
3272 struct ofputil_table_features *f = &features[i];
3273
3274 if (table->name) {
3275 ovs_strzcpy(f->name, table->name, sizeof f->name);
3276 }
3277
3278 if (table->max_flows < f->max_entries) {
3279 f->max_entries = table->max_flows;
3280 }
3281 }
3282 }
3283
3284 static void
3285 query_switch_features(struct ofproto *ofproto,
3286 bool *arp_match_ip, uint64_t *ofpacts)
3287 {
3288 struct ofputil_table_features *features, *f;
3289
3290 *arp_match_ip = false;
3291 *ofpacts = 0;
3292
3293 query_tables(ofproto, &features, NULL);
3294 for (f = features; f < &features[ofproto->n_tables]; f++) {
3295 *ofpacts |= f->nonmiss.apply.ofpacts | f->miss.apply.ofpacts;
3296 if (bitmap_is_set(f->match.bm, MFF_ARP_SPA) ||
3297 bitmap_is_set(f->match.bm, MFF_ARP_TPA)) {
3298 *arp_match_ip = true;
3299 }
3300 }
3301 free(features);
3302
3303 /* Sanity check. */
3304 ovs_assert(*ofpacts & (UINT64_C(1) << OFPACT_OUTPUT));
3305 }
3306
3307 static enum ofperr
3308 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
3309 {
3310 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3311 struct ofputil_switch_features features;
3312 struct ofport *port;
3313 bool arp_match_ip;
3314 struct ofpbuf *b;
3315
3316 query_switch_features(ofproto, &arp_match_ip, &features.ofpacts);
3317
3318 features.datapath_id = ofproto->datapath_id;
3319 features.n_buffers = 0;
3320 features.n_tables = ofproto_get_n_visible_tables(ofproto);
3321 features.capabilities = (OFPUTIL_C_FLOW_STATS | OFPUTIL_C_TABLE_STATS |
3322 OFPUTIL_C_PORT_STATS | OFPUTIL_C_QUEUE_STATS |
3323 OFPUTIL_C_GROUP_STATS | OFPUTIL_C_BUNDLES);
3324 if (arp_match_ip) {
3325 features.capabilities |= OFPUTIL_C_ARP_MATCH_IP;
3326 }
3327 /* FIXME: Fill in proper features.auxiliary_id for auxiliary connections */
3328 features.auxiliary_id = 0;
3329 b = ofputil_encode_switch_features(&features, ofconn_get_protocol(ofconn),
3330 oh->xid);
3331 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3332 ofputil_put_switch_features_port(&port->pp, b);
3333 }
3334
3335 ofconn_send_reply(ofconn, b);
3336 return 0;
3337 }
3338
3339 static enum ofperr
3340 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
3341 {
3342 struct ofputil_switch_config config;
3343 config.frag = ofconn_get_ofproto(ofconn)->frag_handling;
3344 config.invalid_ttl_to_controller
3345 = ofconn_get_invalid_ttl_to_controller(ofconn);
3346 config.miss_send_len = ofconn_get_miss_send_len(ofconn);
3347
3348 ofconn_send_reply(ofconn, ofputil_encode_get_config_reply(oh, &config));
3349
3350 return 0;
3351 }
3352
3353 static enum ofperr
3354 handle_set_config(struct ofconn *ofconn, const struct ofp_header *oh)
3355 {
3356 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3357 struct ofputil_switch_config config;
3358 enum ofperr error;
3359
3360 error = ofputil_decode_set_config(oh, &config);
3361 if (error) {
3362 return error;
3363 }
3364
3365 if (ofconn_get_type(ofconn) != OFCONN_PRIMARY
3366 || ofconn_get_role(ofconn) != OFPCR12_ROLE_SLAVE) {
3367 enum ofputil_frag_handling cur = ofproto->frag_handling;
3368 enum ofputil_frag_handling next = config.frag;
3369
3370 if (cur != next) {
3371 if (ofproto->ofproto_class->set_frag_handling(ofproto, next)) {
3372 ofproto->frag_handling = next;
3373 } else {
3374 VLOG_WARN_RL(&rl, "%s: unsupported fragment handling mode %s",
3375 ofproto->name,
3376 ofputil_frag_handling_to_string(next));
3377 }
3378 }
3379 }
3380
3381 if (config.invalid_ttl_to_controller >= 0) {
3382 ofconn_set_invalid_ttl_to_controller(ofconn,
3383 config.invalid_ttl_to_controller);
3384 }
3385
3386 ofconn_set_miss_send_len(ofconn, config.miss_send_len);
3387
3388 return 0;
3389 }
3390
3391 /* Checks whether 'ofconn' is a slave controller. If so, returns an OpenFlow
3392 * error message code for the caller to propagate upward. Otherwise, returns
3393 * 0.
3394 *
3395 * The log message mentions 'msg_type'. */
3396 static enum ofperr
3397 reject_slave_controller(struct ofconn *ofconn)
3398 {
3399 if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
3400 && ofconn_get_role(ofconn) == OFPCR12_ROLE_SLAVE) {
3401 return OFPERR_OFPBRC_IS_SLAVE;
3402 } else {
3403 return 0;
3404 }
3405 }
3406
3407 /* Checks that the 'ofpacts_len' bytes of action in 'ofpacts' are appropriate
3408 * for 'ofproto':
3409 *
3410 * - If they use a meter, then 'ofproto' has that meter configured.
3411 * Updates the meter action with ofproto's datapath's provider_meter_id.
3412 *
3413 * - If they use any groups, then 'ofproto' has that group configured.
3414 *
3415 * Returns 0 if successful, otherwise an OpenFlow error. Caller must hold
3416 * 'ofproto_mutex' for the result to be valid also after this function
3417 * returns. */
3418 enum ofperr
3419 ofproto_check_ofpacts(struct ofproto *ofproto,
3420 const struct ofpact ofpacts[], size_t ofpacts_len)
3421 OVS_REQUIRES(ofproto_mutex)
3422 {
3423 const struct ofpact *a;
3424
3425 OFPACT_FOR_EACH_FLATTENED (a, ofpacts, ofpacts_len) {
3426 if (a->type == OFPACT_METER &&
3427 !ofproto_fix_meter_action(ofproto, ofpact_get_METER(a))) {
3428 return OFPERR_OFPMMFC_INVALID_METER;
3429 }
3430
3431 if (a->type == OFPACT_GROUP
3432 && !ofproto_group_exists(ofproto, ofpact_get_GROUP(a)->group_id)) {
3433 return OFPERR_OFPBAC_BAD_OUT_GROUP;
3434 }
3435 }
3436
3437 return 0;
3438 }
3439
3440 void
3441 ofproto_packet_out_uninit(struct ofproto_packet_out *opo)
3442 {
3443 dp_packet_delete(opo->packet);
3444 opo->packet = NULL;
3445 free(opo->flow);
3446 opo->flow = NULL;
3447 free(opo->ofpacts);
3448 opo->ofpacts = NULL;
3449 opo->ofpacts_len = 0;
3450 ovs_assert(!opo->aux);
3451 }
3452
3453 /* Takes ownership of po->ofpacts, which must have been malloc'ed. */
3454 static enum ofperr
3455 ofproto_packet_out_init(struct ofproto *ofproto,
3456 struct ofconn *ofconn,
3457 struct ofproto_packet_out *opo,
3458 const struct ofputil_packet_out *po)
3459 {
3460 enum ofperr error;
3461 struct match match;
3462 struct {
3463 struct miniflow mf;
3464 uint64_t buf[FLOW_U64S];
3465 } m;
3466
3467 uint16_t in_port = ofp_to_u16(po->flow_metadata.flow.in_port.ofp_port);
3468 if (in_port >= ofproto->max_ports && in_port < ofp_to_u16(OFPP_MAX)) {
3469 return OFPERR_OFPBRC_BAD_PORT;
3470 }
3471
3472 /* Get payload. */
3473 if (po->buffer_id != UINT32_MAX) {
3474 return OFPERR_OFPBRC_BUFFER_UNKNOWN;
3475 }
3476
3477 /* Ensure that the L3 header is 32-bit aligned. */
3478 opo->packet = dp_packet_clone_data_with_headroom(po->packet,
3479 po->packet_len, 2);
3480 /* Take the received packet_tpye as packet_type of the packet. */
3481 opo->packet->packet_type = po->flow_metadata.flow.packet_type;
3482
3483 /* Store struct flow. */
3484 opo->flow = xmalloc(sizeof *opo->flow);
3485 *opo->flow = po->flow_metadata.flow;
3486 miniflow_extract(opo->packet, &m.mf);
3487 flow_union_with_miniflow(opo->flow, &m.mf);
3488
3489 /* Check actions like for flow mods. We pass a 'table_id' of 0 to
3490 * ofproto_check_consistency(), which isn't strictly correct because these
3491 * actions aren't in any table. This is OK as 'table_id' is only used to
3492 * check instructions (e.g., goto-table), which can't appear on the action
3493 * list of a packet-out. */
3494 match_wc_init(&match, opo->flow);
3495 error = ofpacts_check_consistency(po->ofpacts, po->ofpacts_len, &match,
3496 u16_to_ofp(ofproto->max_ports), 0,
3497 ofproto->n_tables,
3498 ofconn_get_protocol(ofconn));
3499 if (error) {
3500 dp_packet_delete(opo->packet);
3501 free(opo->flow);
3502 return error;
3503 }
3504
3505 opo->ofpacts = po->ofpacts;
3506 opo->ofpacts_len = po->ofpacts_len;
3507
3508 opo->aux = NULL;
3509 return 0;
3510 }
3511
3512 static enum ofperr
3513 ofproto_packet_out_start(struct ofproto *ofproto,
3514 struct ofproto_packet_out *opo)
3515 OVS_REQUIRES(ofproto_mutex)
3516 {
3517 enum ofperr error;
3518
3519 error = ofproto_check_ofpacts(ofproto, opo->ofpacts, opo->ofpacts_len);
3520 if (error) {
3521 return error;
3522 }
3523
3524 return ofproto->ofproto_class->packet_xlate(ofproto, opo);
3525 }
3526
3527 static void
3528 ofproto_packet_out_revert(struct ofproto *ofproto,
3529 struct ofproto_packet_out *opo)
3530 OVS_REQUIRES(ofproto_mutex)
3531 {
3532 ofproto->ofproto_class->packet_xlate_revert(ofproto, opo);
3533 }
3534
3535 static void
3536 ofproto_packet_out_finish(struct ofproto *ofproto,
3537 struct ofproto_packet_out *opo)
3538 OVS_REQUIRES(ofproto_mutex)
3539 {
3540 ofproto->ofproto_class->packet_execute(ofproto, opo);
3541 }
3542
3543 static enum ofperr
3544 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
3545 OVS_EXCLUDED(ofproto_mutex)
3546 {
3547 struct ofproto *p = ofconn_get_ofproto(ofconn);
3548 struct ofputil_packet_out po;
3549 struct ofproto_packet_out opo;
3550 uint64_t ofpacts_stub[1024 / 8];
3551 struct ofpbuf ofpacts;
3552 enum ofperr error;
3553
3554 COVERAGE_INC(ofproto_packet_out);
3555
3556 error = reject_slave_controller(ofconn);
3557 if (error) {
3558 return error;
3559 }
3560
3561 /* Decode message. */
3562 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
3563 error = ofputil_decode_packet_out(&po, oh, ofproto_get_tun_tab(p),
3564 &ofpacts);
3565 if (error) {
3566 ofpbuf_uninit(&ofpacts);
3567 return error;
3568 }
3569
3570 po.ofpacts = ofpbuf_steal_data(&ofpacts); /* Move to heap. */
3571 error = ofproto_packet_out_init(p, ofconn, &opo, &po);
3572 if (error) {
3573 free(po.ofpacts);
3574 return error;
3575 }
3576
3577 ovs_mutex_lock(&ofproto_mutex);
3578 opo.version = p->tables_version;
3579 error = ofproto_packet_out_start(p, &opo);
3580 if (!error) {
3581 ofproto_packet_out_finish(p, &opo);
3582 }
3583 ovs_mutex_unlock(&ofproto_mutex);
3584
3585 ofproto_packet_out_uninit(&opo);
3586 return error;
3587 }
3588
3589 static enum ofperr
3590 handle_nxt_resume(struct ofconn *ofconn, const struct ofp_header *oh)
3591 {
3592 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3593 struct ofputil_packet_in_private pin;
3594 enum ofperr error;
3595
3596 error = ofputil_decode_packet_in_private(oh, false,
3597 ofproto_get_tun_tab(ofproto),
3598 &ofproto->vl_mff_map, &pin, NULL,
3599 NULL);
3600 if (error) {
3601 return error;
3602 }
3603
3604 error = (ofproto->ofproto_class->nxt_resume
3605 ? ofproto->ofproto_class->nxt_resume(ofproto, &pin)
3606 : OFPERR_NXR_NOT_SUPPORTED);
3607
3608 ofputil_packet_in_private_destroy(&pin);
3609
3610 return error;
3611 }
3612
3613 static void
3614 update_port_config(struct ofconn *ofconn, struct ofport *port,
3615 enum ofputil_port_config config,
3616 enum ofputil_port_config mask)
3617 {
3618 enum ofputil_port_config toggle = (config ^ port->pp.config) & mask;
3619
3620 if (toggle & OFPUTIL_PC_PORT_DOWN
3621 && (config & OFPUTIL_PC_PORT_DOWN
3622 ? netdev_turn_flags_off(port->netdev, NETDEV_UP, NULL)
3623 : netdev_turn_flags_on(port->netdev, NETDEV_UP, NULL))) {
3624 /* We tried to bring the port up or down, but it failed, so don't
3625 * update the "down" bit. */
3626 toggle &= ~OFPUTIL_PC_PORT_DOWN;
3627 }
3628
3629 if (toggle) {
3630 enum ofputil_port_config old_config = port->pp.config;
3631 port->pp.config ^= toggle;
3632 port->ofproto->ofproto_class->port_reconfigured(port, old_config);
3633 connmgr_send_port_status(port->ofproto->connmgr, ofconn, &port->pp,
3634 OFPPR_MODIFY);
3635 }
3636 }
3637
3638 static enum ofperr
3639 port_mod_start(struct ofconn *ofconn, struct ofputil_port_mod *pm,
3640 struct ofport **port)
3641 {
3642 struct ofproto *p = ofconn_get_ofproto(ofconn);
3643
3644 *port = ofproto_get_port(p, pm->port_no);
3645 if (!*port) {
3646 return OFPERR_OFPPMFC_BAD_PORT;
3647 }
3648 if (!eth_addr_equals((*port)->pp.hw_addr, pm->hw_addr) ||
3649 !eth_addr64_equals((*port)->pp.hw_addr64, pm->hw_addr64)) {
3650 return OFPERR_OFPPMFC_BAD_HW_ADDR;
3651 }
3652 return 0;
3653 }
3654
3655 static void
3656 port_mod_finish(struct ofconn *ofconn, struct ofputil_port_mod *pm,
3657 struct ofport *port)
3658 {
3659 update_port_config(ofconn, port, pm->config, pm->mask);
3660 if (pm->advertise) {
3661 netdev_set_advertisements(port->netdev, pm->advertise);
3662 }
3663 }
3664
3665 static enum ofperr
3666 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
3667 {
3668 struct ofputil_port_mod pm;
3669 struct ofport *port;
3670 enum ofperr error;
3671
3672 error = reject_slave_controller(ofconn);
3673 if (error) {
3674 return error;
3675 }
3676
3677 error = ofputil_decode_port_mod(oh, &pm, false);
3678 if (error) {
3679 return error;
3680 }
3681
3682 error = port_mod_start(ofconn, &pm, &port);
3683 if (!error) {
3684 port_mod_finish(ofconn, &pm, port);
3685 }
3686 return error;
3687 }
3688
3689 static enum ofperr
3690 handle_desc_stats_request(struct ofconn *ofconn,
3691 const struct ofp_header *request)
3692 {
3693 static const char *default_mfr_desc = "Nicira, Inc.";
3694 static const char *default_hw_desc = "Open vSwitch";
3695 static const char *default_sw_desc = VERSION;
3696 static const char *default_serial_desc = "None";
3697 static const char *default_dp_desc = "None";
3698
3699 struct ofproto *p = ofconn_get_ofproto(ofconn);
3700 struct ofp_desc_stats *ods;
3701 struct ofpbuf *msg;
3702
3703 msg = ofpraw_alloc_stats_reply(request, 0);
3704 ods = ofpbuf_put_zeros(msg, sizeof *ods);
3705 ovs_strlcpy(ods->mfr_desc, p->mfr_desc ? p->mfr_desc : default_mfr_desc,
3706 sizeof ods->mfr_desc);
3707 ovs_strlcpy(ods->hw_desc, p->hw_desc ? p->hw_desc : default_hw_desc,
3708 sizeof ods->hw_desc);
3709 ovs_strlcpy(ods->sw_desc, p->sw_desc ? p->sw_desc : default_sw_desc,
3710 sizeof ods->sw_desc);
3711 ovs_strlcpy(ods->serial_num,
3712 p->serial_desc ? p->serial_desc : default_serial_desc,
3713 sizeof ods->serial_num);
3714 ovs_strlcpy(ods->dp_desc, p->dp_desc ? p->dp_desc : default_dp_desc,
3715 sizeof ods->dp_desc);
3716 ofconn_send_reply(ofconn, msg);
3717
3718 return 0;
3719 }
3720
3721 static enum ofperr
3722 handle_table_stats_request(struct ofconn *ofconn,
3723 const struct ofp_header *request)
3724 {
3725 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3726 struct ofputil_table_features *features;
3727 struct ofputil_table_stats *stats;
3728 struct ofpbuf *reply;
3729 size_t i;
3730
3731 query_tables(ofproto, &features, &stats);
3732
3733 reply = ofputil_encode_table_stats_reply(request);
3734 for (i = 0; i < ofproto->n_tables; i++) {
3735 if (!(ofproto->tables[i].flags & OFTABLE_HIDDEN)) {
3736 ofputil_append_table_stats_reply(reply, &stats[i], &features[i]);
3737 }
3738 }
3739 ofconn_send_reply(ofconn, reply);
3740
3741 free(features);
3742 free(stats);
3743
3744 return 0;
3745 }
3746
3747 static enum ofperr
3748 handle_table_features_request(struct ofconn *ofconn,
3749 const struct ofp_header *request)
3750 {
3751 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3752 struct ofpbuf msg = ofpbuf_const_initializer(request,
3753 ntohs(request->length));
3754 ofpraw_pull_assert(&msg);
3755 if (msg.size || ofpmp_more(request)) {
3756 return OFPERR_OFPTFFC_EPERM;
3757 }
3758
3759 struct ofputil_table_features *features;
3760 query_tables(ofproto, &features, NULL);
3761
3762 struct ovs_list replies;
3763 ofpmp_init(&replies, request);
3764 for (size_t i = 0; i < ofproto->n_tables; i++) {
3765 if (!(ofproto->tables[i].flags & OFTABLE_HIDDEN)) {
3766 ofputil_append_table_features_reply(&features[i], &replies);
3767 }
3768 }
3769 ofconn_send_replies(ofconn, &replies);
3770
3771 free(features);
3772
3773 return 0;
3774 }
3775
3776 /* Returns the vacancy of 'oftable', a number that ranges from 0 (if the table
3777 * is full) to 100 (if the table is empty).
3778 *
3779 * A table without a limit on flows is considered to be empty. */
3780 static uint8_t
3781 oftable_vacancy(const struct oftable *t)
3782 {
3783 return (!t->max_flows ? 100
3784 : t->n_flows >= t->max_flows ? 0
3785 : (t->max_flows - t->n_flows) * 100.0 / t->max_flows);
3786 }
3787
3788 static void
3789 query_table_desc__(struct ofputil_table_desc *td,
3790 struct ofproto *ofproto, uint8_t table_id)
3791 {
3792 const struct oftable *t = &ofproto->tables[table_id];
3793
3794 td->table_id = table_id;
3795 td->eviction = (t->eviction & EVICTION_OPENFLOW
3796 ? OFPUTIL_TABLE_EVICTION_ON
3797 : OFPUTIL_TABLE_EVICTION_OFF);
3798 td->eviction_flags = OFPROTO_EVICTION_FLAGS;
3799 td->vacancy = (t->vacancy_event
3800 ? OFPUTIL_TABLE_VACANCY_ON
3801 : OFPUTIL_TABLE_VACANCY_OFF);
3802 td->table_vacancy.vacancy_down = t->vacancy_down;
3803 td->table_vacancy.vacancy_up = t->vacancy_up;
3804 td->table_vacancy.vacancy = oftable_vacancy(t);
3805 }
3806
3807 /* This function queries the database for dumping table-desc. */
3808 static void
3809 query_tables_desc(struct ofproto *ofproto, struct ofputil_table_desc **descp)
3810 {
3811 struct ofputil_table_desc *table_desc;
3812 size_t i;
3813
3814 table_desc = *descp = xcalloc(ofproto->n_tables, sizeof *table_desc);
3815 for (i = 0; i < ofproto->n_tables; i++) {
3816 struct ofputil_table_desc *td = &table_desc[i];
3817 query_table_desc__(td, ofproto, i);
3818 }
3819 }
3820
3821 /* Function to handle dump-table-desc request. */
3822 static enum ofperr
3823 handle_table_desc_request(struct ofconn *ofconn,
3824 const struct ofp_header *request)
3825 {
3826 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3827 struct ofputil_table_desc *table_desc;
3828 struct ovs_list replies;
3829 size_t i;
3830
3831 query_tables_desc(ofproto, &table_desc);
3832 ofpmp_init(&replies, request);
3833 for (i = 0; i < ofproto->n_tables; i++) {
3834 if (!(ofproto->tables[i].flags & OFTABLE_HIDDEN)) {
3835 ofputil_append_table_desc_reply(&table_desc[i], &replies,
3836 request->version);
3837 }
3838 }
3839 ofconn_send_replies(ofconn, &replies);
3840 free(table_desc);
3841 return 0;
3842 }
3843
3844 /* This function determines and sends the vacancy event, based on the value
3845 * of current vacancy and threshold vacancy. If the current vacancy is less
3846 * than or equal to vacancy_down, vacancy up events must be enabled, and when
3847 * the current vacancy is greater or equal to vacancy_up, vacancy down events
3848 * must be enabled. */
3849 static void
3850 send_table_status(struct ofproto *ofproto, uint8_t table_id)
3851 {
3852 struct oftable *t = &ofproto->tables[table_id];
3853 if (!t->vacancy_event) {
3854 return;
3855 }
3856
3857 uint8_t vacancy = oftable_vacancy(t);
3858 enum ofp14_table_reason event;
3859 if (vacancy < t->vacancy_down) {
3860 event = OFPTR_VACANCY_DOWN;
3861 } else if (vacancy > t->vacancy_up) {
3862 event = OFPTR_VACANCY_UP;
3863 } else {
3864 return;
3865 }
3866
3867 if (event == t->vacancy_event) {
3868 struct ofputil_table_desc td;
3869 query_table_desc__(&td, ofproto, table_id);
3870 connmgr_send_table_status(ofproto->connmgr, &td, event);
3871
3872 t->vacancy_event = (event == OFPTR_VACANCY_DOWN
3873 ? OFPTR_VACANCY_UP
3874 : OFPTR_VACANCY_DOWN);
3875 }
3876 }
3877
3878 static void
3879 append_port_stat(struct ofport *port, struct ovs_list *replies)
3880 {
3881 struct ofputil_port_stats ops = { .port_no = port->pp.port_no };
3882
3883 calc_duration(port->created, time_msec(),
3884 &ops.duration_sec, &ops.duration_nsec);
3885
3886 /* Intentionally ignore return value, since errors will set
3887 * 'stats' to all-1s, which is correct for OpenFlow, and
3888 * netdev_get_stats() will log errors. */
3889 ofproto_port_get_stats(port, &ops.stats);
3890
3891 ofputil_append_port_stat(replies, &ops);
3892 }
3893
3894 static void
3895 handle_port_request(struct ofconn *ofconn,
3896 const struct ofp_header *request, ofp_port_t port_no,
3897 void (*cb)(struct ofport *, struct ovs_list *replies))
3898 {
3899 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
3900 struct ofport *port;
3901 struct ovs_list replies;
3902
3903 ofpmp_init(&replies, request);
3904 if (port_no != OFPP_ANY) {
3905 port = ofproto_get_port(ofproto, port_no);
3906 if (port) {
3907 cb(port, &replies);
3908 }
3909 } else {
3910 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
3911 cb(port, &replies);
3912 }
3913 }
3914
3915 ofconn_send_replies(ofconn, &replies);
3916 }
3917
3918 static enum ofperr
3919 handle_port_stats_request(struct ofconn *ofconn,
3920 const struct ofp_header *request)
3921 {
3922 ofp_port_t port_no;
3923 enum ofperr error;
3924
3925 error = ofputil_decode_port_stats_request(request, &port_no);
3926 if (!error) {
3927 handle_port_request(ofconn, request, port_no, append_port_stat);
3928 }
3929 return error;
3930 }
3931
3932 static void
3933 append_port_desc(struct ofport *port, struct ovs_list *replies)
3934 {
3935 ofputil_append_port_desc_stats_reply(&port->pp, replies);
3936 }
3937
3938 static enum ofperr
3939 handle_port_desc_stats_request(struct ofconn *ofconn,
3940 const struct ofp_header *request)
3941 {
3942 ofp_port_t port_no;
3943 enum ofperr error;
3944
3945 error = ofputil_decode_port_desc_stats_request(request, &port_no);
3946 if (!error) {
3947 handle_port_request(ofconn, request, port_no, append_port_desc);
3948 }
3949 return error;
3950 }
3951
3952 static uint32_t
3953 hash_cookie(ovs_be64 cookie)
3954 {
3955 return hash_uint64((OVS_FORCE uint64_t)cookie);
3956 }
3957
3958 static void
3959 cookies_insert(struct ofproto *ofproto, struct rule *rule)
3960 OVS_REQUIRES(ofproto_mutex)
3961 {
3962 hindex_insert(&ofproto->cookies, &rule->cookie_node,
3963 hash_cookie(rule->flow_cookie));
3964 }
3965
3966 static void
3967 cookies_remove(struct ofproto *ofproto, struct rule *rule)
3968 OVS_REQUIRES(ofproto_mutex)
3969 {
3970 hindex_remove(&ofproto->cookies, &rule->cookie_node);
3971 }
3972
3973 static void
3974 calc_duration(long long int start, long long int now,
3975 uint32_t *sec, uint32_t *nsec)
3976 {
3977 long long int msecs = now - start;
3978 *sec = msecs / 1000;
3979 *nsec = (msecs % 1000) * (1000 * 1000);
3980 }
3981
3982 /* Checks whether 'table_id' is 0xff or a valid table ID in 'ofproto'. Returns
3983 * true if 'table_id' is OK, false otherwise. */
3984 static bool
3985 check_table_id(const struct ofproto *ofproto, uint8_t table_id)
3986 {
3987 return table_id == OFPTT_ALL || table_id < ofproto->n_tables;
3988 }
3989
3990 static struct oftable *
3991 next_visible_table(const struct ofproto *ofproto, uint8_t table_id)
3992 {
3993 struct oftable *table;
3994
3995 for (table = &ofproto->tables[table_id];
3996 table < &ofproto->tables[ofproto->n_tables];
3997 table++) {
3998 if (!(table->flags & OFTABLE_HIDDEN)) {
3999 return table;
4000 }
4001 }
4002
4003 return NULL;
4004 }
4005
4006 static struct oftable *
4007 first_matching_table(const struct ofproto *ofproto, uint8_t table_id)
4008 {
4009 if (table_id == 0xff) {
4010 return next_visible_table(ofproto, 0);
4011 } else if (table_id < ofproto->n_tables) {
4012 return &ofproto->tables[table_id];
4013 } else {
4014 return NULL;
4015 }
4016 }
4017
4018 static struct oftable *
4019 next_matching_table(const struct ofproto *ofproto,
4020 const struct oftable *table, uint8_t table_id)
4021 {
4022 return (table_id == 0xff
4023 ? next_visible_table(ofproto, (table - ofproto->tables) + 1)
4024 : NULL);
4025 }
4026
4027 /* Assigns TABLE to each oftable, in turn, that matches TABLE_ID in OFPROTO:
4028 *
4029 * - If TABLE_ID is 0xff, this iterates over every classifier table in
4030 * OFPROTO, skipping tables marked OFTABLE_HIDDEN.
4031 *
4032 * - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
4033 * only once, for that table. (This can be used to access tables marked
4034 * OFTABLE_HIDDEN.)
4035 *
4036 * - Otherwise, TABLE_ID isn't valid for OFPROTO, so the loop won't be
4037 * entered at all. (Perhaps you should have validated TABLE_ID with
4038 * check_table_id().)
4039 *
4040 * All parameters are evaluated multiple times.
4041 */
4042 #define FOR_EACH_MATCHING_TABLE(TABLE, TABLE_ID, OFPROTO) \
4043 for ((TABLE) = first_matching_table(OFPROTO, TABLE_ID); \
4044 (TABLE) != NULL; \
4045 (TABLE) = next_matching_table(OFPROTO, TABLE, TABLE_ID))
4046
4047 /* Initializes 'criteria' in a straightforward way based on the other
4048 * parameters.
4049 *
4050 * By default, the criteria include flows that are read-only, on the assumption
4051 * that the collected flows won't be modified. Call rule_criteria_require_rw()
4052 * if flows will be modified.
4053 *
4054 * For "loose" matching, the 'priority' parameter is unimportant and may be
4055 * supplied as 0. */
4056 static void
4057 rule_criteria_init(struct rule_criteria *criteria, uint8_t table_id,
4058 const struct match *match, int priority,
4059 ovs_version_t version, ovs_be64 cookie,
4060 ovs_be64 cookie_mask, ofp_port_t out_port,
4061 uint32_t out_group)
4062 {
4063 criteria->table_id = table_id;
4064 cls_rule_init(&criteria->cr, match, priority);
4065 criteria->version = version;
4066 criteria->cookie = cookie;
4067 criteria->cookie_mask = cookie_mask;
4068 criteria->out_port = out_port;
4069 criteria->out_group = out_group;
4070
4071 /* We ordinarily want to skip hidden rules, but there has to be a way for
4072 * code internal to OVS to modify and delete them, so if the criteria
4073 * specify a priority that can only be for a hidden flow, then allow hidden
4074 * rules to be selected. (This doesn't allow OpenFlow clients to meddle
4075 * with hidden flows because OpenFlow uses only a 16-bit field to specify
4076 * priority.) */
4077 criteria->include_hidden = priority > UINT16_MAX;
4078
4079 /* We assume that the criteria are being used to collect flows for reading
4080 * but not modification. Thus, we should collect read-only flows. */
4081 criteria->include_readonly = true;
4082 }
4083
4084 /* By default, criteria initialized by rule_criteria_init() will match flows
4085 * that are read-only, on the assumption that the collected flows won't be
4086 * modified. Call this function to match only flows that are be modifiable.
4087 *
4088 * Specify 'can_write_readonly' as false in ordinary circumstances, true if the
4089 * caller has special privileges that allow it to modify even "read-only"
4090 * flows. */
4091 static void
4092 rule_criteria_require_rw(struct rule_criteria *criteria,
4093 bool can_write_readonly)
4094 {
4095 criteria->include_readonly = can_write_readonly;
4096 }
4097
4098 static void
4099 rule_criteria_destroy(struct rule_criteria *criteria)
4100 {
4101 cls_rule_destroy(&criteria->cr);
4102 criteria->version = OVS_VERSION_NOT_REMOVED; /* Mark as destroyed. */
4103 }
4104
4105 /* Schedules postponed removal of rules, destroys 'rules'. */
4106 static void
4107 remove_rules_postponed(struct rule_collection *rules)
4108 OVS_REQUIRES(ofproto_mutex)
4109 {
4110 if (rule_collection_n(rules) > 0) {
4111 if (rule_collection_n(rules) == 1) {
4112 ovsrcu_postpone(remove_rule_rcu, rule_collection_rules(rules)[0]);
4113 rule_collection_init(rules);
4114 } else {
4115 ovsrcu_postpone(remove_rules_rcu, rule_collection_detach(rules));
4116 }
4117 }
4118 }
4119
4120 /* Schedules postponed removal of groups, destroys 'groups'. */
4121 static void
4122 remove_groups_postponed(struct group_collection *groups)
4123 OVS_REQUIRES(ofproto_mutex)
4124 {
4125 if (group_collection_n(groups) > 0) {
4126 if (group_collection_n(groups) == 1) {
4127 ovsrcu_postpone(remove_group_rcu,
4128 group_collection_groups(groups)[0]);
4129 group_collection_init(groups);
4130 } else {
4131 ovsrcu_postpone(remove_groups_rcu,
4132 group_collection_detach(groups));
4133 }
4134 }
4135 }
4136
4137 /* Checks whether 'rule' matches 'c' and, if so, adds it to 'rules'. This
4138 * function verifies most of the criteria in 'c' itself, but the caller must
4139 * check 'c->cr' itself.
4140 *
4141 * Rules that have already been marked for removal are not collected.
4142 *
4143 * Increments '*n_readonly' if 'rule' wasn't added because it's read-only (and
4144 * 'c' only includes modifiable rules). */
4145 static void
4146 collect_rule(struct rule *rule, const struct rule_criteria *c,
4147 struct rule_collection *rules, size_t *n_readonly)
4148 OVS_REQUIRES(ofproto_mutex)
4149 {
4150 if ((c->table_id == rule->table_id || c->table_id == 0xff)
4151 && ofproto_rule_has_out_port(rule, c->out_port)
4152 && ofproto_rule_has_out_group(rule, c->out_group)
4153 && !((rule->flow_cookie ^ c->cookie) & c->cookie_mask)
4154 && (!rule_is_hidden(rule) || c->include_hidden)
4155 && cls_rule_visible_in_version(&rule->cr, c->version)) {
4156 /* Rule matches all the criteria... */
4157 if (!rule_is_readonly(rule) || c->include_readonly) {
4158 /* ...add it. */
4159 rule_collection_add(rules, rule);
4160 } else {
4161 /* ...except it's read-only. */
4162 ++*n_readonly;
4163 }
4164 }
4165 }
4166
4167 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
4168 * on classifiers rules are done in the "loose" way required for OpenFlow
4169 * OFPFC_MODIFY and OFPFC_DELETE requests. Puts the selected rules on list
4170 * 'rules'.
4171 *
4172 * Returns 0 on success, otherwise an OpenFlow error code. */
4173 static enum ofperr
4174 collect_rules_loose(struct ofproto *ofproto,
4175 const struct rule_criteria *criteria,
4176 struct rule_collection *rules)
4177 OVS_REQUIRES(ofproto_mutex)
4178 {
4179 struct oftable *table;
4180 enum ofperr error = 0;
4181 size_t n_readonly = 0;
4182
4183 rule_collection_init(rules);
4184
4185 if (!check_table_id(ofproto, criteria->table_id)) {
4186 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4187 goto exit;
4188 }
4189
4190 if (criteria->cookie_mask == OVS_BE64_MAX) {
4191 struct rule *rule;
4192
4193 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
4194 hash_cookie(criteria->cookie),
4195 &ofproto->cookies) {
4196 if (cls_rule_is_loose_match(&rule->cr, &criteria->cr.match)) {
4197 collect_rule(rule, criteria, rules, &n_readonly);
4198 }
4199 }
4200 } else {
4201 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
4202 struct rule *rule;
4203
4204 CLS_FOR_EACH_TARGET (rule, cr, &table->cls, &criteria->cr,
4205 criteria->version) {
4206 collect_rule(rule, criteria, rules, &n_readonly);
4207 }
4208 }
4209 }
4210
4211 exit:
4212 if (!error && !rule_collection_n(rules) && n_readonly) {
4213 /* We didn't find any rules to modify. We did find some read-only
4214 * rules that we're not allowed to modify, so report that. */
4215 error = OFPERR_OFPBRC_EPERM;
4216 }
4217 if (error) {
4218 rule_collection_destroy(rules);
4219 }
4220 return error;
4221 }
4222
4223 /* Searches 'ofproto' for rules that match the criteria in 'criteria'. Matches
4224 * on classifiers rules are done in the "strict" way required for OpenFlow
4225 * OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests. Puts the selected
4226 * rules on list 'rules'.
4227 *
4228 * Returns 0 on success, otherwise an OpenFlow error code. */
4229 static enum ofperr
4230 collect_rules_strict(struct ofproto *ofproto,
4231 const struct rule_criteria *criteria,
4232 struct rule_collection *rules)
4233 OVS_REQUIRES(ofproto_mutex)
4234 {
4235 struct oftable *table;
4236 size_t n_readonly = 0;
4237 enum ofperr error = 0;
4238
4239 rule_collection_init(rules);
4240
4241 if (!check_table_id(ofproto, criteria->table_id)) {
4242 error = OFPERR_OFPBRC_BAD_TABLE_ID;
4243 goto exit;
4244 }
4245
4246 if (criteria->cookie_mask == OVS_BE64_MAX) {
4247 struct rule *rule;
4248
4249 HINDEX_FOR_EACH_WITH_HASH (rule, cookie_node,
4250 hash_cookie(criteria->cookie),
4251 &ofproto->cookies) {
4252 if (cls_rule_equal(&rule->cr, &criteria->cr)) {
4253 collect_rule(rule, criteria, rules, &n_readonly);
4254 }
4255 }
4256 } else {
4257 FOR_EACH_MATCHING_TABLE (table, criteria->table_id, ofproto) {
4258 struct rule *rule;
4259
4260 rule = rule_from_cls_rule(classifier_find_rule_exactly(
4261 &table->cls, &criteria->cr,
4262 criteria->version));
4263 if (rule) {
4264 collect_rule(rule, criteria, rules, &n_readonly);
4265 }
4266 }
4267 }
4268
4269 exit:
4270 if (!error && !rule_collection_n(rules) && n_readonly) {
4271 /* We didn't find any rules to modify. We did find some read-only
4272 * rules that we're not allowed to modify, so report that. */
4273 error = OFPERR_OFPBRC_EPERM;
4274 }
4275 if (error) {
4276 rule_collection_destroy(rules);
4277 }
4278 return error;
4279 }
4280
4281 /* Returns 'age_ms' (a duration in milliseconds), converted to seconds and
4282 * forced into the range of a uint16_t. */
4283 static int
4284 age_secs(long long int age_ms)
4285 {
4286 return (age_ms < 0 ? 0
4287 : age_ms >= UINT16_MAX * 1000 ? UINT16_MAX
4288 : (unsigned int) age_ms / 1000);
4289 }
4290
4291 static enum ofperr
4292 handle_flow_stats_request(struct ofconn *ofconn,
4293 const struct ofp_header *request)
4294 OVS_EXCLUDED(ofproto_mutex)
4295 {
4296 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4297 struct ofputil_flow_stats_request fsr;
4298 struct rule_criteria criteria;
4299 struct rule_collection rules;
4300 struct ovs_list replies;
4301 enum ofperr error;
4302
4303 error = ofputil_decode_flow_stats_request(&fsr, request,
4304 ofproto_get_tun_tab(ofproto),
4305 &ofproto->vl_mff_map);
4306 if (error) {
4307 return error;
4308 }
4309
4310 rule_criteria_init(&criteria, fsr.table_id, &fsr.match, 0, OVS_VERSION_MAX,
4311 fsr.cookie, fsr.cookie_mask, fsr.out_port,
4312 fsr.out_group);
4313
4314 ovs_mutex_lock(&ofproto_mutex);
4315 error = collect_rules_loose(ofproto, &criteria, &rules);
4316 rule_criteria_destroy(&criteria);
4317 if (!error) {
4318 rule_collection_ref(&rules);
4319 }
4320 ovs_mutex_unlock(&ofproto_mutex);
4321
4322 if (error) {
4323 return error;
4324 }
4325
4326 ofpmp_init(&replies, request);
4327 struct rule *rule;
4328 RULE_COLLECTION_FOR_EACH (rule, &rules) {
4329 long long int now = time_msec();
4330 struct ofputil_flow_stats fs;
4331 long long int created, used, modified;
4332 const struct rule_actions *actions;
4333 enum ofputil_flow_mod_flags flags;
4334
4335 ovs_mutex_lock(&rule->mutex);
4336 fs.cookie = rule->flow_cookie;
4337 fs.idle_timeout = rule->idle_timeout;
4338 fs.hard_timeout = rule->hard_timeout;
4339 fs.importance = rule->importance;
4340 created = rule->created;
4341 modified = rule->modified;
4342 actions = rule_get_actions(rule);
4343 flags = rule->flags;
4344 ovs_mutex_unlock(&rule->mutex);
4345
4346 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
4347 &fs.byte_count, &used);
4348
4349 minimatch_expand(&rule->cr.match, &fs.match);
4350 fs.table_id = rule->table_id;
4351 calc_duration(created, now, &fs.duration_sec, &fs.duration_nsec);
4352 fs.priority = rule->cr.priority;
4353 fs.idle_age = age_secs(now - used);
4354 fs.hard_age = age_secs(now - modified);
4355 fs.ofpacts = actions->ofpacts;
4356 fs.ofpacts_len = actions->ofpacts_len;
4357
4358 fs.flags = flags;
4359 ofputil_append_flow_stats_reply(&fs, &replies,
4360 ofproto_get_tun_tab(ofproto));
4361 }
4362
4363 rule_collection_unref(&rules);
4364 rule_collection_destroy(&rules);
4365
4366 ofconn_send_replies(ofconn, &replies);
4367
4368 return 0;
4369 }
4370
4371 static void
4372 flow_stats_ds(struct ofproto *ofproto, struct rule *rule, struct ds *results)
4373 {
4374 uint64_t packet_count, byte_count;
4375 const struct rule_actions *actions;
4376 long long int created, used;
4377
4378 rule->ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
4379 &byte_count, &used);
4380
4381 ovs_mutex_lock(&rule->mutex);
4382 actions = rule_get_actions(rule);
4383 created = rule->created;
4384 ovs_mutex_unlock(&rule->mutex);
4385
4386 if (rule->table_id != 0) {
4387 ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
4388 }
4389 ds_put_format(results, "duration=%llds, ", (time_msec() - created) / 1000);
4390 ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
4391 ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
4392 cls_rule_format(&rule->cr, ofproto_get_tun_tab(ofproto), NULL, results);
4393 ds_put_char(results, ',');
4394
4395 ds_put_cstr(results, "actions=");
4396 ofpacts_format(actions->ofpacts, actions->ofpacts_len, NULL, results);
4397
4398 ds_put_cstr(results, "\n");
4399 }
4400
4401 /* Adds a pretty-printed description of all flows to 'results', including
4402 * hidden flows (e.g., set up by in-band control). */
4403 void
4404 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
4405 {
4406 struct oftable *table;
4407
4408 OFPROTO_FOR_EACH_TABLE (table, p) {
4409 struct rule *rule;
4410
4411 CLS_FOR_EACH (rule, cr, &table->cls) {
4412 flow_stats_ds(p, rule, results);
4413 }
4414 }
4415 }
4416
4417 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
4418 * '*engine_type' and '*engine_id', respectively. */
4419 void
4420 ofproto_get_netflow_ids(const struct ofproto *ofproto,
4421 uint8_t *engine_type, uint8_t *engine_id)
4422 {
4423 ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
4424 }
4425
4426 /* Checks the status change of CFM on 'ofport'.
4427 *
4428 * Returns true if 'ofproto_class' does not support 'cfm_status_changed'. */
4429 bool
4430 ofproto_port_cfm_status_changed(struct ofproto *ofproto, ofp_port_t ofp_port)
4431 {
4432 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
4433 return (ofport && ofproto->ofproto_class->cfm_status_changed
4434 ? ofproto->ofproto_class->cfm_status_changed(ofport)
4435 : true);
4436 }
4437
4438 /* Checks the status of CFM configured on 'ofp_port' within 'ofproto'.
4439 * Returns 0 if the port's CFM status was successfully stored into
4440 * '*status'. Returns positive errno if the port did not have CFM
4441 * configured.
4442 *
4443 * The caller must provide and own '*status', and must free 'status->rmps'.
4444 * '*status' is indeterminate if the return value is non-zero. */
4445 int
4446 ofproto_port_get_cfm_status(const struct ofproto *ofproto, ofp_port_t ofp_port,
4447 struct cfm_status *status)
4448 {
4449 struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
4450 return (ofport && ofproto->ofproto_class->get_cfm_status
4451 ? ofproto->ofproto_class->get_cfm_status(ofport, status)
4452 : EOPNOTSUPP);
4453 }
4454
4455 static enum ofperr
4456 handle_aggregate_stats_request(struct ofconn *ofconn,
4457 const struct ofp_header *oh)
4458 OVS_EXCLUDED(ofproto_mutex)
4459 {
4460 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4461 struct ofputil_flow_stats_request request;
4462 struct ofputil_aggregate_stats stats;
4463 bool unknown_packets, unknown_bytes;
4464 struct rule_criteria criteria;
4465 struct rule_collection rules;
4466 struct ofpbuf *reply;
4467 enum ofperr error;
4468
4469 error = ofputil_decode_flow_stats_request(&request, oh,
4470 ofproto_get_tun_tab(ofproto),
4471 &ofproto->vl_mff_map);
4472 if (error) {
4473 return error;
4474 }
4475
4476 rule_criteria_init(&criteria, request.table_id, &request.match, 0,
4477 OVS_VERSION_MAX, request.cookie, request.cookie_mask,
4478 request.out_port, request.out_group);
4479
4480 ovs_mutex_lock(&ofproto_mutex);
4481 error = collect_rules_loose(ofproto, &criteria, &rules);
4482 rule_criteria_destroy(&criteria);
4483 if (!error) {
4484 rule_collection_ref(&rules);
4485 }
4486 ovs_mutex_unlock(&ofproto_mutex);
4487
4488 if (error) {
4489 return error;
4490 }
4491
4492 memset(&stats, 0, sizeof stats);
4493 unknown_packets = unknown_bytes = false;
4494
4495 struct rule *rule;
4496 RULE_COLLECTION_FOR_EACH (rule, &rules) {
4497 uint64_t packet_count;
4498 uint64_t byte_count;
4499 long long int used;
4500
4501 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
4502 &byte_count, &used);
4503
4504 if (packet_count == UINT64_MAX) {
4505 unknown_packets = true;
4506 } else {
4507 stats.packet_count += packet_count;
4508 }
4509
4510 if (byte_count == UINT64_MAX) {
4511 unknown_bytes = true;
4512 } else {
4513 stats.byte_count += byte_count;
4514 }
4515
4516 stats.flow_count++;
4517 }
4518 if (unknown_packets) {
4519 stats.packet_count = UINT64_MAX;
4520 }
4521 if (unknown_bytes) {
4522 stats.byte_count = UINT64_MAX;
4523 }
4524
4525 rule_collection_unref(&rules);
4526 rule_collection_destroy(&rules);
4527
4528 reply = ofputil_encode_aggregate_stats_reply(&stats, oh);
4529 ofconn_send_reply(ofconn, reply);
4530
4531 return 0;
4532 }
4533
4534 struct queue_stats_cbdata {
4535 struct ofport *ofport;
4536 struct ovs_list replies;
4537 long long int now;
4538 };
4539
4540 static void
4541 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
4542 const struct netdev_queue_stats *stats)
4543 {
4544 struct ofputil_queue_stats oqs;
4545
4546 oqs.port_no = cbdata->ofport->pp.port_no;
4547 oqs.queue_id = queue_id;
4548 oqs.tx_bytes = stats->tx_bytes;
4549 oqs.tx_packets = stats->tx_packets;
4550 oqs.tx_errors = stats->tx_errors;
4551 if (stats->created != LLONG_MIN) {
4552 calc_duration(stats->created, cbdata->now,
4553 &oqs.duration_sec, &oqs.duration_nsec);
4554 } else {
4555 oqs.duration_sec = oqs.duration_nsec = UINT32_MAX;
4556 }
4557 ofputil_append_queue_stat(&cbdata->replies, &oqs);
4558 }
4559
4560 static void
4561 handle_queue_stats_dump_cb(uint32_t queue_id,
4562 struct netdev_queue_stats *stats,
4563 void *cbdata_)
4564 {
4565 struct queue_stats_cbdata *cbdata = cbdata_;
4566
4567 put_queue_stats(cbdata, queue_id, stats);
4568 }
4569
4570 static enum ofperr
4571 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
4572 struct queue_stats_cbdata *cbdata)
4573 {
4574 cbdata->ofport = port;
4575 if (queue_id == OFPQ_ALL) {
4576 netdev_dump_queue_stats(port->netdev,
4577 handle_queue_stats_dump_cb, cbdata);
4578 } else {
4579 struct netdev_queue_stats stats;
4580
4581 if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
4582 put_queue_stats(cbdata, queue_id, &stats);
4583 } else {
4584 return OFPERR_OFPQOFC_BAD_QUEUE;
4585 }
4586 }
4587 return 0;
4588 }
4589
4590 static enum ofperr
4591 handle_queue_stats_request(struct ofconn *ofconn,
4592 const struct ofp_header *rq)
4593 {
4594 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
4595 struct queue_stats_cbdata cbdata;
4596 struct ofport *port;
4597 enum ofperr error;
4598 struct ofputil_queue_stats_request oqsr;
4599
4600 COVERAGE_INC(ofproto_queue_req);
4601
4602 ofpmp_init(&cbdata.replies, rq);
4603 cbdata.now = time_msec();
4604
4605 error = ofputil_decode_queue_stats_request(rq, &oqsr);
4606 if (error) {
4607 return error;
4608 }
4609
4610 if (oqsr.port_no == OFPP_ANY) {
4611 error = OFPERR_OFPQOFC_BAD_QUEUE;
4612 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
4613 if (!handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)) {
4614 error = 0;
4615 }
4616 }
4617 } else {
4618 port = ofproto_get_port(ofproto, oqsr.port_no);
4619 error = (port
4620 ? handle_queue_stats_for_port(port, oqsr.queue_id, &cbdata)
4621 : OFPERR_OFPQOFC_BAD_PORT);
4622 }
4623 if (!error) {
4624 ofconn_send_replies(ofconn, &cbdata.replies);
4625 } else {
4626 ofpbuf_list_delete(&cbdata.replies);
4627 }
4628
4629 return error;
4630 }
4631
4632 static enum ofperr
4633 evict_rules_from_table(struct oftable *table)
4634 OVS_REQUIRES(ofproto_mutex)
4635 {
4636 enum ofperr error = 0;
4637 struct rule_collection rules;
4638 unsigned int count = table->n_flows;
4639 unsigned int max_flows = table->max_flows;
4640
4641 rule_collection_init(&rules);
4642
4643 while (count-- > max_flows) {
4644 struct rule *rule;
4645
4646 if (!choose_rule_to_evict(table, &rule)) {
4647 error = OFPERR_OFPFMFC_TABLE_FULL;
4648 break;
4649 } else {
4650 eviction_group_remove_rule(rule);
4651 rule_collection_add(&rules, rule);
4652 }
4653 }
4654 delete_flows__(&rules, OFPRR_EVICTION, NULL);
4655
4656 return error;
4657 }
4658
4659 static void
4660 get_conjunctions(const struct ofputil_flow_mod *fm,
4661 struct cls_conjunction **conjsp, size_t *n_conjsp)
4662 {
4663 struct cls_conjunction *conjs = NULL;
4664 int n_conjs = 0;
4665
4666 const struct ofpact *ofpact;
4667 OFPACT_FOR_EACH (ofpact, fm->ofpacts, fm->ofpacts_len) {
4668 if (ofpact->type == OFPACT_CONJUNCTION) {
4669 n_conjs++;
4670 } else if (ofpact->type != OFPACT_NOTE) {
4671 /* "conjunction" may appear with "note" actions but not with any
4672 * other type of actions. */
4673 ovs_assert(!n_conjs);
4674 break;
4675 }
4676 }
4677 if (n_conjs) {
4678 int i = 0;
4679
4680 conjs = xzalloc(n_conjs * sizeof *conjs);
4681 OFPACT_FOR_EACH (ofpact, fm->ofpacts, fm->ofpacts_len) {
4682 if (ofpact->type == OFPACT_CONJUNCTION) {
4683 struct ofpact_conjunction *oc = ofpact_get_CONJUNCTION(ofpact);
4684 conjs[i].clause = oc->clause;
4685 conjs[i].n_clauses = oc->n_clauses;
4686 conjs[i].id = oc->id;
4687 i++;
4688 }
4689 }
4690 }
4691
4692 *conjsp = conjs;
4693 *n_conjsp = n_conjs;
4694 }
4695
4696 /* add_flow_init(), add_flow_start(), add_flow_revert(), and add_flow_finish()
4697 * implement OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
4698 * in which no matching flow already exists in the flow table.
4699 *
4700 * add_flow_init() creates a new flow according to 'fm' and stores it to 'ofm'
4701 * for later reference. If the flow replaces other flow, it will be updated to
4702 * match modify semantics later by add_flow_start() (by calling
4703 * replace_rule_start()).
4704 *
4705 * Returns 0 on success, or an OpenFlow error code on failure.
4706 *
4707 * On successful return the caller must complete the operation by calling
4708 * add_flow_start(), and if that succeeds, then either add_flow_finish(), or
4709 * add_flow_revert() if the operation needs to be reverted due to a later
4710 * failure.
4711 */
4712 static enum ofperr
4713 add_flow_init(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
4714 const struct ofputil_flow_mod *fm)
4715 OVS_EXCLUDED(ofproto_mutex)
4716 {
4717 struct oftable *table;
4718 struct cls_rule cr;
4719 uint8_t table_id;
4720 enum ofperr error;
4721
4722 if (!check_table_id(ofproto, fm->table_id)) {
4723 return OFPERR_OFPBRC_BAD_TABLE_ID;
4724 }
4725
4726 /* Pick table. */
4727 if (fm->table_id == 0xff) {
4728 if (ofproto->ofproto_class->rule_choose_table) {
4729 error = ofproto->ofproto_class->rule_choose_table(ofproto,
4730 &fm->match,
4731 &table_id);
4732 if (error) {
4733 return error;
4734 }
4735 ovs_assert(table_id < ofproto->n_tables);
4736 } else {
4737 table_id = 0;
4738 }
4739 } else if (fm->table_id < ofproto->n_tables) {
4740 table_id = fm->table_id;
4741 } else {
4742 return OFPERR_OFPBRC_BAD_TABLE_ID;
4743 }
4744
4745 table = &ofproto->tables[table_id];
4746 if (table->flags & OFTABLE_READONLY
4747 && !(fm->flags & OFPUTIL_FF_NO_READONLY)) {
4748 return OFPERR_OFPBRC_EPERM;
4749 }
4750
4751 if (!(fm->flags & OFPUTIL_FF_HIDDEN_FIELDS)
4752 && !match_has_default_hidden_fields(&fm->match)) {
4753 VLOG_WARN_RL(&rl, "%s: (add_flow) only internal flows can set "
4754 "non-default values to hidden fields", ofproto->name);
4755 return OFPERR_OFPBRC_EPERM;
4756 }
4757
4758 if (!ofm->temp_rule) {
4759 cls_rule_init(&cr, &fm->match, fm->priority);
4760
4761 /* Allocate new rule. Destroys 'cr'. */
4762 error = ofproto_rule_create(ofproto, &cr, table - ofproto->tables,
4763 fm->new_cookie, fm->idle_timeout,
4764 fm->hard_timeout, fm->flags,
4765 fm->importance, fm->ofpacts,
4766 fm->ofpacts_len,
4767 fm->match.flow.tunnel.metadata.present.map,
4768 fm->ofpacts_tlv_bitmap, &ofm->temp_rule);
4769 if (error) {
4770 return error;
4771 }
4772
4773 get_conjunctions(fm, &ofm->conjs, &ofm->n_conjs);
4774 }
4775 return 0;
4776 }
4777
4778 /* ofm->temp_rule is consumed only in the successful case. */
4779 static enum ofperr
4780 add_flow_start(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
4781 OVS_REQUIRES(ofproto_mutex)
4782 {
4783 struct rule *old_rule = NULL;
4784 struct rule *new_rule = ofm->temp_rule;
4785 const struct rule_actions *actions = rule_get_actions(new_rule);
4786 struct oftable *table = &ofproto->tables[new_rule->table_id];
4787 enum ofperr error;
4788
4789 /* Must check actions while holding ofproto_mutex to avoid a race. */
4790 error = ofproto_check_ofpacts(ofproto, actions->ofpacts,
4791 actions->ofpacts_len);
4792 if (error) {
4793 return error;
4794 }
4795
4796 /* Check for the existence of an identical rule.
4797 * This will not return rules earlier marked for removal. */
4798 old_rule = rule_from_cls_rule(classifier_find_rule_exactly(&table->cls,
4799 &new_rule->cr,
4800 ofm->version));
4801 if (!old_rule) {
4802 /* Check for overlap, if requested. */
4803 if (new_rule->flags & OFPUTIL_FF_CHECK_OVERLAP
4804 && classifier_rule_overlaps(&table->cls, &new_rule->cr,
4805 ofm->version)) {
4806 return OFPERR_OFPFMFC_OVERLAP;
4807 }
4808
4809 /* If necessary, evict an existing rule to clear out space. */
4810 if (table->n_flows >= table->max_flows) {
4811 if (!choose_rule_to_evict(table, &old_rule)) {
4812 return OFPERR_OFPFMFC_TABLE_FULL;
4813 }
4814 eviction_group_remove_rule(old_rule);
4815 /* Marks 'old_rule' as an evicted rule rather than replaced rule.
4816 */
4817 old_rule->removed_reason = OFPRR_EVICTION;
4818 }
4819 } else {
4820 ofm->modify_cookie = true;
4821 }
4822
4823 if (old_rule) {
4824 rule_collection_add(&ofm->old_rules, old_rule);
4825 }
4826 /* Take ownership of the temp_rule. */
4827 rule_collection_add(&ofm->new_rules, new_rule);
4828 ofm->temp_rule = NULL;
4829
4830 replace_rule_start(ofproto, ofm, old_rule, new_rule);
4831 return 0;
4832 }
4833
4834 /* Revert the effects of add_flow_start(). */
4835 static void
4836 add_flow_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
4837 OVS_REQUIRES(ofproto_mutex)
4838 {
4839 struct rule *old_rule = rule_collection_n(&ofm->old_rules)
4840 ? rule_collection_rules(&ofm->old_rules)[0] : NULL;
4841 struct rule *new_rule = rule_collection_rules(&ofm->new_rules)[0];
4842
4843 replace_rule_revert(ofproto, old_rule, new_rule);
4844 }
4845
4846 /* To be called after version bump. */
4847 static void
4848 add_flow_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
4849 const struct openflow_mod_requester *req)
4850 OVS_REQUIRES(ofproto_mutex)
4851 {
4852 struct rule *old_rule = rule_collection_n(&ofm->old_rules)
4853 ? rule_collection_rules(&ofm->old_rules)[0] : NULL;
4854 struct rule *new_rule = rule_collection_rules(&ofm->new_rules)[0];
4855 struct ovs_list dead_cookies = OVS_LIST_INITIALIZER(&dead_cookies);
4856
4857 replace_rule_finish(ofproto, ofm, req, old_rule, new_rule, &dead_cookies);
4858 learned_cookies_flush(ofproto, &dead_cookies);
4859
4860 if (old_rule) {
4861 ovsrcu_postpone(remove_rule_rcu, old_rule);
4862 } else {
4863 ofmonitor_report(ofproto->connmgr, new_rule, NXFME_ADDED, 0,
4864 req ? req->ofconn : NULL,
4865 req ? req->request->xid : 0, NULL);
4866
4867 /* Send Vacancy Events for OF1.4+. */
4868 send_table_status(ofproto, new_rule->table_id);
4869 }
4870 }
4871 \f
4872 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
4873
4874 /* Create a new rule. Note that the rule is NOT inserted into a any data
4875 * structures yet. Takes ownership of 'cr'. Only assigns '*new_rule' if
4876 * successful. */
4877 static enum ofperr
4878 ofproto_rule_create(struct ofproto *ofproto, struct cls_rule *cr,
4879 uint8_t table_id, ovs_be64 new_cookie,
4880 uint16_t idle_timeout, uint16_t hard_timeout,
4881 enum ofputil_flow_mod_flags flags, uint16_t importance,
4882 const struct ofpact *ofpacts, size_t ofpacts_len,
4883 uint64_t match_tlv_bitmap, uint64_t ofpacts_tlv_bitmap,
4884 struct rule **new_rule)
4885 OVS_NO_THREAD_SAFETY_ANALYSIS
4886 {
4887 struct rule *rule;
4888 enum ofperr error;
4889
4890 /* Allocate new rule. */
4891 rule = ofproto->ofproto_class->rule_alloc();
4892 if (!rule) {
4893 cls_rule_destroy(cr);
4894 VLOG_WARN_RL(&rl, "%s: failed to allocate a rule.", ofproto->name);
4895 return OFPERR_OFPFMFC_UNKNOWN;
4896 }
4897
4898 /* Initialize base state. */
4899 *CONST_CAST(struct ofproto **, &rule->ofproto) = ofproto;
4900 cls_rule_move(CONST_CAST(struct cls_rule *, &rule->cr), cr);
4901 ovs_refcount_init(&rule->ref_count);
4902
4903 ovs_mutex_init(&rule->mutex);
4904 ovs_mutex_lock(&rule->mutex);
4905 *CONST_CAST(ovs_be64 *, &rule->flow_cookie) = new_cookie;
4906 rule->created = rule->modified = time_msec();
4907 rule->idle_timeout = idle_timeout;
4908 rule->hard_timeout = hard_timeout;
4909 *CONST_CAST(uint16_t *, &rule->importance) = importance;
4910 rule->removed_reason = OVS_OFPRR_NONE;
4911
4912 *CONST_CAST(uint8_t *, &rule->table_id) = table_id;
4913 rule->flags = flags & OFPUTIL_FF_STATE;
4914
4915 *CONST_CAST(const struct rule_actions **, &rule->actions)
4916 = rule_actions_create(ofpacts, ofpacts_len);
4917
4918 ovs_list_init(&rule->meter_list_node);
4919 rule->eviction_group = NULL;
4920 rule->monitor_flags = 0;
4921 rule->add_seqno = 0;
4922 rule->modify_seqno = 0;
4923 ovs_list_init(&rule->expirable);
4924 ovs_mutex_unlock(&rule->mutex);
4925
4926 /* Construct rule, initializing derived state. */
4927 error = ofproto->ofproto_class->rule_construct(rule);
4928 if (error) {
4929 ofproto_rule_destroy__(rule);
4930 return error;
4931 }
4932
4933 rule->state = RULE_INITIALIZED;
4934 rule->match_tlv_bitmap = match_tlv_bitmap;
4935 rule->ofpacts_tlv_bitmap = ofpacts_tlv_bitmap;
4936 mf_vl_mff_ref(&rule->ofproto->vl_mff_map, match_tlv_bitmap);
4937 mf_vl_mff_ref(&rule->ofproto->vl_mff_map, ofpacts_tlv_bitmap);
4938
4939 *new_rule = rule;
4940 return 0;
4941 }
4942
4943 /* Initialize 'ofm' for a learn action. If the rule already existed, reference
4944 * to that rule is taken, otherwise a new rule is created. 'ofm' keeps the
4945 * rule reference in both. This does not take the global 'ofproto_mutex'. */
4946 enum ofperr
4947 ofproto_flow_mod_init_for_learn(struct ofproto *ofproto,
4948 const struct ofputil_flow_mod *fm,
4949 struct ofproto_flow_mod *ofm)
4950 OVS_EXCLUDED(ofproto_mutex)
4951 {
4952 enum ofperr error;
4953
4954 /* Reject flow mods that do not look like they were generated by a learn
4955 * action. */
4956 if (fm->command != OFPFC_MODIFY_STRICT || fm->table_id == OFPTT_ALL
4957 || fm->flags & OFPUTIL_FF_RESET_COUNTS
4958 || fm->buffer_id != UINT32_MAX) {
4959 return OFPERR_OFPFMFC_UNKNOWN;
4960 }
4961
4962 /* Check if the rule already exists, and we can get a reference to it. */
4963 struct oftable *table = &ofproto->tables[fm->table_id];
4964 struct rule *rule;
4965
4966 rule = rule_from_cls_rule(classifier_find_match_exactly(
4967 &table->cls, &fm->match, fm->priority,
4968 OVS_VERSION_MAX));
4969 if (rule) {
4970 /* Check if the rule's attributes match as well. */
4971 const struct rule_actions *actions;
4972
4973 ovs_mutex_lock(&rule->mutex);
4974 actions = rule_get_actions(rule);
4975 if (rule->idle_timeout == fm->idle_timeout
4976 && rule->hard_timeout == fm->hard_timeout
4977 && rule->importance == fm->importance
4978 && rule->flags == (fm->flags & OFPUTIL_FF_STATE)
4979 && (!fm->modify_cookie || (fm->new_cookie == rule->flow_cookie))
4980 && ofpacts_equal(fm->ofpacts, fm->ofpacts_len,
4981 actions->ofpacts, actions->ofpacts_len)) {
4982 /* Rule already exists and need not change, except for the modified
4983 * timestamp. Get a reference to the existing rule. */
4984 ovs_mutex_unlock(&rule->mutex);
4985 if (!ofproto_rule_try_ref(rule)) {
4986 rule = NULL; /* Pretend it did not exist. */
4987 }
4988 } else {
4989 ovs_mutex_unlock(&rule->mutex);
4990 rule = NULL;
4991 }
4992 }
4993
4994 /* Initialize ofproto_flow_mod for future use. */
4995 error = ofproto_flow_mod_init(ofproto, ofm, fm, rule);
4996 if (error) {
4997 ofproto_rule_unref(rule);
4998 return error;
4999 }
5000 return 0;
5001 }
5002
5003 enum ofperr
5004 ofproto_flow_mod_learn_refresh(struct ofproto_flow_mod *ofm)
5005 {
5006 enum ofperr error = 0;
5007
5008 /* ofm->temp_rule is our reference to the learned rule. We have a
5009 * reference to an existing rule, if it already was in the classifier,
5010 * otherwise we may have a fresh rule that we need to insert. */
5011 struct rule *rule = ofm->temp_rule;
5012 if (!rule) {
5013 return OFPERR_OFPFMFC_UNKNOWN;
5014 }
5015
5016 /* Create a new rule if the current one has been removed from the
5017 * classifier. We need to do this since RCU does not allow a current rule
5018 * to be reinserted before all threads have quiesced.
5019 *
5020 * It is possible that the rule is removed asynchronously, e.g., right
5021 * after we have read the 'rule->state' below. In this case the next time
5022 * this function is executed the rule will be reinstated. */
5023 if (rule->state == RULE_REMOVED) {
5024 struct cls_rule cr;
5025
5026 cls_rule_clone(&cr, &rule->cr);
5027 ovs_mutex_lock(&rule->mutex);
5028 error = ofproto_rule_create(rule->ofproto, &cr, rule->table_id,
5029 rule->flow_cookie,
5030 rule->idle_timeout,
5031 rule->hard_timeout, rule->flags,
5032 rule->importance,
5033 rule->actions->ofpacts,
5034 rule->actions->ofpacts_len,
5035 rule->match_tlv_bitmap,
5036 rule->ofpacts_tlv_bitmap,
5037 &ofm->temp_rule);
5038 ovs_mutex_unlock(&rule->mutex);
5039 if (!error) {
5040 ofproto_rule_unref(rule); /* Release old reference. */
5041 }
5042 } else {
5043 /* Refresh the existing rule. */
5044 ovs_mutex_lock(&rule->mutex);
5045 rule->modified = time_msec();
5046 ovs_mutex_unlock(&rule->mutex);
5047 }
5048 return error;
5049 }
5050
5051 enum ofperr
5052 ofproto_flow_mod_learn_start(struct ofproto_flow_mod *ofm)
5053 OVS_REQUIRES(ofproto_mutex)
5054 {
5055 struct rule *rule = ofm->temp_rule;
5056
5057 /* ofproto_flow_mod_start() consumes the reference, so we
5058 * take a new one. */
5059 ofproto_rule_ref(rule);
5060 enum ofperr error = ofproto_flow_mod_start(rule->ofproto, ofm);
5061 ofm->temp_rule = rule;
5062
5063 return error;
5064 }
5065
5066 void
5067 ofproto_flow_mod_learn_revert(struct ofproto_flow_mod *ofm)
5068 OVS_REQUIRES(ofproto_mutex)
5069 {
5070 struct rule *rule = rule_collection_rules(&ofm->new_rules)[0];
5071 ofproto_flow_mod_revert(rule->ofproto, ofm);
5072 }
5073
5074 void
5075 ofproto_flow_mod_learn_finish(struct ofproto_flow_mod *ofm,
5076 struct ofproto *orig_ofproto)
5077 OVS_REQUIRES(ofproto_mutex)
5078 {
5079 struct rule *rule = rule_collection_rules(&ofm->new_rules)[0];
5080
5081 /* If learning on a different bridge, must bump its version
5082 * number and flush connmgr afterwards. */
5083 if (rule->ofproto != orig_ofproto) {
5084 ofproto_bump_tables_version(rule->ofproto);
5085 }
5086 ofproto_flow_mod_finish(rule->ofproto, ofm, NULL);
5087 if (rule->ofproto != orig_ofproto) {
5088 ofmonitor_flush(rule->ofproto->connmgr);
5089 }
5090 }
5091
5092 /* Refresh 'ofm->temp_rule', for which the caller holds a reference, if already
5093 * in the classifier, insert it otherwise. If the rule has already been
5094 * removed from the classifier, a new rule is created using 'ofm->temp_rule' as
5095 * a template and the reference to the old 'ofm->temp_rule' is freed. If
5096 * 'keep_ref' is true, then a reference to the current rule is held, otherwise
5097 * it is released and 'ofm->temp_rule' is set to NULL.
5098 *
5099 * If 'limit' != 0, insertion will fail if there are more than 'limit' rules
5100 * in the same table with the same cookie. If insertion succeeds,
5101 * '*below_limitp' will be set to true. If insertion fails '*below_limitp'
5102 * will be set to false.
5103 *
5104 * Caller needs to be the exclusive owner of 'ofm' as it is being manipulated
5105 * during the call. */
5106 enum ofperr
5107 ofproto_flow_mod_learn(struct ofproto_flow_mod *ofm, bool keep_ref,
5108 unsigned limit, bool *below_limitp)
5109 OVS_EXCLUDED(ofproto_mutex)
5110 {
5111 enum ofperr error = ofproto_flow_mod_learn_refresh(ofm);
5112 struct rule *rule = ofm->temp_rule;
5113 bool below_limit = true;
5114
5115 /* Do we need to insert the rule? */
5116 if (!error && rule->state == RULE_INITIALIZED) {
5117 ovs_mutex_lock(&ofproto_mutex);
5118
5119 if (limit) {
5120 struct rule_criteria criteria;
5121 struct rule_collection rules;
5122 struct match match;
5123
5124 match_init_catchall(&match);
5125 rule_criteria_init(&criteria, rule->table_id, &match, 0,
5126 OVS_VERSION_MAX, rule->flow_cookie,
5127 OVS_BE64_MAX, OFPP_ANY, OFPG_ANY);
5128 rule_criteria_require_rw(&criteria, false);
5129 collect_rules_loose(rule->ofproto, &criteria, &rules);
5130 if (rule_collection_n(&rules) >= limit) {
5131 below_limit = false;
5132 }
5133 rule_collection_destroy(&rules);
5134 rule_criteria_destroy(&criteria);
5135 }
5136
5137 if (below_limit) {
5138 ofm->version = rule->ofproto->tables_version + 1;
5139
5140 error = ofproto_flow_mod_learn_start(ofm);
5141 if (!error) {
5142 ofproto_flow_mod_learn_finish(ofm, NULL);
5143 }
5144 } else {
5145 ofproto_flow_mod_uninit(ofm);
5146 }
5147 ovs_mutex_unlock(&ofproto_mutex);
5148
5149 if (!below_limit) {
5150 static struct vlog_rate_limit learn_rl = VLOG_RATE_LIMIT_INIT(1, 5);
5151 VLOG_INFO_RL(&learn_rl, "Learn limit for flow %"PRIu64" reached.",
5152 rule->flow_cookie);
5153 }
5154 }
5155
5156 if (!keep_ref && below_limit) {
5157 ofproto_rule_unref(rule);
5158 ofm->temp_rule = NULL;
5159 }
5160 if (below_limitp) {
5161 *below_limitp = below_limit;
5162 }
5163 return error;
5164 }
5165
5166 static void
5167 replace_rule_start(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5168 struct rule *old_rule, struct rule *new_rule)
5169 {
5170 struct oftable *table = &ofproto->tables[new_rule->table_id];
5171
5172 /* 'old_rule' may be either an evicted rule or replaced rule. */
5173 if (old_rule) {
5174 /* Copy values from old rule for modify semantics. */
5175 if (old_rule->removed_reason != OFPRR_EVICTION) {
5176 bool change_cookie = (ofm->modify_cookie
5177 && new_rule->flow_cookie != OVS_BE64_MAX
5178 && new_rule->flow_cookie != old_rule->flow_cookie);
5179
5180 ovs_mutex_lock(&new_rule->mutex);
5181 ovs_mutex_lock(&old_rule->mutex);
5182 if (ofm->command != OFPFC_ADD) {
5183 new_rule->idle_timeout = old_rule->idle_timeout;
5184 new_rule->hard_timeout = old_rule->hard_timeout;
5185 *CONST_CAST(uint16_t *, &new_rule->importance) = old_rule->importance;
5186 new_rule->flags = old_rule->flags;
5187 new_rule->created = old_rule->created;
5188 }
5189 if (!change_cookie) {
5190 *CONST_CAST(ovs_be64 *, &new_rule->flow_cookie)
5191 = old_rule->flow_cookie;
5192 }
5193 ovs_mutex_unlock(&old_rule->mutex);
5194 ovs_mutex_unlock(&new_rule->mutex);
5195 }
5196
5197 /* Mark the old rule for removal in the next version. */
5198 cls_rule_make_invisible_in_version(&old_rule->cr, ofm->version);
5199
5200 /* Remove the old rule from data structures. */
5201 ofproto_rule_remove__(ofproto, old_rule);
5202 } else {
5203 table->n_flows++;
5204 }
5205 /* Insert flow to ofproto data structures, so that later flow_mods may
5206 * relate to it. This is reversible, in case later errors require this to
5207 * be reverted. */
5208 ofproto_rule_insert__(ofproto, new_rule);
5209 /* Make the new rule visible for classifier lookups only from the next
5210 * version. */
5211 classifier_insert(&table->cls, &new_rule->cr, ofm->version, ofm->conjs,
5212 ofm->n_conjs);
5213 }
5214
5215 static void
5216 replace_rule_revert(struct ofproto *ofproto,
5217 struct rule *old_rule, struct rule *new_rule)
5218 {
5219 struct oftable *table = &ofproto->tables[new_rule->table_id];
5220
5221 if (old_rule) {
5222 if (old_rule->removed_reason == OFPRR_EVICTION) {
5223 /* Revert the eviction. */
5224 eviction_group_add_rule(old_rule);
5225 }
5226
5227 /* Restore the old rule to data structures. */
5228 ofproto_rule_insert__(ofproto, old_rule);
5229
5230 /* Restore the original visibility of the old rule. */
5231 cls_rule_restore_visibility(&old_rule->cr);
5232 } else {
5233 /* Restore table's rule count. */
5234 table->n_flows--;
5235 }
5236
5237 /* Remove the new rule immediately. It was never visible to lookups. */
5238 if (!classifier_remove(&table->cls, &new_rule->cr)) {
5239 OVS_NOT_REACHED();
5240 }
5241 ofproto_rule_remove__(ofproto, new_rule);
5242 ofproto_rule_unref(new_rule);
5243 }
5244
5245 /* Adds the 'new_rule', replacing the 'old_rule'. */
5246 static void
5247 replace_rule_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5248 const struct openflow_mod_requester *req,
5249 struct rule *old_rule, struct rule *new_rule,
5250 struct ovs_list *dead_cookies)
5251 OVS_REQUIRES(ofproto_mutex)
5252 {
5253 struct rule *replaced_rule;
5254
5255 replaced_rule = (old_rule && old_rule->removed_reason != OFPRR_EVICTION)
5256 ? old_rule : NULL;
5257
5258 /* Insert the new flow to the ofproto provider. A non-NULL 'replaced_rule'
5259 * is a duplicate rule the 'new_rule' is replacing. The provider should
5260 * link the packet and byte counts from the old rule to the new one if
5261 * 'modify_keep_counts' is 'true'. The 'replaced_rule' will be deleted
5262 * right after this call. */
5263 ofproto->ofproto_class->rule_insert(new_rule, replaced_rule,
5264 ofm->modify_keep_counts);
5265 learned_cookies_inc(ofproto, rule_get_actions(new_rule));
5266
5267 if (old_rule) {
5268 const struct rule_actions *old_actions = rule_get_actions(old_rule);
5269 const struct rule_actions *new_actions = rule_get_actions(new_rule);
5270
5271 learned_cookies_dec(ofproto, old_actions, dead_cookies);
5272
5273 if (replaced_rule) {
5274 enum nx_flow_update_event event = ofm->command == OFPFC_ADD
5275 ? NXFME_ADDED : NXFME_MODIFIED;
5276
5277 bool changed_cookie = (new_rule->flow_cookie
5278 != old_rule->flow_cookie);
5279
5280 bool changed_actions = !ofpacts_equal(new_actions->ofpacts,
5281 new_actions->ofpacts_len,
5282 old_actions->ofpacts,
5283 old_actions->ofpacts_len);
5284
5285 if (event != NXFME_MODIFIED || changed_actions
5286 || changed_cookie) {
5287 ofmonitor_report(ofproto->connmgr, new_rule, event, 0,
5288 req ? req->ofconn : NULL,
5289 req ? req->request->xid : 0,
5290 changed_actions ? old_actions : NULL);
5291 }
5292 } else {
5293 /* XXX: This is slight duplication with delete_flows_finish__() */
5294 ofmonitor_report(ofproto->connmgr, old_rule, NXFME_DELETED,
5295 OFPRR_EVICTION,
5296 req ? req->ofconn : NULL,
5297 req ? req->request->xid : 0, NULL);
5298 }
5299 }
5300 }
5301
5302 /* ofm->temp_rule is consumed only in the successful case. */
5303 static enum ofperr
5304 modify_flows_start__(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5305 OVS_REQUIRES(ofproto_mutex)
5306 {
5307 struct rule_collection *old_rules = &ofm->old_rules;
5308 struct rule_collection *new_rules = &ofm->new_rules;
5309 enum ofperr error;
5310
5311 if (rule_collection_n(old_rules) > 0) {
5312 /* Create a new 'modified' rule for each old rule. */
5313 struct rule *old_rule, *new_rule;
5314 const struct rule_actions *actions = rule_get_actions(ofm->temp_rule);
5315
5316 /* Must check actions while holding ofproto_mutex to avoid a race. */
5317 error = ofproto_check_ofpacts(ofproto, actions->ofpacts,
5318 actions->ofpacts_len);
5319 if (error) {
5320 return error;
5321 }
5322
5323 /* Use the temp rule as the first new rule, and as the template for
5324 * the rest. */
5325 struct rule *temp = ofm->temp_rule;
5326 ofm->temp_rule = NULL; /* We consume the template. */
5327
5328 bool first = true;
5329 RULE_COLLECTION_FOR_EACH (old_rule, old_rules) {
5330 if (first) {
5331 /* The template rule's match is possibly a loose one, so it
5332 * must be replaced with the old rule's match so that the new
5333 * rule actually replaces the old one. */
5334 cls_rule_destroy(CONST_CAST(struct cls_rule *, &temp->cr));
5335 cls_rule_clone(CONST_CAST(struct cls_rule *, &temp->cr),
5336 &old_rule->cr);
5337 if (temp->match_tlv_bitmap != old_rule->match_tlv_bitmap) {
5338 mf_vl_mff_unref(&temp->ofproto->vl_mff_map,
5339 temp->match_tlv_bitmap);
5340 temp->match_tlv_bitmap = old_rule->match_tlv_bitmap;
5341 mf_vl_mff_ref(&temp->ofproto->vl_mff_map,
5342 temp->match_tlv_bitmap);
5343 }
5344 *CONST_CAST(uint8_t *, &temp->table_id) = old_rule->table_id;
5345 rule_collection_add(new_rules, temp);
5346 first = false;
5347 } else {
5348 struct cls_rule cr;
5349 cls_rule_clone(&cr, &old_rule->cr);
5350 error = ofproto_rule_create(ofproto, &cr, old_rule->table_id,
5351 temp->flow_cookie,
5352 temp->idle_timeout,
5353 temp->hard_timeout, temp->flags,
5354 temp->importance,
5355 temp->actions->ofpacts,
5356 temp->actions->ofpacts_len,
5357 old_rule->match_tlv_bitmap,
5358 temp->ofpacts_tlv_bitmap,
5359 &new_rule);
5360 if (!error) {
5361 rule_collection_add(new_rules, new_rule);
5362 } else {
5363 /* Return the template rule in place in the error case. */
5364 ofm->temp_rule = temp;
5365 rule_collection_rules(new_rules)[0] = NULL;
5366
5367 rule_collection_unref(new_rules);
5368 rule_collection_destroy(new_rules);
5369 return error;
5370 }
5371 }
5372 }
5373 ovs_assert(rule_collection_n(new_rules)
5374 == rule_collection_n(old_rules));
5375
5376 RULE_COLLECTIONS_FOR_EACH (old_rule, new_rule, old_rules, new_rules) {
5377 replace_rule_start(ofproto, ofm, old_rule, new_rule);
5378 }
5379 } else if (ofm->modify_may_add_flow) {
5380 /* No match, add a new flow, consumes 'temp'. */
5381 error = add_flow_start(ofproto, ofm);
5382 } else {
5383 /* No flow to modify and may not add a flow. */
5384 ofproto_rule_unref(ofm->temp_rule);
5385 ofm->temp_rule = NULL; /* We consume the template. */
5386 error = 0;
5387 }
5388
5389 return error;
5390 }
5391
5392 static enum ofperr
5393 modify_flows_init_loose(struct ofproto *ofproto,
5394 struct ofproto_flow_mod *ofm,
5395 const struct ofputil_flow_mod *fm)
5396 OVS_EXCLUDED(ofproto_mutex)
5397 {
5398 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, 0,
5399 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask, OFPP_ANY,
5400 OFPG_ANY);
5401 rule_criteria_require_rw(&ofm->criteria,
5402 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5403 /* Must create a new flow in advance for the case that no matches are
5404 * found. Also used for template for multiple modified flows. */
5405 add_flow_init(ofproto, ofm, fm);
5406
5407 return 0;
5408 }
5409
5410 /* Implements OFPFC_MODIFY. Returns 0 on success or an OpenFlow error code on
5411 * failure. */
5412 static enum ofperr
5413 modify_flows_start_loose(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5414 OVS_REQUIRES(ofproto_mutex)
5415 {
5416 struct rule_collection *old_rules = &ofm->old_rules;
5417 enum ofperr error;
5418
5419 error = collect_rules_loose(ofproto, &ofm->criteria, old_rules);
5420
5421 if (!error) {
5422 error = modify_flows_start__(ofproto, ofm);
5423 }
5424
5425 if (error) {
5426 rule_collection_destroy(old_rules);
5427 }
5428
5429 return error;
5430 }
5431
5432 static void
5433 modify_flows_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5434 OVS_REQUIRES(ofproto_mutex)
5435 {
5436 struct rule_collection *old_rules = &ofm->old_rules;
5437 struct rule_collection *new_rules = &ofm->new_rules;
5438
5439 /* Old rules were not changed yet, only need to revert new rules. */
5440 if (rule_collection_n(old_rules) > 0) {
5441 struct rule *old_rule, *new_rule;
5442 RULE_COLLECTIONS_FOR_EACH (old_rule, new_rule, old_rules, new_rules) {
5443 replace_rule_revert(ofproto, old_rule, new_rule);
5444 }
5445 rule_collection_destroy(new_rules);
5446 rule_collection_destroy(old_rules);
5447 }
5448 }
5449
5450 static void
5451 modify_flows_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5452 const struct openflow_mod_requester *req)
5453 OVS_REQUIRES(ofproto_mutex)
5454 {
5455 struct rule_collection *old_rules = &ofm->old_rules;
5456 struct rule_collection *new_rules = &ofm->new_rules;
5457
5458 if (rule_collection_n(old_rules) == 0
5459 && rule_collection_n(new_rules) == 1) {
5460 add_flow_finish(ofproto, ofm, req);
5461 } else if (rule_collection_n(old_rules) > 0) {
5462 struct ovs_list dead_cookies = OVS_LIST_INITIALIZER(&dead_cookies);
5463
5464 ovs_assert(rule_collection_n(new_rules)
5465 == rule_collection_n(old_rules));
5466
5467 struct rule *old_rule, *new_rule;
5468 RULE_COLLECTIONS_FOR_EACH (old_rule, new_rule, old_rules, new_rules) {
5469 replace_rule_finish(ofproto, ofm, req, old_rule, new_rule,
5470 &dead_cookies);
5471 }
5472 learned_cookies_flush(ofproto, &dead_cookies);
5473 remove_rules_postponed(old_rules);
5474 }
5475 }
5476
5477 static enum ofperr
5478 modify_flow_init_strict(struct ofproto *ofproto OVS_UNUSED,
5479 struct ofproto_flow_mod *ofm,
5480 const struct ofputil_flow_mod *fm)
5481 OVS_EXCLUDED(ofproto_mutex)
5482 {
5483 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, fm->priority,
5484 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask, OFPP_ANY,
5485 OFPG_ANY);
5486 rule_criteria_require_rw(&ofm->criteria,
5487 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5488 /* Must create a new flow in advance for the case that no matches are
5489 * found. Also used for template for multiple modified flows. */
5490 add_flow_init(ofproto, ofm, fm);
5491
5492 return 0;
5493 }
5494
5495 /* Implements OFPFC_MODIFY_STRICT. Returns 0 on success or an OpenFlow error
5496 * code on failure. */
5497 static enum ofperr
5498 modify_flow_start_strict(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5499 OVS_REQUIRES(ofproto_mutex)
5500 {
5501 struct rule_collection *old_rules = &ofm->old_rules;
5502 enum ofperr error;
5503
5504 error = collect_rules_strict(ofproto, &ofm->criteria, old_rules);
5505
5506 if (!error) {
5507 /* collect_rules_strict() can return max 1 rule. */
5508 error = modify_flows_start__(ofproto, ofm);
5509 }
5510
5511 return error;
5512 }
5513 \f
5514 /* OFPFC_DELETE implementation. */
5515
5516 static void
5517 delete_flows_start__(struct ofproto *ofproto, ovs_version_t version,
5518 const struct rule_collection *rules)
5519 OVS_REQUIRES(ofproto_mutex)
5520 {
5521 struct rule *rule;
5522
5523 RULE_COLLECTION_FOR_EACH (rule, rules) {
5524 struct oftable *table = &ofproto->tables[rule->table_id];
5525
5526 table->n_flows--;
5527 cls_rule_make_invisible_in_version(&rule->cr, version);
5528
5529 /* Remove rule from ofproto data structures. */
5530 ofproto_rule_remove__(ofproto, rule);
5531 }
5532 }
5533
5534 static void
5535 delete_flows_revert__(struct ofproto *ofproto,
5536 const struct rule_collection *rules)
5537 OVS_REQUIRES(ofproto_mutex)
5538 {
5539 struct rule *rule;
5540
5541 RULE_COLLECTION_FOR_EACH (rule, rules) {
5542 struct oftable *table = &ofproto->tables[rule->table_id];
5543
5544 /* Add rule back to ofproto data structures. */
5545 ofproto_rule_insert__(ofproto, rule);
5546
5547 /* Restore table's rule count. */
5548 table->n_flows++;
5549
5550 /* Restore the original visibility of the rule. */
5551 cls_rule_restore_visibility(&rule->cr);
5552 }
5553 }
5554
5555 static void
5556 delete_flows_finish__(struct ofproto *ofproto,
5557 struct rule_collection *rules,
5558 enum ofp_flow_removed_reason reason,
5559 const struct openflow_mod_requester *req)
5560 OVS_REQUIRES(ofproto_mutex)
5561 {
5562 if (rule_collection_n(rules)) {
5563 struct ovs_list dead_cookies = OVS_LIST_INITIALIZER(&dead_cookies);
5564 struct rule *rule;
5565
5566 RULE_COLLECTION_FOR_EACH (rule, rules) {
5567 /* This value will be used to send the flow removed message right
5568 * before the rule is actually destroyed. */
5569 rule->removed_reason = reason;
5570
5571 ofmonitor_report(ofproto->connmgr, rule, NXFME_DELETED, reason,
5572 req ? req->ofconn : NULL,
5573 req ? req->request->xid : 0, NULL);
5574
5575 /* Send Vacancy Event for OF1.4+. */
5576 send_table_status(ofproto, rule->table_id);
5577
5578 learned_cookies_dec(ofproto, rule_get_actions(rule),
5579 &dead_cookies);
5580 }
5581 remove_rules_postponed(rules);
5582
5583 learned_cookies_flush(ofproto, &dead_cookies);
5584 }
5585 }
5586
5587 /* Deletes the rules listed in 'rules'.
5588 * The deleted rules will become invisible to the lookups in the next version.
5589 * Destroys 'rules'. */
5590 static void
5591 delete_flows__(struct rule_collection *rules,
5592 enum ofp_flow_removed_reason reason,
5593 const struct openflow_mod_requester *req)
5594 OVS_REQUIRES(ofproto_mutex)
5595 {
5596 if (rule_collection_n(rules)) {
5597 struct ofproto *ofproto = rule_collection_rules(rules)[0]->ofproto;
5598
5599 delete_flows_start__(ofproto, ofproto->tables_version + 1, rules);
5600 ofproto_bump_tables_version(ofproto);
5601 delete_flows_finish__(ofproto, rules, reason, req);
5602 ofmonitor_flush(ofproto->connmgr);
5603 }
5604 }
5605
5606 static enum ofperr
5607 delete_flows_init_loose(struct ofproto *ofproto OVS_UNUSED,
5608 struct ofproto_flow_mod *ofm,
5609 const struct ofputil_flow_mod *fm)
5610 OVS_EXCLUDED(ofproto_mutex)
5611 {
5612 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, 0,
5613 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask,
5614 fm->out_port, fm->out_group);
5615 rule_criteria_require_rw(&ofm->criteria,
5616 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5617 return 0;
5618 }
5619
5620 /* Implements OFPFC_DELETE. */
5621 static enum ofperr
5622 delete_flows_start_loose(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5623 OVS_REQUIRES(ofproto_mutex)
5624 {
5625 struct rule_collection *rules = &ofm->old_rules;
5626 enum ofperr error;
5627
5628 error = collect_rules_loose(ofproto, &ofm->criteria, rules);
5629
5630 if (!error) {
5631 delete_flows_start__(ofproto, ofm->version, rules);
5632 }
5633
5634 return error;
5635 }
5636
5637 static void
5638 delete_flows_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5639 OVS_REQUIRES(ofproto_mutex)
5640 {
5641 delete_flows_revert__(ofproto, &ofm->old_rules);
5642 }
5643
5644 static void
5645 delete_flows_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
5646 const struct openflow_mod_requester *req)
5647 OVS_REQUIRES(ofproto_mutex)
5648 {
5649 delete_flows_finish__(ofproto, &ofm->old_rules, OFPRR_DELETE, req);
5650 }
5651
5652 static enum ofperr
5653 delete_flows_init_strict(struct ofproto *ofproto OVS_UNUSED,
5654 struct ofproto_flow_mod *ofm,
5655 const struct ofputil_flow_mod *fm)
5656 OVS_EXCLUDED(ofproto_mutex)
5657 {
5658 rule_criteria_init(&ofm->criteria, fm->table_id, &fm->match, fm->priority,
5659 OVS_VERSION_MAX, fm->cookie, fm->cookie_mask,
5660 fm->out_port, fm->out_group);
5661 rule_criteria_require_rw(&ofm->criteria,
5662 (fm->flags & OFPUTIL_FF_NO_READONLY) != 0);
5663 return 0;
5664 }
5665
5666 /* Implements OFPFC_DELETE_STRICT. */
5667 static enum ofperr
5668 delete_flow_start_strict(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
5669 OVS_REQUIRES(ofproto_mutex)
5670 {
5671 struct rule_collection *rules = &ofm->old_rules;
5672 enum ofperr error;
5673
5674 error = collect_rules_strict(ofproto, &ofm->criteria, rules);
5675
5676 if (!error) {
5677 delete_flows_start__(ofproto, ofm->version, rules);
5678 }
5679
5680 return error;
5681 }
5682
5683 /* This may only be called by rule_destroy_cb()! */
5684 static void
5685 ofproto_rule_send_removed(struct rule *rule)
5686 OVS_EXCLUDED(ofproto_mutex)
5687 {
5688 struct ofputil_flow_removed fr;
5689 long long int used;
5690
5691 minimatch_expand(&rule->cr.match, &fr.match);
5692 fr.priority = rule->cr.priority;
5693
5694 /* Synchronize with connmgr_destroy() calls to prevent connmgr disappearing
5695 * while we use it. */
5696 ovs_mutex_lock(&ofproto_mutex);
5697 struct connmgr *connmgr = rule->ofproto->connmgr;
5698 if (!connmgr) {
5699 ovs_mutex_unlock(&ofproto_mutex);
5700 return;
5701 }
5702
5703 fr.cookie = rule->flow_cookie;
5704 fr.reason = rule->removed_reason;
5705 fr.table_id = rule->table_id;
5706 calc_duration(rule->created, time_msec(),
5707 &fr.duration_sec, &fr.duration_nsec);
5708 ovs_mutex_lock(&rule->mutex);
5709 fr.idle_timeout = rule->idle_timeout;
5710 fr.hard_timeout = rule->hard_timeout;
5711 ovs_mutex_unlock(&rule->mutex);
5712 rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
5713 &fr.byte_count, &used);
5714 connmgr_send_flow_removed(connmgr, &fr);
5715 ovs_mutex_unlock(&ofproto_mutex);
5716 }
5717
5718 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
5719 * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
5720 * ofproto.
5721 *
5722 * ofproto implementation ->run() functions should use this function to expire
5723 * OpenFlow flows. */
5724 void
5725 ofproto_rule_expire(struct rule *rule, uint8_t reason)
5726 OVS_REQUIRES(ofproto_mutex)
5727 {
5728 struct rule_collection rules;
5729
5730 rule_collection_init(&rules);
5731 rule_collection_add(&rules, rule);
5732 delete_flows__(&rules, reason, NULL);
5733 }
5734
5735 /* Reduces '*timeout' to no more than 'max'. A value of zero in either case
5736 * means "infinite". */
5737 static void
5738 reduce_timeout(uint16_t max, uint16_t *timeout)
5739 {
5740 if (max && (!*timeout || *timeout > max)) {
5741 *timeout = max;
5742 }
5743 }
5744
5745 /* If 'idle_timeout' is nonzero, and 'rule' has no idle timeout or an idle
5746 * timeout greater than 'idle_timeout', lowers 'rule''s idle timeout to
5747 * 'idle_timeout' seconds. Similarly for 'hard_timeout'.
5748 *
5749 * Suitable for implementing OFPACT_FIN_TIMEOUT. */
5750 void
5751 ofproto_rule_reduce_timeouts__(struct rule *rule,
5752 uint16_t idle_timeout, uint16_t hard_timeout)
5753 OVS_REQUIRES(ofproto_mutex)
5754 OVS_EXCLUDED(rule->mutex)
5755 {
5756 if (!idle_timeout && !hard_timeout) {
5757 return;
5758 }
5759
5760 if (ovs_list_is_empty(&rule->expirable)) {
5761 ovs_list_insert(&rule->ofproto->expirable, &rule->expirable);
5762 }
5763
5764 ovs_mutex_lock(&rule->mutex);
5765 reduce_timeout(idle_timeout, &rule->idle_timeout);
5766 reduce_timeout(hard_timeout, &rule->hard_timeout);
5767 ovs_mutex_unlock(&rule->mutex);
5768 }
5769
5770 void
5771 ofproto_rule_reduce_timeouts(struct rule *rule,
5772 uint16_t idle_timeout, uint16_t hard_timeout)
5773 OVS_EXCLUDED(ofproto_mutex, rule->mutex)
5774 {
5775 if (!idle_timeout && !hard_timeout) {
5776 return;
5777 }
5778
5779 ovs_mutex_lock(&ofproto_mutex);
5780 if (ovs_list_is_empty(&rule->expirable)) {
5781 ovs_list_insert(&rule->ofproto->expirable, &rule->expirable);
5782 }
5783 ovs_mutex_unlock(&ofproto_mutex);
5784
5785 ovs_mutex_lock(&rule->mutex);
5786 reduce_timeout(idle_timeout, &rule->idle_timeout);
5787 reduce_timeout(hard_timeout, &rule->hard_timeout);
5788 ovs_mutex_unlock(&rule->mutex);
5789 }
5790 \f
5791 static enum ofperr
5792 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
5793 OVS_EXCLUDED(ofproto_mutex)
5794 {
5795 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
5796 struct ofputil_flow_mod fm;
5797 uint64_t ofpacts_stub[1024 / 8];
5798 struct ofpbuf ofpacts;
5799 enum ofperr error;
5800
5801 error = reject_slave_controller(ofconn);
5802 if (error) {
5803 return error;
5804 }
5805
5806 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
5807 error = ofputil_decode_flow_mod(&fm, oh, ofconn_get_protocol(ofconn),
5808 ofproto_get_tun_tab(ofproto),
5809 &ofproto->vl_mff_map, &ofpacts,
5810 u16_to_ofp(ofproto->max_ports),
5811 ofproto->n_tables);
5812 if (!error) {
5813 struct openflow_mod_requester req = { ofconn, oh };
5814 error = handle_flow_mod__(ofproto, &fm, &req);
5815 }
5816
5817 ofpbuf_uninit(&ofpacts);
5818 return error;
5819 }
5820
5821 static enum ofperr
5822 handle_flow_mod__(struct ofproto *ofproto, const struct ofputil_flow_mod *fm,
5823 const struct openflow_mod_requester *req)
5824 OVS_EXCLUDED(ofproto_mutex)
5825 {
5826 struct ofproto_flow_mod ofm;
5827 enum ofperr error;
5828
5829 error = ofproto_flow_mod_init(ofproto, &ofm, fm, NULL);
5830 if (error) {
5831 return error;
5832 }
5833
5834 ovs_mutex_lock(&ofproto_mutex);
5835 ofm.version = ofproto->tables_version + 1;
5836 error = ofproto_flow_mod_start(ofproto, &ofm);
5837 if (!error) {
5838 ofproto_bump_tables_version(ofproto);
5839 ofproto_flow_mod_finish(ofproto, &ofm, req);
5840 ofmonitor_flush(ofproto->connmgr);
5841 }
5842 ovs_mutex_unlock(&ofproto_mutex);
5843
5844 return error;
5845 }
5846
5847 static enum ofperr
5848 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
5849 {
5850 struct ofputil_role_request request;
5851 struct ofputil_role_request reply;
5852 struct ofpbuf *buf;
5853 enum ofperr error;
5854
5855 error = ofputil_decode_role_message(oh, &request);
5856 if (error) {
5857 return error;
5858 }
5859
5860 if (request.role != OFPCR12_ROLE_NOCHANGE) {
5861 if (request.role != OFPCR12_ROLE_EQUAL
5862 && request.have_generation_id
5863 && !ofconn_set_master_election_id(ofconn, request.generation_id)) {
5864 return OFPERR_OFPRRFC_STALE;
5865 }
5866
5867 ofconn_set_role(ofconn, request.role);
5868 }
5869
5870 reply.role = ofconn_get_role(ofconn);
5871 reply.have_generation_id = ofconn_get_master_election_id(
5872 ofconn, &reply.generation_id);
5873 buf = ofputil_encode_role_reply(oh, &reply);
5874 ofconn_send_reply(ofconn, buf);
5875
5876 return 0;
5877 }
5878
5879 static enum ofperr
5880 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
5881 const struct ofp_header *oh)
5882 {
5883 const struct nx_flow_mod_table_id *msg = ofpmsg_body(oh);
5884 enum ofputil_protocol cur, next;
5885
5886 cur = ofconn_get_protocol(ofconn);
5887 next = ofputil_protocol_set_tid(cur, msg->set != 0);
5888 ofconn_set_protocol(ofconn, next);
5889
5890 return 0;
5891 }
5892
5893 static enum ofperr
5894 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
5895 {
5896 const struct nx_set_flow_format *msg = ofpmsg_body(oh);
5897 enum ofputil_protocol cur, next;
5898 enum ofputil_protocol next_base;
5899
5900 next_base = ofputil_nx_flow_format_to_protocol(ntohl(msg->format));
5901 if (!next_base) {
5902 return OFPERR_OFPBRC_EPERM;
5903 }
5904
5905 cur = ofconn_get_protocol(ofconn);
5906 next = ofputil_protocol_set_base(cur, next_base);
5907 ofconn_set_protocol(ofconn, next);
5908
5909 return 0;
5910 }
5911
5912 static enum ofperr
5913 handle_nxt_set_packet_in_format(struct ofconn *ofconn,
5914 const struct ofp_header *oh)
5915 {
5916 const struct nx_set_packet_in_format *msg = ofpmsg_body(oh);
5917 uint32_t format;
5918
5919 format = ntohl(msg->format);
5920 if (!ofputil_packet_in_format_is_valid(format)) {
5921 return OFPERR_OFPBRC_EPERM;
5922 }
5923
5924 ofconn_set_packet_in_format(ofconn, format);
5925 return 0;
5926 }
5927
5928 static enum ofperr
5929 handle_nxt_set_async_config(struct ofconn *ofconn, const struct ofp_header *oh)
5930 {
5931 struct ofputil_async_cfg basis = ofconn_get_async_config(ofconn);
5932 struct ofputil_async_cfg ac;
5933 enum ofperr error;
5934
5935 error = ofputil_decode_set_async_config(oh, false, &basis, &ac);
5936 if (error) {
5937 return error;
5938 }
5939
5940 ofconn_set_async_config(ofconn, &ac);
5941 if (ofconn_get_type(ofconn) == OFCONN_SERVICE &&
5942 !ofconn_get_miss_send_len(ofconn)) {
5943 ofconn_set_miss_send_len(ofconn, OFP_DEFAULT_MISS_SEND_LEN);
5944 }
5945
5946 return 0;
5947 }
5948
5949 static enum ofperr
5950 handle_nxt_get_async_request(struct ofconn *ofconn, const struct ofp_header *oh)
5951 {
5952 struct ofputil_async_cfg ac = ofconn_get_async_config(ofconn);
5953 ofconn_send_reply(ofconn, ofputil_encode_get_async_reply(oh, &ac));
5954
5955 return 0;
5956 }
5957
5958 static enum ofperr
5959 handle_nxt_set_controller_id(struct ofconn *ofconn,
5960 const struct ofp_header *oh)
5961 {
5962 const struct nx_controller_id *nci = ofpmsg_body(oh);
5963
5964 if (!is_all_zeros(nci->zero, sizeof nci->zero)) {
5965 return OFPERR_NXBRC_MUST_BE_ZERO;
5966 }
5967
5968 ofconn_set_controller_id(ofconn, ntohs(nci->controller_id));
5969 return 0;
5970 }
5971
5972 static enum ofperr
5973 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
5974 {
5975 struct ofpbuf *buf;
5976
5977 buf = ofpraw_alloc_reply((oh->version == OFP10_VERSION
5978 ? OFPRAW_OFPT10_BARRIER_REPLY
5979 : OFPRAW_OFPT11_BARRIER_REPLY), oh, 0);
5980 ofconn_send_reply(ofconn, buf);
5981 return 0;
5982 }
5983
5984 static void
5985 ofproto_compose_flow_refresh_update(const struct rule *rule,
5986 enum nx_flow_monitor_flags flags,
5987 struct ovs_list *msgs,
5988 const struct tun_table *tun_table)
5989 OVS_REQUIRES(ofproto_mutex)
5990 {
5991 const struct rule_actions *actions;
5992 struct ofputil_flow_update fu;
5993
5994 fu.event = (flags & (NXFMF_INITIAL | NXFMF_ADD)
5995 ? NXFME_ADDED : NXFME_MODIFIED);
5996 fu.reason = 0;
5997 ovs_mutex_lock(&rule->mutex);
5998 fu.idle_timeout = rule->idle_timeout;
5999 fu.hard_timeout = rule->hard_timeout;
6000 ovs_mutex_unlock(&rule->mutex);
6001 fu.table_id = rule->table_id;
6002 fu.cookie = rule->flow_cookie;
6003 minimatch_expand(&rule->cr.match, &fu.match);
6004 fu.priority = rule->cr.priority;
6005
6006 actions = flags & NXFMF_ACTIONS ? rule_get_actions(rule) : NULL;
6007 fu.ofpacts = actions ? actions->ofpacts : NULL;
6008 fu.ofpacts_len = actions ? actions->ofpacts_len : 0;
6009
6010 if (ovs_list_is_empty(msgs)) {
6011 ofputil_start_flow_update(msgs);
6012 }
6013 ofputil_append_flow_update(&fu, msgs, tun_table);
6014 }
6015
6016 void
6017 ofmonitor_compose_refresh_updates(struct rule_collection *rules,
6018 struct ovs_list *msgs)
6019 OVS_REQUIRES(ofproto_mutex)
6020 {
6021 struct rule *rule;
6022
6023 RULE_COLLECTION_FOR_EACH (rule, rules) {
6024 enum nx_flow_monitor_flags flags = rule->monitor_flags;
6025 rule->monitor_flags = 0;
6026
6027 ofproto_compose_flow_refresh_update(rule, flags, msgs,
6028 ofproto_get_tun_tab(rule->ofproto));
6029 }
6030 }
6031
6032 static void
6033 ofproto_collect_ofmonitor_refresh_rule(const struct ofmonitor *m,
6034 struct rule *rule, uint64_t seqno,
6035 struct rule_collection *rules)
6036 OVS_REQUIRES(ofproto_mutex)
6037 {
6038 enum nx_flow_monitor_flags update;
6039
6040 if (rule_is_hidden(rule)) {
6041 return;
6042 }
6043
6044 if (!ofproto_rule_has_out_port(rule, m->out_port)) {
6045 return;
6046 }
6047
6048 if (seqno) {
6049 if (rule->add_seqno > seqno) {
6050 update = NXFMF_ADD | NXFMF_MODIFY;
6051 } else if (rule->modify_seqno > seqno) {
6052 update = NXFMF_MODIFY;
6053 } else {
6054 return;
6055 }
6056
6057 if (!(m->flags & update)) {
6058 return;
6059 }
6060 } else {
6061 update = NXFMF_INITIAL;
6062 }
6063
6064 if (!rule->monitor_flags) {
6065 rule_collection_add(rules, rule);
6066 }
6067 rule->monitor_flags |= update | (m->flags & NXFMF_ACTIONS);
6068 }
6069
6070 static void
6071 ofproto_collect_ofmonitor_refresh_rules(const struct ofmonitor *m,
6072 uint64_t seqno,
6073 struct rule_collection *rules)
6074 OVS_REQUIRES(ofproto_mutex)
6075 {
6076 const struct ofproto *ofproto = ofconn_get_ofproto(m->ofconn);
6077 const struct oftable *table;
6078 struct cls_rule target;
6079
6080 cls_rule_init_from_minimatch(&target, &m->match, 0);
6081 FOR_EACH_MATCHING_TABLE (table, m->table_id, ofproto) {
6082 struct rule *rule;
6083
6084 CLS_FOR_EACH_TARGET (rule, cr, &table->cls, &target, OVS_VERSION_MAX) {
6085 ofproto_collect_ofmonitor_refresh_rule(m, rule, seqno, rules);
6086 }
6087 }
6088 cls_rule_destroy(&target);
6089 }
6090
6091 static void
6092 ofproto_collect_ofmonitor_initial_rules(struct ofmonitor *m,
6093 struct rule_collection *rules)
6094 OVS_REQUIRES(ofproto_mutex)
6095 {
6096 if (m->flags & NXFMF_INITIAL) {
6097 ofproto_collect_ofmonitor_refresh_rules(m, 0, rules);
6098 }
6099 }
6100
6101 void
6102 ofmonitor_collect_resume_rules(struct ofmonitor *m,
6103 uint64_t seqno, struct rule_collection *rules)
6104 OVS_REQUIRES(ofproto_mutex)
6105 {
6106 ofproto_collect_ofmonitor_refresh_rules(m, seqno, rules);
6107 }
6108
6109 static enum ofperr
6110 flow_monitor_delete(struct ofconn *ofconn, uint32_t id)
6111 OVS_REQUIRES(ofproto_mutex)
6112 {
6113 struct ofmonitor *m;
6114 enum ofperr error;
6115
6116 m = ofmonitor_lookup(ofconn, id);
6117 if (m) {
6118 ofmonitor_destroy(m);
6119 error = 0;
6120 } else {
6121 error = OFPERR_OFPMOFC_UNKNOWN_MONITOR;
6122 }
6123
6124 return error;
6125 }
6126
6127 static enum ofperr
6128 handle_flow_monitor_request(struct ofconn *ofconn, const struct ofp_header *oh)
6129 OVS_EXCLUDED(ofproto_mutex)
6130 {
6131 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6132
6133 struct ofpbuf b = ofpbuf_const_initializer(oh, ntohs(oh->length));
6134
6135 struct ofmonitor **monitors = NULL;
6136 size_t allocated_monitors = 0;
6137 size_t n_monitors = 0;
6138
6139 enum ofperr error;
6140
6141 ovs_mutex_lock(&ofproto_mutex);
6142 for (;;) {
6143 struct ofputil_flow_monitor_request request;
6144 struct ofmonitor *m;
6145 int retval;
6146
6147 retval = ofputil_decode_flow_monitor_request(&request, &b);
6148 if (retval == EOF) {
6149 break;
6150 } else if (retval) {
6151 error = retval;
6152 goto error;
6153 }
6154
6155 if (request.table_id != 0xff
6156 && request.table_id >= ofproto->n_tables) {
6157 error = OFPERR_OFPBRC_BAD_TABLE_ID;
6158 goto error;
6159 }
6160
6161 error = ofmonitor_create(&request, ofconn, &m);
6162 if (error) {
6163 goto error;
6164 }
6165
6166 if (n_monitors >= allocated_monitors) {
6167 monitors = x2nrealloc(monitors, &allocated_monitors,
6168 sizeof *monitors);
6169 }
6170 monitors[n_monitors++] = m;
6171 }
6172
6173 struct rule_collection rules;
6174 rule_collection_init(&rules);
6175 for (size_t i = 0; i < n_monitors; i++) {
6176 ofproto_collect_ofmonitor_initial_rules(monitors[i], &rules);
6177 }
6178
6179 struct ovs_list replies;
6180 ofpmp_init(&replies, oh);
6181 ofmonitor_compose_refresh_updates(&rules, &replies);
6182 ovs_mutex_unlock(&ofproto_mutex);
6183
6184 rule_collection_destroy(&rules);
6185
6186 ofconn_send_replies(ofconn, &replies);
6187 free(monitors);
6188
6189 return 0;
6190
6191 error:
6192 for (size_t i = 0; i < n_monitors; i++) {
6193 ofmonitor_destroy(monitors[i]);
6194 }
6195 free(monitors);
6196 ovs_mutex_unlock(&ofproto_mutex);
6197
6198 return error;
6199 }
6200
6201 static enum ofperr
6202 handle_flow_monitor_cancel(struct ofconn *ofconn, const struct ofp_header *oh)
6203 OVS_EXCLUDED(ofproto_mutex)
6204 {
6205 enum ofperr error;
6206 uint32_t id;
6207
6208 id = ofputil_decode_flow_monitor_cancel(oh);
6209
6210 ovs_mutex_lock(&ofproto_mutex);
6211 error = flow_monitor_delete(ofconn, id);
6212 ovs_mutex_unlock(&ofproto_mutex);
6213
6214 return error;
6215 }
6216
6217 /* Meters implementation.
6218 *
6219 * Meter table entry, indexed by the OpenFlow meter_id.
6220 * 'created' is used to compute the duration for meter stats.
6221 * 'list rules' is needed so that we can delete the dependent rules when the
6222 * meter table entry is deleted.
6223 * 'provider_meter_id' is for the provider's private use.
6224 */
6225 struct meter {
6226 struct hmap_node node; /* In ofproto->meters. */
6227 long long int created; /* Time created. */
6228 struct ovs_list rules; /* List of "struct rule_dpif"s. */
6229 uint32_t id; /* OpenFlow meter_id. */
6230 ofproto_meter_id provider_meter_id;
6231 uint16_t flags; /* Meter flags. */
6232 uint16_t n_bands; /* Number of meter bands. */
6233 struct ofputil_meter_band *bands;
6234 };
6235
6236 static struct meter *
6237 ofproto_get_meter(const struct ofproto *ofproto, uint32_t meter_id)
6238 {
6239 struct meter *meter;
6240 uint32_t hash = hash_int(meter_id, 0);
6241
6242 HMAP_FOR_EACH_WITH_HASH (meter, node, hash, &ofproto->meters) {
6243 if (meter->id == meter_id) {
6244 return meter;
6245 }
6246 }
6247
6248 return NULL;
6249 }
6250
6251 static uint32_t *
6252 ofproto_upcall_meter_ptr(struct ofproto *ofproto, uint32_t meter_id)
6253 {
6254 switch(meter_id) {
6255 case OFPM13_SLOWPATH:
6256 return &ofproto->slowpath_meter_id;
6257 break;
6258 case OFPM13_CONTROLLER:
6259 return &ofproto->controller_meter_id;
6260 break;
6261 case OFPM13_ALL:
6262 OVS_NOT_REACHED();
6263 default:
6264 return NULL;
6265 }
6266 }
6267
6268 static void
6269 ofproto_add_meter(struct ofproto *ofproto, struct meter *meter)
6270 {
6271 uint32_t *upcall_meter_ptr = ofproto_upcall_meter_ptr(ofproto, meter->id);
6272
6273 /* Cache datapath meter IDs of special meters. */
6274 if (upcall_meter_ptr) {
6275 *upcall_meter_ptr = meter->provider_meter_id.uint32;
6276 }
6277
6278 hmap_insert(&ofproto->meters, &meter->node, hash_int(meter->id, 0));
6279 }
6280
6281 /*
6282 * This is used in instruction validation at flow set-up time, to map
6283 * the OpenFlow meter ID to the corresponding datapath provider meter
6284 * ID. If either does not exist, returns false. Otherwise updates
6285 * the meter action and returns true.
6286 */
6287 static bool
6288 ofproto_fix_meter_action(const struct ofproto *ofproto,
6289 struct ofpact_meter *ma)
6290 {
6291 if (ma->meter_id) {
6292 const struct meter *meter = ofproto_get_meter(ofproto, ma->meter_id);
6293
6294 if (meter && meter->provider_meter_id.uint32 != UINT32_MAX) {
6295 /* Update the action with the provider's meter ID, so that we
6296 * do not need any synchronization between ofproto_dpif_xlate
6297 * and ofproto for meter table access. */
6298 ma->provider_meter_id = meter->provider_meter_id.uint32;
6299 return true;
6300 }
6301 }
6302 return false;
6303 }
6304
6305 /* Finds the meter invoked by 'rule''s actions and adds 'rule' to the meter's
6306 * list of rules. */
6307 static void
6308 meter_insert_rule(struct rule *rule)
6309 {
6310 const struct rule_actions *a = rule_get_actions(rule);
6311 uint32_t meter_id = ofpacts_get_meter(a->ofpacts, a->ofpacts_len);
6312 struct meter *meter = ofproto_get_meter(rule->ofproto, meter_id);
6313
6314 ovs_list_insert(&meter->rules, &rule->meter_list_node);
6315 }
6316
6317 static void
6318 meter_update(struct meter *meter, const struct ofputil_meter_config *config)
6319 {
6320 free(meter->bands);
6321
6322 meter->flags = config->flags;
6323 meter->n_bands = config->n_bands;
6324 meter->bands = xmemdup(config->bands,
6325 config->n_bands * sizeof *meter->bands);
6326 }
6327
6328 static struct meter *
6329 meter_create(const struct ofputil_meter_config *config,
6330 ofproto_meter_id provider_meter_id)
6331 {
6332 struct meter *meter;
6333
6334 meter = xzalloc(sizeof *meter);
6335 meter->provider_meter_id = provider_meter_id;
6336 meter->created = time_msec();
6337 meter->id = config->meter_id;
6338 ovs_list_init(&meter->rules);
6339
6340 meter_update(meter, config);
6341
6342 return meter;
6343 }
6344
6345 static void
6346 meter_destroy(struct ofproto *ofproto, struct meter *meter)
6347 OVS_REQUIRES(ofproto_mutex)
6348 {
6349 uint32_t *upcall_meter_ptr;
6350 upcall_meter_ptr = ofproto_upcall_meter_ptr(ofproto, meter->id);
6351 if (upcall_meter_ptr) {
6352 *upcall_meter_ptr = UINT32_MAX;
6353 }
6354
6355 if (!ovs_list_is_empty(&meter->rules)) {
6356 struct rule_collection rules;
6357 struct rule *rule;
6358
6359 rule_collection_init(&rules);
6360 LIST_FOR_EACH (rule, meter_list_node, &meter->rules) {
6361 rule_collection_add(&rules, rule);
6362 }
6363 delete_flows__(&rules, OFPRR_METER_DELETE, NULL);
6364 }
6365
6366 ofproto->ofproto_class->meter_del(ofproto, meter->provider_meter_id);
6367 free(meter->bands);
6368 free(meter);
6369 }
6370
6371 static void
6372 meter_delete(struct ofproto *ofproto, uint32_t meter_id)
6373 OVS_REQUIRES(ofproto_mutex)
6374 {
6375 struct meter *meter = ofproto_get_meter(ofproto, meter_id);
6376
6377 if (meter) {
6378 hmap_remove(&ofproto->meters, &meter->node);
6379 meter_destroy(ofproto, meter);
6380 }
6381 }
6382
6383 static void
6384 meter_delete_all(struct ofproto *ofproto)
6385 OVS_REQUIRES(ofproto_mutex)
6386 {
6387 struct meter *meter, *next;
6388
6389 HMAP_FOR_EACH_SAFE (meter, next, node, &ofproto->meters) {
6390 hmap_remove(&ofproto->meters, &meter->node);
6391 meter_destroy(ofproto, meter);
6392 }
6393 }
6394
6395 static enum ofperr
6396 handle_add_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
6397 {
6398 ofproto_meter_id provider_meter_id = { UINT32_MAX };
6399 struct meter *meter = ofproto_get_meter(ofproto, mm->meter.meter_id);
6400 enum ofperr error;
6401
6402 if (meter) {
6403 return OFPERR_OFPMMFC_METER_EXISTS;
6404 }
6405
6406 error = ofproto->ofproto_class->meter_set(ofproto, &provider_meter_id,
6407 &mm->meter);
6408 if (!error) {
6409 ovs_assert(provider_meter_id.uint32 != UINT32_MAX);
6410 meter = meter_create(&mm->meter, provider_meter_id);
6411 ofproto_add_meter(ofproto, meter);
6412 }
6413 return error;
6414 }
6415
6416 static enum ofperr
6417 handle_modify_meter(struct ofproto *ofproto, struct ofputil_meter_mod *mm)
6418 {
6419 struct meter *meter = ofproto_get_meter(ofproto, mm->meter.meter_id);
6420 enum ofperr error;
6421 uint32_t provider_meter_id;
6422
6423 if (!meter) {
6424 return OFPERR_OFPMMFC_UNKNOWN_METER;
6425 }
6426
6427 provider_meter_id = meter->provider_meter_id.uint32;
6428 error = ofproto->ofproto_class->meter_set(ofproto,
6429 &meter->provider_meter_id,
6430 &mm->meter);
6431 ovs_assert(meter->provider_meter_id.uint32 == provider_meter_id);
6432 if (!error) {
6433 meter_update(meter, &mm->meter);
6434 }
6435 return error;
6436 }
6437
6438 static enum ofperr
6439 handle_delete_meter(struct ofconn *ofconn, struct ofputil_meter_mod *mm)
6440 OVS_EXCLUDED(ofproto_mutex)
6441 {
6442 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6443 uint32_t meter_id = mm->meter.meter_id;
6444
6445 /* OpenFlow does not support Meter ID 0. */
6446 if (meter_id) {
6447 ovs_mutex_lock(&ofproto_mutex);
6448
6449 if (meter_id == OFPM13_ALL) {
6450 meter_delete_all(ofproto);
6451 } else {
6452 meter_delete(ofproto, meter_id);
6453 }
6454
6455 ovs_mutex_unlock(&ofproto_mutex);
6456 }
6457
6458 return 0;
6459 }
6460
6461 static enum ofperr
6462 handle_meter_mod(struct ofconn *ofconn, const struct ofp_header *oh)
6463 {
6464 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6465 struct ofputil_meter_mod mm;
6466 uint64_t bands_stub[256 / 8];
6467 struct ofpbuf bands;
6468 uint32_t meter_id;
6469 enum ofperr error;
6470
6471 error = reject_slave_controller(ofconn);
6472 if (error) {
6473 return error;
6474 }
6475
6476 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
6477
6478 error = ofputil_decode_meter_mod(oh, &mm, &bands);
6479 if (error) {
6480 goto exit_free_bands;
6481 }
6482
6483 meter_id = mm.meter.meter_id;
6484
6485 if (mm.command != OFPMC13_DELETE) {
6486 /* Fails also when meters are not implemented by the provider. */
6487 if (ofproto->meter_features.max_meters == 0) {
6488 error = OFPERR_OFPMMFC_INVALID_METER;
6489 goto exit_free_bands;
6490 }
6491
6492 if (meter_id == 0) {
6493 error = OFPERR_OFPMMFC_INVALID_METER;
6494 goto exit_free_bands;
6495 } else if (meter_id > OFPM13_MAX) {
6496 switch(meter_id) {
6497 case OFPM13_SLOWPATH:
6498 case OFPM13_CONTROLLER:
6499 break;
6500 case OFPM13_ALL:
6501 default:
6502 error = OFPERR_OFPMMFC_INVALID_METER;
6503 goto exit_free_bands;
6504 }
6505 }
6506 if (mm.meter.n_bands > ofproto->meter_features.max_bands) {
6507 error = OFPERR_OFPMMFC_OUT_OF_BANDS;
6508 goto exit_free_bands;
6509 }
6510 }
6511
6512 switch (mm.command) {
6513 case OFPMC13_ADD:
6514 error = handle_add_meter(ofproto, &mm);
6515 break;
6516
6517 case OFPMC13_MODIFY:
6518 error = handle_modify_meter(ofproto, &mm);
6519 break;
6520
6521 case OFPMC13_DELETE:
6522 error = handle_delete_meter(ofconn, &mm);
6523 break;
6524
6525 default:
6526 error = OFPERR_OFPMMFC_BAD_COMMAND;
6527 break;
6528 }
6529
6530 if (!error) {
6531 struct ofputil_requestforward rf;
6532 rf.xid = oh->xid;
6533 rf.reason = OFPRFR_METER_MOD;
6534 rf.meter_mod = &mm;
6535 connmgr_send_requestforward(ofproto->connmgr, ofconn, &rf);
6536 }
6537
6538 exit_free_bands:
6539 ofpbuf_uninit(&bands);
6540 return error;
6541 }
6542
6543 static enum ofperr
6544 handle_meter_features_request(struct ofconn *ofconn,
6545 const struct ofp_header *request)
6546 {
6547 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6548 struct ofputil_meter_features features;
6549 struct ofpbuf *b;
6550
6551 if (ofproto->ofproto_class->meter_get_features) {
6552 ofproto->ofproto_class->meter_get_features(ofproto, &features);
6553 } else {
6554 memset(&features, 0, sizeof features);
6555 }
6556 b = ofputil_encode_meter_features_reply(&features, request);
6557
6558 ofconn_send_reply(ofconn, b);
6559 return 0;
6560 }
6561
6562 static void
6563 meter_request_reply(struct ofproto *ofproto, struct meter *meter,
6564 enum ofptype type, struct ovs_list *replies)
6565 {
6566 uint64_t bands_stub[256 / 8];
6567 struct ofpbuf bands;
6568
6569 ofpbuf_use_stub(&bands, bands_stub, sizeof bands_stub);
6570
6571 if (type == OFPTYPE_METER_STATS_REQUEST) {
6572 struct ofputil_meter_stats stats;
6573
6574 stats.meter_id = meter->id;
6575
6576 /* Provider sets the packet and byte counts, we do the rest. */
6577 stats.flow_count = ovs_list_size(&meter->rules);
6578 calc_duration(meter->created, time_msec(),
6579 &stats.duration_sec, &stats.duration_nsec);
6580 stats.n_bands = meter->n_bands;
6581 ofpbuf_clear(&bands);
6582 stats.bands = ofpbuf_put_uninit(&bands, meter->n_bands
6583 * sizeof *stats.bands);
6584
6585 if (!ofproto->ofproto_class->meter_get(ofproto,
6586 meter->provider_meter_id,
6587 &stats, meter->n_bands)) {
6588 ofputil_append_meter_stats(replies, &stats);
6589 }
6590 } else { /* type == OFPTYPE_METER_CONFIG_REQUEST */
6591 struct ofputil_meter_config config;
6592
6593 config.meter_id = meter->id;
6594 config.flags = meter->flags;
6595 config.n_bands = meter->n_bands;
6596 config.bands = meter->bands;
6597 ofputil_append_meter_config(replies, &config);
6598 }
6599
6600 ofpbuf_uninit(&bands);
6601 }
6602
6603 static void
6604 meter_request_reply_all(struct ofproto *ofproto, enum ofptype type,
6605 struct ovs_list *replies)
6606 {
6607 struct meter *meter;
6608
6609 HMAP_FOR_EACH (meter, node, &ofproto->meters) {
6610 meter_request_reply(ofproto, meter, type, replies);
6611 }
6612 }
6613
6614 static enum ofperr
6615 handle_meter_request(struct ofconn *ofconn, const struct ofp_header *request,
6616 enum ofptype type)
6617 {
6618 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6619 struct ovs_list replies;
6620 uint32_t meter_id;
6621 struct meter *meter;
6622
6623 ofputil_decode_meter_request(request, &meter_id);
6624
6625 if (meter_id != OFPM13_ALL) {
6626 meter = ofproto_get_meter(ofproto, meter_id);
6627 if (!meter) {
6628 /* Meter does not exist. */
6629 return OFPERR_OFPMMFC_UNKNOWN_METER;
6630 }
6631 } else {
6632 /* GCC 4.9.2 complains about 'meter' can potentially be used
6633 * uninitialized. Logically, this is a false alarm since
6634 * meter is only used when meter_id != OFPM13_ALL.
6635 * Set NULL to make compiler happy. */
6636 meter = NULL;
6637 }
6638
6639 ofpmp_init(&replies, request);
6640 if (meter_id == OFPM13_ALL) {
6641 meter_request_reply_all(ofproto, type, &replies);
6642 } else {
6643 meter_request_reply(ofproto, meter, type, &replies);
6644 }
6645 ofconn_send_replies(ofconn, &replies);
6646 return 0;
6647 }
6648
6649 /* Returned group is RCU protected. */
6650 static struct ofgroup *
6651 ofproto_group_lookup__(const struct ofproto *ofproto, uint32_t group_id,
6652 ovs_version_t version)
6653 {
6654 struct ofgroup *group;
6655
6656 CMAP_FOR_EACH_WITH_HASH (group, cmap_node, hash_int(group_id, 0),
6657 &ofproto->groups) {
6658 if (group->group_id == group_id
6659 && versions_visible_in_version(&group->versions, version)) {
6660 return group;
6661 }
6662 }
6663
6664 return NULL;
6665 }
6666
6667 /* If the group exists, this function increments the groups's reference count.
6668 *
6669 * Make sure to call ofproto_group_unref() after no longer needing to maintain
6670 * a reference to the group. */
6671 struct ofgroup *
6672 ofproto_group_lookup(const struct ofproto *ofproto, uint32_t group_id,
6673 ovs_version_t version, bool take_ref)
6674 {
6675 struct ofgroup *group;
6676
6677 group = ofproto_group_lookup__(ofproto, group_id, version);
6678 if (group && take_ref) {
6679 /* Not holding a lock, so it is possible that another thread releases
6680 * the last reference just before we manage to get one. */
6681 return ofproto_group_try_ref(group) ? group : NULL;
6682 }
6683 return group;
6684 }
6685
6686 /* Caller should hold 'ofproto_mutex' if it is important that the
6687 * group is not removed by someone else. */
6688 static bool
6689 ofproto_group_exists(const struct ofproto *ofproto, uint32_t group_id)
6690 {
6691 return ofproto_group_lookup__(ofproto, group_id, OVS_VERSION_MAX) != NULL;
6692 }
6693
6694 static void
6695 group_add_rule(struct ofgroup *group, struct rule *rule)
6696 {
6697 rule_collection_add(&group->rules, rule);
6698 }
6699
6700 static void
6701 group_remove_rule(struct ofgroup *group, struct rule *rule)
6702 {
6703 rule_collection_remove(&group->rules, rule);
6704 }
6705
6706 static void
6707 append_group_stats(struct ofgroup *group, struct ovs_list *replies)
6708 OVS_REQUIRES(ofproto_mutex)
6709 {
6710 struct ofputil_group_stats ogs;
6711 const struct ofproto *ofproto = group->ofproto;
6712 long long int now = time_msec();
6713 int error;
6714
6715 ogs.bucket_stats = xmalloc(group->n_buckets * sizeof *ogs.bucket_stats);
6716
6717 /* Provider sets the packet and byte counts, we do the rest. */
6718 ogs.ref_count = rule_collection_n(&group->rules);
6719 ogs.n_buckets = group->n_buckets;
6720
6721 error = (ofproto->ofproto_class->group_get_stats
6722 ? ofproto->ofproto_class->group_get_stats(group, &ogs)
6723 : EOPNOTSUPP);
6724 if (error) {
6725 ogs.packet_count = UINT64_MAX;
6726 ogs.byte_count = UINT64_MAX;
6727 memset(ogs.bucket_stats, 0xff,
6728 ogs.n_buckets * sizeof *ogs.bucket_stats);
6729 }
6730
6731 ogs.group_id = group->group_id;
6732 calc_duration(group->created, now, &ogs.duration_sec, &ogs.duration_nsec);
6733
6734 ofputil_append_group_stats(replies, &ogs);
6735
6736 free(ogs.bucket_stats);
6737 }
6738
6739 static void
6740 handle_group_request(struct ofconn *ofconn,
6741 const struct ofp_header *request, uint32_t group_id,
6742 void (*cb)(struct ofgroup *, struct ovs_list *replies))
6743 OVS_EXCLUDED(ofproto_mutex)
6744 {
6745 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6746 struct ofgroup *group;
6747 struct ovs_list replies;
6748
6749 ofpmp_init(&replies, request);
6750 /* Must exclude modifications to guarantee iterating groups. */
6751 ovs_mutex_lock(&ofproto_mutex);
6752 if (group_id == OFPG_ALL) {
6753 CMAP_FOR_EACH (group, cmap_node, &ofproto->groups) {
6754 if (versions_visible_in_version(&group->versions,
6755 OVS_VERSION_MAX)) {
6756 cb(group, &replies);
6757 }
6758 }
6759 } else {
6760 group = ofproto_group_lookup__(ofproto, group_id, OVS_VERSION_MAX);
6761 if (group) {
6762 cb(group, &replies);
6763 }
6764 }
6765 ovs_mutex_unlock(&ofproto_mutex);
6766 ofconn_send_replies(ofconn, &replies);
6767 }
6768
6769 static enum ofperr
6770 handle_group_stats_request(struct ofconn *ofconn,
6771 const struct ofp_header *request)
6772 {
6773 uint32_t group_id;
6774 enum ofperr error;
6775
6776 error = ofputil_decode_group_stats_request(request, &group_id);
6777 if (error) {
6778 return error;
6779 }
6780
6781 handle_group_request(ofconn, request, group_id, append_group_stats);
6782 return 0;
6783 }
6784
6785 static void
6786 append_group_desc(struct ofgroup *group, struct ovs_list *replies)
6787 {
6788 struct ofputil_group_desc gds;
6789
6790 gds.group_id = group->group_id;
6791 gds.type = group->type;
6792 gds.props = group->props;
6793
6794 ofputil_append_group_desc_reply(&gds, &group->buckets, replies);
6795 }
6796
6797 static enum ofperr
6798 handle_group_desc_stats_request(struct ofconn *ofconn,
6799 const struct ofp_header *request)
6800 {
6801 handle_group_request(ofconn, request,
6802 ofputil_decode_group_desc_request(request),
6803 append_group_desc);
6804 return 0;
6805 }
6806
6807 static enum ofperr
6808 handle_group_features_stats_request(struct ofconn *ofconn,
6809 const struct ofp_header *request)
6810 {
6811 struct ofproto *p = ofconn_get_ofproto(ofconn);
6812 struct ofpbuf *msg;
6813
6814 msg = ofputil_encode_group_features_reply(&p->ogf, request);
6815 if (msg) {
6816 ofconn_send_reply(ofconn, msg);
6817 }
6818
6819 return 0;
6820 }
6821
6822 static void
6823 put_queue_get_config_reply(struct ofport *port, uint32_t queue,
6824 struct ovs_list *replies)
6825 {
6826 struct ofputil_queue_config qc;
6827
6828 /* None of the existing queues have compatible properties, so we hard-code
6829 * omitting min_rate and max_rate. */
6830 qc.port = port->ofp_port;
6831 qc.queue = queue;
6832 qc.min_rate = UINT16_MAX;
6833 qc.max_rate = UINT16_MAX;
6834 ofputil_append_queue_get_config_reply(&qc, replies);
6835 }
6836
6837 static int
6838 handle_queue_get_config_request_for_port(struct ofport *port, uint32_t queue,
6839 struct ovs_list *replies)
6840 {
6841 struct smap details = SMAP_INITIALIZER(&details);
6842 if (queue != OFPQ_ALL) {
6843 int error = netdev_get_queue(port->netdev, queue, &details);
6844 switch (error) {
6845 case 0:
6846 put_queue_get_config_reply(port, queue, replies);
6847 break;
6848 case EOPNOTSUPP:
6849 case EINVAL:
6850 return OFPERR_OFPQOFC_BAD_QUEUE;
6851 default:
6852 return OFPERR_NXQOFC_QUEUE_ERROR;
6853 }
6854 } else {
6855 struct netdev_queue_dump queue_dump;
6856 uint32_t queue_id;
6857
6858 NETDEV_QUEUE_FOR_EACH (&queue_id, &details, &queue_dump,
6859 port->netdev) {
6860 put_queue_get_config_reply(port, queue_id, replies);
6861 }
6862 }
6863 smap_destroy(&details);
6864 return 0;
6865 }
6866
6867 static enum ofperr
6868 handle_queue_get_config_request(struct ofconn *ofconn,
6869 const struct ofp_header *oh)
6870 {
6871 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
6872 struct ovs_list replies;
6873 struct ofport *port;
6874 ofp_port_t req_port;
6875 uint32_t req_queue;
6876 enum ofperr error;
6877
6878 error = ofputil_decode_queue_get_config_request(oh, &req_port, &req_queue);
6879 if (error) {
6880 return error;
6881 }
6882
6883 ofputil_start_queue_get_config_reply(oh, &replies);
6884 if (req_port == OFPP_ANY) {
6885 error = OFPERR_OFPQOFC_BAD_QUEUE;
6886 HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
6887 if (!handle_queue_get_config_request_for_port(port, req_queue,
6888 &replies)) {
6889 error = 0;
6890 }
6891 }
6892 } else {
6893 port = ofproto_get_port(ofproto, req_port);
6894 error = (port
6895 ? handle_queue_get_config_request_for_port(port, req_queue,
6896 &replies)
6897 : OFPERR_OFPQOFC_BAD_PORT);
6898 }
6899 if (!error) {
6900 ofconn_send_replies(ofconn, &replies);
6901 } else {
6902 ofpbuf_list_delete(&replies);
6903 }
6904
6905 return error;
6906 }
6907
6908 static enum ofperr
6909 init_group(struct ofproto *ofproto, const struct ofputil_group_mod *gm,
6910 ovs_version_t version, struct ofgroup **ofgroup)
6911 {
6912 enum ofperr error;
6913 const long long int now = time_msec();
6914
6915 if (gm->group_id > OFPG_MAX) {
6916 return OFPERR_OFPGMFC_INVALID_GROUP;
6917 }
6918 if (gm->type > OFPGT11_FF) {
6919 return OFPERR_OFPGMFC_BAD_TYPE;
6920 }
6921
6922 *ofgroup = ofproto->ofproto_class->group_alloc();
6923 if (!*ofgroup) {
6924 VLOG_WARN_RL(&rl, "%s: failed to allocate group", ofproto->name);
6925 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
6926 }
6927
6928 *CONST_CAST(struct ofproto **, &(*ofgroup)->ofproto) = ofproto;
6929 *CONST_CAST(uint32_t *, &((*ofgroup)->group_id)) = gm->group_id;
6930 *CONST_CAST(enum ofp11_group_type *, &(*ofgroup)->type) = gm->type;
6931 *CONST_CAST(long long int *, &((*ofgroup)->created)) = now;
6932 *CONST_CAST(long long int *, &((*ofgroup)->modified)) = now;
6933 ovs_refcount_init(&(*ofgroup)->ref_count);
6934 (*ofgroup)->being_deleted = false;
6935
6936 ovs_list_init(CONST_CAST(struct ovs_list *, &(*ofgroup)->buckets));
6937 ofputil_bucket_clone_list(CONST_CAST(struct ovs_list *,
6938 &(*ofgroup)->buckets),
6939 &gm->buckets, NULL);
6940
6941 *CONST_CAST(uint32_t *, &(*ofgroup)->n_buckets) =
6942 ovs_list_size(&(*ofgroup)->buckets);
6943
6944 ofputil_group_properties_copy(CONST_CAST(struct ofputil_group_props *,
6945 &(*ofgroup)->props),
6946 &gm->props);
6947 rule_collection_init(&(*ofgroup)->rules);
6948
6949 /* Make group visible from 'version'. */
6950 (*ofgroup)->versions = VERSIONS_INITIALIZER(version,
6951 OVS_VERSION_NOT_REMOVED);
6952
6953 /* Construct called BEFORE any locks are held. */
6954 error = ofproto->ofproto_class->group_construct(*ofgroup);
6955 if (error) {
6956 ofputil_group_properties_destroy(CONST_CAST(struct ofputil_group_props *,
6957 &(*ofgroup)->props));
6958 ofputil_bucket_list_destroy(CONST_CAST(struct ovs_list *,
6959 &(*ofgroup)->buckets));
6960 ofproto->ofproto_class->group_dealloc(*ofgroup);
6961 }
6962 return error;
6963 }
6964
6965 /* Implements the OFPGC11_ADD operation specified by 'gm', adding a group to
6966 * 'ofproto''s group table. Returns 0 on success or an OpenFlow error code on
6967 * failure. */
6968 static enum ofperr
6969 add_group_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
6970 OVS_REQUIRES(ofproto_mutex)
6971 {
6972 enum ofperr error;
6973
6974 if (ofproto_group_exists(ofproto, ogm->gm.group_id)) {
6975 return OFPERR_OFPGMFC_GROUP_EXISTS;
6976 }
6977
6978 if (ofproto->n_groups[ogm->gm.type]
6979 >= ofproto->ogf.max_groups[ogm->gm.type]) {
6980 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
6981 }
6982
6983 /* Allocate new group and initialize it. */
6984 error = init_group(ofproto, &ogm->gm, ogm->version, &ogm->new_group);
6985 if (!error) {
6986 /* Insert new group. */
6987 cmap_insert(&ofproto->groups, &ogm->new_group->cmap_node,
6988 hash_int(ogm->new_group->group_id, 0));
6989 ofproto->n_groups[ogm->new_group->type]++;
6990 }
6991 return error;
6992 }
6993
6994 /* Adds all of the buckets from 'ofgroup' to 'new_ofgroup'. The buckets
6995 * already in 'new_ofgroup' will be placed just after the (copy of the) bucket
6996 * in 'ofgroup' with bucket ID 'command_bucket_id'. Special
6997 * 'command_bucket_id' values OFPG15_BUCKET_FIRST and OFPG15_BUCKET_LAST are
6998 * also honored. */
6999 static enum ofperr
7000 copy_buckets_for_insert_bucket(const struct ofgroup *ofgroup,
7001 struct ofgroup *new_ofgroup,
7002 uint32_t command_bucket_id)
7003 {
7004 struct ofputil_bucket *last = NULL;
7005
7006 if (command_bucket_id <= OFPG15_BUCKET_MAX) {
7007 /* Check here to ensure that a bucket corresponding to
7008 * command_bucket_id exists in the old bucket list.
7009 *
7010 * The subsequent search of below of new_ofgroup covers
7011 * both buckets in the old bucket list and buckets added
7012 * by the insert buckets group mod message this function processes. */
7013 if (!ofputil_bucket_find(&ofgroup->buckets, command_bucket_id)) {
7014 return OFPERR_OFPGMFC_UNKNOWN_BUCKET;
7015 }
7016
7017 if (!ovs_list_is_empty(&new_ofgroup->buckets)) {
7018 last = ofputil_bucket_list_back(&new_ofgroup->buckets);
7019 }
7020 }
7021
7022 ofputil_bucket_clone_list(CONST_CAST(struct ovs_list *,
7023 &new_ofgroup->buckets),
7024 &ofgroup->buckets, NULL);
7025
7026 if (ofputil_bucket_check_duplicate_id(&new_ofgroup->buckets)) {
7027 VLOG_INFO_RL(&rl, "Duplicate bucket id");
7028 return OFPERR_OFPGMFC_BUCKET_EXISTS;
7029 }
7030
7031 /* Rearrange list according to command_bucket_id */
7032 if (command_bucket_id == OFPG15_BUCKET_LAST) {
7033 if (!ovs_list_is_empty(&ofgroup->buckets)) {
7034 struct ofputil_bucket *new_first;
7035 const struct ofputil_bucket *first;
7036
7037 first = ofputil_bucket_list_front(&ofgroup->buckets);
7038 new_first = ofputil_bucket_find(&new_ofgroup->buckets,
7039 first->bucket_id);
7040
7041 ovs_list_splice(new_ofgroup->buckets.next, &new_first->list_node,
7042 CONST_CAST(struct ovs_list *,
7043 &new_ofgroup->buckets));
7044 }
7045 } else if (command_bucket_id <= OFPG15_BUCKET_MAX && last) {
7046 struct ofputil_bucket *after;
7047
7048 /* Presence of bucket is checked above so after should never be NULL */
7049 after = ofputil_bucket_find(&new_ofgroup->buckets, command_bucket_id);
7050
7051 ovs_list_splice(after->list_node.next, new_ofgroup->buckets.next,
7052 last->list_node.next);
7053 }
7054
7055 return 0;
7056 }
7057
7058 /* Appends all of the a copy of all the buckets from 'ofgroup' to 'new_ofgroup'
7059 * with the exception of the bucket whose bucket id is 'command_bucket_id'.
7060 * Special 'command_bucket_id' values OFPG15_BUCKET_FIRST, OFPG15_BUCKET_LAST
7061 * and OFPG15_BUCKET_ALL are also honored. */
7062 static enum ofperr
7063 copy_buckets_for_remove_bucket(const struct ofgroup *ofgroup,
7064 struct ofgroup *new_ofgroup,
7065 uint32_t command_bucket_id)
7066 {
7067 const struct ofputil_bucket *skip = NULL;
7068
7069 if (command_bucket_id == OFPG15_BUCKET_ALL) {
7070 return 0;
7071 }
7072
7073 if (command_bucket_id == OFPG15_BUCKET_FIRST) {
7074 if (!ovs_list_is_empty(&ofgroup->buckets)) {
7075 skip = ofputil_bucket_list_front(&ofgroup->buckets);
7076 }
7077 } else if (command_bucket_id == OFPG15_BUCKET_LAST) {
7078 if (!ovs_list_is_empty(&ofgroup->buckets)) {
7079 skip = ofputil_bucket_list_back(&ofgroup->buckets);
7080 }
7081 } else {
7082 skip = ofputil_bucket_find(&ofgroup->buckets, command_bucket_id);
7083 if (!skip) {
7084 return OFPERR_OFPGMFC_UNKNOWN_BUCKET;
7085 }
7086 }
7087
7088 ofputil_bucket_clone_list(CONST_CAST(struct ovs_list *,
7089 &new_ofgroup->buckets),
7090 &ofgroup->buckets, skip);
7091
7092 return 0;
7093 }
7094
7095 /* Implements OFPGC11_MODIFY, OFPGC15_INSERT_BUCKET and
7096 * OFPGC15_REMOVE_BUCKET. Returns 0 on success or an OpenFlow error code
7097 * on failure.
7098 *
7099 * Note that the group is re-created and then replaces the old group in
7100 * ofproto's ofgroup hash map. Thus, the group is never altered while users of
7101 * the xlate module hold a pointer to the group. */
7102 static enum ofperr
7103 modify_group_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
7104 OVS_REQUIRES(ofproto_mutex)
7105 {
7106 struct ofgroup *old_group; /* Modified group. */
7107 struct ofgroup *new_group;
7108 enum ofperr error;
7109
7110 old_group = ofproto_group_lookup__(ofproto, ogm->gm.group_id,
7111 OVS_VERSION_MAX);
7112 if (!old_group) {
7113 return OFPERR_OFPGMFC_UNKNOWN_GROUP;
7114 }
7115
7116 if (old_group->type != ogm->gm.type
7117 && (ofproto->n_groups[ogm->gm.type]
7118 >= ofproto->ogf.max_groups[ogm->gm.type])) {
7119 return OFPERR_OFPGMFC_OUT_OF_GROUPS;
7120 }
7121
7122 error = init_group(ofproto, &ogm->gm, ogm->version, &ogm->new_group);
7123 if (error) {
7124 return error;
7125 }
7126 new_group = ogm->new_group;
7127
7128 /* Manipulate bucket list for bucket commands */
7129 if (ogm->gm.command == OFPGC15_INSERT_BUCKET) {
7130 error = copy_buckets_for_insert_bucket(old_group, new_group,
7131 ogm->gm.command_bucket_id);
7132 } else if (ogm->gm.command == OFPGC15_REMOVE_BUCKET) {
7133 error = copy_buckets_for_remove_bucket(old_group, new_group,
7134 ogm->gm.command_bucket_id);
7135 }
7136 if (error) {
7137 goto out;
7138 }
7139
7140 /* The group creation time does not change during modification. */
7141 *CONST_CAST(long long int *, &(new_group->created)) = old_group->created;
7142 *CONST_CAST(long long int *, &(new_group->modified)) = time_msec();
7143
7144 group_collection_add(&ogm->old_groups, old_group);
7145
7146 /* Mark the old group for deletion. */
7147 versions_set_remove_version(&old_group->versions, ogm->version);
7148 /* Insert replacement group. */
7149 cmap_insert(&ofproto->groups, &new_group->cmap_node,
7150 hash_int(new_group->group_id, 0));
7151 /* Transfer rules. */
7152 rule_collection_move(&new_group->rules, &old_group->rules);
7153
7154 if (old_group->type != new_group->type) {
7155 ofproto->n_groups[old_group->type]--;
7156 ofproto->n_groups[new_group->type]++;
7157 }
7158 return 0;
7159
7160 out:
7161 ofproto_group_unref(new_group);
7162 return error;
7163 }
7164
7165 /* Implements the OFPGC11_ADD_OR_MOD command which creates the group when it does not
7166 * exist yet and modifies it otherwise */
7167 static enum ofperr
7168 add_or_modify_group_start(struct ofproto *ofproto,
7169 struct ofproto_group_mod *ogm)
7170 OVS_REQUIRES(ofproto_mutex)
7171 {
7172 enum ofperr error;
7173
7174 if (!ofproto_group_exists(ofproto, ogm->gm.group_id)) {
7175 error = add_group_start(ofproto, ogm);
7176 } else {
7177 error = modify_group_start(ofproto, ogm);
7178 }
7179
7180 return error;
7181 }
7182
7183 static void
7184 delete_group_start(struct ofproto *ofproto, ovs_version_t version,
7185 struct group_collection *groups, struct ofgroup *group)
7186 OVS_REQUIRES(ofproto_mutex)
7187 {
7188 /* Makes flow deletion code leave the rule pointers in 'group->rules'
7189 * intact, so that we can later refer to the rules deleted due to the group
7190 * deletion. Rule pointers will be removed from all other groups, if any,
7191 * so we will never try to delete the same rule twice. */
7192 group->being_deleted = true;
7193
7194 /* Mark all the referring groups for deletion. */
7195 delete_flows_start__(ofproto, version, &group->rules);
7196 group_collection_add(groups, group);
7197 versions_set_remove_version(&group->versions, version);
7198 ofproto->n_groups[group->type]--;
7199 }
7200
7201 static void
7202 delete_group_finish(struct ofproto *ofproto, struct ofgroup *group)
7203 OVS_REQUIRES(ofproto_mutex)
7204 {
7205 /* Finish deletion of all flow entries containing this group in a group
7206 * action. */
7207 delete_flows_finish__(ofproto, &group->rules, OFPRR_GROUP_DELETE, NULL);
7208
7209 /* Group removal is postponed by the caller. */
7210 }
7211
7212 /* Implements OFPGC11_DELETE. */
7213 static void
7214 delete_groups_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
7215 OVS_REQUIRES(ofproto_mutex)
7216 {
7217 struct ofgroup *group;
7218
7219 if (ogm->gm.group_id == OFPG_ALL) {
7220 CMAP_FOR_EACH (group, cmap_node, &ofproto->groups) {
7221 if (versions_visible_in_version(&group->versions, ogm->version)) {
7222 delete_group_start(ofproto, ogm->version, &ogm->old_groups,
7223 group);
7224 }
7225 }
7226 } else {
7227 group = ofproto_group_lookup__(ofproto, ogm->gm.group_id, ogm->version);
7228 if (group) {
7229 delete_group_start(ofproto, ogm->version, &ogm->old_groups, group);
7230 }
7231 }
7232 }
7233
7234 static enum ofperr
7235 ofproto_group_mod_start(struct ofproto *ofproto, struct ofproto_group_mod *ogm)
7236 OVS_REQUIRES(ofproto_mutex)
7237 {
7238 enum ofperr error;
7239
7240 ogm->new_group = NULL;
7241 group_collection_init(&ogm->old_groups);
7242
7243 switch (ogm->gm.command) {
7244 case OFPGC11_ADD:
7245 error = add_group_start(ofproto, ogm);
7246 break;
7247
7248 case OFPGC11_MODIFY:
7249 error = modify_group_start(ofproto, ogm);
7250 break;
7251
7252 case OFPGC11_ADD_OR_MOD:
7253 error = add_or_modify_group_start(ofproto, ogm);
7254 break;
7255
7256 case OFPGC11_DELETE:
7257 delete_groups_start(ofproto, ogm);
7258 error = 0;
7259 break;
7260
7261 case OFPGC15_INSERT_BUCKET:
7262 error = modify_group_start(ofproto, ogm);
7263 break;
7264
7265 case OFPGC15_REMOVE_BUCKET:
7266 error = modify_group_start(ofproto, ogm);
7267 break;
7268
7269 default:
7270 if (ogm->gm.command > OFPGC11_DELETE) {
7271 VLOG_INFO_RL(&rl, "%s: Invalid group_mod command type %d",
7272 ofproto->name, ogm->gm.command);
7273 }
7274 error = OFPERR_OFPGMFC_BAD_COMMAND;
7275 break;
7276 }
7277 return error;
7278 }
7279
7280 static void
7281 ofproto_group_mod_revert(struct ofproto *ofproto,
7282 struct ofproto_group_mod *ogm)
7283 OVS_REQUIRES(ofproto_mutex)
7284 {
7285 struct ofgroup *new_group = ogm->new_group;
7286 struct ofgroup *old_group;
7287
7288 /* Restore replaced or deleted groups. */
7289 GROUP_COLLECTION_FOR_EACH (old_group, &ogm->old_groups) {
7290 ofproto->n_groups[old_group->type]++;
7291 if (new_group) {
7292 ovs_assert(group_collection_n(&ogm->old_groups) == 1);
7293 /* Transfer rules back. */
7294 rule_collection_move(&old_group->rules, &new_group->rules);
7295 } else {
7296 old_group->being_deleted = false;
7297 /* Revert rule deletion. */
7298 delete_flows_revert__(ofproto, &old_group->rules);
7299 }
7300 /* Restore visibility. */
7301 versions_set_remove_version(&old_group->versions,
7302 OVS_VERSION_NOT_REMOVED);
7303 }
7304 if (new_group) {
7305 /* Remove the new group immediately. It was never visible to
7306 * lookups. */
7307 cmap_remove(&ofproto->groups, &new_group->cmap_node,
7308 hash_int(new_group->group_id, 0));
7309 ofproto->n_groups[new_group->type]--;
7310 ofproto_group_unref(new_group);
7311 }
7312 }
7313
7314 static void
7315 ofproto_group_mod_finish(struct ofproto *ofproto,
7316 struct ofproto_group_mod *ogm,
7317 const struct openflow_mod_requester *req)
7318 OVS_REQUIRES(ofproto_mutex)
7319 {
7320 struct ofgroup *new_group = ogm->new_group;
7321 struct ofgroup *old_group;
7322
7323 if (new_group && group_collection_n(&ogm->old_groups) &&
7324 ofproto->ofproto_class->group_modify) {
7325 /* Modify a group. */
7326 ovs_assert(group_collection_n(&ogm->old_groups) == 1);
7327
7328 /* XXX: OK to lose old group's stats? */
7329 ofproto->ofproto_class->group_modify(new_group);
7330 }
7331
7332 /* Delete old groups. */
7333 GROUP_COLLECTION_FOR_EACH(old_group, &ogm->old_groups) {
7334 delete_group_finish(ofproto, old_group);
7335 }
7336 remove_groups_postponed(&ogm->old_groups);
7337
7338 if (req) {
7339 struct ofputil_requestforward rf;
7340 rf.xid = req->request->xid;
7341 rf.reason = OFPRFR_GROUP_MOD;
7342 rf.group_mod = &ogm->gm;
7343 connmgr_send_requestforward(ofproto->connmgr, req->ofconn, &rf);
7344 }
7345 }
7346
7347 /* Delete all groups from 'ofproto'.
7348 *
7349 * This is intended for use within an ofproto provider's 'destruct'
7350 * function. */
7351 void
7352 ofproto_group_delete_all(struct ofproto *ofproto)
7353 OVS_EXCLUDED(ofproto_mutex)
7354 {
7355 struct ofproto_group_mod ogm;
7356
7357 ogm.gm.command = OFPGC11_DELETE;
7358 ogm.gm.group_id = OFPG_ALL;
7359
7360 ovs_mutex_lock(&ofproto_mutex);
7361 ogm.version = ofproto->tables_version + 1;
7362 ofproto_group_mod_start(ofproto, &ogm);
7363 ofproto_bump_tables_version(ofproto);
7364 ofproto_group_mod_finish(ofproto, &ogm, NULL);
7365 ovs_mutex_unlock(&ofproto_mutex);
7366 }
7367
7368 static enum ofperr
7369 handle_group_mod(struct ofconn *ofconn, const struct ofp_header *oh)
7370 OVS_EXCLUDED(ofproto_mutex)
7371 {
7372 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7373 struct ofproto_group_mod ogm;
7374 enum ofperr error;
7375
7376 error = reject_slave_controller(ofconn);
7377 if (error) {
7378 return error;
7379 }
7380
7381 error = ofputil_decode_group_mod(oh, &ogm.gm);
7382 if (error) {
7383 return error;
7384 }
7385
7386 ovs_mutex_lock(&ofproto_mutex);
7387 ogm.version = ofproto->tables_version + 1;
7388 error = ofproto_group_mod_start(ofproto, &ogm);
7389 if (!error) {
7390 struct openflow_mod_requester req = { ofconn, oh };
7391
7392 ofproto_bump_tables_version(ofproto);
7393 ofproto_group_mod_finish(ofproto, &ogm, &req);
7394 ofmonitor_flush(ofproto->connmgr);
7395 }
7396 ovs_mutex_unlock(&ofproto_mutex);
7397
7398 ofputil_uninit_group_mod(&ogm.gm);
7399
7400 return error;
7401 }
7402
7403 enum ofputil_table_miss
7404 ofproto_table_get_miss_config(const struct ofproto *ofproto, uint8_t table_id)
7405 {
7406 enum ofputil_table_miss miss;
7407
7408 atomic_read_relaxed(&ofproto->tables[table_id].miss_config, &miss);
7409 return miss;
7410 }
7411
7412 static void
7413 table_mod__(struct oftable *oftable,
7414 const struct ofputil_table_mod *tm)
7415 {
7416 if (tm->miss == OFPUTIL_TABLE_MISS_DEFAULT) {
7417 /* This is how an OFPT_TABLE_MOD decodes if it doesn't specify any
7418 * table-miss configuration (because the protocol used doesn't have
7419 * such a concept), so there's nothing to do. */
7420 } else {
7421 atomic_store_relaxed(&oftable->miss_config, tm->miss);
7422 }
7423
7424 unsigned int new_eviction = oftable->eviction;
7425 if (tm->eviction == OFPUTIL_TABLE_EVICTION_ON) {
7426 new_eviction |= EVICTION_OPENFLOW;
7427 } else if (tm->eviction == OFPUTIL_TABLE_EVICTION_OFF) {
7428 new_eviction &= ~EVICTION_OPENFLOW;
7429 }
7430
7431 if (new_eviction != oftable->eviction) {
7432 ovs_mutex_lock(&ofproto_mutex);
7433 oftable_configure_eviction(oftable, new_eviction,
7434 oftable->eviction_fields,
7435 oftable->n_eviction_fields);
7436 ovs_mutex_unlock(&ofproto_mutex);
7437 }
7438
7439 if (tm->vacancy != OFPUTIL_TABLE_VACANCY_DEFAULT) {
7440 ovs_mutex_lock(&ofproto_mutex);
7441 oftable->vacancy_down = tm->table_vacancy.vacancy_down;
7442 oftable->vacancy_up = tm->table_vacancy.vacancy_up;
7443 if (tm->vacancy == OFPUTIL_TABLE_VACANCY_OFF) {
7444 oftable->vacancy_event = 0;
7445 } else if (!oftable->vacancy_event) {
7446 uint8_t vacancy = oftable_vacancy(oftable);
7447 oftable->vacancy_event = (vacancy < oftable->vacancy_up
7448 ? OFPTR_VACANCY_UP
7449 : OFPTR_VACANCY_DOWN);
7450 }
7451 ovs_mutex_unlock(&ofproto_mutex);
7452 }
7453 }
7454
7455 static enum ofperr
7456 table_mod(struct ofproto *ofproto, const struct ofputil_table_mod *tm)
7457 {
7458 if (!check_table_id(ofproto, tm->table_id)) {
7459 return OFPERR_OFPTMFC_BAD_TABLE;
7460 }
7461
7462 /* Don't allow the eviction flags to be changed (except to the only fixed
7463 * value that OVS supports). OF1.4 says this is normal: "The
7464 * OFPTMPT_EVICTION property usually cannot be modified using a
7465 * OFP_TABLE_MOD request, because the eviction mechanism is switch
7466 * defined". */
7467 if (tm->eviction_flags != UINT32_MAX
7468 && tm->eviction_flags != OFPROTO_EVICTION_FLAGS) {
7469 return OFPERR_OFPTMFC_BAD_CONFIG;
7470 }
7471
7472 if (tm->table_id == OFPTT_ALL) {
7473 struct oftable *oftable;
7474 OFPROTO_FOR_EACH_TABLE (oftable, ofproto) {
7475 if (!(oftable->flags & (OFTABLE_HIDDEN | OFTABLE_READONLY))) {
7476 table_mod__(oftable, tm);
7477 }
7478 }
7479 } else {
7480 struct oftable *oftable = &ofproto->tables[tm->table_id];
7481 if (oftable->flags & OFTABLE_READONLY) {
7482 return OFPERR_OFPTMFC_EPERM;
7483 }
7484 table_mod__(oftable, tm);
7485 }
7486
7487 return 0;
7488 }
7489
7490 static enum ofperr
7491 handle_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
7492 {
7493 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7494 struct ofputil_table_mod tm;
7495 enum ofperr error;
7496
7497 error = reject_slave_controller(ofconn);
7498 if (error) {
7499 return error;
7500 }
7501
7502 error = ofputil_decode_table_mod(oh, &tm);
7503 if (error) {
7504 return error;
7505 }
7506
7507 return table_mod(ofproto, &tm);
7508 }
7509
7510 /* Free resources that may be allocated by ofproto_flow_mod_init(). */
7511 void
7512 ofproto_flow_mod_uninit(struct ofproto_flow_mod *ofm)
7513 {
7514 if (ofm->temp_rule) {
7515 ofproto_rule_unref(ofm->temp_rule);
7516 ofm->temp_rule = NULL;
7517 }
7518 if (ofm->criteria.version != OVS_VERSION_NOT_REMOVED) {
7519 rule_criteria_destroy(&ofm->criteria);
7520 }
7521 if (ofm->conjs) {
7522 free(ofm->conjs);
7523 ofm->conjs = NULL;
7524 ofm->n_conjs = 0;
7525 }
7526 }
7527
7528 static enum ofperr
7529 ofproto_flow_mod_init(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
7530 const struct ofputil_flow_mod *fm, struct rule *rule)
7531 OVS_EXCLUDED(ofproto_mutex)
7532 {
7533 enum ofperr error;
7534
7535 /* Forward flow mod fields we need later. */
7536 ofm->command = fm->command;
7537 ofm->modify_cookie = fm->modify_cookie;
7538
7539 ofm->modify_may_add_flow = (fm->new_cookie != OVS_BE64_MAX
7540 && fm->cookie_mask == htonll(0));
7541 /* Old flags must be kept when modifying a flow, but we still must
7542 * honor the reset counts flag if present in the flow mod. */
7543 ofm->modify_keep_counts = !(fm->flags & OFPUTIL_FF_RESET_COUNTS);
7544
7545 /* Initialize state needed by ofproto_flow_mod_uninit(). */
7546 ofm->temp_rule = rule;
7547 ofm->criteria.version = OVS_VERSION_NOT_REMOVED;
7548 ofm->conjs = NULL;
7549 ofm->n_conjs = 0;
7550
7551 bool check_buffer_id = false;
7552
7553 switch (ofm->command) {
7554 case OFPFC_ADD:
7555 check_buffer_id = true;
7556 error = add_flow_init(ofproto, ofm, fm);
7557 break;
7558 case OFPFC_MODIFY:
7559 check_buffer_id = true;
7560 error = modify_flows_init_loose(ofproto, ofm, fm);
7561 break;
7562 case OFPFC_MODIFY_STRICT:
7563 check_buffer_id = true;
7564 error = modify_flow_init_strict(ofproto, ofm, fm);
7565 break;
7566 case OFPFC_DELETE:
7567 error = delete_flows_init_loose(ofproto, ofm, fm);
7568 break;
7569 case OFPFC_DELETE_STRICT:
7570 error = delete_flows_init_strict(ofproto, ofm, fm);
7571 break;
7572 default:
7573 error = OFPERR_OFPFMFC_BAD_COMMAND;
7574 break;
7575 }
7576 if (!error && check_buffer_id && fm->buffer_id != UINT32_MAX) {
7577 error = OFPERR_OFPBRC_BUFFER_UNKNOWN;
7578 }
7579
7580 if (error) {
7581 ofproto_flow_mod_uninit(ofm);
7582 }
7583 return error;
7584 }
7585
7586 static enum ofperr
7587 ofproto_flow_mod_start(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
7588 OVS_REQUIRES(ofproto_mutex)
7589 {
7590 enum ofperr error;
7591
7592 rule_collection_init(&ofm->old_rules);
7593 rule_collection_init(&ofm->new_rules);
7594
7595 switch (ofm->command) {
7596 case OFPFC_ADD:
7597 error = add_flow_start(ofproto, ofm);
7598 break;
7599 case OFPFC_MODIFY:
7600 error = modify_flows_start_loose(ofproto, ofm);
7601 break;
7602 case OFPFC_MODIFY_STRICT:
7603 error = modify_flow_start_strict(ofproto, ofm);
7604 break;
7605 case OFPFC_DELETE:
7606 error = delete_flows_start_loose(ofproto, ofm);
7607 break;
7608 case OFPFC_DELETE_STRICT:
7609 error = delete_flow_start_strict(ofproto, ofm);
7610 break;
7611 default:
7612 OVS_NOT_REACHED();
7613 }
7614 /* Release resources not needed after start. */
7615 ofproto_flow_mod_uninit(ofm);
7616
7617 if (error) {
7618 rule_collection_destroy(&ofm->old_rules);
7619 rule_collection_destroy(&ofm->new_rules);
7620 }
7621 return error;
7622 }
7623
7624 static void
7625 ofproto_flow_mod_revert(struct ofproto *ofproto, struct ofproto_flow_mod *ofm)
7626 OVS_REQUIRES(ofproto_mutex)
7627 {
7628 switch (ofm->command) {
7629 case OFPFC_ADD:
7630 add_flow_revert(ofproto, ofm);
7631 break;
7632
7633 case OFPFC_MODIFY:
7634 case OFPFC_MODIFY_STRICT:
7635 modify_flows_revert(ofproto, ofm);
7636 break;
7637
7638 case OFPFC_DELETE:
7639 case OFPFC_DELETE_STRICT:
7640 delete_flows_revert(ofproto, ofm);
7641 break;
7642
7643 default:
7644 break;
7645 }
7646
7647 rule_collection_destroy(&ofm->old_rules);
7648 rule_collection_destroy(&ofm->new_rules);
7649 }
7650
7651 static void
7652 ofproto_flow_mod_finish(struct ofproto *ofproto, struct ofproto_flow_mod *ofm,
7653 const struct openflow_mod_requester *req)
7654 OVS_REQUIRES(ofproto_mutex)
7655 {
7656 switch (ofm->command) {
7657 case OFPFC_ADD:
7658 add_flow_finish(ofproto, ofm, req);
7659 break;
7660
7661 case OFPFC_MODIFY:
7662 case OFPFC_MODIFY_STRICT:
7663 modify_flows_finish(ofproto, ofm, req);
7664 break;
7665
7666 case OFPFC_DELETE:
7667 case OFPFC_DELETE_STRICT:
7668 delete_flows_finish(ofproto, ofm, req);
7669 break;
7670
7671 default:
7672 break;
7673 }
7674
7675 rule_collection_destroy(&ofm->old_rules);
7676 rule_collection_destroy(&ofm->new_rules);
7677
7678 if (req) {
7679 ofconn_report_flow_mod(req->ofconn, ofm->command);
7680 }
7681 }
7682
7683 /* Commit phases (all while locking ofproto_mutex):
7684 *
7685 * 1. Begin: Gather resources and make changes visible in the next version.
7686 * - Mark affected rules for removal in the next version.
7687 * - Create new replacement rules, make visible in the next
7688 * version.
7689 * - Do not send any events or notifications.
7690 *
7691 * 2. Revert: Fail if any errors are found. After this point no errors are
7692 * possible. No visible changes were made, so rollback is minimal (remove
7693 * added invisible rules, restore visibility of rules marked for removal).
7694 *
7695 * 3. Finish: Make the changes visible for lookups. Insert replacement rules to
7696 * the ofproto provider. Remove replaced and deleted rules from ofproto data
7697 * structures, and Schedule postponed removal of deleted rules from the
7698 * classifier. Send notifications, buffered packets, etc.
7699 */
7700 static enum ofperr
7701 do_bundle_commit(struct ofconn *ofconn, uint32_t id, uint16_t flags)
7702 {
7703 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7704 ovs_version_t version = ofproto->tables_version + 1;
7705 struct ofp_bundle *bundle;
7706 struct ofp_bundle_entry *be;
7707 enum ofperr error;
7708
7709 bundle = ofconn_get_bundle(ofconn, id);
7710
7711 if (!bundle) {
7712 return OFPERR_OFPBFC_BAD_ID;
7713 }
7714 if (bundle->flags != flags) {
7715 error = OFPERR_OFPBFC_BAD_FLAGS;
7716 } else {
7717 bool prev_is_port_mod = false;
7718
7719 error = 0;
7720 ovs_mutex_lock(&ofproto_mutex);
7721
7722 /* 1. Begin. */
7723 LIST_FOR_EACH (be, node, &bundle->msg_list) {
7724 if (be->type == OFPTYPE_PORT_MOD) {
7725 /* Our port mods are not atomic. */
7726 if (flags & OFPBF_ATOMIC) {
7727 error = OFPERR_OFPBFC_MSG_FAILED;
7728 } else {
7729 prev_is_port_mod = true;
7730 error = port_mod_start(ofconn, &be->opm.pm, &be->opm.port);
7731 }
7732 } else {
7733 /* Flow & group mods between port mods are applied as a single
7734 * version, but the versions are published only after we know
7735 * the commit is successful. */
7736 if (prev_is_port_mod) {
7737 prev_is_port_mod = false;
7738 ++version;
7739 }
7740 if (be->type == OFPTYPE_FLOW_MOD) {
7741 /* Store the version in which the changes should take
7742 * effect. */
7743 be->ofm.version = version;
7744 error = ofproto_flow_mod_start(ofproto, &be->ofm);
7745 } else if (be->type == OFPTYPE_GROUP_MOD) {
7746 /* Store the version in which the changes should take
7747 * effect. */
7748 be->ogm.version = version;
7749 error = ofproto_group_mod_start(ofproto, &be->ogm);
7750 } else if (be->type == OFPTYPE_PACKET_OUT) {
7751 be->opo.version = version;
7752 error = ofproto_packet_out_start(ofproto, &be->opo);
7753 } else {
7754 OVS_NOT_REACHED();
7755 }
7756 }
7757 if (error) {
7758 break;
7759 }
7760 }
7761
7762 if (error) {
7763 /* Send error referring to the original message. */
7764 if (error) {
7765 ofconn_send_error(ofconn, &be->ofp_msg, error);
7766 error = OFPERR_OFPBFC_MSG_FAILED;
7767 }
7768
7769 /* 2. Revert. Undo all the changes made above. */
7770 LIST_FOR_EACH_REVERSE_CONTINUE(be, node, &bundle->msg_list) {
7771 if (be->type == OFPTYPE_FLOW_MOD) {
7772 ofproto_flow_mod_revert(ofproto, &be->ofm);
7773 } else if (be->type == OFPTYPE_GROUP_MOD) {
7774 ofproto_group_mod_revert(ofproto, &be->ogm);
7775 } else if (be->type == OFPTYPE_PACKET_OUT) {
7776 ofproto_packet_out_revert(ofproto, &be->opo);
7777 }
7778 /* Nothing needs to be reverted for a port mod. */
7779 }
7780 } else {
7781 /* 4. Finish. */
7782 LIST_FOR_EACH (be, node, &bundle->msg_list) {
7783 if (be->type == OFPTYPE_PORT_MOD) {
7784 /* Perform the actual port mod. This is not atomic, i.e.,
7785 * the effects will be immediately seen by upcall
7786 * processing regardless of the lookup version. It should
7787 * be noted that port configuration changes can originate
7788 * also from OVSDB changes asynchronously to all upcall
7789 * processing. */
7790 port_mod_finish(ofconn, &be->opm.pm, be->opm.port);
7791 } else {
7792 version =
7793 (be->type == OFPTYPE_FLOW_MOD) ? be->ofm.version :
7794 (be->type == OFPTYPE_GROUP_MOD) ? be->ogm.version :
7795 (be->type == OFPTYPE_PACKET_OUT) ? be->opo.version :
7796 version;
7797
7798 /* Bump the lookup version to the one of the current
7799 * message. This makes all the changes in the bundle at
7800 * this version visible to lookups at once. */
7801 if (ofproto->tables_version < version) {
7802 ofproto->tables_version = version;
7803 ofproto->ofproto_class->set_tables_version(
7804 ofproto, ofproto->tables_version);
7805 }
7806
7807 struct openflow_mod_requester req = { ofconn,
7808 &be->ofp_msg };
7809
7810 if (be->type == OFPTYPE_FLOW_MOD) {
7811 ofproto_flow_mod_finish(ofproto, &be->ofm, &req);
7812 } else if (be->type == OFPTYPE_GROUP_MOD) {
7813 ofproto_group_mod_finish(ofproto, &be->ogm, &req);
7814 } else if (be->type == OFPTYPE_PACKET_OUT) {
7815 ofproto_packet_out_finish(ofproto, &be->opo);
7816 }
7817 }
7818 }
7819 }
7820
7821 ofmonitor_flush(ofproto->connmgr);
7822 ovs_mutex_unlock(&ofproto_mutex);
7823 }
7824
7825 /* The bundle is discarded regardless the outcome. */
7826 ofp_bundle_remove__(ofconn, bundle);
7827 return error;
7828 }
7829
7830 static enum ofperr
7831 handle_bundle_control(struct ofconn *ofconn, const struct ofp_header *oh)
7832 {
7833 struct ofputil_bundle_ctrl_msg bctrl;
7834 struct ofputil_bundle_ctrl_msg reply;
7835 struct ofpbuf *buf;
7836 enum ofperr error;
7837
7838 error = reject_slave_controller(ofconn);
7839 if (error) {
7840 return error;
7841 }
7842
7843 error = ofputil_decode_bundle_ctrl(oh, &bctrl);
7844 if (error) {
7845 return error;
7846 }
7847 reply.flags = 0;
7848 reply.bundle_id = bctrl.bundle_id;
7849
7850 switch (bctrl.type) {
7851 case OFPBCT_OPEN_REQUEST:
7852 error = ofp_bundle_open(ofconn, bctrl.bundle_id, bctrl.flags, oh);
7853 reply.type = OFPBCT_OPEN_REPLY;
7854 break;
7855 case OFPBCT_CLOSE_REQUEST:
7856 error = ofp_bundle_close(ofconn, bctrl.bundle_id, bctrl.flags);
7857 reply.type = OFPBCT_CLOSE_REPLY;
7858 break;
7859 case OFPBCT_COMMIT_REQUEST:
7860 error = do_bundle_commit(ofconn, bctrl.bundle_id, bctrl.flags);
7861 reply.type = OFPBCT_COMMIT_REPLY;
7862 break;
7863 case OFPBCT_DISCARD_REQUEST:
7864 error = ofp_bundle_discard(ofconn, bctrl.bundle_id);
7865 reply.type = OFPBCT_DISCARD_REPLY;
7866 break;
7867
7868 case OFPBCT_OPEN_REPLY:
7869 case OFPBCT_CLOSE_REPLY:
7870 case OFPBCT_COMMIT_REPLY:
7871 case OFPBCT_DISCARD_REPLY:
7872 return OFPERR_OFPBFC_BAD_TYPE;
7873 break;
7874 }
7875
7876 if (!error) {
7877 buf = ofputil_encode_bundle_ctrl_reply(oh, &reply);
7878 ofconn_send_reply(ofconn, buf);
7879 }
7880 return error;
7881 }
7882
7883 static enum ofperr
7884 handle_bundle_add(struct ofconn *ofconn, const struct ofp_header *oh)
7885 OVS_EXCLUDED(ofproto_mutex)
7886 {
7887 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7888 enum ofperr error;
7889 struct ofputil_bundle_add_msg badd;
7890 struct ofp_bundle_entry *bmsg;
7891 enum ofptype type;
7892
7893 error = reject_slave_controller(ofconn);
7894 if (error) {
7895 return error;
7896 }
7897
7898 error = ofputil_decode_bundle_add(oh, &badd, &type);
7899 if (error) {
7900 return error;
7901 }
7902
7903 bmsg = ofp_bundle_entry_alloc(type, badd.msg);
7904
7905 struct ofpbuf ofpacts;
7906 uint64_t ofpacts_stub[1024 / 8];
7907 ofpbuf_use_stub(&ofpacts, ofpacts_stub, sizeof ofpacts_stub);
7908
7909 if (type == OFPTYPE_PORT_MOD) {
7910 error = ofputil_decode_port_mod(badd.msg, &bmsg->opm.pm, false);
7911 } else if (type == OFPTYPE_FLOW_MOD) {
7912 struct ofputil_flow_mod fm;
7913
7914 error = ofputil_decode_flow_mod(&fm, badd.msg,
7915 ofconn_get_protocol(ofconn),
7916 ofproto_get_tun_tab(ofproto),
7917 &ofproto->vl_mff_map, &ofpacts,
7918 u16_to_ofp(ofproto->max_ports),
7919 ofproto->n_tables);
7920 if (!error) {
7921 error = ofproto_flow_mod_init(ofproto, &bmsg->ofm, &fm, NULL);
7922 }
7923 } else if (type == OFPTYPE_GROUP_MOD) {
7924 error = ofputil_decode_group_mod(badd.msg, &bmsg->ogm.gm);
7925 } else if (type == OFPTYPE_PACKET_OUT) {
7926 struct ofputil_packet_out po;
7927
7928 COVERAGE_INC(ofproto_packet_out);
7929
7930 /* Decode message. */
7931 error = ofputil_decode_packet_out(&po, badd.msg,
7932 ofproto_get_tun_tab(ofproto),
7933 &ofpacts);
7934 if (!error) {
7935 po.ofpacts = ofpbuf_steal_data(&ofpacts); /* Move to heap. */
7936 error = ofproto_packet_out_init(ofproto, ofconn, &bmsg->opo, &po);
7937 }
7938 } else {
7939 OVS_NOT_REACHED();
7940 }
7941
7942 ofpbuf_uninit(&ofpacts);
7943
7944 if (!error) {
7945 error = ofp_bundle_add_message(ofconn, badd.bundle_id, badd.flags,
7946 bmsg, oh);
7947 }
7948
7949 if (error) {
7950 ofp_bundle_entry_free(bmsg);
7951 }
7952
7953 return error;
7954 }
7955
7956 static enum ofperr
7957 handle_tlv_table_mod(struct ofconn *ofconn, const struct ofp_header *oh)
7958 {
7959 struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7960 struct tun_table *old_tab, *new_tab;
7961 struct ofputil_tlv_table_mod ttm;
7962 enum ofperr error;
7963
7964 error = reject_slave_controller(ofconn);
7965 if (error) {
7966 return error;
7967 }
7968
7969 error = ofputil_decode_tlv_table_mod(oh, &ttm);
7970 if (error) {
7971 return error;
7972 }
7973
7974 old_tab = ovsrcu_get_protected(struct tun_table *, &ofproto->metadata_tab);
7975 error = tun_metadata_table_mod(&ttm, old_tab, &new_tab);
7976 if (!error) {
7977 ovs_mutex_lock(&ofproto->vl_mff_map.mutex);
7978 error = mf_vl_mff_map_mod_from_tun_metadata(&ofproto->vl_mff_map,
7979 &ttm);
7980 ovs_mutex_unlock(&ofproto->vl_mff_map.mutex);
7981 if (!error) {
7982 ovsrcu_set(&ofproto->metadata_tab, new_tab);
7983 tun_metadata_postpone_free(old_tab);
7984 } else {
7985 tun_metadata_free(new_tab);
7986 }
7987 }
7988
7989 ofputil_uninit_tlv_table(&ttm.mappings);
7990 return error;
7991 }
7992
7993 static enum ofperr
7994 handle_tlv_table_request(struct ofconn *ofconn, const struct ofp_header *oh)
7995 {
7996 const struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
7997 struct ofputil_tlv_table_reply ttr;
7998 struct ofpbuf *b;
7999
8000 tun_metadata_table_request(ofproto_get_tun_tab(ofproto), &ttr);
8001
8002 b = ofputil_encode_tlv_table_reply(oh, &ttr);
8003 ofputil_uninit_tlv_table(&ttr.mappings);
8004
8005 ofconn_send_reply(ofconn, b);
8006 return 0;
8007 }
8008
8009 static enum ofperr
8010 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
8011 OVS_EXCLUDED(ofproto_mutex)
8012 {
8013 const struct ofp_header *oh = msg->data;
8014 enum ofptype type;
8015 enum ofperr error;
8016
8017 error = ofptype_decode(&type, oh);
8018 if (error) {
8019 return error;
8020 }
8021 if (oh->version >= OFP13_VERSION && ofpmsg_is_stat_request(oh)
8022 && ofpmp_more(oh)) {
8023 /* We have no buffer implementation for multipart requests.
8024 * Report overflow for requests which consists of multiple
8025 * messages. */
8026 return OFPERR_OFPBRC_MULTIPART_BUFFER_OVERFLOW;
8027 }
8028
8029 switch (type) {
8030 /* OpenFlow requests. */
8031 case OFPTYPE_ECHO_REQUEST:
8032 return handle_echo_request(ofconn, oh);
8033
8034 case OFPTYPE_FEATURES_REQUEST:
8035 return handle_features_request(ofconn, oh);
8036
8037 case OFPTYPE_GET_CONFIG_REQUEST:
8038 return handle_get_config_request(ofconn, oh);
8039
8040 case OFPTYPE_SET_CONFIG:
8041 return handle_set_config(ofconn, oh);
8042
8043 case OFPTYPE_PACKET_OUT:
8044 return handle_packet_out(ofconn, oh);
8045
8046 case OFPTYPE_PORT_MOD:
8047 return handle_port_mod(ofconn, oh);
8048
8049 case OFPTYPE_FLOW_MOD:
8050 return handle_flow_mod(ofconn, oh);
8051
8052 case OFPTYPE_GROUP_MOD:
8053 return handle_group_mod(ofconn, oh);
8054
8055 case OFPTYPE_TABLE_MOD:
8056 return handle_table_mod(ofconn, oh);
8057
8058 case OFPTYPE_METER_MOD:
8059 return handle_meter_mod(ofconn, oh);
8060
8061 case OFPTYPE_BARRIER_REQUEST:
8062 return handle_barrier_request(ofconn, oh);
8063
8064 case OFPTYPE_ROLE_REQUEST:
8065 return handle_role_request(ofconn, oh);
8066
8067 /* OpenFlow replies. */
8068 case OFPTYPE_ECHO_REPLY:
8069 return 0;
8070
8071 /* Nicira extension requests. */
8072 case OFPTYPE_FLOW_MOD_TABLE_ID:
8073 return handle_nxt_flow_mod_table_id(ofconn, oh);
8074
8075 case OFPTYPE_SET_FLOW_FORMAT:
8076 return handle_nxt_set_flow_format(ofconn, oh);
8077
8078 case OFPTYPE_SET_PACKET_IN_FORMAT:
8079 return handle_nxt_set_packet_in_format(ofconn, oh);
8080
8081 case OFPTYPE_SET_CONTROLLER_ID:
8082 return handle_nxt_set_controller_id(ofconn, oh);
8083
8084 case OFPTYPE_FLOW_AGE:
8085 /* Nothing to do. */
8086 return 0;
8087
8088 case OFPTYPE_FLOW_MONITOR_CANCEL:
8089 return handle_flow_monitor_cancel(ofconn, oh);
8090
8091 case OFPTYPE_SET_ASYNC_CONFIG:
8092 return handle_nxt_set_async_config(ofconn, oh);
8093
8094 case OFPTYPE_GET_ASYNC_REQUEST:
8095 return handle_nxt_get_async_request(ofconn, oh);
8096
8097 case OFPTYPE_NXT_RESUME:
8098 return handle_nxt_resume(ofconn, oh);
8099
8100 /* Statistics requests. */
8101 case OFPTYPE_DESC_STATS_REQUEST:
8102 return handle_desc_stats_request(ofconn, oh);
8103
8104 case OFPTYPE_FLOW_STATS_REQUEST:
8105 return handle_flow_stats_request(ofconn, oh);
8106
8107 case OFPTYPE_AGGREGATE_STATS_REQUEST:
8108 return handle_aggregate_stats_request(ofconn, oh);
8109
8110 case OFPTYPE_TABLE_STATS_REQUEST:
8111 return handle_table_stats_request(ofconn, oh);
8112
8113 case OFPTYPE_TABLE_FEATURES_STATS_REQUEST:
8114 return handle_table_features_request(ofconn, oh);
8115
8116 case OFPTYPE_TABLE_DESC_REQUEST:
8117 return handle_table_desc_request(ofconn, oh);
8118
8119 case OFPTYPE_PORT_STATS_REQUEST:
8120 return handle_port_stats_request(ofconn, oh);
8121
8122 case OFPTYPE_QUEUE_STATS_REQUEST:
8123 return handle_queue_stats_request(ofconn, oh);
8124
8125 case OFPTYPE_PORT_DESC_STATS_REQUEST:
8126 return handle_port_desc_stats_request(ofconn, oh);
8127
8128 case OFPTYPE_FLOW_MONITOR_STATS_REQUEST:
8129 return handle_flow_monitor_request(ofconn, oh);
8130
8131 case OFPTYPE_METER_STATS_REQUEST:
8132 case OFPTYPE_METER_CONFIG_STATS_REQUEST:
8133 return handle_meter_request(ofconn, oh, type);
8134
8135 case OFPTYPE_METER_FEATURES_STATS_REQUEST:
8136 return handle_meter_features_request(ofconn, oh);
8137
8138 case OFPTYPE_GROUP_STATS_REQUEST:
8139 return handle_group_stats_request(ofconn, oh);
8140
8141 case OFPTYPE_GROUP_DESC_STATS_REQUEST:
8142 return handle_group_desc_stats_request(ofconn, oh);
8143
8144 case OFPTYPE_GROUP_FEATURES_STATS_REQUEST:
8145 return handle_group_features_stats_request(ofconn, oh);
8146
8147 case OFPTYPE_QUEUE_GET_CONFIG_REQUEST:
8148 return handle_queue_get_config_request(ofconn, oh);
8149
8150 case OFPTYPE_BUNDLE_CONTROL:
8151 return handle_bundle_control(ofconn, oh);
8152
8153 case OFPTYPE_BUNDLE_ADD_MESSAGE:
8154 return handle_bundle_add(ofconn, oh);
8155
8156 case OFPTYPE_NXT_TLV_TABLE_MOD:
8157 return handle_tlv_table_mod(ofconn, oh);
8158
8159 case OFPTYPE_NXT_TLV_TABLE_REQUEST:
8160 return handle_tlv_table_request(ofconn, oh);
8161
8162 case OFPTYPE_IPFIX_BRIDGE_STATS_REQUEST:
8163 return handle_ipfix_bridge_stats_request(ofconn, oh);
8164
8165 case OFPTYPE_IPFIX_FLOW_STATS_REQUEST:
8166 return handle_ipfix_flow_stats_request(ofconn, oh);
8167
8168 case OFPTYPE_CT_FLUSH_ZONE:
8169 return handle_nxt_ct_flush_zone(ofconn, oh);
8170
8171 case OFPTYPE_HELLO:
8172 case OFPTYPE_ERROR:
8173 case OFPTYPE_FEATURES_REPLY:
8174 case OFPTYPE_GET_CONFIG_REPLY:
8175 case OFPTYPE_PACKET_IN:
8176 case OFPTYPE_FLOW_REMOVED:
8177 case OFPTYPE_PORT_STATUS:
8178 case OFPTYPE_BARRIER_REPLY:
8179 case OFPTYPE_QUEUE_GET_CONFIG_REPLY:
8180 case OFPTYPE_DESC_STATS_REPLY:
8181 case OFPTYPE_FLOW_STATS_REPLY:
8182 case OFPTYPE_QUEUE_STATS_REPLY:
8183 case OFPTYPE_PORT_STATS_REPLY:
8184 case OFPTYPE_TABLE_STATS_REPLY:
8185 case OFPTYPE_AGGREGATE_STATS_REPLY:
8186 case OFPTYPE_PORT_DESC_STATS_REPLY:
8187 case OFPTYPE_ROLE_REPLY:
8188 case OFPTYPE_FLOW_MONITOR_PAUSED:
8189 case OFPTYPE_FLOW_MONITOR_RESUMED:
8190 case OFPTYPE_FLOW_MONITOR_STATS_REPLY:
8191 case OFPTYPE_GET_ASYNC_REPLY:
8192 case OFPTYPE_GROUP_STATS_REPLY:
8193 case OFPTYPE_GROUP_DESC_STATS_REPLY:
8194 case OFPTYPE_GROUP_FEATURES_STATS_REPLY:
8195 case OFPTYPE_METER_STATS_REPLY:
8196 case OFPTYPE_METER_CONFIG_STATS_REPLY:
8197 case OFPTYPE_METER_FEATURES_STATS_REPLY:
8198 case OFPTYPE_TABLE_FEATURES_STATS_REPLY:
8199 case OFPTYPE_TABLE_DESC_REPLY:
8200 case OFPTYPE_ROLE_STATUS:
8201 case OFPTYPE_REQUESTFORWARD:
8202 case OFPTYPE_TABLE_STATUS:
8203 case OFPTYPE_NXT_TLV_TABLE_REPLY:
8204 case OFPTYPE_IPFIX_BRIDGE_STATS_REPLY:
8205 case OFPTYPE_IPFIX_FLOW_STATS_REPLY:
8206 default:
8207 if (ofpmsg_is_stat_request(oh)) {
8208 return OFPERR_OFPBRC_BAD_STAT;
8209 } else {
8210 return OFPERR_OFPBRC_BAD_TYPE;
8211 }
8212 }
8213 }
8214
8215 static void
8216 handle_openflow(struct ofconn *ofconn, const struct ofpbuf *ofp_msg)
8217 OVS_EXCLUDED(ofproto_mutex)
8218 {
8219 enum ofperr error = handle_openflow__(ofconn, ofp_msg);
8220
8221 if (error) {
8222 ofconn_send_error(ofconn, ofp_msg->data, error);
8223 }
8224 COVERAGE_INC(ofproto_recv_openflow);
8225 }
8226 \f
8227 static uint64_t
8228 pick_datapath_id(const struct ofproto *ofproto)
8229 {
8230 const struct ofport *port;
8231
8232 port = ofproto_get_port(ofproto, OFPP_LOCAL);
8233 if (port) {
8234 struct eth_addr ea;
8235 int error;
8236
8237 error = netdev_get_etheraddr(port->netdev, &ea);
8238 if (!error) {
8239 return eth_addr_to_uint64(ea);
8240 }
8241 VLOG_WARN("%s: could not get MAC address for %s (%s)",
8242 ofproto->name, netdev_get_name(port->netdev),
8243 ovs_strerror(error));
8244 }
8245 return ofproto->fallback_dpid;
8246 }
8247
8248 static uint64_t
8249 pick_fallback_dpid(void)
8250 {
8251 struct eth_addr ea;
8252 eth_addr_nicira_random(&ea);
8253 return eth_addr_to_uint64(ea);
8254 }
8255 \f
8256 /* Table overflow policy. */
8257
8258 /* Chooses and updates 'rulep' with a rule to evict from 'table'. Sets 'rulep'
8259 * to NULL if the table is not configured to evict rules or if the table
8260 * contains no evictable rules. (Rules with a readlock on their evict rwlock,
8261 * or with no timeouts are not evictable.) */
8262 static bool
8263 choose_rule_to_evict(struct oftable *table, struct rule **rulep)
8264 OVS_REQUIRES(ofproto_mutex)
8265 {
8266 struct eviction_group *evg;
8267
8268 *rulep = NULL;
8269 if (!table->eviction) {
8270 return false;
8271 }
8272
8273 /* In the common case, the outer and inner loops here will each be entered
8274 * exactly once:
8275 *
8276 * - The inner loop normally "return"s in its first iteration. If the
8277 * eviction group has any evictable rules, then it always returns in
8278 * some iteration.
8279 *
8280 * - The outer loop only iterates more than once if the largest eviction
8281 * group has no evictable rules.
8282 *
8283 * - The outer loop can exit only if table's 'max_flows' is all filled up
8284 * by unevictable rules. */
8285 HEAP_FOR_EACH (evg, size_node, &table->eviction_groups_by_size) {
8286 struct rule *rule;
8287
8288 HEAP_FOR_EACH (rule, evg_node, &evg->rules) {
8289 *rulep = rule;
8290 return true;
8291 }
8292 }
8293
8294 return false;
8295 }
8296 \f
8297 /* Eviction groups. */
8298
8299 /* Returns the priority to use for an eviction_group that contains 'n_rules'
8300 * rules. The priority contains low-order random bits to ensure that eviction
8301 * groups with the same number of rules are prioritized randomly. */
8302 static uint32_t
8303 eviction_group_priority(size_t n_rules)
8304 {
8305 uint16_t size = MIN(UINT16_MAX, n_rules);
8306 return (size << 16) | random_uint16();
8307 }
8308
8309 /* Updates 'evg', an eviction_group within 'table', following a change that
8310 * adds or removes rules in 'evg'. */
8311 static void
8312 eviction_group_resized(struct oftable *table, struct eviction_group *evg)
8313 OVS_REQUIRES(ofproto_mutex)
8314 {
8315 heap_change(&table->eviction_groups_by_size, &evg->size_node,
8316 eviction_group_priority(heap_count(&evg->rules)));
8317 }
8318
8319 /* Destroys 'evg', an eviction_group within 'table':
8320 *
8321 * - Removes all the rules, if any, from 'evg'. (It doesn't destroy the
8322 * rules themselves, just removes them from the eviction group.)
8323 *
8324 * - Removes 'evg' from 'table'.
8325 *
8326 * - Frees 'evg'. */
8327 static void
8328 eviction_group_destroy(struct oftable *table, struct eviction_group *evg)
8329 OVS_REQUIRES(ofproto_mutex)
8330 {
8331 while (!heap_is_empty(&evg->rules)) {
8332 struct rule *rule;
8333
8334 rule = CONTAINER_OF(heap_pop(&evg->rules), struct rule, evg_node);
8335 rule->eviction_group = NULL;
8336 }
8337 hmap_remove(&table->eviction_groups_by_id, &evg->id_node);
8338 heap_remove(&table->eviction_groups_by_size, &evg->size_node);
8339 heap_destroy(&evg->rules);
8340 free(evg);
8341 }
8342
8343 /* Removes 'rule' from its eviction group, if any. */
8344 static void
8345 eviction_group_remove_rule(struct rule *rule)
8346 OVS_REQUIRES(ofproto_mutex)
8347 {
8348 if (rule->eviction_group) {
8349 struct oftable *table = &rule->ofproto->tables[rule->table_id];
8350 struct eviction_group *evg = rule->eviction_group;
8351
8352 rule->eviction_group = NULL;
8353 heap_remove(&evg->rules, &rule->evg_node);
8354 if (heap_is_empty(&evg->rules)) {
8355 eviction_group_destroy(table, evg);
8356 } else {
8357 eviction_group_resized(table, evg);
8358 }
8359 }
8360 }
8361
8362 /* Hashes the 'rule''s values for the eviction_fields of 'rule''s table, and
8363 * returns the hash value. */
8364 static uint32_t
8365 eviction_group_hash_rule(struct rule *rule)
8366 OVS_REQUIRES(ofproto_mutex)
8367 {
8368 struct oftable *table = &rule->ofproto->tables[rule->table_id];
8369 const struct mf_subfield *sf;
8370 struct flow flow;
8371 uint32_t hash;
8372
8373 hash = table->eviction_group_id_basis;
8374 miniflow_expand(rule->cr.match.flow, &flow);
8375 for (sf = table->eviction_fields;
8376 sf < &table->eviction_fields[table->n_eviction_fields];
8377 sf++)
8378 {
8379 if (mf_are_prereqs_ok(sf->field, &flow, NULL)) {
8380 union mf_value value;
8381
8382 mf_get_value(sf->field, &flow, &value);
8383 if (sf->ofs) {
8384 bitwise_zero(&value, sf->field->n_bytes, 0, sf->ofs);
8385 }
8386 if (sf->ofs + sf->n_bits < sf->field->n_bytes * 8) {
8387 unsigned int start = sf->ofs + sf->n_bits;
8388 bitwise_zero(&value, sf->field->n_bytes, start,
8389 sf->field->n_bytes * 8 - start);
8390 }
8391 hash = hash_bytes(&value, sf->field->n_bytes, hash);
8392 } else {
8393 hash = hash_int(hash, 0);
8394 }
8395 }
8396
8397 return hash;
8398 }
8399
8400 /* Returns an eviction group within 'table' with the given 'id', creating one
8401 * if necessary. */
8402 static struct eviction_group *
8403 eviction_group_find(struct oftable *table, uint32_t id)
8404 OVS_REQUIRES(ofproto_mutex)
8405 {
8406 struct eviction_group *evg;
8407
8408 HMAP_FOR_EACH_WITH_HASH (evg, id_node, id, &table->eviction_groups_by_id) {
8409 return evg;
8410 }
8411
8412 evg = xmalloc(sizeof *evg);
8413 hmap_insert(&table->eviction_groups_by_id, &evg->id_node, id);
8414 heap_insert(&table->eviction_groups_by_size, &evg->size_node,
8415 eviction_group_priority(0));
8416 heap_init(&evg->rules);
8417
8418 return evg;
8419 }
8420
8421 /* Returns an eviction priority for 'rule'. The return value should be
8422 * interpreted so that higher priorities make a rule a more attractive
8423 * candidate for eviction. */
8424 static uint64_t
8425 rule_eviction_priority(struct ofproto *ofproto, struct rule *rule)
8426 OVS_REQUIRES(ofproto_mutex)
8427 {
8428 /* Calculate absolute time when this flow will expire. If it will never
8429 * expire, then return 0 to make it unevictable. */
8430 long long int expiration = LLONG_MAX;
8431 if (rule->hard_timeout) {
8432 /* 'modified' needs protection even when we hold 'ofproto_mutex'. */
8433 ovs_mutex_lock(&rule->mutex);
8434 long long int modified = rule->modified;
8435 ovs_mutex_unlock(&rule->mutex);
8436
8437 expiration = modified + rule->hard_timeout * 1000;
8438 }
8439 if (rule->idle_timeout) {
8440 uint64_t packets, bytes;
8441 long long int used;
8442 long long int idle_expiration;
8443
8444 ofproto->ofproto_class->rule_get_stats(rule, &packets, &bytes, &used);
8445 idle_expiration = used + rule->idle_timeout * 1000;
8446 expiration = MIN(expiration, idle_expiration);
8447 }
8448 if (expiration == LLONG_MAX) {
8449 return 0;
8450 }
8451
8452 /* Calculate the time of expiration as a number of (approximate) seconds
8453 * after program startup.
8454 *
8455 * This should work OK for program runs that last UINT32_MAX seconds or
8456 * less. Therefore, please restart OVS at least once every 136 years. */
8457 uint32_t expiration_ofs = (expiration >> 10) - (time_boot_msec() >> 10);
8458
8459 /* Combine expiration time with OpenFlow "importance" to form a single
8460 * priority value. We want flows with relatively low "importance" to be
8461 * evicted before even considering expiration time, so put "importance" in
8462 * the most significant bits and expiration time in the least significant
8463 * bits.
8464 *
8465 * Small 'priority' should be evicted before those with large 'priority'.
8466 * The caller expects the opposite convention (a large return value being
8467 * more attractive for eviction) so we invert it before returning. */
8468 uint64_t priority = ((uint64_t) rule->importance << 32) + expiration_ofs;
8469 return UINT64_MAX - priority;
8470 }
8471
8472 /* Adds 'rule' to an appropriate eviction group for its oftable's
8473 * configuration. Does nothing if 'rule''s oftable doesn't have eviction
8474 * enabled, or if 'rule' is a permanent rule (one that will never expire on its
8475 * own).
8476 *
8477 * The caller must ensure that 'rule' is not already in an eviction group. */
8478 static void
8479 eviction_group_add_rule(struct rule *rule)
8480 OVS_REQUIRES(ofproto_mutex)
8481 {
8482 struct ofproto *ofproto = rule->ofproto;
8483 struct oftable *table = &ofproto->tables[rule->table_id];
8484 bool has_timeout;
8485
8486 /* Timeouts may be modified only when holding 'ofproto_mutex'. We have it
8487 * so no additional protection is needed. */
8488 has_timeout = rule->hard_timeout || rule->idle_timeout;
8489
8490 if (table->eviction && has_timeout) {
8491 struct eviction_group *evg;
8492
8493 evg = eviction_group_find(table, eviction_group_hash_rule(rule));
8494
8495 rule->eviction_group = evg;
8496 heap_insert(&evg->rules, &rule->evg_node,
8497 rule_eviction_priority(ofproto, rule));
8498 eviction_group_resized(table, evg);
8499 }
8500 }
8501 \f
8502 /* oftables. */
8503
8504 /* Initializes 'table'. */
8505 static void
8506 oftable_init(struct oftable *table)
8507 {
8508 memset(table, 0, sizeof *table);
8509 classifier_init(&table->cls, flow_segment_u64s);
8510 table->max_flows = UINT_MAX;
8511 table->n_flows = 0;
8512 hmap_init(&table->eviction_groups_by_id);
8513 heap_init(&table->eviction_groups_by_size);
8514 atomic_init(&table->miss_config, OFPUTIL_TABLE_MISS_DEFAULT);
8515
8516 classifier_set_prefix_fields(&table->cls, default_prefix_fields,
8517 ARRAY_SIZE(default_prefix_fields));
8518
8519 atomic_init(&table->n_matched, 0);
8520 atomic_init(&table->n_missed, 0);
8521 }
8522
8523 /* Destroys 'table', including its classifier and eviction groups.
8524 *
8525 * The caller is responsible for freeing 'table' itself. */
8526 static void
8527 oftable_destroy(struct oftable *table)
8528 {
8529 ovs_assert(classifier_is_empty(&table->cls));
8530
8531 ovs_mutex_lock(&ofproto_mutex);
8532 oftable_configure_eviction(table, 0, NULL, 0);
8533 ovs_mutex_unlock(&ofproto_mutex);
8534
8535 hmap_destroy(&table->eviction_groups_by_id);
8536 heap_destroy(&table->eviction_groups_by_size);
8537 classifier_destroy(&table->cls);
8538 free(table->name);
8539 }
8540
8541 /* Changes the name of 'table' to 'name'. If 'name' is NULL or the empty
8542 * string, then 'table' will use its default name.
8543 *
8544 * This only affects the name exposed for a table exposed through the OpenFlow
8545 * OFPST_TABLE (as printed by "ovs-ofctl dump-tables"). */
8546 static void
8547 oftable_set_name(struct oftable *table, const char *name)
8548 {
8549 if (name && name[0]) {
8550 int len = strnlen(name, OFP_MAX_TABLE_NAME_LEN);
8551 if (!table->name || strncmp(name, table->name, len)) {
8552 free(table->name);
8553 table->name = xmemdup0(name, len);
8554 }
8555 } else {
8556 free(table->name);
8557 table->name = NULL;
8558 }
8559 }
8560
8561 /* oftables support a choice of two policies when adding a rule would cause the
8562 * number of flows in the table to exceed the configured maximum number: either
8563 * they can refuse to add the new flow or they can evict some existing flow.
8564 * This function configures the latter policy on 'table', with fairness based
8565 * on the values of the 'n_fields' fields specified in 'fields'. (Specifying
8566 * 'n_fields' as 0 disables fairness.) */
8567 static void
8568 oftable_configure_eviction(struct oftable *table, unsigned int eviction,
8569 const struct mf_subfield *fields, size_t n_fields)
8570 OVS_REQUIRES(ofproto_mutex)
8571 {
8572 struct rule *rule;
8573
8574 if ((table->eviction != 0) == (eviction != 0)
8575 && n_fields == table->n_eviction_fields
8576 && (!n_fields
8577 || !memcmp(fields, table->eviction_fields,
8578 n_fields * sizeof *fields))) {
8579 /* The set of eviction fields did not change. If 'eviction' changed,
8580 * it remains nonzero, so that we can just update table->eviction
8581 * without fussing with the eviction groups. */
8582 table->eviction = eviction;
8583 return;
8584 }
8585
8586 /* Destroy existing eviction groups, then destroy and recreate data
8587 * structures to recover memory. */
8588 struct eviction_group *evg, *next;
8589 HMAP_FOR_EACH_SAFE (evg, next, id_node, &table->eviction_groups_by_id) {
8590 eviction_group_destroy(table, evg);
8591 }
8592 hmap_destroy(&table->eviction_groups_by_id);
8593 hmap_init(&table->eviction_groups_by_id);
8594 heap_destroy(&table->eviction_groups_by_size);
8595 heap_init(&table->eviction_groups_by_size);
8596
8597 /* Replace eviction groups by the new ones, if there is a change. Free the
8598 * old fields only after allocating the new ones, because 'fields ==
8599 * table->eviction_fields' is possible. */
8600 struct mf_subfield *old_fields = table->eviction_fields;
8601 table->n_eviction_fields = n_fields;
8602 table->eviction_fields = (fields
8603 ? xmemdup(fields, n_fields * sizeof *fields)
8604 : NULL);
8605 free(old_fields);
8606
8607 /* Add the new eviction groups, if enabled. */
8608 table->eviction = eviction;
8609 if (table->eviction) {
8610 table->eviction_group_id_basis = random_uint32();
8611 CLS_FOR_EACH (rule, cr, &table->cls) {
8612 eviction_group_add_rule(rule);
8613 }
8614 }
8615 }
8616
8617 /* Inserts 'rule' from the ofproto data structures BEFORE caller has inserted
8618 * it to the classifier. */
8619 static void
8620 ofproto_rule_insert__(struct ofproto *ofproto, struct rule *rule)
8621 OVS_REQUIRES(ofproto_mutex)
8622 {
8623 const struct rule_actions *actions = rule_get_actions(rule);
8624
8625 /* A rule may not be reinserted. */
8626 ovs_assert(rule->state == RULE_INITIALIZED);
8627
8628 if (rule->hard_timeout || rule->idle_timeout) {
8629 ovs_list_insert(&ofproto->expirable, &rule->expirable);
8630 }
8631 cookies_insert(ofproto, rule);
8632 eviction_group_add_rule(rule);
8633 if (actions->has_meter) {
8634 meter_insert_rule(rule);
8635 }
8636 if (actions->has_groups) {
8637 const struct ofpact_group *a;
8638 OFPACT_FOR_EACH_TYPE_FLATTENED (a, GROUP, actions->ofpacts,
8639 actions->ofpacts_len) {
8640 struct ofgroup *group;
8641
8642 group = ofproto_group_lookup(ofproto, a->group_id, OVS_VERSION_MAX,
8643 false);
8644 ovs_assert(group != NULL);
8645 group_add_rule(group, rule);
8646 }
8647 }
8648
8649 rule->state = RULE_INSERTED;
8650 }
8651
8652 /* Removes 'rule' from the ofproto data structures. Caller may have deferred
8653 * the removal from the classifier. */
8654 static void
8655 ofproto_rule_remove__(struct ofproto *ofproto, struct rule *rule)
8656 OVS_REQUIRES(ofproto_mutex)
8657 {
8658 ovs_assert(rule->state == RULE_INSERTED);
8659
8660 cookies_remove(ofproto, rule);
8661
8662 eviction_group_remove_rule(rule);
8663 if (!ovs_list_is_empty(&rule->expirable)) {
8664 ovs_list_remove(&rule->expirable);
8665 }
8666 if (!ovs_list_is_empty(&rule->meter_list_node)) {
8667 ovs_list_remove(&rule->meter_list_node);
8668 ovs_list_init(&rule->meter_list_node);
8669 }
8670
8671 /* Remove the rule from any groups, except from the group that is being
8672 * deleted, if any. */
8673 const struct rule_actions *actions = rule_get_actions(rule);
8674
8675 if (actions->has_groups) {
8676 const struct ofpact_group *a;
8677
8678 OFPACT_FOR_EACH_TYPE_FLATTENED(a, GROUP, actions->ofpacts,
8679 actions->ofpacts_len) {
8680 struct ofgroup *group;
8681
8682 group = ofproto_group_lookup(ofproto, a->group_id, OVS_VERSION_MAX,
8683 false);
8684 ovs_assert(group);
8685
8686 /* Leave the rule for the group that is being deleted, if any,
8687 * as we still need the list of rules for clean-up. */
8688 if (!group->being_deleted) {
8689 group_remove_rule(group, rule);
8690 }
8691 }
8692 }
8693
8694 rule->state = RULE_REMOVED;
8695 }
8696 \f
8697 /* unixctl commands. */
8698
8699 struct ofproto *
8700 ofproto_lookup(const char *name)
8701 {
8702 struct ofproto *ofproto;
8703
8704 HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
8705 &all_ofprotos) {
8706 if (!strcmp(ofproto->name, name)) {
8707 return ofproto;
8708 }
8709 }
8710 return NULL;
8711 }
8712
8713 static void
8714 ofproto_unixctl_list(struct unixctl_conn *conn, int argc OVS_UNUSED,
8715 const char *argv[] OVS_UNUSED, void *aux OVS_UNUSED)
8716 {
8717 struct ofproto *ofproto;
8718 struct ds results;
8719
8720 ds_init(&results);
8721 HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
8722 ds_put_format(&results, "%s\n", ofproto->name);
8723 }
8724 unixctl_command_reply(conn, ds_cstr(&results));
8725 ds_destroy(&results);
8726 }
8727
8728 static void
8729 ofproto_unixctl_init(void)
8730 {
8731 static bool registered;
8732 if (registered) {
8733 return;
8734 }
8735 registered = true;
8736
8737 unixctl_command_register("ofproto/list", "", 0, 0,
8738 ofproto_unixctl_list, NULL);
8739 }
8740
8741 void
8742 ofproto_set_vlan_limit(int vlan_limit)
8743 {
8744 flow_limit_vlans(vlan_limit);
8745 }