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