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