2
0

qemu-nbd.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  1. /*
  2. * Copyright (C) 2005 Anthony Liguori <anthony@codemonkey.ws>
  3. *
  4. * Network Block Device
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; under version 2 of the License.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program; if not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #include "qemu-common.h"
  19. #include "block/block.h"
  20. #include "block/nbd.h"
  21. #include "qemu/main-loop.h"
  22. #include "qemu/sockets.h"
  23. #include "qemu/error-report.h"
  24. #include "block/snapshot.h"
  25. #include <stdarg.h>
  26. #include <stdio.h>
  27. #include <getopt.h>
  28. #include <err.h>
  29. #include <sys/types.h>
  30. #include <sys/socket.h>
  31. #include <netinet/in.h>
  32. #include <netinet/tcp.h>
  33. #include <arpa/inet.h>
  34. #include <signal.h>
  35. #include <libgen.h>
  36. #include <pthread.h>
  37. #define SOCKET_PATH "/var/lock/qemu-nbd-%s"
  38. #define QEMU_NBD_OPT_CACHE 1
  39. #define QEMU_NBD_OPT_AIO 2
  40. #define QEMU_NBD_OPT_DISCARD 3
  41. static NBDExport *exp;
  42. static int verbose;
  43. static char *srcpath;
  44. static char *sockpath;
  45. static int persistent = 0;
  46. static enum { RUNNING, TERMINATE, TERMINATING, TERMINATED } state;
  47. static int shared = 1;
  48. static int nb_fds;
  49. static void usage(const char *name)
  50. {
  51. (printf) (
  52. "Usage: %s [OPTIONS] FILE\n"
  53. "QEMU Disk Network Block Device Server\n"
  54. "\n"
  55. " -h, --help display this help and exit\n"
  56. " -V, --version output version information and exit\n"
  57. "\n"
  58. "Connection properties:\n"
  59. " -p, --port=PORT port to listen on (default `%d')\n"
  60. " -b, --bind=IFACE interface to bind to (default `0.0.0.0')\n"
  61. " -k, --socket=PATH path to the unix socket\n"
  62. " (default '"SOCKET_PATH"')\n"
  63. " -e, --shared=NUM device can be shared by NUM clients (default '1')\n"
  64. " -t, --persistent don't exit on the last connection\n"
  65. " -v, --verbose display extra debugging information\n"
  66. "\n"
  67. "Exposing part of the image:\n"
  68. " -o, --offset=OFFSET offset into the image\n"
  69. " -P, --partition=NUM only expose partition NUM\n"
  70. "\n"
  71. #ifdef __linux__
  72. "Kernel NBD client support:\n"
  73. " -c, --connect=DEV connect FILE to the local NBD device DEV\n"
  74. " -d, --disconnect disconnect the specified device\n"
  75. "\n"
  76. #endif
  77. "\n"
  78. "Block device options:\n"
  79. " -f, --format=FORMAT set image format (raw, qcow2, ...)\n"
  80. " -r, --read-only export read-only\n"
  81. " -s, --snapshot use FILE as an external snapshot, create a temporary\n"
  82. " file with backing_file=FILE, redirect the write to\n"
  83. " the temporary one\n"
  84. " -l, --load-snapshot=SNAPSHOT_PARAM\n"
  85. " load an internal snapshot inside FILE and export it\n"
  86. " as an read-only device, SNAPSHOT_PARAM format is\n"
  87. " 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
  88. " '[ID_OR_NAME]'\n"
  89. " -n, --nocache disable host cache\n"
  90. " --cache=MODE set cache mode (none, writeback, ...)\n"
  91. #ifdef CONFIG_LINUX_AIO
  92. " --aio=MODE set AIO mode (native or threads)\n"
  93. #endif
  94. "\n"
  95. "Report bugs to <qemu-devel@nongnu.org>\n"
  96. , name, NBD_DEFAULT_PORT, "DEVICE");
  97. }
  98. static void version(const char *name)
  99. {
  100. printf(
  101. "%s version 0.0.1\n"
  102. "Written by Anthony Liguori.\n"
  103. "\n"
  104. "Copyright (C) 2006 Anthony Liguori <anthony@codemonkey.ws>.\n"
  105. "This is free software; see the source for copying conditions. There is NO\n"
  106. "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
  107. , name);
  108. }
  109. struct partition_record
  110. {
  111. uint8_t bootable;
  112. uint8_t start_head;
  113. uint32_t start_cylinder;
  114. uint8_t start_sector;
  115. uint8_t system;
  116. uint8_t end_head;
  117. uint8_t end_cylinder;
  118. uint8_t end_sector;
  119. uint32_t start_sector_abs;
  120. uint32_t nb_sectors_abs;
  121. };
  122. static void read_partition(uint8_t *p, struct partition_record *r)
  123. {
  124. r->bootable = p[0];
  125. r->start_head = p[1];
  126. r->start_cylinder = p[3] | ((p[2] << 2) & 0x0300);
  127. r->start_sector = p[2] & 0x3f;
  128. r->system = p[4];
  129. r->end_head = p[5];
  130. r->end_cylinder = p[7] | ((p[6] << 2) & 0x300);
  131. r->end_sector = p[6] & 0x3f;
  132. r->start_sector_abs = p[8] | p[9] << 8 | p[10] << 16 | p[11] << 24;
  133. r->nb_sectors_abs = p[12] | p[13] << 8 | p[14] << 16 | p[15] << 24;
  134. }
  135. static int find_partition(BlockDriverState *bs, int partition,
  136. off_t *offset, off_t *size)
  137. {
  138. struct partition_record mbr[4];
  139. uint8_t data[512];
  140. int i;
  141. int ext_partnum = 4;
  142. int ret;
  143. if ((ret = bdrv_read(bs, 0, data, 1)) < 0) {
  144. errno = -ret;
  145. err(EXIT_FAILURE, "error while reading");
  146. }
  147. if (data[510] != 0x55 || data[511] != 0xaa) {
  148. return -EINVAL;
  149. }
  150. for (i = 0; i < 4; i++) {
  151. read_partition(&data[446 + 16 * i], &mbr[i]);
  152. if (!mbr[i].nb_sectors_abs)
  153. continue;
  154. if (mbr[i].system == 0xF || mbr[i].system == 0x5) {
  155. struct partition_record ext[4];
  156. uint8_t data1[512];
  157. int j;
  158. if ((ret = bdrv_read(bs, mbr[i].start_sector_abs, data1, 1)) < 0) {
  159. errno = -ret;
  160. err(EXIT_FAILURE, "error while reading");
  161. }
  162. for (j = 0; j < 4; j++) {
  163. read_partition(&data1[446 + 16 * j], &ext[j]);
  164. if (!ext[j].nb_sectors_abs)
  165. continue;
  166. if ((ext_partnum + j + 1) == partition) {
  167. *offset = (uint64_t)ext[j].start_sector_abs << 9;
  168. *size = (uint64_t)ext[j].nb_sectors_abs << 9;
  169. return 0;
  170. }
  171. }
  172. ext_partnum += 4;
  173. } else if ((i + 1) == partition) {
  174. *offset = (uint64_t)mbr[i].start_sector_abs << 9;
  175. *size = (uint64_t)mbr[i].nb_sectors_abs << 9;
  176. return 0;
  177. }
  178. }
  179. return -ENOENT;
  180. }
  181. static void termsig_handler(int signum)
  182. {
  183. state = TERMINATE;
  184. qemu_notify_event();
  185. }
  186. static void combine_addr(char *buf, size_t len, const char* address,
  187. uint16_t port)
  188. {
  189. /* If the address-part contains a colon, it's an IPv6 IP so needs [] */
  190. if (strstr(address, ":")) {
  191. snprintf(buf, len, "[%s]:%u", address, port);
  192. } else {
  193. snprintf(buf, len, "%s:%u", address, port);
  194. }
  195. }
  196. static int tcp_socket_incoming(const char *address, uint16_t port)
  197. {
  198. char address_and_port[128];
  199. Error *local_err = NULL;
  200. combine_addr(address_and_port, 128, address, port);
  201. int fd = inet_listen(address_and_port, NULL, 0, SOCK_STREAM, 0, &local_err);
  202. if (local_err != NULL) {
  203. error_report("%s", error_get_pretty(local_err));
  204. error_free(local_err);
  205. }
  206. return fd;
  207. }
  208. static int unix_socket_incoming(const char *path)
  209. {
  210. Error *local_err = NULL;
  211. int fd = unix_listen(path, NULL, 0, &local_err);
  212. if (local_err != NULL) {
  213. error_report("%s", error_get_pretty(local_err));
  214. error_free(local_err);
  215. }
  216. return fd;
  217. }
  218. static int unix_socket_outgoing(const char *path)
  219. {
  220. Error *local_err = NULL;
  221. int fd = unix_connect(path, &local_err);
  222. if (local_err != NULL) {
  223. error_report("%s", error_get_pretty(local_err));
  224. error_free(local_err);
  225. }
  226. return fd;
  227. }
  228. static void *show_parts(void *arg)
  229. {
  230. char *device = arg;
  231. int nbd;
  232. /* linux just needs an open() to trigger
  233. * the partition table update
  234. * but remember to load the module with max_part != 0 :
  235. * modprobe nbd max_part=63
  236. */
  237. nbd = open(device, O_RDWR);
  238. if (nbd >= 0) {
  239. close(nbd);
  240. }
  241. return NULL;
  242. }
  243. static void *nbd_client_thread(void *arg)
  244. {
  245. char *device = arg;
  246. off_t size;
  247. size_t blocksize;
  248. uint32_t nbdflags;
  249. int fd, sock;
  250. int ret;
  251. pthread_t show_parts_thread;
  252. sock = unix_socket_outgoing(sockpath);
  253. if (sock < 0) {
  254. goto out;
  255. }
  256. ret = nbd_receive_negotiate(sock, NULL, &nbdflags,
  257. &size, &blocksize);
  258. if (ret < 0) {
  259. goto out_socket;
  260. }
  261. fd = open(device, O_RDWR);
  262. if (fd < 0) {
  263. /* Linux-only, we can use %m in printf. */
  264. fprintf(stderr, "Failed to open %s: %m\n", device);
  265. goto out_socket;
  266. }
  267. ret = nbd_init(fd, sock, nbdflags, size, blocksize);
  268. if (ret < 0) {
  269. goto out_fd;
  270. }
  271. /* update partition table */
  272. pthread_create(&show_parts_thread, NULL, show_parts, device);
  273. if (verbose) {
  274. fprintf(stderr, "NBD device %s is now connected to %s\n",
  275. device, srcpath);
  276. } else {
  277. /* Close stderr so that the qemu-nbd process exits. */
  278. dup2(STDOUT_FILENO, STDERR_FILENO);
  279. }
  280. ret = nbd_client(fd);
  281. if (ret) {
  282. goto out_fd;
  283. }
  284. close(fd);
  285. kill(getpid(), SIGTERM);
  286. return (void *) EXIT_SUCCESS;
  287. out_fd:
  288. close(fd);
  289. out_socket:
  290. closesocket(sock);
  291. out:
  292. kill(getpid(), SIGTERM);
  293. return (void *) EXIT_FAILURE;
  294. }
  295. static int nbd_can_accept(void *opaque)
  296. {
  297. return nb_fds < shared;
  298. }
  299. static void nbd_export_closed(NBDExport *exp)
  300. {
  301. assert(state == TERMINATING);
  302. state = TERMINATED;
  303. }
  304. static void nbd_client_closed(NBDClient *client)
  305. {
  306. nb_fds--;
  307. if (nb_fds == 0 && !persistent && state == RUNNING) {
  308. state = TERMINATE;
  309. }
  310. qemu_notify_event();
  311. nbd_client_put(client);
  312. }
  313. static void nbd_accept(void *opaque)
  314. {
  315. int server_fd = (uintptr_t) opaque;
  316. struct sockaddr_in addr;
  317. socklen_t addr_len = sizeof(addr);
  318. int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
  319. if (fd < 0) {
  320. perror("accept");
  321. return;
  322. }
  323. if (state >= TERMINATE) {
  324. close(fd);
  325. return;
  326. }
  327. if (nbd_client_new(exp, fd, nbd_client_closed)) {
  328. nb_fds++;
  329. } else {
  330. shutdown(fd, 2);
  331. close(fd);
  332. }
  333. }
  334. int main(int argc, char **argv)
  335. {
  336. BlockDriverState *bs;
  337. BlockDriver *drv;
  338. off_t dev_offset = 0;
  339. uint32_t nbdflags = 0;
  340. bool disconnect = false;
  341. const char *bindto = "0.0.0.0";
  342. char *device = NULL;
  343. int port = NBD_DEFAULT_PORT;
  344. off_t fd_size;
  345. QemuOpts *sn_opts = NULL;
  346. const char *sn_id_or_name = NULL;
  347. const char *sopt = "hVb:o:p:rsnP:c:dvk:e:f:tl:";
  348. struct option lopt[] = {
  349. { "help", 0, NULL, 'h' },
  350. { "version", 0, NULL, 'V' },
  351. { "bind", 1, NULL, 'b' },
  352. { "port", 1, NULL, 'p' },
  353. { "socket", 1, NULL, 'k' },
  354. { "offset", 1, NULL, 'o' },
  355. { "read-only", 0, NULL, 'r' },
  356. { "partition", 1, NULL, 'P' },
  357. { "connect", 1, NULL, 'c' },
  358. { "disconnect", 0, NULL, 'd' },
  359. { "snapshot", 0, NULL, 's' },
  360. { "load-snapshot", 1, NULL, 'l' },
  361. { "nocache", 0, NULL, 'n' },
  362. { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
  363. #ifdef CONFIG_LINUX_AIO
  364. { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
  365. #endif
  366. { "discard", 1, NULL, QEMU_NBD_OPT_DISCARD },
  367. { "shared", 1, NULL, 'e' },
  368. { "format", 1, NULL, 'f' },
  369. { "persistent", 0, NULL, 't' },
  370. { "verbose", 0, NULL, 'v' },
  371. { NULL, 0, NULL, 0 }
  372. };
  373. int ch;
  374. int opt_ind = 0;
  375. int li;
  376. char *end;
  377. int flags = BDRV_O_RDWR;
  378. int partition = -1;
  379. int ret;
  380. int fd;
  381. bool seen_cache = false;
  382. bool seen_discard = false;
  383. #ifdef CONFIG_LINUX_AIO
  384. bool seen_aio = false;
  385. #endif
  386. pthread_t client_thread;
  387. const char *fmt = NULL;
  388. Error *local_err = NULL;
  389. /* The client thread uses SIGTERM to interrupt the server. A signal
  390. * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
  391. */
  392. struct sigaction sa_sigterm;
  393. memset(&sa_sigterm, 0, sizeof(sa_sigterm));
  394. sa_sigterm.sa_handler = termsig_handler;
  395. sigaction(SIGTERM, &sa_sigterm, NULL);
  396. qemu_init_exec_dir(argv[0]);
  397. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  398. switch (ch) {
  399. case 's':
  400. flags |= BDRV_O_SNAPSHOT;
  401. break;
  402. case 'n':
  403. optarg = (char *) "none";
  404. /* fallthrough */
  405. case QEMU_NBD_OPT_CACHE:
  406. if (seen_cache) {
  407. errx(EXIT_FAILURE, "-n and --cache can only be specified once");
  408. }
  409. seen_cache = true;
  410. if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
  411. errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
  412. }
  413. break;
  414. #ifdef CONFIG_LINUX_AIO
  415. case QEMU_NBD_OPT_AIO:
  416. if (seen_aio) {
  417. errx(EXIT_FAILURE, "--aio can only be specified once");
  418. }
  419. seen_aio = true;
  420. if (!strcmp(optarg, "native")) {
  421. flags |= BDRV_O_NATIVE_AIO;
  422. } else if (!strcmp(optarg, "threads")) {
  423. /* this is the default */
  424. } else {
  425. errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
  426. }
  427. break;
  428. #endif
  429. case QEMU_NBD_OPT_DISCARD:
  430. if (seen_discard) {
  431. errx(EXIT_FAILURE, "--discard can only be specified once");
  432. }
  433. seen_discard = true;
  434. if (bdrv_parse_discard_flags(optarg, &flags) == -1) {
  435. errx(EXIT_FAILURE, "Invalid discard mode `%s'", optarg);
  436. }
  437. break;
  438. case 'b':
  439. bindto = optarg;
  440. break;
  441. case 'p':
  442. li = strtol(optarg, &end, 0);
  443. if (*end) {
  444. errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
  445. }
  446. if (li < 1 || li > 65535) {
  447. errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
  448. }
  449. port = (uint16_t)li;
  450. break;
  451. case 'o':
  452. dev_offset = strtoll (optarg, &end, 0);
  453. if (*end) {
  454. errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
  455. }
  456. if (dev_offset < 0) {
  457. errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
  458. }
  459. break;
  460. case 'l':
  461. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  462. sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
  463. if (!sn_opts) {
  464. errx(EXIT_FAILURE, "Failed in parsing snapshot param `%s'",
  465. optarg);
  466. }
  467. } else {
  468. sn_id_or_name = optarg;
  469. }
  470. /* fall through */
  471. case 'r':
  472. nbdflags |= NBD_FLAG_READ_ONLY;
  473. flags &= ~BDRV_O_RDWR;
  474. break;
  475. case 'P':
  476. partition = strtol(optarg, &end, 0);
  477. if (*end)
  478. errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
  479. if (partition < 1 || partition > 8)
  480. errx(EXIT_FAILURE, "Invalid partition %d", partition);
  481. break;
  482. case 'k':
  483. sockpath = optarg;
  484. if (sockpath[0] != '/')
  485. errx(EXIT_FAILURE, "socket path must be absolute\n");
  486. break;
  487. case 'd':
  488. disconnect = true;
  489. break;
  490. case 'c':
  491. device = optarg;
  492. break;
  493. case 'e':
  494. shared = strtol(optarg, &end, 0);
  495. if (*end) {
  496. errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
  497. }
  498. if (shared < 1) {
  499. errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
  500. }
  501. break;
  502. case 'f':
  503. fmt = optarg;
  504. break;
  505. case 't':
  506. persistent = 1;
  507. break;
  508. case 'v':
  509. verbose = 1;
  510. break;
  511. case 'V':
  512. version(argv[0]);
  513. exit(0);
  514. break;
  515. case 'h':
  516. usage(argv[0]);
  517. exit(0);
  518. break;
  519. case '?':
  520. errx(EXIT_FAILURE, "Try `%s --help' for more information.",
  521. argv[0]);
  522. }
  523. }
  524. if ((argc - optind) != 1) {
  525. errx(EXIT_FAILURE, "Invalid number of argument.\n"
  526. "Try `%s --help' for more information.",
  527. argv[0]);
  528. }
  529. if (disconnect) {
  530. fd = open(argv[optind], O_RDWR);
  531. if (fd < 0) {
  532. err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
  533. }
  534. nbd_disconnect(fd);
  535. close(fd);
  536. printf("%s disconnected\n", argv[optind]);
  537. return 0;
  538. }
  539. if (device && !verbose) {
  540. int stderr_fd[2];
  541. pid_t pid;
  542. int ret;
  543. if (qemu_pipe(stderr_fd) < 0) {
  544. err(EXIT_FAILURE, "Error setting up communication pipe");
  545. }
  546. /* Now daemonize, but keep a communication channel open to
  547. * print errors and exit with the proper status code.
  548. */
  549. pid = fork();
  550. if (pid == 0) {
  551. close(stderr_fd[0]);
  552. ret = qemu_daemon(1, 0);
  553. /* Temporarily redirect stderr to the parent's pipe... */
  554. dup2(stderr_fd[1], STDERR_FILENO);
  555. if (ret < 0) {
  556. err(EXIT_FAILURE, "Failed to daemonize");
  557. }
  558. /* ... close the descriptor we inherited and go on. */
  559. close(stderr_fd[1]);
  560. } else {
  561. bool errors = false;
  562. char *buf;
  563. /* In the parent. Print error messages from the child until
  564. * it closes the pipe.
  565. */
  566. close(stderr_fd[1]);
  567. buf = g_malloc(1024);
  568. while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
  569. errors = true;
  570. ret = qemu_write_full(STDERR_FILENO, buf, ret);
  571. if (ret < 0) {
  572. exit(EXIT_FAILURE);
  573. }
  574. }
  575. if (ret < 0) {
  576. err(EXIT_FAILURE, "Cannot read from daemon");
  577. }
  578. /* Usually the daemon should not print any message.
  579. * Exit with zero status in that case.
  580. */
  581. exit(errors);
  582. }
  583. }
  584. if (device != NULL && sockpath == NULL) {
  585. sockpath = g_malloc(128);
  586. snprintf(sockpath, 128, SOCKET_PATH, basename(device));
  587. }
  588. qemu_init_main_loop();
  589. bdrv_init();
  590. atexit(bdrv_close_all);
  591. if (fmt) {
  592. drv = bdrv_find_format(fmt);
  593. if (!drv) {
  594. errx(EXIT_FAILURE, "Unknown file format '%s'", fmt);
  595. }
  596. } else {
  597. drv = NULL;
  598. }
  599. bs = bdrv_new("hda", &error_abort);
  600. srcpath = argv[optind];
  601. ret = bdrv_open(&bs, srcpath, NULL, NULL, flags, drv, &local_err);
  602. if (ret < 0) {
  603. errno = -ret;
  604. err(EXIT_FAILURE, "Failed to bdrv_open '%s': %s", argv[optind],
  605. error_get_pretty(local_err));
  606. }
  607. if (sn_opts) {
  608. ret = bdrv_snapshot_load_tmp(bs,
  609. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  610. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  611. &local_err);
  612. } else if (sn_id_or_name) {
  613. ret = bdrv_snapshot_load_tmp_by_id_or_name(bs, sn_id_or_name,
  614. &local_err);
  615. }
  616. if (ret < 0) {
  617. errno = -ret;
  618. err(EXIT_FAILURE,
  619. "Failed to load snapshot: %s",
  620. error_get_pretty(local_err));
  621. }
  622. fd_size = bdrv_getlength(bs);
  623. if (partition != -1) {
  624. ret = find_partition(bs, partition, &dev_offset, &fd_size);
  625. if (ret < 0) {
  626. errno = -ret;
  627. err(EXIT_FAILURE, "Could not find partition %d", partition);
  628. }
  629. }
  630. exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags, nbd_export_closed);
  631. if (sockpath) {
  632. fd = unix_socket_incoming(sockpath);
  633. } else {
  634. fd = tcp_socket_incoming(bindto, port);
  635. }
  636. if (fd < 0) {
  637. return 1;
  638. }
  639. if (device) {
  640. int ret;
  641. ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
  642. if (ret != 0) {
  643. errx(EXIT_FAILURE, "Failed to create client thread: %s",
  644. strerror(ret));
  645. }
  646. } else {
  647. /* Shut up GCC warnings. */
  648. memset(&client_thread, 0, sizeof(client_thread));
  649. }
  650. qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
  651. (void *)(uintptr_t)fd);
  652. /* now when the initialization is (almost) complete, chdir("/")
  653. * to free any busy filesystems */
  654. if (chdir("/") < 0) {
  655. err(EXIT_FAILURE, "Could not chdir to root directory");
  656. }
  657. state = RUNNING;
  658. do {
  659. main_loop_wait(false);
  660. if (state == TERMINATE) {
  661. state = TERMINATING;
  662. nbd_export_close(exp);
  663. nbd_export_put(exp);
  664. exp = NULL;
  665. }
  666. } while (state != TERMINATED);
  667. bdrv_close(bs);
  668. if (sockpath) {
  669. unlink(sockpath);
  670. }
  671. if (sn_opts) {
  672. qemu_opts_del(sn_opts);
  673. }
  674. if (device) {
  675. void *ret;
  676. pthread_join(client_thread, &ret);
  677. exit(ret != NULL);
  678. } else {
  679. exit(EXIT_SUCCESS);
  680. }
  681. }