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