qemu-img.c 162 KB

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