Clean up and comment netdev implementation.
[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 <stdlib.h>
39 #include <string.h>
40 #include "buffer.h"
41 #include "chain.h"
42 #include "controller.h"
43 #include "flow.h"
44 #include "forward.h"
45 #include "netdev.h"
46 #include "packets.h"
47 #include "poll-loop.h"
48 #include "table.h"
49 #include "xtoxll.h"
50
51 #define THIS_MODULE VLM_datapath
52 #include "vlog.h"
53
54 #define BRIDGE_PORT_NO_FLOOD    0x00000001
55
56 static void send_port_status(struct sw_port *p, uint8_t status);
57 static void del_switch_port(struct sw_port *p);
58 static int port_no(struct datapath *dp, struct sw_port *p) 
59 {
60     assert(p >= dp->ports && p < &dp->ports[ARRAY_SIZE(dp->ports)]);
61     return p - dp->ports;
62 }
63
64 /* Generates a unique datapath id.  It incorporates the datapath index
65  * and a hardware address, if available.  If not, it generates a random
66  * one.
67  */
68 static uint64_t
69 gen_datapath_id(void)
70 {
71     /* Choose a random datapath id. */
72     uint64_t id = 0;
73     int i;
74
75     srand(time(0));
76
77     for (i = 0; i < ETH_ADDR_LEN; i++) {
78         id |= (uint64_t)(rand() & 0xff) << (8*(ETH_ADDR_LEN-1 - i));
79     }
80
81     return id;
82 }
83
84 int
85 dp_new(struct datapath **dp_, uint64_t dpid, struct controller_connection *cc)
86 {
87     struct datapath *dp;
88
89     dp = calloc(1, sizeof *dp);
90     if (!dp) {
91         return ENOMEM;
92     }
93
94     dp->last_timeout = time(0);
95     dp->cc = cc;
96     dp->id = dpid <= UINT64_C(0xffffffffffff) ? dpid : gen_datapath_id();
97     dp->chain = chain_create();
98     if (!dp->chain) {
99         VLOG_ERR("could not create chain");
100         free(dp);
101         return ENOMEM;
102     }
103
104     list_init(&dp->port_list);
105     dp->miss_send_len = OFP_DEFAULT_MISS_SEND_LEN;
106     *dp_ = dp;
107     return 0;
108 }
109
110 int
111 dp_add_port(struct datapath *dp, const char *name)
112 {
113     struct netdev *netdev;
114     struct sw_port *p;
115     int error;
116
117     error = netdev_open(name, &netdev);
118     if (error) {
119         return error;
120     }
121
122     for (p = dp->ports; ; p++) {
123         if (p >= &dp->ports[ARRAY_SIZE(dp->ports)]) {
124             return EXFULL;
125         } else if (!p->netdev) {
126             break;
127         }
128     }
129
130     p->dp = dp;
131     p->netdev = netdev;
132     list_push_back(&dp->port_list, &p->node);
133
134     /* Notify the ctlpath that this port has been added */
135     send_port_status(p, OFPPR_ADD);
136
137     return 0;
138 }
139
140 void
141 dp_run(struct datapath *dp) 
142 {
143     time_t now = time(0);
144     struct sw_port *p, *n;
145     struct buffer *buffer = NULL;
146
147     if (now != dp->last_timeout) {
148         chain_timeout(dp->chain, dp);
149         dp->last_timeout = now;
150     }
151     poll_timer_wait(1000);
152     
153     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
154         int error;
155
156         if (!buffer) {
157             /* Allocate buffer with some headroom to add headers in forwarding
158              * to the controller or adding a vlan tag, plus an extra 2 bytes to
159              * allow IP headers to be aligned on a 4-byte boundary.  */
160             const int headroom = 128 + 2;
161             const int hard_header = VLAN_ETH_HEADER_LEN;
162             const int mtu = netdev_get_mtu(p->netdev);
163             buffer = buffer_new(headroom + hard_header + mtu);
164             buffer->data += headroom;
165         }
166         error = netdev_recv(p->netdev, buffer);
167         if (!error) {
168             fwd_port_input(dp, buffer, port_no(dp, p));
169             buffer = NULL;
170         } else if (error != EAGAIN) {
171             VLOG_ERR("Error receiving data from %s: %s",
172                      netdev_get_name(p->netdev), strerror(error));
173             del_switch_port(p);
174         }
175     }
176     buffer_delete(buffer);
177 }
178
179 void
180 dp_wait(struct datapath *dp) 
181 {
182     struct sw_port *p;
183
184     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
185         netdev_recv_wait(p->netdev);
186     }
187 }
188
189 /* Delete 'p' from switch. */
190 static void
191 del_switch_port(struct sw_port *p)
192 {
193     send_port_status(p, OFPPR_DELETE);
194     netdev_close(p->netdev);
195     p->netdev = NULL;
196     list_remove(&p->node);
197 }
198
199 void
200 dp_destroy(struct datapath *dp)
201 {
202     struct sw_port *p, *n;
203
204     if (!dp) {
205         return;
206     }
207
208     LIST_FOR_EACH_SAFE (p, n, struct sw_port, node, &dp->port_list) {
209         del_switch_port(p); 
210     }
211     chain_destroy(dp->chain);
212     free(dp);
213 }
214
215 static int
216 flood(struct datapath *dp, struct buffer *buffer, int in_port)
217 {
218     struct sw_port *p;
219     struct sw_port *prev_port;
220
221     prev_port = NULL;
222     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
223         if (port_no(dp, p) == in_port || p->flags & BRIDGE_PORT_NO_FLOOD) {
224             continue;
225         }
226         if (prev_port) {
227             struct buffer *clone = buffer_clone(buffer);
228             if (!clone) {
229                 buffer_delete(buffer);
230                 return -ENOMEM;
231             }
232             dp_output_port(dp, clone, in_port, port_no(dp, prev_port)); 
233         }
234         prev_port = p;
235     }
236     if (prev_port)
237         dp_output_port(dp, buffer, in_port, port_no(dp, prev_port));
238     else
239         buffer_delete(buffer);
240
241     return 0;
242 }
243
244 void
245 output_packet(struct datapath *dp, struct buffer *buffer, int out_port) 
246 {
247     if (out_port >= 0 && out_port < OFPP_MAX) { 
248         struct sw_port *p = &dp->ports[out_port];
249         if (p->netdev != NULL) {
250             netdev_send(p->netdev, buffer);
251             return;
252         }
253     }
254
255     buffer_delete(buffer);
256     /* FIXME: ratelimit */
257     VLOG_DBG("can't forward to bad port %d\n", out_port);
258 }
259
260 /* Takes ownership of 'buffer' and transmits it to 'out_port' on 'dp'.
261  */
262 void
263 dp_output_port(struct datapath *dp, struct buffer *buffer,
264                int in_port, int out_port)
265 {
266
267     assert(buffer);
268     if (out_port == OFPP_FLOOD) {
269         flood(dp, buffer, in_port); 
270     } else if (out_port == OFPP_CONTROLLER) {
271         dp_output_control(dp, buffer, in_port, fwd_save_buffer(buffer), 0,
272                           OFPR_ACTION); 
273     } else {
274         output_packet(dp, buffer, out_port);
275     }
276 }
277
278 /* Takes ownership of 'buffer' and transmits it to 'dp''s controller.  If
279  * 'buffer_id' != -1, then only the first 64 bytes of 'buffer' are sent;
280  * otherwise, all of 'buffer' is sent.  'reason' indicates why 'buffer' is
281  * being sent. 'max_len' sets the maximum number of bytes that the caller wants
282  * to be sent; a value of 0 indicates the entire packet should be sent. */
283 void
284 dp_output_control(struct datapath *dp, struct buffer *buffer, int in_port,
285                   uint32_t buffer_id, size_t max_len, int reason)
286 {
287     struct ofp_packet_in *opi;
288     size_t total_len;
289
290     total_len = buffer->size;
291     if (buffer_id != UINT32_MAX && max_len > buffer->size) {
292         buffer->size = max_len;
293     }
294
295     opi = buffer_push_uninit(buffer, offsetof(struct ofp_packet_in, data));
296     opi->header.version = OFP_VERSION;
297     opi->header.type    = OFPT_PACKET_IN;
298     opi->header.length  = htons(buffer->size);
299     opi->header.xid     = htonl(0);
300     opi->buffer_id      = htonl(buffer_id);
301     opi->total_len      = htons(total_len);
302     opi->in_port        = htons(in_port);
303     opi->reason         = reason;
304     opi->pad            = 0;
305     controller_send(dp->cc, buffer);
306 }
307
308 static void fill_port_desc(struct datapath *dp, struct sw_port *p,
309                            struct ofp_phy_port *desc)
310 {
311     desc->port_no = htons(port_no(dp, p));
312     strncpy((char *) desc->name, netdev_get_name(p->netdev),
313             sizeof desc->name);
314     desc->name[sizeof desc->name - 1] = '\0';
315     memcpy(desc->hw_addr, netdev_get_etheraddr(p->netdev), ETH_ADDR_LEN);
316     desc->flags = htonl(p->flags);
317     desc->features = htonl(netdev_get_features(p->netdev));
318     desc->speed = htonl(netdev_get_speed(p->netdev));
319 }
320
321 void
322 dp_send_hello(struct datapath *dp)
323 {
324     struct buffer *buffer;
325     struct ofp_data_hello *odh;
326     struct sw_port *p;
327
328     buffer = buffer_new(sizeof *odh);
329     odh = buffer_put_uninit(buffer, sizeof *odh);
330     memset(odh, 0, sizeof *odh);
331     odh->header.version = OFP_VERSION;
332     odh->header.type    = OFPT_DATA_HELLO;
333     odh->header.xid     = htonl(0);
334     odh->datapath_id    = htonll(dp->id); 
335     odh->n_exact        = htonl(2 * TABLE_HASH_MAX_FLOWS);
336     odh->n_mac_only     = htonl(TABLE_MAC_MAX_FLOWS);
337     odh->n_compression  = 0;                                           /* Not supported */
338     odh->n_general      = htonl(TABLE_LINEAR_MAX_FLOWS);
339     odh->buffer_mb      = htonl(UINT32_MAX);
340     odh->n_buffers      = htonl(N_PKT_BUFFERS);
341     odh->capabilities   = htonl(OFP_SUPPORTED_CAPABILITIES);
342     odh->actions        = htonl(OFP_SUPPORTED_ACTIONS);
343     odh->miss_send_len  = htons(dp->miss_send_len); 
344     LIST_FOR_EACH (p, struct sw_port, node, &dp->port_list) {
345         struct ofp_phy_port *opp = buffer_put_uninit(buffer, sizeof *opp);
346         memset(opp, 0, sizeof *opp);
347         fill_port_desc(dp, p, opp);
348     }
349     odh = buffer_at_assert(buffer, 0, sizeof *odh);
350     odh->header.length = htons(buffer->size);
351     controller_send(dp->cc, buffer);
352 }
353
354 void
355 dp_update_port_flags(struct datapath *dp, const struct ofp_phy_port *opp)
356 {
357     struct sw_port *p;
358
359     p = &dp->ports[htons(opp->port_no)];
360
361     /* Make sure the port id hasn't changed since this was sent */
362     if (!p || memcmp(opp->hw_addr, netdev_get_etheraddr(p->netdev),
363                      ETH_ADDR_LEN) != 0) 
364         return;
365         
366     p->flags = htonl(opp->flags);
367 }
368
369 static void
370 send_port_status(struct sw_port *p, uint8_t status) 
371 {
372     struct buffer *buffer;
373     struct ofp_port_status *ops;
374     buffer = buffer_new(sizeof *ops);
375     ops = buffer_put_uninit(buffer, sizeof *ops);
376     ops->header.version = OFP_VERSION;
377     ops->header.type    = OFPT_PORT_STATUS;
378     ops->header.length  = htons(sizeof(*ops));
379     ops->header.xid     = htonl(0);
380     ops->reason         = status;
381     fill_port_desc(p->dp, p, &ops->desc);
382     controller_send(p->dp->cc, buffer);
383 }
384
385 void
386 dp_send_flow_expired(struct datapath *dp, struct sw_flow *flow)
387 {
388     struct buffer *buffer;
389     struct ofp_flow_expired *ofe;
390     buffer = buffer_new(sizeof *ofe);
391     ofe = buffer_put_uninit(buffer, sizeof *ofe);
392     ofe->header.version = OFP_VERSION;
393     ofe->header.type    = OFPT_FLOW_EXPIRED;
394     ofe->header.length  = htons(sizeof(*ofe));
395     ofe->header.xid     = htonl(0);
396     flow_fill_match(&ofe->match, &flow->key);
397     ofe->duration   = htonl(flow->timeout - flow->max_idle - flow->created);
398     ofe->packet_count   = htonll(flow->packet_count);
399     ofe->byte_count     = htonll(flow->byte_count);
400     controller_send(dp->cc, buffer);
401 }