qemu-img.c 160 KB

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