qemu-img.c 145 KB

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