Merge branch 'locking'
[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 <config.h>
35 #include "dpif.h"
36
37 #include <ctype.h>
38 #include <errno.h>
39 #include <inttypes.h>
40 #include <netinet/in.h>
41 #include <stdlib.h>
42 #include <string.h>
43
44 #include "buffer.h"
45 #include "netlink.h"
46 #include "netlink-protocol.h"
47 #include "ofp-print.h"
48 #include "openflow-netlink.h"
49 #include "openflow.h"
50 #include "packets.h"
51 #include "util.h"
52 #include "xtoxll.h"
53
54 #include "vlog.h"
55 #define THIS_MODULE VLM_dpif
56
57 /* The Generic Netlink family number used for OpenFlow. */
58 static int openflow_family;
59
60 static int lookup_openflow_multicast_group(int dp_idx, int *multicast_group);
61 static int send_mgmt_command(struct dpif *, int command,
62                              const char *netdev);
63
64 /* Opens the local datapath numbered 'dp_idx', initializing 'dp'.  If
65  * 'subscribe' is true, listens for asynchronous messages (packet-in, etc.)
66  * from the datapath; otherwise, 'dp' will receive only replies to explicitly
67  * initiated requests. */
68 int
69 dpif_open(int dp_idx, bool subscribe, struct dpif *dp)
70 {
71     struct nl_sock *sock;
72     int multicast_group = 0;
73     int retval;
74
75     retval = nl_lookup_genl_family(DP_GENL_FAMILY_NAME, &openflow_family);
76     if (retval) {
77         return retval;
78     }
79
80     if (subscribe) {
81         retval = lookup_openflow_multicast_group(dp_idx, &multicast_group);
82         if (retval) {
83             return retval;
84         }
85     }
86
87     /* Specify a large so_rcvbuf size because we occasionally need to be able
88      * to retrieve large collections of flow records. */
89     retval = nl_sock_create(NETLINK_GENERIC, multicast_group, 0,
90                             4 * 1024u * 1024, &sock);
91     if (retval) {
92         return retval;
93     }
94
95     dp->dp_idx = dp_idx;
96     dp->sock = sock;
97     return 0;
98 }
99
100 /* Closes 'dp'. */
101 void
102 dpif_close(struct dpif *dp) 
103 {
104     nl_sock_destroy(dp->sock);
105 }
106
107 static const struct nl_policy openflow_policy[] = {
108     [DP_GENL_A_DP_IDX] = { .type = NL_A_U32 },
109     [DP_GENL_A_OPENFLOW] = { .type = NL_A_UNSPEC,
110                               .min_len = sizeof(struct ofp_header),
111                               .max_len = OFP_MAXLEN },
112 };
113
114 /* Tries to receive an openflow message from the kernel on 'sock'.  If
115  * successful, stores the received message into '*msgp' and returns 0.  The
116  * caller is responsible for destroying the message with buffer_delete().  On
117  * failure, returns a positive errno value and stores a null pointer into
118  * '*msgp'.
119  *
120  * Only Netlink messages with embedded OpenFlow messages are accepted.  Other
121  * Netlink messages provoke errors.
122  *
123  * If 'wait' is true, dpif_recv_openflow waits for a message to be ready;
124  * otherwise, returns EAGAIN if the 'sock' receive buffer is empty. */
125 int
126 dpif_recv_openflow(struct dpif *dp, struct buffer **bufferp,
127                         bool wait) 
128 {
129     struct nlattr *attrs[ARRAY_SIZE(openflow_policy)];
130     struct buffer *buffer;
131     struct ofp_header *oh;
132     uint16_t ofp_len;
133     int retval;
134
135     buffer = *bufferp = NULL;
136     do {
137         buffer_delete(buffer);
138         retval = nl_sock_recv(dp->sock, &buffer, wait);
139     } while (retval == ENOBUFS
140              || (!retval
141                  && (nl_msg_nlmsgerr(buffer, NULL)
142                      || nl_msg_nlmsghdr(buffer)->nlmsg_type == NLMSG_DONE)));
143     if (retval) {
144         if (retval != EAGAIN) {
145             VLOG_WARN("dpif_recv_openflow: %s", strerror(retval)); 
146         }
147         return retval;
148     }
149
150     if (nl_msg_genlmsghdr(buffer) == NULL) {
151         VLOG_DBG("received packet too short for Generic Netlink");
152         goto error;
153     }
154     if (nl_msg_nlmsghdr(buffer)->nlmsg_type != openflow_family) {
155         VLOG_DBG("received type (%"PRIu16") != openflow family (%d)",
156                  nl_msg_nlmsghdr(buffer)->nlmsg_type, openflow_family);
157         goto error;
158     }
159
160     if (!nl_policy_parse(buffer, openflow_policy, attrs,
161                          ARRAY_SIZE(openflow_policy))) {
162         goto error;
163     }
164     if (nl_attr_get_u32(attrs[DP_GENL_A_DP_IDX]) != dp->dp_idx) {
165         VLOG_WARN("received dp_idx (%"PRIu32") differs from expected (%d)",
166                   nl_attr_get_u32(attrs[DP_GENL_A_DP_IDX]), dp->dp_idx);
167         goto error;
168     }
169
170     oh = buffer->data = (void *) nl_attr_get(attrs[DP_GENL_A_OPENFLOW]);
171     buffer->size = nl_attr_get_size(attrs[DP_GENL_A_OPENFLOW]);
172     ofp_len = ntohs(oh->length);
173     if (ofp_len != buffer->size) {
174         VLOG_WARN("ofp_header.length %"PRIu16" != attribute length %zu\n",
175                   ofp_len, buffer->size);
176         buffer->size = MIN(ofp_len, buffer->size);
177     }
178     *bufferp = buffer;
179     return 0;
180
181 error:
182     buffer_delete(buffer);
183     return EPROTO;
184 }
185
186 /* Encapsulates 'msg', which must contain an OpenFlow message, in a Netlink
187  * message, and sends it to the OpenFlow kernel module via 'sock'.
188  *
189  * Returns 0 if successful, otherwise a positive errno value.  If
190  * 'wait' is true, then the send will wait until buffer space is ready;
191  * otherwise, returns EAGAIN if the 'sock' send buffer is full.
192  *
193  * If the send is successful, then the kernel module will receive it, but there
194  * is no guarantee that any reply will not be dropped (see nl_sock_transact()
195  * for details). 
196  */
197 int
198 dpif_send_openflow(struct dpif *dp, struct buffer *buffer, bool wait) 
199 {
200     struct ofp_header *oh;
201     unsigned int dump_flag;
202     struct buffer hdr;
203     struct nlattr *nla;
204     uint32_t fixed_buffer[64 / 4];
205     struct iovec iov[3];
206     int pad_bytes;
207     int n_iov;
208     int retval;
209
210     /* The reply to OFPT_STATS_REQUEST may be multiple segments long, so we
211      * need to specify NLM_F_DUMP in the request. */
212     oh = buffer_at_assert(buffer, 0, sizeof *oh);
213     dump_flag = oh->type == OFPT_STATS_REQUEST ? NLM_F_DUMP : 0;
214
215     buffer_use(&hdr, fixed_buffer, sizeof fixed_buffer);
216     nl_msg_put_genlmsghdr(&hdr, dp->sock, 32, openflow_family,
217                           NLM_F_REQUEST | dump_flag, DP_GENL_C_OPENFLOW, 1);
218     nl_msg_put_u32(&hdr, DP_GENL_A_DP_IDX, dp->dp_idx);
219     nla = buffer_put_uninit(&hdr, sizeof *nla);
220     nla->nla_len = sizeof *nla + buffer->size;
221     nla->nla_type = DP_GENL_A_OPENFLOW;
222     pad_bytes = NLA_ALIGN(nla->nla_len) - nla->nla_len;
223     nl_msg_nlmsghdr(&hdr)->nlmsg_len = hdr.size + buffer->size + pad_bytes;
224     n_iov = 2;
225     iov[0].iov_base = hdr.data;
226     iov[0].iov_len = hdr.size;
227     iov[1].iov_base = buffer->data;
228     iov[1].iov_len = buffer->size;
229     if (pad_bytes) {
230         static char zeros[NLA_ALIGNTO];
231         n_iov++;
232         iov[2].iov_base = zeros;
233         iov[2].iov_len = pad_bytes; 
234     }
235     retval = nl_sock_sendv(dp->sock, iov, n_iov, false);
236     if (retval && retval != EAGAIN) {
237         VLOG_WARN("dpif_send_openflow: %s", strerror(retval));
238     }
239     return retval;
240 }
241
242 /* Creates the datapath represented by 'dp'.  Returns 0 if successful,
243  * otherwise a positive errno value. */
244 int
245 dpif_add_dp(struct dpif *dp)
246 {
247     return send_mgmt_command(dp, DP_GENL_C_ADD_DP, NULL);
248 }
249
250 /* Destroys the datapath represented by 'dp'.  Returns 0 if successful,
251  * otherwise a positive errno value. */
252 int
253 dpif_del_dp(struct dpif *dp) 
254 {
255     return send_mgmt_command(dp, DP_GENL_C_DEL_DP, NULL);
256 }
257
258 /* Adds the Ethernet device named 'netdev' to this datapath.  Returns 0 if
259  * successful, otherwise a positive errno value. */
260 int
261 dpif_add_port(struct dpif *dp, const char *netdev)
262 {
263     return send_mgmt_command(dp, DP_GENL_C_ADD_PORT, netdev);
264 }
265
266 /* Removes the Ethernet device named 'netdev' from this datapath.  Returns 0
267  * if successful, otherwise a positive errno value. */
268 int
269 dpif_del_port(struct dpif *dp, const char *netdev)
270 {
271     return send_mgmt_command(dp, DP_GENL_C_DEL_PORT, netdev);
272 }
273 \f
274 static const struct nl_policy openflow_multicast_policy[] = {
275     [DP_GENL_A_DP_IDX] = { .type = NL_A_U32 },
276     [DP_GENL_A_MC_GROUP] = { .type = NL_A_U32 },
277 };
278
279 /* Looks up the Netlink multicast group used by datapath 'dp_idx'.  If
280  * successful, stores the multicast group in '*multicast_group' and returns 0.
281  * Otherwise, returns a positve errno value. */
282 static int
283 lookup_openflow_multicast_group(int dp_idx, int *multicast_group) 
284 {
285     struct nl_sock *sock;
286     struct buffer request, *reply;
287     struct nlattr *attrs[ARRAY_SIZE(openflow_multicast_policy)];
288     int retval;
289
290     retval = nl_sock_create(NETLINK_GENERIC, 0, 0, 0, &sock);
291     if (retval) {
292         return retval;
293     }
294     buffer_init(&request, 0);
295     nl_msg_put_genlmsghdr(&request, sock, 0, openflow_family, NLM_F_REQUEST,
296                           DP_GENL_C_QUERY_DP, 1);
297     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp_idx);
298     retval = nl_sock_transact(sock, &request, &reply);
299     buffer_uninit(&request);
300     if (retval) {
301         nl_sock_destroy(sock);
302         return retval;
303     }
304     if (!nl_policy_parse(reply, openflow_multicast_policy, attrs,
305                          ARRAY_SIZE(openflow_multicast_policy))) {
306         nl_sock_destroy(sock);
307         buffer_delete(reply);
308         return EPROTO;
309     }
310     *multicast_group = nl_attr_get_u32(attrs[DP_GENL_A_MC_GROUP]);
311     nl_sock_destroy(sock);
312     buffer_delete(reply);
313
314     return 0;
315 }
316
317 /* Sends the given 'command' to datapath 'dp'.  If 'netdev' is nonnull, adds it
318  * to the command as the port name attribute.  Returns 0 if successful,
319  * otherwise a positive errno value. */
320 static int
321 send_mgmt_command(struct dpif *dp, int command, const char *netdev) 
322 {
323     struct buffer request, *reply;
324     int retval;
325
326     buffer_init(&request, 0);
327     nl_msg_put_genlmsghdr(&request, dp->sock, 32, openflow_family,
328                           NLM_F_REQUEST | NLM_F_ACK, command, 1);
329     nl_msg_put_u32(&request, DP_GENL_A_DP_IDX, dp->dp_idx);
330     if (netdev) {
331         nl_msg_put_string(&request, DP_GENL_A_PORTNAME, netdev);
332     }
333     retval = nl_sock_transact(dp->sock, &request, &reply);
334     buffer_uninit(&request);
335     buffer_delete(reply);
336
337     return retval;
338 }