mballoc.c 199 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (c) 2003-2006, Cluster File Systems, Inc, info@clusterfs.com
  4. * Written by Alex Tomas <alex@clusterfs.com>
  5. */
  6. /*
  7. * mballoc.c contains the multiblocks allocation routines
  8. */
  9. #include "ext4_jbd2.h"
  10. #include "mballoc.h"
  11. #include <linux/log2.h>
  12. #include <linux/module.h>
  13. #include <linux/slab.h>
  14. #include <linux/nospec.h>
  15. #include <linux/backing-dev.h>
  16. #include <linux/freezer.h>
  17. #include <trace/events/ext4.h>
  18. #include <kunit/static_stub.h>
  19. /*
  20. * MUSTDO:
  21. * - test ext4_ext_search_left() and ext4_ext_search_right()
  22. * - search for metadata in few groups
  23. *
  24. * TODO v4:
  25. * - normalization should take into account whether file is still open
  26. * - discard preallocations if no free space left (policy?)
  27. * - don't normalize tails
  28. * - quota
  29. * - reservation for superuser
  30. *
  31. * TODO v3:
  32. * - bitmap read-ahead (proposed by Oleg Drokin aka green)
  33. * - track min/max extents in each group for better group selection
  34. * - mb_mark_used() may allocate chunk right after splitting buddy
  35. * - tree of groups sorted by number of free blocks
  36. * - error handling
  37. */
  38. /*
  39. * The allocation request involve request for multiple number of blocks
  40. * near to the goal(block) value specified.
  41. *
  42. * During initialization phase of the allocator we decide to use the
  43. * group preallocation or inode preallocation depending on the size of
  44. * the file. The size of the file could be the resulting file size we
  45. * would have after allocation, or the current file size, which ever
  46. * is larger. If the size is less than sbi->s_mb_stream_request we
  47. * select to use the group preallocation. The default value of
  48. * s_mb_stream_request is 16 blocks. This can also be tuned via
  49. * /sys/fs/ext4/<partition>/mb_stream_req. The value is represented in
  50. * terms of number of blocks.
  51. *
  52. * The main motivation for having small file use group preallocation is to
  53. * ensure that we have small files closer together on the disk.
  54. *
  55. * First stage the allocator looks at the inode prealloc list,
  56. * ext4_inode_info->i_prealloc_list, which contains list of prealloc
  57. * spaces for this particular inode. The inode prealloc space is
  58. * represented as:
  59. *
  60. * pa_lstart -> the logical start block for this prealloc space
  61. * pa_pstart -> the physical start block for this prealloc space
  62. * pa_len -> length for this prealloc space (in clusters)
  63. * pa_free -> free space available in this prealloc space (in clusters)
  64. *
  65. * The inode preallocation space is used looking at the _logical_ start
  66. * block. If only the logical file block falls within the range of prealloc
  67. * space we will consume the particular prealloc space. This makes sure that
  68. * we have contiguous physical blocks representing the file blocks
  69. *
  70. * The important thing to be noted in case of inode prealloc space is that
  71. * we don't modify the values associated to inode prealloc space except
  72. * pa_free.
  73. *
  74. * If we are not able to find blocks in the inode prealloc space and if we
  75. * have the group allocation flag set then we look at the locality group
  76. * prealloc space. These are per CPU prealloc list represented as
  77. *
  78. * ext4_sb_info.s_locality_groups[smp_processor_id()]
  79. *
  80. * The reason for having a per cpu locality group is to reduce the contention
  81. * between CPUs. It is possible to get scheduled at this point.
  82. *
  83. * The locality group prealloc space is used looking at whether we have
  84. * enough free space (pa_free) within the prealloc space.
  85. *
  86. * If we can't allocate blocks via inode prealloc or/and locality group
  87. * prealloc then we look at the buddy cache. The buddy cache is represented
  88. * by ext4_sb_info.s_buddy_cache (struct inode) whose file offset gets
  89. * mapped to the buddy and bitmap information regarding different
  90. * groups. The buddy information is attached to buddy cache inode so that
  91. * we can access them through the page cache. The information regarding
  92. * each group is loaded via ext4_mb_load_buddy. The information involve
  93. * block bitmap and buddy information. The information are stored in the
  94. * inode as:
  95. *
  96. * { page }
  97. * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
  98. *
  99. *
  100. * one block each for bitmap and buddy information. So for each group we
  101. * take up 2 blocks. A page can contain blocks_per_page (PAGE_SIZE /
  102. * blocksize) blocks. So it can have information regarding groups_per_page
  103. * which is blocks_per_page/2
  104. *
  105. * The buddy cache inode is not stored on disk. The inode is thrown
  106. * away when the filesystem is unmounted.
  107. *
  108. * We look for count number of blocks in the buddy cache. If we were able
  109. * to locate that many free blocks we return with additional information
  110. * regarding rest of the contiguous physical block available
  111. *
  112. * Before allocating blocks via buddy cache we normalize the request
  113. * blocks. This ensure we ask for more blocks that we needed. The extra
  114. * blocks that we get after allocation is added to the respective prealloc
  115. * list. In case of inode preallocation we follow a list of heuristics
  116. * based on file size. This can be found in ext4_mb_normalize_request. If
  117. * we are doing a group prealloc we try to normalize the request to
  118. * sbi->s_mb_group_prealloc. The default value of s_mb_group_prealloc is
  119. * dependent on the cluster size; for non-bigalloc file systems, it is
  120. * 512 blocks. This can be tuned via
  121. * /sys/fs/ext4/<partition>/mb_group_prealloc. The value is represented in
  122. * terms of number of blocks. If we have mounted the file system with -O
  123. * stripe=<value> option the group prealloc request is normalized to the
  124. * smallest multiple of the stripe value (sbi->s_stripe) which is
  125. * greater than the default mb_group_prealloc.
  126. *
  127. * If "mb_optimize_scan" mount option is set, we maintain in memory group info
  128. * structures in two data structures:
  129. *
  130. * 1) Array of largest free order lists (sbi->s_mb_largest_free_orders)
  131. *
  132. * Locking: sbi->s_mb_largest_free_orders_locks(array of rw locks)
  133. *
  134. * This is an array of lists where the index in the array represents the
  135. * largest free order in the buddy bitmap of the participating group infos of
  136. * that list. So, there are exactly MB_NUM_ORDERS(sb) (which means total
  137. * number of buddy bitmap orders possible) number of lists. Group-infos are
  138. * placed in appropriate lists.
  139. *
  140. * 2) Average fragment size lists (sbi->s_mb_avg_fragment_size)
  141. *
  142. * Locking: sbi->s_mb_avg_fragment_size_locks(array of rw locks)
  143. *
  144. * This is an array of lists where in the i-th list there are groups with
  145. * average fragment size >= 2^i and < 2^(i+1). The average fragment size
  146. * is computed as ext4_group_info->bb_free / ext4_group_info->bb_fragments.
  147. * Note that we don't bother with a special list for completely empty groups
  148. * so we only have MB_NUM_ORDERS(sb) lists.
  149. *
  150. * When "mb_optimize_scan" mount option is set, mballoc consults the above data
  151. * structures to decide the order in which groups are to be traversed for
  152. * fulfilling an allocation request.
  153. *
  154. * At CR_POWER2_ALIGNED , we look for groups which have the largest_free_order
  155. * >= the order of the request. We directly look at the largest free order list
  156. * in the data structure (1) above where largest_free_order = order of the
  157. * request. If that list is empty, we look at remaining list in the increasing
  158. * order of largest_free_order. This allows us to perform CR_POWER2_ALIGNED
  159. * lookup in O(1) time.
  160. *
  161. * At CR_GOAL_LEN_FAST, we only consider groups where
  162. * average fragment size > request size. So, we lookup a group which has average
  163. * fragment size just above or equal to request size using our average fragment
  164. * size group lists (data structure 2) in O(1) time.
  165. *
  166. * At CR_BEST_AVAIL_LEN, we aim to optimize allocations which can't be satisfied
  167. * in CR_GOAL_LEN_FAST. The fact that we couldn't find a group in
  168. * CR_GOAL_LEN_FAST suggests that there is no BG that has avg
  169. * fragment size > goal length. So before falling to the slower
  170. * CR_GOAL_LEN_SLOW, in CR_BEST_AVAIL_LEN we proactively trim goal length and
  171. * then use the same fragment lists as CR_GOAL_LEN_FAST to find a BG with a big
  172. * enough average fragment size. This increases the chances of finding a
  173. * suitable block group in O(1) time and results in faster allocation at the
  174. * cost of reduced size of allocation.
  175. *
  176. * If "mb_optimize_scan" mount option is not set, mballoc traverses groups in
  177. * linear order which requires O(N) search time for each CR_POWER2_ALIGNED and
  178. * CR_GOAL_LEN_FAST phase.
  179. *
  180. * The regular allocator (using the buddy cache) supports a few tunables.
  181. *
  182. * /sys/fs/ext4/<partition>/mb_min_to_scan
  183. * /sys/fs/ext4/<partition>/mb_max_to_scan
  184. * /sys/fs/ext4/<partition>/mb_order2_req
  185. * /sys/fs/ext4/<partition>/mb_linear_limit
  186. *
  187. * The regular allocator uses buddy scan only if the request len is power of
  188. * 2 blocks and the order of allocation is >= sbi->s_mb_order2_reqs. The
  189. * value of s_mb_order2_reqs can be tuned via
  190. * /sys/fs/ext4/<partition>/mb_order2_req. If the request len is equal to
  191. * stripe size (sbi->s_stripe), we try to search for contiguous block in
  192. * stripe size. This should result in better allocation on RAID setups. If
  193. * not, we search in the specific group using bitmap for best extents. The
  194. * tunable min_to_scan and max_to_scan control the behaviour here.
  195. * min_to_scan indicate how long the mballoc __must__ look for a best
  196. * extent and max_to_scan indicates how long the mballoc __can__ look for a
  197. * best extent in the found extents. Searching for the blocks starts with
  198. * the group specified as the goal value in allocation context via
  199. * ac_g_ex. Each group is first checked based on the criteria whether it
  200. * can be used for allocation. ext4_mb_good_group explains how the groups are
  201. * checked.
  202. *
  203. * When "mb_optimize_scan" is turned on, as mentioned above, the groups may not
  204. * get traversed linearly. That may result in subsequent allocations being not
  205. * close to each other. And so, the underlying device may get filled up in a
  206. * non-linear fashion. While that may not matter on non-rotational devices, for
  207. * rotational devices that may result in higher seek times. "mb_linear_limit"
  208. * tells mballoc how many groups mballoc should search linearly before
  209. * performing consulting above data structures for more efficient lookups. For
  210. * non rotational devices, this value defaults to 0 and for rotational devices
  211. * this is set to MB_DEFAULT_LINEAR_LIMIT.
  212. *
  213. * Both the prealloc space are getting populated as above. So for the first
  214. * request we will hit the buddy cache which will result in this prealloc
  215. * space getting filled. The prealloc space is then later used for the
  216. * subsequent request.
  217. */
  218. /*
  219. * mballoc operates on the following data:
  220. * - on-disk bitmap
  221. * - in-core buddy (actually includes buddy and bitmap)
  222. * - preallocation descriptors (PAs)
  223. *
  224. * there are two types of preallocations:
  225. * - inode
  226. * assiged to specific inode and can be used for this inode only.
  227. * it describes part of inode's space preallocated to specific
  228. * physical blocks. any block from that preallocated can be used
  229. * independent. the descriptor just tracks number of blocks left
  230. * unused. so, before taking some block from descriptor, one must
  231. * make sure corresponded logical block isn't allocated yet. this
  232. * also means that freeing any block within descriptor's range
  233. * must discard all preallocated blocks.
  234. * - locality group
  235. * assigned to specific locality group which does not translate to
  236. * permanent set of inodes: inode can join and leave group. space
  237. * from this type of preallocation can be used for any inode. thus
  238. * it's consumed from the beginning to the end.
  239. *
  240. * relation between them can be expressed as:
  241. * in-core buddy = on-disk bitmap + preallocation descriptors
  242. *
  243. * this mean blocks mballoc considers used are:
  244. * - allocated blocks (persistent)
  245. * - preallocated blocks (non-persistent)
  246. *
  247. * consistency in mballoc world means that at any time a block is either
  248. * free or used in ALL structures. notice: "any time" should not be read
  249. * literally -- time is discrete and delimited by locks.
  250. *
  251. * to keep it simple, we don't use block numbers, instead we count number of
  252. * blocks: how many blocks marked used/free in on-disk bitmap, buddy and PA.
  253. *
  254. * all operations can be expressed as:
  255. * - init buddy: buddy = on-disk + PAs
  256. * - new PA: buddy += N; PA = N
  257. * - use inode PA: on-disk += N; PA -= N
  258. * - discard inode PA buddy -= on-disk - PA; PA = 0
  259. * - use locality group PA on-disk += N; PA -= N
  260. * - discard locality group PA buddy -= PA; PA = 0
  261. * note: 'buddy -= on-disk - PA' is used to show that on-disk bitmap
  262. * is used in real operation because we can't know actual used
  263. * bits from PA, only from on-disk bitmap
  264. *
  265. * if we follow this strict logic, then all operations above should be atomic.
  266. * given some of them can block, we'd have to use something like semaphores
  267. * killing performance on high-end SMP hardware. let's try to relax it using
  268. * the following knowledge:
  269. * 1) if buddy is referenced, it's already initialized
  270. * 2) while block is used in buddy and the buddy is referenced,
  271. * nobody can re-allocate that block
  272. * 3) we work on bitmaps and '+' actually means 'set bits'. if on-disk has
  273. * bit set and PA claims same block, it's OK. IOW, one can set bit in
  274. * on-disk bitmap if buddy has same bit set or/and PA covers corresponded
  275. * block
  276. *
  277. * so, now we're building a concurrency table:
  278. * - init buddy vs.
  279. * - new PA
  280. * blocks for PA are allocated in the buddy, buddy must be referenced
  281. * until PA is linked to allocation group to avoid concurrent buddy init
  282. * - use inode PA
  283. * we need to make sure that either on-disk bitmap or PA has uptodate data
  284. * given (3) we care that PA-=N operation doesn't interfere with init
  285. * - discard inode PA
  286. * the simplest way would be to have buddy initialized by the discard
  287. * - use locality group PA
  288. * again PA-=N must be serialized with init
  289. * - discard locality group PA
  290. * the simplest way would be to have buddy initialized by the discard
  291. * - new PA vs.
  292. * - use inode PA
  293. * i_data_sem serializes them
  294. * - discard inode PA
  295. * discard process must wait until PA isn't used by another process
  296. * - use locality group PA
  297. * some mutex should serialize them
  298. * - discard locality group PA
  299. * discard process must wait until PA isn't used by another process
  300. * - use inode PA
  301. * - use inode PA
  302. * i_data_sem or another mutex should serializes them
  303. * - discard inode PA
  304. * discard process must wait until PA isn't used by another process
  305. * - use locality group PA
  306. * nothing wrong here -- they're different PAs covering different blocks
  307. * - discard locality group PA
  308. * discard process must wait until PA isn't used by another process
  309. *
  310. * now we're ready to make few consequences:
  311. * - PA is referenced and while it is no discard is possible
  312. * - PA is referenced until block isn't marked in on-disk bitmap
  313. * - PA changes only after on-disk bitmap
  314. * - discard must not compete with init. either init is done before
  315. * any discard or they're serialized somehow
  316. * - buddy init as sum of on-disk bitmap and PAs is done atomically
  317. *
  318. * a special case when we've used PA to emptiness. no need to modify buddy
  319. * in this case, but we should care about concurrent init
  320. *
  321. */
  322. /*
  323. * Logic in few words:
  324. *
  325. * - allocation:
  326. * load group
  327. * find blocks
  328. * mark bits in on-disk bitmap
  329. * release group
  330. *
  331. * - use preallocation:
  332. * find proper PA (per-inode or group)
  333. * load group
  334. * mark bits in on-disk bitmap
  335. * release group
  336. * release PA
  337. *
  338. * - free:
  339. * load group
  340. * mark bits in on-disk bitmap
  341. * release group
  342. *
  343. * - discard preallocations in group:
  344. * mark PAs deleted
  345. * move them onto local list
  346. * load on-disk bitmap
  347. * load group
  348. * remove PA from object (inode or locality group)
  349. * mark free blocks in-core
  350. *
  351. * - discard inode's preallocations:
  352. */
  353. /*
  354. * Locking rules
  355. *
  356. * Locks:
  357. * - bitlock on a group (group)
  358. * - object (inode/locality) (object)
  359. * - per-pa lock (pa)
  360. * - cr_power2_aligned lists lock (cr_power2_aligned)
  361. * - cr_goal_len_fast lists lock (cr_goal_len_fast)
  362. *
  363. * Paths:
  364. * - new pa
  365. * object
  366. * group
  367. *
  368. * - find and use pa:
  369. * pa
  370. *
  371. * - release consumed pa:
  372. * pa
  373. * group
  374. * object
  375. *
  376. * - generate in-core bitmap:
  377. * group
  378. * pa
  379. *
  380. * - discard all for given object (inode, locality group):
  381. * object
  382. * pa
  383. * group
  384. *
  385. * - discard all for given group:
  386. * group
  387. * pa
  388. * group
  389. * object
  390. *
  391. * - allocation path (ext4_mb_regular_allocator)
  392. * group
  393. * cr_power2_aligned/cr_goal_len_fast
  394. */
  395. static struct kmem_cache *ext4_pspace_cachep;
  396. static struct kmem_cache *ext4_ac_cachep;
  397. static struct kmem_cache *ext4_free_data_cachep;
  398. /* We create slab caches for groupinfo data structures based on the
  399. * superblock block size. There will be one per mounted filesystem for
  400. * each unique s_blocksize_bits */
  401. #define NR_GRPINFO_CACHES 8
  402. static struct kmem_cache *ext4_groupinfo_caches[NR_GRPINFO_CACHES];
  403. static const char * const ext4_groupinfo_slab_names[NR_GRPINFO_CACHES] = {
  404. "ext4_groupinfo_1k", "ext4_groupinfo_2k", "ext4_groupinfo_4k",
  405. "ext4_groupinfo_8k", "ext4_groupinfo_16k", "ext4_groupinfo_32k",
  406. "ext4_groupinfo_64k", "ext4_groupinfo_128k"
  407. };
  408. static void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
  409. ext4_group_t group);
  410. static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac);
  411. static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
  412. ext4_group_t group, enum criteria cr);
  413. static int ext4_try_to_trim_range(struct super_block *sb,
  414. struct ext4_buddy *e4b, ext4_grpblk_t start,
  415. ext4_grpblk_t max, ext4_grpblk_t minblocks);
  416. /*
  417. * The algorithm using this percpu seq counter goes below:
  418. * 1. We sample the percpu discard_pa_seq counter before trying for block
  419. * allocation in ext4_mb_new_blocks().
  420. * 2. We increment this percpu discard_pa_seq counter when we either allocate
  421. * or free these blocks i.e. while marking those blocks as used/free in
  422. * mb_mark_used()/mb_free_blocks().
  423. * 3. We also increment this percpu seq counter when we successfully identify
  424. * that the bb_prealloc_list is not empty and hence proceed for discarding
  425. * of those PAs inside ext4_mb_discard_group_preallocations().
  426. *
  427. * Now to make sure that the regular fast path of block allocation is not
  428. * affected, as a small optimization we only sample the percpu seq counter
  429. * on that cpu. Only when the block allocation fails and when freed blocks
  430. * found were 0, that is when we sample percpu seq counter for all cpus using
  431. * below function ext4_get_discard_pa_seq_sum(). This happens after making
  432. * sure that all the PAs on grp->bb_prealloc_list got freed or if it's empty.
  433. */
  434. static DEFINE_PER_CPU(u64, discard_pa_seq);
  435. static inline u64 ext4_get_discard_pa_seq_sum(void)
  436. {
  437. int __cpu;
  438. u64 __seq = 0;
  439. for_each_possible_cpu(__cpu)
  440. __seq += per_cpu(discard_pa_seq, __cpu);
  441. return __seq;
  442. }
  443. static inline void *mb_correct_addr_and_bit(int *bit, void *addr)
  444. {
  445. #if BITS_PER_LONG == 64
  446. *bit += ((unsigned long) addr & 7UL) << 3;
  447. addr = (void *) ((unsigned long) addr & ~7UL);
  448. #elif BITS_PER_LONG == 32
  449. *bit += ((unsigned long) addr & 3UL) << 3;
  450. addr = (void *) ((unsigned long) addr & ~3UL);
  451. #else
  452. #error "how many bits you are?!"
  453. #endif
  454. return addr;
  455. }
  456. static inline int mb_test_bit(int bit, void *addr)
  457. {
  458. /*
  459. * ext4_test_bit on architecture like powerpc
  460. * needs unsigned long aligned address
  461. */
  462. addr = mb_correct_addr_and_bit(&bit, addr);
  463. return ext4_test_bit(bit, addr);
  464. }
  465. static inline void mb_set_bit(int bit, void *addr)
  466. {
  467. addr = mb_correct_addr_and_bit(&bit, addr);
  468. ext4_set_bit(bit, addr);
  469. }
  470. static inline void mb_clear_bit(int bit, void *addr)
  471. {
  472. addr = mb_correct_addr_and_bit(&bit, addr);
  473. ext4_clear_bit(bit, addr);
  474. }
  475. static inline int mb_test_and_clear_bit(int bit, void *addr)
  476. {
  477. addr = mb_correct_addr_and_bit(&bit, addr);
  478. return ext4_test_and_clear_bit(bit, addr);
  479. }
  480. static inline int mb_find_next_zero_bit(void *addr, int max, int start)
  481. {
  482. int fix = 0, ret, tmpmax;
  483. addr = mb_correct_addr_and_bit(&fix, addr);
  484. tmpmax = max + fix;
  485. start += fix;
  486. ret = ext4_find_next_zero_bit(addr, tmpmax, start) - fix;
  487. if (ret > max)
  488. return max;
  489. return ret;
  490. }
  491. static inline int mb_find_next_bit(void *addr, int max, int start)
  492. {
  493. int fix = 0, ret, tmpmax;
  494. addr = mb_correct_addr_and_bit(&fix, addr);
  495. tmpmax = max + fix;
  496. start += fix;
  497. ret = ext4_find_next_bit(addr, tmpmax, start) - fix;
  498. if (ret > max)
  499. return max;
  500. return ret;
  501. }
  502. static void *mb_find_buddy(struct ext4_buddy *e4b, int order, int *max)
  503. {
  504. char *bb;
  505. BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
  506. BUG_ON(max == NULL);
  507. if (order > e4b->bd_blkbits + 1) {
  508. *max = 0;
  509. return NULL;
  510. }
  511. /* at order 0 we see each particular block */
  512. if (order == 0) {
  513. *max = 1 << (e4b->bd_blkbits + 3);
  514. return e4b->bd_bitmap;
  515. }
  516. bb = e4b->bd_buddy + EXT4_SB(e4b->bd_sb)->s_mb_offsets[order];
  517. *max = EXT4_SB(e4b->bd_sb)->s_mb_maxs[order];
  518. return bb;
  519. }
  520. #ifdef DOUBLE_CHECK
  521. static void mb_free_blocks_double(struct inode *inode, struct ext4_buddy *e4b,
  522. int first, int count)
  523. {
  524. int i;
  525. struct super_block *sb = e4b->bd_sb;
  526. if (unlikely(e4b->bd_info->bb_bitmap == NULL))
  527. return;
  528. assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
  529. for (i = 0; i < count; i++) {
  530. if (!mb_test_bit(first + i, e4b->bd_info->bb_bitmap)) {
  531. ext4_fsblk_t blocknr;
  532. blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
  533. blocknr += EXT4_C2B(EXT4_SB(sb), first + i);
  534. ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
  535. EXT4_GROUP_INFO_BBITMAP_CORRUPT);
  536. ext4_grp_locked_error(sb, e4b->bd_group,
  537. inode ? inode->i_ino : 0,
  538. blocknr,
  539. "freeing block already freed "
  540. "(bit %u)",
  541. first + i);
  542. }
  543. mb_clear_bit(first + i, e4b->bd_info->bb_bitmap);
  544. }
  545. }
  546. static void mb_mark_used_double(struct ext4_buddy *e4b, int first, int count)
  547. {
  548. int i;
  549. if (unlikely(e4b->bd_info->bb_bitmap == NULL))
  550. return;
  551. assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
  552. for (i = 0; i < count; i++) {
  553. BUG_ON(mb_test_bit(first + i, e4b->bd_info->bb_bitmap));
  554. mb_set_bit(first + i, e4b->bd_info->bb_bitmap);
  555. }
  556. }
  557. static void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
  558. {
  559. if (unlikely(e4b->bd_info->bb_bitmap == NULL))
  560. return;
  561. if (memcmp(e4b->bd_info->bb_bitmap, bitmap, e4b->bd_sb->s_blocksize)) {
  562. unsigned char *b1, *b2;
  563. int i;
  564. b1 = (unsigned char *) e4b->bd_info->bb_bitmap;
  565. b2 = (unsigned char *) bitmap;
  566. for (i = 0; i < e4b->bd_sb->s_blocksize; i++) {
  567. if (b1[i] != b2[i]) {
  568. ext4_msg(e4b->bd_sb, KERN_ERR,
  569. "corruption in group %u "
  570. "at byte %u(%u): %x in copy != %x "
  571. "on disk/prealloc",
  572. e4b->bd_group, i, i * 8, b1[i], b2[i]);
  573. BUG();
  574. }
  575. }
  576. }
  577. }
  578. static void mb_group_bb_bitmap_alloc(struct super_block *sb,
  579. struct ext4_group_info *grp, ext4_group_t group)
  580. {
  581. struct buffer_head *bh;
  582. grp->bb_bitmap = kmalloc(sb->s_blocksize, GFP_NOFS);
  583. if (!grp->bb_bitmap)
  584. return;
  585. bh = ext4_read_block_bitmap(sb, group);
  586. if (IS_ERR_OR_NULL(bh)) {
  587. kfree(grp->bb_bitmap);
  588. grp->bb_bitmap = NULL;
  589. return;
  590. }
  591. memcpy(grp->bb_bitmap, bh->b_data, sb->s_blocksize);
  592. put_bh(bh);
  593. }
  594. static void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
  595. {
  596. kfree(grp->bb_bitmap);
  597. }
  598. #else
  599. static inline void mb_free_blocks_double(struct inode *inode,
  600. struct ext4_buddy *e4b, int first, int count)
  601. {
  602. return;
  603. }
  604. static inline void mb_mark_used_double(struct ext4_buddy *e4b,
  605. int first, int count)
  606. {
  607. return;
  608. }
  609. static inline void mb_cmp_bitmaps(struct ext4_buddy *e4b, void *bitmap)
  610. {
  611. return;
  612. }
  613. static inline void mb_group_bb_bitmap_alloc(struct super_block *sb,
  614. struct ext4_group_info *grp, ext4_group_t group)
  615. {
  616. return;
  617. }
  618. static inline void mb_group_bb_bitmap_free(struct ext4_group_info *grp)
  619. {
  620. return;
  621. }
  622. #endif
  623. #ifdef AGGRESSIVE_CHECK
  624. #define MB_CHECK_ASSERT(assert) \
  625. do { \
  626. if (!(assert)) { \
  627. printk(KERN_EMERG \
  628. "Assertion failure in %s() at %s:%d: \"%s\"\n", \
  629. function, file, line, # assert); \
  630. BUG(); \
  631. } \
  632. } while (0)
  633. static void __mb_check_buddy(struct ext4_buddy *e4b, char *file,
  634. const char *function, int line)
  635. {
  636. struct super_block *sb = e4b->bd_sb;
  637. int order = e4b->bd_blkbits + 1;
  638. int max;
  639. int max2;
  640. int i;
  641. int j;
  642. int k;
  643. int count;
  644. struct ext4_group_info *grp;
  645. int fragments = 0;
  646. int fstart;
  647. struct list_head *cur;
  648. void *buddy;
  649. void *buddy2;
  650. if (e4b->bd_info->bb_check_counter++ % 10)
  651. return;
  652. while (order > 1) {
  653. buddy = mb_find_buddy(e4b, order, &max);
  654. MB_CHECK_ASSERT(buddy);
  655. buddy2 = mb_find_buddy(e4b, order - 1, &max2);
  656. MB_CHECK_ASSERT(buddy2);
  657. MB_CHECK_ASSERT(buddy != buddy2);
  658. MB_CHECK_ASSERT(max * 2 == max2);
  659. count = 0;
  660. for (i = 0; i < max; i++) {
  661. if (mb_test_bit(i, buddy)) {
  662. /* only single bit in buddy2 may be 0 */
  663. if (!mb_test_bit(i << 1, buddy2)) {
  664. MB_CHECK_ASSERT(
  665. mb_test_bit((i<<1)+1, buddy2));
  666. }
  667. continue;
  668. }
  669. /* both bits in buddy2 must be 1 */
  670. MB_CHECK_ASSERT(mb_test_bit(i << 1, buddy2));
  671. MB_CHECK_ASSERT(mb_test_bit((i << 1) + 1, buddy2));
  672. for (j = 0; j < (1 << order); j++) {
  673. k = (i * (1 << order)) + j;
  674. MB_CHECK_ASSERT(
  675. !mb_test_bit(k, e4b->bd_bitmap));
  676. }
  677. count++;
  678. }
  679. MB_CHECK_ASSERT(e4b->bd_info->bb_counters[order] == count);
  680. order--;
  681. }
  682. fstart = -1;
  683. buddy = mb_find_buddy(e4b, 0, &max);
  684. for (i = 0; i < max; i++) {
  685. if (!mb_test_bit(i, buddy)) {
  686. MB_CHECK_ASSERT(i >= e4b->bd_info->bb_first_free);
  687. if (fstart == -1) {
  688. fragments++;
  689. fstart = i;
  690. }
  691. continue;
  692. }
  693. fstart = -1;
  694. /* check used bits only */
  695. for (j = 0; j < e4b->bd_blkbits + 1; j++) {
  696. buddy2 = mb_find_buddy(e4b, j, &max2);
  697. k = i >> j;
  698. MB_CHECK_ASSERT(k < max2);
  699. MB_CHECK_ASSERT(mb_test_bit(k, buddy2));
  700. }
  701. }
  702. MB_CHECK_ASSERT(!EXT4_MB_GRP_NEED_INIT(e4b->bd_info));
  703. MB_CHECK_ASSERT(e4b->bd_info->bb_fragments == fragments);
  704. grp = ext4_get_group_info(sb, e4b->bd_group);
  705. if (!grp)
  706. return;
  707. list_for_each(cur, &grp->bb_prealloc_list) {
  708. ext4_group_t groupnr;
  709. struct ext4_prealloc_space *pa;
  710. pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
  711. ext4_get_group_no_and_offset(sb, pa->pa_pstart, &groupnr, &k);
  712. MB_CHECK_ASSERT(groupnr == e4b->bd_group);
  713. for (i = 0; i < pa->pa_len; i++)
  714. MB_CHECK_ASSERT(mb_test_bit(k + i, buddy));
  715. }
  716. }
  717. #undef MB_CHECK_ASSERT
  718. #define mb_check_buddy(e4b) __mb_check_buddy(e4b, \
  719. __FILE__, __func__, __LINE__)
  720. #else
  721. #define mb_check_buddy(e4b)
  722. #endif
  723. /*
  724. * Divide blocks started from @first with length @len into
  725. * smaller chunks with power of 2 blocks.
  726. * Clear the bits in bitmap which the blocks of the chunk(s) covered,
  727. * then increase bb_counters[] for corresponded chunk size.
  728. */
  729. static void ext4_mb_mark_free_simple(struct super_block *sb,
  730. void *buddy, ext4_grpblk_t first, ext4_grpblk_t len,
  731. struct ext4_group_info *grp)
  732. {
  733. struct ext4_sb_info *sbi = EXT4_SB(sb);
  734. ext4_grpblk_t min;
  735. ext4_grpblk_t max;
  736. ext4_grpblk_t chunk;
  737. unsigned int border;
  738. BUG_ON(len > EXT4_CLUSTERS_PER_GROUP(sb));
  739. border = 2 << sb->s_blocksize_bits;
  740. while (len > 0) {
  741. /* find how many blocks can be covered since this position */
  742. max = ffs(first | border) - 1;
  743. /* find how many blocks of power 2 we need to mark */
  744. min = fls(len) - 1;
  745. if (max < min)
  746. min = max;
  747. chunk = 1 << min;
  748. /* mark multiblock chunks only */
  749. grp->bb_counters[min]++;
  750. if (min > 0)
  751. mb_clear_bit(first >> min,
  752. buddy + sbi->s_mb_offsets[min]);
  753. len -= chunk;
  754. first += chunk;
  755. }
  756. }
  757. static int mb_avg_fragment_size_order(struct super_block *sb, ext4_grpblk_t len)
  758. {
  759. int order;
  760. /*
  761. * We don't bother with a special lists groups with only 1 block free
  762. * extents and for completely empty groups.
  763. */
  764. order = fls(len) - 2;
  765. if (order < 0)
  766. return 0;
  767. if (order == MB_NUM_ORDERS(sb))
  768. order--;
  769. if (WARN_ON_ONCE(order > MB_NUM_ORDERS(sb)))
  770. order = MB_NUM_ORDERS(sb) - 1;
  771. return order;
  772. }
  773. /* Move group to appropriate avg_fragment_size list */
  774. static void
  775. mb_update_avg_fragment_size(struct super_block *sb, struct ext4_group_info *grp)
  776. {
  777. struct ext4_sb_info *sbi = EXT4_SB(sb);
  778. int new, old;
  779. if (!test_opt2(sb, MB_OPTIMIZE_SCAN))
  780. return;
  781. old = grp->bb_avg_fragment_size_order;
  782. new = grp->bb_fragments == 0 ? -1 :
  783. mb_avg_fragment_size_order(sb, grp->bb_free / grp->bb_fragments);
  784. if (new == old)
  785. return;
  786. if (old >= 0) {
  787. write_lock(&sbi->s_mb_avg_fragment_size_locks[old]);
  788. list_del(&grp->bb_avg_fragment_size_node);
  789. write_unlock(&sbi->s_mb_avg_fragment_size_locks[old]);
  790. }
  791. grp->bb_avg_fragment_size_order = new;
  792. if (new >= 0) {
  793. write_lock(&sbi->s_mb_avg_fragment_size_locks[new]);
  794. list_add_tail(&grp->bb_avg_fragment_size_node,
  795. &sbi->s_mb_avg_fragment_size[new]);
  796. write_unlock(&sbi->s_mb_avg_fragment_size_locks[new]);
  797. }
  798. }
  799. /*
  800. * Choose next group by traversing largest_free_order lists. Updates *new_cr if
  801. * cr level needs an update.
  802. */
  803. static void ext4_mb_choose_next_group_p2_aligned(struct ext4_allocation_context *ac,
  804. enum criteria *new_cr, ext4_group_t *group)
  805. {
  806. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  807. struct ext4_group_info *iter;
  808. int i;
  809. if (ac->ac_status == AC_STATUS_FOUND)
  810. return;
  811. if (unlikely(sbi->s_mb_stats && ac->ac_flags & EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED))
  812. atomic_inc(&sbi->s_bal_p2_aligned_bad_suggestions);
  813. for (i = ac->ac_2order; i < MB_NUM_ORDERS(ac->ac_sb); i++) {
  814. if (list_empty(&sbi->s_mb_largest_free_orders[i]))
  815. continue;
  816. read_lock(&sbi->s_mb_largest_free_orders_locks[i]);
  817. if (list_empty(&sbi->s_mb_largest_free_orders[i])) {
  818. read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
  819. continue;
  820. }
  821. list_for_each_entry(iter, &sbi->s_mb_largest_free_orders[i],
  822. bb_largest_free_order_node) {
  823. if (sbi->s_mb_stats)
  824. atomic64_inc(&sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]);
  825. if (likely(ext4_mb_good_group(ac, iter->bb_group, CR_POWER2_ALIGNED))) {
  826. *group = iter->bb_group;
  827. ac->ac_flags |= EXT4_MB_CR_POWER2_ALIGNED_OPTIMIZED;
  828. read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
  829. return;
  830. }
  831. }
  832. read_unlock(&sbi->s_mb_largest_free_orders_locks[i]);
  833. }
  834. /* Increment cr and search again if no group is found */
  835. *new_cr = CR_GOAL_LEN_FAST;
  836. }
  837. /*
  838. * Find a suitable group of given order from the average fragments list.
  839. */
  840. static struct ext4_group_info *
  841. ext4_mb_find_good_group_avg_frag_lists(struct ext4_allocation_context *ac, int order)
  842. {
  843. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  844. struct list_head *frag_list = &sbi->s_mb_avg_fragment_size[order];
  845. rwlock_t *frag_list_lock = &sbi->s_mb_avg_fragment_size_locks[order];
  846. struct ext4_group_info *grp = NULL, *iter;
  847. enum criteria cr = ac->ac_criteria;
  848. if (list_empty(frag_list))
  849. return NULL;
  850. read_lock(frag_list_lock);
  851. if (list_empty(frag_list)) {
  852. read_unlock(frag_list_lock);
  853. return NULL;
  854. }
  855. list_for_each_entry(iter, frag_list, bb_avg_fragment_size_node) {
  856. if (sbi->s_mb_stats)
  857. atomic64_inc(&sbi->s_bal_cX_groups_considered[cr]);
  858. if (likely(ext4_mb_good_group(ac, iter->bb_group, cr))) {
  859. grp = iter;
  860. break;
  861. }
  862. }
  863. read_unlock(frag_list_lock);
  864. return grp;
  865. }
  866. /*
  867. * Choose next group by traversing average fragment size list of suitable
  868. * order. Updates *new_cr if cr level needs an update.
  869. */
  870. static void ext4_mb_choose_next_group_goal_fast(struct ext4_allocation_context *ac,
  871. enum criteria *new_cr, ext4_group_t *group)
  872. {
  873. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  874. struct ext4_group_info *grp = NULL;
  875. int i;
  876. if (unlikely(ac->ac_flags & EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED)) {
  877. if (sbi->s_mb_stats)
  878. atomic_inc(&sbi->s_bal_goal_fast_bad_suggestions);
  879. }
  880. for (i = mb_avg_fragment_size_order(ac->ac_sb, ac->ac_g_ex.fe_len);
  881. i < MB_NUM_ORDERS(ac->ac_sb); i++) {
  882. grp = ext4_mb_find_good_group_avg_frag_lists(ac, i);
  883. if (grp) {
  884. *group = grp->bb_group;
  885. ac->ac_flags |= EXT4_MB_CR_GOAL_LEN_FAST_OPTIMIZED;
  886. return;
  887. }
  888. }
  889. /*
  890. * CR_BEST_AVAIL_LEN works based on the concept that we have
  891. * a larger normalized goal len request which can be trimmed to
  892. * a smaller goal len such that it can still satisfy original
  893. * request len. However, allocation request for non-regular
  894. * files never gets normalized.
  895. * See function ext4_mb_normalize_request() (EXT4_MB_HINT_DATA).
  896. */
  897. if (ac->ac_flags & EXT4_MB_HINT_DATA)
  898. *new_cr = CR_BEST_AVAIL_LEN;
  899. else
  900. *new_cr = CR_GOAL_LEN_SLOW;
  901. }
  902. /*
  903. * We couldn't find a group in CR_GOAL_LEN_FAST so try to find the highest free fragment
  904. * order we have and proactively trim the goal request length to that order to
  905. * find a suitable group faster.
  906. *
  907. * This optimizes allocation speed at the cost of slightly reduced
  908. * preallocations. However, we make sure that we don't trim the request too
  909. * much and fall to CR_GOAL_LEN_SLOW in that case.
  910. */
  911. static void ext4_mb_choose_next_group_best_avail(struct ext4_allocation_context *ac,
  912. enum criteria *new_cr, ext4_group_t *group)
  913. {
  914. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  915. struct ext4_group_info *grp = NULL;
  916. int i, order, min_order;
  917. unsigned long num_stripe_clusters = 0;
  918. if (unlikely(ac->ac_flags & EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED)) {
  919. if (sbi->s_mb_stats)
  920. atomic_inc(&sbi->s_bal_best_avail_bad_suggestions);
  921. }
  922. /*
  923. * mb_avg_fragment_size_order() returns order in a way that makes
  924. * retrieving back the length using (1 << order) inaccurate. Hence, use
  925. * fls() instead since we need to know the actual length while modifying
  926. * goal length.
  927. */
  928. order = fls(ac->ac_g_ex.fe_len) - 1;
  929. if (WARN_ON_ONCE(order - 1 > MB_NUM_ORDERS(ac->ac_sb)))
  930. order = MB_NUM_ORDERS(ac->ac_sb);
  931. min_order = order - sbi->s_mb_best_avail_max_trim_order;
  932. if (min_order < 0)
  933. min_order = 0;
  934. if (sbi->s_stripe > 0) {
  935. /*
  936. * We are assuming that stripe size is always a multiple of
  937. * cluster ratio otherwise __ext4_fill_super exists early.
  938. */
  939. num_stripe_clusters = EXT4_NUM_B2C(sbi, sbi->s_stripe);
  940. if (1 << min_order < num_stripe_clusters)
  941. /*
  942. * We consider 1 order less because later we round
  943. * up the goal len to num_stripe_clusters
  944. */
  945. min_order = fls(num_stripe_clusters) - 1;
  946. }
  947. if (1 << min_order < ac->ac_o_ex.fe_len)
  948. min_order = fls(ac->ac_o_ex.fe_len);
  949. for (i = order; i >= min_order; i--) {
  950. int frag_order;
  951. /*
  952. * Scale down goal len to make sure we find something
  953. * in the free fragments list. Basically, reduce
  954. * preallocations.
  955. */
  956. ac->ac_g_ex.fe_len = 1 << i;
  957. if (num_stripe_clusters > 0) {
  958. /*
  959. * Try to round up the adjusted goal length to
  960. * stripe size (in cluster units) multiple for
  961. * efficiency.
  962. */
  963. ac->ac_g_ex.fe_len = roundup(ac->ac_g_ex.fe_len,
  964. num_stripe_clusters);
  965. }
  966. frag_order = mb_avg_fragment_size_order(ac->ac_sb,
  967. ac->ac_g_ex.fe_len);
  968. grp = ext4_mb_find_good_group_avg_frag_lists(ac, frag_order);
  969. if (grp) {
  970. *group = grp->bb_group;
  971. ac->ac_flags |= EXT4_MB_CR_BEST_AVAIL_LEN_OPTIMIZED;
  972. return;
  973. }
  974. }
  975. /* Reset goal length to original goal length before falling into CR_GOAL_LEN_SLOW */
  976. ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
  977. *new_cr = CR_GOAL_LEN_SLOW;
  978. }
  979. static inline int should_optimize_scan(struct ext4_allocation_context *ac)
  980. {
  981. if (unlikely(!test_opt2(ac->ac_sb, MB_OPTIMIZE_SCAN)))
  982. return 0;
  983. if (ac->ac_criteria >= CR_GOAL_LEN_SLOW)
  984. return 0;
  985. if (!ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS))
  986. return 0;
  987. return 1;
  988. }
  989. /*
  990. * Return next linear group for allocation.
  991. */
  992. static ext4_group_t
  993. next_linear_group(ext4_group_t group, ext4_group_t ngroups)
  994. {
  995. /*
  996. * Artificially restricted ngroups for non-extent
  997. * files makes group > ngroups possible on first loop.
  998. */
  999. return group + 1 >= ngroups ? 0 : group + 1;
  1000. }
  1001. /*
  1002. * ext4_mb_choose_next_group: choose next group for allocation.
  1003. *
  1004. * @ac Allocation Context
  1005. * @new_cr This is an output parameter. If the there is no good group
  1006. * available at current CR level, this field is updated to indicate
  1007. * the new cr level that should be used.
  1008. * @group This is an input / output parameter. As an input it indicates the
  1009. * next group that the allocator intends to use for allocation. As
  1010. * output, this field indicates the next group that should be used as
  1011. * determined by the optimization functions.
  1012. * @ngroups Total number of groups
  1013. */
  1014. static void ext4_mb_choose_next_group(struct ext4_allocation_context *ac,
  1015. enum criteria *new_cr, ext4_group_t *group, ext4_group_t ngroups)
  1016. {
  1017. *new_cr = ac->ac_criteria;
  1018. if (!should_optimize_scan(ac)) {
  1019. *group = next_linear_group(*group, ngroups);
  1020. return;
  1021. }
  1022. /*
  1023. * Optimized scanning can return non adjacent groups which can cause
  1024. * seek overhead for rotational disks. So try few linear groups before
  1025. * trying optimized scan.
  1026. */
  1027. if (ac->ac_groups_linear_remaining) {
  1028. *group = next_linear_group(*group, ngroups);
  1029. ac->ac_groups_linear_remaining--;
  1030. return;
  1031. }
  1032. if (*new_cr == CR_POWER2_ALIGNED) {
  1033. ext4_mb_choose_next_group_p2_aligned(ac, new_cr, group);
  1034. } else if (*new_cr == CR_GOAL_LEN_FAST) {
  1035. ext4_mb_choose_next_group_goal_fast(ac, new_cr, group);
  1036. } else if (*new_cr == CR_BEST_AVAIL_LEN) {
  1037. ext4_mb_choose_next_group_best_avail(ac, new_cr, group);
  1038. } else {
  1039. /*
  1040. * TODO: For CR_GOAL_LEN_SLOW, we can arrange groups in an
  1041. * rb tree sorted by bb_free. But until that happens, we should
  1042. * never come here.
  1043. */
  1044. WARN_ON(1);
  1045. }
  1046. }
  1047. /*
  1048. * Cache the order of the largest free extent we have available in this block
  1049. * group.
  1050. */
  1051. static void
  1052. mb_set_largest_free_order(struct super_block *sb, struct ext4_group_info *grp)
  1053. {
  1054. struct ext4_sb_info *sbi = EXT4_SB(sb);
  1055. int new, old = grp->bb_largest_free_order;
  1056. for (new = MB_NUM_ORDERS(sb) - 1; new >= 0; new--)
  1057. if (grp->bb_counters[new] > 0)
  1058. break;
  1059. /* No need to move between order lists? */
  1060. if (new == old)
  1061. return;
  1062. if (old >= 0 && !list_empty(&grp->bb_largest_free_order_node)) {
  1063. write_lock(&sbi->s_mb_largest_free_orders_locks[old]);
  1064. list_del_init(&grp->bb_largest_free_order_node);
  1065. write_unlock(&sbi->s_mb_largest_free_orders_locks[old]);
  1066. }
  1067. grp->bb_largest_free_order = new;
  1068. if (test_opt2(sb, MB_OPTIMIZE_SCAN) && new >= 0 && grp->bb_free) {
  1069. write_lock(&sbi->s_mb_largest_free_orders_locks[new]);
  1070. list_add_tail(&grp->bb_largest_free_order_node,
  1071. &sbi->s_mb_largest_free_orders[new]);
  1072. write_unlock(&sbi->s_mb_largest_free_orders_locks[new]);
  1073. }
  1074. }
  1075. static noinline_for_stack
  1076. void ext4_mb_generate_buddy(struct super_block *sb,
  1077. void *buddy, void *bitmap, ext4_group_t group,
  1078. struct ext4_group_info *grp)
  1079. {
  1080. struct ext4_sb_info *sbi = EXT4_SB(sb);
  1081. ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
  1082. ext4_grpblk_t i = 0;
  1083. ext4_grpblk_t first;
  1084. ext4_grpblk_t len;
  1085. unsigned free = 0;
  1086. unsigned fragments = 0;
  1087. unsigned long long period = get_cycles();
  1088. /* initialize buddy from bitmap which is aggregation
  1089. * of on-disk bitmap and preallocations */
  1090. i = mb_find_next_zero_bit(bitmap, max, 0);
  1091. grp->bb_first_free = i;
  1092. while (i < max) {
  1093. fragments++;
  1094. first = i;
  1095. i = mb_find_next_bit(bitmap, max, i);
  1096. len = i - first;
  1097. free += len;
  1098. if (len > 1)
  1099. ext4_mb_mark_free_simple(sb, buddy, first, len, grp);
  1100. else
  1101. grp->bb_counters[0]++;
  1102. if (i < max)
  1103. i = mb_find_next_zero_bit(bitmap, max, i);
  1104. }
  1105. grp->bb_fragments = fragments;
  1106. if (free != grp->bb_free) {
  1107. ext4_grp_locked_error(sb, group, 0, 0,
  1108. "block bitmap and bg descriptor "
  1109. "inconsistent: %u vs %u free clusters",
  1110. free, grp->bb_free);
  1111. /*
  1112. * If we intend to continue, we consider group descriptor
  1113. * corrupt and update bb_free using bitmap value
  1114. */
  1115. grp->bb_free = free;
  1116. ext4_mark_group_bitmap_corrupted(sb, group,
  1117. EXT4_GROUP_INFO_BBITMAP_CORRUPT);
  1118. }
  1119. mb_set_largest_free_order(sb, grp);
  1120. mb_update_avg_fragment_size(sb, grp);
  1121. clear_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &(grp->bb_state));
  1122. period = get_cycles() - period;
  1123. atomic_inc(&sbi->s_mb_buddies_generated);
  1124. atomic64_add(period, &sbi->s_mb_generation_time);
  1125. }
  1126. static void mb_regenerate_buddy(struct ext4_buddy *e4b)
  1127. {
  1128. int count;
  1129. int order = 1;
  1130. void *buddy;
  1131. while ((buddy = mb_find_buddy(e4b, order++, &count)))
  1132. mb_set_bits(buddy, 0, count);
  1133. e4b->bd_info->bb_fragments = 0;
  1134. memset(e4b->bd_info->bb_counters, 0,
  1135. sizeof(*e4b->bd_info->bb_counters) *
  1136. (e4b->bd_sb->s_blocksize_bits + 2));
  1137. ext4_mb_generate_buddy(e4b->bd_sb, e4b->bd_buddy,
  1138. e4b->bd_bitmap, e4b->bd_group, e4b->bd_info);
  1139. }
  1140. /* The buddy information is attached the buddy cache inode
  1141. * for convenience. The information regarding each group
  1142. * is loaded via ext4_mb_load_buddy. The information involve
  1143. * block bitmap and buddy information. The information are
  1144. * stored in the inode as
  1145. *
  1146. * { page }
  1147. * [ group 0 bitmap][ group 0 buddy] [group 1][ group 1]...
  1148. *
  1149. *
  1150. * one block each for bitmap and buddy information.
  1151. * So for each group we take up 2 blocks. A page can
  1152. * contain blocks_per_page (PAGE_SIZE / blocksize) blocks.
  1153. * So it can have information regarding groups_per_page which
  1154. * is blocks_per_page/2
  1155. *
  1156. * Locking note: This routine takes the block group lock of all groups
  1157. * for this page; do not hold this lock when calling this routine!
  1158. */
  1159. static int ext4_mb_init_cache(struct folio *folio, char *incore, gfp_t gfp)
  1160. {
  1161. ext4_group_t ngroups;
  1162. unsigned int blocksize;
  1163. int blocks_per_page;
  1164. int groups_per_page;
  1165. int err = 0;
  1166. int i;
  1167. ext4_group_t first_group, group;
  1168. int first_block;
  1169. struct super_block *sb;
  1170. struct buffer_head *bhs;
  1171. struct buffer_head **bh = NULL;
  1172. struct inode *inode;
  1173. char *data;
  1174. char *bitmap;
  1175. struct ext4_group_info *grinfo;
  1176. inode = folio->mapping->host;
  1177. sb = inode->i_sb;
  1178. ngroups = ext4_get_groups_count(sb);
  1179. blocksize = i_blocksize(inode);
  1180. blocks_per_page = PAGE_SIZE / blocksize;
  1181. mb_debug(sb, "init folio %lu\n", folio->index);
  1182. groups_per_page = blocks_per_page >> 1;
  1183. if (groups_per_page == 0)
  1184. groups_per_page = 1;
  1185. /* allocate buffer_heads to read bitmaps */
  1186. if (groups_per_page > 1) {
  1187. i = sizeof(struct buffer_head *) * groups_per_page;
  1188. bh = kzalloc(i, gfp);
  1189. if (bh == NULL)
  1190. return -ENOMEM;
  1191. } else
  1192. bh = &bhs;
  1193. first_group = folio->index * blocks_per_page / 2;
  1194. /* read all groups the folio covers into the cache */
  1195. for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
  1196. if (group >= ngroups)
  1197. break;
  1198. grinfo = ext4_get_group_info(sb, group);
  1199. if (!grinfo)
  1200. continue;
  1201. /*
  1202. * If page is uptodate then we came here after online resize
  1203. * which added some new uninitialized group info structs, so
  1204. * we must skip all initialized uptodate buddies on the folio,
  1205. * which may be currently in use by an allocating task.
  1206. */
  1207. if (folio_test_uptodate(folio) &&
  1208. !EXT4_MB_GRP_NEED_INIT(grinfo)) {
  1209. bh[i] = NULL;
  1210. continue;
  1211. }
  1212. bh[i] = ext4_read_block_bitmap_nowait(sb, group, false);
  1213. if (IS_ERR(bh[i])) {
  1214. err = PTR_ERR(bh[i]);
  1215. bh[i] = NULL;
  1216. goto out;
  1217. }
  1218. mb_debug(sb, "read bitmap for group %u\n", group);
  1219. }
  1220. /* wait for I/O completion */
  1221. for (i = 0, group = first_group; i < groups_per_page; i++, group++) {
  1222. int err2;
  1223. if (!bh[i])
  1224. continue;
  1225. err2 = ext4_wait_block_bitmap(sb, group, bh[i]);
  1226. if (!err)
  1227. err = err2;
  1228. }
  1229. first_block = folio->index * blocks_per_page;
  1230. for (i = 0; i < blocks_per_page; i++) {
  1231. group = (first_block + i) >> 1;
  1232. if (group >= ngroups)
  1233. break;
  1234. if (!bh[group - first_group])
  1235. /* skip initialized uptodate buddy */
  1236. continue;
  1237. if (!buffer_verified(bh[group - first_group]))
  1238. /* Skip faulty bitmaps */
  1239. continue;
  1240. err = 0;
  1241. /*
  1242. * data carry information regarding this
  1243. * particular group in the format specified
  1244. * above
  1245. *
  1246. */
  1247. data = folio_address(folio) + (i * blocksize);
  1248. bitmap = bh[group - first_group]->b_data;
  1249. /*
  1250. * We place the buddy block and bitmap block
  1251. * close together
  1252. */
  1253. grinfo = ext4_get_group_info(sb, group);
  1254. if (!grinfo) {
  1255. err = -EFSCORRUPTED;
  1256. goto out;
  1257. }
  1258. if ((first_block + i) & 1) {
  1259. /* this is block of buddy */
  1260. BUG_ON(incore == NULL);
  1261. mb_debug(sb, "put buddy for group %u in folio %lu/%x\n",
  1262. group, folio->index, i * blocksize);
  1263. trace_ext4_mb_buddy_bitmap_load(sb, group);
  1264. grinfo->bb_fragments = 0;
  1265. memset(grinfo->bb_counters, 0,
  1266. sizeof(*grinfo->bb_counters) *
  1267. (MB_NUM_ORDERS(sb)));
  1268. /*
  1269. * incore got set to the group block bitmap below
  1270. */
  1271. ext4_lock_group(sb, group);
  1272. /* init the buddy */
  1273. memset(data, 0xff, blocksize);
  1274. ext4_mb_generate_buddy(sb, data, incore, group, grinfo);
  1275. ext4_unlock_group(sb, group);
  1276. incore = NULL;
  1277. } else {
  1278. /* this is block of bitmap */
  1279. BUG_ON(incore != NULL);
  1280. mb_debug(sb, "put bitmap for group %u in folio %lu/%x\n",
  1281. group, folio->index, i * blocksize);
  1282. trace_ext4_mb_bitmap_load(sb, group);
  1283. /* see comments in ext4_mb_put_pa() */
  1284. ext4_lock_group(sb, group);
  1285. memcpy(data, bitmap, blocksize);
  1286. /* mark all preallocated blks used in in-core bitmap */
  1287. ext4_mb_generate_from_pa(sb, data, group);
  1288. WARN_ON_ONCE(!RB_EMPTY_ROOT(&grinfo->bb_free_root));
  1289. ext4_unlock_group(sb, group);
  1290. /* set incore so that the buddy information can be
  1291. * generated using this
  1292. */
  1293. incore = data;
  1294. }
  1295. }
  1296. folio_mark_uptodate(folio);
  1297. out:
  1298. if (bh) {
  1299. for (i = 0; i < groups_per_page; i++)
  1300. brelse(bh[i]);
  1301. if (bh != &bhs)
  1302. kfree(bh);
  1303. }
  1304. return err;
  1305. }
  1306. /*
  1307. * Lock the buddy and bitmap pages. This make sure other parallel init_group
  1308. * on the same buddy page doesn't happen whild holding the buddy page lock.
  1309. * Return locked buddy and bitmap pages on e4b struct. If buddy and bitmap
  1310. * are on the same page e4b->bd_buddy_folio is NULL and return value is 0.
  1311. */
  1312. static int ext4_mb_get_buddy_page_lock(struct super_block *sb,
  1313. ext4_group_t group, struct ext4_buddy *e4b, gfp_t gfp)
  1314. {
  1315. struct inode *inode = EXT4_SB(sb)->s_buddy_cache;
  1316. int block, pnum, poff;
  1317. int blocks_per_page;
  1318. struct folio *folio;
  1319. e4b->bd_buddy_folio = NULL;
  1320. e4b->bd_bitmap_folio = NULL;
  1321. blocks_per_page = PAGE_SIZE / sb->s_blocksize;
  1322. /*
  1323. * the buddy cache inode stores the block bitmap
  1324. * and buddy information in consecutive blocks.
  1325. * So for each group we need two blocks.
  1326. */
  1327. block = group * 2;
  1328. pnum = block / blocks_per_page;
  1329. poff = block % blocks_per_page;
  1330. folio = __filemap_get_folio(inode->i_mapping, pnum,
  1331. FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
  1332. if (IS_ERR(folio))
  1333. return PTR_ERR(folio);
  1334. BUG_ON(folio->mapping != inode->i_mapping);
  1335. e4b->bd_bitmap_folio = folio;
  1336. e4b->bd_bitmap = folio_address(folio) + (poff * sb->s_blocksize);
  1337. if (blocks_per_page >= 2) {
  1338. /* buddy and bitmap are on the same page */
  1339. return 0;
  1340. }
  1341. /* blocks_per_page == 1, hence we need another page for the buddy */
  1342. folio = __filemap_get_folio(inode->i_mapping, block + 1,
  1343. FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
  1344. if (IS_ERR(folio))
  1345. return PTR_ERR(folio);
  1346. BUG_ON(folio->mapping != inode->i_mapping);
  1347. e4b->bd_buddy_folio = folio;
  1348. return 0;
  1349. }
  1350. static void ext4_mb_put_buddy_page_lock(struct ext4_buddy *e4b)
  1351. {
  1352. if (e4b->bd_bitmap_folio) {
  1353. folio_unlock(e4b->bd_bitmap_folio);
  1354. folio_put(e4b->bd_bitmap_folio);
  1355. }
  1356. if (e4b->bd_buddy_folio) {
  1357. folio_unlock(e4b->bd_buddy_folio);
  1358. folio_put(e4b->bd_buddy_folio);
  1359. }
  1360. }
  1361. /*
  1362. * Locking note: This routine calls ext4_mb_init_cache(), which takes the
  1363. * block group lock of all groups for this page; do not hold the BG lock when
  1364. * calling this routine!
  1365. */
  1366. static noinline_for_stack
  1367. int ext4_mb_init_group(struct super_block *sb, ext4_group_t group, gfp_t gfp)
  1368. {
  1369. struct ext4_group_info *this_grp;
  1370. struct ext4_buddy e4b;
  1371. struct folio *folio;
  1372. int ret = 0;
  1373. might_sleep();
  1374. mb_debug(sb, "init group %u\n", group);
  1375. this_grp = ext4_get_group_info(sb, group);
  1376. if (!this_grp)
  1377. return -EFSCORRUPTED;
  1378. /*
  1379. * This ensures that we don't reinit the buddy cache
  1380. * page which map to the group from which we are already
  1381. * allocating. If we are looking at the buddy cache we would
  1382. * have taken a reference using ext4_mb_load_buddy and that
  1383. * would have pinned buddy page to page cache.
  1384. * The call to ext4_mb_get_buddy_page_lock will mark the
  1385. * page accessed.
  1386. */
  1387. ret = ext4_mb_get_buddy_page_lock(sb, group, &e4b, gfp);
  1388. if (ret || !EXT4_MB_GRP_NEED_INIT(this_grp)) {
  1389. /*
  1390. * somebody initialized the group
  1391. * return without doing anything
  1392. */
  1393. goto err;
  1394. }
  1395. folio = e4b.bd_bitmap_folio;
  1396. ret = ext4_mb_init_cache(folio, NULL, gfp);
  1397. if (ret)
  1398. goto err;
  1399. if (!folio_test_uptodate(folio)) {
  1400. ret = -EIO;
  1401. goto err;
  1402. }
  1403. if (e4b.bd_buddy_folio == NULL) {
  1404. /*
  1405. * If both the bitmap and buddy are in
  1406. * the same page we don't need to force
  1407. * init the buddy
  1408. */
  1409. ret = 0;
  1410. goto err;
  1411. }
  1412. /* init buddy cache */
  1413. folio = e4b.bd_buddy_folio;
  1414. ret = ext4_mb_init_cache(folio, e4b.bd_bitmap, gfp);
  1415. if (ret)
  1416. goto err;
  1417. if (!folio_test_uptodate(folio)) {
  1418. ret = -EIO;
  1419. goto err;
  1420. }
  1421. err:
  1422. ext4_mb_put_buddy_page_lock(&e4b);
  1423. return ret;
  1424. }
  1425. /*
  1426. * Locking note: This routine calls ext4_mb_init_cache(), which takes the
  1427. * block group lock of all groups for this page; do not hold the BG lock when
  1428. * calling this routine!
  1429. */
  1430. static noinline_for_stack int
  1431. ext4_mb_load_buddy_gfp(struct super_block *sb, ext4_group_t group,
  1432. struct ext4_buddy *e4b, gfp_t gfp)
  1433. {
  1434. int blocks_per_page;
  1435. int block;
  1436. int pnum;
  1437. int poff;
  1438. struct folio *folio;
  1439. int ret;
  1440. struct ext4_group_info *grp;
  1441. struct ext4_sb_info *sbi = EXT4_SB(sb);
  1442. struct inode *inode = sbi->s_buddy_cache;
  1443. might_sleep();
  1444. mb_debug(sb, "load group %u\n", group);
  1445. blocks_per_page = PAGE_SIZE / sb->s_blocksize;
  1446. grp = ext4_get_group_info(sb, group);
  1447. if (!grp)
  1448. return -EFSCORRUPTED;
  1449. e4b->bd_blkbits = sb->s_blocksize_bits;
  1450. e4b->bd_info = grp;
  1451. e4b->bd_sb = sb;
  1452. e4b->bd_group = group;
  1453. e4b->bd_buddy_folio = NULL;
  1454. e4b->bd_bitmap_folio = NULL;
  1455. if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
  1456. /*
  1457. * we need full data about the group
  1458. * to make a good selection
  1459. */
  1460. ret = ext4_mb_init_group(sb, group, gfp);
  1461. if (ret)
  1462. return ret;
  1463. }
  1464. /*
  1465. * the buddy cache inode stores the block bitmap
  1466. * and buddy information in consecutive blocks.
  1467. * So for each group we need two blocks.
  1468. */
  1469. block = group * 2;
  1470. pnum = block / blocks_per_page;
  1471. poff = block % blocks_per_page;
  1472. /* Avoid locking the folio in the fast path ... */
  1473. folio = __filemap_get_folio(inode->i_mapping, pnum, FGP_ACCESSED, 0);
  1474. if (IS_ERR(folio) || !folio_test_uptodate(folio)) {
  1475. if (!IS_ERR(folio))
  1476. /*
  1477. * drop the folio reference and try
  1478. * to get the folio with lock. If we
  1479. * are not uptodate that implies
  1480. * somebody just created the folio but
  1481. * is yet to initialize it. So
  1482. * wait for it to initialize.
  1483. */
  1484. folio_put(folio);
  1485. folio = __filemap_get_folio(inode->i_mapping, pnum,
  1486. FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
  1487. if (!IS_ERR(folio)) {
  1488. if (WARN_RATELIMIT(folio->mapping != inode->i_mapping,
  1489. "ext4: bitmap's mapping != inode->i_mapping\n")) {
  1490. /* should never happen */
  1491. folio_unlock(folio);
  1492. ret = -EINVAL;
  1493. goto err;
  1494. }
  1495. if (!folio_test_uptodate(folio)) {
  1496. ret = ext4_mb_init_cache(folio, NULL, gfp);
  1497. if (ret) {
  1498. folio_unlock(folio);
  1499. goto err;
  1500. }
  1501. mb_cmp_bitmaps(e4b, folio_address(folio) +
  1502. (poff * sb->s_blocksize));
  1503. }
  1504. folio_unlock(folio);
  1505. }
  1506. }
  1507. if (IS_ERR(folio)) {
  1508. ret = PTR_ERR(folio);
  1509. goto err;
  1510. }
  1511. if (!folio_test_uptodate(folio)) {
  1512. ret = -EIO;
  1513. goto err;
  1514. }
  1515. /* Folios marked accessed already */
  1516. e4b->bd_bitmap_folio = folio;
  1517. e4b->bd_bitmap = folio_address(folio) + (poff * sb->s_blocksize);
  1518. block++;
  1519. pnum = block / blocks_per_page;
  1520. poff = block % blocks_per_page;
  1521. folio = __filemap_get_folio(inode->i_mapping, pnum, FGP_ACCESSED, 0);
  1522. if (IS_ERR(folio) || !folio_test_uptodate(folio)) {
  1523. if (!IS_ERR(folio))
  1524. folio_put(folio);
  1525. folio = __filemap_get_folio(inode->i_mapping, pnum,
  1526. FGP_LOCK | FGP_ACCESSED | FGP_CREAT, gfp);
  1527. if (!IS_ERR(folio)) {
  1528. if (WARN_RATELIMIT(folio->mapping != inode->i_mapping,
  1529. "ext4: buddy bitmap's mapping != inode->i_mapping\n")) {
  1530. /* should never happen */
  1531. folio_unlock(folio);
  1532. ret = -EINVAL;
  1533. goto err;
  1534. }
  1535. if (!folio_test_uptodate(folio)) {
  1536. ret = ext4_mb_init_cache(folio, e4b->bd_bitmap,
  1537. gfp);
  1538. if (ret) {
  1539. folio_unlock(folio);
  1540. goto err;
  1541. }
  1542. }
  1543. folio_unlock(folio);
  1544. }
  1545. }
  1546. if (IS_ERR(folio)) {
  1547. ret = PTR_ERR(folio);
  1548. goto err;
  1549. }
  1550. if (!folio_test_uptodate(folio)) {
  1551. ret = -EIO;
  1552. goto err;
  1553. }
  1554. /* Folios marked accessed already */
  1555. e4b->bd_buddy_folio = folio;
  1556. e4b->bd_buddy = folio_address(folio) + (poff * sb->s_blocksize);
  1557. return 0;
  1558. err:
  1559. if (!IS_ERR_OR_NULL(folio))
  1560. folio_put(folio);
  1561. if (e4b->bd_bitmap_folio)
  1562. folio_put(e4b->bd_bitmap_folio);
  1563. e4b->bd_buddy = NULL;
  1564. e4b->bd_bitmap = NULL;
  1565. return ret;
  1566. }
  1567. static int ext4_mb_load_buddy(struct super_block *sb, ext4_group_t group,
  1568. struct ext4_buddy *e4b)
  1569. {
  1570. return ext4_mb_load_buddy_gfp(sb, group, e4b, GFP_NOFS);
  1571. }
  1572. static void ext4_mb_unload_buddy(struct ext4_buddy *e4b)
  1573. {
  1574. if (e4b->bd_bitmap_folio)
  1575. folio_put(e4b->bd_bitmap_folio);
  1576. if (e4b->bd_buddy_folio)
  1577. folio_put(e4b->bd_buddy_folio);
  1578. }
  1579. static int mb_find_order_for_block(struct ext4_buddy *e4b, int block)
  1580. {
  1581. int order = 1, max;
  1582. void *bb;
  1583. BUG_ON(e4b->bd_bitmap == e4b->bd_buddy);
  1584. BUG_ON(block >= (1 << (e4b->bd_blkbits + 3)));
  1585. while (order <= e4b->bd_blkbits + 1) {
  1586. bb = mb_find_buddy(e4b, order, &max);
  1587. if (!mb_test_bit(block >> order, bb)) {
  1588. /* this block is part of buddy of order 'order' */
  1589. return order;
  1590. }
  1591. order++;
  1592. }
  1593. return 0;
  1594. }
  1595. static void mb_clear_bits(void *bm, int cur, int len)
  1596. {
  1597. __u32 *addr;
  1598. len = cur + len;
  1599. while (cur < len) {
  1600. if ((cur & 31) == 0 && (len - cur) >= 32) {
  1601. /* fast path: clear whole word at once */
  1602. addr = bm + (cur >> 3);
  1603. *addr = 0;
  1604. cur += 32;
  1605. continue;
  1606. }
  1607. mb_clear_bit(cur, bm);
  1608. cur++;
  1609. }
  1610. }
  1611. /* clear bits in given range
  1612. * will return first found zero bit if any, -1 otherwise
  1613. */
  1614. static int mb_test_and_clear_bits(void *bm, int cur, int len)
  1615. {
  1616. __u32 *addr;
  1617. int zero_bit = -1;
  1618. len = cur + len;
  1619. while (cur < len) {
  1620. if ((cur & 31) == 0 && (len - cur) >= 32) {
  1621. /* fast path: clear whole word at once */
  1622. addr = bm + (cur >> 3);
  1623. if (*addr != (__u32)(-1) && zero_bit == -1)
  1624. zero_bit = cur + mb_find_next_zero_bit(addr, 32, 0);
  1625. *addr = 0;
  1626. cur += 32;
  1627. continue;
  1628. }
  1629. if (!mb_test_and_clear_bit(cur, bm) && zero_bit == -1)
  1630. zero_bit = cur;
  1631. cur++;
  1632. }
  1633. return zero_bit;
  1634. }
  1635. void mb_set_bits(void *bm, int cur, int len)
  1636. {
  1637. __u32 *addr;
  1638. len = cur + len;
  1639. while (cur < len) {
  1640. if ((cur & 31) == 0 && (len - cur) >= 32) {
  1641. /* fast path: set whole word at once */
  1642. addr = bm + (cur >> 3);
  1643. *addr = 0xffffffff;
  1644. cur += 32;
  1645. continue;
  1646. }
  1647. mb_set_bit(cur, bm);
  1648. cur++;
  1649. }
  1650. }
  1651. static inline int mb_buddy_adjust_border(int* bit, void* bitmap, int side)
  1652. {
  1653. if (mb_test_bit(*bit + side, bitmap)) {
  1654. mb_clear_bit(*bit, bitmap);
  1655. (*bit) -= side;
  1656. return 1;
  1657. }
  1658. else {
  1659. (*bit) += side;
  1660. mb_set_bit(*bit, bitmap);
  1661. return -1;
  1662. }
  1663. }
  1664. static void mb_buddy_mark_free(struct ext4_buddy *e4b, int first, int last)
  1665. {
  1666. int max;
  1667. int order = 1;
  1668. void *buddy = mb_find_buddy(e4b, order, &max);
  1669. while (buddy) {
  1670. void *buddy2;
  1671. /* Bits in range [first; last] are known to be set since
  1672. * corresponding blocks were allocated. Bits in range
  1673. * (first; last) will stay set because they form buddies on
  1674. * upper layer. We just deal with borders if they don't
  1675. * align with upper layer and then go up.
  1676. * Releasing entire group is all about clearing
  1677. * single bit of highest order buddy.
  1678. */
  1679. /* Example:
  1680. * ---------------------------------
  1681. * | 1 | 1 | 1 | 1 |
  1682. * ---------------------------------
  1683. * | 0 | 1 | 1 | 1 | 1 | 1 | 1 | 1 |
  1684. * ---------------------------------
  1685. * 0 1 2 3 4 5 6 7
  1686. * \_____________________/
  1687. *
  1688. * Neither [1] nor [6] is aligned to above layer.
  1689. * Left neighbour [0] is free, so mark it busy,
  1690. * decrease bb_counters and extend range to
  1691. * [0; 6]
  1692. * Right neighbour [7] is busy. It can't be coaleasced with [6], so
  1693. * mark [6] free, increase bb_counters and shrink range to
  1694. * [0; 5].
  1695. * Then shift range to [0; 2], go up and do the same.
  1696. */
  1697. if (first & 1)
  1698. e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&first, buddy, -1);
  1699. if (!(last & 1))
  1700. e4b->bd_info->bb_counters[order] += mb_buddy_adjust_border(&last, buddy, 1);
  1701. if (first > last)
  1702. break;
  1703. order++;
  1704. buddy2 = mb_find_buddy(e4b, order, &max);
  1705. if (!buddy2) {
  1706. mb_clear_bits(buddy, first, last - first + 1);
  1707. e4b->bd_info->bb_counters[order - 1] += last - first + 1;
  1708. break;
  1709. }
  1710. first >>= 1;
  1711. last >>= 1;
  1712. buddy = buddy2;
  1713. }
  1714. }
  1715. static void mb_free_blocks(struct inode *inode, struct ext4_buddy *e4b,
  1716. int first, int count)
  1717. {
  1718. int left_is_free = 0;
  1719. int right_is_free = 0;
  1720. int block;
  1721. int last = first + count - 1;
  1722. struct super_block *sb = e4b->bd_sb;
  1723. if (WARN_ON(count == 0))
  1724. return;
  1725. BUG_ON(last >= (sb->s_blocksize << 3));
  1726. assert_spin_locked(ext4_group_lock_ptr(sb, e4b->bd_group));
  1727. /* Don't bother if the block group is corrupt. */
  1728. if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
  1729. return;
  1730. mb_check_buddy(e4b);
  1731. mb_free_blocks_double(inode, e4b, first, count);
  1732. /* access memory sequentially: check left neighbour,
  1733. * clear range and then check right neighbour
  1734. */
  1735. if (first != 0)
  1736. left_is_free = !mb_test_bit(first - 1, e4b->bd_bitmap);
  1737. block = mb_test_and_clear_bits(e4b->bd_bitmap, first, count);
  1738. if (last + 1 < EXT4_SB(sb)->s_mb_maxs[0])
  1739. right_is_free = !mb_test_bit(last + 1, e4b->bd_bitmap);
  1740. if (unlikely(block != -1)) {
  1741. struct ext4_sb_info *sbi = EXT4_SB(sb);
  1742. ext4_fsblk_t blocknr;
  1743. /*
  1744. * Fastcommit replay can free already freed blocks which
  1745. * corrupts allocation info. Regenerate it.
  1746. */
  1747. if (sbi->s_mount_state & EXT4_FC_REPLAY) {
  1748. mb_regenerate_buddy(e4b);
  1749. goto check;
  1750. }
  1751. blocknr = ext4_group_first_block_no(sb, e4b->bd_group);
  1752. blocknr += EXT4_C2B(sbi, block);
  1753. ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
  1754. EXT4_GROUP_INFO_BBITMAP_CORRUPT);
  1755. ext4_grp_locked_error(sb, e4b->bd_group,
  1756. inode ? inode->i_ino : 0, blocknr,
  1757. "freeing already freed block (bit %u); block bitmap corrupt.",
  1758. block);
  1759. return;
  1760. }
  1761. this_cpu_inc(discard_pa_seq);
  1762. e4b->bd_info->bb_free += count;
  1763. if (first < e4b->bd_info->bb_first_free)
  1764. e4b->bd_info->bb_first_free = first;
  1765. /* let's maintain fragments counter */
  1766. if (left_is_free && right_is_free)
  1767. e4b->bd_info->bb_fragments--;
  1768. else if (!left_is_free && !right_is_free)
  1769. e4b->bd_info->bb_fragments++;
  1770. /* buddy[0] == bd_bitmap is a special case, so handle
  1771. * it right away and let mb_buddy_mark_free stay free of
  1772. * zero order checks.
  1773. * Check if neighbours are to be coaleasced,
  1774. * adjust bitmap bb_counters and borders appropriately.
  1775. */
  1776. if (first & 1) {
  1777. first += !left_is_free;
  1778. e4b->bd_info->bb_counters[0] += left_is_free ? -1 : 1;
  1779. }
  1780. if (!(last & 1)) {
  1781. last -= !right_is_free;
  1782. e4b->bd_info->bb_counters[0] += right_is_free ? -1 : 1;
  1783. }
  1784. if (first <= last)
  1785. mb_buddy_mark_free(e4b, first >> 1, last >> 1);
  1786. mb_set_largest_free_order(sb, e4b->bd_info);
  1787. mb_update_avg_fragment_size(sb, e4b->bd_info);
  1788. check:
  1789. mb_check_buddy(e4b);
  1790. }
  1791. static int mb_find_extent(struct ext4_buddy *e4b, int block,
  1792. int needed, struct ext4_free_extent *ex)
  1793. {
  1794. int max, order, next;
  1795. void *buddy;
  1796. assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
  1797. BUG_ON(ex == NULL);
  1798. buddy = mb_find_buddy(e4b, 0, &max);
  1799. BUG_ON(buddy == NULL);
  1800. BUG_ON(block >= max);
  1801. if (mb_test_bit(block, buddy)) {
  1802. ex->fe_len = 0;
  1803. ex->fe_start = 0;
  1804. ex->fe_group = 0;
  1805. return 0;
  1806. }
  1807. /* find actual order */
  1808. order = mb_find_order_for_block(e4b, block);
  1809. ex->fe_len = (1 << order) - (block & ((1 << order) - 1));
  1810. ex->fe_start = block;
  1811. ex->fe_group = e4b->bd_group;
  1812. block = block >> order;
  1813. while (needed > ex->fe_len &&
  1814. mb_find_buddy(e4b, order, &max)) {
  1815. if (block + 1 >= max)
  1816. break;
  1817. next = (block + 1) * (1 << order);
  1818. if (mb_test_bit(next, e4b->bd_bitmap))
  1819. break;
  1820. order = mb_find_order_for_block(e4b, next);
  1821. block = next >> order;
  1822. ex->fe_len += 1 << order;
  1823. }
  1824. if (ex->fe_start + ex->fe_len > EXT4_CLUSTERS_PER_GROUP(e4b->bd_sb)) {
  1825. /* Should never happen! (but apparently sometimes does?!?) */
  1826. WARN_ON(1);
  1827. ext4_grp_locked_error(e4b->bd_sb, e4b->bd_group, 0, 0,
  1828. "corruption or bug in mb_find_extent "
  1829. "block=%d, order=%d needed=%d ex=%u/%d/%d@%u",
  1830. block, order, needed, ex->fe_group, ex->fe_start,
  1831. ex->fe_len, ex->fe_logical);
  1832. ex->fe_len = 0;
  1833. ex->fe_start = 0;
  1834. ex->fe_group = 0;
  1835. }
  1836. return ex->fe_len;
  1837. }
  1838. static int mb_mark_used(struct ext4_buddy *e4b, struct ext4_free_extent *ex)
  1839. {
  1840. int ord;
  1841. int mlen = 0;
  1842. int max = 0;
  1843. int start = ex->fe_start;
  1844. int len = ex->fe_len;
  1845. unsigned ret = 0;
  1846. int len0 = len;
  1847. void *buddy;
  1848. int ord_start, ord_end;
  1849. BUG_ON(start + len > (e4b->bd_sb->s_blocksize << 3));
  1850. BUG_ON(e4b->bd_group != ex->fe_group);
  1851. assert_spin_locked(ext4_group_lock_ptr(e4b->bd_sb, e4b->bd_group));
  1852. mb_check_buddy(e4b);
  1853. mb_mark_used_double(e4b, start, len);
  1854. this_cpu_inc(discard_pa_seq);
  1855. e4b->bd_info->bb_free -= len;
  1856. if (e4b->bd_info->bb_first_free == start)
  1857. e4b->bd_info->bb_first_free += len;
  1858. /* let's maintain fragments counter */
  1859. if (start != 0)
  1860. mlen = !mb_test_bit(start - 1, e4b->bd_bitmap);
  1861. if (start + len < EXT4_SB(e4b->bd_sb)->s_mb_maxs[0])
  1862. max = !mb_test_bit(start + len, e4b->bd_bitmap);
  1863. if (mlen && max)
  1864. e4b->bd_info->bb_fragments++;
  1865. else if (!mlen && !max)
  1866. e4b->bd_info->bb_fragments--;
  1867. /* let's maintain buddy itself */
  1868. while (len) {
  1869. ord = mb_find_order_for_block(e4b, start);
  1870. if (((start >> ord) << ord) == start && len >= (1 << ord)) {
  1871. /* the whole chunk may be allocated at once! */
  1872. mlen = 1 << ord;
  1873. buddy = mb_find_buddy(e4b, ord, &max);
  1874. BUG_ON((start >> ord) >= max);
  1875. mb_set_bit(start >> ord, buddy);
  1876. e4b->bd_info->bb_counters[ord]--;
  1877. start += mlen;
  1878. len -= mlen;
  1879. BUG_ON(len < 0);
  1880. continue;
  1881. }
  1882. /* store for history */
  1883. if (ret == 0)
  1884. ret = len | (ord << 16);
  1885. BUG_ON(ord <= 0);
  1886. buddy = mb_find_buddy(e4b, ord, &max);
  1887. mb_set_bit(start >> ord, buddy);
  1888. e4b->bd_info->bb_counters[ord]--;
  1889. ord_start = (start >> ord) << ord;
  1890. ord_end = ord_start + (1 << ord);
  1891. /* first chunk */
  1892. if (start > ord_start)
  1893. ext4_mb_mark_free_simple(e4b->bd_sb, e4b->bd_buddy,
  1894. ord_start, start - ord_start,
  1895. e4b->bd_info);
  1896. /* last chunk */
  1897. if (start + len < ord_end) {
  1898. ext4_mb_mark_free_simple(e4b->bd_sb, e4b->bd_buddy,
  1899. start + len,
  1900. ord_end - (start + len),
  1901. e4b->bd_info);
  1902. break;
  1903. }
  1904. len = start + len - ord_end;
  1905. start = ord_end;
  1906. }
  1907. mb_set_largest_free_order(e4b->bd_sb, e4b->bd_info);
  1908. mb_update_avg_fragment_size(e4b->bd_sb, e4b->bd_info);
  1909. mb_set_bits(e4b->bd_bitmap, ex->fe_start, len0);
  1910. mb_check_buddy(e4b);
  1911. return ret;
  1912. }
  1913. /*
  1914. * Must be called under group lock!
  1915. */
  1916. static void ext4_mb_use_best_found(struct ext4_allocation_context *ac,
  1917. struct ext4_buddy *e4b)
  1918. {
  1919. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  1920. int ret;
  1921. BUG_ON(ac->ac_b_ex.fe_group != e4b->bd_group);
  1922. BUG_ON(ac->ac_status == AC_STATUS_FOUND);
  1923. ac->ac_b_ex.fe_len = min(ac->ac_b_ex.fe_len, ac->ac_g_ex.fe_len);
  1924. ac->ac_b_ex.fe_logical = ac->ac_g_ex.fe_logical;
  1925. ret = mb_mark_used(e4b, &ac->ac_b_ex);
  1926. /* preallocation can change ac_b_ex, thus we store actually
  1927. * allocated blocks for history */
  1928. ac->ac_f_ex = ac->ac_b_ex;
  1929. ac->ac_status = AC_STATUS_FOUND;
  1930. ac->ac_tail = ret & 0xffff;
  1931. ac->ac_buddy = ret >> 16;
  1932. /*
  1933. * take the page reference. We want the page to be pinned
  1934. * so that we don't get a ext4_mb_init_cache_call for this
  1935. * group until we update the bitmap. That would mean we
  1936. * double allocate blocks. The reference is dropped
  1937. * in ext4_mb_release_context
  1938. */
  1939. ac->ac_bitmap_folio = e4b->bd_bitmap_folio;
  1940. folio_get(ac->ac_bitmap_folio);
  1941. ac->ac_buddy_folio = e4b->bd_buddy_folio;
  1942. folio_get(ac->ac_buddy_folio);
  1943. /* store last allocated for subsequent stream allocation */
  1944. if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
  1945. spin_lock(&sbi->s_md_lock);
  1946. sbi->s_mb_last_group = ac->ac_f_ex.fe_group;
  1947. sbi->s_mb_last_start = ac->ac_f_ex.fe_start;
  1948. spin_unlock(&sbi->s_md_lock);
  1949. }
  1950. /*
  1951. * As we've just preallocated more space than
  1952. * user requested originally, we store allocated
  1953. * space in a special descriptor.
  1954. */
  1955. if (ac->ac_o_ex.fe_len < ac->ac_b_ex.fe_len)
  1956. ext4_mb_new_preallocation(ac);
  1957. }
  1958. static void ext4_mb_check_limits(struct ext4_allocation_context *ac,
  1959. struct ext4_buddy *e4b,
  1960. int finish_group)
  1961. {
  1962. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  1963. struct ext4_free_extent *bex = &ac->ac_b_ex;
  1964. struct ext4_free_extent *gex = &ac->ac_g_ex;
  1965. if (ac->ac_status == AC_STATUS_FOUND)
  1966. return;
  1967. /*
  1968. * We don't want to scan for a whole year
  1969. */
  1970. if (ac->ac_found > sbi->s_mb_max_to_scan &&
  1971. !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
  1972. ac->ac_status = AC_STATUS_BREAK;
  1973. return;
  1974. }
  1975. /*
  1976. * Haven't found good chunk so far, let's continue
  1977. */
  1978. if (bex->fe_len < gex->fe_len)
  1979. return;
  1980. if (finish_group || ac->ac_found > sbi->s_mb_min_to_scan)
  1981. ext4_mb_use_best_found(ac, e4b);
  1982. }
  1983. /*
  1984. * The routine checks whether found extent is good enough. If it is,
  1985. * then the extent gets marked used and flag is set to the context
  1986. * to stop scanning. Otherwise, the extent is compared with the
  1987. * previous found extent and if new one is better, then it's stored
  1988. * in the context. Later, the best found extent will be used, if
  1989. * mballoc can't find good enough extent.
  1990. *
  1991. * The algorithm used is roughly as follows:
  1992. *
  1993. * * If free extent found is exactly as big as goal, then
  1994. * stop the scan and use it immediately
  1995. *
  1996. * * If free extent found is smaller than goal, then keep retrying
  1997. * upto a max of sbi->s_mb_max_to_scan times (default 200). After
  1998. * that stop scanning and use whatever we have.
  1999. *
  2000. * * If free extent found is bigger than goal, then keep retrying
  2001. * upto a max of sbi->s_mb_min_to_scan times (default 10) before
  2002. * stopping the scan and using the extent.
  2003. *
  2004. *
  2005. * FIXME: real allocation policy is to be designed yet!
  2006. */
  2007. static void ext4_mb_measure_extent(struct ext4_allocation_context *ac,
  2008. struct ext4_free_extent *ex,
  2009. struct ext4_buddy *e4b)
  2010. {
  2011. struct ext4_free_extent *bex = &ac->ac_b_ex;
  2012. struct ext4_free_extent *gex = &ac->ac_g_ex;
  2013. BUG_ON(ex->fe_len <= 0);
  2014. BUG_ON(ex->fe_len > EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
  2015. BUG_ON(ex->fe_start >= EXT4_CLUSTERS_PER_GROUP(ac->ac_sb));
  2016. BUG_ON(ac->ac_status != AC_STATUS_CONTINUE);
  2017. ac->ac_found++;
  2018. ac->ac_cX_found[ac->ac_criteria]++;
  2019. /*
  2020. * The special case - take what you catch first
  2021. */
  2022. if (unlikely(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
  2023. *bex = *ex;
  2024. ext4_mb_use_best_found(ac, e4b);
  2025. return;
  2026. }
  2027. /*
  2028. * Let's check whether the chuck is good enough
  2029. */
  2030. if (ex->fe_len == gex->fe_len) {
  2031. *bex = *ex;
  2032. ext4_mb_use_best_found(ac, e4b);
  2033. return;
  2034. }
  2035. /*
  2036. * If this is first found extent, just store it in the context
  2037. */
  2038. if (bex->fe_len == 0) {
  2039. *bex = *ex;
  2040. return;
  2041. }
  2042. /*
  2043. * If new found extent is better, store it in the context
  2044. */
  2045. if (bex->fe_len < gex->fe_len) {
  2046. /* if the request isn't satisfied, any found extent
  2047. * larger than previous best one is better */
  2048. if (ex->fe_len > bex->fe_len)
  2049. *bex = *ex;
  2050. } else if (ex->fe_len > gex->fe_len) {
  2051. /* if the request is satisfied, then we try to find
  2052. * an extent that still satisfy the request, but is
  2053. * smaller than previous one */
  2054. if (ex->fe_len < bex->fe_len)
  2055. *bex = *ex;
  2056. }
  2057. ext4_mb_check_limits(ac, e4b, 0);
  2058. }
  2059. static noinline_for_stack
  2060. void ext4_mb_try_best_found(struct ext4_allocation_context *ac,
  2061. struct ext4_buddy *e4b)
  2062. {
  2063. struct ext4_free_extent ex = ac->ac_b_ex;
  2064. ext4_group_t group = ex.fe_group;
  2065. int max;
  2066. int err;
  2067. BUG_ON(ex.fe_len <= 0);
  2068. err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
  2069. if (err)
  2070. return;
  2071. ext4_lock_group(ac->ac_sb, group);
  2072. if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
  2073. goto out;
  2074. max = mb_find_extent(e4b, ex.fe_start, ex.fe_len, &ex);
  2075. if (max > 0) {
  2076. ac->ac_b_ex = ex;
  2077. ext4_mb_use_best_found(ac, e4b);
  2078. }
  2079. out:
  2080. ext4_unlock_group(ac->ac_sb, group);
  2081. ext4_mb_unload_buddy(e4b);
  2082. }
  2083. static noinline_for_stack
  2084. int ext4_mb_find_by_goal(struct ext4_allocation_context *ac,
  2085. struct ext4_buddy *e4b)
  2086. {
  2087. ext4_group_t group = ac->ac_g_ex.fe_group;
  2088. int max;
  2089. int err;
  2090. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  2091. struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
  2092. struct ext4_free_extent ex;
  2093. if (!grp)
  2094. return -EFSCORRUPTED;
  2095. if (!(ac->ac_flags & (EXT4_MB_HINT_TRY_GOAL | EXT4_MB_HINT_GOAL_ONLY)))
  2096. return 0;
  2097. if (grp->bb_free == 0)
  2098. return 0;
  2099. err = ext4_mb_load_buddy(ac->ac_sb, group, e4b);
  2100. if (err)
  2101. return err;
  2102. ext4_lock_group(ac->ac_sb, group);
  2103. if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
  2104. goto out;
  2105. max = mb_find_extent(e4b, ac->ac_g_ex.fe_start,
  2106. ac->ac_g_ex.fe_len, &ex);
  2107. ex.fe_logical = 0xDEADFA11; /* debug value */
  2108. if (max >= ac->ac_g_ex.fe_len &&
  2109. ac->ac_g_ex.fe_len == EXT4_NUM_B2C(sbi, sbi->s_stripe)) {
  2110. ext4_fsblk_t start;
  2111. start = ext4_grp_offs_to_block(ac->ac_sb, &ex);
  2112. /* use do_div to get remainder (would be 64-bit modulo) */
  2113. if (do_div(start, sbi->s_stripe) == 0) {
  2114. ac->ac_found++;
  2115. ac->ac_b_ex = ex;
  2116. ext4_mb_use_best_found(ac, e4b);
  2117. }
  2118. } else if (max >= ac->ac_g_ex.fe_len) {
  2119. BUG_ON(ex.fe_len <= 0);
  2120. BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
  2121. BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
  2122. ac->ac_found++;
  2123. ac->ac_b_ex = ex;
  2124. ext4_mb_use_best_found(ac, e4b);
  2125. } else if (max > 0 && (ac->ac_flags & EXT4_MB_HINT_MERGE)) {
  2126. /* Sometimes, caller may want to merge even small
  2127. * number of blocks to an existing extent */
  2128. BUG_ON(ex.fe_len <= 0);
  2129. BUG_ON(ex.fe_group != ac->ac_g_ex.fe_group);
  2130. BUG_ON(ex.fe_start != ac->ac_g_ex.fe_start);
  2131. ac->ac_found++;
  2132. ac->ac_b_ex = ex;
  2133. ext4_mb_use_best_found(ac, e4b);
  2134. }
  2135. out:
  2136. ext4_unlock_group(ac->ac_sb, group);
  2137. ext4_mb_unload_buddy(e4b);
  2138. return 0;
  2139. }
  2140. /*
  2141. * The routine scans buddy structures (not bitmap!) from given order
  2142. * to max order and tries to find big enough chunk to satisfy the req
  2143. */
  2144. static noinline_for_stack
  2145. void ext4_mb_simple_scan_group(struct ext4_allocation_context *ac,
  2146. struct ext4_buddy *e4b)
  2147. {
  2148. struct super_block *sb = ac->ac_sb;
  2149. struct ext4_group_info *grp = e4b->bd_info;
  2150. void *buddy;
  2151. int i;
  2152. int k;
  2153. int max;
  2154. BUG_ON(ac->ac_2order <= 0);
  2155. for (i = ac->ac_2order; i < MB_NUM_ORDERS(sb); i++) {
  2156. if (grp->bb_counters[i] == 0)
  2157. continue;
  2158. buddy = mb_find_buddy(e4b, i, &max);
  2159. if (WARN_RATELIMIT(buddy == NULL,
  2160. "ext4: mb_simple_scan_group: mb_find_buddy failed, (%d)\n", i))
  2161. continue;
  2162. k = mb_find_next_zero_bit(buddy, max, 0);
  2163. if (k >= max) {
  2164. ext4_mark_group_bitmap_corrupted(ac->ac_sb,
  2165. e4b->bd_group,
  2166. EXT4_GROUP_INFO_BBITMAP_CORRUPT);
  2167. ext4_grp_locked_error(ac->ac_sb, e4b->bd_group, 0, 0,
  2168. "%d free clusters of order %d. But found 0",
  2169. grp->bb_counters[i], i);
  2170. break;
  2171. }
  2172. ac->ac_found++;
  2173. ac->ac_cX_found[ac->ac_criteria]++;
  2174. ac->ac_b_ex.fe_len = 1 << i;
  2175. ac->ac_b_ex.fe_start = k << i;
  2176. ac->ac_b_ex.fe_group = e4b->bd_group;
  2177. ext4_mb_use_best_found(ac, e4b);
  2178. BUG_ON(ac->ac_f_ex.fe_len != ac->ac_g_ex.fe_len);
  2179. if (EXT4_SB(sb)->s_mb_stats)
  2180. atomic_inc(&EXT4_SB(sb)->s_bal_2orders);
  2181. break;
  2182. }
  2183. }
  2184. /*
  2185. * The routine scans the group and measures all found extents.
  2186. * In order to optimize scanning, caller must pass number of
  2187. * free blocks in the group, so the routine can know upper limit.
  2188. */
  2189. static noinline_for_stack
  2190. void ext4_mb_complex_scan_group(struct ext4_allocation_context *ac,
  2191. struct ext4_buddy *e4b)
  2192. {
  2193. struct super_block *sb = ac->ac_sb;
  2194. void *bitmap = e4b->bd_bitmap;
  2195. struct ext4_free_extent ex;
  2196. int i, j, freelen;
  2197. int free;
  2198. free = e4b->bd_info->bb_free;
  2199. if (WARN_ON(free <= 0))
  2200. return;
  2201. i = e4b->bd_info->bb_first_free;
  2202. while (free && ac->ac_status == AC_STATUS_CONTINUE) {
  2203. i = mb_find_next_zero_bit(bitmap,
  2204. EXT4_CLUSTERS_PER_GROUP(sb), i);
  2205. if (i >= EXT4_CLUSTERS_PER_GROUP(sb)) {
  2206. /*
  2207. * IF we have corrupt bitmap, we won't find any
  2208. * free blocks even though group info says we
  2209. * have free blocks
  2210. */
  2211. ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
  2212. EXT4_GROUP_INFO_BBITMAP_CORRUPT);
  2213. ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
  2214. "%d free clusters as per "
  2215. "group info. But bitmap says 0",
  2216. free);
  2217. break;
  2218. }
  2219. if (!ext4_mb_cr_expensive(ac->ac_criteria)) {
  2220. /*
  2221. * In CR_GOAL_LEN_FAST and CR_BEST_AVAIL_LEN, we are
  2222. * sure that this group will have a large enough
  2223. * continuous free extent, so skip over the smaller free
  2224. * extents
  2225. */
  2226. j = mb_find_next_bit(bitmap,
  2227. EXT4_CLUSTERS_PER_GROUP(sb), i);
  2228. freelen = j - i;
  2229. if (freelen < ac->ac_g_ex.fe_len) {
  2230. i = j;
  2231. free -= freelen;
  2232. continue;
  2233. }
  2234. }
  2235. mb_find_extent(e4b, i, ac->ac_g_ex.fe_len, &ex);
  2236. if (WARN_ON(ex.fe_len <= 0))
  2237. break;
  2238. if (free < ex.fe_len) {
  2239. ext4_mark_group_bitmap_corrupted(sb, e4b->bd_group,
  2240. EXT4_GROUP_INFO_BBITMAP_CORRUPT);
  2241. ext4_grp_locked_error(sb, e4b->bd_group, 0, 0,
  2242. "%d free clusters as per "
  2243. "group info. But got %d blocks",
  2244. free, ex.fe_len);
  2245. /*
  2246. * The number of free blocks differs. This mostly
  2247. * indicate that the bitmap is corrupt. So exit
  2248. * without claiming the space.
  2249. */
  2250. break;
  2251. }
  2252. ex.fe_logical = 0xDEADC0DE; /* debug value */
  2253. ext4_mb_measure_extent(ac, &ex, e4b);
  2254. i += ex.fe_len;
  2255. free -= ex.fe_len;
  2256. }
  2257. ext4_mb_check_limits(ac, e4b, 1);
  2258. }
  2259. /*
  2260. * This is a special case for storages like raid5
  2261. * we try to find stripe-aligned chunks for stripe-size-multiple requests
  2262. */
  2263. static noinline_for_stack
  2264. void ext4_mb_scan_aligned(struct ext4_allocation_context *ac,
  2265. struct ext4_buddy *e4b)
  2266. {
  2267. struct super_block *sb = ac->ac_sb;
  2268. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2269. void *bitmap = e4b->bd_bitmap;
  2270. struct ext4_free_extent ex;
  2271. ext4_fsblk_t first_group_block;
  2272. ext4_fsblk_t a;
  2273. ext4_grpblk_t i, stripe;
  2274. int max;
  2275. BUG_ON(sbi->s_stripe == 0);
  2276. /* find first stripe-aligned block in group */
  2277. first_group_block = ext4_group_first_block_no(sb, e4b->bd_group);
  2278. a = first_group_block + sbi->s_stripe - 1;
  2279. do_div(a, sbi->s_stripe);
  2280. i = (a * sbi->s_stripe) - first_group_block;
  2281. stripe = EXT4_NUM_B2C(sbi, sbi->s_stripe);
  2282. i = EXT4_B2C(sbi, i);
  2283. while (i < EXT4_CLUSTERS_PER_GROUP(sb)) {
  2284. if (!mb_test_bit(i, bitmap)) {
  2285. max = mb_find_extent(e4b, i, stripe, &ex);
  2286. if (max >= stripe) {
  2287. ac->ac_found++;
  2288. ac->ac_cX_found[ac->ac_criteria]++;
  2289. ex.fe_logical = 0xDEADF00D; /* debug value */
  2290. ac->ac_b_ex = ex;
  2291. ext4_mb_use_best_found(ac, e4b);
  2292. break;
  2293. }
  2294. }
  2295. i += stripe;
  2296. }
  2297. }
  2298. /*
  2299. * This is also called BEFORE we load the buddy bitmap.
  2300. * Returns either 1 or 0 indicating that the group is either suitable
  2301. * for the allocation or not.
  2302. */
  2303. static bool ext4_mb_good_group(struct ext4_allocation_context *ac,
  2304. ext4_group_t group, enum criteria cr)
  2305. {
  2306. ext4_grpblk_t free, fragments;
  2307. int flex_size = ext4_flex_bg_size(EXT4_SB(ac->ac_sb));
  2308. struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
  2309. BUG_ON(cr < CR_POWER2_ALIGNED || cr >= EXT4_MB_NUM_CRS);
  2310. if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
  2311. return false;
  2312. free = grp->bb_free;
  2313. if (free == 0)
  2314. return false;
  2315. fragments = grp->bb_fragments;
  2316. if (fragments == 0)
  2317. return false;
  2318. switch (cr) {
  2319. case CR_POWER2_ALIGNED:
  2320. BUG_ON(ac->ac_2order == 0);
  2321. /* Avoid using the first bg of a flexgroup for data files */
  2322. if ((ac->ac_flags & EXT4_MB_HINT_DATA) &&
  2323. (flex_size >= EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME) &&
  2324. ((group % flex_size) == 0))
  2325. return false;
  2326. if (free < ac->ac_g_ex.fe_len)
  2327. return false;
  2328. if (ac->ac_2order >= MB_NUM_ORDERS(ac->ac_sb))
  2329. return true;
  2330. if (grp->bb_largest_free_order < ac->ac_2order)
  2331. return false;
  2332. return true;
  2333. case CR_GOAL_LEN_FAST:
  2334. case CR_BEST_AVAIL_LEN:
  2335. if ((free / fragments) >= ac->ac_g_ex.fe_len)
  2336. return true;
  2337. break;
  2338. case CR_GOAL_LEN_SLOW:
  2339. if (free >= ac->ac_g_ex.fe_len)
  2340. return true;
  2341. break;
  2342. case CR_ANY_FREE:
  2343. return true;
  2344. default:
  2345. BUG();
  2346. }
  2347. return false;
  2348. }
  2349. /*
  2350. * This could return negative error code if something goes wrong
  2351. * during ext4_mb_init_group(). This should not be called with
  2352. * ext4_lock_group() held.
  2353. *
  2354. * Note: because we are conditionally operating with the group lock in
  2355. * the EXT4_MB_STRICT_CHECK case, we need to fake out sparse in this
  2356. * function using __acquire and __release. This means we need to be
  2357. * super careful before messing with the error path handling via "goto
  2358. * out"!
  2359. */
  2360. static int ext4_mb_good_group_nolock(struct ext4_allocation_context *ac,
  2361. ext4_group_t group, enum criteria cr)
  2362. {
  2363. struct ext4_group_info *grp = ext4_get_group_info(ac->ac_sb, group);
  2364. struct super_block *sb = ac->ac_sb;
  2365. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2366. bool should_lock = ac->ac_flags & EXT4_MB_STRICT_CHECK;
  2367. ext4_grpblk_t free;
  2368. int ret = 0;
  2369. if (!grp)
  2370. return -EFSCORRUPTED;
  2371. if (sbi->s_mb_stats)
  2372. atomic64_inc(&sbi->s_bal_cX_groups_considered[ac->ac_criteria]);
  2373. if (should_lock) {
  2374. ext4_lock_group(sb, group);
  2375. __release(ext4_group_lock_ptr(sb, group));
  2376. }
  2377. free = grp->bb_free;
  2378. if (free == 0)
  2379. goto out;
  2380. /*
  2381. * In all criterias except CR_ANY_FREE we try to avoid groups that
  2382. * can't possibly satisfy the full goal request due to insufficient
  2383. * free blocks.
  2384. */
  2385. if (cr < CR_ANY_FREE && free < ac->ac_g_ex.fe_len)
  2386. goto out;
  2387. if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
  2388. goto out;
  2389. if (should_lock) {
  2390. __acquire(ext4_group_lock_ptr(sb, group));
  2391. ext4_unlock_group(sb, group);
  2392. }
  2393. /* We only do this if the grp has never been initialized */
  2394. if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
  2395. struct ext4_group_desc *gdp =
  2396. ext4_get_group_desc(sb, group, NULL);
  2397. int ret;
  2398. /*
  2399. * CR_POWER2_ALIGNED/CR_GOAL_LEN_FAST is a very optimistic
  2400. * search to find large good chunks almost for free. If buddy
  2401. * data is not ready, then this optimization makes no sense. But
  2402. * we never skip the first block group in a flex_bg, since this
  2403. * gets used for metadata block allocation, and we want to make
  2404. * sure we locate metadata blocks in the first block group in
  2405. * the flex_bg if possible.
  2406. */
  2407. if (!ext4_mb_cr_expensive(cr) &&
  2408. (!sbi->s_log_groups_per_flex ||
  2409. ((group & ((1 << sbi->s_log_groups_per_flex) - 1)) != 0)) &&
  2410. !(ext4_has_group_desc_csum(sb) &&
  2411. (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))))
  2412. return 0;
  2413. ret = ext4_mb_init_group(sb, group, GFP_NOFS);
  2414. if (ret)
  2415. return ret;
  2416. }
  2417. if (should_lock) {
  2418. ext4_lock_group(sb, group);
  2419. __release(ext4_group_lock_ptr(sb, group));
  2420. }
  2421. ret = ext4_mb_good_group(ac, group, cr);
  2422. out:
  2423. if (should_lock) {
  2424. __acquire(ext4_group_lock_ptr(sb, group));
  2425. ext4_unlock_group(sb, group);
  2426. }
  2427. return ret;
  2428. }
  2429. /*
  2430. * Start prefetching @nr block bitmaps starting at @group.
  2431. * Return the next group which needs to be prefetched.
  2432. */
  2433. ext4_group_t ext4_mb_prefetch(struct super_block *sb, ext4_group_t group,
  2434. unsigned int nr, int *cnt)
  2435. {
  2436. ext4_group_t ngroups = ext4_get_groups_count(sb);
  2437. struct buffer_head *bh;
  2438. struct blk_plug plug;
  2439. blk_start_plug(&plug);
  2440. while (nr-- > 0) {
  2441. struct ext4_group_desc *gdp = ext4_get_group_desc(sb, group,
  2442. NULL);
  2443. struct ext4_group_info *grp = ext4_get_group_info(sb, group);
  2444. /*
  2445. * Prefetch block groups with free blocks; but don't
  2446. * bother if it is marked uninitialized on disk, since
  2447. * it won't require I/O to read. Also only try to
  2448. * prefetch once, so we avoid getblk() call, which can
  2449. * be expensive.
  2450. */
  2451. if (gdp && grp && !EXT4_MB_GRP_TEST_AND_SET_READ(grp) &&
  2452. EXT4_MB_GRP_NEED_INIT(grp) &&
  2453. ext4_free_group_clusters(sb, gdp) > 0 ) {
  2454. bh = ext4_read_block_bitmap_nowait(sb, group, true);
  2455. if (bh && !IS_ERR(bh)) {
  2456. if (!buffer_uptodate(bh) && cnt)
  2457. (*cnt)++;
  2458. brelse(bh);
  2459. }
  2460. }
  2461. if (++group >= ngroups)
  2462. group = 0;
  2463. }
  2464. blk_finish_plug(&plug);
  2465. return group;
  2466. }
  2467. /*
  2468. * Prefetching reads the block bitmap into the buffer cache; but we
  2469. * need to make sure that the buddy bitmap in the page cache has been
  2470. * initialized. Note that ext4_mb_init_group() will block if the I/O
  2471. * is not yet completed, or indeed if it was not initiated by
  2472. * ext4_mb_prefetch did not start the I/O.
  2473. *
  2474. * TODO: We should actually kick off the buddy bitmap setup in a work
  2475. * queue when the buffer I/O is completed, so that we don't block
  2476. * waiting for the block allocation bitmap read to finish when
  2477. * ext4_mb_prefetch_fini is called from ext4_mb_regular_allocator().
  2478. */
  2479. void ext4_mb_prefetch_fini(struct super_block *sb, ext4_group_t group,
  2480. unsigned int nr)
  2481. {
  2482. struct ext4_group_desc *gdp;
  2483. struct ext4_group_info *grp;
  2484. while (nr-- > 0) {
  2485. if (!group)
  2486. group = ext4_get_groups_count(sb);
  2487. group--;
  2488. gdp = ext4_get_group_desc(sb, group, NULL);
  2489. grp = ext4_get_group_info(sb, group);
  2490. if (grp && gdp && EXT4_MB_GRP_NEED_INIT(grp) &&
  2491. ext4_free_group_clusters(sb, gdp) > 0) {
  2492. if (ext4_mb_init_group(sb, group, GFP_NOFS))
  2493. break;
  2494. }
  2495. }
  2496. }
  2497. static noinline_for_stack int
  2498. ext4_mb_regular_allocator(struct ext4_allocation_context *ac)
  2499. {
  2500. ext4_group_t prefetch_grp = 0, ngroups, group, i;
  2501. enum criteria new_cr, cr = CR_GOAL_LEN_FAST;
  2502. int err = 0, first_err = 0;
  2503. unsigned int nr = 0, prefetch_ios = 0;
  2504. struct ext4_sb_info *sbi;
  2505. struct super_block *sb;
  2506. struct ext4_buddy e4b;
  2507. int lost;
  2508. sb = ac->ac_sb;
  2509. sbi = EXT4_SB(sb);
  2510. ngroups = ext4_get_groups_count(sb);
  2511. /* non-extent files are limited to low blocks/groups */
  2512. if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)))
  2513. ngroups = sbi->s_blockfile_groups;
  2514. BUG_ON(ac->ac_status == AC_STATUS_FOUND);
  2515. /* first, try the goal */
  2516. err = ext4_mb_find_by_goal(ac, &e4b);
  2517. if (err || ac->ac_status == AC_STATUS_FOUND)
  2518. goto out;
  2519. if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
  2520. goto out;
  2521. /*
  2522. * ac->ac_2order is set only if the fe_len is a power of 2
  2523. * if ac->ac_2order is set we also set criteria to CR_POWER2_ALIGNED
  2524. * so that we try exact allocation using buddy.
  2525. */
  2526. i = fls(ac->ac_g_ex.fe_len);
  2527. ac->ac_2order = 0;
  2528. /*
  2529. * We search using buddy data only if the order of the request
  2530. * is greater than equal to the sbi_s_mb_order2_reqs
  2531. * You can tune it via /sys/fs/ext4/<partition>/mb_order2_req
  2532. * We also support searching for power-of-two requests only for
  2533. * requests upto maximum buddy size we have constructed.
  2534. */
  2535. if (i >= sbi->s_mb_order2_reqs && i <= MB_NUM_ORDERS(sb)) {
  2536. if (is_power_of_2(ac->ac_g_ex.fe_len))
  2537. ac->ac_2order = array_index_nospec(i - 1,
  2538. MB_NUM_ORDERS(sb));
  2539. }
  2540. /* if stream allocation is enabled, use global goal */
  2541. if (ac->ac_flags & EXT4_MB_STREAM_ALLOC) {
  2542. /* TBD: may be hot point */
  2543. spin_lock(&sbi->s_md_lock);
  2544. ac->ac_g_ex.fe_group = sbi->s_mb_last_group;
  2545. ac->ac_g_ex.fe_start = sbi->s_mb_last_start;
  2546. spin_unlock(&sbi->s_md_lock);
  2547. }
  2548. /*
  2549. * Let's just scan groups to find more-less suitable blocks We
  2550. * start with CR_GOAL_LEN_FAST, unless it is power of 2
  2551. * aligned, in which case let's do that faster approach first.
  2552. */
  2553. if (ac->ac_2order)
  2554. cr = CR_POWER2_ALIGNED;
  2555. repeat:
  2556. for (; cr < EXT4_MB_NUM_CRS && ac->ac_status == AC_STATUS_CONTINUE; cr++) {
  2557. ac->ac_criteria = cr;
  2558. /*
  2559. * searching for the right group start
  2560. * from the goal value specified
  2561. */
  2562. group = ac->ac_g_ex.fe_group;
  2563. ac->ac_groups_linear_remaining = sbi->s_mb_max_linear_groups;
  2564. prefetch_grp = group;
  2565. nr = 0;
  2566. for (i = 0, new_cr = cr; i < ngroups; i++,
  2567. ext4_mb_choose_next_group(ac, &new_cr, &group, ngroups)) {
  2568. int ret = 0;
  2569. cond_resched();
  2570. if (new_cr != cr) {
  2571. cr = new_cr;
  2572. goto repeat;
  2573. }
  2574. /*
  2575. * Batch reads of the block allocation bitmaps
  2576. * to get multiple READs in flight; limit
  2577. * prefetching at inexpensive CR, otherwise mballoc
  2578. * can spend a lot of time loading imperfect groups
  2579. */
  2580. if ((prefetch_grp == group) &&
  2581. (ext4_mb_cr_expensive(cr) ||
  2582. prefetch_ios < sbi->s_mb_prefetch_limit)) {
  2583. nr = sbi->s_mb_prefetch;
  2584. if (ext4_has_feature_flex_bg(sb)) {
  2585. nr = 1 << sbi->s_log_groups_per_flex;
  2586. nr -= group & (nr - 1);
  2587. nr = min(nr, sbi->s_mb_prefetch);
  2588. }
  2589. prefetch_grp = ext4_mb_prefetch(sb, group,
  2590. nr, &prefetch_ios);
  2591. }
  2592. /* This now checks without needing the buddy page */
  2593. ret = ext4_mb_good_group_nolock(ac, group, cr);
  2594. if (ret <= 0) {
  2595. if (!first_err)
  2596. first_err = ret;
  2597. continue;
  2598. }
  2599. err = ext4_mb_load_buddy(sb, group, &e4b);
  2600. if (err)
  2601. goto out;
  2602. ext4_lock_group(sb, group);
  2603. /*
  2604. * We need to check again after locking the
  2605. * block group
  2606. */
  2607. ret = ext4_mb_good_group(ac, group, cr);
  2608. if (ret == 0) {
  2609. ext4_unlock_group(sb, group);
  2610. ext4_mb_unload_buddy(&e4b);
  2611. continue;
  2612. }
  2613. ac->ac_groups_scanned++;
  2614. if (cr == CR_POWER2_ALIGNED)
  2615. ext4_mb_simple_scan_group(ac, &e4b);
  2616. else {
  2617. bool is_stripe_aligned =
  2618. (sbi->s_stripe >=
  2619. sbi->s_cluster_ratio) &&
  2620. !(ac->ac_g_ex.fe_len %
  2621. EXT4_NUM_B2C(sbi, sbi->s_stripe));
  2622. if ((cr == CR_GOAL_LEN_FAST ||
  2623. cr == CR_BEST_AVAIL_LEN) &&
  2624. is_stripe_aligned)
  2625. ext4_mb_scan_aligned(ac, &e4b);
  2626. if (ac->ac_status == AC_STATUS_CONTINUE)
  2627. ext4_mb_complex_scan_group(ac, &e4b);
  2628. }
  2629. ext4_unlock_group(sb, group);
  2630. ext4_mb_unload_buddy(&e4b);
  2631. if (ac->ac_status != AC_STATUS_CONTINUE)
  2632. break;
  2633. }
  2634. /* Processed all groups and haven't found blocks */
  2635. if (sbi->s_mb_stats && i == ngroups)
  2636. atomic64_inc(&sbi->s_bal_cX_failed[cr]);
  2637. if (i == ngroups && ac->ac_criteria == CR_BEST_AVAIL_LEN)
  2638. /* Reset goal length to original goal length before
  2639. * falling into CR_GOAL_LEN_SLOW */
  2640. ac->ac_g_ex.fe_len = ac->ac_orig_goal_len;
  2641. }
  2642. if (ac->ac_b_ex.fe_len > 0 && ac->ac_status != AC_STATUS_FOUND &&
  2643. !(ac->ac_flags & EXT4_MB_HINT_FIRST)) {
  2644. /*
  2645. * We've been searching too long. Let's try to allocate
  2646. * the best chunk we've found so far
  2647. */
  2648. ext4_mb_try_best_found(ac, &e4b);
  2649. if (ac->ac_status != AC_STATUS_FOUND) {
  2650. /*
  2651. * Someone more lucky has already allocated it.
  2652. * The only thing we can do is just take first
  2653. * found block(s)
  2654. */
  2655. lost = atomic_inc_return(&sbi->s_mb_lost_chunks);
  2656. mb_debug(sb, "lost chunk, group: %u, start: %d, len: %d, lost: %d\n",
  2657. ac->ac_b_ex.fe_group, ac->ac_b_ex.fe_start,
  2658. ac->ac_b_ex.fe_len, lost);
  2659. ac->ac_b_ex.fe_group = 0;
  2660. ac->ac_b_ex.fe_start = 0;
  2661. ac->ac_b_ex.fe_len = 0;
  2662. ac->ac_status = AC_STATUS_CONTINUE;
  2663. ac->ac_flags |= EXT4_MB_HINT_FIRST;
  2664. cr = CR_ANY_FREE;
  2665. goto repeat;
  2666. }
  2667. }
  2668. if (sbi->s_mb_stats && ac->ac_status == AC_STATUS_FOUND)
  2669. atomic64_inc(&sbi->s_bal_cX_hits[ac->ac_criteria]);
  2670. out:
  2671. if (!err && ac->ac_status != AC_STATUS_FOUND && first_err)
  2672. err = first_err;
  2673. mb_debug(sb, "Best len %d, origin len %d, ac_status %u, ac_flags 0x%x, cr %d ret %d\n",
  2674. ac->ac_b_ex.fe_len, ac->ac_o_ex.fe_len, ac->ac_status,
  2675. ac->ac_flags, cr, err);
  2676. if (nr)
  2677. ext4_mb_prefetch_fini(sb, prefetch_grp, nr);
  2678. return err;
  2679. }
  2680. static void *ext4_mb_seq_groups_start(struct seq_file *seq, loff_t *pos)
  2681. {
  2682. struct super_block *sb = pde_data(file_inode(seq->file));
  2683. ext4_group_t group;
  2684. if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
  2685. return NULL;
  2686. group = *pos + 1;
  2687. return (void *) ((unsigned long) group);
  2688. }
  2689. static void *ext4_mb_seq_groups_next(struct seq_file *seq, void *v, loff_t *pos)
  2690. {
  2691. struct super_block *sb = pde_data(file_inode(seq->file));
  2692. ext4_group_t group;
  2693. ++*pos;
  2694. if (*pos < 0 || *pos >= ext4_get_groups_count(sb))
  2695. return NULL;
  2696. group = *pos + 1;
  2697. return (void *) ((unsigned long) group);
  2698. }
  2699. static int ext4_mb_seq_groups_show(struct seq_file *seq, void *v)
  2700. {
  2701. struct super_block *sb = pde_data(file_inode(seq->file));
  2702. ext4_group_t group = (ext4_group_t) ((unsigned long) v);
  2703. int i, err;
  2704. char nbuf[16];
  2705. struct ext4_buddy e4b;
  2706. struct ext4_group_info *grinfo;
  2707. unsigned char blocksize_bits = min_t(unsigned char,
  2708. sb->s_blocksize_bits,
  2709. EXT4_MAX_BLOCK_LOG_SIZE);
  2710. struct sg {
  2711. struct ext4_group_info info;
  2712. ext4_grpblk_t counters[EXT4_MAX_BLOCK_LOG_SIZE + 2];
  2713. } sg;
  2714. group--;
  2715. if (group == 0)
  2716. seq_puts(seq, "#group: free frags first ["
  2717. " 2^0 2^1 2^2 2^3 2^4 2^5 2^6 "
  2718. " 2^7 2^8 2^9 2^10 2^11 2^12 2^13 ]\n");
  2719. i = (blocksize_bits + 2) * sizeof(sg.info.bb_counters[0]) +
  2720. sizeof(struct ext4_group_info);
  2721. grinfo = ext4_get_group_info(sb, group);
  2722. if (!grinfo)
  2723. return 0;
  2724. /* Load the group info in memory only if not already loaded. */
  2725. if (unlikely(EXT4_MB_GRP_NEED_INIT(grinfo))) {
  2726. err = ext4_mb_load_buddy(sb, group, &e4b);
  2727. if (err) {
  2728. seq_printf(seq, "#%-5u: %s\n", group, ext4_decode_error(NULL, err, nbuf));
  2729. return 0;
  2730. }
  2731. ext4_mb_unload_buddy(&e4b);
  2732. }
  2733. /*
  2734. * We care only about free space counters in the group info and
  2735. * these are safe to access even after the buddy has been unloaded
  2736. */
  2737. memcpy(&sg, grinfo, i);
  2738. seq_printf(seq, "#%-5u: %-5u %-5u %-5u [", group, sg.info.bb_free,
  2739. sg.info.bb_fragments, sg.info.bb_first_free);
  2740. for (i = 0; i <= 13; i++)
  2741. seq_printf(seq, " %-5u", i <= blocksize_bits + 1 ?
  2742. sg.info.bb_counters[i] : 0);
  2743. seq_puts(seq, " ]");
  2744. if (EXT4_MB_GRP_BBITMAP_CORRUPT(&sg.info))
  2745. seq_puts(seq, " Block bitmap corrupted!");
  2746. seq_putc(seq, '\n');
  2747. return 0;
  2748. }
  2749. static void ext4_mb_seq_groups_stop(struct seq_file *seq, void *v)
  2750. {
  2751. }
  2752. const struct seq_operations ext4_mb_seq_groups_ops = {
  2753. .start = ext4_mb_seq_groups_start,
  2754. .next = ext4_mb_seq_groups_next,
  2755. .stop = ext4_mb_seq_groups_stop,
  2756. .show = ext4_mb_seq_groups_show,
  2757. };
  2758. int ext4_seq_mb_stats_show(struct seq_file *seq, void *offset)
  2759. {
  2760. struct super_block *sb = seq->private;
  2761. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2762. seq_puts(seq, "mballoc:\n");
  2763. if (!sbi->s_mb_stats) {
  2764. seq_puts(seq, "\tmb stats collection turned off.\n");
  2765. seq_puts(
  2766. seq,
  2767. "\tTo enable, please write \"1\" to sysfs file mb_stats.\n");
  2768. return 0;
  2769. }
  2770. seq_printf(seq, "\treqs: %u\n", atomic_read(&sbi->s_bal_reqs));
  2771. seq_printf(seq, "\tsuccess: %u\n", atomic_read(&sbi->s_bal_success));
  2772. seq_printf(seq, "\tgroups_scanned: %u\n",
  2773. atomic_read(&sbi->s_bal_groups_scanned));
  2774. /* CR_POWER2_ALIGNED stats */
  2775. seq_puts(seq, "\tcr_p2_aligned_stats:\n");
  2776. seq_printf(seq, "\t\thits: %llu\n",
  2777. atomic64_read(&sbi->s_bal_cX_hits[CR_POWER2_ALIGNED]));
  2778. seq_printf(
  2779. seq, "\t\tgroups_considered: %llu\n",
  2780. atomic64_read(
  2781. &sbi->s_bal_cX_groups_considered[CR_POWER2_ALIGNED]));
  2782. seq_printf(seq, "\t\textents_scanned: %u\n",
  2783. atomic_read(&sbi->s_bal_cX_ex_scanned[CR_POWER2_ALIGNED]));
  2784. seq_printf(seq, "\t\tuseless_loops: %llu\n",
  2785. atomic64_read(&sbi->s_bal_cX_failed[CR_POWER2_ALIGNED]));
  2786. seq_printf(seq, "\t\tbad_suggestions: %u\n",
  2787. atomic_read(&sbi->s_bal_p2_aligned_bad_suggestions));
  2788. /* CR_GOAL_LEN_FAST stats */
  2789. seq_puts(seq, "\tcr_goal_fast_stats:\n");
  2790. seq_printf(seq, "\t\thits: %llu\n",
  2791. atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_FAST]));
  2792. seq_printf(seq, "\t\tgroups_considered: %llu\n",
  2793. atomic64_read(
  2794. &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_FAST]));
  2795. seq_printf(seq, "\t\textents_scanned: %u\n",
  2796. atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_FAST]));
  2797. seq_printf(seq, "\t\tuseless_loops: %llu\n",
  2798. atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_FAST]));
  2799. seq_printf(seq, "\t\tbad_suggestions: %u\n",
  2800. atomic_read(&sbi->s_bal_goal_fast_bad_suggestions));
  2801. /* CR_BEST_AVAIL_LEN stats */
  2802. seq_puts(seq, "\tcr_best_avail_stats:\n");
  2803. seq_printf(seq, "\t\thits: %llu\n",
  2804. atomic64_read(&sbi->s_bal_cX_hits[CR_BEST_AVAIL_LEN]));
  2805. seq_printf(
  2806. seq, "\t\tgroups_considered: %llu\n",
  2807. atomic64_read(
  2808. &sbi->s_bal_cX_groups_considered[CR_BEST_AVAIL_LEN]));
  2809. seq_printf(seq, "\t\textents_scanned: %u\n",
  2810. atomic_read(&sbi->s_bal_cX_ex_scanned[CR_BEST_AVAIL_LEN]));
  2811. seq_printf(seq, "\t\tuseless_loops: %llu\n",
  2812. atomic64_read(&sbi->s_bal_cX_failed[CR_BEST_AVAIL_LEN]));
  2813. seq_printf(seq, "\t\tbad_suggestions: %u\n",
  2814. atomic_read(&sbi->s_bal_best_avail_bad_suggestions));
  2815. /* CR_GOAL_LEN_SLOW stats */
  2816. seq_puts(seq, "\tcr_goal_slow_stats:\n");
  2817. seq_printf(seq, "\t\thits: %llu\n",
  2818. atomic64_read(&sbi->s_bal_cX_hits[CR_GOAL_LEN_SLOW]));
  2819. seq_printf(seq, "\t\tgroups_considered: %llu\n",
  2820. atomic64_read(
  2821. &sbi->s_bal_cX_groups_considered[CR_GOAL_LEN_SLOW]));
  2822. seq_printf(seq, "\t\textents_scanned: %u\n",
  2823. atomic_read(&sbi->s_bal_cX_ex_scanned[CR_GOAL_LEN_SLOW]));
  2824. seq_printf(seq, "\t\tuseless_loops: %llu\n",
  2825. atomic64_read(&sbi->s_bal_cX_failed[CR_GOAL_LEN_SLOW]));
  2826. /* CR_ANY_FREE stats */
  2827. seq_puts(seq, "\tcr_any_free_stats:\n");
  2828. seq_printf(seq, "\t\thits: %llu\n",
  2829. atomic64_read(&sbi->s_bal_cX_hits[CR_ANY_FREE]));
  2830. seq_printf(
  2831. seq, "\t\tgroups_considered: %llu\n",
  2832. atomic64_read(&sbi->s_bal_cX_groups_considered[CR_ANY_FREE]));
  2833. seq_printf(seq, "\t\textents_scanned: %u\n",
  2834. atomic_read(&sbi->s_bal_cX_ex_scanned[CR_ANY_FREE]));
  2835. seq_printf(seq, "\t\tuseless_loops: %llu\n",
  2836. atomic64_read(&sbi->s_bal_cX_failed[CR_ANY_FREE]));
  2837. /* Aggregates */
  2838. seq_printf(seq, "\textents_scanned: %u\n",
  2839. atomic_read(&sbi->s_bal_ex_scanned));
  2840. seq_printf(seq, "\t\tgoal_hits: %u\n", atomic_read(&sbi->s_bal_goals));
  2841. seq_printf(seq, "\t\tlen_goal_hits: %u\n",
  2842. atomic_read(&sbi->s_bal_len_goals));
  2843. seq_printf(seq, "\t\t2^n_hits: %u\n", atomic_read(&sbi->s_bal_2orders));
  2844. seq_printf(seq, "\t\tbreaks: %u\n", atomic_read(&sbi->s_bal_breaks));
  2845. seq_printf(seq, "\t\tlost: %u\n", atomic_read(&sbi->s_mb_lost_chunks));
  2846. seq_printf(seq, "\tbuddies_generated: %u/%u\n",
  2847. atomic_read(&sbi->s_mb_buddies_generated),
  2848. ext4_get_groups_count(sb));
  2849. seq_printf(seq, "\tbuddies_time_used: %llu\n",
  2850. atomic64_read(&sbi->s_mb_generation_time));
  2851. seq_printf(seq, "\tpreallocated: %u\n",
  2852. atomic_read(&sbi->s_mb_preallocated));
  2853. seq_printf(seq, "\tdiscarded: %u\n", atomic_read(&sbi->s_mb_discarded));
  2854. return 0;
  2855. }
  2856. static void *ext4_mb_seq_structs_summary_start(struct seq_file *seq, loff_t *pos)
  2857. {
  2858. struct super_block *sb = pde_data(file_inode(seq->file));
  2859. unsigned long position;
  2860. if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
  2861. return NULL;
  2862. position = *pos + 1;
  2863. return (void *) ((unsigned long) position);
  2864. }
  2865. static void *ext4_mb_seq_structs_summary_next(struct seq_file *seq, void *v, loff_t *pos)
  2866. {
  2867. struct super_block *sb = pde_data(file_inode(seq->file));
  2868. unsigned long position;
  2869. ++*pos;
  2870. if (*pos < 0 || *pos >= 2*MB_NUM_ORDERS(sb))
  2871. return NULL;
  2872. position = *pos + 1;
  2873. return (void *) ((unsigned long) position);
  2874. }
  2875. static int ext4_mb_seq_structs_summary_show(struct seq_file *seq, void *v)
  2876. {
  2877. struct super_block *sb = pde_data(file_inode(seq->file));
  2878. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2879. unsigned long position = ((unsigned long) v);
  2880. struct ext4_group_info *grp;
  2881. unsigned int count;
  2882. position--;
  2883. if (position >= MB_NUM_ORDERS(sb)) {
  2884. position -= MB_NUM_ORDERS(sb);
  2885. if (position == 0)
  2886. seq_puts(seq, "avg_fragment_size_lists:\n");
  2887. count = 0;
  2888. read_lock(&sbi->s_mb_avg_fragment_size_locks[position]);
  2889. list_for_each_entry(grp, &sbi->s_mb_avg_fragment_size[position],
  2890. bb_avg_fragment_size_node)
  2891. count++;
  2892. read_unlock(&sbi->s_mb_avg_fragment_size_locks[position]);
  2893. seq_printf(seq, "\tlist_order_%u_groups: %u\n",
  2894. (unsigned int)position, count);
  2895. return 0;
  2896. }
  2897. if (position == 0) {
  2898. seq_printf(seq, "optimize_scan: %d\n",
  2899. test_opt2(sb, MB_OPTIMIZE_SCAN) ? 1 : 0);
  2900. seq_puts(seq, "max_free_order_lists:\n");
  2901. }
  2902. count = 0;
  2903. read_lock(&sbi->s_mb_largest_free_orders_locks[position]);
  2904. list_for_each_entry(grp, &sbi->s_mb_largest_free_orders[position],
  2905. bb_largest_free_order_node)
  2906. count++;
  2907. read_unlock(&sbi->s_mb_largest_free_orders_locks[position]);
  2908. seq_printf(seq, "\tlist_order_%u_groups: %u\n",
  2909. (unsigned int)position, count);
  2910. return 0;
  2911. }
  2912. static void ext4_mb_seq_structs_summary_stop(struct seq_file *seq, void *v)
  2913. {
  2914. }
  2915. const struct seq_operations ext4_mb_seq_structs_summary_ops = {
  2916. .start = ext4_mb_seq_structs_summary_start,
  2917. .next = ext4_mb_seq_structs_summary_next,
  2918. .stop = ext4_mb_seq_structs_summary_stop,
  2919. .show = ext4_mb_seq_structs_summary_show,
  2920. };
  2921. static struct kmem_cache *get_groupinfo_cache(int blocksize_bits)
  2922. {
  2923. int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
  2924. struct kmem_cache *cachep = ext4_groupinfo_caches[cache_index];
  2925. BUG_ON(!cachep);
  2926. return cachep;
  2927. }
  2928. /*
  2929. * Allocate the top-level s_group_info array for the specified number
  2930. * of groups
  2931. */
  2932. int ext4_mb_alloc_groupinfo(struct super_block *sb, ext4_group_t ngroups)
  2933. {
  2934. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2935. unsigned size;
  2936. struct ext4_group_info ***old_groupinfo, ***new_groupinfo;
  2937. size = (ngroups + EXT4_DESC_PER_BLOCK(sb) - 1) >>
  2938. EXT4_DESC_PER_BLOCK_BITS(sb);
  2939. if (size <= sbi->s_group_info_size)
  2940. return 0;
  2941. size = roundup_pow_of_two(sizeof(*sbi->s_group_info) * size);
  2942. new_groupinfo = kvzalloc(size, GFP_KERNEL);
  2943. if (!new_groupinfo) {
  2944. ext4_msg(sb, KERN_ERR, "can't allocate buddy meta group");
  2945. return -ENOMEM;
  2946. }
  2947. rcu_read_lock();
  2948. old_groupinfo = rcu_dereference(sbi->s_group_info);
  2949. if (old_groupinfo)
  2950. memcpy(new_groupinfo, old_groupinfo,
  2951. sbi->s_group_info_size * sizeof(*sbi->s_group_info));
  2952. rcu_read_unlock();
  2953. rcu_assign_pointer(sbi->s_group_info, new_groupinfo);
  2954. sbi->s_group_info_size = size / sizeof(*sbi->s_group_info);
  2955. if (old_groupinfo)
  2956. ext4_kvfree_array_rcu(old_groupinfo);
  2957. ext4_debug("allocated s_groupinfo array for %d meta_bg's\n",
  2958. sbi->s_group_info_size);
  2959. return 0;
  2960. }
  2961. /* Create and initialize ext4_group_info data for the given group. */
  2962. int ext4_mb_add_groupinfo(struct super_block *sb, ext4_group_t group,
  2963. struct ext4_group_desc *desc)
  2964. {
  2965. int i;
  2966. int metalen = 0;
  2967. int idx = group >> EXT4_DESC_PER_BLOCK_BITS(sb);
  2968. struct ext4_sb_info *sbi = EXT4_SB(sb);
  2969. struct ext4_group_info **meta_group_info;
  2970. struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
  2971. /*
  2972. * First check if this group is the first of a reserved block.
  2973. * If it's true, we have to allocate a new table of pointers
  2974. * to ext4_group_info structures
  2975. */
  2976. if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
  2977. metalen = sizeof(*meta_group_info) <<
  2978. EXT4_DESC_PER_BLOCK_BITS(sb);
  2979. meta_group_info = kmalloc(metalen, GFP_NOFS);
  2980. if (meta_group_info == NULL) {
  2981. ext4_msg(sb, KERN_ERR, "can't allocate mem "
  2982. "for a buddy group");
  2983. return -ENOMEM;
  2984. }
  2985. rcu_read_lock();
  2986. rcu_dereference(sbi->s_group_info)[idx] = meta_group_info;
  2987. rcu_read_unlock();
  2988. }
  2989. meta_group_info = sbi_array_rcu_deref(sbi, s_group_info, idx);
  2990. i = group & (EXT4_DESC_PER_BLOCK(sb) - 1);
  2991. meta_group_info[i] = kmem_cache_zalloc(cachep, GFP_NOFS);
  2992. if (meta_group_info[i] == NULL) {
  2993. ext4_msg(sb, KERN_ERR, "can't allocate buddy mem");
  2994. goto exit_group_info;
  2995. }
  2996. set_bit(EXT4_GROUP_INFO_NEED_INIT_BIT,
  2997. &(meta_group_info[i]->bb_state));
  2998. /*
  2999. * initialize bb_free to be able to skip
  3000. * empty groups without initialization
  3001. */
  3002. if (ext4_has_group_desc_csum(sb) &&
  3003. (desc->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
  3004. meta_group_info[i]->bb_free =
  3005. ext4_free_clusters_after_init(sb, group, desc);
  3006. } else {
  3007. meta_group_info[i]->bb_free =
  3008. ext4_free_group_clusters(sb, desc);
  3009. }
  3010. INIT_LIST_HEAD(&meta_group_info[i]->bb_prealloc_list);
  3011. init_rwsem(&meta_group_info[i]->alloc_sem);
  3012. meta_group_info[i]->bb_free_root = RB_ROOT;
  3013. INIT_LIST_HEAD(&meta_group_info[i]->bb_largest_free_order_node);
  3014. INIT_LIST_HEAD(&meta_group_info[i]->bb_avg_fragment_size_node);
  3015. meta_group_info[i]->bb_largest_free_order = -1; /* uninit */
  3016. meta_group_info[i]->bb_avg_fragment_size_order = -1; /* uninit */
  3017. meta_group_info[i]->bb_group = group;
  3018. mb_group_bb_bitmap_alloc(sb, meta_group_info[i], group);
  3019. return 0;
  3020. exit_group_info:
  3021. /* If a meta_group_info table has been allocated, release it now */
  3022. if (group % EXT4_DESC_PER_BLOCK(sb) == 0) {
  3023. struct ext4_group_info ***group_info;
  3024. rcu_read_lock();
  3025. group_info = rcu_dereference(sbi->s_group_info);
  3026. kfree(group_info[idx]);
  3027. group_info[idx] = NULL;
  3028. rcu_read_unlock();
  3029. }
  3030. return -ENOMEM;
  3031. } /* ext4_mb_add_groupinfo */
  3032. static int ext4_mb_init_backend(struct super_block *sb)
  3033. {
  3034. ext4_group_t ngroups = ext4_get_groups_count(sb);
  3035. ext4_group_t i;
  3036. struct ext4_sb_info *sbi = EXT4_SB(sb);
  3037. int err;
  3038. struct ext4_group_desc *desc;
  3039. struct ext4_group_info ***group_info;
  3040. struct kmem_cache *cachep;
  3041. err = ext4_mb_alloc_groupinfo(sb, ngroups);
  3042. if (err)
  3043. return err;
  3044. sbi->s_buddy_cache = new_inode(sb);
  3045. if (sbi->s_buddy_cache == NULL) {
  3046. ext4_msg(sb, KERN_ERR, "can't get new inode");
  3047. goto err_freesgi;
  3048. }
  3049. /* To avoid potentially colliding with an valid on-disk inode number,
  3050. * use EXT4_BAD_INO for the buddy cache inode number. This inode is
  3051. * not in the inode hash, so it should never be found by iget(), but
  3052. * this will avoid confusion if it ever shows up during debugging. */
  3053. sbi->s_buddy_cache->i_ino = EXT4_BAD_INO;
  3054. EXT4_I(sbi->s_buddy_cache)->i_disksize = 0;
  3055. for (i = 0; i < ngroups; i++) {
  3056. cond_resched();
  3057. desc = ext4_get_group_desc(sb, i, NULL);
  3058. if (desc == NULL) {
  3059. ext4_msg(sb, KERN_ERR, "can't read descriptor %u", i);
  3060. goto err_freebuddy;
  3061. }
  3062. if (ext4_mb_add_groupinfo(sb, i, desc) != 0)
  3063. goto err_freebuddy;
  3064. }
  3065. if (ext4_has_feature_flex_bg(sb)) {
  3066. /* a single flex group is supposed to be read by a single IO.
  3067. * 2 ^ s_log_groups_per_flex != UINT_MAX as s_mb_prefetch is
  3068. * unsigned integer, so the maximum shift is 32.
  3069. */
  3070. if (sbi->s_es->s_log_groups_per_flex >= 32) {
  3071. ext4_msg(sb, KERN_ERR, "too many log groups per flexible block group");
  3072. goto err_freebuddy;
  3073. }
  3074. sbi->s_mb_prefetch = min_t(uint, 1 << sbi->s_es->s_log_groups_per_flex,
  3075. BLK_MAX_SEGMENT_SIZE >> (sb->s_blocksize_bits - 9));
  3076. sbi->s_mb_prefetch *= 8; /* 8 prefetch IOs in flight at most */
  3077. } else {
  3078. sbi->s_mb_prefetch = 32;
  3079. }
  3080. if (sbi->s_mb_prefetch > ext4_get_groups_count(sb))
  3081. sbi->s_mb_prefetch = ext4_get_groups_count(sb);
  3082. /*
  3083. * now many real IOs to prefetch within a single allocation at
  3084. * CR_POWER2_ALIGNED. Given CR_POWER2_ALIGNED is an CPU-related
  3085. * optimization we shouldn't try to load too many groups, at some point
  3086. * we should start to use what we've got in memory.
  3087. * with an average random access time 5ms, it'd take a second to get
  3088. * 200 groups (* N with flex_bg), so let's make this limit 4
  3089. */
  3090. sbi->s_mb_prefetch_limit = sbi->s_mb_prefetch * 4;
  3091. if (sbi->s_mb_prefetch_limit > ext4_get_groups_count(sb))
  3092. sbi->s_mb_prefetch_limit = ext4_get_groups_count(sb);
  3093. return 0;
  3094. err_freebuddy:
  3095. cachep = get_groupinfo_cache(sb->s_blocksize_bits);
  3096. while (i-- > 0) {
  3097. struct ext4_group_info *grp = ext4_get_group_info(sb, i);
  3098. if (grp)
  3099. kmem_cache_free(cachep, grp);
  3100. }
  3101. i = sbi->s_group_info_size;
  3102. rcu_read_lock();
  3103. group_info = rcu_dereference(sbi->s_group_info);
  3104. while (i-- > 0)
  3105. kfree(group_info[i]);
  3106. rcu_read_unlock();
  3107. iput(sbi->s_buddy_cache);
  3108. err_freesgi:
  3109. rcu_read_lock();
  3110. kvfree(rcu_dereference(sbi->s_group_info));
  3111. rcu_read_unlock();
  3112. return -ENOMEM;
  3113. }
  3114. static void ext4_groupinfo_destroy_slabs(void)
  3115. {
  3116. int i;
  3117. for (i = 0; i < NR_GRPINFO_CACHES; i++) {
  3118. kmem_cache_destroy(ext4_groupinfo_caches[i]);
  3119. ext4_groupinfo_caches[i] = NULL;
  3120. }
  3121. }
  3122. static int ext4_groupinfo_create_slab(size_t size)
  3123. {
  3124. static DEFINE_MUTEX(ext4_grpinfo_slab_create_mutex);
  3125. int slab_size;
  3126. int blocksize_bits = order_base_2(size);
  3127. int cache_index = blocksize_bits - EXT4_MIN_BLOCK_LOG_SIZE;
  3128. struct kmem_cache *cachep;
  3129. if (cache_index >= NR_GRPINFO_CACHES)
  3130. return -EINVAL;
  3131. if (unlikely(cache_index < 0))
  3132. cache_index = 0;
  3133. mutex_lock(&ext4_grpinfo_slab_create_mutex);
  3134. if (ext4_groupinfo_caches[cache_index]) {
  3135. mutex_unlock(&ext4_grpinfo_slab_create_mutex);
  3136. return 0; /* Already created */
  3137. }
  3138. slab_size = offsetof(struct ext4_group_info,
  3139. bb_counters[blocksize_bits + 2]);
  3140. cachep = kmem_cache_create(ext4_groupinfo_slab_names[cache_index],
  3141. slab_size, 0, SLAB_RECLAIM_ACCOUNT,
  3142. NULL);
  3143. ext4_groupinfo_caches[cache_index] = cachep;
  3144. mutex_unlock(&ext4_grpinfo_slab_create_mutex);
  3145. if (!cachep) {
  3146. printk(KERN_EMERG
  3147. "EXT4-fs: no memory for groupinfo slab cache\n");
  3148. return -ENOMEM;
  3149. }
  3150. return 0;
  3151. }
  3152. static void ext4_discard_work(struct work_struct *work)
  3153. {
  3154. struct ext4_sb_info *sbi = container_of(work,
  3155. struct ext4_sb_info, s_discard_work);
  3156. struct super_block *sb = sbi->s_sb;
  3157. struct ext4_free_data *fd, *nfd;
  3158. struct ext4_buddy e4b;
  3159. LIST_HEAD(discard_list);
  3160. ext4_group_t grp, load_grp;
  3161. int err = 0;
  3162. spin_lock(&sbi->s_md_lock);
  3163. list_splice_init(&sbi->s_discard_list, &discard_list);
  3164. spin_unlock(&sbi->s_md_lock);
  3165. load_grp = UINT_MAX;
  3166. list_for_each_entry_safe(fd, nfd, &discard_list, efd_list) {
  3167. /*
  3168. * If filesystem is umounting or no memory or suffering
  3169. * from no space, give up the discard
  3170. */
  3171. if ((sb->s_flags & SB_ACTIVE) && !err &&
  3172. !atomic_read(&sbi->s_retry_alloc_pending)) {
  3173. grp = fd->efd_group;
  3174. if (grp != load_grp) {
  3175. if (load_grp != UINT_MAX)
  3176. ext4_mb_unload_buddy(&e4b);
  3177. err = ext4_mb_load_buddy(sb, grp, &e4b);
  3178. if (err) {
  3179. kmem_cache_free(ext4_free_data_cachep, fd);
  3180. load_grp = UINT_MAX;
  3181. continue;
  3182. } else {
  3183. load_grp = grp;
  3184. }
  3185. }
  3186. ext4_lock_group(sb, grp);
  3187. ext4_try_to_trim_range(sb, &e4b, fd->efd_start_cluster,
  3188. fd->efd_start_cluster + fd->efd_count - 1, 1);
  3189. ext4_unlock_group(sb, grp);
  3190. }
  3191. kmem_cache_free(ext4_free_data_cachep, fd);
  3192. }
  3193. if (load_grp != UINT_MAX)
  3194. ext4_mb_unload_buddy(&e4b);
  3195. }
  3196. int ext4_mb_init(struct super_block *sb)
  3197. {
  3198. struct ext4_sb_info *sbi = EXT4_SB(sb);
  3199. unsigned i, j;
  3200. unsigned offset, offset_incr;
  3201. unsigned max;
  3202. int ret;
  3203. i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_offsets);
  3204. sbi->s_mb_offsets = kmalloc(i, GFP_KERNEL);
  3205. if (sbi->s_mb_offsets == NULL) {
  3206. ret = -ENOMEM;
  3207. goto out;
  3208. }
  3209. i = MB_NUM_ORDERS(sb) * sizeof(*sbi->s_mb_maxs);
  3210. sbi->s_mb_maxs = kmalloc(i, GFP_KERNEL);
  3211. if (sbi->s_mb_maxs == NULL) {
  3212. ret = -ENOMEM;
  3213. goto out;
  3214. }
  3215. ret = ext4_groupinfo_create_slab(sb->s_blocksize);
  3216. if (ret < 0)
  3217. goto out;
  3218. /* order 0 is regular bitmap */
  3219. sbi->s_mb_maxs[0] = sb->s_blocksize << 3;
  3220. sbi->s_mb_offsets[0] = 0;
  3221. i = 1;
  3222. offset = 0;
  3223. offset_incr = 1 << (sb->s_blocksize_bits - 1);
  3224. max = sb->s_blocksize << 2;
  3225. do {
  3226. sbi->s_mb_offsets[i] = offset;
  3227. sbi->s_mb_maxs[i] = max;
  3228. offset += offset_incr;
  3229. offset_incr = offset_incr >> 1;
  3230. max = max >> 1;
  3231. i++;
  3232. } while (i < MB_NUM_ORDERS(sb));
  3233. sbi->s_mb_avg_fragment_size =
  3234. kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
  3235. GFP_KERNEL);
  3236. if (!sbi->s_mb_avg_fragment_size) {
  3237. ret = -ENOMEM;
  3238. goto out;
  3239. }
  3240. sbi->s_mb_avg_fragment_size_locks =
  3241. kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
  3242. GFP_KERNEL);
  3243. if (!sbi->s_mb_avg_fragment_size_locks) {
  3244. ret = -ENOMEM;
  3245. goto out;
  3246. }
  3247. for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
  3248. INIT_LIST_HEAD(&sbi->s_mb_avg_fragment_size[i]);
  3249. rwlock_init(&sbi->s_mb_avg_fragment_size_locks[i]);
  3250. }
  3251. sbi->s_mb_largest_free_orders =
  3252. kmalloc_array(MB_NUM_ORDERS(sb), sizeof(struct list_head),
  3253. GFP_KERNEL);
  3254. if (!sbi->s_mb_largest_free_orders) {
  3255. ret = -ENOMEM;
  3256. goto out;
  3257. }
  3258. sbi->s_mb_largest_free_orders_locks =
  3259. kmalloc_array(MB_NUM_ORDERS(sb), sizeof(rwlock_t),
  3260. GFP_KERNEL);
  3261. if (!sbi->s_mb_largest_free_orders_locks) {
  3262. ret = -ENOMEM;
  3263. goto out;
  3264. }
  3265. for (i = 0; i < MB_NUM_ORDERS(sb); i++) {
  3266. INIT_LIST_HEAD(&sbi->s_mb_largest_free_orders[i]);
  3267. rwlock_init(&sbi->s_mb_largest_free_orders_locks[i]);
  3268. }
  3269. spin_lock_init(&sbi->s_md_lock);
  3270. sbi->s_mb_free_pending = 0;
  3271. INIT_LIST_HEAD(&sbi->s_freed_data_list[0]);
  3272. INIT_LIST_HEAD(&sbi->s_freed_data_list[1]);
  3273. INIT_LIST_HEAD(&sbi->s_discard_list);
  3274. INIT_WORK(&sbi->s_discard_work, ext4_discard_work);
  3275. atomic_set(&sbi->s_retry_alloc_pending, 0);
  3276. sbi->s_mb_max_to_scan = MB_DEFAULT_MAX_TO_SCAN;
  3277. sbi->s_mb_min_to_scan = MB_DEFAULT_MIN_TO_SCAN;
  3278. sbi->s_mb_stats = MB_DEFAULT_STATS;
  3279. sbi->s_mb_stream_request = MB_DEFAULT_STREAM_THRESHOLD;
  3280. sbi->s_mb_order2_reqs = MB_DEFAULT_ORDER2_REQS;
  3281. sbi->s_mb_best_avail_max_trim_order = MB_DEFAULT_BEST_AVAIL_TRIM_ORDER;
  3282. /*
  3283. * The default group preallocation is 512, which for 4k block
  3284. * sizes translates to 2 megabytes. However for bigalloc file
  3285. * systems, this is probably too big (i.e, if the cluster size
  3286. * is 1 megabyte, then group preallocation size becomes half a
  3287. * gigabyte!). As a default, we will keep a two megabyte
  3288. * group pralloc size for cluster sizes up to 64k, and after
  3289. * that, we will force a minimum group preallocation size of
  3290. * 32 clusters. This translates to 8 megs when the cluster
  3291. * size is 256k, and 32 megs when the cluster size is 1 meg,
  3292. * which seems reasonable as a default.
  3293. */
  3294. sbi->s_mb_group_prealloc = max(MB_DEFAULT_GROUP_PREALLOC >>
  3295. sbi->s_cluster_bits, 32);
  3296. /*
  3297. * If there is a s_stripe > 1, then we set the s_mb_group_prealloc
  3298. * to the lowest multiple of s_stripe which is bigger than
  3299. * the s_mb_group_prealloc as determined above. We want
  3300. * the preallocation size to be an exact multiple of the
  3301. * RAID stripe size so that preallocations don't fragment
  3302. * the stripes.
  3303. */
  3304. if (sbi->s_stripe > 1) {
  3305. sbi->s_mb_group_prealloc = roundup(
  3306. sbi->s_mb_group_prealloc, EXT4_NUM_B2C(sbi, sbi->s_stripe));
  3307. }
  3308. sbi->s_locality_groups = alloc_percpu(struct ext4_locality_group);
  3309. if (sbi->s_locality_groups == NULL) {
  3310. ret = -ENOMEM;
  3311. goto out;
  3312. }
  3313. for_each_possible_cpu(i) {
  3314. struct ext4_locality_group *lg;
  3315. lg = per_cpu_ptr(sbi->s_locality_groups, i);
  3316. mutex_init(&lg->lg_mutex);
  3317. for (j = 0; j < PREALLOC_TB_SIZE; j++)
  3318. INIT_LIST_HEAD(&lg->lg_prealloc_list[j]);
  3319. spin_lock_init(&lg->lg_prealloc_lock);
  3320. }
  3321. if (bdev_nonrot(sb->s_bdev))
  3322. sbi->s_mb_max_linear_groups = 0;
  3323. else
  3324. sbi->s_mb_max_linear_groups = MB_DEFAULT_LINEAR_LIMIT;
  3325. /* init file for buddy data */
  3326. ret = ext4_mb_init_backend(sb);
  3327. if (ret != 0)
  3328. goto out_free_locality_groups;
  3329. return 0;
  3330. out_free_locality_groups:
  3331. free_percpu(sbi->s_locality_groups);
  3332. sbi->s_locality_groups = NULL;
  3333. out:
  3334. kfree(sbi->s_mb_avg_fragment_size);
  3335. kfree(sbi->s_mb_avg_fragment_size_locks);
  3336. kfree(sbi->s_mb_largest_free_orders);
  3337. kfree(sbi->s_mb_largest_free_orders_locks);
  3338. kfree(sbi->s_mb_offsets);
  3339. sbi->s_mb_offsets = NULL;
  3340. kfree(sbi->s_mb_maxs);
  3341. sbi->s_mb_maxs = NULL;
  3342. return ret;
  3343. }
  3344. /* need to called with the ext4 group lock held */
  3345. static int ext4_mb_cleanup_pa(struct ext4_group_info *grp)
  3346. {
  3347. struct ext4_prealloc_space *pa;
  3348. struct list_head *cur, *tmp;
  3349. int count = 0;
  3350. list_for_each_safe(cur, tmp, &grp->bb_prealloc_list) {
  3351. pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
  3352. list_del(&pa->pa_group_list);
  3353. count++;
  3354. kmem_cache_free(ext4_pspace_cachep, pa);
  3355. }
  3356. return count;
  3357. }
  3358. void ext4_mb_release(struct super_block *sb)
  3359. {
  3360. ext4_group_t ngroups = ext4_get_groups_count(sb);
  3361. ext4_group_t i;
  3362. int num_meta_group_infos;
  3363. struct ext4_group_info *grinfo, ***group_info;
  3364. struct ext4_sb_info *sbi = EXT4_SB(sb);
  3365. struct kmem_cache *cachep = get_groupinfo_cache(sb->s_blocksize_bits);
  3366. int count;
  3367. if (test_opt(sb, DISCARD)) {
  3368. /*
  3369. * wait the discard work to drain all of ext4_free_data
  3370. */
  3371. flush_work(&sbi->s_discard_work);
  3372. WARN_ON_ONCE(!list_empty(&sbi->s_discard_list));
  3373. }
  3374. if (sbi->s_group_info) {
  3375. for (i = 0; i < ngroups; i++) {
  3376. cond_resched();
  3377. grinfo = ext4_get_group_info(sb, i);
  3378. if (!grinfo)
  3379. continue;
  3380. mb_group_bb_bitmap_free(grinfo);
  3381. ext4_lock_group(sb, i);
  3382. count = ext4_mb_cleanup_pa(grinfo);
  3383. if (count)
  3384. mb_debug(sb, "mballoc: %d PAs left\n",
  3385. count);
  3386. ext4_unlock_group(sb, i);
  3387. kmem_cache_free(cachep, grinfo);
  3388. }
  3389. num_meta_group_infos = (ngroups +
  3390. EXT4_DESC_PER_BLOCK(sb) - 1) >>
  3391. EXT4_DESC_PER_BLOCK_BITS(sb);
  3392. rcu_read_lock();
  3393. group_info = rcu_dereference(sbi->s_group_info);
  3394. for (i = 0; i < num_meta_group_infos; i++)
  3395. kfree(group_info[i]);
  3396. kvfree(group_info);
  3397. rcu_read_unlock();
  3398. }
  3399. kfree(sbi->s_mb_avg_fragment_size);
  3400. kfree(sbi->s_mb_avg_fragment_size_locks);
  3401. kfree(sbi->s_mb_largest_free_orders);
  3402. kfree(sbi->s_mb_largest_free_orders_locks);
  3403. kfree(sbi->s_mb_offsets);
  3404. kfree(sbi->s_mb_maxs);
  3405. iput(sbi->s_buddy_cache);
  3406. if (sbi->s_mb_stats) {
  3407. ext4_msg(sb, KERN_INFO,
  3408. "mballoc: %u blocks %u reqs (%u success)",
  3409. atomic_read(&sbi->s_bal_allocated),
  3410. atomic_read(&sbi->s_bal_reqs),
  3411. atomic_read(&sbi->s_bal_success));
  3412. ext4_msg(sb, KERN_INFO,
  3413. "mballoc: %u extents scanned, %u groups scanned, %u goal hits, "
  3414. "%u 2^N hits, %u breaks, %u lost",
  3415. atomic_read(&sbi->s_bal_ex_scanned),
  3416. atomic_read(&sbi->s_bal_groups_scanned),
  3417. atomic_read(&sbi->s_bal_goals),
  3418. atomic_read(&sbi->s_bal_2orders),
  3419. atomic_read(&sbi->s_bal_breaks),
  3420. atomic_read(&sbi->s_mb_lost_chunks));
  3421. ext4_msg(sb, KERN_INFO,
  3422. "mballoc: %u generated and it took %llu",
  3423. atomic_read(&sbi->s_mb_buddies_generated),
  3424. atomic64_read(&sbi->s_mb_generation_time));
  3425. ext4_msg(sb, KERN_INFO,
  3426. "mballoc: %u preallocated, %u discarded",
  3427. atomic_read(&sbi->s_mb_preallocated),
  3428. atomic_read(&sbi->s_mb_discarded));
  3429. }
  3430. free_percpu(sbi->s_locality_groups);
  3431. }
  3432. static inline int ext4_issue_discard(struct super_block *sb,
  3433. ext4_group_t block_group, ext4_grpblk_t cluster, int count)
  3434. {
  3435. ext4_fsblk_t discard_block;
  3436. discard_block = (EXT4_C2B(EXT4_SB(sb), cluster) +
  3437. ext4_group_first_block_no(sb, block_group));
  3438. count = EXT4_C2B(EXT4_SB(sb), count);
  3439. trace_ext4_discard_blocks(sb,
  3440. (unsigned long long) discard_block, count);
  3441. return sb_issue_discard(sb, discard_block, count, GFP_NOFS, 0);
  3442. }
  3443. static void ext4_free_data_in_buddy(struct super_block *sb,
  3444. struct ext4_free_data *entry)
  3445. {
  3446. struct ext4_buddy e4b;
  3447. struct ext4_group_info *db;
  3448. int err, count = 0;
  3449. mb_debug(sb, "gonna free %u blocks in group %u (0x%p):",
  3450. entry->efd_count, entry->efd_group, entry);
  3451. err = ext4_mb_load_buddy(sb, entry->efd_group, &e4b);
  3452. /* we expect to find existing buddy because it's pinned */
  3453. BUG_ON(err != 0);
  3454. spin_lock(&EXT4_SB(sb)->s_md_lock);
  3455. EXT4_SB(sb)->s_mb_free_pending -= entry->efd_count;
  3456. spin_unlock(&EXT4_SB(sb)->s_md_lock);
  3457. db = e4b.bd_info;
  3458. /* there are blocks to put in buddy to make them really free */
  3459. count += entry->efd_count;
  3460. ext4_lock_group(sb, entry->efd_group);
  3461. /* Take it out of per group rb tree */
  3462. rb_erase(&entry->efd_node, &(db->bb_free_root));
  3463. mb_free_blocks(NULL, &e4b, entry->efd_start_cluster, entry->efd_count);
  3464. /*
  3465. * Clear the trimmed flag for the group so that the next
  3466. * ext4_trim_fs can trim it.
  3467. */
  3468. EXT4_MB_GRP_CLEAR_TRIMMED(db);
  3469. if (!db->bb_free_root.rb_node) {
  3470. /* No more items in the per group rb tree
  3471. * balance refcounts from ext4_mb_free_metadata()
  3472. */
  3473. folio_put(e4b.bd_buddy_folio);
  3474. folio_put(e4b.bd_bitmap_folio);
  3475. }
  3476. ext4_unlock_group(sb, entry->efd_group);
  3477. ext4_mb_unload_buddy(&e4b);
  3478. mb_debug(sb, "freed %d blocks in 1 structures\n", count);
  3479. }
  3480. /*
  3481. * This function is called by the jbd2 layer once the commit has finished,
  3482. * so we know we can free the blocks that were released with that commit.
  3483. */
  3484. void ext4_process_freed_data(struct super_block *sb, tid_t commit_tid)
  3485. {
  3486. struct ext4_sb_info *sbi = EXT4_SB(sb);
  3487. struct ext4_free_data *entry, *tmp;
  3488. LIST_HEAD(freed_data_list);
  3489. struct list_head *s_freed_head = &sbi->s_freed_data_list[commit_tid & 1];
  3490. bool wake;
  3491. list_replace_init(s_freed_head, &freed_data_list);
  3492. list_for_each_entry(entry, &freed_data_list, efd_list)
  3493. ext4_free_data_in_buddy(sb, entry);
  3494. if (test_opt(sb, DISCARD)) {
  3495. spin_lock(&sbi->s_md_lock);
  3496. wake = list_empty(&sbi->s_discard_list);
  3497. list_splice_tail(&freed_data_list, &sbi->s_discard_list);
  3498. spin_unlock(&sbi->s_md_lock);
  3499. if (wake)
  3500. queue_work(system_unbound_wq, &sbi->s_discard_work);
  3501. } else {
  3502. list_for_each_entry_safe(entry, tmp, &freed_data_list, efd_list)
  3503. kmem_cache_free(ext4_free_data_cachep, entry);
  3504. }
  3505. }
  3506. int __init ext4_init_mballoc(void)
  3507. {
  3508. ext4_pspace_cachep = KMEM_CACHE(ext4_prealloc_space,
  3509. SLAB_RECLAIM_ACCOUNT);
  3510. if (ext4_pspace_cachep == NULL)
  3511. goto out;
  3512. ext4_ac_cachep = KMEM_CACHE(ext4_allocation_context,
  3513. SLAB_RECLAIM_ACCOUNT);
  3514. if (ext4_ac_cachep == NULL)
  3515. goto out_pa_free;
  3516. ext4_free_data_cachep = KMEM_CACHE(ext4_free_data,
  3517. SLAB_RECLAIM_ACCOUNT);
  3518. if (ext4_free_data_cachep == NULL)
  3519. goto out_ac_free;
  3520. return 0;
  3521. out_ac_free:
  3522. kmem_cache_destroy(ext4_ac_cachep);
  3523. out_pa_free:
  3524. kmem_cache_destroy(ext4_pspace_cachep);
  3525. out:
  3526. return -ENOMEM;
  3527. }
  3528. void ext4_exit_mballoc(void)
  3529. {
  3530. /*
  3531. * Wait for completion of call_rcu()'s on ext4_pspace_cachep
  3532. * before destroying the slab cache.
  3533. */
  3534. rcu_barrier();
  3535. kmem_cache_destroy(ext4_pspace_cachep);
  3536. kmem_cache_destroy(ext4_ac_cachep);
  3537. kmem_cache_destroy(ext4_free_data_cachep);
  3538. ext4_groupinfo_destroy_slabs();
  3539. }
  3540. #define EXT4_MB_BITMAP_MARKED_CHECK 0x0001
  3541. #define EXT4_MB_SYNC_UPDATE 0x0002
  3542. static int
  3543. ext4_mb_mark_context(handle_t *handle, struct super_block *sb, bool state,
  3544. ext4_group_t group, ext4_grpblk_t blkoff,
  3545. ext4_grpblk_t len, int flags, ext4_grpblk_t *ret_changed)
  3546. {
  3547. struct ext4_sb_info *sbi = EXT4_SB(sb);
  3548. struct buffer_head *bitmap_bh = NULL;
  3549. struct ext4_group_desc *gdp;
  3550. struct buffer_head *gdp_bh;
  3551. int err;
  3552. unsigned int i, already, changed = len;
  3553. KUNIT_STATIC_STUB_REDIRECT(ext4_mb_mark_context,
  3554. handle, sb, state, group, blkoff, len,
  3555. flags, ret_changed);
  3556. if (ret_changed)
  3557. *ret_changed = 0;
  3558. bitmap_bh = ext4_read_block_bitmap(sb, group);
  3559. if (IS_ERR(bitmap_bh))
  3560. return PTR_ERR(bitmap_bh);
  3561. if (handle) {
  3562. BUFFER_TRACE(bitmap_bh, "getting write access");
  3563. err = ext4_journal_get_write_access(handle, sb, bitmap_bh,
  3564. EXT4_JTR_NONE);
  3565. if (err)
  3566. goto out_err;
  3567. }
  3568. err = -EIO;
  3569. gdp = ext4_get_group_desc(sb, group, &gdp_bh);
  3570. if (!gdp)
  3571. goto out_err;
  3572. if (handle) {
  3573. BUFFER_TRACE(gdp_bh, "get_write_access");
  3574. err = ext4_journal_get_write_access(handle, sb, gdp_bh,
  3575. EXT4_JTR_NONE);
  3576. if (err)
  3577. goto out_err;
  3578. }
  3579. ext4_lock_group(sb, group);
  3580. if (ext4_has_group_desc_csum(sb) &&
  3581. (gdp->bg_flags & cpu_to_le16(EXT4_BG_BLOCK_UNINIT))) {
  3582. gdp->bg_flags &= cpu_to_le16(~EXT4_BG_BLOCK_UNINIT);
  3583. ext4_free_group_clusters_set(sb, gdp,
  3584. ext4_free_clusters_after_init(sb, group, gdp));
  3585. }
  3586. if (flags & EXT4_MB_BITMAP_MARKED_CHECK) {
  3587. already = 0;
  3588. for (i = 0; i < len; i++)
  3589. if (mb_test_bit(blkoff + i, bitmap_bh->b_data) ==
  3590. state)
  3591. already++;
  3592. changed = len - already;
  3593. }
  3594. if (state) {
  3595. mb_set_bits(bitmap_bh->b_data, blkoff, len);
  3596. ext4_free_group_clusters_set(sb, gdp,
  3597. ext4_free_group_clusters(sb, gdp) - changed);
  3598. } else {
  3599. mb_clear_bits(bitmap_bh->b_data, blkoff, len);
  3600. ext4_free_group_clusters_set(sb, gdp,
  3601. ext4_free_group_clusters(sb, gdp) + changed);
  3602. }
  3603. ext4_block_bitmap_csum_set(sb, gdp, bitmap_bh);
  3604. ext4_group_desc_csum_set(sb, group, gdp);
  3605. ext4_unlock_group(sb, group);
  3606. if (ret_changed)
  3607. *ret_changed = changed;
  3608. if (sbi->s_log_groups_per_flex) {
  3609. ext4_group_t flex_group = ext4_flex_group(sbi, group);
  3610. struct flex_groups *fg = sbi_array_rcu_deref(sbi,
  3611. s_flex_groups, flex_group);
  3612. if (state)
  3613. atomic64_sub(changed, &fg->free_clusters);
  3614. else
  3615. atomic64_add(changed, &fg->free_clusters);
  3616. }
  3617. err = ext4_handle_dirty_metadata(handle, NULL, bitmap_bh);
  3618. if (err)
  3619. goto out_err;
  3620. err = ext4_handle_dirty_metadata(handle, NULL, gdp_bh);
  3621. if (err)
  3622. goto out_err;
  3623. if (flags & EXT4_MB_SYNC_UPDATE) {
  3624. sync_dirty_buffer(bitmap_bh);
  3625. sync_dirty_buffer(gdp_bh);
  3626. }
  3627. out_err:
  3628. brelse(bitmap_bh);
  3629. return err;
  3630. }
  3631. /*
  3632. * Check quota and mark chosen space (ac->ac_b_ex) non-free in bitmaps
  3633. * Returns 0 if success or error code
  3634. */
  3635. static noinline_for_stack int
  3636. ext4_mb_mark_diskspace_used(struct ext4_allocation_context *ac,
  3637. handle_t *handle, unsigned int reserv_clstrs)
  3638. {
  3639. struct ext4_group_desc *gdp;
  3640. struct ext4_sb_info *sbi;
  3641. struct super_block *sb;
  3642. ext4_fsblk_t block;
  3643. int err, len;
  3644. int flags = 0;
  3645. ext4_grpblk_t changed;
  3646. BUG_ON(ac->ac_status != AC_STATUS_FOUND);
  3647. BUG_ON(ac->ac_b_ex.fe_len <= 0);
  3648. sb = ac->ac_sb;
  3649. sbi = EXT4_SB(sb);
  3650. gdp = ext4_get_group_desc(sb, ac->ac_b_ex.fe_group, NULL);
  3651. if (!gdp)
  3652. return -EIO;
  3653. ext4_debug("using block group %u(%d)\n", ac->ac_b_ex.fe_group,
  3654. ext4_free_group_clusters(sb, gdp));
  3655. block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
  3656. len = EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
  3657. if (!ext4_inode_block_valid(ac->ac_inode, block, len)) {
  3658. ext4_error(sb, "Allocating blocks %llu-%llu which overlap "
  3659. "fs metadata", block, block+len);
  3660. /* File system mounted not to panic on error
  3661. * Fix the bitmap and return EFSCORRUPTED
  3662. * We leak some of the blocks here.
  3663. */
  3664. err = ext4_mb_mark_context(handle, sb, true,
  3665. ac->ac_b_ex.fe_group,
  3666. ac->ac_b_ex.fe_start,
  3667. ac->ac_b_ex.fe_len,
  3668. 0, NULL);
  3669. if (!err)
  3670. err = -EFSCORRUPTED;
  3671. return err;
  3672. }
  3673. #ifdef AGGRESSIVE_CHECK
  3674. flags |= EXT4_MB_BITMAP_MARKED_CHECK;
  3675. #endif
  3676. err = ext4_mb_mark_context(handle, sb, true, ac->ac_b_ex.fe_group,
  3677. ac->ac_b_ex.fe_start, ac->ac_b_ex.fe_len,
  3678. flags, &changed);
  3679. if (err && changed == 0)
  3680. return err;
  3681. #ifdef AGGRESSIVE_CHECK
  3682. BUG_ON(changed != ac->ac_b_ex.fe_len);
  3683. #endif
  3684. percpu_counter_sub(&sbi->s_freeclusters_counter, ac->ac_b_ex.fe_len);
  3685. /*
  3686. * Now reduce the dirty block count also. Should not go negative
  3687. */
  3688. if (!(ac->ac_flags & EXT4_MB_DELALLOC_RESERVED))
  3689. /* release all the reserved blocks if non delalloc */
  3690. percpu_counter_sub(&sbi->s_dirtyclusters_counter,
  3691. reserv_clstrs);
  3692. return err;
  3693. }
  3694. /*
  3695. * Idempotent helper for Ext4 fast commit replay path to set the state of
  3696. * blocks in bitmaps and update counters.
  3697. */
  3698. void ext4_mb_mark_bb(struct super_block *sb, ext4_fsblk_t block,
  3699. int len, bool state)
  3700. {
  3701. struct ext4_sb_info *sbi = EXT4_SB(sb);
  3702. ext4_group_t group;
  3703. ext4_grpblk_t blkoff;
  3704. int err = 0;
  3705. unsigned int clen, thisgrp_len;
  3706. while (len > 0) {
  3707. ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
  3708. /*
  3709. * Check to see if we are freeing blocks across a group
  3710. * boundary.
  3711. * In case of flex_bg, this can happen that (block, len) may
  3712. * span across more than one group. In that case we need to
  3713. * get the corresponding group metadata to work with.
  3714. * For this we have goto again loop.
  3715. */
  3716. thisgrp_len = min_t(unsigned int, (unsigned int)len,
  3717. EXT4_BLOCKS_PER_GROUP(sb) - EXT4_C2B(sbi, blkoff));
  3718. clen = EXT4_NUM_B2C(sbi, thisgrp_len);
  3719. if (!ext4_sb_block_valid(sb, NULL, block, thisgrp_len)) {
  3720. ext4_error(sb, "Marking blocks in system zone - "
  3721. "Block = %llu, len = %u",
  3722. block, thisgrp_len);
  3723. break;
  3724. }
  3725. err = ext4_mb_mark_context(NULL, sb, state,
  3726. group, blkoff, clen,
  3727. EXT4_MB_BITMAP_MARKED_CHECK |
  3728. EXT4_MB_SYNC_UPDATE,
  3729. NULL);
  3730. if (err)
  3731. break;
  3732. block += thisgrp_len;
  3733. len -= thisgrp_len;
  3734. BUG_ON(len < 0);
  3735. }
  3736. }
  3737. /*
  3738. * here we normalize request for locality group
  3739. * Group request are normalized to s_mb_group_prealloc, which goes to
  3740. * s_strip if we set the same via mount option.
  3741. * s_mb_group_prealloc can be configured via
  3742. * /sys/fs/ext4/<partition>/mb_group_prealloc
  3743. *
  3744. * XXX: should we try to preallocate more than the group has now?
  3745. */
  3746. static void ext4_mb_normalize_group_request(struct ext4_allocation_context *ac)
  3747. {
  3748. struct super_block *sb = ac->ac_sb;
  3749. struct ext4_locality_group *lg = ac->ac_lg;
  3750. BUG_ON(lg == NULL);
  3751. ac->ac_g_ex.fe_len = EXT4_SB(sb)->s_mb_group_prealloc;
  3752. mb_debug(sb, "goal %u blocks for locality group\n", ac->ac_g_ex.fe_len);
  3753. }
  3754. /*
  3755. * This function returns the next element to look at during inode
  3756. * PA rbtree walk. We assume that we have held the inode PA rbtree lock
  3757. * (ei->i_prealloc_lock)
  3758. *
  3759. * new_start The start of the range we want to compare
  3760. * cur_start The existing start that we are comparing against
  3761. * node The node of the rb_tree
  3762. */
  3763. static inline struct rb_node*
  3764. ext4_mb_pa_rb_next_iter(ext4_lblk_t new_start, ext4_lblk_t cur_start, struct rb_node *node)
  3765. {
  3766. if (new_start < cur_start)
  3767. return node->rb_left;
  3768. else
  3769. return node->rb_right;
  3770. }
  3771. static inline void
  3772. ext4_mb_pa_assert_overlap(struct ext4_allocation_context *ac,
  3773. ext4_lblk_t start, loff_t end)
  3774. {
  3775. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  3776. struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
  3777. struct ext4_prealloc_space *tmp_pa;
  3778. ext4_lblk_t tmp_pa_start;
  3779. loff_t tmp_pa_end;
  3780. struct rb_node *iter;
  3781. read_lock(&ei->i_prealloc_lock);
  3782. for (iter = ei->i_prealloc_node.rb_node; iter;
  3783. iter = ext4_mb_pa_rb_next_iter(start, tmp_pa_start, iter)) {
  3784. tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
  3785. pa_node.inode_node);
  3786. tmp_pa_start = tmp_pa->pa_lstart;
  3787. tmp_pa_end = pa_logical_end(sbi, tmp_pa);
  3788. spin_lock(&tmp_pa->pa_lock);
  3789. if (tmp_pa->pa_deleted == 0)
  3790. BUG_ON(!(start >= tmp_pa_end || end <= tmp_pa_start));
  3791. spin_unlock(&tmp_pa->pa_lock);
  3792. }
  3793. read_unlock(&ei->i_prealloc_lock);
  3794. }
  3795. /*
  3796. * Given an allocation context "ac" and a range "start", "end", check
  3797. * and adjust boundaries if the range overlaps with any of the existing
  3798. * preallocatoins stored in the corresponding inode of the allocation context.
  3799. *
  3800. * Parameters:
  3801. * ac allocation context
  3802. * start start of the new range
  3803. * end end of the new range
  3804. */
  3805. static inline void
  3806. ext4_mb_pa_adjust_overlap(struct ext4_allocation_context *ac,
  3807. ext4_lblk_t *start, loff_t *end)
  3808. {
  3809. struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
  3810. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  3811. struct ext4_prealloc_space *tmp_pa = NULL, *left_pa = NULL, *right_pa = NULL;
  3812. struct rb_node *iter;
  3813. ext4_lblk_t new_start, tmp_pa_start, right_pa_start = -1;
  3814. loff_t new_end, tmp_pa_end, left_pa_end = -1;
  3815. new_start = *start;
  3816. new_end = *end;
  3817. /*
  3818. * Adjust the normalized range so that it doesn't overlap with any
  3819. * existing preallocated blocks(PAs). Make sure to hold the rbtree lock
  3820. * so it doesn't change underneath us.
  3821. */
  3822. read_lock(&ei->i_prealloc_lock);
  3823. /* Step 1: find any one immediate neighboring PA of the normalized range */
  3824. for (iter = ei->i_prealloc_node.rb_node; iter;
  3825. iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
  3826. tmp_pa_start, iter)) {
  3827. tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
  3828. pa_node.inode_node);
  3829. tmp_pa_start = tmp_pa->pa_lstart;
  3830. tmp_pa_end = pa_logical_end(sbi, tmp_pa);
  3831. /* PA must not overlap original request */
  3832. spin_lock(&tmp_pa->pa_lock);
  3833. if (tmp_pa->pa_deleted == 0)
  3834. BUG_ON(!(ac->ac_o_ex.fe_logical >= tmp_pa_end ||
  3835. ac->ac_o_ex.fe_logical < tmp_pa_start));
  3836. spin_unlock(&tmp_pa->pa_lock);
  3837. }
  3838. /*
  3839. * Step 2: check if the found PA is left or right neighbor and
  3840. * get the other neighbor
  3841. */
  3842. if (tmp_pa) {
  3843. if (tmp_pa->pa_lstart < ac->ac_o_ex.fe_logical) {
  3844. struct rb_node *tmp;
  3845. left_pa = tmp_pa;
  3846. tmp = rb_next(&left_pa->pa_node.inode_node);
  3847. if (tmp) {
  3848. right_pa = rb_entry(tmp,
  3849. struct ext4_prealloc_space,
  3850. pa_node.inode_node);
  3851. }
  3852. } else {
  3853. struct rb_node *tmp;
  3854. right_pa = tmp_pa;
  3855. tmp = rb_prev(&right_pa->pa_node.inode_node);
  3856. if (tmp) {
  3857. left_pa = rb_entry(tmp,
  3858. struct ext4_prealloc_space,
  3859. pa_node.inode_node);
  3860. }
  3861. }
  3862. }
  3863. /* Step 3: get the non deleted neighbors */
  3864. if (left_pa) {
  3865. for (iter = &left_pa->pa_node.inode_node;;
  3866. iter = rb_prev(iter)) {
  3867. if (!iter) {
  3868. left_pa = NULL;
  3869. break;
  3870. }
  3871. tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
  3872. pa_node.inode_node);
  3873. left_pa = tmp_pa;
  3874. spin_lock(&tmp_pa->pa_lock);
  3875. if (tmp_pa->pa_deleted == 0) {
  3876. spin_unlock(&tmp_pa->pa_lock);
  3877. break;
  3878. }
  3879. spin_unlock(&tmp_pa->pa_lock);
  3880. }
  3881. }
  3882. if (right_pa) {
  3883. for (iter = &right_pa->pa_node.inode_node;;
  3884. iter = rb_next(iter)) {
  3885. if (!iter) {
  3886. right_pa = NULL;
  3887. break;
  3888. }
  3889. tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
  3890. pa_node.inode_node);
  3891. right_pa = tmp_pa;
  3892. spin_lock(&tmp_pa->pa_lock);
  3893. if (tmp_pa->pa_deleted == 0) {
  3894. spin_unlock(&tmp_pa->pa_lock);
  3895. break;
  3896. }
  3897. spin_unlock(&tmp_pa->pa_lock);
  3898. }
  3899. }
  3900. if (left_pa) {
  3901. left_pa_end = pa_logical_end(sbi, left_pa);
  3902. BUG_ON(left_pa_end > ac->ac_o_ex.fe_logical);
  3903. }
  3904. if (right_pa) {
  3905. right_pa_start = right_pa->pa_lstart;
  3906. BUG_ON(right_pa_start <= ac->ac_o_ex.fe_logical);
  3907. }
  3908. /* Step 4: trim our normalized range to not overlap with the neighbors */
  3909. if (left_pa) {
  3910. if (left_pa_end > new_start)
  3911. new_start = left_pa_end;
  3912. }
  3913. if (right_pa) {
  3914. if (right_pa_start < new_end)
  3915. new_end = right_pa_start;
  3916. }
  3917. read_unlock(&ei->i_prealloc_lock);
  3918. /* XXX: extra loop to check we really don't overlap preallocations */
  3919. ext4_mb_pa_assert_overlap(ac, new_start, new_end);
  3920. *start = new_start;
  3921. *end = new_end;
  3922. }
  3923. /*
  3924. * Normalization means making request better in terms of
  3925. * size and alignment
  3926. */
  3927. static noinline_for_stack void
  3928. ext4_mb_normalize_request(struct ext4_allocation_context *ac,
  3929. struct ext4_allocation_request *ar)
  3930. {
  3931. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  3932. struct ext4_super_block *es = sbi->s_es;
  3933. int bsbits, max;
  3934. loff_t size, start_off, end;
  3935. loff_t orig_size __maybe_unused;
  3936. ext4_lblk_t start;
  3937. /* do normalize only data requests, metadata requests
  3938. do not need preallocation */
  3939. if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
  3940. return;
  3941. /* sometime caller may want exact blocks */
  3942. if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
  3943. return;
  3944. /* caller may indicate that preallocation isn't
  3945. * required (it's a tail, for example) */
  3946. if (ac->ac_flags & EXT4_MB_HINT_NOPREALLOC)
  3947. return;
  3948. if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC) {
  3949. ext4_mb_normalize_group_request(ac);
  3950. return ;
  3951. }
  3952. bsbits = ac->ac_sb->s_blocksize_bits;
  3953. /* first, let's learn actual file size
  3954. * given current request is allocated */
  3955. size = extent_logical_end(sbi, &ac->ac_o_ex);
  3956. size = size << bsbits;
  3957. if (size < i_size_read(ac->ac_inode))
  3958. size = i_size_read(ac->ac_inode);
  3959. orig_size = size;
  3960. /* max size of free chunks */
  3961. max = 2 << bsbits;
  3962. #define NRL_CHECK_SIZE(req, size, max, chunk_size) \
  3963. (req <= (size) || max <= (chunk_size))
  3964. /* first, try to predict filesize */
  3965. /* XXX: should this table be tunable? */
  3966. start_off = 0;
  3967. if (size <= 16 * 1024) {
  3968. size = 16 * 1024;
  3969. } else if (size <= 32 * 1024) {
  3970. size = 32 * 1024;
  3971. } else if (size <= 64 * 1024) {
  3972. size = 64 * 1024;
  3973. } else if (size <= 128 * 1024) {
  3974. size = 128 * 1024;
  3975. } else if (size <= 256 * 1024) {
  3976. size = 256 * 1024;
  3977. } else if (size <= 512 * 1024) {
  3978. size = 512 * 1024;
  3979. } else if (size <= 1024 * 1024) {
  3980. size = 1024 * 1024;
  3981. } else if (NRL_CHECK_SIZE(size, 4 * 1024 * 1024, max, 2 * 1024)) {
  3982. start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
  3983. (21 - bsbits)) << 21;
  3984. size = 2 * 1024 * 1024;
  3985. } else if (NRL_CHECK_SIZE(size, 8 * 1024 * 1024, max, 4 * 1024)) {
  3986. start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
  3987. (22 - bsbits)) << 22;
  3988. size = 4 * 1024 * 1024;
  3989. } else if (NRL_CHECK_SIZE(EXT4_C2B(sbi, ac->ac_o_ex.fe_len),
  3990. (8<<20)>>bsbits, max, 8 * 1024)) {
  3991. start_off = ((loff_t)ac->ac_o_ex.fe_logical >>
  3992. (23 - bsbits)) << 23;
  3993. size = 8 * 1024 * 1024;
  3994. } else {
  3995. start_off = (loff_t) ac->ac_o_ex.fe_logical << bsbits;
  3996. size = (loff_t) EXT4_C2B(sbi,
  3997. ac->ac_o_ex.fe_len) << bsbits;
  3998. }
  3999. size = size >> bsbits;
  4000. start = start_off >> bsbits;
  4001. /*
  4002. * For tiny groups (smaller than 8MB) the chosen allocation
  4003. * alignment may be larger than group size. Make sure the
  4004. * alignment does not move allocation to a different group which
  4005. * makes mballoc fail assertions later.
  4006. */
  4007. start = max(start, rounddown(ac->ac_o_ex.fe_logical,
  4008. (ext4_lblk_t)EXT4_BLOCKS_PER_GROUP(ac->ac_sb)));
  4009. /* avoid unnecessary preallocation that may trigger assertions */
  4010. if (start + size > EXT_MAX_BLOCKS)
  4011. size = EXT_MAX_BLOCKS - start;
  4012. /* don't cover already allocated blocks in selected range */
  4013. if (ar->pleft && start <= ar->lleft) {
  4014. size -= ar->lleft + 1 - start;
  4015. start = ar->lleft + 1;
  4016. }
  4017. if (ar->pright && start + size - 1 >= ar->lright)
  4018. size -= start + size - ar->lright;
  4019. /*
  4020. * Trim allocation request for filesystems with artificially small
  4021. * groups.
  4022. */
  4023. if (size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb))
  4024. size = EXT4_BLOCKS_PER_GROUP(ac->ac_sb);
  4025. end = start + size;
  4026. ext4_mb_pa_adjust_overlap(ac, &start, &end);
  4027. size = end - start;
  4028. /*
  4029. * In this function "start" and "size" are normalized for better
  4030. * alignment and length such that we could preallocate more blocks.
  4031. * This normalization is done such that original request of
  4032. * ac->ac_o_ex.fe_logical & fe_len should always lie within "start" and
  4033. * "size" boundaries.
  4034. * (Note fe_len can be relaxed since FS block allocation API does not
  4035. * provide gurantee on number of contiguous blocks allocation since that
  4036. * depends upon free space left, etc).
  4037. * In case of inode pa, later we use the allocated blocks
  4038. * [pa_pstart + fe_logical - pa_lstart, fe_len/size] from the preallocated
  4039. * range of goal/best blocks [start, size] to put it at the
  4040. * ac_o_ex.fe_logical extent of this inode.
  4041. * (See ext4_mb_use_inode_pa() for more details)
  4042. */
  4043. if (start + size <= ac->ac_o_ex.fe_logical ||
  4044. start > ac->ac_o_ex.fe_logical) {
  4045. ext4_msg(ac->ac_sb, KERN_ERR,
  4046. "start %lu, size %lu, fe_logical %lu",
  4047. (unsigned long) start, (unsigned long) size,
  4048. (unsigned long) ac->ac_o_ex.fe_logical);
  4049. BUG();
  4050. }
  4051. BUG_ON(size <= 0 || size > EXT4_BLOCKS_PER_GROUP(ac->ac_sb));
  4052. /* now prepare goal request */
  4053. /* XXX: is it better to align blocks WRT to logical
  4054. * placement or satisfy big request as is */
  4055. ac->ac_g_ex.fe_logical = start;
  4056. ac->ac_g_ex.fe_len = EXT4_NUM_B2C(sbi, size);
  4057. ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
  4058. /* define goal start in order to merge */
  4059. if (ar->pright && (ar->lright == (start + size)) &&
  4060. ar->pright >= size &&
  4061. ar->pright - size >= le32_to_cpu(es->s_first_data_block)) {
  4062. /* merge to the right */
  4063. ext4_get_group_no_and_offset(ac->ac_sb, ar->pright - size,
  4064. &ac->ac_g_ex.fe_group,
  4065. &ac->ac_g_ex.fe_start);
  4066. ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
  4067. }
  4068. if (ar->pleft && (ar->lleft + 1 == start) &&
  4069. ar->pleft + 1 < ext4_blocks_count(es)) {
  4070. /* merge to the left */
  4071. ext4_get_group_no_and_offset(ac->ac_sb, ar->pleft + 1,
  4072. &ac->ac_g_ex.fe_group,
  4073. &ac->ac_g_ex.fe_start);
  4074. ac->ac_flags |= EXT4_MB_HINT_TRY_GOAL;
  4075. }
  4076. mb_debug(ac->ac_sb, "goal: %lld(was %lld) blocks at %u\n", size,
  4077. orig_size, start);
  4078. }
  4079. static void ext4_mb_collect_stats(struct ext4_allocation_context *ac)
  4080. {
  4081. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  4082. if (sbi->s_mb_stats && ac->ac_g_ex.fe_len >= 1) {
  4083. atomic_inc(&sbi->s_bal_reqs);
  4084. atomic_add(ac->ac_b_ex.fe_len, &sbi->s_bal_allocated);
  4085. if (ac->ac_b_ex.fe_len >= ac->ac_o_ex.fe_len)
  4086. atomic_inc(&sbi->s_bal_success);
  4087. atomic_add(ac->ac_found, &sbi->s_bal_ex_scanned);
  4088. for (int i=0; i<EXT4_MB_NUM_CRS; i++) {
  4089. atomic_add(ac->ac_cX_found[i], &sbi->s_bal_cX_ex_scanned[i]);
  4090. }
  4091. atomic_add(ac->ac_groups_scanned, &sbi->s_bal_groups_scanned);
  4092. if (ac->ac_g_ex.fe_start == ac->ac_b_ex.fe_start &&
  4093. ac->ac_g_ex.fe_group == ac->ac_b_ex.fe_group)
  4094. atomic_inc(&sbi->s_bal_goals);
  4095. /* did we allocate as much as normalizer originally wanted? */
  4096. if (ac->ac_f_ex.fe_len == ac->ac_orig_goal_len)
  4097. atomic_inc(&sbi->s_bal_len_goals);
  4098. if (ac->ac_found > sbi->s_mb_max_to_scan)
  4099. atomic_inc(&sbi->s_bal_breaks);
  4100. }
  4101. if (ac->ac_op == EXT4_MB_HISTORY_ALLOC)
  4102. trace_ext4_mballoc_alloc(ac);
  4103. else
  4104. trace_ext4_mballoc_prealloc(ac);
  4105. }
  4106. /*
  4107. * Called on failure; free up any blocks from the inode PA for this
  4108. * context. We don't need this for MB_GROUP_PA because we only change
  4109. * pa_free in ext4_mb_release_context(), but on failure, we've already
  4110. * zeroed out ac->ac_b_ex.fe_len, so group_pa->pa_free is not changed.
  4111. */
  4112. static void ext4_discard_allocated_blocks(struct ext4_allocation_context *ac)
  4113. {
  4114. struct ext4_prealloc_space *pa = ac->ac_pa;
  4115. struct ext4_buddy e4b;
  4116. int err;
  4117. if (pa == NULL) {
  4118. if (ac->ac_f_ex.fe_len == 0)
  4119. return;
  4120. err = ext4_mb_load_buddy(ac->ac_sb, ac->ac_f_ex.fe_group, &e4b);
  4121. if (WARN_RATELIMIT(err,
  4122. "ext4: mb_load_buddy failed (%d)", err))
  4123. /*
  4124. * This should never happen since we pin the
  4125. * pages in the ext4_allocation_context so
  4126. * ext4_mb_load_buddy() should never fail.
  4127. */
  4128. return;
  4129. ext4_lock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
  4130. mb_free_blocks(ac->ac_inode, &e4b, ac->ac_f_ex.fe_start,
  4131. ac->ac_f_ex.fe_len);
  4132. ext4_unlock_group(ac->ac_sb, ac->ac_f_ex.fe_group);
  4133. ext4_mb_unload_buddy(&e4b);
  4134. return;
  4135. }
  4136. if (pa->pa_type == MB_INODE_PA) {
  4137. spin_lock(&pa->pa_lock);
  4138. pa->pa_free += ac->ac_b_ex.fe_len;
  4139. spin_unlock(&pa->pa_lock);
  4140. }
  4141. }
  4142. /*
  4143. * use blocks preallocated to inode
  4144. */
  4145. static void ext4_mb_use_inode_pa(struct ext4_allocation_context *ac,
  4146. struct ext4_prealloc_space *pa)
  4147. {
  4148. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  4149. ext4_fsblk_t start;
  4150. ext4_fsblk_t end;
  4151. int len;
  4152. /* found preallocated blocks, use them */
  4153. start = pa->pa_pstart + (ac->ac_o_ex.fe_logical - pa->pa_lstart);
  4154. end = min(pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len),
  4155. start + EXT4_C2B(sbi, ac->ac_o_ex.fe_len));
  4156. len = EXT4_NUM_B2C(sbi, end - start);
  4157. ext4_get_group_no_and_offset(ac->ac_sb, start, &ac->ac_b_ex.fe_group,
  4158. &ac->ac_b_ex.fe_start);
  4159. ac->ac_b_ex.fe_len = len;
  4160. ac->ac_status = AC_STATUS_FOUND;
  4161. ac->ac_pa = pa;
  4162. BUG_ON(start < pa->pa_pstart);
  4163. BUG_ON(end > pa->pa_pstart + EXT4_C2B(sbi, pa->pa_len));
  4164. BUG_ON(pa->pa_free < len);
  4165. BUG_ON(ac->ac_b_ex.fe_len <= 0);
  4166. pa->pa_free -= len;
  4167. mb_debug(ac->ac_sb, "use %llu/%d from inode pa %p\n", start, len, pa);
  4168. }
  4169. /*
  4170. * use blocks preallocated to locality group
  4171. */
  4172. static void ext4_mb_use_group_pa(struct ext4_allocation_context *ac,
  4173. struct ext4_prealloc_space *pa)
  4174. {
  4175. unsigned int len = ac->ac_o_ex.fe_len;
  4176. ext4_get_group_no_and_offset(ac->ac_sb, pa->pa_pstart,
  4177. &ac->ac_b_ex.fe_group,
  4178. &ac->ac_b_ex.fe_start);
  4179. ac->ac_b_ex.fe_len = len;
  4180. ac->ac_status = AC_STATUS_FOUND;
  4181. ac->ac_pa = pa;
  4182. /* we don't correct pa_pstart or pa_len here to avoid
  4183. * possible race when the group is being loaded concurrently
  4184. * instead we correct pa later, after blocks are marked
  4185. * in on-disk bitmap -- see ext4_mb_release_context()
  4186. * Other CPUs are prevented from allocating from this pa by lg_mutex
  4187. */
  4188. mb_debug(ac->ac_sb, "use %u/%u from group pa %p\n",
  4189. pa->pa_lstart, len, pa);
  4190. }
  4191. /*
  4192. * Return the prealloc space that have minimal distance
  4193. * from the goal block. @cpa is the prealloc
  4194. * space that is having currently known minimal distance
  4195. * from the goal block.
  4196. */
  4197. static struct ext4_prealloc_space *
  4198. ext4_mb_check_group_pa(ext4_fsblk_t goal_block,
  4199. struct ext4_prealloc_space *pa,
  4200. struct ext4_prealloc_space *cpa)
  4201. {
  4202. ext4_fsblk_t cur_distance, new_distance;
  4203. if (cpa == NULL) {
  4204. atomic_inc(&pa->pa_count);
  4205. return pa;
  4206. }
  4207. cur_distance = abs(goal_block - cpa->pa_pstart);
  4208. new_distance = abs(goal_block - pa->pa_pstart);
  4209. if (cur_distance <= new_distance)
  4210. return cpa;
  4211. /* drop the previous reference */
  4212. atomic_dec(&cpa->pa_count);
  4213. atomic_inc(&pa->pa_count);
  4214. return pa;
  4215. }
  4216. /*
  4217. * check if found pa meets EXT4_MB_HINT_GOAL_ONLY
  4218. */
  4219. static bool
  4220. ext4_mb_pa_goal_check(struct ext4_allocation_context *ac,
  4221. struct ext4_prealloc_space *pa)
  4222. {
  4223. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  4224. ext4_fsblk_t start;
  4225. if (likely(!(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY)))
  4226. return true;
  4227. /*
  4228. * If EXT4_MB_HINT_GOAL_ONLY is set, ac_g_ex will not be adjusted
  4229. * in ext4_mb_normalize_request and will keep same with ac_o_ex
  4230. * from ext4_mb_initialize_context. Choose ac_g_ex here to keep
  4231. * consistent with ext4_mb_find_by_goal.
  4232. */
  4233. start = pa->pa_pstart +
  4234. (ac->ac_g_ex.fe_logical - pa->pa_lstart);
  4235. if (ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex) != start)
  4236. return false;
  4237. if (ac->ac_g_ex.fe_len > pa->pa_len -
  4238. EXT4_B2C(sbi, ac->ac_g_ex.fe_logical - pa->pa_lstart))
  4239. return false;
  4240. return true;
  4241. }
  4242. /*
  4243. * search goal blocks in preallocated space
  4244. */
  4245. static noinline_for_stack bool
  4246. ext4_mb_use_preallocated(struct ext4_allocation_context *ac)
  4247. {
  4248. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  4249. int order, i;
  4250. struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
  4251. struct ext4_locality_group *lg;
  4252. struct ext4_prealloc_space *tmp_pa = NULL, *cpa = NULL;
  4253. struct rb_node *iter;
  4254. ext4_fsblk_t goal_block;
  4255. /* only data can be preallocated */
  4256. if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
  4257. return false;
  4258. /*
  4259. * first, try per-file preallocation by searching the inode pa rbtree.
  4260. *
  4261. * Here, we can't do a direct traversal of the tree because
  4262. * ext4_mb_discard_group_preallocation() can paralelly mark the pa
  4263. * deleted and that can cause direct traversal to skip some entries.
  4264. */
  4265. read_lock(&ei->i_prealloc_lock);
  4266. if (RB_EMPTY_ROOT(&ei->i_prealloc_node)) {
  4267. goto try_group_pa;
  4268. }
  4269. /*
  4270. * Step 1: Find a pa with logical start immediately adjacent to the
  4271. * original logical start. This could be on the left or right.
  4272. *
  4273. * (tmp_pa->pa_lstart never changes so we can skip locking for it).
  4274. */
  4275. for (iter = ei->i_prealloc_node.rb_node; iter;
  4276. iter = ext4_mb_pa_rb_next_iter(ac->ac_o_ex.fe_logical,
  4277. tmp_pa->pa_lstart, iter)) {
  4278. tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
  4279. pa_node.inode_node);
  4280. }
  4281. /*
  4282. * Step 2: The adjacent pa might be to the right of logical start, find
  4283. * the left adjacent pa. After this step we'd have a valid tmp_pa whose
  4284. * logical start is towards the left of original request's logical start
  4285. */
  4286. if (tmp_pa->pa_lstart > ac->ac_o_ex.fe_logical) {
  4287. struct rb_node *tmp;
  4288. tmp = rb_prev(&tmp_pa->pa_node.inode_node);
  4289. if (tmp) {
  4290. tmp_pa = rb_entry(tmp, struct ext4_prealloc_space,
  4291. pa_node.inode_node);
  4292. } else {
  4293. /*
  4294. * If there is no adjacent pa to the left then finding
  4295. * an overlapping pa is not possible hence stop searching
  4296. * inode pa tree
  4297. */
  4298. goto try_group_pa;
  4299. }
  4300. }
  4301. BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
  4302. /*
  4303. * Step 3: If the left adjacent pa is deleted, keep moving left to find
  4304. * the first non deleted adjacent pa. After this step we should have a
  4305. * valid tmp_pa which is guaranteed to be non deleted.
  4306. */
  4307. for (iter = &tmp_pa->pa_node.inode_node;; iter = rb_prev(iter)) {
  4308. if (!iter) {
  4309. /*
  4310. * no non deleted left adjacent pa, so stop searching
  4311. * inode pa tree
  4312. */
  4313. goto try_group_pa;
  4314. }
  4315. tmp_pa = rb_entry(iter, struct ext4_prealloc_space,
  4316. pa_node.inode_node);
  4317. spin_lock(&tmp_pa->pa_lock);
  4318. if (tmp_pa->pa_deleted == 0) {
  4319. /*
  4320. * We will keep holding the pa_lock from
  4321. * this point on because we don't want group discard
  4322. * to delete this pa underneath us. Since group
  4323. * discard is anyways an ENOSPC operation it
  4324. * should be okay for it to wait a few more cycles.
  4325. */
  4326. break;
  4327. } else {
  4328. spin_unlock(&tmp_pa->pa_lock);
  4329. }
  4330. }
  4331. BUG_ON(!(tmp_pa && tmp_pa->pa_lstart <= ac->ac_o_ex.fe_logical));
  4332. BUG_ON(tmp_pa->pa_deleted == 1);
  4333. /*
  4334. * Step 4: We now have the non deleted left adjacent pa. Only this
  4335. * pa can possibly satisfy the request hence check if it overlaps
  4336. * original logical start and stop searching if it doesn't.
  4337. */
  4338. if (ac->ac_o_ex.fe_logical >= pa_logical_end(sbi, tmp_pa)) {
  4339. spin_unlock(&tmp_pa->pa_lock);
  4340. goto try_group_pa;
  4341. }
  4342. /* non-extent files can't have physical blocks past 2^32 */
  4343. if (!(ext4_test_inode_flag(ac->ac_inode, EXT4_INODE_EXTENTS)) &&
  4344. (tmp_pa->pa_pstart + EXT4_C2B(sbi, tmp_pa->pa_len) >
  4345. EXT4_MAX_BLOCK_FILE_PHYS)) {
  4346. /*
  4347. * Since PAs don't overlap, we won't find any other PA to
  4348. * satisfy this.
  4349. */
  4350. spin_unlock(&tmp_pa->pa_lock);
  4351. goto try_group_pa;
  4352. }
  4353. if (tmp_pa->pa_free && likely(ext4_mb_pa_goal_check(ac, tmp_pa))) {
  4354. atomic_inc(&tmp_pa->pa_count);
  4355. ext4_mb_use_inode_pa(ac, tmp_pa);
  4356. spin_unlock(&tmp_pa->pa_lock);
  4357. read_unlock(&ei->i_prealloc_lock);
  4358. return true;
  4359. } else {
  4360. /*
  4361. * We found a valid overlapping pa but couldn't use it because
  4362. * it had no free blocks. This should ideally never happen
  4363. * because:
  4364. *
  4365. * 1. When a new inode pa is added to rbtree it must have
  4366. * pa_free > 0 since otherwise we won't actually need
  4367. * preallocation.
  4368. *
  4369. * 2. An inode pa that is in the rbtree can only have it's
  4370. * pa_free become zero when another thread calls:
  4371. * ext4_mb_new_blocks
  4372. * ext4_mb_use_preallocated
  4373. * ext4_mb_use_inode_pa
  4374. *
  4375. * 3. Further, after the above calls make pa_free == 0, we will
  4376. * immediately remove it from the rbtree in:
  4377. * ext4_mb_new_blocks
  4378. * ext4_mb_release_context
  4379. * ext4_mb_put_pa
  4380. *
  4381. * 4. Since the pa_free becoming 0 and pa_free getting removed
  4382. * from tree both happen in ext4_mb_new_blocks, which is always
  4383. * called with i_data_sem held for data allocations, we can be
  4384. * sure that another process will never see a pa in rbtree with
  4385. * pa_free == 0.
  4386. */
  4387. WARN_ON_ONCE(tmp_pa->pa_free == 0);
  4388. }
  4389. spin_unlock(&tmp_pa->pa_lock);
  4390. try_group_pa:
  4391. read_unlock(&ei->i_prealloc_lock);
  4392. /* can we use group allocation? */
  4393. if (!(ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC))
  4394. return false;
  4395. /* inode may have no locality group for some reason */
  4396. lg = ac->ac_lg;
  4397. if (lg == NULL)
  4398. return false;
  4399. order = fls(ac->ac_o_ex.fe_len) - 1;
  4400. if (order > PREALLOC_TB_SIZE - 1)
  4401. /* The max size of hash table is PREALLOC_TB_SIZE */
  4402. order = PREALLOC_TB_SIZE - 1;
  4403. goal_block = ext4_grp_offs_to_block(ac->ac_sb, &ac->ac_g_ex);
  4404. /*
  4405. * search for the prealloc space that is having
  4406. * minimal distance from the goal block.
  4407. */
  4408. for (i = order; i < PREALLOC_TB_SIZE; i++) {
  4409. rcu_read_lock();
  4410. list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[i],
  4411. pa_node.lg_list) {
  4412. spin_lock(&tmp_pa->pa_lock);
  4413. if (tmp_pa->pa_deleted == 0 &&
  4414. tmp_pa->pa_free >= ac->ac_o_ex.fe_len) {
  4415. cpa = ext4_mb_check_group_pa(goal_block,
  4416. tmp_pa, cpa);
  4417. }
  4418. spin_unlock(&tmp_pa->pa_lock);
  4419. }
  4420. rcu_read_unlock();
  4421. }
  4422. if (cpa) {
  4423. ext4_mb_use_group_pa(ac, cpa);
  4424. return true;
  4425. }
  4426. return false;
  4427. }
  4428. /*
  4429. * the function goes through all preallocation in this group and marks them
  4430. * used in in-core bitmap. buddy must be generated from this bitmap
  4431. * Need to be called with ext4 group lock held
  4432. */
  4433. static noinline_for_stack
  4434. void ext4_mb_generate_from_pa(struct super_block *sb, void *bitmap,
  4435. ext4_group_t group)
  4436. {
  4437. struct ext4_group_info *grp = ext4_get_group_info(sb, group);
  4438. struct ext4_prealloc_space *pa;
  4439. struct list_head *cur;
  4440. ext4_group_t groupnr;
  4441. ext4_grpblk_t start;
  4442. int preallocated = 0;
  4443. int len;
  4444. if (!grp)
  4445. return;
  4446. /* all form of preallocation discards first load group,
  4447. * so the only competing code is preallocation use.
  4448. * we don't need any locking here
  4449. * notice we do NOT ignore preallocations with pa_deleted
  4450. * otherwise we could leave used blocks available for
  4451. * allocation in buddy when concurrent ext4_mb_put_pa()
  4452. * is dropping preallocation
  4453. */
  4454. list_for_each(cur, &grp->bb_prealloc_list) {
  4455. pa = list_entry(cur, struct ext4_prealloc_space, pa_group_list);
  4456. spin_lock(&pa->pa_lock);
  4457. ext4_get_group_no_and_offset(sb, pa->pa_pstart,
  4458. &groupnr, &start);
  4459. len = pa->pa_len;
  4460. spin_unlock(&pa->pa_lock);
  4461. if (unlikely(len == 0))
  4462. continue;
  4463. BUG_ON(groupnr != group);
  4464. mb_set_bits(bitmap, start, len);
  4465. preallocated += len;
  4466. }
  4467. mb_debug(sb, "preallocated %d for group %u\n", preallocated, group);
  4468. }
  4469. static void ext4_mb_mark_pa_deleted(struct super_block *sb,
  4470. struct ext4_prealloc_space *pa)
  4471. {
  4472. struct ext4_inode_info *ei;
  4473. if (pa->pa_deleted) {
  4474. ext4_warning(sb, "deleted pa, type:%d, pblk:%llu, lblk:%u, len:%d\n",
  4475. pa->pa_type, pa->pa_pstart, pa->pa_lstart,
  4476. pa->pa_len);
  4477. return;
  4478. }
  4479. pa->pa_deleted = 1;
  4480. if (pa->pa_type == MB_INODE_PA) {
  4481. ei = EXT4_I(pa->pa_inode);
  4482. atomic_dec(&ei->i_prealloc_active);
  4483. }
  4484. }
  4485. static inline void ext4_mb_pa_free(struct ext4_prealloc_space *pa)
  4486. {
  4487. BUG_ON(!pa);
  4488. BUG_ON(atomic_read(&pa->pa_count));
  4489. BUG_ON(pa->pa_deleted == 0);
  4490. kmem_cache_free(ext4_pspace_cachep, pa);
  4491. }
  4492. static void ext4_mb_pa_callback(struct rcu_head *head)
  4493. {
  4494. struct ext4_prealloc_space *pa;
  4495. pa = container_of(head, struct ext4_prealloc_space, u.pa_rcu);
  4496. ext4_mb_pa_free(pa);
  4497. }
  4498. /*
  4499. * drops a reference to preallocated space descriptor
  4500. * if this was the last reference and the space is consumed
  4501. */
  4502. static void ext4_mb_put_pa(struct ext4_allocation_context *ac,
  4503. struct super_block *sb, struct ext4_prealloc_space *pa)
  4504. {
  4505. ext4_group_t grp;
  4506. ext4_fsblk_t grp_blk;
  4507. struct ext4_inode_info *ei = EXT4_I(ac->ac_inode);
  4508. /* in this short window concurrent discard can set pa_deleted */
  4509. spin_lock(&pa->pa_lock);
  4510. if (!atomic_dec_and_test(&pa->pa_count) || pa->pa_free != 0) {
  4511. spin_unlock(&pa->pa_lock);
  4512. return;
  4513. }
  4514. if (pa->pa_deleted == 1) {
  4515. spin_unlock(&pa->pa_lock);
  4516. return;
  4517. }
  4518. ext4_mb_mark_pa_deleted(sb, pa);
  4519. spin_unlock(&pa->pa_lock);
  4520. grp_blk = pa->pa_pstart;
  4521. /*
  4522. * If doing group-based preallocation, pa_pstart may be in the
  4523. * next group when pa is used up
  4524. */
  4525. if (pa->pa_type == MB_GROUP_PA)
  4526. grp_blk--;
  4527. grp = ext4_get_group_number(sb, grp_blk);
  4528. /*
  4529. * possible race:
  4530. *
  4531. * P1 (buddy init) P2 (regular allocation)
  4532. * find block B in PA
  4533. * copy on-disk bitmap to buddy
  4534. * mark B in on-disk bitmap
  4535. * drop PA from group
  4536. * mark all PAs in buddy
  4537. *
  4538. * thus, P1 initializes buddy with B available. to prevent this
  4539. * we make "copy" and "mark all PAs" atomic and serialize "drop PA"
  4540. * against that pair
  4541. */
  4542. ext4_lock_group(sb, grp);
  4543. list_del(&pa->pa_group_list);
  4544. ext4_unlock_group(sb, grp);
  4545. if (pa->pa_type == MB_INODE_PA) {
  4546. write_lock(pa->pa_node_lock.inode_lock);
  4547. rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
  4548. write_unlock(pa->pa_node_lock.inode_lock);
  4549. ext4_mb_pa_free(pa);
  4550. } else {
  4551. spin_lock(pa->pa_node_lock.lg_lock);
  4552. list_del_rcu(&pa->pa_node.lg_list);
  4553. spin_unlock(pa->pa_node_lock.lg_lock);
  4554. call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
  4555. }
  4556. }
  4557. static void ext4_mb_pa_rb_insert(struct rb_root *root, struct rb_node *new)
  4558. {
  4559. struct rb_node **iter = &root->rb_node, *parent = NULL;
  4560. struct ext4_prealloc_space *iter_pa, *new_pa;
  4561. ext4_lblk_t iter_start, new_start;
  4562. while (*iter) {
  4563. iter_pa = rb_entry(*iter, struct ext4_prealloc_space,
  4564. pa_node.inode_node);
  4565. new_pa = rb_entry(new, struct ext4_prealloc_space,
  4566. pa_node.inode_node);
  4567. iter_start = iter_pa->pa_lstart;
  4568. new_start = new_pa->pa_lstart;
  4569. parent = *iter;
  4570. if (new_start < iter_start)
  4571. iter = &((*iter)->rb_left);
  4572. else
  4573. iter = &((*iter)->rb_right);
  4574. }
  4575. rb_link_node(new, parent, iter);
  4576. rb_insert_color(new, root);
  4577. }
  4578. /*
  4579. * creates new preallocated space for given inode
  4580. */
  4581. static noinline_for_stack void
  4582. ext4_mb_new_inode_pa(struct ext4_allocation_context *ac)
  4583. {
  4584. struct super_block *sb = ac->ac_sb;
  4585. struct ext4_sb_info *sbi = EXT4_SB(sb);
  4586. struct ext4_prealloc_space *pa;
  4587. struct ext4_group_info *grp;
  4588. struct ext4_inode_info *ei;
  4589. /* preallocate only when found space is larger then requested */
  4590. BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
  4591. BUG_ON(ac->ac_status != AC_STATUS_FOUND);
  4592. BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
  4593. BUG_ON(ac->ac_pa == NULL);
  4594. pa = ac->ac_pa;
  4595. if (ac->ac_b_ex.fe_len < ac->ac_orig_goal_len) {
  4596. struct ext4_free_extent ex = {
  4597. .fe_logical = ac->ac_g_ex.fe_logical,
  4598. .fe_len = ac->ac_orig_goal_len,
  4599. };
  4600. loff_t orig_goal_end = extent_logical_end(sbi, &ex);
  4601. loff_t o_ex_end = extent_logical_end(sbi, &ac->ac_o_ex);
  4602. /*
  4603. * We can't allocate as much as normalizer wants, so we try
  4604. * to get proper lstart to cover the original request, except
  4605. * when the goal doesn't cover the original request as below:
  4606. *
  4607. * orig_ex:2045/2055(10), isize:8417280 -> normalized:0/2048
  4608. * best_ex:0/200(200) -> adjusted: 1848/2048(200)
  4609. */
  4610. BUG_ON(ac->ac_g_ex.fe_logical > ac->ac_o_ex.fe_logical);
  4611. BUG_ON(ac->ac_g_ex.fe_len < ac->ac_o_ex.fe_len);
  4612. /*
  4613. * Use the below logic for adjusting best extent as it keeps
  4614. * fragmentation in check while ensuring logical range of best
  4615. * extent doesn't overflow out of goal extent:
  4616. *
  4617. * 1. Check if best ex can be kept at end of goal (before
  4618. * cr_best_avail trimmed it) and still cover original start
  4619. * 2. Else, check if best ex can be kept at start of goal and
  4620. * still cover original end
  4621. * 3. Else, keep the best ex at start of original request.
  4622. */
  4623. ex.fe_len = ac->ac_b_ex.fe_len;
  4624. ex.fe_logical = orig_goal_end - EXT4_C2B(sbi, ex.fe_len);
  4625. if (ac->ac_o_ex.fe_logical >= ex.fe_logical)
  4626. goto adjust_bex;
  4627. ex.fe_logical = ac->ac_g_ex.fe_logical;
  4628. if (o_ex_end <= extent_logical_end(sbi, &ex))
  4629. goto adjust_bex;
  4630. ex.fe_logical = ac->ac_o_ex.fe_logical;
  4631. adjust_bex:
  4632. ac->ac_b_ex.fe_logical = ex.fe_logical;
  4633. BUG_ON(ac->ac_o_ex.fe_logical < ac->ac_b_ex.fe_logical);
  4634. BUG_ON(extent_logical_end(sbi, &ex) > orig_goal_end);
  4635. }
  4636. pa->pa_lstart = ac->ac_b_ex.fe_logical;
  4637. pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
  4638. pa->pa_len = ac->ac_b_ex.fe_len;
  4639. pa->pa_free = pa->pa_len;
  4640. spin_lock_init(&pa->pa_lock);
  4641. INIT_LIST_HEAD(&pa->pa_group_list);
  4642. pa->pa_deleted = 0;
  4643. pa->pa_type = MB_INODE_PA;
  4644. mb_debug(sb, "new inode pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
  4645. pa->pa_len, pa->pa_lstart);
  4646. trace_ext4_mb_new_inode_pa(ac, pa);
  4647. atomic_add(pa->pa_free, &sbi->s_mb_preallocated);
  4648. ext4_mb_use_inode_pa(ac, pa);
  4649. ei = EXT4_I(ac->ac_inode);
  4650. grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
  4651. if (!grp)
  4652. return;
  4653. pa->pa_node_lock.inode_lock = &ei->i_prealloc_lock;
  4654. pa->pa_inode = ac->ac_inode;
  4655. list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
  4656. write_lock(pa->pa_node_lock.inode_lock);
  4657. ext4_mb_pa_rb_insert(&ei->i_prealloc_node, &pa->pa_node.inode_node);
  4658. write_unlock(pa->pa_node_lock.inode_lock);
  4659. atomic_inc(&ei->i_prealloc_active);
  4660. }
  4661. /*
  4662. * creates new preallocated space for locality group inodes belongs to
  4663. */
  4664. static noinline_for_stack void
  4665. ext4_mb_new_group_pa(struct ext4_allocation_context *ac)
  4666. {
  4667. struct super_block *sb = ac->ac_sb;
  4668. struct ext4_locality_group *lg;
  4669. struct ext4_prealloc_space *pa;
  4670. struct ext4_group_info *grp;
  4671. /* preallocate only when found space is larger then requested */
  4672. BUG_ON(ac->ac_o_ex.fe_len >= ac->ac_b_ex.fe_len);
  4673. BUG_ON(ac->ac_status != AC_STATUS_FOUND);
  4674. BUG_ON(!S_ISREG(ac->ac_inode->i_mode));
  4675. BUG_ON(ac->ac_pa == NULL);
  4676. pa = ac->ac_pa;
  4677. pa->pa_pstart = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
  4678. pa->pa_lstart = pa->pa_pstart;
  4679. pa->pa_len = ac->ac_b_ex.fe_len;
  4680. pa->pa_free = pa->pa_len;
  4681. spin_lock_init(&pa->pa_lock);
  4682. INIT_LIST_HEAD(&pa->pa_node.lg_list);
  4683. INIT_LIST_HEAD(&pa->pa_group_list);
  4684. pa->pa_deleted = 0;
  4685. pa->pa_type = MB_GROUP_PA;
  4686. mb_debug(sb, "new group pa %p: %llu/%d for %u\n", pa, pa->pa_pstart,
  4687. pa->pa_len, pa->pa_lstart);
  4688. trace_ext4_mb_new_group_pa(ac, pa);
  4689. ext4_mb_use_group_pa(ac, pa);
  4690. atomic_add(pa->pa_free, &EXT4_SB(sb)->s_mb_preallocated);
  4691. grp = ext4_get_group_info(sb, ac->ac_b_ex.fe_group);
  4692. if (!grp)
  4693. return;
  4694. lg = ac->ac_lg;
  4695. BUG_ON(lg == NULL);
  4696. pa->pa_node_lock.lg_lock = &lg->lg_prealloc_lock;
  4697. pa->pa_inode = NULL;
  4698. list_add(&pa->pa_group_list, &grp->bb_prealloc_list);
  4699. /*
  4700. * We will later add the new pa to the right bucket
  4701. * after updating the pa_free in ext4_mb_release_context
  4702. */
  4703. }
  4704. static void ext4_mb_new_preallocation(struct ext4_allocation_context *ac)
  4705. {
  4706. if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
  4707. ext4_mb_new_group_pa(ac);
  4708. else
  4709. ext4_mb_new_inode_pa(ac);
  4710. }
  4711. /*
  4712. * finds all unused blocks in on-disk bitmap, frees them in
  4713. * in-core bitmap and buddy.
  4714. * @pa must be unlinked from inode and group lists, so that
  4715. * nobody else can find/use it.
  4716. * the caller MUST hold group/inode locks.
  4717. * TODO: optimize the case when there are no in-core structures yet
  4718. */
  4719. static noinline_for_stack void
  4720. ext4_mb_release_inode_pa(struct ext4_buddy *e4b, struct buffer_head *bitmap_bh,
  4721. struct ext4_prealloc_space *pa)
  4722. {
  4723. struct super_block *sb = e4b->bd_sb;
  4724. struct ext4_sb_info *sbi = EXT4_SB(sb);
  4725. unsigned int end;
  4726. unsigned int next;
  4727. ext4_group_t group;
  4728. ext4_grpblk_t bit;
  4729. unsigned long long grp_blk_start;
  4730. int free = 0;
  4731. BUG_ON(pa->pa_deleted == 0);
  4732. ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
  4733. grp_blk_start = pa->pa_pstart - EXT4_C2B(sbi, bit);
  4734. BUG_ON(group != e4b->bd_group && pa->pa_len != 0);
  4735. end = bit + pa->pa_len;
  4736. while (bit < end) {
  4737. bit = mb_find_next_zero_bit(bitmap_bh->b_data, end, bit);
  4738. if (bit >= end)
  4739. break;
  4740. next = mb_find_next_bit(bitmap_bh->b_data, end, bit);
  4741. mb_debug(sb, "free preallocated %u/%u in group %u\n",
  4742. (unsigned) ext4_group_first_block_no(sb, group) + bit,
  4743. (unsigned) next - bit, (unsigned) group);
  4744. free += next - bit;
  4745. trace_ext4_mballoc_discard(sb, NULL, group, bit, next - bit);
  4746. trace_ext4_mb_release_inode_pa(pa, (grp_blk_start +
  4747. EXT4_C2B(sbi, bit)),
  4748. next - bit);
  4749. mb_free_blocks(pa->pa_inode, e4b, bit, next - bit);
  4750. bit = next + 1;
  4751. }
  4752. if (free != pa->pa_free) {
  4753. ext4_msg(e4b->bd_sb, KERN_CRIT,
  4754. "pa %p: logic %lu, phys. %lu, len %d",
  4755. pa, (unsigned long) pa->pa_lstart,
  4756. (unsigned long) pa->pa_pstart,
  4757. pa->pa_len);
  4758. ext4_grp_locked_error(sb, group, 0, 0, "free %u, pa_free %u",
  4759. free, pa->pa_free);
  4760. /*
  4761. * pa is already deleted so we use the value obtained
  4762. * from the bitmap and continue.
  4763. */
  4764. }
  4765. atomic_add(free, &sbi->s_mb_discarded);
  4766. }
  4767. static noinline_for_stack void
  4768. ext4_mb_release_group_pa(struct ext4_buddy *e4b,
  4769. struct ext4_prealloc_space *pa)
  4770. {
  4771. struct super_block *sb = e4b->bd_sb;
  4772. ext4_group_t group;
  4773. ext4_grpblk_t bit;
  4774. trace_ext4_mb_release_group_pa(sb, pa);
  4775. BUG_ON(pa->pa_deleted == 0);
  4776. ext4_get_group_no_and_offset(sb, pa->pa_pstart, &group, &bit);
  4777. if (unlikely(group != e4b->bd_group && pa->pa_len != 0)) {
  4778. ext4_warning(sb, "bad group: expected %u, group %u, pa_start %llu",
  4779. e4b->bd_group, group, pa->pa_pstart);
  4780. return;
  4781. }
  4782. mb_free_blocks(pa->pa_inode, e4b, bit, pa->pa_len);
  4783. atomic_add(pa->pa_len, &EXT4_SB(sb)->s_mb_discarded);
  4784. trace_ext4_mballoc_discard(sb, NULL, group, bit, pa->pa_len);
  4785. }
  4786. /*
  4787. * releases all preallocations in given group
  4788. *
  4789. * first, we need to decide discard policy:
  4790. * - when do we discard
  4791. * 1) ENOSPC
  4792. * - how many do we discard
  4793. * 1) how many requested
  4794. */
  4795. static noinline_for_stack int
  4796. ext4_mb_discard_group_preallocations(struct super_block *sb,
  4797. ext4_group_t group, int *busy)
  4798. {
  4799. struct ext4_group_info *grp = ext4_get_group_info(sb, group);
  4800. struct buffer_head *bitmap_bh = NULL;
  4801. struct ext4_prealloc_space *pa, *tmp;
  4802. LIST_HEAD(list);
  4803. struct ext4_buddy e4b;
  4804. struct ext4_inode_info *ei;
  4805. int err;
  4806. int free = 0;
  4807. if (!grp)
  4808. return 0;
  4809. mb_debug(sb, "discard preallocation for group %u\n", group);
  4810. if (list_empty(&grp->bb_prealloc_list))
  4811. goto out_dbg;
  4812. bitmap_bh = ext4_read_block_bitmap(sb, group);
  4813. if (IS_ERR(bitmap_bh)) {
  4814. err = PTR_ERR(bitmap_bh);
  4815. ext4_error_err(sb, -err,
  4816. "Error %d reading block bitmap for %u",
  4817. err, group);
  4818. goto out_dbg;
  4819. }
  4820. err = ext4_mb_load_buddy(sb, group, &e4b);
  4821. if (err) {
  4822. ext4_warning(sb, "Error %d loading buddy information for %u",
  4823. err, group);
  4824. put_bh(bitmap_bh);
  4825. goto out_dbg;
  4826. }
  4827. ext4_lock_group(sb, group);
  4828. list_for_each_entry_safe(pa, tmp,
  4829. &grp->bb_prealloc_list, pa_group_list) {
  4830. spin_lock(&pa->pa_lock);
  4831. if (atomic_read(&pa->pa_count)) {
  4832. spin_unlock(&pa->pa_lock);
  4833. *busy = 1;
  4834. continue;
  4835. }
  4836. if (pa->pa_deleted) {
  4837. spin_unlock(&pa->pa_lock);
  4838. continue;
  4839. }
  4840. /* seems this one can be freed ... */
  4841. ext4_mb_mark_pa_deleted(sb, pa);
  4842. if (!free)
  4843. this_cpu_inc(discard_pa_seq);
  4844. /* we can trust pa_free ... */
  4845. free += pa->pa_free;
  4846. spin_unlock(&pa->pa_lock);
  4847. list_del(&pa->pa_group_list);
  4848. list_add(&pa->u.pa_tmp_list, &list);
  4849. }
  4850. /* now free all selected PAs */
  4851. list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
  4852. /* remove from object (inode or locality group) */
  4853. if (pa->pa_type == MB_GROUP_PA) {
  4854. spin_lock(pa->pa_node_lock.lg_lock);
  4855. list_del_rcu(&pa->pa_node.lg_list);
  4856. spin_unlock(pa->pa_node_lock.lg_lock);
  4857. } else {
  4858. write_lock(pa->pa_node_lock.inode_lock);
  4859. ei = EXT4_I(pa->pa_inode);
  4860. rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
  4861. write_unlock(pa->pa_node_lock.inode_lock);
  4862. }
  4863. list_del(&pa->u.pa_tmp_list);
  4864. if (pa->pa_type == MB_GROUP_PA) {
  4865. ext4_mb_release_group_pa(&e4b, pa);
  4866. call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
  4867. } else {
  4868. ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
  4869. ext4_mb_pa_free(pa);
  4870. }
  4871. }
  4872. ext4_unlock_group(sb, group);
  4873. ext4_mb_unload_buddy(&e4b);
  4874. put_bh(bitmap_bh);
  4875. out_dbg:
  4876. mb_debug(sb, "discarded (%d) blocks preallocated for group %u bb_free (%d)\n",
  4877. free, group, grp->bb_free);
  4878. return free;
  4879. }
  4880. /*
  4881. * releases all non-used preallocated blocks for given inode
  4882. *
  4883. * It's important to discard preallocations under i_data_sem
  4884. * We don't want another block to be served from the prealloc
  4885. * space when we are discarding the inode prealloc space.
  4886. *
  4887. * FIXME!! Make sure it is valid at all the call sites
  4888. */
  4889. void ext4_discard_preallocations(struct inode *inode)
  4890. {
  4891. struct ext4_inode_info *ei = EXT4_I(inode);
  4892. struct super_block *sb = inode->i_sb;
  4893. struct buffer_head *bitmap_bh = NULL;
  4894. struct ext4_prealloc_space *pa, *tmp;
  4895. ext4_group_t group = 0;
  4896. LIST_HEAD(list);
  4897. struct ext4_buddy e4b;
  4898. struct rb_node *iter;
  4899. int err;
  4900. if (!S_ISREG(inode->i_mode))
  4901. return;
  4902. if (EXT4_SB(sb)->s_mount_state & EXT4_FC_REPLAY)
  4903. return;
  4904. mb_debug(sb, "discard preallocation for inode %lu\n",
  4905. inode->i_ino);
  4906. trace_ext4_discard_preallocations(inode,
  4907. atomic_read(&ei->i_prealloc_active));
  4908. repeat:
  4909. /* first, collect all pa's in the inode */
  4910. write_lock(&ei->i_prealloc_lock);
  4911. for (iter = rb_first(&ei->i_prealloc_node); iter;
  4912. iter = rb_next(iter)) {
  4913. pa = rb_entry(iter, struct ext4_prealloc_space,
  4914. pa_node.inode_node);
  4915. BUG_ON(pa->pa_node_lock.inode_lock != &ei->i_prealloc_lock);
  4916. spin_lock(&pa->pa_lock);
  4917. if (atomic_read(&pa->pa_count)) {
  4918. /* this shouldn't happen often - nobody should
  4919. * use preallocation while we're discarding it */
  4920. spin_unlock(&pa->pa_lock);
  4921. write_unlock(&ei->i_prealloc_lock);
  4922. ext4_msg(sb, KERN_ERR,
  4923. "uh-oh! used pa while discarding");
  4924. WARN_ON(1);
  4925. schedule_timeout_uninterruptible(HZ);
  4926. goto repeat;
  4927. }
  4928. if (pa->pa_deleted == 0) {
  4929. ext4_mb_mark_pa_deleted(sb, pa);
  4930. spin_unlock(&pa->pa_lock);
  4931. rb_erase(&pa->pa_node.inode_node, &ei->i_prealloc_node);
  4932. list_add(&pa->u.pa_tmp_list, &list);
  4933. continue;
  4934. }
  4935. /* someone is deleting pa right now */
  4936. spin_unlock(&pa->pa_lock);
  4937. write_unlock(&ei->i_prealloc_lock);
  4938. /* we have to wait here because pa_deleted
  4939. * doesn't mean pa is already unlinked from
  4940. * the list. as we might be called from
  4941. * ->clear_inode() the inode will get freed
  4942. * and concurrent thread which is unlinking
  4943. * pa from inode's list may access already
  4944. * freed memory, bad-bad-bad */
  4945. /* XXX: if this happens too often, we can
  4946. * add a flag to force wait only in case
  4947. * of ->clear_inode(), but not in case of
  4948. * regular truncate */
  4949. schedule_timeout_uninterruptible(HZ);
  4950. goto repeat;
  4951. }
  4952. write_unlock(&ei->i_prealloc_lock);
  4953. list_for_each_entry_safe(pa, tmp, &list, u.pa_tmp_list) {
  4954. BUG_ON(pa->pa_type != MB_INODE_PA);
  4955. group = ext4_get_group_number(sb, pa->pa_pstart);
  4956. err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
  4957. GFP_NOFS|__GFP_NOFAIL);
  4958. if (err) {
  4959. ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
  4960. err, group);
  4961. continue;
  4962. }
  4963. bitmap_bh = ext4_read_block_bitmap(sb, group);
  4964. if (IS_ERR(bitmap_bh)) {
  4965. err = PTR_ERR(bitmap_bh);
  4966. ext4_error_err(sb, -err, "Error %d reading block bitmap for %u",
  4967. err, group);
  4968. ext4_mb_unload_buddy(&e4b);
  4969. continue;
  4970. }
  4971. ext4_lock_group(sb, group);
  4972. list_del(&pa->pa_group_list);
  4973. ext4_mb_release_inode_pa(&e4b, bitmap_bh, pa);
  4974. ext4_unlock_group(sb, group);
  4975. ext4_mb_unload_buddy(&e4b);
  4976. put_bh(bitmap_bh);
  4977. list_del(&pa->u.pa_tmp_list);
  4978. ext4_mb_pa_free(pa);
  4979. }
  4980. }
  4981. static int ext4_mb_pa_alloc(struct ext4_allocation_context *ac)
  4982. {
  4983. struct ext4_prealloc_space *pa;
  4984. BUG_ON(ext4_pspace_cachep == NULL);
  4985. pa = kmem_cache_zalloc(ext4_pspace_cachep, GFP_NOFS);
  4986. if (!pa)
  4987. return -ENOMEM;
  4988. atomic_set(&pa->pa_count, 1);
  4989. ac->ac_pa = pa;
  4990. return 0;
  4991. }
  4992. static void ext4_mb_pa_put_free(struct ext4_allocation_context *ac)
  4993. {
  4994. struct ext4_prealloc_space *pa = ac->ac_pa;
  4995. BUG_ON(!pa);
  4996. ac->ac_pa = NULL;
  4997. WARN_ON(!atomic_dec_and_test(&pa->pa_count));
  4998. /*
  4999. * current function is only called due to an error or due to
  5000. * len of found blocks < len of requested blocks hence the PA has not
  5001. * been added to grp->bb_prealloc_list. So we don't need to lock it
  5002. */
  5003. pa->pa_deleted = 1;
  5004. ext4_mb_pa_free(pa);
  5005. }
  5006. #ifdef CONFIG_EXT4_DEBUG
  5007. static inline void ext4_mb_show_pa(struct super_block *sb)
  5008. {
  5009. ext4_group_t i, ngroups;
  5010. if (ext4_forced_shutdown(sb))
  5011. return;
  5012. ngroups = ext4_get_groups_count(sb);
  5013. mb_debug(sb, "groups: ");
  5014. for (i = 0; i < ngroups; i++) {
  5015. struct ext4_group_info *grp = ext4_get_group_info(sb, i);
  5016. struct ext4_prealloc_space *pa;
  5017. ext4_grpblk_t start;
  5018. struct list_head *cur;
  5019. if (!grp)
  5020. continue;
  5021. ext4_lock_group(sb, i);
  5022. list_for_each(cur, &grp->bb_prealloc_list) {
  5023. pa = list_entry(cur, struct ext4_prealloc_space,
  5024. pa_group_list);
  5025. spin_lock(&pa->pa_lock);
  5026. ext4_get_group_no_and_offset(sb, pa->pa_pstart,
  5027. NULL, &start);
  5028. spin_unlock(&pa->pa_lock);
  5029. mb_debug(sb, "PA:%u:%d:%d\n", i, start,
  5030. pa->pa_len);
  5031. }
  5032. ext4_unlock_group(sb, i);
  5033. mb_debug(sb, "%u: %d/%d\n", i, grp->bb_free,
  5034. grp->bb_fragments);
  5035. }
  5036. }
  5037. static void ext4_mb_show_ac(struct ext4_allocation_context *ac)
  5038. {
  5039. struct super_block *sb = ac->ac_sb;
  5040. if (ext4_forced_shutdown(sb))
  5041. return;
  5042. mb_debug(sb, "Can't allocate:"
  5043. " Allocation context details:");
  5044. mb_debug(sb, "status %u flags 0x%x",
  5045. ac->ac_status, ac->ac_flags);
  5046. mb_debug(sb, "orig %lu/%lu/%lu@%lu, "
  5047. "goal %lu/%lu/%lu@%lu, "
  5048. "best %lu/%lu/%lu@%lu cr %d",
  5049. (unsigned long)ac->ac_o_ex.fe_group,
  5050. (unsigned long)ac->ac_o_ex.fe_start,
  5051. (unsigned long)ac->ac_o_ex.fe_len,
  5052. (unsigned long)ac->ac_o_ex.fe_logical,
  5053. (unsigned long)ac->ac_g_ex.fe_group,
  5054. (unsigned long)ac->ac_g_ex.fe_start,
  5055. (unsigned long)ac->ac_g_ex.fe_len,
  5056. (unsigned long)ac->ac_g_ex.fe_logical,
  5057. (unsigned long)ac->ac_b_ex.fe_group,
  5058. (unsigned long)ac->ac_b_ex.fe_start,
  5059. (unsigned long)ac->ac_b_ex.fe_len,
  5060. (unsigned long)ac->ac_b_ex.fe_logical,
  5061. (int)ac->ac_criteria);
  5062. mb_debug(sb, "%u found", ac->ac_found);
  5063. mb_debug(sb, "used pa: %s, ", ac->ac_pa ? "yes" : "no");
  5064. if (ac->ac_pa)
  5065. mb_debug(sb, "pa_type %s\n", ac->ac_pa->pa_type == MB_GROUP_PA ?
  5066. "group pa" : "inode pa");
  5067. ext4_mb_show_pa(sb);
  5068. }
  5069. #else
  5070. static inline void ext4_mb_show_pa(struct super_block *sb)
  5071. {
  5072. }
  5073. static inline void ext4_mb_show_ac(struct ext4_allocation_context *ac)
  5074. {
  5075. ext4_mb_show_pa(ac->ac_sb);
  5076. }
  5077. #endif
  5078. /*
  5079. * We use locality group preallocation for small size file. The size of the
  5080. * file is determined by the current size or the resulting size after
  5081. * allocation which ever is larger
  5082. *
  5083. * One can tune this size via /sys/fs/ext4/<partition>/mb_stream_req
  5084. */
  5085. static void ext4_mb_group_or_file(struct ext4_allocation_context *ac)
  5086. {
  5087. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  5088. int bsbits = ac->ac_sb->s_blocksize_bits;
  5089. loff_t size, isize;
  5090. bool inode_pa_eligible, group_pa_eligible;
  5091. if (!(ac->ac_flags & EXT4_MB_HINT_DATA))
  5092. return;
  5093. if (unlikely(ac->ac_flags & EXT4_MB_HINT_GOAL_ONLY))
  5094. return;
  5095. group_pa_eligible = sbi->s_mb_group_prealloc > 0;
  5096. inode_pa_eligible = true;
  5097. size = extent_logical_end(sbi, &ac->ac_o_ex);
  5098. isize = (i_size_read(ac->ac_inode) + ac->ac_sb->s_blocksize - 1)
  5099. >> bsbits;
  5100. /* No point in using inode preallocation for closed files */
  5101. if ((size == isize) && !ext4_fs_is_busy(sbi) &&
  5102. !inode_is_open_for_write(ac->ac_inode))
  5103. inode_pa_eligible = false;
  5104. size = max(size, isize);
  5105. /* Don't use group allocation for large files */
  5106. if (size > sbi->s_mb_stream_request)
  5107. group_pa_eligible = false;
  5108. if (!group_pa_eligible) {
  5109. if (inode_pa_eligible)
  5110. ac->ac_flags |= EXT4_MB_STREAM_ALLOC;
  5111. else
  5112. ac->ac_flags |= EXT4_MB_HINT_NOPREALLOC;
  5113. return;
  5114. }
  5115. BUG_ON(ac->ac_lg != NULL);
  5116. /*
  5117. * locality group prealloc space are per cpu. The reason for having
  5118. * per cpu locality group is to reduce the contention between block
  5119. * request from multiple CPUs.
  5120. */
  5121. ac->ac_lg = raw_cpu_ptr(sbi->s_locality_groups);
  5122. /* we're going to use group allocation */
  5123. ac->ac_flags |= EXT4_MB_HINT_GROUP_ALLOC;
  5124. /* serialize all allocations in the group */
  5125. mutex_lock(&ac->ac_lg->lg_mutex);
  5126. }
  5127. static noinline_for_stack void
  5128. ext4_mb_initialize_context(struct ext4_allocation_context *ac,
  5129. struct ext4_allocation_request *ar)
  5130. {
  5131. struct super_block *sb = ar->inode->i_sb;
  5132. struct ext4_sb_info *sbi = EXT4_SB(sb);
  5133. struct ext4_super_block *es = sbi->s_es;
  5134. ext4_group_t group;
  5135. unsigned int len;
  5136. ext4_fsblk_t goal;
  5137. ext4_grpblk_t block;
  5138. /* we can't allocate > group size */
  5139. len = ar->len;
  5140. /* just a dirty hack to filter too big requests */
  5141. if (len >= EXT4_CLUSTERS_PER_GROUP(sb))
  5142. len = EXT4_CLUSTERS_PER_GROUP(sb);
  5143. /* start searching from the goal */
  5144. goal = ar->goal;
  5145. if (goal < le32_to_cpu(es->s_first_data_block) ||
  5146. goal >= ext4_blocks_count(es))
  5147. goal = le32_to_cpu(es->s_first_data_block);
  5148. ext4_get_group_no_and_offset(sb, goal, &group, &block);
  5149. /* set up allocation goals */
  5150. ac->ac_b_ex.fe_logical = EXT4_LBLK_CMASK(sbi, ar->logical);
  5151. ac->ac_status = AC_STATUS_CONTINUE;
  5152. ac->ac_sb = sb;
  5153. ac->ac_inode = ar->inode;
  5154. ac->ac_o_ex.fe_logical = ac->ac_b_ex.fe_logical;
  5155. ac->ac_o_ex.fe_group = group;
  5156. ac->ac_o_ex.fe_start = block;
  5157. ac->ac_o_ex.fe_len = len;
  5158. ac->ac_g_ex = ac->ac_o_ex;
  5159. ac->ac_orig_goal_len = ac->ac_g_ex.fe_len;
  5160. ac->ac_flags = ar->flags;
  5161. /* we have to define context: we'll work with a file or
  5162. * locality group. this is a policy, actually */
  5163. ext4_mb_group_or_file(ac);
  5164. mb_debug(sb, "init ac: %u blocks @ %u, goal %u, flags 0x%x, 2^%d, "
  5165. "left: %u/%u, right %u/%u to %swritable\n",
  5166. (unsigned) ar->len, (unsigned) ar->logical,
  5167. (unsigned) ar->goal, ac->ac_flags, ac->ac_2order,
  5168. (unsigned) ar->lleft, (unsigned) ar->pleft,
  5169. (unsigned) ar->lright, (unsigned) ar->pright,
  5170. inode_is_open_for_write(ar->inode) ? "" : "non-");
  5171. }
  5172. static noinline_for_stack void
  5173. ext4_mb_discard_lg_preallocations(struct super_block *sb,
  5174. struct ext4_locality_group *lg,
  5175. int order, int total_entries)
  5176. {
  5177. ext4_group_t group = 0;
  5178. struct ext4_buddy e4b;
  5179. LIST_HEAD(discard_list);
  5180. struct ext4_prealloc_space *pa, *tmp;
  5181. mb_debug(sb, "discard locality group preallocation\n");
  5182. spin_lock(&lg->lg_prealloc_lock);
  5183. list_for_each_entry_rcu(pa, &lg->lg_prealloc_list[order],
  5184. pa_node.lg_list,
  5185. lockdep_is_held(&lg->lg_prealloc_lock)) {
  5186. spin_lock(&pa->pa_lock);
  5187. if (atomic_read(&pa->pa_count)) {
  5188. /*
  5189. * This is the pa that we just used
  5190. * for block allocation. So don't
  5191. * free that
  5192. */
  5193. spin_unlock(&pa->pa_lock);
  5194. continue;
  5195. }
  5196. if (pa->pa_deleted) {
  5197. spin_unlock(&pa->pa_lock);
  5198. continue;
  5199. }
  5200. /* only lg prealloc space */
  5201. BUG_ON(pa->pa_type != MB_GROUP_PA);
  5202. /* seems this one can be freed ... */
  5203. ext4_mb_mark_pa_deleted(sb, pa);
  5204. spin_unlock(&pa->pa_lock);
  5205. list_del_rcu(&pa->pa_node.lg_list);
  5206. list_add(&pa->u.pa_tmp_list, &discard_list);
  5207. total_entries--;
  5208. if (total_entries <= 5) {
  5209. /*
  5210. * we want to keep only 5 entries
  5211. * allowing it to grow to 8. This
  5212. * mak sure we don't call discard
  5213. * soon for this list.
  5214. */
  5215. break;
  5216. }
  5217. }
  5218. spin_unlock(&lg->lg_prealloc_lock);
  5219. list_for_each_entry_safe(pa, tmp, &discard_list, u.pa_tmp_list) {
  5220. int err;
  5221. group = ext4_get_group_number(sb, pa->pa_pstart);
  5222. err = ext4_mb_load_buddy_gfp(sb, group, &e4b,
  5223. GFP_NOFS|__GFP_NOFAIL);
  5224. if (err) {
  5225. ext4_error_err(sb, -err, "Error %d loading buddy information for %u",
  5226. err, group);
  5227. continue;
  5228. }
  5229. ext4_lock_group(sb, group);
  5230. list_del(&pa->pa_group_list);
  5231. ext4_mb_release_group_pa(&e4b, pa);
  5232. ext4_unlock_group(sb, group);
  5233. ext4_mb_unload_buddy(&e4b);
  5234. list_del(&pa->u.pa_tmp_list);
  5235. call_rcu(&(pa)->u.pa_rcu, ext4_mb_pa_callback);
  5236. }
  5237. }
  5238. /*
  5239. * We have incremented pa_count. So it cannot be freed at this
  5240. * point. Also we hold lg_mutex. So no parallel allocation is
  5241. * possible from this lg. That means pa_free cannot be updated.
  5242. *
  5243. * A parallel ext4_mb_discard_group_preallocations is possible.
  5244. * which can cause the lg_prealloc_list to be updated.
  5245. */
  5246. static void ext4_mb_add_n_trim(struct ext4_allocation_context *ac)
  5247. {
  5248. int order, added = 0, lg_prealloc_count = 1;
  5249. struct super_block *sb = ac->ac_sb;
  5250. struct ext4_locality_group *lg = ac->ac_lg;
  5251. struct ext4_prealloc_space *tmp_pa, *pa = ac->ac_pa;
  5252. order = fls(pa->pa_free) - 1;
  5253. if (order > PREALLOC_TB_SIZE - 1)
  5254. /* The max size of hash table is PREALLOC_TB_SIZE */
  5255. order = PREALLOC_TB_SIZE - 1;
  5256. /* Add the prealloc space to lg */
  5257. spin_lock(&lg->lg_prealloc_lock);
  5258. list_for_each_entry_rcu(tmp_pa, &lg->lg_prealloc_list[order],
  5259. pa_node.lg_list,
  5260. lockdep_is_held(&lg->lg_prealloc_lock)) {
  5261. spin_lock(&tmp_pa->pa_lock);
  5262. if (tmp_pa->pa_deleted) {
  5263. spin_unlock(&tmp_pa->pa_lock);
  5264. continue;
  5265. }
  5266. if (!added && pa->pa_free < tmp_pa->pa_free) {
  5267. /* Add to the tail of the previous entry */
  5268. list_add_tail_rcu(&pa->pa_node.lg_list,
  5269. &tmp_pa->pa_node.lg_list);
  5270. added = 1;
  5271. /*
  5272. * we want to count the total
  5273. * number of entries in the list
  5274. */
  5275. }
  5276. spin_unlock(&tmp_pa->pa_lock);
  5277. lg_prealloc_count++;
  5278. }
  5279. if (!added)
  5280. list_add_tail_rcu(&pa->pa_node.lg_list,
  5281. &lg->lg_prealloc_list[order]);
  5282. spin_unlock(&lg->lg_prealloc_lock);
  5283. /* Now trim the list to be not more than 8 elements */
  5284. if (lg_prealloc_count > 8)
  5285. ext4_mb_discard_lg_preallocations(sb, lg,
  5286. order, lg_prealloc_count);
  5287. }
  5288. /*
  5289. * release all resource we used in allocation
  5290. */
  5291. static void ext4_mb_release_context(struct ext4_allocation_context *ac)
  5292. {
  5293. struct ext4_sb_info *sbi = EXT4_SB(ac->ac_sb);
  5294. struct ext4_prealloc_space *pa = ac->ac_pa;
  5295. if (pa) {
  5296. if (pa->pa_type == MB_GROUP_PA) {
  5297. /* see comment in ext4_mb_use_group_pa() */
  5298. spin_lock(&pa->pa_lock);
  5299. pa->pa_pstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
  5300. pa->pa_lstart += EXT4_C2B(sbi, ac->ac_b_ex.fe_len);
  5301. pa->pa_free -= ac->ac_b_ex.fe_len;
  5302. pa->pa_len -= ac->ac_b_ex.fe_len;
  5303. spin_unlock(&pa->pa_lock);
  5304. /*
  5305. * We want to add the pa to the right bucket.
  5306. * Remove it from the list and while adding
  5307. * make sure the list to which we are adding
  5308. * doesn't grow big.
  5309. */
  5310. if (likely(pa->pa_free)) {
  5311. spin_lock(pa->pa_node_lock.lg_lock);
  5312. list_del_rcu(&pa->pa_node.lg_list);
  5313. spin_unlock(pa->pa_node_lock.lg_lock);
  5314. ext4_mb_add_n_trim(ac);
  5315. }
  5316. }
  5317. ext4_mb_put_pa(ac, ac->ac_sb, pa);
  5318. }
  5319. if (ac->ac_bitmap_folio)
  5320. folio_put(ac->ac_bitmap_folio);
  5321. if (ac->ac_buddy_folio)
  5322. folio_put(ac->ac_buddy_folio);
  5323. if (ac->ac_flags & EXT4_MB_HINT_GROUP_ALLOC)
  5324. mutex_unlock(&ac->ac_lg->lg_mutex);
  5325. ext4_mb_collect_stats(ac);
  5326. }
  5327. static int ext4_mb_discard_preallocations(struct super_block *sb, int needed)
  5328. {
  5329. ext4_group_t i, ngroups = ext4_get_groups_count(sb);
  5330. int ret;
  5331. int freed = 0, busy = 0;
  5332. int retry = 0;
  5333. trace_ext4_mb_discard_preallocations(sb, needed);
  5334. if (needed == 0)
  5335. needed = EXT4_CLUSTERS_PER_GROUP(sb) + 1;
  5336. repeat:
  5337. for (i = 0; i < ngroups && needed > 0; i++) {
  5338. ret = ext4_mb_discard_group_preallocations(sb, i, &busy);
  5339. freed += ret;
  5340. needed -= ret;
  5341. cond_resched();
  5342. }
  5343. if (needed > 0 && busy && ++retry < 3) {
  5344. busy = 0;
  5345. goto repeat;
  5346. }
  5347. return freed;
  5348. }
  5349. static bool ext4_mb_discard_preallocations_should_retry(struct super_block *sb,
  5350. struct ext4_allocation_context *ac, u64 *seq)
  5351. {
  5352. int freed;
  5353. u64 seq_retry = 0;
  5354. bool ret = false;
  5355. freed = ext4_mb_discard_preallocations(sb, ac->ac_o_ex.fe_len);
  5356. if (freed) {
  5357. ret = true;
  5358. goto out_dbg;
  5359. }
  5360. seq_retry = ext4_get_discard_pa_seq_sum();
  5361. if (!(ac->ac_flags & EXT4_MB_STRICT_CHECK) || seq_retry != *seq) {
  5362. ac->ac_flags |= EXT4_MB_STRICT_CHECK;
  5363. *seq = seq_retry;
  5364. ret = true;
  5365. }
  5366. out_dbg:
  5367. mb_debug(sb, "freed %d, retry ? %s\n", freed, ret ? "yes" : "no");
  5368. return ret;
  5369. }
  5370. /*
  5371. * Simple allocator for Ext4 fast commit replay path. It searches for blocks
  5372. * linearly starting at the goal block and also excludes the blocks which
  5373. * are going to be in use after fast commit replay.
  5374. */
  5375. static ext4_fsblk_t
  5376. ext4_mb_new_blocks_simple(struct ext4_allocation_request *ar, int *errp)
  5377. {
  5378. struct buffer_head *bitmap_bh;
  5379. struct super_block *sb = ar->inode->i_sb;
  5380. struct ext4_sb_info *sbi = EXT4_SB(sb);
  5381. ext4_group_t group, nr;
  5382. ext4_grpblk_t blkoff;
  5383. ext4_grpblk_t max = EXT4_CLUSTERS_PER_GROUP(sb);
  5384. ext4_grpblk_t i = 0;
  5385. ext4_fsblk_t goal, block;
  5386. struct ext4_super_block *es = sbi->s_es;
  5387. goal = ar->goal;
  5388. if (goal < le32_to_cpu(es->s_first_data_block) ||
  5389. goal >= ext4_blocks_count(es))
  5390. goal = le32_to_cpu(es->s_first_data_block);
  5391. ar->len = 0;
  5392. ext4_get_group_no_and_offset(sb, goal, &group, &blkoff);
  5393. for (nr = ext4_get_groups_count(sb); nr > 0; nr--) {
  5394. bitmap_bh = ext4_read_block_bitmap(sb, group);
  5395. if (IS_ERR(bitmap_bh)) {
  5396. *errp = PTR_ERR(bitmap_bh);
  5397. pr_warn("Failed to read block bitmap\n");
  5398. return 0;
  5399. }
  5400. while (1) {
  5401. i = mb_find_next_zero_bit(bitmap_bh->b_data, max,
  5402. blkoff);
  5403. if (i >= max)
  5404. break;
  5405. if (ext4_fc_replay_check_excluded(sb,
  5406. ext4_group_first_block_no(sb, group) +
  5407. EXT4_C2B(sbi, i))) {
  5408. blkoff = i + 1;
  5409. } else
  5410. break;
  5411. }
  5412. brelse(bitmap_bh);
  5413. if (i < max)
  5414. break;
  5415. if (++group >= ext4_get_groups_count(sb))
  5416. group = 0;
  5417. blkoff = 0;
  5418. }
  5419. if (i >= max) {
  5420. *errp = -ENOSPC;
  5421. return 0;
  5422. }
  5423. block = ext4_group_first_block_no(sb, group) + EXT4_C2B(sbi, i);
  5424. ext4_mb_mark_bb(sb, block, 1, true);
  5425. ar->len = 1;
  5426. *errp = 0;
  5427. return block;
  5428. }
  5429. /*
  5430. * Main entry point into mballoc to allocate blocks
  5431. * it tries to use preallocation first, then falls back
  5432. * to usual allocation
  5433. */
  5434. ext4_fsblk_t ext4_mb_new_blocks(handle_t *handle,
  5435. struct ext4_allocation_request *ar, int *errp)
  5436. {
  5437. struct ext4_allocation_context *ac = NULL;
  5438. struct ext4_sb_info *sbi;
  5439. struct super_block *sb;
  5440. ext4_fsblk_t block = 0;
  5441. unsigned int inquota = 0;
  5442. unsigned int reserv_clstrs = 0;
  5443. int retries = 0;
  5444. u64 seq;
  5445. might_sleep();
  5446. sb = ar->inode->i_sb;
  5447. sbi = EXT4_SB(sb);
  5448. trace_ext4_request_blocks(ar);
  5449. if (sbi->s_mount_state & EXT4_FC_REPLAY)
  5450. return ext4_mb_new_blocks_simple(ar, errp);
  5451. /* Allow to use superuser reservation for quota file */
  5452. if (ext4_is_quota_file(ar->inode))
  5453. ar->flags |= EXT4_MB_USE_ROOT_BLOCKS;
  5454. if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0) {
  5455. /* Without delayed allocation we need to verify
  5456. * there is enough free blocks to do block allocation
  5457. * and verify allocation doesn't exceed the quota limits.
  5458. */
  5459. while (ar->len &&
  5460. ext4_claim_free_clusters(sbi, ar->len, ar->flags)) {
  5461. /* let others to free the space */
  5462. cond_resched();
  5463. ar->len = ar->len >> 1;
  5464. }
  5465. if (!ar->len) {
  5466. ext4_mb_show_pa(sb);
  5467. *errp = -ENOSPC;
  5468. return 0;
  5469. }
  5470. reserv_clstrs = ar->len;
  5471. if (ar->flags & EXT4_MB_USE_ROOT_BLOCKS) {
  5472. dquot_alloc_block_nofail(ar->inode,
  5473. EXT4_C2B(sbi, ar->len));
  5474. } else {
  5475. while (ar->len &&
  5476. dquot_alloc_block(ar->inode,
  5477. EXT4_C2B(sbi, ar->len))) {
  5478. ar->flags |= EXT4_MB_HINT_NOPREALLOC;
  5479. ar->len--;
  5480. }
  5481. }
  5482. inquota = ar->len;
  5483. if (ar->len == 0) {
  5484. *errp = -EDQUOT;
  5485. goto out;
  5486. }
  5487. }
  5488. ac = kmem_cache_zalloc(ext4_ac_cachep, GFP_NOFS);
  5489. if (!ac) {
  5490. ar->len = 0;
  5491. *errp = -ENOMEM;
  5492. goto out;
  5493. }
  5494. ext4_mb_initialize_context(ac, ar);
  5495. ac->ac_op = EXT4_MB_HISTORY_PREALLOC;
  5496. seq = this_cpu_read(discard_pa_seq);
  5497. if (!ext4_mb_use_preallocated(ac)) {
  5498. ac->ac_op = EXT4_MB_HISTORY_ALLOC;
  5499. ext4_mb_normalize_request(ac, ar);
  5500. *errp = ext4_mb_pa_alloc(ac);
  5501. if (*errp)
  5502. goto errout;
  5503. repeat:
  5504. /* allocate space in core */
  5505. *errp = ext4_mb_regular_allocator(ac);
  5506. /*
  5507. * pa allocated above is added to grp->bb_prealloc_list only
  5508. * when we were able to allocate some block i.e. when
  5509. * ac->ac_status == AC_STATUS_FOUND.
  5510. * And error from above mean ac->ac_status != AC_STATUS_FOUND
  5511. * So we have to free this pa here itself.
  5512. */
  5513. if (*errp) {
  5514. ext4_mb_pa_put_free(ac);
  5515. ext4_discard_allocated_blocks(ac);
  5516. goto errout;
  5517. }
  5518. if (ac->ac_status == AC_STATUS_FOUND &&
  5519. ac->ac_o_ex.fe_len >= ac->ac_f_ex.fe_len)
  5520. ext4_mb_pa_put_free(ac);
  5521. }
  5522. if (likely(ac->ac_status == AC_STATUS_FOUND)) {
  5523. *errp = ext4_mb_mark_diskspace_used(ac, handle, reserv_clstrs);
  5524. if (*errp) {
  5525. ext4_discard_allocated_blocks(ac);
  5526. goto errout;
  5527. } else {
  5528. block = ext4_grp_offs_to_block(sb, &ac->ac_b_ex);
  5529. ar->len = ac->ac_b_ex.fe_len;
  5530. }
  5531. } else {
  5532. if (++retries < 3 &&
  5533. ext4_mb_discard_preallocations_should_retry(sb, ac, &seq))
  5534. goto repeat;
  5535. /*
  5536. * If block allocation fails then the pa allocated above
  5537. * needs to be freed here itself.
  5538. */
  5539. ext4_mb_pa_put_free(ac);
  5540. *errp = -ENOSPC;
  5541. }
  5542. if (*errp) {
  5543. errout:
  5544. ac->ac_b_ex.fe_len = 0;
  5545. ar->len = 0;
  5546. ext4_mb_show_ac(ac);
  5547. }
  5548. ext4_mb_release_context(ac);
  5549. kmem_cache_free(ext4_ac_cachep, ac);
  5550. out:
  5551. if (inquota && ar->len < inquota)
  5552. dquot_free_block(ar->inode, EXT4_C2B(sbi, inquota - ar->len));
  5553. if (!ar->len) {
  5554. if ((ar->flags & EXT4_MB_DELALLOC_RESERVED) == 0)
  5555. /* release all the reserved blocks if non delalloc */
  5556. percpu_counter_sub(&sbi->s_dirtyclusters_counter,
  5557. reserv_clstrs);
  5558. }
  5559. trace_ext4_allocate_blocks(ar, (unsigned long long)block);
  5560. return block;
  5561. }
  5562. /*
  5563. * We can merge two free data extents only if the physical blocks
  5564. * are contiguous, AND the extents were freed by the same transaction,
  5565. * AND the blocks are associated with the same group.
  5566. */
  5567. static void ext4_try_merge_freed_extent(struct ext4_sb_info *sbi,
  5568. struct ext4_free_data *entry,
  5569. struct ext4_free_data *new_entry,
  5570. struct rb_root *entry_rb_root)
  5571. {
  5572. if ((entry->efd_tid != new_entry->efd_tid) ||
  5573. (entry->efd_group != new_entry->efd_group))
  5574. return;
  5575. if (entry->efd_start_cluster + entry->efd_count ==
  5576. new_entry->efd_start_cluster) {
  5577. new_entry->efd_start_cluster = entry->efd_start_cluster;
  5578. new_entry->efd_count += entry->efd_count;
  5579. } else if (new_entry->efd_start_cluster + new_entry->efd_count ==
  5580. entry->efd_start_cluster) {
  5581. new_entry->efd_count += entry->efd_count;
  5582. } else
  5583. return;
  5584. spin_lock(&sbi->s_md_lock);
  5585. list_del(&entry->efd_list);
  5586. spin_unlock(&sbi->s_md_lock);
  5587. rb_erase(&entry->efd_node, entry_rb_root);
  5588. kmem_cache_free(ext4_free_data_cachep, entry);
  5589. }
  5590. static noinline_for_stack void
  5591. ext4_mb_free_metadata(handle_t *handle, struct ext4_buddy *e4b,
  5592. struct ext4_free_data *new_entry)
  5593. {
  5594. ext4_group_t group = e4b->bd_group;
  5595. ext4_grpblk_t cluster;
  5596. ext4_grpblk_t clusters = new_entry->efd_count;
  5597. struct ext4_free_data *entry;
  5598. struct ext4_group_info *db = e4b->bd_info;
  5599. struct super_block *sb = e4b->bd_sb;
  5600. struct ext4_sb_info *sbi = EXT4_SB(sb);
  5601. struct rb_node **n = &db->bb_free_root.rb_node, *node;
  5602. struct rb_node *parent = NULL, *new_node;
  5603. BUG_ON(!ext4_handle_valid(handle));
  5604. BUG_ON(e4b->bd_bitmap_folio == NULL);
  5605. BUG_ON(e4b->bd_buddy_folio == NULL);
  5606. new_node = &new_entry->efd_node;
  5607. cluster = new_entry->efd_start_cluster;
  5608. if (!*n) {
  5609. /* first free block exent. We need to
  5610. protect buddy cache from being freed,
  5611. * otherwise we'll refresh it from
  5612. * on-disk bitmap and lose not-yet-available
  5613. * blocks */
  5614. folio_get(e4b->bd_buddy_folio);
  5615. folio_get(e4b->bd_bitmap_folio);
  5616. }
  5617. while (*n) {
  5618. parent = *n;
  5619. entry = rb_entry(parent, struct ext4_free_data, efd_node);
  5620. if (cluster < entry->efd_start_cluster)
  5621. n = &(*n)->rb_left;
  5622. else if (cluster >= (entry->efd_start_cluster + entry->efd_count))
  5623. n = &(*n)->rb_right;
  5624. else {
  5625. ext4_grp_locked_error(sb, group, 0,
  5626. ext4_group_first_block_no(sb, group) +
  5627. EXT4_C2B(sbi, cluster),
  5628. "Block already on to-be-freed list");
  5629. kmem_cache_free(ext4_free_data_cachep, new_entry);
  5630. return;
  5631. }
  5632. }
  5633. rb_link_node(new_node, parent, n);
  5634. rb_insert_color(new_node, &db->bb_free_root);
  5635. /* Now try to see the extent can be merged to left and right */
  5636. node = rb_prev(new_node);
  5637. if (node) {
  5638. entry = rb_entry(node, struct ext4_free_data, efd_node);
  5639. ext4_try_merge_freed_extent(sbi, entry, new_entry,
  5640. &(db->bb_free_root));
  5641. }
  5642. node = rb_next(new_node);
  5643. if (node) {
  5644. entry = rb_entry(node, struct ext4_free_data, efd_node);
  5645. ext4_try_merge_freed_extent(sbi, entry, new_entry,
  5646. &(db->bb_free_root));
  5647. }
  5648. spin_lock(&sbi->s_md_lock);
  5649. list_add_tail(&new_entry->efd_list, &sbi->s_freed_data_list[new_entry->efd_tid & 1]);
  5650. sbi->s_mb_free_pending += clusters;
  5651. spin_unlock(&sbi->s_md_lock);
  5652. }
  5653. static void ext4_free_blocks_simple(struct inode *inode, ext4_fsblk_t block,
  5654. unsigned long count)
  5655. {
  5656. struct super_block *sb = inode->i_sb;
  5657. ext4_group_t group;
  5658. ext4_grpblk_t blkoff;
  5659. ext4_get_group_no_and_offset(sb, block, &group, &blkoff);
  5660. ext4_mb_mark_context(NULL, sb, false, group, blkoff, count,
  5661. EXT4_MB_BITMAP_MARKED_CHECK |
  5662. EXT4_MB_SYNC_UPDATE,
  5663. NULL);
  5664. }
  5665. /**
  5666. * ext4_mb_clear_bb() -- helper function for freeing blocks.
  5667. * Used by ext4_free_blocks()
  5668. * @handle: handle for this transaction
  5669. * @inode: inode
  5670. * @block: starting physical block to be freed
  5671. * @count: number of blocks to be freed
  5672. * @flags: flags used by ext4_free_blocks
  5673. */
  5674. static void ext4_mb_clear_bb(handle_t *handle, struct inode *inode,
  5675. ext4_fsblk_t block, unsigned long count,
  5676. int flags)
  5677. {
  5678. struct super_block *sb = inode->i_sb;
  5679. struct ext4_group_info *grp;
  5680. unsigned int overflow;
  5681. ext4_grpblk_t bit;
  5682. ext4_group_t block_group;
  5683. struct ext4_sb_info *sbi;
  5684. struct ext4_buddy e4b;
  5685. unsigned int count_clusters;
  5686. int err = 0;
  5687. int mark_flags = 0;
  5688. ext4_grpblk_t changed;
  5689. sbi = EXT4_SB(sb);
  5690. if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
  5691. !ext4_inode_block_valid(inode, block, count)) {
  5692. ext4_error(sb, "Freeing blocks in system zone - "
  5693. "Block = %llu, count = %lu", block, count);
  5694. /* err = 0. ext4_std_error should be a no op */
  5695. goto error_out;
  5696. }
  5697. flags |= EXT4_FREE_BLOCKS_VALIDATED;
  5698. do_more:
  5699. overflow = 0;
  5700. ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
  5701. grp = ext4_get_group_info(sb, block_group);
  5702. if (unlikely(!grp || EXT4_MB_GRP_BBITMAP_CORRUPT(grp)))
  5703. return;
  5704. /*
  5705. * Check to see if we are freeing blocks across a group
  5706. * boundary.
  5707. */
  5708. if (EXT4_C2B(sbi, bit) + count > EXT4_BLOCKS_PER_GROUP(sb)) {
  5709. overflow = EXT4_C2B(sbi, bit) + count -
  5710. EXT4_BLOCKS_PER_GROUP(sb);
  5711. count -= overflow;
  5712. /* The range changed so it's no longer validated */
  5713. flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
  5714. }
  5715. count_clusters = EXT4_NUM_B2C(sbi, count);
  5716. trace_ext4_mballoc_free(sb, inode, block_group, bit, count_clusters);
  5717. /* __GFP_NOFAIL: retry infinitely, ignore TIF_MEMDIE and memcg limit. */
  5718. err = ext4_mb_load_buddy_gfp(sb, block_group, &e4b,
  5719. GFP_NOFS|__GFP_NOFAIL);
  5720. if (err)
  5721. goto error_out;
  5722. if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
  5723. !ext4_inode_block_valid(inode, block, count)) {
  5724. ext4_error(sb, "Freeing blocks in system zone - "
  5725. "Block = %llu, count = %lu", block, count);
  5726. /* err = 0. ext4_std_error should be a no op */
  5727. goto error_clean;
  5728. }
  5729. #ifdef AGGRESSIVE_CHECK
  5730. mark_flags |= EXT4_MB_BITMAP_MARKED_CHECK;
  5731. #endif
  5732. err = ext4_mb_mark_context(handle, sb, false, block_group, bit,
  5733. count_clusters, mark_flags, &changed);
  5734. if (err && changed == 0)
  5735. goto error_clean;
  5736. #ifdef AGGRESSIVE_CHECK
  5737. BUG_ON(changed != count_clusters);
  5738. #endif
  5739. /*
  5740. * We need to make sure we don't reuse the freed block until after the
  5741. * transaction is committed. We make an exception if the inode is to be
  5742. * written in writeback mode since writeback mode has weak data
  5743. * consistency guarantees.
  5744. */
  5745. if (ext4_handle_valid(handle) &&
  5746. ((flags & EXT4_FREE_BLOCKS_METADATA) ||
  5747. !ext4_should_writeback_data(inode))) {
  5748. struct ext4_free_data *new_entry;
  5749. /*
  5750. * We use __GFP_NOFAIL because ext4_free_blocks() is not allowed
  5751. * to fail.
  5752. */
  5753. new_entry = kmem_cache_alloc(ext4_free_data_cachep,
  5754. GFP_NOFS|__GFP_NOFAIL);
  5755. new_entry->efd_start_cluster = bit;
  5756. new_entry->efd_group = block_group;
  5757. new_entry->efd_count = count_clusters;
  5758. new_entry->efd_tid = handle->h_transaction->t_tid;
  5759. ext4_lock_group(sb, block_group);
  5760. ext4_mb_free_metadata(handle, &e4b, new_entry);
  5761. } else {
  5762. if (test_opt(sb, DISCARD)) {
  5763. err = ext4_issue_discard(sb, block_group, bit,
  5764. count_clusters);
  5765. /*
  5766. * Ignore EOPNOTSUPP error. This is consistent with
  5767. * what happens when using journal.
  5768. */
  5769. if (err == -EOPNOTSUPP)
  5770. err = 0;
  5771. if (err)
  5772. ext4_msg(sb, KERN_WARNING, "discard request in"
  5773. " group:%u block:%d count:%lu failed"
  5774. " with %d", block_group, bit, count,
  5775. err);
  5776. }
  5777. EXT4_MB_GRP_CLEAR_TRIMMED(e4b.bd_info);
  5778. ext4_lock_group(sb, block_group);
  5779. mb_free_blocks(inode, &e4b, bit, count_clusters);
  5780. }
  5781. ext4_unlock_group(sb, block_group);
  5782. /*
  5783. * on a bigalloc file system, defer the s_freeclusters_counter
  5784. * update to the caller (ext4_remove_space and friends) so they
  5785. * can determine if a cluster freed here should be rereserved
  5786. */
  5787. if (!(flags & EXT4_FREE_BLOCKS_RERESERVE_CLUSTER)) {
  5788. if (!(flags & EXT4_FREE_BLOCKS_NO_QUOT_UPDATE))
  5789. dquot_free_block(inode, EXT4_C2B(sbi, count_clusters));
  5790. percpu_counter_add(&sbi->s_freeclusters_counter,
  5791. count_clusters);
  5792. }
  5793. if (overflow && !err) {
  5794. block += count;
  5795. count = overflow;
  5796. ext4_mb_unload_buddy(&e4b);
  5797. /* The range changed so it's no longer validated */
  5798. flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
  5799. goto do_more;
  5800. }
  5801. error_clean:
  5802. ext4_mb_unload_buddy(&e4b);
  5803. error_out:
  5804. ext4_std_error(sb, err);
  5805. }
  5806. /**
  5807. * ext4_free_blocks() -- Free given blocks and update quota
  5808. * @handle: handle for this transaction
  5809. * @inode: inode
  5810. * @bh: optional buffer of the block to be freed
  5811. * @block: starting physical block to be freed
  5812. * @count: number of blocks to be freed
  5813. * @flags: flags used by ext4_free_blocks
  5814. */
  5815. void ext4_free_blocks(handle_t *handle, struct inode *inode,
  5816. struct buffer_head *bh, ext4_fsblk_t block,
  5817. unsigned long count, int flags)
  5818. {
  5819. struct super_block *sb = inode->i_sb;
  5820. unsigned int overflow;
  5821. struct ext4_sb_info *sbi;
  5822. sbi = EXT4_SB(sb);
  5823. if (bh) {
  5824. if (block)
  5825. BUG_ON(block != bh->b_blocknr);
  5826. else
  5827. block = bh->b_blocknr;
  5828. }
  5829. if (sbi->s_mount_state & EXT4_FC_REPLAY) {
  5830. ext4_free_blocks_simple(inode, block, EXT4_NUM_B2C(sbi, count));
  5831. return;
  5832. }
  5833. might_sleep();
  5834. if (!(flags & EXT4_FREE_BLOCKS_VALIDATED) &&
  5835. !ext4_inode_block_valid(inode, block, count)) {
  5836. ext4_error(sb, "Freeing blocks not in datazone - "
  5837. "block = %llu, count = %lu", block, count);
  5838. return;
  5839. }
  5840. flags |= EXT4_FREE_BLOCKS_VALIDATED;
  5841. ext4_debug("freeing block %llu\n", block);
  5842. trace_ext4_free_blocks(inode, block, count, flags);
  5843. if (bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
  5844. BUG_ON(count > 1);
  5845. ext4_forget(handle, flags & EXT4_FREE_BLOCKS_METADATA,
  5846. inode, bh, block);
  5847. }
  5848. /*
  5849. * If the extent to be freed does not begin on a cluster
  5850. * boundary, we need to deal with partial clusters at the
  5851. * beginning and end of the extent. Normally we will free
  5852. * blocks at the beginning or the end unless we are explicitly
  5853. * requested to avoid doing so.
  5854. */
  5855. overflow = EXT4_PBLK_COFF(sbi, block);
  5856. if (overflow) {
  5857. if (flags & EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER) {
  5858. overflow = sbi->s_cluster_ratio - overflow;
  5859. block += overflow;
  5860. if (count > overflow)
  5861. count -= overflow;
  5862. else
  5863. return;
  5864. } else {
  5865. block -= overflow;
  5866. count += overflow;
  5867. }
  5868. /* The range changed so it's no longer validated */
  5869. flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
  5870. }
  5871. overflow = EXT4_LBLK_COFF(sbi, count);
  5872. if (overflow) {
  5873. if (flags & EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER) {
  5874. if (count > overflow)
  5875. count -= overflow;
  5876. else
  5877. return;
  5878. } else
  5879. count += sbi->s_cluster_ratio - overflow;
  5880. /* The range changed so it's no longer validated */
  5881. flags &= ~EXT4_FREE_BLOCKS_VALIDATED;
  5882. }
  5883. if (!bh && (flags & EXT4_FREE_BLOCKS_FORGET)) {
  5884. int i;
  5885. int is_metadata = flags & EXT4_FREE_BLOCKS_METADATA;
  5886. for (i = 0; i < count; i++) {
  5887. cond_resched();
  5888. if (is_metadata)
  5889. bh = sb_find_get_block_nonatomic(inode->i_sb,
  5890. block + i);
  5891. ext4_forget(handle, is_metadata, inode, bh, block + i);
  5892. }
  5893. }
  5894. ext4_mb_clear_bb(handle, inode, block, count, flags);
  5895. }
  5896. /**
  5897. * ext4_group_add_blocks() -- Add given blocks to an existing group
  5898. * @handle: handle to this transaction
  5899. * @sb: super block
  5900. * @block: start physical block to add to the block group
  5901. * @count: number of blocks to free
  5902. *
  5903. * This marks the blocks as free in the bitmap and buddy.
  5904. */
  5905. int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
  5906. ext4_fsblk_t block, unsigned long count)
  5907. {
  5908. ext4_group_t block_group;
  5909. ext4_grpblk_t bit;
  5910. struct ext4_sb_info *sbi = EXT4_SB(sb);
  5911. struct ext4_buddy e4b;
  5912. int err = 0;
  5913. ext4_fsblk_t first_cluster = EXT4_B2C(sbi, block);
  5914. ext4_fsblk_t last_cluster = EXT4_B2C(sbi, block + count - 1);
  5915. unsigned long cluster_count = last_cluster - first_cluster + 1;
  5916. ext4_grpblk_t changed;
  5917. ext4_debug("Adding block(s) %llu-%llu\n", block, block + count - 1);
  5918. if (cluster_count == 0)
  5919. return 0;
  5920. ext4_get_group_no_and_offset(sb, block, &block_group, &bit);
  5921. /*
  5922. * Check to see if we are freeing blocks across a group
  5923. * boundary.
  5924. */
  5925. if (bit + cluster_count > EXT4_CLUSTERS_PER_GROUP(sb)) {
  5926. ext4_warning(sb, "too many blocks added to group %u",
  5927. block_group);
  5928. err = -EINVAL;
  5929. goto error_out;
  5930. }
  5931. err = ext4_mb_load_buddy(sb, block_group, &e4b);
  5932. if (err)
  5933. goto error_out;
  5934. if (!ext4_sb_block_valid(sb, NULL, block, count)) {
  5935. ext4_error(sb, "Adding blocks in system zones - "
  5936. "Block = %llu, count = %lu",
  5937. block, count);
  5938. err = -EINVAL;
  5939. goto error_clean;
  5940. }
  5941. err = ext4_mb_mark_context(handle, sb, false, block_group, bit,
  5942. cluster_count, EXT4_MB_BITMAP_MARKED_CHECK,
  5943. &changed);
  5944. if (err && changed == 0)
  5945. goto error_clean;
  5946. if (changed != cluster_count)
  5947. ext4_error(sb, "bit already cleared in group %u", block_group);
  5948. ext4_lock_group(sb, block_group);
  5949. mb_free_blocks(NULL, &e4b, bit, cluster_count);
  5950. ext4_unlock_group(sb, block_group);
  5951. percpu_counter_add(&sbi->s_freeclusters_counter,
  5952. changed);
  5953. error_clean:
  5954. ext4_mb_unload_buddy(&e4b);
  5955. error_out:
  5956. ext4_std_error(sb, err);
  5957. return err;
  5958. }
  5959. /**
  5960. * ext4_trim_extent -- function to TRIM one single free extent in the group
  5961. * @sb: super block for the file system
  5962. * @start: starting block of the free extent in the alloc. group
  5963. * @count: number of blocks to TRIM
  5964. * @e4b: ext4 buddy for the group
  5965. *
  5966. * Trim "count" blocks starting at "start" in the "group". To assure that no
  5967. * one will allocate those blocks, mark it as used in buddy bitmap. This must
  5968. * be called with under the group lock.
  5969. */
  5970. static int ext4_trim_extent(struct super_block *sb,
  5971. int start, int count, struct ext4_buddy *e4b)
  5972. __releases(bitlock)
  5973. __acquires(bitlock)
  5974. {
  5975. struct ext4_free_extent ex;
  5976. ext4_group_t group = e4b->bd_group;
  5977. int ret = 0;
  5978. trace_ext4_trim_extent(sb, group, start, count);
  5979. assert_spin_locked(ext4_group_lock_ptr(sb, group));
  5980. ex.fe_start = start;
  5981. ex.fe_group = group;
  5982. ex.fe_len = count;
  5983. /*
  5984. * Mark blocks used, so no one can reuse them while
  5985. * being trimmed.
  5986. */
  5987. mb_mark_used(e4b, &ex);
  5988. ext4_unlock_group(sb, group);
  5989. ret = ext4_issue_discard(sb, group, start, count);
  5990. ext4_lock_group(sb, group);
  5991. mb_free_blocks(NULL, e4b, start, ex.fe_len);
  5992. return ret;
  5993. }
  5994. static ext4_grpblk_t ext4_last_grp_cluster(struct super_block *sb,
  5995. ext4_group_t grp)
  5996. {
  5997. unsigned long nr_clusters_in_group;
  5998. if (grp < (ext4_get_groups_count(sb) - 1))
  5999. nr_clusters_in_group = EXT4_CLUSTERS_PER_GROUP(sb);
  6000. else
  6001. nr_clusters_in_group = (ext4_blocks_count(EXT4_SB(sb)->s_es) -
  6002. ext4_group_first_block_no(sb, grp))
  6003. >> EXT4_CLUSTER_BITS(sb);
  6004. return nr_clusters_in_group - 1;
  6005. }
  6006. static bool ext4_trim_interrupted(void)
  6007. {
  6008. return fatal_signal_pending(current) || freezing(current);
  6009. }
  6010. static int ext4_try_to_trim_range(struct super_block *sb,
  6011. struct ext4_buddy *e4b, ext4_grpblk_t start,
  6012. ext4_grpblk_t max, ext4_grpblk_t minblocks)
  6013. __acquires(ext4_group_lock_ptr(sb, e4b->bd_group))
  6014. __releases(ext4_group_lock_ptr(sb, e4b->bd_group))
  6015. {
  6016. ext4_grpblk_t next, count, free_count, last, origin_start;
  6017. bool set_trimmed = false;
  6018. void *bitmap;
  6019. if (unlikely(EXT4_MB_GRP_BBITMAP_CORRUPT(e4b->bd_info)))
  6020. return 0;
  6021. last = ext4_last_grp_cluster(sb, e4b->bd_group);
  6022. bitmap = e4b->bd_bitmap;
  6023. if (start == 0 && max >= last)
  6024. set_trimmed = true;
  6025. origin_start = start;
  6026. start = max(e4b->bd_info->bb_first_free, start);
  6027. count = 0;
  6028. free_count = 0;
  6029. while (start <= max) {
  6030. start = mb_find_next_zero_bit(bitmap, max + 1, start);
  6031. if (start > max)
  6032. break;
  6033. next = mb_find_next_bit(bitmap, last + 1, start);
  6034. if (origin_start == 0 && next >= last)
  6035. set_trimmed = true;
  6036. if ((next - start) >= minblocks) {
  6037. int ret = ext4_trim_extent(sb, start, next - start, e4b);
  6038. if (ret && ret != -EOPNOTSUPP)
  6039. return count;
  6040. count += next - start;
  6041. }
  6042. free_count += next - start;
  6043. start = next + 1;
  6044. if (ext4_trim_interrupted())
  6045. return count;
  6046. if (need_resched()) {
  6047. ext4_unlock_group(sb, e4b->bd_group);
  6048. cond_resched();
  6049. ext4_lock_group(sb, e4b->bd_group);
  6050. }
  6051. if ((e4b->bd_info->bb_free - free_count) < minblocks)
  6052. break;
  6053. }
  6054. if (set_trimmed)
  6055. EXT4_MB_GRP_SET_TRIMMED(e4b->bd_info);
  6056. return count;
  6057. }
  6058. /**
  6059. * ext4_trim_all_free -- function to trim all free space in alloc. group
  6060. * @sb: super block for file system
  6061. * @group: group to be trimmed
  6062. * @start: first group block to examine
  6063. * @max: last group block to examine
  6064. * @minblocks: minimum extent block count
  6065. *
  6066. * ext4_trim_all_free walks through group's block bitmap searching for free
  6067. * extents. When the free extent is found, mark it as used in group buddy
  6068. * bitmap. Then issue a TRIM command on this extent and free the extent in
  6069. * the group buddy bitmap.
  6070. */
  6071. static ext4_grpblk_t
  6072. ext4_trim_all_free(struct super_block *sb, ext4_group_t group,
  6073. ext4_grpblk_t start, ext4_grpblk_t max,
  6074. ext4_grpblk_t minblocks)
  6075. {
  6076. struct ext4_buddy e4b;
  6077. int ret;
  6078. trace_ext4_trim_all_free(sb, group, start, max);
  6079. ret = ext4_mb_load_buddy(sb, group, &e4b);
  6080. if (ret) {
  6081. ext4_warning(sb, "Error %d loading buddy information for %u",
  6082. ret, group);
  6083. return ret;
  6084. }
  6085. ext4_lock_group(sb, group);
  6086. if (!EXT4_MB_GRP_WAS_TRIMMED(e4b.bd_info) ||
  6087. minblocks < EXT4_SB(sb)->s_last_trim_minblks)
  6088. ret = ext4_try_to_trim_range(sb, &e4b, start, max, minblocks);
  6089. else
  6090. ret = 0;
  6091. ext4_unlock_group(sb, group);
  6092. ext4_mb_unload_buddy(&e4b);
  6093. ext4_debug("trimmed %d blocks in the group %d\n",
  6094. ret, group);
  6095. return ret;
  6096. }
  6097. /**
  6098. * ext4_trim_fs() -- trim ioctl handle function
  6099. * @sb: superblock for filesystem
  6100. * @range: fstrim_range structure
  6101. *
  6102. * start: First Byte to trim
  6103. * len: number of Bytes to trim from start
  6104. * minlen: minimum extent length in Bytes
  6105. * ext4_trim_fs goes through all allocation groups containing Bytes from
  6106. * start to start+len. For each such a group ext4_trim_all_free function
  6107. * is invoked to trim all free space.
  6108. */
  6109. int ext4_trim_fs(struct super_block *sb, struct fstrim_range *range)
  6110. {
  6111. unsigned int discard_granularity = bdev_discard_granularity(sb->s_bdev);
  6112. struct ext4_group_info *grp;
  6113. ext4_group_t group, first_group, last_group;
  6114. ext4_grpblk_t cnt = 0, first_cluster, last_cluster;
  6115. uint64_t start, end, minlen, trimmed = 0;
  6116. ext4_fsblk_t first_data_blk =
  6117. le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
  6118. ext4_fsblk_t max_blks = ext4_blocks_count(EXT4_SB(sb)->s_es);
  6119. int ret = 0;
  6120. start = range->start >> sb->s_blocksize_bits;
  6121. end = start + (range->len >> sb->s_blocksize_bits) - 1;
  6122. minlen = EXT4_NUM_B2C(EXT4_SB(sb),
  6123. range->minlen >> sb->s_blocksize_bits);
  6124. if (minlen > EXT4_CLUSTERS_PER_GROUP(sb) ||
  6125. start >= max_blks ||
  6126. range->len < sb->s_blocksize)
  6127. return -EINVAL;
  6128. /* No point to try to trim less than discard granularity */
  6129. if (range->minlen < discard_granularity) {
  6130. minlen = EXT4_NUM_B2C(EXT4_SB(sb),
  6131. discard_granularity >> sb->s_blocksize_bits);
  6132. if (minlen > EXT4_CLUSTERS_PER_GROUP(sb))
  6133. goto out;
  6134. }
  6135. if (end >= max_blks - 1)
  6136. end = max_blks - 1;
  6137. if (end <= first_data_blk)
  6138. goto out;
  6139. if (start < first_data_blk)
  6140. start = first_data_blk;
  6141. /* Determine first and last group to examine based on start and end */
  6142. ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) start,
  6143. &first_group, &first_cluster);
  6144. ext4_get_group_no_and_offset(sb, (ext4_fsblk_t) end,
  6145. &last_group, &last_cluster);
  6146. /* end now represents the last cluster to discard in this group */
  6147. end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
  6148. for (group = first_group; group <= last_group; group++) {
  6149. if (ext4_trim_interrupted())
  6150. break;
  6151. grp = ext4_get_group_info(sb, group);
  6152. if (!grp)
  6153. continue;
  6154. /* We only do this if the grp has never been initialized */
  6155. if (unlikely(EXT4_MB_GRP_NEED_INIT(grp))) {
  6156. ret = ext4_mb_init_group(sb, group, GFP_NOFS);
  6157. if (ret)
  6158. break;
  6159. }
  6160. /*
  6161. * For all the groups except the last one, last cluster will
  6162. * always be EXT4_CLUSTERS_PER_GROUP(sb)-1, so we only need to
  6163. * change it for the last group, note that last_cluster is
  6164. * already computed earlier by ext4_get_group_no_and_offset()
  6165. */
  6166. if (group == last_group)
  6167. end = last_cluster;
  6168. if (grp->bb_free >= minlen) {
  6169. cnt = ext4_trim_all_free(sb, group, first_cluster,
  6170. end, minlen);
  6171. if (cnt < 0) {
  6172. ret = cnt;
  6173. break;
  6174. }
  6175. trimmed += cnt;
  6176. }
  6177. /*
  6178. * For every group except the first one, we are sure
  6179. * that the first cluster to discard will be cluster #0.
  6180. */
  6181. first_cluster = 0;
  6182. }
  6183. if (!ret)
  6184. EXT4_SB(sb)->s_last_trim_minblks = minlen;
  6185. out:
  6186. range->len = EXT4_C2B(EXT4_SB(sb), trimmed) << sb->s_blocksize_bits;
  6187. return ret;
  6188. }
  6189. /* Iterate all the free extents in the group. */
  6190. int
  6191. ext4_mballoc_query_range(
  6192. struct super_block *sb,
  6193. ext4_group_t group,
  6194. ext4_grpblk_t first,
  6195. ext4_grpblk_t end,
  6196. ext4_mballoc_query_range_fn meta_formatter,
  6197. ext4_mballoc_query_range_fn formatter,
  6198. void *priv)
  6199. {
  6200. void *bitmap;
  6201. ext4_grpblk_t start, next;
  6202. struct ext4_buddy e4b;
  6203. int error;
  6204. error = ext4_mb_load_buddy(sb, group, &e4b);
  6205. if (error)
  6206. return error;
  6207. bitmap = e4b.bd_bitmap;
  6208. ext4_lock_group(sb, group);
  6209. start = max(e4b.bd_info->bb_first_free, first);
  6210. if (end >= EXT4_CLUSTERS_PER_GROUP(sb))
  6211. end = EXT4_CLUSTERS_PER_GROUP(sb) - 1;
  6212. if (meta_formatter && start != first) {
  6213. if (start > end)
  6214. start = end;
  6215. ext4_unlock_group(sb, group);
  6216. error = meta_formatter(sb, group, first, start - first,
  6217. priv);
  6218. if (error)
  6219. goto out_unload;
  6220. ext4_lock_group(sb, group);
  6221. }
  6222. while (start <= end) {
  6223. start = mb_find_next_zero_bit(bitmap, end + 1, start);
  6224. if (start > end)
  6225. break;
  6226. next = mb_find_next_bit(bitmap, end + 1, start);
  6227. ext4_unlock_group(sb, group);
  6228. error = formatter(sb, group, start, next - start, priv);
  6229. if (error)
  6230. goto out_unload;
  6231. ext4_lock_group(sb, group);
  6232. start = next + 1;
  6233. }
  6234. ext4_unlock_group(sb, group);
  6235. out_unload:
  6236. ext4_mb_unload_buddy(&e4b);
  6237. return error;
  6238. }
  6239. #ifdef CONFIG_EXT4_KUNIT_TESTS
  6240. #include "mballoc-test.c"
  6241. #endif