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