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