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