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