4d4c23201b42e4904b6fe3ca333c3bda22b422e7
[sliver-openvswitch.git] / ofproto / ofproto.c
1 /*
2  * Copyright (c) 2009, 2010, 2011 Nicira Networks.
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 "byte-order.h"
25 #include "classifier.h"
26 #include "connmgr.h"
27 #include "coverage.h"
28 #include "dynamic-string.h"
29 #include "hash.h"
30 #include "hmap.h"
31 #include "netdev.h"
32 #include "nx-match.h"
33 #include "ofp-print.h"
34 #include "ofp-util.h"
35 #include "ofpbuf.h"
36 #include "ofproto-provider.h"
37 #include "openflow/nicira-ext.h"
38 #include "openflow/openflow.h"
39 #include "packets.h"
40 #include "pinsched.h"
41 #include "pktbuf.h"
42 #include "poll-loop.h"
43 #include "shash.h"
44 #include "sset.h"
45 #include "timeval.h"
46 #include "unaligned.h"
47 #include "unixctl.h"
48 #include "vlog.h"
49
50 VLOG_DEFINE_THIS_MODULE(ofproto);
51
52 COVERAGE_DEFINE(ofproto_error);
53 COVERAGE_DEFINE(ofproto_flush);
54 COVERAGE_DEFINE(ofproto_no_packet_in);
55 COVERAGE_DEFINE(ofproto_packet_out);
56 COVERAGE_DEFINE(ofproto_queue_req);
57 COVERAGE_DEFINE(ofproto_recv_openflow);
58 COVERAGE_DEFINE(ofproto_reinit_ports);
59 COVERAGE_DEFINE(ofproto_uninstallable);
60 COVERAGE_DEFINE(ofproto_update_port);
61
62 enum ofproto_state {
63     S_OPENFLOW,                 /* Processing OpenFlow commands. */
64     S_FLUSH,                    /* Deleting all flow table rules. */
65 };
66
67 enum ofoperation_type {
68     OFOPERATION_ADD,
69     OFOPERATION_DELETE,
70     OFOPERATION_MODIFY
71 };
72
73 /* A single OpenFlow request can execute any number of operations.  The
74  * ofopgroup maintain OpenFlow state common to all of the operations, e.g. the
75  * ofconn to which an error reply should be sent if necessary.
76  *
77  * ofproto initiates some operations internally.  These operations are still
78  * assigned to groups but will not have an associated ofconn. */
79 struct ofopgroup {
80     struct ofproto *ofproto;    /* Owning ofproto. */
81     struct list ofproto_node;   /* In ofproto's "pending" list. */
82     struct list ops;            /* List of "struct ofoperation"s. */
83
84     /* Data needed to send OpenFlow reply on failure or to send a buffered
85      * packet on success.
86      *
87      * If list_is_empty(ofconn_node) then this ofopgroup never had an
88      * associated ofconn or its ofconn's connection dropped after it initiated
89      * the operation.  In the latter case 'ofconn' is a wild pointer that
90      * refers to freed memory, so the 'ofconn' member must be used only if
91      * !list_is_empty(ofconn_node).
92      */
93     struct list ofconn_node;    /* In ofconn's list of pending opgroups. */
94     struct ofconn *ofconn;      /* ofconn for reply (but see note above). */
95     struct ofp_header *request; /* Original request (truncated at 64 bytes). */
96     uint32_t buffer_id;         /* Buffer id from original request. */
97     int error;                  /* 0 if no error yet, otherwise error code. */
98 };
99
100 static struct ofopgroup *ofopgroup_create(struct ofproto *);
101 static struct ofopgroup *ofopgroup_create_for_ofconn(struct ofconn *,
102                                                      const struct ofp_header *,
103                                                      uint32_t buffer_id);
104 static void ofopgroup_submit(struct ofopgroup *);
105 static void ofopgroup_destroy(struct ofopgroup *);
106
107 /* A single flow table operation. */
108 struct ofoperation {
109     struct ofopgroup *group;    /* Owning group. */
110     struct list group_node;     /* In ofopgroup's "ops" list. */
111     struct hmap_node hmap_node; /* In ofproto's "deletions" hmap. */
112     struct rule *rule;          /* Rule being operated upon. */
113     enum ofoperation_type type; /* Type of operation. */
114     int status;                 /* -1 if pending, otherwise 0 or error code. */
115     struct rule *victim;        /* OFOPERATION_ADDING: Replaced rule. */
116     union ofp_action *actions;  /* OFOPERATION_MODIFYING: Replaced actions. */
117     int n_actions;              /* OFOPERATION_MODIFYING: # of old actions. */
118     ovs_be64 flow_cookie;       /* Rule's old flow cookie. */
119 };
120
121 static void ofoperation_create(struct ofopgroup *, struct rule *,
122                                enum ofoperation_type);
123 static void ofoperation_destroy(struct ofoperation *);
124
125 static void ofport_destroy__(struct ofport *);
126 static void ofport_destroy(struct ofport *);
127
128 static uint64_t pick_datapath_id(const struct ofproto *);
129 static uint64_t pick_fallback_dpid(void);
130
131 static void ofproto_destroy__(struct ofproto *);
132
133 static void ofproto_rule_destroy__(struct rule *);
134 static void ofproto_rule_send_removed(struct rule *, uint8_t reason);
135
136 static void ofopgroup_destroy(struct ofopgroup *);
137
138 static int add_flow(struct ofproto *, struct ofconn *, struct flow_mod *,
139                     const struct ofp_header *);
140
141 /* This return value tells handle_openflow() that processing of the current
142  * OpenFlow message must be postponed until some ongoing operations have
143  * completed.
144  *
145  * This particular value is a good choice because it is negative (so it won't
146  * collide with any errno value or any value returned by ofp_mkerr()) and large
147  * (so it won't accidentally collide with EOF or a negative errno value). */
148 enum { OFPROTO_POSTPONE = -100000 };
149
150 static bool handle_openflow(struct ofconn *, struct ofpbuf *);
151
152 static void update_port(struct ofproto *, const char *devname);
153 static int init_ports(struct ofproto *);
154 static void reinit_ports(struct ofproto *);
155
156 static void ofproto_unixctl_init(void);
157
158 /* All registered ofproto classes, in probe order. */
159 static const struct ofproto_class **ofproto_classes;
160 static size_t n_ofproto_classes;
161 static size_t allocated_ofproto_classes;
162
163 /* Map from datapath name to struct ofproto, for use by unixctl commands. */
164 static struct hmap all_ofprotos = HMAP_INITIALIZER(&all_ofprotos);
165
166 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(1, 5);
167
168 static void
169 ofproto_initialize(void)
170 {
171     static bool inited;
172
173     if (!inited) {
174         inited = true;
175         ofproto_class_register(&ofproto_dpif_class);
176     }
177 }
178
179 /* 'type' should be a normalized datapath type, as returned by
180  * ofproto_normalize_type().  Returns the corresponding ofproto_class
181  * structure, or a null pointer if there is none registered for 'type'. */
182 static const struct ofproto_class *
183 ofproto_class_find__(const char *type)
184 {
185     size_t i;
186
187     ofproto_initialize();
188     for (i = 0; i < n_ofproto_classes; i++) {
189         const struct ofproto_class *class = ofproto_classes[i];
190         struct sset types;
191         bool found;
192
193         sset_init(&types);
194         class->enumerate_types(&types);
195         found = sset_contains(&types, type);
196         sset_destroy(&types);
197
198         if (found) {
199             return class;
200         }
201     }
202     VLOG_WARN("unknown datapath type %s", type);
203     return NULL;
204 }
205
206 /* Registers a new ofproto class.  After successful registration, new ofprotos
207  * of that type can be created using ofproto_create(). */
208 int
209 ofproto_class_register(const struct ofproto_class *new_class)
210 {
211     size_t i;
212
213     for (i = 0; i < n_ofproto_classes; i++) {
214         if (ofproto_classes[i] == new_class) {
215             return EEXIST;
216         }
217     }
218
219     if (n_ofproto_classes >= allocated_ofproto_classes) {
220         ofproto_classes = x2nrealloc(ofproto_classes,
221                                      &allocated_ofproto_classes,
222                                      sizeof *ofproto_classes);
223     }
224     ofproto_classes[n_ofproto_classes++] = new_class;
225     return 0;
226 }
227
228 /* Unregisters a datapath provider.  'type' must have been previously
229  * registered and not currently be in use by any ofprotos.  After
230  * unregistration new datapaths of that type cannot be opened using
231  * ofproto_create(). */
232 int
233 ofproto_class_unregister(const struct ofproto_class *class)
234 {
235     size_t i;
236
237     for (i = 0; i < n_ofproto_classes; i++) {
238         if (ofproto_classes[i] == class) {
239             for (i++; i < n_ofproto_classes; i++) {
240                 ofproto_classes[i - 1] = ofproto_classes[i];
241             }
242             n_ofproto_classes--;
243             return 0;
244         }
245     }
246     VLOG_WARN("attempted to unregister an ofproto class that is not "
247               "registered");
248     return EAFNOSUPPORT;
249 }
250
251 /* Clears 'types' and enumerates all registered ofproto types into it.  The
252  * caller must first initialize the sset. */
253 void
254 ofproto_enumerate_types(struct sset *types)
255 {
256     size_t i;
257
258     ofproto_initialize();
259     for (i = 0; i < n_ofproto_classes; i++) {
260         ofproto_classes[i]->enumerate_types(types);
261     }
262 }
263
264 /* Returns the fully spelled out name for the given ofproto 'type'.
265  *
266  * Normalized type string can be compared with strcmp().  Unnormalized type
267  * string might be the same even if they have different spellings. */
268 const char *
269 ofproto_normalize_type(const char *type)
270 {
271     return type && type[0] ? type : "system";
272 }
273
274 /* Clears 'names' and enumerates the names of all known created ofprotos with
275  * the given 'type'.  The caller must first initialize the sset.  Returns 0 if
276  * successful, otherwise a positive errno value.
277  *
278  * Some kinds of datapaths might not be practically enumerable.  This is not
279  * considered an error. */
280 int
281 ofproto_enumerate_names(const char *type, struct sset *names)
282 {
283     const struct ofproto_class *class = ofproto_class_find__(type);
284     return class ? class->enumerate_names(type, names) : EAFNOSUPPORT;
285  }
286
287 int
288 ofproto_create(const char *datapath_name, const char *datapath_type,
289                struct ofproto **ofprotop)
290 {
291     const struct ofproto_class *class;
292     struct ofproto *ofproto;
293     int n_tables;
294     int error;
295     int i;
296
297     *ofprotop = NULL;
298
299     ofproto_initialize();
300     ofproto_unixctl_init();
301
302     datapath_type = ofproto_normalize_type(datapath_type);
303     class = ofproto_class_find__(datapath_type);
304     if (!class) {
305         VLOG_WARN("could not create datapath %s of unknown type %s",
306                   datapath_name, datapath_type);
307         return EAFNOSUPPORT;
308     }
309
310     ofproto = class->alloc();
311     if (!ofproto) {
312         VLOG_ERR("failed to allocate datapath %s of type %s",
313                  datapath_name, datapath_type);
314         return ENOMEM;
315     }
316
317     /* Initialize. */
318     memset(ofproto, 0, sizeof *ofproto);
319     ofproto->ofproto_class = class;
320     ofproto->name = xstrdup(datapath_name);
321     ofproto->type = xstrdup(datapath_type);
322     hmap_insert(&all_ofprotos, &ofproto->hmap_node,
323                 hash_string(ofproto->name, 0));
324     ofproto->datapath_id = 0;
325     ofproto_set_flow_eviction_threshold(ofproto,
326                                         OFPROTO_FLOW_EVICTON_THRESHOLD_DEFAULT);
327     ofproto->fallback_dpid = pick_fallback_dpid();
328     ofproto->mfr_desc = xstrdup(DEFAULT_MFR_DESC);
329     ofproto->hw_desc = xstrdup(DEFAULT_HW_DESC);
330     ofproto->sw_desc = xstrdup(DEFAULT_SW_DESC);
331     ofproto->serial_desc = xstrdup(DEFAULT_SERIAL_DESC);
332     ofproto->dp_desc = xstrdup(DEFAULT_DP_DESC);
333     hmap_init(&ofproto->ports);
334     shash_init(&ofproto->port_by_name);
335     ofproto->tables = NULL;
336     ofproto->n_tables = 0;
337     ofproto->connmgr = connmgr_create(ofproto, datapath_name, datapath_name);
338     ofproto->state = S_OPENFLOW;
339     list_init(&ofproto->pending);
340     hmap_init(&ofproto->deletions);
341
342     error = ofproto->ofproto_class->construct(ofproto, &n_tables);
343     if (error) {
344         VLOG_ERR("failed to open datapath %s: %s",
345                  datapath_name, strerror(error));
346         ofproto_destroy__(ofproto);
347         return error;
348     }
349
350     assert(n_tables >= 1 && n_tables <= 255);
351     ofproto->n_tables = n_tables;
352     ofproto->tables = xmalloc(n_tables * sizeof *ofproto->tables);
353     for (i = 0; i < n_tables; i++) {
354         classifier_init(&ofproto->tables[i]);
355     }
356
357     ofproto->datapath_id = pick_datapath_id(ofproto);
358     VLOG_INFO("using datapath ID %016"PRIx64, ofproto->datapath_id);
359     init_ports(ofproto);
360
361     *ofprotop = ofproto;
362     return 0;
363 }
364
365 void
366 ofproto_set_datapath_id(struct ofproto *p, uint64_t datapath_id)
367 {
368     uint64_t old_dpid = p->datapath_id;
369     p->datapath_id = datapath_id ? datapath_id : pick_datapath_id(p);
370     if (p->datapath_id != old_dpid) {
371         VLOG_INFO("datapath ID changed to %016"PRIx64, p->datapath_id);
372
373         /* Force all active connections to reconnect, since there is no way to
374          * notify a controller that the datapath ID has changed. */
375         ofproto_reconnect_controllers(p);
376     }
377 }
378
379 void
380 ofproto_set_controllers(struct ofproto *p,
381                         const struct ofproto_controller *controllers,
382                         size_t n_controllers)
383 {
384     connmgr_set_controllers(p->connmgr, controllers, n_controllers);
385 }
386
387 void
388 ofproto_set_fail_mode(struct ofproto *p, enum ofproto_fail_mode fail_mode)
389 {
390     connmgr_set_fail_mode(p->connmgr, fail_mode);
391 }
392
393 /* Drops the connections between 'ofproto' and all of its controllers, forcing
394  * them to reconnect. */
395 void
396 ofproto_reconnect_controllers(struct ofproto *ofproto)
397 {
398     connmgr_reconnect(ofproto->connmgr);
399 }
400
401 /* Sets the 'n' TCP port addresses in 'extras' as ones to which 'ofproto''s
402  * in-band control should guarantee access, in the same way that in-band
403  * control guarantees access to OpenFlow controllers. */
404 void
405 ofproto_set_extra_in_band_remotes(struct ofproto *ofproto,
406                                   const struct sockaddr_in *extras, size_t n)
407 {
408     connmgr_set_extra_in_band_remotes(ofproto->connmgr, extras, n);
409 }
410
411 /* Sets the OpenFlow queue used by flows set up by in-band control on
412  * 'ofproto' to 'queue_id'.  If 'queue_id' is negative, then in-band control
413  * flows will use the default queue. */
414 void
415 ofproto_set_in_band_queue(struct ofproto *ofproto, int queue_id)
416 {
417     connmgr_set_in_band_queue(ofproto->connmgr, queue_id);
418 }
419
420 /* Sets the number of flows at which eviction from the kernel flow table
421  * will occur. */
422 void
423 ofproto_set_flow_eviction_threshold(struct ofproto *ofproto, unsigned threshold)
424 {
425     if (threshold < OFPROTO_FLOW_EVICTION_THRESHOLD_MIN) {
426         ofproto->flow_eviction_threshold = OFPROTO_FLOW_EVICTION_THRESHOLD_MIN;
427     } else {
428         ofproto->flow_eviction_threshold = threshold;
429     }
430 }
431
432 void
433 ofproto_set_desc(struct ofproto *p,
434                  const char *mfr_desc, const char *hw_desc,
435                  const char *sw_desc, const char *serial_desc,
436                  const char *dp_desc)
437 {
438     struct ofp_desc_stats *ods;
439
440     if (mfr_desc) {
441         if (strlen(mfr_desc) >= sizeof ods->mfr_desc) {
442             VLOG_WARN("truncating mfr_desc, must be less than %zu characters",
443                     sizeof ods->mfr_desc);
444         }
445         free(p->mfr_desc);
446         p->mfr_desc = xstrdup(mfr_desc);
447     }
448     if (hw_desc) {
449         if (strlen(hw_desc) >= sizeof ods->hw_desc) {
450             VLOG_WARN("truncating hw_desc, must be less than %zu characters",
451                     sizeof ods->hw_desc);
452         }
453         free(p->hw_desc);
454         p->hw_desc = xstrdup(hw_desc);
455     }
456     if (sw_desc) {
457         if (strlen(sw_desc) >= sizeof ods->sw_desc) {
458             VLOG_WARN("truncating sw_desc, must be less than %zu characters",
459                     sizeof ods->sw_desc);
460         }
461         free(p->sw_desc);
462         p->sw_desc = xstrdup(sw_desc);
463     }
464     if (serial_desc) {
465         if (strlen(serial_desc) >= sizeof ods->serial_num) {
466             VLOG_WARN("truncating serial_desc, must be less than %zu "
467                     "characters",
468                     sizeof ods->serial_num);
469         }
470         free(p->serial_desc);
471         p->serial_desc = xstrdup(serial_desc);
472     }
473     if (dp_desc) {
474         if (strlen(dp_desc) >= sizeof ods->dp_desc) {
475             VLOG_WARN("truncating dp_desc, must be less than %zu characters",
476                     sizeof ods->dp_desc);
477         }
478         free(p->dp_desc);
479         p->dp_desc = xstrdup(dp_desc);
480     }
481 }
482
483 int
484 ofproto_set_snoops(struct ofproto *ofproto, const struct sset *snoops)
485 {
486     return connmgr_set_snoops(ofproto->connmgr, snoops);
487 }
488
489 int
490 ofproto_set_netflow(struct ofproto *ofproto,
491                     const struct netflow_options *nf_options)
492 {
493     if (nf_options && sset_is_empty(&nf_options->collectors)) {
494         nf_options = NULL;
495     }
496
497     if (ofproto->ofproto_class->set_netflow) {
498         return ofproto->ofproto_class->set_netflow(ofproto, nf_options);
499     } else {
500         return nf_options ? EOPNOTSUPP : 0;
501     }
502 }
503
504 int
505 ofproto_set_sflow(struct ofproto *ofproto,
506                   const struct ofproto_sflow_options *oso)
507 {
508     if (oso && sset_is_empty(&oso->targets)) {
509         oso = NULL;
510     }
511
512     if (ofproto->ofproto_class->set_sflow) {
513         return ofproto->ofproto_class->set_sflow(ofproto, oso);
514     } else {
515         return oso ? EOPNOTSUPP : 0;
516     }
517 }
518 \f
519 /* Connectivity Fault Management configuration. */
520
521 /* Clears the CFM configuration from 'ofp_port' on 'ofproto'. */
522 void
523 ofproto_port_clear_cfm(struct ofproto *ofproto, uint16_t ofp_port)
524 {
525     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
526     if (ofport && ofproto->ofproto_class->set_cfm) {
527         ofproto->ofproto_class->set_cfm(ofport, NULL);
528     }
529 }
530
531 /* Configures connectivity fault management on 'ofp_port' in 'ofproto'.  Takes
532  * basic configuration from the configuration members in 'cfm', and the remote
533  * maintenance point ID from  remote_mpid.  Ignores the statistics members of
534  * 'cfm'.
535  *
536  * This function has no effect if 'ofproto' does not have a port 'ofp_port'. */
537 void
538 ofproto_port_set_cfm(struct ofproto *ofproto, uint16_t ofp_port,
539                      const struct cfm_settings *s)
540 {
541     struct ofport *ofport;
542     int error;
543
544     ofport = ofproto_get_port(ofproto, ofp_port);
545     if (!ofport) {
546         VLOG_WARN("%s: cannot configure CFM on nonexistent port %"PRIu16,
547                   ofproto->name, ofp_port);
548         return;
549     }
550
551     /* XXX: For configuration simplicity, we only support one remote_mpid
552      * outside of the CFM module.  It's not clear if this is the correct long
553      * term solution or not. */
554     error = (ofproto->ofproto_class->set_cfm
555              ? ofproto->ofproto_class->set_cfm(ofport, s)
556              : EOPNOTSUPP);
557     if (error) {
558         VLOG_WARN("%s: CFM configuration on port %"PRIu16" (%s) failed (%s)",
559                   ofproto->name, ofp_port, netdev_get_name(ofport->netdev),
560                   strerror(error));
561     }
562 }
563
564 /* Checks the status of LACP negotiation for 'ofp_port' within ofproto.
565  * Returns 1 if LACP partner information for 'ofp_port' is up-to-date,
566  * 0 if LACP partner information is not current (generally indicating a
567  * connectivity problem), or -1 if LACP is not enabled on 'ofp_port'. */
568 int
569 ofproto_port_is_lacp_current(struct ofproto *ofproto, uint16_t ofp_port)
570 {
571     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
572     return (ofport && ofproto->ofproto_class->port_is_lacp_current
573             ? ofproto->ofproto_class->port_is_lacp_current(ofport)
574             : -1);
575 }
576 \f
577 /* Bundles. */
578
579 /* Registers a "bundle" associated with client data pointer 'aux' in 'ofproto'.
580  * A bundle is the same concept as a Port in OVSDB, that is, it consists of one
581  * or more "slave" devices (Interfaces, in OVSDB) along with a VLAN
582  * configuration plus, if there is more than one slave, a bonding
583  * configuration.
584  *
585  * If 'aux' is already registered then this function updates its configuration
586  * to 's'.  Otherwise, this function registers a new bundle.
587  *
588  * Bundles only affect the NXAST_AUTOPATH action and output to the OFPP_NORMAL
589  * port. */
590 int
591 ofproto_bundle_register(struct ofproto *ofproto, void *aux,
592                         const struct ofproto_bundle_settings *s)
593 {
594     return (ofproto->ofproto_class->bundle_set
595             ? ofproto->ofproto_class->bundle_set(ofproto, aux, s)
596             : EOPNOTSUPP);
597 }
598
599 /* Unregisters the bundle registered on 'ofproto' with auxiliary data 'aux'.
600  * If no such bundle has been registered, this has no effect. */
601 int
602 ofproto_bundle_unregister(struct ofproto *ofproto, void *aux)
603 {
604     return ofproto_bundle_register(ofproto, aux, NULL);
605 }
606
607 \f
608 /* Registers a mirror associated with client data pointer 'aux' in 'ofproto'.
609  * If 'aux' is already registered then this function updates its configuration
610  * to 's'.  Otherwise, this function registers a new mirror.
611  *
612  * Mirrors affect only the treatment of packets output to the OFPP_NORMAL
613  * port.  */
614 int
615 ofproto_mirror_register(struct ofproto *ofproto, void *aux,
616                         const struct ofproto_mirror_settings *s)
617 {
618     return (ofproto->ofproto_class->mirror_set
619             ? ofproto->ofproto_class->mirror_set(ofproto, aux, s)
620             : EOPNOTSUPP);
621 }
622
623 /* Unregisters the mirror registered on 'ofproto' with auxiliary data 'aux'.
624  * If no mirror has been registered, this has no effect. */
625 int
626 ofproto_mirror_unregister(struct ofproto *ofproto, void *aux)
627 {
628     return ofproto_mirror_register(ofproto, aux, NULL);
629 }
630
631 /* Configures the VLANs whose bits are set to 1 in 'flood_vlans' as VLANs on
632  * which all packets are flooded, instead of using MAC learning.  If
633  * 'flood_vlans' is NULL, then MAC learning applies to all VLANs.
634  *
635  * Flood VLANs affect only the treatment of packets output to the OFPP_NORMAL
636  * port. */
637 int
638 ofproto_set_flood_vlans(struct ofproto *ofproto, unsigned long *flood_vlans)
639 {
640     return (ofproto->ofproto_class->set_flood_vlans
641             ? ofproto->ofproto_class->set_flood_vlans(ofproto, flood_vlans)
642             : EOPNOTSUPP);
643 }
644
645 /* Returns true if 'aux' is a registered bundle that is currently in use as the
646  * output for a mirror. */
647 bool
648 ofproto_is_mirror_output_bundle(struct ofproto *ofproto, void *aux)
649 {
650     return (ofproto->ofproto_class->is_mirror_output_bundle
651             ? ofproto->ofproto_class->is_mirror_output_bundle(ofproto, aux)
652             : false);
653 }
654 \f
655 bool
656 ofproto_has_snoops(const struct ofproto *ofproto)
657 {
658     return connmgr_has_snoops(ofproto->connmgr);
659 }
660
661 void
662 ofproto_get_snoops(const struct ofproto *ofproto, struct sset *snoops)
663 {
664     connmgr_get_snoops(ofproto->connmgr, snoops);
665 }
666
667 static void
668 ofproto_flush__(struct ofproto *ofproto)
669 {
670     struct classifier *table;
671     struct ofopgroup *group;
672
673     if (ofproto->ofproto_class->flush) {
674         ofproto->ofproto_class->flush(ofproto);
675     }
676
677     group = ofopgroup_create(ofproto);
678     for (table = ofproto->tables; table < &ofproto->tables[ofproto->n_tables];
679          table++) {
680         struct rule *rule, *next_rule;
681         struct cls_cursor cursor;
682
683         cls_cursor_init(&cursor, table, NULL);
684         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
685             if (!rule->pending) {
686                 ofoperation_create(group, rule, OFOPERATION_DELETE);
687                 classifier_remove(table, &rule->cr);
688                 ofproto->ofproto_class->rule_destruct(rule);
689             }
690         }
691     }
692     ofopgroup_submit(group);
693 }
694
695 static void
696 ofproto_destroy__(struct ofproto *ofproto)
697 {
698     size_t i;
699
700     assert(list_is_empty(&ofproto->pending));
701
702     connmgr_destroy(ofproto->connmgr);
703
704     hmap_remove(&all_ofprotos, &ofproto->hmap_node);
705     free(ofproto->name);
706     free(ofproto->type);
707     free(ofproto->mfr_desc);
708     free(ofproto->hw_desc);
709     free(ofproto->sw_desc);
710     free(ofproto->serial_desc);
711     free(ofproto->dp_desc);
712     hmap_destroy(&ofproto->ports);
713     shash_destroy(&ofproto->port_by_name);
714
715     for (i = 0; i < ofproto->n_tables; i++) {
716         assert(classifier_is_empty(&ofproto->tables[i]));
717         classifier_destroy(&ofproto->tables[i]);
718     }
719     free(ofproto->tables);
720
721     hmap_destroy(&ofproto->deletions);
722
723     ofproto->ofproto_class->dealloc(ofproto);
724 }
725
726 void
727 ofproto_destroy(struct ofproto *p)
728 {
729     struct ofport *ofport, *next_ofport;
730
731     if (!p) {
732         return;
733     }
734
735     ofproto_flush__(p);
736     HMAP_FOR_EACH_SAFE (ofport, next_ofport, hmap_node, &p->ports) {
737         ofport_destroy(ofport);
738     }
739
740     p->ofproto_class->destruct(p);
741     ofproto_destroy__(p);
742 }
743
744 /* Destroys the datapath with the respective 'name' and 'type'.  With the Linux
745  * kernel datapath, for example, this destroys the datapath in the kernel, and
746  * with the netdev-based datapath, it tears down the data structures that
747  * represent the datapath.
748  *
749  * The datapath should not be currently open as an ofproto. */
750 int
751 ofproto_delete(const char *name, const char *type)
752 {
753     const struct ofproto_class *class = ofproto_class_find__(type);
754     return (!class ? EAFNOSUPPORT
755             : !class->del ? EACCES
756             : class->del(type, name));
757 }
758
759 static void
760 process_port_change(struct ofproto *ofproto, int error, char *devname)
761 {
762     if (error == ENOBUFS) {
763         reinit_ports(ofproto);
764     } else if (!error) {
765         update_port(ofproto, devname);
766         free(devname);
767     }
768 }
769
770 int
771 ofproto_run(struct ofproto *p)
772 {
773     struct ofport *ofport;
774     char *devname;
775     int error;
776
777     error = p->ofproto_class->run(p);
778     if (error == ENODEV) {
779         /* Someone destroyed the datapath behind our back.  The caller
780          * better destroy us and give up, because we're just going to
781          * spin from here on out. */
782         static struct vlog_rate_limit rl2 = VLOG_RATE_LIMIT_INIT(1, 5);
783         VLOG_ERR_RL(&rl2, "%s: datapath was destroyed externally",
784                     p->name);
785         return ENODEV;
786     }
787
788     if (p->ofproto_class->port_poll) {
789         while ((error = p->ofproto_class->port_poll(p, &devname)) != EAGAIN) {
790             process_port_change(p, error, devname);
791         }
792     }
793
794     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
795         unsigned int change_seq = netdev_change_seq(ofport->netdev);
796         if (ofport->change_seq != change_seq) {
797             ofport->change_seq = change_seq;
798             update_port(p, netdev_get_name(ofport->netdev));
799         }
800     }
801
802
803     switch (p->state) {
804     case S_OPENFLOW:
805         connmgr_run(p->connmgr, handle_openflow);
806         break;
807
808     case S_FLUSH:
809         connmgr_run(p->connmgr, NULL);
810         ofproto_flush__(p);
811         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
812             connmgr_flushed(p->connmgr);
813             p->state = S_OPENFLOW;
814         }
815         break;
816
817     default:
818         NOT_REACHED();
819     }
820
821     return 0;
822 }
823
824 void
825 ofproto_wait(struct ofproto *p)
826 {
827     struct ofport *ofport;
828
829     p->ofproto_class->wait(p);
830     if (p->ofproto_class->port_poll_wait) {
831         p->ofproto_class->port_poll_wait(p);
832     }
833
834     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
835         if (ofport->change_seq != netdev_change_seq(ofport->netdev)) {
836             poll_immediate_wake();
837         }
838     }
839
840     switch (p->state) {
841     case S_OPENFLOW:
842         connmgr_wait(p->connmgr, true);
843         break;
844
845     case S_FLUSH:
846         connmgr_wait(p->connmgr, false);
847         if (list_is_empty(&p->pending) && hmap_is_empty(&p->deletions)) {
848             poll_immediate_wake();
849         }
850         break;
851     }
852 }
853
854 bool
855 ofproto_is_alive(const struct ofproto *p)
856 {
857     return connmgr_has_controllers(p->connmgr);
858 }
859
860 void
861 ofproto_get_ofproto_controller_info(const struct ofproto *ofproto,
862                                     struct shash *info)
863 {
864     connmgr_get_controller_info(ofproto->connmgr, info);
865 }
866
867 void
868 ofproto_free_ofproto_controller_info(struct shash *info)
869 {
870     connmgr_free_controller_info(info);
871 }
872
873 /* Makes a deep copy of 'old' into 'port'. */
874 void
875 ofproto_port_clone(struct ofproto_port *port, const struct ofproto_port *old)
876 {
877     port->name = xstrdup(old->name);
878     port->type = xstrdup(old->type);
879     port->ofp_port = old->ofp_port;
880 }
881
882 /* Frees memory allocated to members of 'ofproto_port'.
883  *
884  * Do not call this function on an ofproto_port obtained from
885  * ofproto_port_dump_next(): that function retains ownership of the data in the
886  * ofproto_port. */
887 void
888 ofproto_port_destroy(struct ofproto_port *ofproto_port)
889 {
890     free(ofproto_port->name);
891     free(ofproto_port->type);
892 }
893
894 /* Initializes 'dump' to begin dumping the ports in an ofproto.
895  *
896  * This function provides no status indication.  An error status for the entire
897  * dump operation is provided when it is completed by calling
898  * ofproto_port_dump_done().
899  */
900 void
901 ofproto_port_dump_start(struct ofproto_port_dump *dump,
902                         const struct ofproto *ofproto)
903 {
904     dump->ofproto = ofproto;
905     dump->error = ofproto->ofproto_class->port_dump_start(ofproto,
906                                                           &dump->state);
907 }
908
909 /* Attempts to retrieve another port from 'dump', which must have been created
910  * with ofproto_port_dump_start().  On success, stores a new ofproto_port into
911  * 'port' and returns true.  On failure, returns false.
912  *
913  * Failure might indicate an actual error or merely that the last port has been
914  * dumped.  An error status for the entire dump operation is provided when it
915  * is completed by calling ofproto_port_dump_done().
916  *
917  * The ofproto owns the data stored in 'port'.  It will remain valid until at
918  * least the next time 'dump' is passed to ofproto_port_dump_next() or
919  * ofproto_port_dump_done(). */
920 bool
921 ofproto_port_dump_next(struct ofproto_port_dump *dump,
922                        struct ofproto_port *port)
923 {
924     const struct ofproto *ofproto = dump->ofproto;
925
926     if (dump->error) {
927         return false;
928     }
929
930     dump->error = ofproto->ofproto_class->port_dump_next(ofproto, dump->state,
931                                                          port);
932     if (dump->error) {
933         ofproto->ofproto_class->port_dump_done(ofproto, dump->state);
934         return false;
935     }
936     return true;
937 }
938
939 /* Completes port table dump operation 'dump', which must have been created
940  * with ofproto_port_dump_start().  Returns 0 if the dump operation was
941  * error-free, otherwise a positive errno value describing the problem. */
942 int
943 ofproto_port_dump_done(struct ofproto_port_dump *dump)
944 {
945     const struct ofproto *ofproto = dump->ofproto;
946     if (!dump->error) {
947         dump->error = ofproto->ofproto_class->port_dump_done(ofproto,
948                                                              dump->state);
949     }
950     return dump->error == EOF ? 0 : dump->error;
951 }
952
953 /* Attempts to add 'netdev' as a port on 'ofproto'.  If successful, returns 0
954  * and sets '*ofp_portp' to the new port's OpenFlow port number (if 'ofp_portp'
955  * is non-null).  On failure, returns a positive errno value and sets
956  * '*ofp_portp' to OFPP_NONE (if 'ofp_portp' is non-null). */
957 int
958 ofproto_port_add(struct ofproto *ofproto, struct netdev *netdev,
959                  uint16_t *ofp_portp)
960 {
961     uint16_t ofp_port;
962     int error;
963
964     error = ofproto->ofproto_class->port_add(ofproto, netdev, &ofp_port);
965     if (!error) {
966         update_port(ofproto, netdev_get_name(netdev));
967     }
968     if (ofp_portp) {
969         *ofp_portp = error ? OFPP_NONE : ofp_port;
970     }
971     return error;
972 }
973
974 /* Looks up a port named 'devname' in 'ofproto'.  On success, returns 0 and
975  * initializes '*port' appropriately; on failure, returns a positive errno
976  * value.
977  *
978  * The caller owns the data in 'ofproto_port' and must free it with
979  * ofproto_port_destroy() when it is no longer needed. */
980 int
981 ofproto_port_query_by_name(const struct ofproto *ofproto, const char *devname,
982                            struct ofproto_port *port)
983 {
984     int error;
985
986     error = ofproto->ofproto_class->port_query_by_name(ofproto, devname, port);
987     if (error) {
988         memset(port, 0, sizeof *port);
989     }
990     return error;
991 }
992
993 /* Deletes port number 'ofp_port' from the datapath for 'ofproto'.
994  * Returns 0 if successful, otherwise a positive errno. */
995 int
996 ofproto_port_del(struct ofproto *ofproto, uint16_t ofp_port)
997 {
998     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
999     const char *name = ofport ? netdev_get_name(ofport->netdev) : "<unknown>";
1000     int error;
1001
1002     error = ofproto->ofproto_class->port_del(ofproto, ofp_port);
1003     if (!error && ofport) {
1004         /* 'name' is the netdev's name and update_port() is going to close the
1005          * netdev.  Just in case update_port() refers to 'name' after it
1006          * destroys 'ofport', make a copy of it around the update_port()
1007          * call. */
1008         char *devname = xstrdup(name);
1009         update_port(ofproto, devname);
1010         free(devname);
1011     }
1012     return error;
1013 }
1014
1015 /* Adds a flow to OpenFlow flow table 0 in 'p' that matches 'cls_rule' and
1016  * performs the 'n_actions' actions in 'actions'.  The new flow will not
1017  * timeout.
1018  *
1019  * If cls_rule->priority is in the range of priorities supported by OpenFlow
1020  * (0...65535, inclusive) then the flow will be visible to OpenFlow
1021  * controllers; otherwise, it will be hidden.
1022  *
1023  * The caller retains ownership of 'cls_rule' and 'actions'.
1024  *
1025  * This is a helper function for in-band control and fail-open. */
1026 void
1027 ofproto_add_flow(struct ofproto *ofproto, const struct cls_rule *cls_rule,
1028                  const union ofp_action *actions, size_t n_actions)
1029 {
1030     const struct rule *rule;
1031
1032     rule = rule_from_cls_rule(classifier_find_rule_exactly(
1033                                     &ofproto->tables[0], cls_rule));
1034     if (!rule || !ofputil_actions_equal(rule->actions, rule->n_actions,
1035                                         actions, n_actions)) {
1036         struct flow_mod fm;
1037
1038         memset(&fm, 0, sizeof fm);
1039         fm.cr = *cls_rule;
1040         fm.buffer_id = UINT32_MAX;
1041         fm.actions = (union ofp_action *) actions;
1042         fm.n_actions = n_actions;
1043         add_flow(ofproto, NULL, &fm, NULL);
1044     }
1045 }
1046
1047 /* Searches for a rule with matching criteria exactly equal to 'target' in
1048  * ofproto's table 0 and, if it finds one, deletes it.
1049  *
1050  * This is a helper function for in-band control and fail-open. */
1051 bool
1052 ofproto_delete_flow(struct ofproto *ofproto, const struct cls_rule *target)
1053 {
1054     struct rule *rule;
1055
1056     rule = rule_from_cls_rule(classifier_find_rule_exactly(
1057                                   &ofproto->tables[0], target));
1058     if (!rule) {
1059         /* No such rule -> success. */
1060         return true;
1061     } else if (rule->pending) {
1062         /* An operation on the rule is already pending -> failure.
1063          * Caller must retry later if it's important. */
1064         return false;
1065     } else {
1066         /* Initiate deletion -> success. */
1067         struct ofopgroup *group = ofopgroup_create(ofproto);
1068         ofoperation_create(group, rule, OFOPERATION_DELETE);
1069         classifier_remove(&ofproto->tables[rule->table_id], &rule->cr);
1070         rule->ofproto->ofproto_class->rule_destruct(rule);
1071         ofopgroup_submit(group);
1072         return true;
1073     }
1074
1075 }
1076
1077 /* Starts the process of deleting all of the flows from all of ofproto's flow
1078  * tables and then reintroducing the flows required by in-band control and
1079  * fail-open.  The process will complete in a later call to ofproto_run(). */
1080 void
1081 ofproto_flush_flows(struct ofproto *ofproto)
1082 {
1083     COVERAGE_INC(ofproto_flush);
1084     ofproto->state = S_FLUSH;
1085 }
1086 \f
1087 static void
1088 reinit_ports(struct ofproto *p)
1089 {
1090     struct ofproto_port_dump dump;
1091     struct sset devnames;
1092     struct ofport *ofport;
1093     struct ofproto_port ofproto_port;
1094     const char *devname;
1095
1096     COVERAGE_INC(ofproto_reinit_ports);
1097
1098     sset_init(&devnames);
1099     HMAP_FOR_EACH (ofport, hmap_node, &p->ports) {
1100         sset_add(&devnames, netdev_get_name(ofport->netdev));
1101     }
1102     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1103         sset_add(&devnames, ofproto_port.name);
1104     }
1105
1106     SSET_FOR_EACH (devname, &devnames) {
1107         update_port(p, devname);
1108     }
1109     sset_destroy(&devnames);
1110 }
1111
1112 /* Opens and returns a netdev for 'ofproto_port', or a null pointer if the
1113  * netdev cannot be opened.  On success, also fills in 'opp'.  */
1114 static struct netdev *
1115 ofport_open(const struct ofproto_port *ofproto_port, struct ofp_phy_port *opp)
1116 {
1117     uint32_t curr, advertised, supported, peer;
1118     enum netdev_flags flags;
1119     struct netdev *netdev;
1120     int error;
1121
1122     error = netdev_open(ofproto_port->name, ofproto_port->type, &netdev);
1123     if (error) {
1124         VLOG_WARN_RL(&rl, "ignoring port %s (%"PRIu16") because netdev %s "
1125                      "cannot be opened (%s)",
1126                      ofproto_port->name, ofproto_port->ofp_port,
1127                      ofproto_port->name, strerror(error));
1128         return NULL;
1129     }
1130
1131     netdev_get_flags(netdev, &flags);
1132     netdev_get_features(netdev, &curr, &advertised, &supported, &peer);
1133
1134     opp->port_no = htons(ofproto_port->ofp_port);
1135     netdev_get_etheraddr(netdev, opp->hw_addr);
1136     ovs_strzcpy(opp->name, ofproto_port->name, sizeof opp->name);
1137     opp->config = flags & NETDEV_UP ? 0 : htonl(OFPPC_PORT_DOWN);
1138     opp->state = netdev_get_carrier(netdev) ? 0 : htonl(OFPPS_LINK_DOWN);
1139     opp->curr = htonl(curr);
1140     opp->advertised = htonl(advertised);
1141     opp->supported = htonl(supported);
1142     opp->peer = htonl(peer);
1143
1144     return netdev;
1145 }
1146
1147 /* Returns true if most fields of 'a' and 'b' are equal.  Differences in name,
1148  * port number, and 'config' bits other than OFPPC_PORT_DOWN are
1149  * disregarded. */
1150 static bool
1151 ofport_equal(const struct ofp_phy_port *a, const struct ofp_phy_port *b)
1152 {
1153     BUILD_ASSERT_DECL(sizeof *a == 48); /* Detect ofp_phy_port changes. */
1154     return (!memcmp(a->hw_addr, b->hw_addr, sizeof a->hw_addr)
1155             && a->state == b->state
1156             && !((a->config ^ b->config) & htonl(OFPPC_PORT_DOWN))
1157             && a->curr == b->curr
1158             && a->advertised == b->advertised
1159             && a->supported == b->supported
1160             && a->peer == b->peer);
1161 }
1162
1163 /* Adds an ofport to 'p' initialized based on the given 'netdev' and 'opp'.
1164  * The caller must ensure that 'p' does not have a conflicting ofport (that is,
1165  * one with the same name or port number). */
1166 static void
1167 ofport_install(struct ofproto *p,
1168                struct netdev *netdev, const struct ofp_phy_port *opp)
1169 {
1170     const char *netdev_name = netdev_get_name(netdev);
1171     struct ofport *ofport;
1172     int error;
1173
1174     /* Create ofport. */
1175     ofport = p->ofproto_class->port_alloc();
1176     if (!ofport) {
1177         error = ENOMEM;
1178         goto error;
1179     }
1180     ofport->ofproto = p;
1181     ofport->netdev = netdev;
1182     ofport->change_seq = netdev_change_seq(netdev);
1183     ofport->opp = *opp;
1184     ofport->ofp_port = ntohs(opp->port_no);
1185
1186     /* Add port to 'p'. */
1187     hmap_insert(&p->ports, &ofport->hmap_node, hash_int(ofport->ofp_port, 0));
1188     shash_add(&p->port_by_name, netdev_name, ofport);
1189
1190     /* Let the ofproto_class initialize its private data. */
1191     error = p->ofproto_class->port_construct(ofport);
1192     if (error) {
1193         goto error;
1194     }
1195     connmgr_send_port_status(p->connmgr, opp, OFPPR_ADD);
1196     return;
1197
1198 error:
1199     VLOG_WARN_RL(&rl, "%s: could not add port %s (%s)",
1200                  p->name, netdev_name, strerror(error));
1201     if (ofport) {
1202         ofport_destroy__(ofport);
1203     } else {
1204         netdev_close(netdev);
1205     }
1206 }
1207
1208 /* Removes 'ofport' from 'p' and destroys it. */
1209 static void
1210 ofport_remove(struct ofport *ofport)
1211 {
1212     connmgr_send_port_status(ofport->ofproto->connmgr, &ofport->opp,
1213                              OFPPR_DELETE);
1214     ofport_destroy(ofport);
1215 }
1216
1217 /* If 'ofproto' contains an ofport named 'name', removes it from 'ofproto' and
1218  * destroys it. */
1219 static void
1220 ofport_remove_with_name(struct ofproto *ofproto, const char *name)
1221 {
1222     struct ofport *port = shash_find_data(&ofproto->port_by_name, name);
1223     if (port) {
1224         ofport_remove(port);
1225     }
1226 }
1227
1228 /* Updates 'port' within 'ofproto' with the new 'netdev' and 'opp'.
1229  *
1230  * Does not handle a name or port number change.  The caller must implement
1231  * such a change as a delete followed by an add.  */
1232 static void
1233 ofport_modified(struct ofport *port, struct ofp_phy_port *opp)
1234 {
1235     memcpy(port->opp.hw_addr, opp->hw_addr, ETH_ADDR_LEN);
1236     port->opp.config = ((port->opp.config & ~htonl(OFPPC_PORT_DOWN))
1237                         | (opp->config & htonl(OFPPC_PORT_DOWN)));
1238     port->opp.state = opp->state;
1239     port->opp.curr = opp->curr;
1240     port->opp.advertised = opp->advertised;
1241     port->opp.supported = opp->supported;
1242     port->opp.peer = opp->peer;
1243
1244     connmgr_send_port_status(port->ofproto->connmgr, &port->opp, OFPPR_MODIFY);
1245 }
1246
1247 void
1248 ofproto_port_unregister(struct ofproto *ofproto, uint16_t ofp_port)
1249 {
1250     struct ofport *port = ofproto_get_port(ofproto, ofp_port);
1251     if (port) {
1252         if (port->ofproto->ofproto_class->set_cfm) {
1253             port->ofproto->ofproto_class->set_cfm(port, NULL);
1254         }
1255         if (port->ofproto->ofproto_class->bundle_remove) {
1256             port->ofproto->ofproto_class->bundle_remove(port);
1257         }
1258     }
1259 }
1260
1261 static void
1262 ofport_destroy__(struct ofport *port)
1263 {
1264     struct ofproto *ofproto = port->ofproto;
1265     const char *name = netdev_get_name(port->netdev);
1266
1267     hmap_remove(&ofproto->ports, &port->hmap_node);
1268     shash_delete(&ofproto->port_by_name,
1269                  shash_find(&ofproto->port_by_name, name));
1270
1271     netdev_close(port->netdev);
1272     ofproto->ofproto_class->port_dealloc(port);
1273 }
1274
1275 static void
1276 ofport_destroy(struct ofport *port)
1277 {
1278     if (port) {
1279         port->ofproto->ofproto_class->port_destruct(port);
1280         ofport_destroy__(port);
1281      }
1282 }
1283
1284 struct ofport *
1285 ofproto_get_port(const struct ofproto *ofproto, uint16_t ofp_port)
1286 {
1287     struct ofport *port;
1288
1289     HMAP_FOR_EACH_IN_BUCKET (port, hmap_node,
1290                              hash_int(ofp_port, 0), &ofproto->ports) {
1291         if (port->ofp_port == ofp_port) {
1292             return port;
1293         }
1294     }
1295     return NULL;
1296 }
1297
1298 static void
1299 update_port(struct ofproto *ofproto, const char *name)
1300 {
1301     struct ofproto_port ofproto_port;
1302     struct ofp_phy_port opp;
1303     struct netdev *netdev;
1304     struct ofport *port;
1305
1306     COVERAGE_INC(ofproto_update_port);
1307
1308     /* Fetch 'name''s location and properties from the datapath. */
1309     netdev = (!ofproto_port_query_by_name(ofproto, name, &ofproto_port)
1310               ? ofport_open(&ofproto_port, &opp)
1311               : NULL);
1312     if (netdev) {
1313         port = ofproto_get_port(ofproto, ofproto_port.ofp_port);
1314         if (port && !strcmp(netdev_get_name(port->netdev), name)) {
1315             struct netdev *old_netdev = port->netdev;
1316
1317             /* 'name' hasn't changed location.  Any properties changed? */
1318             if (!ofport_equal(&port->opp, &opp)) {
1319                 ofport_modified(port, &opp);
1320             }
1321
1322             /* Install the newly opened netdev in case it has changed.
1323              * Don't close the old netdev yet in case port_modified has to
1324              * remove a retained reference to it.*/
1325             port->netdev = netdev;
1326             port->change_seq = netdev_change_seq(netdev);
1327
1328             if (port->ofproto->ofproto_class->port_modified) {
1329                 port->ofproto->ofproto_class->port_modified(port);
1330             }
1331
1332             netdev_close(old_netdev);
1333         } else {
1334             /* If 'port' is nonnull then its name differs from 'name' and thus
1335              * we should delete it.  If we think there's a port named 'name'
1336              * then its port number must be wrong now so delete it too. */
1337             if (port) {
1338                 ofport_remove(port);
1339             }
1340             ofport_remove_with_name(ofproto, name);
1341             ofport_install(ofproto, netdev, &opp);
1342         }
1343     } else {
1344         /* Any port named 'name' is gone now. */
1345         ofport_remove_with_name(ofproto, name);
1346     }
1347     ofproto_port_destroy(&ofproto_port);
1348 }
1349
1350 static int
1351 init_ports(struct ofproto *p)
1352 {
1353     struct ofproto_port_dump dump;
1354     struct ofproto_port ofproto_port;
1355
1356     OFPROTO_PORT_FOR_EACH (&ofproto_port, &dump, p) {
1357         uint16_t ofp_port = ofproto_port.ofp_port;
1358         if (ofproto_get_port(p, ofp_port)) {
1359             VLOG_WARN_RL(&rl, "ignoring duplicate port %"PRIu16" in datapath",
1360                          ofp_port);
1361         } else if (shash_find(&p->port_by_name, ofproto_port.name)) {
1362             VLOG_WARN_RL(&rl, "ignoring duplicate device %s in datapath",
1363                          ofproto_port.name);
1364         } else {
1365             struct ofp_phy_port opp;
1366             struct netdev *netdev;
1367
1368             netdev = ofport_open(&ofproto_port, &opp);
1369             if (netdev) {
1370                 ofport_install(p, netdev, &opp);
1371             }
1372         }
1373     }
1374
1375     return 0;
1376 }
1377 \f
1378 static void
1379 ofproto_rule_destroy__(struct rule *rule)
1380 {
1381     free(rule->actions);
1382     rule->ofproto->ofproto_class->rule_dealloc(rule);
1383 }
1384
1385 /* This function allows an ofproto implementation to destroy any rules that
1386  * remain when its ->destruct() function is called.  The caller must have
1387  * already uninitialized any derived members of 'rule' (step 5 described in the
1388  * large comment in ofproto/ofproto-provider.h titled "Life Cycle").
1389  * This function implements steps 6 and 7.
1390  *
1391  * This function should only be called from an ofproto implementation's
1392  * ->destruct() function.  It is not suitable elsewhere. */
1393 void
1394 ofproto_rule_destroy(struct rule *rule)
1395 {
1396     assert(!rule->pending);
1397     classifier_remove(&rule->ofproto->tables[rule->table_id], &rule->cr);
1398     ofproto_rule_destroy__(rule);
1399 }
1400
1401 /* Returns true if 'rule' has an OpenFlow OFPAT_OUTPUT or OFPAT_ENQUEUE action
1402  * that outputs to 'out_port' (output to OFPP_FLOOD and OFPP_ALL doesn't
1403  * count). */
1404 static bool
1405 rule_has_out_port(const struct rule *rule, uint16_t out_port)
1406 {
1407     const union ofp_action *oa;
1408     size_t left;
1409
1410     if (out_port == OFPP_NONE) {
1411         return true;
1412     }
1413     OFPUTIL_ACTION_FOR_EACH_UNSAFE (oa, left, rule->actions, rule->n_actions) {
1414         if (action_outputs_to_port(oa, htons(out_port))) {
1415             return true;
1416         }
1417     }
1418     return false;
1419 }
1420
1421 /* Executes the actions indicated by 'rule' on 'packet' and credits 'rule''s
1422  * statistics appropriately.  'packet' must have at least sizeof(struct
1423  * ofp_packet_in) bytes of headroom.
1424  *
1425  * 'packet' doesn't necessarily have to match 'rule'.  'rule' will be credited
1426  * with statistics for 'packet' either way.
1427  *
1428  * Takes ownership of 'packet'. */
1429 static int
1430 rule_execute(struct rule *rule, uint16_t in_port, struct ofpbuf *packet)
1431 {
1432     struct flow flow;
1433
1434     assert(ofpbuf_headroom(packet) >= sizeof(struct ofp_packet_in));
1435
1436     flow_extract(packet, 0, in_port, &flow);
1437     return rule->ofproto->ofproto_class->rule_execute(rule, &flow, packet);
1438 }
1439
1440 /* Returns true if 'rule' should be hidden from the controller.
1441  *
1442  * Rules with priority higher than UINT16_MAX are set up by ofproto itself
1443  * (e.g. by in-band control) and are intentionally hidden from the
1444  * controller. */
1445 static bool
1446 rule_is_hidden(const struct rule *rule)
1447 {
1448     return rule->cr.priority > UINT16_MAX;
1449 }
1450 \f
1451 static int
1452 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
1453 {
1454     ofconn_send_reply(ofconn, make_echo_reply(oh));
1455     return 0;
1456 }
1457
1458 static int
1459 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
1460 {
1461     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1462     struct ofp_switch_features *osf;
1463     struct ofpbuf *buf;
1464     struct ofport *port;
1465     bool arp_match_ip;
1466     uint32_t actions;
1467
1468     ofproto->ofproto_class->get_features(ofproto, &arp_match_ip, &actions);
1469     assert(actions & (1 << OFPAT_OUTPUT)); /* sanity check */
1470
1471     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
1472     osf->datapath_id = htonll(ofproto->datapath_id);
1473     osf->n_buffers = htonl(pktbuf_capacity());
1474     osf->n_tables = ofproto->n_tables;
1475     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
1476                               OFPC_PORT_STATS);
1477     if (arp_match_ip) {
1478         osf->capabilities |= htonl(OFPC_ARP_MATCH_IP);
1479     }
1480     osf->actions = htonl(actions);
1481
1482     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
1483         ofpbuf_put(buf, &port->opp, sizeof port->opp);
1484     }
1485
1486     ofconn_send_reply(ofconn, buf);
1487     return 0;
1488 }
1489
1490 static int
1491 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
1492 {
1493     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1494     struct ofpbuf *buf;
1495     struct ofp_switch_config *osc;
1496     uint16_t flags;
1497     bool drop_frags;
1498
1499     /* Figure out flags. */
1500     drop_frags = ofproto->ofproto_class->get_drop_frags(ofproto);
1501     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
1502
1503     /* Send reply. */
1504     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1505     osc->flags = htons(flags);
1506     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
1507     ofconn_send_reply(ofconn, buf);
1508
1509     return 0;
1510 }
1511
1512 static int
1513 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
1514 {
1515     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1516     uint16_t flags = ntohs(osc->flags);
1517
1518     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
1519         && ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
1520         switch (flags & OFPC_FRAG_MASK) {
1521         case OFPC_FRAG_NORMAL:
1522             ofproto->ofproto_class->set_drop_frags(ofproto, false);
1523             break;
1524         case OFPC_FRAG_DROP:
1525             ofproto->ofproto_class->set_drop_frags(ofproto, true);
1526             break;
1527         default:
1528             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
1529                          osc->flags);
1530             break;
1531         }
1532     }
1533
1534     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
1535
1536     return 0;
1537 }
1538
1539 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
1540  * error message code (composed with ofp_mkerr()) for the caller to propagate
1541  * upward.  Otherwise, returns 0.
1542  *
1543  * The log message mentions 'msg_type'. */
1544 static int
1545 reject_slave_controller(struct ofconn *ofconn, const char *msg_type)
1546 {
1547     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
1548         && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
1549         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
1550         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
1551                      msg_type);
1552
1553         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
1554     } else {
1555         return 0;
1556     }
1557 }
1558
1559 static int
1560 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
1561 {
1562     struct ofproto *p = ofconn_get_ofproto(ofconn);
1563     struct ofp_packet_out *opo;
1564     struct ofpbuf payload, *buffer;
1565     union ofp_action *ofp_actions;
1566     struct ofpbuf request;
1567     struct flow flow;
1568     size_t n_ofp_actions;
1569     uint16_t in_port;
1570     int error;
1571
1572     COVERAGE_INC(ofproto_packet_out);
1573
1574     error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
1575     if (error) {
1576         return error;
1577     }
1578
1579     /* Get ofp_packet_out. */
1580     ofpbuf_use_const(&request, oh, ntohs(oh->length));
1581     opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
1582
1583     /* Get actions. */
1584     error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
1585                                  &ofp_actions, &n_ofp_actions);
1586     if (error) {
1587         return error;
1588     }
1589
1590     /* Get payload. */
1591     if (opo->buffer_id != htonl(UINT32_MAX)) {
1592         error = ofconn_pktbuf_retrieve(ofconn, ntohl(opo->buffer_id),
1593                                        &buffer, &in_port);
1594         if (error || !buffer) {
1595             return error;
1596         }
1597         payload = *buffer;
1598     } else {
1599         payload = request;
1600         buffer = NULL;
1601     }
1602
1603     /* Send out packet. */
1604     flow_extract(&payload, 0, ntohs(opo->in_port), &flow);
1605     error = p->ofproto_class->packet_out(p, &payload, &flow,
1606                                          ofp_actions, n_ofp_actions);
1607     ofpbuf_delete(buffer);
1608
1609     return error;
1610 }
1611
1612 static void
1613 update_port_config(struct ofport *port, ovs_be32 config, ovs_be32 mask)
1614 {
1615     ovs_be32 old_config = port->opp.config;
1616
1617     mask &= config ^ port->opp.config;
1618     if (mask & htonl(OFPPC_PORT_DOWN)) {
1619         if (config & htonl(OFPPC_PORT_DOWN)) {
1620             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
1621         } else {
1622             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
1623         }
1624     }
1625
1626     port->opp.config ^= mask & (htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
1627                                       OFPPC_NO_FLOOD | OFPPC_NO_FWD |
1628                                       OFPPC_NO_PACKET_IN));
1629     if (port->opp.config != old_config) {
1630         port->ofproto->ofproto_class->port_reconfigured(port, old_config);
1631     }
1632 }
1633
1634 static int
1635 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
1636 {
1637     struct ofproto *p = ofconn_get_ofproto(ofconn);
1638     const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
1639     struct ofport *port;
1640     int error;
1641
1642     error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
1643     if (error) {
1644         return error;
1645     }
1646
1647     port = ofproto_get_port(p, ntohs(opm->port_no));
1648     if (!port) {
1649         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
1650     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
1651         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
1652     } else {
1653         update_port_config(port, opm->config, opm->mask);
1654         if (opm->advertise) {
1655             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
1656         }
1657     }
1658     return 0;
1659 }
1660
1661 static int
1662 handle_desc_stats_request(struct ofconn *ofconn,
1663                           const struct ofp_stats_msg *request)
1664 {
1665     struct ofproto *p = ofconn_get_ofproto(ofconn);
1666     struct ofp_desc_stats *ods;
1667     struct ofpbuf *msg;
1668
1669     ods = ofputil_make_stats_reply(sizeof *ods, request, &msg);
1670     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
1671     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
1672     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
1673     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
1674     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
1675     ofconn_send_reply(ofconn, msg);
1676
1677     return 0;
1678 }
1679
1680 static int
1681 handle_table_stats_request(struct ofconn *ofconn,
1682                            const struct ofp_stats_msg *request)
1683 {
1684     struct ofproto *p = ofconn_get_ofproto(ofconn);
1685     struct ofp_table_stats *ots;
1686     struct ofpbuf *msg;
1687     size_t i;
1688
1689     ofputil_make_stats_reply(sizeof(struct ofp_stats_msg), request, &msg);
1690
1691     ots = ofpbuf_put_zeros(msg, sizeof *ots * p->n_tables);
1692     for (i = 0; i < p->n_tables; i++) {
1693         ots[i].table_id = i;
1694         sprintf(ots[i].name, "table%zu", i);
1695         ots[i].wildcards = htonl(OFPFW_ALL);
1696         ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
1697         ots[i].active_count = htonl(classifier_count(&p->tables[i]));
1698     }
1699
1700     p->ofproto_class->get_tables(p, ots);
1701
1702     ofconn_send_reply(ofconn, msg);
1703     return 0;
1704 }
1705
1706 static void
1707 append_port_stat(struct ofport *port, struct list *replies)
1708 {
1709     struct netdev_stats stats;
1710     struct ofp_port_stats *ops;
1711
1712     /* Intentionally ignore return value, since errors will set
1713      * 'stats' to all-1s, which is correct for OpenFlow, and
1714      * netdev_get_stats() will log errors. */
1715     netdev_get_stats(port->netdev, &stats);
1716
1717     ops = ofputil_append_stats_reply(sizeof *ops, replies);
1718     ops->port_no = port->opp.port_no;
1719     memset(ops->pad, 0, sizeof ops->pad);
1720     put_32aligned_be64(&ops->rx_packets, htonll(stats.rx_packets));
1721     put_32aligned_be64(&ops->tx_packets, htonll(stats.tx_packets));
1722     put_32aligned_be64(&ops->rx_bytes, htonll(stats.rx_bytes));
1723     put_32aligned_be64(&ops->tx_bytes, htonll(stats.tx_bytes));
1724     put_32aligned_be64(&ops->rx_dropped, htonll(stats.rx_dropped));
1725     put_32aligned_be64(&ops->tx_dropped, htonll(stats.tx_dropped));
1726     put_32aligned_be64(&ops->rx_errors, htonll(stats.rx_errors));
1727     put_32aligned_be64(&ops->tx_errors, htonll(stats.tx_errors));
1728     put_32aligned_be64(&ops->rx_frame_err, htonll(stats.rx_frame_errors));
1729     put_32aligned_be64(&ops->rx_over_err, htonll(stats.rx_over_errors));
1730     put_32aligned_be64(&ops->rx_crc_err, htonll(stats.rx_crc_errors));
1731     put_32aligned_be64(&ops->collisions, htonll(stats.collisions));
1732 }
1733
1734 static int
1735 handle_port_stats_request(struct ofconn *ofconn,
1736                           const struct ofp_port_stats_request *psr)
1737 {
1738     struct ofproto *p = ofconn_get_ofproto(ofconn);
1739     struct ofport *port;
1740     struct list replies;
1741
1742     ofputil_start_stats_reply(&psr->osm, &replies);
1743     if (psr->port_no != htons(OFPP_NONE)) {
1744         port = ofproto_get_port(p, ntohs(psr->port_no));
1745         if (port) {
1746             append_port_stat(port, &replies);
1747         }
1748     } else {
1749         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
1750             append_port_stat(port, &replies);
1751         }
1752     }
1753
1754     ofconn_send_replies(ofconn, &replies);
1755     return 0;
1756 }
1757
1758 static void
1759 calc_flow_duration__(long long int start, uint32_t *sec, uint32_t *nsec)
1760 {
1761     long long int msecs = time_msec() - start;
1762     *sec = msecs / 1000;
1763     *nsec = (msecs % 1000) * (1000 * 1000);
1764 }
1765
1766 static struct classifier *
1767 first_matching_table(struct ofproto *ofproto, uint8_t table_id)
1768 {
1769     if (table_id == 0xff) {
1770         return &ofproto->tables[0];
1771     } else if (table_id < ofproto->n_tables) {
1772         return &ofproto->tables[table_id];
1773     } else {
1774         /* It would probably be better to reply with an error but there doesn't
1775          * seem to be any appropriate value, so that might just be
1776          * confusing. */
1777         VLOG_WARN_RL(&rl, "controller asked for invalid table %"PRIu8,
1778                      table_id);
1779         return NULL;
1780     }
1781 }
1782
1783 static struct classifier *
1784 next_matching_table(struct ofproto *ofproto,
1785                     struct classifier *cls, uint8_t table_id)
1786 {
1787     return (table_id == 0xff && cls != &ofproto->tables[ofproto->n_tables - 1]
1788             ? cls + 1
1789             : NULL);
1790 }
1791
1792 /* Assigns CLS to each classifier table, in turn, that matches TABLE_ID in
1793  * OFPROTO:
1794  *
1795  *   - If TABLE_ID is 0xff, this iterates over every classifier table in
1796  *     OFPROTO.
1797  *
1798  *   - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
1799  *     only once, for that table.
1800  *
1801  *   - Otherwise, TABLE_ID isn't valid for OFPROTO, so ofproto logs a warning
1802  *     and does not enter the loop at all.
1803  *
1804  * All parameters are evaluated multiple times.
1805  */
1806 #define FOR_EACH_MATCHING_TABLE(CLS, TABLE_ID, OFPROTO)         \
1807     for ((CLS) = first_matching_table(OFPROTO, TABLE_ID);       \
1808          (CLS) != NULL;                                         \
1809          (CLS) = next_matching_table(OFPROTO, CLS, TABLE_ID))
1810
1811 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
1812  * 'table_id' is 0xff) that match 'match' in the "loose" way required for
1813  * OpenFlow OFPFC_MODIFY and OFPFC_DELETE requests and puts them on list
1814  * 'rules'.
1815  *
1816  * If 'out_port' is anything other than OFPP_NONE, then only rules that output
1817  * to 'out_port' are included.
1818  *
1819  * Hidden rules are always omitted.
1820  *
1821  * Returns 0 on success, otherwise an OpenFlow error code. */
1822 static int
1823 collect_rules_loose(struct ofproto *ofproto, uint8_t table_id,
1824                     const struct cls_rule *match, uint16_t out_port,
1825                     struct list *rules)
1826 {
1827     struct classifier *cls;
1828
1829     list_init(rules);
1830     FOR_EACH_MATCHING_TABLE (cls, table_id, ofproto) {
1831         struct cls_cursor cursor;
1832         struct rule *rule;
1833
1834         cls_cursor_init(&cursor, cls, match);
1835         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1836             if (rule->pending) {
1837                 return OFPROTO_POSTPONE;
1838             }
1839             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
1840                 list_push_back(rules, &rule->ofproto_node);
1841             }
1842         }
1843     }
1844     return 0;
1845 }
1846
1847 /* Searches 'ofproto' for rules in table 'table_id' (or in all tables, if
1848  * 'table_id' is 0xff) that match 'match' in the "strict" way required for
1849  * OpenFlow OFPFC_MODIFY_STRICT and OFPFC_DELETE_STRICT requests and puts them
1850  * on list 'rules'.
1851  *
1852  * If 'out_port' is anything other than OFPP_NONE, then only rules that output
1853  * to 'out_port' are included.
1854  *
1855  * Hidden rules are always omitted.
1856  *
1857  * Returns 0 on success, otherwise an OpenFlow error code. */
1858 static int
1859 collect_rules_strict(struct ofproto *ofproto, uint8_t table_id,
1860                      const struct cls_rule *match, uint16_t out_port,
1861                      struct list *rules)
1862 {
1863     struct classifier *cls;
1864
1865     list_init(rules);
1866     FOR_EACH_MATCHING_TABLE (cls, table_id, ofproto) {
1867         struct rule *rule;
1868
1869         rule = rule_from_cls_rule(classifier_find_rule_exactly(cls, match));
1870         if (rule) {
1871             if (rule->pending) {
1872                 return OFPROTO_POSTPONE;
1873             }
1874             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
1875                 list_push_back(rules, &rule->ofproto_node);
1876             }
1877         }
1878     }
1879     return 0;
1880 }
1881
1882 static int
1883 handle_flow_stats_request(struct ofconn *ofconn,
1884                           const struct ofp_stats_msg *osm)
1885 {
1886     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1887     struct flow_stats_request fsr;
1888     struct list replies;
1889     struct list rules;
1890     struct rule *rule;
1891     int error;
1892
1893     error = ofputil_decode_flow_stats_request(&fsr, &osm->header);
1894     if (error) {
1895         return error;
1896     }
1897
1898     error = collect_rules_loose(ofproto, fsr.table_id, &fsr.match,
1899                                 fsr.out_port, &rules);
1900     if (error) {
1901         return error;
1902     }
1903
1904     ofputil_start_stats_reply(osm, &replies);
1905     LIST_FOR_EACH (rule, ofproto_node, &rules) {
1906         struct ofputil_flow_stats fs;
1907
1908         fs.rule = rule->cr;
1909         fs.cookie = rule->flow_cookie;
1910         fs.table_id = rule->table_id;
1911         calc_flow_duration__(rule->created, &fs.duration_sec,
1912                              &fs.duration_nsec);
1913         fs.idle_timeout = rule->idle_timeout;
1914         fs.hard_timeout = rule->hard_timeout;
1915         ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
1916                                                &fs.byte_count);
1917         fs.actions = rule->actions;
1918         fs.n_actions = rule->n_actions;
1919         ofputil_append_flow_stats_reply(&fs, &replies);
1920     }
1921     ofconn_send_replies(ofconn, &replies);
1922
1923     return 0;
1924 }
1925
1926 static void
1927 flow_stats_ds(struct rule *rule, struct ds *results)
1928 {
1929     uint64_t packet_count, byte_count;
1930
1931     rule->ofproto->ofproto_class->rule_get_stats(rule,
1932                                                  &packet_count, &byte_count);
1933
1934     if (rule->table_id != 0) {
1935         ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
1936     }
1937     ds_put_format(results, "duration=%llds, ",
1938                   (time_msec() - rule->created) / 1000);
1939     ds_put_format(results, "priority=%u, ", rule->cr.priority);
1940     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
1941     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
1942     cls_rule_format(&rule->cr, results);
1943     ds_put_char(results, ',');
1944     if (rule->n_actions > 0) {
1945         ofp_print_actions(results, rule->actions, rule->n_actions);
1946     } else {
1947         ds_put_cstr(results, "drop");
1948     }
1949     ds_put_cstr(results, "\n");
1950 }
1951
1952 /* Adds a pretty-printed description of all flows to 'results', including
1953  * hidden flows (e.g., set up by in-band control). */
1954 void
1955 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
1956 {
1957     struct classifier *cls;
1958
1959     for (cls = &p->tables[0]; cls < &p->tables[p->n_tables]; cls++) {
1960         struct cls_cursor cursor;
1961         struct rule *rule;
1962
1963         cls_cursor_init(&cursor, cls, NULL);
1964         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1965             flow_stats_ds(rule, results);
1966         }
1967     }
1968 }
1969
1970 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
1971  * '*engine_type' and '*engine_id', respectively. */
1972 void
1973 ofproto_get_netflow_ids(const struct ofproto *ofproto,
1974                         uint8_t *engine_type, uint8_t *engine_id)
1975 {
1976     ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
1977 }
1978
1979 /* Checks the fault status of CFM for 'ofp_port' within 'ofproto'.  Returns 1
1980  * if CFM is faulted (generally indiciating a connectivity problem), 0 if CFM
1981  * is not faulted, and -1 if CFM is not enabled on 'ofp_port'. */
1982 int
1983 ofproto_port_get_cfm_fault(const struct ofproto *ofproto, uint16_t ofp_port)
1984 {
1985     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1986     return (ofport && ofproto->ofproto_class->get_cfm_fault
1987             ? ofproto->ofproto_class->get_cfm_fault(ofport)
1988             : -1);
1989 }
1990
1991 static int
1992 handle_aggregate_stats_request(struct ofconn *ofconn,
1993                                const struct ofp_stats_msg *osm)
1994 {
1995     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1996     struct flow_stats_request request;
1997     struct ofputil_aggregate_stats stats;
1998     bool unknown_packets, unknown_bytes;
1999     struct ofpbuf *reply;
2000     struct list rules;
2001     struct rule *rule;
2002     int error;
2003
2004     error = ofputil_decode_flow_stats_request(&request, &osm->header);
2005     if (error) {
2006         return error;
2007     }
2008
2009     error = collect_rules_loose(ofproto, request.table_id, &request.match,
2010                                 request.out_port, &rules);
2011     if (error) {
2012         return error;
2013     }
2014
2015     memset(&stats, 0, sizeof stats);
2016     unknown_packets = unknown_bytes = false;
2017     LIST_FOR_EACH (rule, ofproto_node, &rules) {
2018         uint64_t packet_count;
2019         uint64_t byte_count;
2020
2021         ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
2022                                                &byte_count);
2023
2024         if (packet_count == UINT64_MAX) {
2025             unknown_packets = true;
2026         } else {
2027             stats.packet_count += packet_count;
2028         }
2029
2030         if (byte_count == UINT64_MAX) {
2031             unknown_bytes = true;
2032         } else {
2033             stats.byte_count += byte_count;
2034         }
2035
2036         stats.flow_count++;
2037     }
2038     if (unknown_packets) {
2039         stats.packet_count = UINT64_MAX;
2040     }
2041     if (unknown_bytes) {
2042         stats.byte_count = UINT64_MAX;
2043     }
2044
2045     reply = ofputil_encode_aggregate_stats_reply(&stats, osm);
2046     ofconn_send_reply(ofconn, reply);
2047
2048     return 0;
2049 }
2050
2051 struct queue_stats_cbdata {
2052     struct ofport *ofport;
2053     struct list replies;
2054 };
2055
2056 static void
2057 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
2058                 const struct netdev_queue_stats *stats)
2059 {
2060     struct ofp_queue_stats *reply;
2061
2062     reply = ofputil_append_stats_reply(sizeof *reply, &cbdata->replies);
2063     reply->port_no = cbdata->ofport->opp.port_no;
2064     memset(reply->pad, 0, sizeof reply->pad);
2065     reply->queue_id = htonl(queue_id);
2066     put_32aligned_be64(&reply->tx_bytes, htonll(stats->tx_bytes));
2067     put_32aligned_be64(&reply->tx_packets, htonll(stats->tx_packets));
2068     put_32aligned_be64(&reply->tx_errors, htonll(stats->tx_errors));
2069 }
2070
2071 static void
2072 handle_queue_stats_dump_cb(uint32_t queue_id,
2073                            struct netdev_queue_stats *stats,
2074                            void *cbdata_)
2075 {
2076     struct queue_stats_cbdata *cbdata = cbdata_;
2077
2078     put_queue_stats(cbdata, queue_id, stats);
2079 }
2080
2081 static void
2082 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
2083                             struct queue_stats_cbdata *cbdata)
2084 {
2085     cbdata->ofport = port;
2086     if (queue_id == OFPQ_ALL) {
2087         netdev_dump_queue_stats(port->netdev,
2088                                 handle_queue_stats_dump_cb, cbdata);
2089     } else {
2090         struct netdev_queue_stats stats;
2091
2092         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
2093             put_queue_stats(cbdata, queue_id, &stats);
2094         }
2095     }
2096 }
2097
2098 static int
2099 handle_queue_stats_request(struct ofconn *ofconn,
2100                            const struct ofp_queue_stats_request *qsr)
2101 {
2102     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2103     struct queue_stats_cbdata cbdata;
2104     struct ofport *port;
2105     unsigned int port_no;
2106     uint32_t queue_id;
2107
2108     COVERAGE_INC(ofproto_queue_req);
2109
2110     ofputil_start_stats_reply(&qsr->osm, &cbdata.replies);
2111
2112     port_no = ntohs(qsr->port_no);
2113     queue_id = ntohl(qsr->queue_id);
2114     if (port_no == OFPP_ALL) {
2115         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
2116             handle_queue_stats_for_port(port, queue_id, &cbdata);
2117         }
2118     } else if (port_no < OFPP_MAX) {
2119         port = ofproto_get_port(ofproto, port_no);
2120         if (port) {
2121             handle_queue_stats_for_port(port, queue_id, &cbdata);
2122         }
2123     } else {
2124         ofpbuf_list_delete(&cbdata.replies);
2125         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
2126     }
2127     ofconn_send_replies(ofconn, &cbdata.replies);
2128
2129     return 0;
2130 }
2131
2132 static bool
2133 is_flow_deletion_pending(const struct ofproto *ofproto,
2134                          const struct cls_rule *cls_rule,
2135                          uint8_t table_id)
2136 {
2137     if (!hmap_is_empty(&ofproto->deletions)) {
2138         struct ofoperation *op;
2139
2140         HMAP_FOR_EACH_WITH_HASH (op, hmap_node,
2141                                  cls_rule_hash(cls_rule, table_id),
2142                                  &ofproto->deletions) {
2143             if (cls_rule_equal(cls_rule, &op->rule->cr)) {
2144                 return true;
2145             }
2146         }
2147     }
2148
2149     return false;
2150 }
2151
2152 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
2153  * in which no matching flow already exists in the flow table.
2154  *
2155  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
2156  * ofp_actions, to the ofproto's flow table.  Returns 0 on success or an
2157  * OpenFlow error code as encoded by ofp_mkerr() on failure.
2158  *
2159  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2160  * if any. */
2161 static int
2162 add_flow(struct ofproto *ofproto, struct ofconn *ofconn, struct flow_mod *fm,
2163          const struct ofp_header *request)
2164 {
2165     struct classifier *table;
2166     struct ofopgroup *group;
2167     struct rule *victim;
2168     struct rule *rule;
2169     int error;
2170
2171     /* Check for overlap, if requested. */
2172     if (fm->flags & OFPFF_CHECK_OVERLAP) {
2173         struct classifier *cls;
2174
2175         FOR_EACH_MATCHING_TABLE (cls, fm->table_id, ofproto) {
2176             if (classifier_rule_overlaps(cls, &fm->cr)) {
2177                 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
2178             }
2179         }
2180     }
2181
2182     /* Pick table. */
2183     if (fm->table_id == 0xff) {
2184         uint8_t table_id;
2185         if (ofproto->n_tables > 1) {
2186             error = ofproto->ofproto_class->rule_choose_table(ofproto, &fm->cr,
2187                                                               &table_id);
2188             if (error) {
2189                 return error;
2190             }
2191             assert(table_id < ofproto->n_tables);
2192             table = &ofproto->tables[table_id];
2193         } else {
2194             table = &ofproto->tables[0];
2195         }
2196     } else if (fm->table_id < ofproto->n_tables) {
2197         table = &ofproto->tables[fm->table_id];
2198     } else {
2199         return ofp_mkerr_nicira(OFPET_FLOW_MOD_FAILED, NXFMFC_BAD_TABLE_ID);
2200     }
2201
2202     /* Serialize against pending deletion. */
2203     if (is_flow_deletion_pending(ofproto, &fm->cr, table - ofproto->tables)) {
2204         return OFPROTO_POSTPONE;
2205     }
2206
2207     /* Allocate new rule. */
2208     rule = ofproto->ofproto_class->rule_alloc();
2209     if (!rule) {
2210         VLOG_WARN_RL(&rl, "%s: failed to create rule (%s)",
2211                      ofproto->name, strerror(error));
2212         return ENOMEM;
2213     }
2214     rule->ofproto = ofproto;
2215     rule->cr = fm->cr;
2216     rule->pending = NULL;
2217     rule->flow_cookie = fm->cookie;
2218     rule->created = time_msec();
2219     rule->idle_timeout = fm->idle_timeout;
2220     rule->hard_timeout = fm->hard_timeout;
2221     rule->table_id = table - ofproto->tables;
2222     rule->send_flow_removed = (fm->flags & OFPFF_SEND_FLOW_REM) != 0;
2223     rule->actions = ofputil_actions_clone(fm->actions, fm->n_actions);
2224     rule->n_actions = fm->n_actions;
2225
2226     /* Insert new rule. */
2227     victim = rule_from_cls_rule(classifier_replace(table, &rule->cr));
2228     if (victim && victim->pending) {
2229         error = OFPROTO_POSTPONE;
2230     } else {
2231         group = (ofconn
2232                  ? ofopgroup_create_for_ofconn(ofconn, request, fm->buffer_id)
2233                  : ofopgroup_create(ofproto));
2234         ofoperation_create(group, rule, OFOPERATION_ADD);
2235         rule->pending->victim = victim;
2236
2237         error = ofproto->ofproto_class->rule_construct(rule);
2238         if (error) {
2239             ofoperation_destroy(rule->pending);
2240         }
2241         ofopgroup_submit(group);
2242     }
2243
2244     /* Back out if an error occurred. */
2245     if (error) {
2246         if (victim) {
2247             classifier_replace(table, &victim->cr);
2248         } else {
2249             classifier_remove(table, &rule->cr);
2250         }
2251         ofproto_rule_destroy__(rule);
2252     }
2253     return error;
2254 }
2255 \f
2256 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
2257
2258 /* Modifies the rules listed in 'rules', changing their actions to match those
2259  * in 'fm'.
2260  *
2261  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2262  * if any.
2263  *
2264  * Returns 0 on success, otherwise an OpenFlow error code. */
2265 static int
2266 modify_flows__(struct ofconn *ofconn, const struct flow_mod *fm,
2267                const struct ofp_header *request, struct list *rules)
2268 {
2269     struct ofopgroup *group;
2270     struct rule *rule;
2271
2272     group = ofopgroup_create_for_ofconn(ofconn, request, fm->buffer_id);
2273     LIST_FOR_EACH (rule, ofproto_node, rules) {
2274         if (!ofputil_actions_equal(fm->actions, fm->n_actions,
2275                                    rule->actions, rule->n_actions)) {
2276             ofoperation_create(group, rule, OFOPERATION_MODIFY);
2277             rule->pending->actions = rule->actions;
2278             rule->pending->n_actions = rule->n_actions;
2279             rule->actions = ofputil_actions_clone(fm->actions, fm->n_actions);
2280             rule->n_actions = fm->n_actions;
2281             rule->ofproto->ofproto_class->rule_modify_actions(rule);
2282         }
2283         rule->flow_cookie = fm->cookie;
2284     }
2285     ofopgroup_submit(group);
2286
2287     return 0;
2288 }
2289
2290 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
2291  * encoded by ofp_mkerr() on failure.
2292  *
2293  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2294  * if any. */
2295 static int
2296 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm,
2297                    const struct ofp_header *request)
2298 {
2299     struct ofproto *p = ofconn_get_ofproto(ofconn);
2300     struct list rules;
2301     int error;
2302
2303     error = collect_rules_loose(p, fm->table_id, &fm->cr, OFPP_NONE, &rules);
2304     return (error ? error
2305             : list_is_empty(&rules) ? add_flow(p, ofconn, fm, request)
2306             : modify_flows__(ofconn, fm, request, &rules));
2307 }
2308
2309 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
2310  * code as encoded by ofp_mkerr() on failure.
2311  *
2312  * 'ofconn' is used to retrieve the packet buffer specified in fm->buffer_id,
2313  * if any. */
2314 static int
2315 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm,
2316                    const struct ofp_header *request)
2317 {
2318     struct ofproto *p = ofconn_get_ofproto(ofconn);
2319     struct list rules;
2320     int error;
2321
2322     error = collect_rules_strict(p, fm->table_id, &fm->cr, OFPP_NONE, &rules);
2323     return (error ? error
2324             : list_is_empty(&rules) ? add_flow(p, ofconn, fm, request)
2325             : list_is_singleton(&rules) ? modify_flows__(ofconn, fm, request,
2326                                                          &rules)
2327             : 0);
2328 }
2329 \f
2330 /* OFPFC_DELETE implementation. */
2331
2332 /* Deletes the rules listed in 'rules'.
2333  *
2334  * Returns 0 on success, otherwise an OpenFlow error code. */
2335 static int
2336 delete_flows__(struct ofconn *ofconn, const struct ofp_header *request,
2337                struct list *rules)
2338 {
2339     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2340     struct rule *rule, *next;
2341     struct ofopgroup *group;
2342
2343     group = ofopgroup_create_for_ofconn(ofconn, request, UINT32_MAX);
2344     LIST_FOR_EACH_SAFE (rule, next, ofproto_node, rules) {
2345         ofproto_rule_send_removed(rule, OFPRR_DELETE);
2346
2347         ofoperation_create(group, rule, OFOPERATION_DELETE);
2348         classifier_remove(&ofproto->tables[rule->table_id], &rule->cr);
2349         rule->ofproto->ofproto_class->rule_destruct(rule);
2350     }
2351     ofopgroup_submit(group);
2352
2353     return 0;
2354 }
2355
2356 /* Implements OFPFC_DELETE. */
2357 static int
2358 delete_flows_loose(struct ofconn *ofconn, const struct flow_mod *fm,
2359                    const struct ofp_header *request)
2360 {
2361     struct ofproto *p = ofconn_get_ofproto(ofconn);
2362     struct list rules;
2363     int error;
2364
2365     error = collect_rules_loose(p, fm->table_id, &fm->cr, fm->out_port,
2366                                 &rules);
2367     return (error ? error
2368             : !list_is_empty(&rules) ? delete_flows__(ofconn, request, &rules)
2369             : 0);
2370 }
2371
2372 /* Implements OFPFC_DELETE_STRICT. */
2373 static int
2374 delete_flow_strict(struct ofconn *ofconn, struct flow_mod *fm,
2375                    const struct ofp_header *request)
2376 {
2377     struct ofproto *p = ofconn_get_ofproto(ofconn);
2378     struct list rules;
2379     int error;
2380
2381     error = collect_rules_strict(p, fm->table_id, &fm->cr, fm->out_port,
2382                                  &rules);
2383     return (error ? error
2384             : list_is_singleton(&rules) ? delete_flows__(ofconn, request,
2385                                                          &rules)
2386             : 0);
2387 }
2388
2389 static void
2390 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
2391 {
2392     struct ofputil_flow_removed fr;
2393
2394     if (rule_is_hidden(rule) || !rule->send_flow_removed) {
2395         return;
2396     }
2397
2398     fr.rule = rule->cr;
2399     fr.cookie = rule->flow_cookie;
2400     fr.reason = reason;
2401     calc_flow_duration__(rule->created, &fr.duration_sec, &fr.duration_nsec);
2402     fr.idle_timeout = rule->idle_timeout;
2403     rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
2404                                                  &fr.byte_count);
2405
2406     connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
2407 }
2408
2409 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
2410  * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
2411  * ofproto.
2412  *
2413  * ofproto implementation ->run() functions should use this function to expire
2414  * OpenFlow flows. */
2415 void
2416 ofproto_rule_expire(struct rule *rule, uint8_t reason)
2417 {
2418     struct ofproto *ofproto = rule->ofproto;
2419     struct ofopgroup *group;
2420
2421     assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
2422
2423     ofproto_rule_send_removed(rule, reason);
2424
2425     group = ofopgroup_create(ofproto);
2426     ofoperation_create(group, rule, OFOPERATION_DELETE);
2427     classifier_remove(&ofproto->tables[rule->table_id], &rule->cr);
2428     rule->ofproto->ofproto_class->rule_destruct(rule);
2429     ofopgroup_submit(group);
2430 }
2431 \f
2432 static int
2433 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2434 {
2435     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
2436     struct flow_mod fm;
2437     int error;
2438
2439     error = reject_slave_controller(ofconn, "flow_mod");
2440     if (error) {
2441         return error;
2442     }
2443
2444     if (list_size(&ofproto->pending) >= 50) {
2445         return OFPROTO_POSTPONE;
2446     }
2447
2448     error = ofputil_decode_flow_mod(&fm, oh,
2449                                     ofconn_get_flow_mod_table_id(ofconn));
2450     if (error) {
2451         return error;
2452     }
2453
2454     /* We do not support the emergency flow cache.  It will hopefully get
2455      * dropped from OpenFlow in the near future. */
2456     if (fm.flags & OFPFF_EMERG) {
2457         /* There isn't a good fit for an error code, so just state that the
2458          * flow table is full. */
2459         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
2460     }
2461
2462     switch (fm.command) {
2463     case OFPFC_ADD:
2464         return add_flow(ofproto, ofconn, &fm, oh);
2465
2466     case OFPFC_MODIFY:
2467         return modify_flows_loose(ofconn, &fm, oh);
2468
2469     case OFPFC_MODIFY_STRICT:
2470         return modify_flow_strict(ofconn, &fm, oh);
2471
2472     case OFPFC_DELETE:
2473         return delete_flows_loose(ofconn, &fm, oh);
2474
2475     case OFPFC_DELETE_STRICT:
2476         return delete_flow_strict(ofconn, &fm, oh);
2477
2478     default:
2479         if (fm.command > 0xff) {
2480             VLOG_WARN_RL(&rl, "flow_mod has explicit table_id but "
2481                          "flow_mod_table_id extension is not enabled");
2482         }
2483         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
2484     }
2485 }
2486
2487 static int
2488 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
2489 {
2490     struct nx_role_request *nrr = (struct nx_role_request *) oh;
2491     struct nx_role_request *reply;
2492     struct ofpbuf *buf;
2493     uint32_t role;
2494
2495     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY) {
2496         VLOG_WARN_RL(&rl, "ignoring role request on service connection");
2497         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2498     }
2499
2500     role = ntohl(nrr->role);
2501     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
2502         && role != NX_ROLE_SLAVE) {
2503         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
2504
2505         /* There's no good error code for this. */
2506         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
2507     }
2508
2509     if (ofconn_get_role(ofconn) != role
2510         && ofconn_has_pending_opgroups(ofconn)) {
2511         return OFPROTO_POSTPONE;
2512     }
2513
2514     ofconn_set_role(ofconn, role);
2515
2516     reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
2517     reply->role = htonl(role);
2518     ofconn_send_reply(ofconn, buf);
2519
2520     return 0;
2521 }
2522
2523 static int
2524 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
2525                              const struct ofp_header *oh)
2526 {
2527     const struct nxt_flow_mod_table_id *msg
2528         = (const struct nxt_flow_mod_table_id *) oh;
2529
2530     ofconn_set_flow_mod_table_id(ofconn, msg->set != 0);
2531     return 0;
2532 }
2533
2534 static int
2535 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
2536 {
2537     const struct nxt_set_flow_format *msg
2538         = (const struct nxt_set_flow_format *) oh;
2539     uint32_t format;
2540
2541     format = ntohl(msg->format);
2542     if (format != NXFF_OPENFLOW10 && format != NXFF_NXM) {
2543         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2544     }
2545
2546     if (format != ofconn_get_flow_format(ofconn)
2547         && ofconn_has_pending_opgroups(ofconn)) {
2548         /* Avoid sending async messages in surprising flow format. */
2549         return OFPROTO_POSTPONE;
2550     }
2551
2552     ofconn_set_flow_format(ofconn, format);
2553     return 0;
2554 }
2555
2556 static int
2557 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
2558 {
2559     struct ofp_header *ob;
2560     struct ofpbuf *buf;
2561
2562     if (ofconn_has_pending_opgroups(ofconn)) {
2563         return OFPROTO_POSTPONE;
2564     }
2565
2566     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
2567     ofconn_send_reply(ofconn, buf);
2568     return 0;
2569 }
2570
2571 static int
2572 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
2573 {
2574     const struct ofp_header *oh = msg->data;
2575     const struct ofputil_msg_type *type;
2576     int error;
2577
2578     error = ofputil_decode_msg_type(oh, &type);
2579     if (error) {
2580         return error;
2581     }
2582
2583     switch (ofputil_msg_type_code(type)) {
2584         /* OpenFlow requests. */
2585     case OFPUTIL_OFPT_ECHO_REQUEST:
2586         return handle_echo_request(ofconn, oh);
2587
2588     case OFPUTIL_OFPT_FEATURES_REQUEST:
2589         return handle_features_request(ofconn, oh);
2590
2591     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
2592         return handle_get_config_request(ofconn, oh);
2593
2594     case OFPUTIL_OFPT_SET_CONFIG:
2595         return handle_set_config(ofconn, msg->data);
2596
2597     case OFPUTIL_OFPT_PACKET_OUT:
2598         return handle_packet_out(ofconn, oh);
2599
2600     case OFPUTIL_OFPT_PORT_MOD:
2601         return handle_port_mod(ofconn, oh);
2602
2603     case OFPUTIL_OFPT_FLOW_MOD:
2604         return handle_flow_mod(ofconn, oh);
2605
2606     case OFPUTIL_OFPT_BARRIER_REQUEST:
2607         return handle_barrier_request(ofconn, oh);
2608
2609         /* OpenFlow replies. */
2610     case OFPUTIL_OFPT_ECHO_REPLY:
2611         return 0;
2612
2613         /* Nicira extension requests. */
2614     case OFPUTIL_NXT_ROLE_REQUEST:
2615         return handle_role_request(ofconn, oh);
2616
2617     case OFPUTIL_NXT_FLOW_MOD_TABLE_ID:
2618         return handle_nxt_flow_mod_table_id(ofconn, oh);
2619
2620     case OFPUTIL_NXT_SET_FLOW_FORMAT:
2621         return handle_nxt_set_flow_format(ofconn, oh);
2622
2623     case OFPUTIL_NXT_FLOW_MOD:
2624         return handle_flow_mod(ofconn, oh);
2625
2626         /* Statistics requests. */
2627     case OFPUTIL_OFPST_DESC_REQUEST:
2628         return handle_desc_stats_request(ofconn, msg->data);
2629
2630     case OFPUTIL_OFPST_FLOW_REQUEST:
2631     case OFPUTIL_NXST_FLOW_REQUEST:
2632         return handle_flow_stats_request(ofconn, msg->data);
2633
2634     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
2635     case OFPUTIL_NXST_AGGREGATE_REQUEST:
2636         return handle_aggregate_stats_request(ofconn, msg->data);
2637
2638     case OFPUTIL_OFPST_TABLE_REQUEST:
2639         return handle_table_stats_request(ofconn, msg->data);
2640
2641     case OFPUTIL_OFPST_PORT_REQUEST:
2642         return handle_port_stats_request(ofconn, msg->data);
2643
2644     case OFPUTIL_OFPST_QUEUE_REQUEST:
2645         return handle_queue_stats_request(ofconn, msg->data);
2646
2647     case OFPUTIL_MSG_INVALID:
2648     case OFPUTIL_OFPT_HELLO:
2649     case OFPUTIL_OFPT_ERROR:
2650     case OFPUTIL_OFPT_FEATURES_REPLY:
2651     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
2652     case OFPUTIL_OFPT_PACKET_IN:
2653     case OFPUTIL_OFPT_FLOW_REMOVED:
2654     case OFPUTIL_OFPT_PORT_STATUS:
2655     case OFPUTIL_OFPT_BARRIER_REPLY:
2656     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
2657     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
2658     case OFPUTIL_OFPST_DESC_REPLY:
2659     case OFPUTIL_OFPST_FLOW_REPLY:
2660     case OFPUTIL_OFPST_QUEUE_REPLY:
2661     case OFPUTIL_OFPST_PORT_REPLY:
2662     case OFPUTIL_OFPST_TABLE_REPLY:
2663     case OFPUTIL_OFPST_AGGREGATE_REPLY:
2664     case OFPUTIL_NXT_ROLE_REPLY:
2665     case OFPUTIL_NXT_FLOW_REMOVED:
2666     case OFPUTIL_NXST_FLOW_REPLY:
2667     case OFPUTIL_NXST_AGGREGATE_REPLY:
2668     default:
2669         if (VLOG_IS_WARN_ENABLED()) {
2670             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
2671             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
2672             free(s);
2673         }
2674         if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
2675             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
2676         } else {
2677             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
2678         }
2679     }
2680 }
2681
2682 static bool
2683 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
2684 {
2685     int error = handle_openflow__(ofconn, ofp_msg);
2686     if (error && error != OFPROTO_POSTPONE) {
2687         ofconn_send_error(ofconn, ofp_msg->data, error);
2688     }
2689     COVERAGE_INC(ofproto_recv_openflow);
2690     return error != OFPROTO_POSTPONE;
2691 }
2692 \f
2693 /* Asynchronous operations. */
2694
2695 /* Creates and returns a new ofopgroup that is not associated with any
2696  * OpenFlow connection.
2697  *
2698  * The caller should add operations to the returned group with
2699  * ofoperation_create() and then submit it with ofopgroup_submit(). */
2700 static struct ofopgroup *
2701 ofopgroup_create(struct ofproto *ofproto)
2702 {
2703     struct ofopgroup *group = xzalloc(sizeof *group);
2704     group->ofproto = ofproto;
2705     list_init(&group->ofproto_node);
2706     list_init(&group->ops);
2707     list_init(&group->ofconn_node);
2708     return group;
2709 }
2710
2711 /* Creates and returns a new ofopgroup that is associated with 'ofconn'.  If
2712  * the ofopgroup eventually fails, then the error reply will include 'request'.
2713  * If the ofopgroup eventually succeeds, then the packet with buffer id
2714  * 'buffer_id' on 'ofconn' will be sent by 'ofconn''s ofproto.
2715  *
2716  * The caller should add operations to the returned group with
2717  * ofoperation_create() and then submit it with ofopgroup_submit(). */
2718 static struct ofopgroup *
2719 ofopgroup_create_for_ofconn(struct ofconn *ofconn,
2720                             const struct ofp_header *request,
2721                             uint32_t buffer_id)
2722 {
2723     struct ofopgroup *group = ofopgroup_create(ofconn_get_ofproto(ofconn));
2724     size_t request_len = ntohs(request->length);
2725
2726     ofconn_add_opgroup(ofconn, &group->ofconn_node);
2727     group->ofconn = ofconn;
2728     group->request = xmemdup(request, MIN(request_len, 64));
2729     group->buffer_id = buffer_id;
2730
2731     return group;
2732 }
2733
2734 /* Submits 'group' for processing.
2735  *
2736  * If 'group' contains no operations (e.g. none were ever added, or all of the
2737  * ones that were added completed synchronously), then it is destroyed
2738  * immediately.  Otherwise it is added to the ofproto's list of pending
2739  * groups. */
2740 static void
2741 ofopgroup_submit(struct ofopgroup *group)
2742 {
2743     if (list_is_empty(&group->ops)) {
2744         ofopgroup_destroy(group);
2745     } else {
2746         list_push_back(&group->ofproto->pending, &group->ofproto_node);
2747     }
2748 }
2749
2750 static void
2751 ofopgroup_destroy(struct ofopgroup *group)
2752 {
2753     assert(list_is_empty(&group->ops));
2754     if (!list_is_empty(&group->ofproto_node)) {
2755         list_remove(&group->ofproto_node);
2756     }
2757     if (!list_is_empty(&group->ofconn_node)) {
2758         list_remove(&group->ofconn_node);
2759         if (group->error) {
2760             ofconn_send_error(group->ofconn, group->request, group->error);
2761         }
2762         connmgr_retry(group->ofproto->connmgr);
2763     }
2764     free(group->request);
2765     free(group);
2766 }
2767
2768 /* Initiates a new operation on 'rule', of the specified 'type', within
2769  * 'group'.  Prior to calling, 'rule' must not have any pending operation. */
2770 static void
2771 ofoperation_create(struct ofopgroup *group, struct rule *rule,
2772                    enum ofoperation_type type)
2773 {
2774     struct ofoperation *op;
2775
2776     assert(!rule->pending);
2777
2778     op = rule->pending = xzalloc(sizeof *op);
2779     op->group = group;
2780     list_push_back(&group->ops, &op->group_node);
2781     op->rule = rule;
2782     op->type = type;
2783     op->status = -1;
2784     op->flow_cookie = rule->flow_cookie;
2785
2786     if (type == OFOPERATION_DELETE) {
2787         hmap_insert(&op->group->ofproto->deletions, &op->hmap_node,
2788                     cls_rule_hash(&rule->cr, rule->table_id));
2789     }
2790 }
2791
2792 static void
2793 ofoperation_destroy(struct ofoperation *op)
2794 {
2795     struct ofopgroup *group = op->group;
2796
2797     if (op->rule) {
2798         op->rule->pending = NULL;
2799     }
2800     if (op->type == OFOPERATION_DELETE) {
2801         hmap_remove(&group->ofproto->deletions, &op->hmap_node);
2802     }
2803     list_remove(&op->group_node);
2804     free(op->actions);
2805     free(op);
2806
2807     if (list_is_empty(&group->ops) && !list_is_empty(&group->ofproto_node)) {
2808         ofopgroup_destroy(group);
2809     }
2810 }
2811
2812 /* Indicates that 'op' completed with status 'error', which is either 0 to
2813  * indicate success or an OpenFlow error code (constructed with
2814  * e.g. ofp_mkerr()).
2815  *
2816  * If 'op' is a "delete flow" operation, 'error' must be 0.  That is, flow
2817  * deletions are not allowed to fail.
2818  *
2819  * Please see the large comment in ofproto/ofproto-provider.h titled
2820  * "Asynchronous Operation Support" for more information. */
2821 void
2822 ofoperation_complete(struct ofoperation *op, int error)
2823 {
2824     struct ofopgroup *group = op->group;
2825     struct rule *rule = op->rule;
2826     struct classifier *table = &rule->ofproto->tables[rule->table_id];
2827
2828     assert(rule->pending == op);
2829     assert(op->status < 0);
2830     assert(error >= 0);
2831
2832     if (!error
2833         && !group->error
2834         && op->type != OFOPERATION_DELETE
2835         && group->ofconn
2836         && group->buffer_id != UINT32_MAX
2837         && list_is_singleton(&op->group_node)) {
2838         struct ofpbuf *packet;
2839         uint16_t in_port;
2840
2841         error = ofconn_pktbuf_retrieve(group->ofconn, group->buffer_id,
2842                                        &packet, &in_port);
2843         if (packet) {
2844             assert(!error);
2845             error = rule_execute(rule, in_port, packet);
2846         }
2847     }
2848     if (!group->error) {
2849         group->error = error;
2850     }
2851
2852     switch (op->type) {
2853     case OFOPERATION_ADD:
2854         if (!error) {
2855             if (op->victim) {
2856                 ofproto_rule_destroy__(op->victim);
2857             }
2858         } else {
2859             if (op->victim) {
2860                 classifier_replace(table, &op->victim->cr);
2861                 op->victim = NULL;
2862             } else {
2863                 classifier_remove(table, &rule->cr);
2864             }
2865             ofproto_rule_destroy__(rule);
2866         }
2867         op->victim = NULL;
2868         break;
2869
2870     case OFOPERATION_DELETE:
2871         assert(!error);
2872         ofproto_rule_destroy__(rule);
2873         op->rule = NULL;
2874         break;
2875
2876     case OFOPERATION_MODIFY:
2877         if (error) {
2878             free(rule->actions);
2879             rule->actions = op->actions;
2880             rule->n_actions = op->n_actions;
2881             op->actions = NULL;
2882         }
2883         break;
2884
2885     default:
2886         NOT_REACHED();
2887     }
2888     ofoperation_destroy(op);
2889 }
2890
2891 struct rule *
2892 ofoperation_get_victim(struct ofoperation *op)
2893 {
2894     assert(op->type == OFOPERATION_ADD);
2895     return op->victim;
2896 }
2897 \f
2898 static uint64_t
2899 pick_datapath_id(const struct ofproto *ofproto)
2900 {
2901     const struct ofport *port;
2902
2903     port = ofproto_get_port(ofproto, OFPP_LOCAL);
2904     if (port) {
2905         uint8_t ea[ETH_ADDR_LEN];
2906         int error;
2907
2908         error = netdev_get_etheraddr(port->netdev, ea);
2909         if (!error) {
2910             return eth_addr_to_uint64(ea);
2911         }
2912         VLOG_WARN("could not get MAC address for %s (%s)",
2913                   netdev_get_name(port->netdev), strerror(error));
2914     }
2915     return ofproto->fallback_dpid;
2916 }
2917
2918 static uint64_t
2919 pick_fallback_dpid(void)
2920 {
2921     uint8_t ea[ETH_ADDR_LEN];
2922     eth_addr_nicira_random(ea);
2923     return eth_addr_to_uint64(ea);
2924 }
2925 \f
2926 /* unixctl commands. */
2927
2928 struct ofproto *
2929 ofproto_lookup(const char *name)
2930 {
2931     struct ofproto *ofproto;
2932
2933     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
2934                              &all_ofprotos) {
2935         if (!strcmp(ofproto->name, name)) {
2936             return ofproto;
2937         }
2938     }
2939     return NULL;
2940 }
2941
2942 static void
2943 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
2944                      void *aux OVS_UNUSED)
2945 {
2946     struct ofproto *ofproto;
2947     struct ds results;
2948
2949     ds_init(&results);
2950     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
2951         ds_put_format(&results, "%s\n", ofproto->name);
2952     }
2953     unixctl_command_reply(conn, 200, ds_cstr(&results));
2954     ds_destroy(&results);
2955 }
2956
2957 static void
2958 ofproto_unixctl_init(void)
2959 {
2960     static bool registered;
2961     if (registered) {
2962         return;
2963     }
2964     registered = true;
2965
2966     unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
2967 }