block/export: Allocate BlockExport in blk_exp_add()
[qemu.git] / block / export / export.c
blob6b2b29078bb4286209d03d7a0f08e9cb417cf771
1 /*
2 * Common block export infrastructure
4 * Copyright (c) 2012, 2020 Red Hat, Inc.
6 * Authors:
7 * Paolo Bonzini <pbonzini@redhat.com>
8 * Kevin Wolf <kwolf@redhat.com>
10 * This work is licensed under the terms of the GNU GPL, version 2 or
11 * later. See the COPYING file in the top-level directory.
14 #include "qemu/osdep.h"
16 #include "block/block.h"
17 #include "sysemu/block-backend.h"
18 #include "block/export.h"
19 #include "block/nbd.h"
20 #include "qapi/error.h"
21 #include "qapi/qapi-commands-block-export.h"
23 static const BlockExportDriver *blk_exp_drivers[] = {
24 &blk_exp_nbd,
27 static const BlockExportDriver *blk_exp_find_driver(BlockExportType type)
29 int i;
31 for (i = 0; i < ARRAY_SIZE(blk_exp_drivers); i++) {
32 if (blk_exp_drivers[i]->type == type) {
33 return blk_exp_drivers[i];
36 return NULL;
39 BlockExport *blk_exp_add(BlockExportOptions *export, Error **errp)
41 const BlockExportDriver *drv;
42 BlockExport *exp;
43 int ret;
45 drv = blk_exp_find_driver(export->type);
46 if (!drv) {
47 error_setg(errp, "No driver found for the requested export type");
48 return NULL;
51 assert(drv->instance_size >= sizeof(BlockExport));
52 exp = g_malloc0(drv->instance_size);
53 *exp = (BlockExport) {
54 .drv = drv,
55 .refcount = 1,
58 ret = drv->create(exp, export, errp);
59 if (ret < 0) {
60 g_free(exp);
61 return NULL;
64 return exp;
67 /* Callers must hold exp->ctx lock */
68 void blk_exp_ref(BlockExport *exp)
70 assert(exp->refcount > 0);
71 exp->refcount++;
74 /* Callers must hold exp->ctx lock */
75 void blk_exp_unref(BlockExport *exp)
77 assert(exp->refcount > 0);
78 if (--exp->refcount == 0) {
79 exp->drv->delete(exp);
80 g_free(exp);
84 void qmp_block_export_add(BlockExportOptions *export, Error **errp)
86 blk_exp_add(export, errp);