2
0

qemu-img.c 149 KB

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