qemu-img.c 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486
  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 "qapi-visit.h"
  25. #include "qapi/qmp-output-visitor.h"
  26. #include "qapi/qmp/qjson.h"
  27. #include "qemu-common.h"
  28. #include "qemu/option.h"
  29. #include "qemu/error-report.h"
  30. #include "qemu/osdep.h"
  31. #include "sysemu/sysemu.h"
  32. #include "block/block_int.h"
  33. #include <getopt.h>
  34. #include <stdio.h>
  35. #include <stdarg.h>
  36. #ifdef _WIN32
  37. #include <windows.h>
  38. #endif
  39. typedef struct img_cmd_t {
  40. const char *name;
  41. int (*handler)(int argc, char **argv);
  42. } img_cmd_t;
  43. enum {
  44. OPTION_OUTPUT = 256,
  45. OPTION_BACKING_CHAIN = 257,
  46. };
  47. typedef enum OutputFormat {
  48. OFORMAT_JSON,
  49. OFORMAT_HUMAN,
  50. } OutputFormat;
  51. /* Default to cache=writeback as data integrity is not important for qemu-tcg. */
  52. #define BDRV_O_FLAGS BDRV_O_CACHE_WB
  53. #define BDRV_DEFAULT_CACHE "writeback"
  54. static void format_print(void *opaque, const char *name)
  55. {
  56. printf(" %s", name);
  57. }
  58. /* Please keep in synch with qemu-img.texi */
  59. static void help(void)
  60. {
  61. const char *help_msg =
  62. "qemu-img version " QEMU_VERSION ", Copyright (c) 2004-2008 Fabrice Bellard\n"
  63. "usage: qemu-img command [command options]\n"
  64. "QEMU disk image utility\n"
  65. "\n"
  66. "Command syntax:\n"
  67. #define DEF(option, callback, arg_string) \
  68. " " arg_string "\n"
  69. #include "qemu-img-cmds.h"
  70. #undef DEF
  71. #undef GEN_DOCS
  72. "\n"
  73. "Command parameters:\n"
  74. " 'filename' is a disk image filename\n"
  75. " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
  76. " 'cache' is the cache mode used to write the output disk image, the valid\n"
  77. " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
  78. " 'directsync' and 'unsafe' (default for convert)\n"
  79. " 'size' is the disk image size in bytes. Optional suffixes\n"
  80. " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M)\n"
  81. " and T (terabyte, 1024G) are supported. 'b' is ignored.\n"
  82. " 'output_filename' is the destination disk image filename\n"
  83. " 'output_fmt' is the destination format\n"
  84. " 'options' is a comma separated list of format specific options in a\n"
  85. " name=value format. Use -o ? for an overview of the options supported by the\n"
  86. " used format\n"
  87. " '-c' indicates that target image must be compressed (qcow format only)\n"
  88. " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
  89. " match exactly. The image doesn't need a working backing file before\n"
  90. " rebasing in this case (useful for renaming the backing file)\n"
  91. " '-h' with or without a command shows this help and lists the supported formats\n"
  92. " '-p' show progress of command (only certain commands)\n"
  93. " '-q' use Quiet mode - do not print any output (except errors)\n"
  94. " '-S' indicates the consecutive number of bytes that must contain only zeros\n"
  95. " for qemu-img to create a sparse image during conversion\n"
  96. " '--output' takes the format in which the output must be done (human or json)\n"
  97. "\n"
  98. "Parameters to check subcommand:\n"
  99. " '-r' tries to repair any inconsistencies that are found during the check.\n"
  100. " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
  101. " kinds of errors, with a higher risk of choosing the wrong fix or\n"
  102. " hiding corruption that has already occurred.\n"
  103. "\n"
  104. "Parameters to snapshot subcommand:\n"
  105. " 'snapshot' is the name of the snapshot to create, apply or delete\n"
  106. " '-a' applies a snapshot (revert disk to saved state)\n"
  107. " '-c' creates a snapshot\n"
  108. " '-d' deletes a snapshot\n"
  109. " '-l' lists all snapshots in the given image\n"
  110. "\n"
  111. "Parameters to compare subcommand:\n"
  112. " '-f' first image format\n"
  113. " '-F' second image format\n"
  114. " '-s' run in Strict mode - fail on different image size or sector allocation\n";
  115. printf("%s\nSupported formats:", help_msg);
  116. bdrv_iterate_format(format_print, NULL);
  117. printf("\n");
  118. exit(1);
  119. }
  120. static int qprintf(bool quiet, const char *fmt, ...)
  121. {
  122. int ret = 0;
  123. if (!quiet) {
  124. va_list args;
  125. va_start(args, fmt);
  126. ret = vprintf(fmt, args);
  127. va_end(args);
  128. }
  129. return ret;
  130. }
  131. #if defined(WIN32)
  132. /* XXX: put correct support for win32 */
  133. static int read_password(char *buf, int buf_size)
  134. {
  135. int c, i;
  136. printf("Password: ");
  137. fflush(stdout);
  138. i = 0;
  139. for(;;) {
  140. c = getchar();
  141. if (c == '\n')
  142. break;
  143. if (i < (buf_size - 1))
  144. buf[i++] = c;
  145. }
  146. buf[i] = '\0';
  147. return 0;
  148. }
  149. #else
  150. #include <termios.h>
  151. static struct termios oldtty;
  152. static void term_exit(void)
  153. {
  154. tcsetattr (0, TCSANOW, &oldtty);
  155. }
  156. static void term_init(void)
  157. {
  158. struct termios tty;
  159. tcgetattr (0, &tty);
  160. oldtty = tty;
  161. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  162. |INLCR|IGNCR|ICRNL|IXON);
  163. tty.c_oflag |= OPOST;
  164. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  165. tty.c_cflag &= ~(CSIZE|PARENB);
  166. tty.c_cflag |= CS8;
  167. tty.c_cc[VMIN] = 1;
  168. tty.c_cc[VTIME] = 0;
  169. tcsetattr (0, TCSANOW, &tty);
  170. atexit(term_exit);
  171. }
  172. static int read_password(char *buf, int buf_size)
  173. {
  174. uint8_t ch;
  175. int i, ret;
  176. printf("password: ");
  177. fflush(stdout);
  178. term_init();
  179. i = 0;
  180. for(;;) {
  181. ret = read(0, &ch, 1);
  182. if (ret == -1) {
  183. if (errno == EAGAIN || errno == EINTR) {
  184. continue;
  185. } else {
  186. ret = -1;
  187. break;
  188. }
  189. } else if (ret == 0) {
  190. ret = -1;
  191. break;
  192. } else {
  193. if (ch == '\r') {
  194. ret = 0;
  195. break;
  196. }
  197. if (i < (buf_size - 1))
  198. buf[i++] = ch;
  199. }
  200. }
  201. term_exit();
  202. buf[i] = '\0';
  203. printf("\n");
  204. return ret;
  205. }
  206. #endif
  207. static int print_block_option_help(const char *filename, const char *fmt)
  208. {
  209. BlockDriver *drv, *proto_drv;
  210. QEMUOptionParameter *create_options = NULL;
  211. /* Find driver and parse its options */
  212. drv = bdrv_find_format(fmt);
  213. if (!drv) {
  214. error_report("Unknown file format '%s'", fmt);
  215. return 1;
  216. }
  217. proto_drv = bdrv_find_protocol(filename);
  218. if (!proto_drv) {
  219. error_report("Unknown protocol '%s'", filename);
  220. return 1;
  221. }
  222. create_options = append_option_parameters(create_options,
  223. drv->create_options);
  224. create_options = append_option_parameters(create_options,
  225. proto_drv->create_options);
  226. print_option_help(create_options);
  227. free_option_parameters(create_options);
  228. return 0;
  229. }
  230. static BlockDriverState *bdrv_new_open(const char *filename,
  231. const char *fmt,
  232. int flags,
  233. bool require_io,
  234. bool quiet)
  235. {
  236. BlockDriverState *bs;
  237. BlockDriver *drv;
  238. char password[256];
  239. int ret;
  240. bs = bdrv_new("image");
  241. if (fmt) {
  242. drv = bdrv_find_format(fmt);
  243. if (!drv) {
  244. error_report("Unknown file format '%s'", fmt);
  245. goto fail;
  246. }
  247. } else {
  248. drv = NULL;
  249. }
  250. ret = bdrv_open(bs, filename, flags, drv);
  251. if (ret < 0) {
  252. error_report("Could not open '%s': %s", filename, strerror(-ret));
  253. goto fail;
  254. }
  255. if (bdrv_is_encrypted(bs) && require_io) {
  256. qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
  257. if (read_password(password, sizeof(password)) < 0) {
  258. error_report("No password given");
  259. goto fail;
  260. }
  261. if (bdrv_set_key(bs, password) < 0) {
  262. error_report("invalid password");
  263. goto fail;
  264. }
  265. }
  266. return bs;
  267. fail:
  268. if (bs) {
  269. bdrv_delete(bs);
  270. }
  271. return NULL;
  272. }
  273. static int add_old_style_options(const char *fmt, QEMUOptionParameter *list,
  274. const char *base_filename,
  275. const char *base_fmt)
  276. {
  277. if (base_filename) {
  278. if (set_option_parameter(list, BLOCK_OPT_BACKING_FILE, base_filename)) {
  279. error_report("Backing file not supported for file format '%s'",
  280. fmt);
  281. return -1;
  282. }
  283. }
  284. if (base_fmt) {
  285. if (set_option_parameter(list, BLOCK_OPT_BACKING_FMT, base_fmt)) {
  286. error_report("Backing file format not supported for file "
  287. "format '%s'", fmt);
  288. return -1;
  289. }
  290. }
  291. return 0;
  292. }
  293. static int img_create(int argc, char **argv)
  294. {
  295. int c;
  296. uint64_t img_size = -1;
  297. const char *fmt = "raw";
  298. const char *base_fmt = NULL;
  299. const char *filename;
  300. const char *base_filename = NULL;
  301. char *options = NULL;
  302. Error *local_err = NULL;
  303. bool quiet = false;
  304. for(;;) {
  305. c = getopt(argc, argv, "F:b:f:he6o:q");
  306. if (c == -1) {
  307. break;
  308. }
  309. switch(c) {
  310. case '?':
  311. case 'h':
  312. help();
  313. break;
  314. case 'F':
  315. base_fmt = optarg;
  316. break;
  317. case 'b':
  318. base_filename = optarg;
  319. break;
  320. case 'f':
  321. fmt = optarg;
  322. break;
  323. case 'e':
  324. error_report("option -e is deprecated, please use \'-o "
  325. "encryption\' instead!");
  326. return 1;
  327. case '6':
  328. error_report("option -6 is deprecated, please use \'-o "
  329. "compat6\' instead!");
  330. return 1;
  331. case 'o':
  332. options = optarg;
  333. break;
  334. case 'q':
  335. quiet = true;
  336. break;
  337. }
  338. }
  339. /* Get the filename */
  340. if (optind >= argc) {
  341. help();
  342. }
  343. filename = argv[optind++];
  344. /* Get image size, if specified */
  345. if (optind < argc) {
  346. int64_t sval;
  347. char *end;
  348. sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
  349. if (sval < 0 || *end) {
  350. if (sval == -ERANGE) {
  351. error_report("Image size must be less than 8 EiB!");
  352. } else {
  353. error_report("Invalid image size specified! You may use k, M, "
  354. "G or T suffixes for ");
  355. error_report("kilobytes, megabytes, gigabytes and terabytes.");
  356. }
  357. return 1;
  358. }
  359. img_size = (uint64_t)sval;
  360. }
  361. if (options && is_help_option(options)) {
  362. return print_block_option_help(filename, fmt);
  363. }
  364. bdrv_img_create(filename, fmt, base_filename, base_fmt,
  365. options, img_size, BDRV_O_FLAGS, &local_err, quiet);
  366. if (error_is_set(&local_err)) {
  367. error_report("%s", error_get_pretty(local_err));
  368. error_free(local_err);
  369. return 1;
  370. }
  371. return 0;
  372. }
  373. static void dump_json_image_check(ImageCheck *check, bool quiet)
  374. {
  375. Error *errp = NULL;
  376. QString *str;
  377. QmpOutputVisitor *ov = qmp_output_visitor_new();
  378. QObject *obj;
  379. visit_type_ImageCheck(qmp_output_get_visitor(ov),
  380. &check, NULL, &errp);
  381. obj = qmp_output_get_qobject(ov);
  382. str = qobject_to_json_pretty(obj);
  383. assert(str != NULL);
  384. qprintf(quiet, "%s\n", qstring_get_str(str));
  385. qobject_decref(obj);
  386. qmp_output_visitor_cleanup(ov);
  387. QDECREF(str);
  388. }
  389. static void dump_human_image_check(ImageCheck *check, bool quiet)
  390. {
  391. if (!(check->corruptions || check->leaks || check->check_errors)) {
  392. qprintf(quiet, "No errors were found on the image.\n");
  393. } else {
  394. if (check->corruptions) {
  395. qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
  396. "Data may be corrupted, or further writes to the image "
  397. "may corrupt it.\n",
  398. check->corruptions);
  399. }
  400. if (check->leaks) {
  401. qprintf(quiet,
  402. "\n%" PRId64 " leaked clusters were found on the image.\n"
  403. "This means waste of disk space, but no harm to data.\n",
  404. check->leaks);
  405. }
  406. if (check->check_errors) {
  407. qprintf(quiet,
  408. "\n%" PRId64
  409. " internal errors have occurred during the check.\n",
  410. check->check_errors);
  411. }
  412. }
  413. if (check->total_clusters != 0 && check->allocated_clusters != 0) {
  414. qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
  415. "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
  416. check->allocated_clusters, check->total_clusters,
  417. check->allocated_clusters * 100.0 / check->total_clusters,
  418. check->fragmented_clusters * 100.0 / check->allocated_clusters,
  419. check->compressed_clusters * 100.0 /
  420. check->allocated_clusters);
  421. }
  422. if (check->image_end_offset) {
  423. qprintf(quiet,
  424. "Image end offset: %" PRId64 "\n", check->image_end_offset);
  425. }
  426. }
  427. static int collect_image_check(BlockDriverState *bs,
  428. ImageCheck *check,
  429. const char *filename,
  430. const char *fmt,
  431. int fix)
  432. {
  433. int ret;
  434. BdrvCheckResult result;
  435. ret = bdrv_check(bs, &result, fix);
  436. if (ret < 0) {
  437. return ret;
  438. }
  439. check->filename = g_strdup(filename);
  440. check->format = g_strdup(bdrv_get_format_name(bs));
  441. check->check_errors = result.check_errors;
  442. check->corruptions = result.corruptions;
  443. check->has_corruptions = result.corruptions != 0;
  444. check->leaks = result.leaks;
  445. check->has_leaks = result.leaks != 0;
  446. check->corruptions_fixed = result.corruptions_fixed;
  447. check->has_corruptions_fixed = result.corruptions != 0;
  448. check->leaks_fixed = result.leaks_fixed;
  449. check->has_leaks_fixed = result.leaks != 0;
  450. check->image_end_offset = result.image_end_offset;
  451. check->has_image_end_offset = result.image_end_offset != 0;
  452. check->total_clusters = result.bfi.total_clusters;
  453. check->has_total_clusters = result.bfi.total_clusters != 0;
  454. check->allocated_clusters = result.bfi.allocated_clusters;
  455. check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
  456. check->fragmented_clusters = result.bfi.fragmented_clusters;
  457. check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
  458. check->compressed_clusters = result.bfi.compressed_clusters;
  459. check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
  460. return 0;
  461. }
  462. /*
  463. * Checks an image for consistency. Exit codes:
  464. *
  465. * 0 - Check completed, image is good
  466. * 1 - Check not completed because of internal errors
  467. * 2 - Check completed, image is corrupted
  468. * 3 - Check completed, image has leaked clusters, but is good otherwise
  469. */
  470. static int img_check(int argc, char **argv)
  471. {
  472. int c, ret;
  473. OutputFormat output_format = OFORMAT_HUMAN;
  474. const char *filename, *fmt, *output;
  475. BlockDriverState *bs;
  476. int fix = 0;
  477. int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
  478. ImageCheck *check;
  479. bool quiet = false;
  480. fmt = NULL;
  481. output = NULL;
  482. for(;;) {
  483. int option_index = 0;
  484. static const struct option long_options[] = {
  485. {"help", no_argument, 0, 'h'},
  486. {"format", required_argument, 0, 'f'},
  487. {"repair", no_argument, 0, 'r'},
  488. {"output", required_argument, 0, OPTION_OUTPUT},
  489. {0, 0, 0, 0}
  490. };
  491. c = getopt_long(argc, argv, "f:hr:q",
  492. long_options, &option_index);
  493. if (c == -1) {
  494. break;
  495. }
  496. switch(c) {
  497. case '?':
  498. case 'h':
  499. help();
  500. break;
  501. case 'f':
  502. fmt = optarg;
  503. break;
  504. case 'r':
  505. flags |= BDRV_O_RDWR;
  506. if (!strcmp(optarg, "leaks")) {
  507. fix = BDRV_FIX_LEAKS;
  508. } else if (!strcmp(optarg, "all")) {
  509. fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
  510. } else {
  511. help();
  512. }
  513. break;
  514. case OPTION_OUTPUT:
  515. output = optarg;
  516. break;
  517. case 'q':
  518. quiet = true;
  519. break;
  520. }
  521. }
  522. if (optind >= argc) {
  523. help();
  524. }
  525. filename = argv[optind++];
  526. if (output && !strcmp(output, "json")) {
  527. output_format = OFORMAT_JSON;
  528. } else if (output && !strcmp(output, "human")) {
  529. output_format = OFORMAT_HUMAN;
  530. } else if (output) {
  531. error_report("--output must be used with human or json as argument.");
  532. return 1;
  533. }
  534. bs = bdrv_new_open(filename, fmt, flags, true, quiet);
  535. if (!bs) {
  536. return 1;
  537. }
  538. check = g_new0(ImageCheck, 1);
  539. ret = collect_image_check(bs, check, filename, fmt, fix);
  540. if (ret == -ENOTSUP) {
  541. if (output_format == OFORMAT_HUMAN) {
  542. error_report("This image format does not support checks");
  543. }
  544. ret = 1;
  545. goto fail;
  546. }
  547. if (check->corruptions_fixed || check->leaks_fixed) {
  548. int corruptions_fixed, leaks_fixed;
  549. leaks_fixed = check->leaks_fixed;
  550. corruptions_fixed = check->corruptions_fixed;
  551. if (output_format == OFORMAT_HUMAN) {
  552. qprintf(quiet,
  553. "The following inconsistencies were found and repaired:\n\n"
  554. " %" PRId64 " leaked clusters\n"
  555. " %" PRId64 " corruptions\n\n"
  556. "Double checking the fixed image now...\n",
  557. check->leaks_fixed,
  558. check->corruptions_fixed);
  559. }
  560. ret = collect_image_check(bs, check, filename, fmt, 0);
  561. check->leaks_fixed = leaks_fixed;
  562. check->corruptions_fixed = corruptions_fixed;
  563. }
  564. switch (output_format) {
  565. case OFORMAT_HUMAN:
  566. dump_human_image_check(check, quiet);
  567. break;
  568. case OFORMAT_JSON:
  569. dump_json_image_check(check, quiet);
  570. break;
  571. }
  572. if (ret || check->check_errors) {
  573. ret = 1;
  574. goto fail;
  575. }
  576. if (check->corruptions) {
  577. ret = 2;
  578. } else if (check->leaks) {
  579. ret = 3;
  580. } else {
  581. ret = 0;
  582. }
  583. fail:
  584. qapi_free_ImageCheck(check);
  585. bdrv_delete(bs);
  586. return ret;
  587. }
  588. static int img_commit(int argc, char **argv)
  589. {
  590. int c, ret, flags;
  591. const char *filename, *fmt, *cache;
  592. BlockDriverState *bs;
  593. bool quiet = false;
  594. fmt = NULL;
  595. cache = BDRV_DEFAULT_CACHE;
  596. for(;;) {
  597. c = getopt(argc, argv, "f:ht:q");
  598. if (c == -1) {
  599. break;
  600. }
  601. switch(c) {
  602. case '?':
  603. case 'h':
  604. help();
  605. break;
  606. case 'f':
  607. fmt = optarg;
  608. break;
  609. case 't':
  610. cache = optarg;
  611. break;
  612. case 'q':
  613. quiet = true;
  614. break;
  615. }
  616. }
  617. if (optind >= argc) {
  618. help();
  619. }
  620. filename = argv[optind++];
  621. flags = BDRV_O_RDWR;
  622. ret = bdrv_parse_cache_flags(cache, &flags);
  623. if (ret < 0) {
  624. error_report("Invalid cache option: %s", cache);
  625. return -1;
  626. }
  627. bs = bdrv_new_open(filename, fmt, flags, true, quiet);
  628. if (!bs) {
  629. return 1;
  630. }
  631. ret = bdrv_commit(bs);
  632. switch(ret) {
  633. case 0:
  634. qprintf(quiet, "Image committed.\n");
  635. break;
  636. case -ENOENT:
  637. error_report("No disk inserted");
  638. break;
  639. case -EACCES:
  640. error_report("Image is read-only");
  641. break;
  642. case -ENOTSUP:
  643. error_report("Image is already committed");
  644. break;
  645. default:
  646. error_report("Error while committing image");
  647. break;
  648. }
  649. bdrv_delete(bs);
  650. if (ret) {
  651. return 1;
  652. }
  653. return 0;
  654. }
  655. /*
  656. * Returns true iff the first sector pointed to by 'buf' contains at least
  657. * a non-NUL byte.
  658. *
  659. * 'pnum' is set to the number of sectors (including and immediately following
  660. * the first one) that are known to be in the same allocated/unallocated state.
  661. */
  662. static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
  663. {
  664. bool is_zero;
  665. int i;
  666. if (n <= 0) {
  667. *pnum = 0;
  668. return 0;
  669. }
  670. is_zero = buffer_is_zero(buf, 512);
  671. for(i = 1; i < n; i++) {
  672. buf += 512;
  673. if (is_zero != buffer_is_zero(buf, 512)) {
  674. break;
  675. }
  676. }
  677. *pnum = i;
  678. return !is_zero;
  679. }
  680. /*
  681. * Like is_allocated_sectors, but if the buffer starts with a used sector,
  682. * up to 'min' consecutive sectors containing zeros are ignored. This avoids
  683. * breaking up write requests for only small sparse areas.
  684. */
  685. static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
  686. int min)
  687. {
  688. int ret;
  689. int num_checked, num_used;
  690. if (n < min) {
  691. min = n;
  692. }
  693. ret = is_allocated_sectors(buf, n, pnum);
  694. if (!ret) {
  695. return ret;
  696. }
  697. num_used = *pnum;
  698. buf += BDRV_SECTOR_SIZE * *pnum;
  699. n -= *pnum;
  700. num_checked = num_used;
  701. while (n > 0) {
  702. ret = is_allocated_sectors(buf, n, pnum);
  703. buf += BDRV_SECTOR_SIZE * *pnum;
  704. n -= *pnum;
  705. num_checked += *pnum;
  706. if (ret) {
  707. num_used = num_checked;
  708. } else if (*pnum >= min) {
  709. break;
  710. }
  711. }
  712. *pnum = num_used;
  713. return 1;
  714. }
  715. /*
  716. * Compares two buffers sector by sector. Returns 0 if the first sector of both
  717. * buffers matches, non-zero otherwise.
  718. *
  719. * pnum is set to the number of sectors (including and immediately following
  720. * the first one) that are known to have the same comparison result
  721. */
  722. static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
  723. int *pnum)
  724. {
  725. int res, i;
  726. if (n <= 0) {
  727. *pnum = 0;
  728. return 0;
  729. }
  730. res = !!memcmp(buf1, buf2, 512);
  731. for(i = 1; i < n; i++) {
  732. buf1 += 512;
  733. buf2 += 512;
  734. if (!!memcmp(buf1, buf2, 512) != res) {
  735. break;
  736. }
  737. }
  738. *pnum = i;
  739. return res;
  740. }
  741. #define IO_BUF_SIZE (2 * 1024 * 1024)
  742. static int64_t sectors_to_bytes(int64_t sectors)
  743. {
  744. return sectors << BDRV_SECTOR_BITS;
  745. }
  746. static int64_t sectors_to_process(int64_t total, int64_t from)
  747. {
  748. return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
  749. }
  750. /*
  751. * Check if passed sectors are empty (not allocated or contain only 0 bytes)
  752. *
  753. * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
  754. * data and negative value on error.
  755. *
  756. * @param bs: Driver used for accessing file
  757. * @param sect_num: Number of first sector to check
  758. * @param sect_count: Number of sectors to check
  759. * @param filename: Name of disk file we are checking (logging purpose)
  760. * @param buffer: Allocated buffer for storing read data
  761. * @param quiet: Flag for quiet mode
  762. */
  763. static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
  764. int sect_count, const char *filename,
  765. uint8_t *buffer, bool quiet)
  766. {
  767. int pnum, ret = 0;
  768. ret = bdrv_read(bs, sect_num, buffer, sect_count);
  769. if (ret < 0) {
  770. error_report("Error while reading offset %" PRId64 " of %s: %s",
  771. sectors_to_bytes(sect_num), filename, strerror(-ret));
  772. return ret;
  773. }
  774. ret = is_allocated_sectors(buffer, sect_count, &pnum);
  775. if (ret || pnum != sect_count) {
  776. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  777. sectors_to_bytes(ret ? sect_num : sect_num + pnum));
  778. return 1;
  779. }
  780. return 0;
  781. }
  782. /*
  783. * Compares two images. Exit codes:
  784. *
  785. * 0 - Images are identical
  786. * 1 - Images differ
  787. * >1 - Error occurred
  788. */
  789. static int img_compare(int argc, char **argv)
  790. {
  791. const char *fmt1 = NULL, *fmt2 = NULL, *filename1, *filename2;
  792. BlockDriverState *bs1, *bs2;
  793. int64_t total_sectors1, total_sectors2;
  794. uint8_t *buf1 = NULL, *buf2 = NULL;
  795. int pnum1, pnum2;
  796. int allocated1, allocated2;
  797. int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
  798. bool progress = false, quiet = false, strict = false;
  799. int64_t total_sectors;
  800. int64_t sector_num = 0;
  801. int64_t nb_sectors;
  802. int c, pnum;
  803. uint64_t bs_sectors;
  804. uint64_t progress_base;
  805. for (;;) {
  806. c = getopt(argc, argv, "hpf:F:sq");
  807. if (c == -1) {
  808. break;
  809. }
  810. switch (c) {
  811. case '?':
  812. case 'h':
  813. help();
  814. break;
  815. case 'f':
  816. fmt1 = optarg;
  817. break;
  818. case 'F':
  819. fmt2 = optarg;
  820. break;
  821. case 'p':
  822. progress = true;
  823. break;
  824. case 'q':
  825. quiet = true;
  826. break;
  827. case 's':
  828. strict = true;
  829. break;
  830. }
  831. }
  832. /* Progress is not shown in Quiet mode */
  833. if (quiet) {
  834. progress = false;
  835. }
  836. if (optind > argc - 2) {
  837. help();
  838. }
  839. filename1 = argv[optind++];
  840. filename2 = argv[optind++];
  841. /* Initialize before goto out */
  842. qemu_progress_init(progress, 2.0);
  843. bs1 = bdrv_new_open(filename1, fmt1, BDRV_O_FLAGS, true, quiet);
  844. if (!bs1) {
  845. error_report("Can't open file %s", filename1);
  846. ret = 2;
  847. goto out3;
  848. }
  849. bs2 = bdrv_new_open(filename2, fmt2, BDRV_O_FLAGS, true, quiet);
  850. if (!bs2) {
  851. error_report("Can't open file %s", filename2);
  852. ret = 2;
  853. goto out2;
  854. }
  855. buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
  856. buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
  857. bdrv_get_geometry(bs1, &bs_sectors);
  858. total_sectors1 = bs_sectors;
  859. bdrv_get_geometry(bs2, &bs_sectors);
  860. total_sectors2 = bs_sectors;
  861. total_sectors = MIN(total_sectors1, total_sectors2);
  862. progress_base = MAX(total_sectors1, total_sectors2);
  863. qemu_progress_print(0, 100);
  864. if (strict && total_sectors1 != total_sectors2) {
  865. ret = 1;
  866. qprintf(quiet, "Strict mode: Image size mismatch!\n");
  867. goto out;
  868. }
  869. for (;;) {
  870. nb_sectors = sectors_to_process(total_sectors, sector_num);
  871. if (nb_sectors <= 0) {
  872. break;
  873. }
  874. allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
  875. &pnum1);
  876. if (allocated1 < 0) {
  877. ret = 3;
  878. error_report("Sector allocation test failed for %s", filename1);
  879. goto out;
  880. }
  881. allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
  882. &pnum2);
  883. if (allocated2 < 0) {
  884. ret = 3;
  885. error_report("Sector allocation test failed for %s", filename2);
  886. goto out;
  887. }
  888. nb_sectors = MIN(pnum1, pnum2);
  889. if (allocated1 == allocated2) {
  890. if (allocated1) {
  891. ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
  892. if (ret < 0) {
  893. error_report("Error while reading offset %" PRId64 " of %s:"
  894. " %s", sectors_to_bytes(sector_num), filename1,
  895. strerror(-ret));
  896. ret = 4;
  897. goto out;
  898. }
  899. ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
  900. if (ret < 0) {
  901. error_report("Error while reading offset %" PRId64
  902. " of %s: %s", sectors_to_bytes(sector_num),
  903. filename2, strerror(-ret));
  904. ret = 4;
  905. goto out;
  906. }
  907. ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
  908. if (ret || pnum != nb_sectors) {
  909. ret = 1;
  910. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  911. sectors_to_bytes(
  912. ret ? sector_num : sector_num + pnum));
  913. goto out;
  914. }
  915. }
  916. } else {
  917. if (strict) {
  918. ret = 1;
  919. qprintf(quiet, "Strict mode: Offset %" PRId64
  920. " allocation mismatch!\n",
  921. sectors_to_bytes(sector_num));
  922. goto out;
  923. }
  924. if (allocated1) {
  925. ret = check_empty_sectors(bs1, sector_num, nb_sectors,
  926. filename1, buf1, quiet);
  927. } else {
  928. ret = check_empty_sectors(bs2, sector_num, nb_sectors,
  929. filename2, buf1, quiet);
  930. }
  931. if (ret) {
  932. if (ret < 0) {
  933. ret = 4;
  934. error_report("Error while reading offset %" PRId64 ": %s",
  935. sectors_to_bytes(sector_num), strerror(-ret));
  936. }
  937. goto out;
  938. }
  939. }
  940. sector_num += nb_sectors;
  941. qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
  942. }
  943. if (total_sectors1 != total_sectors2) {
  944. BlockDriverState *bs_over;
  945. int64_t total_sectors_over;
  946. const char *filename_over;
  947. qprintf(quiet, "Warning: Image size mismatch!\n");
  948. if (total_sectors1 > total_sectors2) {
  949. total_sectors_over = total_sectors1;
  950. bs_over = bs1;
  951. filename_over = filename1;
  952. } else {
  953. total_sectors_over = total_sectors2;
  954. bs_over = bs2;
  955. filename_over = filename2;
  956. }
  957. for (;;) {
  958. nb_sectors = sectors_to_process(total_sectors_over, sector_num);
  959. if (nb_sectors <= 0) {
  960. break;
  961. }
  962. ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
  963. nb_sectors, &pnum);
  964. if (ret < 0) {
  965. ret = 3;
  966. error_report("Sector allocation test failed for %s",
  967. filename_over);
  968. goto out;
  969. }
  970. nb_sectors = pnum;
  971. if (ret) {
  972. ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
  973. filename_over, buf1, quiet);
  974. if (ret) {
  975. if (ret < 0) {
  976. ret = 4;
  977. error_report("Error while reading offset %" PRId64
  978. " of %s: %s", sectors_to_bytes(sector_num),
  979. filename_over, strerror(-ret));
  980. }
  981. goto out;
  982. }
  983. }
  984. sector_num += nb_sectors;
  985. qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
  986. }
  987. }
  988. qprintf(quiet, "Images are identical.\n");
  989. ret = 0;
  990. out:
  991. bdrv_delete(bs2);
  992. qemu_vfree(buf1);
  993. qemu_vfree(buf2);
  994. out2:
  995. bdrv_delete(bs1);
  996. out3:
  997. qemu_progress_end();
  998. return ret;
  999. }
  1000. static int img_convert(int argc, char **argv)
  1001. {
  1002. int c, ret = 0, n, n1, bs_n, bs_i, compress, cluster_size, cluster_sectors;
  1003. int progress = 0, flags;
  1004. const char *fmt, *out_fmt, *cache, *out_baseimg, *out_filename;
  1005. BlockDriver *drv, *proto_drv;
  1006. BlockDriverState **bs = NULL, *out_bs = NULL;
  1007. int64_t total_sectors, nb_sectors, sector_num, bs_offset;
  1008. uint64_t bs_sectors;
  1009. uint8_t * buf = NULL;
  1010. const uint8_t *buf1;
  1011. BlockDriverInfo bdi;
  1012. QEMUOptionParameter *param = NULL, *create_options = NULL;
  1013. QEMUOptionParameter *out_baseimg_param;
  1014. char *options = NULL;
  1015. const char *snapshot_name = NULL;
  1016. float local_progress = 0;
  1017. int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
  1018. bool quiet = false;
  1019. fmt = NULL;
  1020. out_fmt = "raw";
  1021. cache = "unsafe";
  1022. out_baseimg = NULL;
  1023. compress = 0;
  1024. for(;;) {
  1025. c = getopt(argc, argv, "f:O:B:s:hce6o:pS:t:q");
  1026. if (c == -1) {
  1027. break;
  1028. }
  1029. switch(c) {
  1030. case '?':
  1031. case 'h':
  1032. help();
  1033. break;
  1034. case 'f':
  1035. fmt = optarg;
  1036. break;
  1037. case 'O':
  1038. out_fmt = optarg;
  1039. break;
  1040. case 'B':
  1041. out_baseimg = optarg;
  1042. break;
  1043. case 'c':
  1044. compress = 1;
  1045. break;
  1046. case 'e':
  1047. error_report("option -e is deprecated, please use \'-o "
  1048. "encryption\' instead!");
  1049. return 1;
  1050. case '6':
  1051. error_report("option -6 is deprecated, please use \'-o "
  1052. "compat6\' instead!");
  1053. return 1;
  1054. case 'o':
  1055. options = optarg;
  1056. break;
  1057. case 's':
  1058. snapshot_name = optarg;
  1059. break;
  1060. case 'S':
  1061. {
  1062. int64_t sval;
  1063. char *end;
  1064. sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
  1065. if (sval < 0 || *end) {
  1066. error_report("Invalid minimum zero buffer size for sparse output specified");
  1067. return 1;
  1068. }
  1069. min_sparse = sval / BDRV_SECTOR_SIZE;
  1070. break;
  1071. }
  1072. case 'p':
  1073. progress = 1;
  1074. break;
  1075. case 't':
  1076. cache = optarg;
  1077. break;
  1078. case 'q':
  1079. quiet = true;
  1080. break;
  1081. }
  1082. }
  1083. if (quiet) {
  1084. progress = 0;
  1085. }
  1086. bs_n = argc - optind - 1;
  1087. if (bs_n < 1) {
  1088. help();
  1089. }
  1090. out_filename = argv[argc - 1];
  1091. /* Initialize before goto out */
  1092. qemu_progress_init(progress, 2.0);
  1093. if (options && is_help_option(options)) {
  1094. ret = print_block_option_help(out_filename, out_fmt);
  1095. goto out;
  1096. }
  1097. if (bs_n > 1 && out_baseimg) {
  1098. error_report("-B makes no sense when concatenating multiple input "
  1099. "images");
  1100. ret = -1;
  1101. goto out;
  1102. }
  1103. qemu_progress_print(0, 100);
  1104. bs = g_malloc0(bs_n * sizeof(BlockDriverState *));
  1105. total_sectors = 0;
  1106. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  1107. bs[bs_i] = bdrv_new_open(argv[optind + bs_i], fmt, BDRV_O_FLAGS, true,
  1108. quiet);
  1109. if (!bs[bs_i]) {
  1110. error_report("Could not open '%s'", argv[optind + bs_i]);
  1111. ret = -1;
  1112. goto out;
  1113. }
  1114. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  1115. total_sectors += bs_sectors;
  1116. }
  1117. if (snapshot_name != NULL) {
  1118. if (bs_n > 1) {
  1119. error_report("No support for concatenating multiple snapshot");
  1120. ret = -1;
  1121. goto out;
  1122. }
  1123. if (bdrv_snapshot_load_tmp(bs[0], snapshot_name) < 0) {
  1124. error_report("Failed to load snapshot");
  1125. ret = -1;
  1126. goto out;
  1127. }
  1128. }
  1129. /* Find driver and parse its options */
  1130. drv = bdrv_find_format(out_fmt);
  1131. if (!drv) {
  1132. error_report("Unknown file format '%s'", out_fmt);
  1133. ret = -1;
  1134. goto out;
  1135. }
  1136. proto_drv = bdrv_find_protocol(out_filename);
  1137. if (!proto_drv) {
  1138. error_report("Unknown protocol '%s'", out_filename);
  1139. ret = -1;
  1140. goto out;
  1141. }
  1142. create_options = append_option_parameters(create_options,
  1143. drv->create_options);
  1144. create_options = append_option_parameters(create_options,
  1145. proto_drv->create_options);
  1146. if (options) {
  1147. param = parse_option_parameters(options, create_options, param);
  1148. if (param == NULL) {
  1149. error_report("Invalid options for file format '%s'.", out_fmt);
  1150. ret = -1;
  1151. goto out;
  1152. }
  1153. } else {
  1154. param = parse_option_parameters("", create_options, param);
  1155. }
  1156. set_option_parameter_int(param, BLOCK_OPT_SIZE, total_sectors * 512);
  1157. ret = add_old_style_options(out_fmt, param, out_baseimg, NULL);
  1158. if (ret < 0) {
  1159. goto out;
  1160. }
  1161. /* Get backing file name if -o backing_file was used */
  1162. out_baseimg_param = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
  1163. if (out_baseimg_param) {
  1164. out_baseimg = out_baseimg_param->value.s;
  1165. }
  1166. /* Check if compression is supported */
  1167. if (compress) {
  1168. QEMUOptionParameter *encryption =
  1169. get_option_parameter(param, BLOCK_OPT_ENCRYPT);
  1170. QEMUOptionParameter *preallocation =
  1171. get_option_parameter(param, BLOCK_OPT_PREALLOC);
  1172. if (!drv->bdrv_write_compressed) {
  1173. error_report("Compression not supported for this file format");
  1174. ret = -1;
  1175. goto out;
  1176. }
  1177. if (encryption && encryption->value.n) {
  1178. error_report("Compression and encryption not supported at "
  1179. "the same time");
  1180. ret = -1;
  1181. goto out;
  1182. }
  1183. if (preallocation && preallocation->value.s
  1184. && strcmp(preallocation->value.s, "off"))
  1185. {
  1186. error_report("Compression and preallocation not supported at "
  1187. "the same time");
  1188. ret = -1;
  1189. goto out;
  1190. }
  1191. }
  1192. /* Create the new image */
  1193. ret = bdrv_create(drv, out_filename, param);
  1194. if (ret < 0) {
  1195. if (ret == -ENOTSUP) {
  1196. error_report("Formatting not supported for file format '%s'",
  1197. out_fmt);
  1198. } else if (ret == -EFBIG) {
  1199. error_report("The image size is too large for file format '%s'",
  1200. out_fmt);
  1201. } else {
  1202. error_report("%s: error while converting %s: %s",
  1203. out_filename, out_fmt, strerror(-ret));
  1204. }
  1205. goto out;
  1206. }
  1207. flags = BDRV_O_RDWR;
  1208. ret = bdrv_parse_cache_flags(cache, &flags);
  1209. if (ret < 0) {
  1210. error_report("Invalid cache option: %s", cache);
  1211. return -1;
  1212. }
  1213. out_bs = bdrv_new_open(out_filename, out_fmt, flags, true, quiet);
  1214. if (!out_bs) {
  1215. ret = -1;
  1216. goto out;
  1217. }
  1218. bs_i = 0;
  1219. bs_offset = 0;
  1220. bdrv_get_geometry(bs[0], &bs_sectors);
  1221. buf = qemu_blockalign(out_bs, IO_BUF_SIZE);
  1222. if (compress) {
  1223. ret = bdrv_get_info(out_bs, &bdi);
  1224. if (ret < 0) {
  1225. error_report("could not get block driver info");
  1226. goto out;
  1227. }
  1228. cluster_size = bdi.cluster_size;
  1229. if (cluster_size <= 0 || cluster_size > IO_BUF_SIZE) {
  1230. error_report("invalid cluster size");
  1231. ret = -1;
  1232. goto out;
  1233. }
  1234. cluster_sectors = cluster_size >> 9;
  1235. sector_num = 0;
  1236. nb_sectors = total_sectors;
  1237. if (nb_sectors != 0) {
  1238. local_progress = (float)100 /
  1239. (nb_sectors / MIN(nb_sectors, cluster_sectors));
  1240. }
  1241. for(;;) {
  1242. int64_t bs_num;
  1243. int remainder;
  1244. uint8_t *buf2;
  1245. nb_sectors = total_sectors - sector_num;
  1246. if (nb_sectors <= 0)
  1247. break;
  1248. if (nb_sectors >= cluster_sectors)
  1249. n = cluster_sectors;
  1250. else
  1251. n = nb_sectors;
  1252. bs_num = sector_num - bs_offset;
  1253. assert (bs_num >= 0);
  1254. remainder = n;
  1255. buf2 = buf;
  1256. while (remainder > 0) {
  1257. int nlow;
  1258. while (bs_num == bs_sectors) {
  1259. bs_i++;
  1260. assert (bs_i < bs_n);
  1261. bs_offset += bs_sectors;
  1262. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  1263. bs_num = 0;
  1264. /* printf("changing part: sector_num=%" PRId64 ", "
  1265. "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
  1266. "\n", sector_num, bs_i, bs_offset, bs_sectors); */
  1267. }
  1268. assert (bs_num < bs_sectors);
  1269. nlow = (remainder > bs_sectors - bs_num) ? bs_sectors - bs_num : remainder;
  1270. ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
  1271. if (ret < 0) {
  1272. error_report("error while reading sector %" PRId64 ": %s",
  1273. bs_num, strerror(-ret));
  1274. goto out;
  1275. }
  1276. buf2 += nlow * 512;
  1277. bs_num += nlow;
  1278. remainder -= nlow;
  1279. }
  1280. assert (remainder == 0);
  1281. if (n < cluster_sectors) {
  1282. memset(buf + n * 512, 0, cluster_size - n * 512);
  1283. }
  1284. if (!buffer_is_zero(buf, cluster_size)) {
  1285. ret = bdrv_write_compressed(out_bs, sector_num, buf,
  1286. cluster_sectors);
  1287. if (ret != 0) {
  1288. error_report("error while compressing sector %" PRId64
  1289. ": %s", sector_num, strerror(-ret));
  1290. goto out;
  1291. }
  1292. }
  1293. sector_num += n;
  1294. qemu_progress_print(local_progress, 100);
  1295. }
  1296. /* signal EOF to align */
  1297. bdrv_write_compressed(out_bs, 0, NULL, 0);
  1298. } else {
  1299. int has_zero_init = bdrv_has_zero_init(out_bs);
  1300. sector_num = 0; // total number of sectors converted so far
  1301. nb_sectors = total_sectors - sector_num;
  1302. if (nb_sectors != 0) {
  1303. local_progress = (float)100 /
  1304. (nb_sectors / MIN(nb_sectors, IO_BUF_SIZE / 512));
  1305. }
  1306. for(;;) {
  1307. nb_sectors = total_sectors - sector_num;
  1308. if (nb_sectors <= 0) {
  1309. break;
  1310. }
  1311. if (nb_sectors >= (IO_BUF_SIZE / 512)) {
  1312. n = (IO_BUF_SIZE / 512);
  1313. } else {
  1314. n = nb_sectors;
  1315. }
  1316. while (sector_num - bs_offset >= bs_sectors) {
  1317. bs_i ++;
  1318. assert (bs_i < bs_n);
  1319. bs_offset += bs_sectors;
  1320. bdrv_get_geometry(bs[bs_i], &bs_sectors);
  1321. /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
  1322. "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
  1323. sector_num, bs_i, bs_offset, bs_sectors); */
  1324. }
  1325. if (n > bs_offset + bs_sectors - sector_num) {
  1326. n = bs_offset + bs_sectors - sector_num;
  1327. }
  1328. if (has_zero_init) {
  1329. /* If the output image is being created as a copy on write image,
  1330. assume that sectors which are unallocated in the input image
  1331. are present in both the output's and input's base images (no
  1332. need to copy them). */
  1333. if (out_baseimg) {
  1334. if (!bdrv_is_allocated(bs[bs_i], sector_num - bs_offset,
  1335. n, &n1)) {
  1336. sector_num += n1;
  1337. continue;
  1338. }
  1339. /* The next 'n1' sectors are allocated in the input image. Copy
  1340. only those as they may be followed by unallocated sectors. */
  1341. n = n1;
  1342. }
  1343. } else {
  1344. n1 = n;
  1345. }
  1346. ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
  1347. if (ret < 0) {
  1348. error_report("error while reading sector %" PRId64 ": %s",
  1349. sector_num - bs_offset, strerror(-ret));
  1350. goto out;
  1351. }
  1352. /* NOTE: at the same time we convert, we do not write zero
  1353. sectors to have a chance to compress the image. Ideally, we
  1354. should add a specific call to have the info to go faster */
  1355. buf1 = buf;
  1356. while (n > 0) {
  1357. /* If the output image is being created as a copy on write image,
  1358. copy all sectors even the ones containing only NUL bytes,
  1359. because they may differ from the sectors in the base image.
  1360. If the output is to a host device, we also write out
  1361. sectors that are entirely 0, since whatever data was
  1362. already there is garbage, not 0s. */
  1363. if (!has_zero_init || out_baseimg ||
  1364. is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
  1365. ret = bdrv_write(out_bs, sector_num, buf1, n1);
  1366. if (ret < 0) {
  1367. error_report("error while writing sector %" PRId64
  1368. ": %s", sector_num, strerror(-ret));
  1369. goto out;
  1370. }
  1371. }
  1372. sector_num += n1;
  1373. n -= n1;
  1374. buf1 += n1 * 512;
  1375. }
  1376. qemu_progress_print(local_progress, 100);
  1377. }
  1378. }
  1379. out:
  1380. qemu_progress_end();
  1381. free_option_parameters(create_options);
  1382. free_option_parameters(param);
  1383. qemu_vfree(buf);
  1384. if (out_bs) {
  1385. bdrv_delete(out_bs);
  1386. }
  1387. if (bs) {
  1388. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  1389. if (bs[bs_i]) {
  1390. bdrv_delete(bs[bs_i]);
  1391. }
  1392. }
  1393. g_free(bs);
  1394. }
  1395. if (ret) {
  1396. return 1;
  1397. }
  1398. return 0;
  1399. }
  1400. static void dump_snapshots(BlockDriverState *bs)
  1401. {
  1402. QEMUSnapshotInfo *sn_tab, *sn;
  1403. int nb_sns, i;
  1404. char buf[256];
  1405. nb_sns = bdrv_snapshot_list(bs, &sn_tab);
  1406. if (nb_sns <= 0)
  1407. return;
  1408. printf("Snapshot list:\n");
  1409. printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
  1410. for(i = 0; i < nb_sns; i++) {
  1411. sn = &sn_tab[i];
  1412. printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
  1413. }
  1414. g_free(sn_tab);
  1415. }
  1416. static void dump_json_image_info_list(ImageInfoList *list)
  1417. {
  1418. Error *errp = NULL;
  1419. QString *str;
  1420. QmpOutputVisitor *ov = qmp_output_visitor_new();
  1421. QObject *obj;
  1422. visit_type_ImageInfoList(qmp_output_get_visitor(ov),
  1423. &list, NULL, &errp);
  1424. obj = qmp_output_get_qobject(ov);
  1425. str = qobject_to_json_pretty(obj);
  1426. assert(str != NULL);
  1427. printf("%s\n", qstring_get_str(str));
  1428. qobject_decref(obj);
  1429. qmp_output_visitor_cleanup(ov);
  1430. QDECREF(str);
  1431. }
  1432. static void collect_snapshots(BlockDriverState *bs , ImageInfo *info)
  1433. {
  1434. int i, sn_count;
  1435. QEMUSnapshotInfo *sn_tab = NULL;
  1436. SnapshotInfoList *info_list, *cur_item = NULL;
  1437. sn_count = bdrv_snapshot_list(bs, &sn_tab);
  1438. for (i = 0; i < sn_count; i++) {
  1439. info->has_snapshots = true;
  1440. info_list = g_new0(SnapshotInfoList, 1);
  1441. info_list->value = g_new0(SnapshotInfo, 1);
  1442. info_list->value->id = g_strdup(sn_tab[i].id_str);
  1443. info_list->value->name = g_strdup(sn_tab[i].name);
  1444. info_list->value->vm_state_size = sn_tab[i].vm_state_size;
  1445. info_list->value->date_sec = sn_tab[i].date_sec;
  1446. info_list->value->date_nsec = sn_tab[i].date_nsec;
  1447. info_list->value->vm_clock_sec = sn_tab[i].vm_clock_nsec / 1000000000;
  1448. info_list->value->vm_clock_nsec = sn_tab[i].vm_clock_nsec % 1000000000;
  1449. /* XXX: waiting for the qapi to support qemu-queue.h types */
  1450. if (!cur_item) {
  1451. info->snapshots = cur_item = info_list;
  1452. } else {
  1453. cur_item->next = info_list;
  1454. cur_item = info_list;
  1455. }
  1456. }
  1457. g_free(sn_tab);
  1458. }
  1459. static void dump_json_image_info(ImageInfo *info)
  1460. {
  1461. Error *errp = NULL;
  1462. QString *str;
  1463. QmpOutputVisitor *ov = qmp_output_visitor_new();
  1464. QObject *obj;
  1465. visit_type_ImageInfo(qmp_output_get_visitor(ov),
  1466. &info, NULL, &errp);
  1467. obj = qmp_output_get_qobject(ov);
  1468. str = qobject_to_json_pretty(obj);
  1469. assert(str != NULL);
  1470. printf("%s\n", qstring_get_str(str));
  1471. qobject_decref(obj);
  1472. qmp_output_visitor_cleanup(ov);
  1473. QDECREF(str);
  1474. }
  1475. static void collect_image_info(BlockDriverState *bs,
  1476. ImageInfo *info,
  1477. const char *filename,
  1478. const char *fmt)
  1479. {
  1480. uint64_t total_sectors;
  1481. char backing_filename[1024];
  1482. char backing_filename2[1024];
  1483. BlockDriverInfo bdi;
  1484. bdrv_get_geometry(bs, &total_sectors);
  1485. info->filename = g_strdup(filename);
  1486. info->format = g_strdup(bdrv_get_format_name(bs));
  1487. info->virtual_size = total_sectors * 512;
  1488. info->actual_size = bdrv_get_allocated_file_size(bs);
  1489. info->has_actual_size = info->actual_size >= 0;
  1490. if (bdrv_is_encrypted(bs)) {
  1491. info->encrypted = true;
  1492. info->has_encrypted = true;
  1493. }
  1494. if (bdrv_get_info(bs, &bdi) >= 0) {
  1495. if (bdi.cluster_size != 0) {
  1496. info->cluster_size = bdi.cluster_size;
  1497. info->has_cluster_size = true;
  1498. }
  1499. info->dirty_flag = bdi.is_dirty;
  1500. info->has_dirty_flag = true;
  1501. }
  1502. bdrv_get_backing_filename(bs, backing_filename, sizeof(backing_filename));
  1503. if (backing_filename[0] != '\0') {
  1504. info->backing_filename = g_strdup(backing_filename);
  1505. info->has_backing_filename = true;
  1506. bdrv_get_full_backing_filename(bs, backing_filename2,
  1507. sizeof(backing_filename2));
  1508. if (strcmp(backing_filename, backing_filename2) != 0) {
  1509. info->full_backing_filename =
  1510. g_strdup(backing_filename2);
  1511. info->has_full_backing_filename = true;
  1512. }
  1513. if (bs->backing_format[0]) {
  1514. info->backing_filename_format = g_strdup(bs->backing_format);
  1515. info->has_backing_filename_format = true;
  1516. }
  1517. }
  1518. }
  1519. static void dump_human_image_info(ImageInfo *info)
  1520. {
  1521. char size_buf[128], dsize_buf[128];
  1522. if (!info->has_actual_size) {
  1523. snprintf(dsize_buf, sizeof(dsize_buf), "unavailable");
  1524. } else {
  1525. get_human_readable_size(dsize_buf, sizeof(dsize_buf),
  1526. info->actual_size);
  1527. }
  1528. get_human_readable_size(size_buf, sizeof(size_buf), info->virtual_size);
  1529. printf("image: %s\n"
  1530. "file format: %s\n"
  1531. "virtual size: %s (%" PRId64 " bytes)\n"
  1532. "disk size: %s\n",
  1533. info->filename, info->format, size_buf,
  1534. info->virtual_size,
  1535. dsize_buf);
  1536. if (info->has_encrypted && info->encrypted) {
  1537. printf("encrypted: yes\n");
  1538. }
  1539. if (info->has_cluster_size) {
  1540. printf("cluster_size: %" PRId64 "\n", info->cluster_size);
  1541. }
  1542. if (info->has_dirty_flag && info->dirty_flag) {
  1543. printf("cleanly shut down: no\n");
  1544. }
  1545. if (info->has_backing_filename) {
  1546. printf("backing file: %s", info->backing_filename);
  1547. if (info->has_full_backing_filename) {
  1548. printf(" (actual path: %s)", info->full_backing_filename);
  1549. }
  1550. putchar('\n');
  1551. if (info->has_backing_filename_format) {
  1552. printf("backing file format: %s\n", info->backing_filename_format);
  1553. }
  1554. }
  1555. if (info->has_snapshots) {
  1556. SnapshotInfoList *elem;
  1557. char buf[256];
  1558. printf("Snapshot list:\n");
  1559. printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
  1560. /* Ideally bdrv_snapshot_dump() would operate on SnapshotInfoList but
  1561. * we convert to the block layer's native QEMUSnapshotInfo for now.
  1562. */
  1563. for (elem = info->snapshots; elem; elem = elem->next) {
  1564. QEMUSnapshotInfo sn = {
  1565. .vm_state_size = elem->value->vm_state_size,
  1566. .date_sec = elem->value->date_sec,
  1567. .date_nsec = elem->value->date_nsec,
  1568. .vm_clock_nsec = elem->value->vm_clock_sec * 1000000000ULL +
  1569. elem->value->vm_clock_nsec,
  1570. };
  1571. pstrcpy(sn.id_str, sizeof(sn.id_str), elem->value->id);
  1572. pstrcpy(sn.name, sizeof(sn.name), elem->value->name);
  1573. printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), &sn));
  1574. }
  1575. }
  1576. }
  1577. static void dump_human_image_info_list(ImageInfoList *list)
  1578. {
  1579. ImageInfoList *elem;
  1580. bool delim = false;
  1581. for (elem = list; elem; elem = elem->next) {
  1582. if (delim) {
  1583. printf("\n");
  1584. }
  1585. delim = true;
  1586. dump_human_image_info(elem->value);
  1587. }
  1588. }
  1589. static gboolean str_equal_func(gconstpointer a, gconstpointer b)
  1590. {
  1591. return strcmp(a, b) == 0;
  1592. }
  1593. /**
  1594. * Open an image file chain and return an ImageInfoList
  1595. *
  1596. * @filename: topmost image filename
  1597. * @fmt: topmost image format (may be NULL to autodetect)
  1598. * @chain: true - enumerate entire backing file chain
  1599. * false - only topmost image file
  1600. *
  1601. * Returns a list of ImageInfo objects or NULL if there was an error opening an
  1602. * image file. If there was an error a message will have been printed to
  1603. * stderr.
  1604. */
  1605. static ImageInfoList *collect_image_info_list(const char *filename,
  1606. const char *fmt,
  1607. bool chain)
  1608. {
  1609. ImageInfoList *head = NULL;
  1610. ImageInfoList **last = &head;
  1611. GHashTable *filenames;
  1612. filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
  1613. while (filename) {
  1614. BlockDriverState *bs;
  1615. ImageInfo *info;
  1616. ImageInfoList *elem;
  1617. if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
  1618. error_report("Backing file '%s' creates an infinite loop.",
  1619. filename);
  1620. goto err;
  1621. }
  1622. g_hash_table_insert(filenames, (gpointer)filename, NULL);
  1623. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_NO_BACKING,
  1624. false, false);
  1625. if (!bs) {
  1626. goto err;
  1627. }
  1628. info = g_new0(ImageInfo, 1);
  1629. collect_image_info(bs, info, filename, fmt);
  1630. collect_snapshots(bs, info);
  1631. elem = g_new0(ImageInfoList, 1);
  1632. elem->value = info;
  1633. *last = elem;
  1634. last = &elem->next;
  1635. bdrv_delete(bs);
  1636. filename = fmt = NULL;
  1637. if (chain) {
  1638. if (info->has_full_backing_filename) {
  1639. filename = info->full_backing_filename;
  1640. } else if (info->has_backing_filename) {
  1641. filename = info->backing_filename;
  1642. }
  1643. if (info->has_backing_filename_format) {
  1644. fmt = info->backing_filename_format;
  1645. }
  1646. }
  1647. }
  1648. g_hash_table_destroy(filenames);
  1649. return head;
  1650. err:
  1651. qapi_free_ImageInfoList(head);
  1652. g_hash_table_destroy(filenames);
  1653. return NULL;
  1654. }
  1655. static int img_info(int argc, char **argv)
  1656. {
  1657. int c;
  1658. OutputFormat output_format = OFORMAT_HUMAN;
  1659. bool chain = false;
  1660. const char *filename, *fmt, *output;
  1661. ImageInfoList *list;
  1662. fmt = NULL;
  1663. output = NULL;
  1664. for(;;) {
  1665. int option_index = 0;
  1666. static const struct option long_options[] = {
  1667. {"help", no_argument, 0, 'h'},
  1668. {"format", required_argument, 0, 'f'},
  1669. {"output", required_argument, 0, OPTION_OUTPUT},
  1670. {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
  1671. {0, 0, 0, 0}
  1672. };
  1673. c = getopt_long(argc, argv, "f:h",
  1674. long_options, &option_index);
  1675. if (c == -1) {
  1676. break;
  1677. }
  1678. switch(c) {
  1679. case '?':
  1680. case 'h':
  1681. help();
  1682. break;
  1683. case 'f':
  1684. fmt = optarg;
  1685. break;
  1686. case OPTION_OUTPUT:
  1687. output = optarg;
  1688. break;
  1689. case OPTION_BACKING_CHAIN:
  1690. chain = true;
  1691. break;
  1692. }
  1693. }
  1694. if (optind >= argc) {
  1695. help();
  1696. }
  1697. filename = argv[optind++];
  1698. if (output && !strcmp(output, "json")) {
  1699. output_format = OFORMAT_JSON;
  1700. } else if (output && !strcmp(output, "human")) {
  1701. output_format = OFORMAT_HUMAN;
  1702. } else if (output) {
  1703. error_report("--output must be used with human or json as argument.");
  1704. return 1;
  1705. }
  1706. list = collect_image_info_list(filename, fmt, chain);
  1707. if (!list) {
  1708. return 1;
  1709. }
  1710. switch (output_format) {
  1711. case OFORMAT_HUMAN:
  1712. dump_human_image_info_list(list);
  1713. break;
  1714. case OFORMAT_JSON:
  1715. if (chain) {
  1716. dump_json_image_info_list(list);
  1717. } else {
  1718. dump_json_image_info(list->value);
  1719. }
  1720. break;
  1721. }
  1722. qapi_free_ImageInfoList(list);
  1723. return 0;
  1724. }
  1725. #define SNAPSHOT_LIST 1
  1726. #define SNAPSHOT_CREATE 2
  1727. #define SNAPSHOT_APPLY 3
  1728. #define SNAPSHOT_DELETE 4
  1729. static int img_snapshot(int argc, char **argv)
  1730. {
  1731. BlockDriverState *bs;
  1732. QEMUSnapshotInfo sn;
  1733. char *filename, *snapshot_name = NULL;
  1734. int c, ret = 0, bdrv_oflags;
  1735. int action = 0;
  1736. qemu_timeval tv;
  1737. bool quiet = false;
  1738. bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
  1739. /* Parse commandline parameters */
  1740. for(;;) {
  1741. c = getopt(argc, argv, "la:c:d:hq");
  1742. if (c == -1) {
  1743. break;
  1744. }
  1745. switch(c) {
  1746. case '?':
  1747. case 'h':
  1748. help();
  1749. return 0;
  1750. case 'l':
  1751. if (action) {
  1752. help();
  1753. return 0;
  1754. }
  1755. action = SNAPSHOT_LIST;
  1756. bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
  1757. break;
  1758. case 'a':
  1759. if (action) {
  1760. help();
  1761. return 0;
  1762. }
  1763. action = SNAPSHOT_APPLY;
  1764. snapshot_name = optarg;
  1765. break;
  1766. case 'c':
  1767. if (action) {
  1768. help();
  1769. return 0;
  1770. }
  1771. action = SNAPSHOT_CREATE;
  1772. snapshot_name = optarg;
  1773. break;
  1774. case 'd':
  1775. if (action) {
  1776. help();
  1777. return 0;
  1778. }
  1779. action = SNAPSHOT_DELETE;
  1780. snapshot_name = optarg;
  1781. break;
  1782. case 'q':
  1783. quiet = true;
  1784. break;
  1785. }
  1786. }
  1787. if (optind >= argc) {
  1788. help();
  1789. }
  1790. filename = argv[optind++];
  1791. /* Open the image */
  1792. bs = bdrv_new_open(filename, NULL, bdrv_oflags, true, quiet);
  1793. if (!bs) {
  1794. return 1;
  1795. }
  1796. /* Perform the requested action */
  1797. switch(action) {
  1798. case SNAPSHOT_LIST:
  1799. dump_snapshots(bs);
  1800. break;
  1801. case SNAPSHOT_CREATE:
  1802. memset(&sn, 0, sizeof(sn));
  1803. pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
  1804. qemu_gettimeofday(&tv);
  1805. sn.date_sec = tv.tv_sec;
  1806. sn.date_nsec = tv.tv_usec * 1000;
  1807. ret = bdrv_snapshot_create(bs, &sn);
  1808. if (ret) {
  1809. error_report("Could not create snapshot '%s': %d (%s)",
  1810. snapshot_name, ret, strerror(-ret));
  1811. }
  1812. break;
  1813. case SNAPSHOT_APPLY:
  1814. ret = bdrv_snapshot_goto(bs, snapshot_name);
  1815. if (ret) {
  1816. error_report("Could not apply snapshot '%s': %d (%s)",
  1817. snapshot_name, ret, strerror(-ret));
  1818. }
  1819. break;
  1820. case SNAPSHOT_DELETE:
  1821. ret = bdrv_snapshot_delete(bs, snapshot_name);
  1822. if (ret) {
  1823. error_report("Could not delete snapshot '%s': %d (%s)",
  1824. snapshot_name, ret, strerror(-ret));
  1825. }
  1826. break;
  1827. }
  1828. /* Cleanup */
  1829. bdrv_delete(bs);
  1830. if (ret) {
  1831. return 1;
  1832. }
  1833. return 0;
  1834. }
  1835. static int img_rebase(int argc, char **argv)
  1836. {
  1837. BlockDriverState *bs, *bs_old_backing = NULL, *bs_new_backing = NULL;
  1838. BlockDriver *old_backing_drv, *new_backing_drv;
  1839. char *filename;
  1840. const char *fmt, *cache, *out_basefmt, *out_baseimg;
  1841. int c, flags, ret;
  1842. int unsafe = 0;
  1843. int progress = 0;
  1844. bool quiet = false;
  1845. /* Parse commandline parameters */
  1846. fmt = NULL;
  1847. cache = BDRV_DEFAULT_CACHE;
  1848. out_baseimg = NULL;
  1849. out_basefmt = NULL;
  1850. for(;;) {
  1851. c = getopt(argc, argv, "uhf:F:b:pt:q");
  1852. if (c == -1) {
  1853. break;
  1854. }
  1855. switch(c) {
  1856. case '?':
  1857. case 'h':
  1858. help();
  1859. return 0;
  1860. case 'f':
  1861. fmt = optarg;
  1862. break;
  1863. case 'F':
  1864. out_basefmt = optarg;
  1865. break;
  1866. case 'b':
  1867. out_baseimg = optarg;
  1868. break;
  1869. case 'u':
  1870. unsafe = 1;
  1871. break;
  1872. case 'p':
  1873. progress = 1;
  1874. break;
  1875. case 't':
  1876. cache = optarg;
  1877. break;
  1878. case 'q':
  1879. quiet = true;
  1880. break;
  1881. }
  1882. }
  1883. if (quiet) {
  1884. progress = 0;
  1885. }
  1886. if ((optind >= argc) || (!unsafe && !out_baseimg)) {
  1887. help();
  1888. }
  1889. filename = argv[optind++];
  1890. qemu_progress_init(progress, 2.0);
  1891. qemu_progress_print(0, 100);
  1892. flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
  1893. ret = bdrv_parse_cache_flags(cache, &flags);
  1894. if (ret < 0) {
  1895. error_report("Invalid cache option: %s", cache);
  1896. return -1;
  1897. }
  1898. /*
  1899. * Open the images.
  1900. *
  1901. * Ignore the old backing file for unsafe rebase in case we want to correct
  1902. * the reference to a renamed or moved backing file.
  1903. */
  1904. bs = bdrv_new_open(filename, fmt, flags, true, quiet);
  1905. if (!bs) {
  1906. return 1;
  1907. }
  1908. /* Find the right drivers for the backing files */
  1909. old_backing_drv = NULL;
  1910. new_backing_drv = NULL;
  1911. if (!unsafe && bs->backing_format[0] != '\0') {
  1912. old_backing_drv = bdrv_find_format(bs->backing_format);
  1913. if (old_backing_drv == NULL) {
  1914. error_report("Invalid format name: '%s'", bs->backing_format);
  1915. ret = -1;
  1916. goto out;
  1917. }
  1918. }
  1919. if (out_basefmt != NULL) {
  1920. new_backing_drv = bdrv_find_format(out_basefmt);
  1921. if (new_backing_drv == NULL) {
  1922. error_report("Invalid format name: '%s'", out_basefmt);
  1923. ret = -1;
  1924. goto out;
  1925. }
  1926. }
  1927. /* For safe rebasing we need to compare old and new backing file */
  1928. if (unsafe) {
  1929. /* Make the compiler happy */
  1930. bs_old_backing = NULL;
  1931. bs_new_backing = NULL;
  1932. } else {
  1933. char backing_name[1024];
  1934. bs_old_backing = bdrv_new("old_backing");
  1935. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  1936. ret = bdrv_open(bs_old_backing, backing_name, BDRV_O_FLAGS,
  1937. old_backing_drv);
  1938. if (ret) {
  1939. error_report("Could not open old backing file '%s'", backing_name);
  1940. goto out;
  1941. }
  1942. if (out_baseimg[0]) {
  1943. bs_new_backing = bdrv_new("new_backing");
  1944. ret = bdrv_open(bs_new_backing, out_baseimg, BDRV_O_FLAGS,
  1945. new_backing_drv);
  1946. if (ret) {
  1947. error_report("Could not open new backing file '%s'",
  1948. out_baseimg);
  1949. goto out;
  1950. }
  1951. }
  1952. }
  1953. /*
  1954. * Check each unallocated cluster in the COW file. If it is unallocated,
  1955. * accesses go to the backing file. We must therefore compare this cluster
  1956. * in the old and new backing file, and if they differ we need to copy it
  1957. * from the old backing file into the COW file.
  1958. *
  1959. * If qemu-img crashes during this step, no harm is done. The content of
  1960. * the image is the same as the original one at any time.
  1961. */
  1962. if (!unsafe) {
  1963. uint64_t num_sectors;
  1964. uint64_t old_backing_num_sectors;
  1965. uint64_t new_backing_num_sectors = 0;
  1966. uint64_t sector;
  1967. int n;
  1968. uint8_t * buf_old;
  1969. uint8_t * buf_new;
  1970. float local_progress = 0;
  1971. buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
  1972. buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
  1973. bdrv_get_geometry(bs, &num_sectors);
  1974. bdrv_get_geometry(bs_old_backing, &old_backing_num_sectors);
  1975. if (bs_new_backing) {
  1976. bdrv_get_geometry(bs_new_backing, &new_backing_num_sectors);
  1977. }
  1978. if (num_sectors != 0) {
  1979. local_progress = (float)100 /
  1980. (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
  1981. }
  1982. for (sector = 0; sector < num_sectors; sector += n) {
  1983. /* How many sectors can we handle with the next read? */
  1984. if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
  1985. n = (IO_BUF_SIZE / 512);
  1986. } else {
  1987. n = num_sectors - sector;
  1988. }
  1989. /* If the cluster is allocated, we don't need to take action */
  1990. ret = bdrv_is_allocated(bs, sector, n, &n);
  1991. if (ret) {
  1992. continue;
  1993. }
  1994. /*
  1995. * Read old and new backing file and take into consideration that
  1996. * backing files may be smaller than the COW image.
  1997. */
  1998. if (sector >= old_backing_num_sectors) {
  1999. memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
  2000. } else {
  2001. if (sector + n > old_backing_num_sectors) {
  2002. n = old_backing_num_sectors - sector;
  2003. }
  2004. ret = bdrv_read(bs_old_backing, sector, buf_old, n);
  2005. if (ret < 0) {
  2006. error_report("error while reading from old backing file");
  2007. goto out;
  2008. }
  2009. }
  2010. if (sector >= new_backing_num_sectors || !bs_new_backing) {
  2011. memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
  2012. } else {
  2013. if (sector + n > new_backing_num_sectors) {
  2014. n = new_backing_num_sectors - sector;
  2015. }
  2016. ret = bdrv_read(bs_new_backing, sector, buf_new, n);
  2017. if (ret < 0) {
  2018. error_report("error while reading from new backing file");
  2019. goto out;
  2020. }
  2021. }
  2022. /* If they differ, we need to write to the COW file */
  2023. uint64_t written = 0;
  2024. while (written < n) {
  2025. int pnum;
  2026. if (compare_sectors(buf_old + written * 512,
  2027. buf_new + written * 512, n - written, &pnum))
  2028. {
  2029. ret = bdrv_write(bs, sector + written,
  2030. buf_old + written * 512, pnum);
  2031. if (ret < 0) {
  2032. error_report("Error while writing to COW image: %s",
  2033. strerror(-ret));
  2034. goto out;
  2035. }
  2036. }
  2037. written += pnum;
  2038. }
  2039. qemu_progress_print(local_progress, 100);
  2040. }
  2041. qemu_vfree(buf_old);
  2042. qemu_vfree(buf_new);
  2043. }
  2044. /*
  2045. * Change the backing file. All clusters that are different from the old
  2046. * backing file are overwritten in the COW file now, so the visible content
  2047. * doesn't change when we switch the backing file.
  2048. */
  2049. if (out_baseimg && *out_baseimg) {
  2050. ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
  2051. } else {
  2052. ret = bdrv_change_backing_file(bs, NULL, NULL);
  2053. }
  2054. if (ret == -ENOSPC) {
  2055. error_report("Could not change the backing file to '%s': No "
  2056. "space left in the file header", out_baseimg);
  2057. } else if (ret < 0) {
  2058. error_report("Could not change the backing file to '%s': %s",
  2059. out_baseimg, strerror(-ret));
  2060. }
  2061. qemu_progress_print(100, 0);
  2062. /*
  2063. * TODO At this point it is possible to check if any clusters that are
  2064. * allocated in the COW file are the same in the backing file. If so, they
  2065. * could be dropped from the COW file. Don't do this before switching the
  2066. * backing file, in case of a crash this would lead to corruption.
  2067. */
  2068. out:
  2069. qemu_progress_end();
  2070. /* Cleanup */
  2071. if (!unsafe) {
  2072. if (bs_old_backing != NULL) {
  2073. bdrv_delete(bs_old_backing);
  2074. }
  2075. if (bs_new_backing != NULL) {
  2076. bdrv_delete(bs_new_backing);
  2077. }
  2078. }
  2079. bdrv_delete(bs);
  2080. if (ret) {
  2081. return 1;
  2082. }
  2083. return 0;
  2084. }
  2085. static int img_resize(int argc, char **argv)
  2086. {
  2087. int c, ret, relative;
  2088. const char *filename, *fmt, *size;
  2089. int64_t n, total_size;
  2090. bool quiet = false;
  2091. BlockDriverState *bs = NULL;
  2092. QemuOpts *param;
  2093. static QemuOptsList resize_options = {
  2094. .name = "resize_options",
  2095. .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
  2096. .desc = {
  2097. {
  2098. .name = BLOCK_OPT_SIZE,
  2099. .type = QEMU_OPT_SIZE,
  2100. .help = "Virtual disk size"
  2101. }, {
  2102. /* end of list */
  2103. }
  2104. },
  2105. };
  2106. /* Remove size from argv manually so that negative numbers are not treated
  2107. * as options by getopt. */
  2108. if (argc < 3) {
  2109. help();
  2110. return 1;
  2111. }
  2112. size = argv[--argc];
  2113. /* Parse getopt arguments */
  2114. fmt = NULL;
  2115. for(;;) {
  2116. c = getopt(argc, argv, "f:hq");
  2117. if (c == -1) {
  2118. break;
  2119. }
  2120. switch(c) {
  2121. case '?':
  2122. case 'h':
  2123. help();
  2124. break;
  2125. case 'f':
  2126. fmt = optarg;
  2127. break;
  2128. case 'q':
  2129. quiet = true;
  2130. break;
  2131. }
  2132. }
  2133. if (optind >= argc) {
  2134. help();
  2135. }
  2136. filename = argv[optind++];
  2137. /* Choose grow, shrink, or absolute resize mode */
  2138. switch (size[0]) {
  2139. case '+':
  2140. relative = 1;
  2141. size++;
  2142. break;
  2143. case '-':
  2144. relative = -1;
  2145. size++;
  2146. break;
  2147. default:
  2148. relative = 0;
  2149. break;
  2150. }
  2151. /* Parse size */
  2152. param = qemu_opts_create_nofail(&resize_options);
  2153. if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
  2154. /* Error message already printed when size parsing fails */
  2155. ret = -1;
  2156. qemu_opts_del(param);
  2157. goto out;
  2158. }
  2159. n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
  2160. qemu_opts_del(param);
  2161. bs = bdrv_new_open(filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR, true, quiet);
  2162. if (!bs) {
  2163. ret = -1;
  2164. goto out;
  2165. }
  2166. if (relative) {
  2167. total_size = bdrv_getlength(bs) + n * relative;
  2168. } else {
  2169. total_size = n;
  2170. }
  2171. if (total_size <= 0) {
  2172. error_report("New image size must be positive");
  2173. ret = -1;
  2174. goto out;
  2175. }
  2176. ret = bdrv_truncate(bs, total_size);
  2177. switch (ret) {
  2178. case 0:
  2179. qprintf(quiet, "Image resized.\n");
  2180. break;
  2181. case -ENOTSUP:
  2182. error_report("This image does not support resize");
  2183. break;
  2184. case -EACCES:
  2185. error_report("Image is read-only");
  2186. break;
  2187. default:
  2188. error_report("Error resizing image (%d)", -ret);
  2189. break;
  2190. }
  2191. out:
  2192. if (bs) {
  2193. bdrv_delete(bs);
  2194. }
  2195. if (ret) {
  2196. return 1;
  2197. }
  2198. return 0;
  2199. }
  2200. static const img_cmd_t img_cmds[] = {
  2201. #define DEF(option, callback, arg_string) \
  2202. { option, callback },
  2203. #include "qemu-img-cmds.h"
  2204. #undef DEF
  2205. #undef GEN_DOCS
  2206. { NULL, NULL, },
  2207. };
  2208. int main(int argc, char **argv)
  2209. {
  2210. const img_cmd_t *cmd;
  2211. const char *cmdname;
  2212. error_set_progname(argv[0]);
  2213. qemu_init_main_loop();
  2214. bdrv_init();
  2215. if (argc < 2)
  2216. help();
  2217. cmdname = argv[1];
  2218. argc--; argv++;
  2219. /* find the command */
  2220. for(cmd = img_cmds; cmd->name != NULL; cmd++) {
  2221. if (!strcmp(cmdname, cmd->name)) {
  2222. return cmd->handler(argc, argv);
  2223. }
  2224. }
  2225. /* not found */
  2226. help();
  2227. return 0;
  2228. }