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