qemu-img.c 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718
  1. /*
  2. * QEMU disk image utility
  3. *
  4. * Copyright (c) 2003-2008 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-common.h"
  25. #include "qemu-option.h"
  26. #include "qemu-error.h"
  27. #include "osdep.h"
  28. #include "sysemu.h"
  29. #include "block_int.h"
  30. #include <stdio.h>
  31. #ifdef _WIN32
  32. #include <windows.h>
  33. #endif
  34. typedef struct img_cmd_t {
  35. const char *name;
  36. int (*handler)(int argc, char **argv);
  37. } img_cmd_t;
  38. /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
  39. #define BDRV_O_FLAGS BDRV_O_CACHE_WB
  40. #define BDRV_DEFAULT_CACHE "writeback"
  41. static void format_print(void *opaque, const char *name)
  42. {
  43. printf(" %s", name);
  44. }
  45. /* Please keep in synch with qemu-img.texi */
  46. static void help(void)
  47. {
  48. const char *help_msg =
  49. "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
  50. "usage: qemu-img command [command options]\n"
  51. "QEMU disk image utility\n"
  52. "\n"
  53. "Command syntax:\n"
  54. #define DEF(option, callback, arg_string) \
  55. " " arg_string "\n"
  56. #include "qemu-img-cmds.h"
  57. #undef DEF
  58. #undef GEN_DOCS
  59. "\n"
  60. "Command parameters:\n"
  61. " 'filename' is a disk image filename\n"
  62. " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
  63. " 'cache' is the cache mode used to write the output disk image, the valid\n"
  64. " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
  65. " 'directsync' and 'unsafe' (default for convert)\n"
  66. " 'size' is the disk image size in bytes. Optional suffixes\n"
  67. " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
  68. " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
  69. " 'output_filename' is the destination disk image filename\n"
  70. " 'output_fmt' is the destination format\n"
  71. " 'options' is a comma separated list of format specific options in a\n"
  72. " name=value format. Use -o ? for an overview of the options supported by the\n"
  73. " used format\n"
  74. " '-c' indicates that target image must be compressed (qcow format only)\n"
  75. " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
  76. " match exactly. The image doesn't need a working backing file before\n"
  77. " rebasing in this case (useful for renaming the backing file)\n"
  78. " '-h' with or without a command shows this help and lists the supported formats\n"
  79. " '-p' show progress of command (only certain commands)\n"
  80. " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
  81. " for qemu-img to create a sparse image during conversion\n"
  82. "\n"
  83. "Parameters to check subcommand:\n"
  84. " '-r' tries to repair any inconsistencies that are found during the check.\n"
  85. " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
  86. " kinds of errors, with a higher risk of choosing the wrong fix or\n"
  87. " hiding corruption that has already occurred.\n"
  88. "\n"
  89. "Parameters to snapshot subcommand:\n"
  90. " 'snapshot' is the name of the snapshot to create, apply or delete\n"
  91. " '-a' applies a snapshot (revert disk to saved state)\n"
  92. " '-c' creates a snapshot\n"
  93. " '-d' deletes a snapshot\n"
  94. " '-l' lists all snapshots in the given image\n";
  95. printf("%s\nSupported formats:", help_msg);
  96. bdrv_iterate_format(format_print, NULL);
  97. printf("\n");
  98. exit(1);
  99. }
  100. #if defined(WIN32)
  101. /* XXX: put correct support for win32 */
  102. static int read_password(char *buf, int buf_size)
  103. {
  104. int c, i;
  105. printf("Password: ");
  106. fflush(stdout);
  107. i = 0;
  108. for(;;) {
  109. c = getchar();
  110. if (c == '\n')
  111. break;
  112. if (i < (buf_size - 1))
  113. buf[i++] = c;
  114. }
  115. buf[i] = '\0';
  116. return 0;
  117. }
  118. #else
  119. #include <termios.h>
  120. static struct termios oldtty;
  121. static void term_exit(void)
  122. {
  123. tcsetattr (0, TCSANOW, &oldtty);
  124. }
  125. static void term_init(void)
  126. {
  127. struct termios tty;
  128. tcgetattr (0, &tty);
  129. oldtty = tty;
  130. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  131. |INLCR|IGNCR|ICRNL|IXON);
  132. tty.c_oflag |= OPOST;
  133. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  134. tty.c_cflag &= ~(CSIZE|PARENB);
  135. tty.c_cflag |= CS8;
  136. tty.c_cc[VMIN] = 1;
  137. tty.c_cc[VTIME] = 0;
  138. tcsetattr (0, TCSANOW, &tty);
  139. atexit(term_exit);
  140. }
  141. static int read_password(char *buf, int buf_size)
  142. {
  143. uint8_t ch;
  144. int i, ret;
  145. printf("password: ");
  146. fflush(stdout);
  147. term_init();
  148. i = 0;
  149. for(;;) {
  150. ret = read(0, &ch, 1);
  151. if (ret == -1) {
  152. if (errno == EAGAIN || errno == EINTR) {
  153. continue;
  154. } else {
  155. ret = -1;
  156. break;
  157. }
  158. } else if (ret == 0) {
  159. ret = -1;
  160. break;
  161. } else {
  162. if (ch == '\r') {
  163. ret = 0;
  164. break;
  165. }
  166. if (i < (buf_size - 1))
  167. buf[i++] = ch;
  168. }
  169. }
  170. term_exit();
  171. buf[i] = '\0';
  172. printf("\n");
  173. return ret;
  174. }
  175. #endif
  176. static int print_block_option_help(const char *filename, const char *fmt)
  177. {
  178. BlockDriver *drv, *proto_drv;
  179. QEMUOptionParameter *create_options = NULL;
  180. /* Find driver and parse its options */
  181. drv = bdrv_find_format(fmt);
  182. if (!drv) {
  183. error_report("Unknown file format '%s'", fmt);
  184. return 1;
  185. }
  186. proto_drv = bdrv_find_protocol(filename);
  187. if (!proto_drv) {
  188. error_report("Unknown protocol '%s'", filename);
  189. return 1;
  190. }
  191. create_options = append_option_parameters(create_options,
  192. drv->create_options);
  193. create_options = append_option_parameters(create_options,
  194. proto_drv->create_options);
  195. print_option_help(create_options);
  196. free_option_parameters(create_options);
  197. return 0;
  198. }
  199. static BlockDriverState *bdrv_new_open(const char *filename,
  200. const char *fmt,
  201. int flags,
  202. bool require_io)
  203. {
  204. BlockDriverState *bs;
  205. BlockDriver *drv;
  206. char password[256];
  207. int ret;
  208. bs = bdrv_new("image");
  209. if (fmt) {
  210. drv = bdrv_find_format(fmt);
  211. if (!drv) {
  212. error_report("Unknown file format '%s'", fmt);
  213. goto fail;
  214. }
  215. } else {
  216. drv = NULL;
  217. }
  218. ret = bdrv_open(bs, filename, flags, drv);
  219. if (ret < 0) {
  220. error_report("Could not open '%s': %s", filename, strerror(-ret));
  221. goto fail;
  222. }
  223. if (bdrv_is_encrypted(bs) && require_io) {
  224. printf("Disk image '%s' is encrypted.\n", filename);
  225. if (read_password(password, sizeof(password)) < 0) {
  226. error_report("No password given");
  227. goto fail;
  228. }
  229. if (bdrv_set_key(bs, password) < 0) {
  230. error_report("invalid password");
  231. goto fail;
  232. }
  233. }
  234. return bs;
  235. fail:
  236. if (bs) {
  237. bdrv_delete(bs);
  238. }
  239. return NULL;
  240. }
  241. static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
  242. const char *base_filename,
  243. const char *base_fmt)
  244. {
  245. if (base_filename) {
  246. if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
  247. error_report("Backing file not supported for file format '%s'",
  248. fmt);
  249. return -1;
  250. }
  251. }
  252. if (base_fmt) {
  253. if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
  254. error_report("Backing file format not supported for file "
  255. "format '%s'", fmt);
  256. return -1;
  257. }
  258. }
  259. return 0;
  260. }
  261. static int img_create(int argc, char **argv)
  262. {
  263. int c, ret = 0;
  264. uint64_t img_size = -1;
  265. const char *fmt = "raw";
  266. const char *base_fmt = NULL;
  267. const char *filename;
  268. const char *base_filename = NULL;
  269. char *options = NULL;
  270. for(;;) {
  271. c = getopt(argc, argv, "F:b:f:he6o:");
  272. if (c == -1) {
  273. break;
  274. }
  275. switch(c) {
  276. case '?':
  277. case 'h':
  278. help();
  279. break;
  280. case 'F':
  281. base_fmt = optarg;
  282. break;
  283. case 'b':
  284. base_filename = optarg;
  285. break;
  286. case 'f':
  287. fmt = optarg;
  288. break;
  289. case 'e':
  290. error_report("option -e is deprecated, please use \'-o "
  291. "encryption\' instead!");
  292. return 1;
  293. case '6':
  294. error_report("option -6 is deprecated, please use \'-o "
  295. "compat6\' instead!");
  296. return 1;
  297. case 'o':
  298. options = optarg;
  299. break;
  300. }
  301. }
  302. /* Get the filename */
  303. if (optind >= argc) {
  304. help();
  305. }
  306. filename = argv[optind++];
  307. /* Get image size, if specified */
  308. if (optind < argc) {
  309. int64_t sval;
  310. char *end;
  311. sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
  312. if (sval < 0 || *end) {
  313. error_report("Invalid image size specified! You may use k, M, G or "
  314. "T suffixes for ");
  315. error_report("kilobytes, megabytes, gigabytes and terabytes.");
  316. ret = -1;
  317. goto out;
  318. }
  319. img_size = (uint64_t)sval;
  320. }
  321. if (options && is_help_option(options)) {
  322. ret = print_block_option_help(filename, fmt);
  323. goto out;
  324. }
  325. ret = bdrv_img_create(filename, fmt, base_filename, base_fmt,
  326. options, img_size, BDRV_O_FLAGS);
  327. out:
  328. if (ret) {
  329. return 1;
  330. }
  331. return 0;
  332. }
  333. /*
  334. * Checks an image for consistency. Exit codes:
  335. *
  336. * 0 - Check completed, image is good
  337. * 1 - Check not completed because of internal errors
  338. * 2 - Check completed, image is corrupted
  339. * 3 - Check completed, image has leaked clusters, but is good otherwise
  340. */
  341. static int img_check(int argc, char **argv)
  342. {
  343. int c, ret;
  344. const char *filename, *fmt;
  345. BlockDriverState *bs;
  346. BdrvCheckResult result;
  347. int fix = 0;
  348. int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
  349. fmt = NULL;
  350. for(;;) {
  351. c = getopt(argc, argv, "f:hr:");
  352. if (c == -1) {
  353. break;
  354. }
  355. switch(c) {
  356. case '?':
  357. case 'h':
  358. help();
  359. break;
  360. case 'f':
  361. fmt = optarg;
  362. break;
  363. case 'r':
  364. flags |= BDRV_O_RDWR;
  365. if (!strcmp(optarg, "leaks")) {
  366. fix = BDRV_FIX_LEAKS;
  367. } else if (!strcmp(optarg, "all")) {
  368. fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
  369. } else {
  370. help();
  371. }
  372. break;
  373. }
  374. }
  375. if (optind >= argc) {
  376. help();
  377. }
  378. filename = argv[optind++];
  379. bs = bdrv_new_open(filename, fmt, flags, true);
  380. if (!bs) {
  381. return 1;
  382. }
  383. ret = bdrv_check(bs, &result, fix);
  384. if (ret == -ENOTSUP) {
  385. error_report("This image format does not support checks");
  386. bdrv_delete(bs);
  387. return 1;
  388. }
  389. if (result.corruptions_fixed || result.leaks_fixed) {
  390. printf("The following inconsistencies were found and repaired:\n\n"
  391. " %d leaked clusters\n"
  392. " %d corruptions\n\n"
  393. "Double checking the fixed image now...\n",
  394. result.leaks_fixed,
  395. result.corruptions_fixed);
  396. ret = bdrv_check(bs, &result, 0);
  397. }
  398. if (!(result.corruptions || result.leaks || result.check_errors)) {
  399. printf("No errors were found on the image.\n");
  400. } else {
  401. if (result.corruptions) {
  402. printf("\n%d errors were found on the image.\n"
  403. "Data may be corrupted, or further writes to the image "
  404. "may corrupt it.\n",
  405. result.corruptions);
  406. }
  407. if (result.leaks) {
  408. printf("\n%d leaked clusters were found on the image.\n"
  409. "This means waste of disk space, but no harm to data.\n",
  410. result.leaks);
  411. }
  412. if (result.check_errors) {
  413. printf("\n%d internal errors have occurred during the check.\n",
  414. result.check_errors);
  415. }
  416. }
  417. if (result.bfi.total_clusters != 0 && result.bfi.allocated_clusters != 0) {
  418. printf("%" PRId64 "/%" PRId64 "= %0.2f%% allocated, %0.2f%% fragmented\n",
  419. result.bfi.allocated_clusters, result.bfi.total_clusters,
  420. result.bfi.allocated_clusters * 100.0 / result.bfi.total_clusters,
  421. result.bfi.fragmented_clusters * 100.0 / result.bfi.allocated_clusters);
  422. }
  423. bdrv_delete(bs);
  424. if (ret < 0 || result.check_errors) {
  425. printf("\nAn error has occurred during the check: %s\n"
  426. "The check is not complete and may have missed error.\n",
  427. strerror(-ret));
  428. return 1;
  429. }
  430. if (result.corruptions) {
  431. return 2;
  432. } else if (result.leaks) {
  433. return 3;
  434. } else {
  435. return 0;
  436. }
  437. }
  438. static int img_commit(int argc, char **argv)
  439. {
  440. int c, ret, flags;
  441. const char *filename, *fmt, *cache;
  442. BlockDriverState *bs;
  443. fmt = NULL;
  444. cache = BDRV_DEFAULT_CACHE;
  445. for(;;) {
  446. c = getopt(argc, argv, "f:ht:");
  447. if (c == -1) {
  448. break;
  449. }
  450. switch(c) {
  451. case '?':
  452. case 'h':
  453. help();
  454. break;
  455. case 'f':
  456. fmt = optarg;
  457. break;
  458. case 't':
  459. cache = optarg;
  460. break;
  461. }
  462. }
  463. if (optind >= argc) {
  464. help();
  465. }
  466. filename = argv[optind++];
  467. flags = BDRV_O_RDWR;
  468. ret = bdrv_parse_cache_flags(cache, &flags);
  469. if (ret < 0) {
  470. error_report("Invalid cache option: %s", cache);
  471. return -1;
  472. }
  473. bs = bdrv_new_open(filename, fmt, flags, true);
  474. if (!bs) {
  475. return 1;
  476. }
  477. ret = bdrv_commit(bs);
  478. switch(ret) {
  479. case 0:
  480. printf("Image committed.\n");
  481. break;
  482. case -ENOENT:
  483. error_report("No disk inserted");
  484. break;
  485. case -EACCES:
  486. error_report("Image is read-only");
  487. break;
  488. case -ENOTSUP:
  489. error_report("Image is already committed");
  490. break;
  491. default:
  492. error_report("Error while committing image");
  493. break;
  494. }
  495. bdrv_delete(bs);
  496. if (ret) {
  497. return 1;
  498. }
  499. return 0;
  500. }
  501. /*
  502. * Returns true iff the first sector pointed to by 'buf' contains at least
  503. * a non-NUL byte.
  504. *
  505. * 'pnum' is set to the number of sectors (including and immediately following
  506. * the first one) that are known to be in the same allocated/unallocated state.
  507. */
  508. static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
  509. {
  510. bool is_zero;
  511. int i;
  512. if (n <= 0) {
  513. *pnum = 0;
  514. return 0;
  515. }
  516. is_zero = buffer_is_zero(buf, 512);
  517. for(i = 1; i < n; i++) {
  518. buf += 512;
  519. if (is_zero != buffer_is_zero(buf, 512)) {
  520. break;
  521. }
  522. }
  523. *pnum = i;
  524. return !is_zero;
  525. }
  526. /*
  527. * Like is_allocated_sectors, but if the buffer starts with a used sector,
  528. * up to 'min' consecutive sectors containing zeros are ignored. This avoids
  529. * breaking up write requests for only small sparse areas.
  530. */
  531. static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
  532. int min)
  533. {
  534. int ret;
  535. int num_checked, num_used;
  536. if (n < min) {
  537. min = n;
  538. }
  539. ret = is_allocated_sectors(buf, n, pnum);
  540. if (!ret) {
  541. return ret;
  542. }
  543. num_used = *pnum;
  544. buf += BDRV_SECTOR_SIZE * *pnum;
  545. n -= *pnum;
  546. num_checked = num_used;
  547. while (n > 0) {
  548. ret = is_allocated_sectors(buf, n, pnum);
  549. buf += BDRV_SECTOR_SIZE * *pnum;
  550. n -= *pnum;
  551. num_checked += *pnum;
  552. if (ret) {
  553. num_used = num_checked;
  554. } else if (*pnum >= min) {
  555. break;
  556. }
  557. }
  558. *pnum = num_used;
  559. return 1;
  560. }
  561. /*
  562. * Compares two buffers sector by sector. Returns 0 if the first sector of both
  563. * buffers matches, non-zero otherwise.
  564. *
  565. * pnum is set to the number of sectors (including and immediately following
  566. * the first one) that are known to have the same comparison result
  567. */
  568. static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
  569. int *pnum)
  570. {
  571. int res, i;
  572. if (n <= 0) {
  573. *pnum = 0;
  574. return 0;
  575. }
  576. res = !!memcmp(buf1, buf2, 512);
  577. for(i = 1; i < n; i++) {
  578. buf1 += 512;
  579. buf2 += 512;
  580. if (!!memcmp(buf1, buf2, 512) != res) {
  581. break;
  582. }
  583. }
  584. *pnum = i;
  585. return res;
  586. }
  587. #define IO_BUF_SIZE (2 * 1024 * 1024)
  588. static int img_convert(int argc, char **argv)
  589. {
  590. int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
  591. int progress = 0, flags;
  592. const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
  593. BlockDriver *drv, *proto_drv;
  594. BlockDriverState **bs = NULL, *out_bs = NULL;
  595. int64_t total_sectors, nb_sectors, sector_num, bs_offset;
  596. uint64_t bs_sectors;
  597. uint8_t * buf = NULL;
  598. const uint8_t *buf1;
  599. BlockDriverInfo bdi;
  600. QEMUOptionParameter *param = NULL, *create_options = NULL;
  601. QEMUOptionParameter *out_baseimg_param;
  602. char *options = NULL;
  603. const char *snapshot_name = NULL;
  604. float local_progress;
  605. int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
  606. fmt = NULL;
  607. out_fmt = "raw";
  608. cache = "unsafe";
  609. out_baseimg = NULL;
  610. compress = 0;
  611. for(;;) {
  612. c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:");
  613. if (c == -1) {
  614. break;
  615. }
  616. switch(c) {
  617. case '?':
  618. case 'h':
  619. help();
  620. break;
  621. case 'f':
  622. fmt = optarg;
  623. break;
  624. case 'O':
  625. out_fmt = optarg;
  626. break;
  627. case 'B':
  628. out_baseimg = optarg;
  629. break;
  630. case 'c':
  631. compress = 1;
  632. break;
  633. case 'e':
  634. error_report("option -e is deprecated, please use \'-o "
  635. "encryption\' instead!");
  636. return 1;
  637. case '6':
  638. error_report("option -6 is deprecated, please use \'-o "
  639. "compat6\' instead!");
  640. return 1;
  641. case 'o':
  642. options = optarg;
  643. break;
  644. case 's':
  645. snapshot_name = optarg;
  646. break;
  647. case 'S':
  648. {
  649. int64_t sval;
  650. char *end;
  651. sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
  652. if (sval < 0 || *end) {
  653. error_report("Invalid minimum zero buffer size for sparse output specified");
  654. return 1;
  655. }
  656. min_sparse = sval / BDRV_SECTOR_SIZE;
  657. break;
  658. }
  659. case 'p':
  660. progress = 1;
  661. break;
  662. case 't':
  663. cache = optarg;
  664. break;
  665. }
  666. }
  667. bs_n = argc - optind - 1;
  668. if (bs_n < 1) {
  669. help();
  670. }
  671. out_filename = argv[argc - 1];
  672. /* Initialize before goto out */
  673. qemu_progress_init(progress, 2.0);
  674. if (options && is_help_option(options)) {
  675. ret = print_block_option_help(out_filename, out_fmt);
  676. goto out;
  677. }
  678. if (bs_n > 1 && out_baseimg) {
  679. error_report("-B makes no sense when concatenating multiple input "
  680. "images");
  681. ret = -1;
  682. goto out;
  683. }
  684. qemu_progress_print(0, 100);
  685. bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
  686. total_sectors = 0;
  687. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  688. bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true);
  689. if (!bs[bs_i]) {
  690. error_report("Could not open '%s'", argv[optind + bs_i]);
  691. ret = -1;
  692. goto out;
  693. }
  694. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  695. total_sectors += bs_sectors;
  696. }
  697. if (snapshot_name != NULL) {
  698. if (bs_n > 1) {
  699. error_report("No support for concatenating multiple snapshot");
  700. ret = -1;
  701. goto out;
  702. }
  703. if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
  704. error_report("Failed to load snapshot");
  705. ret = -1;
  706. goto out;
  707. }
  708. }
  709. /* Find driver and parse its options */
  710. drv = bdrv_find_format(out_fmt);
  711. if (!drv) {
  712. error_report("Unknown file format '%s'", out_fmt);
  713. ret = -1;
  714. goto out;
  715. }
  716. proto_drv = bdrv_find_protocol(out_filename);
  717. if (!proto_drv) {
  718. error_report("Unknown protocol '%s'", out_filename);
  719. ret = -1;
  720. goto out;
  721. }
  722. create_options = append_option_parameters(create_options,
  723. drv->create_options);
  724. create_options = append_option_parameters(create_options,
  725. proto_drv->create_options);
  726. if (options) {
  727. param = parse_option_parameters(options, create_options, param);
  728. if (param == NULL) {
  729. error_report("Invalid options for file format '%s'.", out_fmt);
  730. ret = -1;
  731. goto out;
  732. }
  733. } else {
  734. param = parse_option_parameters("", create_options, param);
  735. }
  736. set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
  737. ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
  738. if (ret < 0) {
  739. goto out;
  740. }
  741. /* Get backing file name if -o backing_file was used */
  742. out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
  743. if (out_baseimg_param) {
  744. out_baseimg = out_baseimg_param->value.s;
  745. }
  746. /* Check if compression is supported */
  747. if (compress) {
  748. QEMUOptionParameter *encryption =
  749. get_option_parameter(param, BLOCK_OPT_ENCRYPT);
  750. QEMUOptionParameter *preallocation =
  751. get_option_parameter(param, BLOCK_OPT_PREALLOC);
  752. if (!drv->bdrv_write_compressed) {
  753. error_report("Compression not supported for this file format");
  754. ret = -1;
  755. goto out;
  756. }
  757. if (encryption && encryption->value.n) {
  758. error_report("Compression and encryption not supported at "
  759. "the same time");
  760. ret = -1;
  761. goto out;
  762. }
  763. if (preallocation && preallocation->value.s
  764. && strcmp(preallocation->value.s, "off"))
  765. {
  766. error_report("Compression and preallocation not supported at "
  767. "the same time");
  768. ret = -1;
  769. goto out;
  770. }
  771. }
  772. /* Create the new image */
  773. ret = bdrv_create(drv, out_filename, param);
  774. if (ret < 0) {
  775. if (ret == -ENOTSUP) {
  776. error_report("Formatting not supported for file format '%s'",
  777. out_fmt);
  778. } else if (ret == -EFBIG) {
  779. error_report("The image size is too large for file format '%s'",
  780. out_fmt);
  781. } else {
  782. error_report("%s: error while converting %s: %s",
  783. out_filename, out_fmt, strerror(-ret));
  784. }
  785. goto out;
  786. }
  787. flags = BDRV_O_RDWR;
  788. ret = bdrv_parse_cache_flags(cache, &flags);
  789. if (ret < 0) {
  790. error_report("Invalid cache option: %s", cache);
  791. return -1;
  792. }
  793. out_bs = bdrv_new_open(out_filename, out_fmt, flags, true);
  794. if (!out_bs) {
  795. ret = -1;
  796. goto out;
  797. }
  798. bs_i = 0;
  799. bs_offset = 0;
  800. bdrv_get_geometry(bs[0], &bs_sectors);
  801. buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
  802. if (compress) {
  803. ret = bdrv_get_info(out_bs, &bdi);
  804. if (ret < 0) {
  805. error_report("could not get block driver info");
  806. goto out;
  807. }
  808. cluster_size = bdi.cluster_size;
  809. if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
  810. error_report("invalid cluster size");
  811. ret = -1;
  812. goto out;
  813. }
  814. cluster_sectors = cluster_size >> 9;
  815. sector_num = 0;
  816. nb_sectors = total_sectors;
  817. local_progress = (float)100 /
  818. (nb_sectors / MIN(nb_sectors, cluster_sectors));
  819. for(;;) {
  820. int64_t bs_num;
  821. int remainder;
  822. uint8_t *buf2;
  823. nb_sectors = total_sectors - sector_num;
  824. if (nb_sectors <= 0)
  825. break;
  826. if (nb_sectors >= cluster_sectors)
  827. n = cluster_sectors;
  828. else
  829. n = nb_sectors;
  830. bs_num = sector_num - bs_offset;
  831. assert (bs_num >= 0);
  832. remainder = n;
  833. buf2 = buf;
  834. while (remainder > 0) {
  835. int nlow;
  836. while (bs_num == bs_sectors) {
  837. bs_i++;
  838. assert (bs_i < bs_n);
  839. bs_offset += bs_sectors;
  840. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  841. bs_num = 0;
  842. /* printf("changing part: sector_num=%" PRId64 ", "
  843. "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
  844. "\n", sector_num, bs_i, bs_offset, bs_sectors); */
  845. }
  846. assert (bs_num < bs_sectors);
  847. nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
  848. ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
  849. if (ret < 0) {
  850. error_report("error while reading sector %" PRId64 ": %s",
  851. bs_num, strerror(-ret));
  852. goto out;
  853. }
  854. buf2 += nlow * 512;
  855. bs_num += nlow;
  856. remainder -= nlow;
  857. }
  858. assert (remainder == 0);
  859. if (n < cluster_sectors) {
  860. memset(buf + n * 512, 0, cluster_size - n * 512);
  861. }
  862. if (!buffer_is_zero(buf, cluster_size)) {
  863. ret = bdrv_write_compressed(out_bs, sector_num, buf,
  864. cluster_sectors);
  865. if (ret != 0) {
  866. error_report("error while compressing sector %" PRId64
  867. ": %s", sector_num, strerror(-ret));
  868. goto out;
  869. }
  870. }
  871. sector_num += n;
  872. qemu_progress_print(local_progress, 100);
  873. }
  874. /* signal EOF to align */
  875. bdrv_write_compressed(out_bs, 0, NULL, 0);
  876. } else {
  877. int has_zero_init = bdrv_has_zero_init(out_bs);
  878. sector_num = 0; // total number of sectors converted so far
  879. nb_sectors = total_sectors - sector_num;
  880. local_progress = (float)100 /
  881. (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
  882. for(;;) {
  883. nb_sectors = total_sectors - sector_num;
  884. if (nb_sectors <= 0) {
  885. break;
  886. }
  887. if (nb_sectors >= (IO_BUF_SIZE / 512)) {
  888. n = (IO_BUF_SIZE / 512);
  889. } else {
  890. n = nb_sectors;
  891. }
  892. while (sector_num - bs_offset >= bs_sectors) {
  893. bs_i ++;
  894. assert (bs_i < bs_n);
  895. bs_offset += bs_sectors;
  896. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  897. /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
  898. "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
  899. sector_num, bs_i, bs_offset, bs_sectors); */
  900. }
  901. if (n > bs_offset + bs_sectors - sector_num) {
  902. n = bs_offset + bs_sectors - sector_num;
  903. }
  904. if (has_zero_init) {
  905. /* If the output image is being created as a copy on write image,
  906. assume that sectors which are unallocated in the input image
  907. are present in both the output's and input's base images (no
  908. need to copy them). */
  909. if (out_baseimg) {
  910. if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
  911. n, &n1)) {
  912. sector_num += n1;
  913. continue;
  914. }
  915. /* The next 'n1' sectors are allocated in the input image. Copy
  916. only those as they may be followed by unallocated sectors. */
  917. n = n1;
  918. }
  919. } else {
  920. n1 = n;
  921. }
  922. ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
  923. if (ret < 0) {
  924. error_report("error while reading sector %" PRId64 ": %s",
  925. sector_num - bs_offset, strerror(-ret));
  926. goto out;
  927. }
  928. /* NOTE: at the same time we convert, we do not write zero
  929. sectors to have a chance to compress the image. Ideally, we
  930. should add a specific call to have the info to go faster */
  931. buf1 = buf;
  932. while (n > 0) {
  933. /* If the output image is being created as a copy on write image,
  934. copy all sectors even the ones containing only NUL bytes,
  935. because they may differ from the sectors in the base image.
  936. If the output is to a host device, we also write out
  937. sectors that are entirely 0, since whatever data was
  938. already there is garbage, not 0s. */
  939. if (!has_zero_init || out_baseimg ||
  940. is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
  941. ret = bdrv_write(out_bs, sector_num, buf1, n1);
  942. if (ret < 0) {
  943. error_report("error while writing sector %" PRId64
  944. ": %s", sector_num, strerror(-ret));
  945. goto out;
  946. }
  947. }
  948. sector_num += n1;
  949. n -= n1;
  950. buf1 += n1 * 512;
  951. }
  952. qemu_progress_print(local_progress, 100);
  953. }
  954. }
  955. out:
  956. qemu_progress_end();
  957. free_option_parameters(create_options);
  958. free_option_parameters(param);
  959. qemu_vfree(buf);
  960. if (out_bs) {
  961. bdrv_delete(out_bs);
  962. }
  963. if (bs) {
  964. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  965. if (bs[bs_i]) {
  966. bdrv_delete(bs[bs_i]);
  967. }
  968. }
  969. g_free(bs);
  970. }
  971. if (ret) {
  972. return 1;
  973. }
  974. return 0;
  975. }
  976. static void dump_snapshots(BlockDriverState *bs)
  977. {
  978. QEMUSnapshotInfo *sn_tab, *sn;
  979. int nb_sns, i;
  980. char buf[256];
  981. nb_sns = bdrv_snapshot_list(bs, &sn_tab);
  982. if (nb_sns <= 0)
  983. return;
  984. printf("Snapshot list:\n");
  985. printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
  986. for(i = 0; i < nb_sns; i++) {
  987. sn = &sn_tab[i];
  988. printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
  989. }
  990. g_free(sn_tab);
  991. }
  992. static int img_info(int argc, char **argv)
  993. {
  994. int c;
  995. const char *filename, *fmt;
  996. BlockDriverState *bs;
  997. char size_buf[128], dsize_buf[128];
  998. uint64_t total_sectors;
  999. int64_t allocated_size;
  1000. char backing_filename[1024];
  1001. char backing_filename2[1024];
  1002. BlockDriverInfo bdi;
  1003. fmt = NULL;
  1004. for(;;) {
  1005. c = getopt(argc, argv, "f:h");
  1006. if (c == -1) {
  1007. break;
  1008. }
  1009. switch(c) {
  1010. case '?':
  1011. case 'h':
  1012. help();
  1013. break;
  1014. case 'f':
  1015. fmt = optarg;
  1016. break;
  1017. }
  1018. }
  1019. if (optind >= argc) {
  1020. help();
  1021. }
  1022. filename = argv[optind++];
  1023. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING, false);
  1024. if (!bs) {
  1025. return 1;
  1026. }
  1027. bdrv_get_geometry(bs, &total_sectors);
  1028. get_human_readable_size(size_buf, sizeof(size_buf), total_sectors * 512);
  1029. allocated_size = bdrv_get_allocated_file_size(bs);
  1030. if (allocated_size < 0) {
  1031. snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
  1032. } else {
  1033. get_human_readable_size(dsize_buf, sizeof(dsize_buf),
  1034. allocated_size);
  1035. }
  1036. printf("image: %s\n"
  1037. "file format: %s\n"
  1038. "virtual size: %s (%" PRId64 " bytes)\n"
  1039. "disk size: %s\n",
  1040. filename, bdrv_get_format_name(bs), size_buf,
  1041. (total_sectors * 512),
  1042. dsize_buf);
  1043. if (bdrv_is_encrypted(bs)) {
  1044. printf("encrypted: yes\n");
  1045. }
  1046. if (bdrv_get_info(bs, &bdi) >= 0) {
  1047. if (bdi.cluster_size != 0) {
  1048. printf("cluster_size: %d\n", bdi.cluster_size);
  1049. }
  1050. if (bdi.is_dirty) {
  1051. printf("cleanly shut down: no\n");
  1052. }
  1053. }
  1054. bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
  1055. if (backing_filename[0] != '\0') {
  1056. bdrv_get_full_backing_filename(bs, backing_filename2,
  1057. sizeof(backing_filename2));
  1058. printf("backing file: %s", backing_filename);
  1059. if (strcmp(backing_filename, backing_filename2) != 0) {
  1060. printf(" (actual path: %s)", backing_filename2);
  1061. }
  1062. putchar('\n');
  1063. }
  1064. dump_snapshots(bs);
  1065. bdrv_delete(bs);
  1066. return 0;
  1067. }
  1068. #define SNAPSHOT_LIST 1
  1069. #define SNAPSHOT_CREATE 2
  1070. #define SNAPSHOT_APPLY 3
  1071. #define SNAPSHOT_DELETE 4
  1072. static int img_snapshot(int argc, char **argv)
  1073. {
  1074. BlockDriverState *bs;
  1075. QEMUSnapshotInfo sn;
  1076. char *filename, *snapshot_name = NULL;
  1077. int c, ret = 0, bdrv_oflags;
  1078. int action = 0;
  1079. qemu_timeval tv;
  1080. bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
  1081. /* Parse commandline parameters */
  1082. for(;;) {
  1083. c = getopt(argc, argv, "la:c:d:h");
  1084. if (c == -1) {
  1085. break;
  1086. }
  1087. switch(c) {
  1088. case '?':
  1089. case 'h':
  1090. help();
  1091. return 0;
  1092. case 'l':
  1093. if (action) {
  1094. help();
  1095. return 0;
  1096. }
  1097. action = SNAPSHOT_LIST;
  1098. bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
  1099. break;
  1100. case 'a':
  1101. if (action) {
  1102. help();
  1103. return 0;
  1104. }
  1105. action = SNAPSHOT_APPLY;
  1106. snapshot_name = optarg;
  1107. break;
  1108. case 'c':
  1109. if (action) {
  1110. help();
  1111. return 0;
  1112. }
  1113. action = SNAPSHOT_CREATE;
  1114. snapshot_name = optarg;
  1115. break;
  1116. case 'd':
  1117. if (action) {
  1118. help();
  1119. return 0;
  1120. }
  1121. action = SNAPSHOT_DELETE;
  1122. snapshot_name = optarg;
  1123. break;
  1124. }
  1125. }
  1126. if (optind >= argc) {
  1127. help();
  1128. }
  1129. filename = argv[optind++];
  1130. /* Open the image */
  1131. bs = bdrv_new_open(filename, NULL, bdrv_oflags, true);
  1132. if (!bs) {
  1133. return 1;
  1134. }
  1135. /* Perform the requested action */
  1136. switch(action) {
  1137. case SNAPSHOT_LIST:
  1138. dump_snapshots(bs);
  1139. break;
  1140. case SNAPSHOT_CREATE:
  1141. memset(&sn, 0, sizeof(sn));
  1142. pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
  1143. qemu_gettimeofday(&tv);
  1144. sn.date_sec = tv.tv_sec;
  1145. sn.date_nsec = tv.tv_usec * 1000;
  1146. ret = bdrv_snapshot_create(bs, &sn);
  1147. if (ret) {
  1148. error_report("Could not create snapshot '%s': %d (%s)",
  1149. snapshot_name, ret, strerror(-ret));
  1150. }
  1151. break;
  1152. case SNAPSHOT_APPLY:
  1153. ret = bdrv_snapshot_goto(bs, snapshot_name);
  1154. if (ret) {
  1155. error_report("Could not apply snapshot '%s': %d (%s)",
  1156. snapshot_name, ret, strerror(-ret));
  1157. }
  1158. break;
  1159. case SNAPSHOT_DELETE:
  1160. ret = bdrv_snapshot_delete(bs, snapshot_name);
  1161. if (ret) {
  1162. error_report("Could not delete snapshot '%s': %d (%s)",
  1163. snapshot_name, ret, strerror(-ret));
  1164. }
  1165. break;
  1166. }
  1167. /* Cleanup */
  1168. bdrv_delete(bs);
  1169. if (ret) {
  1170. return 1;
  1171. }
  1172. return 0;
  1173. }
  1174. static int img_rebase(int argc, char **argv)
  1175. {
  1176. BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
  1177. BlockDriver *old_backing_drv, *new_backing_drv;
  1178. char *filename;
  1179. const char *fmt, *cache, *out_basefmt, *out_baseimg;
  1180. int c, flags, ret;
  1181. int unsafe = 0;
  1182. int progress = 0;
  1183. /* Parse commandline parameters */
  1184. fmt = NULL;
  1185. cache = BDRV_DEFAULT_CACHE;
  1186. out_baseimg = NULL;
  1187. out_basefmt = NULL;
  1188. for(;;) {
  1189. c = getopt(argc, argv, "uhf:F:b:pt:");
  1190. if (c == -1) {
  1191. break;
  1192. }
  1193. switch(c) {
  1194. case '?':
  1195. case 'h':
  1196. help();
  1197. return 0;
  1198. case 'f':
  1199. fmt = optarg;
  1200. break;
  1201. case 'F':
  1202. out_basefmt = optarg;
  1203. break;
  1204. case 'b':
  1205. out_baseimg = optarg;
  1206. break;
  1207. case 'u':
  1208. unsafe = 1;
  1209. break;
  1210. case 'p':
  1211. progress = 1;
  1212. break;
  1213. case 't':
  1214. cache = optarg;
  1215. break;
  1216. }
  1217. }
  1218. if ((optind >= argc) || (!unsafe && !out_baseimg)) {
  1219. help();
  1220. }
  1221. filename = argv[optind++];
  1222. qemu_progress_init(progress, 2.0);
  1223. qemu_progress_print(0, 100);
  1224. flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
  1225. ret = bdrv_parse_cache_flags(cache, &flags);
  1226. if (ret < 0) {
  1227. error_report("Invalid cache option: %s", cache);
  1228. return -1;
  1229. }
  1230. /*
  1231. * Open the images.
  1232. *
  1233. * Ignore the old backing file for unsafe rebase in case we want to correct
  1234. * the reference to a renamed or moved backing file.
  1235. */
  1236. bs = bdrv_new_open(filename, fmt, flags, true);
  1237. if (!bs) {
  1238. return 1;
  1239. }
  1240. /* Find the right drivers for the backing files */
  1241. old_backing_drv = NULL;
  1242. new_backing_drv = NULL;
  1243. if (!unsafe && bs->backing_format[0] != '\0') {
  1244. old_backing_drv = bdrv_find_format(bs->backing_format);
  1245. if (old_backing_drv == NULL) {
  1246. error_report("Invalid format name: '%s'", bs->backing_format);
  1247. ret = -1;
  1248. goto out;
  1249. }
  1250. }
  1251. if (out_basefmt != NULL) {
  1252. new_backing_drv = bdrv_find_format(out_basefmt);
  1253. if (new_backing_drv == NULL) {
  1254. error_report("Invalid format name: '%s'", out_basefmt);
  1255. ret = -1;
  1256. goto out;
  1257. }
  1258. }
  1259. /* For safe rebasing we need to compare old and new backing file */
  1260. if (unsafe) {
  1261. /* Make the compiler happy */
  1262. bs_old_backing = NULL;
  1263. bs_new_backing = NULL;
  1264. } else {
  1265. char backing_name[1024];
  1266. bs_old_backing = bdrv_new("old_backing");
  1267. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  1268. ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
  1269. old_backing_drv);
  1270. if (ret) {
  1271. error_report("Could not open old backing file '%s'", backing_name);
  1272. goto out;
  1273. }
  1274. bs_new_backing = bdrv_new("new_backing");
  1275. ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
  1276. new_backing_drv);
  1277. if (ret) {
  1278. error_report("Could not open new backing file '%s'", out_baseimg);
  1279. goto out;
  1280. }
  1281. }
  1282. /*
  1283. * Check each unallocated cluster in the COW file. If it is unallocated,
  1284. * accesses go to the backing file. We must therefore compare this cluster
  1285. * in the old and new backing file, and if they differ we need to copy it
  1286. * from the old backing file into the COW file.
  1287. *
  1288. * If qemu-img crashes during this step, no harm is done. The content of
  1289. * the image is the same as the original one at any time.
  1290. */
  1291. if (!unsafe) {
  1292. uint64_t num_sectors;
  1293. uint64_t old_backing_num_sectors;
  1294. uint64_t new_backing_num_sectors;
  1295. uint64_t sector;
  1296. int n;
  1297. uint8_t * buf_old;
  1298. uint8_t * buf_new;
  1299. float local_progress;
  1300. buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
  1301. buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
  1302. bdrv_get_geometry(bs, &num_sectors);
  1303. bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
  1304. bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
  1305. local_progress = (float)100 /
  1306. (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
  1307. for (sector = 0; sector < num_sectors; sector += n) {
  1308. /* How many sectors can we handle with the next read? */
  1309. if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
  1310. n = (IO_BUF_SIZE / 512);
  1311. } else {
  1312. n = num_sectors - sector;
  1313. }
  1314. /* If the cluster is allocated, we don't need to take action */
  1315. ret = bdrv_is_allocated(bs, sector, n, &n);
  1316. if (ret) {
  1317. continue;
  1318. }
  1319. /*
  1320. * Read old and new backing file and take into consideration that
  1321. * backing files may be smaller than the COW image.
  1322. */
  1323. if (sector >= old_backing_num_sectors) {
  1324. memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
  1325. } else {
  1326. if (sector + n > old_backing_num_sectors) {
  1327. n = old_backing_num_sectors - sector;
  1328. }
  1329. ret = bdrv_read(bs_old_backing, sector, buf_old, n);
  1330. if (ret < 0) {
  1331. error_report("error while reading from old backing file");
  1332. goto out;
  1333. }
  1334. }
  1335. if (sector >= new_backing_num_sectors) {
  1336. memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
  1337. } else {
  1338. if (sector + n > new_backing_num_sectors) {
  1339. n = new_backing_num_sectors - sector;
  1340. }
  1341. ret = bdrv_read(bs_new_backing, sector, buf_new, n);
  1342. if (ret < 0) {
  1343. error_report("error while reading from new backing file");
  1344. goto out;
  1345. }
  1346. }
  1347. /* If they differ, we need to write to the COW file */
  1348. uint64_t written = 0;
  1349. while (written < n) {
  1350. int pnum;
  1351. if (compare_sectors(buf_old + written * 512,
  1352. buf_new + written * 512, n - written, &pnum))
  1353. {
  1354. ret = bdrv_write(bs, sector + written,
  1355. buf_old + written * 512, pnum);
  1356. if (ret < 0) {
  1357. error_report("Error while writing to COW image: %s",
  1358. strerror(-ret));
  1359. goto out;
  1360. }
  1361. }
  1362. written += pnum;
  1363. }
  1364. qemu_progress_print(local_progress, 100);
  1365. }
  1366. qemu_vfree(buf_old);
  1367. qemu_vfree(buf_new);
  1368. }
  1369. /*
  1370. * Change the backing file. All clusters that are different from the old
  1371. * backing file are overwritten in the COW file now, so the visible content
  1372. * doesn't change when we switch the backing file.
  1373. */
  1374. ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
  1375. if (ret == -ENOSPC) {
  1376. error_report("Could not change the backing file to '%s': No "
  1377. "space left in the file header", out_baseimg);
  1378. } else if (ret < 0) {
  1379. error_report("Could not change the backing file to '%s': %s",
  1380. out_baseimg, strerror(-ret));
  1381. }
  1382. qemu_progress_print(100, 0);
  1383. /*
  1384. * TODO At this point it is possible to check if any clusters that are
  1385. * allocated in the COW file are the same in the backing file. If so, they
  1386. * could be dropped from the COW file. Don't do this before switching the
  1387. * backing file, in case of a crash this would lead to corruption.
  1388. */
  1389. out:
  1390. qemu_progress_end();
  1391. /* Cleanup */
  1392. if (!unsafe) {
  1393. if (bs_old_backing != NULL) {
  1394. bdrv_delete(bs_old_backing);
  1395. }
  1396. if (bs_new_backing != NULL) {
  1397. bdrv_delete(bs_new_backing);
  1398. }
  1399. }
  1400. bdrv_delete(bs);
  1401. if (ret) {
  1402. return 1;
  1403. }
  1404. return 0;
  1405. }
  1406. static int img_resize(int argc, char **argv)
  1407. {
  1408. int c, ret, relative;
  1409. const char *filename, *fmt, *size;
  1410. int64_t n, total_size;
  1411. BlockDriverState *bs = NULL;
  1412. QemuOpts *param;
  1413. static QemuOptsList resize_options = {
  1414. .name = "resize_options",
  1415. .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
  1416. .desc = {
  1417. {
  1418. .name = BLOCK_OPT_SIZE,
  1419. .type = QEMU_OPT_SIZE,
  1420. .help = "Virtual disk size"
  1421. }, {
  1422. /* end of list */
  1423. }
  1424. },
  1425. };
  1426. /* Remove size from argv manually so that negative numbers are not treated
  1427. * as options by getopt. */
  1428. if (argc < 3) {
  1429. help();
  1430. return 1;
  1431. }
  1432. size = argv[--argc];
  1433. /* Parse getopt arguments */
  1434. fmt = NULL;
  1435. for(;;) {
  1436. c = getopt(argc, argv, "f:h");
  1437. if (c == -1) {
  1438. break;
  1439. }
  1440. switch(c) {
  1441. case '?':
  1442. case 'h':
  1443. help();
  1444. break;
  1445. case 'f':
  1446. fmt = optarg;
  1447. break;
  1448. }
  1449. }
  1450. if (optind >= argc) {
  1451. help();
  1452. }
  1453. filename = argv[optind++];
  1454. /* Choose grow, shrink, or absolute resize mode */
  1455. switch (size[0]) {
  1456. case '+':
  1457. relative = 1;
  1458. size++;
  1459. break;
  1460. case '-':
  1461. relative = -1;
  1462. size++;
  1463. break;
  1464. default:
  1465. relative = 0;
  1466. break;
  1467. }
  1468. /* Parse size */
  1469. param = qemu_opts_create(&resize_options, NULL, 0, NULL);
  1470. if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
  1471. /* Error message already printed when size parsing fails */
  1472. ret = -1;
  1473. qemu_opts_del(param);
  1474. goto out;
  1475. }
  1476. n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
  1477. qemu_opts_del(param);
  1478. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true);
  1479. if (!bs) {
  1480. ret = -1;
  1481. goto out;
  1482. }
  1483. if (relative) {
  1484. total_size = bdrv_getlength(bs) + n * relative;
  1485. } else {
  1486. total_size = n;
  1487. }
  1488. if (total_size <= 0) {
  1489. error_report("New image size must be positive");
  1490. ret = -1;
  1491. goto out;
  1492. }
  1493. ret = bdrv_truncate(bs, total_size);
  1494. switch (ret) {
  1495. case 0:
  1496. printf("Image resized.\n");
  1497. break;
  1498. case -ENOTSUP:
  1499. error_report("This image does not support resize");
  1500. break;
  1501. case -EACCES:
  1502. error_report("Image is read-only");
  1503. break;
  1504. default:
  1505. error_report("Error resizing image (%d)", -ret);
  1506. break;
  1507. }
  1508. out:
  1509. if (bs) {
  1510. bdrv_delete(bs);
  1511. }
  1512. if (ret) {
  1513. return 1;
  1514. }
  1515. return 0;
  1516. }
  1517. static const img_cmd_t img_cmds[] = {
  1518. #define DEF(option, callback, arg_string) \
  1519. { option, callback },
  1520. #include "qemu-img-cmds.h"
  1521. #undef DEF
  1522. #undef GEN_DOCS
  1523. { NULL, NULL, },
  1524. };
  1525. int main(int argc, char **argv)
  1526. {
  1527. const img_cmd_t *cmd;
  1528. const char *cmdname;
  1529. error_set_progname(argv[0]);
  1530. qemu_init_main_loop();
  1531. bdrv_init();
  1532. if (argc < 2)
  1533. help();
  1534. cmdname = argv[1];
  1535. argc--; argv++;
  1536. /* find the command */
  1537. for(cmd = img_cmds; cmd->name != NULL; cmd++) {
  1538. if (!strcmp(cmdname, cmd->name)) {
  1539. return cmd->handler(argc, argv);
  1540. }
  1541. }
  1542. /* not found */
  1543. help();
  1544. return 0;
  1545. }