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

qemu-img.c 149KB

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