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