2
0

qemu-img.c 89 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086
  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 "sysemu/block-backend.h"
  33. #include "block/block_int.h"
  34. #include "block/blockjob.h"
  35. #include "block/qapi.h"
  36. #include <getopt.h>
  37. #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION \
  38. ", Copyright (c) 2004-2008 Fabrice Bellard\n"
  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. static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
  59. {
  60. va_list ap;
  61. error_printf("qemu-img: ");
  62. va_start(ap, fmt);
  63. error_vprintf(fmt, ap);
  64. va_end(ap);
  65. error_printf("\nTry 'qemu-img --help' for more information\n");
  66. exit(EXIT_FAILURE);
  67. }
  68. /* Please keep in synch with qemu-img.texi */
  69. static void QEMU_NORETURN help(void)
  70. {
  71. const char *help_msg =
  72. QEMU_IMG_VERSION
  73. "usage: qemu-img command [command options]\n"
  74. "QEMU disk image utility\n"
  75. "\n"
  76. "Command syntax:\n"
  77. #define DEF(option, callback, arg_string) \
  78. " " arg_string "\n"
  79. #include "qemu-img-cmds.h"
  80. #undef DEF
  81. #undef GEN_DOCS
  82. "\n"
  83. "Command parameters:\n"
  84. " 'filename' is a disk image filename\n"
  85. " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
  86. " 'cache' is the cache mode used to write the output disk image, the valid\n"
  87. " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
  88. " 'directsync' and 'unsafe' (default for convert)\n"
  89. " 'src_cache' is the cache mode used to read input disk images, the valid\n"
  90. " options are the same as for the 'cache' option\n"
  91. " 'size' is the disk image size in bytes. Optional suffixes\n"
  92. " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
  93. " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
  94. " supported. 'b' is ignored.\n"
  95. " 'output_filename' is the destination disk image filename\n"
  96. " 'output_fmt' is the destination format\n"
  97. " 'options' is a comma separated list of format specific options in a\n"
  98. " name=value format. Use -o ? for an overview of the options supported by the\n"
  99. " used format\n"
  100. " 'snapshot_param' is param used for internal snapshot, format\n"
  101. " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
  102. " '[ID_OR_NAME]'\n"
  103. " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
  104. " instead\n"
  105. " '-c' indicates that target image must be compressed (qcow format only)\n"
  106. " '-u' enables unsafe rebasing. It is assumed that old and new backing file\n"
  107. " match exactly. The image doesn't need a working backing file before\n"
  108. " rebasing in this case (useful for renaming the backing file)\n"
  109. " '-h' with or without a command shows this help and lists the supported formats\n"
  110. " '-p' show progress of command (only certain commands)\n"
  111. " '-q' use Quiet mode - do not print any output (except errors)\n"
  112. " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
  113. " contain only zeros for qemu-img to create a sparse image during\n"
  114. " conversion. If the number of bytes is 0, the source will not be scanned for\n"
  115. " unallocated or zero sectors, and the destination image will always be\n"
  116. " fully allocated\n"
  117. " '--output' takes the format in which the output must be done (human or json)\n"
  118. " '-n' skips the target volume creation (useful if the volume is created\n"
  119. " prior to running qemu-img)\n"
  120. "\n"
  121. "Parameters to check subcommand:\n"
  122. " '-r' tries to repair any inconsistencies that are found during the check.\n"
  123. " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
  124. " kinds of errors, with a higher risk of choosing the wrong fix or\n"
  125. " hiding corruption that has already occurred.\n"
  126. "\n"
  127. "Parameters to snapshot subcommand:\n"
  128. " 'snapshot' is the name of the snapshot to create, apply or delete\n"
  129. " '-a' applies a snapshot (revert disk to saved state)\n"
  130. " '-c' creates a snapshot\n"
  131. " '-d' deletes a snapshot\n"
  132. " '-l' lists all snapshots in the given image\n"
  133. "\n"
  134. "Parameters to compare subcommand:\n"
  135. " '-f' first image format\n"
  136. " '-F' second image format\n"
  137. " '-s' run in Strict mode - fail on different image size or sector allocation\n";
  138. printf("%s\nSupported formats:", help_msg);
  139. bdrv_iterate_format(format_print, NULL);
  140. printf("\n");
  141. exit(EXIT_SUCCESS);
  142. }
  143. static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
  144. {
  145. int ret = 0;
  146. if (!quiet) {
  147. va_list args;
  148. va_start(args, fmt);
  149. ret = vprintf(fmt, args);
  150. va_end(args);
  151. }
  152. return ret;
  153. }
  154. #if defined(WIN32)
  155. /* XXX: put correct support for win32 */
  156. static int read_password(char *buf, int buf_size)
  157. {
  158. int c, i;
  159. printf("Password: ");
  160. fflush(stdout);
  161. i = 0;
  162. for(;;) {
  163. c = getchar();
  164. if (c < 0) {
  165. buf[i] = '\0';
  166. return -1;
  167. } else if (c == '\n') {
  168. break;
  169. } else if (i < (buf_size - 1)) {
  170. buf[i++] = c;
  171. }
  172. }
  173. buf[i] = '\0';
  174. return 0;
  175. }
  176. #else
  177. #include <termios.h>
  178. static struct termios oldtty;
  179. static void term_exit(void)
  180. {
  181. tcsetattr (0, TCSANOW, &oldtty);
  182. }
  183. static void term_init(void)
  184. {
  185. struct termios tty;
  186. tcgetattr (0, &tty);
  187. oldtty = tty;
  188. tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
  189. |INLCR|IGNCR|ICRNL|IXON);
  190. tty.c_oflag |= OPOST;
  191. tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
  192. tty.c_cflag &= ~(CSIZE|PARENB);
  193. tty.c_cflag |= CS8;
  194. tty.c_cc[VMIN] = 1;
  195. tty.c_cc[VTIME] = 0;
  196. tcsetattr (0, TCSANOW, &tty);
  197. atexit(term_exit);
  198. }
  199. static int read_password(char *buf, int buf_size)
  200. {
  201. uint8_t ch;
  202. int i, ret;
  203. printf("password: ");
  204. fflush(stdout);
  205. term_init();
  206. i = 0;
  207. for(;;) {
  208. ret = read(0, &ch, 1);
  209. if (ret == -1) {
  210. if (errno == EAGAIN || errno == EINTR) {
  211. continue;
  212. } else {
  213. break;
  214. }
  215. } else if (ret == 0) {
  216. ret = -1;
  217. break;
  218. } else {
  219. if (ch == '\r') {
  220. ret = 0;
  221. break;
  222. }
  223. if (i < (buf_size - 1))
  224. buf[i++] = ch;
  225. }
  226. }
  227. term_exit();
  228. buf[i] = '\0';
  229. printf("\n");
  230. return ret;
  231. }
  232. #endif
  233. static int print_block_option_help(const char *filename, const char *fmt)
  234. {
  235. BlockDriver *drv, *proto_drv;
  236. QemuOptsList *create_opts = NULL;
  237. /* Find driver and parse its options */
  238. drv = bdrv_find_format(fmt);
  239. if (!drv) {
  240. error_report("Unknown file format '%s'", fmt);
  241. return 1;
  242. }
  243. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  244. if (filename) {
  245. proto_drv = bdrv_find_protocol(filename, true);
  246. if (!proto_drv) {
  247. error_report("Unknown protocol '%s'", filename);
  248. qemu_opts_free(create_opts);
  249. return 1;
  250. }
  251. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  252. }
  253. qemu_opts_print_help(create_opts);
  254. qemu_opts_free(create_opts);
  255. return 0;
  256. }
  257. static BlockBackend *img_open(const char *id, const char *filename,
  258. const char *fmt, int flags,
  259. bool require_io, bool quiet)
  260. {
  261. BlockBackend *blk;
  262. BlockDriverState *bs;
  263. BlockDriver *drv;
  264. char password[256];
  265. Error *local_err = NULL;
  266. int ret;
  267. blk = blk_new_with_bs(id, &error_abort);
  268. bs = blk_bs(blk);
  269. if (fmt) {
  270. drv = bdrv_find_format(fmt);
  271. if (!drv) {
  272. error_report("Unknown file format '%s'", fmt);
  273. goto fail;
  274. }
  275. } else {
  276. drv = NULL;
  277. }
  278. ret = bdrv_open(&bs, filename, NULL, NULL, flags, drv, &local_err);
  279. if (ret < 0) {
  280. error_report("Could not open '%s': %s", filename,
  281. error_get_pretty(local_err));
  282. error_free(local_err);
  283. goto fail;
  284. }
  285. if (bdrv_is_encrypted(bs) && require_io) {
  286. qprintf(quiet, "Disk image '%s' is encrypted.\n", filename);
  287. if (read_password(password, sizeof(password)) < 0) {
  288. error_report("No password given");
  289. goto fail;
  290. }
  291. if (bdrv_set_key(bs, password) < 0) {
  292. error_report("invalid password");
  293. goto fail;
  294. }
  295. }
  296. return blk;
  297. fail:
  298. blk_unref(blk);
  299. return NULL;
  300. }
  301. static int add_old_style_options(const char *fmt, QemuOpts *opts,
  302. const char *base_filename,
  303. const char *base_fmt)
  304. {
  305. if (base_filename) {
  306. if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
  307. error_report("Backing file not supported for file format '%s'",
  308. fmt);
  309. return -1;
  310. }
  311. }
  312. if (base_fmt) {
  313. if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
  314. error_report("Backing file format not supported for file "
  315. "format '%s'", fmt);
  316. return -1;
  317. }
  318. }
  319. return 0;
  320. }
  321. static int img_create(int argc, char **argv)
  322. {
  323. int c;
  324. uint64_t img_size = -1;
  325. const char *fmt = "raw";
  326. const char *base_fmt = NULL;
  327. const char *filename;
  328. const char *base_filename = NULL;
  329. char *options = NULL;
  330. Error *local_err = NULL;
  331. bool quiet = false;
  332. for(;;) {
  333. c = getopt(argc, argv, "F:b:f:he6o:q");
  334. if (c == -1) {
  335. break;
  336. }
  337. switch(c) {
  338. case '?':
  339. case 'h':
  340. help();
  341. break;
  342. case 'F':
  343. base_fmt = optarg;
  344. break;
  345. case 'b':
  346. base_filename = optarg;
  347. break;
  348. case 'f':
  349. fmt = optarg;
  350. break;
  351. case 'e':
  352. error_report("option -e is deprecated, please use \'-o "
  353. "encryption\' instead!");
  354. goto fail;
  355. case '6':
  356. error_report("option -6 is deprecated, please use \'-o "
  357. "compat6\' instead!");
  358. goto fail;
  359. case 'o':
  360. if (!is_valid_option_list(optarg)) {
  361. error_report("Invalid option list: %s", optarg);
  362. goto fail;
  363. }
  364. if (!options) {
  365. options = g_strdup(optarg);
  366. } else {
  367. char *old_options = options;
  368. options = g_strdup_printf("%s,%s", options, optarg);
  369. g_free(old_options);
  370. }
  371. break;
  372. case 'q':
  373. quiet = true;
  374. break;
  375. }
  376. }
  377. /* Get the filename */
  378. filename = (optind < argc) ? argv[optind] : NULL;
  379. if (options && has_help_option(options)) {
  380. g_free(options);
  381. return print_block_option_help(filename, fmt);
  382. }
  383. if (optind >= argc) {
  384. error_exit("Expecting image file name");
  385. }
  386. optind++;
  387. /* Get image size, if specified */
  388. if (optind < argc) {
  389. int64_t sval;
  390. char *end;
  391. sval = strtosz_suffix(argv[optind++], &end, STRTOSZ_DEFSUFFIX_B);
  392. if (sval < 0 || *end) {
  393. if (sval == -ERANGE) {
  394. error_report("Image size must be less than 8 EiB!");
  395. } else {
  396. error_report("Invalid image size specified! You may use k, M, "
  397. "G, T, P or E suffixes for ");
  398. error_report("kilobytes, megabytes, gigabytes, terabytes, "
  399. "petabytes and exabytes.");
  400. }
  401. goto fail;
  402. }
  403. img_size = (uint64_t)sval;
  404. }
  405. if (optind != argc) {
  406. error_exit("Unexpected argument: %s", argv[optind]);
  407. }
  408. bdrv_img_create(filename, fmt, base_filename, base_fmt,
  409. options, img_size, BDRV_O_FLAGS, &local_err, quiet);
  410. if (local_err) {
  411. error_report("%s: %s", filename, error_get_pretty(local_err));
  412. error_free(local_err);
  413. goto fail;
  414. }
  415. g_free(options);
  416. return 0;
  417. fail:
  418. g_free(options);
  419. return 1;
  420. }
  421. static void dump_json_image_check(ImageCheck *check, bool quiet)
  422. {
  423. Error *local_err = NULL;
  424. QString *str;
  425. QmpOutputVisitor *ov = qmp_output_visitor_new();
  426. QObject *obj;
  427. visit_type_ImageCheck(qmp_output_get_visitor(ov),
  428. &check, NULL, &local_err);
  429. obj = qmp_output_get_qobject(ov);
  430. str = qobject_to_json_pretty(obj);
  431. assert(str != NULL);
  432. qprintf(quiet, "%s\n", qstring_get_str(str));
  433. qobject_decref(obj);
  434. qmp_output_visitor_cleanup(ov);
  435. QDECREF(str);
  436. }
  437. static void dump_human_image_check(ImageCheck *check, bool quiet)
  438. {
  439. if (!(check->corruptions || check->leaks || check->check_errors)) {
  440. qprintf(quiet, "No errors were found on the image.\n");
  441. } else {
  442. if (check->corruptions) {
  443. qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
  444. "Data may be corrupted, or further writes to the image "
  445. "may corrupt it.\n",
  446. check->corruptions);
  447. }
  448. if (check->leaks) {
  449. qprintf(quiet,
  450. "\n%" PRId64 " leaked clusters were found on the image.\n"
  451. "This means waste of disk space, but no harm to data.\n",
  452. check->leaks);
  453. }
  454. if (check->check_errors) {
  455. qprintf(quiet,
  456. "\n%" PRId64
  457. " internal errors have occurred during the check.\n",
  458. check->check_errors);
  459. }
  460. }
  461. if (check->total_clusters != 0 && check->allocated_clusters != 0) {
  462. qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
  463. "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
  464. check->allocated_clusters, check->total_clusters,
  465. check->allocated_clusters * 100.0 / check->total_clusters,
  466. check->fragmented_clusters * 100.0 / check->allocated_clusters,
  467. check->compressed_clusters * 100.0 /
  468. check->allocated_clusters);
  469. }
  470. if (check->image_end_offset) {
  471. qprintf(quiet,
  472. "Image end offset: %" PRId64 "\n", check->image_end_offset);
  473. }
  474. }
  475. static int collect_image_check(BlockDriverState *bs,
  476. ImageCheck *check,
  477. const char *filename,
  478. const char *fmt,
  479. int fix)
  480. {
  481. int ret;
  482. BdrvCheckResult result;
  483. ret = bdrv_check(bs, &result, fix);
  484. if (ret < 0) {
  485. return ret;
  486. }
  487. check->filename = g_strdup(filename);
  488. check->format = g_strdup(bdrv_get_format_name(bs));
  489. check->check_errors = result.check_errors;
  490. check->corruptions = result.corruptions;
  491. check->has_corruptions = result.corruptions != 0;
  492. check->leaks = result.leaks;
  493. check->has_leaks = result.leaks != 0;
  494. check->corruptions_fixed = result.corruptions_fixed;
  495. check->has_corruptions_fixed = result.corruptions != 0;
  496. check->leaks_fixed = result.leaks_fixed;
  497. check->has_leaks_fixed = result.leaks != 0;
  498. check->image_end_offset = result.image_end_offset;
  499. check->has_image_end_offset = result.image_end_offset != 0;
  500. check->total_clusters = result.bfi.total_clusters;
  501. check->has_total_clusters = result.bfi.total_clusters != 0;
  502. check->allocated_clusters = result.bfi.allocated_clusters;
  503. check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
  504. check->fragmented_clusters = result.bfi.fragmented_clusters;
  505. check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
  506. check->compressed_clusters = result.bfi.compressed_clusters;
  507. check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
  508. return 0;
  509. }
  510. /*
  511. * Checks an image for consistency. Exit codes:
  512. *
  513. * 0 - Check completed, image is good
  514. * 1 - Check not completed because of internal errors
  515. * 2 - Check completed, image is corrupted
  516. * 3 - Check completed, image has leaked clusters, but is good otherwise
  517. * 63 - Checks are not supported by the image format
  518. */
  519. static int img_check(int argc, char **argv)
  520. {
  521. int c, ret;
  522. OutputFormat output_format = OFORMAT_HUMAN;
  523. const char *filename, *fmt, *output, *cache;
  524. BlockBackend *blk;
  525. BlockDriverState *bs;
  526. int fix = 0;
  527. int flags = BDRV_O_FLAGS | BDRV_O_CHECK;
  528. ImageCheck *check;
  529. bool quiet = false;
  530. fmt = NULL;
  531. output = NULL;
  532. cache = BDRV_DEFAULT_CACHE;
  533. for(;;) {
  534. int option_index = 0;
  535. static const struct option long_options[] = {
  536. {"help", no_argument, 0, 'h'},
  537. {"format", required_argument, 0, 'f'},
  538. {"repair", required_argument, 0, 'r'},
  539. {"output", required_argument, 0, OPTION_OUTPUT},
  540. {0, 0, 0, 0}
  541. };
  542. c = getopt_long(argc, argv, "hf:r:T:q",
  543. long_options, &option_index);
  544. if (c == -1) {
  545. break;
  546. }
  547. switch(c) {
  548. case '?':
  549. case 'h':
  550. help();
  551. break;
  552. case 'f':
  553. fmt = optarg;
  554. break;
  555. case 'r':
  556. flags |= BDRV_O_RDWR;
  557. if (!strcmp(optarg, "leaks")) {
  558. fix = BDRV_FIX_LEAKS;
  559. } else if (!strcmp(optarg, "all")) {
  560. fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
  561. } else {
  562. error_exit("Unknown option value for -r "
  563. "(expecting 'leaks' or 'all'): %s", optarg);
  564. }
  565. break;
  566. case OPTION_OUTPUT:
  567. output = optarg;
  568. break;
  569. case 'T':
  570. cache = optarg;
  571. break;
  572. case 'q':
  573. quiet = true;
  574. break;
  575. }
  576. }
  577. if (optind != argc - 1) {
  578. error_exit("Expecting one image file name");
  579. }
  580. filename = argv[optind++];
  581. if (output && !strcmp(output, "json")) {
  582. output_format = OFORMAT_JSON;
  583. } else if (output && !strcmp(output, "human")) {
  584. output_format = OFORMAT_HUMAN;
  585. } else if (output) {
  586. error_report("--output must be used with human or json as argument.");
  587. return 1;
  588. }
  589. ret = bdrv_parse_cache_flags(cache, &flags);
  590. if (ret < 0) {
  591. error_report("Invalid source cache option: %s", cache);
  592. return 1;
  593. }
  594. blk = img_open("image", filename, fmt, flags, true, quiet);
  595. if (!blk) {
  596. return 1;
  597. }
  598. bs = blk_bs(blk);
  599. check = g_new0(ImageCheck, 1);
  600. ret = collect_image_check(bs, check, filename, fmt, fix);
  601. if (ret == -ENOTSUP) {
  602. error_report("This image format does not support checks");
  603. ret = 63;
  604. goto fail;
  605. }
  606. if (check->corruptions_fixed || check->leaks_fixed) {
  607. int corruptions_fixed, leaks_fixed;
  608. leaks_fixed = check->leaks_fixed;
  609. corruptions_fixed = check->corruptions_fixed;
  610. if (output_format == OFORMAT_HUMAN) {
  611. qprintf(quiet,
  612. "The following inconsistencies were found and repaired:\n\n"
  613. " %" PRId64 " leaked clusters\n"
  614. " %" PRId64 " corruptions\n\n"
  615. "Double checking the fixed image now...\n",
  616. check->leaks_fixed,
  617. check->corruptions_fixed);
  618. }
  619. ret = collect_image_check(bs, check, filename, fmt, 0);
  620. check->leaks_fixed = leaks_fixed;
  621. check->corruptions_fixed = corruptions_fixed;
  622. }
  623. if (!ret) {
  624. switch (output_format) {
  625. case OFORMAT_HUMAN:
  626. dump_human_image_check(check, quiet);
  627. break;
  628. case OFORMAT_JSON:
  629. dump_json_image_check(check, quiet);
  630. break;
  631. }
  632. }
  633. if (ret || check->check_errors) {
  634. if (ret) {
  635. error_report("Check failed: %s", strerror(-ret));
  636. } else {
  637. error_report("Check failed");
  638. }
  639. ret = 1;
  640. goto fail;
  641. }
  642. if (check->corruptions) {
  643. ret = 2;
  644. } else if (check->leaks) {
  645. ret = 3;
  646. } else {
  647. ret = 0;
  648. }
  649. fail:
  650. qapi_free_ImageCheck(check);
  651. blk_unref(blk);
  652. return ret;
  653. }
  654. typedef struct CommonBlockJobCBInfo {
  655. BlockDriverState *bs;
  656. Error **errp;
  657. } CommonBlockJobCBInfo;
  658. static void common_block_job_cb(void *opaque, int ret)
  659. {
  660. CommonBlockJobCBInfo *cbi = opaque;
  661. if (ret < 0) {
  662. error_setg_errno(cbi->errp, -ret, "Block job failed");
  663. }
  664. /* Drop this block job's reference */
  665. bdrv_unref(cbi->bs);
  666. }
  667. static void run_block_job(BlockJob *job, Error **errp)
  668. {
  669. AioContext *aio_context = bdrv_get_aio_context(job->bs);
  670. do {
  671. aio_poll(aio_context, true);
  672. qemu_progress_print((float)job->offset / job->len * 100.f, 0);
  673. } while (!job->ready);
  674. block_job_complete_sync(job, errp);
  675. /* A block job may finish instantaneously without publishing any progress,
  676. * so just signal completion here */
  677. qemu_progress_print(100.f, 0);
  678. }
  679. static int img_commit(int argc, char **argv)
  680. {
  681. int c, ret, flags;
  682. const char *filename, *fmt, *cache, *base;
  683. BlockBackend *blk;
  684. BlockDriverState *bs, *base_bs;
  685. bool progress = false, quiet = false, drop = false;
  686. Error *local_err = NULL;
  687. CommonBlockJobCBInfo cbi;
  688. fmt = NULL;
  689. cache = BDRV_DEFAULT_CACHE;
  690. base = NULL;
  691. for(;;) {
  692. c = getopt(argc, argv, "f:ht:b:dpq");
  693. if (c == -1) {
  694. break;
  695. }
  696. switch(c) {
  697. case '?':
  698. case 'h':
  699. help();
  700. break;
  701. case 'f':
  702. fmt = optarg;
  703. break;
  704. case 't':
  705. cache = optarg;
  706. break;
  707. case 'b':
  708. base = optarg;
  709. /* -b implies -d */
  710. drop = true;
  711. break;
  712. case 'd':
  713. drop = true;
  714. break;
  715. case 'p':
  716. progress = true;
  717. break;
  718. case 'q':
  719. quiet = true;
  720. break;
  721. }
  722. }
  723. /* Progress is not shown in Quiet mode */
  724. if (quiet) {
  725. progress = false;
  726. }
  727. if (optind != argc - 1) {
  728. error_exit("Expecting one image file name");
  729. }
  730. filename = argv[optind++];
  731. flags = BDRV_O_RDWR | BDRV_O_UNMAP;
  732. ret = bdrv_parse_cache_flags(cache, &flags);
  733. if (ret < 0) {
  734. error_report("Invalid cache option: %s", cache);
  735. return 1;
  736. }
  737. blk = img_open("image", filename, fmt, flags, true, quiet);
  738. if (!blk) {
  739. return 1;
  740. }
  741. bs = blk_bs(blk);
  742. qemu_progress_init(progress, 1.f);
  743. qemu_progress_print(0.f, 100);
  744. if (base) {
  745. base_bs = bdrv_find_backing_image(bs, base);
  746. if (!base_bs) {
  747. error_set(&local_err, QERR_BASE_NOT_FOUND, base);
  748. goto done;
  749. }
  750. } else {
  751. /* This is different from QMP, which by default uses the deepest file in
  752. * the backing chain (i.e., the very base); however, the traditional
  753. * behavior of qemu-img commit is using the immediate backing file. */
  754. base_bs = bs->backing_hd;
  755. if (!base_bs) {
  756. error_setg(&local_err, "Image does not have a backing file");
  757. goto done;
  758. }
  759. }
  760. cbi = (CommonBlockJobCBInfo){
  761. .errp = &local_err,
  762. .bs = bs,
  763. };
  764. commit_active_start(bs, base_bs, 0, BLOCKDEV_ON_ERROR_REPORT,
  765. common_block_job_cb, &cbi, &local_err);
  766. if (local_err) {
  767. goto done;
  768. }
  769. /* The block job will swap base_bs and bs (which is not what we really want
  770. * here, but okay) and unref base_bs (after the swap, i.e., the old top
  771. * image). In order to still be able to empty that top image afterwards,
  772. * increment the reference counter here preemptively. */
  773. if (!drop) {
  774. bdrv_ref(base_bs);
  775. }
  776. run_block_job(bs->job, &local_err);
  777. if (local_err) {
  778. goto unref_backing;
  779. }
  780. if (!drop && base_bs->drv->bdrv_make_empty) {
  781. ret = base_bs->drv->bdrv_make_empty(base_bs);
  782. if (ret) {
  783. error_setg_errno(&local_err, -ret, "Could not empty %s",
  784. filename);
  785. goto unref_backing;
  786. }
  787. }
  788. unref_backing:
  789. if (!drop) {
  790. bdrv_unref(base_bs);
  791. }
  792. done:
  793. qemu_progress_end();
  794. blk_unref(blk);
  795. if (local_err) {
  796. qerror_report_err(local_err);
  797. error_free(local_err);
  798. return 1;
  799. }
  800. qprintf(quiet, "Image committed.\n");
  801. return 0;
  802. }
  803. /*
  804. * Returns true iff the first sector pointed to by 'buf' contains at least
  805. * a non-NUL byte.
  806. *
  807. * 'pnum' is set to the number of sectors (including and immediately following
  808. * the first one) that are known to be in the same allocated/unallocated state.
  809. */
  810. static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
  811. {
  812. bool is_zero;
  813. int i;
  814. if (n <= 0) {
  815. *pnum = 0;
  816. return 0;
  817. }
  818. is_zero = buffer_is_zero(buf, 512);
  819. for(i = 1; i < n; i++) {
  820. buf += 512;
  821. if (is_zero != buffer_is_zero(buf, 512)) {
  822. break;
  823. }
  824. }
  825. *pnum = i;
  826. return !is_zero;
  827. }
  828. /*
  829. * Like is_allocated_sectors, but if the buffer starts with a used sector,
  830. * up to 'min' consecutive sectors containing zeros are ignored. This avoids
  831. * breaking up write requests for only small sparse areas.
  832. */
  833. static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
  834. int min)
  835. {
  836. int ret;
  837. int num_checked, num_used;
  838. if (n < min) {
  839. min = n;
  840. }
  841. ret = is_allocated_sectors(buf, n, pnum);
  842. if (!ret) {
  843. return ret;
  844. }
  845. num_used = *pnum;
  846. buf += BDRV_SECTOR_SIZE * *pnum;
  847. n -= *pnum;
  848. num_checked = num_used;
  849. while (n > 0) {
  850. ret = is_allocated_sectors(buf, n, pnum);
  851. buf += BDRV_SECTOR_SIZE * *pnum;
  852. n -= *pnum;
  853. num_checked += *pnum;
  854. if (ret) {
  855. num_used = num_checked;
  856. } else if (*pnum >= min) {
  857. break;
  858. }
  859. }
  860. *pnum = num_used;
  861. return 1;
  862. }
  863. /*
  864. * Compares two buffers sector by sector. Returns 0 if the first sector of both
  865. * buffers matches, non-zero otherwise.
  866. *
  867. * pnum is set to the number of sectors (including and immediately following
  868. * the first one) that are known to have the same comparison result
  869. */
  870. static int compare_sectors(const uint8_t *buf1, const uint8_t *buf2, int n,
  871. int *pnum)
  872. {
  873. int res, i;
  874. if (n <= 0) {
  875. *pnum = 0;
  876. return 0;
  877. }
  878. res = !!memcmp(buf1, buf2, 512);
  879. for(i = 1; i < n; i++) {
  880. buf1 += 512;
  881. buf2 += 512;
  882. if (!!memcmp(buf1, buf2, 512) != res) {
  883. break;
  884. }
  885. }
  886. *pnum = i;
  887. return res;
  888. }
  889. #define IO_BUF_SIZE (2 * 1024 * 1024)
  890. static int64_t sectors_to_bytes(int64_t sectors)
  891. {
  892. return sectors << BDRV_SECTOR_BITS;
  893. }
  894. static int64_t sectors_to_process(int64_t total, int64_t from)
  895. {
  896. return MIN(total - from, IO_BUF_SIZE >> BDRV_SECTOR_BITS);
  897. }
  898. /*
  899. * Check if passed sectors are empty (not allocated or contain only 0 bytes)
  900. *
  901. * Returns 0 in case sectors are filled with 0, 1 if sectors contain non-zero
  902. * data and negative value on error.
  903. *
  904. * @param bs: Driver used for accessing file
  905. * @param sect_num: Number of first sector to check
  906. * @param sect_count: Number of sectors to check
  907. * @param filename: Name of disk file we are checking (logging purpose)
  908. * @param buffer: Allocated buffer for storing read data
  909. * @param quiet: Flag for quiet mode
  910. */
  911. static int check_empty_sectors(BlockDriverState *bs, int64_t sect_num,
  912. int sect_count, const char *filename,
  913. uint8_t *buffer, bool quiet)
  914. {
  915. int pnum, ret = 0;
  916. ret = bdrv_read(bs, sect_num, buffer, sect_count);
  917. if (ret < 0) {
  918. error_report("Error while reading offset %" PRId64 " of %s: %s",
  919. sectors_to_bytes(sect_num), filename, strerror(-ret));
  920. return ret;
  921. }
  922. ret = is_allocated_sectors(buffer, sect_count, &pnum);
  923. if (ret || pnum != sect_count) {
  924. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  925. sectors_to_bytes(ret ? sect_num : sect_num + pnum));
  926. return 1;
  927. }
  928. return 0;
  929. }
  930. /*
  931. * Compares two images. Exit codes:
  932. *
  933. * 0 - Images are identical
  934. * 1 - Images differ
  935. * >1 - Error occurred
  936. */
  937. static int img_compare(int argc, char **argv)
  938. {
  939. const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
  940. BlockBackend *blk1, *blk2;
  941. BlockDriverState *bs1, *bs2;
  942. int64_t total_sectors1, total_sectors2;
  943. uint8_t *buf1 = NULL, *buf2 = NULL;
  944. int pnum1, pnum2;
  945. int allocated1, allocated2;
  946. int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
  947. bool progress = false, quiet = false, strict = false;
  948. int flags;
  949. int64_t total_sectors;
  950. int64_t sector_num = 0;
  951. int64_t nb_sectors;
  952. int c, pnum;
  953. uint64_t progress_base;
  954. cache = BDRV_DEFAULT_CACHE;
  955. for (;;) {
  956. c = getopt(argc, argv, "hf:F:T:pqs");
  957. if (c == -1) {
  958. break;
  959. }
  960. switch (c) {
  961. case '?':
  962. case 'h':
  963. help();
  964. break;
  965. case 'f':
  966. fmt1 = optarg;
  967. break;
  968. case 'F':
  969. fmt2 = optarg;
  970. break;
  971. case 'T':
  972. cache = optarg;
  973. break;
  974. case 'p':
  975. progress = true;
  976. break;
  977. case 'q':
  978. quiet = true;
  979. break;
  980. case 's':
  981. strict = true;
  982. break;
  983. }
  984. }
  985. /* Progress is not shown in Quiet mode */
  986. if (quiet) {
  987. progress = false;
  988. }
  989. if (optind != argc - 2) {
  990. error_exit("Expecting two image file names");
  991. }
  992. filename1 = argv[optind++];
  993. filename2 = argv[optind++];
  994. /* Initialize before goto out */
  995. qemu_progress_init(progress, 2.0);
  996. flags = BDRV_O_FLAGS;
  997. ret = bdrv_parse_cache_flags(cache, &flags);
  998. if (ret < 0) {
  999. error_report("Invalid source cache option: %s", cache);
  1000. ret = 2;
  1001. goto out3;
  1002. }
  1003. blk1 = img_open("image_1", filename1, fmt1, flags, true, quiet);
  1004. if (!blk1) {
  1005. ret = 2;
  1006. goto out3;
  1007. }
  1008. bs1 = blk_bs(blk1);
  1009. blk2 = img_open("image_2", filename2, fmt2, flags, true, quiet);
  1010. if (!blk2) {
  1011. ret = 2;
  1012. goto out2;
  1013. }
  1014. bs2 = blk_bs(blk2);
  1015. buf1 = qemu_blockalign(bs1, IO_BUF_SIZE);
  1016. buf2 = qemu_blockalign(bs2, IO_BUF_SIZE);
  1017. total_sectors1 = bdrv_nb_sectors(bs1);
  1018. if (total_sectors1 < 0) {
  1019. error_report("Can't get size of %s: %s",
  1020. filename1, strerror(-total_sectors1));
  1021. ret = 4;
  1022. goto out;
  1023. }
  1024. total_sectors2 = bdrv_nb_sectors(bs2);
  1025. if (total_sectors2 < 0) {
  1026. error_report("Can't get size of %s: %s",
  1027. filename2, strerror(-total_sectors2));
  1028. ret = 4;
  1029. goto out;
  1030. }
  1031. total_sectors = MIN(total_sectors1, total_sectors2);
  1032. progress_base = MAX(total_sectors1, total_sectors2);
  1033. qemu_progress_print(0, 100);
  1034. if (strict && total_sectors1 != total_sectors2) {
  1035. ret = 1;
  1036. qprintf(quiet, "Strict mode: Image size mismatch!\n");
  1037. goto out;
  1038. }
  1039. for (;;) {
  1040. nb_sectors = sectors_to_process(total_sectors, sector_num);
  1041. if (nb_sectors <= 0) {
  1042. break;
  1043. }
  1044. allocated1 = bdrv_is_allocated_above(bs1, NULL, sector_num, nb_sectors,
  1045. &pnum1);
  1046. if (allocated1 < 0) {
  1047. ret = 3;
  1048. error_report("Sector allocation test failed for %s", filename1);
  1049. goto out;
  1050. }
  1051. allocated2 = bdrv_is_allocated_above(bs2, NULL, sector_num, nb_sectors,
  1052. &pnum2);
  1053. if (allocated2 < 0) {
  1054. ret = 3;
  1055. error_report("Sector allocation test failed for %s", filename2);
  1056. goto out;
  1057. }
  1058. nb_sectors = MIN(pnum1, pnum2);
  1059. if (allocated1 == allocated2) {
  1060. if (allocated1) {
  1061. ret = bdrv_read(bs1, sector_num, buf1, nb_sectors);
  1062. if (ret < 0) {
  1063. error_report("Error while reading offset %" PRId64 " of %s:"
  1064. " %s", sectors_to_bytes(sector_num), filename1,
  1065. strerror(-ret));
  1066. ret = 4;
  1067. goto out;
  1068. }
  1069. ret = bdrv_read(bs2, sector_num, buf2, nb_sectors);
  1070. if (ret < 0) {
  1071. error_report("Error while reading offset %" PRId64
  1072. " of %s: %s", sectors_to_bytes(sector_num),
  1073. filename2, strerror(-ret));
  1074. ret = 4;
  1075. goto out;
  1076. }
  1077. ret = compare_sectors(buf1, buf2, nb_sectors, &pnum);
  1078. if (ret || pnum != nb_sectors) {
  1079. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  1080. sectors_to_bytes(
  1081. ret ? sector_num : sector_num + pnum));
  1082. ret = 1;
  1083. goto out;
  1084. }
  1085. }
  1086. } else {
  1087. if (strict) {
  1088. ret = 1;
  1089. qprintf(quiet, "Strict mode: Offset %" PRId64
  1090. " allocation mismatch!\n",
  1091. sectors_to_bytes(sector_num));
  1092. goto out;
  1093. }
  1094. if (allocated1) {
  1095. ret = check_empty_sectors(bs1, sector_num, nb_sectors,
  1096. filename1, buf1, quiet);
  1097. } else {
  1098. ret = check_empty_sectors(bs2, sector_num, nb_sectors,
  1099. filename2, buf1, quiet);
  1100. }
  1101. if (ret) {
  1102. if (ret < 0) {
  1103. error_report("Error while reading offset %" PRId64 ": %s",
  1104. sectors_to_bytes(sector_num), strerror(-ret));
  1105. ret = 4;
  1106. }
  1107. goto out;
  1108. }
  1109. }
  1110. sector_num += nb_sectors;
  1111. qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
  1112. }
  1113. if (total_sectors1 != total_sectors2) {
  1114. BlockDriverState *bs_over;
  1115. int64_t total_sectors_over;
  1116. const char *filename_over;
  1117. qprintf(quiet, "Warning: Image size mismatch!\n");
  1118. if (total_sectors1 > total_sectors2) {
  1119. total_sectors_over = total_sectors1;
  1120. bs_over = bs1;
  1121. filename_over = filename1;
  1122. } else {
  1123. total_sectors_over = total_sectors2;
  1124. bs_over = bs2;
  1125. filename_over = filename2;
  1126. }
  1127. for (;;) {
  1128. nb_sectors = sectors_to_process(total_sectors_over, sector_num);
  1129. if (nb_sectors <= 0) {
  1130. break;
  1131. }
  1132. ret = bdrv_is_allocated_above(bs_over, NULL, sector_num,
  1133. nb_sectors, &pnum);
  1134. if (ret < 0) {
  1135. ret = 3;
  1136. error_report("Sector allocation test failed for %s",
  1137. filename_over);
  1138. goto out;
  1139. }
  1140. nb_sectors = pnum;
  1141. if (ret) {
  1142. ret = check_empty_sectors(bs_over, sector_num, nb_sectors,
  1143. filename_over, buf1, quiet);
  1144. if (ret) {
  1145. if (ret < 0) {
  1146. error_report("Error while reading offset %" PRId64
  1147. " of %s: %s", sectors_to_bytes(sector_num),
  1148. filename_over, strerror(-ret));
  1149. ret = 4;
  1150. }
  1151. goto out;
  1152. }
  1153. }
  1154. sector_num += nb_sectors;
  1155. qemu_progress_print(((float) nb_sectors / progress_base)*100, 100);
  1156. }
  1157. }
  1158. qprintf(quiet, "Images are identical.\n");
  1159. ret = 0;
  1160. out:
  1161. qemu_vfree(buf1);
  1162. qemu_vfree(buf2);
  1163. blk_unref(blk2);
  1164. out2:
  1165. blk_unref(blk1);
  1166. out3:
  1167. qemu_progress_end();
  1168. return ret;
  1169. }
  1170. static int img_convert(int argc, char **argv)
  1171. {
  1172. int c, n, n1, bs_n, bs_i, compress, cluster_sectors, skip_create;
  1173. int64_t ret = 0;
  1174. int progress = 0, flags, src_flags;
  1175. const char *fmt, *out_fmt, *cache, *src_cache, *out_baseimg, *out_filename;
  1176. BlockDriver *drv, *proto_drv;
  1177. BlockBackend **blk = NULL, *out_blk = NULL;
  1178. BlockDriverState **bs = NULL, *out_bs = NULL;
  1179. int64_t total_sectors, nb_sectors, sector_num, bs_offset;
  1180. int64_t *bs_sectors = NULL;
  1181. uint8_t * buf = NULL;
  1182. size_t bufsectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE;
  1183. const uint8_t *buf1;
  1184. BlockDriverInfo bdi;
  1185. QemuOpts *opts = NULL;
  1186. QemuOptsList *create_opts = NULL;
  1187. const char *out_baseimg_param;
  1188. char *options = NULL;
  1189. const char *snapshot_name = NULL;
  1190. int min_sparse = 8; /* Need at least 4k of zeros for sparse detection */
  1191. bool quiet = false;
  1192. Error *local_err = NULL;
  1193. QemuOpts *sn_opts = NULL;
  1194. fmt = NULL;
  1195. out_fmt = "raw";
  1196. cache = "unsafe";
  1197. src_cache = BDRV_DEFAULT_CACHE;
  1198. out_baseimg = NULL;
  1199. compress = 0;
  1200. skip_create = 0;
  1201. for(;;) {
  1202. c = getopt(argc, argv, "hf:O:B:ce6o:s:l:S:pt:T:qn");
  1203. if (c == -1) {
  1204. break;
  1205. }
  1206. switch(c) {
  1207. case '?':
  1208. case 'h':
  1209. help();
  1210. break;
  1211. case 'f':
  1212. fmt = optarg;
  1213. break;
  1214. case 'O':
  1215. out_fmt = optarg;
  1216. break;
  1217. case 'B':
  1218. out_baseimg = optarg;
  1219. break;
  1220. case 'c':
  1221. compress = 1;
  1222. break;
  1223. case 'e':
  1224. error_report("option -e is deprecated, please use \'-o "
  1225. "encryption\' instead!");
  1226. ret = -1;
  1227. goto fail_getopt;
  1228. case '6':
  1229. error_report("option -6 is deprecated, please use \'-o "
  1230. "compat6\' instead!");
  1231. ret = -1;
  1232. goto fail_getopt;
  1233. case 'o':
  1234. if (!is_valid_option_list(optarg)) {
  1235. error_report("Invalid option list: %s", optarg);
  1236. ret = -1;
  1237. goto fail_getopt;
  1238. }
  1239. if (!options) {
  1240. options = g_strdup(optarg);
  1241. } else {
  1242. char *old_options = options;
  1243. options = g_strdup_printf("%s,%s", options, optarg);
  1244. g_free(old_options);
  1245. }
  1246. break;
  1247. case 's':
  1248. snapshot_name = optarg;
  1249. break;
  1250. case 'l':
  1251. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  1252. sn_opts = qemu_opts_parse(&internal_snapshot_opts, optarg, 0);
  1253. if (!sn_opts) {
  1254. error_report("Failed in parsing snapshot param '%s'",
  1255. optarg);
  1256. ret = -1;
  1257. goto fail_getopt;
  1258. }
  1259. } else {
  1260. snapshot_name = optarg;
  1261. }
  1262. break;
  1263. case 'S':
  1264. {
  1265. int64_t sval;
  1266. char *end;
  1267. sval = strtosz_suffix(optarg, &end, STRTOSZ_DEFSUFFIX_B);
  1268. if (sval < 0 || *end) {
  1269. error_report("Invalid minimum zero buffer size for sparse output specified");
  1270. ret = -1;
  1271. goto fail_getopt;
  1272. }
  1273. min_sparse = sval / BDRV_SECTOR_SIZE;
  1274. break;
  1275. }
  1276. case 'p':
  1277. progress = 1;
  1278. break;
  1279. case 't':
  1280. cache = optarg;
  1281. break;
  1282. case 'T':
  1283. src_cache = optarg;
  1284. break;
  1285. case 'q':
  1286. quiet = true;
  1287. break;
  1288. case 'n':
  1289. skip_create = 1;
  1290. break;
  1291. }
  1292. }
  1293. /* Initialize before goto out */
  1294. if (quiet) {
  1295. progress = 0;
  1296. }
  1297. qemu_progress_init(progress, 1.0);
  1298. bs_n = argc - optind - 1;
  1299. out_filename = bs_n >= 1 ? argv[argc - 1] : NULL;
  1300. if (options && has_help_option(options)) {
  1301. ret = print_block_option_help(out_filename, out_fmt);
  1302. goto out;
  1303. }
  1304. if (bs_n < 1) {
  1305. error_exit("Must specify image file name");
  1306. }
  1307. if (bs_n > 1 && out_baseimg) {
  1308. error_report("-B makes no sense when concatenating multiple input "
  1309. "images");
  1310. ret = -1;
  1311. goto out;
  1312. }
  1313. src_flags = BDRV_O_FLAGS;
  1314. ret = bdrv_parse_cache_flags(src_cache, &src_flags);
  1315. if (ret < 0) {
  1316. error_report("Invalid source cache option: %s", src_cache);
  1317. goto out;
  1318. }
  1319. qemu_progress_print(0, 100);
  1320. blk = g_new0(BlockBackend *, bs_n);
  1321. bs = g_new0(BlockDriverState *, bs_n);
  1322. bs_sectors = g_new(int64_t, bs_n);
  1323. total_sectors = 0;
  1324. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  1325. char *id = bs_n > 1 ? g_strdup_printf("source_%d", bs_i)
  1326. : g_strdup("source");
  1327. blk[bs_i] = img_open(id, argv[optind + bs_i], fmt, src_flags,
  1328. true, quiet);
  1329. g_free(id);
  1330. if (!blk[bs_i]) {
  1331. ret = -1;
  1332. goto out;
  1333. }
  1334. bs[bs_i] = blk_bs(blk[bs_i]);
  1335. bs_sectors[bs_i] = bdrv_nb_sectors(bs[bs_i]);
  1336. if (bs_sectors[bs_i] < 0) {
  1337. error_report("Could not get size of %s: %s",
  1338. argv[optind + bs_i], strerror(-bs_sectors[bs_i]));
  1339. ret = -1;
  1340. goto out;
  1341. }
  1342. total_sectors += bs_sectors[bs_i];
  1343. }
  1344. if (sn_opts) {
  1345. ret = bdrv_snapshot_load_tmp(bs[0],
  1346. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  1347. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  1348. &local_err);
  1349. } else if (snapshot_name != NULL) {
  1350. if (bs_n > 1) {
  1351. error_report("No support for concatenating multiple snapshot");
  1352. ret = -1;
  1353. goto out;
  1354. }
  1355. bdrv_snapshot_load_tmp_by_id_or_name(bs[0], snapshot_name, &local_err);
  1356. }
  1357. if (local_err) {
  1358. error_report("Failed to load snapshot: %s",
  1359. error_get_pretty(local_err));
  1360. error_free(local_err);
  1361. ret = -1;
  1362. goto out;
  1363. }
  1364. /* Find driver and parse its options */
  1365. drv = bdrv_find_format(out_fmt);
  1366. if (!drv) {
  1367. error_report("Unknown file format '%s'", out_fmt);
  1368. ret = -1;
  1369. goto out;
  1370. }
  1371. proto_drv = bdrv_find_protocol(out_filename, true);
  1372. if (!proto_drv) {
  1373. error_report("Unknown protocol '%s'", out_filename);
  1374. ret = -1;
  1375. goto out;
  1376. }
  1377. if (!drv->create_opts) {
  1378. error_report("Format driver '%s' does not support image creation",
  1379. drv->format_name);
  1380. ret = -1;
  1381. goto out;
  1382. }
  1383. if (!proto_drv->create_opts) {
  1384. error_report("Protocol driver '%s' does not support image creation",
  1385. proto_drv->format_name);
  1386. ret = -1;
  1387. goto out;
  1388. }
  1389. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  1390. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  1391. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  1392. if (options && qemu_opts_do_parse(opts, options, NULL)) {
  1393. error_report("Invalid options for file format '%s'", out_fmt);
  1394. ret = -1;
  1395. goto out;
  1396. }
  1397. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_sectors * 512);
  1398. ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
  1399. if (ret < 0) {
  1400. goto out;
  1401. }
  1402. /* Get backing file name if -o backing_file was used */
  1403. out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
  1404. if (out_baseimg_param) {
  1405. out_baseimg = out_baseimg_param;
  1406. }
  1407. /* Check if compression is supported */
  1408. if (compress) {
  1409. bool encryption =
  1410. qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
  1411. const char *preallocation =
  1412. qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
  1413. if (!drv->bdrv_write_compressed) {
  1414. error_report("Compression not supported for this file format");
  1415. ret = -1;
  1416. goto out;
  1417. }
  1418. if (encryption) {
  1419. error_report("Compression and encryption not supported at "
  1420. "the same time");
  1421. ret = -1;
  1422. goto out;
  1423. }
  1424. if (preallocation
  1425. && strcmp(preallocation, "off"))
  1426. {
  1427. error_report("Compression and preallocation not supported at "
  1428. "the same time");
  1429. ret = -1;
  1430. goto out;
  1431. }
  1432. }
  1433. if (!skip_create) {
  1434. /* Create the new image */
  1435. ret = bdrv_create(drv, out_filename, opts, &local_err);
  1436. if (ret < 0) {
  1437. error_report("%s: error while converting %s: %s",
  1438. out_filename, out_fmt, error_get_pretty(local_err));
  1439. error_free(local_err);
  1440. goto out;
  1441. }
  1442. }
  1443. flags = min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
  1444. ret = bdrv_parse_cache_flags(cache, &flags);
  1445. if (ret < 0) {
  1446. error_report("Invalid cache option: %s", cache);
  1447. goto out;
  1448. }
  1449. out_blk = img_open("target", out_filename, out_fmt, flags, true, quiet);
  1450. if (!out_blk) {
  1451. ret = -1;
  1452. goto out;
  1453. }
  1454. out_bs = blk_bs(out_blk);
  1455. bs_i = 0;
  1456. bs_offset = 0;
  1457. /* increase bufsectors from the default 4096 (2M) if opt_transfer_length
  1458. * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
  1459. * as maximum. */
  1460. bufsectors = MIN(32768,
  1461. MAX(bufsectors, MAX(out_bs->bl.opt_transfer_length,
  1462. out_bs->bl.discard_alignment))
  1463. );
  1464. buf = qemu_blockalign(out_bs, bufsectors * BDRV_SECTOR_SIZE);
  1465. if (skip_create) {
  1466. int64_t output_sectors = bdrv_nb_sectors(out_bs);
  1467. if (output_sectors < 0) {
  1468. error_report("unable to get output image length: %s\n",
  1469. strerror(-output_sectors));
  1470. ret = -1;
  1471. goto out;
  1472. } else if (output_sectors < total_sectors) {
  1473. error_report("output file is smaller than input file");
  1474. ret = -1;
  1475. goto out;
  1476. }
  1477. }
  1478. cluster_sectors = 0;
  1479. ret = bdrv_get_info(out_bs, &bdi);
  1480. if (ret < 0) {
  1481. if (compress) {
  1482. error_report("could not get block driver info");
  1483. goto out;
  1484. }
  1485. } else {
  1486. compress = compress || bdi.needs_compressed_writes;
  1487. cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
  1488. }
  1489. if (compress) {
  1490. if (cluster_sectors <= 0 || cluster_sectors > bufsectors) {
  1491. error_report("invalid cluster size");
  1492. ret = -1;
  1493. goto out;
  1494. }
  1495. sector_num = 0;
  1496. nb_sectors = total_sectors;
  1497. for(;;) {
  1498. int64_t bs_num;
  1499. int remainder;
  1500. uint8_t *buf2;
  1501. nb_sectors = total_sectors - sector_num;
  1502. if (nb_sectors <= 0)
  1503. break;
  1504. if (nb_sectors >= cluster_sectors)
  1505. n = cluster_sectors;
  1506. else
  1507. n = nb_sectors;
  1508. bs_num = sector_num - bs_offset;
  1509. assert (bs_num >= 0);
  1510. remainder = n;
  1511. buf2 = buf;
  1512. while (remainder > 0) {
  1513. int nlow;
  1514. while (bs_num == bs_sectors[bs_i]) {
  1515. bs_offset += bs_sectors[bs_i];
  1516. bs_i++;
  1517. assert (bs_i < bs_n);
  1518. bs_num = 0;
  1519. /* printf("changing part: sector_num=%" PRId64 ", "
  1520. "bs_i=%d, bs_offset=%" PRId64 ", bs_sectors=%" PRId64
  1521. "\n", sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
  1522. }
  1523. assert (bs_num < bs_sectors[bs_i]);
  1524. nlow = remainder > bs_sectors[bs_i] - bs_num
  1525. ? bs_sectors[bs_i] - bs_num : remainder;
  1526. ret = bdrv_read(bs[bs_i], bs_num, buf2, nlow);
  1527. if (ret < 0) {
  1528. error_report("error while reading sector %" PRId64 ": %s",
  1529. bs_num, strerror(-ret));
  1530. goto out;
  1531. }
  1532. buf2 += nlow * 512;
  1533. bs_num += nlow;
  1534. remainder -= nlow;
  1535. }
  1536. assert (remainder == 0);
  1537. if (!buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)) {
  1538. ret = bdrv_write_compressed(out_bs, sector_num, buf, n);
  1539. if (ret != 0) {
  1540. error_report("error while compressing sector %" PRId64
  1541. ": %s", sector_num, strerror(-ret));
  1542. goto out;
  1543. }
  1544. }
  1545. sector_num += n;
  1546. qemu_progress_print(100.0 * sector_num / total_sectors, 0);
  1547. }
  1548. /* signal EOF to align */
  1549. bdrv_write_compressed(out_bs, 0, NULL, 0);
  1550. } else {
  1551. int64_t sectors_to_read, sectors_read, sector_num_next_status;
  1552. bool count_allocated_sectors;
  1553. int has_zero_init = min_sparse ? bdrv_has_zero_init(out_bs) : 0;
  1554. if (!has_zero_init && bdrv_can_write_zeroes_with_unmap(out_bs)) {
  1555. ret = bdrv_make_zero(out_bs, BDRV_REQ_MAY_UNMAP);
  1556. if (ret < 0) {
  1557. goto out;
  1558. }
  1559. has_zero_init = 1;
  1560. }
  1561. sectors_to_read = total_sectors;
  1562. count_allocated_sectors = progress && (out_baseimg || has_zero_init);
  1563. restart:
  1564. sector_num = 0; // total number of sectors converted so far
  1565. sectors_read = 0;
  1566. sector_num_next_status = 0;
  1567. for(;;) {
  1568. nb_sectors = total_sectors - sector_num;
  1569. if (nb_sectors <= 0) {
  1570. if (count_allocated_sectors) {
  1571. sectors_to_read = sectors_read;
  1572. count_allocated_sectors = false;
  1573. goto restart;
  1574. }
  1575. ret = 0;
  1576. break;
  1577. }
  1578. while (sector_num - bs_offset >= bs_sectors[bs_i]) {
  1579. bs_offset += bs_sectors[bs_i];
  1580. bs_i ++;
  1581. assert (bs_i < bs_n);
  1582. /* printf("changing part: sector_num=%" PRId64 ", bs_i=%d, "
  1583. "bs_offset=%" PRId64 ", bs_sectors=%" PRId64 "\n",
  1584. sector_num, bs_i, bs_offset, bs_sectors[bs_i]); */
  1585. }
  1586. if ((out_baseimg || has_zero_init) &&
  1587. sector_num >= sector_num_next_status) {
  1588. n = nb_sectors > INT_MAX ? INT_MAX : nb_sectors;
  1589. ret = bdrv_get_block_status(bs[bs_i], sector_num - bs_offset,
  1590. n, &n1);
  1591. if (ret < 0) {
  1592. error_report("error while reading block status of sector %"
  1593. PRId64 ": %s", sector_num - bs_offset,
  1594. strerror(-ret));
  1595. goto out;
  1596. }
  1597. /* If the output image is zero initialized, we are not working
  1598. * on a shared base and the input is zero we can skip the next
  1599. * n1 sectors */
  1600. if (has_zero_init && !out_baseimg && (ret & BDRV_BLOCK_ZERO)) {
  1601. sector_num += n1;
  1602. continue;
  1603. }
  1604. /* If the output image is being created as a copy on write
  1605. * image, assume that sectors which are unallocated in the
  1606. * input image are present in both the output's and input's
  1607. * base images (no need to copy them). */
  1608. if (out_baseimg) {
  1609. if (!(ret & BDRV_BLOCK_DATA)) {
  1610. sector_num += n1;
  1611. continue;
  1612. }
  1613. /* The next 'n1' sectors are allocated in the input image.
  1614. * Copy only those as they may be followed by unallocated
  1615. * sectors. */
  1616. nb_sectors = n1;
  1617. }
  1618. /* avoid redundant callouts to get_block_status */
  1619. sector_num_next_status = sector_num + n1;
  1620. }
  1621. n = MIN(nb_sectors, bufsectors);
  1622. /* round down request length to an aligned sector, but
  1623. * do not bother doing this on short requests. They happen
  1624. * when we found an all-zero area, and the next sector to
  1625. * write will not be sector_num + n. */
  1626. if (cluster_sectors > 0 && n >= cluster_sectors) {
  1627. int64_t next_aligned_sector = (sector_num + n);
  1628. next_aligned_sector -= next_aligned_sector % cluster_sectors;
  1629. if (sector_num + n > next_aligned_sector) {
  1630. n = next_aligned_sector - sector_num;
  1631. }
  1632. }
  1633. n = MIN(n, bs_sectors[bs_i] - (sector_num - bs_offset));
  1634. sectors_read += n;
  1635. if (count_allocated_sectors) {
  1636. sector_num += n;
  1637. continue;
  1638. }
  1639. n1 = n;
  1640. ret = bdrv_read(bs[bs_i], sector_num - bs_offset, buf, n);
  1641. if (ret < 0) {
  1642. error_report("error while reading sector %" PRId64 ": %s",
  1643. sector_num - bs_offset, strerror(-ret));
  1644. goto out;
  1645. }
  1646. /* NOTE: at the same time we convert, we do not write zero
  1647. sectors to have a chance to compress the image. Ideally, we
  1648. should add a specific call to have the info to go faster */
  1649. buf1 = buf;
  1650. while (n > 0) {
  1651. if (!has_zero_init ||
  1652. is_allocated_sectors_min(buf1, n, &n1, min_sparse)) {
  1653. ret = bdrv_write(out_bs, sector_num, buf1, n1);
  1654. if (ret < 0) {
  1655. error_report("error while writing sector %" PRId64
  1656. ": %s", sector_num, strerror(-ret));
  1657. goto out;
  1658. }
  1659. }
  1660. sector_num += n1;
  1661. n -= n1;
  1662. buf1 += n1 * 512;
  1663. }
  1664. qemu_progress_print(100.0 * sectors_read / sectors_to_read, 0);
  1665. }
  1666. }
  1667. out:
  1668. if (!ret) {
  1669. qemu_progress_print(100, 0);
  1670. }
  1671. qemu_progress_end();
  1672. qemu_opts_del(opts);
  1673. qemu_opts_free(create_opts);
  1674. qemu_vfree(buf);
  1675. qemu_opts_del(sn_opts);
  1676. blk_unref(out_blk);
  1677. g_free(bs);
  1678. if (blk) {
  1679. for (bs_i = 0; bs_i < bs_n; bs_i++) {
  1680. blk_unref(blk[bs_i]);
  1681. }
  1682. g_free(blk);
  1683. }
  1684. g_free(bs_sectors);
  1685. fail_getopt:
  1686. g_free(options);
  1687. if (ret) {
  1688. return 1;
  1689. }
  1690. return 0;
  1691. }
  1692. static void dump_snapshots(BlockDriverState *bs)
  1693. {
  1694. QEMUSnapshotInfo *sn_tab, *sn;
  1695. int nb_sns, i;
  1696. nb_sns = bdrv_snapshot_list(bs, &sn_tab);
  1697. if (nb_sns <= 0)
  1698. return;
  1699. printf("Snapshot list:\n");
  1700. bdrv_snapshot_dump(fprintf, stdout, NULL);
  1701. printf("\n");
  1702. for(i = 0; i < nb_sns; i++) {
  1703. sn = &sn_tab[i];
  1704. bdrv_snapshot_dump(fprintf, stdout, sn);
  1705. printf("\n");
  1706. }
  1707. g_free(sn_tab);
  1708. }
  1709. static void dump_json_image_info_list(ImageInfoList *list)
  1710. {
  1711. Error *local_err = NULL;
  1712. QString *str;
  1713. QmpOutputVisitor *ov = qmp_output_visitor_new();
  1714. QObject *obj;
  1715. visit_type_ImageInfoList(qmp_output_get_visitor(ov),
  1716. &list, NULL, &local_err);
  1717. obj = qmp_output_get_qobject(ov);
  1718. str = qobject_to_json_pretty(obj);
  1719. assert(str != NULL);
  1720. printf("%s\n", qstring_get_str(str));
  1721. qobject_decref(obj);
  1722. qmp_output_visitor_cleanup(ov);
  1723. QDECREF(str);
  1724. }
  1725. static void dump_json_image_info(ImageInfo *info)
  1726. {
  1727. Error *local_err = NULL;
  1728. QString *str;
  1729. QmpOutputVisitor *ov = qmp_output_visitor_new();
  1730. QObject *obj;
  1731. visit_type_ImageInfo(qmp_output_get_visitor(ov),
  1732. &info, NULL, &local_err);
  1733. obj = qmp_output_get_qobject(ov);
  1734. str = qobject_to_json_pretty(obj);
  1735. assert(str != NULL);
  1736. printf("%s\n", qstring_get_str(str));
  1737. qobject_decref(obj);
  1738. qmp_output_visitor_cleanup(ov);
  1739. QDECREF(str);
  1740. }
  1741. static void dump_human_image_info_list(ImageInfoList *list)
  1742. {
  1743. ImageInfoList *elem;
  1744. bool delim = false;
  1745. for (elem = list; elem; elem = elem->next) {
  1746. if (delim) {
  1747. printf("\n");
  1748. }
  1749. delim = true;
  1750. bdrv_image_info_dump(fprintf, stdout, elem->value);
  1751. }
  1752. }
  1753. static gboolean str_equal_func(gconstpointer a, gconstpointer b)
  1754. {
  1755. return strcmp(a, b) == 0;
  1756. }
  1757. /**
  1758. * Open an image file chain and return an ImageInfoList
  1759. *
  1760. * @filename: topmost image filename
  1761. * @fmt: topmost image format (may be NULL to autodetect)
  1762. * @chain: true - enumerate entire backing file chain
  1763. * false - only topmost image file
  1764. *
  1765. * Returns a list of ImageInfo objects or NULL if there was an error opening an
  1766. * image file. If there was an error a message will have been printed to
  1767. * stderr.
  1768. */
  1769. static ImageInfoList *collect_image_info_list(const char *filename,
  1770. const char *fmt,
  1771. bool chain)
  1772. {
  1773. ImageInfoList *head = NULL;
  1774. ImageInfoList **last = &head;
  1775. GHashTable *filenames;
  1776. Error *err = NULL;
  1777. filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
  1778. while (filename) {
  1779. BlockBackend *blk;
  1780. BlockDriverState *bs;
  1781. ImageInfo *info;
  1782. ImageInfoList *elem;
  1783. if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
  1784. error_report("Backing file '%s' creates an infinite loop.",
  1785. filename);
  1786. goto err;
  1787. }
  1788. g_hash_table_insert(filenames, (gpointer)filename, NULL);
  1789. blk = img_open("image", filename, fmt,
  1790. BDRV_O_FLAGS | BDRV_O_NO_BACKING, false, false);
  1791. if (!blk) {
  1792. goto err;
  1793. }
  1794. bs = blk_bs(blk);
  1795. bdrv_query_image_info(bs, &info, &err);
  1796. if (err) {
  1797. error_report("%s", error_get_pretty(err));
  1798. error_free(err);
  1799. blk_unref(blk);
  1800. goto err;
  1801. }
  1802. elem = g_new0(ImageInfoList, 1);
  1803. elem->value = info;
  1804. *last = elem;
  1805. last = &elem->next;
  1806. blk_unref(blk);
  1807. filename = fmt = NULL;
  1808. if (chain) {
  1809. if (info->has_full_backing_filename) {
  1810. filename = info->full_backing_filename;
  1811. } else if (info->has_backing_filename) {
  1812. filename = info->backing_filename;
  1813. }
  1814. if (info->has_backing_filename_format) {
  1815. fmt = info->backing_filename_format;
  1816. }
  1817. }
  1818. }
  1819. g_hash_table_destroy(filenames);
  1820. return head;
  1821. err:
  1822. qapi_free_ImageInfoList(head);
  1823. g_hash_table_destroy(filenames);
  1824. return NULL;
  1825. }
  1826. static int img_info(int argc, char **argv)
  1827. {
  1828. int c;
  1829. OutputFormat output_format = OFORMAT_HUMAN;
  1830. bool chain = false;
  1831. const char *filename, *fmt, *output;
  1832. ImageInfoList *list;
  1833. fmt = NULL;
  1834. output = NULL;
  1835. for(;;) {
  1836. int option_index = 0;
  1837. static const struct option long_options[] = {
  1838. {"help", no_argument, 0, 'h'},
  1839. {"format", required_argument, 0, 'f'},
  1840. {"output", required_argument, 0, OPTION_OUTPUT},
  1841. {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
  1842. {0, 0, 0, 0}
  1843. };
  1844. c = getopt_long(argc, argv, "f:h",
  1845. long_options, &option_index);
  1846. if (c == -1) {
  1847. break;
  1848. }
  1849. switch(c) {
  1850. case '?':
  1851. case 'h':
  1852. help();
  1853. break;
  1854. case 'f':
  1855. fmt = optarg;
  1856. break;
  1857. case OPTION_OUTPUT:
  1858. output = optarg;
  1859. break;
  1860. case OPTION_BACKING_CHAIN:
  1861. chain = true;
  1862. break;
  1863. }
  1864. }
  1865. if (optind != argc - 1) {
  1866. error_exit("Expecting one image file name");
  1867. }
  1868. filename = argv[optind++];
  1869. if (output && !strcmp(output, "json")) {
  1870. output_format = OFORMAT_JSON;
  1871. } else if (output && !strcmp(output, "human")) {
  1872. output_format = OFORMAT_HUMAN;
  1873. } else if (output) {
  1874. error_report("--output must be used with human or json as argument.");
  1875. return 1;
  1876. }
  1877. list = collect_image_info_list(filename, fmt, chain);
  1878. if (!list) {
  1879. return 1;
  1880. }
  1881. switch (output_format) {
  1882. case OFORMAT_HUMAN:
  1883. dump_human_image_info_list(list);
  1884. break;
  1885. case OFORMAT_JSON:
  1886. if (chain) {
  1887. dump_json_image_info_list(list);
  1888. } else {
  1889. dump_json_image_info(list->value);
  1890. }
  1891. break;
  1892. }
  1893. qapi_free_ImageInfoList(list);
  1894. return 0;
  1895. }
  1896. typedef struct MapEntry {
  1897. int flags;
  1898. int depth;
  1899. int64_t start;
  1900. int64_t length;
  1901. int64_t offset;
  1902. BlockDriverState *bs;
  1903. } MapEntry;
  1904. static void dump_map_entry(OutputFormat output_format, MapEntry *e,
  1905. MapEntry *next)
  1906. {
  1907. switch (output_format) {
  1908. case OFORMAT_HUMAN:
  1909. if ((e->flags & BDRV_BLOCK_DATA) &&
  1910. !(e->flags & BDRV_BLOCK_OFFSET_VALID)) {
  1911. error_report("File contains external, encrypted or compressed clusters.");
  1912. exit(1);
  1913. }
  1914. if ((e->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) == BDRV_BLOCK_DATA) {
  1915. printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
  1916. e->start, e->length, e->offset, e->bs->filename);
  1917. }
  1918. /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
  1919. * Modify the flags here to allow more coalescing.
  1920. */
  1921. if (next &&
  1922. (next->flags & (BDRV_BLOCK_DATA|BDRV_BLOCK_ZERO)) != BDRV_BLOCK_DATA) {
  1923. next->flags &= ~BDRV_BLOCK_DATA;
  1924. next->flags |= BDRV_BLOCK_ZERO;
  1925. }
  1926. break;
  1927. case OFORMAT_JSON:
  1928. printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64", \"depth\": %d,"
  1929. " \"zero\": %s, \"data\": %s",
  1930. (e->start == 0 ? "[" : ",\n"),
  1931. e->start, e->length, e->depth,
  1932. (e->flags & BDRV_BLOCK_ZERO) ? "true" : "false",
  1933. (e->flags & BDRV_BLOCK_DATA) ? "true" : "false");
  1934. if (e->flags & BDRV_BLOCK_OFFSET_VALID) {
  1935. printf(", \"offset\": %"PRId64"", e->offset);
  1936. }
  1937. putchar('}');
  1938. if (!next) {
  1939. printf("]\n");
  1940. }
  1941. break;
  1942. }
  1943. }
  1944. static int get_block_status(BlockDriverState *bs, int64_t sector_num,
  1945. int nb_sectors, MapEntry *e)
  1946. {
  1947. int64_t ret;
  1948. int depth;
  1949. /* As an optimization, we could cache the current range of unallocated
  1950. * clusters in each file of the chain, and avoid querying the same
  1951. * range repeatedly.
  1952. */
  1953. depth = 0;
  1954. for (;;) {
  1955. ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &nb_sectors);
  1956. if (ret < 0) {
  1957. return ret;
  1958. }
  1959. assert(nb_sectors);
  1960. if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
  1961. break;
  1962. }
  1963. bs = bs->backing_hd;
  1964. if (bs == NULL) {
  1965. ret = 0;
  1966. break;
  1967. }
  1968. depth++;
  1969. }
  1970. e->start = sector_num * BDRV_SECTOR_SIZE;
  1971. e->length = nb_sectors * BDRV_SECTOR_SIZE;
  1972. e->flags = ret & ~BDRV_BLOCK_OFFSET_MASK;
  1973. e->offset = ret & BDRV_BLOCK_OFFSET_MASK;
  1974. e->depth = depth;
  1975. e->bs = bs;
  1976. return 0;
  1977. }
  1978. static int img_map(int argc, char **argv)
  1979. {
  1980. int c;
  1981. OutputFormat output_format = OFORMAT_HUMAN;
  1982. BlockBackend *blk;
  1983. BlockDriverState *bs;
  1984. const char *filename, *fmt, *output;
  1985. int64_t length;
  1986. MapEntry curr = { .length = 0 }, next;
  1987. int ret = 0;
  1988. fmt = NULL;
  1989. output = NULL;
  1990. for (;;) {
  1991. int option_index = 0;
  1992. static const struct option long_options[] = {
  1993. {"help", no_argument, 0, 'h'},
  1994. {"format", required_argument, 0, 'f'},
  1995. {"output", required_argument, 0, OPTION_OUTPUT},
  1996. {0, 0, 0, 0}
  1997. };
  1998. c = getopt_long(argc, argv, "f:h",
  1999. long_options, &option_index);
  2000. if (c == -1) {
  2001. break;
  2002. }
  2003. switch (c) {
  2004. case '?':
  2005. case 'h':
  2006. help();
  2007. break;
  2008. case 'f':
  2009. fmt = optarg;
  2010. break;
  2011. case OPTION_OUTPUT:
  2012. output = optarg;
  2013. break;
  2014. }
  2015. }
  2016. if (optind != argc - 1) {
  2017. error_exit("Expecting one image file name");
  2018. }
  2019. filename = argv[optind];
  2020. if (output && !strcmp(output, "json")) {
  2021. output_format = OFORMAT_JSON;
  2022. } else if (output && !strcmp(output, "human")) {
  2023. output_format = OFORMAT_HUMAN;
  2024. } else if (output) {
  2025. error_report("--output must be used with human or json as argument.");
  2026. return 1;
  2027. }
  2028. blk = img_open("image", filename, fmt, BDRV_O_FLAGS, true, false);
  2029. if (!blk) {
  2030. return 1;
  2031. }
  2032. bs = blk_bs(blk);
  2033. if (output_format == OFORMAT_HUMAN) {
  2034. printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
  2035. }
  2036. length = bdrv_getlength(bs);
  2037. while (curr.start + curr.length < length) {
  2038. int64_t nsectors_left;
  2039. int64_t sector_num;
  2040. int n;
  2041. sector_num = (curr.start + curr.length) >> BDRV_SECTOR_BITS;
  2042. /* Probe up to 1 GiB at a time. */
  2043. nsectors_left = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE) - sector_num;
  2044. n = MIN(1 << (30 - BDRV_SECTOR_BITS), nsectors_left);
  2045. ret = get_block_status(bs, sector_num, n, &next);
  2046. if (ret < 0) {
  2047. error_report("Could not read file metadata: %s", strerror(-ret));
  2048. goto out;
  2049. }
  2050. if (curr.length != 0 && curr.flags == next.flags &&
  2051. curr.depth == next.depth &&
  2052. ((curr.flags & BDRV_BLOCK_OFFSET_VALID) == 0 ||
  2053. curr.offset + curr.length == next.offset)) {
  2054. curr.length += next.length;
  2055. continue;
  2056. }
  2057. if (curr.length > 0) {
  2058. dump_map_entry(output_format, &curr, &next);
  2059. }
  2060. curr = next;
  2061. }
  2062. dump_map_entry(output_format, &curr, NULL);
  2063. out:
  2064. blk_unref(blk);
  2065. return ret < 0;
  2066. }
  2067. #define SNAPSHOT_LIST 1
  2068. #define SNAPSHOT_CREATE 2
  2069. #define SNAPSHOT_APPLY 3
  2070. #define SNAPSHOT_DELETE 4
  2071. static int img_snapshot(int argc, char **argv)
  2072. {
  2073. BlockBackend *blk;
  2074. BlockDriverState *bs;
  2075. QEMUSnapshotInfo sn;
  2076. char *filename, *snapshot_name = NULL;
  2077. int c, ret = 0, bdrv_oflags;
  2078. int action = 0;
  2079. qemu_timeval tv;
  2080. bool quiet = false;
  2081. Error *err = NULL;
  2082. bdrv_oflags = BDRV_O_FLAGS | BDRV_O_RDWR;
  2083. /* Parse commandline parameters */
  2084. for(;;) {
  2085. c = getopt(argc, argv, "la:c:d:hq");
  2086. if (c == -1) {
  2087. break;
  2088. }
  2089. switch(c) {
  2090. case '?':
  2091. case 'h':
  2092. help();
  2093. return 0;
  2094. case 'l':
  2095. if (action) {
  2096. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2097. return 0;
  2098. }
  2099. action = SNAPSHOT_LIST;
  2100. bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
  2101. break;
  2102. case 'a':
  2103. if (action) {
  2104. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2105. return 0;
  2106. }
  2107. action = SNAPSHOT_APPLY;
  2108. snapshot_name = optarg;
  2109. break;
  2110. case 'c':
  2111. if (action) {
  2112. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2113. return 0;
  2114. }
  2115. action = SNAPSHOT_CREATE;
  2116. snapshot_name = optarg;
  2117. break;
  2118. case 'd':
  2119. if (action) {
  2120. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2121. return 0;
  2122. }
  2123. action = SNAPSHOT_DELETE;
  2124. snapshot_name = optarg;
  2125. break;
  2126. case 'q':
  2127. quiet = true;
  2128. break;
  2129. }
  2130. }
  2131. if (optind != argc - 1) {
  2132. error_exit("Expecting one image file name");
  2133. }
  2134. filename = argv[optind++];
  2135. /* Open the image */
  2136. blk = img_open("image", filename, NULL, bdrv_oflags, true, quiet);
  2137. if (!blk) {
  2138. return 1;
  2139. }
  2140. bs = blk_bs(blk);
  2141. /* Perform the requested action */
  2142. switch(action) {
  2143. case SNAPSHOT_LIST:
  2144. dump_snapshots(bs);
  2145. break;
  2146. case SNAPSHOT_CREATE:
  2147. memset(&sn, 0, sizeof(sn));
  2148. pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
  2149. qemu_gettimeofday(&tv);
  2150. sn.date_sec = tv.tv_sec;
  2151. sn.date_nsec = tv.tv_usec * 1000;
  2152. ret = bdrv_snapshot_create(bs, &sn);
  2153. if (ret) {
  2154. error_report("Could not create snapshot '%s': %d (%s)",
  2155. snapshot_name, ret, strerror(-ret));
  2156. }
  2157. break;
  2158. case SNAPSHOT_APPLY:
  2159. ret = bdrv_snapshot_goto(bs, snapshot_name);
  2160. if (ret) {
  2161. error_report("Could not apply snapshot '%s': %d (%s)",
  2162. snapshot_name, ret, strerror(-ret));
  2163. }
  2164. break;
  2165. case SNAPSHOT_DELETE:
  2166. bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
  2167. if (err) {
  2168. error_report("Could not delete snapshot '%s': (%s)",
  2169. snapshot_name, error_get_pretty(err));
  2170. error_free(err);
  2171. ret = 1;
  2172. }
  2173. break;
  2174. }
  2175. /* Cleanup */
  2176. blk_unref(blk);
  2177. if (ret) {
  2178. return 1;
  2179. }
  2180. return 0;
  2181. }
  2182. static int img_rebase(int argc, char **argv)
  2183. {
  2184. BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
  2185. BlockDriverState *bs = NULL, *bs_old_backing = NULL, *bs_new_backing = NULL;
  2186. BlockDriver *old_backing_drv, *new_backing_drv;
  2187. char *filename;
  2188. const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
  2189. int c, flags, src_flags, ret;
  2190. int unsafe = 0;
  2191. int progress = 0;
  2192. bool quiet = false;
  2193. Error *local_err = NULL;
  2194. /* Parse commandline parameters */
  2195. fmt = NULL;
  2196. cache = BDRV_DEFAULT_CACHE;
  2197. src_cache = BDRV_DEFAULT_CACHE;
  2198. out_baseimg = NULL;
  2199. out_basefmt = NULL;
  2200. for(;;) {
  2201. c = getopt(argc, argv, "hf:F:b:upt:T:q");
  2202. if (c == -1) {
  2203. break;
  2204. }
  2205. switch(c) {
  2206. case '?':
  2207. case 'h':
  2208. help();
  2209. return 0;
  2210. case 'f':
  2211. fmt = optarg;
  2212. break;
  2213. case 'F':
  2214. out_basefmt = optarg;
  2215. break;
  2216. case 'b':
  2217. out_baseimg = optarg;
  2218. break;
  2219. case 'u':
  2220. unsafe = 1;
  2221. break;
  2222. case 'p':
  2223. progress = 1;
  2224. break;
  2225. case 't':
  2226. cache = optarg;
  2227. break;
  2228. case 'T':
  2229. src_cache = optarg;
  2230. break;
  2231. case 'q':
  2232. quiet = true;
  2233. break;
  2234. }
  2235. }
  2236. if (quiet) {
  2237. progress = 0;
  2238. }
  2239. if (optind != argc - 1) {
  2240. error_exit("Expecting one image file name");
  2241. }
  2242. if (!unsafe && !out_baseimg) {
  2243. error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
  2244. }
  2245. filename = argv[optind++];
  2246. qemu_progress_init(progress, 2.0);
  2247. qemu_progress_print(0, 100);
  2248. flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
  2249. ret = bdrv_parse_cache_flags(cache, &flags);
  2250. if (ret < 0) {
  2251. error_report("Invalid cache option: %s", cache);
  2252. goto out;
  2253. }
  2254. src_flags = BDRV_O_FLAGS;
  2255. ret = bdrv_parse_cache_flags(src_cache, &src_flags);
  2256. if (ret < 0) {
  2257. error_report("Invalid source cache option: %s", src_cache);
  2258. goto out;
  2259. }
  2260. /*
  2261. * Open the images.
  2262. *
  2263. * Ignore the old backing file for unsafe rebase in case we want to correct
  2264. * the reference to a renamed or moved backing file.
  2265. */
  2266. blk = img_open("image", filename, fmt, flags, true, quiet);
  2267. if (!blk) {
  2268. ret = -1;
  2269. goto out;
  2270. }
  2271. bs = blk_bs(blk);
  2272. /* Find the right drivers for the backing files */
  2273. old_backing_drv = NULL;
  2274. new_backing_drv = NULL;
  2275. if (!unsafe && bs->backing_format[0] != '\0') {
  2276. old_backing_drv = bdrv_find_format(bs->backing_format);
  2277. if (old_backing_drv == NULL) {
  2278. error_report("Invalid format name: '%s'", bs->backing_format);
  2279. ret = -1;
  2280. goto out;
  2281. }
  2282. }
  2283. if (out_basefmt != NULL) {
  2284. new_backing_drv = bdrv_find_format(out_basefmt);
  2285. if (new_backing_drv == NULL) {
  2286. error_report("Invalid format name: '%s'", out_basefmt);
  2287. ret = -1;
  2288. goto out;
  2289. }
  2290. }
  2291. /* For safe rebasing we need to compare old and new backing file */
  2292. if (!unsafe) {
  2293. char backing_name[1024];
  2294. blk_old_backing = blk_new_with_bs("old_backing", &error_abort);
  2295. bs_old_backing = blk_bs(blk_old_backing);
  2296. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  2297. ret = bdrv_open(&bs_old_backing, backing_name, NULL, NULL, src_flags,
  2298. old_backing_drv, &local_err);
  2299. if (ret) {
  2300. error_report("Could not open old backing file '%s': %s",
  2301. backing_name, error_get_pretty(local_err));
  2302. error_free(local_err);
  2303. goto out;
  2304. }
  2305. if (out_baseimg[0]) {
  2306. blk_new_backing = blk_new_with_bs("new_backing", &error_abort);
  2307. bs_new_backing = blk_bs(blk_new_backing);
  2308. ret = bdrv_open(&bs_new_backing, out_baseimg, NULL, NULL, src_flags,
  2309. new_backing_drv, &local_err);
  2310. if (ret) {
  2311. error_report("Could not open new backing file '%s': %s",
  2312. out_baseimg, error_get_pretty(local_err));
  2313. error_free(local_err);
  2314. goto out;
  2315. }
  2316. }
  2317. }
  2318. /*
  2319. * Check each unallocated cluster in the COW file. If it is unallocated,
  2320. * accesses go to the backing file. We must therefore compare this cluster
  2321. * in the old and new backing file, and if they differ we need to copy it
  2322. * from the old backing file into the COW file.
  2323. *
  2324. * If qemu-img crashes during this step, no harm is done. The content of
  2325. * the image is the same as the original one at any time.
  2326. */
  2327. if (!unsafe) {
  2328. int64_t num_sectors;
  2329. int64_t old_backing_num_sectors;
  2330. int64_t new_backing_num_sectors = 0;
  2331. uint64_t sector;
  2332. int n;
  2333. uint8_t * buf_old;
  2334. uint8_t * buf_new;
  2335. float local_progress = 0;
  2336. buf_old = qemu_blockalign(bs, IO_BUF_SIZE);
  2337. buf_new = qemu_blockalign(bs, IO_BUF_SIZE);
  2338. num_sectors = bdrv_nb_sectors(bs);
  2339. if (num_sectors < 0) {
  2340. error_report("Could not get size of '%s': %s",
  2341. filename, strerror(-num_sectors));
  2342. ret = -1;
  2343. goto out;
  2344. }
  2345. old_backing_num_sectors = bdrv_nb_sectors(bs_old_backing);
  2346. if (old_backing_num_sectors < 0) {
  2347. char backing_name[1024];
  2348. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  2349. error_report("Could not get size of '%s': %s",
  2350. backing_name, strerror(-old_backing_num_sectors));
  2351. ret = -1;
  2352. goto out;
  2353. }
  2354. if (bs_new_backing) {
  2355. new_backing_num_sectors = bdrv_nb_sectors(bs_new_backing);
  2356. if (new_backing_num_sectors < 0) {
  2357. error_report("Could not get size of '%s': %s",
  2358. out_baseimg, strerror(-new_backing_num_sectors));
  2359. ret = -1;
  2360. goto out;
  2361. }
  2362. }
  2363. if (num_sectors != 0) {
  2364. local_progress = (float)100 /
  2365. (num_sectors / MIN(num_sectors, IO_BUF_SIZE / 512));
  2366. }
  2367. for (sector = 0; sector < num_sectors; sector += n) {
  2368. /* How many sectors can we handle with the next read? */
  2369. if (sector + (IO_BUF_SIZE / 512) <= num_sectors) {
  2370. n = (IO_BUF_SIZE / 512);
  2371. } else {
  2372. n = num_sectors - sector;
  2373. }
  2374. /* If the cluster is allocated, we don't need to take action */
  2375. ret = bdrv_is_allocated(bs, sector, n, &n);
  2376. if (ret < 0) {
  2377. error_report("error while reading image metadata: %s",
  2378. strerror(-ret));
  2379. goto out;
  2380. }
  2381. if (ret) {
  2382. continue;
  2383. }
  2384. /*
  2385. * Read old and new backing file and take into consideration that
  2386. * backing files may be smaller than the COW image.
  2387. */
  2388. if (sector >= old_backing_num_sectors) {
  2389. memset(buf_old, 0, n * BDRV_SECTOR_SIZE);
  2390. } else {
  2391. if (sector + n > old_backing_num_sectors) {
  2392. n = old_backing_num_sectors - sector;
  2393. }
  2394. ret = bdrv_read(bs_old_backing, sector, buf_old, n);
  2395. if (ret < 0) {
  2396. error_report("error while reading from old backing file");
  2397. goto out;
  2398. }
  2399. }
  2400. if (sector >= new_backing_num_sectors || !bs_new_backing) {
  2401. memset(buf_new, 0, n * BDRV_SECTOR_SIZE);
  2402. } else {
  2403. if (sector + n > new_backing_num_sectors) {
  2404. n = new_backing_num_sectors - sector;
  2405. }
  2406. ret = bdrv_read(bs_new_backing, sector, buf_new, n);
  2407. if (ret < 0) {
  2408. error_report("error while reading from new backing file");
  2409. goto out;
  2410. }
  2411. }
  2412. /* If they differ, we need to write to the COW file */
  2413. uint64_t written = 0;
  2414. while (written < n) {
  2415. int pnum;
  2416. if (compare_sectors(buf_old + written * 512,
  2417. buf_new + written * 512, n - written, &pnum))
  2418. {
  2419. ret = bdrv_write(bs, sector + written,
  2420. buf_old + written * 512, pnum);
  2421. if (ret < 0) {
  2422. error_report("Error while writing to COW image: %s",
  2423. strerror(-ret));
  2424. goto out;
  2425. }
  2426. }
  2427. written += pnum;
  2428. }
  2429. qemu_progress_print(local_progress, 100);
  2430. }
  2431. qemu_vfree(buf_old);
  2432. qemu_vfree(buf_new);
  2433. }
  2434. /*
  2435. * Change the backing file. All clusters that are different from the old
  2436. * backing file are overwritten in the COW file now, so the visible content
  2437. * doesn't change when we switch the backing file.
  2438. */
  2439. if (out_baseimg && *out_baseimg) {
  2440. ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
  2441. } else {
  2442. ret = bdrv_change_backing_file(bs, NULL, NULL);
  2443. }
  2444. if (ret == -ENOSPC) {
  2445. error_report("Could not change the backing file to '%s': No "
  2446. "space left in the file header", out_baseimg);
  2447. } else if (ret < 0) {
  2448. error_report("Could not change the backing file to '%s': %s",
  2449. out_baseimg, strerror(-ret));
  2450. }
  2451. qemu_progress_print(100, 0);
  2452. /*
  2453. * TODO At this point it is possible to check if any clusters that are
  2454. * allocated in the COW file are the same in the backing file. If so, they
  2455. * could be dropped from the COW file. Don't do this before switching the
  2456. * backing file, in case of a crash this would lead to corruption.
  2457. */
  2458. out:
  2459. qemu_progress_end();
  2460. /* Cleanup */
  2461. if (!unsafe) {
  2462. blk_unref(blk_old_backing);
  2463. blk_unref(blk_new_backing);
  2464. }
  2465. blk_unref(blk);
  2466. if (ret) {
  2467. return 1;
  2468. }
  2469. return 0;
  2470. }
  2471. static int img_resize(int argc, char **argv)
  2472. {
  2473. int c, ret, relative;
  2474. const char *filename, *fmt, *size;
  2475. int64_t n, total_size;
  2476. bool quiet = false;
  2477. BlockBackend *blk = NULL;
  2478. BlockDriverState *bs = NULL;
  2479. QemuOpts *param;
  2480. static QemuOptsList resize_options = {
  2481. .name = "resize_options",
  2482. .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
  2483. .desc = {
  2484. {
  2485. .name = BLOCK_OPT_SIZE,
  2486. .type = QEMU_OPT_SIZE,
  2487. .help = "Virtual disk size"
  2488. }, {
  2489. /* end of list */
  2490. }
  2491. },
  2492. };
  2493. /* Remove size from argv manually so that negative numbers are not treated
  2494. * as options by getopt. */
  2495. if (argc < 3) {
  2496. error_exit("Not enough arguments");
  2497. return 1;
  2498. }
  2499. size = argv[--argc];
  2500. /* Parse getopt arguments */
  2501. fmt = NULL;
  2502. for(;;) {
  2503. c = getopt(argc, argv, "f:hq");
  2504. if (c == -1) {
  2505. break;
  2506. }
  2507. switch(c) {
  2508. case '?':
  2509. case 'h':
  2510. help();
  2511. break;
  2512. case 'f':
  2513. fmt = optarg;
  2514. break;
  2515. case 'q':
  2516. quiet = true;
  2517. break;
  2518. }
  2519. }
  2520. if (optind != argc - 1) {
  2521. error_exit("Expecting one image file name");
  2522. }
  2523. filename = argv[optind++];
  2524. /* Choose grow, shrink, or absolute resize mode */
  2525. switch (size[0]) {
  2526. case '+':
  2527. relative = 1;
  2528. size++;
  2529. break;
  2530. case '-':
  2531. relative = -1;
  2532. size++;
  2533. break;
  2534. default:
  2535. relative = 0;
  2536. break;
  2537. }
  2538. /* Parse size */
  2539. param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
  2540. if (qemu_opt_set(param, BLOCK_OPT_SIZE, size)) {
  2541. /* Error message already printed when size parsing fails */
  2542. ret = -1;
  2543. qemu_opts_del(param);
  2544. goto out;
  2545. }
  2546. n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
  2547. qemu_opts_del(param);
  2548. blk = img_open("image", filename, fmt, BDRV_O_FLAGS | BDRV_O_RDWR,
  2549. true, quiet);
  2550. if (!blk) {
  2551. ret = -1;
  2552. goto out;
  2553. }
  2554. bs = blk_bs(blk);
  2555. if (relative) {
  2556. total_size = bdrv_getlength(bs) + n * relative;
  2557. } else {
  2558. total_size = n;
  2559. }
  2560. if (total_size <= 0) {
  2561. error_report("New image size must be positive");
  2562. ret = -1;
  2563. goto out;
  2564. }
  2565. ret = bdrv_truncate(bs, total_size);
  2566. switch (ret) {
  2567. case 0:
  2568. qprintf(quiet, "Image resized.\n");
  2569. break;
  2570. case -ENOTSUP:
  2571. error_report("This image does not support resize");
  2572. break;
  2573. case -EACCES:
  2574. error_report("Image is read-only");
  2575. break;
  2576. default:
  2577. error_report("Error resizing image (%d)", -ret);
  2578. break;
  2579. }
  2580. out:
  2581. blk_unref(blk);
  2582. if (ret) {
  2583. return 1;
  2584. }
  2585. return 0;
  2586. }
  2587. static void amend_status_cb(BlockDriverState *bs,
  2588. int64_t offset, int64_t total_work_size)
  2589. {
  2590. qemu_progress_print(100.f * offset / total_work_size, 0);
  2591. }
  2592. static int img_amend(int argc, char **argv)
  2593. {
  2594. int c, ret = 0;
  2595. char *options = NULL;
  2596. QemuOptsList *create_opts = NULL;
  2597. QemuOpts *opts = NULL;
  2598. const char *fmt = NULL, *filename, *cache;
  2599. int flags;
  2600. bool quiet = false, progress = false;
  2601. BlockBackend *blk = NULL;
  2602. BlockDriverState *bs = NULL;
  2603. cache = BDRV_DEFAULT_CACHE;
  2604. for (;;) {
  2605. c = getopt(argc, argv, "ho:f:t:pq");
  2606. if (c == -1) {
  2607. break;
  2608. }
  2609. switch (c) {
  2610. case 'h':
  2611. case '?':
  2612. help();
  2613. break;
  2614. case 'o':
  2615. if (!is_valid_option_list(optarg)) {
  2616. error_report("Invalid option list: %s", optarg);
  2617. ret = -1;
  2618. goto out;
  2619. }
  2620. if (!options) {
  2621. options = g_strdup(optarg);
  2622. } else {
  2623. char *old_options = options;
  2624. options = g_strdup_printf("%s,%s", options, optarg);
  2625. g_free(old_options);
  2626. }
  2627. break;
  2628. case 'f':
  2629. fmt = optarg;
  2630. break;
  2631. case 't':
  2632. cache = optarg;
  2633. break;
  2634. case 'p':
  2635. progress = true;
  2636. break;
  2637. case 'q':
  2638. quiet = true;
  2639. break;
  2640. }
  2641. }
  2642. if (!options) {
  2643. error_exit("Must specify options (-o)");
  2644. }
  2645. if (quiet) {
  2646. progress = false;
  2647. }
  2648. qemu_progress_init(progress, 1.0);
  2649. filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
  2650. if (fmt && has_help_option(options)) {
  2651. /* If a format is explicitly specified (and possibly no filename is
  2652. * given), print option help here */
  2653. ret = print_block_option_help(filename, fmt);
  2654. goto out;
  2655. }
  2656. if (optind != argc - 1) {
  2657. error_report("Expecting one image file name");
  2658. ret = -1;
  2659. goto out;
  2660. }
  2661. flags = BDRV_O_FLAGS | BDRV_O_RDWR;
  2662. ret = bdrv_parse_cache_flags(cache, &flags);
  2663. if (ret < 0) {
  2664. error_report("Invalid cache option: %s", cache);
  2665. goto out;
  2666. }
  2667. blk = img_open("image", filename, fmt, flags, true, quiet);
  2668. if (!blk) {
  2669. ret = -1;
  2670. goto out;
  2671. }
  2672. bs = blk_bs(blk);
  2673. fmt = bs->drv->format_name;
  2674. if (has_help_option(options)) {
  2675. /* If the format was auto-detected, print option help here */
  2676. ret = print_block_option_help(filename, fmt);
  2677. goto out;
  2678. }
  2679. if (!bs->drv->create_opts) {
  2680. error_report("Format driver '%s' does not support any options to amend",
  2681. fmt);
  2682. ret = -1;
  2683. goto out;
  2684. }
  2685. create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
  2686. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  2687. if (options && qemu_opts_do_parse(opts, options, NULL)) {
  2688. error_report("Invalid options for file format '%s'", fmt);
  2689. ret = -1;
  2690. goto out;
  2691. }
  2692. /* In case the driver does not call amend_status_cb() */
  2693. qemu_progress_print(0.f, 0);
  2694. ret = bdrv_amend_options(bs, opts, &amend_status_cb);
  2695. qemu_progress_print(100.f, 0);
  2696. if (ret < 0) {
  2697. error_report("Error while amending options: %s", strerror(-ret));
  2698. goto out;
  2699. }
  2700. out:
  2701. qemu_progress_end();
  2702. blk_unref(blk);
  2703. qemu_opts_del(opts);
  2704. qemu_opts_free(create_opts);
  2705. g_free(options);
  2706. if (ret) {
  2707. return 1;
  2708. }
  2709. return 0;
  2710. }
  2711. static const img_cmd_t img_cmds[] = {
  2712. #define DEF(option, callback, arg_string) \
  2713. { option, callback },
  2714. #include "qemu-img-cmds.h"
  2715. #undef DEF
  2716. #undef GEN_DOCS
  2717. { NULL, NULL, },
  2718. };
  2719. int main(int argc, char **argv)
  2720. {
  2721. const img_cmd_t *cmd;
  2722. const char *cmdname;
  2723. Error *local_error = NULL;
  2724. int c;
  2725. static const struct option long_options[] = {
  2726. {"help", no_argument, 0, 'h'},
  2727. {"version", no_argument, 0, 'v'},
  2728. {0, 0, 0, 0}
  2729. };
  2730. #ifdef CONFIG_POSIX
  2731. signal(SIGPIPE, SIG_IGN);
  2732. #endif
  2733. error_set_progname(argv[0]);
  2734. qemu_init_exec_dir(argv[0]);
  2735. if (qemu_init_main_loop(&local_error)) {
  2736. error_report("%s", error_get_pretty(local_error));
  2737. error_free(local_error);
  2738. exit(EXIT_FAILURE);
  2739. }
  2740. bdrv_init();
  2741. if (argc < 2) {
  2742. error_exit("Not enough arguments");
  2743. }
  2744. cmdname = argv[1];
  2745. /* find the command */
  2746. for (cmd = img_cmds; cmd->name != NULL; cmd++) {
  2747. if (!strcmp(cmdname, cmd->name)) {
  2748. return cmd->handler(argc - 1, argv + 1);
  2749. }
  2750. }
  2751. c = getopt_long(argc, argv, "h", long_options, NULL);
  2752. if (c == 'h') {
  2753. help();
  2754. }
  2755. if (c == 'v') {
  2756. printf(QEMU_IMG_VERSION);
  2757. return 0;
  2758. }
  2759. /* not found */
  2760. error_exit("Command not found: %s", cmdname);
  2761. }