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