block.c 153 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500
  1. /*
  2. * QEMU System Emulator block driver
  3. *
  4. * Copyright (c) 2003 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 "config-host.h"
  25. #include "qemu-common.h"
  26. #include "trace.h"
  27. #include "monitor/monitor.h"
  28. #include "block/block_int.h"
  29. #include "block/blockjob.h"
  30. #include "qemu/module.h"
  31. #include "qapi/qmp/qjson.h"
  32. #include "sysemu/sysemu.h"
  33. #include "qemu/notify.h"
  34. #include "block/coroutine.h"
  35. #include "block/qapi.h"
  36. #include "qmp-commands.h"
  37. #include "qemu/timer.h"
  38. #ifdef CONFIG_BSD
  39. #include <sys/types.h>
  40. #include <sys/stat.h>
  41. #include <sys/ioctl.h>
  42. #include <sys/queue.h>
  43. #ifndef __DragonFly__
  44. #include <sys/disk.h>
  45. #endif
  46. #endif
  47. #ifdef _WIN32
  48. #include <windows.h>
  49. #endif
  50. struct BdrvDirtyBitmap {
  51. HBitmap *bitmap;
  52. QLIST_ENTRY(BdrvDirtyBitmap) list;
  53. };
  54. #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
  55. static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
  56. static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
  57. int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
  58. BlockDriverCompletionFunc *cb, void *opaque);
  59. static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
  60. int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
  61. BlockDriverCompletionFunc *cb, void *opaque);
  62. static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
  63. int64_t sector_num, int nb_sectors,
  64. QEMUIOVector *iov);
  65. static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
  66. int64_t sector_num, int nb_sectors,
  67. QEMUIOVector *iov);
  68. static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
  69. int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
  70. BdrvRequestFlags flags);
  71. static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
  72. int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
  73. BdrvRequestFlags flags);
  74. static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
  75. int64_t sector_num,
  76. QEMUIOVector *qiov,
  77. int nb_sectors,
  78. BdrvRequestFlags flags,
  79. BlockDriverCompletionFunc *cb,
  80. void *opaque,
  81. bool is_write);
  82. static void coroutine_fn bdrv_co_do_rw(void *opaque);
  83. static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
  84. int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
  85. static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
  86. QTAILQ_HEAD_INITIALIZER(bdrv_states);
  87. static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
  88. QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
  89. static QLIST_HEAD(, BlockDriver) bdrv_drivers =
  90. QLIST_HEAD_INITIALIZER(bdrv_drivers);
  91. /* If non-zero, use only whitelisted block drivers */
  92. static int use_bdrv_whitelist;
  93. #ifdef _WIN32
  94. static int is_windows_drive_prefix(const char *filename)
  95. {
  96. return (((filename[0] >= 'a' && filename[0] <= 'z') ||
  97. (filename[0] >= 'A' && filename[0] <= 'Z')) &&
  98. filename[1] == ':');
  99. }
  100. int is_windows_drive(const char *filename)
  101. {
  102. if (is_windows_drive_prefix(filename) &&
  103. filename[2] == '\0')
  104. return 1;
  105. if (strstart(filename, "\\\\.\\", NULL) ||
  106. strstart(filename, "//./", NULL))
  107. return 1;
  108. return 0;
  109. }
  110. #endif
  111. /* throttling disk I/O limits */
  112. void bdrv_set_io_limits(BlockDriverState *bs,
  113. ThrottleConfig *cfg)
  114. {
  115. int i;
  116. throttle_config(&bs->throttle_state, cfg);
  117. for (i = 0; i < 2; i++) {
  118. qemu_co_enter_next(&bs->throttled_reqs[i]);
  119. }
  120. }
  121. /* this function drain all the throttled IOs */
  122. static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
  123. {
  124. bool drained = false;
  125. bool enabled = bs->io_limits_enabled;
  126. int i;
  127. bs->io_limits_enabled = false;
  128. for (i = 0; i < 2; i++) {
  129. while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
  130. drained = true;
  131. }
  132. }
  133. bs->io_limits_enabled = enabled;
  134. return drained;
  135. }
  136. void bdrv_io_limits_disable(BlockDriverState *bs)
  137. {
  138. bs->io_limits_enabled = false;
  139. bdrv_start_throttled_reqs(bs);
  140. throttle_destroy(&bs->throttle_state);
  141. }
  142. static void bdrv_throttle_read_timer_cb(void *opaque)
  143. {
  144. BlockDriverState *bs = opaque;
  145. qemu_co_enter_next(&bs->throttled_reqs[0]);
  146. }
  147. static void bdrv_throttle_write_timer_cb(void *opaque)
  148. {
  149. BlockDriverState *bs = opaque;
  150. qemu_co_enter_next(&bs->throttled_reqs[1]);
  151. }
  152. /* should be called before bdrv_set_io_limits if a limit is set */
  153. void bdrv_io_limits_enable(BlockDriverState *bs)
  154. {
  155. assert(!bs->io_limits_enabled);
  156. throttle_init(&bs->throttle_state,
  157. QEMU_CLOCK_VIRTUAL,
  158. bdrv_throttle_read_timer_cb,
  159. bdrv_throttle_write_timer_cb,
  160. bs);
  161. bs->io_limits_enabled = true;
  162. }
  163. /* This function makes an IO wait if needed
  164. *
  165. * @nb_sectors: the number of sectors of the IO
  166. * @is_write: is the IO a write
  167. */
  168. static void bdrv_io_limits_intercept(BlockDriverState *bs,
  169. unsigned int bytes,
  170. bool is_write)
  171. {
  172. /* does this io must wait */
  173. bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
  174. /* if must wait or any request of this type throttled queue the IO */
  175. if (must_wait ||
  176. !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
  177. qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
  178. }
  179. /* the IO will be executed, do the accounting */
  180. throttle_account(&bs->throttle_state, is_write, bytes);
  181. /* if the next request must wait -> do nothing */
  182. if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
  183. return;
  184. }
  185. /* else queue next request for execution */
  186. qemu_co_queue_next(&bs->throttled_reqs[is_write]);
  187. }
  188. size_t bdrv_opt_mem_align(BlockDriverState *bs)
  189. {
  190. if (!bs || !bs->drv) {
  191. /* 4k should be on the safe side */
  192. return 4096;
  193. }
  194. return bs->bl.opt_mem_alignment;
  195. }
  196. /* check if the path starts with "<protocol>:" */
  197. static int path_has_protocol(const char *path)
  198. {
  199. const char *p;
  200. #ifdef _WIN32
  201. if (is_windows_drive(path) ||
  202. is_windows_drive_prefix(path)) {
  203. return 0;
  204. }
  205. p = path + strcspn(path, ":/\\");
  206. #else
  207. p = path + strcspn(path, ":/");
  208. #endif
  209. return *p == ':';
  210. }
  211. int path_is_absolute(const char *path)
  212. {
  213. #ifdef _WIN32
  214. /* specific case for names like: "\\.\d:" */
  215. if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
  216. return 1;
  217. }
  218. return (*path == '/' || *path == '\\');
  219. #else
  220. return (*path == '/');
  221. #endif
  222. }
  223. /* if filename is absolute, just copy it to dest. Otherwise, build a
  224. path to it by considering it is relative to base_path. URL are
  225. supported. */
  226. void path_combine(char *dest, int dest_size,
  227. const char *base_path,
  228. const char *filename)
  229. {
  230. const char *p, *p1;
  231. int len;
  232. if (dest_size <= 0)
  233. return;
  234. if (path_is_absolute(filename)) {
  235. pstrcpy(dest, dest_size, filename);
  236. } else {
  237. p = strchr(base_path, ':');
  238. if (p)
  239. p++;
  240. else
  241. p = base_path;
  242. p1 = strrchr(base_path, '/');
  243. #ifdef _WIN32
  244. {
  245. const char *p2;
  246. p2 = strrchr(base_path, '\\');
  247. if (!p1 || p2 > p1)
  248. p1 = p2;
  249. }
  250. #endif
  251. if (p1)
  252. p1++;
  253. else
  254. p1 = base_path;
  255. if (p1 > p)
  256. p = p1;
  257. len = p - base_path;
  258. if (len > dest_size - 1)
  259. len = dest_size - 1;
  260. memcpy(dest, base_path, len);
  261. dest[len] = '\0';
  262. pstrcat(dest, dest_size, filename);
  263. }
  264. }
  265. void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
  266. {
  267. if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
  268. pstrcpy(dest, sz, bs->backing_file);
  269. } else {
  270. path_combine(dest, sz, bs->filename, bs->backing_file);
  271. }
  272. }
  273. void bdrv_register(BlockDriver *bdrv)
  274. {
  275. /* Block drivers without coroutine functions need emulation */
  276. if (!bdrv->bdrv_co_readv) {
  277. bdrv->bdrv_co_readv = bdrv_co_readv_em;
  278. bdrv->bdrv_co_writev = bdrv_co_writev_em;
  279. /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
  280. * the block driver lacks aio we need to emulate that too.
  281. */
  282. if (!bdrv->bdrv_aio_readv) {
  283. /* add AIO emulation layer */
  284. bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
  285. bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
  286. }
  287. }
  288. QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
  289. }
  290. /* create a new block device (by default it is empty) */
  291. BlockDriverState *bdrv_new(const char *device_name)
  292. {
  293. BlockDriverState *bs;
  294. bs = g_malloc0(sizeof(BlockDriverState));
  295. QLIST_INIT(&bs->dirty_bitmaps);
  296. pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
  297. if (device_name[0] != '\0') {
  298. QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
  299. }
  300. bdrv_iostatus_disable(bs);
  301. notifier_list_init(&bs->close_notifiers);
  302. notifier_with_return_list_init(&bs->before_write_notifiers);
  303. qemu_co_queue_init(&bs->throttled_reqs[0]);
  304. qemu_co_queue_init(&bs->throttled_reqs[1]);
  305. bs->refcnt = 1;
  306. return bs;
  307. }
  308. void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
  309. {
  310. notifier_list_add(&bs->close_notifiers, notify);
  311. }
  312. BlockDriver *bdrv_find_format(const char *format_name)
  313. {
  314. BlockDriver *drv1;
  315. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  316. if (!strcmp(drv1->format_name, format_name)) {
  317. return drv1;
  318. }
  319. }
  320. return NULL;
  321. }
  322. static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
  323. {
  324. static const char *whitelist_rw[] = {
  325. CONFIG_BDRV_RW_WHITELIST
  326. };
  327. static const char *whitelist_ro[] = {
  328. CONFIG_BDRV_RO_WHITELIST
  329. };
  330. const char **p;
  331. if (!whitelist_rw[0] && !whitelist_ro[0]) {
  332. return 1; /* no whitelist, anything goes */
  333. }
  334. for (p = whitelist_rw; *p; p++) {
  335. if (!strcmp(drv->format_name, *p)) {
  336. return 1;
  337. }
  338. }
  339. if (read_only) {
  340. for (p = whitelist_ro; *p; p++) {
  341. if (!strcmp(drv->format_name, *p)) {
  342. return 1;
  343. }
  344. }
  345. }
  346. return 0;
  347. }
  348. BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
  349. bool read_only)
  350. {
  351. BlockDriver *drv = bdrv_find_format(format_name);
  352. return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
  353. }
  354. typedef struct CreateCo {
  355. BlockDriver *drv;
  356. char *filename;
  357. QEMUOptionParameter *options;
  358. int ret;
  359. Error *err;
  360. } CreateCo;
  361. static void coroutine_fn bdrv_create_co_entry(void *opaque)
  362. {
  363. Error *local_err = NULL;
  364. int ret;
  365. CreateCo *cco = opaque;
  366. assert(cco->drv);
  367. ret = cco->drv->bdrv_create(cco->filename, cco->options, &local_err);
  368. if (local_err) {
  369. error_propagate(&cco->err, local_err);
  370. }
  371. cco->ret = ret;
  372. }
  373. int bdrv_create(BlockDriver *drv, const char* filename,
  374. QEMUOptionParameter *options, Error **errp)
  375. {
  376. int ret;
  377. Coroutine *co;
  378. CreateCo cco = {
  379. .drv = drv,
  380. .filename = g_strdup(filename),
  381. .options = options,
  382. .ret = NOT_DONE,
  383. .err = NULL,
  384. };
  385. if (!drv->bdrv_create) {
  386. error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
  387. ret = -ENOTSUP;
  388. goto out;
  389. }
  390. if (qemu_in_coroutine()) {
  391. /* Fast-path if already in coroutine context */
  392. bdrv_create_co_entry(&cco);
  393. } else {
  394. co = qemu_coroutine_create(bdrv_create_co_entry);
  395. qemu_coroutine_enter(co, &cco);
  396. while (cco.ret == NOT_DONE) {
  397. qemu_aio_wait();
  398. }
  399. }
  400. ret = cco.ret;
  401. if (ret < 0) {
  402. if (cco.err) {
  403. error_propagate(errp, cco.err);
  404. } else {
  405. error_setg_errno(errp, -ret, "Could not create image");
  406. }
  407. }
  408. out:
  409. g_free(cco.filename);
  410. return ret;
  411. }
  412. int bdrv_create_file(const char* filename, QEMUOptionParameter *options,
  413. Error **errp)
  414. {
  415. BlockDriver *drv;
  416. Error *local_err = NULL;
  417. int ret;
  418. drv = bdrv_find_protocol(filename, true);
  419. if (drv == NULL) {
  420. error_setg(errp, "Could not find protocol for file '%s'", filename);
  421. return -ENOENT;
  422. }
  423. ret = bdrv_create(drv, filename, options, &local_err);
  424. if (local_err) {
  425. error_propagate(errp, local_err);
  426. }
  427. return ret;
  428. }
  429. int bdrv_refresh_limits(BlockDriverState *bs)
  430. {
  431. BlockDriver *drv = bs->drv;
  432. memset(&bs->bl, 0, sizeof(bs->bl));
  433. if (!drv) {
  434. return 0;
  435. }
  436. /* Take some limits from the children as a default */
  437. if (bs->file) {
  438. bdrv_refresh_limits(bs->file);
  439. bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
  440. bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
  441. } else {
  442. bs->bl.opt_mem_alignment = 512;
  443. }
  444. if (bs->backing_hd) {
  445. bdrv_refresh_limits(bs->backing_hd);
  446. bs->bl.opt_transfer_length =
  447. MAX(bs->bl.opt_transfer_length,
  448. bs->backing_hd->bl.opt_transfer_length);
  449. bs->bl.opt_mem_alignment =
  450. MAX(bs->bl.opt_mem_alignment,
  451. bs->backing_hd->bl.opt_mem_alignment);
  452. }
  453. /* Then let the driver override it */
  454. if (drv->bdrv_refresh_limits) {
  455. return drv->bdrv_refresh_limits(bs);
  456. }
  457. return 0;
  458. }
  459. /*
  460. * Create a uniquely-named empty temporary file.
  461. * Return 0 upon success, otherwise a negative errno value.
  462. */
  463. int get_tmp_filename(char *filename, int size)
  464. {
  465. #ifdef _WIN32
  466. char temp_dir[MAX_PATH];
  467. /* GetTempFileName requires that its output buffer (4th param)
  468. have length MAX_PATH or greater. */
  469. assert(size >= MAX_PATH);
  470. return (GetTempPath(MAX_PATH, temp_dir)
  471. && GetTempFileName(temp_dir, "qem", 0, filename)
  472. ? 0 : -GetLastError());
  473. #else
  474. int fd;
  475. const char *tmpdir;
  476. tmpdir = getenv("TMPDIR");
  477. if (!tmpdir) {
  478. tmpdir = "/var/tmp";
  479. }
  480. if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
  481. return -EOVERFLOW;
  482. }
  483. fd = mkstemp(filename);
  484. if (fd < 0) {
  485. return -errno;
  486. }
  487. if (close(fd) != 0) {
  488. unlink(filename);
  489. return -errno;
  490. }
  491. return 0;
  492. #endif
  493. }
  494. /*
  495. * Detect host devices. By convention, /dev/cdrom[N] is always
  496. * recognized as a host CDROM.
  497. */
  498. static BlockDriver *find_hdev_driver(const char *filename)
  499. {
  500. int score_max = 0, score;
  501. BlockDriver *drv = NULL, *d;
  502. QLIST_FOREACH(d, &bdrv_drivers, list) {
  503. if (d->bdrv_probe_device) {
  504. score = d->bdrv_probe_device(filename);
  505. if (score > score_max) {
  506. score_max = score;
  507. drv = d;
  508. }
  509. }
  510. }
  511. return drv;
  512. }
  513. BlockDriver *bdrv_find_protocol(const char *filename,
  514. bool allow_protocol_prefix)
  515. {
  516. BlockDriver *drv1;
  517. char protocol[128];
  518. int len;
  519. const char *p;
  520. /* TODO Drivers without bdrv_file_open must be specified explicitly */
  521. /*
  522. * XXX(hch): we really should not let host device detection
  523. * override an explicit protocol specification, but moving this
  524. * later breaks access to device names with colons in them.
  525. * Thanks to the brain-dead persistent naming schemes on udev-
  526. * based Linux systems those actually are quite common.
  527. */
  528. drv1 = find_hdev_driver(filename);
  529. if (drv1) {
  530. return drv1;
  531. }
  532. if (!path_has_protocol(filename) || !allow_protocol_prefix) {
  533. return bdrv_find_format("file");
  534. }
  535. p = strchr(filename, ':');
  536. assert(p != NULL);
  537. len = p - filename;
  538. if (len > sizeof(protocol) - 1)
  539. len = sizeof(protocol) - 1;
  540. memcpy(protocol, filename, len);
  541. protocol[len] = '\0';
  542. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  543. if (drv1->protocol_name &&
  544. !strcmp(drv1->protocol_name, protocol)) {
  545. return drv1;
  546. }
  547. }
  548. return NULL;
  549. }
  550. static int find_image_format(BlockDriverState *bs, const char *filename,
  551. BlockDriver **pdrv, Error **errp)
  552. {
  553. int score, score_max;
  554. BlockDriver *drv1, *drv;
  555. uint8_t buf[2048];
  556. int ret = 0;
  557. /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
  558. if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
  559. drv = bdrv_find_format("raw");
  560. if (!drv) {
  561. error_setg(errp, "Could not find raw image format");
  562. ret = -ENOENT;
  563. }
  564. *pdrv = drv;
  565. return ret;
  566. }
  567. ret = bdrv_pread(bs, 0, buf, sizeof(buf));
  568. if (ret < 0) {
  569. error_setg_errno(errp, -ret, "Could not read image for determining its "
  570. "format");
  571. *pdrv = NULL;
  572. return ret;
  573. }
  574. score_max = 0;
  575. drv = NULL;
  576. QLIST_FOREACH(drv1, &bdrv_drivers, list) {
  577. if (drv1->bdrv_probe) {
  578. score = drv1->bdrv_probe(buf, ret, filename);
  579. if (score > score_max) {
  580. score_max = score;
  581. drv = drv1;
  582. }
  583. }
  584. }
  585. if (!drv) {
  586. error_setg(errp, "Could not determine image format: No compatible "
  587. "driver found");
  588. ret = -ENOENT;
  589. }
  590. *pdrv = drv;
  591. return ret;
  592. }
  593. /**
  594. * Set the current 'total_sectors' value
  595. */
  596. static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
  597. {
  598. BlockDriver *drv = bs->drv;
  599. /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
  600. if (bs->sg)
  601. return 0;
  602. /* query actual device if possible, otherwise just trust the hint */
  603. if (drv->bdrv_getlength) {
  604. int64_t length = drv->bdrv_getlength(bs);
  605. if (length < 0) {
  606. return length;
  607. }
  608. hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
  609. }
  610. bs->total_sectors = hint;
  611. return 0;
  612. }
  613. /**
  614. * Set open flags for a given discard mode
  615. *
  616. * Return 0 on success, -1 if the discard mode was invalid.
  617. */
  618. int bdrv_parse_discard_flags(const char *mode, int *flags)
  619. {
  620. *flags &= ~BDRV_O_UNMAP;
  621. if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
  622. /* do nothing */
  623. } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
  624. *flags |= BDRV_O_UNMAP;
  625. } else {
  626. return -1;
  627. }
  628. return 0;
  629. }
  630. /**
  631. * Set open flags for a given cache mode
  632. *
  633. * Return 0 on success, -1 if the cache mode was invalid.
  634. */
  635. int bdrv_parse_cache_flags(const char *mode, int *flags)
  636. {
  637. *flags &= ~BDRV_O_CACHE_MASK;
  638. if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
  639. *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
  640. } else if (!strcmp(mode, "directsync")) {
  641. *flags |= BDRV_O_NOCACHE;
  642. } else if (!strcmp(mode, "writeback")) {
  643. *flags |= BDRV_O_CACHE_WB;
  644. } else if (!strcmp(mode, "unsafe")) {
  645. *flags |= BDRV_O_CACHE_WB;
  646. *flags |= BDRV_O_NO_FLUSH;
  647. } else if (!strcmp(mode, "writethrough")) {
  648. /* this is the default */
  649. } else {
  650. return -1;
  651. }
  652. return 0;
  653. }
  654. /**
  655. * The copy-on-read flag is actually a reference count so multiple users may
  656. * use the feature without worrying about clobbering its previous state.
  657. * Copy-on-read stays enabled until all users have called to disable it.
  658. */
  659. void bdrv_enable_copy_on_read(BlockDriverState *bs)
  660. {
  661. bs->copy_on_read++;
  662. }
  663. void bdrv_disable_copy_on_read(BlockDriverState *bs)
  664. {
  665. assert(bs->copy_on_read > 0);
  666. bs->copy_on_read--;
  667. }
  668. static int bdrv_open_flags(BlockDriverState *bs, int flags)
  669. {
  670. int open_flags = flags | BDRV_O_CACHE_WB;
  671. /* The backing file of a temporary snapshot is read-only */
  672. if (flags & BDRV_O_SNAPSHOT) {
  673. open_flags &= ~BDRV_O_RDWR;
  674. }
  675. /*
  676. * Clear flags that are internal to the block layer before opening the
  677. * image.
  678. */
  679. open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
  680. /*
  681. * Snapshots should be writable.
  682. */
  683. if (bs->is_temporary) {
  684. open_flags |= BDRV_O_RDWR;
  685. }
  686. return open_flags;
  687. }
  688. static int bdrv_assign_node_name(BlockDriverState *bs,
  689. const char *node_name,
  690. Error **errp)
  691. {
  692. if (!node_name) {
  693. return 0;
  694. }
  695. /* empty string node name is invalid */
  696. if (node_name[0] == '\0') {
  697. error_setg(errp, "Empty node name");
  698. return -EINVAL;
  699. }
  700. /* takes care of avoiding namespaces collisions */
  701. if (bdrv_find(node_name)) {
  702. error_setg(errp, "node-name=%s is conflicting with a device id",
  703. node_name);
  704. return -EINVAL;
  705. }
  706. /* takes care of avoiding duplicates node names */
  707. if (bdrv_find_node(node_name)) {
  708. error_setg(errp, "Duplicate node name");
  709. return -EINVAL;
  710. }
  711. /* copy node name into the bs and insert it into the graph list */
  712. pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
  713. QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
  714. return 0;
  715. }
  716. /*
  717. * Common part for opening disk images and files
  718. *
  719. * Removes all processed options from *options.
  720. */
  721. static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
  722. QDict *options, int flags, BlockDriver *drv, Error **errp)
  723. {
  724. int ret, open_flags;
  725. const char *filename;
  726. const char *node_name = NULL;
  727. Error *local_err = NULL;
  728. assert(drv != NULL);
  729. assert(bs->file == NULL);
  730. assert(options != NULL && bs->options != options);
  731. if (file != NULL) {
  732. filename = file->filename;
  733. } else {
  734. filename = qdict_get_try_str(options, "filename");
  735. }
  736. if (drv->bdrv_needs_filename && !filename) {
  737. error_setg(errp, "The '%s' block driver requires a file name",
  738. drv->format_name);
  739. return -EINVAL;
  740. }
  741. trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
  742. node_name = qdict_get_try_str(options, "node-name");
  743. ret = bdrv_assign_node_name(bs, node_name, errp);
  744. if (ret < 0) {
  745. return ret;
  746. }
  747. qdict_del(options, "node-name");
  748. /* bdrv_open() with directly using a protocol as drv. This layer is already
  749. * opened, so assign it to bs (while file becomes a closed BlockDriverState)
  750. * and return immediately. */
  751. if (file != NULL && drv->bdrv_file_open) {
  752. bdrv_swap(file, bs);
  753. return 0;
  754. }
  755. bs->open_flags = flags;
  756. bs->guest_block_size = 512;
  757. bs->request_alignment = 512;
  758. bs->zero_beyond_eof = true;
  759. open_flags = bdrv_open_flags(bs, flags);
  760. bs->read_only = !(open_flags & BDRV_O_RDWR);
  761. if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
  762. error_setg(errp,
  763. !bs->read_only && bdrv_is_whitelisted(drv, true)
  764. ? "Driver '%s' can only be used for read-only devices"
  765. : "Driver '%s' is not whitelisted",
  766. drv->format_name);
  767. return -ENOTSUP;
  768. }
  769. assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
  770. if (flags & BDRV_O_COPY_ON_READ) {
  771. if (!bs->read_only) {
  772. bdrv_enable_copy_on_read(bs);
  773. } else {
  774. error_setg(errp, "Can't use copy-on-read on read-only device");
  775. return -EINVAL;
  776. }
  777. }
  778. if (filename != NULL) {
  779. pstrcpy(bs->filename, sizeof(bs->filename), filename);
  780. } else {
  781. bs->filename[0] = '\0';
  782. }
  783. bs->drv = drv;
  784. bs->opaque = g_malloc0(drv->instance_size);
  785. bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
  786. /* Open the image, either directly or using a protocol */
  787. if (drv->bdrv_file_open) {
  788. assert(file == NULL);
  789. assert(!drv->bdrv_needs_filename || filename != NULL);
  790. ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
  791. } else {
  792. if (file == NULL) {
  793. error_setg(errp, "Can't use '%s' as a block driver for the "
  794. "protocol level", drv->format_name);
  795. ret = -EINVAL;
  796. goto free_and_fail;
  797. }
  798. bs->file = file;
  799. ret = drv->bdrv_open(bs, options, open_flags, &local_err);
  800. }
  801. if (ret < 0) {
  802. if (local_err) {
  803. error_propagate(errp, local_err);
  804. } else if (bs->filename[0]) {
  805. error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
  806. } else {
  807. error_setg_errno(errp, -ret, "Could not open image");
  808. }
  809. goto free_and_fail;
  810. }
  811. ret = refresh_total_sectors(bs, bs->total_sectors);
  812. if (ret < 0) {
  813. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  814. goto free_and_fail;
  815. }
  816. bdrv_refresh_limits(bs);
  817. assert(bdrv_opt_mem_align(bs) != 0);
  818. assert((bs->request_alignment != 0) || bs->sg);
  819. #ifndef _WIN32
  820. if (bs->is_temporary) {
  821. assert(bs->filename[0] != '\0');
  822. unlink(bs->filename);
  823. }
  824. #endif
  825. return 0;
  826. free_and_fail:
  827. bs->file = NULL;
  828. g_free(bs->opaque);
  829. bs->opaque = NULL;
  830. bs->drv = NULL;
  831. return ret;
  832. }
  833. /*
  834. * Opens a file using a protocol (file, host_device, nbd, ...)
  835. *
  836. * options is an indirect pointer to a QDict of options to pass to the block
  837. * drivers, or pointer to NULL for an empty set of options. If this function
  838. * takes ownership of the QDict reference, it will set *options to NULL;
  839. * otherwise, it will contain unused/unrecognized options after this function
  840. * returns. Then, the caller is responsible for freeing it. If it intends to
  841. * reuse the QDict, QINCREF() should be called beforehand.
  842. */
  843. static int bdrv_file_open(BlockDriverState *bs, const char *filename,
  844. QDict **options, int flags, Error **errp)
  845. {
  846. BlockDriver *drv;
  847. const char *drvname;
  848. bool parse_filename = false;
  849. Error *local_err = NULL;
  850. int ret;
  851. /* Fetch the file name from the options QDict if necessary */
  852. if (!filename) {
  853. filename = qdict_get_try_str(*options, "filename");
  854. } else if (filename && !qdict_haskey(*options, "filename")) {
  855. qdict_put(*options, "filename", qstring_from_str(filename));
  856. parse_filename = true;
  857. } else {
  858. error_setg(errp, "Can't specify 'file' and 'filename' options at the "
  859. "same time");
  860. ret = -EINVAL;
  861. goto fail;
  862. }
  863. /* Find the right block driver */
  864. drvname = qdict_get_try_str(*options, "driver");
  865. if (drvname) {
  866. drv = bdrv_find_format(drvname);
  867. if (!drv) {
  868. error_setg(errp, "Unknown driver '%s'", drvname);
  869. }
  870. qdict_del(*options, "driver");
  871. } else if (filename) {
  872. drv = bdrv_find_protocol(filename, parse_filename);
  873. if (!drv) {
  874. error_setg(errp, "Unknown protocol");
  875. }
  876. } else {
  877. error_setg(errp, "Must specify either driver or file");
  878. drv = NULL;
  879. }
  880. if (!drv) {
  881. /* errp has been set already */
  882. ret = -ENOENT;
  883. goto fail;
  884. }
  885. /* Parse the filename and open it */
  886. if (drv->bdrv_parse_filename && parse_filename) {
  887. drv->bdrv_parse_filename(filename, *options, &local_err);
  888. if (local_err) {
  889. error_propagate(errp, local_err);
  890. ret = -EINVAL;
  891. goto fail;
  892. }
  893. if (!drv->bdrv_needs_filename) {
  894. qdict_del(*options, "filename");
  895. } else {
  896. filename = qdict_get_str(*options, "filename");
  897. }
  898. }
  899. if (!drv->bdrv_file_open) {
  900. ret = bdrv_open(&bs, filename, NULL, *options, flags, drv, &local_err);
  901. *options = NULL;
  902. } else {
  903. ret = bdrv_open_common(bs, NULL, *options, flags, drv, &local_err);
  904. }
  905. if (ret < 0) {
  906. error_propagate(errp, local_err);
  907. goto fail;
  908. }
  909. bs->growable = 1;
  910. return 0;
  911. fail:
  912. return ret;
  913. }
  914. /*
  915. * Opens the backing file for a BlockDriverState if not yet open
  916. *
  917. * options is a QDict of options to pass to the block drivers, or NULL for an
  918. * empty set of options. The reference to the QDict is transferred to this
  919. * function (even on failure), so if the caller intends to reuse the dictionary,
  920. * it needs to use QINCREF() before calling bdrv_file_open.
  921. */
  922. int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
  923. {
  924. char *backing_filename = g_malloc0(PATH_MAX);
  925. int back_flags, ret = 0;
  926. BlockDriver *back_drv = NULL;
  927. Error *local_err = NULL;
  928. if (bs->backing_hd != NULL) {
  929. QDECREF(options);
  930. goto free_exit;
  931. }
  932. /* NULL means an empty set of options */
  933. if (options == NULL) {
  934. options = qdict_new();
  935. }
  936. bs->open_flags &= ~BDRV_O_NO_BACKING;
  937. if (qdict_haskey(options, "file.filename")) {
  938. backing_filename[0] = '\0';
  939. } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
  940. QDECREF(options);
  941. goto free_exit;
  942. } else {
  943. bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX);
  944. }
  945. if (bs->backing_format[0] != '\0') {
  946. back_drv = bdrv_find_format(bs->backing_format);
  947. }
  948. /* backing files always opened read-only */
  949. back_flags = bs->open_flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT |
  950. BDRV_O_COPY_ON_READ);
  951. assert(bs->backing_hd == NULL);
  952. ret = bdrv_open(&bs->backing_hd,
  953. *backing_filename ? backing_filename : NULL, NULL, options,
  954. back_flags, back_drv, &local_err);
  955. if (ret < 0) {
  956. bs->backing_hd = NULL;
  957. bs->open_flags |= BDRV_O_NO_BACKING;
  958. error_setg(errp, "Could not open backing file: %s",
  959. error_get_pretty(local_err));
  960. error_free(local_err);
  961. goto free_exit;
  962. }
  963. if (bs->backing_hd->file) {
  964. pstrcpy(bs->backing_file, sizeof(bs->backing_file),
  965. bs->backing_hd->file->filename);
  966. }
  967. /* Recalculate the BlockLimits with the backing file */
  968. bdrv_refresh_limits(bs);
  969. free_exit:
  970. g_free(backing_filename);
  971. return ret;
  972. }
  973. /*
  974. * Opens a disk image whose options are given as BlockdevRef in another block
  975. * device's options.
  976. *
  977. * If allow_none is true, no image will be opened if filename is false and no
  978. * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
  979. *
  980. * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
  981. * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
  982. * itself, all options starting with "${bdref_key}." are considered part of the
  983. * BlockdevRef.
  984. *
  985. * The BlockdevRef will be removed from the options QDict.
  986. *
  987. * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
  988. */
  989. int bdrv_open_image(BlockDriverState **pbs, const char *filename,
  990. QDict *options, const char *bdref_key, int flags,
  991. bool allow_none, Error **errp)
  992. {
  993. QDict *image_options;
  994. int ret;
  995. char *bdref_key_dot;
  996. const char *reference;
  997. assert(pbs);
  998. assert(*pbs == NULL);
  999. bdref_key_dot = g_strdup_printf("%s.", bdref_key);
  1000. qdict_extract_subqdict(options, &image_options, bdref_key_dot);
  1001. g_free(bdref_key_dot);
  1002. reference = qdict_get_try_str(options, bdref_key);
  1003. if (!filename && !reference && !qdict_size(image_options)) {
  1004. if (allow_none) {
  1005. ret = 0;
  1006. } else {
  1007. error_setg(errp, "A block device must be specified for \"%s\"",
  1008. bdref_key);
  1009. ret = -EINVAL;
  1010. }
  1011. QDECREF(image_options);
  1012. goto done;
  1013. }
  1014. ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
  1015. done:
  1016. qdict_del(options, bdref_key);
  1017. return ret;
  1018. }
  1019. void bdrv_append_temp_snapshot(BlockDriverState *bs, Error **errp)
  1020. {
  1021. /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
  1022. char *tmp_filename = g_malloc0(PATH_MAX + 1);
  1023. int64_t total_size;
  1024. BlockDriver *bdrv_qcow2;
  1025. QEMUOptionParameter *create_options;
  1026. QDict *snapshot_options;
  1027. BlockDriverState *bs_snapshot;
  1028. Error *local_err;
  1029. int ret;
  1030. /* if snapshot, we create a temporary backing file and open it
  1031. instead of opening 'filename' directly */
  1032. /* Get the required size from the image */
  1033. total_size = bdrv_getlength(bs);
  1034. if (total_size < 0) {
  1035. error_setg_errno(errp, -total_size, "Could not get image size");
  1036. goto out;
  1037. }
  1038. total_size &= BDRV_SECTOR_MASK;
  1039. /* Create the temporary image */
  1040. ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
  1041. if (ret < 0) {
  1042. error_setg_errno(errp, -ret, "Could not get temporary filename");
  1043. goto out;
  1044. }
  1045. bdrv_qcow2 = bdrv_find_format("qcow2");
  1046. create_options = parse_option_parameters("", bdrv_qcow2->create_options,
  1047. NULL);
  1048. set_option_parameter_int(create_options, BLOCK_OPT_SIZE, total_size);
  1049. ret = bdrv_create(bdrv_qcow2, tmp_filename, create_options, &local_err);
  1050. free_option_parameters(create_options);
  1051. if (ret < 0) {
  1052. error_setg_errno(errp, -ret, "Could not create temporary overlay "
  1053. "'%s': %s", tmp_filename,
  1054. error_get_pretty(local_err));
  1055. error_free(local_err);
  1056. goto out;
  1057. }
  1058. /* Prepare a new options QDict for the temporary file */
  1059. snapshot_options = qdict_new();
  1060. qdict_put(snapshot_options, "file.driver",
  1061. qstring_from_str("file"));
  1062. qdict_put(snapshot_options, "file.filename",
  1063. qstring_from_str(tmp_filename));
  1064. bs_snapshot = bdrv_new("");
  1065. bs_snapshot->is_temporary = 1;
  1066. ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
  1067. bs->open_flags & ~BDRV_O_SNAPSHOT, bdrv_qcow2, &local_err);
  1068. if (ret < 0) {
  1069. error_propagate(errp, local_err);
  1070. goto out;
  1071. }
  1072. bdrv_append(bs_snapshot, bs);
  1073. out:
  1074. g_free(tmp_filename);
  1075. }
  1076. /*
  1077. * Opens a disk image (raw, qcow2, vmdk, ...)
  1078. *
  1079. * options is a QDict of options to pass to the block drivers, or NULL for an
  1080. * empty set of options. The reference to the QDict belongs to the block layer
  1081. * after the call (even on failure), so if the caller intends to reuse the
  1082. * dictionary, it needs to use QINCREF() before calling bdrv_open.
  1083. *
  1084. * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
  1085. * If it is not NULL, the referenced BDS will be reused.
  1086. *
  1087. * The reference parameter may be used to specify an existing block device which
  1088. * should be opened. If specified, neither options nor a filename may be given,
  1089. * nor can an existing BDS be reused (that is, *pbs has to be NULL).
  1090. */
  1091. int bdrv_open(BlockDriverState **pbs, const char *filename,
  1092. const char *reference, QDict *options, int flags,
  1093. BlockDriver *drv, Error **errp)
  1094. {
  1095. int ret;
  1096. BlockDriverState *file = NULL, *bs;
  1097. const char *drvname;
  1098. Error *local_err = NULL;
  1099. assert(pbs);
  1100. if (reference) {
  1101. bool options_non_empty = options ? qdict_size(options) : false;
  1102. QDECREF(options);
  1103. if (*pbs) {
  1104. error_setg(errp, "Cannot reuse an existing BDS when referencing "
  1105. "another block device");
  1106. return -EINVAL;
  1107. }
  1108. if (filename || options_non_empty) {
  1109. error_setg(errp, "Cannot reference an existing block device with "
  1110. "additional options or a new filename");
  1111. return -EINVAL;
  1112. }
  1113. bs = bdrv_lookup_bs(reference, reference, errp);
  1114. if (!bs) {
  1115. return -ENODEV;
  1116. }
  1117. bdrv_ref(bs);
  1118. *pbs = bs;
  1119. return 0;
  1120. }
  1121. if (*pbs) {
  1122. bs = *pbs;
  1123. } else {
  1124. bs = bdrv_new("");
  1125. }
  1126. /* NULL means an empty set of options */
  1127. if (options == NULL) {
  1128. options = qdict_new();
  1129. }
  1130. bs->options = options;
  1131. options = qdict_clone_shallow(options);
  1132. if (flags & BDRV_O_PROTOCOL) {
  1133. assert(!drv);
  1134. ret = bdrv_file_open(bs, filename, &options, flags & ~BDRV_O_PROTOCOL,
  1135. &local_err);
  1136. if (!ret) {
  1137. drv = bs->drv;
  1138. goto done;
  1139. } else if (bs->drv) {
  1140. goto close_and_fail;
  1141. } else {
  1142. goto fail;
  1143. }
  1144. }
  1145. /* Open image file without format layer */
  1146. if (flags & BDRV_O_RDWR) {
  1147. flags |= BDRV_O_ALLOW_RDWR;
  1148. }
  1149. assert(file == NULL);
  1150. ret = bdrv_open_image(&file, filename, options, "file",
  1151. bdrv_open_flags(bs, flags | BDRV_O_UNMAP) |
  1152. BDRV_O_PROTOCOL, true, &local_err);
  1153. if (ret < 0) {
  1154. goto unlink_and_fail;
  1155. }
  1156. /* Find the right image format driver */
  1157. drvname = qdict_get_try_str(options, "driver");
  1158. if (drvname) {
  1159. drv = bdrv_find_format(drvname);
  1160. qdict_del(options, "driver");
  1161. if (!drv) {
  1162. error_setg(errp, "Invalid driver: '%s'", drvname);
  1163. ret = -EINVAL;
  1164. goto unlink_and_fail;
  1165. }
  1166. }
  1167. if (!drv) {
  1168. if (file) {
  1169. ret = find_image_format(file, filename, &drv, &local_err);
  1170. } else {
  1171. error_setg(errp, "Must specify either driver or file");
  1172. ret = -EINVAL;
  1173. goto unlink_and_fail;
  1174. }
  1175. }
  1176. if (!drv) {
  1177. goto unlink_and_fail;
  1178. }
  1179. /* Open the image */
  1180. ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
  1181. if (ret < 0) {
  1182. goto unlink_and_fail;
  1183. }
  1184. if (file && (bs->file != file)) {
  1185. bdrv_unref(file);
  1186. file = NULL;
  1187. }
  1188. /* If there is a backing file, use it */
  1189. if ((flags & BDRV_O_NO_BACKING) == 0) {
  1190. QDict *backing_options;
  1191. qdict_extract_subqdict(options, &backing_options, "backing.");
  1192. ret = bdrv_open_backing_file(bs, backing_options, &local_err);
  1193. if (ret < 0) {
  1194. goto close_and_fail;
  1195. }
  1196. }
  1197. /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
  1198. * temporary snapshot afterwards. */
  1199. if (flags & BDRV_O_SNAPSHOT) {
  1200. bdrv_append_temp_snapshot(bs, &local_err);
  1201. if (local_err) {
  1202. error_propagate(errp, local_err);
  1203. goto close_and_fail;
  1204. }
  1205. }
  1206. done:
  1207. /* Check if any unknown options were used */
  1208. if (options && (qdict_size(options) != 0)) {
  1209. const QDictEntry *entry = qdict_first(options);
  1210. if (flags & BDRV_O_PROTOCOL) {
  1211. error_setg(errp, "Block protocol '%s' doesn't support the option "
  1212. "'%s'", drv->format_name, entry->key);
  1213. } else {
  1214. error_setg(errp, "Block format '%s' used by device '%s' doesn't "
  1215. "support the option '%s'", drv->format_name,
  1216. bs->device_name, entry->key);
  1217. }
  1218. ret = -EINVAL;
  1219. goto close_and_fail;
  1220. }
  1221. if (!bdrv_key_required(bs)) {
  1222. bdrv_dev_change_media_cb(bs, true);
  1223. } else if (!runstate_check(RUN_STATE_PRELAUNCH)
  1224. && !runstate_check(RUN_STATE_INMIGRATE)
  1225. && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
  1226. error_setg(errp,
  1227. "Guest must be stopped for opening of encrypted image");
  1228. ret = -EBUSY;
  1229. goto close_and_fail;
  1230. }
  1231. QDECREF(options);
  1232. *pbs = bs;
  1233. return 0;
  1234. unlink_and_fail:
  1235. if (file != NULL) {
  1236. bdrv_unref(file);
  1237. }
  1238. if (bs->is_temporary) {
  1239. unlink(filename);
  1240. }
  1241. fail:
  1242. QDECREF(bs->options);
  1243. QDECREF(options);
  1244. bs->options = NULL;
  1245. if (!*pbs) {
  1246. /* If *pbs is NULL, a new BDS has been created in this function and
  1247. needs to be freed now. Otherwise, it does not need to be closed,
  1248. since it has not really been opened yet. */
  1249. bdrv_unref(bs);
  1250. }
  1251. if (local_err) {
  1252. error_propagate(errp, local_err);
  1253. }
  1254. return ret;
  1255. close_and_fail:
  1256. /* See fail path, but now the BDS has to be always closed */
  1257. if (*pbs) {
  1258. bdrv_close(bs);
  1259. } else {
  1260. bdrv_unref(bs);
  1261. }
  1262. QDECREF(options);
  1263. if (local_err) {
  1264. error_propagate(errp, local_err);
  1265. }
  1266. return ret;
  1267. }
  1268. typedef struct BlockReopenQueueEntry {
  1269. bool prepared;
  1270. BDRVReopenState state;
  1271. QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
  1272. } BlockReopenQueueEntry;
  1273. /*
  1274. * Adds a BlockDriverState to a simple queue for an atomic, transactional
  1275. * reopen of multiple devices.
  1276. *
  1277. * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
  1278. * already performed, or alternatively may be NULL a new BlockReopenQueue will
  1279. * be created and initialized. This newly created BlockReopenQueue should be
  1280. * passed back in for subsequent calls that are intended to be of the same
  1281. * atomic 'set'.
  1282. *
  1283. * bs is the BlockDriverState to add to the reopen queue.
  1284. *
  1285. * flags contains the open flags for the associated bs
  1286. *
  1287. * returns a pointer to bs_queue, which is either the newly allocated
  1288. * bs_queue, or the existing bs_queue being used.
  1289. *
  1290. */
  1291. BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
  1292. BlockDriverState *bs, int flags)
  1293. {
  1294. assert(bs != NULL);
  1295. BlockReopenQueueEntry *bs_entry;
  1296. if (bs_queue == NULL) {
  1297. bs_queue = g_new0(BlockReopenQueue, 1);
  1298. QSIMPLEQ_INIT(bs_queue);
  1299. }
  1300. if (bs->file) {
  1301. bdrv_reopen_queue(bs_queue, bs->file, flags);
  1302. }
  1303. bs_entry = g_new0(BlockReopenQueueEntry, 1);
  1304. QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
  1305. bs_entry->state.bs = bs;
  1306. bs_entry->state.flags = flags;
  1307. return bs_queue;
  1308. }
  1309. /*
  1310. * Reopen multiple BlockDriverStates atomically & transactionally.
  1311. *
  1312. * The queue passed in (bs_queue) must have been built up previous
  1313. * via bdrv_reopen_queue().
  1314. *
  1315. * Reopens all BDS specified in the queue, with the appropriate
  1316. * flags. All devices are prepared for reopen, and failure of any
  1317. * device will cause all device changes to be abandonded, and intermediate
  1318. * data cleaned up.
  1319. *
  1320. * If all devices prepare successfully, then the changes are committed
  1321. * to all devices.
  1322. *
  1323. */
  1324. int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
  1325. {
  1326. int ret = -1;
  1327. BlockReopenQueueEntry *bs_entry, *next;
  1328. Error *local_err = NULL;
  1329. assert(bs_queue != NULL);
  1330. bdrv_drain_all();
  1331. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  1332. if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
  1333. error_propagate(errp, local_err);
  1334. goto cleanup;
  1335. }
  1336. bs_entry->prepared = true;
  1337. }
  1338. /* If we reach this point, we have success and just need to apply the
  1339. * changes
  1340. */
  1341. QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
  1342. bdrv_reopen_commit(&bs_entry->state);
  1343. }
  1344. ret = 0;
  1345. cleanup:
  1346. QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
  1347. if (ret && bs_entry->prepared) {
  1348. bdrv_reopen_abort(&bs_entry->state);
  1349. }
  1350. g_free(bs_entry);
  1351. }
  1352. g_free(bs_queue);
  1353. return ret;
  1354. }
  1355. /* Reopen a single BlockDriverState with the specified flags. */
  1356. int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
  1357. {
  1358. int ret = -1;
  1359. Error *local_err = NULL;
  1360. BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
  1361. ret = bdrv_reopen_multiple(queue, &local_err);
  1362. if (local_err != NULL) {
  1363. error_propagate(errp, local_err);
  1364. }
  1365. return ret;
  1366. }
  1367. /*
  1368. * Prepares a BlockDriverState for reopen. All changes are staged in the
  1369. * 'opaque' field of the BDRVReopenState, which is used and allocated by
  1370. * the block driver layer .bdrv_reopen_prepare()
  1371. *
  1372. * bs is the BlockDriverState to reopen
  1373. * flags are the new open flags
  1374. * queue is the reopen queue
  1375. *
  1376. * Returns 0 on success, non-zero on error. On error errp will be set
  1377. * as well.
  1378. *
  1379. * On failure, bdrv_reopen_abort() will be called to clean up any data.
  1380. * It is the responsibility of the caller to then call the abort() or
  1381. * commit() for any other BDS that have been left in a prepare() state
  1382. *
  1383. */
  1384. int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
  1385. Error **errp)
  1386. {
  1387. int ret = -1;
  1388. Error *local_err = NULL;
  1389. BlockDriver *drv;
  1390. assert(reopen_state != NULL);
  1391. assert(reopen_state->bs->drv != NULL);
  1392. drv = reopen_state->bs->drv;
  1393. /* if we are to stay read-only, do not allow permission change
  1394. * to r/w */
  1395. if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
  1396. reopen_state->flags & BDRV_O_RDWR) {
  1397. error_set(errp, QERR_DEVICE_IS_READ_ONLY,
  1398. reopen_state->bs->device_name);
  1399. goto error;
  1400. }
  1401. ret = bdrv_flush(reopen_state->bs);
  1402. if (ret) {
  1403. error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
  1404. strerror(-ret));
  1405. goto error;
  1406. }
  1407. if (drv->bdrv_reopen_prepare) {
  1408. ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
  1409. if (ret) {
  1410. if (local_err != NULL) {
  1411. error_propagate(errp, local_err);
  1412. } else {
  1413. error_setg(errp, "failed while preparing to reopen image '%s'",
  1414. reopen_state->bs->filename);
  1415. }
  1416. goto error;
  1417. }
  1418. } else {
  1419. /* It is currently mandatory to have a bdrv_reopen_prepare()
  1420. * handler for each supported drv. */
  1421. error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
  1422. drv->format_name, reopen_state->bs->device_name,
  1423. "reopening of file");
  1424. ret = -1;
  1425. goto error;
  1426. }
  1427. ret = 0;
  1428. error:
  1429. return ret;
  1430. }
  1431. /*
  1432. * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
  1433. * makes them final by swapping the staging BlockDriverState contents into
  1434. * the active BlockDriverState contents.
  1435. */
  1436. void bdrv_reopen_commit(BDRVReopenState *reopen_state)
  1437. {
  1438. BlockDriver *drv;
  1439. assert(reopen_state != NULL);
  1440. drv = reopen_state->bs->drv;
  1441. assert(drv != NULL);
  1442. /* If there are any driver level actions to take */
  1443. if (drv->bdrv_reopen_commit) {
  1444. drv->bdrv_reopen_commit(reopen_state);
  1445. }
  1446. /* set BDS specific flags now */
  1447. reopen_state->bs->open_flags = reopen_state->flags;
  1448. reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
  1449. BDRV_O_CACHE_WB);
  1450. reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
  1451. bdrv_refresh_limits(reopen_state->bs);
  1452. }
  1453. /*
  1454. * Abort the reopen, and delete and free the staged changes in
  1455. * reopen_state
  1456. */
  1457. void bdrv_reopen_abort(BDRVReopenState *reopen_state)
  1458. {
  1459. BlockDriver *drv;
  1460. assert(reopen_state != NULL);
  1461. drv = reopen_state->bs->drv;
  1462. assert(drv != NULL);
  1463. if (drv->bdrv_reopen_abort) {
  1464. drv->bdrv_reopen_abort(reopen_state);
  1465. }
  1466. }
  1467. void bdrv_close(BlockDriverState *bs)
  1468. {
  1469. if (bs->job) {
  1470. block_job_cancel_sync(bs->job);
  1471. }
  1472. bdrv_drain_all(); /* complete I/O */
  1473. bdrv_flush(bs);
  1474. bdrv_drain_all(); /* in case flush left pending I/O */
  1475. notifier_list_notify(&bs->close_notifiers, bs);
  1476. if (bs->drv) {
  1477. if (bs->backing_hd) {
  1478. bdrv_unref(bs->backing_hd);
  1479. bs->backing_hd = NULL;
  1480. }
  1481. bs->drv->bdrv_close(bs);
  1482. g_free(bs->opaque);
  1483. #ifdef _WIN32
  1484. if (bs->is_temporary) {
  1485. unlink(bs->filename);
  1486. }
  1487. #endif
  1488. bs->opaque = NULL;
  1489. bs->drv = NULL;
  1490. bs->copy_on_read = 0;
  1491. bs->backing_file[0] = '\0';
  1492. bs->backing_format[0] = '\0';
  1493. bs->total_sectors = 0;
  1494. bs->encrypted = 0;
  1495. bs->valid_key = 0;
  1496. bs->sg = 0;
  1497. bs->growable = 0;
  1498. bs->zero_beyond_eof = false;
  1499. QDECREF(bs->options);
  1500. bs->options = NULL;
  1501. if (bs->file != NULL) {
  1502. bdrv_unref(bs->file);
  1503. bs->file = NULL;
  1504. }
  1505. }
  1506. bdrv_dev_change_media_cb(bs, false);
  1507. /*throttling disk I/O limits*/
  1508. if (bs->io_limits_enabled) {
  1509. bdrv_io_limits_disable(bs);
  1510. }
  1511. }
  1512. void bdrv_close_all(void)
  1513. {
  1514. BlockDriverState *bs;
  1515. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  1516. bdrv_close(bs);
  1517. }
  1518. }
  1519. /* Check if any requests are in-flight (including throttled requests) */
  1520. static bool bdrv_requests_pending(BlockDriverState *bs)
  1521. {
  1522. if (!QLIST_EMPTY(&bs->tracked_requests)) {
  1523. return true;
  1524. }
  1525. if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
  1526. return true;
  1527. }
  1528. if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
  1529. return true;
  1530. }
  1531. if (bs->file && bdrv_requests_pending(bs->file)) {
  1532. return true;
  1533. }
  1534. if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
  1535. return true;
  1536. }
  1537. return false;
  1538. }
  1539. static bool bdrv_requests_pending_all(void)
  1540. {
  1541. BlockDriverState *bs;
  1542. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  1543. if (bdrv_requests_pending(bs)) {
  1544. return true;
  1545. }
  1546. }
  1547. return false;
  1548. }
  1549. /*
  1550. * Wait for pending requests to complete across all BlockDriverStates
  1551. *
  1552. * This function does not flush data to disk, use bdrv_flush_all() for that
  1553. * after calling this function.
  1554. *
  1555. * Note that completion of an asynchronous I/O operation can trigger any
  1556. * number of other I/O operations on other devices---for example a coroutine
  1557. * can be arbitrarily complex and a constant flow of I/O can come until the
  1558. * coroutine is complete. Because of this, it is not possible to have a
  1559. * function to drain a single device's I/O queue.
  1560. */
  1561. void bdrv_drain_all(void)
  1562. {
  1563. /* Always run first iteration so any pending completion BHs run */
  1564. bool busy = true;
  1565. BlockDriverState *bs;
  1566. while (busy) {
  1567. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  1568. bdrv_start_throttled_reqs(bs);
  1569. }
  1570. busy = bdrv_requests_pending_all();
  1571. busy |= aio_poll(qemu_get_aio_context(), busy);
  1572. }
  1573. }
  1574. /* make a BlockDriverState anonymous by removing from bdrv_state and
  1575. * graph_bdrv_state list.
  1576. Also, NULL terminate the device_name to prevent double remove */
  1577. void bdrv_make_anon(BlockDriverState *bs)
  1578. {
  1579. if (bs->device_name[0] != '\0') {
  1580. QTAILQ_REMOVE(&bdrv_states, bs, device_list);
  1581. }
  1582. bs->device_name[0] = '\0';
  1583. if (bs->node_name[0] != '\0') {
  1584. QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
  1585. }
  1586. bs->node_name[0] = '\0';
  1587. }
  1588. static void bdrv_rebind(BlockDriverState *bs)
  1589. {
  1590. if (bs->drv && bs->drv->bdrv_rebind) {
  1591. bs->drv->bdrv_rebind(bs);
  1592. }
  1593. }
  1594. static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
  1595. BlockDriverState *bs_src)
  1596. {
  1597. /* move some fields that need to stay attached to the device */
  1598. bs_dest->open_flags = bs_src->open_flags;
  1599. /* dev info */
  1600. bs_dest->dev_ops = bs_src->dev_ops;
  1601. bs_dest->dev_opaque = bs_src->dev_opaque;
  1602. bs_dest->dev = bs_src->dev;
  1603. bs_dest->guest_block_size = bs_src->guest_block_size;
  1604. bs_dest->copy_on_read = bs_src->copy_on_read;
  1605. bs_dest->enable_write_cache = bs_src->enable_write_cache;
  1606. /* i/o throttled req */
  1607. memcpy(&bs_dest->throttle_state,
  1608. &bs_src->throttle_state,
  1609. sizeof(ThrottleState));
  1610. bs_dest->throttled_reqs[0] = bs_src->throttled_reqs[0];
  1611. bs_dest->throttled_reqs[1] = bs_src->throttled_reqs[1];
  1612. bs_dest->io_limits_enabled = bs_src->io_limits_enabled;
  1613. /* r/w error */
  1614. bs_dest->on_read_error = bs_src->on_read_error;
  1615. bs_dest->on_write_error = bs_src->on_write_error;
  1616. /* i/o status */
  1617. bs_dest->iostatus_enabled = bs_src->iostatus_enabled;
  1618. bs_dest->iostatus = bs_src->iostatus;
  1619. /* dirty bitmap */
  1620. bs_dest->dirty_bitmaps = bs_src->dirty_bitmaps;
  1621. /* reference count */
  1622. bs_dest->refcnt = bs_src->refcnt;
  1623. /* job */
  1624. bs_dest->in_use = bs_src->in_use;
  1625. bs_dest->job = bs_src->job;
  1626. /* keep the same entry in bdrv_states */
  1627. pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
  1628. bs_src->device_name);
  1629. bs_dest->device_list = bs_src->device_list;
  1630. }
  1631. /*
  1632. * Swap bs contents for two image chains while they are live,
  1633. * while keeping required fields on the BlockDriverState that is
  1634. * actually attached to a device.
  1635. *
  1636. * This will modify the BlockDriverState fields, and swap contents
  1637. * between bs_new and bs_old. Both bs_new and bs_old are modified.
  1638. *
  1639. * bs_new is required to be anonymous.
  1640. *
  1641. * This function does not create any image files.
  1642. */
  1643. void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
  1644. {
  1645. BlockDriverState tmp;
  1646. /* The code needs to swap the node_name but simply swapping node_list won't
  1647. * work so first remove the nodes from the graph list, do the swap then
  1648. * insert them back if needed.
  1649. */
  1650. if (bs_new->node_name[0] != '\0') {
  1651. QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
  1652. }
  1653. if (bs_old->node_name[0] != '\0') {
  1654. QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
  1655. }
  1656. /* bs_new must be anonymous and shouldn't have anything fancy enabled */
  1657. assert(bs_new->device_name[0] == '\0');
  1658. assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
  1659. assert(bs_new->job == NULL);
  1660. assert(bs_new->dev == NULL);
  1661. assert(bs_new->in_use == 0);
  1662. assert(bs_new->io_limits_enabled == false);
  1663. assert(!throttle_have_timer(&bs_new->throttle_state));
  1664. tmp = *bs_new;
  1665. *bs_new = *bs_old;
  1666. *bs_old = tmp;
  1667. /* there are some fields that should not be swapped, move them back */
  1668. bdrv_move_feature_fields(&tmp, bs_old);
  1669. bdrv_move_feature_fields(bs_old, bs_new);
  1670. bdrv_move_feature_fields(bs_new, &tmp);
  1671. /* bs_new shouldn't be in bdrv_states even after the swap! */
  1672. assert(bs_new->device_name[0] == '\0');
  1673. /* Check a few fields that should remain attached to the device */
  1674. assert(bs_new->dev == NULL);
  1675. assert(bs_new->job == NULL);
  1676. assert(bs_new->in_use == 0);
  1677. assert(bs_new->io_limits_enabled == false);
  1678. assert(!throttle_have_timer(&bs_new->throttle_state));
  1679. /* insert the nodes back into the graph node list if needed */
  1680. if (bs_new->node_name[0] != '\0') {
  1681. QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
  1682. }
  1683. if (bs_old->node_name[0] != '\0') {
  1684. QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
  1685. }
  1686. bdrv_rebind(bs_new);
  1687. bdrv_rebind(bs_old);
  1688. }
  1689. /*
  1690. * Add new bs contents at the top of an image chain while the chain is
  1691. * live, while keeping required fields on the top layer.
  1692. *
  1693. * This will modify the BlockDriverState fields, and swap contents
  1694. * between bs_new and bs_top. Both bs_new and bs_top are modified.
  1695. *
  1696. * bs_new is required to be anonymous.
  1697. *
  1698. * This function does not create any image files.
  1699. */
  1700. void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
  1701. {
  1702. bdrv_swap(bs_new, bs_top);
  1703. /* The contents of 'tmp' will become bs_top, as we are
  1704. * swapping bs_new and bs_top contents. */
  1705. bs_top->backing_hd = bs_new;
  1706. bs_top->open_flags &= ~BDRV_O_NO_BACKING;
  1707. pstrcpy(bs_top->backing_file, sizeof(bs_top->backing_file),
  1708. bs_new->filename);
  1709. pstrcpy(bs_top->backing_format, sizeof(bs_top->backing_format),
  1710. bs_new->drv ? bs_new->drv->format_name : "");
  1711. }
  1712. static void bdrv_delete(BlockDriverState *bs)
  1713. {
  1714. assert(!bs->dev);
  1715. assert(!bs->job);
  1716. assert(!bs->in_use);
  1717. assert(!bs->refcnt);
  1718. assert(QLIST_EMPTY(&bs->dirty_bitmaps));
  1719. bdrv_close(bs);
  1720. /* remove from list, if necessary */
  1721. bdrv_make_anon(bs);
  1722. g_free(bs);
  1723. }
  1724. int bdrv_attach_dev(BlockDriverState *bs, void *dev)
  1725. /* TODO change to DeviceState *dev when all users are qdevified */
  1726. {
  1727. if (bs->dev) {
  1728. return -EBUSY;
  1729. }
  1730. bs->dev = dev;
  1731. bdrv_iostatus_reset(bs);
  1732. return 0;
  1733. }
  1734. /* TODO qdevified devices don't use this, remove when devices are qdevified */
  1735. void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
  1736. {
  1737. if (bdrv_attach_dev(bs, dev) < 0) {
  1738. abort();
  1739. }
  1740. }
  1741. void bdrv_detach_dev(BlockDriverState *bs, void *dev)
  1742. /* TODO change to DeviceState *dev when all users are qdevified */
  1743. {
  1744. assert(bs->dev == dev);
  1745. bs->dev = NULL;
  1746. bs->dev_ops = NULL;
  1747. bs->dev_opaque = NULL;
  1748. bs->guest_block_size = 512;
  1749. }
  1750. /* TODO change to return DeviceState * when all users are qdevified */
  1751. void *bdrv_get_attached_dev(BlockDriverState *bs)
  1752. {
  1753. return bs->dev;
  1754. }
  1755. void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
  1756. void *opaque)
  1757. {
  1758. bs->dev_ops = ops;
  1759. bs->dev_opaque = opaque;
  1760. }
  1761. void bdrv_emit_qmp_error_event(const BlockDriverState *bdrv,
  1762. enum MonitorEvent ev,
  1763. BlockErrorAction action, bool is_read)
  1764. {
  1765. QObject *data;
  1766. const char *action_str;
  1767. switch (action) {
  1768. case BDRV_ACTION_REPORT:
  1769. action_str = "report";
  1770. break;
  1771. case BDRV_ACTION_IGNORE:
  1772. action_str = "ignore";
  1773. break;
  1774. case BDRV_ACTION_STOP:
  1775. action_str = "stop";
  1776. break;
  1777. default:
  1778. abort();
  1779. }
  1780. data = qobject_from_jsonf("{ 'device': %s, 'action': %s, 'operation': %s }",
  1781. bdrv->device_name,
  1782. action_str,
  1783. is_read ? "read" : "write");
  1784. monitor_protocol_event(ev, data);
  1785. qobject_decref(data);
  1786. }
  1787. static void bdrv_emit_qmp_eject_event(BlockDriverState *bs, bool ejected)
  1788. {
  1789. QObject *data;
  1790. data = qobject_from_jsonf("{ 'device': %s, 'tray-open': %i }",
  1791. bdrv_get_device_name(bs), ejected);
  1792. monitor_protocol_event(QEVENT_DEVICE_TRAY_MOVED, data);
  1793. qobject_decref(data);
  1794. }
  1795. static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
  1796. {
  1797. if (bs->dev_ops && bs->dev_ops->change_media_cb) {
  1798. bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
  1799. bs->dev_ops->change_media_cb(bs->dev_opaque, load);
  1800. if (tray_was_closed) {
  1801. /* tray open */
  1802. bdrv_emit_qmp_eject_event(bs, true);
  1803. }
  1804. if (load) {
  1805. /* tray close */
  1806. bdrv_emit_qmp_eject_event(bs, false);
  1807. }
  1808. }
  1809. }
  1810. bool bdrv_dev_has_removable_media(BlockDriverState *bs)
  1811. {
  1812. return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
  1813. }
  1814. void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
  1815. {
  1816. if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
  1817. bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
  1818. }
  1819. }
  1820. bool bdrv_dev_is_tray_open(BlockDriverState *bs)
  1821. {
  1822. if (bs->dev_ops && bs->dev_ops->is_tray_open) {
  1823. return bs->dev_ops->is_tray_open(bs->dev_opaque);
  1824. }
  1825. return false;
  1826. }
  1827. static void bdrv_dev_resize_cb(BlockDriverState *bs)
  1828. {
  1829. if (bs->dev_ops && bs->dev_ops->resize_cb) {
  1830. bs->dev_ops->resize_cb(bs->dev_opaque);
  1831. }
  1832. }
  1833. bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
  1834. {
  1835. if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
  1836. return bs->dev_ops->is_medium_locked(bs->dev_opaque);
  1837. }
  1838. return false;
  1839. }
  1840. /*
  1841. * Run consistency checks on an image
  1842. *
  1843. * Returns 0 if the check could be completed (it doesn't mean that the image is
  1844. * free of errors) or -errno when an internal error occurred. The results of the
  1845. * check are stored in res.
  1846. */
  1847. int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
  1848. {
  1849. if (bs->drv->bdrv_check == NULL) {
  1850. return -ENOTSUP;
  1851. }
  1852. memset(res, 0, sizeof(*res));
  1853. return bs->drv->bdrv_check(bs, res, fix);
  1854. }
  1855. #define COMMIT_BUF_SECTORS 2048
  1856. /* commit COW file into the raw image */
  1857. int bdrv_commit(BlockDriverState *bs)
  1858. {
  1859. BlockDriver *drv = bs->drv;
  1860. int64_t sector, total_sectors, length, backing_length;
  1861. int n, ro, open_flags;
  1862. int ret = 0;
  1863. uint8_t *buf = NULL;
  1864. char filename[PATH_MAX];
  1865. if (!drv)
  1866. return -ENOMEDIUM;
  1867. if (!bs->backing_hd) {
  1868. return -ENOTSUP;
  1869. }
  1870. if (bdrv_in_use(bs) || bdrv_in_use(bs->backing_hd)) {
  1871. return -EBUSY;
  1872. }
  1873. ro = bs->backing_hd->read_only;
  1874. /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
  1875. pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
  1876. open_flags = bs->backing_hd->open_flags;
  1877. if (ro) {
  1878. if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
  1879. return -EACCES;
  1880. }
  1881. }
  1882. length = bdrv_getlength(bs);
  1883. if (length < 0) {
  1884. ret = length;
  1885. goto ro_cleanup;
  1886. }
  1887. backing_length = bdrv_getlength(bs->backing_hd);
  1888. if (backing_length < 0) {
  1889. ret = backing_length;
  1890. goto ro_cleanup;
  1891. }
  1892. /* If our top snapshot is larger than the backing file image,
  1893. * grow the backing file image if possible. If not possible,
  1894. * we must return an error */
  1895. if (length > backing_length) {
  1896. ret = bdrv_truncate(bs->backing_hd, length);
  1897. if (ret < 0) {
  1898. goto ro_cleanup;
  1899. }
  1900. }
  1901. total_sectors = length >> BDRV_SECTOR_BITS;
  1902. buf = g_malloc(COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
  1903. for (sector = 0; sector < total_sectors; sector += n) {
  1904. ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
  1905. if (ret < 0) {
  1906. goto ro_cleanup;
  1907. }
  1908. if (ret) {
  1909. ret = bdrv_read(bs, sector, buf, n);
  1910. if (ret < 0) {
  1911. goto ro_cleanup;
  1912. }
  1913. ret = bdrv_write(bs->backing_hd, sector, buf, n);
  1914. if (ret < 0) {
  1915. goto ro_cleanup;
  1916. }
  1917. }
  1918. }
  1919. if (drv->bdrv_make_empty) {
  1920. ret = drv->bdrv_make_empty(bs);
  1921. if (ret < 0) {
  1922. goto ro_cleanup;
  1923. }
  1924. bdrv_flush(bs);
  1925. }
  1926. /*
  1927. * Make sure all data we wrote to the backing device is actually
  1928. * stable on disk.
  1929. */
  1930. if (bs->backing_hd) {
  1931. bdrv_flush(bs->backing_hd);
  1932. }
  1933. ret = 0;
  1934. ro_cleanup:
  1935. g_free(buf);
  1936. if (ro) {
  1937. /* ignoring error return here */
  1938. bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
  1939. }
  1940. return ret;
  1941. }
  1942. int bdrv_commit_all(void)
  1943. {
  1944. BlockDriverState *bs;
  1945. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  1946. if (bs->drv && bs->backing_hd) {
  1947. int ret = bdrv_commit(bs);
  1948. if (ret < 0) {
  1949. return ret;
  1950. }
  1951. }
  1952. }
  1953. return 0;
  1954. }
  1955. /**
  1956. * Remove an active request from the tracked requests list
  1957. *
  1958. * This function should be called when a tracked request is completing.
  1959. */
  1960. static void tracked_request_end(BdrvTrackedRequest *req)
  1961. {
  1962. if (req->serialising) {
  1963. req->bs->serialising_in_flight--;
  1964. }
  1965. QLIST_REMOVE(req, list);
  1966. qemu_co_queue_restart_all(&req->wait_queue);
  1967. }
  1968. /**
  1969. * Add an active request to the tracked requests list
  1970. */
  1971. static void tracked_request_begin(BdrvTrackedRequest *req,
  1972. BlockDriverState *bs,
  1973. int64_t offset,
  1974. unsigned int bytes, bool is_write)
  1975. {
  1976. *req = (BdrvTrackedRequest){
  1977. .bs = bs,
  1978. .offset = offset,
  1979. .bytes = bytes,
  1980. .is_write = is_write,
  1981. .co = qemu_coroutine_self(),
  1982. .serialising = false,
  1983. .overlap_offset = offset,
  1984. .overlap_bytes = bytes,
  1985. };
  1986. qemu_co_queue_init(&req->wait_queue);
  1987. QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
  1988. }
  1989. static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
  1990. {
  1991. int64_t overlap_offset = req->offset & ~(align - 1);
  1992. unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
  1993. - overlap_offset;
  1994. if (!req->serialising) {
  1995. req->bs->serialising_in_flight++;
  1996. req->serialising = true;
  1997. }
  1998. req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
  1999. req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
  2000. }
  2001. /**
  2002. * Round a region to cluster boundaries
  2003. */
  2004. void bdrv_round_to_clusters(BlockDriverState *bs,
  2005. int64_t sector_num, int nb_sectors,
  2006. int64_t *cluster_sector_num,
  2007. int *cluster_nb_sectors)
  2008. {
  2009. BlockDriverInfo bdi;
  2010. if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
  2011. *cluster_sector_num = sector_num;
  2012. *cluster_nb_sectors = nb_sectors;
  2013. } else {
  2014. int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
  2015. *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
  2016. *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
  2017. nb_sectors, c);
  2018. }
  2019. }
  2020. static int bdrv_get_cluster_size(BlockDriverState *bs)
  2021. {
  2022. BlockDriverInfo bdi;
  2023. int ret;
  2024. ret = bdrv_get_info(bs, &bdi);
  2025. if (ret < 0 || bdi.cluster_size == 0) {
  2026. return bs->request_alignment;
  2027. } else {
  2028. return bdi.cluster_size;
  2029. }
  2030. }
  2031. static bool tracked_request_overlaps(BdrvTrackedRequest *req,
  2032. int64_t offset, unsigned int bytes)
  2033. {
  2034. /* aaaa bbbb */
  2035. if (offset >= req->overlap_offset + req->overlap_bytes) {
  2036. return false;
  2037. }
  2038. /* bbbb aaaa */
  2039. if (req->overlap_offset >= offset + bytes) {
  2040. return false;
  2041. }
  2042. return true;
  2043. }
  2044. static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
  2045. {
  2046. BlockDriverState *bs = self->bs;
  2047. BdrvTrackedRequest *req;
  2048. bool retry;
  2049. bool waited = false;
  2050. if (!bs->serialising_in_flight) {
  2051. return false;
  2052. }
  2053. do {
  2054. retry = false;
  2055. QLIST_FOREACH(req, &bs->tracked_requests, list) {
  2056. if (req == self || (!req->serialising && !self->serialising)) {
  2057. continue;
  2058. }
  2059. if (tracked_request_overlaps(req, self->overlap_offset,
  2060. self->overlap_bytes))
  2061. {
  2062. /* Hitting this means there was a reentrant request, for
  2063. * example, a block driver issuing nested requests. This must
  2064. * never happen since it means deadlock.
  2065. */
  2066. assert(qemu_coroutine_self() != req->co);
  2067. /* If the request is already (indirectly) waiting for us, or
  2068. * will wait for us as soon as it wakes up, then just go on
  2069. * (instead of producing a deadlock in the former case). */
  2070. if (!req->waiting_for) {
  2071. self->waiting_for = req;
  2072. qemu_co_queue_wait(&req->wait_queue);
  2073. self->waiting_for = NULL;
  2074. retry = true;
  2075. waited = true;
  2076. break;
  2077. }
  2078. }
  2079. }
  2080. } while (retry);
  2081. return waited;
  2082. }
  2083. /*
  2084. * Return values:
  2085. * 0 - success
  2086. * -EINVAL - backing format specified, but no file
  2087. * -ENOSPC - can't update the backing file because no space is left in the
  2088. * image file header
  2089. * -ENOTSUP - format driver doesn't support changing the backing file
  2090. */
  2091. int bdrv_change_backing_file(BlockDriverState *bs,
  2092. const char *backing_file, const char *backing_fmt)
  2093. {
  2094. BlockDriver *drv = bs->drv;
  2095. int ret;
  2096. /* Backing file format doesn't make sense without a backing file */
  2097. if (backing_fmt && !backing_file) {
  2098. return -EINVAL;
  2099. }
  2100. if (drv->bdrv_change_backing_file != NULL) {
  2101. ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
  2102. } else {
  2103. ret = -ENOTSUP;
  2104. }
  2105. if (ret == 0) {
  2106. pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
  2107. pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
  2108. }
  2109. return ret;
  2110. }
  2111. /*
  2112. * Finds the image layer in the chain that has 'bs' as its backing file.
  2113. *
  2114. * active is the current topmost image.
  2115. *
  2116. * Returns NULL if bs is not found in active's image chain,
  2117. * or if active == bs.
  2118. */
  2119. BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
  2120. BlockDriverState *bs)
  2121. {
  2122. BlockDriverState *overlay = NULL;
  2123. BlockDriverState *intermediate;
  2124. assert(active != NULL);
  2125. assert(bs != NULL);
  2126. /* if bs is the same as active, then by definition it has no overlay
  2127. */
  2128. if (active == bs) {
  2129. return NULL;
  2130. }
  2131. intermediate = active;
  2132. while (intermediate->backing_hd) {
  2133. if (intermediate->backing_hd == bs) {
  2134. overlay = intermediate;
  2135. break;
  2136. }
  2137. intermediate = intermediate->backing_hd;
  2138. }
  2139. return overlay;
  2140. }
  2141. typedef struct BlkIntermediateStates {
  2142. BlockDriverState *bs;
  2143. QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
  2144. } BlkIntermediateStates;
  2145. /*
  2146. * Drops images above 'base' up to and including 'top', and sets the image
  2147. * above 'top' to have base as its backing file.
  2148. *
  2149. * Requires that the overlay to 'top' is opened r/w, so that the backing file
  2150. * information in 'bs' can be properly updated.
  2151. *
  2152. * E.g., this will convert the following chain:
  2153. * bottom <- base <- intermediate <- top <- active
  2154. *
  2155. * to
  2156. *
  2157. * bottom <- base <- active
  2158. *
  2159. * It is allowed for bottom==base, in which case it converts:
  2160. *
  2161. * base <- intermediate <- top <- active
  2162. *
  2163. * to
  2164. *
  2165. * base <- active
  2166. *
  2167. * Error conditions:
  2168. * if active == top, that is considered an error
  2169. *
  2170. */
  2171. int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
  2172. BlockDriverState *base)
  2173. {
  2174. BlockDriverState *intermediate;
  2175. BlockDriverState *base_bs = NULL;
  2176. BlockDriverState *new_top_bs = NULL;
  2177. BlkIntermediateStates *intermediate_state, *next;
  2178. int ret = -EIO;
  2179. QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
  2180. QSIMPLEQ_INIT(&states_to_delete);
  2181. if (!top->drv || !base->drv) {
  2182. goto exit;
  2183. }
  2184. new_top_bs = bdrv_find_overlay(active, top);
  2185. if (new_top_bs == NULL) {
  2186. /* we could not find the image above 'top', this is an error */
  2187. goto exit;
  2188. }
  2189. /* special case of new_top_bs->backing_hd already pointing to base - nothing
  2190. * to do, no intermediate images */
  2191. if (new_top_bs->backing_hd == base) {
  2192. ret = 0;
  2193. goto exit;
  2194. }
  2195. intermediate = top;
  2196. /* now we will go down through the list, and add each BDS we find
  2197. * into our deletion queue, until we hit the 'base'
  2198. */
  2199. while (intermediate) {
  2200. intermediate_state = g_malloc0(sizeof(BlkIntermediateStates));
  2201. intermediate_state->bs = intermediate;
  2202. QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
  2203. if (intermediate->backing_hd == base) {
  2204. base_bs = intermediate->backing_hd;
  2205. break;
  2206. }
  2207. intermediate = intermediate->backing_hd;
  2208. }
  2209. if (base_bs == NULL) {
  2210. /* something went wrong, we did not end at the base. safely
  2211. * unravel everything, and exit with error */
  2212. goto exit;
  2213. }
  2214. /* success - we can delete the intermediate states, and link top->base */
  2215. ret = bdrv_change_backing_file(new_top_bs, base_bs->filename,
  2216. base_bs->drv ? base_bs->drv->format_name : "");
  2217. if (ret) {
  2218. goto exit;
  2219. }
  2220. new_top_bs->backing_hd = base_bs;
  2221. bdrv_refresh_limits(new_top_bs);
  2222. QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
  2223. /* so that bdrv_close() does not recursively close the chain */
  2224. intermediate_state->bs->backing_hd = NULL;
  2225. bdrv_unref(intermediate_state->bs);
  2226. }
  2227. ret = 0;
  2228. exit:
  2229. QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
  2230. g_free(intermediate_state);
  2231. }
  2232. return ret;
  2233. }
  2234. static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
  2235. size_t size)
  2236. {
  2237. int64_t len;
  2238. if (!bdrv_is_inserted(bs))
  2239. return -ENOMEDIUM;
  2240. if (bs->growable)
  2241. return 0;
  2242. len = bdrv_getlength(bs);
  2243. if (offset < 0)
  2244. return -EIO;
  2245. if ((offset > len) || (len - offset < size))
  2246. return -EIO;
  2247. return 0;
  2248. }
  2249. static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
  2250. int nb_sectors)
  2251. {
  2252. if (nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
  2253. return -EIO;
  2254. }
  2255. return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
  2256. nb_sectors * BDRV_SECTOR_SIZE);
  2257. }
  2258. typedef struct RwCo {
  2259. BlockDriverState *bs;
  2260. int64_t offset;
  2261. QEMUIOVector *qiov;
  2262. bool is_write;
  2263. int ret;
  2264. BdrvRequestFlags flags;
  2265. } RwCo;
  2266. static void coroutine_fn bdrv_rw_co_entry(void *opaque)
  2267. {
  2268. RwCo *rwco = opaque;
  2269. if (!rwco->is_write) {
  2270. rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
  2271. rwco->qiov->size, rwco->qiov,
  2272. rwco->flags);
  2273. } else {
  2274. rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
  2275. rwco->qiov->size, rwco->qiov,
  2276. rwco->flags);
  2277. }
  2278. }
  2279. /*
  2280. * Process a vectored synchronous request using coroutines
  2281. */
  2282. static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
  2283. QEMUIOVector *qiov, bool is_write,
  2284. BdrvRequestFlags flags)
  2285. {
  2286. Coroutine *co;
  2287. RwCo rwco = {
  2288. .bs = bs,
  2289. .offset = offset,
  2290. .qiov = qiov,
  2291. .is_write = is_write,
  2292. .ret = NOT_DONE,
  2293. .flags = flags,
  2294. };
  2295. /**
  2296. * In sync call context, when the vcpu is blocked, this throttling timer
  2297. * will not fire; so the I/O throttling function has to be disabled here
  2298. * if it has been enabled.
  2299. */
  2300. if (bs->io_limits_enabled) {
  2301. fprintf(stderr, "Disabling I/O throttling on '%s' due "
  2302. "to synchronous I/O.\n", bdrv_get_device_name(bs));
  2303. bdrv_io_limits_disable(bs);
  2304. }
  2305. if (qemu_in_coroutine()) {
  2306. /* Fast-path if already in coroutine context */
  2307. bdrv_rw_co_entry(&rwco);
  2308. } else {
  2309. co = qemu_coroutine_create(bdrv_rw_co_entry);
  2310. qemu_coroutine_enter(co, &rwco);
  2311. while (rwco.ret == NOT_DONE) {
  2312. qemu_aio_wait();
  2313. }
  2314. }
  2315. return rwco.ret;
  2316. }
  2317. /*
  2318. * Process a synchronous request using coroutines
  2319. */
  2320. static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
  2321. int nb_sectors, bool is_write, BdrvRequestFlags flags)
  2322. {
  2323. QEMUIOVector qiov;
  2324. struct iovec iov = {
  2325. .iov_base = (void *)buf,
  2326. .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
  2327. };
  2328. qemu_iovec_init_external(&qiov, &iov, 1);
  2329. return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
  2330. &qiov, is_write, flags);
  2331. }
  2332. /* return < 0 if error. See bdrv_write() for the return codes */
  2333. int bdrv_read(BlockDriverState *bs, int64_t sector_num,
  2334. uint8_t *buf, int nb_sectors)
  2335. {
  2336. return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
  2337. }
  2338. /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
  2339. int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
  2340. uint8_t *buf, int nb_sectors)
  2341. {
  2342. bool enabled;
  2343. int ret;
  2344. enabled = bs->io_limits_enabled;
  2345. bs->io_limits_enabled = false;
  2346. ret = bdrv_read(bs, sector_num, buf, nb_sectors);
  2347. bs->io_limits_enabled = enabled;
  2348. return ret;
  2349. }
  2350. /* Return < 0 if error. Important errors are:
  2351. -EIO generic I/O error (may happen for all errors)
  2352. -ENOMEDIUM No media inserted.
  2353. -EINVAL Invalid sector number or nb_sectors
  2354. -EACCES Trying to write a read-only device
  2355. */
  2356. int bdrv_write(BlockDriverState *bs, int64_t sector_num,
  2357. const uint8_t *buf, int nb_sectors)
  2358. {
  2359. return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
  2360. }
  2361. int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
  2362. int nb_sectors, BdrvRequestFlags flags)
  2363. {
  2364. return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
  2365. BDRV_REQ_ZERO_WRITE | flags);
  2366. }
  2367. /*
  2368. * Completely zero out a block device with the help of bdrv_write_zeroes.
  2369. * The operation is sped up by checking the block status and only writing
  2370. * zeroes to the device if they currently do not return zeroes. Optional
  2371. * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
  2372. *
  2373. * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
  2374. */
  2375. int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
  2376. {
  2377. int64_t target_size = bdrv_getlength(bs) / BDRV_SECTOR_SIZE;
  2378. int64_t ret, nb_sectors, sector_num = 0;
  2379. int n;
  2380. for (;;) {
  2381. nb_sectors = target_size - sector_num;
  2382. if (nb_sectors <= 0) {
  2383. return 0;
  2384. }
  2385. if (nb_sectors > INT_MAX) {
  2386. nb_sectors = INT_MAX;
  2387. }
  2388. ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
  2389. if (ret < 0) {
  2390. error_report("error getting block status at sector %" PRId64 ": %s",
  2391. sector_num, strerror(-ret));
  2392. return ret;
  2393. }
  2394. if (ret & BDRV_BLOCK_ZERO) {
  2395. sector_num += n;
  2396. continue;
  2397. }
  2398. ret = bdrv_write_zeroes(bs, sector_num, n, flags);
  2399. if (ret < 0) {
  2400. error_report("error writing zeroes at sector %" PRId64 ": %s",
  2401. sector_num, strerror(-ret));
  2402. return ret;
  2403. }
  2404. sector_num += n;
  2405. }
  2406. }
  2407. int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
  2408. {
  2409. QEMUIOVector qiov;
  2410. struct iovec iov = {
  2411. .iov_base = (void *)buf,
  2412. .iov_len = bytes,
  2413. };
  2414. int ret;
  2415. if (bytes < 0) {
  2416. return -EINVAL;
  2417. }
  2418. qemu_iovec_init_external(&qiov, &iov, 1);
  2419. ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
  2420. if (ret < 0) {
  2421. return ret;
  2422. }
  2423. return bytes;
  2424. }
  2425. int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
  2426. {
  2427. int ret;
  2428. ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
  2429. if (ret < 0) {
  2430. return ret;
  2431. }
  2432. return qiov->size;
  2433. }
  2434. int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
  2435. const void *buf, int bytes)
  2436. {
  2437. QEMUIOVector qiov;
  2438. struct iovec iov = {
  2439. .iov_base = (void *) buf,
  2440. .iov_len = bytes,
  2441. };
  2442. if (bytes < 0) {
  2443. return -EINVAL;
  2444. }
  2445. qemu_iovec_init_external(&qiov, &iov, 1);
  2446. return bdrv_pwritev(bs, offset, &qiov);
  2447. }
  2448. /*
  2449. * Writes to the file and ensures that no writes are reordered across this
  2450. * request (acts as a barrier)
  2451. *
  2452. * Returns 0 on success, -errno in error cases.
  2453. */
  2454. int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
  2455. const void *buf, int count)
  2456. {
  2457. int ret;
  2458. ret = bdrv_pwrite(bs, offset, buf, count);
  2459. if (ret < 0) {
  2460. return ret;
  2461. }
  2462. /* No flush needed for cache modes that already do it */
  2463. if (bs->enable_write_cache) {
  2464. bdrv_flush(bs);
  2465. }
  2466. return 0;
  2467. }
  2468. static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
  2469. int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
  2470. {
  2471. /* Perform I/O through a temporary buffer so that users who scribble over
  2472. * their read buffer while the operation is in progress do not end up
  2473. * modifying the image file. This is critical for zero-copy guest I/O
  2474. * where anything might happen inside guest memory.
  2475. */
  2476. void *bounce_buffer;
  2477. BlockDriver *drv = bs->drv;
  2478. struct iovec iov;
  2479. QEMUIOVector bounce_qiov;
  2480. int64_t cluster_sector_num;
  2481. int cluster_nb_sectors;
  2482. size_t skip_bytes;
  2483. int ret;
  2484. /* Cover entire cluster so no additional backing file I/O is required when
  2485. * allocating cluster in the image file.
  2486. */
  2487. bdrv_round_to_clusters(bs, sector_num, nb_sectors,
  2488. &cluster_sector_num, &cluster_nb_sectors);
  2489. trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
  2490. cluster_sector_num, cluster_nb_sectors);
  2491. iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
  2492. iov.iov_base = bounce_buffer = qemu_blockalign(bs, iov.iov_len);
  2493. qemu_iovec_init_external(&bounce_qiov, &iov, 1);
  2494. ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
  2495. &bounce_qiov);
  2496. if (ret < 0) {
  2497. goto err;
  2498. }
  2499. if (drv->bdrv_co_write_zeroes &&
  2500. buffer_is_zero(bounce_buffer, iov.iov_len)) {
  2501. ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
  2502. cluster_nb_sectors, 0);
  2503. } else {
  2504. /* This does not change the data on the disk, it is not necessary
  2505. * to flush even in cache=writethrough mode.
  2506. */
  2507. ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
  2508. &bounce_qiov);
  2509. }
  2510. if (ret < 0) {
  2511. /* It might be okay to ignore write errors for guest requests. If this
  2512. * is a deliberate copy-on-read then we don't want to ignore the error.
  2513. * Simply report it in all cases.
  2514. */
  2515. goto err;
  2516. }
  2517. skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
  2518. qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
  2519. nb_sectors * BDRV_SECTOR_SIZE);
  2520. err:
  2521. qemu_vfree(bounce_buffer);
  2522. return ret;
  2523. }
  2524. /*
  2525. * Forwards an already correctly aligned request to the BlockDriver. This
  2526. * handles copy on read and zeroing after EOF; any other features must be
  2527. * implemented by the caller.
  2528. */
  2529. static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
  2530. BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
  2531. int64_t align, QEMUIOVector *qiov, int flags)
  2532. {
  2533. BlockDriver *drv = bs->drv;
  2534. int ret;
  2535. int64_t sector_num = offset >> BDRV_SECTOR_BITS;
  2536. unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
  2537. assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
  2538. assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
  2539. /* Handle Copy on Read and associated serialisation */
  2540. if (flags & BDRV_REQ_COPY_ON_READ) {
  2541. /* If we touch the same cluster it counts as an overlap. This
  2542. * guarantees that allocating writes will be serialized and not race
  2543. * with each other for the same cluster. For example, in copy-on-read
  2544. * it ensures that the CoR read and write operations are atomic and
  2545. * guest writes cannot interleave between them. */
  2546. mark_request_serialising(req, bdrv_get_cluster_size(bs));
  2547. }
  2548. wait_serialising_requests(req);
  2549. if (flags & BDRV_REQ_COPY_ON_READ) {
  2550. int pnum;
  2551. ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
  2552. if (ret < 0) {
  2553. goto out;
  2554. }
  2555. if (!ret || pnum != nb_sectors) {
  2556. ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
  2557. goto out;
  2558. }
  2559. }
  2560. /* Forward the request to the BlockDriver */
  2561. if (!(bs->zero_beyond_eof && bs->growable)) {
  2562. ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
  2563. } else {
  2564. /* Read zeros after EOF of growable BDSes */
  2565. int64_t len, total_sectors, max_nb_sectors;
  2566. len = bdrv_getlength(bs);
  2567. if (len < 0) {
  2568. ret = len;
  2569. goto out;
  2570. }
  2571. total_sectors = DIV_ROUND_UP(len, BDRV_SECTOR_SIZE);
  2572. max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
  2573. align >> BDRV_SECTOR_BITS);
  2574. if (max_nb_sectors > 0) {
  2575. ret = drv->bdrv_co_readv(bs, sector_num,
  2576. MIN(nb_sectors, max_nb_sectors), qiov);
  2577. } else {
  2578. ret = 0;
  2579. }
  2580. /* Reading beyond end of file is supposed to produce zeroes */
  2581. if (ret == 0 && total_sectors < sector_num + nb_sectors) {
  2582. uint64_t offset = MAX(0, total_sectors - sector_num);
  2583. uint64_t bytes = (sector_num + nb_sectors - offset) *
  2584. BDRV_SECTOR_SIZE;
  2585. qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
  2586. }
  2587. }
  2588. out:
  2589. return ret;
  2590. }
  2591. /*
  2592. * Handle a read request in coroutine context
  2593. */
  2594. static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
  2595. int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
  2596. BdrvRequestFlags flags)
  2597. {
  2598. BlockDriver *drv = bs->drv;
  2599. BdrvTrackedRequest req;
  2600. /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
  2601. uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
  2602. uint8_t *head_buf = NULL;
  2603. uint8_t *tail_buf = NULL;
  2604. QEMUIOVector local_qiov;
  2605. bool use_local_qiov = false;
  2606. int ret;
  2607. if (!drv) {
  2608. return -ENOMEDIUM;
  2609. }
  2610. if (bdrv_check_byte_request(bs, offset, bytes)) {
  2611. return -EIO;
  2612. }
  2613. if (bs->copy_on_read) {
  2614. flags |= BDRV_REQ_COPY_ON_READ;
  2615. }
  2616. /* throttling disk I/O */
  2617. if (bs->io_limits_enabled) {
  2618. bdrv_io_limits_intercept(bs, bytes, false);
  2619. }
  2620. /* Align read if necessary by padding qiov */
  2621. if (offset & (align - 1)) {
  2622. head_buf = qemu_blockalign(bs, align);
  2623. qemu_iovec_init(&local_qiov, qiov->niov + 2);
  2624. qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
  2625. qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
  2626. use_local_qiov = true;
  2627. bytes += offset & (align - 1);
  2628. offset = offset & ~(align - 1);
  2629. }
  2630. if ((offset + bytes) & (align - 1)) {
  2631. if (!use_local_qiov) {
  2632. qemu_iovec_init(&local_qiov, qiov->niov + 1);
  2633. qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
  2634. use_local_qiov = true;
  2635. }
  2636. tail_buf = qemu_blockalign(bs, align);
  2637. qemu_iovec_add(&local_qiov, tail_buf,
  2638. align - ((offset + bytes) & (align - 1)));
  2639. bytes = ROUND_UP(bytes, align);
  2640. }
  2641. tracked_request_begin(&req, bs, offset, bytes, false);
  2642. ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
  2643. use_local_qiov ? &local_qiov : qiov,
  2644. flags);
  2645. tracked_request_end(&req);
  2646. if (use_local_qiov) {
  2647. qemu_iovec_destroy(&local_qiov);
  2648. qemu_vfree(head_buf);
  2649. qemu_vfree(tail_buf);
  2650. }
  2651. return ret;
  2652. }
  2653. static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
  2654. int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
  2655. BdrvRequestFlags flags)
  2656. {
  2657. if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
  2658. return -EINVAL;
  2659. }
  2660. return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
  2661. nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
  2662. }
  2663. int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
  2664. int nb_sectors, QEMUIOVector *qiov)
  2665. {
  2666. trace_bdrv_co_readv(bs, sector_num, nb_sectors);
  2667. return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
  2668. }
  2669. int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
  2670. int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
  2671. {
  2672. trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
  2673. return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
  2674. BDRV_REQ_COPY_ON_READ);
  2675. }
  2676. /* if no limit is specified in the BlockLimits use a default
  2677. * of 32768 512-byte sectors (16 MiB) per request.
  2678. */
  2679. #define MAX_WRITE_ZEROES_DEFAULT 32768
  2680. static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
  2681. int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
  2682. {
  2683. BlockDriver *drv = bs->drv;
  2684. QEMUIOVector qiov;
  2685. struct iovec iov = {0};
  2686. int ret = 0;
  2687. int max_write_zeroes = bs->bl.max_write_zeroes ?
  2688. bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
  2689. while (nb_sectors > 0 && !ret) {
  2690. int num = nb_sectors;
  2691. /* Align request. Block drivers can expect the "bulk" of the request
  2692. * to be aligned.
  2693. */
  2694. if (bs->bl.write_zeroes_alignment
  2695. && num > bs->bl.write_zeroes_alignment) {
  2696. if (sector_num % bs->bl.write_zeroes_alignment != 0) {
  2697. /* Make a small request up to the first aligned sector. */
  2698. num = bs->bl.write_zeroes_alignment;
  2699. num -= sector_num % bs->bl.write_zeroes_alignment;
  2700. } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
  2701. /* Shorten the request to the last aligned sector. num cannot
  2702. * underflow because num > bs->bl.write_zeroes_alignment.
  2703. */
  2704. num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
  2705. }
  2706. }
  2707. /* limit request size */
  2708. if (num > max_write_zeroes) {
  2709. num = max_write_zeroes;
  2710. }
  2711. ret = -ENOTSUP;
  2712. /* First try the efficient write zeroes operation */
  2713. if (drv->bdrv_co_write_zeroes) {
  2714. ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
  2715. }
  2716. if (ret == -ENOTSUP) {
  2717. /* Fall back to bounce buffer if write zeroes is unsupported */
  2718. iov.iov_len = num * BDRV_SECTOR_SIZE;
  2719. if (iov.iov_base == NULL) {
  2720. iov.iov_base = qemu_blockalign(bs, num * BDRV_SECTOR_SIZE);
  2721. memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
  2722. }
  2723. qemu_iovec_init_external(&qiov, &iov, 1);
  2724. ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
  2725. /* Keep bounce buffer around if it is big enough for all
  2726. * all future requests.
  2727. */
  2728. if (num < max_write_zeroes) {
  2729. qemu_vfree(iov.iov_base);
  2730. iov.iov_base = NULL;
  2731. }
  2732. }
  2733. sector_num += num;
  2734. nb_sectors -= num;
  2735. }
  2736. qemu_vfree(iov.iov_base);
  2737. return ret;
  2738. }
  2739. /*
  2740. * Forwards an already correctly aligned write request to the BlockDriver.
  2741. */
  2742. static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
  2743. BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
  2744. QEMUIOVector *qiov, int flags)
  2745. {
  2746. BlockDriver *drv = bs->drv;
  2747. bool waited;
  2748. int ret;
  2749. int64_t sector_num = offset >> BDRV_SECTOR_BITS;
  2750. unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
  2751. assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
  2752. assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
  2753. waited = wait_serialising_requests(req);
  2754. assert(!waited || !req->serialising);
  2755. assert(req->overlap_offset <= offset);
  2756. assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
  2757. ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
  2758. if (ret < 0) {
  2759. /* Do nothing, write notifier decided to fail this request */
  2760. } else if (flags & BDRV_REQ_ZERO_WRITE) {
  2761. BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
  2762. ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
  2763. } else {
  2764. BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
  2765. ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
  2766. }
  2767. BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
  2768. if (ret == 0 && !bs->enable_write_cache) {
  2769. ret = bdrv_co_flush(bs);
  2770. }
  2771. bdrv_set_dirty(bs, sector_num, nb_sectors);
  2772. if (bs->wr_highest_sector < sector_num + nb_sectors - 1) {
  2773. bs->wr_highest_sector = sector_num + nb_sectors - 1;
  2774. }
  2775. if (bs->growable && ret >= 0) {
  2776. bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
  2777. }
  2778. return ret;
  2779. }
  2780. /*
  2781. * Handle a write request in coroutine context
  2782. */
  2783. static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
  2784. int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
  2785. BdrvRequestFlags flags)
  2786. {
  2787. BdrvTrackedRequest req;
  2788. /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
  2789. uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
  2790. uint8_t *head_buf = NULL;
  2791. uint8_t *tail_buf = NULL;
  2792. QEMUIOVector local_qiov;
  2793. bool use_local_qiov = false;
  2794. int ret;
  2795. if (!bs->drv) {
  2796. return -ENOMEDIUM;
  2797. }
  2798. if (bs->read_only) {
  2799. return -EACCES;
  2800. }
  2801. if (bdrv_check_byte_request(bs, offset, bytes)) {
  2802. return -EIO;
  2803. }
  2804. /* throttling disk I/O */
  2805. if (bs->io_limits_enabled) {
  2806. bdrv_io_limits_intercept(bs, bytes, true);
  2807. }
  2808. /*
  2809. * Align write if necessary by performing a read-modify-write cycle.
  2810. * Pad qiov with the read parts and be sure to have a tracked request not
  2811. * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
  2812. */
  2813. tracked_request_begin(&req, bs, offset, bytes, true);
  2814. if (offset & (align - 1)) {
  2815. QEMUIOVector head_qiov;
  2816. struct iovec head_iov;
  2817. mark_request_serialising(&req, align);
  2818. wait_serialising_requests(&req);
  2819. head_buf = qemu_blockalign(bs, align);
  2820. head_iov = (struct iovec) {
  2821. .iov_base = head_buf,
  2822. .iov_len = align,
  2823. };
  2824. qemu_iovec_init_external(&head_qiov, &head_iov, 1);
  2825. BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
  2826. ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
  2827. align, &head_qiov, 0);
  2828. if (ret < 0) {
  2829. goto fail;
  2830. }
  2831. BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
  2832. qemu_iovec_init(&local_qiov, qiov->niov + 2);
  2833. qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
  2834. qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
  2835. use_local_qiov = true;
  2836. bytes += offset & (align - 1);
  2837. offset = offset & ~(align - 1);
  2838. }
  2839. if ((offset + bytes) & (align - 1)) {
  2840. QEMUIOVector tail_qiov;
  2841. struct iovec tail_iov;
  2842. size_t tail_bytes;
  2843. bool waited;
  2844. mark_request_serialising(&req, align);
  2845. waited = wait_serialising_requests(&req);
  2846. assert(!waited || !use_local_qiov);
  2847. tail_buf = qemu_blockalign(bs, align);
  2848. tail_iov = (struct iovec) {
  2849. .iov_base = tail_buf,
  2850. .iov_len = align,
  2851. };
  2852. qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
  2853. BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
  2854. ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
  2855. align, &tail_qiov, 0);
  2856. if (ret < 0) {
  2857. goto fail;
  2858. }
  2859. BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
  2860. if (!use_local_qiov) {
  2861. qemu_iovec_init(&local_qiov, qiov->niov + 1);
  2862. qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
  2863. use_local_qiov = true;
  2864. }
  2865. tail_bytes = (offset + bytes) & (align - 1);
  2866. qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
  2867. bytes = ROUND_UP(bytes, align);
  2868. }
  2869. ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
  2870. use_local_qiov ? &local_qiov : qiov,
  2871. flags);
  2872. fail:
  2873. tracked_request_end(&req);
  2874. if (use_local_qiov) {
  2875. qemu_iovec_destroy(&local_qiov);
  2876. }
  2877. qemu_vfree(head_buf);
  2878. qemu_vfree(tail_buf);
  2879. return ret;
  2880. }
  2881. static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
  2882. int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
  2883. BdrvRequestFlags flags)
  2884. {
  2885. if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
  2886. return -EINVAL;
  2887. }
  2888. return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
  2889. nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
  2890. }
  2891. int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
  2892. int nb_sectors, QEMUIOVector *qiov)
  2893. {
  2894. trace_bdrv_co_writev(bs, sector_num, nb_sectors);
  2895. return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
  2896. }
  2897. int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
  2898. int64_t sector_num, int nb_sectors,
  2899. BdrvRequestFlags flags)
  2900. {
  2901. trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
  2902. if (!(bs->open_flags & BDRV_O_UNMAP)) {
  2903. flags &= ~BDRV_REQ_MAY_UNMAP;
  2904. }
  2905. return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
  2906. BDRV_REQ_ZERO_WRITE | flags);
  2907. }
  2908. /**
  2909. * Truncate file to 'offset' bytes (needed only for file protocols)
  2910. */
  2911. int bdrv_truncate(BlockDriverState *bs, int64_t offset)
  2912. {
  2913. BlockDriver *drv = bs->drv;
  2914. int ret;
  2915. if (!drv)
  2916. return -ENOMEDIUM;
  2917. if (!drv->bdrv_truncate)
  2918. return -ENOTSUP;
  2919. if (bs->read_only)
  2920. return -EACCES;
  2921. if (bdrv_in_use(bs))
  2922. return -EBUSY;
  2923. ret = drv->bdrv_truncate(bs, offset);
  2924. if (ret == 0) {
  2925. ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
  2926. bdrv_dev_resize_cb(bs);
  2927. }
  2928. return ret;
  2929. }
  2930. /**
  2931. * Length of a allocated file in bytes. Sparse files are counted by actual
  2932. * allocated space. Return < 0 if error or unknown.
  2933. */
  2934. int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
  2935. {
  2936. BlockDriver *drv = bs->drv;
  2937. if (!drv) {
  2938. return -ENOMEDIUM;
  2939. }
  2940. if (drv->bdrv_get_allocated_file_size) {
  2941. return drv->bdrv_get_allocated_file_size(bs);
  2942. }
  2943. if (bs->file) {
  2944. return bdrv_get_allocated_file_size(bs->file);
  2945. }
  2946. return -ENOTSUP;
  2947. }
  2948. /**
  2949. * Length of a file in bytes. Return < 0 if error or unknown.
  2950. */
  2951. int64_t bdrv_getlength(BlockDriverState *bs)
  2952. {
  2953. BlockDriver *drv = bs->drv;
  2954. if (!drv)
  2955. return -ENOMEDIUM;
  2956. if (drv->has_variable_length) {
  2957. int ret = refresh_total_sectors(bs, bs->total_sectors);
  2958. if (ret < 0) {
  2959. return ret;
  2960. }
  2961. }
  2962. return bs->total_sectors * BDRV_SECTOR_SIZE;
  2963. }
  2964. /* return 0 as number of sectors if no device present or error */
  2965. void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
  2966. {
  2967. int64_t length;
  2968. length = bdrv_getlength(bs);
  2969. if (length < 0)
  2970. length = 0;
  2971. else
  2972. length = length >> BDRV_SECTOR_BITS;
  2973. *nb_sectors_ptr = length;
  2974. }
  2975. void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
  2976. BlockdevOnError on_write_error)
  2977. {
  2978. bs->on_read_error = on_read_error;
  2979. bs->on_write_error = on_write_error;
  2980. }
  2981. BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
  2982. {
  2983. return is_read ? bs->on_read_error : bs->on_write_error;
  2984. }
  2985. BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
  2986. {
  2987. BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
  2988. switch (on_err) {
  2989. case BLOCKDEV_ON_ERROR_ENOSPC:
  2990. return (error == ENOSPC) ? BDRV_ACTION_STOP : BDRV_ACTION_REPORT;
  2991. case BLOCKDEV_ON_ERROR_STOP:
  2992. return BDRV_ACTION_STOP;
  2993. case BLOCKDEV_ON_ERROR_REPORT:
  2994. return BDRV_ACTION_REPORT;
  2995. case BLOCKDEV_ON_ERROR_IGNORE:
  2996. return BDRV_ACTION_IGNORE;
  2997. default:
  2998. abort();
  2999. }
  3000. }
  3001. /* This is done by device models because, while the block layer knows
  3002. * about the error, it does not know whether an operation comes from
  3003. * the device or the block layer (from a job, for example).
  3004. */
  3005. void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
  3006. bool is_read, int error)
  3007. {
  3008. assert(error >= 0);
  3009. bdrv_emit_qmp_error_event(bs, QEVENT_BLOCK_IO_ERROR, action, is_read);
  3010. if (action == BDRV_ACTION_STOP) {
  3011. vm_stop(RUN_STATE_IO_ERROR);
  3012. bdrv_iostatus_set_err(bs, error);
  3013. }
  3014. }
  3015. int bdrv_is_read_only(BlockDriverState *bs)
  3016. {
  3017. return bs->read_only;
  3018. }
  3019. int bdrv_is_sg(BlockDriverState *bs)
  3020. {
  3021. return bs->sg;
  3022. }
  3023. int bdrv_enable_write_cache(BlockDriverState *bs)
  3024. {
  3025. return bs->enable_write_cache;
  3026. }
  3027. void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
  3028. {
  3029. bs->enable_write_cache = wce;
  3030. /* so a reopen() will preserve wce */
  3031. if (wce) {
  3032. bs->open_flags |= BDRV_O_CACHE_WB;
  3033. } else {
  3034. bs->open_flags &= ~BDRV_O_CACHE_WB;
  3035. }
  3036. }
  3037. int bdrv_is_encrypted(BlockDriverState *bs)
  3038. {
  3039. if (bs->backing_hd && bs->backing_hd->encrypted)
  3040. return 1;
  3041. return bs->encrypted;
  3042. }
  3043. int bdrv_key_required(BlockDriverState *bs)
  3044. {
  3045. BlockDriverState *backing_hd = bs->backing_hd;
  3046. if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
  3047. return 1;
  3048. return (bs->encrypted && !bs->valid_key);
  3049. }
  3050. int bdrv_set_key(BlockDriverState *bs, const char *key)
  3051. {
  3052. int ret;
  3053. if (bs->backing_hd && bs->backing_hd->encrypted) {
  3054. ret = bdrv_set_key(bs->backing_hd, key);
  3055. if (ret < 0)
  3056. return ret;
  3057. if (!bs->encrypted)
  3058. return 0;
  3059. }
  3060. if (!bs->encrypted) {
  3061. return -EINVAL;
  3062. } else if (!bs->drv || !bs->drv->bdrv_set_key) {
  3063. return -ENOMEDIUM;
  3064. }
  3065. ret = bs->drv->bdrv_set_key(bs, key);
  3066. if (ret < 0) {
  3067. bs->valid_key = 0;
  3068. } else if (!bs->valid_key) {
  3069. bs->valid_key = 1;
  3070. /* call the change callback now, we skipped it on open */
  3071. bdrv_dev_change_media_cb(bs, true);
  3072. }
  3073. return ret;
  3074. }
  3075. const char *bdrv_get_format_name(BlockDriverState *bs)
  3076. {
  3077. return bs->drv ? bs->drv->format_name : NULL;
  3078. }
  3079. void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
  3080. void *opaque)
  3081. {
  3082. BlockDriver *drv;
  3083. QLIST_FOREACH(drv, &bdrv_drivers, list) {
  3084. it(opaque, drv->format_name);
  3085. }
  3086. }
  3087. /* This function is to find block backend bs */
  3088. BlockDriverState *bdrv_find(const char *name)
  3089. {
  3090. BlockDriverState *bs;
  3091. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  3092. if (!strcmp(name, bs->device_name)) {
  3093. return bs;
  3094. }
  3095. }
  3096. return NULL;
  3097. }
  3098. /* This function is to find a node in the bs graph */
  3099. BlockDriverState *bdrv_find_node(const char *node_name)
  3100. {
  3101. BlockDriverState *bs;
  3102. assert(node_name);
  3103. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  3104. if (!strcmp(node_name, bs->node_name)) {
  3105. return bs;
  3106. }
  3107. }
  3108. return NULL;
  3109. }
  3110. /* Put this QMP function here so it can access the static graph_bdrv_states. */
  3111. BlockDeviceInfoList *bdrv_named_nodes_list(void)
  3112. {
  3113. BlockDeviceInfoList *list, *entry;
  3114. BlockDriverState *bs;
  3115. list = NULL;
  3116. QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
  3117. entry = g_malloc0(sizeof(*entry));
  3118. entry->value = bdrv_block_device_info(bs);
  3119. entry->next = list;
  3120. list = entry;
  3121. }
  3122. return list;
  3123. }
  3124. BlockDriverState *bdrv_lookup_bs(const char *device,
  3125. const char *node_name,
  3126. Error **errp)
  3127. {
  3128. BlockDriverState *bs = NULL;
  3129. if (device) {
  3130. bs = bdrv_find(device);
  3131. if (bs) {
  3132. return bs;
  3133. }
  3134. }
  3135. if (node_name) {
  3136. bs = bdrv_find_node(node_name);
  3137. if (bs) {
  3138. return bs;
  3139. }
  3140. }
  3141. error_setg(errp, "Cannot find device=%s nor node_name=%s",
  3142. device ? device : "",
  3143. node_name ? node_name : "");
  3144. return NULL;
  3145. }
  3146. BlockDriverState *bdrv_next(BlockDriverState *bs)
  3147. {
  3148. if (!bs) {
  3149. return QTAILQ_FIRST(&bdrv_states);
  3150. }
  3151. return QTAILQ_NEXT(bs, device_list);
  3152. }
  3153. void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
  3154. {
  3155. BlockDriverState *bs;
  3156. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  3157. it(opaque, bs);
  3158. }
  3159. }
  3160. const char *bdrv_get_device_name(BlockDriverState *bs)
  3161. {
  3162. return bs->device_name;
  3163. }
  3164. int bdrv_get_flags(BlockDriverState *bs)
  3165. {
  3166. return bs->open_flags;
  3167. }
  3168. int bdrv_flush_all(void)
  3169. {
  3170. BlockDriverState *bs;
  3171. int result = 0;
  3172. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  3173. int ret = bdrv_flush(bs);
  3174. if (ret < 0 && !result) {
  3175. result = ret;
  3176. }
  3177. }
  3178. return result;
  3179. }
  3180. int bdrv_has_zero_init_1(BlockDriverState *bs)
  3181. {
  3182. return 1;
  3183. }
  3184. int bdrv_has_zero_init(BlockDriverState *bs)
  3185. {
  3186. assert(bs->drv);
  3187. /* If BS is a copy on write image, it is initialized to
  3188. the contents of the base image, which may not be zeroes. */
  3189. if (bs->backing_hd) {
  3190. return 0;
  3191. }
  3192. if (bs->drv->bdrv_has_zero_init) {
  3193. return bs->drv->bdrv_has_zero_init(bs);
  3194. }
  3195. /* safe default */
  3196. return 0;
  3197. }
  3198. bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
  3199. {
  3200. BlockDriverInfo bdi;
  3201. if (bs->backing_hd) {
  3202. return false;
  3203. }
  3204. if (bdrv_get_info(bs, &bdi) == 0) {
  3205. return bdi.unallocated_blocks_are_zero;
  3206. }
  3207. return false;
  3208. }
  3209. bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
  3210. {
  3211. BlockDriverInfo bdi;
  3212. if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
  3213. return false;
  3214. }
  3215. if (bdrv_get_info(bs, &bdi) == 0) {
  3216. return bdi.can_write_zeroes_with_unmap;
  3217. }
  3218. return false;
  3219. }
  3220. typedef struct BdrvCoGetBlockStatusData {
  3221. BlockDriverState *bs;
  3222. BlockDriverState *base;
  3223. int64_t sector_num;
  3224. int nb_sectors;
  3225. int *pnum;
  3226. int64_t ret;
  3227. bool done;
  3228. } BdrvCoGetBlockStatusData;
  3229. /*
  3230. * Returns true iff the specified sector is present in the disk image. Drivers
  3231. * not implementing the functionality are assumed to not support backing files,
  3232. * hence all their sectors are reported as allocated.
  3233. *
  3234. * If 'sector_num' is beyond the end of the disk image the return value is 0
  3235. * and 'pnum' is set to 0.
  3236. *
  3237. * 'pnum' is set to the number of sectors (including and immediately following
  3238. * the specified sector) that are known to be in the same
  3239. * allocated/unallocated state.
  3240. *
  3241. * 'nb_sectors' is the max value 'pnum' should be set to. If nb_sectors goes
  3242. * beyond the end of the disk image it will be clamped.
  3243. */
  3244. static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
  3245. int64_t sector_num,
  3246. int nb_sectors, int *pnum)
  3247. {
  3248. int64_t length;
  3249. int64_t n;
  3250. int64_t ret, ret2;
  3251. length = bdrv_getlength(bs);
  3252. if (length < 0) {
  3253. return length;
  3254. }
  3255. if (sector_num >= (length >> BDRV_SECTOR_BITS)) {
  3256. *pnum = 0;
  3257. return 0;
  3258. }
  3259. n = bs->total_sectors - sector_num;
  3260. if (n < nb_sectors) {
  3261. nb_sectors = n;
  3262. }
  3263. if (!bs->drv->bdrv_co_get_block_status) {
  3264. *pnum = nb_sectors;
  3265. ret = BDRV_BLOCK_DATA;
  3266. if (bs->drv->protocol_name) {
  3267. ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
  3268. }
  3269. return ret;
  3270. }
  3271. ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
  3272. if (ret < 0) {
  3273. *pnum = 0;
  3274. return ret;
  3275. }
  3276. if (ret & BDRV_BLOCK_RAW) {
  3277. assert(ret & BDRV_BLOCK_OFFSET_VALID);
  3278. return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
  3279. *pnum, pnum);
  3280. }
  3281. if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
  3282. if (bdrv_unallocated_blocks_are_zero(bs)) {
  3283. ret |= BDRV_BLOCK_ZERO;
  3284. } else if (bs->backing_hd) {
  3285. BlockDriverState *bs2 = bs->backing_hd;
  3286. int64_t length2 = bdrv_getlength(bs2);
  3287. if (length2 >= 0 && sector_num >= (length2 >> BDRV_SECTOR_BITS)) {
  3288. ret |= BDRV_BLOCK_ZERO;
  3289. }
  3290. }
  3291. }
  3292. if (bs->file &&
  3293. (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
  3294. (ret & BDRV_BLOCK_OFFSET_VALID)) {
  3295. ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
  3296. *pnum, pnum);
  3297. if (ret2 >= 0) {
  3298. /* Ignore errors. This is just providing extra information, it
  3299. * is useful but not necessary.
  3300. */
  3301. ret |= (ret2 & BDRV_BLOCK_ZERO);
  3302. }
  3303. }
  3304. return ret;
  3305. }
  3306. /* Coroutine wrapper for bdrv_get_block_status() */
  3307. static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
  3308. {
  3309. BdrvCoGetBlockStatusData *data = opaque;
  3310. BlockDriverState *bs = data->bs;
  3311. data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
  3312. data->pnum);
  3313. data->done = true;
  3314. }
  3315. /*
  3316. * Synchronous wrapper around bdrv_co_get_block_status().
  3317. *
  3318. * See bdrv_co_get_block_status() for details.
  3319. */
  3320. int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
  3321. int nb_sectors, int *pnum)
  3322. {
  3323. Coroutine *co;
  3324. BdrvCoGetBlockStatusData data = {
  3325. .bs = bs,
  3326. .sector_num = sector_num,
  3327. .nb_sectors = nb_sectors,
  3328. .pnum = pnum,
  3329. .done = false,
  3330. };
  3331. if (qemu_in_coroutine()) {
  3332. /* Fast-path if already in coroutine context */
  3333. bdrv_get_block_status_co_entry(&data);
  3334. } else {
  3335. co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
  3336. qemu_coroutine_enter(co, &data);
  3337. while (!data.done) {
  3338. qemu_aio_wait();
  3339. }
  3340. }
  3341. return data.ret;
  3342. }
  3343. int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
  3344. int nb_sectors, int *pnum)
  3345. {
  3346. int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
  3347. if (ret < 0) {
  3348. return ret;
  3349. }
  3350. return
  3351. (ret & BDRV_BLOCK_DATA) ||
  3352. ((ret & BDRV_BLOCK_ZERO) && !bdrv_has_zero_init(bs));
  3353. }
  3354. /*
  3355. * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
  3356. *
  3357. * Return true if the given sector is allocated in any image between
  3358. * BASE and TOP (inclusive). BASE can be NULL to check if the given
  3359. * sector is allocated in any image of the chain. Return false otherwise.
  3360. *
  3361. * 'pnum' is set to the number of sectors (including and immediately following
  3362. * the specified sector) that are known to be in the same
  3363. * allocated/unallocated state.
  3364. *
  3365. */
  3366. int bdrv_is_allocated_above(BlockDriverState *top,
  3367. BlockDriverState *base,
  3368. int64_t sector_num,
  3369. int nb_sectors, int *pnum)
  3370. {
  3371. BlockDriverState *intermediate;
  3372. int ret, n = nb_sectors;
  3373. intermediate = top;
  3374. while (intermediate && intermediate != base) {
  3375. int pnum_inter;
  3376. ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
  3377. &pnum_inter);
  3378. if (ret < 0) {
  3379. return ret;
  3380. } else if (ret) {
  3381. *pnum = pnum_inter;
  3382. return 1;
  3383. }
  3384. /*
  3385. * [sector_num, nb_sectors] is unallocated on top but intermediate
  3386. * might have
  3387. *
  3388. * [sector_num+x, nr_sectors] allocated.
  3389. */
  3390. if (n > pnum_inter &&
  3391. (intermediate == top ||
  3392. sector_num + pnum_inter < intermediate->total_sectors)) {
  3393. n = pnum_inter;
  3394. }
  3395. intermediate = intermediate->backing_hd;
  3396. }
  3397. *pnum = n;
  3398. return 0;
  3399. }
  3400. const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
  3401. {
  3402. if (bs->backing_hd && bs->backing_hd->encrypted)
  3403. return bs->backing_file;
  3404. else if (bs->encrypted)
  3405. return bs->filename;
  3406. else
  3407. return NULL;
  3408. }
  3409. void bdrv_get_backing_filename(BlockDriverState *bs,
  3410. char *filename, int filename_size)
  3411. {
  3412. pstrcpy(filename, filename_size, bs->backing_file);
  3413. }
  3414. int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
  3415. const uint8_t *buf, int nb_sectors)
  3416. {
  3417. BlockDriver *drv = bs->drv;
  3418. if (!drv)
  3419. return -ENOMEDIUM;
  3420. if (!drv->bdrv_write_compressed)
  3421. return -ENOTSUP;
  3422. if (bdrv_check_request(bs, sector_num, nb_sectors))
  3423. return -EIO;
  3424. assert(QLIST_EMPTY(&bs->dirty_bitmaps));
  3425. return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
  3426. }
  3427. int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
  3428. {
  3429. BlockDriver *drv = bs->drv;
  3430. if (!drv)
  3431. return -ENOMEDIUM;
  3432. if (!drv->bdrv_get_info)
  3433. return -ENOTSUP;
  3434. memset(bdi, 0, sizeof(*bdi));
  3435. return drv->bdrv_get_info(bs, bdi);
  3436. }
  3437. ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
  3438. {
  3439. BlockDriver *drv = bs->drv;
  3440. if (drv && drv->bdrv_get_specific_info) {
  3441. return drv->bdrv_get_specific_info(bs);
  3442. }
  3443. return NULL;
  3444. }
  3445. int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
  3446. int64_t pos, int size)
  3447. {
  3448. QEMUIOVector qiov;
  3449. struct iovec iov = {
  3450. .iov_base = (void *) buf,
  3451. .iov_len = size,
  3452. };
  3453. qemu_iovec_init_external(&qiov, &iov, 1);
  3454. return bdrv_writev_vmstate(bs, &qiov, pos);
  3455. }
  3456. int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
  3457. {
  3458. BlockDriver *drv = bs->drv;
  3459. if (!drv) {
  3460. return -ENOMEDIUM;
  3461. } else if (drv->bdrv_save_vmstate) {
  3462. return drv->bdrv_save_vmstate(bs, qiov, pos);
  3463. } else if (bs->file) {
  3464. return bdrv_writev_vmstate(bs->file, qiov, pos);
  3465. }
  3466. return -ENOTSUP;
  3467. }
  3468. int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
  3469. int64_t pos, int size)
  3470. {
  3471. BlockDriver *drv = bs->drv;
  3472. if (!drv)
  3473. return -ENOMEDIUM;
  3474. if (drv->bdrv_load_vmstate)
  3475. return drv->bdrv_load_vmstate(bs, buf, pos, size);
  3476. if (bs->file)
  3477. return bdrv_load_vmstate(bs->file, buf, pos, size);
  3478. return -ENOTSUP;
  3479. }
  3480. void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
  3481. {
  3482. if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
  3483. return;
  3484. }
  3485. bs->drv->bdrv_debug_event(bs, event);
  3486. }
  3487. int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
  3488. const char *tag)
  3489. {
  3490. while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
  3491. bs = bs->file;
  3492. }
  3493. if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
  3494. return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
  3495. }
  3496. return -ENOTSUP;
  3497. }
  3498. int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
  3499. {
  3500. while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
  3501. bs = bs->file;
  3502. }
  3503. if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
  3504. return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
  3505. }
  3506. return -ENOTSUP;
  3507. }
  3508. int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
  3509. {
  3510. while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
  3511. bs = bs->file;
  3512. }
  3513. if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
  3514. return bs->drv->bdrv_debug_resume(bs, tag);
  3515. }
  3516. return -ENOTSUP;
  3517. }
  3518. bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
  3519. {
  3520. while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
  3521. bs = bs->file;
  3522. }
  3523. if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
  3524. return bs->drv->bdrv_debug_is_suspended(bs, tag);
  3525. }
  3526. return false;
  3527. }
  3528. int bdrv_is_snapshot(BlockDriverState *bs)
  3529. {
  3530. return !!(bs->open_flags & BDRV_O_SNAPSHOT);
  3531. }
  3532. /* backing_file can either be relative, or absolute, or a protocol. If it is
  3533. * relative, it must be relative to the chain. So, passing in bs->filename
  3534. * from a BDS as backing_file should not be done, as that may be relative to
  3535. * the CWD rather than the chain. */
  3536. BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
  3537. const char *backing_file)
  3538. {
  3539. char *filename_full = NULL;
  3540. char *backing_file_full = NULL;
  3541. char *filename_tmp = NULL;
  3542. int is_protocol = 0;
  3543. BlockDriverState *curr_bs = NULL;
  3544. BlockDriverState *retval = NULL;
  3545. if (!bs || !bs->drv || !backing_file) {
  3546. return NULL;
  3547. }
  3548. filename_full = g_malloc(PATH_MAX);
  3549. backing_file_full = g_malloc(PATH_MAX);
  3550. filename_tmp = g_malloc(PATH_MAX);
  3551. is_protocol = path_has_protocol(backing_file);
  3552. for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
  3553. /* If either of the filename paths is actually a protocol, then
  3554. * compare unmodified paths; otherwise make paths relative */
  3555. if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
  3556. if (strcmp(backing_file, curr_bs->backing_file) == 0) {
  3557. retval = curr_bs->backing_hd;
  3558. break;
  3559. }
  3560. } else {
  3561. /* If not an absolute filename path, make it relative to the current
  3562. * image's filename path */
  3563. path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
  3564. backing_file);
  3565. /* We are going to compare absolute pathnames */
  3566. if (!realpath(filename_tmp, filename_full)) {
  3567. continue;
  3568. }
  3569. /* We need to make sure the backing filename we are comparing against
  3570. * is relative to the current image filename (or absolute) */
  3571. path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
  3572. curr_bs->backing_file);
  3573. if (!realpath(filename_tmp, backing_file_full)) {
  3574. continue;
  3575. }
  3576. if (strcmp(backing_file_full, filename_full) == 0) {
  3577. retval = curr_bs->backing_hd;
  3578. break;
  3579. }
  3580. }
  3581. }
  3582. g_free(filename_full);
  3583. g_free(backing_file_full);
  3584. g_free(filename_tmp);
  3585. return retval;
  3586. }
  3587. int bdrv_get_backing_file_depth(BlockDriverState *bs)
  3588. {
  3589. if (!bs->drv) {
  3590. return 0;
  3591. }
  3592. if (!bs->backing_hd) {
  3593. return 0;
  3594. }
  3595. return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
  3596. }
  3597. BlockDriverState *bdrv_find_base(BlockDriverState *bs)
  3598. {
  3599. BlockDriverState *curr_bs = NULL;
  3600. if (!bs) {
  3601. return NULL;
  3602. }
  3603. curr_bs = bs;
  3604. while (curr_bs->backing_hd) {
  3605. curr_bs = curr_bs->backing_hd;
  3606. }
  3607. return curr_bs;
  3608. }
  3609. /**************************************************************/
  3610. /* async I/Os */
  3611. BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
  3612. QEMUIOVector *qiov, int nb_sectors,
  3613. BlockDriverCompletionFunc *cb, void *opaque)
  3614. {
  3615. trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
  3616. return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
  3617. cb, opaque, false);
  3618. }
  3619. BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
  3620. QEMUIOVector *qiov, int nb_sectors,
  3621. BlockDriverCompletionFunc *cb, void *opaque)
  3622. {
  3623. trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
  3624. return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
  3625. cb, opaque, true);
  3626. }
  3627. BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
  3628. int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
  3629. BlockDriverCompletionFunc *cb, void *opaque)
  3630. {
  3631. trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
  3632. return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
  3633. BDRV_REQ_ZERO_WRITE | flags,
  3634. cb, opaque, true);
  3635. }
  3636. typedef struct MultiwriteCB {
  3637. int error;
  3638. int num_requests;
  3639. int num_callbacks;
  3640. struct {
  3641. BlockDriverCompletionFunc *cb;
  3642. void *opaque;
  3643. QEMUIOVector *free_qiov;
  3644. } callbacks[];
  3645. } MultiwriteCB;
  3646. static void multiwrite_user_cb(MultiwriteCB *mcb)
  3647. {
  3648. int i;
  3649. for (i = 0; i < mcb->num_callbacks; i++) {
  3650. mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
  3651. if (mcb->callbacks[i].free_qiov) {
  3652. qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
  3653. }
  3654. g_free(mcb->callbacks[i].free_qiov);
  3655. }
  3656. }
  3657. static void multiwrite_cb(void *opaque, int ret)
  3658. {
  3659. MultiwriteCB *mcb = opaque;
  3660. trace_multiwrite_cb(mcb, ret);
  3661. if (ret < 0 && !mcb->error) {
  3662. mcb->error = ret;
  3663. }
  3664. mcb->num_requests--;
  3665. if (mcb->num_requests == 0) {
  3666. multiwrite_user_cb(mcb);
  3667. g_free(mcb);
  3668. }
  3669. }
  3670. static int multiwrite_req_compare(const void *a, const void *b)
  3671. {
  3672. const BlockRequest *req1 = a, *req2 = b;
  3673. /*
  3674. * Note that we can't simply subtract req2->sector from req1->sector
  3675. * here as that could overflow the return value.
  3676. */
  3677. if (req1->sector > req2->sector) {
  3678. return 1;
  3679. } else if (req1->sector < req2->sector) {
  3680. return -1;
  3681. } else {
  3682. return 0;
  3683. }
  3684. }
  3685. /*
  3686. * Takes a bunch of requests and tries to merge them. Returns the number of
  3687. * requests that remain after merging.
  3688. */
  3689. static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
  3690. int num_reqs, MultiwriteCB *mcb)
  3691. {
  3692. int i, outidx;
  3693. // Sort requests by start sector
  3694. qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
  3695. // Check if adjacent requests touch the same clusters. If so, combine them,
  3696. // filling up gaps with zero sectors.
  3697. outidx = 0;
  3698. for (i = 1; i < num_reqs; i++) {
  3699. int merge = 0;
  3700. int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
  3701. // Handle exactly sequential writes and overlapping writes.
  3702. if (reqs[i].sector <= oldreq_last) {
  3703. merge = 1;
  3704. }
  3705. if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
  3706. merge = 0;
  3707. }
  3708. if (merge) {
  3709. size_t size;
  3710. QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
  3711. qemu_iovec_init(qiov,
  3712. reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
  3713. // Add the first request to the merged one. If the requests are
  3714. // overlapping, drop the last sectors of the first request.
  3715. size = (reqs[i].sector - reqs[outidx].sector) << 9;
  3716. qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
  3717. // We should need to add any zeros between the two requests
  3718. assert (reqs[i].sector <= oldreq_last);
  3719. // Add the second request
  3720. qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
  3721. reqs[outidx].nb_sectors = qiov->size >> 9;
  3722. reqs[outidx].qiov = qiov;
  3723. mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
  3724. } else {
  3725. outidx++;
  3726. reqs[outidx].sector = reqs[i].sector;
  3727. reqs[outidx].nb_sectors = reqs[i].nb_sectors;
  3728. reqs[outidx].qiov = reqs[i].qiov;
  3729. }
  3730. }
  3731. return outidx + 1;
  3732. }
  3733. /*
  3734. * Submit multiple AIO write requests at once.
  3735. *
  3736. * On success, the function returns 0 and all requests in the reqs array have
  3737. * been submitted. In error case this function returns -1, and any of the
  3738. * requests may or may not be submitted yet. In particular, this means that the
  3739. * callback will be called for some of the requests, for others it won't. The
  3740. * caller must check the error field of the BlockRequest to wait for the right
  3741. * callbacks (if error != 0, no callback will be called).
  3742. *
  3743. * The implementation may modify the contents of the reqs array, e.g. to merge
  3744. * requests. However, the fields opaque and error are left unmodified as they
  3745. * are used to signal failure for a single request to the caller.
  3746. */
  3747. int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
  3748. {
  3749. MultiwriteCB *mcb;
  3750. int i;
  3751. /* don't submit writes if we don't have a medium */
  3752. if (bs->drv == NULL) {
  3753. for (i = 0; i < num_reqs; i++) {
  3754. reqs[i].error = -ENOMEDIUM;
  3755. }
  3756. return -1;
  3757. }
  3758. if (num_reqs == 0) {
  3759. return 0;
  3760. }
  3761. // Create MultiwriteCB structure
  3762. mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
  3763. mcb->num_requests = 0;
  3764. mcb->num_callbacks = num_reqs;
  3765. for (i = 0; i < num_reqs; i++) {
  3766. mcb->callbacks[i].cb = reqs[i].cb;
  3767. mcb->callbacks[i].opaque = reqs[i].opaque;
  3768. }
  3769. // Check for mergable requests
  3770. num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
  3771. trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
  3772. /* Run the aio requests. */
  3773. mcb->num_requests = num_reqs;
  3774. for (i = 0; i < num_reqs; i++) {
  3775. bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
  3776. reqs[i].nb_sectors, reqs[i].flags,
  3777. multiwrite_cb, mcb,
  3778. true);
  3779. }
  3780. return 0;
  3781. }
  3782. void bdrv_aio_cancel(BlockDriverAIOCB *acb)
  3783. {
  3784. acb->aiocb_info->cancel(acb);
  3785. }
  3786. /**************************************************************/
  3787. /* async block device emulation */
  3788. typedef struct BlockDriverAIOCBSync {
  3789. BlockDriverAIOCB common;
  3790. QEMUBH *bh;
  3791. int ret;
  3792. /* vector translation state */
  3793. QEMUIOVector *qiov;
  3794. uint8_t *bounce;
  3795. int is_write;
  3796. } BlockDriverAIOCBSync;
  3797. static void bdrv_aio_cancel_em(BlockDriverAIOCB *blockacb)
  3798. {
  3799. BlockDriverAIOCBSync *acb =
  3800. container_of(blockacb, BlockDriverAIOCBSync, common);
  3801. qemu_bh_delete(acb->bh);
  3802. acb->bh = NULL;
  3803. qemu_aio_release(acb);
  3804. }
  3805. static const AIOCBInfo bdrv_em_aiocb_info = {
  3806. .aiocb_size = sizeof(BlockDriverAIOCBSync),
  3807. .cancel = bdrv_aio_cancel_em,
  3808. };
  3809. static void bdrv_aio_bh_cb(void *opaque)
  3810. {
  3811. BlockDriverAIOCBSync *acb = opaque;
  3812. if (!acb->is_write)
  3813. qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
  3814. qemu_vfree(acb->bounce);
  3815. acb->common.cb(acb->common.opaque, acb->ret);
  3816. qemu_bh_delete(acb->bh);
  3817. acb->bh = NULL;
  3818. qemu_aio_release(acb);
  3819. }
  3820. static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
  3821. int64_t sector_num,
  3822. QEMUIOVector *qiov,
  3823. int nb_sectors,
  3824. BlockDriverCompletionFunc *cb,
  3825. void *opaque,
  3826. int is_write)
  3827. {
  3828. BlockDriverAIOCBSync *acb;
  3829. acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
  3830. acb->is_write = is_write;
  3831. acb->qiov = qiov;
  3832. acb->bounce = qemu_blockalign(bs, qiov->size);
  3833. acb->bh = qemu_bh_new(bdrv_aio_bh_cb, acb);
  3834. if (is_write) {
  3835. qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
  3836. acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
  3837. } else {
  3838. acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
  3839. }
  3840. qemu_bh_schedule(acb->bh);
  3841. return &acb->common;
  3842. }
  3843. static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
  3844. int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
  3845. BlockDriverCompletionFunc *cb, void *opaque)
  3846. {
  3847. return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
  3848. }
  3849. static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
  3850. int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
  3851. BlockDriverCompletionFunc *cb, void *opaque)
  3852. {
  3853. return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
  3854. }
  3855. typedef struct BlockDriverAIOCBCoroutine {
  3856. BlockDriverAIOCB common;
  3857. BlockRequest req;
  3858. bool is_write;
  3859. bool *done;
  3860. QEMUBH* bh;
  3861. } BlockDriverAIOCBCoroutine;
  3862. static void bdrv_aio_co_cancel_em(BlockDriverAIOCB *blockacb)
  3863. {
  3864. BlockDriverAIOCBCoroutine *acb =
  3865. container_of(blockacb, BlockDriverAIOCBCoroutine, common);
  3866. bool done = false;
  3867. acb->done = &done;
  3868. while (!done) {
  3869. qemu_aio_wait();
  3870. }
  3871. }
  3872. static const AIOCBInfo bdrv_em_co_aiocb_info = {
  3873. .aiocb_size = sizeof(BlockDriverAIOCBCoroutine),
  3874. .cancel = bdrv_aio_co_cancel_em,
  3875. };
  3876. static void bdrv_co_em_bh(void *opaque)
  3877. {
  3878. BlockDriverAIOCBCoroutine *acb = opaque;
  3879. acb->common.cb(acb->common.opaque, acb->req.error);
  3880. if (acb->done) {
  3881. *acb->done = true;
  3882. }
  3883. qemu_bh_delete(acb->bh);
  3884. qemu_aio_release(acb);
  3885. }
  3886. /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
  3887. static void coroutine_fn bdrv_co_do_rw(void *opaque)
  3888. {
  3889. BlockDriverAIOCBCoroutine *acb = opaque;
  3890. BlockDriverState *bs = acb->common.bs;
  3891. if (!acb->is_write) {
  3892. acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
  3893. acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
  3894. } else {
  3895. acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
  3896. acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
  3897. }
  3898. acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
  3899. qemu_bh_schedule(acb->bh);
  3900. }
  3901. static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
  3902. int64_t sector_num,
  3903. QEMUIOVector *qiov,
  3904. int nb_sectors,
  3905. BdrvRequestFlags flags,
  3906. BlockDriverCompletionFunc *cb,
  3907. void *opaque,
  3908. bool is_write)
  3909. {
  3910. Coroutine *co;
  3911. BlockDriverAIOCBCoroutine *acb;
  3912. acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
  3913. acb->req.sector = sector_num;
  3914. acb->req.nb_sectors = nb_sectors;
  3915. acb->req.qiov = qiov;
  3916. acb->req.flags = flags;
  3917. acb->is_write = is_write;
  3918. acb->done = NULL;
  3919. co = qemu_coroutine_create(bdrv_co_do_rw);
  3920. qemu_coroutine_enter(co, acb);
  3921. return &acb->common;
  3922. }
  3923. static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
  3924. {
  3925. BlockDriverAIOCBCoroutine *acb = opaque;
  3926. BlockDriverState *bs = acb->common.bs;
  3927. acb->req.error = bdrv_co_flush(bs);
  3928. acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
  3929. qemu_bh_schedule(acb->bh);
  3930. }
  3931. BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
  3932. BlockDriverCompletionFunc *cb, void *opaque)
  3933. {
  3934. trace_bdrv_aio_flush(bs, opaque);
  3935. Coroutine *co;
  3936. BlockDriverAIOCBCoroutine *acb;
  3937. acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
  3938. acb->done = NULL;
  3939. co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
  3940. qemu_coroutine_enter(co, acb);
  3941. return &acb->common;
  3942. }
  3943. static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
  3944. {
  3945. BlockDriverAIOCBCoroutine *acb = opaque;
  3946. BlockDriverState *bs = acb->common.bs;
  3947. acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
  3948. acb->bh = qemu_bh_new(bdrv_co_em_bh, acb);
  3949. qemu_bh_schedule(acb->bh);
  3950. }
  3951. BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
  3952. int64_t sector_num, int nb_sectors,
  3953. BlockDriverCompletionFunc *cb, void *opaque)
  3954. {
  3955. Coroutine *co;
  3956. BlockDriverAIOCBCoroutine *acb;
  3957. trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
  3958. acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
  3959. acb->req.sector = sector_num;
  3960. acb->req.nb_sectors = nb_sectors;
  3961. acb->done = NULL;
  3962. co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
  3963. qemu_coroutine_enter(co, acb);
  3964. return &acb->common;
  3965. }
  3966. void bdrv_init(void)
  3967. {
  3968. module_call_init(MODULE_INIT_BLOCK);
  3969. }
  3970. void bdrv_init_with_whitelist(void)
  3971. {
  3972. use_bdrv_whitelist = 1;
  3973. bdrv_init();
  3974. }
  3975. void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
  3976. BlockDriverCompletionFunc *cb, void *opaque)
  3977. {
  3978. BlockDriverAIOCB *acb;
  3979. acb = g_slice_alloc(aiocb_info->aiocb_size);
  3980. acb->aiocb_info = aiocb_info;
  3981. acb->bs = bs;
  3982. acb->cb = cb;
  3983. acb->opaque = opaque;
  3984. return acb;
  3985. }
  3986. void qemu_aio_release(void *p)
  3987. {
  3988. BlockDriverAIOCB *acb = p;
  3989. g_slice_free1(acb->aiocb_info->aiocb_size, acb);
  3990. }
  3991. /**************************************************************/
  3992. /* Coroutine block device emulation */
  3993. typedef struct CoroutineIOCompletion {
  3994. Coroutine *coroutine;
  3995. int ret;
  3996. } CoroutineIOCompletion;
  3997. static void bdrv_co_io_em_complete(void *opaque, int ret)
  3998. {
  3999. CoroutineIOCompletion *co = opaque;
  4000. co->ret = ret;
  4001. qemu_coroutine_enter(co->coroutine, NULL);
  4002. }
  4003. static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
  4004. int nb_sectors, QEMUIOVector *iov,
  4005. bool is_write)
  4006. {
  4007. CoroutineIOCompletion co = {
  4008. .coroutine = qemu_coroutine_self(),
  4009. };
  4010. BlockDriverAIOCB *acb;
  4011. if (is_write) {
  4012. acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
  4013. bdrv_co_io_em_complete, &co);
  4014. } else {
  4015. acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
  4016. bdrv_co_io_em_complete, &co);
  4017. }
  4018. trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
  4019. if (!acb) {
  4020. return -EIO;
  4021. }
  4022. qemu_coroutine_yield();
  4023. return co.ret;
  4024. }
  4025. static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
  4026. int64_t sector_num, int nb_sectors,
  4027. QEMUIOVector *iov)
  4028. {
  4029. return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
  4030. }
  4031. static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
  4032. int64_t sector_num, int nb_sectors,
  4033. QEMUIOVector *iov)
  4034. {
  4035. return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
  4036. }
  4037. static void coroutine_fn bdrv_flush_co_entry(void *opaque)
  4038. {
  4039. RwCo *rwco = opaque;
  4040. rwco->ret = bdrv_co_flush(rwco->bs);
  4041. }
  4042. int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
  4043. {
  4044. int ret;
  4045. if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
  4046. return 0;
  4047. }
  4048. /* Write back cached data to the OS even with cache=unsafe */
  4049. BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
  4050. if (bs->drv->bdrv_co_flush_to_os) {
  4051. ret = bs->drv->bdrv_co_flush_to_os(bs);
  4052. if (ret < 0) {
  4053. return ret;
  4054. }
  4055. }
  4056. /* But don't actually force it to the disk with cache=unsafe */
  4057. if (bs->open_flags & BDRV_O_NO_FLUSH) {
  4058. goto flush_parent;
  4059. }
  4060. BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
  4061. if (bs->drv->bdrv_co_flush_to_disk) {
  4062. ret = bs->drv->bdrv_co_flush_to_disk(bs);
  4063. } else if (bs->drv->bdrv_aio_flush) {
  4064. BlockDriverAIOCB *acb;
  4065. CoroutineIOCompletion co = {
  4066. .coroutine = qemu_coroutine_self(),
  4067. };
  4068. acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
  4069. if (acb == NULL) {
  4070. ret = -EIO;
  4071. } else {
  4072. qemu_coroutine_yield();
  4073. ret = co.ret;
  4074. }
  4075. } else {
  4076. /*
  4077. * Some block drivers always operate in either writethrough or unsafe
  4078. * mode and don't support bdrv_flush therefore. Usually qemu doesn't
  4079. * know how the server works (because the behaviour is hardcoded or
  4080. * depends on server-side configuration), so we can't ensure that
  4081. * everything is safe on disk. Returning an error doesn't work because
  4082. * that would break guests even if the server operates in writethrough
  4083. * mode.
  4084. *
  4085. * Let's hope the user knows what he's doing.
  4086. */
  4087. ret = 0;
  4088. }
  4089. if (ret < 0) {
  4090. return ret;
  4091. }
  4092. /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
  4093. * in the case of cache=unsafe, so there are no useless flushes.
  4094. */
  4095. flush_parent:
  4096. return bdrv_co_flush(bs->file);
  4097. }
  4098. void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
  4099. {
  4100. Error *local_err = NULL;
  4101. int ret;
  4102. if (!bs->drv) {
  4103. return;
  4104. }
  4105. if (bs->drv->bdrv_invalidate_cache) {
  4106. bs->drv->bdrv_invalidate_cache(bs, &local_err);
  4107. } else if (bs->file) {
  4108. bdrv_invalidate_cache(bs->file, &local_err);
  4109. }
  4110. if (local_err) {
  4111. error_propagate(errp, local_err);
  4112. return;
  4113. }
  4114. ret = refresh_total_sectors(bs, bs->total_sectors);
  4115. if (ret < 0) {
  4116. error_setg_errno(errp, -ret, "Could not refresh total sector count");
  4117. return;
  4118. }
  4119. }
  4120. void bdrv_invalidate_cache_all(Error **errp)
  4121. {
  4122. BlockDriverState *bs;
  4123. Error *local_err = NULL;
  4124. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  4125. bdrv_invalidate_cache(bs, &local_err);
  4126. if (local_err) {
  4127. error_propagate(errp, local_err);
  4128. return;
  4129. }
  4130. }
  4131. }
  4132. void bdrv_clear_incoming_migration_all(void)
  4133. {
  4134. BlockDriverState *bs;
  4135. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  4136. bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
  4137. }
  4138. }
  4139. int bdrv_flush(BlockDriverState *bs)
  4140. {
  4141. Coroutine *co;
  4142. RwCo rwco = {
  4143. .bs = bs,
  4144. .ret = NOT_DONE,
  4145. };
  4146. if (qemu_in_coroutine()) {
  4147. /* Fast-path if already in coroutine context */
  4148. bdrv_flush_co_entry(&rwco);
  4149. } else {
  4150. co = qemu_coroutine_create(bdrv_flush_co_entry);
  4151. qemu_coroutine_enter(co, &rwco);
  4152. while (rwco.ret == NOT_DONE) {
  4153. qemu_aio_wait();
  4154. }
  4155. }
  4156. return rwco.ret;
  4157. }
  4158. typedef struct DiscardCo {
  4159. BlockDriverState *bs;
  4160. int64_t sector_num;
  4161. int nb_sectors;
  4162. int ret;
  4163. } DiscardCo;
  4164. static void coroutine_fn bdrv_discard_co_entry(void *opaque)
  4165. {
  4166. DiscardCo *rwco = opaque;
  4167. rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
  4168. }
  4169. /* if no limit is specified in the BlockLimits use a default
  4170. * of 32768 512-byte sectors (16 MiB) per request.
  4171. */
  4172. #define MAX_DISCARD_DEFAULT 32768
  4173. int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
  4174. int nb_sectors)
  4175. {
  4176. int max_discard;
  4177. if (!bs->drv) {
  4178. return -ENOMEDIUM;
  4179. } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
  4180. return -EIO;
  4181. } else if (bs->read_only) {
  4182. return -EROFS;
  4183. }
  4184. bdrv_reset_dirty(bs, sector_num, nb_sectors);
  4185. /* Do nothing if disabled. */
  4186. if (!(bs->open_flags & BDRV_O_UNMAP)) {
  4187. return 0;
  4188. }
  4189. if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
  4190. return 0;
  4191. }
  4192. max_discard = bs->bl.max_discard ? bs->bl.max_discard : MAX_DISCARD_DEFAULT;
  4193. while (nb_sectors > 0) {
  4194. int ret;
  4195. int num = nb_sectors;
  4196. /* align request */
  4197. if (bs->bl.discard_alignment &&
  4198. num >= bs->bl.discard_alignment &&
  4199. sector_num % bs->bl.discard_alignment) {
  4200. if (num > bs->bl.discard_alignment) {
  4201. num = bs->bl.discard_alignment;
  4202. }
  4203. num -= sector_num % bs->bl.discard_alignment;
  4204. }
  4205. /* limit request size */
  4206. if (num > max_discard) {
  4207. num = max_discard;
  4208. }
  4209. if (bs->drv->bdrv_co_discard) {
  4210. ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
  4211. } else {
  4212. BlockDriverAIOCB *acb;
  4213. CoroutineIOCompletion co = {
  4214. .coroutine = qemu_coroutine_self(),
  4215. };
  4216. acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
  4217. bdrv_co_io_em_complete, &co);
  4218. if (acb == NULL) {
  4219. return -EIO;
  4220. } else {
  4221. qemu_coroutine_yield();
  4222. ret = co.ret;
  4223. }
  4224. }
  4225. if (ret && ret != -ENOTSUP) {
  4226. return ret;
  4227. }
  4228. sector_num += num;
  4229. nb_sectors -= num;
  4230. }
  4231. return 0;
  4232. }
  4233. int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
  4234. {
  4235. Coroutine *co;
  4236. DiscardCo rwco = {
  4237. .bs = bs,
  4238. .sector_num = sector_num,
  4239. .nb_sectors = nb_sectors,
  4240. .ret = NOT_DONE,
  4241. };
  4242. if (qemu_in_coroutine()) {
  4243. /* Fast-path if already in coroutine context */
  4244. bdrv_discard_co_entry(&rwco);
  4245. } else {
  4246. co = qemu_coroutine_create(bdrv_discard_co_entry);
  4247. qemu_coroutine_enter(co, &rwco);
  4248. while (rwco.ret == NOT_DONE) {
  4249. qemu_aio_wait();
  4250. }
  4251. }
  4252. return rwco.ret;
  4253. }
  4254. /**************************************************************/
  4255. /* removable device support */
  4256. /**
  4257. * Return TRUE if the media is present
  4258. */
  4259. int bdrv_is_inserted(BlockDriverState *bs)
  4260. {
  4261. BlockDriver *drv = bs->drv;
  4262. if (!drv)
  4263. return 0;
  4264. if (!drv->bdrv_is_inserted)
  4265. return 1;
  4266. return drv->bdrv_is_inserted(bs);
  4267. }
  4268. /**
  4269. * Return whether the media changed since the last call to this
  4270. * function, or -ENOTSUP if we don't know. Most drivers don't know.
  4271. */
  4272. int bdrv_media_changed(BlockDriverState *bs)
  4273. {
  4274. BlockDriver *drv = bs->drv;
  4275. if (drv && drv->bdrv_media_changed) {
  4276. return drv->bdrv_media_changed(bs);
  4277. }
  4278. return -ENOTSUP;
  4279. }
  4280. /**
  4281. * If eject_flag is TRUE, eject the media. Otherwise, close the tray
  4282. */
  4283. void bdrv_eject(BlockDriverState *bs, bool eject_flag)
  4284. {
  4285. BlockDriver *drv = bs->drv;
  4286. if (drv && drv->bdrv_eject) {
  4287. drv->bdrv_eject(bs, eject_flag);
  4288. }
  4289. if (bs->device_name[0] != '\0') {
  4290. bdrv_emit_qmp_eject_event(bs, eject_flag);
  4291. }
  4292. }
  4293. /**
  4294. * Lock or unlock the media (if it is locked, the user won't be able
  4295. * to eject it manually).
  4296. */
  4297. void bdrv_lock_medium(BlockDriverState *bs, bool locked)
  4298. {
  4299. BlockDriver *drv = bs->drv;
  4300. trace_bdrv_lock_medium(bs, locked);
  4301. if (drv && drv->bdrv_lock_medium) {
  4302. drv->bdrv_lock_medium(bs, locked);
  4303. }
  4304. }
  4305. /* needed for generic scsi interface */
  4306. int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
  4307. {
  4308. BlockDriver *drv = bs->drv;
  4309. if (drv && drv->bdrv_ioctl)
  4310. return drv->bdrv_ioctl(bs, req, buf);
  4311. return -ENOTSUP;
  4312. }
  4313. BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
  4314. unsigned long int req, void *buf,
  4315. BlockDriverCompletionFunc *cb, void *opaque)
  4316. {
  4317. BlockDriver *drv = bs->drv;
  4318. if (drv && drv->bdrv_aio_ioctl)
  4319. return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
  4320. return NULL;
  4321. }
  4322. void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
  4323. {
  4324. bs->guest_block_size = align;
  4325. }
  4326. void *qemu_blockalign(BlockDriverState *bs, size_t size)
  4327. {
  4328. return qemu_memalign(bdrv_opt_mem_align(bs), size);
  4329. }
  4330. /*
  4331. * Check if all memory in this vector is sector aligned.
  4332. */
  4333. bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
  4334. {
  4335. int i;
  4336. size_t alignment = bdrv_opt_mem_align(bs);
  4337. for (i = 0; i < qiov->niov; i++) {
  4338. if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
  4339. return false;
  4340. }
  4341. if (qiov->iov[i].iov_len % alignment) {
  4342. return false;
  4343. }
  4344. }
  4345. return true;
  4346. }
  4347. BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity)
  4348. {
  4349. int64_t bitmap_size;
  4350. BdrvDirtyBitmap *bitmap;
  4351. assert((granularity & (granularity - 1)) == 0);
  4352. granularity >>= BDRV_SECTOR_BITS;
  4353. assert(granularity);
  4354. bitmap_size = (bdrv_getlength(bs) >> BDRV_SECTOR_BITS);
  4355. bitmap = g_malloc0(sizeof(BdrvDirtyBitmap));
  4356. bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
  4357. QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
  4358. return bitmap;
  4359. }
  4360. void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
  4361. {
  4362. BdrvDirtyBitmap *bm, *next;
  4363. QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
  4364. if (bm == bitmap) {
  4365. QLIST_REMOVE(bitmap, list);
  4366. hbitmap_free(bitmap->bitmap);
  4367. g_free(bitmap);
  4368. return;
  4369. }
  4370. }
  4371. }
  4372. BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
  4373. {
  4374. BdrvDirtyBitmap *bm;
  4375. BlockDirtyInfoList *list = NULL;
  4376. BlockDirtyInfoList **plist = &list;
  4377. QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
  4378. BlockDirtyInfo *info = g_malloc0(sizeof(BlockDirtyInfo));
  4379. BlockDirtyInfoList *entry = g_malloc0(sizeof(BlockDirtyInfoList));
  4380. info->count = bdrv_get_dirty_count(bs, bm);
  4381. info->granularity =
  4382. ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
  4383. entry->value = info;
  4384. *plist = entry;
  4385. plist = &entry->next;
  4386. }
  4387. return list;
  4388. }
  4389. int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
  4390. {
  4391. if (bitmap) {
  4392. return hbitmap_get(bitmap->bitmap, sector);
  4393. } else {
  4394. return 0;
  4395. }
  4396. }
  4397. void bdrv_dirty_iter_init(BlockDriverState *bs,
  4398. BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
  4399. {
  4400. hbitmap_iter_init(hbi, bitmap->bitmap, 0);
  4401. }
  4402. void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
  4403. int nr_sectors)
  4404. {
  4405. BdrvDirtyBitmap *bitmap;
  4406. QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
  4407. hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
  4408. }
  4409. }
  4410. void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
  4411. {
  4412. BdrvDirtyBitmap *bitmap;
  4413. QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
  4414. hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
  4415. }
  4416. }
  4417. int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
  4418. {
  4419. return hbitmap_count(bitmap->bitmap);
  4420. }
  4421. /* Get a reference to bs */
  4422. void bdrv_ref(BlockDriverState *bs)
  4423. {
  4424. bs->refcnt++;
  4425. }
  4426. /* Release a previously grabbed reference to bs.
  4427. * If after releasing, reference count is zero, the BlockDriverState is
  4428. * deleted. */
  4429. void bdrv_unref(BlockDriverState *bs)
  4430. {
  4431. assert(bs->refcnt > 0);
  4432. if (--bs->refcnt == 0) {
  4433. bdrv_delete(bs);
  4434. }
  4435. }
  4436. void bdrv_set_in_use(BlockDriverState *bs, int in_use)
  4437. {
  4438. assert(bs->in_use != in_use);
  4439. bs->in_use = in_use;
  4440. }
  4441. int bdrv_in_use(BlockDriverState *bs)
  4442. {
  4443. return bs->in_use;
  4444. }
  4445. void bdrv_iostatus_enable(BlockDriverState *bs)
  4446. {
  4447. bs->iostatus_enabled = true;
  4448. bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
  4449. }
  4450. /* The I/O status is only enabled if the drive explicitly
  4451. * enables it _and_ the VM is configured to stop on errors */
  4452. bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
  4453. {
  4454. return (bs->iostatus_enabled &&
  4455. (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
  4456. bs->on_write_error == BLOCKDEV_ON_ERROR_STOP ||
  4457. bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
  4458. }
  4459. void bdrv_iostatus_disable(BlockDriverState *bs)
  4460. {
  4461. bs->iostatus_enabled = false;
  4462. }
  4463. void bdrv_iostatus_reset(BlockDriverState *bs)
  4464. {
  4465. if (bdrv_iostatus_is_enabled(bs)) {
  4466. bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
  4467. if (bs->job) {
  4468. block_job_iostatus_reset(bs->job);
  4469. }
  4470. }
  4471. }
  4472. void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
  4473. {
  4474. assert(bdrv_iostatus_is_enabled(bs));
  4475. if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
  4476. bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
  4477. BLOCK_DEVICE_IO_STATUS_FAILED;
  4478. }
  4479. }
  4480. void
  4481. bdrv_acct_start(BlockDriverState *bs, BlockAcctCookie *cookie, int64_t bytes,
  4482. enum BlockAcctType type)
  4483. {
  4484. assert(type < BDRV_MAX_IOTYPE);
  4485. cookie->bytes = bytes;
  4486. cookie->start_time_ns = get_clock();
  4487. cookie->type = type;
  4488. }
  4489. void
  4490. bdrv_acct_done(BlockDriverState *bs, BlockAcctCookie *cookie)
  4491. {
  4492. assert(cookie->type < BDRV_MAX_IOTYPE);
  4493. bs->nr_bytes[cookie->type] += cookie->bytes;
  4494. bs->nr_ops[cookie->type]++;
  4495. bs->total_time_ns[cookie->type] += get_clock() - cookie->start_time_ns;
  4496. }
  4497. void bdrv_img_create(const char *filename, const char *fmt,
  4498. const char *base_filename, const char *base_fmt,
  4499. char *options, uint64_t img_size, int flags,
  4500. Error **errp, bool quiet)
  4501. {
  4502. QEMUOptionParameter *param = NULL, *create_options = NULL;
  4503. QEMUOptionParameter *backing_fmt, *backing_file, *size;
  4504. BlockDriver *drv, *proto_drv;
  4505. BlockDriver *backing_drv = NULL;
  4506. Error *local_err = NULL;
  4507. int ret = 0;
  4508. /* Find driver and parse its options */
  4509. drv = bdrv_find_format(fmt);
  4510. if (!drv) {
  4511. error_setg(errp, "Unknown file format '%s'", fmt);
  4512. return;
  4513. }
  4514. proto_drv = bdrv_find_protocol(filename, true);
  4515. if (!proto_drv) {
  4516. error_setg(errp, "Unknown protocol '%s'", filename);
  4517. return;
  4518. }
  4519. create_options = append_option_parameters(create_options,
  4520. drv->create_options);
  4521. create_options = append_option_parameters(create_options,
  4522. proto_drv->create_options);
  4523. /* Create parameter list with default values */
  4524. param = parse_option_parameters("", create_options, param);
  4525. set_option_parameter_int(param, BLOCK_OPT_SIZE, img_size);
  4526. /* Parse -o options */
  4527. if (options) {
  4528. param = parse_option_parameters(options, create_options, param);
  4529. if (param == NULL) {
  4530. error_setg(errp, "Invalid options for file format '%s'.", fmt);
  4531. goto out;
  4532. }
  4533. }
  4534. if (base_filename) {
  4535. if (set_option_parameter(param, BLOCK_OPT_BACKING_FILE,
  4536. base_filename)) {
  4537. error_setg(errp, "Backing file not supported for file format '%s'",
  4538. fmt);
  4539. goto out;
  4540. }
  4541. }
  4542. if (base_fmt) {
  4543. if (set_option_parameter(param, BLOCK_OPT_BACKING_FMT, base_fmt)) {
  4544. error_setg(errp, "Backing file format not supported for file "
  4545. "format '%s'", fmt);
  4546. goto out;
  4547. }
  4548. }
  4549. backing_file = get_option_parameter(param, BLOCK_OPT_BACKING_FILE);
  4550. if (backing_file && backing_file->value.s) {
  4551. if (!strcmp(filename, backing_file->value.s)) {
  4552. error_setg(errp, "Error: Trying to create an image with the "
  4553. "same filename as the backing file");
  4554. goto out;
  4555. }
  4556. }
  4557. backing_fmt = get_option_parameter(param, BLOCK_OPT_BACKING_FMT);
  4558. if (backing_fmt && backing_fmt->value.s) {
  4559. backing_drv = bdrv_find_format(backing_fmt->value.s);
  4560. if (!backing_drv) {
  4561. error_setg(errp, "Unknown backing file format '%s'",
  4562. backing_fmt->value.s);
  4563. goto out;
  4564. }
  4565. }
  4566. // The size for the image must always be specified, with one exception:
  4567. // If we are using a backing file, we can obtain the size from there
  4568. size = get_option_parameter(param, BLOCK_OPT_SIZE);
  4569. if (size && size->value.n == -1) {
  4570. if (backing_file && backing_file->value.s) {
  4571. BlockDriverState *bs;
  4572. uint64_t size;
  4573. char buf[32];
  4574. int back_flags;
  4575. /* backing files always opened read-only */
  4576. back_flags =
  4577. flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
  4578. bs = NULL;
  4579. ret = bdrv_open(&bs, backing_file->value.s, NULL, NULL, back_flags,
  4580. backing_drv, &local_err);
  4581. if (ret < 0) {
  4582. error_setg_errno(errp, -ret, "Could not open '%s': %s",
  4583. backing_file->value.s,
  4584. error_get_pretty(local_err));
  4585. error_free(local_err);
  4586. local_err = NULL;
  4587. goto out;
  4588. }
  4589. bdrv_get_geometry(bs, &size);
  4590. size *= 512;
  4591. snprintf(buf, sizeof(buf), "%" PRId64, size);
  4592. set_option_parameter(param, BLOCK_OPT_SIZE, buf);
  4593. bdrv_unref(bs);
  4594. } else {
  4595. error_setg(errp, "Image creation needs a size parameter");
  4596. goto out;
  4597. }
  4598. }
  4599. if (!quiet) {
  4600. printf("Formatting '%s', fmt=%s ", filename, fmt);
  4601. print_option_parameters(param);
  4602. puts("");
  4603. }
  4604. ret = bdrv_create(drv, filename, param, &local_err);
  4605. if (ret == -EFBIG) {
  4606. /* This is generally a better message than whatever the driver would
  4607. * deliver (especially because of the cluster_size_hint), since that
  4608. * is most probably not much different from "image too large". */
  4609. const char *cluster_size_hint = "";
  4610. if (get_option_parameter(create_options, BLOCK_OPT_CLUSTER_SIZE)) {
  4611. cluster_size_hint = " (try using a larger cluster size)";
  4612. }
  4613. error_setg(errp, "The image size is too large for file format '%s'"
  4614. "%s", fmt, cluster_size_hint);
  4615. error_free(local_err);
  4616. local_err = NULL;
  4617. }
  4618. out:
  4619. free_option_parameters(create_options);
  4620. free_option_parameters(param);
  4621. if (local_err) {
  4622. error_propagate(errp, local_err);
  4623. }
  4624. }
  4625. AioContext *bdrv_get_aio_context(BlockDriverState *bs)
  4626. {
  4627. /* Currently BlockDriverState always uses the main loop AioContext */
  4628. return qemu_get_aio_context();
  4629. }
  4630. void bdrv_add_before_write_notifier(BlockDriverState *bs,
  4631. NotifierWithReturn *notifier)
  4632. {
  4633. notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
  4634. }
  4635. int bdrv_amend_options(BlockDriverState *bs, QEMUOptionParameter *options)
  4636. {
  4637. if (bs->drv->bdrv_amend_options == NULL) {
  4638. return -ENOTSUP;
  4639. }
  4640. return bs->drv->bdrv_amend_options(bs, options);
  4641. }
  4642. /* This function will be called by the bdrv_recurse_is_first_non_filter method
  4643. * of block filter and by bdrv_is_first_non_filter.
  4644. * It is used to test if the given bs is the candidate or recurse more in the
  4645. * node graph.
  4646. */
  4647. bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
  4648. BlockDriverState *candidate)
  4649. {
  4650. /* return false if basic checks fails */
  4651. if (!bs || !bs->drv) {
  4652. return false;
  4653. }
  4654. /* the code reached a non block filter driver -> check if the bs is
  4655. * the same as the candidate. It's the recursion termination condition.
  4656. */
  4657. if (!bs->drv->is_filter) {
  4658. return bs == candidate;
  4659. }
  4660. /* Down this path the driver is a block filter driver */
  4661. /* If the block filter recursion method is defined use it to recurse down
  4662. * the node graph.
  4663. */
  4664. if (bs->drv->bdrv_recurse_is_first_non_filter) {
  4665. return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
  4666. }
  4667. /* the driver is a block filter but don't allow to recurse -> return false
  4668. */
  4669. return false;
  4670. }
  4671. /* This function checks if the candidate is the first non filter bs down it's
  4672. * bs chain. Since we don't have pointers to parents it explore all bs chains
  4673. * from the top. Some filters can choose not to pass down the recursion.
  4674. */
  4675. bool bdrv_is_first_non_filter(BlockDriverState *candidate)
  4676. {
  4677. BlockDriverState *bs;
  4678. /* walk down the bs forest recursively */
  4679. QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
  4680. bool perm;
  4681. /* try to recurse in this top level bs */
  4682. perm = bdrv_recurse_is_first_non_filter(bs, candidate);
  4683. /* candidate is the first non filter */
  4684. if (perm) {
  4685. return true;
  4686. }
  4687. }
  4688. return false;
  4689. }