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