qemu-img.c 138 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790
  1. /*
  2. * QEMU disk image utility
  3. *
  4. * Copyright (c) 2003-2008 Fabrice Bellard
  5. *
  6. * Permission is hereby granted, free of charge, to any person obtaining a copy
  7. * of this software and associated documentation files (the "Software"), to deal
  8. * in the Software without restriction, including without limitation the rights
  9. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. * copies of the Software, and to permit persons to whom the Software is
  11. * furnished to do so, subject to the following conditions:
  12. *
  13. * The above copyright notice and this permission notice shall be included in
  14. * all copies or substantial portions of the Software.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  19. * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. * THE SOFTWARE.
  23. */
  24. #include "qemu/osdep.h"
  25. #include <getopt.h>
  26. #include "qemu-version.h"
  27. #include "qapi/error.h"
  28. #include "qapi-visit.h"
  29. #include "qapi/qobject-output-visitor.h"
  30. #include "qapi/qmp/qerror.h"
  31. #include "qapi/qmp/qjson.h"
  32. #include "qapi/qmp/qbool.h"
  33. #include "qemu/cutils.h"
  34. #include "qemu/config-file.h"
  35. #include "qemu/option.h"
  36. #include "qemu/error-report.h"
  37. #include "qemu/log.h"
  38. #include "qom/object_interfaces.h"
  39. #include "sysemu/sysemu.h"
  40. #include "sysemu/block-backend.h"
  41. #include "block/block_int.h"
  42. #include "block/blockjob.h"
  43. #include "block/qapi.h"
  44. #include "crypto/init.h"
  45. #include "trace/control.h"
  46. #define QEMU_IMG_VERSION "qemu-img version " QEMU_VERSION QEMU_PKGVERSION \
  47. "\n" QEMU_COPYRIGHT "\n"
  48. typedef struct img_cmd_t {
  49. const char *name;
  50. int (*handler)(int argc, char **argv);
  51. } img_cmd_t;
  52. enum {
  53. OPTION_OUTPUT = 256,
  54. OPTION_BACKING_CHAIN = 257,
  55. OPTION_OBJECT = 258,
  56. OPTION_IMAGE_OPTS = 259,
  57. OPTION_PATTERN = 260,
  58. OPTION_FLUSH_INTERVAL = 261,
  59. OPTION_NO_DRAIN = 262,
  60. OPTION_TARGET_IMAGE_OPTS = 263,
  61. OPTION_SIZE = 264,
  62. OPTION_PREALLOCATION = 265,
  63. OPTION_SHRINK = 266,
  64. };
  65. typedef enum OutputFormat {
  66. OFORMAT_JSON,
  67. OFORMAT_HUMAN,
  68. } OutputFormat;
  69. /* Default to cache=writeback as data integrity is not important for qemu-img */
  70. #define BDRV_DEFAULT_CACHE "writeback"
  71. static void format_print(void *opaque, const char *name)
  72. {
  73. printf(" %s", name);
  74. }
  75. static void QEMU_NORETURN GCC_FMT_ATTR(1, 2) error_exit(const char *fmt, ...)
  76. {
  77. va_list ap;
  78. error_printf("qemu-img: ");
  79. va_start(ap, fmt);
  80. error_vprintf(fmt, ap);
  81. va_end(ap);
  82. error_printf("\nTry 'qemu-img --help' for more information\n");
  83. exit(EXIT_FAILURE);
  84. }
  85. static void QEMU_NORETURN missing_argument(const char *option)
  86. {
  87. error_exit("missing argument for option '%s'", option);
  88. }
  89. static void QEMU_NORETURN unrecognized_option(const char *option)
  90. {
  91. error_exit("unrecognized option '%s'", option);
  92. }
  93. /* Please keep in synch with qemu-img.texi */
  94. static void QEMU_NORETURN help(void)
  95. {
  96. const char *help_msg =
  97. QEMU_IMG_VERSION
  98. "usage: qemu-img [standard options] command [command options]\n"
  99. "QEMU disk image utility\n"
  100. "\n"
  101. " '-h', '--help' display this help and exit\n"
  102. " '-V', '--version' output version information and exit\n"
  103. " '-T', '--trace' [[enable=]<pattern>][,events=<file>][,file=<file>]\n"
  104. " specify tracing options\n"
  105. "\n"
  106. "Command syntax:\n"
  107. #define DEF(option, callback, arg_string) \
  108. " " arg_string "\n"
  109. #include "qemu-img-cmds.h"
  110. #undef DEF
  111. #undef GEN_DOCS
  112. "\n"
  113. "Command parameters:\n"
  114. " 'filename' is a disk image filename\n"
  115. " 'objectdef' is a QEMU user creatable object definition. See the qemu(1)\n"
  116. " manual page for a description of the object properties. The most common\n"
  117. " object type is a 'secret', which is used to supply passwords and/or\n"
  118. " encryption keys.\n"
  119. " 'fmt' is the disk image format. It is guessed automatically in most cases\n"
  120. " 'cache' is the cache mode used to write the output disk image, the valid\n"
  121. " options are: 'none', 'writeback' (default, except for convert), 'writethrough',\n"
  122. " 'directsync' and 'unsafe' (default for convert)\n"
  123. " 'src_cache' is the cache mode used to read input disk images, the valid\n"
  124. " options are the same as for the 'cache' option\n"
  125. " 'size' is the disk image size in bytes. Optional suffixes\n"
  126. " 'k' or 'K' (kilobyte, 1024), 'M' (megabyte, 1024k), 'G' (gigabyte, 1024M),\n"
  127. " 'T' (terabyte, 1024G), 'P' (petabyte, 1024T) and 'E' (exabyte, 1024P) are\n"
  128. " supported. 'b' is ignored.\n"
  129. " 'output_filename' is the destination disk image filename\n"
  130. " 'output_fmt' is the destination format\n"
  131. " 'options' is a comma separated list of format specific options in a\n"
  132. " name=value format. Use -o ? for an overview of the options supported by the\n"
  133. " used format\n"
  134. " 'snapshot_param' is param used for internal snapshot, format\n"
  135. " is 'snapshot.id=[ID],snapshot.name=[NAME]', or\n"
  136. " '[ID_OR_NAME]'\n"
  137. " 'snapshot_id_or_name' is deprecated, use 'snapshot_param'\n"
  138. " instead\n"
  139. " '-c' indicates that target image must be compressed (qcow format only)\n"
  140. " '-u' allows unsafe backing chains. For rebasing, it is assumed that old and\n"
  141. " new backing file match exactly. The image doesn't need a working\n"
  142. " backing file before rebasing in this case (useful for renaming the\n"
  143. " backing file). For image creation, allow creating without attempting\n"
  144. " to open the backing file.\n"
  145. " '-h' with or without a command shows this help and lists the supported formats\n"
  146. " '-p' show progress of command (only certain commands)\n"
  147. " '-q' use Quiet mode - do not print any output (except errors)\n"
  148. " '-S' indicates the consecutive number of bytes (defaults to 4k) that must\n"
  149. " contain only zeros for qemu-img to create a sparse image during\n"
  150. " conversion. If the number of bytes is 0, the source will not be scanned for\n"
  151. " unallocated or zero sectors, and the destination image will always be\n"
  152. " fully allocated\n"
  153. " '--output' takes the format in which the output must be done (human or json)\n"
  154. " '-n' skips the target volume creation (useful if the volume is created\n"
  155. " prior to running qemu-img)\n"
  156. "\n"
  157. "Parameters to check subcommand:\n"
  158. " '-r' tries to repair any inconsistencies that are found during the check.\n"
  159. " '-r leaks' repairs only cluster leaks, whereas '-r all' fixes all\n"
  160. " kinds of errors, with a higher risk of choosing the wrong fix or\n"
  161. " hiding corruption that has already occurred.\n"
  162. "\n"
  163. "Parameters to convert subcommand:\n"
  164. " '-m' specifies how many coroutines work in parallel during the convert\n"
  165. " process (defaults to 8)\n"
  166. " '-W' allow to write to the target out of order rather than sequential\n"
  167. "\n"
  168. "Parameters to snapshot subcommand:\n"
  169. " 'snapshot' is the name of the snapshot to create, apply or delete\n"
  170. " '-a' applies a snapshot (revert disk to saved state)\n"
  171. " '-c' creates a snapshot\n"
  172. " '-d' deletes a snapshot\n"
  173. " '-l' lists all snapshots in the given image\n"
  174. "\n"
  175. "Parameters to compare subcommand:\n"
  176. " '-f' first image format\n"
  177. " '-F' second image format\n"
  178. " '-s' run in Strict mode - fail on different image size or sector allocation\n"
  179. "\n"
  180. "Parameters to dd subcommand:\n"
  181. " 'bs=BYTES' read and write up to BYTES bytes at a time "
  182. "(default: 512)\n"
  183. " 'count=N' copy only N input blocks\n"
  184. " 'if=FILE' read from FILE\n"
  185. " 'of=FILE' write to FILE\n"
  186. " 'skip=N' skip N bs-sized blocks at the start of input\n";
  187. printf("%s\nSupported formats:", help_msg);
  188. bdrv_iterate_format(format_print, NULL);
  189. printf("\n\n" QEMU_HELP_BOTTOM "\n");
  190. exit(EXIT_SUCCESS);
  191. }
  192. static QemuOptsList qemu_object_opts = {
  193. .name = "object",
  194. .implied_opt_name = "qom-type",
  195. .head = QTAILQ_HEAD_INITIALIZER(qemu_object_opts.head),
  196. .desc = {
  197. { }
  198. },
  199. };
  200. static QemuOptsList qemu_source_opts = {
  201. .name = "source",
  202. .implied_opt_name = "file",
  203. .head = QTAILQ_HEAD_INITIALIZER(qemu_source_opts.head),
  204. .desc = {
  205. { }
  206. },
  207. };
  208. static int GCC_FMT_ATTR(2, 3) qprintf(bool quiet, const char *fmt, ...)
  209. {
  210. int ret = 0;
  211. if (!quiet) {
  212. va_list args;
  213. va_start(args, fmt);
  214. ret = vprintf(fmt, args);
  215. va_end(args);
  216. }
  217. return ret;
  218. }
  219. static int print_block_option_help(const char *filename, const char *fmt)
  220. {
  221. BlockDriver *drv, *proto_drv;
  222. QemuOptsList *create_opts = NULL;
  223. Error *local_err = NULL;
  224. /* Find driver and parse its options */
  225. drv = bdrv_find_format(fmt);
  226. if (!drv) {
  227. error_report("Unknown file format '%s'", fmt);
  228. return 1;
  229. }
  230. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  231. if (filename) {
  232. proto_drv = bdrv_find_protocol(filename, true, &local_err);
  233. if (!proto_drv) {
  234. error_report_err(local_err);
  235. qemu_opts_free(create_opts);
  236. return 1;
  237. }
  238. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  239. }
  240. qemu_opts_print_help(create_opts);
  241. qemu_opts_free(create_opts);
  242. return 0;
  243. }
  244. static BlockBackend *img_open_opts(const char *optstr,
  245. QemuOpts *opts, int flags, bool writethrough,
  246. bool quiet, bool force_share)
  247. {
  248. QDict *options;
  249. Error *local_err = NULL;
  250. BlockBackend *blk;
  251. options = qemu_opts_to_qdict(opts, NULL);
  252. if (force_share) {
  253. if (qdict_haskey(options, BDRV_OPT_FORCE_SHARE)
  254. && strcmp(qdict_get_str(options, BDRV_OPT_FORCE_SHARE), "on")) {
  255. error_report("--force-share/-U conflicts with image options");
  256. QDECREF(options);
  257. return NULL;
  258. }
  259. qdict_put_str(options, BDRV_OPT_FORCE_SHARE, "on");
  260. }
  261. blk = blk_new_open(NULL, NULL, options, flags, &local_err);
  262. if (!blk) {
  263. error_reportf_err(local_err, "Could not open '%s': ", optstr);
  264. return NULL;
  265. }
  266. blk_set_enable_write_cache(blk, !writethrough);
  267. return blk;
  268. }
  269. static BlockBackend *img_open_file(const char *filename,
  270. QDict *options,
  271. const char *fmt, int flags,
  272. bool writethrough, bool quiet,
  273. bool force_share)
  274. {
  275. BlockBackend *blk;
  276. Error *local_err = NULL;
  277. if (!options) {
  278. options = qdict_new();
  279. }
  280. if (fmt) {
  281. qdict_put_str(options, "driver", fmt);
  282. }
  283. if (force_share) {
  284. qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
  285. }
  286. blk = blk_new_open(filename, NULL, options, flags, &local_err);
  287. if (!blk) {
  288. error_reportf_err(local_err, "Could not open '%s': ", filename);
  289. return NULL;
  290. }
  291. blk_set_enable_write_cache(blk, !writethrough);
  292. return blk;
  293. }
  294. static int img_add_key_secrets(void *opaque,
  295. const char *name, const char *value,
  296. Error **errp)
  297. {
  298. QDict *options = opaque;
  299. if (g_str_has_suffix(name, "key-secret")) {
  300. qdict_put_str(options, name, value);
  301. }
  302. return 0;
  303. }
  304. static BlockBackend *img_open_new_file(const char *filename,
  305. QemuOpts *create_opts,
  306. const char *fmt, int flags,
  307. bool writethrough, bool quiet,
  308. bool force_share)
  309. {
  310. QDict *options = NULL;
  311. options = qdict_new();
  312. qemu_opt_foreach(create_opts, img_add_key_secrets, options, &error_abort);
  313. return img_open_file(filename, options, fmt, flags, writethrough, quiet,
  314. force_share);
  315. }
  316. static BlockBackend *img_open(bool image_opts,
  317. const char *filename,
  318. const char *fmt, int flags, bool writethrough,
  319. bool quiet, bool force_share)
  320. {
  321. BlockBackend *blk;
  322. if (image_opts) {
  323. QemuOpts *opts;
  324. if (fmt) {
  325. error_report("--image-opts and --format are mutually exclusive");
  326. return NULL;
  327. }
  328. opts = qemu_opts_parse_noisily(qemu_find_opts("source"),
  329. filename, true);
  330. if (!opts) {
  331. return NULL;
  332. }
  333. blk = img_open_opts(filename, opts, flags, writethrough, quiet,
  334. force_share);
  335. } else {
  336. blk = img_open_file(filename, NULL, fmt, flags, writethrough, quiet,
  337. force_share);
  338. }
  339. return blk;
  340. }
  341. static int add_old_style_options(const char *fmt, QemuOpts *opts,
  342. const char *base_filename,
  343. const char *base_fmt)
  344. {
  345. Error *err = NULL;
  346. if (base_filename) {
  347. qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &err);
  348. if (err) {
  349. error_report("Backing file not supported for file format '%s'",
  350. fmt);
  351. error_free(err);
  352. return -1;
  353. }
  354. }
  355. if (base_fmt) {
  356. qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &err);
  357. if (err) {
  358. error_report("Backing file format not supported for file "
  359. "format '%s'", fmt);
  360. error_free(err);
  361. return -1;
  362. }
  363. }
  364. return 0;
  365. }
  366. static int64_t cvtnum(const char *s)
  367. {
  368. int err;
  369. uint64_t value;
  370. err = qemu_strtosz(s, NULL, &value);
  371. if (err < 0) {
  372. return err;
  373. }
  374. if (value > INT64_MAX) {
  375. return -ERANGE;
  376. }
  377. return value;
  378. }
  379. static int img_create(int argc, char **argv)
  380. {
  381. int c;
  382. uint64_t img_size = -1;
  383. const char *fmt = "raw";
  384. const char *base_fmt = NULL;
  385. const char *filename;
  386. const char *base_filename = NULL;
  387. char *options = NULL;
  388. Error *local_err = NULL;
  389. bool quiet = false;
  390. int flags = 0;
  391. for(;;) {
  392. static const struct option long_options[] = {
  393. {"help", no_argument, 0, 'h'},
  394. {"object", required_argument, 0, OPTION_OBJECT},
  395. {0, 0, 0, 0}
  396. };
  397. c = getopt_long(argc, argv, ":F:b:f:ho:qu",
  398. long_options, NULL);
  399. if (c == -1) {
  400. break;
  401. }
  402. switch(c) {
  403. case ':':
  404. missing_argument(argv[optind - 1]);
  405. break;
  406. case '?':
  407. unrecognized_option(argv[optind - 1]);
  408. break;
  409. case 'h':
  410. help();
  411. break;
  412. case 'F':
  413. base_fmt = optarg;
  414. break;
  415. case 'b':
  416. base_filename = optarg;
  417. break;
  418. case 'f':
  419. fmt = optarg;
  420. break;
  421. case 'o':
  422. if (!is_valid_option_list(optarg)) {
  423. error_report("Invalid option list: %s", optarg);
  424. goto fail;
  425. }
  426. if (!options) {
  427. options = g_strdup(optarg);
  428. } else {
  429. char *old_options = options;
  430. options = g_strdup_printf("%s,%s", options, optarg);
  431. g_free(old_options);
  432. }
  433. break;
  434. case 'q':
  435. quiet = true;
  436. break;
  437. case 'u':
  438. flags |= BDRV_O_NO_BACKING;
  439. break;
  440. case OPTION_OBJECT: {
  441. QemuOpts *opts;
  442. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  443. optarg, true);
  444. if (!opts) {
  445. goto fail;
  446. }
  447. } break;
  448. }
  449. }
  450. /* Get the filename */
  451. filename = (optind < argc) ? argv[optind] : NULL;
  452. if (options && has_help_option(options)) {
  453. g_free(options);
  454. return print_block_option_help(filename, fmt);
  455. }
  456. if (optind >= argc) {
  457. error_exit("Expecting image file name");
  458. }
  459. optind++;
  460. if (qemu_opts_foreach(&qemu_object_opts,
  461. user_creatable_add_opts_foreach,
  462. NULL, NULL)) {
  463. goto fail;
  464. }
  465. /* Get image size, if specified */
  466. if (optind < argc) {
  467. int64_t sval;
  468. sval = cvtnum(argv[optind++]);
  469. if (sval < 0) {
  470. if (sval == -ERANGE) {
  471. error_report("Image size must be less than 8 EiB!");
  472. } else {
  473. error_report("Invalid image size specified! You may use k, M, "
  474. "G, T, P or E suffixes for ");
  475. error_report("kilobytes, megabytes, gigabytes, terabytes, "
  476. "petabytes and exabytes.");
  477. }
  478. goto fail;
  479. }
  480. img_size = (uint64_t)sval;
  481. }
  482. if (optind != argc) {
  483. error_exit("Unexpected argument: %s", argv[optind]);
  484. }
  485. bdrv_img_create(filename, fmt, base_filename, base_fmt,
  486. options, img_size, flags, quiet, &local_err);
  487. if (local_err) {
  488. error_reportf_err(local_err, "%s: ", filename);
  489. goto fail;
  490. }
  491. g_free(options);
  492. return 0;
  493. fail:
  494. g_free(options);
  495. return 1;
  496. }
  497. static void dump_json_image_check(ImageCheck *check, bool quiet)
  498. {
  499. QString *str;
  500. QObject *obj;
  501. Visitor *v = qobject_output_visitor_new(&obj);
  502. visit_type_ImageCheck(v, NULL, &check, &error_abort);
  503. visit_complete(v, &obj);
  504. str = qobject_to_json_pretty(obj);
  505. assert(str != NULL);
  506. qprintf(quiet, "%s\n", qstring_get_str(str));
  507. qobject_decref(obj);
  508. visit_free(v);
  509. QDECREF(str);
  510. }
  511. static void dump_human_image_check(ImageCheck *check, bool quiet)
  512. {
  513. if (!(check->corruptions || check->leaks || check->check_errors)) {
  514. qprintf(quiet, "No errors were found on the image.\n");
  515. } else {
  516. if (check->corruptions) {
  517. qprintf(quiet, "\n%" PRId64 " errors were found on the image.\n"
  518. "Data may be corrupted, or further writes to the image "
  519. "may corrupt it.\n",
  520. check->corruptions);
  521. }
  522. if (check->leaks) {
  523. qprintf(quiet,
  524. "\n%" PRId64 " leaked clusters were found on the image.\n"
  525. "This means waste of disk space, but no harm to data.\n",
  526. check->leaks);
  527. }
  528. if (check->check_errors) {
  529. qprintf(quiet,
  530. "\n%" PRId64
  531. " internal errors have occurred during the check.\n",
  532. check->check_errors);
  533. }
  534. }
  535. if (check->total_clusters != 0 && check->allocated_clusters != 0) {
  536. qprintf(quiet, "%" PRId64 "/%" PRId64 " = %0.2f%% allocated, "
  537. "%0.2f%% fragmented, %0.2f%% compressed clusters\n",
  538. check->allocated_clusters, check->total_clusters,
  539. check->allocated_clusters * 100.0 / check->total_clusters,
  540. check->fragmented_clusters * 100.0 / check->allocated_clusters,
  541. check->compressed_clusters * 100.0 /
  542. check->allocated_clusters);
  543. }
  544. if (check->image_end_offset) {
  545. qprintf(quiet,
  546. "Image end offset: %" PRId64 "\n", check->image_end_offset);
  547. }
  548. }
  549. static int collect_image_check(BlockDriverState *bs,
  550. ImageCheck *check,
  551. const char *filename,
  552. const char *fmt,
  553. int fix)
  554. {
  555. int ret;
  556. BdrvCheckResult result;
  557. ret = bdrv_check(bs, &result, fix);
  558. if (ret < 0) {
  559. return ret;
  560. }
  561. check->filename = g_strdup(filename);
  562. check->format = g_strdup(bdrv_get_format_name(bs));
  563. check->check_errors = result.check_errors;
  564. check->corruptions = result.corruptions;
  565. check->has_corruptions = result.corruptions != 0;
  566. check->leaks = result.leaks;
  567. check->has_leaks = result.leaks != 0;
  568. check->corruptions_fixed = result.corruptions_fixed;
  569. check->has_corruptions_fixed = result.corruptions != 0;
  570. check->leaks_fixed = result.leaks_fixed;
  571. check->has_leaks_fixed = result.leaks != 0;
  572. check->image_end_offset = result.image_end_offset;
  573. check->has_image_end_offset = result.image_end_offset != 0;
  574. check->total_clusters = result.bfi.total_clusters;
  575. check->has_total_clusters = result.bfi.total_clusters != 0;
  576. check->allocated_clusters = result.bfi.allocated_clusters;
  577. check->has_allocated_clusters = result.bfi.allocated_clusters != 0;
  578. check->fragmented_clusters = result.bfi.fragmented_clusters;
  579. check->has_fragmented_clusters = result.bfi.fragmented_clusters != 0;
  580. check->compressed_clusters = result.bfi.compressed_clusters;
  581. check->has_compressed_clusters = result.bfi.compressed_clusters != 0;
  582. return 0;
  583. }
  584. /*
  585. * Checks an image for consistency. Exit codes:
  586. *
  587. * 0 - Check completed, image is good
  588. * 1 - Check not completed because of internal errors
  589. * 2 - Check completed, image is corrupted
  590. * 3 - Check completed, image has leaked clusters, but is good otherwise
  591. * 63 - Checks are not supported by the image format
  592. */
  593. static int img_check(int argc, char **argv)
  594. {
  595. int c, ret;
  596. OutputFormat output_format = OFORMAT_HUMAN;
  597. const char *filename, *fmt, *output, *cache;
  598. BlockBackend *blk;
  599. BlockDriverState *bs;
  600. int fix = 0;
  601. int flags = BDRV_O_CHECK;
  602. bool writethrough;
  603. ImageCheck *check;
  604. bool quiet = false;
  605. bool image_opts = false;
  606. bool force_share = false;
  607. fmt = NULL;
  608. output = NULL;
  609. cache = BDRV_DEFAULT_CACHE;
  610. for(;;) {
  611. int option_index = 0;
  612. static const struct option long_options[] = {
  613. {"help", no_argument, 0, 'h'},
  614. {"format", required_argument, 0, 'f'},
  615. {"repair", required_argument, 0, 'r'},
  616. {"output", required_argument, 0, OPTION_OUTPUT},
  617. {"object", required_argument, 0, OPTION_OBJECT},
  618. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  619. {"force-share", no_argument, 0, 'U'},
  620. {0, 0, 0, 0}
  621. };
  622. c = getopt_long(argc, argv, ":hf:r:T:qU",
  623. long_options, &option_index);
  624. if (c == -1) {
  625. break;
  626. }
  627. switch(c) {
  628. case ':':
  629. missing_argument(argv[optind - 1]);
  630. break;
  631. case '?':
  632. unrecognized_option(argv[optind - 1]);
  633. break;
  634. case 'h':
  635. help();
  636. break;
  637. case 'f':
  638. fmt = optarg;
  639. break;
  640. case 'r':
  641. flags |= BDRV_O_RDWR;
  642. if (!strcmp(optarg, "leaks")) {
  643. fix = BDRV_FIX_LEAKS;
  644. } else if (!strcmp(optarg, "all")) {
  645. fix = BDRV_FIX_LEAKS | BDRV_FIX_ERRORS;
  646. } else {
  647. error_exit("Unknown option value for -r "
  648. "(expecting 'leaks' or 'all'): %s", optarg);
  649. }
  650. break;
  651. case OPTION_OUTPUT:
  652. output = optarg;
  653. break;
  654. case 'T':
  655. cache = optarg;
  656. break;
  657. case 'q':
  658. quiet = true;
  659. break;
  660. case 'U':
  661. force_share = true;
  662. break;
  663. case OPTION_OBJECT: {
  664. QemuOpts *opts;
  665. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  666. optarg, true);
  667. if (!opts) {
  668. return 1;
  669. }
  670. } break;
  671. case OPTION_IMAGE_OPTS:
  672. image_opts = true;
  673. break;
  674. }
  675. }
  676. if (optind != argc - 1) {
  677. error_exit("Expecting one image file name");
  678. }
  679. filename = argv[optind++];
  680. if (output && !strcmp(output, "json")) {
  681. output_format = OFORMAT_JSON;
  682. } else if (output && !strcmp(output, "human")) {
  683. output_format = OFORMAT_HUMAN;
  684. } else if (output) {
  685. error_report("--output must be used with human or json as argument.");
  686. return 1;
  687. }
  688. if (qemu_opts_foreach(&qemu_object_opts,
  689. user_creatable_add_opts_foreach,
  690. NULL, NULL)) {
  691. return 1;
  692. }
  693. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  694. if (ret < 0) {
  695. error_report("Invalid source cache option: %s", cache);
  696. return 1;
  697. }
  698. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  699. force_share);
  700. if (!blk) {
  701. return 1;
  702. }
  703. bs = blk_bs(blk);
  704. check = g_new0(ImageCheck, 1);
  705. ret = collect_image_check(bs, check, filename, fmt, fix);
  706. if (ret == -ENOTSUP) {
  707. error_report("This image format does not support checks");
  708. ret = 63;
  709. goto fail;
  710. }
  711. if (check->corruptions_fixed || check->leaks_fixed) {
  712. int corruptions_fixed, leaks_fixed;
  713. leaks_fixed = check->leaks_fixed;
  714. corruptions_fixed = check->corruptions_fixed;
  715. if (output_format == OFORMAT_HUMAN) {
  716. qprintf(quiet,
  717. "The following inconsistencies were found and repaired:\n\n"
  718. " %" PRId64 " leaked clusters\n"
  719. " %" PRId64 " corruptions\n\n"
  720. "Double checking the fixed image now...\n",
  721. check->leaks_fixed,
  722. check->corruptions_fixed);
  723. }
  724. ret = collect_image_check(bs, check, filename, fmt, 0);
  725. check->leaks_fixed = leaks_fixed;
  726. check->corruptions_fixed = corruptions_fixed;
  727. }
  728. if (!ret) {
  729. switch (output_format) {
  730. case OFORMAT_HUMAN:
  731. dump_human_image_check(check, quiet);
  732. break;
  733. case OFORMAT_JSON:
  734. dump_json_image_check(check, quiet);
  735. break;
  736. }
  737. }
  738. if (ret || check->check_errors) {
  739. if (ret) {
  740. error_report("Check failed: %s", strerror(-ret));
  741. } else {
  742. error_report("Check failed");
  743. }
  744. ret = 1;
  745. goto fail;
  746. }
  747. if (check->corruptions) {
  748. ret = 2;
  749. } else if (check->leaks) {
  750. ret = 3;
  751. } else {
  752. ret = 0;
  753. }
  754. fail:
  755. qapi_free_ImageCheck(check);
  756. blk_unref(blk);
  757. return ret;
  758. }
  759. typedef struct CommonBlockJobCBInfo {
  760. BlockDriverState *bs;
  761. Error **errp;
  762. } CommonBlockJobCBInfo;
  763. static void common_block_job_cb(void *opaque, int ret)
  764. {
  765. CommonBlockJobCBInfo *cbi = opaque;
  766. if (ret < 0) {
  767. error_setg_errno(cbi->errp, -ret, "Block job failed");
  768. }
  769. }
  770. static void run_block_job(BlockJob *job, Error **errp)
  771. {
  772. AioContext *aio_context = blk_get_aio_context(job->blk);
  773. int ret = 0;
  774. aio_context_acquire(aio_context);
  775. block_job_ref(job);
  776. do {
  777. aio_poll(aio_context, true);
  778. qemu_progress_print(job->len ?
  779. ((float)job->offset / job->len * 100.f) : 0.0f, 0);
  780. } while (!job->ready && !job->completed);
  781. if (!job->completed) {
  782. ret = block_job_complete_sync(job, errp);
  783. } else {
  784. ret = job->ret;
  785. }
  786. block_job_unref(job);
  787. aio_context_release(aio_context);
  788. /* publish completion progress only when success */
  789. if (!ret) {
  790. qemu_progress_print(100.f, 0);
  791. }
  792. }
  793. static int img_commit(int argc, char **argv)
  794. {
  795. int c, ret, flags;
  796. const char *filename, *fmt, *cache, *base;
  797. BlockBackend *blk;
  798. BlockDriverState *bs, *base_bs;
  799. BlockJob *job;
  800. bool progress = false, quiet = false, drop = false;
  801. bool writethrough;
  802. Error *local_err = NULL;
  803. CommonBlockJobCBInfo cbi;
  804. bool image_opts = false;
  805. AioContext *aio_context;
  806. fmt = NULL;
  807. cache = BDRV_DEFAULT_CACHE;
  808. base = NULL;
  809. for(;;) {
  810. static const struct option long_options[] = {
  811. {"help", no_argument, 0, 'h'},
  812. {"object", required_argument, 0, OPTION_OBJECT},
  813. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  814. {0, 0, 0, 0}
  815. };
  816. c = getopt_long(argc, argv, ":f:ht:b:dpq",
  817. long_options, NULL);
  818. if (c == -1) {
  819. break;
  820. }
  821. switch(c) {
  822. case ':':
  823. missing_argument(argv[optind - 1]);
  824. break;
  825. case '?':
  826. unrecognized_option(argv[optind - 1]);
  827. break;
  828. case 'h':
  829. help();
  830. break;
  831. case 'f':
  832. fmt = optarg;
  833. break;
  834. case 't':
  835. cache = optarg;
  836. break;
  837. case 'b':
  838. base = optarg;
  839. /* -b implies -d */
  840. drop = true;
  841. break;
  842. case 'd':
  843. drop = true;
  844. break;
  845. case 'p':
  846. progress = true;
  847. break;
  848. case 'q':
  849. quiet = true;
  850. break;
  851. case OPTION_OBJECT: {
  852. QemuOpts *opts;
  853. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  854. optarg, true);
  855. if (!opts) {
  856. return 1;
  857. }
  858. } break;
  859. case OPTION_IMAGE_OPTS:
  860. image_opts = true;
  861. break;
  862. }
  863. }
  864. /* Progress is not shown in Quiet mode */
  865. if (quiet) {
  866. progress = false;
  867. }
  868. if (optind != argc - 1) {
  869. error_exit("Expecting one image file name");
  870. }
  871. filename = argv[optind++];
  872. if (qemu_opts_foreach(&qemu_object_opts,
  873. user_creatable_add_opts_foreach,
  874. NULL, NULL)) {
  875. return 1;
  876. }
  877. flags = BDRV_O_RDWR | BDRV_O_UNMAP;
  878. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  879. if (ret < 0) {
  880. error_report("Invalid cache option: %s", cache);
  881. return 1;
  882. }
  883. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  884. false);
  885. if (!blk) {
  886. return 1;
  887. }
  888. bs = blk_bs(blk);
  889. qemu_progress_init(progress, 1.f);
  890. qemu_progress_print(0.f, 100);
  891. if (base) {
  892. base_bs = bdrv_find_backing_image(bs, base);
  893. if (!base_bs) {
  894. error_setg(&local_err,
  895. "Did not find '%s' in the backing chain of '%s'",
  896. base, filename);
  897. goto done;
  898. }
  899. } else {
  900. /* This is different from QMP, which by default uses the deepest file in
  901. * the backing chain (i.e., the very base); however, the traditional
  902. * behavior of qemu-img commit is using the immediate backing file. */
  903. base_bs = backing_bs(bs);
  904. if (!base_bs) {
  905. error_setg(&local_err, "Image does not have a backing file");
  906. goto done;
  907. }
  908. }
  909. cbi = (CommonBlockJobCBInfo){
  910. .errp = &local_err,
  911. .bs = bs,
  912. };
  913. aio_context = bdrv_get_aio_context(bs);
  914. aio_context_acquire(aio_context);
  915. commit_active_start("commit", bs, base_bs, BLOCK_JOB_DEFAULT, 0,
  916. BLOCKDEV_ON_ERROR_REPORT, NULL, common_block_job_cb,
  917. &cbi, false, &local_err);
  918. aio_context_release(aio_context);
  919. if (local_err) {
  920. goto done;
  921. }
  922. /* When the block job completes, the BlockBackend reference will point to
  923. * the old backing file. In order to avoid that the top image is already
  924. * deleted, so we can still empty it afterwards, increment the reference
  925. * counter here preemptively. */
  926. if (!drop) {
  927. bdrv_ref(bs);
  928. }
  929. job = block_job_get("commit");
  930. run_block_job(job, &local_err);
  931. if (local_err) {
  932. goto unref_backing;
  933. }
  934. if (!drop && bs->drv->bdrv_make_empty) {
  935. ret = bs->drv->bdrv_make_empty(bs);
  936. if (ret) {
  937. error_setg_errno(&local_err, -ret, "Could not empty %s",
  938. filename);
  939. goto unref_backing;
  940. }
  941. }
  942. unref_backing:
  943. if (!drop) {
  944. bdrv_unref(bs);
  945. }
  946. done:
  947. qemu_progress_end();
  948. blk_unref(blk);
  949. if (local_err) {
  950. error_report_err(local_err);
  951. return 1;
  952. }
  953. qprintf(quiet, "Image committed.\n");
  954. return 0;
  955. }
  956. /*
  957. * Returns -1 if 'buf' contains only zeroes, otherwise the byte index
  958. * of the first sector boundary within buf where the sector contains a
  959. * non-zero byte. This function is robust to a buffer that is not
  960. * sector-aligned.
  961. */
  962. static int64_t find_nonzero(const uint8_t *buf, int64_t n)
  963. {
  964. int64_t i;
  965. int64_t end = QEMU_ALIGN_DOWN(n, BDRV_SECTOR_SIZE);
  966. for (i = 0; i < end; i += BDRV_SECTOR_SIZE) {
  967. if (!buffer_is_zero(buf + i, BDRV_SECTOR_SIZE)) {
  968. return i;
  969. }
  970. }
  971. if (i < n && !buffer_is_zero(buf + i, n - end)) {
  972. return i;
  973. }
  974. return -1;
  975. }
  976. /*
  977. * Returns true iff the first sector pointed to by 'buf' contains at least
  978. * a non-NUL byte.
  979. *
  980. * 'pnum' is set to the number of sectors (including and immediately following
  981. * the first one) that are known to be in the same allocated/unallocated state.
  982. */
  983. static int is_allocated_sectors(const uint8_t *buf, int n, int *pnum)
  984. {
  985. bool is_zero;
  986. int i;
  987. if (n <= 0) {
  988. *pnum = 0;
  989. return 0;
  990. }
  991. is_zero = buffer_is_zero(buf, 512);
  992. for(i = 1; i < n; i++) {
  993. buf += 512;
  994. if (is_zero != buffer_is_zero(buf, 512)) {
  995. break;
  996. }
  997. }
  998. *pnum = i;
  999. return !is_zero;
  1000. }
  1001. /*
  1002. * Like is_allocated_sectors, but if the buffer starts with a used sector,
  1003. * up to 'min' consecutive sectors containing zeros are ignored. This avoids
  1004. * breaking up write requests for only small sparse areas.
  1005. */
  1006. static int is_allocated_sectors_min(const uint8_t *buf, int n, int *pnum,
  1007. int min)
  1008. {
  1009. int ret;
  1010. int num_checked, num_used;
  1011. if (n < min) {
  1012. min = n;
  1013. }
  1014. ret = is_allocated_sectors(buf, n, pnum);
  1015. if (!ret) {
  1016. return ret;
  1017. }
  1018. num_used = *pnum;
  1019. buf += BDRV_SECTOR_SIZE * *pnum;
  1020. n -= *pnum;
  1021. num_checked = num_used;
  1022. while (n > 0) {
  1023. ret = is_allocated_sectors(buf, n, pnum);
  1024. buf += BDRV_SECTOR_SIZE * *pnum;
  1025. n -= *pnum;
  1026. num_checked += *pnum;
  1027. if (ret) {
  1028. num_used = num_checked;
  1029. } else if (*pnum >= min) {
  1030. break;
  1031. }
  1032. }
  1033. *pnum = num_used;
  1034. return 1;
  1035. }
  1036. /*
  1037. * Compares two buffers sector by sector. Returns 0 if the first
  1038. * sector of each buffer matches, non-zero otherwise.
  1039. *
  1040. * pnum is set to the sector-aligned size of the buffer prefix that
  1041. * has the same matching status as the first sector.
  1042. */
  1043. static int compare_buffers(const uint8_t *buf1, const uint8_t *buf2,
  1044. int64_t bytes, int64_t *pnum)
  1045. {
  1046. bool res;
  1047. int64_t i = MIN(bytes, BDRV_SECTOR_SIZE);
  1048. assert(bytes > 0);
  1049. res = !!memcmp(buf1, buf2, i);
  1050. while (i < bytes) {
  1051. int64_t len = MIN(bytes - i, BDRV_SECTOR_SIZE);
  1052. if (!!memcmp(buf1 + i, buf2 + i, len) != res) {
  1053. break;
  1054. }
  1055. i += len;
  1056. }
  1057. *pnum = i;
  1058. return res;
  1059. }
  1060. #define IO_BUF_SIZE (2 * 1024 * 1024)
  1061. /*
  1062. * Check if passed sectors are empty (not allocated or contain only 0 bytes)
  1063. *
  1064. * Intended for use by 'qemu-img compare': Returns 0 in case sectors are
  1065. * filled with 0, 1 if sectors contain non-zero data (this is a comparison
  1066. * failure), and 4 on error (the exit status for read errors), after emitting
  1067. * an error message.
  1068. *
  1069. * @param blk: BlockBackend for the image
  1070. * @param offset: Starting offset to check
  1071. * @param bytes: Number of bytes to check
  1072. * @param filename: Name of disk file we are checking (logging purpose)
  1073. * @param buffer: Allocated buffer for storing read data
  1074. * @param quiet: Flag for quiet mode
  1075. */
  1076. static int check_empty_sectors(BlockBackend *blk, int64_t offset,
  1077. int64_t bytes, const char *filename,
  1078. uint8_t *buffer, bool quiet)
  1079. {
  1080. int ret = 0;
  1081. int64_t idx;
  1082. ret = blk_pread(blk, offset, buffer, bytes);
  1083. if (ret < 0) {
  1084. error_report("Error while reading offset %" PRId64 " of %s: %s",
  1085. offset, filename, strerror(-ret));
  1086. return 4;
  1087. }
  1088. idx = find_nonzero(buffer, bytes);
  1089. if (idx >= 0) {
  1090. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  1091. offset + idx);
  1092. return 1;
  1093. }
  1094. return 0;
  1095. }
  1096. /*
  1097. * Compares two images. Exit codes:
  1098. *
  1099. * 0 - Images are identical
  1100. * 1 - Images differ
  1101. * >1 - Error occurred
  1102. */
  1103. static int img_compare(int argc, char **argv)
  1104. {
  1105. const char *fmt1 = NULL, *fmt2 = NULL, *cache, *filename1, *filename2;
  1106. BlockBackend *blk1, *blk2;
  1107. BlockDriverState *bs1, *bs2;
  1108. int64_t total_size1, total_size2;
  1109. uint8_t *buf1 = NULL, *buf2 = NULL;
  1110. int64_t pnum1, pnum2;
  1111. int allocated1, allocated2;
  1112. int ret = 0; /* return value - 0 Ident, 1 Different, >1 Error */
  1113. bool progress = false, quiet = false, strict = false;
  1114. int flags;
  1115. bool writethrough;
  1116. int64_t total_size;
  1117. int64_t offset = 0;
  1118. int64_t chunk;
  1119. int c;
  1120. uint64_t progress_base;
  1121. bool image_opts = false;
  1122. bool force_share = false;
  1123. cache = BDRV_DEFAULT_CACHE;
  1124. for (;;) {
  1125. static const struct option long_options[] = {
  1126. {"help", no_argument, 0, 'h'},
  1127. {"object", required_argument, 0, OPTION_OBJECT},
  1128. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  1129. {"force-share", no_argument, 0, 'U'},
  1130. {0, 0, 0, 0}
  1131. };
  1132. c = getopt_long(argc, argv, ":hf:F:T:pqsU",
  1133. long_options, NULL);
  1134. if (c == -1) {
  1135. break;
  1136. }
  1137. switch (c) {
  1138. case ':':
  1139. missing_argument(argv[optind - 1]);
  1140. break;
  1141. case '?':
  1142. unrecognized_option(argv[optind - 1]);
  1143. break;
  1144. case 'h':
  1145. help();
  1146. break;
  1147. case 'f':
  1148. fmt1 = optarg;
  1149. break;
  1150. case 'F':
  1151. fmt2 = optarg;
  1152. break;
  1153. case 'T':
  1154. cache = optarg;
  1155. break;
  1156. case 'p':
  1157. progress = true;
  1158. break;
  1159. case 'q':
  1160. quiet = true;
  1161. break;
  1162. case 's':
  1163. strict = true;
  1164. break;
  1165. case 'U':
  1166. force_share = true;
  1167. break;
  1168. case OPTION_OBJECT: {
  1169. QemuOpts *opts;
  1170. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  1171. optarg, true);
  1172. if (!opts) {
  1173. ret = 2;
  1174. goto out4;
  1175. }
  1176. } break;
  1177. case OPTION_IMAGE_OPTS:
  1178. image_opts = true;
  1179. break;
  1180. }
  1181. }
  1182. /* Progress is not shown in Quiet mode */
  1183. if (quiet) {
  1184. progress = false;
  1185. }
  1186. if (optind != argc - 2) {
  1187. error_exit("Expecting two image file names");
  1188. }
  1189. filename1 = argv[optind++];
  1190. filename2 = argv[optind++];
  1191. if (qemu_opts_foreach(&qemu_object_opts,
  1192. user_creatable_add_opts_foreach,
  1193. NULL, NULL)) {
  1194. ret = 2;
  1195. goto out4;
  1196. }
  1197. /* Initialize before goto out */
  1198. qemu_progress_init(progress, 2.0);
  1199. flags = 0;
  1200. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  1201. if (ret < 0) {
  1202. error_report("Invalid source cache option: %s", cache);
  1203. ret = 2;
  1204. goto out3;
  1205. }
  1206. blk1 = img_open(image_opts, filename1, fmt1, flags, writethrough, quiet,
  1207. force_share);
  1208. if (!blk1) {
  1209. ret = 2;
  1210. goto out3;
  1211. }
  1212. blk2 = img_open(image_opts, filename2, fmt2, flags, writethrough, quiet,
  1213. force_share);
  1214. if (!blk2) {
  1215. ret = 2;
  1216. goto out2;
  1217. }
  1218. bs1 = blk_bs(blk1);
  1219. bs2 = blk_bs(blk2);
  1220. buf1 = blk_blockalign(blk1, IO_BUF_SIZE);
  1221. buf2 = blk_blockalign(blk2, IO_BUF_SIZE);
  1222. total_size1 = blk_getlength(blk1);
  1223. if (total_size1 < 0) {
  1224. error_report("Can't get size of %s: %s",
  1225. filename1, strerror(-total_size1));
  1226. ret = 4;
  1227. goto out;
  1228. }
  1229. total_size2 = blk_getlength(blk2);
  1230. if (total_size2 < 0) {
  1231. error_report("Can't get size of %s: %s",
  1232. filename2, strerror(-total_size2));
  1233. ret = 4;
  1234. goto out;
  1235. }
  1236. total_size = MIN(total_size1, total_size2);
  1237. progress_base = MAX(total_size1, total_size2);
  1238. qemu_progress_print(0, 100);
  1239. if (strict && total_size1 != total_size2) {
  1240. ret = 1;
  1241. qprintf(quiet, "Strict mode: Image size mismatch!\n");
  1242. goto out;
  1243. }
  1244. while (offset < total_size) {
  1245. int status1, status2;
  1246. status1 = bdrv_block_status_above(bs1, NULL, offset,
  1247. total_size1 - offset, &pnum1, NULL,
  1248. NULL);
  1249. if (status1 < 0) {
  1250. ret = 3;
  1251. error_report("Sector allocation test failed for %s", filename1);
  1252. goto out;
  1253. }
  1254. allocated1 = status1 & BDRV_BLOCK_ALLOCATED;
  1255. status2 = bdrv_block_status_above(bs2, NULL, offset,
  1256. total_size2 - offset, &pnum2, NULL,
  1257. NULL);
  1258. if (status2 < 0) {
  1259. ret = 3;
  1260. error_report("Sector allocation test failed for %s", filename2);
  1261. goto out;
  1262. }
  1263. allocated2 = status2 & BDRV_BLOCK_ALLOCATED;
  1264. assert(pnum1 && pnum2);
  1265. chunk = MIN(pnum1, pnum2);
  1266. if (strict) {
  1267. if (status1 != status2) {
  1268. ret = 1;
  1269. qprintf(quiet, "Strict mode: Offset %" PRId64
  1270. " block status mismatch!\n", offset);
  1271. goto out;
  1272. }
  1273. }
  1274. if ((status1 & BDRV_BLOCK_ZERO) && (status2 & BDRV_BLOCK_ZERO)) {
  1275. /* nothing to do */
  1276. } else if (allocated1 == allocated2) {
  1277. if (allocated1) {
  1278. int64_t pnum;
  1279. chunk = MIN(chunk, IO_BUF_SIZE);
  1280. ret = blk_pread(blk1, offset, buf1, chunk);
  1281. if (ret < 0) {
  1282. error_report("Error while reading offset %" PRId64
  1283. " of %s: %s",
  1284. offset, filename1, strerror(-ret));
  1285. ret = 4;
  1286. goto out;
  1287. }
  1288. ret = blk_pread(blk2, offset, buf2, chunk);
  1289. if (ret < 0) {
  1290. error_report("Error while reading offset %" PRId64
  1291. " of %s: %s",
  1292. offset, filename2, strerror(-ret));
  1293. ret = 4;
  1294. goto out;
  1295. }
  1296. ret = compare_buffers(buf1, buf2, chunk, &pnum);
  1297. if (ret || pnum != chunk) {
  1298. qprintf(quiet, "Content mismatch at offset %" PRId64 "!\n",
  1299. offset + (ret ? 0 : pnum));
  1300. ret = 1;
  1301. goto out;
  1302. }
  1303. }
  1304. } else {
  1305. chunk = MIN(chunk, IO_BUF_SIZE);
  1306. if (allocated1) {
  1307. ret = check_empty_sectors(blk1, offset, chunk,
  1308. filename1, buf1, quiet);
  1309. } else {
  1310. ret = check_empty_sectors(blk2, offset, chunk,
  1311. filename2, buf1, quiet);
  1312. }
  1313. if (ret) {
  1314. goto out;
  1315. }
  1316. }
  1317. offset += chunk;
  1318. qemu_progress_print(((float) chunk / progress_base) * 100, 100);
  1319. }
  1320. if (total_size1 != total_size2) {
  1321. BlockBackend *blk_over;
  1322. const char *filename_over;
  1323. qprintf(quiet, "Warning: Image size mismatch!\n");
  1324. if (total_size1 > total_size2) {
  1325. blk_over = blk1;
  1326. filename_over = filename1;
  1327. } else {
  1328. blk_over = blk2;
  1329. filename_over = filename2;
  1330. }
  1331. while (offset < progress_base) {
  1332. ret = bdrv_block_status_above(blk_bs(blk_over), NULL, offset,
  1333. progress_base - offset, &chunk,
  1334. NULL, NULL);
  1335. if (ret < 0) {
  1336. ret = 3;
  1337. error_report("Sector allocation test failed for %s",
  1338. filename_over);
  1339. goto out;
  1340. }
  1341. if (ret & BDRV_BLOCK_ALLOCATED && !(ret & BDRV_BLOCK_ZERO)) {
  1342. chunk = MIN(chunk, IO_BUF_SIZE);
  1343. ret = check_empty_sectors(blk_over, offset, chunk,
  1344. filename_over, buf1, quiet);
  1345. if (ret) {
  1346. goto out;
  1347. }
  1348. }
  1349. offset += chunk;
  1350. qemu_progress_print(((float) chunk / progress_base) * 100, 100);
  1351. }
  1352. }
  1353. qprintf(quiet, "Images are identical.\n");
  1354. ret = 0;
  1355. out:
  1356. qemu_vfree(buf1);
  1357. qemu_vfree(buf2);
  1358. blk_unref(blk2);
  1359. out2:
  1360. blk_unref(blk1);
  1361. out3:
  1362. qemu_progress_end();
  1363. out4:
  1364. return ret;
  1365. }
  1366. enum ImgConvertBlockStatus {
  1367. BLK_DATA,
  1368. BLK_ZERO,
  1369. BLK_BACKING_FILE,
  1370. };
  1371. #define MAX_COROUTINES 16
  1372. typedef struct ImgConvertState {
  1373. BlockBackend **src;
  1374. int64_t *src_sectors;
  1375. int src_num;
  1376. int64_t total_sectors;
  1377. int64_t allocated_sectors;
  1378. int64_t allocated_done;
  1379. int64_t sector_num;
  1380. int64_t wr_offs;
  1381. enum ImgConvertBlockStatus status;
  1382. int64_t sector_next_status;
  1383. BlockBackend *target;
  1384. bool has_zero_init;
  1385. bool compressed;
  1386. bool target_has_backing;
  1387. bool wr_in_order;
  1388. int min_sparse;
  1389. size_t cluster_sectors;
  1390. size_t buf_sectors;
  1391. long num_coroutines;
  1392. int running_coroutines;
  1393. Coroutine *co[MAX_COROUTINES];
  1394. int64_t wait_sector_num[MAX_COROUTINES];
  1395. CoMutex lock;
  1396. int ret;
  1397. } ImgConvertState;
  1398. static void convert_select_part(ImgConvertState *s, int64_t sector_num,
  1399. int *src_cur, int64_t *src_cur_offset)
  1400. {
  1401. *src_cur = 0;
  1402. *src_cur_offset = 0;
  1403. while (sector_num - *src_cur_offset >= s->src_sectors[*src_cur]) {
  1404. *src_cur_offset += s->src_sectors[*src_cur];
  1405. (*src_cur)++;
  1406. assert(*src_cur < s->src_num);
  1407. }
  1408. }
  1409. static int convert_iteration_sectors(ImgConvertState *s, int64_t sector_num)
  1410. {
  1411. int64_t src_cur_offset;
  1412. int ret, n, src_cur;
  1413. convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
  1414. assert(s->total_sectors > sector_num);
  1415. n = MIN(s->total_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
  1416. if (s->sector_next_status <= sector_num) {
  1417. int64_t count = n * BDRV_SECTOR_SIZE;
  1418. if (s->target_has_backing) {
  1419. ret = bdrv_block_status(blk_bs(s->src[src_cur]),
  1420. (sector_num - src_cur_offset) *
  1421. BDRV_SECTOR_SIZE,
  1422. count, &count, NULL, NULL);
  1423. } else {
  1424. ret = bdrv_block_status_above(blk_bs(s->src[src_cur]), NULL,
  1425. (sector_num - src_cur_offset) *
  1426. BDRV_SECTOR_SIZE,
  1427. count, &count, NULL, NULL);
  1428. }
  1429. if (ret < 0) {
  1430. return ret;
  1431. }
  1432. n = DIV_ROUND_UP(count, BDRV_SECTOR_SIZE);
  1433. if (ret & BDRV_BLOCK_ZERO) {
  1434. s->status = BLK_ZERO;
  1435. } else if (ret & BDRV_BLOCK_DATA) {
  1436. s->status = BLK_DATA;
  1437. } else {
  1438. s->status = s->target_has_backing ? BLK_BACKING_FILE : BLK_DATA;
  1439. }
  1440. s->sector_next_status = sector_num + n;
  1441. }
  1442. n = MIN(n, s->sector_next_status - sector_num);
  1443. if (s->status == BLK_DATA) {
  1444. n = MIN(n, s->buf_sectors);
  1445. }
  1446. /* We need to write complete clusters for compressed images, so if an
  1447. * unallocated area is shorter than that, we must consider the whole
  1448. * cluster allocated. */
  1449. if (s->compressed) {
  1450. if (n < s->cluster_sectors) {
  1451. n = MIN(s->cluster_sectors, s->total_sectors - sector_num);
  1452. s->status = BLK_DATA;
  1453. } else {
  1454. n = QEMU_ALIGN_DOWN(n, s->cluster_sectors);
  1455. }
  1456. }
  1457. return n;
  1458. }
  1459. static int coroutine_fn convert_co_read(ImgConvertState *s, int64_t sector_num,
  1460. int nb_sectors, uint8_t *buf)
  1461. {
  1462. int n, ret;
  1463. QEMUIOVector qiov;
  1464. struct iovec iov;
  1465. assert(nb_sectors <= s->buf_sectors);
  1466. while (nb_sectors > 0) {
  1467. BlockBackend *blk;
  1468. int src_cur;
  1469. int64_t bs_sectors, src_cur_offset;
  1470. /* In the case of compression with multiple source files, we can get a
  1471. * nb_sectors that spreads into the next part. So we must be able to
  1472. * read across multiple BDSes for one convert_read() call. */
  1473. convert_select_part(s, sector_num, &src_cur, &src_cur_offset);
  1474. blk = s->src[src_cur];
  1475. bs_sectors = s->src_sectors[src_cur];
  1476. n = MIN(nb_sectors, bs_sectors - (sector_num - src_cur_offset));
  1477. iov.iov_base = buf;
  1478. iov.iov_len = n << BDRV_SECTOR_BITS;
  1479. qemu_iovec_init_external(&qiov, &iov, 1);
  1480. ret = blk_co_preadv(
  1481. blk, (sector_num - src_cur_offset) << BDRV_SECTOR_BITS,
  1482. n << BDRV_SECTOR_BITS, &qiov, 0);
  1483. if (ret < 0) {
  1484. return ret;
  1485. }
  1486. sector_num += n;
  1487. nb_sectors -= n;
  1488. buf += n * BDRV_SECTOR_SIZE;
  1489. }
  1490. return 0;
  1491. }
  1492. static int coroutine_fn convert_co_write(ImgConvertState *s, int64_t sector_num,
  1493. int nb_sectors, uint8_t *buf,
  1494. enum ImgConvertBlockStatus status)
  1495. {
  1496. int ret;
  1497. QEMUIOVector qiov;
  1498. struct iovec iov;
  1499. while (nb_sectors > 0) {
  1500. int n = nb_sectors;
  1501. BdrvRequestFlags flags = s->compressed ? BDRV_REQ_WRITE_COMPRESSED : 0;
  1502. switch (status) {
  1503. case BLK_BACKING_FILE:
  1504. /* If we have a backing file, leave clusters unallocated that are
  1505. * unallocated in the source image, so that the backing file is
  1506. * visible at the respective offset. */
  1507. assert(s->target_has_backing);
  1508. break;
  1509. case BLK_DATA:
  1510. /* If we're told to keep the target fully allocated (-S 0) or there
  1511. * is real non-zero data, we must write it. Otherwise we can treat
  1512. * it as zero sectors.
  1513. * Compressed clusters need to be written as a whole, so in that
  1514. * case we can only save the write if the buffer is completely
  1515. * zeroed. */
  1516. if (!s->min_sparse ||
  1517. (!s->compressed &&
  1518. is_allocated_sectors_min(buf, n, &n, s->min_sparse)) ||
  1519. (s->compressed &&
  1520. !buffer_is_zero(buf, n * BDRV_SECTOR_SIZE)))
  1521. {
  1522. iov.iov_base = buf;
  1523. iov.iov_len = n << BDRV_SECTOR_BITS;
  1524. qemu_iovec_init_external(&qiov, &iov, 1);
  1525. ret = blk_co_pwritev(s->target, sector_num << BDRV_SECTOR_BITS,
  1526. n << BDRV_SECTOR_BITS, &qiov, flags);
  1527. if (ret < 0) {
  1528. return ret;
  1529. }
  1530. break;
  1531. }
  1532. /* fall-through */
  1533. case BLK_ZERO:
  1534. if (s->has_zero_init) {
  1535. assert(!s->target_has_backing);
  1536. break;
  1537. }
  1538. ret = blk_co_pwrite_zeroes(s->target,
  1539. sector_num << BDRV_SECTOR_BITS,
  1540. n << BDRV_SECTOR_BITS, 0);
  1541. if (ret < 0) {
  1542. return ret;
  1543. }
  1544. break;
  1545. }
  1546. sector_num += n;
  1547. nb_sectors -= n;
  1548. buf += n * BDRV_SECTOR_SIZE;
  1549. }
  1550. return 0;
  1551. }
  1552. static void coroutine_fn convert_co_do_copy(void *opaque)
  1553. {
  1554. ImgConvertState *s = opaque;
  1555. uint8_t *buf = NULL;
  1556. int ret, i;
  1557. int index = -1;
  1558. for (i = 0; i < s->num_coroutines; i++) {
  1559. if (s->co[i] == qemu_coroutine_self()) {
  1560. index = i;
  1561. break;
  1562. }
  1563. }
  1564. assert(index >= 0);
  1565. s->running_coroutines++;
  1566. buf = blk_blockalign(s->target, s->buf_sectors * BDRV_SECTOR_SIZE);
  1567. while (1) {
  1568. int n;
  1569. int64_t sector_num;
  1570. enum ImgConvertBlockStatus status;
  1571. qemu_co_mutex_lock(&s->lock);
  1572. if (s->ret != -EINPROGRESS || s->sector_num >= s->total_sectors) {
  1573. qemu_co_mutex_unlock(&s->lock);
  1574. break;
  1575. }
  1576. n = convert_iteration_sectors(s, s->sector_num);
  1577. if (n < 0) {
  1578. qemu_co_mutex_unlock(&s->lock);
  1579. s->ret = n;
  1580. break;
  1581. }
  1582. /* save current sector and allocation status to local variables */
  1583. sector_num = s->sector_num;
  1584. status = s->status;
  1585. if (!s->min_sparse && s->status == BLK_ZERO) {
  1586. n = MIN(n, s->buf_sectors);
  1587. }
  1588. /* increment global sector counter so that other coroutines can
  1589. * already continue reading beyond this request */
  1590. s->sector_num += n;
  1591. qemu_co_mutex_unlock(&s->lock);
  1592. if (status == BLK_DATA || (!s->min_sparse && status == BLK_ZERO)) {
  1593. s->allocated_done += n;
  1594. qemu_progress_print(100.0 * s->allocated_done /
  1595. s->allocated_sectors, 0);
  1596. }
  1597. if (status == BLK_DATA) {
  1598. ret = convert_co_read(s, sector_num, n, buf);
  1599. if (ret < 0) {
  1600. error_report("error while reading sector %" PRId64
  1601. ": %s", sector_num, strerror(-ret));
  1602. s->ret = ret;
  1603. }
  1604. } else if (!s->min_sparse && status == BLK_ZERO) {
  1605. status = BLK_DATA;
  1606. memset(buf, 0x00, n * BDRV_SECTOR_SIZE);
  1607. }
  1608. if (s->wr_in_order) {
  1609. /* keep writes in order */
  1610. while (s->wr_offs != sector_num && s->ret == -EINPROGRESS) {
  1611. s->wait_sector_num[index] = sector_num;
  1612. qemu_coroutine_yield();
  1613. }
  1614. s->wait_sector_num[index] = -1;
  1615. }
  1616. if (s->ret == -EINPROGRESS) {
  1617. ret = convert_co_write(s, sector_num, n, buf, status);
  1618. if (ret < 0) {
  1619. error_report("error while writing sector %" PRId64
  1620. ": %s", sector_num, strerror(-ret));
  1621. s->ret = ret;
  1622. }
  1623. }
  1624. if (s->wr_in_order) {
  1625. /* reenter the coroutine that might have waited
  1626. * for this write to complete */
  1627. s->wr_offs = sector_num + n;
  1628. for (i = 0; i < s->num_coroutines; i++) {
  1629. if (s->co[i] && s->wait_sector_num[i] == s->wr_offs) {
  1630. /*
  1631. * A -> B -> A cannot occur because A has
  1632. * s->wait_sector_num[i] == -1 during A -> B. Therefore
  1633. * B will never enter A during this time window.
  1634. */
  1635. qemu_coroutine_enter(s->co[i]);
  1636. break;
  1637. }
  1638. }
  1639. }
  1640. }
  1641. qemu_vfree(buf);
  1642. s->co[index] = NULL;
  1643. s->running_coroutines--;
  1644. if (!s->running_coroutines && s->ret == -EINPROGRESS) {
  1645. /* the convert job finished successfully */
  1646. s->ret = 0;
  1647. }
  1648. }
  1649. static int convert_do_copy(ImgConvertState *s)
  1650. {
  1651. int ret, i, n;
  1652. int64_t sector_num = 0;
  1653. /* Check whether we have zero initialisation or can get it efficiently */
  1654. s->has_zero_init = s->min_sparse && !s->target_has_backing
  1655. ? bdrv_has_zero_init(blk_bs(s->target))
  1656. : false;
  1657. if (!s->has_zero_init && !s->target_has_backing &&
  1658. bdrv_can_write_zeroes_with_unmap(blk_bs(s->target)))
  1659. {
  1660. ret = blk_make_zero(s->target, BDRV_REQ_MAY_UNMAP);
  1661. if (ret == 0) {
  1662. s->has_zero_init = true;
  1663. }
  1664. }
  1665. /* Allocate buffer for copied data. For compressed images, only one cluster
  1666. * can be copied at a time. */
  1667. if (s->compressed) {
  1668. if (s->cluster_sectors <= 0 || s->cluster_sectors > s->buf_sectors) {
  1669. error_report("invalid cluster size");
  1670. return -EINVAL;
  1671. }
  1672. s->buf_sectors = s->cluster_sectors;
  1673. }
  1674. while (sector_num < s->total_sectors) {
  1675. n = convert_iteration_sectors(s, sector_num);
  1676. if (n < 0) {
  1677. return n;
  1678. }
  1679. if (s->status == BLK_DATA || (!s->min_sparse && s->status == BLK_ZERO))
  1680. {
  1681. s->allocated_sectors += n;
  1682. }
  1683. sector_num += n;
  1684. }
  1685. /* Do the copy */
  1686. s->sector_next_status = 0;
  1687. s->ret = -EINPROGRESS;
  1688. qemu_co_mutex_init(&s->lock);
  1689. for (i = 0; i < s->num_coroutines; i++) {
  1690. s->co[i] = qemu_coroutine_create(convert_co_do_copy, s);
  1691. s->wait_sector_num[i] = -1;
  1692. qemu_coroutine_enter(s->co[i]);
  1693. }
  1694. while (s->running_coroutines) {
  1695. main_loop_wait(false);
  1696. }
  1697. if (s->compressed && !s->ret) {
  1698. /* signal EOF to align */
  1699. ret = blk_pwrite_compressed(s->target, 0, NULL, 0);
  1700. if (ret < 0) {
  1701. return ret;
  1702. }
  1703. }
  1704. return s->ret;
  1705. }
  1706. static int img_convert(int argc, char **argv)
  1707. {
  1708. int c, bs_i, flags, src_flags = 0;
  1709. const char *fmt = NULL, *out_fmt = NULL, *cache = "unsafe",
  1710. *src_cache = BDRV_DEFAULT_CACHE, *out_baseimg = NULL,
  1711. *out_filename, *out_baseimg_param, *snapshot_name = NULL;
  1712. BlockDriver *drv = NULL, *proto_drv = NULL;
  1713. BlockDriverInfo bdi;
  1714. BlockDriverState *out_bs;
  1715. QemuOpts *opts = NULL, *sn_opts = NULL;
  1716. QemuOptsList *create_opts = NULL;
  1717. char *options = NULL;
  1718. Error *local_err = NULL;
  1719. bool writethrough, src_writethrough, quiet = false, image_opts = false,
  1720. skip_create = false, progress = false, tgt_image_opts = false;
  1721. int64_t ret = -EINVAL;
  1722. bool force_share = false;
  1723. ImgConvertState s = (ImgConvertState) {
  1724. /* Need at least 4k of zeros for sparse detection */
  1725. .min_sparse = 8,
  1726. .buf_sectors = IO_BUF_SIZE / BDRV_SECTOR_SIZE,
  1727. .wr_in_order = true,
  1728. .num_coroutines = 8,
  1729. };
  1730. for(;;) {
  1731. static const struct option long_options[] = {
  1732. {"help", no_argument, 0, 'h'},
  1733. {"object", required_argument, 0, OPTION_OBJECT},
  1734. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  1735. {"force-share", no_argument, 0, 'U'},
  1736. {"target-image-opts", no_argument, 0, OPTION_TARGET_IMAGE_OPTS},
  1737. {0, 0, 0, 0}
  1738. };
  1739. c = getopt_long(argc, argv, ":hf:O:B:co:s:l:S:pt:T:qnm:WU",
  1740. long_options, NULL);
  1741. if (c == -1) {
  1742. break;
  1743. }
  1744. switch(c) {
  1745. case ':':
  1746. missing_argument(argv[optind - 1]);
  1747. break;
  1748. case '?':
  1749. unrecognized_option(argv[optind - 1]);
  1750. break;
  1751. case 'h':
  1752. help();
  1753. break;
  1754. case 'f':
  1755. fmt = optarg;
  1756. break;
  1757. case 'O':
  1758. out_fmt = optarg;
  1759. break;
  1760. case 'B':
  1761. out_baseimg = optarg;
  1762. break;
  1763. case 'c':
  1764. s.compressed = true;
  1765. break;
  1766. case 'o':
  1767. if (!is_valid_option_list(optarg)) {
  1768. error_report("Invalid option list: %s", optarg);
  1769. goto fail_getopt;
  1770. }
  1771. if (!options) {
  1772. options = g_strdup(optarg);
  1773. } else {
  1774. char *old_options = options;
  1775. options = g_strdup_printf("%s,%s", options, optarg);
  1776. g_free(old_options);
  1777. }
  1778. break;
  1779. case 's':
  1780. snapshot_name = optarg;
  1781. break;
  1782. case 'l':
  1783. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  1784. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  1785. optarg, false);
  1786. if (!sn_opts) {
  1787. error_report("Failed in parsing snapshot param '%s'",
  1788. optarg);
  1789. goto fail_getopt;
  1790. }
  1791. } else {
  1792. snapshot_name = optarg;
  1793. }
  1794. break;
  1795. case 'S':
  1796. {
  1797. int64_t sval;
  1798. sval = cvtnum(optarg);
  1799. if (sval < 0) {
  1800. error_report("Invalid minimum zero buffer size for sparse output specified");
  1801. goto fail_getopt;
  1802. }
  1803. s.min_sparse = sval / BDRV_SECTOR_SIZE;
  1804. break;
  1805. }
  1806. case 'p':
  1807. progress = true;
  1808. break;
  1809. case 't':
  1810. cache = optarg;
  1811. break;
  1812. case 'T':
  1813. src_cache = optarg;
  1814. break;
  1815. case 'q':
  1816. quiet = true;
  1817. break;
  1818. case 'n':
  1819. skip_create = true;
  1820. break;
  1821. case 'm':
  1822. if (qemu_strtol(optarg, NULL, 0, &s.num_coroutines) ||
  1823. s.num_coroutines < 1 || s.num_coroutines > MAX_COROUTINES) {
  1824. error_report("Invalid number of coroutines. Allowed number of"
  1825. " coroutines is between 1 and %d", MAX_COROUTINES);
  1826. goto fail_getopt;
  1827. }
  1828. break;
  1829. case 'W':
  1830. s.wr_in_order = false;
  1831. break;
  1832. case 'U':
  1833. force_share = true;
  1834. break;
  1835. case OPTION_OBJECT: {
  1836. QemuOpts *object_opts;
  1837. object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
  1838. optarg, true);
  1839. if (!object_opts) {
  1840. goto fail_getopt;
  1841. }
  1842. break;
  1843. }
  1844. case OPTION_IMAGE_OPTS:
  1845. image_opts = true;
  1846. break;
  1847. case OPTION_TARGET_IMAGE_OPTS:
  1848. tgt_image_opts = true;
  1849. break;
  1850. }
  1851. }
  1852. if (!out_fmt && !tgt_image_opts) {
  1853. out_fmt = "raw";
  1854. }
  1855. if (qemu_opts_foreach(&qemu_object_opts,
  1856. user_creatable_add_opts_foreach,
  1857. NULL, NULL)) {
  1858. goto fail_getopt;
  1859. }
  1860. if (!s.wr_in_order && s.compressed) {
  1861. error_report("Out of order write and compress are mutually exclusive");
  1862. goto fail_getopt;
  1863. }
  1864. if (tgt_image_opts && !skip_create) {
  1865. error_report("--target-image-opts requires use of -n flag");
  1866. goto fail_getopt;
  1867. }
  1868. s.src_num = argc - optind - 1;
  1869. out_filename = s.src_num >= 1 ? argv[argc - 1] : NULL;
  1870. if (options && has_help_option(options)) {
  1871. if (out_fmt) {
  1872. ret = print_block_option_help(out_filename, out_fmt);
  1873. goto fail_getopt;
  1874. } else {
  1875. error_report("Option help requires a format be specified");
  1876. goto fail_getopt;
  1877. }
  1878. }
  1879. if (s.src_num < 1) {
  1880. error_report("Must specify image file name");
  1881. goto fail_getopt;
  1882. }
  1883. /* ret is still -EINVAL until here */
  1884. ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
  1885. if (ret < 0) {
  1886. error_report("Invalid source cache option: %s", src_cache);
  1887. goto fail_getopt;
  1888. }
  1889. /* Initialize before goto out */
  1890. if (quiet) {
  1891. progress = false;
  1892. }
  1893. qemu_progress_init(progress, 1.0);
  1894. qemu_progress_print(0, 100);
  1895. s.src = g_new0(BlockBackend *, s.src_num);
  1896. s.src_sectors = g_new(int64_t, s.src_num);
  1897. for (bs_i = 0; bs_i < s.src_num; bs_i++) {
  1898. s.src[bs_i] = img_open(image_opts, argv[optind + bs_i],
  1899. fmt, src_flags, src_writethrough, quiet,
  1900. force_share);
  1901. if (!s.src[bs_i]) {
  1902. ret = -1;
  1903. goto out;
  1904. }
  1905. s.src_sectors[bs_i] = blk_nb_sectors(s.src[bs_i]);
  1906. if (s.src_sectors[bs_i] < 0) {
  1907. error_report("Could not get size of %s: %s",
  1908. argv[optind + bs_i], strerror(-s.src_sectors[bs_i]));
  1909. ret = -1;
  1910. goto out;
  1911. }
  1912. s.total_sectors += s.src_sectors[bs_i];
  1913. }
  1914. if (sn_opts) {
  1915. bdrv_snapshot_load_tmp(blk_bs(s.src[0]),
  1916. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  1917. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  1918. &local_err);
  1919. } else if (snapshot_name != NULL) {
  1920. if (s.src_num > 1) {
  1921. error_report("No support for concatenating multiple snapshot");
  1922. ret = -1;
  1923. goto out;
  1924. }
  1925. bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(s.src[0]), snapshot_name,
  1926. &local_err);
  1927. }
  1928. if (local_err) {
  1929. error_reportf_err(local_err, "Failed to load snapshot: ");
  1930. ret = -1;
  1931. goto out;
  1932. }
  1933. if (!skip_create) {
  1934. /* Find driver and parse its options */
  1935. drv = bdrv_find_format(out_fmt);
  1936. if (!drv) {
  1937. error_report("Unknown file format '%s'", out_fmt);
  1938. ret = -1;
  1939. goto out;
  1940. }
  1941. proto_drv = bdrv_find_protocol(out_filename, true, &local_err);
  1942. if (!proto_drv) {
  1943. error_report_err(local_err);
  1944. ret = -1;
  1945. goto out;
  1946. }
  1947. if (!drv->create_opts) {
  1948. error_report("Format driver '%s' does not support image creation",
  1949. drv->format_name);
  1950. ret = -1;
  1951. goto out;
  1952. }
  1953. if (!proto_drv->create_opts) {
  1954. error_report("Protocol driver '%s' does not support image creation",
  1955. proto_drv->format_name);
  1956. ret = -1;
  1957. goto out;
  1958. }
  1959. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  1960. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  1961. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  1962. if (options) {
  1963. qemu_opts_do_parse(opts, options, NULL, &local_err);
  1964. if (local_err) {
  1965. error_report_err(local_err);
  1966. ret = -1;
  1967. goto out;
  1968. }
  1969. }
  1970. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, s.total_sectors * 512,
  1971. &error_abort);
  1972. ret = add_old_style_options(out_fmt, opts, out_baseimg, NULL);
  1973. if (ret < 0) {
  1974. goto out;
  1975. }
  1976. }
  1977. /* Get backing file name if -o backing_file was used */
  1978. out_baseimg_param = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
  1979. if (out_baseimg_param) {
  1980. out_baseimg = out_baseimg_param;
  1981. }
  1982. s.target_has_backing = (bool) out_baseimg;
  1983. if (s.src_num > 1 && out_baseimg) {
  1984. error_report("Having a backing file for the target makes no sense when "
  1985. "concatenating multiple input images");
  1986. ret = -1;
  1987. goto out;
  1988. }
  1989. /* Check if compression is supported */
  1990. if (s.compressed) {
  1991. bool encryption =
  1992. qemu_opt_get_bool(opts, BLOCK_OPT_ENCRYPT, false);
  1993. const char *encryptfmt =
  1994. qemu_opt_get(opts, BLOCK_OPT_ENCRYPT_FORMAT);
  1995. const char *preallocation =
  1996. qemu_opt_get(opts, BLOCK_OPT_PREALLOC);
  1997. if (drv && !drv->bdrv_co_pwritev_compressed) {
  1998. error_report("Compression not supported for this file format");
  1999. ret = -1;
  2000. goto out;
  2001. }
  2002. if (encryption || encryptfmt) {
  2003. error_report("Compression and encryption not supported at "
  2004. "the same time");
  2005. ret = -1;
  2006. goto out;
  2007. }
  2008. if (preallocation
  2009. && strcmp(preallocation, "off"))
  2010. {
  2011. error_report("Compression and preallocation not supported at "
  2012. "the same time");
  2013. ret = -1;
  2014. goto out;
  2015. }
  2016. }
  2017. if (!skip_create) {
  2018. /* Create the new image */
  2019. ret = bdrv_create(drv, out_filename, opts, &local_err);
  2020. if (ret < 0) {
  2021. error_reportf_err(local_err, "%s: error while converting %s: ",
  2022. out_filename, out_fmt);
  2023. goto out;
  2024. }
  2025. }
  2026. flags = s.min_sparse ? (BDRV_O_RDWR | BDRV_O_UNMAP) : BDRV_O_RDWR;
  2027. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  2028. if (ret < 0) {
  2029. error_report("Invalid cache option: %s", cache);
  2030. goto out;
  2031. }
  2032. if (skip_create) {
  2033. s.target = img_open(tgt_image_opts, out_filename, out_fmt,
  2034. flags, writethrough, quiet, false);
  2035. } else {
  2036. /* TODO ultimately we should allow --target-image-opts
  2037. * to be used even when -n is not given.
  2038. * That has to wait for bdrv_create to be improved
  2039. * to allow filenames in option syntax
  2040. */
  2041. s.target = img_open_new_file(out_filename, opts, out_fmt,
  2042. flags, writethrough, quiet, false);
  2043. }
  2044. if (!s.target) {
  2045. ret = -1;
  2046. goto out;
  2047. }
  2048. out_bs = blk_bs(s.target);
  2049. if (s.compressed && !out_bs->drv->bdrv_co_pwritev_compressed) {
  2050. error_report("Compression not supported for this file format");
  2051. ret = -1;
  2052. goto out;
  2053. }
  2054. /* increase bufsectors from the default 4096 (2M) if opt_transfer
  2055. * or discard_alignment of the out_bs is greater. Limit to 32768 (16MB)
  2056. * as maximum. */
  2057. s.buf_sectors = MIN(32768,
  2058. MAX(s.buf_sectors,
  2059. MAX(out_bs->bl.opt_transfer >> BDRV_SECTOR_BITS,
  2060. out_bs->bl.pdiscard_alignment >>
  2061. BDRV_SECTOR_BITS)));
  2062. if (skip_create) {
  2063. int64_t output_sectors = blk_nb_sectors(s.target);
  2064. if (output_sectors < 0) {
  2065. error_report("unable to get output image length: %s",
  2066. strerror(-output_sectors));
  2067. ret = -1;
  2068. goto out;
  2069. } else if (output_sectors < s.total_sectors) {
  2070. error_report("output file is smaller than input file");
  2071. ret = -1;
  2072. goto out;
  2073. }
  2074. }
  2075. ret = bdrv_get_info(out_bs, &bdi);
  2076. if (ret < 0) {
  2077. if (s.compressed) {
  2078. error_report("could not get block driver info");
  2079. goto out;
  2080. }
  2081. } else {
  2082. s.compressed = s.compressed || bdi.needs_compressed_writes;
  2083. s.cluster_sectors = bdi.cluster_size / BDRV_SECTOR_SIZE;
  2084. }
  2085. ret = convert_do_copy(&s);
  2086. out:
  2087. if (!ret) {
  2088. qemu_progress_print(100, 0);
  2089. }
  2090. qemu_progress_end();
  2091. qemu_opts_del(opts);
  2092. qemu_opts_free(create_opts);
  2093. qemu_opts_del(sn_opts);
  2094. blk_unref(s.target);
  2095. if (s.src) {
  2096. for (bs_i = 0; bs_i < s.src_num; bs_i++) {
  2097. blk_unref(s.src[bs_i]);
  2098. }
  2099. g_free(s.src);
  2100. }
  2101. g_free(s.src_sectors);
  2102. fail_getopt:
  2103. g_free(options);
  2104. return !!ret;
  2105. }
  2106. static void dump_snapshots(BlockDriverState *bs)
  2107. {
  2108. QEMUSnapshotInfo *sn_tab, *sn;
  2109. int nb_sns, i;
  2110. nb_sns = bdrv_snapshot_list(bs, &sn_tab);
  2111. if (nb_sns <= 0)
  2112. return;
  2113. printf("Snapshot list:\n");
  2114. bdrv_snapshot_dump(fprintf, stdout, NULL);
  2115. printf("\n");
  2116. for(i = 0; i < nb_sns; i++) {
  2117. sn = &sn_tab[i];
  2118. bdrv_snapshot_dump(fprintf, stdout, sn);
  2119. printf("\n");
  2120. }
  2121. g_free(sn_tab);
  2122. }
  2123. static void dump_json_image_info_list(ImageInfoList *list)
  2124. {
  2125. QString *str;
  2126. QObject *obj;
  2127. Visitor *v = qobject_output_visitor_new(&obj);
  2128. visit_type_ImageInfoList(v, NULL, &list, &error_abort);
  2129. visit_complete(v, &obj);
  2130. str = qobject_to_json_pretty(obj);
  2131. assert(str != NULL);
  2132. printf("%s\n", qstring_get_str(str));
  2133. qobject_decref(obj);
  2134. visit_free(v);
  2135. QDECREF(str);
  2136. }
  2137. static void dump_json_image_info(ImageInfo *info)
  2138. {
  2139. QString *str;
  2140. QObject *obj;
  2141. Visitor *v = qobject_output_visitor_new(&obj);
  2142. visit_type_ImageInfo(v, NULL, &info, &error_abort);
  2143. visit_complete(v, &obj);
  2144. str = qobject_to_json_pretty(obj);
  2145. assert(str != NULL);
  2146. printf("%s\n", qstring_get_str(str));
  2147. qobject_decref(obj);
  2148. visit_free(v);
  2149. QDECREF(str);
  2150. }
  2151. static void dump_human_image_info_list(ImageInfoList *list)
  2152. {
  2153. ImageInfoList *elem;
  2154. bool delim = false;
  2155. for (elem = list; elem; elem = elem->next) {
  2156. if (delim) {
  2157. printf("\n");
  2158. }
  2159. delim = true;
  2160. bdrv_image_info_dump(fprintf, stdout, elem->value);
  2161. }
  2162. }
  2163. static gboolean str_equal_func(gconstpointer a, gconstpointer b)
  2164. {
  2165. return strcmp(a, b) == 0;
  2166. }
  2167. /**
  2168. * Open an image file chain and return an ImageInfoList
  2169. *
  2170. * @filename: topmost image filename
  2171. * @fmt: topmost image format (may be NULL to autodetect)
  2172. * @chain: true - enumerate entire backing file chain
  2173. * false - only topmost image file
  2174. *
  2175. * Returns a list of ImageInfo objects or NULL if there was an error opening an
  2176. * image file. If there was an error a message will have been printed to
  2177. * stderr.
  2178. */
  2179. static ImageInfoList *collect_image_info_list(bool image_opts,
  2180. const char *filename,
  2181. const char *fmt,
  2182. bool chain, bool force_share)
  2183. {
  2184. ImageInfoList *head = NULL;
  2185. ImageInfoList **last = &head;
  2186. GHashTable *filenames;
  2187. Error *err = NULL;
  2188. filenames = g_hash_table_new_full(g_str_hash, str_equal_func, NULL, NULL);
  2189. while (filename) {
  2190. BlockBackend *blk;
  2191. BlockDriverState *bs;
  2192. ImageInfo *info;
  2193. ImageInfoList *elem;
  2194. if (g_hash_table_lookup_extended(filenames, filename, NULL, NULL)) {
  2195. error_report("Backing file '%s' creates an infinite loop.",
  2196. filename);
  2197. goto err;
  2198. }
  2199. g_hash_table_insert(filenames, (gpointer)filename, NULL);
  2200. blk = img_open(image_opts, filename, fmt,
  2201. BDRV_O_NO_BACKING | BDRV_O_NO_IO, false, false,
  2202. force_share);
  2203. if (!blk) {
  2204. goto err;
  2205. }
  2206. bs = blk_bs(blk);
  2207. bdrv_query_image_info(bs, &info, &err);
  2208. if (err) {
  2209. error_report_err(err);
  2210. blk_unref(blk);
  2211. goto err;
  2212. }
  2213. elem = g_new0(ImageInfoList, 1);
  2214. elem->value = info;
  2215. *last = elem;
  2216. last = &elem->next;
  2217. blk_unref(blk);
  2218. filename = fmt = NULL;
  2219. if (chain) {
  2220. if (info->has_full_backing_filename) {
  2221. filename = info->full_backing_filename;
  2222. } else if (info->has_backing_filename) {
  2223. error_report("Could not determine absolute backing filename,"
  2224. " but backing filename '%s' present",
  2225. info->backing_filename);
  2226. goto err;
  2227. }
  2228. if (info->has_backing_filename_format) {
  2229. fmt = info->backing_filename_format;
  2230. }
  2231. }
  2232. }
  2233. g_hash_table_destroy(filenames);
  2234. return head;
  2235. err:
  2236. qapi_free_ImageInfoList(head);
  2237. g_hash_table_destroy(filenames);
  2238. return NULL;
  2239. }
  2240. static int img_info(int argc, char **argv)
  2241. {
  2242. int c;
  2243. OutputFormat output_format = OFORMAT_HUMAN;
  2244. bool chain = false;
  2245. const char *filename, *fmt, *output;
  2246. ImageInfoList *list;
  2247. bool image_opts = false;
  2248. bool force_share = false;
  2249. fmt = NULL;
  2250. output = NULL;
  2251. for(;;) {
  2252. int option_index = 0;
  2253. static const struct option long_options[] = {
  2254. {"help", no_argument, 0, 'h'},
  2255. {"format", required_argument, 0, 'f'},
  2256. {"output", required_argument, 0, OPTION_OUTPUT},
  2257. {"backing-chain", no_argument, 0, OPTION_BACKING_CHAIN},
  2258. {"object", required_argument, 0, OPTION_OBJECT},
  2259. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2260. {"force-share", no_argument, 0, 'U'},
  2261. {0, 0, 0, 0}
  2262. };
  2263. c = getopt_long(argc, argv, ":f:hU",
  2264. long_options, &option_index);
  2265. if (c == -1) {
  2266. break;
  2267. }
  2268. switch(c) {
  2269. case ':':
  2270. missing_argument(argv[optind - 1]);
  2271. break;
  2272. case '?':
  2273. unrecognized_option(argv[optind - 1]);
  2274. break;
  2275. case 'h':
  2276. help();
  2277. break;
  2278. case 'f':
  2279. fmt = optarg;
  2280. break;
  2281. case 'U':
  2282. force_share = true;
  2283. break;
  2284. case OPTION_OUTPUT:
  2285. output = optarg;
  2286. break;
  2287. case OPTION_BACKING_CHAIN:
  2288. chain = true;
  2289. break;
  2290. case OPTION_OBJECT: {
  2291. QemuOpts *opts;
  2292. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2293. optarg, true);
  2294. if (!opts) {
  2295. return 1;
  2296. }
  2297. } break;
  2298. case OPTION_IMAGE_OPTS:
  2299. image_opts = true;
  2300. break;
  2301. }
  2302. }
  2303. if (optind != argc - 1) {
  2304. error_exit("Expecting one image file name");
  2305. }
  2306. filename = argv[optind++];
  2307. if (output && !strcmp(output, "json")) {
  2308. output_format = OFORMAT_JSON;
  2309. } else if (output && !strcmp(output, "human")) {
  2310. output_format = OFORMAT_HUMAN;
  2311. } else if (output) {
  2312. error_report("--output must be used with human or json as argument.");
  2313. return 1;
  2314. }
  2315. if (qemu_opts_foreach(&qemu_object_opts,
  2316. user_creatable_add_opts_foreach,
  2317. NULL, NULL)) {
  2318. return 1;
  2319. }
  2320. list = collect_image_info_list(image_opts, filename, fmt, chain,
  2321. force_share);
  2322. if (!list) {
  2323. return 1;
  2324. }
  2325. switch (output_format) {
  2326. case OFORMAT_HUMAN:
  2327. dump_human_image_info_list(list);
  2328. break;
  2329. case OFORMAT_JSON:
  2330. if (chain) {
  2331. dump_json_image_info_list(list);
  2332. } else {
  2333. dump_json_image_info(list->value);
  2334. }
  2335. break;
  2336. }
  2337. qapi_free_ImageInfoList(list);
  2338. return 0;
  2339. }
  2340. static void dump_map_entry(OutputFormat output_format, MapEntry *e,
  2341. MapEntry *next)
  2342. {
  2343. switch (output_format) {
  2344. case OFORMAT_HUMAN:
  2345. if (e->data && !e->has_offset) {
  2346. error_report("File contains external, encrypted or compressed clusters.");
  2347. exit(1);
  2348. }
  2349. if (e->data && !e->zero) {
  2350. printf("%#-16"PRIx64"%#-16"PRIx64"%#-16"PRIx64"%s\n",
  2351. e->start, e->length,
  2352. e->has_offset ? e->offset : 0,
  2353. e->has_filename ? e->filename : "");
  2354. }
  2355. /* This format ignores the distinction between 0, ZERO and ZERO|DATA.
  2356. * Modify the flags here to allow more coalescing.
  2357. */
  2358. if (next && (!next->data || next->zero)) {
  2359. next->data = false;
  2360. next->zero = true;
  2361. }
  2362. break;
  2363. case OFORMAT_JSON:
  2364. printf("%s{ \"start\": %"PRId64", \"length\": %"PRId64","
  2365. " \"depth\": %"PRId64", \"zero\": %s, \"data\": %s",
  2366. (e->start == 0 ? "[" : ",\n"),
  2367. e->start, e->length, e->depth,
  2368. e->zero ? "true" : "false",
  2369. e->data ? "true" : "false");
  2370. if (e->has_offset) {
  2371. printf(", \"offset\": %"PRId64"", e->offset);
  2372. }
  2373. putchar('}');
  2374. if (!next) {
  2375. printf("]\n");
  2376. }
  2377. break;
  2378. }
  2379. }
  2380. static int get_block_status(BlockDriverState *bs, int64_t offset,
  2381. int64_t bytes, MapEntry *e)
  2382. {
  2383. int ret;
  2384. int depth;
  2385. BlockDriverState *file;
  2386. bool has_offset;
  2387. int64_t map;
  2388. /* As an optimization, we could cache the current range of unallocated
  2389. * clusters in each file of the chain, and avoid querying the same
  2390. * range repeatedly.
  2391. */
  2392. depth = 0;
  2393. for (;;) {
  2394. ret = bdrv_block_status(bs, offset, bytes, &bytes, &map, &file);
  2395. if (ret < 0) {
  2396. return ret;
  2397. }
  2398. assert(bytes);
  2399. if (ret & (BDRV_BLOCK_ZERO|BDRV_BLOCK_DATA)) {
  2400. break;
  2401. }
  2402. bs = backing_bs(bs);
  2403. if (bs == NULL) {
  2404. ret = 0;
  2405. break;
  2406. }
  2407. depth++;
  2408. }
  2409. has_offset = !!(ret & BDRV_BLOCK_OFFSET_VALID);
  2410. *e = (MapEntry) {
  2411. .start = offset,
  2412. .length = bytes,
  2413. .data = !!(ret & BDRV_BLOCK_DATA),
  2414. .zero = !!(ret & BDRV_BLOCK_ZERO),
  2415. .offset = map,
  2416. .has_offset = has_offset,
  2417. .depth = depth,
  2418. .has_filename = file && has_offset,
  2419. .filename = file && has_offset ? file->filename : NULL,
  2420. };
  2421. return 0;
  2422. }
  2423. static inline bool entry_mergeable(const MapEntry *curr, const MapEntry *next)
  2424. {
  2425. if (curr->length == 0) {
  2426. return false;
  2427. }
  2428. if (curr->zero != next->zero ||
  2429. curr->data != next->data ||
  2430. curr->depth != next->depth ||
  2431. curr->has_filename != next->has_filename ||
  2432. curr->has_offset != next->has_offset) {
  2433. return false;
  2434. }
  2435. if (curr->has_filename && strcmp(curr->filename, next->filename)) {
  2436. return false;
  2437. }
  2438. if (curr->has_offset && curr->offset + curr->length != next->offset) {
  2439. return false;
  2440. }
  2441. return true;
  2442. }
  2443. static int img_map(int argc, char **argv)
  2444. {
  2445. int c;
  2446. OutputFormat output_format = OFORMAT_HUMAN;
  2447. BlockBackend *blk;
  2448. BlockDriverState *bs;
  2449. const char *filename, *fmt, *output;
  2450. int64_t length;
  2451. MapEntry curr = { .length = 0 }, next;
  2452. int ret = 0;
  2453. bool image_opts = false;
  2454. bool force_share = false;
  2455. fmt = NULL;
  2456. output = NULL;
  2457. for (;;) {
  2458. int option_index = 0;
  2459. static const struct option long_options[] = {
  2460. {"help", no_argument, 0, 'h'},
  2461. {"format", required_argument, 0, 'f'},
  2462. {"output", required_argument, 0, OPTION_OUTPUT},
  2463. {"object", required_argument, 0, OPTION_OBJECT},
  2464. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2465. {"force-share", no_argument, 0, 'U'},
  2466. {0, 0, 0, 0}
  2467. };
  2468. c = getopt_long(argc, argv, ":f:hU",
  2469. long_options, &option_index);
  2470. if (c == -1) {
  2471. break;
  2472. }
  2473. switch (c) {
  2474. case ':':
  2475. missing_argument(argv[optind - 1]);
  2476. break;
  2477. case '?':
  2478. unrecognized_option(argv[optind - 1]);
  2479. break;
  2480. case 'h':
  2481. help();
  2482. break;
  2483. case 'f':
  2484. fmt = optarg;
  2485. break;
  2486. case 'U':
  2487. force_share = true;
  2488. break;
  2489. case OPTION_OUTPUT:
  2490. output = optarg;
  2491. break;
  2492. case OPTION_OBJECT: {
  2493. QemuOpts *opts;
  2494. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2495. optarg, true);
  2496. if (!opts) {
  2497. return 1;
  2498. }
  2499. } break;
  2500. case OPTION_IMAGE_OPTS:
  2501. image_opts = true;
  2502. break;
  2503. }
  2504. }
  2505. if (optind != argc - 1) {
  2506. error_exit("Expecting one image file name");
  2507. }
  2508. filename = argv[optind];
  2509. if (output && !strcmp(output, "json")) {
  2510. output_format = OFORMAT_JSON;
  2511. } else if (output && !strcmp(output, "human")) {
  2512. output_format = OFORMAT_HUMAN;
  2513. } else if (output) {
  2514. error_report("--output must be used with human or json as argument.");
  2515. return 1;
  2516. }
  2517. if (qemu_opts_foreach(&qemu_object_opts,
  2518. user_creatable_add_opts_foreach,
  2519. NULL, NULL)) {
  2520. return 1;
  2521. }
  2522. blk = img_open(image_opts, filename, fmt, 0, false, false, force_share);
  2523. if (!blk) {
  2524. return 1;
  2525. }
  2526. bs = blk_bs(blk);
  2527. if (output_format == OFORMAT_HUMAN) {
  2528. printf("%-16s%-16s%-16s%s\n", "Offset", "Length", "Mapped to", "File");
  2529. }
  2530. length = blk_getlength(blk);
  2531. while (curr.start + curr.length < length) {
  2532. int64_t offset = curr.start + curr.length;
  2533. int64_t n;
  2534. /* Probe up to 1 GiB at a time. */
  2535. n = MIN(1 << 30, length - offset);
  2536. ret = get_block_status(bs, offset, n, &next);
  2537. if (ret < 0) {
  2538. error_report("Could not read file metadata: %s", strerror(-ret));
  2539. goto out;
  2540. }
  2541. if (entry_mergeable(&curr, &next)) {
  2542. curr.length += next.length;
  2543. continue;
  2544. }
  2545. if (curr.length > 0) {
  2546. dump_map_entry(output_format, &curr, &next);
  2547. }
  2548. curr = next;
  2549. }
  2550. dump_map_entry(output_format, &curr, NULL);
  2551. out:
  2552. blk_unref(blk);
  2553. return ret < 0;
  2554. }
  2555. #define SNAPSHOT_LIST 1
  2556. #define SNAPSHOT_CREATE 2
  2557. #define SNAPSHOT_APPLY 3
  2558. #define SNAPSHOT_DELETE 4
  2559. static int img_snapshot(int argc, char **argv)
  2560. {
  2561. BlockBackend *blk;
  2562. BlockDriverState *bs;
  2563. QEMUSnapshotInfo sn;
  2564. char *filename, *snapshot_name = NULL;
  2565. int c, ret = 0, bdrv_oflags;
  2566. int action = 0;
  2567. qemu_timeval tv;
  2568. bool quiet = false;
  2569. Error *err = NULL;
  2570. bool image_opts = false;
  2571. bool force_share = false;
  2572. bdrv_oflags = BDRV_O_RDWR;
  2573. /* Parse commandline parameters */
  2574. for(;;) {
  2575. static const struct option long_options[] = {
  2576. {"help", no_argument, 0, 'h'},
  2577. {"object", required_argument, 0, OPTION_OBJECT},
  2578. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2579. {"force-share", no_argument, 0, 'U'},
  2580. {0, 0, 0, 0}
  2581. };
  2582. c = getopt_long(argc, argv, ":la:c:d:hqU",
  2583. long_options, NULL);
  2584. if (c == -1) {
  2585. break;
  2586. }
  2587. switch(c) {
  2588. case ':':
  2589. missing_argument(argv[optind - 1]);
  2590. break;
  2591. case '?':
  2592. unrecognized_option(argv[optind - 1]);
  2593. break;
  2594. case 'h':
  2595. help();
  2596. return 0;
  2597. case 'l':
  2598. if (action) {
  2599. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2600. return 0;
  2601. }
  2602. action = SNAPSHOT_LIST;
  2603. bdrv_oflags &= ~BDRV_O_RDWR; /* no need for RW */
  2604. break;
  2605. case 'a':
  2606. if (action) {
  2607. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2608. return 0;
  2609. }
  2610. action = SNAPSHOT_APPLY;
  2611. snapshot_name = optarg;
  2612. break;
  2613. case 'c':
  2614. if (action) {
  2615. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2616. return 0;
  2617. }
  2618. action = SNAPSHOT_CREATE;
  2619. snapshot_name = optarg;
  2620. break;
  2621. case 'd':
  2622. if (action) {
  2623. error_exit("Cannot mix '-l', '-a', '-c', '-d'");
  2624. return 0;
  2625. }
  2626. action = SNAPSHOT_DELETE;
  2627. snapshot_name = optarg;
  2628. break;
  2629. case 'q':
  2630. quiet = true;
  2631. break;
  2632. case 'U':
  2633. force_share = true;
  2634. break;
  2635. case OPTION_OBJECT: {
  2636. QemuOpts *opts;
  2637. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2638. optarg, true);
  2639. if (!opts) {
  2640. return 1;
  2641. }
  2642. } break;
  2643. case OPTION_IMAGE_OPTS:
  2644. image_opts = true;
  2645. break;
  2646. }
  2647. }
  2648. if (optind != argc - 1) {
  2649. error_exit("Expecting one image file name");
  2650. }
  2651. filename = argv[optind++];
  2652. if (qemu_opts_foreach(&qemu_object_opts,
  2653. user_creatable_add_opts_foreach,
  2654. NULL, NULL)) {
  2655. return 1;
  2656. }
  2657. /* Open the image */
  2658. blk = img_open(image_opts, filename, NULL, bdrv_oflags, false, quiet,
  2659. force_share);
  2660. if (!blk) {
  2661. return 1;
  2662. }
  2663. bs = blk_bs(blk);
  2664. /* Perform the requested action */
  2665. switch(action) {
  2666. case SNAPSHOT_LIST:
  2667. dump_snapshots(bs);
  2668. break;
  2669. case SNAPSHOT_CREATE:
  2670. memset(&sn, 0, sizeof(sn));
  2671. pstrcpy(sn.name, sizeof(sn.name), snapshot_name);
  2672. qemu_gettimeofday(&tv);
  2673. sn.date_sec = tv.tv_sec;
  2674. sn.date_nsec = tv.tv_usec * 1000;
  2675. ret = bdrv_snapshot_create(bs, &sn);
  2676. if (ret) {
  2677. error_report("Could not create snapshot '%s': %d (%s)",
  2678. snapshot_name, ret, strerror(-ret));
  2679. }
  2680. break;
  2681. case SNAPSHOT_APPLY:
  2682. ret = bdrv_snapshot_goto(bs, snapshot_name, &err);
  2683. if (ret) {
  2684. error_reportf_err(err, "Could not apply snapshot '%s': ",
  2685. snapshot_name);
  2686. }
  2687. break;
  2688. case SNAPSHOT_DELETE:
  2689. bdrv_snapshot_delete_by_id_or_name(bs, snapshot_name, &err);
  2690. if (err) {
  2691. error_reportf_err(err, "Could not delete snapshot '%s': ",
  2692. snapshot_name);
  2693. ret = 1;
  2694. }
  2695. break;
  2696. }
  2697. /* Cleanup */
  2698. blk_unref(blk);
  2699. if (ret) {
  2700. return 1;
  2701. }
  2702. return 0;
  2703. }
  2704. static int img_rebase(int argc, char **argv)
  2705. {
  2706. BlockBackend *blk = NULL, *blk_old_backing = NULL, *blk_new_backing = NULL;
  2707. uint8_t *buf_old = NULL;
  2708. uint8_t *buf_new = NULL;
  2709. BlockDriverState *bs = NULL;
  2710. char *filename;
  2711. const char *fmt, *cache, *src_cache, *out_basefmt, *out_baseimg;
  2712. int c, flags, src_flags, ret;
  2713. bool writethrough, src_writethrough;
  2714. int unsafe = 0;
  2715. bool force_share = false;
  2716. int progress = 0;
  2717. bool quiet = false;
  2718. Error *local_err = NULL;
  2719. bool image_opts = false;
  2720. /* Parse commandline parameters */
  2721. fmt = NULL;
  2722. cache = BDRV_DEFAULT_CACHE;
  2723. src_cache = BDRV_DEFAULT_CACHE;
  2724. out_baseimg = NULL;
  2725. out_basefmt = NULL;
  2726. for(;;) {
  2727. static const struct option long_options[] = {
  2728. {"help", no_argument, 0, 'h'},
  2729. {"object", required_argument, 0, OPTION_OBJECT},
  2730. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  2731. {"force-share", no_argument, 0, 'U'},
  2732. {0, 0, 0, 0}
  2733. };
  2734. c = getopt_long(argc, argv, ":hf:F:b:upt:T:qU",
  2735. long_options, NULL);
  2736. if (c == -1) {
  2737. break;
  2738. }
  2739. switch(c) {
  2740. case ':':
  2741. missing_argument(argv[optind - 1]);
  2742. break;
  2743. case '?':
  2744. unrecognized_option(argv[optind - 1]);
  2745. break;
  2746. case 'h':
  2747. help();
  2748. return 0;
  2749. case 'f':
  2750. fmt = optarg;
  2751. break;
  2752. case 'F':
  2753. out_basefmt = optarg;
  2754. break;
  2755. case 'b':
  2756. out_baseimg = optarg;
  2757. break;
  2758. case 'u':
  2759. unsafe = 1;
  2760. break;
  2761. case 'p':
  2762. progress = 1;
  2763. break;
  2764. case 't':
  2765. cache = optarg;
  2766. break;
  2767. case 'T':
  2768. src_cache = optarg;
  2769. break;
  2770. case 'q':
  2771. quiet = true;
  2772. break;
  2773. case OPTION_OBJECT: {
  2774. QemuOpts *opts;
  2775. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  2776. optarg, true);
  2777. if (!opts) {
  2778. return 1;
  2779. }
  2780. } break;
  2781. case OPTION_IMAGE_OPTS:
  2782. image_opts = true;
  2783. break;
  2784. case 'U':
  2785. force_share = true;
  2786. break;
  2787. }
  2788. }
  2789. if (quiet) {
  2790. progress = 0;
  2791. }
  2792. if (optind != argc - 1) {
  2793. error_exit("Expecting one image file name");
  2794. }
  2795. if (!unsafe && !out_baseimg) {
  2796. error_exit("Must specify backing file (-b) or use unsafe mode (-u)");
  2797. }
  2798. filename = argv[optind++];
  2799. if (qemu_opts_foreach(&qemu_object_opts,
  2800. user_creatable_add_opts_foreach,
  2801. NULL, NULL)) {
  2802. return 1;
  2803. }
  2804. qemu_progress_init(progress, 2.0);
  2805. qemu_progress_print(0, 100);
  2806. flags = BDRV_O_RDWR | (unsafe ? BDRV_O_NO_BACKING : 0);
  2807. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  2808. if (ret < 0) {
  2809. error_report("Invalid cache option: %s", cache);
  2810. goto out;
  2811. }
  2812. src_flags = 0;
  2813. ret = bdrv_parse_cache_mode(src_cache, &src_flags, &src_writethrough);
  2814. if (ret < 0) {
  2815. error_report("Invalid source cache option: %s", src_cache);
  2816. goto out;
  2817. }
  2818. /* The source files are opened read-only, don't care about WCE */
  2819. assert((src_flags & BDRV_O_RDWR) == 0);
  2820. (void) src_writethrough;
  2821. /*
  2822. * Open the images.
  2823. *
  2824. * Ignore the old backing file for unsafe rebase in case we want to correct
  2825. * the reference to a renamed or moved backing file.
  2826. */
  2827. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  2828. false);
  2829. if (!blk) {
  2830. ret = -1;
  2831. goto out;
  2832. }
  2833. bs = blk_bs(blk);
  2834. if (out_basefmt != NULL) {
  2835. if (bdrv_find_format(out_basefmt) == NULL) {
  2836. error_report("Invalid format name: '%s'", out_basefmt);
  2837. ret = -1;
  2838. goto out;
  2839. }
  2840. }
  2841. /* For safe rebasing we need to compare old and new backing file */
  2842. if (!unsafe) {
  2843. char backing_name[PATH_MAX];
  2844. QDict *options = NULL;
  2845. if (bs->backing_format[0] != '\0') {
  2846. options = qdict_new();
  2847. qdict_put_str(options, "driver", bs->backing_format);
  2848. }
  2849. if (force_share) {
  2850. if (!options) {
  2851. options = qdict_new();
  2852. }
  2853. qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
  2854. }
  2855. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  2856. blk_old_backing = blk_new_open(backing_name, NULL,
  2857. options, src_flags, &local_err);
  2858. if (!blk_old_backing) {
  2859. error_reportf_err(local_err,
  2860. "Could not open old backing file '%s': ",
  2861. backing_name);
  2862. ret = -1;
  2863. goto out;
  2864. }
  2865. if (out_baseimg[0]) {
  2866. const char *overlay_filename;
  2867. char *out_real_path;
  2868. options = qdict_new();
  2869. if (out_basefmt) {
  2870. qdict_put_str(options, "driver", out_basefmt);
  2871. }
  2872. if (force_share) {
  2873. qdict_put_bool(options, BDRV_OPT_FORCE_SHARE, true);
  2874. }
  2875. overlay_filename = bs->exact_filename[0] ? bs->exact_filename
  2876. : bs->filename;
  2877. out_real_path = g_malloc(PATH_MAX);
  2878. bdrv_get_full_backing_filename_from_filename(overlay_filename,
  2879. out_baseimg,
  2880. out_real_path,
  2881. PATH_MAX,
  2882. &local_err);
  2883. if (local_err) {
  2884. error_reportf_err(local_err,
  2885. "Could not resolve backing filename: ");
  2886. ret = -1;
  2887. g_free(out_real_path);
  2888. goto out;
  2889. }
  2890. blk_new_backing = blk_new_open(out_real_path, NULL,
  2891. options, src_flags, &local_err);
  2892. g_free(out_real_path);
  2893. if (!blk_new_backing) {
  2894. error_reportf_err(local_err,
  2895. "Could not open new backing file '%s': ",
  2896. out_baseimg);
  2897. ret = -1;
  2898. goto out;
  2899. }
  2900. }
  2901. }
  2902. /*
  2903. * Check each unallocated cluster in the COW file. If it is unallocated,
  2904. * accesses go to the backing file. We must therefore compare this cluster
  2905. * in the old and new backing file, and if they differ we need to copy it
  2906. * from the old backing file into the COW file.
  2907. *
  2908. * If qemu-img crashes during this step, no harm is done. The content of
  2909. * the image is the same as the original one at any time.
  2910. */
  2911. if (!unsafe) {
  2912. int64_t size;
  2913. int64_t old_backing_size;
  2914. int64_t new_backing_size = 0;
  2915. uint64_t offset;
  2916. int64_t n;
  2917. float local_progress = 0;
  2918. buf_old = blk_blockalign(blk, IO_BUF_SIZE);
  2919. buf_new = blk_blockalign(blk, IO_BUF_SIZE);
  2920. size = blk_getlength(blk);
  2921. if (size < 0) {
  2922. error_report("Could not get size of '%s': %s",
  2923. filename, strerror(-size));
  2924. ret = -1;
  2925. goto out;
  2926. }
  2927. old_backing_size = blk_getlength(blk_old_backing);
  2928. if (old_backing_size < 0) {
  2929. char backing_name[PATH_MAX];
  2930. bdrv_get_backing_filename(bs, backing_name, sizeof(backing_name));
  2931. error_report("Could not get size of '%s': %s",
  2932. backing_name, strerror(-old_backing_size));
  2933. ret = -1;
  2934. goto out;
  2935. }
  2936. if (blk_new_backing) {
  2937. new_backing_size = blk_getlength(blk_new_backing);
  2938. if (new_backing_size < 0) {
  2939. error_report("Could not get size of '%s': %s",
  2940. out_baseimg, strerror(-new_backing_size));
  2941. ret = -1;
  2942. goto out;
  2943. }
  2944. }
  2945. if (size != 0) {
  2946. local_progress = (float)100 / (size / MIN(size, IO_BUF_SIZE));
  2947. }
  2948. for (offset = 0; offset < size; offset += n) {
  2949. /* How many bytes can we handle with the next read? */
  2950. n = MIN(IO_BUF_SIZE, size - offset);
  2951. /* If the cluster is allocated, we don't need to take action */
  2952. ret = bdrv_is_allocated(bs, offset, n, &n);
  2953. if (ret < 0) {
  2954. error_report("error while reading image metadata: %s",
  2955. strerror(-ret));
  2956. goto out;
  2957. }
  2958. if (ret) {
  2959. continue;
  2960. }
  2961. /*
  2962. * Read old and new backing file and take into consideration that
  2963. * backing files may be smaller than the COW image.
  2964. */
  2965. if (offset >= old_backing_size) {
  2966. memset(buf_old, 0, n);
  2967. } else {
  2968. if (offset + n > old_backing_size) {
  2969. n = old_backing_size - offset;
  2970. }
  2971. ret = blk_pread(blk_old_backing, offset, buf_old, n);
  2972. if (ret < 0) {
  2973. error_report("error while reading from old backing file");
  2974. goto out;
  2975. }
  2976. }
  2977. if (offset >= new_backing_size || !blk_new_backing) {
  2978. memset(buf_new, 0, n);
  2979. } else {
  2980. if (offset + n > new_backing_size) {
  2981. n = new_backing_size - offset;
  2982. }
  2983. ret = blk_pread(blk_new_backing, offset, buf_new, n);
  2984. if (ret < 0) {
  2985. error_report("error while reading from new backing file");
  2986. goto out;
  2987. }
  2988. }
  2989. /* If they differ, we need to write to the COW file */
  2990. uint64_t written = 0;
  2991. while (written < n) {
  2992. int64_t pnum;
  2993. if (compare_buffers(buf_old + written, buf_new + written,
  2994. n - written, &pnum))
  2995. {
  2996. ret = blk_pwrite(blk, offset + written,
  2997. buf_old + written, pnum, 0);
  2998. if (ret < 0) {
  2999. error_report("Error while writing to COW image: %s",
  3000. strerror(-ret));
  3001. goto out;
  3002. }
  3003. }
  3004. written += pnum;
  3005. }
  3006. qemu_progress_print(local_progress, 100);
  3007. }
  3008. }
  3009. /*
  3010. * Change the backing file. All clusters that are different from the old
  3011. * backing file are overwritten in the COW file now, so the visible content
  3012. * doesn't change when we switch the backing file.
  3013. */
  3014. if (out_baseimg && *out_baseimg) {
  3015. ret = bdrv_change_backing_file(bs, out_baseimg, out_basefmt);
  3016. } else {
  3017. ret = bdrv_change_backing_file(bs, NULL, NULL);
  3018. }
  3019. if (ret == -ENOSPC) {
  3020. error_report("Could not change the backing file to '%s': No "
  3021. "space left in the file header", out_baseimg);
  3022. } else if (ret < 0) {
  3023. error_report("Could not change the backing file to '%s': %s",
  3024. out_baseimg, strerror(-ret));
  3025. }
  3026. qemu_progress_print(100, 0);
  3027. /*
  3028. * TODO At this point it is possible to check if any clusters that are
  3029. * allocated in the COW file are the same in the backing file. If so, they
  3030. * could be dropped from the COW file. Don't do this before switching the
  3031. * backing file, in case of a crash this would lead to corruption.
  3032. */
  3033. out:
  3034. qemu_progress_end();
  3035. /* Cleanup */
  3036. if (!unsafe) {
  3037. blk_unref(blk_old_backing);
  3038. blk_unref(blk_new_backing);
  3039. }
  3040. qemu_vfree(buf_old);
  3041. qemu_vfree(buf_new);
  3042. blk_unref(blk);
  3043. if (ret) {
  3044. return 1;
  3045. }
  3046. return 0;
  3047. }
  3048. static int img_resize(int argc, char **argv)
  3049. {
  3050. Error *err = NULL;
  3051. int c, ret, relative;
  3052. const char *filename, *fmt, *size;
  3053. int64_t n, total_size, current_size;
  3054. bool quiet = false;
  3055. BlockBackend *blk = NULL;
  3056. PreallocMode prealloc = PREALLOC_MODE_OFF;
  3057. QemuOpts *param;
  3058. static QemuOptsList resize_options = {
  3059. .name = "resize_options",
  3060. .head = QTAILQ_HEAD_INITIALIZER(resize_options.head),
  3061. .desc = {
  3062. {
  3063. .name = BLOCK_OPT_SIZE,
  3064. .type = QEMU_OPT_SIZE,
  3065. .help = "Virtual disk size"
  3066. }, {
  3067. /* end of list */
  3068. }
  3069. },
  3070. };
  3071. bool image_opts = false;
  3072. bool shrink = false;
  3073. /* Remove size from argv manually so that negative numbers are not treated
  3074. * as options by getopt. */
  3075. if (argc < 3) {
  3076. error_exit("Not enough arguments");
  3077. return 1;
  3078. }
  3079. size = argv[--argc];
  3080. /* Parse getopt arguments */
  3081. fmt = NULL;
  3082. for(;;) {
  3083. static const struct option long_options[] = {
  3084. {"help", no_argument, 0, 'h'},
  3085. {"object", required_argument, 0, OPTION_OBJECT},
  3086. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3087. {"preallocation", required_argument, 0, OPTION_PREALLOCATION},
  3088. {"shrink", no_argument, 0, OPTION_SHRINK},
  3089. {0, 0, 0, 0}
  3090. };
  3091. c = getopt_long(argc, argv, ":f:hq",
  3092. long_options, NULL);
  3093. if (c == -1) {
  3094. break;
  3095. }
  3096. switch(c) {
  3097. case ':':
  3098. missing_argument(argv[optind - 1]);
  3099. break;
  3100. case '?':
  3101. unrecognized_option(argv[optind - 1]);
  3102. break;
  3103. case 'h':
  3104. help();
  3105. break;
  3106. case 'f':
  3107. fmt = optarg;
  3108. break;
  3109. case 'q':
  3110. quiet = true;
  3111. break;
  3112. case OPTION_OBJECT: {
  3113. QemuOpts *opts;
  3114. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  3115. optarg, true);
  3116. if (!opts) {
  3117. return 1;
  3118. }
  3119. } break;
  3120. case OPTION_IMAGE_OPTS:
  3121. image_opts = true;
  3122. break;
  3123. case OPTION_PREALLOCATION:
  3124. prealloc = qapi_enum_parse(&PreallocMode_lookup, optarg,
  3125. PREALLOC_MODE__MAX, NULL);
  3126. if (prealloc == PREALLOC_MODE__MAX) {
  3127. error_report("Invalid preallocation mode '%s'", optarg);
  3128. return 1;
  3129. }
  3130. break;
  3131. case OPTION_SHRINK:
  3132. shrink = true;
  3133. break;
  3134. }
  3135. }
  3136. if (optind != argc - 1) {
  3137. error_exit("Expecting one image file name");
  3138. }
  3139. filename = argv[optind++];
  3140. if (qemu_opts_foreach(&qemu_object_opts,
  3141. user_creatable_add_opts_foreach,
  3142. NULL, NULL)) {
  3143. return 1;
  3144. }
  3145. /* Choose grow, shrink, or absolute resize mode */
  3146. switch (size[0]) {
  3147. case '+':
  3148. relative = 1;
  3149. size++;
  3150. break;
  3151. case '-':
  3152. relative = -1;
  3153. size++;
  3154. break;
  3155. default:
  3156. relative = 0;
  3157. break;
  3158. }
  3159. /* Parse size */
  3160. param = qemu_opts_create(&resize_options, NULL, 0, &error_abort);
  3161. qemu_opt_set(param, BLOCK_OPT_SIZE, size, &err);
  3162. if (err) {
  3163. error_report_err(err);
  3164. ret = -1;
  3165. qemu_opts_del(param);
  3166. goto out;
  3167. }
  3168. n = qemu_opt_get_size(param, BLOCK_OPT_SIZE, 0);
  3169. qemu_opts_del(param);
  3170. blk = img_open(image_opts, filename, fmt,
  3171. BDRV_O_RDWR | BDRV_O_RESIZE, false, quiet,
  3172. false);
  3173. if (!blk) {
  3174. ret = -1;
  3175. goto out;
  3176. }
  3177. current_size = blk_getlength(blk);
  3178. if (current_size < 0) {
  3179. error_report("Failed to inquire current image length: %s",
  3180. strerror(-current_size));
  3181. ret = -1;
  3182. goto out;
  3183. }
  3184. if (relative) {
  3185. total_size = current_size + n * relative;
  3186. } else {
  3187. total_size = n;
  3188. }
  3189. if (total_size <= 0) {
  3190. error_report("New image size must be positive");
  3191. ret = -1;
  3192. goto out;
  3193. }
  3194. if (total_size <= current_size && prealloc != PREALLOC_MODE_OFF) {
  3195. error_report("Preallocation can only be used for growing images");
  3196. ret = -1;
  3197. goto out;
  3198. }
  3199. if (total_size < current_size && !shrink) {
  3200. warn_report("Shrinking an image will delete all data beyond the "
  3201. "shrunken image's end. Before performing such an "
  3202. "operation, make sure there is no important data there.");
  3203. if (g_strcmp0(bdrv_get_format_name(blk_bs(blk)), "raw") != 0) {
  3204. error_report(
  3205. "Use the --shrink option to perform a shrink operation.");
  3206. ret = -1;
  3207. goto out;
  3208. } else {
  3209. warn_report("Using the --shrink option will suppress this message. "
  3210. "Note that future versions of qemu-img may refuse to "
  3211. "shrink images without this option.");
  3212. }
  3213. }
  3214. ret = blk_truncate(blk, total_size, prealloc, &err);
  3215. if (!ret) {
  3216. qprintf(quiet, "Image resized.\n");
  3217. } else {
  3218. error_report_err(err);
  3219. }
  3220. out:
  3221. blk_unref(blk);
  3222. if (ret) {
  3223. return 1;
  3224. }
  3225. return 0;
  3226. }
  3227. static void amend_status_cb(BlockDriverState *bs,
  3228. int64_t offset, int64_t total_work_size,
  3229. void *opaque)
  3230. {
  3231. qemu_progress_print(100.f * offset / total_work_size, 0);
  3232. }
  3233. static int img_amend(int argc, char **argv)
  3234. {
  3235. Error *err = NULL;
  3236. int c, ret = 0;
  3237. char *options = NULL;
  3238. QemuOptsList *create_opts = NULL;
  3239. QemuOpts *opts = NULL;
  3240. const char *fmt = NULL, *filename, *cache;
  3241. int flags;
  3242. bool writethrough;
  3243. bool quiet = false, progress = false;
  3244. BlockBackend *blk = NULL;
  3245. BlockDriverState *bs = NULL;
  3246. bool image_opts = false;
  3247. cache = BDRV_DEFAULT_CACHE;
  3248. for (;;) {
  3249. static const struct option long_options[] = {
  3250. {"help", no_argument, 0, 'h'},
  3251. {"object", required_argument, 0, OPTION_OBJECT},
  3252. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3253. {0, 0, 0, 0}
  3254. };
  3255. c = getopt_long(argc, argv, ":ho:f:t:pq",
  3256. long_options, NULL);
  3257. if (c == -1) {
  3258. break;
  3259. }
  3260. switch (c) {
  3261. case ':':
  3262. missing_argument(argv[optind - 1]);
  3263. break;
  3264. case '?':
  3265. unrecognized_option(argv[optind - 1]);
  3266. break;
  3267. case 'h':
  3268. help();
  3269. break;
  3270. case 'o':
  3271. if (!is_valid_option_list(optarg)) {
  3272. error_report("Invalid option list: %s", optarg);
  3273. ret = -1;
  3274. goto out_no_progress;
  3275. }
  3276. if (!options) {
  3277. options = g_strdup(optarg);
  3278. } else {
  3279. char *old_options = options;
  3280. options = g_strdup_printf("%s,%s", options, optarg);
  3281. g_free(old_options);
  3282. }
  3283. break;
  3284. case 'f':
  3285. fmt = optarg;
  3286. break;
  3287. case 't':
  3288. cache = optarg;
  3289. break;
  3290. case 'p':
  3291. progress = true;
  3292. break;
  3293. case 'q':
  3294. quiet = true;
  3295. break;
  3296. case OPTION_OBJECT:
  3297. opts = qemu_opts_parse_noisily(&qemu_object_opts,
  3298. optarg, true);
  3299. if (!opts) {
  3300. ret = -1;
  3301. goto out_no_progress;
  3302. }
  3303. break;
  3304. case OPTION_IMAGE_OPTS:
  3305. image_opts = true;
  3306. break;
  3307. }
  3308. }
  3309. if (!options) {
  3310. error_exit("Must specify options (-o)");
  3311. }
  3312. if (qemu_opts_foreach(&qemu_object_opts,
  3313. user_creatable_add_opts_foreach,
  3314. NULL, NULL)) {
  3315. ret = -1;
  3316. goto out_no_progress;
  3317. }
  3318. if (quiet) {
  3319. progress = false;
  3320. }
  3321. qemu_progress_init(progress, 1.0);
  3322. filename = (optind == argc - 1) ? argv[argc - 1] : NULL;
  3323. if (fmt && has_help_option(options)) {
  3324. /* If a format is explicitly specified (and possibly no filename is
  3325. * given), print option help here */
  3326. ret = print_block_option_help(filename, fmt);
  3327. goto out;
  3328. }
  3329. if (optind != argc - 1) {
  3330. error_report("Expecting one image file name");
  3331. ret = -1;
  3332. goto out;
  3333. }
  3334. flags = BDRV_O_RDWR;
  3335. ret = bdrv_parse_cache_mode(cache, &flags, &writethrough);
  3336. if (ret < 0) {
  3337. error_report("Invalid cache option: %s", cache);
  3338. goto out;
  3339. }
  3340. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  3341. false);
  3342. if (!blk) {
  3343. ret = -1;
  3344. goto out;
  3345. }
  3346. bs = blk_bs(blk);
  3347. fmt = bs->drv->format_name;
  3348. if (has_help_option(options)) {
  3349. /* If the format was auto-detected, print option help here */
  3350. ret = print_block_option_help(filename, fmt);
  3351. goto out;
  3352. }
  3353. if (!bs->drv->create_opts) {
  3354. error_report("Format driver '%s' does not support any options to amend",
  3355. fmt);
  3356. ret = -1;
  3357. goto out;
  3358. }
  3359. create_opts = qemu_opts_append(create_opts, bs->drv->create_opts);
  3360. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  3361. qemu_opts_do_parse(opts, options, NULL, &err);
  3362. if (err) {
  3363. error_report_err(err);
  3364. ret = -1;
  3365. goto out;
  3366. }
  3367. /* In case the driver does not call amend_status_cb() */
  3368. qemu_progress_print(0.f, 0);
  3369. ret = bdrv_amend_options(bs, opts, &amend_status_cb, NULL);
  3370. qemu_progress_print(100.f, 0);
  3371. if (ret < 0) {
  3372. error_report("Error while amending options: %s", strerror(-ret));
  3373. goto out;
  3374. }
  3375. out:
  3376. qemu_progress_end();
  3377. out_no_progress:
  3378. blk_unref(blk);
  3379. qemu_opts_del(opts);
  3380. qemu_opts_free(create_opts);
  3381. g_free(options);
  3382. if (ret) {
  3383. return 1;
  3384. }
  3385. return 0;
  3386. }
  3387. typedef struct BenchData {
  3388. BlockBackend *blk;
  3389. uint64_t image_size;
  3390. bool write;
  3391. int bufsize;
  3392. int step;
  3393. int nrreq;
  3394. int n;
  3395. int flush_interval;
  3396. bool drain_on_flush;
  3397. uint8_t *buf;
  3398. QEMUIOVector *qiov;
  3399. int in_flight;
  3400. bool in_flush;
  3401. uint64_t offset;
  3402. } BenchData;
  3403. static void bench_undrained_flush_cb(void *opaque, int ret)
  3404. {
  3405. if (ret < 0) {
  3406. error_report("Failed flush request: %s", strerror(-ret));
  3407. exit(EXIT_FAILURE);
  3408. }
  3409. }
  3410. static void bench_cb(void *opaque, int ret)
  3411. {
  3412. BenchData *b = opaque;
  3413. BlockAIOCB *acb;
  3414. if (ret < 0) {
  3415. error_report("Failed request: %s", strerror(-ret));
  3416. exit(EXIT_FAILURE);
  3417. }
  3418. if (b->in_flush) {
  3419. /* Just finished a flush with drained queue: Start next requests */
  3420. assert(b->in_flight == 0);
  3421. b->in_flush = false;
  3422. } else if (b->in_flight > 0) {
  3423. int remaining = b->n - b->in_flight;
  3424. b->n--;
  3425. b->in_flight--;
  3426. /* Time for flush? Drain queue if requested, then flush */
  3427. if (b->flush_interval && remaining % b->flush_interval == 0) {
  3428. if (!b->in_flight || !b->drain_on_flush) {
  3429. BlockCompletionFunc *cb;
  3430. if (b->drain_on_flush) {
  3431. b->in_flush = true;
  3432. cb = bench_cb;
  3433. } else {
  3434. cb = bench_undrained_flush_cb;
  3435. }
  3436. acb = blk_aio_flush(b->blk, cb, b);
  3437. if (!acb) {
  3438. error_report("Failed to issue flush request");
  3439. exit(EXIT_FAILURE);
  3440. }
  3441. }
  3442. if (b->drain_on_flush) {
  3443. return;
  3444. }
  3445. }
  3446. }
  3447. while (b->n > b->in_flight && b->in_flight < b->nrreq) {
  3448. int64_t offset = b->offset;
  3449. /* blk_aio_* might look for completed I/Os and kick bench_cb
  3450. * again, so make sure this operation is counted by in_flight
  3451. * and b->offset is ready for the next submission.
  3452. */
  3453. b->in_flight++;
  3454. b->offset += b->step;
  3455. b->offset %= b->image_size;
  3456. if (b->write) {
  3457. acb = blk_aio_pwritev(b->blk, offset, b->qiov, 0, bench_cb, b);
  3458. } else {
  3459. acb = blk_aio_preadv(b->blk, offset, b->qiov, 0, bench_cb, b);
  3460. }
  3461. if (!acb) {
  3462. error_report("Failed to issue request");
  3463. exit(EXIT_FAILURE);
  3464. }
  3465. }
  3466. }
  3467. static int img_bench(int argc, char **argv)
  3468. {
  3469. int c, ret = 0;
  3470. const char *fmt = NULL, *filename;
  3471. bool quiet = false;
  3472. bool image_opts = false;
  3473. bool is_write = false;
  3474. int count = 75000;
  3475. int depth = 64;
  3476. int64_t offset = 0;
  3477. size_t bufsize = 4096;
  3478. int pattern = 0;
  3479. size_t step = 0;
  3480. int flush_interval = 0;
  3481. bool drain_on_flush = true;
  3482. int64_t image_size;
  3483. BlockBackend *blk = NULL;
  3484. BenchData data = {};
  3485. int flags = 0;
  3486. bool writethrough = false;
  3487. struct timeval t1, t2;
  3488. int i;
  3489. bool force_share = false;
  3490. for (;;) {
  3491. static const struct option long_options[] = {
  3492. {"help", no_argument, 0, 'h'},
  3493. {"flush-interval", required_argument, 0, OPTION_FLUSH_INTERVAL},
  3494. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3495. {"pattern", required_argument, 0, OPTION_PATTERN},
  3496. {"no-drain", no_argument, 0, OPTION_NO_DRAIN},
  3497. {"force-share", no_argument, 0, 'U'},
  3498. {0, 0, 0, 0}
  3499. };
  3500. c = getopt_long(argc, argv, ":hc:d:f:no:qs:S:t:wU", long_options, NULL);
  3501. if (c == -1) {
  3502. break;
  3503. }
  3504. switch (c) {
  3505. case ':':
  3506. missing_argument(argv[optind - 1]);
  3507. break;
  3508. case '?':
  3509. unrecognized_option(argv[optind - 1]);
  3510. break;
  3511. case 'h':
  3512. help();
  3513. break;
  3514. case 'c':
  3515. {
  3516. unsigned long res;
  3517. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
  3518. error_report("Invalid request count specified");
  3519. return 1;
  3520. }
  3521. count = res;
  3522. break;
  3523. }
  3524. case 'd':
  3525. {
  3526. unsigned long res;
  3527. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
  3528. error_report("Invalid queue depth specified");
  3529. return 1;
  3530. }
  3531. depth = res;
  3532. break;
  3533. }
  3534. case 'f':
  3535. fmt = optarg;
  3536. break;
  3537. case 'n':
  3538. flags |= BDRV_O_NATIVE_AIO;
  3539. break;
  3540. case 'o':
  3541. {
  3542. offset = cvtnum(optarg);
  3543. if (offset < 0) {
  3544. error_report("Invalid offset specified");
  3545. return 1;
  3546. }
  3547. break;
  3548. }
  3549. break;
  3550. case 'q':
  3551. quiet = true;
  3552. break;
  3553. case 's':
  3554. {
  3555. int64_t sval;
  3556. sval = cvtnum(optarg);
  3557. if (sval < 0 || sval > INT_MAX) {
  3558. error_report("Invalid buffer size specified");
  3559. return 1;
  3560. }
  3561. bufsize = sval;
  3562. break;
  3563. }
  3564. case 'S':
  3565. {
  3566. int64_t sval;
  3567. sval = cvtnum(optarg);
  3568. if (sval < 0 || sval > INT_MAX) {
  3569. error_report("Invalid step size specified");
  3570. return 1;
  3571. }
  3572. step = sval;
  3573. break;
  3574. }
  3575. case 't':
  3576. ret = bdrv_parse_cache_mode(optarg, &flags, &writethrough);
  3577. if (ret < 0) {
  3578. error_report("Invalid cache mode");
  3579. ret = -1;
  3580. goto out;
  3581. }
  3582. break;
  3583. case 'w':
  3584. flags |= BDRV_O_RDWR;
  3585. is_write = true;
  3586. break;
  3587. case 'U':
  3588. force_share = true;
  3589. break;
  3590. case OPTION_PATTERN:
  3591. {
  3592. unsigned long res;
  3593. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > 0xff) {
  3594. error_report("Invalid pattern byte specified");
  3595. return 1;
  3596. }
  3597. pattern = res;
  3598. break;
  3599. }
  3600. case OPTION_FLUSH_INTERVAL:
  3601. {
  3602. unsigned long res;
  3603. if (qemu_strtoul(optarg, NULL, 0, &res) < 0 || res > INT_MAX) {
  3604. error_report("Invalid flush interval specified");
  3605. return 1;
  3606. }
  3607. flush_interval = res;
  3608. break;
  3609. }
  3610. case OPTION_NO_DRAIN:
  3611. drain_on_flush = false;
  3612. break;
  3613. case OPTION_IMAGE_OPTS:
  3614. image_opts = true;
  3615. break;
  3616. }
  3617. }
  3618. if (optind != argc - 1) {
  3619. error_exit("Expecting one image file name");
  3620. }
  3621. filename = argv[argc - 1];
  3622. if (!is_write && flush_interval) {
  3623. error_report("--flush-interval is only available in write tests");
  3624. ret = -1;
  3625. goto out;
  3626. }
  3627. if (flush_interval && flush_interval < depth) {
  3628. error_report("Flush interval can't be smaller than depth");
  3629. ret = -1;
  3630. goto out;
  3631. }
  3632. blk = img_open(image_opts, filename, fmt, flags, writethrough, quiet,
  3633. force_share);
  3634. if (!blk) {
  3635. ret = -1;
  3636. goto out;
  3637. }
  3638. image_size = blk_getlength(blk);
  3639. if (image_size < 0) {
  3640. ret = image_size;
  3641. goto out;
  3642. }
  3643. data = (BenchData) {
  3644. .blk = blk,
  3645. .image_size = image_size,
  3646. .bufsize = bufsize,
  3647. .step = step ?: bufsize,
  3648. .nrreq = depth,
  3649. .n = count,
  3650. .offset = offset,
  3651. .write = is_write,
  3652. .flush_interval = flush_interval,
  3653. .drain_on_flush = drain_on_flush,
  3654. };
  3655. printf("Sending %d %s requests, %d bytes each, %d in parallel "
  3656. "(starting at offset %" PRId64 ", step size %d)\n",
  3657. data.n, data.write ? "write" : "read", data.bufsize, data.nrreq,
  3658. data.offset, data.step);
  3659. if (flush_interval) {
  3660. printf("Sending flush every %d requests\n", flush_interval);
  3661. }
  3662. data.buf = blk_blockalign(blk, data.nrreq * data.bufsize);
  3663. memset(data.buf, pattern, data.nrreq * data.bufsize);
  3664. data.qiov = g_new(QEMUIOVector, data.nrreq);
  3665. for (i = 0; i < data.nrreq; i++) {
  3666. qemu_iovec_init(&data.qiov[i], 1);
  3667. qemu_iovec_add(&data.qiov[i],
  3668. data.buf + i * data.bufsize, data.bufsize);
  3669. }
  3670. gettimeofday(&t1, NULL);
  3671. bench_cb(&data, 0);
  3672. while (data.n > 0) {
  3673. main_loop_wait(false);
  3674. }
  3675. gettimeofday(&t2, NULL);
  3676. printf("Run completed in %3.3f seconds.\n",
  3677. (t2.tv_sec - t1.tv_sec)
  3678. + ((double)(t2.tv_usec - t1.tv_usec) / 1000000));
  3679. out:
  3680. qemu_vfree(data.buf);
  3681. blk_unref(blk);
  3682. if (ret) {
  3683. return 1;
  3684. }
  3685. return 0;
  3686. }
  3687. #define C_BS 01
  3688. #define C_COUNT 02
  3689. #define C_IF 04
  3690. #define C_OF 010
  3691. #define C_SKIP 020
  3692. struct DdInfo {
  3693. unsigned int flags;
  3694. int64_t count;
  3695. };
  3696. struct DdIo {
  3697. int bsz; /* Block size */
  3698. char *filename;
  3699. uint8_t *buf;
  3700. int64_t offset;
  3701. };
  3702. struct DdOpts {
  3703. const char *name;
  3704. int (*f)(const char *, struct DdIo *, struct DdIo *, struct DdInfo *);
  3705. unsigned int flag;
  3706. };
  3707. static int img_dd_bs(const char *arg,
  3708. struct DdIo *in, struct DdIo *out,
  3709. struct DdInfo *dd)
  3710. {
  3711. int64_t res;
  3712. res = cvtnum(arg);
  3713. if (res <= 0 || res > INT_MAX) {
  3714. error_report("invalid number: '%s'", arg);
  3715. return 1;
  3716. }
  3717. in->bsz = out->bsz = res;
  3718. return 0;
  3719. }
  3720. static int img_dd_count(const char *arg,
  3721. struct DdIo *in, struct DdIo *out,
  3722. struct DdInfo *dd)
  3723. {
  3724. dd->count = cvtnum(arg);
  3725. if (dd->count < 0) {
  3726. error_report("invalid number: '%s'", arg);
  3727. return 1;
  3728. }
  3729. return 0;
  3730. }
  3731. static int img_dd_if(const char *arg,
  3732. struct DdIo *in, struct DdIo *out,
  3733. struct DdInfo *dd)
  3734. {
  3735. in->filename = g_strdup(arg);
  3736. return 0;
  3737. }
  3738. static int img_dd_of(const char *arg,
  3739. struct DdIo *in, struct DdIo *out,
  3740. struct DdInfo *dd)
  3741. {
  3742. out->filename = g_strdup(arg);
  3743. return 0;
  3744. }
  3745. static int img_dd_skip(const char *arg,
  3746. struct DdIo *in, struct DdIo *out,
  3747. struct DdInfo *dd)
  3748. {
  3749. in->offset = cvtnum(arg);
  3750. if (in->offset < 0) {
  3751. error_report("invalid number: '%s'", arg);
  3752. return 1;
  3753. }
  3754. return 0;
  3755. }
  3756. static int img_dd(int argc, char **argv)
  3757. {
  3758. int ret = 0;
  3759. char *arg = NULL;
  3760. char *tmp;
  3761. BlockDriver *drv = NULL, *proto_drv = NULL;
  3762. BlockBackend *blk1 = NULL, *blk2 = NULL;
  3763. QemuOpts *opts = NULL;
  3764. QemuOptsList *create_opts = NULL;
  3765. Error *local_err = NULL;
  3766. bool image_opts = false;
  3767. int c, i;
  3768. const char *out_fmt = "raw";
  3769. const char *fmt = NULL;
  3770. int64_t size = 0;
  3771. int64_t block_count = 0, out_pos, in_pos;
  3772. bool force_share = false;
  3773. struct DdInfo dd = {
  3774. .flags = 0,
  3775. .count = 0,
  3776. };
  3777. struct DdIo in = {
  3778. .bsz = 512, /* Block size is by default 512 bytes */
  3779. .filename = NULL,
  3780. .buf = NULL,
  3781. .offset = 0
  3782. };
  3783. struct DdIo out = {
  3784. .bsz = 512,
  3785. .filename = NULL,
  3786. .buf = NULL,
  3787. .offset = 0
  3788. };
  3789. const struct DdOpts options[] = {
  3790. { "bs", img_dd_bs, C_BS },
  3791. { "count", img_dd_count, C_COUNT },
  3792. { "if", img_dd_if, C_IF },
  3793. { "of", img_dd_of, C_OF },
  3794. { "skip", img_dd_skip, C_SKIP },
  3795. { NULL, NULL, 0 }
  3796. };
  3797. const struct option long_options[] = {
  3798. { "help", no_argument, 0, 'h'},
  3799. { "object", required_argument, 0, OPTION_OBJECT},
  3800. { "image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  3801. { "force-share", no_argument, 0, 'U'},
  3802. { 0, 0, 0, 0 }
  3803. };
  3804. while ((c = getopt_long(argc, argv, ":hf:O:U", long_options, NULL))) {
  3805. if (c == EOF) {
  3806. break;
  3807. }
  3808. switch (c) {
  3809. case 'O':
  3810. out_fmt = optarg;
  3811. break;
  3812. case 'f':
  3813. fmt = optarg;
  3814. break;
  3815. case ':':
  3816. missing_argument(argv[optind - 1]);
  3817. break;
  3818. case '?':
  3819. unrecognized_option(argv[optind - 1]);
  3820. break;
  3821. case 'h':
  3822. help();
  3823. break;
  3824. case 'U':
  3825. force_share = true;
  3826. break;
  3827. case OPTION_OBJECT:
  3828. if (!qemu_opts_parse_noisily(&qemu_object_opts, optarg, true)) {
  3829. ret = -1;
  3830. goto out;
  3831. }
  3832. break;
  3833. case OPTION_IMAGE_OPTS:
  3834. image_opts = true;
  3835. break;
  3836. }
  3837. }
  3838. for (i = optind; i < argc; i++) {
  3839. int j;
  3840. arg = g_strdup(argv[i]);
  3841. tmp = strchr(arg, '=');
  3842. if (tmp == NULL) {
  3843. error_report("unrecognized operand %s", arg);
  3844. ret = -1;
  3845. goto out;
  3846. }
  3847. *tmp++ = '\0';
  3848. for (j = 0; options[j].name != NULL; j++) {
  3849. if (!strcmp(arg, options[j].name)) {
  3850. break;
  3851. }
  3852. }
  3853. if (options[j].name == NULL) {
  3854. error_report("unrecognized operand %s", arg);
  3855. ret = -1;
  3856. goto out;
  3857. }
  3858. if (options[j].f(tmp, &in, &out, &dd) != 0) {
  3859. ret = -1;
  3860. goto out;
  3861. }
  3862. dd.flags |= options[j].flag;
  3863. g_free(arg);
  3864. arg = NULL;
  3865. }
  3866. if (!(dd.flags & C_IF && dd.flags & C_OF)) {
  3867. error_report("Must specify both input and output files");
  3868. ret = -1;
  3869. goto out;
  3870. }
  3871. if (qemu_opts_foreach(&qemu_object_opts,
  3872. user_creatable_add_opts_foreach,
  3873. NULL, NULL)) {
  3874. ret = -1;
  3875. goto out;
  3876. }
  3877. blk1 = img_open(image_opts, in.filename, fmt, 0, false, false,
  3878. force_share);
  3879. if (!blk1) {
  3880. ret = -1;
  3881. goto out;
  3882. }
  3883. drv = bdrv_find_format(out_fmt);
  3884. if (!drv) {
  3885. error_report("Unknown file format");
  3886. ret = -1;
  3887. goto out;
  3888. }
  3889. proto_drv = bdrv_find_protocol(out.filename, true, &local_err);
  3890. if (!proto_drv) {
  3891. error_report_err(local_err);
  3892. ret = -1;
  3893. goto out;
  3894. }
  3895. if (!drv->create_opts) {
  3896. error_report("Format driver '%s' does not support image creation",
  3897. drv->format_name);
  3898. ret = -1;
  3899. goto out;
  3900. }
  3901. if (!proto_drv->create_opts) {
  3902. error_report("Protocol driver '%s' does not support image creation",
  3903. proto_drv->format_name);
  3904. ret = -1;
  3905. goto out;
  3906. }
  3907. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  3908. create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
  3909. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  3910. size = blk_getlength(blk1);
  3911. if (size < 0) {
  3912. error_report("Failed to get size for '%s'", in.filename);
  3913. ret = -1;
  3914. goto out;
  3915. }
  3916. if (dd.flags & C_COUNT && dd.count <= INT64_MAX / in.bsz &&
  3917. dd.count * in.bsz < size) {
  3918. size = dd.count * in.bsz;
  3919. }
  3920. /* Overflow means the specified offset is beyond input image's size */
  3921. if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
  3922. size < in.bsz * in.offset)) {
  3923. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, 0, &error_abort);
  3924. } else {
  3925. qemu_opt_set_number(opts, BLOCK_OPT_SIZE,
  3926. size - in.bsz * in.offset, &error_abort);
  3927. }
  3928. ret = bdrv_create(drv, out.filename, opts, &local_err);
  3929. if (ret < 0) {
  3930. error_reportf_err(local_err,
  3931. "%s: error while creating output image: ",
  3932. out.filename);
  3933. ret = -1;
  3934. goto out;
  3935. }
  3936. /* TODO, we can't honour --image-opts for the target,
  3937. * since it needs to be given in a format compatible
  3938. * with the bdrv_create() call above which does not
  3939. * support image-opts style.
  3940. */
  3941. blk2 = img_open_file(out.filename, NULL, out_fmt, BDRV_O_RDWR,
  3942. false, false, false);
  3943. if (!blk2) {
  3944. ret = -1;
  3945. goto out;
  3946. }
  3947. if (dd.flags & C_SKIP && (in.offset > INT64_MAX / in.bsz ||
  3948. size < in.offset * in.bsz)) {
  3949. /* We give a warning if the skip option is bigger than the input
  3950. * size and create an empty output disk image (i.e. like dd(1)).
  3951. */
  3952. error_report("%s: cannot skip to specified offset", in.filename);
  3953. in_pos = size;
  3954. } else {
  3955. in_pos = in.offset * in.bsz;
  3956. }
  3957. in.buf = g_new(uint8_t, in.bsz);
  3958. for (out_pos = 0; in_pos < size; block_count++) {
  3959. int in_ret, out_ret;
  3960. if (in_pos + in.bsz > size) {
  3961. in_ret = blk_pread(blk1, in_pos, in.buf, size - in_pos);
  3962. } else {
  3963. in_ret = blk_pread(blk1, in_pos, in.buf, in.bsz);
  3964. }
  3965. if (in_ret < 0) {
  3966. error_report("error while reading from input image file: %s",
  3967. strerror(-in_ret));
  3968. ret = -1;
  3969. goto out;
  3970. }
  3971. in_pos += in_ret;
  3972. out_ret = blk_pwrite(blk2, out_pos, in.buf, in_ret, 0);
  3973. if (out_ret < 0) {
  3974. error_report("error while writing to output image file: %s",
  3975. strerror(-out_ret));
  3976. ret = -1;
  3977. goto out;
  3978. }
  3979. out_pos += out_ret;
  3980. }
  3981. out:
  3982. g_free(arg);
  3983. qemu_opts_del(opts);
  3984. qemu_opts_free(create_opts);
  3985. blk_unref(blk1);
  3986. blk_unref(blk2);
  3987. g_free(in.filename);
  3988. g_free(out.filename);
  3989. g_free(in.buf);
  3990. g_free(out.buf);
  3991. if (ret) {
  3992. return 1;
  3993. }
  3994. return 0;
  3995. }
  3996. static void dump_json_block_measure_info(BlockMeasureInfo *info)
  3997. {
  3998. QString *str;
  3999. QObject *obj;
  4000. Visitor *v = qobject_output_visitor_new(&obj);
  4001. visit_type_BlockMeasureInfo(v, NULL, &info, &error_abort);
  4002. visit_complete(v, &obj);
  4003. str = qobject_to_json_pretty(obj);
  4004. assert(str != NULL);
  4005. printf("%s\n", qstring_get_str(str));
  4006. qobject_decref(obj);
  4007. visit_free(v);
  4008. QDECREF(str);
  4009. }
  4010. static int img_measure(int argc, char **argv)
  4011. {
  4012. static const struct option long_options[] = {
  4013. {"help", no_argument, 0, 'h'},
  4014. {"image-opts", no_argument, 0, OPTION_IMAGE_OPTS},
  4015. {"object", required_argument, 0, OPTION_OBJECT},
  4016. {"output", required_argument, 0, OPTION_OUTPUT},
  4017. {"size", required_argument, 0, OPTION_SIZE},
  4018. {"force-share", no_argument, 0, 'U'},
  4019. {0, 0, 0, 0}
  4020. };
  4021. OutputFormat output_format = OFORMAT_HUMAN;
  4022. BlockBackend *in_blk = NULL;
  4023. BlockDriver *drv;
  4024. const char *filename = NULL;
  4025. const char *fmt = NULL;
  4026. const char *out_fmt = "raw";
  4027. char *options = NULL;
  4028. char *snapshot_name = NULL;
  4029. bool force_share = false;
  4030. QemuOpts *opts = NULL;
  4031. QemuOpts *object_opts = NULL;
  4032. QemuOpts *sn_opts = NULL;
  4033. QemuOptsList *create_opts = NULL;
  4034. bool image_opts = false;
  4035. uint64_t img_size = UINT64_MAX;
  4036. BlockMeasureInfo *info = NULL;
  4037. Error *local_err = NULL;
  4038. int ret = 1;
  4039. int c;
  4040. while ((c = getopt_long(argc, argv, "hf:O:o:l:U",
  4041. long_options, NULL)) != -1) {
  4042. switch (c) {
  4043. case '?':
  4044. case 'h':
  4045. help();
  4046. break;
  4047. case 'f':
  4048. fmt = optarg;
  4049. break;
  4050. case 'O':
  4051. out_fmt = optarg;
  4052. break;
  4053. case 'o':
  4054. if (!is_valid_option_list(optarg)) {
  4055. error_report("Invalid option list: %s", optarg);
  4056. goto out;
  4057. }
  4058. if (!options) {
  4059. options = g_strdup(optarg);
  4060. } else {
  4061. char *old_options = options;
  4062. options = g_strdup_printf("%s,%s", options, optarg);
  4063. g_free(old_options);
  4064. }
  4065. break;
  4066. case 'l':
  4067. if (strstart(optarg, SNAPSHOT_OPT_BASE, NULL)) {
  4068. sn_opts = qemu_opts_parse_noisily(&internal_snapshot_opts,
  4069. optarg, false);
  4070. if (!sn_opts) {
  4071. error_report("Failed in parsing snapshot param '%s'",
  4072. optarg);
  4073. goto out;
  4074. }
  4075. } else {
  4076. snapshot_name = optarg;
  4077. }
  4078. break;
  4079. case 'U':
  4080. force_share = true;
  4081. break;
  4082. case OPTION_OBJECT:
  4083. object_opts = qemu_opts_parse_noisily(&qemu_object_opts,
  4084. optarg, true);
  4085. if (!object_opts) {
  4086. goto out;
  4087. }
  4088. break;
  4089. case OPTION_IMAGE_OPTS:
  4090. image_opts = true;
  4091. break;
  4092. case OPTION_OUTPUT:
  4093. if (!strcmp(optarg, "json")) {
  4094. output_format = OFORMAT_JSON;
  4095. } else if (!strcmp(optarg, "human")) {
  4096. output_format = OFORMAT_HUMAN;
  4097. } else {
  4098. error_report("--output must be used with human or json "
  4099. "as argument.");
  4100. goto out;
  4101. }
  4102. break;
  4103. case OPTION_SIZE:
  4104. {
  4105. int64_t sval;
  4106. sval = cvtnum(optarg);
  4107. if (sval < 0) {
  4108. if (sval == -ERANGE) {
  4109. error_report("Image size must be less than 8 EiB!");
  4110. } else {
  4111. error_report("Invalid image size specified! You may use "
  4112. "k, M, G, T, P or E suffixes for ");
  4113. error_report("kilobytes, megabytes, gigabytes, terabytes, "
  4114. "petabytes and exabytes.");
  4115. }
  4116. goto out;
  4117. }
  4118. img_size = (uint64_t)sval;
  4119. }
  4120. break;
  4121. }
  4122. }
  4123. if (qemu_opts_foreach(&qemu_object_opts,
  4124. user_creatable_add_opts_foreach,
  4125. NULL, NULL)) {
  4126. goto out;
  4127. }
  4128. if (argc - optind > 1) {
  4129. error_report("At most one filename argument is allowed.");
  4130. goto out;
  4131. } else if (argc - optind == 1) {
  4132. filename = argv[optind];
  4133. }
  4134. if (!filename &&
  4135. (object_opts || image_opts || fmt || snapshot_name || sn_opts)) {
  4136. error_report("--object, --image-opts, -f, and -l "
  4137. "require a filename argument.");
  4138. goto out;
  4139. }
  4140. if (filename && img_size != UINT64_MAX) {
  4141. error_report("--size N cannot be used together with a filename.");
  4142. goto out;
  4143. }
  4144. if (!filename && img_size == UINT64_MAX) {
  4145. error_report("Either --size N or one filename must be specified.");
  4146. goto out;
  4147. }
  4148. if (filename) {
  4149. in_blk = img_open(image_opts, filename, fmt, 0,
  4150. false, false, force_share);
  4151. if (!in_blk) {
  4152. goto out;
  4153. }
  4154. if (sn_opts) {
  4155. bdrv_snapshot_load_tmp(blk_bs(in_blk),
  4156. qemu_opt_get(sn_opts, SNAPSHOT_OPT_ID),
  4157. qemu_opt_get(sn_opts, SNAPSHOT_OPT_NAME),
  4158. &local_err);
  4159. } else if (snapshot_name != NULL) {
  4160. bdrv_snapshot_load_tmp_by_id_or_name(blk_bs(in_blk),
  4161. snapshot_name, &local_err);
  4162. }
  4163. if (local_err) {
  4164. error_reportf_err(local_err, "Failed to load snapshot: ");
  4165. goto out;
  4166. }
  4167. }
  4168. drv = bdrv_find_format(out_fmt);
  4169. if (!drv) {
  4170. error_report("Unknown file format '%s'", out_fmt);
  4171. goto out;
  4172. }
  4173. if (!drv->create_opts) {
  4174. error_report("Format driver '%s' does not support image creation",
  4175. drv->format_name);
  4176. goto out;
  4177. }
  4178. create_opts = qemu_opts_append(create_opts, drv->create_opts);
  4179. create_opts = qemu_opts_append(create_opts, bdrv_file.create_opts);
  4180. opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
  4181. if (options) {
  4182. qemu_opts_do_parse(opts, options, NULL, &local_err);
  4183. if (local_err) {
  4184. error_report_err(local_err);
  4185. error_report("Invalid options for file format '%s'", out_fmt);
  4186. goto out;
  4187. }
  4188. }
  4189. if (img_size != UINT64_MAX) {
  4190. qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
  4191. }
  4192. info = bdrv_measure(drv, opts, in_blk ? blk_bs(in_blk) : NULL, &local_err);
  4193. if (local_err) {
  4194. error_report_err(local_err);
  4195. goto out;
  4196. }
  4197. if (output_format == OFORMAT_HUMAN) {
  4198. printf("required size: %" PRIu64 "\n", info->required);
  4199. printf("fully allocated size: %" PRIu64 "\n", info->fully_allocated);
  4200. } else {
  4201. dump_json_block_measure_info(info);
  4202. }
  4203. ret = 0;
  4204. out:
  4205. qapi_free_BlockMeasureInfo(info);
  4206. qemu_opts_del(object_opts);
  4207. qemu_opts_del(opts);
  4208. qemu_opts_del(sn_opts);
  4209. qemu_opts_free(create_opts);
  4210. g_free(options);
  4211. blk_unref(in_blk);
  4212. return ret;
  4213. }
  4214. static const img_cmd_t img_cmds[] = {
  4215. #define DEF(option, callback, arg_string) \
  4216. { option, callback },
  4217. #include "qemu-img-cmds.h"
  4218. #undef DEF
  4219. #undef GEN_DOCS
  4220. { NULL, NULL, },
  4221. };
  4222. int main(int argc, char **argv)
  4223. {
  4224. const img_cmd_t *cmd;
  4225. const char *cmdname;
  4226. Error *local_error = NULL;
  4227. char *trace_file = NULL;
  4228. int c;
  4229. static const struct option long_options[] = {
  4230. {"help", no_argument, 0, 'h'},
  4231. {"version", no_argument, 0, 'V'},
  4232. {"trace", required_argument, NULL, 'T'},
  4233. {0, 0, 0, 0}
  4234. };
  4235. #ifdef CONFIG_POSIX
  4236. signal(SIGPIPE, SIG_IGN);
  4237. #endif
  4238. module_call_init(MODULE_INIT_TRACE);
  4239. error_set_progname(argv[0]);
  4240. qemu_init_exec_dir(argv[0]);
  4241. if (qemu_init_main_loop(&local_error)) {
  4242. error_report_err(local_error);
  4243. exit(EXIT_FAILURE);
  4244. }
  4245. qcrypto_init(&error_fatal);
  4246. module_call_init(MODULE_INIT_QOM);
  4247. bdrv_init();
  4248. if (argc < 2) {
  4249. error_exit("Not enough arguments");
  4250. }
  4251. qemu_add_opts(&qemu_object_opts);
  4252. qemu_add_opts(&qemu_source_opts);
  4253. qemu_add_opts(&qemu_trace_opts);
  4254. while ((c = getopt_long(argc, argv, "+:hVT:", long_options, NULL)) != -1) {
  4255. switch (c) {
  4256. case ':':
  4257. missing_argument(argv[optind - 1]);
  4258. return 0;
  4259. case '?':
  4260. unrecognized_option(argv[optind - 1]);
  4261. return 0;
  4262. case 'h':
  4263. help();
  4264. return 0;
  4265. case 'V':
  4266. printf(QEMU_IMG_VERSION);
  4267. return 0;
  4268. case 'T':
  4269. g_free(trace_file);
  4270. trace_file = trace_opt_parse(optarg);
  4271. break;
  4272. }
  4273. }
  4274. cmdname = argv[optind];
  4275. /* reset getopt_long scanning */
  4276. argc -= optind;
  4277. if (argc < 1) {
  4278. return 0;
  4279. }
  4280. argv += optind;
  4281. optind = 0;
  4282. if (!trace_init_backends()) {
  4283. exit(1);
  4284. }
  4285. trace_init_file(trace_file);
  4286. qemu_set_log(LOG_TRACE);
  4287. /* find the command */
  4288. for (cmd = img_cmds; cmd->name != NULL; cmd++) {
  4289. if (!strcmp(cmdname, cmd->name)) {
  4290. return cmd->handler(argc, argv);
  4291. }
  4292. }
  4293. /* not found */
  4294. error_exit("Command not found: %s", cmdname);
  4295. }