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