Update copyright on all non-GPL files
[sliver-openvswitch.git] / lib / dpif.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 "dpif.h"
35
36 #include <ctype.h>
37 #include <errno.h>
38 #include <inttypes.h>
39 #include <netinet/in.h>
40 #include <stdlib.h>
41 #include <string.h>
42
43 #include "buffer.h"
44 #include "mac.h"
45 #include "netlink.h"
46 #include "ofp-print.h"
47 #include "openflow-netlink.h"
48 #include "openflow.h"
49 #include "util.h"
50 #include "xtoxll.h"
51
52 #include "vlog.h"
53 #define THIS_MODULE VLM_dpif
54
55 /* The Generic Netlink family number used for OpenFlow. */
56 static int openflow_family;
57
58 static int lookup_openflow_multicast_group(int dp_idx, int *multicast_group);
59 static int send_mgmt_command(struct dpif *, int command,
60                              const char *netdev);
61
62 /* Opens the local datapath numbered 'dp_idx', initializing 'dp'.  If
63  * 'subscribe' is true, listens for asynchronous messages (packet-in, etc.)
64  * from the datapath; otherwise, 'dp' will receive only replies to explicitly
65  * initiated requests. */
66 int
67 dpif_open(int dp_idx, bool subscribe, struct dpif *dp)
68 {
69     struct nl_sock *sock;
70     int multicast_group = 0;
71     int retval;
72
73     retval = nl_lookup_genl_family(DP_GENL_FAMILY_NAME, &openflow_family);
74     if (retval) {
75         return retval;
76     }
77
78     if (subscribe) {
79         retval = lookup_openflow_multicast_group(dp_idx, &multicast_group);
80         if (retval) {
81             return retval;
82         }
83     }
84
85     /* Specify a large so_rcvbuf size because we occasionally need to be able
86      * to retrieve large collections of flow records. */
87     retval = nl_sock_create(NETLINK_GENERIC, multicast_group, 0,
88                             4 * 1024u * 1024, &sock);
89     if (retval) {
90         return retval;
91     }
92
93     dp->dp_idx = dp_idx;
94     dp->sock = sock;
95     return 0;
96 }
97
98 /* Closes 'dp'. */
99 void
100 dpif_close(struct dpif *dp) 
101 {
102     nl_sock_destroy(dp->sock);
103 }
104
105 static const struct nl_policy openflow_policy[] = {
106     [DP_GENL_A_DP_IDX] = { .type = NL_A_U32 },
107     [DP_GENL_A_OPENFLOW] = { .type = NL_A_UNSPEC,
108                               .min_len = sizeof(struct ofp_header),
109                               .max_len = OFP_MAXLEN },
110 };
111
112 /* Tries to receive an openflow message from the kernel on 'sock'.  If
113  * successful, stores the received message into '*msgp' and returns 0.  The
114  * caller is responsible for destroying the message with buffer_delete().  On
115  * failure, returns a positive errno value and stores a null pointer into
116  * '*msgp'.
117  *
118  * Only Netlink messages with embedded OpenFlow messages are accepted.  Other
119  * Netlink messages provoke errors.
120  *
121  * If 'wait' is true, dpif_recv_openflow waits for a message to be ready;
122  * otherwise, returns EAGAIN if the 'sock' receive buffer is empty. */
123 int
124 dpif_recv_openflow(struct dpif *dp, struct buffer **bufferp,
125                         bool wait) 
126 {
127     struct nlattr *attrs[ARRAY_SIZE(openflow_policy)];
128     struct buffer *buffer;
129     struct ofp_header *oh;
130     size_t ofp_len;
131     int retval;
132
133     *bufferp = NULL;
134     do {
135         retval = nl_sock_recv(dp->sock, &buffer, wait);
136     } while (retval == ENOBUFS || (!retval && nl_msg_nlmsgerr(buffer, NULL)));
137     if (retval) {
138         if (retval != EAGAIN) {
139             VLOG_WARN("dpif_recv_openflow: %s", strerror(retval)); 
140         }
141         return retval;
142     }
143
144     if (nl_msg_genlmsghdr(buffer) == NULL) {
145         VLOG_DBG("received packet too short for Generic Netlink");
146         goto error;
147     }
148     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != openflow_family) {
149         VLOG_DBG("received type (%"PRIu16") != openflow family (%d)",
150                  nl_msg_nlmsghdr(buffer)->nlmsg_type, openflow_family);
151         goto error;
152     }
153
154     if (!nl_policy_parse(buffer, openflow_policy, attrs,
155                          ARRAY_SIZE(openflow_policy))) {
156         goto error;
157     }
158     if (nl_attr_get_u32(attrs[DP_GENL_A_DP_IDX]) != dp->dp_idx) {
159         VLOG_WARN("received dp_idx (%"PRIu32") differs from expected (%d)",
160                   nl_attr_get_u32(attrs[DP_GENL_A_DP_IDX]), dp->dp_idx);
161         goto error;
162     }
163
164     oh = buffer->data = (void *) nl_attr_get(attrs[DP_GENL_A_OPENFLOW]);
165     buffer->size = nl_attr_get_size(attrs[DP_GENL_A_OPENFLOW]);
166     ofp_len = ntohs(oh->length);
167     if (ofp_len != buffer->size) {
168         VLOG_WARN("ofp_header.length %"PRIu16" != attribute length %zu\n",
169                   ofp_len, buffer->size);
170         buffer->size = MIN(ofp_len, buffer->size);
171     }
172     *bufferp = buffer;
173     return 0;
174
175 error:
176     buffer_delete(buffer);
177     return EPROTO;
178 }
179
180 /* Encapsulates 'msg', which must contain an OpenFlow message, in a Netlink
181  * message, and sends it to the OpenFlow kernel module via 'sock'.
182  *
183  * Returns 0 if successful, otherwise a positive errno value.  If
184  * 'wait' is true, then the send will wait until buffer space is ready;
185  * otherwise, returns EAGAIN if the 'sock' send buffer is full.
186  *
187  * If the send is successful, then the kernel module will receive it, but there
188  * is no guarantee that any reply will not be dropped (see nl_sock_transact()
189  * for details). 
190  */
191 int
192 dpif_send_openflow(struct dpif *dp, struct buffer *buffer, bool wait) 
193 {
194     struct buffer hdr;
195     struct nlattr *nla;
196     uint32_t fixed_buffer[64 / 4];
197     struct iovec iov[3];
198     int pad_bytes;
199     int n_iov;
200     int retval;
201
202     buffer_use(&hdr, fixed_buffer, sizeof fixed_buffer);
203     nl_msg_put_genlmsghdr(&hdr, dp->sock, 32, openflow_family,
204                           NLM_F_REQUEST, DP_GENL_C_OPENFLOW, 1);
205     nl_msg_put_u32(&hdr, DP_GENL_A_DP_IDX, dp->dp_idx);
206     nla = buffer_put_uninit(&hdr, sizeof nla);
207     nla->nla_len = sizeof nla + buffer->size;
208     nla->nla_type = DP_GENL_A_OPENFLOW;
209     pad_bytes = NLA_ALIGN(nla->nla_len) - nla->nla_len;
210     nl_msg_nlmsghdr(&hdr)->nlmsg_len = hdr.size + buffer->size + pad_bytes;
211     n_iov = 2;
212     iov[0].iov_base = hdr.data;
213     iov[0].iov_len = hdr.size;
214     iov[1].iov_base = buffer->data;
215     iov[1].iov_len = buffer->size;
216     if (pad_bytes) {
217         static char zeros[NLA_ALIGNTO];
218         n_iov++;
219         iov[2].iov_base = zeros;
220         iov[2].iov_len = pad_bytes; 
221     }
222     retval = nl_sock_sendv(dp->sock, iov, n_iov, false);
223     if (retval && retval != EAGAIN) {
224         VLOG_WARN("dpif_send_openflow: %s", strerror(retval));
225     }
226     return retval;
227 }
228
229 /* Creates the datapath represented by 'dp'.  Returns 0 if successful,
230  * otherwise a positive errno value. */
231 int
232 dpif_add_dp(struct dpif *dp)
233 {
234     return send_mgmt_command(dp, DP_GENL_C_ADD_DP, NULL);
235 }
236
237 /* Destroys the datapath represented by 'dp'.  Returns 0 if successful,
238  * otherwise a positive errno value. */
239 int
240 dpif_del_dp(struct dpif *dp) 
241 {
242     return send_mgmt_command(dp, DP_GENL_C_DEL_DP, NULL);
243 }
244
245 /* Adds the Ethernet device named 'netdev' to this datapath.  Returns 0 if
246  * successful, otherwise a positive errno value. */
247 int
248 dpif_add_port(struct dpif *dp, const char *netdev)
249 {
250     return send_mgmt_command(dp, DP_GENL_C_ADD_PORT, netdev);
251 }
252
253 /* Removes the Ethernet device named 'netdev' from this datapath.  Returns 0
254  * if successful, otherwise a positive errno value. */
255 int
256 dpif_del_port(struct dpif *dp, const char *netdev)
257 {
258     return send_mgmt_command(dp, DP_GENL_C_DEL_PORT, netdev);
259 }
260
261 /* Prints a description of 'dp' to stdout.  Returns 0 if successful, otherwise
262  * a positive errno value. */
263 int
264 dpif_show(struct dpif *dp) 
265 {
266     static const struct nl_policy show_policy[] = {
267         [DP_GENL_A_DP_INFO] = { .type = NL_A_UNSPEC,
268                                 .min_len = sizeof(struct ofp_data_hello),
269                                 .max_len = SIZE_MAX },
270     };
271
272     struct buffer request, *reply;
273     struct nlattr *attrs[ARRAY_SIZE(show_policy)];
274     struct ofp_data_hello *odh;
275     int retval;
276     size_t len;
277
278     buffer_init(&request, 0);
279     nl_msg_put_genlmsghdr(&request, dp->sock, 0, openflow_family,
280                           NLM_F_REQUEST, DP_GENL_C_SHOW_DP, 1);
281     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp->dp_idx);
282     retval = nl_sock_transact(dp->sock, &request, &reply);
283     buffer_uninit(&request);
284     if (retval) {
285         return retval;
286     }
287     if (!nl_policy_parse(reply, show_policy, attrs,
288                          ARRAY_SIZE(show_policy))) {
289         buffer_delete(reply);
290         return EPROTO;
291     }
292
293     odh = (void *) nl_attr_get(attrs[DP_GENL_A_DP_INFO]);
294     if (odh->header.version != OFP_VERSION
295         || odh->header.type != OFPT_DATA_HELLO) {
296         VLOG_ERR("bad show query response (%"PRIu8",%"PRIu8")",
297                  odh->header.version, odh->header.type);
298         buffer_delete(reply);
299         return EPROTO;
300     }
301
302     len = nl_attr_get_size(attrs[DP_GENL_A_DP_INFO]);
303     ofp_print_data_hello(stdout, odh, len, 1);
304
305     return retval;
306 }
307
308 static const struct nl_policy table_policy[] = {
309     [DP_GENL_A_NUMTABLES] = { .type = NL_A_U32 },
310     [DP_GENL_A_TABLE] = { .type = NL_A_UNSPEC },
311 };
312
313 /* Writes a description of 'dp''s tables to stdout.  Returns 0 if successful,
314  * otherwise a positive errno value. */
315 int
316 dpif_dump_tables(struct dpif *dp) 
317 {
318     struct buffer request, *reply;
319     struct nlattr *attrs[ARRAY_SIZE(table_policy)];
320     const struct ofp_table *tables;
321     int n_tables;
322     int i;
323     int retval;
324
325     buffer_init(&request, 0);
326     nl_msg_put_genlmsghdr(&request, dp->sock, 0, openflow_family,
327                           NLM_F_REQUEST, DP_GENL_C_QUERY_TABLE, 1);
328     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp->dp_idx);
329     retval = nl_sock_transact(dp->sock, &request, &reply);
330     buffer_uninit(&request);
331     if (retval) {
332         return retval;
333     }
334     if (!nl_policy_parse(reply, table_policy, attrs,
335                          ARRAY_SIZE(table_policy))) {
336         buffer_delete(reply);
337         return EPROTO;
338     }
339
340     tables = nl_attr_get(attrs[DP_GENL_A_TABLE]);
341     n_tables = (nl_attr_get_size(attrs[DP_GENL_A_TABLE])
342                 / sizeof(struct ofp_table));
343     n_tables = MIN(n_tables, nl_attr_get_u32(attrs[DP_GENL_A_NUMTABLES]));
344     for (i = 0; i < n_tables; i++) {
345         const struct ofp_table *ot = &tables[i];
346         if (ot->header.version != 1 || ot->header.type != OFPT_TABLE) {
347             VLOG_DBG("bad table query response (%"PRIu8",%"PRIu8")",
348                      ot->header.version, ot->header.type);
349             retval = EPROTO;
350             break;
351         }
352
353         ofp_print_table(stdout, ot);
354         fprintf(stdout,"\n");
355     }
356     buffer_delete(reply);
357
358     return retval;
359 }
360
361 static const struct nl_policy flow_policy[] = {
362     [DP_GENL_A_TABLEIDX] = { .type = NL_A_U16 },
363     [DP_GENL_A_NUMFLOWS] = { .type = NL_A_U32 },
364     [DP_GENL_A_FLOW] = { .type = NL_A_UNSPEC },
365 };
366
367 struct _dump_ofp_flow_mod
368 {
369     struct ofp_flow_mod ofm;
370     struct ofp_action   oa;
371 };
372
373 /* Writes a description of flows in the given 'table' in 'dp' to stdout.  If
374  * 'match' is null, all flows in the table are written; otherwise, only
375  * matching flows are written.  Returns 0 if successful, otherwise a positive
376  * errno value. */
377 int
378 dpif_dump_flows(struct dpif *dp, int table, struct ofp_match *match)
379 {
380     struct buffer request, *reply;
381     struct ofp_flow_mod *ofm;
382     int retval;
383
384     buffer_init(&request, 0);
385     nl_msg_put_genlmsghdr(&request, dp->sock, 0, openflow_family, NLM_F_REQUEST,
386                           DP_GENL_C_QUERY_FLOW, 1);
387     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp->dp_idx);
388     nl_msg_put_u16(&request, DP_GENL_A_TABLEIDX, table);
389     ofm = nl_msg_put_unspec_uninit(&request, DP_GENL_A_FLOW, sizeof *ofm);
390     memset(ofm, 0, sizeof *ofm);
391     ofm->header.version = 1;
392     ofm->header.type = OFPT_FLOW_MOD;
393     ofm->header.length = htons(sizeof ofm);
394     if (match) {
395         ofm->match = *match;
396     } else {
397         ofm->match.wildcards = htons(OFPFW_ALL);
398     }
399     retval = nl_sock_transact(dp->sock, &request, &reply);
400     buffer_uninit(&request);
401     if (retval) {
402         return retval;
403     }
404
405     for (;;) {
406         struct nlattr *attrs[ARRAY_SIZE(flow_policy)];
407         const struct _dump_ofp_flow_mod *flows, *ofm;
408         int n_flows;
409
410         if (!nl_policy_parse(reply, flow_policy, attrs,
411                              ARRAY_SIZE(flow_policy))) {
412             buffer_delete(reply);
413             return EPROTO;
414         }
415         n_flows = (nl_attr_get_size(attrs[DP_GENL_A_FLOW])
416                    / sizeof(struct ofp_flow_mod));
417         n_flows = MIN(n_flows, nl_attr_get_u32(attrs[DP_GENL_A_NUMFLOWS]));
418         if (n_flows <= 0) {
419             break;
420         }
421
422         flows = nl_attr_get(attrs[DP_GENL_A_FLOW]);
423         for (ofm = flows; ofm < &flows[n_flows]; ofm++) {
424             if (ofm->ofm.header.version != 1){
425                 VLOG_DBG("recv_dp_flow incorrect version");
426                 buffer_delete(reply);
427                 return EPROTO;
428             } else if (ofm->ofm.header.type != OFPT_FLOW_MOD) {
429                 VLOG_DBG("recv_fp_flow bad return message type");
430                 buffer_delete(reply);
431                 return EPROTO;
432             }
433
434             ofp_print_flow_mod(stdout, &ofm->ofm, 
435                     sizeof(struct ofp_flow_mod), 1);
436             putc('\n', stdout);
437         }
438
439         buffer_delete(reply);
440         retval = nl_sock_recv(dp->sock, &reply, true);
441         if (retval) {
442             return retval;
443         }
444     }
445     return 0;
446 }
447
448 /* Tells dp to send num_packets up through netlink for benchmarking*/
449 int
450 dpif_benchmark_nl(struct dpif *dp, uint32_t num_packets, uint32_t packet_size)
451 {
452     struct buffer request;
453     int retval;
454
455     buffer_init(&request, 0);
456     nl_msg_put_genlmsghdr(&request, dp->sock, 0, openflow_family,
457                           NLM_F_REQUEST, DP_GENL_C_BENCHMARK_NL, 1);
458     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp->dp_idx);
459     nl_msg_put_u32(&request, DP_GENL_A_NPACKETS, num_packets);
460     nl_msg_put_u32(&request, DP_GENL_A_PSIZE, packet_size);
461     retval = nl_sock_send(dp->sock, &request, true);
462     buffer_uninit(&request);
463
464     return retval;
465 }
466 \f
467 static const struct nl_policy openflow_multicast_policy[] = {
468     [DP_GENL_A_DP_IDX] = { .type = NL_A_U32 },
469     [DP_GENL_A_MC_GROUP] = { .type = NL_A_U32 },
470 };
471
472 /* Looks up the Netlink multicast group used by datapath 'dp_idx'.  If
473  * successful, stores the multicast group in '*multicast_group' and returns 0.
474  * Otherwise, returns a positve errno value. */
475 static int
476 lookup_openflow_multicast_group(int dp_idx, int *multicast_group) 
477 {
478     struct nl_sock *sock;
479     struct buffer request, *reply;
480     struct nlattr *attrs[ARRAY_SIZE(openflow_multicast_policy)];
481     int retval;
482
483     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
484     if (retval) {
485         return retval;
486     }
487     buffer_init(&request, 0);
488     nl_msg_put_genlmsghdr(&request, sock, 0, openflow_family, NLM_F_REQUEST,
489                           DP_GENL_C_QUERY_DP, 1);
490     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp_idx);
491     retval = nl_sock_transact(sock, &request, &reply);
492     buffer_uninit(&request);
493     if (retval) {
494         nl_sock_destroy(sock);
495         return retval;
496     }
497     if (!nl_policy_parse(reply, openflow_multicast_policy, attrs,
498                          ARRAY_SIZE(openflow_multicast_policy))) {
499         nl_sock_destroy(sock);
500         buffer_delete(reply);
501         return EPROTO;
502     }
503     *multicast_group = nl_attr_get_u32(attrs[DP_GENL_A_MC_GROUP]);
504     nl_sock_destroy(sock);
505     buffer_delete(reply);
506
507     return 0;
508 }
509
510 /* Sends the given 'command' to datapath 'dp'.  If 'netdev' is nonnull, adds it
511  * to the command as the port name attribute.  Returns 0 if successful,
512  * otherwise a positive errno value. */
513 static int
514 send_mgmt_command(struct dpif *dp, int command, const char *netdev) 
515 {
516     struct buffer request, *reply;
517     int retval;
518
519     buffer_init(&request, 0);
520     nl_msg_put_genlmsghdr(&request, dp->sock, 32, openflow_family,
521                           NLM_F_REQUEST | NLM_F_ACK, command, 1);
522     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp->dp_idx);
523     if (netdev) {
524         nl_msg_put_string(&request, DP_GENL_A_PORTNAME, netdev);
525     }
526     retval = nl_sock_transact(dp->sock, &request, &reply);
527     buffer_uninit(&request);
528     buffer_delete(reply);
529
530     return retval;
531 }