]> Git Repo - qemu.git/blob - block/nbd-client.c
qcow2: Implement .bdrv_inactivate
[qemu.git] / block / nbd-client.c
1 /*
2  * QEMU Block driver for  NBD
3  *
4  * Copyright (C) 2008 Bull S.A.S.
5  *     Author: Laurent Vivier <[email protected]>
6  *
7  * Some parts:
8  *    Copyright (C) 2007 Anthony Liguori <[email protected]>
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining a copy
11  * of this software and associated documentation files (the "Software"), to deal
12  * in the Software without restriction, including without limitation the rights
13  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14  * copies of the Software, and to permit persons to whom the Software is
15  * furnished to do so, subject to the following conditions:
16  *
17  * The above copyright notice and this permission notice shall be included in
18  * all copies or substantial portions of the Software.
19  *
20  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
23  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26  * THE SOFTWARE.
27  */
28
29 #include "qemu/osdep.h"
30 #include "nbd-client.h"
31 #include "qemu/sockets.h"
32
33 #define HANDLE_TO_INDEX(bs, handle) ((handle) ^ ((uint64_t)(intptr_t)bs))
34 #define INDEX_TO_HANDLE(bs, index)  ((index)  ^ ((uint64_t)(intptr_t)bs))
35
36 static void nbd_recv_coroutines_enter_all(NbdClientSession *s)
37 {
38     int i;
39
40     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
41         if (s->recv_coroutine[i]) {
42             qemu_coroutine_enter(s->recv_coroutine[i], NULL);
43         }
44     }
45 }
46
47 static void nbd_teardown_connection(BlockDriverState *bs)
48 {
49     NbdClientSession *client = nbd_get_client_session(bs);
50
51     /* finish any pending coroutines */
52     shutdown(client->sock, 2);
53     nbd_recv_coroutines_enter_all(client);
54
55     nbd_client_detach_aio_context(bs);
56     closesocket(client->sock);
57     client->sock = -1;
58 }
59
60 static void nbd_reply_ready(void *opaque)
61 {
62     BlockDriverState *bs = opaque;
63     NbdClientSession *s = nbd_get_client_session(bs);
64     uint64_t i;
65     int ret;
66
67     if (s->reply.handle == 0) {
68         /* No reply already in flight.  Fetch a header.  It is possible
69          * that another thread has done the same thing in parallel, so
70          * the socket is not readable anymore.
71          */
72         ret = nbd_receive_reply(s->sock, &s->reply);
73         if (ret == -EAGAIN) {
74             return;
75         }
76         if (ret < 0) {
77             s->reply.handle = 0;
78             goto fail;
79         }
80     }
81
82     /* There's no need for a mutex on the receive side, because the
83      * handler acts as a synchronization point and ensures that only
84      * one coroutine is called until the reply finishes.  */
85     i = HANDLE_TO_INDEX(s, s->reply.handle);
86     if (i >= MAX_NBD_REQUESTS) {
87         goto fail;
88     }
89
90     if (s->recv_coroutine[i]) {
91         qemu_coroutine_enter(s->recv_coroutine[i], NULL);
92         return;
93     }
94
95 fail:
96     nbd_teardown_connection(bs);
97 }
98
99 static void nbd_restart_write(void *opaque)
100 {
101     BlockDriverState *bs = opaque;
102
103     qemu_coroutine_enter(nbd_get_client_session(bs)->send_coroutine, NULL);
104 }
105
106 static int nbd_co_send_request(BlockDriverState *bs,
107                                struct nbd_request *request,
108                                QEMUIOVector *qiov, int offset)
109 {
110     NbdClientSession *s = nbd_get_client_session(bs);
111     AioContext *aio_context;
112     int rc, ret, i;
113
114     qemu_co_mutex_lock(&s->send_mutex);
115
116     for (i = 0; i < MAX_NBD_REQUESTS; i++) {
117         if (s->recv_coroutine[i] == NULL) {
118             s->recv_coroutine[i] = qemu_coroutine_self();
119             break;
120         }
121     }
122
123     assert(i < MAX_NBD_REQUESTS);
124     request->handle = INDEX_TO_HANDLE(s, i);
125     s->send_coroutine = qemu_coroutine_self();
126     aio_context = bdrv_get_aio_context(bs);
127
128     aio_set_fd_handler(aio_context, s->sock, false,
129                        nbd_reply_ready, nbd_restart_write, bs);
130     if (qiov) {
131         if (!s->is_unix) {
132             socket_set_cork(s->sock, 1);
133         }
134         rc = nbd_send_request(s->sock, request);
135         if (rc >= 0) {
136             ret = qemu_co_sendv(s->sock, qiov->iov, qiov->niov,
137                                 offset, request->len);
138             if (ret != request->len) {
139                 rc = -EIO;
140             }
141         }
142         if (!s->is_unix) {
143             socket_set_cork(s->sock, 0);
144         }
145     } else {
146         rc = nbd_send_request(s->sock, request);
147     }
148     aio_set_fd_handler(aio_context, s->sock, false,
149                        nbd_reply_ready, NULL, bs);
150     s->send_coroutine = NULL;
151     qemu_co_mutex_unlock(&s->send_mutex);
152     return rc;
153 }
154
155 static void nbd_co_receive_reply(NbdClientSession *s,
156     struct nbd_request *request, struct nbd_reply *reply,
157     QEMUIOVector *qiov, int offset)
158 {
159     int ret;
160
161     /* Wait until we're woken up by the read handler.  TODO: perhaps
162      * peek at the next reply and avoid yielding if it's ours?  */
163     qemu_coroutine_yield();
164     *reply = s->reply;
165     if (reply->handle != request->handle) {
166         reply->error = EIO;
167     } else {
168         if (qiov && reply->error == 0) {
169             ret = qemu_co_recvv(s->sock, qiov->iov, qiov->niov,
170                                 offset, request->len);
171             if (ret != request->len) {
172                 reply->error = EIO;
173             }
174         }
175
176         /* Tell the read handler to read another header.  */
177         s->reply.handle = 0;
178     }
179 }
180
181 static void nbd_coroutine_start(NbdClientSession *s,
182    struct nbd_request *request)
183 {
184     /* Poor man semaphore.  The free_sema is locked when no other request
185      * can be accepted, and unlocked after receiving one reply.  */
186     if (s->in_flight >= MAX_NBD_REQUESTS - 1) {
187         qemu_co_mutex_lock(&s->free_sema);
188         assert(s->in_flight < MAX_NBD_REQUESTS);
189     }
190     s->in_flight++;
191
192     /* s->recv_coroutine[i] is set as soon as we get the send_lock.  */
193 }
194
195 static void nbd_coroutine_end(NbdClientSession *s,
196     struct nbd_request *request)
197 {
198     int i = HANDLE_TO_INDEX(s, request->handle);
199     s->recv_coroutine[i] = NULL;
200     if (s->in_flight-- == MAX_NBD_REQUESTS) {
201         qemu_co_mutex_unlock(&s->free_sema);
202     }
203 }
204
205 static int nbd_co_readv_1(BlockDriverState *bs, int64_t sector_num,
206                           int nb_sectors, QEMUIOVector *qiov,
207                           int offset)
208 {
209     NbdClientSession *client = nbd_get_client_session(bs);
210     struct nbd_request request = { .type = NBD_CMD_READ };
211     struct nbd_reply reply;
212     ssize_t ret;
213
214     request.from = sector_num * 512;
215     request.len = nb_sectors * 512;
216
217     nbd_coroutine_start(client, &request);
218     ret = nbd_co_send_request(bs, &request, NULL, 0);
219     if (ret < 0) {
220         reply.error = -ret;
221     } else {
222         nbd_co_receive_reply(client, &request, &reply, qiov, offset);
223     }
224     nbd_coroutine_end(client, &request);
225     return -reply.error;
226
227 }
228
229 static int nbd_co_writev_1(BlockDriverState *bs, int64_t sector_num,
230                            int nb_sectors, QEMUIOVector *qiov,
231                            int offset)
232 {
233     NbdClientSession *client = nbd_get_client_session(bs);
234     struct nbd_request request = { .type = NBD_CMD_WRITE };
235     struct nbd_reply reply;
236     ssize_t ret;
237
238     if (!bdrv_enable_write_cache(bs) &&
239         (client->nbdflags & NBD_FLAG_SEND_FUA)) {
240         request.type |= NBD_CMD_FLAG_FUA;
241     }
242
243     request.from = sector_num * 512;
244     request.len = nb_sectors * 512;
245
246     nbd_coroutine_start(client, &request);
247     ret = nbd_co_send_request(bs, &request, qiov, offset);
248     if (ret < 0) {
249         reply.error = -ret;
250     } else {
251         nbd_co_receive_reply(client, &request, &reply, NULL, 0);
252     }
253     nbd_coroutine_end(client, &request);
254     return -reply.error;
255 }
256
257 /* qemu-nbd has a limit of slightly less than 1M per request.  Try to
258  * remain aligned to 4K. */
259 #define NBD_MAX_SECTORS 2040
260
261 int nbd_client_co_readv(BlockDriverState *bs, int64_t sector_num,
262                         int nb_sectors, QEMUIOVector *qiov)
263 {
264     int offset = 0;
265     int ret;
266     while (nb_sectors > NBD_MAX_SECTORS) {
267         ret = nbd_co_readv_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
268         if (ret < 0) {
269             return ret;
270         }
271         offset += NBD_MAX_SECTORS * 512;
272         sector_num += NBD_MAX_SECTORS;
273         nb_sectors -= NBD_MAX_SECTORS;
274     }
275     return nbd_co_readv_1(bs, sector_num, nb_sectors, qiov, offset);
276 }
277
278 int nbd_client_co_writev(BlockDriverState *bs, int64_t sector_num,
279                          int nb_sectors, QEMUIOVector *qiov)
280 {
281     int offset = 0;
282     int ret;
283     while (nb_sectors > NBD_MAX_SECTORS) {
284         ret = nbd_co_writev_1(bs, sector_num, NBD_MAX_SECTORS, qiov, offset);
285         if (ret < 0) {
286             return ret;
287         }
288         offset += NBD_MAX_SECTORS * 512;
289         sector_num += NBD_MAX_SECTORS;
290         nb_sectors -= NBD_MAX_SECTORS;
291     }
292     return nbd_co_writev_1(bs, sector_num, nb_sectors, qiov, offset);
293 }
294
295 int nbd_client_co_flush(BlockDriverState *bs)
296 {
297     NbdClientSession *client = nbd_get_client_session(bs);
298     struct nbd_request request = { .type = NBD_CMD_FLUSH };
299     struct nbd_reply reply;
300     ssize_t ret;
301
302     if (!(client->nbdflags & NBD_FLAG_SEND_FLUSH)) {
303         return 0;
304     }
305
306     if (client->nbdflags & NBD_FLAG_SEND_FUA) {
307         request.type |= NBD_CMD_FLAG_FUA;
308     }
309
310     request.from = 0;
311     request.len = 0;
312
313     nbd_coroutine_start(client, &request);
314     ret = nbd_co_send_request(bs, &request, NULL, 0);
315     if (ret < 0) {
316         reply.error = -ret;
317     } else {
318         nbd_co_receive_reply(client, &request, &reply, NULL, 0);
319     }
320     nbd_coroutine_end(client, &request);
321     return -reply.error;
322 }
323
324 int nbd_client_co_discard(BlockDriverState *bs, int64_t sector_num,
325                           int nb_sectors)
326 {
327     NbdClientSession *client = nbd_get_client_session(bs);
328     struct nbd_request request = { .type = NBD_CMD_TRIM };
329     struct nbd_reply reply;
330     ssize_t ret;
331
332     if (!(client->nbdflags & NBD_FLAG_SEND_TRIM)) {
333         return 0;
334     }
335     request.from = sector_num * 512;
336     request.len = nb_sectors * 512;
337
338     nbd_coroutine_start(client, &request);
339     ret = nbd_co_send_request(bs, &request, NULL, 0);
340     if (ret < 0) {
341         reply.error = -ret;
342     } else {
343         nbd_co_receive_reply(client, &request, &reply, NULL, 0);
344     }
345     nbd_coroutine_end(client, &request);
346     return -reply.error;
347
348 }
349
350 void nbd_client_detach_aio_context(BlockDriverState *bs)
351 {
352     aio_set_fd_handler(bdrv_get_aio_context(bs),
353                        nbd_get_client_session(bs)->sock,
354                        false, NULL, NULL, NULL);
355 }
356
357 void nbd_client_attach_aio_context(BlockDriverState *bs,
358                                    AioContext *new_context)
359 {
360     aio_set_fd_handler(new_context, nbd_get_client_session(bs)->sock,
361                        false, nbd_reply_ready, NULL, bs);
362 }
363
364 void nbd_client_close(BlockDriverState *bs)
365 {
366     NbdClientSession *client = nbd_get_client_session(bs);
367     struct nbd_request request = {
368         .type = NBD_CMD_DISC,
369         .from = 0,
370         .len = 0
371     };
372
373     if (client->sock == -1) {
374         return;
375     }
376
377     nbd_send_request(client->sock, &request);
378
379     nbd_teardown_connection(bs);
380 }
381
382 int nbd_client_init(BlockDriverState *bs, int sock, const char *export,
383                     Error **errp)
384 {
385     NbdClientSession *client = nbd_get_client_session(bs);
386     int ret;
387
388     /* NBD handshake */
389     logout("session init %s\n", export);
390     qemu_set_block(sock);
391     ret = nbd_receive_negotiate(sock, export,
392                                 &client->nbdflags, &client->size, errp);
393     if (ret < 0) {
394         logout("Failed to negotiate with the NBD server\n");
395         closesocket(sock);
396         return ret;
397     }
398
399     qemu_co_mutex_init(&client->send_mutex);
400     qemu_co_mutex_init(&client->free_sema);
401     client->sock = sock;
402
403     /* Now that we're connected, set the socket to be non-blocking and
404      * kick the reply mechanism.  */
405     qemu_set_nonblock(sock);
406     nbd_client_attach_aio_context(bs, bdrv_get_aio_context(bs));
407
408     logout("Established connection with NBD server\n");
409     return 0;
410 }
This page took 0.044453 seconds and 4 git commands to generate.