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