qemu-img.c 158 KB

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