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