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