connmgr: New function ofconn_send_error().
[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 int
1363 handle_echo_request(struct ofconn *ofconn, const struct ofp_header *oh)
1364 {
1365     ofconn_send_reply(ofconn, make_echo_reply(oh));
1366     return 0;
1367 }
1368
1369 static int
1370 handle_features_request(struct ofconn *ofconn, const struct ofp_header *oh)
1371 {
1372     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1373     struct ofp_switch_features *osf;
1374     struct ofpbuf *buf;
1375     struct ofport *port;
1376     bool arp_match_ip;
1377     uint32_t actions;
1378
1379     ofproto->ofproto_class->get_features(ofproto, &arp_match_ip, &actions);
1380     assert(actions & (1 << OFPAT_OUTPUT)); /* sanity check */
1381
1382     osf = make_openflow_xid(sizeof *osf, OFPT_FEATURES_REPLY, oh->xid, &buf);
1383     osf->datapath_id = htonll(ofproto->datapath_id);
1384     osf->n_buffers = htonl(pktbuf_capacity());
1385     osf->n_tables = ofproto->n_tables;
1386     osf->capabilities = htonl(OFPC_FLOW_STATS | OFPC_TABLE_STATS |
1387                               OFPC_PORT_STATS);
1388     if (arp_match_ip) {
1389         osf->capabilities |= htonl(OFPC_ARP_MATCH_IP);
1390     }
1391     osf->actions = htonl(actions);
1392
1393     HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
1394         ofpbuf_put(buf, &port->opp, sizeof port->opp);
1395     }
1396
1397     ofconn_send_reply(ofconn, buf);
1398     return 0;
1399 }
1400
1401 static int
1402 handle_get_config_request(struct ofconn *ofconn, const struct ofp_header *oh)
1403 {
1404     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1405     struct ofpbuf *buf;
1406     struct ofp_switch_config *osc;
1407     uint16_t flags;
1408     bool drop_frags;
1409
1410     /* Figure out flags. */
1411     drop_frags = ofproto->ofproto_class->get_drop_frags(ofproto);
1412     flags = drop_frags ? OFPC_FRAG_DROP : OFPC_FRAG_NORMAL;
1413
1414     /* Send reply. */
1415     osc = make_openflow_xid(sizeof *osc, OFPT_GET_CONFIG_REPLY, oh->xid, &buf);
1416     osc->flags = htons(flags);
1417     osc->miss_send_len = htons(ofconn_get_miss_send_len(ofconn));
1418     ofconn_send_reply(ofconn, buf);
1419
1420     return 0;
1421 }
1422
1423 static int
1424 handle_set_config(struct ofconn *ofconn, const struct ofp_switch_config *osc)
1425 {
1426     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1427     uint16_t flags = ntohs(osc->flags);
1428
1429     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
1430         && ofconn_get_role(ofconn) != NX_ROLE_SLAVE) {
1431         switch (flags & OFPC_FRAG_MASK) {
1432         case OFPC_FRAG_NORMAL:
1433             ofproto->ofproto_class->set_drop_frags(ofproto, false);
1434             break;
1435         case OFPC_FRAG_DROP:
1436             ofproto->ofproto_class->set_drop_frags(ofproto, true);
1437             break;
1438         default:
1439             VLOG_WARN_RL(&rl, "requested bad fragment mode (flags=%"PRIx16")",
1440                          osc->flags);
1441             break;
1442         }
1443     }
1444
1445     ofconn_set_miss_send_len(ofconn, ntohs(osc->miss_send_len));
1446
1447     return 0;
1448 }
1449
1450 /* Checks whether 'ofconn' is a slave controller.  If so, returns an OpenFlow
1451  * error message code (composed with ofp_mkerr()) for the caller to propagate
1452  * upward.  Otherwise, returns 0.
1453  *
1454  * The log message mentions 'msg_type'. */
1455 static int
1456 reject_slave_controller(struct ofconn *ofconn, const char *msg_type)
1457 {
1458     if (ofconn_get_type(ofconn) == OFCONN_PRIMARY
1459         && ofconn_get_role(ofconn) == NX_ROLE_SLAVE) {
1460         static struct vlog_rate_limit perm_rl = VLOG_RATE_LIMIT_INIT(1, 5);
1461         VLOG_WARN_RL(&perm_rl, "rejecting %s message from slave controller",
1462                      msg_type);
1463
1464         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
1465     } else {
1466         return 0;
1467     }
1468 }
1469
1470 static int
1471 handle_packet_out(struct ofconn *ofconn, const struct ofp_header *oh)
1472 {
1473     struct ofproto *p = ofconn_get_ofproto(ofconn);
1474     struct ofp_packet_out *opo;
1475     struct ofpbuf payload, *buffer;
1476     union ofp_action *ofp_actions;
1477     struct ofpbuf request;
1478     struct flow flow;
1479     size_t n_ofp_actions;
1480     uint16_t in_port;
1481     int error;
1482
1483     COVERAGE_INC(ofproto_packet_out);
1484
1485     error = reject_slave_controller(ofconn, "OFPT_PACKET_OUT");
1486     if (error) {
1487         return error;
1488     }
1489
1490     /* Get ofp_packet_out. */
1491     ofpbuf_use_const(&request, oh, ntohs(oh->length));
1492     opo = ofpbuf_pull(&request, offsetof(struct ofp_packet_out, actions));
1493
1494     /* Get actions. */
1495     error = ofputil_pull_actions(&request, ntohs(opo->actions_len),
1496                                  &ofp_actions, &n_ofp_actions);
1497     if (error) {
1498         return error;
1499     }
1500
1501     /* Get payload. */
1502     if (opo->buffer_id != htonl(UINT32_MAX)) {
1503         error = ofconn_pktbuf_retrieve(ofconn, ntohl(opo->buffer_id),
1504                                        &buffer, &in_port);
1505         if (error || !buffer) {
1506             return error;
1507         }
1508         payload = *buffer;
1509     } else {
1510         payload = request;
1511         buffer = NULL;
1512     }
1513
1514     /* Send out packet. */
1515     flow_extract(&payload, 0, ntohs(opo->in_port), &flow);
1516     error = p->ofproto_class->packet_out(p, &payload, &flow,
1517                                          ofp_actions, n_ofp_actions);
1518     ofpbuf_delete(buffer);
1519
1520     return error;
1521 }
1522
1523 static void
1524 update_port_config(struct ofport *port, ovs_be32 config, ovs_be32 mask)
1525 {
1526     ovs_be32 old_config = port->opp.config;
1527
1528     mask &= config ^ port->opp.config;
1529     if (mask & htonl(OFPPC_PORT_DOWN)) {
1530         if (config & htonl(OFPPC_PORT_DOWN)) {
1531             netdev_turn_flags_off(port->netdev, NETDEV_UP, true);
1532         } else {
1533             netdev_turn_flags_on(port->netdev, NETDEV_UP, true);
1534         }
1535     }
1536
1537     port->opp.config ^= mask & (htonl(OFPPC_NO_RECV | OFPPC_NO_RECV_STP |
1538                                       OFPPC_NO_FLOOD | OFPPC_NO_FWD |
1539                                       OFPPC_NO_PACKET_IN));
1540     if (port->opp.config != old_config) {
1541         port->ofproto->ofproto_class->port_reconfigured(port, old_config);
1542     }
1543 }
1544
1545 static int
1546 handle_port_mod(struct ofconn *ofconn, const struct ofp_header *oh)
1547 {
1548     struct ofproto *p = ofconn_get_ofproto(ofconn);
1549     const struct ofp_port_mod *opm = (const struct ofp_port_mod *) oh;
1550     struct ofport *port;
1551     int error;
1552
1553     error = reject_slave_controller(ofconn, "OFPT_PORT_MOD");
1554     if (error) {
1555         return error;
1556     }
1557
1558     port = ofproto_get_port(p, ntohs(opm->port_no));
1559     if (!port) {
1560         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_PORT);
1561     } else if (memcmp(port->opp.hw_addr, opm->hw_addr, OFP_ETH_ALEN)) {
1562         return ofp_mkerr(OFPET_PORT_MOD_FAILED, OFPPMFC_BAD_HW_ADDR);
1563     } else {
1564         update_port_config(port, opm->config, opm->mask);
1565         if (opm->advertise) {
1566             netdev_set_advertisements(port->netdev, ntohl(opm->advertise));
1567         }
1568     }
1569     return 0;
1570 }
1571
1572 static int
1573 handle_desc_stats_request(struct ofconn *ofconn,
1574                           const struct ofp_stats_msg *request)
1575 {
1576     struct ofproto *p = ofconn_get_ofproto(ofconn);
1577     struct ofp_desc_stats *ods;
1578     struct ofpbuf *msg;
1579
1580     ods = ofputil_make_stats_reply(sizeof *ods, request, &msg);
1581     ovs_strlcpy(ods->mfr_desc, p->mfr_desc, sizeof ods->mfr_desc);
1582     ovs_strlcpy(ods->hw_desc, p->hw_desc, sizeof ods->hw_desc);
1583     ovs_strlcpy(ods->sw_desc, p->sw_desc, sizeof ods->sw_desc);
1584     ovs_strlcpy(ods->serial_num, p->serial_desc, sizeof ods->serial_num);
1585     ovs_strlcpy(ods->dp_desc, p->dp_desc, sizeof ods->dp_desc);
1586     ofconn_send_reply(ofconn, msg);
1587
1588     return 0;
1589 }
1590
1591 static int
1592 handle_table_stats_request(struct ofconn *ofconn,
1593                            const struct ofp_stats_msg *request)
1594 {
1595     struct ofproto *p = ofconn_get_ofproto(ofconn);
1596     struct ofp_table_stats *ots;
1597     struct ofpbuf *msg;
1598     size_t i;
1599
1600     ofputil_make_stats_reply(sizeof(struct ofp_stats_msg), request, &msg);
1601
1602     ots = ofpbuf_put_zeros(msg, sizeof *ots * p->n_tables);
1603     for (i = 0; i < p->n_tables; i++) {
1604         ots[i].table_id = i;
1605         sprintf(ots[i].name, "table%zu", i);
1606         ots[i].wildcards = htonl(OFPFW_ALL);
1607         ots[i].max_entries = htonl(1000000); /* An arbitrary big number. */
1608         ots[i].active_count = htonl(classifier_count(&p->tables[i]));
1609     }
1610
1611     p->ofproto_class->get_tables(p, ots);
1612
1613     ofconn_send_reply(ofconn, msg);
1614     return 0;
1615 }
1616
1617 static void
1618 append_port_stat(struct ofport *port, struct list *replies)
1619 {
1620     struct netdev_stats stats;
1621     struct ofp_port_stats *ops;
1622
1623     /* Intentionally ignore return value, since errors will set
1624      * 'stats' to all-1s, which is correct for OpenFlow, and
1625      * netdev_get_stats() will log errors. */
1626     netdev_get_stats(port->netdev, &stats);
1627
1628     ops = ofputil_append_stats_reply(sizeof *ops, replies);
1629     ops->port_no = port->opp.port_no;
1630     memset(ops->pad, 0, sizeof ops->pad);
1631     put_32aligned_be64(&ops->rx_packets, htonll(stats.rx_packets));
1632     put_32aligned_be64(&ops->tx_packets, htonll(stats.tx_packets));
1633     put_32aligned_be64(&ops->rx_bytes, htonll(stats.rx_bytes));
1634     put_32aligned_be64(&ops->tx_bytes, htonll(stats.tx_bytes));
1635     put_32aligned_be64(&ops->rx_dropped, htonll(stats.rx_dropped));
1636     put_32aligned_be64(&ops->tx_dropped, htonll(stats.tx_dropped));
1637     put_32aligned_be64(&ops->rx_errors, htonll(stats.rx_errors));
1638     put_32aligned_be64(&ops->tx_errors, htonll(stats.tx_errors));
1639     put_32aligned_be64(&ops->rx_frame_err, htonll(stats.rx_frame_errors));
1640     put_32aligned_be64(&ops->rx_over_err, htonll(stats.rx_over_errors));
1641     put_32aligned_be64(&ops->rx_crc_err, htonll(stats.rx_crc_errors));
1642     put_32aligned_be64(&ops->collisions, htonll(stats.collisions));
1643 }
1644
1645 static int
1646 handle_port_stats_request(struct ofconn *ofconn,
1647                           const struct ofp_port_stats_request *psr)
1648 {
1649     struct ofproto *p = ofconn_get_ofproto(ofconn);
1650     struct ofport *port;
1651     struct list replies;
1652
1653     ofputil_start_stats_reply(&psr->osm, &replies);
1654     if (psr->port_no != htons(OFPP_NONE)) {
1655         port = ofproto_get_port(p, ntohs(psr->port_no));
1656         if (port) {
1657             append_port_stat(port, &replies);
1658         }
1659     } else {
1660         HMAP_FOR_EACH (port, hmap_node, &p->ports) {
1661             append_port_stat(port, &replies);
1662         }
1663     }
1664
1665     ofconn_send_replies(ofconn, &replies);
1666     return 0;
1667 }
1668
1669 static void
1670 calc_flow_duration__(long long int start, uint32_t *sec, uint32_t *nsec)
1671 {
1672     long long int msecs = time_msec() - start;
1673     *sec = msecs / 1000;
1674     *nsec = (msecs % 1000) * (1000 * 1000);
1675 }
1676
1677 static struct classifier *
1678 first_matching_table(struct ofproto *ofproto, uint8_t table_id)
1679 {
1680     if (table_id == 0xff) {
1681         return &ofproto->tables[0];
1682     } else if (table_id < ofproto->n_tables) {
1683         return &ofproto->tables[table_id];
1684     } else {
1685         /* It would probably be better to reply with an error but there doesn't
1686          * seem to be any appropriate value, so that might just be
1687          * confusing. */
1688         VLOG_WARN_RL(&rl, "controller asked for invalid table %"PRIu8,
1689                      table_id);
1690         return NULL;
1691     }
1692 }
1693
1694 static struct classifier *
1695 next_matching_table(struct ofproto *ofproto,
1696                     struct classifier *cls, uint8_t table_id)
1697 {
1698     return (table_id == 0xff && cls != &ofproto->tables[ofproto->n_tables - 1]
1699             ? cls + 1
1700             : NULL);
1701 }
1702
1703 /* Assigns CLS to each classifier table, in turn, that matches TABLE_ID in
1704  * OFPROTO:
1705  *
1706  *   - If TABLE_ID is 0xff, this iterates over every classifier table in
1707  *     OFPROTO.
1708  *
1709  *   - If TABLE_ID is the number of a table in OFPROTO, then the loop iterates
1710  *     only once, for that table.
1711  *
1712  *   - Otherwise, TABLE_ID isn't valid for OFPROTO, so ofproto logs a warning
1713  *     and does not enter the loop at all.
1714  *
1715  * All parameters are evaluated multiple times.
1716  */
1717 #define FOR_EACH_MATCHING_TABLE(CLS, TABLE_ID, OFPROTO)         \
1718     for ((CLS) = first_matching_table(OFPROTO, TABLE_ID);       \
1719          (CLS) != NULL;                                         \
1720          (CLS) = next_matching_table(OFPROTO, CLS, TABLE_ID))
1721
1722 static int
1723 handle_flow_stats_request(struct ofconn *ofconn,
1724                           const struct ofp_stats_msg *osm)
1725 {
1726     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1727     struct flow_stats_request fsr;
1728     struct classifier *cls;
1729     struct list replies;
1730     ovs_be16 out_port;
1731     int error;
1732
1733     error = ofputil_decode_flow_stats_request(&fsr, &osm->header);
1734     if (error) {
1735         return error;
1736     }
1737     out_port = htons(fsr.out_port);
1738
1739     list_init(&replies);
1740     ofputil_start_stats_reply(osm, &replies);
1741     FOR_EACH_MATCHING_TABLE (cls, fsr.table_id, ofproto) {
1742         struct cls_cursor cursor;
1743         struct rule *rule;
1744
1745         cls_cursor_init(&cursor, cls, &fsr.match);
1746         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1747             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
1748                 struct ofputil_flow_stats fs;
1749
1750                 fs.rule = rule->cr;
1751                 fs.cookie = rule->flow_cookie;
1752                 fs.table_id = rule->table_id;
1753                 calc_flow_duration__(rule->created, &fs.duration_sec,
1754                                      &fs.duration_nsec);
1755                 fs.idle_timeout = rule->idle_timeout;
1756                 fs.hard_timeout = rule->hard_timeout;
1757                 ofproto->ofproto_class->rule_get_stats(rule, &fs.packet_count,
1758                                                        &fs.byte_count);
1759                 fs.actions = rule->actions;
1760                 fs.n_actions = rule->n_actions;
1761                 ofputil_append_flow_stats_reply(&fs, &replies);
1762             }
1763         }
1764     }
1765     ofconn_send_replies(ofconn, &replies);
1766
1767     return 0;
1768 }
1769
1770 static void
1771 flow_stats_ds(struct rule *rule, struct ds *results)
1772 {
1773     uint64_t packet_count, byte_count;
1774     size_t act_len = sizeof *rule->actions * rule->n_actions;
1775
1776     rule->ofproto->ofproto_class->rule_get_stats(rule,
1777                                                  &packet_count, &byte_count);
1778
1779     if (rule->table_id != 0) {
1780         ds_put_format(results, "table_id=%"PRIu8", ", rule->table_id);
1781     }
1782     ds_put_format(results, "duration=%llds, ",
1783                   (time_msec() - rule->created) / 1000);
1784     ds_put_format(results, "priority=%u, ", rule->cr.priority);
1785     ds_put_format(results, "n_packets=%"PRIu64", ", packet_count);
1786     ds_put_format(results, "n_bytes=%"PRIu64", ", byte_count);
1787     cls_rule_format(&rule->cr, results);
1788     ds_put_char(results, ',');
1789     if (act_len > 0) {
1790         ofp_print_actions(results, &rule->actions->header, act_len);
1791     } else {
1792         ds_put_cstr(results, "drop");
1793     }
1794     ds_put_cstr(results, "\n");
1795 }
1796
1797 /* Adds a pretty-printed description of all flows to 'results', including
1798  * hidden flows (e.g., set up by in-band control). */
1799 void
1800 ofproto_get_all_flows(struct ofproto *p, struct ds *results)
1801 {
1802     struct classifier *cls;
1803
1804     for (cls = &p->tables[0]; cls < &p->tables[p->n_tables]; cls++) {
1805         struct cls_cursor cursor;
1806         struct rule *rule;
1807
1808         cls_cursor_init(&cursor, cls, NULL);
1809         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1810             flow_stats_ds(rule, results);
1811         }
1812     }
1813 }
1814
1815 /* Obtains the NetFlow engine type and engine ID for 'ofproto' into
1816  * '*engine_type' and '*engine_id', respectively. */
1817 void
1818 ofproto_get_netflow_ids(const struct ofproto *ofproto,
1819                         uint8_t *engine_type, uint8_t *engine_id)
1820 {
1821     ofproto->ofproto_class->get_netflow_ids(ofproto, engine_type, engine_id);
1822 }
1823
1824 /* Checks the fault status of CFM for 'ofp_port' within 'ofproto'.  Returns 1
1825  * if CFM is faulted (generally indiciating a connectivity problem), 0 if CFM
1826  * is not faulted, and -1 if CFM is not enabled on 'ofp_port'. */
1827 int
1828 ofproto_port_get_cfm_fault(const struct ofproto *ofproto, uint16_t ofp_port)
1829 {
1830     struct ofport *ofport = ofproto_get_port(ofproto, ofp_port);
1831     return (ofport && ofproto->ofproto_class->get_cfm_fault
1832             ? ofproto->ofproto_class->get_cfm_fault(ofport)
1833             : -1);
1834 }
1835
1836 static int
1837 handle_aggregate_stats_request(struct ofconn *ofconn,
1838                                const struct ofp_stats_msg *osm)
1839 {
1840     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1841     struct flow_stats_request request;
1842     struct ofputil_aggregate_stats stats;
1843     struct classifier *cls;
1844     struct ofpbuf *reply;
1845     ovs_be16 out_port;
1846     int error;
1847
1848     error = ofputil_decode_flow_stats_request(&request, &osm->header);
1849     if (error) {
1850         return error;
1851     }
1852     out_port = htons(request.out_port);
1853
1854     memset(&stats, 0, sizeof stats);
1855     FOR_EACH_MATCHING_TABLE (cls, request.table_id, ofproto) {
1856         struct cls_cursor cursor;
1857         struct rule *rule;
1858
1859         cls_cursor_init(&cursor, cls, &request.match);
1860         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
1861             if (!rule_is_hidden(rule) && rule_has_out_port(rule, out_port)) {
1862                 uint64_t packet_count;
1863                 uint64_t byte_count;
1864
1865                 ofproto->ofproto_class->rule_get_stats(rule, &packet_count,
1866                                                        &byte_count);
1867
1868                 stats.packet_count += packet_count;
1869                 stats.byte_count += byte_count;
1870                 stats.flow_count++;
1871             }
1872         }
1873     }
1874
1875     reply = ofputil_encode_aggregate_stats_reply(&stats, osm);
1876     ofconn_send_reply(ofconn, reply);
1877
1878     return 0;
1879 }
1880
1881 struct queue_stats_cbdata {
1882     struct ofport *ofport;
1883     struct list replies;
1884 };
1885
1886 static void
1887 put_queue_stats(struct queue_stats_cbdata *cbdata, uint32_t queue_id,
1888                 const struct netdev_queue_stats *stats)
1889 {
1890     struct ofp_queue_stats *reply;
1891
1892     reply = ofputil_append_stats_reply(sizeof *reply, &cbdata->replies);
1893     reply->port_no = cbdata->ofport->opp.port_no;
1894     memset(reply->pad, 0, sizeof reply->pad);
1895     reply->queue_id = htonl(queue_id);
1896     put_32aligned_be64(&reply->tx_bytes, htonll(stats->tx_bytes));
1897     put_32aligned_be64(&reply->tx_packets, htonll(stats->tx_packets));
1898     put_32aligned_be64(&reply->tx_errors, htonll(stats->tx_errors));
1899 }
1900
1901 static void
1902 handle_queue_stats_dump_cb(uint32_t queue_id,
1903                            struct netdev_queue_stats *stats,
1904                            void *cbdata_)
1905 {
1906     struct queue_stats_cbdata *cbdata = cbdata_;
1907
1908     put_queue_stats(cbdata, queue_id, stats);
1909 }
1910
1911 static void
1912 handle_queue_stats_for_port(struct ofport *port, uint32_t queue_id,
1913                             struct queue_stats_cbdata *cbdata)
1914 {
1915     cbdata->ofport = port;
1916     if (queue_id == OFPQ_ALL) {
1917         netdev_dump_queue_stats(port->netdev,
1918                                 handle_queue_stats_dump_cb, cbdata);
1919     } else {
1920         struct netdev_queue_stats stats;
1921
1922         if (!netdev_get_queue_stats(port->netdev, queue_id, &stats)) {
1923             put_queue_stats(cbdata, queue_id, &stats);
1924         }
1925     }
1926 }
1927
1928 static int
1929 handle_queue_stats_request(struct ofconn *ofconn,
1930                            const struct ofp_queue_stats_request *qsr)
1931 {
1932     struct ofproto *ofproto = ofconn_get_ofproto(ofconn);
1933     struct queue_stats_cbdata cbdata;
1934     struct ofport *port;
1935     unsigned int port_no;
1936     uint32_t queue_id;
1937
1938     COVERAGE_INC(ofproto_queue_req);
1939
1940     ofputil_start_stats_reply(&qsr->osm, &cbdata.replies);
1941
1942     port_no = ntohs(qsr->port_no);
1943     queue_id = ntohl(qsr->queue_id);
1944     if (port_no == OFPP_ALL) {
1945         HMAP_FOR_EACH (port, hmap_node, &ofproto->ports) {
1946             handle_queue_stats_for_port(port, queue_id, &cbdata);
1947         }
1948     } else if (port_no < OFPP_MAX) {
1949         port = ofproto_get_port(ofproto, port_no);
1950         if (port) {
1951             handle_queue_stats_for_port(port, queue_id, &cbdata);
1952         }
1953     } else {
1954         ofpbuf_list_delete(&cbdata.replies);
1955         return ofp_mkerr(OFPET_QUEUE_OP_FAILED, OFPQOFC_BAD_PORT);
1956     }
1957     ofconn_send_replies(ofconn, &cbdata.replies);
1958
1959     return 0;
1960 }
1961
1962 /* Implements OFPFC_ADD and the cases for OFPFC_MODIFY and OFPFC_MODIFY_STRICT
1963  * in which no matching flow already exists in the flow table.
1964  *
1965  * Adds the flow specified by 'ofm', which is followed by 'n_actions'
1966  * ofp_actions, to the ofproto's flow table.  Returns 0 on success or an
1967  * OpenFlow error code as encoded by ofp_mkerr() on failure.
1968  *
1969  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
1970  * if any. */
1971 static int
1972 add_flow(struct ofconn *ofconn, struct flow_mod *fm)
1973 {
1974     struct ofproto *p = ofconn_get_ofproto(ofconn);
1975     struct ofpbuf *packet;
1976     struct rule *rule;
1977     uint16_t in_port;
1978     int buf_err;
1979     int error;
1980
1981     if (fm->flags & OFPFF_CHECK_OVERLAP) {
1982         struct classifier *cls;
1983
1984         FOR_EACH_MATCHING_TABLE (cls, fm->table_id, p) {
1985             if (classifier_rule_overlaps(cls, &fm->cr)) {
1986                 return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_OVERLAP);
1987             }
1988         }
1989     }
1990
1991     buf_err = ofconn_pktbuf_retrieve(ofconn, fm->buffer_id, &packet, &in_port);
1992     error = rule_create(p, &fm->cr, fm->table_id, fm->actions, fm->n_actions,
1993                         fm->idle_timeout, fm->hard_timeout, fm->cookie,
1994                         fm->flags & OFPFF_SEND_FLOW_REM, &rule);
1995     if (error) {
1996         ofpbuf_delete(packet);
1997         return error;
1998     }
1999
2000     if (packet) {
2001         assert(!buf_err);
2002         return rule_execute(rule, in_port, packet);
2003     }
2004     return buf_err;
2005 }
2006
2007 /* Searches 'p' for an exact match for 'fm', in the table or tables indicated
2008  * by fm->table_id.  Returns 0 if no match was found, 1 if exactly one match
2009  * was found, 2 if more than one match was found.  If exactly one match is
2010  * found, sets '*rulep' to the match, otherwise to NULL.
2011  *
2012  * This implements the rules for "strict" matching explained in the comment on
2013  * struct nxt_flow_mod_table_id in nicira-ext.h.
2014  *
2015  * Ignores hidden rules. */
2016 static int
2017 find_flow_strict(struct ofproto *p, const struct flow_mod *fm,
2018                  struct rule **rulep)
2019 {
2020     struct classifier *cls;
2021
2022     *rulep = NULL;
2023     FOR_EACH_MATCHING_TABLE (cls, fm->table_id, p) {
2024         struct rule *rule;
2025
2026         rule = rule_from_cls_rule(classifier_find_rule_exactly(cls, &fm->cr));
2027         if (rule && !rule_is_hidden(rule)) {
2028             if (*rulep) {
2029                 *rulep = NULL;
2030                 return 2;
2031             }
2032             *rulep = rule;
2033         }
2034     }
2035     return *rulep != NULL;
2036 }
2037
2038 static int
2039 send_buffered_packet(struct ofconn *ofconn,
2040                      struct rule *rule, uint32_t buffer_id)
2041 {
2042     struct ofpbuf *packet;
2043     uint16_t in_port;
2044     int error;
2045
2046     if (buffer_id == UINT32_MAX) {
2047         return 0;
2048     }
2049
2050     error = ofconn_pktbuf_retrieve(ofconn, buffer_id, &packet, &in_port);
2051     if (error) {
2052         return error;
2053     }
2054
2055     return rule_execute(rule, in_port, packet);
2056 }
2057 \f
2058 /* OFPFC_MODIFY and OFPFC_MODIFY_STRICT. */
2059
2060 struct modify_flows_cbdata {
2061     struct ofproto *ofproto;
2062     const struct flow_mod *fm;
2063     struct rule *match;
2064 };
2065
2066 static int modify_flow(const struct flow_mod *, struct rule *);
2067
2068 /* Implements OFPFC_MODIFY.  Returns 0 on success or an OpenFlow error code as
2069  * encoded by ofp_mkerr() on failure.
2070  *
2071  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2072  * if any. */
2073 static int
2074 modify_flows_loose(struct ofconn *ofconn, struct flow_mod *fm)
2075 {
2076     struct ofproto *p = ofconn_get_ofproto(ofconn);
2077     struct rule *match = NULL;
2078     struct classifier *cls;
2079     int error;
2080
2081     error = 0;
2082     FOR_EACH_MATCHING_TABLE (cls, fm->table_id, p) {
2083         struct cls_cursor cursor;
2084         struct rule *rule;
2085
2086         cls_cursor_init(&cursor, cls, &fm->cr);
2087         CLS_CURSOR_FOR_EACH (rule, cr, &cursor) {
2088             if (!rule_is_hidden(rule)) {
2089                 int retval = modify_flow(fm, rule);
2090                 if (!retval) {
2091                     match = rule;
2092                 } else {
2093                     error = retval;
2094                 }
2095             }
2096         }
2097     }
2098
2099     if (error) {
2100         return error;
2101     } else if (match) {
2102         /* This credits the packet to whichever flow happened to match last.
2103          * That's weird.  Maybe we should do a lookup for the flow that
2104          * actually matches the packet?  Who knows. */
2105         send_buffered_packet(ofconn, match, fm->buffer_id);
2106         return 0;
2107     } else {
2108         return add_flow(ofconn, fm);
2109     }
2110 }
2111
2112 /* Implements OFPFC_MODIFY_STRICT.  Returns 0 on success or an OpenFlow error
2113  * code as encoded by ofp_mkerr() on failure.
2114  *
2115  * 'ofconn' is used to retrieve the packet buffer specified in ofm->buffer_id,
2116  * if any. */
2117 static int
2118 modify_flow_strict(struct ofconn *ofconn, struct flow_mod *fm)
2119 {
2120     struct ofproto *p = ofconn_get_ofproto(ofconn);
2121     struct rule *rule;
2122     int error;
2123
2124     switch (find_flow_strict(p, fm, &rule)) {
2125     case 0:
2126         return add_flow(ofconn, fm);
2127
2128     case 1:
2129         error = modify_flow(fm, rule);
2130         if (!error) {
2131             error = send_buffered_packet(ofconn, rule, fm->buffer_id);
2132         }
2133         return error;
2134
2135     case 2:
2136         return 0;
2137
2138     default:
2139         NOT_REACHED();
2140     }
2141 }
2142
2143 /* Implements core of OFPFC_MODIFY and OFPFC_MODIFY_STRICT where 'rule' has
2144  * been identified as a flow to be modified, by changing the rule's actions to
2145  * match those in 'ofm' (which is followed by 'n_actions' ofp_action[]
2146  * structures). */
2147 static int
2148 modify_flow(const struct flow_mod *fm, struct rule *rule)
2149 {
2150     size_t actions_len = fm->n_actions * sizeof *rule->actions;
2151     int error;
2152
2153     if (fm->n_actions == rule->n_actions
2154         && (!fm->n_actions
2155             || !memcmp(fm->actions, rule->actions, actions_len))) {
2156         error = 0;
2157     } else {
2158         error = rule->ofproto->ofproto_class->rule_modify_actions(
2159             rule, fm->actions, fm->n_actions);
2160         if (!error) {
2161             free(rule->actions);
2162             rule->actions = (fm->n_actions
2163                              ? xmemdup(fm->actions, actions_len)
2164                              : NULL);
2165             rule->n_actions = fm->n_actions;
2166         }
2167     }
2168
2169     if (!error) {
2170         rule->flow_cookie = fm->cookie;
2171     }
2172
2173     return error;
2174 }
2175 \f
2176 /* OFPFC_DELETE implementation. */
2177
2178 static void delete_flow(struct rule *, ovs_be16 out_port);
2179
2180 /* Implements OFPFC_DELETE. */
2181 static void
2182 delete_flows_loose(struct ofproto *p, const struct flow_mod *fm)
2183 {
2184     struct classifier *cls;
2185
2186     FOR_EACH_MATCHING_TABLE (cls, fm->table_id, p) {
2187         struct rule *rule, *next_rule;
2188         struct cls_cursor cursor;
2189
2190         cls_cursor_init(&cursor, cls, &fm->cr);
2191         CLS_CURSOR_FOR_EACH_SAFE (rule, next_rule, cr, &cursor) {
2192             delete_flow(rule, htons(fm->out_port));
2193         }
2194     }
2195 }
2196
2197 /* Implements OFPFC_DELETE_STRICT. */
2198 static void
2199 delete_flow_strict(struct ofproto *p, struct flow_mod *fm)
2200 {
2201     struct rule *rule;
2202     if (find_flow_strict(p, fm, &rule) == 1) {
2203         delete_flow(rule, htons(fm->out_port));
2204     }
2205 }
2206
2207 /* Implements core of OFPFC_DELETE and OFPFC_DELETE_STRICT where 'rule' has
2208  * been identified as a flow to delete from 'p''s flow table, by deleting the
2209  * flow and sending out a OFPT_FLOW_REMOVED message to any interested
2210  * controller.
2211  *
2212  * Will not delete 'rule' if it is hidden.  Will delete 'rule' only if
2213  * 'out_port' is htons(OFPP_NONE) or if 'rule' actually outputs to the
2214  * specified 'out_port'. */
2215 static void
2216 delete_flow(struct rule *rule, ovs_be16 out_port)
2217 {
2218     if (rule_is_hidden(rule)) {
2219         return;
2220     }
2221
2222     if (out_port != htons(OFPP_NONE) && !rule_has_out_port(rule, out_port)) {
2223         return;
2224     }
2225
2226     ofproto_rule_send_removed(rule, OFPRR_DELETE);
2227     ofproto_rule_destroy(rule);
2228 }
2229
2230 static void
2231 ofproto_rule_send_removed(struct rule *rule, uint8_t reason)
2232 {
2233     struct ofputil_flow_removed fr;
2234
2235     if (rule_is_hidden(rule) || !rule->send_flow_removed) {
2236         return;
2237     }
2238
2239     fr.rule = rule->cr;
2240     fr.cookie = rule->flow_cookie;
2241     fr.reason = reason;
2242     calc_flow_duration__(rule->created, &fr.duration_sec, &fr.duration_nsec);
2243     fr.idle_timeout = rule->idle_timeout;
2244     rule->ofproto->ofproto_class->rule_get_stats(rule, &fr.packet_count,
2245                                                  &fr.byte_count);
2246
2247     connmgr_send_flow_removed(rule->ofproto->connmgr, &fr);
2248 }
2249
2250 /* Sends an OpenFlow "flow removed" message with the given 'reason' (either
2251  * OFPRR_HARD_TIMEOUT or OFPRR_IDLE_TIMEOUT), and then removes 'rule' from its
2252  * ofproto.
2253  *
2254  * ofproto implementation ->run() functions should use this function to expire
2255  * OpenFlow flows. */
2256 void
2257 ofproto_rule_expire(struct rule *rule, uint8_t reason)
2258 {
2259     assert(reason == OFPRR_HARD_TIMEOUT || reason == OFPRR_IDLE_TIMEOUT);
2260     ofproto_rule_send_removed(rule, reason);
2261     ofproto_rule_destroy(rule);
2262 }
2263 \f
2264 static int
2265 handle_flow_mod(struct ofconn *ofconn, const struct ofp_header *oh)
2266 {
2267     struct ofproto *p = ofconn_get_ofproto(ofconn);
2268     struct flow_mod fm;
2269     int error;
2270
2271     error = reject_slave_controller(ofconn, "flow_mod");
2272     if (error) {
2273         return error;
2274     }
2275
2276     error = ofputil_decode_flow_mod(&fm, oh,
2277                                     ofconn_get_flow_mod_table_id(ofconn));
2278     if (error) {
2279         return error;
2280     }
2281
2282     /* We do not support the emergency flow cache.  It will hopefully get
2283      * dropped from OpenFlow in the near future. */
2284     if (fm.flags & OFPFF_EMERG) {
2285         /* There isn't a good fit for an error code, so just state that the
2286          * flow table is full. */
2287         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_ALL_TABLES_FULL);
2288     }
2289
2290     switch (fm.command) {
2291     case OFPFC_ADD:
2292         return add_flow(ofconn, &fm);
2293
2294     case OFPFC_MODIFY:
2295         return modify_flows_loose(ofconn, &fm);
2296
2297     case OFPFC_MODIFY_STRICT:
2298         return modify_flow_strict(ofconn, &fm);
2299
2300     case OFPFC_DELETE:
2301         delete_flows_loose(p, &fm);
2302         return 0;
2303
2304     case OFPFC_DELETE_STRICT:
2305         delete_flow_strict(p, &fm);
2306         return 0;
2307
2308     default:
2309         if (fm.command > 0xff) {
2310             VLOG_WARN_RL(&rl, "flow_mod has explicit table_id but "
2311                          "flow_mod_table_id extension is not enabled");
2312         }
2313         return ofp_mkerr(OFPET_FLOW_MOD_FAILED, OFPFMFC_BAD_COMMAND);
2314     }
2315 }
2316
2317 static int
2318 handle_role_request(struct ofconn *ofconn, const struct ofp_header *oh)
2319 {
2320     struct nx_role_request *nrr = (struct nx_role_request *) oh;
2321     struct nx_role_request *reply;
2322     struct ofpbuf *buf;
2323     uint32_t role;
2324
2325     if (ofconn_get_type(ofconn) != OFCONN_PRIMARY) {
2326         VLOG_WARN_RL(&rl, "ignoring role request on service connection");
2327         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2328     }
2329
2330     role = ntohl(nrr->role);
2331     if (role != NX_ROLE_OTHER && role != NX_ROLE_MASTER
2332         && role != NX_ROLE_SLAVE) {
2333         VLOG_WARN_RL(&rl, "received request for unknown role %"PRIu32, role);
2334
2335         /* There's no good error code for this. */
2336         return ofp_mkerr(OFPET_BAD_REQUEST, -1);
2337     }
2338
2339     ofconn_set_role(ofconn, role);
2340
2341     reply = make_nxmsg_xid(sizeof *reply, NXT_ROLE_REPLY, oh->xid, &buf);
2342     reply->role = htonl(role);
2343     ofconn_send_reply(ofconn, buf);
2344
2345     return 0;
2346 }
2347
2348 static int
2349 handle_nxt_flow_mod_table_id(struct ofconn *ofconn,
2350                              const struct ofp_header *oh)
2351 {
2352     const struct nxt_flow_mod_table_id *msg
2353         = (const struct nxt_flow_mod_table_id *) oh;
2354
2355     ofconn_set_flow_mod_table_id(ofconn, msg->set != 0);
2356     return 0;
2357 }
2358
2359 static int
2360 handle_nxt_set_flow_format(struct ofconn *ofconn, const struct ofp_header *oh)
2361 {
2362     const struct nxt_set_flow_format *msg
2363         = (const struct nxt_set_flow_format *) oh;
2364     uint32_t format;
2365
2366     format = ntohl(msg->format);
2367     if (format == NXFF_OPENFLOW10
2368         || format == NXFF_NXM) {
2369         ofconn_set_flow_format(ofconn, format);
2370         return 0;
2371     } else {
2372         return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_EPERM);
2373     }
2374 }
2375
2376 static int
2377 handle_barrier_request(struct ofconn *ofconn, const struct ofp_header *oh)
2378 {
2379     struct ofp_header *ob;
2380     struct ofpbuf *buf;
2381
2382     /* Currently, everything executes synchronously, so we can just
2383      * immediately send the barrier reply. */
2384     ob = make_openflow_xid(sizeof *ob, OFPT_BARRIER_REPLY, oh->xid, &buf);
2385     ofconn_send_reply(ofconn, buf);
2386     return 0;
2387 }
2388
2389 static int
2390 handle_openflow__(struct ofconn *ofconn, const struct ofpbuf *msg)
2391 {
2392     const struct ofp_header *oh = msg->data;
2393     const struct ofputil_msg_type *type;
2394     int error;
2395
2396     error = ofputil_decode_msg_type(oh, &type);
2397     if (error) {
2398         return error;
2399     }
2400
2401     switch (ofputil_msg_type_code(type)) {
2402         /* OpenFlow requests. */
2403     case OFPUTIL_OFPT_ECHO_REQUEST:
2404         return handle_echo_request(ofconn, oh);
2405
2406     case OFPUTIL_OFPT_FEATURES_REQUEST:
2407         return handle_features_request(ofconn, oh);
2408
2409     case OFPUTIL_OFPT_GET_CONFIG_REQUEST:
2410         return handle_get_config_request(ofconn, oh);
2411
2412     case OFPUTIL_OFPT_SET_CONFIG:
2413         return handle_set_config(ofconn, msg->data);
2414
2415     case OFPUTIL_OFPT_PACKET_OUT:
2416         return handle_packet_out(ofconn, oh);
2417
2418     case OFPUTIL_OFPT_PORT_MOD:
2419         return handle_port_mod(ofconn, oh);
2420
2421     case OFPUTIL_OFPT_FLOW_MOD:
2422         return handle_flow_mod(ofconn, oh);
2423
2424     case OFPUTIL_OFPT_BARRIER_REQUEST:
2425         return handle_barrier_request(ofconn, oh);
2426
2427         /* OpenFlow replies. */
2428     case OFPUTIL_OFPT_ECHO_REPLY:
2429         return 0;
2430
2431         /* Nicira extension requests. */
2432     case OFPUTIL_NXT_ROLE_REQUEST:
2433         return handle_role_request(ofconn, oh);
2434
2435     case OFPUTIL_NXT_FLOW_MOD_TABLE_ID:
2436         return handle_nxt_flow_mod_table_id(ofconn, oh);
2437
2438     case OFPUTIL_NXT_SET_FLOW_FORMAT:
2439         return handle_nxt_set_flow_format(ofconn, oh);
2440
2441     case OFPUTIL_NXT_FLOW_MOD:
2442         return handle_flow_mod(ofconn, oh);
2443
2444         /* Statistics requests. */
2445     case OFPUTIL_OFPST_DESC_REQUEST:
2446         return handle_desc_stats_request(ofconn, msg->data);
2447
2448     case OFPUTIL_OFPST_FLOW_REQUEST:
2449     case OFPUTIL_NXST_FLOW_REQUEST:
2450         return handle_flow_stats_request(ofconn, msg->data);
2451
2452     case OFPUTIL_OFPST_AGGREGATE_REQUEST:
2453     case OFPUTIL_NXST_AGGREGATE_REQUEST:
2454         return handle_aggregate_stats_request(ofconn, msg->data);
2455
2456     case OFPUTIL_OFPST_TABLE_REQUEST:
2457         return handle_table_stats_request(ofconn, msg->data);
2458
2459     case OFPUTIL_OFPST_PORT_REQUEST:
2460         return handle_port_stats_request(ofconn, msg->data);
2461
2462     case OFPUTIL_OFPST_QUEUE_REQUEST:
2463         return handle_queue_stats_request(ofconn, msg->data);
2464
2465     case OFPUTIL_INVALID:
2466     case OFPUTIL_OFPT_HELLO:
2467     case OFPUTIL_OFPT_ERROR:
2468     case OFPUTIL_OFPT_FEATURES_REPLY:
2469     case OFPUTIL_OFPT_GET_CONFIG_REPLY:
2470     case OFPUTIL_OFPT_PACKET_IN:
2471     case OFPUTIL_OFPT_FLOW_REMOVED:
2472     case OFPUTIL_OFPT_PORT_STATUS:
2473     case OFPUTIL_OFPT_BARRIER_REPLY:
2474     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REQUEST:
2475     case OFPUTIL_OFPT_QUEUE_GET_CONFIG_REPLY:
2476     case OFPUTIL_OFPST_DESC_REPLY:
2477     case OFPUTIL_OFPST_FLOW_REPLY:
2478     case OFPUTIL_OFPST_QUEUE_REPLY:
2479     case OFPUTIL_OFPST_PORT_REPLY:
2480     case OFPUTIL_OFPST_TABLE_REPLY:
2481     case OFPUTIL_OFPST_AGGREGATE_REPLY:
2482     case OFPUTIL_NXT_ROLE_REPLY:
2483     case OFPUTIL_NXT_FLOW_REMOVED:
2484     case OFPUTIL_NXST_FLOW_REPLY:
2485     case OFPUTIL_NXST_AGGREGATE_REPLY:
2486     default:
2487         if (VLOG_IS_WARN_ENABLED()) {
2488             char *s = ofp_to_string(oh, ntohs(oh->length), 2);
2489             VLOG_DBG_RL(&rl, "OpenFlow message ignored: %s", s);
2490             free(s);
2491         }
2492         if (oh->type == OFPT_STATS_REQUEST || oh->type == OFPT_STATS_REPLY) {
2493             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_STAT);
2494         } else {
2495             return ofp_mkerr(OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE);
2496         }
2497     }
2498 }
2499
2500 static void
2501 handle_openflow(struct ofconn *ofconn, struct ofpbuf *ofp_msg)
2502 {
2503     int error = handle_openflow__(ofconn, ofp_msg);
2504     if (error) {
2505         ofconn_send_error(ofconn, ofp_msg->data, error);
2506     }
2507     COVERAGE_INC(ofproto_recv_openflow);
2508 }
2509 \f
2510 static uint64_t
2511 pick_datapath_id(const struct ofproto *ofproto)
2512 {
2513     const struct ofport *port;
2514
2515     port = ofproto_get_port(ofproto, OFPP_LOCAL);
2516     if (port) {
2517         uint8_t ea[ETH_ADDR_LEN];
2518         int error;
2519
2520         error = netdev_get_etheraddr(port->netdev, ea);
2521         if (!error) {
2522             return eth_addr_to_uint64(ea);
2523         }
2524         VLOG_WARN("could not get MAC address for %s (%s)",
2525                   netdev_get_name(port->netdev), strerror(error));
2526     }
2527     return ofproto->fallback_dpid;
2528 }
2529
2530 static uint64_t
2531 pick_fallback_dpid(void)
2532 {
2533     uint8_t ea[ETH_ADDR_LEN];
2534     eth_addr_nicira_random(ea);
2535     return eth_addr_to_uint64(ea);
2536 }
2537 \f
2538 /* unixctl commands. */
2539
2540 struct ofproto *
2541 ofproto_lookup(const char *name)
2542 {
2543     struct ofproto *ofproto;
2544
2545     HMAP_FOR_EACH_WITH_HASH (ofproto, hmap_node, hash_string(name, 0),
2546                              &all_ofprotos) {
2547         if (!strcmp(ofproto->name, name)) {
2548             return ofproto;
2549         }
2550     }
2551     return NULL;
2552 }
2553
2554 static void
2555 ofproto_unixctl_list(struct unixctl_conn *conn, const char *arg OVS_UNUSED,
2556                      void *aux OVS_UNUSED)
2557 {
2558     struct ofproto *ofproto;
2559     struct ds results;
2560
2561     ds_init(&results);
2562     HMAP_FOR_EACH (ofproto, hmap_node, &all_ofprotos) {
2563         ds_put_format(&results, "%s\n", ofproto->name);
2564     }
2565     unixctl_command_reply(conn, 200, ds_cstr(&results));
2566     ds_destroy(&results);
2567 }
2568
2569 static void
2570 ofproto_unixctl_init(void)
2571 {
2572     static bool registered;
2573     if (registered) {
2574         return;
2575     }
2576     registered = true;
2577
2578     unixctl_command_register("ofproto/list", ofproto_unixctl_list, NULL);
2579 }