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