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