You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

qemu-img.c 149KB

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