qemu-img.c 160 KB

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