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