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