Add reminder comment to lib/learning-switch.c.
[sliver-openvswitch.git] / udatapath / datapath.c
1 /* Copyright (c) 2008 The Board of Trustees of The Leland Stanford
2  * Junior University
3  * 
4  * We are making the OpenFlow specification and associated documentation
5  * (Software) available for public use and benefit with the expectation
6  * that others will use, modify and enhance the Software and contribute
7  * those enhancements back to the community. However, since we would
8  * like to make the Software available for broadest use, with as few
9  * restrictions as possible permission is hereby granted, free of
10  * charge, to any person obtaining a copy of this Software to deal in
11  * the Software under the copyrights without restriction, including
12  * without limitation the rights to use, copy, modify, merge, publish,
13  * distribute, sublicense, and/or sell copies of the Software, and to
14  * permit persons to whom the Software is furnished to do so, subject to
15  * the following conditions:
16  * 
17  * The above copyright notice and this permission notice shall be
18  * included in all copies or substantial portions of the Software.
19  * 
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
21  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
23  * NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
24  * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
25  * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
26  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
27  * SOFTWARE.
28  * 
29  * The name and trademarks of copyright holder(s) may NOT be used in
30  * advertising or publicity pertaining to the Software or any
31  * derivatives without specific, written prior permission.
32  */
33
34 #include "datapath.h"
35 #include <arpa/inet.h>
36 #include <assert.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include "chain.h"
42 #include "csum.h"
43 #include "flow.h"
44 #include "list.h"
45 #include "netdev.h"
46 #include "ofpbuf.h"
47 #include "openflow/openflow.h"
48 #include "packets.h"
49 #include "poll-loop.h"
50 #include "rconn.h"
51 #include "stp.h"
52 #include "switch-flow.h"
53 #include "table.h"
54 #include "timeval.h"
55 #include "vconn.h"
56 #include "xtoxll.h"
57 #include "dp_act.h"
58
59 #define THIS_MODULE VLM_datapath
60 #include "vlog.h"
61
62 extern char mfr_desc;
63 extern char hw_desc;
64 extern char sw_desc;
65 extern char serial_num;
66
67 /* Capabilities supported by this implementation. */
68 #define OFP_SUPPORTED_CAPABILITIES ( OFPC_FLOW_STATS \
69         | OFPC_TABLE_STATS \
70         | OFPC_PORT_STATS \
71         | OFPC_MULTI_PHY_TX )
72
73 /* Actions supported by this implementation. */
74 #define OFP_SUPPORTED_ACTIONS ( (1 << OFPAT_OUTPUT)         \
75                                 | (1 << OFPAT_SET_VLAN_VID) \
76                                 | (1 << OFPAT_SET_VLAN_PCP) \
77                                 | (1 << OFPAT_STRIP_VLAN)   \
78                                 | (1 << OFPAT_SET_DL_SRC)   \
79                                 | (1 << OFPAT_SET_DL_DST)   \
80                                 | (1 << OFPAT_SET_NW_SRC)   \
81                                 | (1 << OFPAT_SET_NW_DST)   \
82                                 | (1 << OFPAT_SET_TP_SRC)   \
83                                 | (1 << OFPAT_SET_TP_DST) )
84
85 struct sw_port {
86     uint32_t config;            /* Some subset of OFPPC_* flags. */
87     uint32_t state;             /* Some subset of OFPPS_* flags. */
88     struct datapath *dp;
89     struct netdev *netdev;
90     struct list node; /* Element in datapath.ports. */
91     unsigned long long int rx_packets, tx_packets;
92     unsigned long long int rx_bytes, tx_bytes;
93     unsigned long long int tx_dropped;
94     uint16_t port_no;
95 };
96
97 /* The origin of a received OpenFlow message, to enable sending a reply. */
98 struct sender {
99     struct remote *remote;      /* The device that sent the message. */
100     uint32_t xid;               /* The OpenFlow transaction ID. */
101 };
102
103 /* A connection to a secure channel. */
104 struct remote {
105     struct list node;
106     struct rconn *rconn;
107 #define TXQ_LIMIT 128           /* Max number of packets to queue for tx. */
108     int n_txq;                  /* Number of packets queued for tx on rconn. */
109
110     /* Support for reliable, multi-message replies to requests.
111      *
112      * If an incoming request needs to have a reliable reply that might
113      * require multiple messages, it can use remote_start_dump() to set up
114      * a callback that will be called as buffer space for replies. */
115     int (*cb_dump)(struct datapath *, void *aux);
116     void (*cb_done)(void *aux);
117     void *cb_aux;
118 };
119
120 #define DP_MAX_PORTS 255
121 BUILD_ASSERT_DECL(DP_MAX_PORTS <= OFPP_MAX);
122
123 struct datapath {
124     /* Remote connections. */
125     struct list remotes;        /* All connections (including controller). */
126
127     /* Listeners. */
128     struct pvconn **listeners;
129     size_t n_listeners;
130
131     time_t last_timeout;
132
133     /* Unique identifier for this datapath */
134     uint64_t  id;
135
136     struct sw_chain *chain;  /* Forwarding rules. */
137
138     /* Configuration set from controller. */
139     uint16_t flags;
140     uint16_t miss_send_len;
141
142     /* Switch ports. */
143     struct sw_port ports[DP_MAX_PORTS];
144     struct sw_port *local_port;  /* OFPP_LOCAL port, if any. */
145     struct list port_list; /* All ports, including local_port. */
146 };
147
148 static struct vlog_rate_limit rl = VLOG_RATE_LIMIT_INIT(60, 60);
149
150 static struct remote *remote_create(struct datapath *, struct rconn *);
151 static void remote_run(struct datapath *, struct remote *);
152 static void remote_wait(struct remote *);
153 static void remote_destroy(struct remote *);
154
155 static void update_port_flags(struct datapath *, const struct ofp_port_mod *);
156 static void send_flow_expired(struct datapath *, struct sw_flow *,
157                               enum ofp_flow_expired_reason);
158 static int update_port_status(struct sw_port *p);
159 static void send_port_status(struct sw_port *p, uint8_t status);
160 static void del_switch_port(struct sw_port *p);
161
162 /* Buffers are identified by a 31-bit opaque ID.  We divide the ID
163  * into a buffer number (low bits) and a cookie (high bits).  The buffer number
164  * is an index into an array of buffers.  The cookie distinguishes between
165  * different packets that have occupied a single buffer.  Thus, the more
166  * buffers we have, the lower-quality the cookie... */
167 #define PKT_BUFFER_BITS 8
168 #define N_PKT_BUFFERS (1 << PKT_BUFFER_BITS)
169 #define PKT_BUFFER_MASK (N_PKT_BUFFERS - 1)
170
171 #define PKT_COOKIE_BITS (32 - PKT_BUFFER_BITS)
172
173 int run_flow_through_tables(struct datapath *, struct ofpbuf *,
174                             struct sw_port *);
175 void fwd_port_input(struct datapath *, struct ofpbuf *, struct sw_port *);
176 int fwd_control_input(struct datapath *, const struct sender *,
177                       const void *, size_t);
178
179 uint32_t save_buffer(struct ofpbuf *);
180 static struct ofpbuf *retrieve_buffer(uint32_t id);
181 static void discard_buffer(uint32_t id);
182
183 static struct sw_port *
184 lookup_port(struct datapath *dp, uint16_t port_no) 
185 {
186     return (port_no < DP_MAX_PORTS ? &dp->ports[port_no]
187             : port_no == OFPP_LOCAL ? dp->local_port
188             : NULL);
189 }
190
191 /* Generates and returns a random datapath id. */
192 static uint64_t
193 gen_datapath_id(void)
194 {
195     uint8_t ea[ETH_ADDR_LEN];
196     eth_addr_random(ea);
197     ea[0] = 0x00;               /* Set Nicira OUI. */
198     ea[1] = 0x23;
199     ea[2] = 0x20;
200     return eth_addr_to_uint64(ea);
201 }
202
203 int
204 dp_new(struct datapath **dp_, uint64_t dpid)
205 {
206     struct datapath *dp;
207
208     dp = calloc(1, sizeof *dp);
209     if (!dp) {
210         return ENOMEM;
211     }
212
213     dp->last_timeout = time_now();
214     list_init(&dp->remotes);
215     dp->listeners = NULL;
216     dp->n_listeners = 0;
217     dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
218     dp->chain = chain_create();
219     if (!dp->chain) {
220         VLOG_ERR("could not create chain");
221         free(dp);
222         return ENOMEM;
223     }
224
225     list_init(&dp->port_list);
226     dp->flags = 0;
227     dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
228     *dp_ = dp;
229     return 0;
230 }
231
232 static int
233 new_port(struct datapath *dp, struct sw_port *port, uint16_t port_no,
234          const char *netdev_name, const uint8_t *new_mac)
235 {
236     struct netdev *netdev;
237     struct in6_addr in6;
238     struct in_addr in4;
239     int error;
240
241     error = netdev_open(netdev_name, NETDEV_ETH_TYPE_ANY, &netdev);
242     if (error) {
243         return error;
244     }
245     if (new_mac && !eth_addr_equals(netdev_get_etheraddr(netdev), new_mac)) {
246         /* Generally the device has to be down before we change its hardware
247          * address.  Don't bother to check for an error because it's really
248          * the netdev_set_etheraddr() call below that we care about. */
249         netdev_set_flags(netdev, 0, false);
250         error = netdev_set_etheraddr(netdev, new_mac);
251         if (error) {
252             VLOG_WARN("failed to change %s Ethernet address "
253                       "to "ETH_ADDR_FMT": %s",
254                       netdev_name, ETH_ADDR_ARGS(new_mac), strerror(error));
255         }
256     }
257     error = netdev_set_flags(netdev, NETDEV_UP | NETDEV_PROMISC, false);
258     if (error) {
259         VLOG_ERR("failed to set promiscuous mode on %s device", netdev_name);
260         netdev_close(netdev);
261         return error;
262     }
263     if (netdev_get_in4(netdev, &in4)) {
264         VLOG_ERR("%s device has assigned IP address %s",
265                  netdev_name, inet_ntoa(in4));
266     }
267     if (netdev_get_in6(netdev, &in6)) {
268         char in6_name[INET6_ADDRSTRLEN + 1];
269         inet_ntop(AF_INET6, &in6, in6_name, sizeof in6_name);
270         VLOG_ERR("%s device has assigned IPv6 address %s",
271                  netdev_name, in6_name);
272     }
273
274     memset(port, '\0', sizeof *port);
275
276     port->dp = dp;
277     port->netdev = netdev;
278     port->port_no = port_no;
279     list_push_back(&dp->port_list, &port->node);
280
281     /* Notify the ctlpath that this port has been added */
282     send_port_status(port, OFPPR_ADD);
283
284     return 0;
285 }
286
287 int
288 dp_add_port(struct datapath *dp, const char *netdev)
289 {
290     int port_no;
291     for (port_no = 0; port_no < DP_MAX_PORTS; port_no++) {
292         struct sw_port *port = &dp->ports[port_no];
293         if (!port->netdev) {
294             return new_port(dp, port, port_no, netdev, NULL);
295         }
296     }
297     return EXFULL;
298 }
299
300 int
301 dp_add_local_port(struct datapath *dp, const char *netdev) 
302 {
303     if (!dp->local_port) {
304         uint8_t ea[ETH_ADDR_LEN];
305         struct sw_port *port;
306         int error;
307
308         port = xcalloc(1, sizeof *port);
309         eth_addr_from_uint64(dp->id, ea);
310         error = new_port(dp, port, OFPP_LOCAL, netdev, ea);
311         if (!error) {
312             dp->local_port = port;
313         } else {
314             free(port);
315         }
316         return error;
317     } else {
318         return EXFULL;
319     }
320 }
321
322 void
323 dp_add_pvconn(struct datapath *dp, struct pvconn *pvconn)
324 {
325     dp->listeners = xrealloc(dp->listeners,
326                              sizeof *dp->listeners * (dp->n_listeners + 1));
327     dp->listeners[dp->n_listeners++] = pvconn;
328 }
329
330 void
331 dp_run(struct datapath *dp)
332 {
333     time_t now = time_now();
334     struct sw_port *p, *pn;
335     struct remote *r, *rn;
336     struct ofpbuf *buffer = NULL;
337     size_t i;
338
339     if (now != dp->last_timeout) {
340         struct list deleted = LIST_INITIALIZER(&deleted);
341         struct sw_flow *f, *n;
342
343         LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
344             if (update_port_status(p)) {
345                 send_port_status(p, OFPPR_MODIFY);
346             }
347         }
348
349         chain_timeout(dp->chain, &deleted);
350         LIST_FOR_EACH_SAFE (f, n, struct sw_flow, node, &deleted) {
351             send_flow_expired(dp, f, f->reason);
352             list_remove(&f->node);
353             flow_free(f);
354         }
355         dp->last_timeout = now;
356     }
357     poll_timer_wait(1000);
358     
359     LIST_FOR_EACH_SAFE (p, pn, struct sw_port, node, &dp->port_list) {
360         int error;
361
362         if (!buffer) {
363             /* Allocate buffer with some headroom to add headers in forwarding
364              * to the controller or adding a vlan tag, plus an extra 2 bytes to
365              * allow IP headers to be aligned on a 4-byte boundary.  */
366             const int headroom = 128 + 2;
367             const int hard_header = VLAN_ETH_HEADER_LEN;
368             const int mtu = netdev_get_mtu(p->netdev);
369             buffer = ofpbuf_new(headroom + hard_header + mtu);
370             buffer->data = (char*)buffer->data + headroom;
371         }
372         error = netdev_recv(p->netdev, buffer);
373         if (!error) {
374             p->rx_packets++;
375             p->rx_bytes += buffer->size;
376             fwd_port_input(dp, buffer, p);
377             buffer = NULL;
378         } else if (error != EAGAIN) {
379             VLOG_ERR_RL(&rl, "error receiving data from %s: %s",
380                         netdev_get_name(p->netdev), strerror(error));
381         }
382     }
383     ofpbuf_delete(buffer);
384
385     /* Talk to remotes. */
386     LIST_FOR_EACH_SAFE (r, rn, struct remote, node, &dp->remotes) {
387         remote_run(dp, r);
388     }
389
390     for (i = 0; i < dp->n_listeners; ) {
391         struct pvconn *pvconn = dp->listeners[i];
392         struct vconn *new_vconn;
393         int retval = pvconn_accept(pvconn, OFP_VERSION, &new_vconn);
394         if (!retval) {
395             remote_create(dp, rconn_new_from_vconn("passive", new_vconn));
396         } else if (retval != EAGAIN) {
397             VLOG_WARN_RL(&rl, "accept failed (%s)", strerror(retval));
398             dp->listeners[i] = dp->listeners[--dp->n_listeners];
399             continue;
400         }
401         i++;
402     }
403 }
404
405 static void
406 remote_run(struct datapath *dp, struct remote *r)
407 {
408     int i;
409
410     rconn_run(r->rconn);
411
412     /* Do some remote processing, but cap it at a reasonable amount so that
413      * other processing doesn't starve. */
414     for (i = 0; i < 50; i++) {
415         if (!r->cb_dump) {
416             struct ofpbuf *buffer;
417             struct ofp_header *oh;
418
419             buffer = rconn_recv(r->rconn);
420             if (!buffer) {
421                 break;
422             }
423
424             if (buffer->size >= sizeof *oh) {
425                 struct sender sender;
426
427                 oh = buffer->data;
428                 sender.remote = r;
429                 sender.xid = oh->xid;
430                 fwd_control_input(dp, &sender, buffer->data, buffer->size);
431             } else {
432                 VLOG_WARN_RL(&rl, "received too-short OpenFlow message");
433             }
434             ofpbuf_delete(buffer); 
435         } else {
436             if (r->n_txq < TXQ_LIMIT) {
437                 int error = r->cb_dump(dp, r->cb_aux);
438                 if (error <= 0) {
439                     if (error) {
440                         VLOG_WARN_RL(&rl, "dump callback error: %s",
441                                      strerror(-error));
442                     }
443                     r->cb_done(r->cb_aux);
444                     r->cb_dump = NULL;
445                 }
446             } else {
447                 break;
448             }
449         }
450     }
451
452     if (!rconn_is_alive(r->rconn)) {
453         remote_destroy(r);
454     }
455 }
456
457 static void
458 remote_wait(struct remote *r) 
459 {
460     rconn_run_wait(r->rconn);
461     rconn_recv_wait(r->rconn);
462 }
463
464 static void
465 remote_destroy(struct remote *r)
466 {
467     if (r) {
468         if (r->cb_dump && r->cb_done) {
469             r->cb_done(r->cb_aux);
470         }
471         list_remove(&r->node);
472         rconn_destroy(r->rconn);
473         free(r);
474     }
475 }
476
477 static struct remote *
478 remote_create(struct datapath *dp, struct rconn *rconn) 
479 {
480     struct remote *remote = xmalloc(sizeof *remote);
481     list_push_back(&dp->remotes, &remote->node);
482     remote->rconn = rconn;
483     remote->cb_dump = NULL;
484     remote->n_txq = 0;
485     return remote;
486 }
487
488 /* Starts a callback-based, reliable, possibly multi-message reply to a
489  * request made by 'remote'.
490  *
491  * 'dump' designates a function that will be called when the 'remote' send
492  * queue has an empty slot.  It should compose a message and send it on
493  * 'remote'.  On success, it should return 1 if it should be called again when
494  * another send queue slot opens up, 0 if its transmissions are complete, or a
495  * negative errno value on failure.
496  *
497  * 'done' designates a function to clean up any resources allocated for the
498  * dump.  It must handle being called before the dump is complete (which will
499  * happen if 'remote' is closed unexpectedly).
500  *
501  * 'aux' is passed to 'dump' and 'done'. */
502 static void
503 remote_start_dump(struct remote *remote,
504                   int (*dump)(struct datapath *, void *),
505                   void (*done)(void *),
506                   void *aux) 
507 {
508     assert(!remote->cb_dump);
509     remote->cb_dump = dump;
510     remote->cb_done = done;
511     remote->cb_aux = aux;
512 }
513
514 void
515 dp_wait(struct datapath *dp) 
516 {
517     struct sw_port *p;
518     struct remote *r;
519     size_t i;
520
521     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
522         netdev_recv_wait(p->netdev);
523     }
524     LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
525         remote_wait(r);
526     }
527     for (i = 0; i < dp->n_listeners; i++) {
528         pvconn_wait(dp->listeners[i]);
529     }
530 }
531
532 /* Delete 'p' from switch. */
533 static void
534 del_switch_port(struct sw_port *p)
535 {
536     send_port_status(p, OFPPR_DELETE);
537     netdev_close(p->netdev);
538     p->netdev = NULL;
539     list_remove(&p->node);
540 }
541
542 void
543 dp_destroy(struct datapath *dp)
544 {
545     struct sw_port *p, *n;
546
547     if (!dp) {
548         return;
549     }
550
551     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
552         del_switch_port(p); 
553     }
554     chain_destroy(dp->chain);
555     free(dp);
556 }
557
558 /* Send packets out all the ports except the originating one.  If the
559  * "flood" argument is set, don't send out ports with flooding disabled.
560  */
561 static int
562 output_all(struct datapath *dp, struct ofpbuf *buffer, int in_port, int flood)
563 {
564     struct sw_port *p;
565     int prev_port;
566
567     prev_port = -1;
568     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
569         if (p->port_no == in_port) {
570             continue;
571         }
572         if (flood && p->config & OFPPC_NO_FLOOD) {
573             continue;
574         }
575         if (prev_port != -1) {
576             dp_output_port(dp, ofpbuf_clone(buffer), in_port, prev_port,
577                            false);
578         }
579         prev_port = p->port_no;
580     }
581     if (prev_port != -1)
582         dp_output_port(dp, buffer, in_port, prev_port, false);
583     else
584         ofpbuf_delete(buffer);
585
586     return 0;
587 }
588
589 void
590 output_packet(struct datapath *dp, struct ofpbuf *buffer, uint16_t out_port) 
591 {
592     struct sw_port *p = lookup_port(dp, out_port);
593     if (p && p->netdev != NULL) {
594         if (!(p->config & OFPPC_PORT_DOWN)) {
595             if (!netdev_send(p->netdev, buffer)) {
596                 p->tx_packets++;
597                 p->tx_bytes += buffer->size;
598             } else {
599                 p->tx_dropped++;
600             }
601         }
602         ofpbuf_delete(buffer);
603         return;
604     }
605
606     ofpbuf_delete(buffer);
607     VLOG_DBG_RL(&rl, "can't forward to bad port %d\n", out_port);
608 }
609
610 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
611  */
612 void
613 dp_output_port(struct datapath *dp, struct ofpbuf *buffer,
614                int in_port, int out_port, bool ignore_no_fwd)
615 {
616
617     assert(buffer);
618     switch (out_port) {
619     case OFPP_IN_PORT:
620         output_packet(dp, buffer, in_port);
621         break;
622
623     case OFPP_TABLE: {
624         struct sw_port *p = lookup_port(dp, in_port);
625                 if (run_flow_through_tables(dp, buffer, p)) {
626                         ofpbuf_delete(buffer);
627         }
628         break;
629     }
630
631     case OFPP_FLOOD:
632         output_all(dp, buffer, in_port, 1);
633         break;
634
635     case OFPP_ALL:
636         output_all(dp, buffer, in_port, 0);
637         break;
638
639     case OFPP_CONTROLLER:
640         dp_output_control(dp, buffer, in_port, 0, OFPR_ACTION);
641         break;
642
643     case OFPP_LOCAL:
644     default:
645         if (in_port == out_port) {
646             VLOG_DBG_RL(&rl, "can't directly forward to input port");
647             return;
648         }
649         output_packet(dp, buffer, out_port);
650         break;
651     }
652 }
653
654 static void *
655 make_openflow_reply(size_t openflow_len, uint8_t type,
656                     const struct sender *sender, struct ofpbuf **bufferp)
657 {
658     return make_openflow_xid(openflow_len, type, sender ? sender->xid : 0,
659                              bufferp);
660 }
661
662 static int
663 send_openflow_buffer_to_remote(struct ofpbuf *buffer, struct remote *remote)
664 {
665     int retval = rconn_send_with_limit(remote->rconn, buffer, &remote->n_txq,
666                                        TXQ_LIMIT);
667     if (retval) {
668         VLOG_WARN_RL(&rl, "send to %s failed: %s",
669                      rconn_get_name(remote->rconn), strerror(retval));
670     }
671     return retval;
672 }
673
674 static int
675 send_openflow_buffer(struct datapath *dp, struct ofpbuf *buffer,
676                      const struct sender *sender)
677 {
678     update_openflow_length(buffer);
679     if (sender) {
680         /* Send back to the sender. */
681         return send_openflow_buffer_to_remote(buffer, sender->remote);
682     } else {
683         /* Broadcast to all remotes. */
684         struct remote *r, *prev = NULL;
685         LIST_FOR_EACH (r, struct remote, node, &dp->remotes) {
686             if (prev) {
687                 send_openflow_buffer_to_remote(ofpbuf_clone(buffer), prev);
688             }
689             prev = r;
690         }
691         if (prev) {
692             send_openflow_buffer_to_remote(buffer, prev);
693         } else {
694             ofpbuf_delete(buffer);
695         }
696         return 0;
697     }
698 }
699
700 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller.  If the
701  * packet can be saved in a buffer, then only the first max_len bytes of
702  * 'buffer' are sent; otherwise, all of 'buffer' is sent.  'reason' indicates
703  * why 'buffer' is being sent. 'max_len' sets the maximum number of bytes that
704  * the caller wants to be sent; a value of 0 indicates the entire packet should
705  * be sent. */
706 void
707 dp_output_control(struct datapath *dp, struct ofpbuf *buffer, int in_port,
708                   size_t max_len, int reason)
709 {
710     struct ofp_packet_in *opi;
711     size_t total_len;
712     uint32_t buffer_id;
713
714     buffer_id = save_buffer(buffer);
715     total_len = buffer->size;
716     if (buffer_id != UINT32_MAX && max_len && buffer->size > max_len) {
717         buffer->size = max_len;
718     }
719
720     opi = ofpbuf_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
721     opi->header.version = OFP_VERSION;
722     opi->header.type    = OFPT_PACKET_IN;
723     opi->header.length  = htons(buffer->size);
724     opi->header.xid     = htonl(0);
725     opi->buffer_id      = htonl(buffer_id);
726     opi->total_len      = htons(total_len);
727     opi->in_port        = htons(in_port);
728     opi->reason         = reason;
729     opi->pad            = 0;
730     send_openflow_buffer(dp, buffer, NULL);
731 }
732
733 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
734                            struct ofp_phy_port *desc)
735 {
736     desc->port_no = htons(p->port_no);
737     strncpy((char *) desc->name, netdev_get_name(p->netdev),
738             sizeof desc->name);
739     desc->name[sizeof desc->name - 1] = '\0';
740     memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
741     desc->config = htonl(p->config);
742     desc->state = htonl(p->state);
743     desc->curr = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_CURRENT));
744     desc->supported = htonl(netdev_get_features(p->netdev, 
745                 NETDEV_FEAT_SUPPORTED));
746     desc->advertised = htonl(netdev_get_features(p->netdev, 
747                 NETDEV_FEAT_ADVERTISED));
748     desc->peer = htonl(netdev_get_features(p->netdev, NETDEV_FEAT_PEER));
749 }
750
751 static void
752 dp_send_features_reply(struct datapath *dp, const struct sender *sender)
753 {
754     struct ofpbuf *buffer;
755     struct ofp_switch_features *ofr;
756     struct sw_port *p;
757
758     ofr = make_openflow_reply(sizeof *ofr, OFPT_FEATURES_REPLY,
759                                sender, &buffer);
760     ofr->datapath_id  = htonll(dp->id); 
761     ofr->n_tables     = dp->chain->n_tables;
762     ofr->n_buffers    = htonl(N_PKT_BUFFERS);
763     ofr->capabilities = htonl(OFP_SUPPORTED_CAPABILITIES);
764     ofr->actions      = htonl(OFP_SUPPORTED_ACTIONS);
765     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
766         struct ofp_phy_port *opp = ofpbuf_put_uninit(buffer, sizeof *opp);
767         memset(opp, 0, sizeof *opp);
768         fill_port_desc(dp, p, opp);
769     }
770     send_openflow_buffer(dp, buffer, sender);
771 }
772
773 void
774 update_port_flags(struct datapath *dp, const struct ofp_port_mod *opm)
775 {
776     struct sw_port *p = lookup_port(dp, ntohs(opm->port_no));
777
778     /* Make sure the port id hasn't changed since this was sent */
779     if (!p || memcmp(opm->hw_addr, netdev_get_etheraddr(p->netdev),
780                      ETH_ADDR_LEN) != 0) {
781         return;
782     }
783
784
785     if (opm->mask) {
786         uint32_t config_mask = ntohl(opm->mask);
787         p->config &= ~config_mask;
788         p->config |= ntohl(opm->config) & config_mask;
789     }
790
791     if (opm->mask & htonl(OFPPC_PORT_DOWN)) {
792         if ((opm->config & htonl(OFPPC_PORT_DOWN))
793             && (p->config & OFPPC_PORT_DOWN) == 0) {
794             p->config |= OFPPC_PORT_DOWN;
795             netdev_turn_flags_off(p->netdev, NETDEV_UP, true);
796         } else if ((opm->config & htonl(OFPPC_PORT_DOWN)) == 0
797                    && (p->config & OFPPC_PORT_DOWN)) {
798             p->config &= ~OFPPC_PORT_DOWN;
799             netdev_turn_flags_on(p->netdev, NETDEV_UP, true);
800         }
801     }
802 }
803
804 /* Update the port status field of the bridge port.  A non-zero return
805  * value indicates some field has changed. 
806  *
807  * NB: Callers of this function may hold the RCU read lock, so any
808  * additional checks must not sleep.
809  */
810 static int
811 update_port_status(struct sw_port *p)
812 {
813     int retval;
814     enum netdev_flags flags;
815     uint32_t orig_config = p->config;
816     uint32_t orig_state = p->state;
817
818     if (netdev_get_flags(p->netdev, &flags) < 0) {
819         VLOG_WARN_RL(&rl, "could not get netdev flags for %s", 
820                      netdev_get_name(p->netdev));
821         return 0;
822     } else {
823         if (flags & NETDEV_UP) {
824             p->config &= ~OFPPC_PORT_DOWN;
825         } else {
826             p->config |= OFPPC_PORT_DOWN;
827         } 
828     }
829
830     /* Not all cards support this getting link status, so don't warn on
831      * error. */
832     retval = netdev_get_link_status(p->netdev);
833     if (retval == 1) {
834         p->state &= ~OFPPS_LINK_DOWN;
835     } else if (retval == 0) {
836         p->state |= OFPPS_LINK_DOWN;
837     } 
838
839     return ((orig_config != p->config) || (orig_state != p->state));
840 }
841
842 static void
843 send_port_status(struct sw_port *p, uint8_t status) 
844 {
845     struct ofpbuf *buffer;
846     struct ofp_port_status *ops;
847     ops = make_openflow_xid(sizeof *ops, OFPT_PORT_STATUS, 0, &buffer);
848     ops->reason = status;
849     memset(ops->pad, 0, sizeof ops->pad);
850     fill_port_desc(p->dp, p, &ops->desc);
851
852     send_openflow_buffer(p->dp, buffer, NULL);
853 }
854
855 void
856 send_flow_expired(struct datapath *dp, struct sw_flow *flow,
857                   enum ofp_flow_expired_reason reason)
858 {
859     struct ofpbuf *buffer;
860     struct ofp_flow_expired *ofe;
861     ofe = make_openflow_xid(sizeof *ofe, OFPT_FLOW_EXPIRED, 0, &buffer);
862     flow_fill_match(&ofe->match, &flow->key);
863
864     ofe->priority = htons(flow->priority);
865     ofe->reason = reason;
866     memset(ofe->pad, 0, sizeof ofe->pad);
867
868     ofe->duration     = htonl(time_now() - flow->created);
869     memset(ofe->pad2, 0, sizeof ofe->pad2);
870     ofe->packet_count = htonll(flow->packet_count);
871     ofe->byte_count   = htonll(flow->byte_count);
872     send_openflow_buffer(dp, buffer, NULL);
873 }
874
875 void
876 dp_send_error_msg(struct datapath *dp, const struct sender *sender,
877                   uint16_t type, uint16_t code, const void *data, size_t len)
878 {
879     struct ofpbuf *buffer;
880     struct ofp_error_msg *oem;
881     oem = make_openflow_reply(sizeof(*oem)+len, OFPT_ERROR, sender, &buffer);
882     oem->type = htons(type);
883     oem->code = htons(code);
884     memcpy(oem->data, data, len);
885     send_openflow_buffer(dp, buffer, sender);
886 }
887
888 static void
889 fill_flow_stats(struct ofpbuf *buffer, struct sw_flow *flow,
890                 int table_idx, time_t now)
891 {
892     struct ofp_flow_stats *ofs;
893     int length = sizeof *ofs + flow->sf_acts->actions_len;
894     ofs = ofpbuf_put_uninit(buffer, length);
895     ofs->length          = htons(length);
896     ofs->table_id        = table_idx;
897     ofs->pad             = 0;
898     ofs->match.wildcards = htonl(flow->key.wildcards);
899     ofs->match.in_port   = flow->key.flow.in_port;
900     memcpy(ofs->match.dl_src, flow->key.flow.dl_src, ETH_ADDR_LEN);
901     memcpy(ofs->match.dl_dst, flow->key.flow.dl_dst, ETH_ADDR_LEN);
902     ofs->match.dl_vlan   = flow->key.flow.dl_vlan;
903     ofs->match.dl_type   = flow->key.flow.dl_type;
904     ofs->match.nw_src    = flow->key.flow.nw_src;
905     ofs->match.nw_dst    = flow->key.flow.nw_dst;
906     ofs->match.nw_proto  = flow->key.flow.nw_proto;
907     ofs->match.pad       = 0;
908     ofs->match.tp_src    = flow->key.flow.tp_src;
909     ofs->match.tp_dst    = flow->key.flow.tp_dst;
910     ofs->duration        = htonl(now - flow->created);
911     ofs->priority        = htons(flow->priority);
912     ofs->idle_timeout    = htons(flow->idle_timeout);
913     ofs->hard_timeout    = htons(flow->hard_timeout);
914     memset(ofs->pad2, 0, sizeof ofs->pad2);
915     ofs->packet_count    = htonll(flow->packet_count);
916     ofs->byte_count      = htonll(flow->byte_count);
917     memcpy(ofs->actions, flow->sf_acts->actions, flow->sf_acts->actions_len);
918 }
919
920 \f
921 /* 'buffer' was received on 'p', which may be a a physical switch port or a
922  * null pointer.  Process it according to 'dp''s flow table.  Returns 0 if
923  * successful, in which case 'buffer' is destroyed, or -ESRCH if there is no
924  * matching flow, in which case 'buffer' still belongs to the caller. */
925 int run_flow_through_tables(struct datapath *dp, struct ofpbuf *buffer,
926                             struct sw_port *p)
927 {
928     struct sw_flow_key key;
929     struct sw_flow *flow;
930
931     key.wildcards = 0;
932     if (flow_extract(buffer, p ? p->port_no : OFPP_NONE, &key.flow)
933         && (dp->flags & OFPC_FRAG_MASK) == OFPC_FRAG_DROP) {
934         /* Drop fragment. */
935         ofpbuf_delete(buffer);
936         return 0;
937     }
938         if (p && p->config & (OFPPC_NO_RECV | OFPPC_NO_RECV_STP)
939         && p->config & (!eth_addr_equals(key.flow.dl_dst, stp_eth_addr)
940                        ? OFPPC_NO_RECV : OFPPC_NO_RECV_STP)) {
941                 ofpbuf_delete(buffer);
942                 return 0;
943         }
944
945     flow = chain_lookup(dp->chain, &key);
946     if (flow != NULL) {
947         flow_used(flow, buffer);
948         execute_actions(dp, buffer, &key, flow->sf_acts->actions, 
949                         flow->sf_acts->actions_len, false);
950         return 0;
951     } else {
952         return -ESRCH;
953     }
954 }
955
956 /* 'buffer' was received on 'p', which may be a a physical switch port or a
957  * null pointer.  Process it according to 'dp''s flow table, sending it up to
958  * the controller if no flow matches.  Takes ownership of 'buffer'. */
959 void fwd_port_input(struct datapath *dp, struct ofpbuf *buffer,
960                     struct sw_port *p)
961 {
962     if (run_flow_through_tables(dp, buffer, p)) {
963         dp_output_control(dp, buffer, p->port_no,
964                           dp->miss_send_len, OFPR_NO_MATCH);
965     }
966 }
967
968 static int
969 recv_features_request(struct datapath *dp, const struct sender *sender,
970                       const void *msg) 
971 {
972     dp_send_features_reply(dp, sender);
973     return 0;
974 }
975
976 static int
977 recv_get_config_request(struct datapath *dp, const struct sender *sender,
978                         const void *msg) 
979 {
980     struct ofpbuf *buffer;
981     struct ofp_switch_config *osc;
982
983     osc = make_openflow_reply(sizeof *osc, OFPT_GET_CONFIG_REPLY,
984                               sender, &buffer);
985
986     osc->flags = htons(dp->flags);
987     osc->miss_send_len = htons(dp->miss_send_len);
988
989     return send_openflow_buffer(dp, buffer, sender);
990 }
991
992 static int
993 recv_set_config(struct datapath *dp, const struct sender *sender UNUSED,
994                 const void *msg)
995 {
996     const struct ofp_switch_config *osc = msg;
997     int flags;
998
999     flags = ntohs(osc->flags) & (OFPC_SEND_FLOW_EXP | OFPC_FRAG_MASK);
1000     if ((flags & OFPC_FRAG_MASK) != OFPC_FRAG_NORMAL
1001         && (flags & OFPC_FRAG_MASK) != OFPC_FRAG_DROP) {
1002         flags = (flags & ~OFPC_FRAG_MASK) | OFPC_FRAG_DROP;
1003     }
1004     dp->flags = flags;
1005     dp->miss_send_len = ntohs(osc->miss_send_len);
1006     return 0;
1007 }
1008
1009 static int
1010 recv_packet_out(struct datapath *dp, const struct sender *sender,
1011                 const void *msg)
1012 {
1013     const struct ofp_packet_out *opo = msg;
1014     struct sw_flow_key key;
1015     uint16_t v_code;
1016     struct ofpbuf *buffer;
1017     size_t actions_len = ntohs(opo->actions_len);
1018
1019     if (actions_len > (ntohs(opo->header.length) - sizeof *opo)) {
1020         VLOG_DBG_RL(&rl, "message too short for number of actions");
1021         return -EINVAL;
1022     }
1023
1024     if (ntohl(opo->buffer_id) == (uint32_t) -1) {
1025         /* FIXME: can we avoid copying data here? */
1026         int data_len = ntohs(opo->header.length) - sizeof *opo - actions_len;
1027         buffer = ofpbuf_new(data_len);
1028         ofpbuf_put(buffer, (uint8_t *)opo->actions + actions_len, data_len);
1029     } else {
1030         buffer = retrieve_buffer(ntohl(opo->buffer_id));
1031         if (!buffer) {
1032             return -ESRCH; 
1033         }
1034     }
1035  
1036     flow_extract(buffer, ntohs(opo->in_port), &key.flow);
1037
1038     v_code = validate_actions(dp, &key, opo->actions, actions_len);
1039     if (v_code != ACT_VALIDATION_OK) {
1040         dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
1041                   msg, ntohs(opo->header.length));
1042         goto error;
1043     }
1044
1045     execute_actions(dp, buffer, &key, opo->actions, actions_len, true);
1046
1047     return 0;
1048
1049 error:
1050     ofpbuf_delete(buffer);
1051     return -EINVAL;
1052 }
1053
1054 static int
1055 recv_port_mod(struct datapath *dp, const struct sender *sender UNUSED,
1056               const void *msg)
1057 {
1058     const struct ofp_port_mod *opm = msg;
1059
1060     update_port_flags(dp, opm);
1061
1062     return 0;
1063 }
1064
1065 static int
1066 add_flow(struct datapath *dp, const struct sender *sender,
1067         const struct ofp_flow_mod *ofm)
1068 {
1069     int error = -ENOMEM;
1070     uint16_t v_code;
1071     struct sw_flow *flow; 
1072     size_t actions_len = ntohs(ofm->header.length) - sizeof *ofm;
1073
1074     /* Allocate memory. */
1075     flow = flow_alloc(actions_len);
1076     if (flow == NULL)
1077         goto error;
1078
1079     flow_extract_match(&flow->key, &ofm->match);
1080
1081     v_code = validate_actions(dp, &flow->key, ofm->actions, actions_len);
1082     if (v_code != ACT_VALIDATION_OK) {
1083         dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
1084                   ofm, ntohs(ofm->header.length));
1085         goto error_free_flow;
1086     }
1087
1088     /* Fill out flow. */
1089     flow->priority = flow->key.wildcards ? ntohs(ofm->priority) : -1;
1090     flow->idle_timeout = ntohs(ofm->idle_timeout);
1091     flow->hard_timeout = ntohs(ofm->hard_timeout);
1092     flow->used = flow->created = time_now();
1093     flow->sf_acts->actions_len = actions_len;
1094     flow->byte_count = 0;
1095     flow->packet_count = 0;
1096     memcpy(flow->sf_acts->actions, ofm->actions, actions_len);
1097
1098     /* Act. */
1099     error = chain_insert(dp->chain, flow);
1100     if (error == -ENOBUFS) {
1101         dp_send_error_msg(dp, sender, OFPET_FLOW_MOD_FAILED, 
1102                 OFPFMFC_ALL_TABLES_FULL, ofm, ntohs(ofm->header.length));
1103         goto error_free_flow;
1104     } else if (error) {
1105         goto error_free_flow; 
1106     }
1107     error = 0;
1108     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1109         struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1110         if (buffer) {
1111             struct sw_flow_key key;
1112             uint16_t in_port = ntohs(ofm->match.in_port);
1113             flow_used(flow, buffer);
1114             flow_extract(buffer, in_port, &key.flow);
1115             execute_actions(dp, buffer, &key, 
1116                     ofm->actions, actions_len, false);
1117         } else {
1118             error = -ESRCH; 
1119         }
1120     }
1121     return error;
1122
1123 error_free_flow:
1124     flow_free(flow);
1125 error:
1126     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1127         discard_buffer(ntohl(ofm->buffer_id));
1128     return error;
1129 }
1130
1131 static int
1132 mod_flow(struct datapath *dp, const struct sender *sender,
1133         const struct ofp_flow_mod *ofm)
1134 {
1135     int error = -ENOMEM;
1136     uint16_t v_code;
1137     size_t actions_len;
1138     struct sw_flow_key key;
1139     uint16_t priority;
1140     int strict;
1141
1142     flow_extract_match(&key, &ofm->match);
1143  
1144     actions_len = ntohs(ofm->header.length) - sizeof *ofm;
1145  
1146     v_code = validate_actions(dp, &key, ofm->actions, actions_len);
1147     if (v_code != ACT_VALIDATION_OK) {
1148         dp_send_error_msg(dp, sender, OFPET_BAD_ACTION, v_code,
1149                   ofm, ntohs(ofm->header.length));
1150         goto error;
1151     }
1152
1153     priority = key.wildcards ? ntohs(ofm->priority) : -1;
1154     strict = (ofm->command == htons(OFPFC_MODIFY_STRICT)) ? 1 : 0;
1155     chain_modify(dp->chain, &key, priority, strict, ofm->actions, actions_len);
1156
1157     if (ntohl(ofm->buffer_id) != UINT32_MAX) {
1158         struct ofpbuf *buffer = retrieve_buffer(ntohl(ofm->buffer_id));
1159         if (buffer) {
1160             struct sw_flow_key skb_key;
1161             uint16_t in_port = ntohs(ofm->match.in_port);
1162             flow_extract(buffer, in_port, &skb_key.flow);
1163             execute_actions(dp, buffer, &skb_key,
1164                             ofm->actions, actions_len, false);
1165         } else {
1166             error = -ESRCH; 
1167         }
1168     }
1169     return error;
1170
1171 error:
1172     if (ntohl(ofm->buffer_id) != (uint32_t) -1)
1173         discard_buffer(ntohl(ofm->buffer_id));
1174     return error;
1175 }
1176
1177 static int
1178 recv_flow(struct datapath *dp, const struct sender *sender,
1179           const void *msg)
1180 {
1181     const struct ofp_flow_mod *ofm = msg;
1182     uint16_t command = ntohs(ofm->command);
1183
1184     if (command == OFPFC_ADD) {
1185         return add_flow(dp, sender, ofm);
1186     } else if ((command == OFPFC_MODIFY) || (command == OFPFC_MODIFY_STRICT)) {
1187         return mod_flow(dp, sender, ofm);
1188     }  else if (command == OFPFC_DELETE) {
1189         struct sw_flow_key key;
1190         flow_extract_match(&key, &ofm->match);
1191         return chain_delete(dp->chain, &key, ofm->out_port, 0, 0) ? 0 : -ESRCH;
1192     } else if (command == OFPFC_DELETE_STRICT) {
1193         struct sw_flow_key key;
1194         uint16_t priority;
1195         flow_extract_match(&key, &ofm->match);
1196         priority = key.wildcards ? ntohs(ofm->priority) : -1;
1197         return chain_delete(dp->chain, &key, ofm->out_port, 
1198                 priority, 1) ? 0 : -ESRCH;
1199     } else {
1200         return -ENODEV;
1201     }
1202 }
1203
1204 static int desc_stats_dump(struct datapath *dp, void *state,
1205                               struct ofpbuf *buffer)
1206 {
1207     struct ofp_desc_stats *ods = ofpbuf_put_uninit(buffer, sizeof *ods);
1208
1209     strncpy(ods->mfr_desc, &mfr_desc, sizeof ods->mfr_desc);
1210     strncpy(ods->hw_desc, &hw_desc, sizeof ods->hw_desc);
1211     strncpy(ods->sw_desc, &sw_desc, sizeof ods->sw_desc);
1212     strncpy(ods->serial_num, &serial_num, sizeof ods->serial_num);
1213
1214     return 0;
1215 }
1216
1217 struct flow_stats_state {
1218     int table_idx;
1219     struct sw_table_position position;
1220     struct ofp_flow_stats_request rq;
1221     time_t now;
1222
1223     struct ofpbuf *buffer;
1224 };
1225
1226 #define MAX_FLOW_STATS_BYTES 4096
1227
1228 static int flow_stats_init(struct datapath *dp, const void *body, int body_len,
1229                            void **state)
1230 {
1231     const struct ofp_flow_stats_request *fsr = body;
1232     struct flow_stats_state *s = xmalloc(sizeof *s);
1233     s->table_idx = fsr->table_id == 0xff ? 0 : fsr->table_id;
1234     memset(&s->position, 0, sizeof s->position);
1235     s->rq = *fsr;
1236     *state = s;
1237     return 0;
1238 }
1239
1240 static int flow_stats_dump_callback(struct sw_flow *flow, void *private)
1241 {
1242     struct flow_stats_state *s = private;
1243     fill_flow_stats(s->buffer, flow, s->table_idx, s->now);
1244     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1245 }
1246
1247 static int flow_stats_dump(struct datapath *dp, void *state,
1248                            struct ofpbuf *buffer)
1249 {
1250     struct flow_stats_state *s = state;
1251     struct sw_flow_key match_key;
1252
1253     flow_extract_match(&match_key, &s->rq.match);
1254     s->buffer = buffer;
1255     s->now = time_now();
1256     while (s->table_idx < dp->chain->n_tables
1257            && (s->rq.table_id == 0xff || s->rq.table_id == s->table_idx))
1258     {
1259         struct sw_table *table = dp->chain->tables[s->table_idx];
1260
1261         if (table->iterate(table, &match_key, s->rq.out_port, 
1262                     &s->position, flow_stats_dump_callback, s))
1263             break;
1264
1265         s->table_idx++;
1266         memset(&s->position, 0, sizeof s->position);
1267     }
1268     return s->buffer->size >= MAX_FLOW_STATS_BYTES;
1269 }
1270
1271 static void flow_stats_done(void *state)
1272 {
1273     free(state);
1274 }
1275
1276 struct aggregate_stats_state {
1277     struct ofp_aggregate_stats_request rq;
1278 };
1279
1280 static int aggregate_stats_init(struct datapath *dp,
1281                                 const void *body, int body_len,
1282                                 void **state)
1283 {
1284     const struct ofp_aggregate_stats_request *rq = body;
1285     struct aggregate_stats_state *s = xmalloc(sizeof *s);
1286     s->rq = *rq;
1287     *state = s;
1288     return 0;
1289 }
1290
1291 static int aggregate_stats_dump_callback(struct sw_flow *flow, void *private)
1292 {
1293     struct ofp_aggregate_stats_reply *rpy = private;
1294     rpy->packet_count += flow->packet_count;
1295     rpy->byte_count += flow->byte_count;
1296     rpy->flow_count++;
1297     return 0;
1298 }
1299
1300 static int aggregate_stats_dump(struct datapath *dp, void *state,
1301                                 struct ofpbuf *buffer)
1302 {
1303     struct aggregate_stats_state *s = state;
1304     struct ofp_aggregate_stats_request *rq = &s->rq;
1305     struct ofp_aggregate_stats_reply *rpy;
1306     struct sw_table_position position;
1307     struct sw_flow_key match_key;
1308     int table_idx;
1309
1310     rpy = ofpbuf_put_uninit(buffer, sizeof *rpy);
1311     memset(rpy, 0, sizeof *rpy);
1312
1313     flow_extract_match(&match_key, &rq->match);
1314     table_idx = rq->table_id == 0xff ? 0 : rq->table_id;
1315     memset(&position, 0, sizeof position);
1316     while (table_idx < dp->chain->n_tables
1317            && (rq->table_id == 0xff || rq->table_id == table_idx))
1318     {
1319         struct sw_table *table = dp->chain->tables[table_idx];
1320         int error;
1321
1322         error = table->iterate(table, &match_key, rq->out_port, &position, 
1323                                aggregate_stats_dump_callback, rpy);
1324         if (error)
1325             return error;
1326
1327         table_idx++;
1328         memset(&position, 0, sizeof position);
1329     }
1330
1331     rpy->packet_count = htonll(rpy->packet_count);
1332     rpy->byte_count = htonll(rpy->byte_count);
1333     rpy->flow_count = htonl(rpy->flow_count);
1334     return 0;
1335 }
1336
1337 static void aggregate_stats_done(void *state) 
1338 {
1339     free(state);
1340 }
1341
1342 static int table_stats_dump(struct datapath *dp, void *state,
1343                             struct ofpbuf *buffer)
1344 {
1345     int i;
1346     for (i = 0; i < dp->chain->n_tables; i++) {
1347         struct ofp_table_stats *ots = ofpbuf_put_uninit(buffer, sizeof *ots);
1348         struct sw_table_stats stats;
1349         dp->chain->tables[i]->stats(dp->chain->tables[i], &stats);
1350         strncpy(ots->name, stats.name, sizeof ots->name);
1351         ots->table_id = i;
1352         ots->wildcards = htonl(stats.wildcards);
1353         memset(ots->pad, 0, sizeof ots->pad);
1354         ots->max_entries = htonl(stats.max_flows);
1355         ots->active_count = htonl(stats.n_flows);
1356         ots->lookup_count = htonll(stats.n_lookup);
1357         ots->matched_count = htonll(stats.n_matched);
1358     }
1359     return 0;
1360 }
1361
1362 struct port_stats_state {
1363     int port;
1364 };
1365
1366 static int port_stats_init(struct datapath *dp, const void *body, int body_len,
1367                void **state)
1368 {
1369     struct port_stats_state *s = xmalloc(sizeof *s);
1370     s->port = 0;
1371     *state = s;
1372     return 0;
1373 }
1374
1375 static void
1376 dump_port_stats(struct sw_port *port, struct ofpbuf *buffer)
1377 {
1378     struct ofp_port_stats *ops = ofpbuf_put_uninit(buffer, sizeof *ops);
1379     ops->port_no = htons(port->port_no);
1380     memset(ops->pad, 0, sizeof ops->pad);
1381     ops->rx_packets   = htonll(port->rx_packets);
1382     ops->tx_packets   = htonll(port->tx_packets);
1383     ops->rx_bytes     = htonll(port->rx_bytes);
1384     ops->tx_bytes     = htonll(port->tx_bytes);
1385     ops->rx_dropped   = htonll(-1);
1386     ops->tx_dropped   = htonll(port->tx_dropped);
1387     ops->rx_errors    = htonll(-1);
1388     ops->tx_errors    = htonll(-1);
1389     ops->rx_frame_err = htonll(-1);
1390     ops->rx_over_err  = htonll(-1);
1391     ops->rx_crc_err   = htonll(-1);
1392     ops->collisions   = htonll(-1);
1393 }
1394
1395 static int port_stats_dump(struct datapath *dp, void *state,
1396                            struct ofpbuf *buffer)
1397 {
1398     struct port_stats_state *s = state;
1399     int i;
1400
1401     for (i = s->port; i < DP_MAX_PORTS; i++) {
1402         struct sw_port *p = &dp->ports[i];
1403         if (p->netdev) {
1404             dump_port_stats(p, buffer);
1405         }
1406     }
1407     s->port = i;
1408
1409     if (dp->local_port) {
1410         dump_port_stats(dp->local_port, buffer);
1411         s->port = OFPP_LOCAL + 1;
1412     }
1413     return 0;
1414 }
1415
1416 static void port_stats_done(void *state)
1417 {
1418     free(state);
1419 }
1420
1421 struct stats_type {
1422     /* Value for 'type' member of struct ofp_stats_request. */
1423     int type;
1424
1425     /* Minimum and maximum acceptable number of bytes in body member of
1426      * struct ofp_stats_request. */
1427     size_t min_body, max_body;
1428
1429     /* Prepares to dump some kind of statistics on 'dp'.  'body' and
1430      * 'body_len' are the 'body' member of the struct ofp_stats_request.
1431      * Returns zero if successful, otherwise a negative error code.
1432      * May initialize '*state' to state information.  May be null if no
1433      * initialization is required.*/
1434     int (*init)(struct datapath *dp, const void *body, int body_len,
1435             void **state);
1436
1437     /* Appends statistics for 'dp' to 'buffer', which initially contains a
1438      * struct ofp_stats_reply.  On success, it should return 1 if it should be
1439      * called again later with another buffer, 0 if it is done, or a negative
1440      * errno value on failure. */
1441     int (*dump)(struct datapath *dp, void *state, struct ofpbuf *buffer);
1442
1443     /* Cleans any state created by the init or dump functions.  May be null
1444      * if no cleanup is required. */
1445     void (*done)(void *state);
1446 };
1447
1448 static const struct stats_type stats[] = {
1449     {
1450         OFPST_DESC,
1451         0,
1452         0,
1453         NULL,
1454         desc_stats_dump,
1455         NULL
1456     },
1457     {
1458         OFPST_FLOW,
1459         sizeof(struct ofp_flow_stats_request),
1460         sizeof(struct ofp_flow_stats_request),
1461         flow_stats_init,
1462         flow_stats_dump,
1463         flow_stats_done
1464     },
1465     {
1466         OFPST_AGGREGATE,
1467         sizeof(struct ofp_aggregate_stats_request),
1468         sizeof(struct ofp_aggregate_stats_request),
1469         aggregate_stats_init,
1470         aggregate_stats_dump,
1471         aggregate_stats_done
1472     },
1473     {
1474         OFPST_TABLE,
1475         0,
1476         0,
1477         NULL,
1478         table_stats_dump,
1479         NULL
1480     },
1481     {
1482         OFPST_PORT,
1483         0,
1484         0,
1485         port_stats_init,
1486         port_stats_dump,
1487         port_stats_done
1488     },
1489 };
1490
1491 struct stats_dump_cb {
1492     bool done;
1493     struct ofp_stats_request *rq;
1494     struct sender sender;
1495     const struct stats_type *s;
1496     void *state;
1497 };
1498
1499 static int
1500 stats_dump(struct datapath *dp, void *cb_)
1501 {
1502     struct stats_dump_cb *cb = cb_;
1503     struct ofp_stats_reply *osr;
1504     struct ofpbuf *buffer;
1505     int err;
1506
1507     if (cb->done) {
1508         return 0;
1509     }
1510
1511     osr = make_openflow_reply(sizeof *osr, OFPT_STATS_REPLY, &cb->sender,
1512                               &buffer);
1513     osr->type = htons(cb->s->type);
1514     osr->flags = 0;
1515
1516     err = cb->s->dump(dp, cb->state, buffer);
1517     if (err >= 0) {
1518         int err2;
1519         if (!err) {
1520             cb->done = true;
1521         } else {
1522             /* Buffer might have been reallocated, so find our data again. */
1523             osr = ofpbuf_at_assert(buffer, 0, sizeof *osr);
1524             osr->flags = ntohs(OFPSF_REPLY_MORE);
1525         }
1526         err2 = send_openflow_buffer(dp, buffer, &cb->sender);
1527         if (err2) {
1528             err = err2;
1529         }
1530     }
1531
1532     return err;
1533 }
1534
1535 static void
1536 stats_done(void *cb_)
1537 {
1538     struct stats_dump_cb *cb = cb_;
1539     if (cb) {
1540         if (cb->s->done) {
1541             cb->s->done(cb->state);
1542         }
1543         free(cb);
1544     }
1545 }
1546
1547 static int
1548 recv_stats_request(struct datapath *dp, const struct sender *sender,
1549                    const void *oh)
1550 {
1551     const struct ofp_stats_request *rq = oh;
1552     size_t rq_len = ntohs(rq->header.length);
1553     const struct stats_type *st;
1554     struct stats_dump_cb *cb;
1555     int type, body_len;
1556     int err;
1557
1558     type = ntohs(rq->type);
1559     for (st = stats; ; st++) {
1560         if (st >= &stats[ARRAY_SIZE(stats)]) {
1561             VLOG_WARN_RL(&rl, "received stats request of unknown type %d",
1562                          type);
1563             return -EINVAL;
1564         } else if (type == st->type) {
1565             break;
1566         }
1567     }
1568
1569     cb = xmalloc(sizeof *cb);
1570     cb->done = false;
1571     cb->rq = xmemdup(rq, rq_len);
1572     cb->sender = *sender;
1573     cb->s = st;
1574     cb->state = NULL;
1575     
1576     body_len = rq_len - offsetof(struct ofp_stats_request, body);
1577     if (body_len < cb->s->min_body || body_len > cb->s->max_body) {
1578         VLOG_WARN_RL(&rl, "stats request type %d with bad body length %d",
1579                      type, body_len);
1580         err = -EINVAL;
1581         goto error;
1582     }
1583
1584     if (cb->s->init) {
1585         err = cb->s->init(dp, rq->body, body_len, &cb->state);
1586         if (err) {
1587             VLOG_WARN_RL(&rl,
1588                          "failed initialization of stats request type %d: %s",
1589                          type, strerror(-err));
1590             goto error;
1591         }
1592     }
1593
1594     remote_start_dump(sender->remote, stats_dump, stats_done, cb);
1595     return 0;
1596
1597 error:
1598     free(cb->rq);
1599     free(cb);
1600     return err;
1601 }
1602
1603 static int
1604 recv_echo_request(struct datapath *dp, const struct sender *sender,
1605                   const void *oh)
1606 {
1607     return send_openflow_buffer(dp, make_echo_reply(oh), sender);
1608 }
1609
1610 static int
1611 recv_echo_reply(struct datapath *dp UNUSED, const struct sender *sender UNUSED,
1612                   const void *oh UNUSED)
1613 {
1614     return 0;
1615 }
1616
1617 /* 'msg', which is 'length' bytes long, was received from the control path.
1618  * Apply it to 'chain'. */
1619 int
1620 fwd_control_input(struct datapath *dp, const struct sender *sender,
1621                   const void *msg, size_t length)
1622 {
1623     int (*handler)(struct datapath *, const struct sender *, const void *);
1624     struct ofp_header *oh;
1625     size_t min_size;
1626
1627     /* Check encapsulated length. */
1628     oh = (struct ofp_header *) msg;
1629     if (ntohs(oh->length) > length) {
1630         return -EINVAL;
1631     }
1632     assert(oh->version == OFP_VERSION);
1633
1634     /* Figure out how to handle it. */
1635     switch (oh->type) {
1636     case OFPT_FEATURES_REQUEST:
1637         min_size = sizeof(struct ofp_header);
1638         handler = recv_features_request;
1639         break;
1640     case OFPT_GET_CONFIG_REQUEST:
1641         min_size = sizeof(struct ofp_header);
1642         handler = recv_get_config_request;
1643         break;
1644     case OFPT_SET_CONFIG:
1645         min_size = sizeof(struct ofp_switch_config);
1646         handler = recv_set_config;
1647         break;
1648     case OFPT_PACKET_OUT:
1649         min_size = sizeof(struct ofp_packet_out);
1650         handler = recv_packet_out;
1651         break;
1652     case OFPT_FLOW_MOD:
1653         min_size = sizeof(struct ofp_flow_mod);
1654         handler = recv_flow;
1655         break;
1656     case OFPT_PORT_MOD:
1657         min_size = sizeof(struct ofp_port_mod);
1658         handler = recv_port_mod;
1659         break;
1660     case OFPT_STATS_REQUEST:
1661         min_size = sizeof(struct ofp_stats_request);
1662         handler = recv_stats_request;
1663         break;
1664     case OFPT_ECHO_REQUEST:
1665         min_size = sizeof(struct ofp_header);
1666         handler = recv_echo_request;
1667         break;
1668     case OFPT_ECHO_REPLY:
1669         min_size = sizeof(struct ofp_header);
1670         handler = recv_echo_reply;
1671         break;
1672     default:
1673         dp_send_error_msg(dp, sender, OFPET_BAD_REQUEST, OFPBRC_BAD_TYPE,
1674                           msg, length);
1675         return -EINVAL;
1676     }
1677
1678     /* Handle it. */
1679     if (length < min_size)
1680         return -EFAULT;
1681     return handler(dp, sender, msg);
1682 }
1683 \f
1684 /* Packet buffering. */
1685
1686 #define OVERWRITE_SECS  1
1687
1688 struct packet_buffer {
1689     struct ofpbuf *buffer;
1690     uint32_t cookie;
1691     time_t timeout;
1692 };
1693
1694 static struct packet_buffer buffers[N_PKT_BUFFERS];
1695 static unsigned int buffer_idx;
1696
1697 uint32_t save_buffer(struct ofpbuf *buffer)
1698 {
1699     struct packet_buffer *p;
1700     uint32_t id;
1701
1702     buffer_idx = (buffer_idx + 1) & PKT_BUFFER_MASK;
1703     p = &buffers[buffer_idx];
1704     if (p->buffer) {
1705         /* Don't buffer packet if existing entry is less than
1706          * OVERWRITE_SECS old. */
1707         if (time_now() < p->timeout) { /* FIXME */
1708             return -1;
1709         } else {
1710             ofpbuf_delete(p->buffer); 
1711         }
1712     }
1713     /* Don't use maximum cookie value since the all-bits-1 id is
1714      * special. */
1715     if (++p->cookie >= (1u << PKT_COOKIE_BITS) - 1)
1716         p->cookie = 0;
1717     p->buffer = ofpbuf_clone(buffer);      /* FIXME */
1718     p->timeout = time_now() + OVERWRITE_SECS; /* FIXME */
1719     id = buffer_idx | (p->cookie << PKT_BUFFER_BITS);
1720
1721     return id;
1722 }
1723
1724 static struct ofpbuf *retrieve_buffer(uint32_t id)
1725 {
1726     struct ofpbuf *buffer = NULL;
1727     struct packet_buffer *p;
1728
1729     p = &buffers[id & PKT_BUFFER_MASK];
1730     if (p->cookie == id >> PKT_BUFFER_BITS) {
1731         buffer = p->buffer;
1732         p->buffer = NULL;
1733     } else {
1734         printf("cookie mismatch: %x != %x\n",
1735                id >> PKT_BUFFER_BITS, p->cookie);
1736     }
1737
1738     return buffer;
1739 }
1740
1741 static void discard_buffer(uint32_t id)
1742 {
1743     struct packet_buffer *p;
1744
1745     p = &buffers[id & PKT_BUFFER_MASK];
1746     if (p->cookie == id >> PKT_BUFFER_BITS) {
1747         ofpbuf_delete(p->buffer);
1748         p->buffer = NULL;
1749     }
1750 }