You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6231 lines
187KB

  1. /*
  2. * QEMU System Emulator block driver
  3. *
  4. * Copyright (c) 2003 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include "block/trace.h"
  26. #include "block/block_int.h"
  27. #include "block/blockjob.h"
  28. #include "block/nbd.h"
  29. #include "block/qdict.h"
  30. #include "qemu/error-report.h"
  31. #include "module_block.h"
  32. #include "qemu/module.h"
  33. #include "qapi/error.h"
  34. #include "qapi/qmp/qdict.h"
  35. #include "qapi/qmp/qjson.h"
  36. #include "qapi/qmp/qnull.h"
  37. #include "qapi/qmp/qstring.h"
  38. #include "qapi/qobject-output-visitor.h"
  39. #include "qapi/qapi-visit-block-core.h"
  40. #include "sysemu/block-backend.h"
  41. #include "sysemu/sysemu.h"
  42. #include "qemu/notify.h"
  43. #include "qemu/option.h"
  44. #include "qemu/coroutine.h"
  45. #include "block/qapi.h"
  46. #include "qemu/timer.h"
  47. #include "qemu/cutils.h"
  48. #include "qemu/id.h"
  49. #ifdef CONFIG_BSD
  50. #include <sys/ioctl.h>
  51. #include <sys/queue.h>
  52. #ifndef __DragonFly__
  53. #include <sys/disk.h>
  54. #endif
  55. #endif
  56. #ifdef _WIN32
  57. #include <windows.h>
  58. #endif
  59. #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
  60. static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
  61. QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
  62. static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
  63. QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
  64. static QLIST_HEAD(, BlockDriver) bdrv_drivers =
  65. QLIST_HEAD_INITIALIZER(bdrv_drivers);
  66. static BlockDriverState *bdrv_open_inherit(const char *filename,
  67. const char *reference,
  68. QDict *options, int flags,
  69. BlockDriverState *parent,
  70. const BdrvChildRole *child_role,
  71. Error **errp);
  72. /* If non-zero, use only whitelisted block drivers */
  73. static int use_bdrv_whitelist;
  74. #ifdef _WIN32
  75. static int is_windows_drive_prefix(const char *filename)
  76. {
  77. return (((filename[0] >= 'a' && filename[0] <= 'z') ||
  78. (filename[0] >= 'A' && filename[0] <= 'Z')) &&
  79. filename[1] == ':');
  80. }
  81. int is_windows_drive(const char *filename)
  82. {
  83. if (is_windows_drive_prefix(filename) &&
  84. filename[2] == '\0')
  85. return 1;
  86. if (strstart(filename, "\\\\.\\", NULL) ||
  87. strstart(filename, "//./", NULL))
  88. return 1;
  89. return 0;
  90. }
  91. #endif
  92. size_t bdrv_opt_mem_align(BlockDriverState *bs)
  93. {
  94. if (!bs || !bs->drv) {
  95. /* page size or 4k (hdd sector size) should be on the safe side */
  96. return MAX(4096, getpagesize());
  97. }
  98. return bs->bl.opt_mem_alignment;
  99. }
  100. size_t bdrv_min_mem_align(BlockDriverState *bs)
  101. {
  102. if (!bs || !bs->drv) {
  103. /* page size or 4k (hdd sector size) should be on the safe side */
  104. return MAX(4096, getpagesize());
  105. }
  106. return bs->bl.min_mem_alignment;
  107. }
  108. /* check if the path starts with "<protocol>:" */
  109. int path_has_protocol(const char *path)
  110. {
  111. const char *p;
  112. #ifdef _WIN32
  113. if (is_windows_drive(path) ||
  114. is_windows_drive_prefix(path)) {
  115. return 0;
  116. }
  117. p = path + strcspn(path, ":/\\");
  118. #else
  119. p = path + strcspn(path, ":/");
  120. #endif
  121. return *p == ':';
  122. }
  123. int path_is_absolute(const char *path)
  124. {
  125. #ifdef _WIN32
  126. /* specific case for names like: "\\.\d:" */
  127. if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
  128. return 1;
  129. }
  130. return (*path == '/' || *path == '\\');
  131. #else
  132. return (*path == '/');
  133. #endif
  134. }
  135. /* if filename is absolute, just return its duplicate. Otherwise, build a
  136. path to it by considering it is relative to base_path. URL are
  137. supported. */
  138. char *path_combine(const char *base_path, const char *filename)
  139. {
  140. const char *protocol_stripped = NULL;
  141. const char *p, *p1;
  142. char *result;
  143. int len;
  144. if (path_is_absolute(filename)) {
  145. return g_strdup(filename);
  146. }
  147. if (path_has_protocol(base_path)) {
  148. protocol_stripped = strchr(base_path, ':');
  149. if (protocol_stripped) {
  150. protocol_stripped++;
  151. }
  152. }
  153. p = protocol_stripped ?: base_path;
  154. p1 = strrchr(base_path, '/');
  155. #ifdef _WIN32
  156. {
  157. const char *p2;
  158. p2 = strrchr(base_path, '\\');
  159. if (!p1 || p2 > p1) {
  160. p1 = p2;
  161. }
  162. }
  163. #endif
  164. if (p1) {
  165. p1++;
  166. } else {
  167. p1 = base_path;
  168. }
  169. if (p1 > p) {
  170. p = p1;
  171. }
  172. len = p - base_path;
  173. result = g_malloc(len + strlen(filename) + 1);
  174. memcpy(result, base_path, len);
  175. strcpy(result + len, filename);
  176. return result;
  177. }
  178. /*
  179. * Helper function for bdrv_parse_filename() implementations to remove optional
  180. * protocol prefixes (especially "file:") from a filename and for putting the
  181. * stripped filename into the options QDict if there is such a prefix.
  182. */
  183. void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
  184. QDict *options)
  185. {
  186. if (strstart(filename, prefix, &filename)) {
  187. /* Stripping the explicit protocol prefix may result in a protocol
  188. * prefix being (wrongly) detected (if the filename contains a colon) */
  189. if (path_has_protocol(filename)) {
  190. QString *fat_filename;
  191. /* This means there is some colon before the first slash; therefore,
  192. * this cannot be an absolute path */
  193. assert(!path_is_absolute(filename));
  194. /* And we can thus fix the protocol detection issue by prefixing it
  195. * by "./" */
  196. fat_filename = qstring_from_str("./");
  197. qstring_append(fat_filename, filename);
  198. assert(!path_has_protocol(qstring_get_str(fat_filename)));
  199. qdict_put(options, "filename", fat_filename);
  200. } else {
  201. /* If no protocol prefix was detected, we can use the shortened
  202. * filename as-is */
  203. qdict_put_str(options, "filename", filename);
  204. }
  205. }
  206. }
  207. /* Returns whether the image file is opened as read-only. Note that this can
  208. * return false and writing to the image file is still not possible because the
  209. * image is inactivated. */
  210. bool bdrv_is_read_only(BlockDriverState *bs)
  211. {
  212. return bs->read_only;
  213. }
  214. int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
  215. bool ignore_allow_rdw, Error **errp)
  216. {
  217. /* Do not set read_only if copy_on_read is enabled */
  218. if (bs->copy_on_read && read_only) {
  219. error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
  220. bdrv_get_device_or_node_name(bs));
  221. return -EINVAL;
  222. }
  223. /* Do not clear read_only if it is prohibited */
  224. if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
  225. !ignore_allow_rdw)
  226. {
  227. error_setg(errp, "Node '%s' is read only",
  228. bdrv_get_device_or_node_name(bs));
  229. return -EPERM;
  230. }
  231. return 0;
  232. }
  233. /*
  234. * Called by a driver that can only provide a read-only image.
  235. *
  236. * Returns 0 if the node is already read-only or it could switch the node to
  237. * read-only because BDRV_O_AUTO_RDONLY is set.
  238. *
  239. * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
  240. * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
  241. * is not NULL, it is used as the error message for the Error object.
  242. */
  243. int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
  244. Error **errp)
  245. {
  246. int ret = 0;
  247. if (!(bs->open_flags & BDRV_O_RDWR)) {
  248. return 0;
  249. }
  250. if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
  251. goto fail;
  252. }
  253. ret = bdrv_can_set_read_only(bs, true, false, NULL);
  254. if (ret < 0) {
  255. goto fail;
  256. }
  257. bs->read_only = true;
  258. bs->open_flags &= ~BDRV_O_RDWR;
  259. return 0;
  260. fail:
  261. error_setg(errp, "%s", errmsg ?: "Image is read-only");
  262. return -EACCES;
  263. }
  264. /*
  265. * If @backing is empty, this function returns NULL without setting
  266. * @errp. In all other cases, NULL will only be returned with @errp
  267. * set.
  268. *
  269. * Therefore, a return value of NULL without @errp set means that
  270. * there is no backing file; if @errp is set, there is one but its
  271. * absolute filename cannot be generated.
  272. */
  273. char *bdrv_get_full_backing_filename_from_filename(const char *backed,
  274. const char *backing,
  275. Error **errp)
  276. {
  277. if (backing[0] == '\0') {
  278. return NULL;
  279. } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
  280. return g_strdup(backing);
  281. } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
  282. error_setg(errp, "Cannot use relative backing file names for '%s'",
  283. backed);
  284. return NULL;
  285. } else {
  286. return path_combine(backed, backing);
  287. }
  288. }
  289. /*
  290. * If @filename is empty or NULL, this function returns NULL without
  291. * setting @errp. In all other cases, NULL will only be returned with
  292. * @errp set.
  293. */
  294. static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
  295. const char *filename, Error **errp)
  296. {
  297. char *dir, *full_name;
  298. if (!filename || filename[0] == '\0') {
  299. return NULL;
  300. } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
  301. return g_strdup(filename);
  302. }
  303. dir = bdrv_dirname(relative_to, errp);
  304. if (!dir) {
  305. return NULL;
  306. }
  307. full_name = g_strconcat(dir, filename, NULL);
  308. g_free(dir);
  309. return full_name;
  310. }
  311. char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
  312. {
  313. return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
  314. }
  315. void bdrv_register(BlockDriver *bdrv)
  316. {
  317. QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
  318. }
  319. BlockDriverState *bdrv_new(void)
  320. {
  321. BlockDriverState *bs;
  322. int i;
  323. bs = g_new0(BlockDriverState, 1);
  324. QLIST_INIT(&bs->dirty_bitmaps);
  325. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  326. QLIST_INIT(&bs->op_blockers[i]);
  327. }
  328. notifier_with_return_list_init(&bs->before_write_notifiers);
  329. qemu_co_mutex_init(&bs->reqs_lock);
  330. qemu_mutex_init(&bs->dirty_bitmap_mutex);
  331. bs->refcnt = 1;
  332. bs->aio_context = qemu_get_aio_context();
  333. qemu_co_queue_init(&bs->flush_queue);
  334. for (i = 0; i < bdrv_drain_all_count; i++) {
  335. bdrv_drained_begin(bs);
  336. }
  337. QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
  338. return bs;
  339. }
  340. static BlockDriver *bdrv_do_find_format(const char *format_name)
  341. {
  342. BlockDriver *drv1;
  343. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  344. if (!strcmp(drv1->format_name, format_name)) {
  345. return drv1;
  346. }
  347. }
  348. return NULL;
  349. }
  350. BlockDriver *bdrv_find_format(const char *format_name)
  351. {
  352. BlockDriver *drv1;
  353. int i;
  354. drv1 = bdrv_do_find_format(format_name);
  355. if (drv1) {
  356. return drv1;
  357. }
  358. /* The driver isn't registered, maybe we need to load a module */
  359. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  360. if (!strcmp(block_driver_modules[i].format_name, format_name)) {
  361. block_module_load_one(block_driver_modules[i].library_name);
  362. break;
  363. }
  364. }
  365. return bdrv_do_find_format(format_name);
  366. }
  367. static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
  368. {
  369. static const char *whitelist_rw[] = {
  370. CONFIG_BDRV_RW_WHITELIST
  371. };
  372. static const char *whitelist_ro[] = {
  373. CONFIG_BDRV_RO_WHITELIST
  374. };
  375. const char **p;
  376. if (!whitelist_rw[0] && !whitelist_ro[0]) {
  377. return 1; /* no whitelist, anything goes */
  378. }
  379. for (p = whitelist_rw; *p; p++) {
  380. if (!strcmp(format_name, *p)) {
  381. return 1;
  382. }
  383. }
  384. if (read_only) {
  385. for (p = whitelist_ro; *p; p++) {
  386. if (!strcmp(format_name, *p)) {
  387. return 1;
  388. }
  389. }
  390. }
  391. return 0;
  392. }
  393. int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
  394. {
  395. return bdrv_format_is_whitelisted(drv->format_name, read_only);
  396. }
  397. bool bdrv_uses_whitelist(void)
  398. {
  399. return use_bdrv_whitelist;
  400. }
  401. typedef struct CreateCo {
  402. BlockDriver *drv;
  403. char *filename;
  404. QemuOpts *opts;
  405. int ret;
  406. Error *err;
  407. } CreateCo;
  408. static void coroutine_fn bdrv_create_co_entry(void *opaque)
  409. {
  410. Error *local_err = NULL;
  411. int ret;
  412. CreateCo *cco = opaque;
  413. assert(cco->drv);
  414. ret = cco->drv->bdrv_co_create_opts(cco->filename, cco->opts, &local_err);
  415. error_propagate(&cco->err, local_err);
  416. cco->ret = ret;
  417. }
  418. int bdrv_create(BlockDriver *drv, const char* filename,
  419. QemuOpts *opts, Error **errp)
  420. {
  421. int ret;
  422. Coroutine *co;
  423. CreateCo cco = {
  424. .drv = drv,
  425. .filename = g_strdup(filename),
  426. .opts = opts,
  427. .ret = NOT_DONE,
  428. .err = NULL,
  429. };
  430. if (!drv->bdrv_co_create_opts) {
  431. error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
  432. ret = -ENOTSUP;
  433. goto out;
  434. }
  435. if (qemu_in_coroutine()) {
  436. /* Fast-path if already in coroutine context */
  437. bdrv_create_co_entry(&cco);
  438. } else {
  439. co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
  440. qemu_coroutine_enter(co);
  441. while (cco.ret == NOT_DONE) {
  442. aio_poll(qemu_get_aio_context(), true);
  443. }
  444. }
  445. ret = cco.ret;
  446. if (ret < 0) {
  447. if (cco.err) {
  448. error_propagate(errp, cco.err);
  449. } else {
  450. error_setg_errno(errp, -ret, "Could not create image");
  451. }
  452. }
  453. out:
  454. g_free(cco.filename);
  455. return ret;
  456. }
  457. int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
  458. {
  459. BlockDriver *drv;
  460. Error *local_err = NULL;
  461. int ret;
  462. drv = bdrv_find_protocol(filename, true, errp);
  463. if (drv == NULL) {
  464. return -ENOENT;
  465. }
  466. ret = bdrv_create(drv, filename, opts, &local_err);
  467. error_propagate(errp, local_err);
  468. return ret;
  469. }
  470. /**
  471. * Try to get @bs's logical and physical block size.
  472. * On success, store them in @bsz struct and return 0.
  473. * On failure return -errno.
  474. * @bs must not be empty.
  475. */
  476. int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
  477. {
  478. BlockDriver *drv = bs->drv;
  479. if (drv && drv->bdrv_probe_blocksizes) {
  480. return drv->bdrv_probe_blocksizes(bs, bsz);
  481. } else if (drv && drv->is_filter && bs->file) {
  482. return bdrv_probe_blocksizes(bs->file->bs, bsz);
  483. }
  484. return -ENOTSUP;
  485. }
  486. /**
  487. * Try to get @bs's geometry (cyls, heads, sectors).
  488. * On success, store them in @geo struct and return 0.
  489. * On failure return -errno.
  490. * @bs must not be empty.
  491. */
  492. int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
  493. {
  494. BlockDriver *drv = bs->drv;
  495. if (drv && drv->bdrv_probe_geometry) {
  496. return drv->bdrv_probe_geometry(bs, geo);
  497. } else if (drv && drv->is_filter && bs->file) {
  498. return bdrv_probe_geometry(bs->file->bs, geo);
  499. }
  500. return -ENOTSUP;
  501. }
  502. /*
  503. * Create a uniquely-named empty temporary file.
  504. * Return 0 upon success, otherwise a negative errno value.
  505. */
  506. int get_tmp_filename(char *filename, int size)
  507. {
  508. #ifdef _WIN32
  509. char temp_dir[MAX_PATH];
  510. /* GetTempFileName requires that its output buffer (4th param)
  511. have length MAX_PATH or greater. */
  512. assert(size >= MAX_PATH);
  513. return (GetTempPath(MAX_PATH, temp_dir)
  514. && GetTempFileName(temp_dir, "qem", 0, filename)
  515. ? 0 : -GetLastError());
  516. #else
  517. int fd;
  518. const char *tmpdir;
  519. tmpdir = getenv("TMPDIR");
  520. if (!tmpdir) {
  521. tmpdir = "/var/tmp";
  522. }
  523. if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
  524. return -EOVERFLOW;
  525. }
  526. fd = mkstemp(filename);
  527. if (fd < 0) {
  528. return -errno;
  529. }
  530. if (close(fd) != 0) {
  531. unlink(filename);
  532. return -errno;
  533. }
  534. return 0;
  535. #endif
  536. }
  537. /*
  538. * Detect host devices. By convention, /dev/cdrom[N] is always
  539. * recognized as a host CDROM.
  540. */
  541. static BlockDriver *find_hdev_driver(const char *filename)
  542. {
  543. int score_max = 0, score;
  544. BlockDriver *drv = NULL, *d;
  545. QLIST_FOREACH(d, &bdrv_drivers, list) {
  546. if (d->bdrv_probe_device) {
  547. score = d->bdrv_probe_device(filename);
  548. if (score > score_max) {
  549. score_max = score;
  550. drv = d;
  551. }
  552. }
  553. }
  554. return drv;
  555. }
  556. static BlockDriver *bdrv_do_find_protocol(const char *protocol)
  557. {
  558. BlockDriver *drv1;
  559. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  560. if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
  561. return drv1;
  562. }
  563. }
  564. return NULL;
  565. }
  566. BlockDriver *bdrv_find_protocol(const char *filename,
  567. bool allow_protocol_prefix,
  568. Error **errp)
  569. {
  570. BlockDriver *drv1;
  571. char protocol[128];
  572. int len;
  573. const char *p;
  574. int i;
  575. /* TODO Drivers without bdrv_file_open must be specified explicitly */
  576. /*
  577. * XXX(hch): we really should not let host device detection
  578. * override an explicit protocol specification, but moving this
  579. * later breaks access to device names with colons in them.
  580. * Thanks to the brain-dead persistent naming schemes on udev-
  581. * based Linux systems those actually are quite common.
  582. */
  583. drv1 = find_hdev_driver(filename);
  584. if (drv1) {
  585. return drv1;
  586. }
  587. if (!path_has_protocol(filename) || !allow_protocol_prefix) {
  588. return &bdrv_file;
  589. }
  590. p = strchr(filename, ':');
  591. assert(p != NULL);
  592. len = p - filename;
  593. if (len > sizeof(protocol) - 1)
  594. len = sizeof(protocol) - 1;
  595. memcpy(protocol, filename, len);
  596. protocol[len] = '\0';
  597. drv1 = bdrv_do_find_protocol(protocol);
  598. if (drv1) {
  599. return drv1;
  600. }
  601. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
  602. if (block_driver_modules[i].protocol_name &&
  603. !strcmp(block_driver_modules[i].protocol_name, protocol)) {
  604. block_module_load_one(block_driver_modules[i].library_name);
  605. break;
  606. }
  607. }
  608. drv1 = bdrv_do_find_protocol(protocol);
  609. if (!drv1) {
  610. error_setg(errp, "Unknown protocol '%s'", protocol);
  611. }
  612. return drv1;
  613. }
  614. /*
  615. * Guess image format by probing its contents.
  616. * This is not a good idea when your image is raw (CVE-2008-2004), but
  617. * we do it anyway for backward compatibility.
  618. *
  619. * @buf contains the image's first @buf_size bytes.
  620. * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
  621. * but can be smaller if the image file is smaller)
  622. * @filename is its filename.
  623. *
  624. * For all block drivers, call the bdrv_probe() method to get its
  625. * probing score.
  626. * Return the first block driver with the highest probing score.
  627. */
  628. BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
  629. const char *filename)
  630. {
  631. int score_max = 0, score;
  632. BlockDriver *drv = NULL, *d;
  633. QLIST_FOREACH(d, &bdrv_drivers, list) {
  634. if (d->bdrv_probe) {
  635. score = d->bdrv_probe(buf, buf_size, filename);
  636. if (score > score_max) {
  637. score_max = score;
  638. drv = d;
  639. }
  640. }
  641. }
  642. return drv;
  643. }
  644. static int find_image_format(BlockBackend *file, const char *filename,
  645. BlockDriver **pdrv, Error **errp)
  646. {
  647. BlockDriver *drv;
  648. uint8_t buf[BLOCK_PROBE_BUF_SIZE];
  649. int ret = 0;
  650. /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
  651. if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
  652. *pdrv = &bdrv_raw;
  653. return ret;
  654. }
  655. ret = blk_pread(file, 0, buf, sizeof(buf));
  656. if (ret < 0) {
  657. error_setg_errno(errp, -ret, "Could not read image for determining its "
  658. "format");
  659. *pdrv = NULL;
  660. return ret;
  661. }
  662. drv = bdrv_probe_all(buf, ret, filename);
  663. if (!drv) {
  664. error_setg(errp, "Could not determine image format: No compatible "
  665. "driver found");
  666. ret = -ENOENT;
  667. }
  668. *pdrv = drv;
  669. return ret;
  670. }
  671. /**
  672. * Set the current 'total_sectors' value
  673. * Return 0 on success, -errno on error.
  674. */
  675. int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
  676. {
  677. BlockDriver *drv = bs->drv;
  678. if (!drv) {
  679. return -ENOMEDIUM;
  680. }
  681. /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
  682. if (bdrv_is_sg(bs))
  683. return 0;
  684. /* query actual device if possible, otherwise just trust the hint */
  685. if (drv->bdrv_getlength) {
  686. int64_t length = drv->bdrv_getlength(bs);
  687. if (length < 0) {
  688. return length;
  689. }
  690. hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
  691. }
  692. bs->total_sectors = hint;
  693. return 0;
  694. }
  695. /**
  696. * Combines a QDict of new block driver @options with any missing options taken
  697. * from @old_options, so that leaving out an option defaults to its old value.
  698. */
  699. static void bdrv_join_options(BlockDriverState *bs, QDict *options,
  700. QDict *old_options)
  701. {
  702. if (bs->drv && bs->drv->bdrv_join_options) {
  703. bs->drv->bdrv_join_options(options, old_options);
  704. } else {
  705. qdict_join(options, old_options, false);
  706. }
  707. }
  708. static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
  709. int open_flags,
  710. Error **errp)
  711. {
  712. Error *local_err = NULL;
  713. char *value = qemu_opt_get_del(opts, "detect-zeroes");
  714. BlockdevDetectZeroesOptions detect_zeroes =
  715. qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
  716. BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
  717. g_free(value);
  718. if (local_err) {
  719. error_propagate(errp, local_err);
  720. return detect_zeroes;
  721. }
  722. if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
  723. !(open_flags & BDRV_O_UNMAP))
  724. {
  725. error_setg(errp, "setting detect-zeroes to unmap is not allowed "
  726. "without setting discard operation to unmap");
  727. }
  728. return detect_zeroes;
  729. }
  730. /**
  731. * Set open flags for a given discard mode
  732. *
  733. * Return 0 on success, -1 if the discard mode was invalid.
  734. */
  735. int bdrv_parse_discard_flags(const char *mode, int *flags)
  736. {
  737. *flags &= ~BDRV_O_UNMAP;
  738. if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
  739. /* do nothing */
  740. } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
  741. *flags |= BDRV_O_UNMAP;
  742. } else {
  743. return -1;
  744. }
  745. return 0;
  746. }
  747. /**
  748. * Set open flags for a given cache mode
  749. *
  750. * Return 0 on success, -1 if the cache mode was invalid.
  751. */
  752. int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
  753. {
  754. *flags &= ~BDRV_O_CACHE_MASK;
  755. if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
  756. *writethrough = false;
  757. *flags |= BDRV_O_NOCACHE;
  758. } else if (!strcmp(mode, "directsync")) {
  759. *writethrough = true;
  760. *flags |= BDRV_O_NOCACHE;
  761. } else if (!strcmp(mode, "writeback")) {
  762. *writethrough = false;
  763. } else if (!strcmp(mode, "unsafe")) {
  764. *writethrough = false;
  765. *flags |= BDRV_O_NO_FLUSH;
  766. } else if (!strcmp(mode, "writethrough")) {
  767. *writethrough = true;
  768. } else {
  769. return -1;
  770. }
  771. return 0;
  772. }
  773. static char *bdrv_child_get_parent_desc(BdrvChild *c)
  774. {
  775. BlockDriverState *parent = c->opaque;
  776. return g_strdup(bdrv_get_device_or_node_name(parent));
  777. }
  778. static void bdrv_child_cb_drained_begin(BdrvChild *child)
  779. {
  780. BlockDriverState *bs = child->opaque;
  781. bdrv_do_drained_begin_quiesce(bs, NULL, false);
  782. }
  783. static bool bdrv_child_cb_drained_poll(BdrvChild *child)
  784. {
  785. BlockDriverState *bs = child->opaque;
  786. return bdrv_drain_poll(bs, false, NULL, false);
  787. }
  788. static void bdrv_child_cb_drained_end(BdrvChild *child)
  789. {
  790. BlockDriverState *bs = child->opaque;
  791. bdrv_drained_end(bs);
  792. }
  793. static void bdrv_child_cb_attach(BdrvChild *child)
  794. {
  795. BlockDriverState *bs = child->opaque;
  796. bdrv_apply_subtree_drain(child, bs);
  797. }
  798. static void bdrv_child_cb_detach(BdrvChild *child)
  799. {
  800. BlockDriverState *bs = child->opaque;
  801. bdrv_unapply_subtree_drain(child, bs);
  802. }
  803. static int bdrv_child_cb_inactivate(BdrvChild *child)
  804. {
  805. BlockDriverState *bs = child->opaque;
  806. assert(bs->open_flags & BDRV_O_INACTIVE);
  807. return 0;
  808. }
  809. /*
  810. * Returns the options and flags that a temporary snapshot should get, based on
  811. * the originally requested flags (the originally requested image will have
  812. * flags like a backing file)
  813. */
  814. static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
  815. int parent_flags, QDict *parent_options)
  816. {
  817. *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
  818. /* For temporary files, unconditional cache=unsafe is fine */
  819. qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
  820. qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
  821. /* Copy the read-only and discard options from the parent */
  822. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  823. qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
  824. /* aio=native doesn't work for cache.direct=off, so disable it for the
  825. * temporary snapshot */
  826. *child_flags &= ~BDRV_O_NATIVE_AIO;
  827. }
  828. /*
  829. * Returns the options and flags that bs->file should get if a protocol driver
  830. * is expected, based on the given options and flags for the parent BDS
  831. */
  832. static void bdrv_inherited_options(int *child_flags, QDict *child_options,
  833. int parent_flags, QDict *parent_options)
  834. {
  835. int flags = parent_flags;
  836. /* Enable protocol handling, disable format probing for bs->file */
  837. flags |= BDRV_O_PROTOCOL;
  838. /* If the cache mode isn't explicitly set, inherit direct and no-flush from
  839. * the parent. */
  840. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
  841. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
  842. qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
  843. /* Inherit the read-only option from the parent if it's not set */
  844. qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
  845. qdict_copy_default(child_options, parent_options, BDRV_OPT_AUTO_READ_ONLY);
  846. /* Our block drivers take care to send flushes and respect unmap policy,
  847. * so we can default to enable both on lower layers regardless of the
  848. * corresponding parent options. */
  849. qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
  850. /* Clear flags that only apply to the top layer */
  851. flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
  852. BDRV_O_NO_IO);
  853. *child_flags = flags;
  854. }
  855. const BdrvChildRole child_file = {
  856. .parent_is_bds = true,
  857. .get_parent_desc = bdrv_child_get_parent_desc,
  858. .inherit_options = bdrv_inherited_options,
  859. .drained_begin = bdrv_child_cb_drained_begin,
  860. .drained_poll = bdrv_child_cb_drained_poll,
  861. .drained_end = bdrv_child_cb_drained_end,
  862. .attach = bdrv_child_cb_attach,
  863. .detach = bdrv_child_cb_detach,
  864. .inactivate = bdrv_child_cb_inactivate,
  865. };
  866. /*
  867. * Returns the options and flags that bs->file should get if the use of formats
  868. * (and not only protocols) is permitted for it, based on the given options and
  869. * flags for the parent BDS
  870. */
  871. static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
  872. int parent_flags, QDict *parent_options)
  873. {
  874. child_file.inherit_options(child_flags, child_options,
  875. parent_flags, parent_options);
  876. *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
  877. }
  878. const BdrvChildRole child_format = {
  879. .parent_is_bds = true,
  880. .get_parent_desc = bdrv_child_get_parent_desc,
  881. .inherit_options = bdrv_inherited_fmt_options,
  882. .drained_begin = bdrv_child_cb_drained_begin,
  883. .drained_poll = bdrv_child_cb_drained_poll,
  884. .drained_end = bdrv_child_cb_drained_end,
  885. .attach = bdrv_child_cb_attach,
  886. .detach = bdrv_child_cb_detach,
  887. .inactivate = bdrv_child_cb_inactivate,
  888. };
  889. static void bdrv_backing_attach(BdrvChild *c)
  890. {
  891. BlockDriverState *parent = c->opaque;
  892. BlockDriverState *backing_hd = c->bs;
  893. assert(!parent->backing_blocker);
  894. error_setg(&parent->backing_blocker,
  895. "node is used as backing hd of '%s'",
  896. bdrv_get_device_or_node_name(parent));
  897. bdrv_refresh_filename(backing_hd);
  898. parent->open_flags &= ~BDRV_O_NO_BACKING;
  899. pstrcpy(parent->backing_file, sizeof(parent->backing_file),
  900. backing_hd->filename);
  901. pstrcpy(parent->backing_format, sizeof(parent->backing_format),
  902. backing_hd->drv ? backing_hd->drv->format_name : "");
  903. bdrv_op_block_all(backing_hd, parent->backing_blocker);
  904. /* Otherwise we won't be able to commit or stream */
  905. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
  906. parent->backing_blocker);
  907. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
  908. parent->backing_blocker);
  909. /*
  910. * We do backup in 3 ways:
  911. * 1. drive backup
  912. * The target bs is new opened, and the source is top BDS
  913. * 2. blockdev backup
  914. * Both the source and the target are top BDSes.
  915. * 3. internal backup(used for block replication)
  916. * Both the source and the target are backing file
  917. *
  918. * In case 1 and 2, neither the source nor the target is the backing file.
  919. * In case 3, we will block the top BDS, so there is only one block job
  920. * for the top BDS and its backing chain.
  921. */
  922. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
  923. parent->backing_blocker);
  924. bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
  925. parent->backing_blocker);
  926. bdrv_child_cb_attach(c);
  927. }
  928. static void bdrv_backing_detach(BdrvChild *c)
  929. {
  930. BlockDriverState *parent = c->opaque;
  931. assert(parent->backing_blocker);
  932. bdrv_op_unblock_all(c->bs, parent->backing_blocker);
  933. error_free(parent->backing_blocker);
  934. parent->backing_blocker = NULL;
  935. bdrv_child_cb_detach(c);
  936. }
  937. /*
  938. * Returns the options and flags that bs->backing should get, based on the
  939. * given options and flags for the parent BDS
  940. */
  941. static void bdrv_backing_options(int *child_flags, QDict *child_options,
  942. int parent_flags, QDict *parent_options)
  943. {
  944. int flags = parent_flags;
  945. /* The cache mode is inherited unmodified for backing files; except WCE,
  946. * which is only applied on the top level (BlockBackend) */
  947. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
  948. qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
  949. qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
  950. /* backing files always opened read-only */
  951. qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
  952. qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
  953. flags &= ~BDRV_O_COPY_ON_READ;
  954. /* snapshot=on is handled on the top layer */
  955. flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
  956. *child_flags = flags;
  957. }
  958. static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
  959. const char *filename, Error **errp)
  960. {
  961. BlockDriverState *parent = c->opaque;
  962. bool read_only = bdrv_is_read_only(parent);
  963. int ret;
  964. if (read_only) {
  965. ret = bdrv_reopen_set_read_only(parent, false, errp);
  966. if (ret < 0) {
  967. return ret;
  968. }
  969. }
  970. ret = bdrv_change_backing_file(parent, filename,
  971. base->drv ? base->drv->format_name : "");
  972. if (ret < 0) {
  973. error_setg_errno(errp, -ret, "Could not update backing file link");
  974. }
  975. if (read_only) {
  976. bdrv_reopen_set_read_only(parent, true, NULL);
  977. }
  978. return ret;
  979. }
  980. const BdrvChildRole child_backing = {
  981. .parent_is_bds = true,
  982. .get_parent_desc = bdrv_child_get_parent_desc,
  983. .attach = bdrv_backing_attach,
  984. .detach = bdrv_backing_detach,
  985. .inherit_options = bdrv_backing_options,
  986. .drained_begin = bdrv_child_cb_drained_begin,
  987. .drained_poll = bdrv_child_cb_drained_poll,
  988. .drained_end = bdrv_child_cb_drained_end,
  989. .inactivate = bdrv_child_cb_inactivate,
  990. .update_filename = bdrv_backing_update_filename,
  991. };
  992. static int bdrv_open_flags(BlockDriverState *bs, int flags)
  993. {
  994. int open_flags = flags;
  995. /*
  996. * Clear flags that are internal to the block layer before opening the
  997. * image.
  998. */
  999. open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
  1000. return open_flags;
  1001. }
  1002. static void update_flags_from_options(int *flags, QemuOpts *opts)
  1003. {
  1004. *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
  1005. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
  1006. *flags |= BDRV_O_NO_FLUSH;
  1007. }
  1008. if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
  1009. *flags |= BDRV_O_NOCACHE;
  1010. }
  1011. if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
  1012. *flags |= BDRV_O_RDWR;
  1013. }
  1014. if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
  1015. *flags |= BDRV_O_AUTO_RDONLY;
  1016. }
  1017. }
  1018. static void update_options_from_flags(QDict *options, int flags)
  1019. {
  1020. if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
  1021. qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
  1022. }
  1023. if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
  1024. qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
  1025. flags & BDRV_O_NO_FLUSH);
  1026. }
  1027. if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
  1028. qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
  1029. }
  1030. if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
  1031. qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
  1032. flags & BDRV_O_AUTO_RDONLY);
  1033. }
  1034. }
  1035. static void bdrv_assign_node_name(BlockDriverState *bs,
  1036. const char *node_name,
  1037. Error **errp)
  1038. {
  1039. char *gen_node_name = NULL;
  1040. if (!node_name) {
  1041. node_name = gen_node_name = id_generate(ID_BLOCK);
  1042. } else if (!id_wellformed(node_name)) {
  1043. /*
  1044. * Check for empty string or invalid characters, but not if it is
  1045. * generated (generated names use characters not available to the user)
  1046. */
  1047. error_setg(errp, "Invalid node name");
  1048. return;
  1049. }
  1050. /* takes care of avoiding namespaces collisions */
  1051. if (blk_by_name(node_name)) {
  1052. error_setg(errp, "node-name=%s is conflicting with a device id",
  1053. node_name);
  1054. goto out;
  1055. }
  1056. /* takes care of avoiding duplicates node names */
  1057. if (bdrv_find_node(node_name)) {
  1058. error_setg(errp, "Duplicate node name");
  1059. goto out;
  1060. }
  1061. /* Make sure that the node name isn't truncated */
  1062. if (strlen(node_name) >= sizeof(bs->node_name)) {
  1063. error_setg(errp, "Node name too long");
  1064. goto out;
  1065. }
  1066. /* copy node name into the bs and insert it into the graph list */
  1067. pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
  1068. QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
  1069. out:
  1070. g_free(gen_node_name);
  1071. }
  1072. static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
  1073. const char *node_name, QDict *options,
  1074. int open_flags, Error **errp)
  1075. {
  1076. Error *local_err = NULL;
  1077. int i, ret;
  1078. bdrv_assign_node_name(bs, node_name, &local_err);
  1079. if (local_err) {
  1080. error_propagate(errp, local_err);
  1081. return -EINVAL;
  1082. }
  1083. bs->drv = drv;
  1084. bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
  1085. bs->opaque = g_malloc0(drv->instance_size);
  1086. if (drv->bdrv_file_open) {
  1087. assert(!drv->bdrv_needs_filename || bs->filename[0]);
  1088. ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
  1089. } else if (drv->bdrv_open) {
  1090. ret = drv->bdrv_open(bs, options, open_flags, &local_err);
  1091. } else {
  1092. ret = 0;
  1093. }
  1094. if (ret < 0) {
  1095. if (local_err) {
  1096. error_propagate(errp, local_err);
  1097. } else if (bs->filename[0]) {
  1098. error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
  1099. } else {
  1100. error_setg_errno(errp, -ret, "Could not open image");
  1101. }
  1102. goto open_failed;
  1103. }
  1104. ret = refresh_total_sectors(bs, bs->total_sectors);
  1105. if (ret < 0) {
  1106. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  1107. return ret;
  1108. }
  1109. bdrv_refresh_limits(bs, &local_err);
  1110. if (local_err) {
  1111. error_propagate(errp, local_err);
  1112. return -EINVAL;
  1113. }
  1114. assert(bdrv_opt_mem_align(bs) != 0);
  1115. assert(bdrv_min_mem_align(bs) != 0);
  1116. assert(is_power_of_2(bs->bl.request_alignment));
  1117. for (i = 0; i < bs->quiesce_counter; i++) {
  1118. if (drv->bdrv_co_drain_begin) {
  1119. drv->bdrv_co_drain_begin(bs);
  1120. }
  1121. }
  1122. return 0;
  1123. open_failed:
  1124. bs->drv = NULL;
  1125. if (bs->file != NULL) {
  1126. bdrv_unref_child(bs, bs->file);
  1127. bs->file = NULL;
  1128. }
  1129. g_free(bs->opaque);
  1130. bs->opaque = NULL;
  1131. return ret;
  1132. }
  1133. BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
  1134. int flags, Error **errp)
  1135. {
  1136. BlockDriverState *bs;
  1137. int ret;
  1138. bs = bdrv_new();
  1139. bs->open_flags = flags;
  1140. bs->explicit_options = qdict_new();
  1141. bs->options = qdict_new();
  1142. bs->opaque = NULL;
  1143. update_options_from_flags(bs->options, flags);
  1144. ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
  1145. if (ret < 0) {
  1146. qobject_unref(bs->explicit_options);
  1147. bs->explicit_options = NULL;
  1148. qobject_unref(bs->options);
  1149. bs->options = NULL;
  1150. bdrv_unref(bs);
  1151. return NULL;
  1152. }
  1153. return bs;
  1154. }
  1155. QemuOptsList bdrv_runtime_opts = {
  1156. .name = "bdrv_common",
  1157. .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
  1158. .desc = {
  1159. {
  1160. .name = "node-name",
  1161. .type = QEMU_OPT_STRING,
  1162. .help = "Node name of the block device node",
  1163. },
  1164. {
  1165. .name = "driver",
  1166. .type = QEMU_OPT_STRING,
  1167. .help = "Block driver to use for the node",
  1168. },
  1169. {
  1170. .name = BDRV_OPT_CACHE_DIRECT,
  1171. .type = QEMU_OPT_BOOL,
  1172. .help = "Bypass software writeback cache on the host",
  1173. },
  1174. {
  1175. .name = BDRV_OPT_CACHE_NO_FLUSH,
  1176. .type = QEMU_OPT_BOOL,
  1177. .help = "Ignore flush requests",
  1178. },
  1179. {
  1180. .name = BDRV_OPT_READ_ONLY,
  1181. .type = QEMU_OPT_BOOL,
  1182. .help = "Node is opened in read-only mode",
  1183. },
  1184. {
  1185. .name = BDRV_OPT_AUTO_READ_ONLY,
  1186. .type = QEMU_OPT_BOOL,
  1187. .help = "Node can become read-only if opening read-write fails",
  1188. },
  1189. {
  1190. .name = "detect-zeroes",
  1191. .type = QEMU_OPT_STRING,
  1192. .help = "try to optimize zero writes (off, on, unmap)",
  1193. },
  1194. {
  1195. .name = BDRV_OPT_DISCARD,
  1196. .type = QEMU_OPT_STRING,
  1197. .help = "discard operation (ignore/off, unmap/on)",
  1198. },
  1199. {
  1200. .name = BDRV_OPT_FORCE_SHARE,
  1201. .type = QEMU_OPT_BOOL,
  1202. .help = "always accept other writers (default: off)",
  1203. },
  1204. { /* end of list */ }
  1205. },
  1206. };
  1207. /*
  1208. * Common part for opening disk images and files
  1209. *
  1210. * Removes all processed options from *options.
  1211. */
  1212. static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
  1213. QDict *options, Error **errp)
  1214. {
  1215. int ret, open_flags;
  1216. const char *filename;
  1217. const char *driver_name = NULL;
  1218. const char *node_name = NULL;
  1219. const char *discard;
  1220. QemuOpts *opts;
  1221. BlockDriver *drv;
  1222. Error *local_err = NULL;
  1223. assert(bs->file == NULL);
  1224. assert(options != NULL && bs->options != options);
  1225. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  1226. qemu_opts_absorb_qdict(opts, options, &local_err);
  1227. if (local_err) {
  1228. error_propagate(errp, local_err);
  1229. ret = -EINVAL;
  1230. goto fail_opts;
  1231. }
  1232. update_flags_from_options(&bs->open_flags, opts);
  1233. driver_name = qemu_opt_get(opts, "driver");
  1234. drv = bdrv_find_format(driver_name);
  1235. assert(drv != NULL);
  1236. bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
  1237. if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
  1238. error_setg(errp,
  1239. BDRV_OPT_FORCE_SHARE
  1240. "=on can only be used with read-only images");
  1241. ret = -EINVAL;
  1242. goto fail_opts;
  1243. }
  1244. if (file != NULL) {
  1245. bdrv_refresh_filename(blk_bs(file));
  1246. filename = blk_bs(file)->filename;
  1247. } else {
  1248. /*
  1249. * Caution: while qdict_get_try_str() is fine, getting
  1250. * non-string types would require more care. When @options
  1251. * come from -blockdev or blockdev_add, its members are typed
  1252. * according to the QAPI schema, but when they come from
  1253. * -drive, they're all QString.
  1254. */
  1255. filename = qdict_get_try_str(options, "filename");
  1256. }
  1257. if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
  1258. error_setg(errp, "The '%s' block driver requires a file name",
  1259. drv->format_name);
  1260. ret = -EINVAL;
  1261. goto fail_opts;
  1262. }
  1263. trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
  1264. drv->format_name);
  1265. bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
  1266. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
  1267. if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
  1268. ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
  1269. } else {
  1270. ret = -ENOTSUP;
  1271. }
  1272. if (ret < 0) {
  1273. error_setg(errp,
  1274. !bs->read_only && bdrv_is_whitelisted(drv, true)
  1275. ? "Driver '%s' can only be used for read-only devices"
  1276. : "Driver '%s' is not whitelisted",
  1277. drv->format_name);
  1278. goto fail_opts;
  1279. }
  1280. }
  1281. /* bdrv_new() and bdrv_close() make it so */
  1282. assert(atomic_read(&bs->copy_on_read) == 0);
  1283. if (bs->open_flags & BDRV_O_COPY_ON_READ) {
  1284. if (!bs->read_only) {
  1285. bdrv_enable_copy_on_read(bs);
  1286. } else {
  1287. error_setg(errp, "Can't use copy-on-read on read-only device");
  1288. ret = -EINVAL;
  1289. goto fail_opts;
  1290. }
  1291. }
  1292. discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
  1293. if (discard != NULL) {
  1294. if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
  1295. error_setg(errp, "Invalid discard option");
  1296. ret = -EINVAL;
  1297. goto fail_opts;
  1298. }
  1299. }
  1300. bs->detect_zeroes =
  1301. bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
  1302. if (local_err) {
  1303. error_propagate(errp, local_err);
  1304. ret = -EINVAL;
  1305. goto fail_opts;
  1306. }
  1307. if (filename != NULL) {
  1308. pstrcpy(bs->filename, sizeof(bs->filename), filename);
  1309. } else {
  1310. bs->filename[0] = '\0';
  1311. }
  1312. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
  1313. /* Open the image, either directly or using a protocol */
  1314. open_flags = bdrv_open_flags(bs, bs->open_flags);
  1315. node_name = qemu_opt_get(opts, "node-name");
  1316. assert(!drv->bdrv_file_open || file == NULL);
  1317. ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
  1318. if (ret < 0) {
  1319. goto fail_opts;
  1320. }
  1321. qemu_opts_del(opts);
  1322. return 0;
  1323. fail_opts:
  1324. qemu_opts_del(opts);
  1325. return ret;
  1326. }
  1327. static QDict *parse_json_filename(const char *filename, Error **errp)
  1328. {
  1329. QObject *options_obj;
  1330. QDict *options;
  1331. int ret;
  1332. ret = strstart(filename, "json:", &filename);
  1333. assert(ret);
  1334. options_obj = qobject_from_json(filename, errp);
  1335. if (!options_obj) {
  1336. error_prepend(errp, "Could not parse the JSON options: ");
  1337. return NULL;
  1338. }
  1339. options = qobject_to(QDict, options_obj);
  1340. if (!options) {
  1341. qobject_unref(options_obj);
  1342. error_setg(errp, "Invalid JSON object given");
  1343. return NULL;
  1344. }
  1345. qdict_flatten(options);
  1346. return options;
  1347. }
  1348. static void parse_json_protocol(QDict *options, const char **pfilename,
  1349. Error **errp)
  1350. {
  1351. QDict *json_options;
  1352. Error *local_err = NULL;
  1353. /* Parse json: pseudo-protocol */
  1354. if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
  1355. return;
  1356. }
  1357. json_options = parse_json_filename(*pfilename, &local_err);
  1358. if (local_err) {
  1359. error_propagate(errp, local_err);
  1360. return;
  1361. }
  1362. /* Options given in the filename have lower priority than options
  1363. * specified directly */
  1364. qdict_join(options, json_options, false);
  1365. qobject_unref(json_options);
  1366. *pfilename = NULL;
  1367. }
  1368. /*
  1369. * Fills in default options for opening images and converts the legacy
  1370. * filename/flags pair to option QDict entries.
  1371. * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
  1372. * block driver has been specified explicitly.
  1373. */
  1374. static int bdrv_fill_options(QDict **options, const char *filename,
  1375. int *flags, Error **errp)
  1376. {
  1377. const char *drvname;
  1378. bool protocol = *flags & BDRV_O_PROTOCOL;
  1379. bool parse_filename = false;
  1380. BlockDriver *drv = NULL;
  1381. Error *local_err = NULL;
  1382. /*
  1383. * Caution: while qdict_get_try_str() is fine, getting non-string
  1384. * types would require more care. When @options come from
  1385. * -blockdev or blockdev_add, its members are typed according to
  1386. * the QAPI schema, but when they come from -drive, they're all
  1387. * QString.
  1388. */
  1389. drvname = qdict_get_try_str(*options, "driver");
  1390. if (drvname) {
  1391. drv = bdrv_find_format(drvname);
  1392. if (!drv) {
  1393. error_setg(errp, "Unknown driver '%s'", drvname);
  1394. return -ENOENT;
  1395. }
  1396. /* If the user has explicitly specified the driver, this choice should
  1397. * override the BDRV_O_PROTOCOL flag */
  1398. protocol = drv->bdrv_file_open;
  1399. }
  1400. if (protocol) {
  1401. *flags |= BDRV_O_PROTOCOL;
  1402. } else {
  1403. *flags &= ~BDRV_O_PROTOCOL;
  1404. }
  1405. /* Translate cache options from flags into options */
  1406. update_options_from_flags(*options, *flags);
  1407. /* Fetch the file name from the options QDict if necessary */
  1408. if (protocol && filename) {
  1409. if (!qdict_haskey(*options, "filename")) {
  1410. qdict_put_str(*options, "filename", filename);
  1411. parse_filename = true;
  1412. } else {
  1413. error_setg(errp, "Can't specify 'file' and 'filename' options at "
  1414. "the same time");
  1415. return -EINVAL;
  1416. }
  1417. }
  1418. /* Find the right block driver */
  1419. /* See cautionary note on accessing @options above */
  1420. filename = qdict_get_try_str(*options, "filename");
  1421. if (!drvname && protocol) {
  1422. if (filename) {
  1423. drv = bdrv_find_protocol(filename, parse_filename, errp);
  1424. if (!drv) {
  1425. return -EINVAL;
  1426. }
  1427. drvname = drv->format_name;
  1428. qdict_put_str(*options, "driver", drvname);
  1429. } else {
  1430. error_setg(errp, "Must specify either driver or file");
  1431. return -EINVAL;
  1432. }
  1433. }
  1434. assert(drv || !protocol);
  1435. /* Driver-specific filename parsing */
  1436. if (drv && drv->bdrv_parse_filename && parse_filename) {
  1437. drv->bdrv_parse_filename(filename, *options, &local_err);
  1438. if (local_err) {
  1439. error_propagate(errp, local_err);
  1440. return -EINVAL;
  1441. }
  1442. if (!drv->bdrv_needs_filename) {
  1443. qdict_del(*options, "filename");
  1444. }
  1445. }
  1446. return 0;
  1447. }
  1448. static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
  1449. uint64_t perm, uint64_t shared,
  1450. GSList *ignore_children, Error **errp);
  1451. static void bdrv_child_abort_perm_update(BdrvChild *c);
  1452. static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
  1453. typedef struct BlockReopenQueueEntry {
  1454. bool prepared;
  1455. bool perms_checked;
  1456. BDRVReopenState state;
  1457. QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
  1458. } BlockReopenQueueEntry;
  1459. /*
  1460. * Return the flags that @bs will have after the reopens in @q have
  1461. * successfully completed. If @q is NULL (or @bs is not contained in @q),
  1462. * return the current flags.
  1463. */
  1464. static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
  1465. {
  1466. BlockReopenQueueEntry *entry;
  1467. if (q != NULL) {
  1468. QSIMPLEQ_FOREACH(entry, q, entry) {
  1469. if (entry->state.bs == bs) {
  1470. return entry->state.flags;
  1471. }
  1472. }
  1473. }
  1474. return bs->open_flags;
  1475. }
  1476. /* Returns whether the image file can be written to after the reopen queue @q
  1477. * has been successfully applied, or right now if @q is NULL. */
  1478. static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
  1479. BlockReopenQueue *q)
  1480. {
  1481. int flags = bdrv_reopen_get_flags(q, bs);
  1482. return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
  1483. }
  1484. /*
  1485. * Return whether the BDS can be written to. This is not necessarily
  1486. * the same as !bdrv_is_read_only(bs), as inactivated images may not
  1487. * be written to but do not count as read-only images.
  1488. */
  1489. bool bdrv_is_writable(BlockDriverState *bs)
  1490. {
  1491. return bdrv_is_writable_after_reopen(bs, NULL);
  1492. }
  1493. static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
  1494. BdrvChild *c, const BdrvChildRole *role,
  1495. BlockReopenQueue *reopen_queue,
  1496. uint64_t parent_perm, uint64_t parent_shared,
  1497. uint64_t *nperm, uint64_t *nshared)
  1498. {
  1499. assert(bs->drv && bs->drv->bdrv_child_perm);
  1500. bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
  1501. parent_perm, parent_shared,
  1502. nperm, nshared);
  1503. /* TODO Take force_share from reopen_queue */
  1504. if (child_bs && child_bs->force_share) {
  1505. *nshared = BLK_PERM_ALL;
  1506. }
  1507. }
  1508. /*
  1509. * Check whether permissions on this node can be changed in a way that
  1510. * @cumulative_perms and @cumulative_shared_perms are the new cumulative
  1511. * permissions of all its parents. This involves checking whether all necessary
  1512. * permission changes to child nodes can be performed.
  1513. *
  1514. * A call to this function must always be followed by a call to bdrv_set_perm()
  1515. * or bdrv_abort_perm_update().
  1516. */
  1517. static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
  1518. uint64_t cumulative_perms,
  1519. uint64_t cumulative_shared_perms,
  1520. GSList *ignore_children, Error **errp)
  1521. {
  1522. BlockDriver *drv = bs->drv;
  1523. BdrvChild *c;
  1524. int ret;
  1525. /* Write permissions never work with read-only images */
  1526. if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
  1527. !bdrv_is_writable_after_reopen(bs, q))
  1528. {
  1529. error_setg(errp, "Block node is read-only");
  1530. return -EPERM;
  1531. }
  1532. /* Check this node */
  1533. if (!drv) {
  1534. return 0;
  1535. }
  1536. if (drv->bdrv_check_perm) {
  1537. return drv->bdrv_check_perm(bs, cumulative_perms,
  1538. cumulative_shared_perms, errp);
  1539. }
  1540. /* Drivers that never have children can omit .bdrv_child_perm() */
  1541. if (!drv->bdrv_child_perm) {
  1542. assert(QLIST_EMPTY(&bs->children));
  1543. return 0;
  1544. }
  1545. /* Check all children */
  1546. QLIST_FOREACH(c, &bs->children, next) {
  1547. uint64_t cur_perm, cur_shared;
  1548. bdrv_child_perm(bs, c->bs, c, c->role, q,
  1549. cumulative_perms, cumulative_shared_perms,
  1550. &cur_perm, &cur_shared);
  1551. ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared,
  1552. ignore_children, errp);
  1553. if (ret < 0) {
  1554. return ret;
  1555. }
  1556. }
  1557. return 0;
  1558. }
  1559. /*
  1560. * Notifies drivers that after a previous bdrv_check_perm() call, the
  1561. * permission update is not performed and any preparations made for it (e.g.
  1562. * taken file locks) need to be undone.
  1563. *
  1564. * This function recursively notifies all child nodes.
  1565. */
  1566. static void bdrv_abort_perm_update(BlockDriverState *bs)
  1567. {
  1568. BlockDriver *drv = bs->drv;
  1569. BdrvChild *c;
  1570. if (!drv) {
  1571. return;
  1572. }
  1573. if (drv->bdrv_abort_perm_update) {
  1574. drv->bdrv_abort_perm_update(bs);
  1575. }
  1576. QLIST_FOREACH(c, &bs->children, next) {
  1577. bdrv_child_abort_perm_update(c);
  1578. }
  1579. }
  1580. static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
  1581. uint64_t cumulative_shared_perms)
  1582. {
  1583. BlockDriver *drv = bs->drv;
  1584. BdrvChild *c;
  1585. if (!drv) {
  1586. return;
  1587. }
  1588. /* Update this node */
  1589. if (drv->bdrv_set_perm) {
  1590. drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
  1591. }
  1592. /* Drivers that never have children can omit .bdrv_child_perm() */
  1593. if (!drv->bdrv_child_perm) {
  1594. assert(QLIST_EMPTY(&bs->children));
  1595. return;
  1596. }
  1597. /* Update all children */
  1598. QLIST_FOREACH(c, &bs->children, next) {
  1599. uint64_t cur_perm, cur_shared;
  1600. bdrv_child_perm(bs, c->bs, c, c->role, NULL,
  1601. cumulative_perms, cumulative_shared_perms,
  1602. &cur_perm, &cur_shared);
  1603. bdrv_child_set_perm(c, cur_perm, cur_shared);
  1604. }
  1605. }
  1606. static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
  1607. uint64_t *shared_perm)
  1608. {
  1609. BdrvChild *c;
  1610. uint64_t cumulative_perms = 0;
  1611. uint64_t cumulative_shared_perms = BLK_PERM_ALL;
  1612. QLIST_FOREACH(c, &bs->parents, next_parent) {
  1613. cumulative_perms |= c->perm;
  1614. cumulative_shared_perms &= c->shared_perm;
  1615. }
  1616. *perm = cumulative_perms;
  1617. *shared_perm = cumulative_shared_perms;
  1618. }
  1619. static char *bdrv_child_user_desc(BdrvChild *c)
  1620. {
  1621. if (c->role->get_parent_desc) {
  1622. return c->role->get_parent_desc(c);
  1623. }
  1624. return g_strdup("another user");
  1625. }
  1626. char *bdrv_perm_names(uint64_t perm)
  1627. {
  1628. struct perm_name {
  1629. uint64_t perm;
  1630. const char *name;
  1631. } permissions[] = {
  1632. { BLK_PERM_CONSISTENT_READ, "consistent read" },
  1633. { BLK_PERM_WRITE, "write" },
  1634. { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
  1635. { BLK_PERM_RESIZE, "resize" },
  1636. { BLK_PERM_GRAPH_MOD, "change children" },
  1637. { 0, NULL }
  1638. };
  1639. char *result = g_strdup("");
  1640. struct perm_name *p;
  1641. for (p = permissions; p->name; p++) {
  1642. if (perm & p->perm) {
  1643. char *old = result;
  1644. result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
  1645. g_free(old);
  1646. }
  1647. }
  1648. return result;
  1649. }
  1650. /*
  1651. * Checks whether a new reference to @bs can be added if the new user requires
  1652. * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
  1653. * set, the BdrvChild objects in this list are ignored in the calculations;
  1654. * this allows checking permission updates for an existing reference.
  1655. *
  1656. * Needs to be followed by a call to either bdrv_set_perm() or
  1657. * bdrv_abort_perm_update(). */
  1658. static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
  1659. uint64_t new_used_perm,
  1660. uint64_t new_shared_perm,
  1661. GSList *ignore_children, Error **errp)
  1662. {
  1663. BdrvChild *c;
  1664. uint64_t cumulative_perms = new_used_perm;
  1665. uint64_t cumulative_shared_perms = new_shared_perm;
  1666. /* There is no reason why anyone couldn't tolerate write_unchanged */
  1667. assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
  1668. QLIST_FOREACH(c, &bs->parents, next_parent) {
  1669. if (g_slist_find(ignore_children, c)) {
  1670. continue;
  1671. }
  1672. if ((new_used_perm & c->shared_perm) != new_used_perm) {
  1673. char *user = bdrv_child_user_desc(c);
  1674. char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
  1675. error_setg(errp, "Conflicts with use by %s as '%s', which does not "
  1676. "allow '%s' on %s",
  1677. user, c->name, perm_names, bdrv_get_node_name(c->bs));
  1678. g_free(user);
  1679. g_free(perm_names);
  1680. return -EPERM;
  1681. }
  1682. if ((c->perm & new_shared_perm) != c->perm) {
  1683. char *user = bdrv_child_user_desc(c);
  1684. char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
  1685. error_setg(errp, "Conflicts with use by %s as '%s', which uses "
  1686. "'%s' on %s",
  1687. user, c->name, perm_names, bdrv_get_node_name(c->bs));
  1688. g_free(user);
  1689. g_free(perm_names);
  1690. return -EPERM;
  1691. }
  1692. cumulative_perms |= c->perm;
  1693. cumulative_shared_perms &= c->shared_perm;
  1694. }
  1695. return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
  1696. ignore_children, errp);
  1697. }
  1698. /* Needs to be followed by a call to either bdrv_child_set_perm() or
  1699. * bdrv_child_abort_perm_update(). */
  1700. static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
  1701. uint64_t perm, uint64_t shared,
  1702. GSList *ignore_children, Error **errp)
  1703. {
  1704. int ret;
  1705. ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
  1706. ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children, errp);
  1707. g_slist_free(ignore_children);
  1708. if (ret < 0) {
  1709. return ret;
  1710. }
  1711. if (!c->has_backup_perm) {
  1712. c->has_backup_perm = true;
  1713. c->backup_perm = c->perm;
  1714. c->backup_shared_perm = c->shared_perm;
  1715. }
  1716. /*
  1717. * Note: it's OK if c->has_backup_perm was already set, as we can find the
  1718. * same child twice during check_perm procedure
  1719. */
  1720. c->perm = perm;
  1721. c->shared_perm = shared;
  1722. return 0;
  1723. }
  1724. static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
  1725. {
  1726. uint64_t cumulative_perms, cumulative_shared_perms;
  1727. c->has_backup_perm = false;
  1728. c->perm = perm;
  1729. c->shared_perm = shared;
  1730. bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
  1731. &cumulative_shared_perms);
  1732. bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
  1733. }
  1734. static void bdrv_child_abort_perm_update(BdrvChild *c)
  1735. {
  1736. if (c->has_backup_perm) {
  1737. c->perm = c->backup_perm;
  1738. c->shared_perm = c->backup_shared_perm;
  1739. c->has_backup_perm = false;
  1740. }
  1741. bdrv_abort_perm_update(c->bs);
  1742. }
  1743. int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
  1744. Error **errp)
  1745. {
  1746. int ret;
  1747. ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL, errp);
  1748. if (ret < 0) {
  1749. bdrv_child_abort_perm_update(c);
  1750. return ret;
  1751. }
  1752. bdrv_child_set_perm(c, perm, shared);
  1753. return 0;
  1754. }
  1755. void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
  1756. const BdrvChildRole *role,
  1757. BlockReopenQueue *reopen_queue,
  1758. uint64_t perm, uint64_t shared,
  1759. uint64_t *nperm, uint64_t *nshared)
  1760. {
  1761. if (c == NULL) {
  1762. *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
  1763. *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
  1764. return;
  1765. }
  1766. *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
  1767. (c->perm & DEFAULT_PERM_UNCHANGED);
  1768. *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
  1769. (c->shared_perm & DEFAULT_PERM_UNCHANGED);
  1770. }
  1771. void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
  1772. const BdrvChildRole *role,
  1773. BlockReopenQueue *reopen_queue,
  1774. uint64_t perm, uint64_t shared,
  1775. uint64_t *nperm, uint64_t *nshared)
  1776. {
  1777. bool backing = (role == &child_backing);
  1778. assert(role == &child_backing || role == &child_file);
  1779. if (!backing) {
  1780. int flags = bdrv_reopen_get_flags(reopen_queue, bs);
  1781. /* Apart from the modifications below, the same permissions are
  1782. * forwarded and left alone as for filters */
  1783. bdrv_filter_default_perms(bs, c, role, reopen_queue, perm, shared,
  1784. &perm, &shared);
  1785. /* Format drivers may touch metadata even if the guest doesn't write */
  1786. if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
  1787. perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  1788. }
  1789. /* bs->file always needs to be consistent because of the metadata. We
  1790. * can never allow other users to resize or write to it. */
  1791. if (!(flags & BDRV_O_NO_IO)) {
  1792. perm |= BLK_PERM_CONSISTENT_READ;
  1793. }
  1794. shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
  1795. } else {
  1796. /* We want consistent read from backing files if the parent needs it.
  1797. * No other operations are performed on backing files. */
  1798. perm &= BLK_PERM_CONSISTENT_READ;
  1799. /* If the parent can deal with changing data, we're okay with a
  1800. * writable and resizable backing file. */
  1801. /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
  1802. if (shared & BLK_PERM_WRITE) {
  1803. shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
  1804. } else {
  1805. shared = 0;
  1806. }
  1807. shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
  1808. BLK_PERM_WRITE_UNCHANGED;
  1809. }
  1810. if (bs->open_flags & BDRV_O_INACTIVE) {
  1811. shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
  1812. }
  1813. *nperm = perm;
  1814. *nshared = shared;
  1815. }
  1816. static void bdrv_replace_child_noperm(BdrvChild *child,
  1817. BlockDriverState *new_bs)
  1818. {
  1819. BlockDriverState *old_bs = child->bs;
  1820. int i;
  1821. assert(!child->frozen);
  1822. if (old_bs && new_bs) {
  1823. assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
  1824. }
  1825. if (old_bs) {
  1826. /* Detach first so that the recursive drain sections coming from @child
  1827. * are already gone and we only end the drain sections that came from
  1828. * elsewhere. */
  1829. if (child->role->detach) {
  1830. child->role->detach(child);
  1831. }
  1832. if (old_bs->quiesce_counter && child->role->drained_end) {
  1833. int num = old_bs->quiesce_counter;
  1834. if (child->role->parent_is_bds) {
  1835. num -= bdrv_drain_all_count;
  1836. }
  1837. assert(num >= 0);
  1838. for (i = 0; i < num; i++) {
  1839. child->role->drained_end(child);
  1840. }
  1841. }
  1842. QLIST_REMOVE(child, next_parent);
  1843. }
  1844. child->bs = new_bs;
  1845. if (new_bs) {
  1846. QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
  1847. if (new_bs->quiesce_counter && child->role->drained_begin) {
  1848. int num = new_bs->quiesce_counter;
  1849. if (child->role->parent_is_bds) {
  1850. num -= bdrv_drain_all_count;
  1851. }
  1852. assert(num >= 0);
  1853. for (i = 0; i < num; i++) {
  1854. bdrv_parent_drained_begin_single(child, true);
  1855. }
  1856. }
  1857. /* Attach only after starting new drained sections, so that recursive
  1858. * drain sections coming from @child don't get an extra .drained_begin
  1859. * callback. */
  1860. if (child->role->attach) {
  1861. child->role->attach(child);
  1862. }
  1863. }
  1864. }
  1865. /*
  1866. * Updates @child to change its reference to point to @new_bs, including
  1867. * checking and applying the necessary permisson updates both to the old node
  1868. * and to @new_bs.
  1869. *
  1870. * NULL is passed as @new_bs for removing the reference before freeing @child.
  1871. *
  1872. * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
  1873. * function uses bdrv_set_perm() to update the permissions according to the new
  1874. * reference that @new_bs gets.
  1875. */
  1876. static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
  1877. {
  1878. BlockDriverState *old_bs = child->bs;
  1879. uint64_t perm, shared_perm;
  1880. bdrv_replace_child_noperm(child, new_bs);
  1881. if (old_bs) {
  1882. /* Update permissions for old node. This is guaranteed to succeed
  1883. * because we're just taking a parent away, so we're loosening
  1884. * restrictions. */
  1885. bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
  1886. bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL, &error_abort);
  1887. bdrv_set_perm(old_bs, perm, shared_perm);
  1888. }
  1889. if (new_bs) {
  1890. bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
  1891. bdrv_set_perm(new_bs, perm, shared_perm);
  1892. }
  1893. }
  1894. BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
  1895. const char *child_name,
  1896. const BdrvChildRole *child_role,
  1897. uint64_t perm, uint64_t shared_perm,
  1898. void *opaque, Error **errp)
  1899. {
  1900. BdrvChild *child;
  1901. int ret;
  1902. ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, errp);
  1903. if (ret < 0) {
  1904. bdrv_abort_perm_update(child_bs);
  1905. return NULL;
  1906. }
  1907. child = g_new(BdrvChild, 1);
  1908. *child = (BdrvChild) {
  1909. .bs = NULL,
  1910. .name = g_strdup(child_name),
  1911. .role = child_role,
  1912. .perm = perm,
  1913. .shared_perm = shared_perm,
  1914. .opaque = opaque,
  1915. };
  1916. /* This performs the matching bdrv_set_perm() for the above check. */
  1917. bdrv_replace_child(child, child_bs);
  1918. return child;
  1919. }
  1920. BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
  1921. BlockDriverState *child_bs,
  1922. const char *child_name,
  1923. const BdrvChildRole *child_role,
  1924. Error **errp)
  1925. {
  1926. BdrvChild *child;
  1927. uint64_t perm, shared_perm;
  1928. bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
  1929. assert(parent_bs->drv);
  1930. assert(bdrv_get_aio_context(parent_bs) == bdrv_get_aio_context(child_bs));
  1931. bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
  1932. perm, shared_perm, &perm, &shared_perm);
  1933. child = bdrv_root_attach_child(child_bs, child_name, child_role,
  1934. perm, shared_perm, parent_bs, errp);
  1935. if (child == NULL) {
  1936. return NULL;
  1937. }
  1938. QLIST_INSERT_HEAD(&parent_bs->children, child, next);
  1939. return child;
  1940. }
  1941. static void bdrv_detach_child(BdrvChild *child)
  1942. {
  1943. if (child->next.le_prev) {
  1944. QLIST_REMOVE(child, next);
  1945. child->next.le_prev = NULL;
  1946. }
  1947. bdrv_replace_child(child, NULL);
  1948. g_free(child->name);
  1949. g_free(child);
  1950. }
  1951. void bdrv_root_unref_child(BdrvChild *child)
  1952. {
  1953. BlockDriverState *child_bs;
  1954. child_bs = child->bs;
  1955. bdrv_detach_child(child);
  1956. bdrv_unref(child_bs);
  1957. }
  1958. void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
  1959. {
  1960. if (child == NULL) {
  1961. return;
  1962. }
  1963. if (child->bs->inherits_from == parent) {
  1964. BdrvChild *c;
  1965. /* Remove inherits_from only when the last reference between parent and
  1966. * child->bs goes away. */
  1967. QLIST_FOREACH(c, &parent->children, next) {
  1968. if (c != child && c->bs == child->bs) {
  1969. break;
  1970. }
  1971. }
  1972. if (c == NULL) {
  1973. child->bs->inherits_from = NULL;
  1974. }
  1975. }
  1976. bdrv_root_unref_child(child);
  1977. }
  1978. static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
  1979. {
  1980. BdrvChild *c;
  1981. QLIST_FOREACH(c, &bs->parents, next_parent) {
  1982. if (c->role->change_media) {
  1983. c->role->change_media(c, load);
  1984. }
  1985. }
  1986. }
  1987. /* Return true if you can reach parent going through child->inherits_from
  1988. * recursively. If parent or child are NULL, return false */
  1989. static bool bdrv_inherits_from_recursive(BlockDriverState *child,
  1990. BlockDriverState *parent)
  1991. {
  1992. while (child && child != parent) {
  1993. child = child->inherits_from;
  1994. }
  1995. return child != NULL;
  1996. }
  1997. /*
  1998. * Sets the backing file link of a BDS. A new reference is created; callers
  1999. * which don't need their own reference any more must call bdrv_unref().
  2000. */
  2001. void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
  2002. Error **errp)
  2003. {
  2004. bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
  2005. bdrv_inherits_from_recursive(backing_hd, bs);
  2006. if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
  2007. return;
  2008. }
  2009. if (backing_hd) {
  2010. bdrv_ref(backing_hd);
  2011. }
  2012. if (bs->backing) {
  2013. bdrv_unref_child(bs, bs->backing);
  2014. }
  2015. if (!backing_hd) {
  2016. bs->backing = NULL;
  2017. goto out;
  2018. }
  2019. bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
  2020. errp);
  2021. /* If backing_hd was already part of bs's backing chain, and
  2022. * inherits_from pointed recursively to bs then let's update it to
  2023. * point directly to bs (else it will become NULL). */
  2024. if (update_inherits_from) {
  2025. backing_hd->inherits_from = bs;
  2026. }
  2027. if (!bs->backing) {
  2028. bdrv_unref(backing_hd);
  2029. }
  2030. out:
  2031. bdrv_refresh_limits(bs, NULL);
  2032. }
  2033. /*
  2034. * Opens the backing file for a BlockDriverState if not yet open
  2035. *
  2036. * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
  2037. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  2038. * itself, all options starting with "${bdref_key}." are considered part of the
  2039. * BlockdevRef.
  2040. *
  2041. * TODO Can this be unified with bdrv_open_image()?
  2042. */
  2043. int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
  2044. const char *bdref_key, Error **errp)
  2045. {
  2046. char *backing_filename = NULL;
  2047. char *bdref_key_dot;
  2048. const char *reference = NULL;
  2049. int ret = 0;
  2050. bool implicit_backing = false;
  2051. BlockDriverState *backing_hd;
  2052. QDict *options;
  2053. QDict *tmp_parent_options = NULL;
  2054. Error *local_err = NULL;
  2055. if (bs->backing != NULL) {
  2056. goto free_exit;
  2057. }
  2058. /* NULL means an empty set of options */
  2059. if (parent_options == NULL) {
  2060. tmp_parent_options = qdict_new();
  2061. parent_options = tmp_parent_options;
  2062. }
  2063. bs->open_flags &= ~BDRV_O_NO_BACKING;
  2064. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  2065. qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
  2066. g_free(bdref_key_dot);
  2067. /*
  2068. * Caution: while qdict_get_try_str() is fine, getting non-string
  2069. * types would require more care. When @parent_options come from
  2070. * -blockdev or blockdev_add, its members are typed according to
  2071. * the QAPI schema, but when they come from -drive, they're all
  2072. * QString.
  2073. */
  2074. reference = qdict_get_try_str(parent_options, bdref_key);
  2075. if (reference || qdict_haskey(options, "file.filename")) {
  2076. /* keep backing_filename NULL */
  2077. } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
  2078. qobject_unref(options);
  2079. goto free_exit;
  2080. } else {
  2081. if (qdict_size(options) == 0) {
  2082. /* If the user specifies options that do not modify the
  2083. * backing file's behavior, we might still consider it the
  2084. * implicit backing file. But it's easier this way, and
  2085. * just specifying some of the backing BDS's options is
  2086. * only possible with -drive anyway (otherwise the QAPI
  2087. * schema forces the user to specify everything). */
  2088. implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
  2089. }
  2090. backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
  2091. if (local_err) {
  2092. ret = -EINVAL;
  2093. error_propagate(errp, local_err);
  2094. qobject_unref(options);
  2095. goto free_exit;
  2096. }
  2097. }
  2098. if (!bs->drv || !bs->drv->supports_backing) {
  2099. ret = -EINVAL;
  2100. error_setg(errp, "Driver doesn't support backing files");
  2101. qobject_unref(options);
  2102. goto free_exit;
  2103. }
  2104. if (!reference &&
  2105. bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
  2106. qdict_put_str(options, "driver", bs->backing_format);
  2107. }
  2108. backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
  2109. &child_backing, errp);
  2110. if (!backing_hd) {
  2111. bs->open_flags |= BDRV_O_NO_BACKING;
  2112. error_prepend(errp, "Could not open backing file: ");
  2113. ret = -EINVAL;
  2114. goto free_exit;
  2115. }
  2116. bdrv_set_aio_context(backing_hd, bdrv_get_aio_context(bs));
  2117. if (implicit_backing) {
  2118. bdrv_refresh_filename(backing_hd);
  2119. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  2120. backing_hd->filename);
  2121. }
  2122. /* Hook up the backing file link; drop our reference, bs owns the
  2123. * backing_hd reference now */
  2124. bdrv_set_backing_hd(bs, backing_hd, &local_err);
  2125. bdrv_unref(backing_hd);
  2126. if (local_err) {
  2127. error_propagate(errp, local_err);
  2128. ret = -EINVAL;
  2129. goto free_exit;
  2130. }
  2131. qdict_del(parent_options, bdref_key);
  2132. free_exit:
  2133. g_free(backing_filename);
  2134. qobject_unref(tmp_parent_options);
  2135. return ret;
  2136. }
  2137. static BlockDriverState *
  2138. bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
  2139. BlockDriverState *parent, const BdrvChildRole *child_role,
  2140. bool allow_none, Error **errp)
  2141. {
  2142. BlockDriverState *bs = NULL;
  2143. QDict *image_options;
  2144. char *bdref_key_dot;
  2145. const char *reference;
  2146. assert(child_role != NULL);
  2147. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  2148. qdict_extract_subqdict(options, &image_options, bdref_key_dot);
  2149. g_free(bdref_key_dot);
  2150. /*
  2151. * Caution: while qdict_get_try_str() is fine, getting non-string
  2152. * types would require more care. When @options come from
  2153. * -blockdev or blockdev_add, its members are typed according to
  2154. * the QAPI schema, but when they come from -drive, they're all
  2155. * QString.
  2156. */
  2157. reference = qdict_get_try_str(options, bdref_key);
  2158. if (!filename && !reference && !qdict_size(image_options)) {
  2159. if (!allow_none) {
  2160. error_setg(errp, "A block device must be specified for \"%s\"",
  2161. bdref_key);
  2162. }
  2163. qobject_unref(image_options);
  2164. goto done;
  2165. }
  2166. bs = bdrv_open_inherit(filename, reference, image_options, 0,
  2167. parent, child_role, errp);
  2168. if (!bs) {
  2169. goto done;
  2170. }
  2171. done:
  2172. qdict_del(options, bdref_key);
  2173. return bs;
  2174. }
  2175. /*
  2176. * Opens a disk image whose options are given as BlockdevRef in another block
  2177. * device's options.
  2178. *
  2179. * If allow_none is true, no image will be opened if filename is false and no
  2180. * BlockdevRef is given. NULL will be returned, but errp remains unset.
  2181. *
  2182. * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
  2183. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  2184. * itself, all options starting with "${bdref_key}." are considered part of the
  2185. * BlockdevRef.
  2186. *
  2187. * The BlockdevRef will be removed from the options QDict.
  2188. */
  2189. BdrvChild *bdrv_open_child(const char *filename,
  2190. QDict *options, const char *bdref_key,
  2191. BlockDriverState *parent,
  2192. const BdrvChildRole *child_role,
  2193. bool allow_none, Error **errp)
  2194. {
  2195. BdrvChild *c;
  2196. BlockDriverState *bs;
  2197. bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
  2198. allow_none, errp);
  2199. if (bs == NULL) {
  2200. return NULL;
  2201. }
  2202. c = bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
  2203. if (!c) {
  2204. bdrv_unref(bs);
  2205. return NULL;
  2206. }
  2207. return c;
  2208. }
  2209. /* TODO Future callers may need to specify parent/child_role in order for
  2210. * option inheritance to work. Existing callers use it for the root node. */
  2211. BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
  2212. {
  2213. BlockDriverState *bs = NULL;
  2214. Error *local_err = NULL;
  2215. QObject *obj = NULL;
  2216. QDict *qdict = NULL;
  2217. const char *reference = NULL;
  2218. Visitor *v = NULL;
  2219. if (ref->type == QTYPE_QSTRING) {
  2220. reference = ref->u.reference;
  2221. } else {
  2222. BlockdevOptions *options = &ref->u.definition;
  2223. assert(ref->type == QTYPE_QDICT);
  2224. v = qobject_output_visitor_new(&obj);
  2225. visit_type_BlockdevOptions(v, NULL, &options, &local_err);
  2226. if (local_err) {
  2227. error_propagate(errp, local_err);
  2228. goto fail;
  2229. }
  2230. visit_complete(v, &obj);
  2231. qdict = qobject_to(QDict, obj);
  2232. qdict_flatten(qdict);
  2233. /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
  2234. * compatibility with other callers) rather than what we want as the
  2235. * real defaults. Apply the defaults here instead. */
  2236. qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
  2237. qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
  2238. qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
  2239. qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
  2240. }
  2241. bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, errp);
  2242. obj = NULL;
  2243. fail:
  2244. qobject_unref(obj);
  2245. visit_free(v);
  2246. return bs;
  2247. }
  2248. static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
  2249. int flags,
  2250. QDict *snapshot_options,
  2251. Error **errp)
  2252. {
  2253. /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
  2254. char *tmp_filename = g_malloc0(PATH_MAX + 1);
  2255. int64_t total_size;
  2256. QemuOpts *opts = NULL;
  2257. BlockDriverState *bs_snapshot = NULL;
  2258. Error *local_err = NULL;
  2259. int ret;
  2260. /* if snapshot, we create a temporary backing file and open it
  2261. instead of opening 'filename' directly */
  2262. /* Get the required size from the image */
  2263. total_size = bdrv_getlength(bs);
  2264. if (total_size < 0) {
  2265. error_setg_errno(errp, -total_size, "Could not get image size");
  2266. goto out;
  2267. }
  2268. /* Create the temporary image */
  2269. ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
  2270. if (ret < 0) {
  2271. error_setg_errno(errp, -ret, "Could not get temporary filename");
  2272. goto out;
  2273. }
  2274. opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
  2275. &error_abort);
  2276. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
  2277. ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
  2278. qemu_opts_del(opts);
  2279. if (ret < 0) {
  2280. error_prepend(errp, "Could not create temporary overlay '%s': ",
  2281. tmp_filename);
  2282. goto out;
  2283. }
  2284. /* Prepare options QDict for the temporary file */
  2285. qdict_put_str(snapshot_options, "file.driver", "file");
  2286. qdict_put_str(snapshot_options, "file.filename", tmp_filename);
  2287. qdict_put_str(snapshot_options, "driver", "qcow2");
  2288. bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
  2289. snapshot_options = NULL;
  2290. if (!bs_snapshot) {
  2291. goto out;
  2292. }
  2293. /* bdrv_append() consumes a strong reference to bs_snapshot
  2294. * (i.e. it will call bdrv_unref() on it) even on error, so in
  2295. * order to be able to return one, we have to increase
  2296. * bs_snapshot's refcount here */
  2297. bdrv_ref(bs_snapshot);
  2298. bdrv_append(bs_snapshot, bs, &local_err);
  2299. if (local_err) {
  2300. error_propagate(errp, local_err);
  2301. bs_snapshot = NULL;
  2302. goto out;
  2303. }
  2304. out:
  2305. qobject_unref(snapshot_options);
  2306. g_free(tmp_filename);
  2307. return bs_snapshot;
  2308. }
  2309. /*
  2310. * Opens a disk image (raw, qcow2, vmdk, ...)
  2311. *
  2312. * options is a QDict of options to pass to the block drivers, or NULL for an
  2313. * empty set of options. The reference to the QDict belongs to the block layer
  2314. * after the call (even on failure), so if the caller intends to reuse the
  2315. * dictionary, it needs to use qobject_ref() before calling bdrv_open.
  2316. *
  2317. * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
  2318. * If it is not NULL, the referenced BDS will be reused.
  2319. *
  2320. * The reference parameter may be used to specify an existing block device which
  2321. * should be opened. If specified, neither options nor a filename may be given,
  2322. * nor can an existing BDS be reused (that is, *pbs has to be NULL).
  2323. */
  2324. static BlockDriverState *bdrv_open_inherit(const char *filename,
  2325. const char *reference,
  2326. QDict *options, int flags,
  2327. BlockDriverState *parent,
  2328. const BdrvChildRole *child_role,
  2329. Error **errp)
  2330. {
  2331. int ret;
  2332. BlockBackend *file = NULL;
  2333. BlockDriverState *bs;
  2334. BlockDriver *drv = NULL;
  2335. BdrvChild *child;
  2336. const char *drvname;
  2337. const char *backing;
  2338. Error *local_err = NULL;
  2339. QDict *snapshot_options = NULL;
  2340. int snapshot_flags = 0;
  2341. assert(!child_role || !flags);
  2342. assert(!child_role == !parent);
  2343. if (reference) {
  2344. bool options_non_empty = options ? qdict_size(options) : false;
  2345. qobject_unref(options);
  2346. if (filename || options_non_empty) {
  2347. error_setg(errp, "Cannot reference an existing block device with "
  2348. "additional options or a new filename");
  2349. return NULL;
  2350. }
  2351. bs = bdrv_lookup_bs(reference, reference, errp);
  2352. if (!bs) {
  2353. return NULL;
  2354. }
  2355. bdrv_ref(bs);
  2356. return bs;
  2357. }
  2358. bs = bdrv_new();
  2359. /* NULL means an empty set of options */
  2360. if (options == NULL) {
  2361. options = qdict_new();
  2362. }
  2363. /* json: syntax counts as explicit options, as if in the QDict */
  2364. parse_json_protocol(options, &filename, &local_err);
  2365. if (local_err) {
  2366. goto fail;
  2367. }
  2368. bs->explicit_options = qdict_clone_shallow(options);
  2369. if (child_role) {
  2370. bs->inherits_from = parent;
  2371. child_role->inherit_options(&flags, options,
  2372. parent->open_flags, parent->options);
  2373. }
  2374. ret = bdrv_fill_options(&options, filename, &flags, &local_err);
  2375. if (local_err) {
  2376. goto fail;
  2377. }
  2378. /*
  2379. * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
  2380. * Caution: getting a boolean member of @options requires care.
  2381. * When @options come from -blockdev or blockdev_add, members are
  2382. * typed according to the QAPI schema, but when they come from
  2383. * -drive, they're all QString.
  2384. */
  2385. if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
  2386. !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
  2387. flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
  2388. } else {
  2389. flags &= ~BDRV_O_RDWR;
  2390. }
  2391. if (flags & BDRV_O_SNAPSHOT) {
  2392. snapshot_options = qdict_new();
  2393. bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
  2394. flags, options);
  2395. /* Let bdrv_backing_options() override "read-only" */
  2396. qdict_del(options, BDRV_OPT_READ_ONLY);
  2397. bdrv_backing_options(&flags, options, flags, options);
  2398. }
  2399. bs->open_flags = flags;
  2400. bs->options = options;
  2401. options = qdict_clone_shallow(options);
  2402. /* Find the right image format driver */
  2403. /* See cautionary note on accessing @options above */
  2404. drvname = qdict_get_try_str(options, "driver");
  2405. if (drvname) {
  2406. drv = bdrv_find_format(drvname);
  2407. if (!drv) {
  2408. error_setg(errp, "Unknown driver: '%s'", drvname);
  2409. goto fail;
  2410. }
  2411. }
  2412. assert(drvname || !(flags & BDRV_O_PROTOCOL));
  2413. /* See cautionary note on accessing @options above */
  2414. backing = qdict_get_try_str(options, "backing");
  2415. if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
  2416. (backing && *backing == '\0'))
  2417. {
  2418. if (backing) {
  2419. warn_report("Use of \"backing\": \"\" is deprecated; "
  2420. "use \"backing\": null instead");
  2421. }
  2422. flags |= BDRV_O_NO_BACKING;
  2423. qdict_del(options, "backing");
  2424. }
  2425. /* Open image file without format layer. This BlockBackend is only used for
  2426. * probing, the block drivers will do their own bdrv_open_child() for the
  2427. * same BDS, which is why we put the node name back into options. */
  2428. if ((flags & BDRV_O_PROTOCOL) == 0) {
  2429. BlockDriverState *file_bs;
  2430. file_bs = bdrv_open_child_bs(filename, options, "file", bs,
  2431. &child_file, true, &local_err);
  2432. if (local_err) {
  2433. goto fail;
  2434. }
  2435. if (file_bs != NULL) {
  2436. /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
  2437. * looking at the header to guess the image format. This works even
  2438. * in cases where a guest would not see a consistent state. */
  2439. file = blk_new(0, BLK_PERM_ALL);
  2440. blk_insert_bs(file, file_bs, &local_err);
  2441. bdrv_unref(file_bs);
  2442. if (local_err) {
  2443. goto fail;
  2444. }
  2445. qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
  2446. }
  2447. }
  2448. /* Image format probing */
  2449. bs->probed = !drv;
  2450. if (!drv && file) {
  2451. ret = find_image_format(file, filename, &drv, &local_err);
  2452. if (ret < 0) {
  2453. goto fail;
  2454. }
  2455. /*
  2456. * This option update would logically belong in bdrv_fill_options(),
  2457. * but we first need to open bs->file for the probing to work, while
  2458. * opening bs->file already requires the (mostly) final set of options
  2459. * so that cache mode etc. can be inherited.
  2460. *
  2461. * Adding the driver later is somewhat ugly, but it's not an option
  2462. * that would ever be inherited, so it's correct. We just need to make
  2463. * sure to update both bs->options (which has the full effective
  2464. * options for bs) and options (which has file.* already removed).
  2465. */
  2466. qdict_put_str(bs->options, "driver", drv->format_name);
  2467. qdict_put_str(options, "driver", drv->format_name);
  2468. } else if (!drv) {
  2469. error_setg(errp, "Must specify either driver or file");
  2470. goto fail;
  2471. }
  2472. /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
  2473. assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
  2474. /* file must be NULL if a protocol BDS is about to be created
  2475. * (the inverse results in an error message from bdrv_open_common()) */
  2476. assert(!(flags & BDRV_O_PROTOCOL) || !file);
  2477. /* Open the image */
  2478. ret = bdrv_open_common(bs, file, options, &local_err);
  2479. if (ret < 0) {
  2480. goto fail;
  2481. }
  2482. if (file) {
  2483. blk_unref(file);
  2484. file = NULL;
  2485. }
  2486. /* If there is a backing file, use it */
  2487. if ((flags & BDRV_O_NO_BACKING) == 0) {
  2488. ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
  2489. if (ret < 0) {
  2490. goto close_and_fail;
  2491. }
  2492. }
  2493. /* Remove all children options and references
  2494. * from bs->options and bs->explicit_options */
  2495. QLIST_FOREACH(child, &bs->children, next) {
  2496. char *child_key_dot;
  2497. child_key_dot = g_strdup_printf("%s.", child->name);
  2498. qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
  2499. qdict_extract_subqdict(bs->options, NULL, child_key_dot);
  2500. qdict_del(bs->explicit_options, child->name);
  2501. qdict_del(bs->options, child->name);
  2502. g_free(child_key_dot);
  2503. }
  2504. /* Check if any unknown options were used */
  2505. if (qdict_size(options) != 0) {
  2506. const QDictEntry *entry = qdict_first(options);
  2507. if (flags & BDRV_O_PROTOCOL) {
  2508. error_setg(errp, "Block protocol '%s' doesn't support the option "
  2509. "'%s'", drv->format_name, entry->key);
  2510. } else {
  2511. error_setg(errp,
  2512. "Block format '%s' does not support the option '%s'",
  2513. drv->format_name, entry->key);
  2514. }
  2515. goto close_and_fail;
  2516. }
  2517. bdrv_parent_cb_change_media(bs, true);
  2518. qobject_unref(options);
  2519. options = NULL;
  2520. /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
  2521. * temporary snapshot afterwards. */
  2522. if (snapshot_flags) {
  2523. BlockDriverState *snapshot_bs;
  2524. snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
  2525. snapshot_options, &local_err);
  2526. snapshot_options = NULL;
  2527. if (local_err) {
  2528. goto close_and_fail;
  2529. }
  2530. /* We are not going to return bs but the overlay on top of it
  2531. * (snapshot_bs); thus, we have to drop the strong reference to bs
  2532. * (which we obtained by calling bdrv_new()). bs will not be deleted,
  2533. * though, because the overlay still has a reference to it. */
  2534. bdrv_unref(bs);
  2535. bs = snapshot_bs;
  2536. }
  2537. return bs;
  2538. fail:
  2539. blk_unref(file);
  2540. qobject_unref(snapshot_options);
  2541. qobject_unref(bs->explicit_options);
  2542. qobject_unref(bs->options);
  2543. qobject_unref(options);
  2544. bs->options = NULL;
  2545. bs->explicit_options = NULL;
  2546. bdrv_unref(bs);
  2547. error_propagate(errp, local_err);
  2548. return NULL;
  2549. close_and_fail:
  2550. bdrv_unref(bs);
  2551. qobject_unref(snapshot_options);
  2552. qobject_unref(options);
  2553. error_propagate(errp, local_err);
  2554. return NULL;
  2555. }
  2556. BlockDriverState *bdrv_open(const char *filename, const char *reference,
  2557. QDict *options, int flags, Error **errp)
  2558. {
  2559. return bdrv_open_inherit(filename, reference, options, flags, NULL,
  2560. NULL, errp);
  2561. }
  2562. /* Return true if the NULL-terminated @list contains @str */
  2563. static bool is_str_in_list(const char *str, const char *const *list)
  2564. {
  2565. if (str && list) {
  2566. int i;
  2567. for (i = 0; list[i] != NULL; i++) {
  2568. if (!strcmp(str, list[i])) {
  2569. return true;
  2570. }
  2571. }
  2572. }
  2573. return false;
  2574. }
  2575. /*
  2576. * Check that every option set in @bs->options is also set in
  2577. * @new_opts.
  2578. *
  2579. * Options listed in the common_options list and in
  2580. * @bs->drv->mutable_opts are skipped.
  2581. *
  2582. * Return 0 on success, otherwise return -EINVAL and set @errp.
  2583. */
  2584. static int bdrv_reset_options_allowed(BlockDriverState *bs,
  2585. const QDict *new_opts, Error **errp)
  2586. {
  2587. const QDictEntry *e;
  2588. /* These options are common to all block drivers and are handled
  2589. * in bdrv_reopen_prepare() so they can be left out of @new_opts */
  2590. const char *const common_options[] = {
  2591. "node-name", "discard", "cache.direct", "cache.no-flush",
  2592. "read-only", "auto-read-only", "detect-zeroes", NULL
  2593. };
  2594. for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
  2595. if (!qdict_haskey(new_opts, e->key) &&
  2596. !is_str_in_list(e->key, common_options) &&
  2597. !is_str_in_list(e->key, bs->drv->mutable_opts)) {
  2598. error_setg(errp, "Option '%s' cannot be reset "
  2599. "to its default value", e->key);
  2600. return -EINVAL;
  2601. }
  2602. }
  2603. return 0;
  2604. }
  2605. /*
  2606. * Returns true if @child can be reached recursively from @bs
  2607. */
  2608. static bool bdrv_recurse_has_child(BlockDriverState *bs,
  2609. BlockDriverState *child)
  2610. {
  2611. BdrvChild *c;
  2612. if (bs == child) {
  2613. return true;
  2614. }
  2615. QLIST_FOREACH(c, &bs->children, next) {
  2616. if (bdrv_recurse_has_child(c->bs, child)) {
  2617. return true;
  2618. }
  2619. }
  2620. return false;
  2621. }
  2622. /*
  2623. * Adds a BlockDriverState to a simple queue for an atomic, transactional
  2624. * reopen of multiple devices.
  2625. *
  2626. * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
  2627. * already performed, or alternatively may be NULL a new BlockReopenQueue will
  2628. * be created and initialized. This newly created BlockReopenQueue should be
  2629. * passed back in for subsequent calls that are intended to be of the same
  2630. * atomic 'set'.
  2631. *
  2632. * bs is the BlockDriverState to add to the reopen queue.
  2633. *
  2634. * options contains the changed options for the associated bs
  2635. * (the BlockReopenQueue takes ownership)
  2636. *
  2637. * flags contains the open flags for the associated bs
  2638. *
  2639. * returns a pointer to bs_queue, which is either the newly allocated
  2640. * bs_queue, or the existing bs_queue being used.
  2641. *
  2642. * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
  2643. */
  2644. static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
  2645. BlockDriverState *bs,
  2646. QDict *options,
  2647. const BdrvChildRole *role,
  2648. QDict *parent_options,
  2649. int parent_flags,
  2650. bool keep_old_opts)
  2651. {
  2652. assert(bs != NULL);
  2653. BlockReopenQueueEntry *bs_entry;
  2654. BdrvChild *child;
  2655. QDict *old_options, *explicit_options, *options_copy;
  2656. int flags;
  2657. QemuOpts *opts;
  2658. /* Make sure that the caller remembered to use a drained section. This is
  2659. * important to avoid graph changes between the recursive queuing here and
  2660. * bdrv_reopen_multiple(). */
  2661. assert(bs->quiesce_counter > 0);
  2662. if (bs_queue == NULL) {
  2663. bs_queue = g_new0(BlockReopenQueue, 1);
  2664. QSIMPLEQ_INIT(bs_queue);
  2665. }
  2666. if (!options) {
  2667. options = qdict_new();
  2668. }
  2669. /* Check if this BlockDriverState is already in the queue */
  2670. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2671. if (bs == bs_entry->state.bs) {
  2672. break;
  2673. }
  2674. }
  2675. /*
  2676. * Precedence of options:
  2677. * 1. Explicitly passed in options (highest)
  2678. * 2. Retained from explicitly set options of bs
  2679. * 3. Inherited from parent node
  2680. * 4. Retained from effective options of bs
  2681. */
  2682. /* Old explicitly set values (don't overwrite by inherited value) */
  2683. if (bs_entry || keep_old_opts) {
  2684. old_options = qdict_clone_shallow(bs_entry ?
  2685. bs_entry->state.explicit_options :
  2686. bs->explicit_options);
  2687. bdrv_join_options(bs, options, old_options);
  2688. qobject_unref(old_options);
  2689. }
  2690. explicit_options = qdict_clone_shallow(options);
  2691. /* Inherit from parent node */
  2692. if (parent_options) {
  2693. flags = 0;
  2694. role->inherit_options(&flags, options, parent_flags, parent_options);
  2695. } else {
  2696. flags = bdrv_get_flags(bs);
  2697. }
  2698. if (keep_old_opts) {
  2699. /* Old values are used for options that aren't set yet */
  2700. old_options = qdict_clone_shallow(bs->options);
  2701. bdrv_join_options(bs, options, old_options);
  2702. qobject_unref(old_options);
  2703. }
  2704. /* We have the final set of options so let's update the flags */
  2705. options_copy = qdict_clone_shallow(options);
  2706. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  2707. qemu_opts_absorb_qdict(opts, options_copy, NULL);
  2708. update_flags_from_options(&flags, opts);
  2709. qemu_opts_del(opts);
  2710. qobject_unref(options_copy);
  2711. /* bdrv_open_inherit() sets and clears some additional flags internally */
  2712. flags &= ~BDRV_O_PROTOCOL;
  2713. if (flags & BDRV_O_RDWR) {
  2714. flags |= BDRV_O_ALLOW_RDWR;
  2715. }
  2716. if (!bs_entry) {
  2717. bs_entry = g_new0(BlockReopenQueueEntry, 1);
  2718. QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
  2719. } else {
  2720. qobject_unref(bs_entry->state.options);
  2721. qobject_unref(bs_entry->state.explicit_options);
  2722. }
  2723. bs_entry->state.bs = bs;
  2724. bs_entry->state.options = options;
  2725. bs_entry->state.explicit_options = explicit_options;
  2726. bs_entry->state.flags = flags;
  2727. /* This needs to be overwritten in bdrv_reopen_prepare() */
  2728. bs_entry->state.perm = UINT64_MAX;
  2729. bs_entry->state.shared_perm = 0;
  2730. /*
  2731. * If keep_old_opts is false then it means that unspecified
  2732. * options must be reset to their original value. We don't allow
  2733. * resetting 'backing' but we need to know if the option is
  2734. * missing in order to decide if we have to return an error.
  2735. */
  2736. if (!keep_old_opts) {
  2737. bs_entry->state.backing_missing =
  2738. !qdict_haskey(options, "backing") &&
  2739. !qdict_haskey(options, "backing.driver");
  2740. }
  2741. QLIST_FOREACH(child, &bs->children, next) {
  2742. QDict *new_child_options = NULL;
  2743. bool child_keep_old = keep_old_opts;
  2744. /* reopen can only change the options of block devices that were
  2745. * implicitly created and inherited options. For other (referenced)
  2746. * block devices, a syntax like "backing.foo" results in an error. */
  2747. if (child->bs->inherits_from != bs) {
  2748. continue;
  2749. }
  2750. /* Check if the options contain a child reference */
  2751. if (qdict_haskey(options, child->name)) {
  2752. const char *childref = qdict_get_try_str(options, child->name);
  2753. /*
  2754. * The current child must not be reopened if the child
  2755. * reference is null or points to a different node.
  2756. */
  2757. if (g_strcmp0(childref, child->bs->node_name)) {
  2758. continue;
  2759. }
  2760. /*
  2761. * If the child reference points to the current child then
  2762. * reopen it with its existing set of options (note that
  2763. * it can still inherit new options from the parent).
  2764. */
  2765. child_keep_old = true;
  2766. } else {
  2767. /* Extract child options ("child-name.*") */
  2768. char *child_key_dot = g_strdup_printf("%s.", child->name);
  2769. qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
  2770. qdict_extract_subqdict(options, &new_child_options, child_key_dot);
  2771. g_free(child_key_dot);
  2772. }
  2773. bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
  2774. child->role, options, flags, child_keep_old);
  2775. }
  2776. return bs_queue;
  2777. }
  2778. BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
  2779. BlockDriverState *bs,
  2780. QDict *options, bool keep_old_opts)
  2781. {
  2782. return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, NULL, 0,
  2783. keep_old_opts);
  2784. }
  2785. /*
  2786. * Reopen multiple BlockDriverStates atomically & transactionally.
  2787. *
  2788. * The queue passed in (bs_queue) must have been built up previous
  2789. * via bdrv_reopen_queue().
  2790. *
  2791. * Reopens all BDS specified in the queue, with the appropriate
  2792. * flags. All devices are prepared for reopen, and failure of any
  2793. * device will cause all device changes to be abandoned, and intermediate
  2794. * data cleaned up.
  2795. *
  2796. * If all devices prepare successfully, then the changes are committed
  2797. * to all devices.
  2798. *
  2799. * All affected nodes must be drained between bdrv_reopen_queue() and
  2800. * bdrv_reopen_multiple().
  2801. */
  2802. int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
  2803. {
  2804. int ret = -1;
  2805. BlockReopenQueueEntry *bs_entry, *next;
  2806. assert(bs_queue != NULL);
  2807. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2808. assert(bs_entry->state.bs->quiesce_counter > 0);
  2809. if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
  2810. goto cleanup;
  2811. }
  2812. bs_entry->prepared = true;
  2813. }
  2814. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2815. BDRVReopenState *state = &bs_entry->state;
  2816. ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
  2817. state->shared_perm, NULL, errp);
  2818. if (ret < 0) {
  2819. goto cleanup_perm;
  2820. }
  2821. /* Check if new_backing_bs would accept the new permissions */
  2822. if (state->replace_backing_bs && state->new_backing_bs) {
  2823. uint64_t nperm, nshared;
  2824. bdrv_child_perm(state->bs, state->new_backing_bs,
  2825. NULL, &child_backing, bs_queue,
  2826. state->perm, state->shared_perm,
  2827. &nperm, &nshared);
  2828. ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
  2829. nperm, nshared, NULL, errp);
  2830. if (ret < 0) {
  2831. goto cleanup_perm;
  2832. }
  2833. }
  2834. bs_entry->perms_checked = true;
  2835. }
  2836. /* If we reach this point, we have success and just need to apply the
  2837. * changes
  2838. */
  2839. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  2840. bdrv_reopen_commit(&bs_entry->state);
  2841. }
  2842. ret = 0;
  2843. cleanup_perm:
  2844. QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  2845. BDRVReopenState *state = &bs_entry->state;
  2846. if (!bs_entry->perms_checked) {
  2847. continue;
  2848. }
  2849. if (ret == 0) {
  2850. bdrv_set_perm(state->bs, state->perm, state->shared_perm);
  2851. } else {
  2852. bdrv_abort_perm_update(state->bs);
  2853. if (state->replace_backing_bs && state->new_backing_bs) {
  2854. bdrv_abort_perm_update(state->new_backing_bs);
  2855. }
  2856. }
  2857. }
  2858. cleanup:
  2859. QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  2860. if (ret) {
  2861. if (bs_entry->prepared) {
  2862. bdrv_reopen_abort(&bs_entry->state);
  2863. }
  2864. qobject_unref(bs_entry->state.explicit_options);
  2865. qobject_unref(bs_entry->state.options);
  2866. }
  2867. if (bs_entry->state.new_backing_bs) {
  2868. bdrv_unref(bs_entry->state.new_backing_bs);
  2869. }
  2870. g_free(bs_entry);
  2871. }
  2872. g_free(bs_queue);
  2873. return ret;
  2874. }
  2875. int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
  2876. Error **errp)
  2877. {
  2878. int ret;
  2879. BlockReopenQueue *queue;
  2880. QDict *opts = qdict_new();
  2881. qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
  2882. bdrv_subtree_drained_begin(bs);
  2883. queue = bdrv_reopen_queue(NULL, bs, opts, true);
  2884. ret = bdrv_reopen_multiple(queue, errp);
  2885. bdrv_subtree_drained_end(bs);
  2886. return ret;
  2887. }
  2888. static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
  2889. BdrvChild *c)
  2890. {
  2891. BlockReopenQueueEntry *entry;
  2892. QSIMPLEQ_FOREACH(entry, q, entry) {
  2893. BlockDriverState *bs = entry->state.bs;
  2894. BdrvChild *child;
  2895. QLIST_FOREACH(child, &bs->children, next) {
  2896. if (child == c) {
  2897. return entry;
  2898. }
  2899. }
  2900. }
  2901. return NULL;
  2902. }
  2903. static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
  2904. uint64_t *perm, uint64_t *shared)
  2905. {
  2906. BdrvChild *c;
  2907. BlockReopenQueueEntry *parent;
  2908. uint64_t cumulative_perms = 0;
  2909. uint64_t cumulative_shared_perms = BLK_PERM_ALL;
  2910. QLIST_FOREACH(c, &bs->parents, next_parent) {
  2911. parent = find_parent_in_reopen_queue(q, c);
  2912. if (!parent) {
  2913. cumulative_perms |= c->perm;
  2914. cumulative_shared_perms &= c->shared_perm;
  2915. } else {
  2916. uint64_t nperm, nshared;
  2917. bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
  2918. parent->state.perm, parent->state.shared_perm,
  2919. &nperm, &nshared);
  2920. cumulative_perms |= nperm;
  2921. cumulative_shared_perms &= nshared;
  2922. }
  2923. }
  2924. *perm = cumulative_perms;
  2925. *shared = cumulative_shared_perms;
  2926. }
  2927. /*
  2928. * Take a BDRVReopenState and check if the value of 'backing' in the
  2929. * reopen_state->options QDict is valid or not.
  2930. *
  2931. * If 'backing' is missing from the QDict then return 0.
  2932. *
  2933. * If 'backing' contains the node name of the backing file of
  2934. * reopen_state->bs then return 0.
  2935. *
  2936. * If 'backing' contains a different node name (or is null) then check
  2937. * whether the current backing file can be replaced with the new one.
  2938. * If that's the case then reopen_state->replace_backing_bs is set to
  2939. * true and reopen_state->new_backing_bs contains a pointer to the new
  2940. * backing BlockDriverState (or NULL).
  2941. *
  2942. * Return 0 on success, otherwise return < 0 and set @errp.
  2943. */
  2944. static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
  2945. Error **errp)
  2946. {
  2947. BlockDriverState *bs = reopen_state->bs;
  2948. BlockDriverState *overlay_bs, *new_backing_bs;
  2949. QObject *value;
  2950. const char *str;
  2951. value = qdict_get(reopen_state->options, "backing");
  2952. if (value == NULL) {
  2953. return 0;
  2954. }
  2955. switch (qobject_type(value)) {
  2956. case QTYPE_QNULL:
  2957. new_backing_bs = NULL;
  2958. break;
  2959. case QTYPE_QSTRING:
  2960. str = qobject_get_try_str(value);
  2961. new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
  2962. if (new_backing_bs == NULL) {
  2963. return -EINVAL;
  2964. } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
  2965. error_setg(errp, "Making '%s' a backing file of '%s' "
  2966. "would create a cycle", str, bs->node_name);
  2967. return -EINVAL;
  2968. }
  2969. break;
  2970. default:
  2971. /* 'backing' does not allow any other data type */
  2972. g_assert_not_reached();
  2973. }
  2974. /*
  2975. * TODO: before removing the x- prefix from x-blockdev-reopen we
  2976. * should move the new backing file into the right AioContext
  2977. * instead of returning an error.
  2978. */
  2979. if (new_backing_bs) {
  2980. if (bdrv_get_aio_context(new_backing_bs) != bdrv_get_aio_context(bs)) {
  2981. error_setg(errp, "Cannot use a new backing file "
  2982. "with a different AioContext");
  2983. return -EINVAL;
  2984. }
  2985. }
  2986. /*
  2987. * Find the "actual" backing file by skipping all links that point
  2988. * to an implicit node, if any (e.g. a commit filter node).
  2989. */
  2990. overlay_bs = bs;
  2991. while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
  2992. overlay_bs = backing_bs(overlay_bs);
  2993. }
  2994. /* If we want to replace the backing file we need some extra checks */
  2995. if (new_backing_bs != backing_bs(overlay_bs)) {
  2996. /* Check for implicit nodes between bs and its backing file */
  2997. if (bs != overlay_bs) {
  2998. error_setg(errp, "Cannot change backing link if '%s' has "
  2999. "an implicit backing file", bs->node_name);
  3000. return -EPERM;
  3001. }
  3002. /* Check if the backing link that we want to replace is frozen */
  3003. if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
  3004. errp)) {
  3005. return -EPERM;
  3006. }
  3007. reopen_state->replace_backing_bs = true;
  3008. if (new_backing_bs) {
  3009. bdrv_ref(new_backing_bs);
  3010. reopen_state->new_backing_bs = new_backing_bs;
  3011. }
  3012. }
  3013. return 0;
  3014. }
  3015. /*
  3016. * Prepares a BlockDriverState for reopen. All changes are staged in the
  3017. * 'opaque' field of the BDRVReopenState, which is used and allocated by
  3018. * the block driver layer .bdrv_reopen_prepare()
  3019. *
  3020. * bs is the BlockDriverState to reopen
  3021. * flags are the new open flags
  3022. * queue is the reopen queue
  3023. *
  3024. * Returns 0 on success, non-zero on error. On error errp will be set
  3025. * as well.
  3026. *
  3027. * On failure, bdrv_reopen_abort() will be called to clean up any data.
  3028. * It is the responsibility of the caller to then call the abort() or
  3029. * commit() for any other BDS that have been left in a prepare() state
  3030. *
  3031. */
  3032. int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
  3033. Error **errp)
  3034. {
  3035. int ret = -1;
  3036. int old_flags;
  3037. Error *local_err = NULL;
  3038. BlockDriver *drv;
  3039. QemuOpts *opts;
  3040. QDict *orig_reopen_opts;
  3041. char *discard = NULL;
  3042. bool read_only;
  3043. bool drv_prepared = false;
  3044. assert(reopen_state != NULL);
  3045. assert(reopen_state->bs->drv != NULL);
  3046. drv = reopen_state->bs->drv;
  3047. /* This function and each driver's bdrv_reopen_prepare() remove
  3048. * entries from reopen_state->options as they are processed, so
  3049. * we need to make a copy of the original QDict. */
  3050. orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
  3051. /* Process generic block layer options */
  3052. opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
  3053. qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
  3054. if (local_err) {
  3055. error_propagate(errp, local_err);
  3056. ret = -EINVAL;
  3057. goto error;
  3058. }
  3059. /* This was already called in bdrv_reopen_queue_child() so the flags
  3060. * are up-to-date. This time we simply want to remove the options from
  3061. * QemuOpts in order to indicate that they have been processed. */
  3062. old_flags = reopen_state->flags;
  3063. update_flags_from_options(&reopen_state->flags, opts);
  3064. assert(old_flags == reopen_state->flags);
  3065. discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
  3066. if (discard != NULL) {
  3067. if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
  3068. error_setg(errp, "Invalid discard option");
  3069. ret = -EINVAL;
  3070. goto error;
  3071. }
  3072. }
  3073. reopen_state->detect_zeroes =
  3074. bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
  3075. if (local_err) {
  3076. error_propagate(errp, local_err);
  3077. ret = -EINVAL;
  3078. goto error;
  3079. }
  3080. /* All other options (including node-name and driver) must be unchanged.
  3081. * Put them back into the QDict, so that they are checked at the end
  3082. * of this function. */
  3083. qemu_opts_to_qdict(opts, reopen_state->options);
  3084. /* If we are to stay read-only, do not allow permission change
  3085. * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
  3086. * not set, or if the BDS still has copy_on_read enabled */
  3087. read_only = !(reopen_state->flags & BDRV_O_RDWR);
  3088. ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
  3089. if (local_err) {
  3090. error_propagate(errp, local_err);
  3091. goto error;
  3092. }
  3093. /* Calculate required permissions after reopening */
  3094. bdrv_reopen_perm(queue, reopen_state->bs,
  3095. &reopen_state->perm, &reopen_state->shared_perm);
  3096. ret = bdrv_flush(reopen_state->bs);
  3097. if (ret) {
  3098. error_setg_errno(errp, -ret, "Error flushing drive");
  3099. goto error;
  3100. }
  3101. if (drv->bdrv_reopen_prepare) {
  3102. /*
  3103. * If a driver-specific option is missing, it means that we
  3104. * should reset it to its default value.
  3105. * But not all options allow that, so we need to check it first.
  3106. */
  3107. ret = bdrv_reset_options_allowed(reopen_state->bs,
  3108. reopen_state->options, errp);
  3109. if (ret) {
  3110. goto error;
  3111. }
  3112. ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
  3113. if (ret) {
  3114. if (local_err != NULL) {
  3115. error_propagate(errp, local_err);
  3116. } else {
  3117. bdrv_refresh_filename(reopen_state->bs);
  3118. error_setg(errp, "failed while preparing to reopen image '%s'",
  3119. reopen_state->bs->filename);
  3120. }
  3121. goto error;
  3122. }
  3123. } else {
  3124. /* It is currently mandatory to have a bdrv_reopen_prepare()
  3125. * handler for each supported drv. */
  3126. error_setg(errp, "Block format '%s' used by node '%s' "
  3127. "does not support reopening files", drv->format_name,
  3128. bdrv_get_device_or_node_name(reopen_state->bs));
  3129. ret = -1;
  3130. goto error;
  3131. }
  3132. drv_prepared = true;
  3133. /*
  3134. * We must provide the 'backing' option if the BDS has a backing
  3135. * file or if the image file has a backing file name as part of
  3136. * its metadata. Otherwise the 'backing' option can be omitted.
  3137. */
  3138. if (drv->supports_backing && reopen_state->backing_missing &&
  3139. (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
  3140. error_setg(errp, "backing is missing for '%s'",
  3141. reopen_state->bs->node_name);
  3142. ret = -EINVAL;
  3143. goto error;
  3144. }
  3145. /*
  3146. * Allow changing the 'backing' option. The new value can be
  3147. * either a reference to an existing node (using its node name)
  3148. * or NULL to simply detach the current backing file.
  3149. */
  3150. ret = bdrv_reopen_parse_backing(reopen_state, errp);
  3151. if (ret < 0) {
  3152. goto error;
  3153. }
  3154. qdict_del(reopen_state->options, "backing");
  3155. /* Options that are not handled are only okay if they are unchanged
  3156. * compared to the old state. It is expected that some options are only
  3157. * used for the initial open, but not reopen (e.g. filename) */
  3158. if (qdict_size(reopen_state->options)) {
  3159. const QDictEntry *entry = qdict_first(reopen_state->options);
  3160. do {
  3161. QObject *new = entry->value;
  3162. QObject *old = qdict_get(reopen_state->bs->options, entry->key);
  3163. /* Allow child references (child_name=node_name) as long as they
  3164. * point to the current child (i.e. everything stays the same). */
  3165. if (qobject_type(new) == QTYPE_QSTRING) {
  3166. BdrvChild *child;
  3167. QLIST_FOREACH(child, &reopen_state->bs->children, next) {
  3168. if (!strcmp(child->name, entry->key)) {
  3169. break;
  3170. }
  3171. }
  3172. if (child) {
  3173. const char *str = qobject_get_try_str(new);
  3174. if (!strcmp(child->bs->node_name, str)) {
  3175. continue; /* Found child with this name, skip option */
  3176. }
  3177. }
  3178. }
  3179. /*
  3180. * TODO: When using -drive to specify blockdev options, all values
  3181. * will be strings; however, when using -blockdev, blockdev-add or
  3182. * filenames using the json:{} pseudo-protocol, they will be
  3183. * correctly typed.
  3184. * In contrast, reopening options are (currently) always strings
  3185. * (because you can only specify them through qemu-io; all other
  3186. * callers do not specify any options).
  3187. * Therefore, when using anything other than -drive to create a BDS,
  3188. * this cannot detect non-string options as unchanged, because
  3189. * qobject_is_equal() always returns false for objects of different
  3190. * type. In the future, this should be remedied by correctly typing
  3191. * all options. For now, this is not too big of an issue because
  3192. * the user can simply omit options which cannot be changed anyway,
  3193. * so they will stay unchanged.
  3194. */
  3195. if (!qobject_is_equal(new, old)) {
  3196. error_setg(errp, "Cannot change the option '%s'", entry->key);
  3197. ret = -EINVAL;
  3198. goto error;
  3199. }
  3200. } while ((entry = qdict_next(reopen_state->options, entry)));
  3201. }
  3202. ret = 0;
  3203. /* Restore the original reopen_state->options QDict */
  3204. qobject_unref(reopen_state->options);
  3205. reopen_state->options = qobject_ref(orig_reopen_opts);
  3206. error:
  3207. if (ret < 0 && drv_prepared) {
  3208. /* drv->bdrv_reopen_prepare() has succeeded, so we need to
  3209. * call drv->bdrv_reopen_abort() before signaling an error
  3210. * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
  3211. * when the respective bdrv_reopen_prepare() has failed) */
  3212. if (drv->bdrv_reopen_abort) {
  3213. drv->bdrv_reopen_abort(reopen_state);
  3214. }
  3215. }
  3216. qemu_opts_del(opts);
  3217. qobject_unref(orig_reopen_opts);
  3218. g_free(discard);
  3219. return ret;
  3220. }
  3221. /*
  3222. * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
  3223. * makes them final by swapping the staging BlockDriverState contents into
  3224. * the active BlockDriverState contents.
  3225. */
  3226. void bdrv_reopen_commit(BDRVReopenState *reopen_state)
  3227. {
  3228. BlockDriver *drv;
  3229. BlockDriverState *bs;
  3230. BdrvChild *child;
  3231. bool old_can_write, new_can_write;
  3232. assert(reopen_state != NULL);
  3233. bs = reopen_state->bs;
  3234. drv = bs->drv;
  3235. assert(drv != NULL);
  3236. old_can_write =
  3237. !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
  3238. /* If there are any driver level actions to take */
  3239. if (drv->bdrv_reopen_commit) {
  3240. drv->bdrv_reopen_commit(reopen_state);
  3241. }
  3242. /* set BDS specific flags now */
  3243. qobject_unref(bs->explicit_options);
  3244. qobject_unref(bs->options);
  3245. bs->explicit_options = reopen_state->explicit_options;
  3246. bs->options = reopen_state->options;
  3247. bs->open_flags = reopen_state->flags;
  3248. bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
  3249. bs->detect_zeroes = reopen_state->detect_zeroes;
  3250. if (reopen_state->replace_backing_bs) {
  3251. qdict_del(bs->explicit_options, "backing");
  3252. qdict_del(bs->options, "backing");
  3253. }
  3254. /* Remove child references from bs->options and bs->explicit_options.
  3255. * Child options were already removed in bdrv_reopen_queue_child() */
  3256. QLIST_FOREACH(child, &bs->children, next) {
  3257. qdict_del(bs->explicit_options, child->name);
  3258. qdict_del(bs->options, child->name);
  3259. }
  3260. /*
  3261. * Change the backing file if a new one was specified. We do this
  3262. * after updating bs->options, so bdrv_refresh_filename() (called
  3263. * from bdrv_set_backing_hd()) has the new values.
  3264. */
  3265. if (reopen_state->replace_backing_bs) {
  3266. BlockDriverState *old_backing_bs = backing_bs(bs);
  3267. assert(!old_backing_bs || !old_backing_bs->implicit);
  3268. /* Abort the permission update on the backing bs we're detaching */
  3269. if (old_backing_bs) {
  3270. bdrv_abort_perm_update(old_backing_bs);
  3271. }
  3272. bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
  3273. }
  3274. bdrv_refresh_limits(bs, NULL);
  3275. new_can_write =
  3276. !bdrv_is_read_only(bs) && !(bdrv_get_flags(bs) & BDRV_O_INACTIVE);
  3277. if (!old_can_write && new_can_write && drv->bdrv_reopen_bitmaps_rw) {
  3278. Error *local_err = NULL;
  3279. if (drv->bdrv_reopen_bitmaps_rw(bs, &local_err) < 0) {
  3280. /* This is not fatal, bitmaps just left read-only, so all following
  3281. * writes will fail. User can remove read-only bitmaps to unblock
  3282. * writes.
  3283. */
  3284. error_reportf_err(local_err,
  3285. "%s: Failed to make dirty bitmaps writable: ",
  3286. bdrv_get_node_name(bs));
  3287. }
  3288. }
  3289. }
  3290. /*
  3291. * Abort the reopen, and delete and free the staged changes in
  3292. * reopen_state
  3293. */
  3294. void bdrv_reopen_abort(BDRVReopenState *reopen_state)
  3295. {
  3296. BlockDriver *drv;
  3297. assert(reopen_state != NULL);
  3298. drv = reopen_state->bs->drv;
  3299. assert(drv != NULL);
  3300. if (drv->bdrv_reopen_abort) {
  3301. drv->bdrv_reopen_abort(reopen_state);
  3302. }
  3303. }
  3304. static void bdrv_close(BlockDriverState *bs)
  3305. {
  3306. BdrvAioNotifier *ban, *ban_next;
  3307. BdrvChild *child, *next;
  3308. assert(!bs->job);
  3309. assert(!bs->refcnt);
  3310. bdrv_drained_begin(bs); /* complete I/O */
  3311. bdrv_flush(bs);
  3312. bdrv_drain(bs); /* in case flush left pending I/O */
  3313. if (bs->drv) {
  3314. if (bs->drv->bdrv_close) {
  3315. bs->drv->bdrv_close(bs);
  3316. }
  3317. bs->drv = NULL;
  3318. }
  3319. bdrv_set_backing_hd(bs, NULL, &error_abort);
  3320. if (bs->file != NULL) {
  3321. bdrv_unref_child(bs, bs->file);
  3322. bs->file = NULL;
  3323. }
  3324. QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
  3325. /* TODO Remove bdrv_unref() from drivers' close function and use
  3326. * bdrv_unref_child() here */
  3327. if (child->bs->inherits_from == bs) {
  3328. child->bs->inherits_from = NULL;
  3329. }
  3330. bdrv_detach_child(child);
  3331. }
  3332. g_free(bs->opaque);
  3333. bs->opaque = NULL;
  3334. atomic_set(&bs->copy_on_read, 0);
  3335. bs->backing_file[0] = '\0';
  3336. bs->backing_format[0] = '\0';
  3337. bs->total_sectors = 0;
  3338. bs->encrypted = false;
  3339. bs->sg = false;
  3340. qobject_unref(bs->options);
  3341. qobject_unref(bs->explicit_options);
  3342. bs->options = NULL;
  3343. bs->explicit_options = NULL;
  3344. qobject_unref(bs->full_open_options);
  3345. bs->full_open_options = NULL;
  3346. bdrv_release_named_dirty_bitmaps(bs);
  3347. assert(QLIST_EMPTY(&bs->dirty_bitmaps));
  3348. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  3349. g_free(ban);
  3350. }
  3351. QLIST_INIT(&bs->aio_notifiers);
  3352. bdrv_drained_end(bs);
  3353. }
  3354. void bdrv_close_all(void)
  3355. {
  3356. assert(job_next(NULL) == NULL);
  3357. nbd_export_close_all();
  3358. /* Drop references from requests still in flight, such as canceled block
  3359. * jobs whose AIO context has not been polled yet */
  3360. bdrv_drain_all();
  3361. blk_remove_all_bs();
  3362. blockdev_close_all_bdrv_states();
  3363. assert(QTAILQ_EMPTY(&all_bdrv_states));
  3364. }
  3365. static bool should_update_child(BdrvChild *c, BlockDriverState *to)
  3366. {
  3367. GQueue *queue;
  3368. GHashTable *found;
  3369. bool ret;
  3370. if (c->role->stay_at_node) {
  3371. return false;
  3372. }
  3373. /* If the child @c belongs to the BDS @to, replacing the current
  3374. * c->bs by @to would mean to create a loop.
  3375. *
  3376. * Such a case occurs when appending a BDS to a backing chain.
  3377. * For instance, imagine the following chain:
  3378. *
  3379. * guest device -> node A -> further backing chain...
  3380. *
  3381. * Now we create a new BDS B which we want to put on top of this
  3382. * chain, so we first attach A as its backing node:
  3383. *
  3384. * node B
  3385. * |
  3386. * v
  3387. * guest device -> node A -> further backing chain...
  3388. *
  3389. * Finally we want to replace A by B. When doing that, we want to
  3390. * replace all pointers to A by pointers to B -- except for the
  3391. * pointer from B because (1) that would create a loop, and (2)
  3392. * that pointer should simply stay intact:
  3393. *
  3394. * guest device -> node B
  3395. * |
  3396. * v
  3397. * node A -> further backing chain...
  3398. *
  3399. * In general, when replacing a node A (c->bs) by a node B (@to),
  3400. * if A is a child of B, that means we cannot replace A by B there
  3401. * because that would create a loop. Silently detaching A from B
  3402. * is also not really an option. So overall just leaving A in
  3403. * place there is the most sensible choice.
  3404. *
  3405. * We would also create a loop in any cases where @c is only
  3406. * indirectly referenced by @to. Prevent this by returning false
  3407. * if @c is found (by breadth-first search) anywhere in the whole
  3408. * subtree of @to.
  3409. */
  3410. ret = true;
  3411. found = g_hash_table_new(NULL, NULL);
  3412. g_hash_table_add(found, to);
  3413. queue = g_queue_new();
  3414. g_queue_push_tail(queue, to);
  3415. while (!g_queue_is_empty(queue)) {
  3416. BlockDriverState *v = g_queue_pop_head(queue);
  3417. BdrvChild *c2;
  3418. QLIST_FOREACH(c2, &v->children, next) {
  3419. if (c2 == c) {
  3420. ret = false;
  3421. break;
  3422. }
  3423. if (g_hash_table_contains(found, c2->bs)) {
  3424. continue;
  3425. }
  3426. g_queue_push_tail(queue, c2->bs);
  3427. g_hash_table_add(found, c2->bs);
  3428. }
  3429. }
  3430. g_queue_free(queue);
  3431. g_hash_table_destroy(found);
  3432. return ret;
  3433. }
  3434. void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
  3435. Error **errp)
  3436. {
  3437. BdrvChild *c, *next;
  3438. GSList *list = NULL, *p;
  3439. uint64_t old_perm, old_shared;
  3440. uint64_t perm = 0, shared = BLK_PERM_ALL;
  3441. int ret;
  3442. assert(!atomic_read(&from->in_flight));
  3443. assert(!atomic_read(&to->in_flight));
  3444. /* Make sure that @from doesn't go away until we have successfully attached
  3445. * all of its parents to @to. */
  3446. bdrv_ref(from);
  3447. /* Put all parents into @list and calculate their cumulative permissions */
  3448. QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
  3449. assert(c->bs == from);
  3450. if (!should_update_child(c, to)) {
  3451. continue;
  3452. }
  3453. if (c->frozen) {
  3454. error_setg(errp, "Cannot change '%s' link to '%s'",
  3455. c->name, from->node_name);
  3456. goto out;
  3457. }
  3458. list = g_slist_prepend(list, c);
  3459. perm |= c->perm;
  3460. shared &= c->shared_perm;
  3461. }
  3462. /* Check whether the required permissions can be granted on @to, ignoring
  3463. * all BdrvChild in @list so that they can't block themselves. */
  3464. ret = bdrv_check_update_perm(to, NULL, perm, shared, list, errp);
  3465. if (ret < 0) {
  3466. bdrv_abort_perm_update(to);
  3467. goto out;
  3468. }
  3469. /* Now actually perform the change. We performed the permission check for
  3470. * all elements of @list at once, so set the permissions all at once at the
  3471. * very end. */
  3472. for (p = list; p != NULL; p = p->next) {
  3473. c = p->data;
  3474. bdrv_ref(to);
  3475. bdrv_replace_child_noperm(c, to);
  3476. bdrv_unref(from);
  3477. }
  3478. bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
  3479. bdrv_set_perm(to, old_perm | perm, old_shared | shared);
  3480. out:
  3481. g_slist_free(list);
  3482. bdrv_unref(from);
  3483. }
  3484. /*
  3485. * Add new bs contents at the top of an image chain while the chain is
  3486. * live, while keeping required fields on the top layer.
  3487. *
  3488. * This will modify the BlockDriverState fields, and swap contents
  3489. * between bs_new and bs_top. Both bs_new and bs_top are modified.
  3490. *
  3491. * bs_new must not be attached to a BlockBackend.
  3492. *
  3493. * This function does not create any image files.
  3494. *
  3495. * bdrv_append() takes ownership of a bs_new reference and unrefs it because
  3496. * that's what the callers commonly need. bs_new will be referenced by the old
  3497. * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
  3498. * reference of its own, it must call bdrv_ref().
  3499. */
  3500. void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
  3501. Error **errp)
  3502. {
  3503. Error *local_err = NULL;
  3504. bdrv_set_backing_hd(bs_new, bs_top, &local_err);
  3505. if (local_err) {
  3506. error_propagate(errp, local_err);
  3507. goto out;
  3508. }
  3509. bdrv_replace_node(bs_top, bs_new, &local_err);
  3510. if (local_err) {
  3511. error_propagate(errp, local_err);
  3512. bdrv_set_backing_hd(bs_new, NULL, &error_abort);
  3513. goto out;
  3514. }
  3515. /* bs_new is now referenced by its new parents, we don't need the
  3516. * additional reference any more. */
  3517. out:
  3518. bdrv_unref(bs_new);
  3519. }
  3520. static void bdrv_delete(BlockDriverState *bs)
  3521. {
  3522. assert(!bs->job);
  3523. assert(bdrv_op_blocker_is_empty(bs));
  3524. assert(!bs->refcnt);
  3525. /* remove from list, if necessary */
  3526. if (bs->node_name[0] != '\0') {
  3527. QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
  3528. }
  3529. QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
  3530. bdrv_close(bs);
  3531. g_free(bs);
  3532. }
  3533. /*
  3534. * Run consistency checks on an image
  3535. *
  3536. * Returns 0 if the check could be completed (it doesn't mean that the image is
  3537. * free of errors) or -errno when an internal error occurred. The results of the
  3538. * check are stored in res.
  3539. */
  3540. static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
  3541. BdrvCheckResult *res, BdrvCheckMode fix)
  3542. {
  3543. if (bs->drv == NULL) {
  3544. return -ENOMEDIUM;
  3545. }
  3546. if (bs->drv->bdrv_co_check == NULL) {
  3547. return -ENOTSUP;
  3548. }
  3549. memset(res, 0, sizeof(*res));
  3550. return bs->drv->bdrv_co_check(bs, res, fix);
  3551. }
  3552. typedef struct CheckCo {
  3553. BlockDriverState *bs;
  3554. BdrvCheckResult *res;
  3555. BdrvCheckMode fix;
  3556. int ret;
  3557. } CheckCo;
  3558. static void coroutine_fn bdrv_check_co_entry(void *opaque)
  3559. {
  3560. CheckCo *cco = opaque;
  3561. cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
  3562. aio_wait_kick();
  3563. }
  3564. int bdrv_check(BlockDriverState *bs,
  3565. BdrvCheckResult *res, BdrvCheckMode fix)
  3566. {
  3567. Coroutine *co;
  3568. CheckCo cco = {
  3569. .bs = bs,
  3570. .res = res,
  3571. .ret = -EINPROGRESS,
  3572. .fix = fix,
  3573. };
  3574. if (qemu_in_coroutine()) {
  3575. /* Fast-path if already in coroutine context */
  3576. bdrv_check_co_entry(&cco);
  3577. } else {
  3578. co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
  3579. bdrv_coroutine_enter(bs, co);
  3580. BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
  3581. }
  3582. return cco.ret;
  3583. }
  3584. /*
  3585. * Return values:
  3586. * 0 - success
  3587. * -EINVAL - backing format specified, but no file
  3588. * -ENOSPC - can't update the backing file because no space is left in the
  3589. * image file header
  3590. * -ENOTSUP - format driver doesn't support changing the backing file
  3591. */
  3592. int bdrv_change_backing_file(BlockDriverState *bs,
  3593. const char *backing_file, const char *backing_fmt)
  3594. {
  3595. BlockDriver *drv = bs->drv;
  3596. int ret;
  3597. if (!drv) {
  3598. return -ENOMEDIUM;
  3599. }
  3600. /* Backing file format doesn't make sense without a backing file */
  3601. if (backing_fmt && !backing_file) {
  3602. return -EINVAL;
  3603. }
  3604. if (drv->bdrv_change_backing_file != NULL) {
  3605. ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
  3606. } else {
  3607. ret = -ENOTSUP;
  3608. }
  3609. if (ret == 0) {
  3610. pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
  3611. pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
  3612. pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
  3613. backing_file ?: "");
  3614. }
  3615. return ret;
  3616. }
  3617. /*
  3618. * Finds the image layer in the chain that has 'bs' as its backing file.
  3619. *
  3620. * active is the current topmost image.
  3621. *
  3622. * Returns NULL if bs is not found in active's image chain,
  3623. * or if active == bs.
  3624. *
  3625. * Returns the bottommost base image if bs == NULL.
  3626. */
  3627. BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
  3628. BlockDriverState *bs)
  3629. {
  3630. while (active && bs != backing_bs(active)) {
  3631. active = backing_bs(active);
  3632. }
  3633. return active;
  3634. }
  3635. /* Given a BDS, searches for the base layer. */
  3636. BlockDriverState *bdrv_find_base(BlockDriverState *bs)
  3637. {
  3638. return bdrv_find_overlay(bs, NULL);
  3639. }
  3640. /*
  3641. * Return true if at least one of the backing links between @bs and
  3642. * @base is frozen. @errp is set if that's the case.
  3643. * @base must be reachable from @bs, or NULL.
  3644. */
  3645. bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
  3646. Error **errp)
  3647. {
  3648. BlockDriverState *i;
  3649. for (i = bs; i != base; i = backing_bs(i)) {
  3650. if (i->backing && i->backing->frozen) {
  3651. error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
  3652. i->backing->name, i->node_name,
  3653. backing_bs(i)->node_name);
  3654. return true;
  3655. }
  3656. }
  3657. return false;
  3658. }
  3659. /*
  3660. * Freeze all backing links between @bs and @base.
  3661. * If any of the links is already frozen the operation is aborted and
  3662. * none of the links are modified.
  3663. * @base must be reachable from @bs, or NULL.
  3664. * Returns 0 on success. On failure returns < 0 and sets @errp.
  3665. */
  3666. int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
  3667. Error **errp)
  3668. {
  3669. BlockDriverState *i;
  3670. if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
  3671. return -EPERM;
  3672. }
  3673. for (i = bs; i != base; i = backing_bs(i)) {
  3674. if (i->backing) {
  3675. i->backing->frozen = true;
  3676. }
  3677. }
  3678. return 0;
  3679. }
  3680. /*
  3681. * Unfreeze all backing links between @bs and @base. The caller must
  3682. * ensure that all links are frozen before using this function.
  3683. * @base must be reachable from @bs, or NULL.
  3684. */
  3685. void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
  3686. {
  3687. BlockDriverState *i;
  3688. for (i = bs; i != base; i = backing_bs(i)) {
  3689. if (i->backing) {
  3690. assert(i->backing->frozen);
  3691. i->backing->frozen = false;
  3692. }
  3693. }
  3694. }
  3695. /*
  3696. * Drops images above 'base' up to and including 'top', and sets the image
  3697. * above 'top' to have base as its backing file.
  3698. *
  3699. * Requires that the overlay to 'top' is opened r/w, so that the backing file
  3700. * information in 'bs' can be properly updated.
  3701. *
  3702. * E.g., this will convert the following chain:
  3703. * bottom <- base <- intermediate <- top <- active
  3704. *
  3705. * to
  3706. *
  3707. * bottom <- base <- active
  3708. *
  3709. * It is allowed for bottom==base, in which case it converts:
  3710. *
  3711. * base <- intermediate <- top <- active
  3712. *
  3713. * to
  3714. *
  3715. * base <- active
  3716. *
  3717. * If backing_file_str is non-NULL, it will be used when modifying top's
  3718. * overlay image metadata.
  3719. *
  3720. * Error conditions:
  3721. * if active == top, that is considered an error
  3722. *
  3723. */
  3724. int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
  3725. const char *backing_file_str)
  3726. {
  3727. BlockDriverState *explicit_top = top;
  3728. bool update_inherits_from;
  3729. BdrvChild *c, *next;
  3730. Error *local_err = NULL;
  3731. int ret = -EIO;
  3732. bdrv_ref(top);
  3733. if (!top->drv || !base->drv) {
  3734. goto exit;
  3735. }
  3736. /* Make sure that base is in the backing chain of top */
  3737. if (!bdrv_chain_contains(top, base)) {
  3738. goto exit;
  3739. }
  3740. /* This function changes all links that point to top and makes
  3741. * them point to base. Check that none of them is frozen. */
  3742. QLIST_FOREACH(c, &top->parents, next_parent) {
  3743. if (c->frozen) {
  3744. goto exit;
  3745. }
  3746. }
  3747. /* If 'base' recursively inherits from 'top' then we should set
  3748. * base->inherits_from to top->inherits_from after 'top' and all
  3749. * other intermediate nodes have been dropped.
  3750. * If 'top' is an implicit node (e.g. "commit_top") we should skip
  3751. * it because no one inherits from it. We use explicit_top for that. */
  3752. while (explicit_top && explicit_top->implicit) {
  3753. explicit_top = backing_bs(explicit_top);
  3754. }
  3755. update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
  3756. /* success - we can delete the intermediate states, and link top->base */
  3757. /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
  3758. * we've figured out how they should work. */
  3759. if (!backing_file_str) {
  3760. bdrv_refresh_filename(base);
  3761. backing_file_str = base->filename;
  3762. }
  3763. QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
  3764. /* Check whether we are allowed to switch c from top to base */
  3765. GSList *ignore_children = g_slist_prepend(NULL, c);
  3766. ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
  3767. ignore_children, &local_err);
  3768. g_slist_free(ignore_children);
  3769. if (ret < 0) {
  3770. error_report_err(local_err);
  3771. goto exit;
  3772. }
  3773. /* If so, update the backing file path in the image file */
  3774. if (c->role->update_filename) {
  3775. ret = c->role->update_filename(c, base, backing_file_str,
  3776. &local_err);
  3777. if (ret < 0) {
  3778. bdrv_abort_perm_update(base);
  3779. error_report_err(local_err);
  3780. goto exit;
  3781. }
  3782. }
  3783. /* Do the actual switch in the in-memory graph.
  3784. * Completes bdrv_check_update_perm() transaction internally. */
  3785. bdrv_ref(base);
  3786. bdrv_replace_child(c, base);
  3787. bdrv_unref(top);
  3788. }
  3789. if (update_inherits_from) {
  3790. base->inherits_from = explicit_top->inherits_from;
  3791. }
  3792. ret = 0;
  3793. exit:
  3794. bdrv_unref(top);
  3795. return ret;
  3796. }
  3797. /**
  3798. * Length of a allocated file in bytes. Sparse files are counted by actual
  3799. * allocated space. Return < 0 if error or unknown.
  3800. */
  3801. int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
  3802. {
  3803. BlockDriver *drv = bs->drv;
  3804. if (!drv) {
  3805. return -ENOMEDIUM;
  3806. }
  3807. if (drv->bdrv_get_allocated_file_size) {
  3808. return drv->bdrv_get_allocated_file_size(bs);
  3809. }
  3810. if (bs->file) {
  3811. return bdrv_get_allocated_file_size(bs->file->bs);
  3812. }
  3813. return -ENOTSUP;
  3814. }
  3815. /*
  3816. * bdrv_measure:
  3817. * @drv: Format driver
  3818. * @opts: Creation options for new image
  3819. * @in_bs: Existing image containing data for new image (may be NULL)
  3820. * @errp: Error object
  3821. * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
  3822. * or NULL on error
  3823. *
  3824. * Calculate file size required to create a new image.
  3825. *
  3826. * If @in_bs is given then space for allocated clusters and zero clusters
  3827. * from that image are included in the calculation. If @opts contains a
  3828. * backing file that is shared by @in_bs then backing clusters may be omitted
  3829. * from the calculation.
  3830. *
  3831. * If @in_bs is NULL then the calculation includes no allocated clusters
  3832. * unless a preallocation option is given in @opts.
  3833. *
  3834. * Note that @in_bs may use a different BlockDriver from @drv.
  3835. *
  3836. * If an error occurs the @errp pointer is set.
  3837. */
  3838. BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
  3839. BlockDriverState *in_bs, Error **errp)
  3840. {
  3841. if (!drv->bdrv_measure) {
  3842. error_setg(errp, "Block driver '%s' does not support size measurement",
  3843. drv->format_name);
  3844. return NULL;
  3845. }
  3846. return drv->bdrv_measure(opts, in_bs, errp);
  3847. }
  3848. /**
  3849. * Return number of sectors on success, -errno on error.
  3850. */
  3851. int64_t bdrv_nb_sectors(BlockDriverState *bs)
  3852. {
  3853. BlockDriver *drv = bs->drv;
  3854. if (!drv)
  3855. return -ENOMEDIUM;
  3856. if (drv->has_variable_length) {
  3857. int ret = refresh_total_sectors(bs, bs->total_sectors);
  3858. if (ret < 0) {
  3859. return ret;
  3860. }
  3861. }
  3862. return bs->total_sectors;
  3863. }
  3864. /**
  3865. * Return length in bytes on success, -errno on error.
  3866. * The length is always a multiple of BDRV_SECTOR_SIZE.
  3867. */
  3868. int64_t bdrv_getlength(BlockDriverState *bs)
  3869. {
  3870. int64_t ret = bdrv_nb_sectors(bs);
  3871. ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
  3872. return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
  3873. }
  3874. /* return 0 as number of sectors if no device present or error */
  3875. void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
  3876. {
  3877. int64_t nb_sectors = bdrv_nb_sectors(bs);
  3878. *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
  3879. }
  3880. bool bdrv_is_sg(BlockDriverState *bs)
  3881. {
  3882. return bs->sg;
  3883. }
  3884. bool bdrv_is_encrypted(BlockDriverState *bs)
  3885. {
  3886. if (bs->backing && bs->backing->bs->encrypted) {
  3887. return true;
  3888. }
  3889. return bs->encrypted;
  3890. }
  3891. const char *bdrv_get_format_name(BlockDriverState *bs)
  3892. {
  3893. return bs->drv ? bs->drv->format_name : NULL;
  3894. }
  3895. static int qsort_strcmp(const void *a, const void *b)
  3896. {
  3897. return strcmp(*(char *const *)a, *(char *const *)b);
  3898. }
  3899. void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
  3900. void *opaque, bool read_only)
  3901. {
  3902. BlockDriver *drv;
  3903. int count = 0;
  3904. int i;
  3905. const char **formats = NULL;
  3906. QLIST_FOREACH(drv, &bdrv_drivers, list) {
  3907. if (drv->format_name) {
  3908. bool found = false;
  3909. int i = count;
  3910. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
  3911. continue;
  3912. }
  3913. while (formats && i && !found) {
  3914. found = !strcmp(formats[--i], drv->format_name);
  3915. }
  3916. if (!found) {
  3917. formats = g_renew(const char *, formats, count + 1);
  3918. formats[count++] = drv->format_name;
  3919. }
  3920. }
  3921. }
  3922. for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
  3923. const char *format_name = block_driver_modules[i].format_name;
  3924. if (format_name) {
  3925. bool found = false;
  3926. int j = count;
  3927. if (use_bdrv_whitelist &&
  3928. !bdrv_format_is_whitelisted(format_name, read_only)) {
  3929. continue;
  3930. }
  3931. while (formats && j && !found) {
  3932. found = !strcmp(formats[--j], format_name);
  3933. }
  3934. if (!found) {
  3935. formats = g_renew(const char *, formats, count + 1);
  3936. formats[count++] = format_name;
  3937. }
  3938. }
  3939. }
  3940. qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
  3941. for (i = 0; i < count; i++) {
  3942. it(opaque, formats[i]);
  3943. }
  3944. g_free(formats);
  3945. }
  3946. /* This function is to find a node in the bs graph */
  3947. BlockDriverState *bdrv_find_node(const char *node_name)
  3948. {
  3949. BlockDriverState *bs;
  3950. assert(node_name);
  3951. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  3952. if (!strcmp(node_name, bs->node_name)) {
  3953. return bs;
  3954. }
  3955. }
  3956. return NULL;
  3957. }
  3958. /* Put this QMP function here so it can access the static graph_bdrv_states. */
  3959. BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
  3960. {
  3961. BlockDeviceInfoList *list, *entry;
  3962. BlockDriverState *bs;
  3963. list = NULL;
  3964. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  3965. BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
  3966. if (!info) {
  3967. qapi_free_BlockDeviceInfoList(list);
  3968. return NULL;
  3969. }
  3970. entry = g_malloc0(sizeof(*entry));
  3971. entry->value = info;
  3972. entry->next = list;
  3973. list = entry;
  3974. }
  3975. return list;
  3976. }
  3977. #define QAPI_LIST_ADD(list, element) do { \
  3978. typeof(list) _tmp = g_new(typeof(*(list)), 1); \
  3979. _tmp->value = (element); \
  3980. _tmp->next = (list); \
  3981. (list) = _tmp; \
  3982. } while (0)
  3983. typedef struct XDbgBlockGraphConstructor {
  3984. XDbgBlockGraph *graph;
  3985. GHashTable *graph_nodes;
  3986. } XDbgBlockGraphConstructor;
  3987. static XDbgBlockGraphConstructor *xdbg_graph_new(void)
  3988. {
  3989. XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
  3990. gr->graph = g_new0(XDbgBlockGraph, 1);
  3991. gr->graph_nodes = g_hash_table_new(NULL, NULL);
  3992. return gr;
  3993. }
  3994. static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
  3995. {
  3996. XDbgBlockGraph *graph = gr->graph;
  3997. g_hash_table_destroy(gr->graph_nodes);
  3998. g_free(gr);
  3999. return graph;
  4000. }
  4001. static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
  4002. {
  4003. uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
  4004. if (ret != 0) {
  4005. return ret;
  4006. }
  4007. /*
  4008. * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
  4009. * answer of g_hash_table_lookup.
  4010. */
  4011. ret = g_hash_table_size(gr->graph_nodes) + 1;
  4012. g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
  4013. return ret;
  4014. }
  4015. static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
  4016. XDbgBlockGraphNodeType type, const char *name)
  4017. {
  4018. XDbgBlockGraphNode *n;
  4019. n = g_new0(XDbgBlockGraphNode, 1);
  4020. n->id = xdbg_graph_node_num(gr, node);
  4021. n->type = type;
  4022. n->name = g_strdup(name);
  4023. QAPI_LIST_ADD(gr->graph->nodes, n);
  4024. }
  4025. static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
  4026. const BdrvChild *child)
  4027. {
  4028. typedef struct {
  4029. unsigned int flag;
  4030. BlockPermission num;
  4031. } PermissionMap;
  4032. static const PermissionMap permissions[] = {
  4033. { BLK_PERM_CONSISTENT_READ, BLOCK_PERMISSION_CONSISTENT_READ },
  4034. { BLK_PERM_WRITE, BLOCK_PERMISSION_WRITE },
  4035. { BLK_PERM_WRITE_UNCHANGED, BLOCK_PERMISSION_WRITE_UNCHANGED },
  4036. { BLK_PERM_RESIZE, BLOCK_PERMISSION_RESIZE },
  4037. { BLK_PERM_GRAPH_MOD, BLOCK_PERMISSION_GRAPH_MOD },
  4038. { 0, 0 }
  4039. };
  4040. const PermissionMap *p;
  4041. XDbgBlockGraphEdge *edge;
  4042. QEMU_BUILD_BUG_ON(1UL << (ARRAY_SIZE(permissions) - 1) != BLK_PERM_ALL + 1);
  4043. edge = g_new0(XDbgBlockGraphEdge, 1);
  4044. edge->parent = xdbg_graph_node_num(gr, parent);
  4045. edge->child = xdbg_graph_node_num(gr, child->bs);
  4046. edge->name = g_strdup(child->name);
  4047. for (p = permissions; p->flag; p++) {
  4048. if (p->flag & child->perm) {
  4049. QAPI_LIST_ADD(edge->perm, p->num);
  4050. }
  4051. if (p->flag & child->shared_perm) {
  4052. QAPI_LIST_ADD(edge->shared_perm, p->num);
  4053. }
  4054. }
  4055. QAPI_LIST_ADD(gr->graph->edges, edge);
  4056. }
  4057. XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
  4058. {
  4059. BlockBackend *blk;
  4060. BlockJob *job;
  4061. BlockDriverState *bs;
  4062. BdrvChild *child;
  4063. XDbgBlockGraphConstructor *gr = xdbg_graph_new();
  4064. for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
  4065. char *allocated_name = NULL;
  4066. const char *name = blk_name(blk);
  4067. if (!*name) {
  4068. name = allocated_name = blk_get_attached_dev_id(blk);
  4069. }
  4070. xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
  4071. name);
  4072. g_free(allocated_name);
  4073. if (blk_root(blk)) {
  4074. xdbg_graph_add_edge(gr, blk, blk_root(blk));
  4075. }
  4076. }
  4077. for (job = block_job_next(NULL); job; job = block_job_next(job)) {
  4078. GSList *el;
  4079. xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
  4080. job->job.id);
  4081. for (el = job->nodes; el; el = el->next) {
  4082. xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
  4083. }
  4084. }
  4085. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  4086. xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
  4087. bs->node_name);
  4088. QLIST_FOREACH(child, &bs->children, next) {
  4089. xdbg_graph_add_edge(gr, bs, child);
  4090. }
  4091. }
  4092. return xdbg_graph_finalize(gr);
  4093. }
  4094. BlockDriverState *bdrv_lookup_bs(const char *device,
  4095. const char *node_name,
  4096. Error **errp)
  4097. {
  4098. BlockBackend *blk;
  4099. BlockDriverState *bs;
  4100. if (device) {
  4101. blk = blk_by_name(device);
  4102. if (blk) {
  4103. bs = blk_bs(blk);
  4104. if (!bs) {
  4105. error_setg(errp, "Device '%s' has no medium", device);
  4106. }
  4107. return bs;
  4108. }
  4109. }
  4110. if (node_name) {
  4111. bs = bdrv_find_node(node_name);
  4112. if (bs) {
  4113. return bs;
  4114. }
  4115. }
  4116. error_setg(errp, "Cannot find device=%s nor node_name=%s",
  4117. device ? device : "",
  4118. node_name ? node_name : "");
  4119. return NULL;
  4120. }
  4121. /* If 'base' is in the same chain as 'top', return true. Otherwise,
  4122. * return false. If either argument is NULL, return false. */
  4123. bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
  4124. {
  4125. while (top && top != base) {
  4126. top = backing_bs(top);
  4127. }
  4128. return top != NULL;
  4129. }
  4130. BlockDriverState *bdrv_next_node(BlockDriverState *bs)
  4131. {
  4132. if (!bs) {
  4133. return QTAILQ_FIRST(&graph_bdrv_states);
  4134. }
  4135. return QTAILQ_NEXT(bs, node_list);
  4136. }
  4137. BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
  4138. {
  4139. if (!bs) {
  4140. return QTAILQ_FIRST(&all_bdrv_states);
  4141. }
  4142. return QTAILQ_NEXT(bs, bs_list);
  4143. }
  4144. const char *bdrv_get_node_name(const BlockDriverState *bs)
  4145. {
  4146. return bs->node_name;
  4147. }
  4148. const char *bdrv_get_parent_name(const BlockDriverState *bs)
  4149. {
  4150. BdrvChild *c;
  4151. const char *name;
  4152. /* If multiple parents have a name, just pick the first one. */
  4153. QLIST_FOREACH(c, &bs->parents, next_parent) {
  4154. if (c->role->get_name) {
  4155. name = c->role->get_name(c);
  4156. if (name && *name) {
  4157. return name;
  4158. }
  4159. }
  4160. }
  4161. return NULL;
  4162. }
  4163. /* TODO check what callers really want: bs->node_name or blk_name() */
  4164. const char *bdrv_get_device_name(const BlockDriverState *bs)
  4165. {
  4166. return bdrv_get_parent_name(bs) ?: "";
  4167. }
  4168. /* This can be used to identify nodes that might not have a device
  4169. * name associated. Since node and device names live in the same
  4170. * namespace, the result is unambiguous. The exception is if both are
  4171. * absent, then this returns an empty (non-null) string. */
  4172. const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
  4173. {
  4174. return bdrv_get_parent_name(bs) ?: bs->node_name;
  4175. }
  4176. int bdrv_get_flags(BlockDriverState *bs)
  4177. {
  4178. return bs->open_flags;
  4179. }
  4180. int bdrv_has_zero_init_1(BlockDriverState *bs)
  4181. {
  4182. return 1;
  4183. }
  4184. int bdrv_has_zero_init(BlockDriverState *bs)
  4185. {
  4186. if (!bs->drv) {
  4187. return 0;
  4188. }
  4189. /* If BS is a copy on write image, it is initialized to
  4190. the contents of the base image, which may not be zeroes. */
  4191. if (bs->backing) {
  4192. return 0;
  4193. }
  4194. if (bs->drv->bdrv_has_zero_init) {
  4195. return bs->drv->bdrv_has_zero_init(bs);
  4196. }
  4197. if (bs->file && bs->drv->is_filter) {
  4198. return bdrv_has_zero_init(bs->file->bs);
  4199. }
  4200. /* safe default */
  4201. return 0;
  4202. }
  4203. bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
  4204. {
  4205. BlockDriverInfo bdi;
  4206. if (bs->backing) {
  4207. return false;
  4208. }
  4209. if (bdrv_get_info(bs, &bdi) == 0) {
  4210. return bdi.unallocated_blocks_are_zero;
  4211. }
  4212. return false;
  4213. }
  4214. bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
  4215. {
  4216. if (!(bs->open_flags & BDRV_O_UNMAP)) {
  4217. return false;
  4218. }
  4219. return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
  4220. }
  4221. void bdrv_get_backing_filename(BlockDriverState *bs,
  4222. char *filename, int filename_size)
  4223. {
  4224. pstrcpy(filename, filename_size, bs->backing_file);
  4225. }
  4226. int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
  4227. {
  4228. BlockDriver *drv = bs->drv;
  4229. /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
  4230. if (!drv) {
  4231. return -ENOMEDIUM;
  4232. }
  4233. if (!drv->bdrv_get_info) {
  4234. if (bs->file && drv->is_filter) {
  4235. return bdrv_get_info(bs->file->bs, bdi);
  4236. }
  4237. return -ENOTSUP;
  4238. }
  4239. memset(bdi, 0, sizeof(*bdi));
  4240. return drv->bdrv_get_info(bs, bdi);
  4241. }
  4242. ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
  4243. Error **errp)
  4244. {
  4245. BlockDriver *drv = bs->drv;
  4246. if (drv && drv->bdrv_get_specific_info) {
  4247. return drv->bdrv_get_specific_info(bs, errp);
  4248. }
  4249. return NULL;
  4250. }
  4251. void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
  4252. {
  4253. if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
  4254. return;
  4255. }
  4256. bs->drv->bdrv_debug_event(bs, event);
  4257. }
  4258. int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
  4259. const char *tag)
  4260. {
  4261. while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
  4262. bs = bs->file ? bs->file->bs : NULL;
  4263. }
  4264. if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
  4265. return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
  4266. }
  4267. return -ENOTSUP;
  4268. }
  4269. int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
  4270. {
  4271. while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
  4272. bs = bs->file ? bs->file->bs : NULL;
  4273. }
  4274. if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
  4275. return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
  4276. }
  4277. return -ENOTSUP;
  4278. }
  4279. int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
  4280. {
  4281. while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
  4282. bs = bs->file ? bs->file->bs : NULL;
  4283. }
  4284. if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
  4285. return bs->drv->bdrv_debug_resume(bs, tag);
  4286. }
  4287. return -ENOTSUP;
  4288. }
  4289. bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
  4290. {
  4291. while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
  4292. bs = bs->file ? bs->file->bs : NULL;
  4293. }
  4294. if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
  4295. return bs->drv->bdrv_debug_is_suspended(bs, tag);
  4296. }
  4297. return false;
  4298. }
  4299. /* backing_file can either be relative, or absolute, or a protocol. If it is
  4300. * relative, it must be relative to the chain. So, passing in bs->filename
  4301. * from a BDS as backing_file should not be done, as that may be relative to
  4302. * the CWD rather than the chain. */
  4303. BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
  4304. const char *backing_file)
  4305. {
  4306. char *filename_full = NULL;
  4307. char *backing_file_full = NULL;
  4308. char *filename_tmp = NULL;
  4309. int is_protocol = 0;
  4310. BlockDriverState *curr_bs = NULL;
  4311. BlockDriverState *retval = NULL;
  4312. if (!bs || !bs->drv || !backing_file) {
  4313. return NULL;
  4314. }
  4315. filename_full = g_malloc(PATH_MAX);
  4316. backing_file_full = g_malloc(PATH_MAX);
  4317. is_protocol = path_has_protocol(backing_file);
  4318. for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
  4319. /* If either of the filename paths is actually a protocol, then
  4320. * compare unmodified paths; otherwise make paths relative */
  4321. if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
  4322. char *backing_file_full_ret;
  4323. if (strcmp(backing_file, curr_bs->backing_file) == 0) {
  4324. retval = curr_bs->backing->bs;
  4325. break;
  4326. }
  4327. /* Also check against the full backing filename for the image */
  4328. backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
  4329. NULL);
  4330. if (backing_file_full_ret) {
  4331. bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
  4332. g_free(backing_file_full_ret);
  4333. if (equal) {
  4334. retval = curr_bs->backing->bs;
  4335. break;
  4336. }
  4337. }
  4338. } else {
  4339. /* If not an absolute filename path, make it relative to the current
  4340. * image's filename path */
  4341. filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
  4342. NULL);
  4343. /* We are going to compare canonicalized absolute pathnames */
  4344. if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
  4345. g_free(filename_tmp);
  4346. continue;
  4347. }
  4348. g_free(filename_tmp);
  4349. /* We need to make sure the backing filename we are comparing against
  4350. * is relative to the current image filename (or absolute) */
  4351. filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
  4352. if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
  4353. g_free(filename_tmp);
  4354. continue;
  4355. }
  4356. g_free(filename_tmp);
  4357. if (strcmp(backing_file_full, filename_full) == 0) {
  4358. retval = curr_bs->backing->bs;
  4359. break;
  4360. }
  4361. }
  4362. }
  4363. g_free(filename_full);
  4364. g_free(backing_file_full);
  4365. return retval;
  4366. }
  4367. void bdrv_init(void)
  4368. {
  4369. module_call_init(MODULE_INIT_BLOCK);
  4370. }
  4371. void bdrv_init_with_whitelist(void)
  4372. {
  4373. use_bdrv_whitelist = 1;
  4374. bdrv_init();
  4375. }
  4376. static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
  4377. Error **errp)
  4378. {
  4379. BdrvChild *child, *parent;
  4380. uint64_t perm, shared_perm;
  4381. Error *local_err = NULL;
  4382. int ret;
  4383. BdrvDirtyBitmap *bm;
  4384. if (!bs->drv) {
  4385. return;
  4386. }
  4387. if (!(bs->open_flags & BDRV_O_INACTIVE)) {
  4388. return;
  4389. }
  4390. QLIST_FOREACH(child, &bs->children, next) {
  4391. bdrv_co_invalidate_cache(child->bs, &local_err);
  4392. if (local_err) {
  4393. error_propagate(errp, local_err);
  4394. return;
  4395. }
  4396. }
  4397. /*
  4398. * Update permissions, they may differ for inactive nodes.
  4399. *
  4400. * Note that the required permissions of inactive images are always a
  4401. * subset of the permissions required after activating the image. This
  4402. * allows us to just get the permissions upfront without restricting
  4403. * drv->bdrv_invalidate_cache().
  4404. *
  4405. * It also means that in error cases, we don't have to try and revert to
  4406. * the old permissions (which is an operation that could fail, too). We can
  4407. * just keep the extended permissions for the next time that an activation
  4408. * of the image is tried.
  4409. */
  4410. bs->open_flags &= ~BDRV_O_INACTIVE;
  4411. bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
  4412. ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &local_err);
  4413. if (ret < 0) {
  4414. bs->open_flags |= BDRV_O_INACTIVE;
  4415. error_propagate(errp, local_err);
  4416. return;
  4417. }
  4418. bdrv_set_perm(bs, perm, shared_perm);
  4419. if (bs->drv->bdrv_co_invalidate_cache) {
  4420. bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
  4421. if (local_err) {
  4422. bs->open_flags |= BDRV_O_INACTIVE;
  4423. error_propagate(errp, local_err);
  4424. return;
  4425. }
  4426. }
  4427. for (bm = bdrv_dirty_bitmap_next(bs, NULL); bm;
  4428. bm = bdrv_dirty_bitmap_next(bs, bm))
  4429. {
  4430. bdrv_dirty_bitmap_set_migration(bm, false);
  4431. }
  4432. ret = refresh_total_sectors(bs, bs->total_sectors);
  4433. if (ret < 0) {
  4434. bs->open_flags |= BDRV_O_INACTIVE;
  4435. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  4436. return;
  4437. }
  4438. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  4439. if (parent->role->activate) {
  4440. parent->role->activate(parent, &local_err);
  4441. if (local_err) {
  4442. bs->open_flags |= BDRV_O_INACTIVE;
  4443. error_propagate(errp, local_err);
  4444. return;
  4445. }
  4446. }
  4447. }
  4448. }
  4449. typedef struct InvalidateCacheCo {
  4450. BlockDriverState *bs;
  4451. Error **errp;
  4452. bool done;
  4453. } InvalidateCacheCo;
  4454. static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
  4455. {
  4456. InvalidateCacheCo *ico = opaque;
  4457. bdrv_co_invalidate_cache(ico->bs, ico->errp);
  4458. ico->done = true;
  4459. aio_wait_kick();
  4460. }
  4461. void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
  4462. {
  4463. Coroutine *co;
  4464. InvalidateCacheCo ico = {
  4465. .bs = bs,
  4466. .done = false,
  4467. .errp = errp
  4468. };
  4469. if (qemu_in_coroutine()) {
  4470. /* Fast-path if already in coroutine context */
  4471. bdrv_invalidate_cache_co_entry(&ico);
  4472. } else {
  4473. co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
  4474. bdrv_coroutine_enter(bs, co);
  4475. BDRV_POLL_WHILE(bs, !ico.done);
  4476. }
  4477. }
  4478. void bdrv_invalidate_cache_all(Error **errp)
  4479. {
  4480. BlockDriverState *bs;
  4481. Error *local_err = NULL;
  4482. BdrvNextIterator it;
  4483. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  4484. AioContext *aio_context = bdrv_get_aio_context(bs);
  4485. aio_context_acquire(aio_context);
  4486. bdrv_invalidate_cache(bs, &local_err);
  4487. aio_context_release(aio_context);
  4488. if (local_err) {
  4489. error_propagate(errp, local_err);
  4490. bdrv_next_cleanup(&it);
  4491. return;
  4492. }
  4493. }
  4494. }
  4495. static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
  4496. {
  4497. BdrvChild *parent;
  4498. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  4499. if (parent->role->parent_is_bds) {
  4500. BlockDriverState *parent_bs = parent->opaque;
  4501. if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
  4502. return true;
  4503. }
  4504. }
  4505. }
  4506. return false;
  4507. }
  4508. static int bdrv_inactivate_recurse(BlockDriverState *bs)
  4509. {
  4510. BdrvChild *child, *parent;
  4511. uint64_t perm, shared_perm;
  4512. int ret;
  4513. if (!bs->drv) {
  4514. return -ENOMEDIUM;
  4515. }
  4516. /* Make sure that we don't inactivate a child before its parent.
  4517. * It will be covered by recursion from the yet active parent. */
  4518. if (bdrv_has_bds_parent(bs, true)) {
  4519. return 0;
  4520. }
  4521. assert(!(bs->open_flags & BDRV_O_INACTIVE));
  4522. /* Inactivate this node */
  4523. if (bs->drv->bdrv_inactivate) {
  4524. ret = bs->drv->bdrv_inactivate(bs);
  4525. if (ret < 0) {
  4526. return ret;
  4527. }
  4528. }
  4529. QLIST_FOREACH(parent, &bs->parents, next_parent) {
  4530. if (parent->role->inactivate) {
  4531. ret = parent->role->inactivate(parent);
  4532. if (ret < 0) {
  4533. return ret;
  4534. }
  4535. }
  4536. }
  4537. bs->open_flags |= BDRV_O_INACTIVE;
  4538. /* Update permissions, they may differ for inactive nodes */
  4539. bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
  4540. bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, &error_abort);
  4541. bdrv_set_perm(bs, perm, shared_perm);
  4542. /* Recursively inactivate children */
  4543. QLIST_FOREACH(child, &bs->children, next) {
  4544. ret = bdrv_inactivate_recurse(child->bs);
  4545. if (ret < 0) {
  4546. return ret;
  4547. }
  4548. }
  4549. return 0;
  4550. }
  4551. int bdrv_inactivate_all(void)
  4552. {
  4553. BlockDriverState *bs = NULL;
  4554. BdrvNextIterator it;
  4555. int ret = 0;
  4556. GSList *aio_ctxs = NULL, *ctx;
  4557. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  4558. AioContext *aio_context = bdrv_get_aio_context(bs);
  4559. if (!g_slist_find(aio_ctxs, aio_context)) {
  4560. aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
  4561. aio_context_acquire(aio_context);
  4562. }
  4563. }
  4564. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  4565. /* Nodes with BDS parents are covered by recursion from the last
  4566. * parent that gets inactivated. Don't inactivate them a second
  4567. * time if that has already happened. */
  4568. if (bdrv_has_bds_parent(bs, false)) {
  4569. continue;
  4570. }
  4571. ret = bdrv_inactivate_recurse(bs);
  4572. if (ret < 0) {
  4573. bdrv_next_cleanup(&it);
  4574. goto out;
  4575. }
  4576. }
  4577. out:
  4578. for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
  4579. AioContext *aio_context = ctx->data;
  4580. aio_context_release(aio_context);
  4581. }
  4582. g_slist_free(aio_ctxs);
  4583. return ret;
  4584. }
  4585. /**************************************************************/
  4586. /* removable device support */
  4587. /**
  4588. * Return TRUE if the media is present
  4589. */
  4590. bool bdrv_is_inserted(BlockDriverState *bs)
  4591. {
  4592. BlockDriver *drv = bs->drv;
  4593. BdrvChild *child;
  4594. if (!drv) {
  4595. return false;
  4596. }
  4597. if (drv->bdrv_is_inserted) {
  4598. return drv->bdrv_is_inserted(bs);
  4599. }
  4600. QLIST_FOREACH(child, &bs->children, next) {
  4601. if (!bdrv_is_inserted(child->bs)) {
  4602. return false;
  4603. }
  4604. }
  4605. return true;
  4606. }
  4607. /**
  4608. * If eject_flag is TRUE, eject the media. Otherwise, close the tray
  4609. */
  4610. void bdrv_eject(BlockDriverState *bs, bool eject_flag)
  4611. {
  4612. BlockDriver *drv = bs->drv;
  4613. if (drv && drv->bdrv_eject) {
  4614. drv->bdrv_eject(bs, eject_flag);
  4615. }
  4616. }
  4617. /**
  4618. * Lock or unlock the media (if it is locked, the user won't be able
  4619. * to eject it manually).
  4620. */
  4621. void bdrv_lock_medium(BlockDriverState *bs, bool locked)
  4622. {
  4623. BlockDriver *drv = bs->drv;
  4624. trace_bdrv_lock_medium(bs, locked);
  4625. if (drv && drv->bdrv_lock_medium) {
  4626. drv->bdrv_lock_medium(bs, locked);
  4627. }
  4628. }
  4629. /* Get a reference to bs */
  4630. void bdrv_ref(BlockDriverState *bs)
  4631. {
  4632. bs->refcnt++;
  4633. }
  4634. /* Release a previously grabbed reference to bs.
  4635. * If after releasing, reference count is zero, the BlockDriverState is
  4636. * deleted. */
  4637. void bdrv_unref(BlockDriverState *bs)
  4638. {
  4639. if (!bs) {
  4640. return;
  4641. }
  4642. assert(bs->refcnt > 0);
  4643. if (--bs->refcnt == 0) {
  4644. bdrv_delete(bs);
  4645. }
  4646. }
  4647. struct BdrvOpBlocker {
  4648. Error *reason;
  4649. QLIST_ENTRY(BdrvOpBlocker) list;
  4650. };
  4651. bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
  4652. {
  4653. BdrvOpBlocker *blocker;
  4654. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  4655. if (!QLIST_EMPTY(&bs->op_blockers[op])) {
  4656. blocker = QLIST_FIRST(&bs->op_blockers[op]);
  4657. error_propagate_prepend(errp, error_copy(blocker->reason),
  4658. "Node '%s' is busy: ",
  4659. bdrv_get_device_or_node_name(bs));
  4660. return true;
  4661. }
  4662. return false;
  4663. }
  4664. void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
  4665. {
  4666. BdrvOpBlocker *blocker;
  4667. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  4668. blocker = g_new0(BdrvOpBlocker, 1);
  4669. blocker->reason = reason;
  4670. QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
  4671. }
  4672. void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
  4673. {
  4674. BdrvOpBlocker *blocker, *next;
  4675. assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
  4676. QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
  4677. if (blocker->reason == reason) {
  4678. QLIST_REMOVE(blocker, list);
  4679. g_free(blocker);
  4680. }
  4681. }
  4682. }
  4683. void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
  4684. {
  4685. int i;
  4686. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  4687. bdrv_op_block(bs, i, reason);
  4688. }
  4689. }
  4690. void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
  4691. {
  4692. int i;
  4693. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  4694. bdrv_op_unblock(bs, i, reason);
  4695. }
  4696. }
  4697. bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
  4698. {
  4699. int i;
  4700. for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
  4701. if (!QLIST_EMPTY(&bs->op_blockers[i])) {
  4702. return false;
  4703. }
  4704. }
  4705. return true;
  4706. }
  4707. void bdrv_img_create(const char *filename, const char *fmt,
  4708. const char *base_filename, const char *base_fmt,
  4709. char *options, uint64_t img_size, int flags, bool quiet,
  4710. Error **errp)
  4711. {
  4712. QemuOptsList *create_opts = NULL;
  4713. QemuOpts *opts = NULL;
  4714. const char *backing_fmt, *backing_file;
  4715. int64_t size;
  4716. BlockDriver *drv, *proto_drv;
  4717. Error *local_err = NULL;
  4718. int ret = 0;
  4719. /* Find driver and parse its options */
  4720. drv = bdrv_find_format(fmt);
  4721. if (!drv) {
  4722. error_setg(errp, "Unknown file format '%s'", fmt);
  4723. return;
  4724. }
  4725. proto_drv = bdrv_find_protocol(filename, true, errp);
  4726. if (!proto_drv) {
  4727. return;
  4728. }
  4729. if (!drv->create_opts) {
  4730. error_setg(errp, "Format driver '%s' does not support image creation",
  4731. drv->format_name);
  4732. return;
  4733. }
  4734. if (!proto_drv->create_opts) {
  4735. error_setg(errp, "Protocol driver '%s' does not support image creation",
  4736. proto_drv->format_name);
  4737. return;
  4738. }
  4739. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  4740. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  4741. /* Create parameter list with default values */
  4742. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  4743. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
  4744. /* Parse -o options */
  4745. if (options) {
  4746. qemu_opts_do_parse(opts, options, NULL, &local_err);
  4747. if (local_err) {
  4748. goto out;
  4749. }
  4750. }
  4751. if (base_filename) {
  4752. qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
  4753. if (local_err) {
  4754. error_setg(errp, "Backing file not supported for file format '%s'",
  4755. fmt);
  4756. goto out;
  4757. }
  4758. }
  4759. if (base_fmt) {
  4760. qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
  4761. if (local_err) {
  4762. error_setg(errp, "Backing file format not supported for file "
  4763. "format '%s'", fmt);
  4764. goto out;
  4765. }
  4766. }
  4767. backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
  4768. if (backing_file) {
  4769. if (!strcmp(filename, backing_file)) {
  4770. error_setg(errp, "Error: Trying to create an image with the "
  4771. "same filename as the backing file");
  4772. goto out;
  4773. }
  4774. }
  4775. backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
  4776. /* The size for the image must always be specified, unless we have a backing
  4777. * file and we have not been forbidden from opening it. */
  4778. size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
  4779. if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
  4780. BlockDriverState *bs;
  4781. char *full_backing;
  4782. int back_flags;
  4783. QDict *backing_options = NULL;
  4784. full_backing =
  4785. bdrv_get_full_backing_filename_from_filename(filename, backing_file,
  4786. &local_err);
  4787. if (local_err) {
  4788. goto out;
  4789. }
  4790. assert(full_backing);
  4791. /* backing files always opened read-only */
  4792. back_flags = flags;
  4793. back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
  4794. backing_options = qdict_new();
  4795. if (backing_fmt) {
  4796. qdict_put_str(backing_options, "driver", backing_fmt);
  4797. }
  4798. qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
  4799. bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
  4800. &local_err);
  4801. g_free(full_backing);
  4802. if (!bs && size != -1) {
  4803. /* Couldn't open BS, but we have a size, so it's nonfatal */
  4804. warn_reportf_err(local_err,
  4805. "Could not verify backing image. "
  4806. "This may become an error in future versions.\n");
  4807. local_err = NULL;
  4808. } else if (!bs) {
  4809. /* Couldn't open bs, do not have size */
  4810. error_append_hint(&local_err,
  4811. "Could not open backing image to determine size.\n");
  4812. goto out;
  4813. } else {
  4814. if (size == -1) {
  4815. /* Opened BS, have no size */
  4816. size = bdrv_getlength(bs);
  4817. if (size < 0) {
  4818. error_setg_errno(errp, -size, "Could not get size of '%s'",
  4819. backing_file);
  4820. bdrv_unref(bs);
  4821. goto out;
  4822. }
  4823. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
  4824. }
  4825. bdrv_unref(bs);
  4826. }
  4827. } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
  4828. if (size == -1) {
  4829. error_setg(errp, "Image creation needs a size parameter");
  4830. goto out;
  4831. }
  4832. if (!quiet) {
  4833. printf("Formatting '%s', fmt=%s ", filename, fmt);
  4834. qemu_opts_print(opts, " ");
  4835. puts("");
  4836. }
  4837. ret = bdrv_create(drv, filename, opts, &local_err);
  4838. if (ret == -EFBIG) {
  4839. /* This is generally a better message than whatever the driver would
  4840. * deliver (especially because of the cluster_size_hint), since that
  4841. * is most probably not much different from "image too large". */
  4842. const char *cluster_size_hint = "";
  4843. if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
  4844. cluster_size_hint = " (try using a larger cluster size)";
  4845. }
  4846. error_setg(errp, "The image size is too large for file format '%s'"
  4847. "%s", fmt, cluster_size_hint);
  4848. error_free(local_err);
  4849. local_err = NULL;
  4850. }
  4851. out:
  4852. qemu_opts_del(opts);
  4853. qemu_opts_free(create_opts);
  4854. error_propagate(errp, local_err);
  4855. }
  4856. AioContext *bdrv_get_aio_context(BlockDriverState *bs)
  4857. {
  4858. return bs ? bs->aio_context : qemu_get_aio_context();
  4859. }
  4860. void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
  4861. {
  4862. aio_co_enter(bdrv_get_aio_context(bs), co);
  4863. }
  4864. static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
  4865. {
  4866. QLIST_REMOVE(ban, list);
  4867. g_free(ban);
  4868. }
  4869. void bdrv_detach_aio_context(BlockDriverState *bs)
  4870. {
  4871. BdrvAioNotifier *baf, *baf_tmp;
  4872. BdrvChild *child;
  4873. assert(!bs->walking_aio_notifiers);
  4874. bs->walking_aio_notifiers = true;
  4875. QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
  4876. if (baf->deleted) {
  4877. bdrv_do_remove_aio_context_notifier(baf);
  4878. } else {
  4879. baf->detach_aio_context(baf->opaque);
  4880. }
  4881. }
  4882. /* Never mind iterating again to check for ->deleted. bdrv_close() will
  4883. * remove remaining aio notifiers if we aren't called again.
  4884. */
  4885. bs->walking_aio_notifiers = false;
  4886. if (bs->drv && bs->drv->bdrv_detach_aio_context) {
  4887. bs->drv->bdrv_detach_aio_context(bs);
  4888. }
  4889. QLIST_FOREACH(child, &bs->children, next) {
  4890. bdrv_detach_aio_context(child->bs);
  4891. }
  4892. if (bs->quiesce_counter) {
  4893. aio_enable_external(bs->aio_context);
  4894. }
  4895. bs->aio_context = NULL;
  4896. }
  4897. void bdrv_attach_aio_context(BlockDriverState *bs,
  4898. AioContext *new_context)
  4899. {
  4900. BdrvAioNotifier *ban, *ban_tmp;
  4901. BdrvChild *child;
  4902. if (bs->quiesce_counter) {
  4903. aio_disable_external(new_context);
  4904. }
  4905. bs->aio_context = new_context;
  4906. QLIST_FOREACH(child, &bs->children, next) {
  4907. bdrv_attach_aio_context(child->bs, new_context);
  4908. }
  4909. if (bs->drv && bs->drv->bdrv_attach_aio_context) {
  4910. bs->drv->bdrv_attach_aio_context(bs, new_context);
  4911. }
  4912. assert(!bs->walking_aio_notifiers);
  4913. bs->walking_aio_notifiers = true;
  4914. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
  4915. if (ban->deleted) {
  4916. bdrv_do_remove_aio_context_notifier(ban);
  4917. } else {
  4918. ban->attached_aio_context(new_context, ban->opaque);
  4919. }
  4920. }
  4921. bs->walking_aio_notifiers = false;
  4922. }
  4923. /* The caller must own the AioContext lock for the old AioContext of bs, but it
  4924. * must not own the AioContext lock for new_context (unless new_context is
  4925. * the same as the current context of bs). */
  4926. void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
  4927. {
  4928. if (bdrv_get_aio_context(bs) == new_context) {
  4929. return;
  4930. }
  4931. bdrv_drained_begin(bs);
  4932. bdrv_detach_aio_context(bs);
  4933. /* This function executes in the old AioContext so acquire the new one in
  4934. * case it runs in a different thread.
  4935. */
  4936. aio_context_acquire(new_context);
  4937. bdrv_attach_aio_context(bs, new_context);
  4938. bdrv_drained_end(bs);
  4939. aio_context_release(new_context);
  4940. }
  4941. void bdrv_add_aio_context_notifier(BlockDriverState *bs,
  4942. void (*attached_aio_context)(AioContext *new_context, void *opaque),
  4943. void (*detach_aio_context)(void *opaque), void *opaque)
  4944. {
  4945. BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
  4946. *ban = (BdrvAioNotifier){
  4947. .attached_aio_context = attached_aio_context,
  4948. .detach_aio_context = detach_aio_context,
  4949. .opaque = opaque
  4950. };
  4951. QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
  4952. }
  4953. void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
  4954. void (*attached_aio_context)(AioContext *,
  4955. void *),
  4956. void (*detach_aio_context)(void *),
  4957. void *opaque)
  4958. {
  4959. BdrvAioNotifier *ban, *ban_next;
  4960. QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
  4961. if (ban->attached_aio_context == attached_aio_context &&
  4962. ban->detach_aio_context == detach_aio_context &&
  4963. ban->opaque == opaque &&
  4964. ban->deleted == false)
  4965. {
  4966. if (bs->walking_aio_notifiers) {
  4967. ban->deleted = true;
  4968. } else {
  4969. bdrv_do_remove_aio_context_notifier(ban);
  4970. }
  4971. return;
  4972. }
  4973. }
  4974. abort();
  4975. }
  4976. int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
  4977. BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
  4978. Error **errp)
  4979. {
  4980. if (!bs->drv) {
  4981. error_setg(errp, "Node is ejected");
  4982. return -ENOMEDIUM;
  4983. }
  4984. if (!bs->drv->bdrv_amend_options) {
  4985. error_setg(errp, "Block driver '%s' does not support option amendment",
  4986. bs->drv->format_name);
  4987. return -ENOTSUP;
  4988. }
  4989. return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
  4990. }
  4991. /* This function will be called by the bdrv_recurse_is_first_non_filter method
  4992. * of block filter and by bdrv_is_first_non_filter.
  4993. * It is used to test if the given bs is the candidate or recurse more in the
  4994. * node graph.
  4995. */
  4996. bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
  4997. BlockDriverState *candidate)
  4998. {
  4999. /* return false if basic checks fails */
  5000. if (!bs || !bs->drv) {
  5001. return false;
  5002. }
  5003. /* the code reached a non block filter driver -> check if the bs is
  5004. * the same as the candidate. It's the recursion termination condition.
  5005. */
  5006. if (!bs->drv->is_filter) {
  5007. return bs == candidate;
  5008. }
  5009. /* Down this path the driver is a block filter driver */
  5010. /* If the block filter recursion method is defined use it to recurse down
  5011. * the node graph.
  5012. */
  5013. if (bs->drv->bdrv_recurse_is_first_non_filter) {
  5014. return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
  5015. }
  5016. /* the driver is a block filter but don't allow to recurse -> return false
  5017. */
  5018. return false;
  5019. }
  5020. /* This function checks if the candidate is the first non filter bs down it's
  5021. * bs chain. Since we don't have pointers to parents it explore all bs chains
  5022. * from the top. Some filters can choose not to pass down the recursion.
  5023. */
  5024. bool bdrv_is_first_non_filter(BlockDriverState *candidate)
  5025. {
  5026. BlockDriverState *bs;
  5027. BdrvNextIterator it;
  5028. /* walk down the bs forest recursively */
  5029. for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
  5030. bool perm;
  5031. /* try to recurse in this top level bs */
  5032. perm = bdrv_recurse_is_first_non_filter(bs, candidate);
  5033. /* candidate is the first non filter */
  5034. if (perm) {
  5035. bdrv_next_cleanup(&it);
  5036. return true;
  5037. }
  5038. }
  5039. return false;
  5040. }
  5041. BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
  5042. const char *node_name, Error **errp)
  5043. {
  5044. BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
  5045. AioContext *aio_context;
  5046. if (!to_replace_bs) {
  5047. error_setg(errp, "Node name '%s' not found", node_name);
  5048. return NULL;
  5049. }
  5050. aio_context = bdrv_get_aio_context(to_replace_bs);
  5051. aio_context_acquire(aio_context);
  5052. if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
  5053. to_replace_bs = NULL;
  5054. goto out;
  5055. }
  5056. /* We don't want arbitrary node of the BDS chain to be replaced only the top
  5057. * most non filter in order to prevent data corruption.
  5058. * Another benefit is that this tests exclude backing files which are
  5059. * blocked by the backing blockers.
  5060. */
  5061. if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
  5062. error_setg(errp, "Only top most non filter can be replaced");
  5063. to_replace_bs = NULL;
  5064. goto out;
  5065. }
  5066. out:
  5067. aio_context_release(aio_context);
  5068. return to_replace_bs;
  5069. }
  5070. /**
  5071. * Iterates through the list of runtime option keys that are said to
  5072. * be "strong" for a BDS. An option is called "strong" if it changes
  5073. * a BDS's data. For example, the null block driver's "size" and
  5074. * "read-zeroes" options are strong, but its "latency-ns" option is
  5075. * not.
  5076. *
  5077. * If a key returned by this function ends with a dot, all options
  5078. * starting with that prefix are strong.
  5079. */
  5080. static const char *const *strong_options(BlockDriverState *bs,
  5081. const char *const *curopt)
  5082. {
  5083. static const char *const global_options[] = {
  5084. "driver", "filename", NULL
  5085. };
  5086. if (!curopt) {
  5087. return &global_options[0];
  5088. }
  5089. curopt++;
  5090. if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
  5091. curopt = bs->drv->strong_runtime_opts;
  5092. }
  5093. return (curopt && *curopt) ? curopt : NULL;
  5094. }
  5095. /**
  5096. * Copies all strong runtime options from bs->options to the given
  5097. * QDict. The set of strong option keys is determined by invoking
  5098. * strong_options().
  5099. *
  5100. * Returns true iff any strong option was present in bs->options (and
  5101. * thus copied to the target QDict) with the exception of "filename"
  5102. * and "driver". The caller is expected to use this value to decide
  5103. * whether the existence of strong options prevents the generation of
  5104. * a plain filename.
  5105. */
  5106. static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
  5107. {
  5108. bool found_any = false;
  5109. const char *const *option_name = NULL;
  5110. if (!bs->drv) {
  5111. return false;
  5112. }
  5113. while ((option_name = strong_options(bs, option_name))) {
  5114. bool option_given = false;
  5115. assert(strlen(*option_name) > 0);
  5116. if ((*option_name)[strlen(*option_name) - 1] != '.') {
  5117. QObject *entry = qdict_get(bs->options, *option_name);
  5118. if (!entry) {
  5119. continue;
  5120. }
  5121. qdict_put_obj(d, *option_name, qobject_ref(entry));
  5122. option_given = true;
  5123. } else {
  5124. const QDictEntry *entry;
  5125. for (entry = qdict_first(bs->options); entry;
  5126. entry = qdict_next(bs->options, entry))
  5127. {
  5128. if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
  5129. qdict_put_obj(d, qdict_entry_key(entry),
  5130. qobject_ref(qdict_entry_value(entry)));
  5131. option_given = true;
  5132. }
  5133. }
  5134. }
  5135. /* While "driver" and "filename" need to be included in a JSON filename,
  5136. * their existence does not prohibit generation of a plain filename. */
  5137. if (!found_any && option_given &&
  5138. strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
  5139. {
  5140. found_any = true;
  5141. }
  5142. }
  5143. if (!qdict_haskey(d, "driver")) {
  5144. /* Drivers created with bdrv_new_open_driver() may not have a
  5145. * @driver option. Add it here. */
  5146. qdict_put_str(d, "driver", bs->drv->format_name);
  5147. }
  5148. return found_any;
  5149. }
  5150. /* Note: This function may return false positives; it may return true
  5151. * even if opening the backing file specified by bs's image header
  5152. * would result in exactly bs->backing. */
  5153. static bool bdrv_backing_overridden(BlockDriverState *bs)
  5154. {
  5155. if (bs->backing) {
  5156. return strcmp(bs->auto_backing_file,
  5157. bs->backing->bs->filename);
  5158. } else {
  5159. /* No backing BDS, so if the image header reports any backing
  5160. * file, it must have been suppressed */
  5161. return bs->auto_backing_file[0] != '\0';
  5162. }
  5163. }
  5164. /* Updates the following BDS fields:
  5165. * - exact_filename: A filename which may be used for opening a block device
  5166. * which (mostly) equals the given BDS (even without any
  5167. * other options; so reading and writing must return the same
  5168. * results, but caching etc. may be different)
  5169. * - full_open_options: Options which, when given when opening a block device
  5170. * (without a filename), result in a BDS (mostly)
  5171. * equalling the given one
  5172. * - filename: If exact_filename is set, it is copied here. Otherwise,
  5173. * full_open_options is converted to a JSON object, prefixed with
  5174. * "json:" (for use through the JSON pseudo protocol) and put here.
  5175. */
  5176. void bdrv_refresh_filename(BlockDriverState *bs)
  5177. {
  5178. BlockDriver *drv = bs->drv;
  5179. BdrvChild *child;
  5180. QDict *opts;
  5181. bool backing_overridden;
  5182. bool generate_json_filename; /* Whether our default implementation should
  5183. fill exact_filename (false) or not (true) */
  5184. if (!drv) {
  5185. return;
  5186. }
  5187. /* This BDS's file name may depend on any of its children's file names, so
  5188. * refresh those first */
  5189. QLIST_FOREACH(child, &bs->children, next) {
  5190. bdrv_refresh_filename(child->bs);
  5191. }
  5192. if (bs->implicit) {
  5193. /* For implicit nodes, just copy everything from the single child */
  5194. child = QLIST_FIRST(&bs->children);
  5195. assert(QLIST_NEXT(child, next) == NULL);
  5196. pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
  5197. child->bs->exact_filename);
  5198. pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
  5199. bs->full_open_options = qobject_ref(child->bs->full_open_options);
  5200. return;
  5201. }
  5202. backing_overridden = bdrv_backing_overridden(bs);
  5203. if (bs->open_flags & BDRV_O_NO_IO) {
  5204. /* Without I/O, the backing file does not change anything.
  5205. * Therefore, in such a case (primarily qemu-img), we can
  5206. * pretend the backing file has not been overridden even if
  5207. * it technically has been. */
  5208. backing_overridden = false;
  5209. }
  5210. /* Gather the options QDict */
  5211. opts = qdict_new();
  5212. generate_json_filename = append_strong_runtime_options(opts, bs);
  5213. generate_json_filename |= backing_overridden;
  5214. if (drv->bdrv_gather_child_options) {
  5215. /* Some block drivers may not want to present all of their children's
  5216. * options, or name them differently from BdrvChild.name */
  5217. drv->bdrv_gather_child_options(bs, opts, backing_overridden);
  5218. } else {
  5219. QLIST_FOREACH(child, &bs->children, next) {
  5220. if (child->role == &child_backing && !backing_overridden) {
  5221. /* We can skip the backing BDS if it has not been overridden */
  5222. continue;
  5223. }
  5224. qdict_put(opts, child->name,
  5225. qobject_ref(child->bs->full_open_options));
  5226. }
  5227. if (backing_overridden && !bs->backing) {
  5228. /* Force no backing file */
  5229. qdict_put_null(opts, "backing");
  5230. }
  5231. }
  5232. qobject_unref(bs->full_open_options);
  5233. bs->full_open_options = opts;
  5234. if (drv->bdrv_refresh_filename) {
  5235. /* Obsolete information is of no use here, so drop the old file name
  5236. * information before refreshing it */
  5237. bs->exact_filename[0] = '\0';
  5238. drv->bdrv_refresh_filename(bs);
  5239. } else if (bs->file) {
  5240. /* Try to reconstruct valid information from the underlying file */
  5241. bs->exact_filename[0] = '\0';
  5242. /*
  5243. * We can use the underlying file's filename if:
  5244. * - it has a filename,
  5245. * - the file is a protocol BDS, and
  5246. * - opening that file (as this BDS's format) will automatically create
  5247. * the BDS tree we have right now, that is:
  5248. * - the user did not significantly change this BDS's behavior with
  5249. * some explicit (strong) options
  5250. * - no non-file child of this BDS has been overridden by the user
  5251. * Both of these conditions are represented by generate_json_filename.
  5252. */
  5253. if (bs->file->bs->exact_filename[0] &&
  5254. bs->file->bs->drv->bdrv_file_open &&
  5255. !generate_json_filename)
  5256. {
  5257. strcpy(bs->exact_filename, bs->file->bs->exact_filename);
  5258. }
  5259. }
  5260. if (bs->exact_filename[0]) {
  5261. pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
  5262. } else {
  5263. QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
  5264. snprintf(bs->filename, sizeof(bs->filename), "json:%s",
  5265. qstring_get_str(json));
  5266. qobject_unref(json);
  5267. }
  5268. }
  5269. char *bdrv_dirname(BlockDriverState *bs, Error **errp)
  5270. {
  5271. BlockDriver *drv = bs->drv;
  5272. if (!drv) {
  5273. error_setg(errp, "Node '%s' is ejected", bs->node_name);
  5274. return NULL;
  5275. }
  5276. if (drv->bdrv_dirname) {
  5277. return drv->bdrv_dirname(bs, errp);
  5278. }
  5279. if (bs->file) {
  5280. return bdrv_dirname(bs->file->bs, errp);
  5281. }
  5282. bdrv_refresh_filename(bs);
  5283. if (bs->exact_filename[0] != '\0') {
  5284. return path_combine(bs->exact_filename, "");
  5285. }
  5286. error_setg(errp, "Cannot generate a base directory for %s nodes",
  5287. drv->format_name);
  5288. return NULL;
  5289. }
  5290. /*
  5291. * Hot add/remove a BDS's child. So the user can take a child offline when
  5292. * it is broken and take a new child online
  5293. */
  5294. void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
  5295. Error **errp)
  5296. {
  5297. if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
  5298. error_setg(errp, "The node %s does not support adding a child",
  5299. bdrv_get_device_or_node_name(parent_bs));
  5300. return;
  5301. }
  5302. if (!QLIST_EMPTY(&child_bs->parents)) {
  5303. error_setg(errp, "The node %s already has a parent",
  5304. child_bs->node_name);
  5305. return;
  5306. }
  5307. parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
  5308. }
  5309. void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
  5310. {
  5311. BdrvChild *tmp;
  5312. if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
  5313. error_setg(errp, "The node %s does not support removing a child",
  5314. bdrv_get_device_or_node_name(parent_bs));
  5315. return;
  5316. }
  5317. QLIST_FOREACH(tmp, &parent_bs->children, next) {
  5318. if (tmp == child) {
  5319. break;
  5320. }
  5321. }
  5322. if (!tmp) {
  5323. error_setg(errp, "The node %s does not have a child named %s",
  5324. bdrv_get_device_or_node_name(parent_bs),
  5325. bdrv_get_device_or_node_name(child->bs));
  5326. return;
  5327. }
  5328. parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
  5329. }
  5330. bool bdrv_can_store_new_dirty_bitmap(BlockDriverState *bs, const char *name,
  5331. uint32_t granularity, Error **errp)
  5332. {
  5333. BlockDriver *drv = bs->drv;
  5334. if (!drv) {
  5335. error_setg_errno(errp, ENOMEDIUM,
  5336. "Can't store persistent bitmaps to %s",
  5337. bdrv_get_device_or_node_name(bs));
  5338. return false;
  5339. }
  5340. if (!drv->bdrv_can_store_new_dirty_bitmap) {
  5341. error_setg_errno(errp, ENOTSUP,
  5342. "Can't store persistent bitmaps to %s",
  5343. bdrv_get_device_or_node_name(bs));
  5344. return false;
  5345. }
  5346. return drv->bdrv_can_store_new_dirty_bitmap(bs, name, granularity, errp);
  5347. }