qemu-nbd.c 17 KB

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