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