qemu-nbd.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600
  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.h"
  20. #include "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 bool sigterm_reported;
  41. static bool nbd_started;
  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. sigterm_reported = true;
  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_client_closed(NBDClient *client)
  241. {
  242. nb_fds--;
  243. qemu_notify_event();
  244. }
  245. static void nbd_accept(void *opaque)
  246. {
  247. int server_fd = (uintptr_t) opaque;
  248. struct sockaddr_in addr;
  249. socklen_t addr_len = sizeof(addr);
  250. int fd = accept(server_fd, (struct sockaddr *)&addr, &addr_len);
  251. nbd_started = true;
  252. if (fd >= 0 && nbd_client_new(exp, fd, nbd_client_closed)) {
  253. nb_fds++;
  254. }
  255. }
  256. int main(int argc, char **argv)
  257. {
  258. BlockDriverState *bs;
  259. off_t dev_offset = 0;
  260. uint32_t nbdflags = 0;
  261. bool disconnect = false;
  262. const char *bindto = "0.0.0.0";
  263. char *device = NULL;
  264. int port = NBD_DEFAULT_PORT;
  265. off_t fd_size;
  266. const char *sopt = "hVb:o:p:rsnP:c:dvk:e:t";
  267. struct option lopt[] = {
  268. { "help", 0, NULL, 'h' },
  269. { "version", 0, NULL, 'V' },
  270. { "bind", 1, NULL, 'b' },
  271. { "port", 1, NULL, 'p' },
  272. { "socket", 1, NULL, 'k' },
  273. { "offset", 1, NULL, 'o' },
  274. { "read-only", 0, NULL, 'r' },
  275. { "partition", 1, NULL, 'P' },
  276. { "connect", 1, NULL, 'c' },
  277. { "disconnect", 0, NULL, 'd' },
  278. { "snapshot", 0, NULL, 's' },
  279. { "nocache", 0, NULL, 'n' },
  280. { "cache", 1, NULL, QEMU_NBD_OPT_CACHE },
  281. #ifdef CONFIG_LINUX_AIO
  282. { "aio", 1, NULL, QEMU_NBD_OPT_AIO },
  283. #endif
  284. { "shared", 1, NULL, 'e' },
  285. { "persistent", 0, NULL, 't' },
  286. { "verbose", 0, NULL, 'v' },
  287. { NULL, 0, NULL, 0 }
  288. };
  289. int ch;
  290. int opt_ind = 0;
  291. int li;
  292. char *end;
  293. int flags = BDRV_O_RDWR;
  294. int partition = -1;
  295. int ret;
  296. int fd;
  297. int persistent = 0;
  298. bool seen_cache = false;
  299. #ifdef CONFIG_LINUX_AIO
  300. bool seen_aio = false;
  301. #endif
  302. pthread_t client_thread;
  303. /* The client thread uses SIGTERM to interrupt the server. A signal
  304. * handler ensures that "qemu-nbd -v -c" exits with a nice status code.
  305. */
  306. struct sigaction sa_sigterm;
  307. memset(&sa_sigterm, 0, sizeof(sa_sigterm));
  308. sa_sigterm.sa_handler = termsig_handler;
  309. sigaction(SIGTERM, &sa_sigterm, NULL);
  310. while ((ch = getopt_long(argc, argv, sopt, lopt, &opt_ind)) != -1) {
  311. switch (ch) {
  312. case 's':
  313. flags |= BDRV_O_SNAPSHOT;
  314. break;
  315. case 'n':
  316. optarg = (char *) "none";
  317. /* fallthrough */
  318. case QEMU_NBD_OPT_CACHE:
  319. if (seen_cache) {
  320. errx(EXIT_FAILURE, "-n and --cache can only be specified once");
  321. }
  322. seen_cache = true;
  323. if (bdrv_parse_cache_flags(optarg, &flags) == -1) {
  324. errx(EXIT_FAILURE, "Invalid cache mode `%s'", optarg);
  325. }
  326. break;
  327. #ifdef CONFIG_LINUX_AIO
  328. case QEMU_NBD_OPT_AIO:
  329. if (seen_aio) {
  330. errx(EXIT_FAILURE, "--aio can only be specified once");
  331. }
  332. seen_aio = true;
  333. if (!strcmp(optarg, "native")) {
  334. flags |= BDRV_O_NATIVE_AIO;
  335. } else if (!strcmp(optarg, "threads")) {
  336. /* this is the default */
  337. } else {
  338. errx(EXIT_FAILURE, "invalid aio mode `%s'", optarg);
  339. }
  340. break;
  341. #endif
  342. case 'b':
  343. bindto = optarg;
  344. break;
  345. case 'p':
  346. li = strtol(optarg, &end, 0);
  347. if (*end) {
  348. errx(EXIT_FAILURE, "Invalid port `%s'", optarg);
  349. }
  350. if (li < 1 || li > 65535) {
  351. errx(EXIT_FAILURE, "Port out of range `%s'", optarg);
  352. }
  353. port = (uint16_t)li;
  354. break;
  355. case 'o':
  356. dev_offset = strtoll (optarg, &end, 0);
  357. if (*end) {
  358. errx(EXIT_FAILURE, "Invalid offset `%s'", optarg);
  359. }
  360. if (dev_offset < 0) {
  361. errx(EXIT_FAILURE, "Offset must be positive `%s'", optarg);
  362. }
  363. break;
  364. case 'r':
  365. nbdflags |= NBD_FLAG_READ_ONLY;
  366. flags &= ~BDRV_O_RDWR;
  367. break;
  368. case 'P':
  369. partition = strtol(optarg, &end, 0);
  370. if (*end)
  371. errx(EXIT_FAILURE, "Invalid partition `%s'", optarg);
  372. if (partition < 1 || partition > 8)
  373. errx(EXIT_FAILURE, "Invalid partition %d", partition);
  374. break;
  375. case 'k':
  376. sockpath = optarg;
  377. if (sockpath[0] != '/')
  378. errx(EXIT_FAILURE, "socket path must be absolute\n");
  379. break;
  380. case 'd':
  381. disconnect = true;
  382. break;
  383. case 'c':
  384. device = optarg;
  385. break;
  386. case 'e':
  387. shared = strtol(optarg, &end, 0);
  388. if (*end) {
  389. errx(EXIT_FAILURE, "Invalid shared device number '%s'", optarg);
  390. }
  391. if (shared < 1) {
  392. errx(EXIT_FAILURE, "Shared device number must be greater than 0\n");
  393. }
  394. break;
  395. case 't':
  396. persistent = 1;
  397. break;
  398. case 'v':
  399. verbose = 1;
  400. break;
  401. case 'V':
  402. version(argv[0]);
  403. exit(0);
  404. break;
  405. case 'h':
  406. usage(argv[0]);
  407. exit(0);
  408. break;
  409. case '?':
  410. errx(EXIT_FAILURE, "Try `%s --help' for more information.",
  411. argv[0]);
  412. }
  413. }
  414. if ((argc - optind) != 1) {
  415. errx(EXIT_FAILURE, "Invalid number of argument.\n"
  416. "Try `%s --help' for more information.",
  417. argv[0]);
  418. }
  419. if (disconnect) {
  420. fd = open(argv[optind], O_RDWR);
  421. if (fd < 0) {
  422. err(EXIT_FAILURE, "Cannot open %s", argv[optind]);
  423. }
  424. nbd_disconnect(fd);
  425. close(fd);
  426. printf("%s disconnected\n", argv[optind]);
  427. return 0;
  428. }
  429. if (device && !verbose) {
  430. int stderr_fd[2];
  431. pid_t pid;
  432. int ret;
  433. if (qemu_pipe(stderr_fd) < 0) {
  434. err(EXIT_FAILURE, "Error setting up communication pipe");
  435. }
  436. /* Now daemonize, but keep a communication channel open to
  437. * print errors and exit with the proper status code.
  438. */
  439. pid = fork();
  440. if (pid == 0) {
  441. close(stderr_fd[0]);
  442. ret = qemu_daemon(1, 0);
  443. /* Temporarily redirect stderr to the parent's pipe... */
  444. dup2(stderr_fd[1], STDERR_FILENO);
  445. if (ret < 0) {
  446. err(EXIT_FAILURE, "Failed to daemonize");
  447. }
  448. /* ... close the descriptor we inherited and go on. */
  449. close(stderr_fd[1]);
  450. } else {
  451. bool errors = false;
  452. char *buf;
  453. /* In the parent. Print error messages from the child until
  454. * it closes the pipe.
  455. */
  456. close(stderr_fd[1]);
  457. buf = g_malloc(1024);
  458. while ((ret = read(stderr_fd[0], buf, 1024)) > 0) {
  459. errors = true;
  460. ret = qemu_write_full(STDERR_FILENO, buf, ret);
  461. if (ret < 0) {
  462. exit(EXIT_FAILURE);
  463. }
  464. }
  465. if (ret < 0) {
  466. err(EXIT_FAILURE, "Cannot read from daemon");
  467. }
  468. /* Usually the daemon should not print any message.
  469. * Exit with zero status in that case.
  470. */
  471. exit(errors);
  472. }
  473. }
  474. if (device != NULL && sockpath == NULL) {
  475. sockpath = g_malloc(128);
  476. snprintf(sockpath, 128, SOCKET_PATH, basename(device));
  477. }
  478. bdrv_init();
  479. atexit(bdrv_close_all);
  480. bs = bdrv_new("hda");
  481. srcpath = argv[optind];
  482. if ((ret = bdrv_open(bs, srcpath, flags, NULL)) < 0) {
  483. errno = -ret;
  484. err(EXIT_FAILURE, "Failed to bdrv_open '%s'", argv[optind]);
  485. }
  486. fd_size = bdrv_getlength(bs);
  487. if (partition != -1) {
  488. ret = find_partition(bs, partition, &dev_offset, &fd_size);
  489. if (ret < 0) {
  490. errno = -ret;
  491. err(EXIT_FAILURE, "Could not find partition %d", partition);
  492. }
  493. }
  494. exp = nbd_export_new(bs, dev_offset, fd_size, nbdflags);
  495. if (sockpath) {
  496. fd = unix_socket_incoming(sockpath);
  497. } else {
  498. fd = tcp_socket_incoming(bindto, port);
  499. }
  500. if (fd < 0) {
  501. return 1;
  502. }
  503. if (device) {
  504. int ret;
  505. ret = pthread_create(&client_thread, NULL, nbd_client_thread, device);
  506. if (ret != 0) {
  507. errx(EXIT_FAILURE, "Failed to create client thread: %s",
  508. strerror(ret));
  509. }
  510. } else {
  511. /* Shut up GCC warnings. */
  512. memset(&client_thread, 0, sizeof(client_thread));
  513. }
  514. qemu_init_main_loop();
  515. qemu_set_fd_handler2(fd, nbd_can_accept, nbd_accept, NULL,
  516. (void *)(uintptr_t)fd);
  517. /* now when the initialization is (almost) complete, chdir("/")
  518. * to free any busy filesystems */
  519. if (chdir("/") < 0) {
  520. err(EXIT_FAILURE, "Could not chdir to root directory");
  521. }
  522. do {
  523. main_loop_wait(false);
  524. } while (!sigterm_reported && (persistent || !nbd_started || nb_fds > 0));
  525. nbd_export_close(exp);
  526. if (sockpath) {
  527. unlink(sockpath);
  528. }
  529. if (device) {
  530. void *ret;
  531. pthread_join(client_thread, &ret);
  532. exit(ret != NULL);
  533. } else {
  534. exit(EXIT_SUCCESS);
  535. }
  536. }