qemu-img.c 159 KB

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