inode.c 326 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2007 Oracle. All rights reserved.
  4. */
  5. #include <crypto/hash.h>
  6. #include <linux/kernel.h>
  7. #include <linux/bio.h>
  8. #include <linux/blk-cgroup.h>
  9. #include <linux/file.h>
  10. #include <linux/fs.h>
  11. #include <linux/pagemap.h>
  12. #include <linux/highmem.h>
  13. #include <linux/time.h>
  14. #include <linux/init.h>
  15. #include <linux/string.h>
  16. #include <linux/backing-dev.h>
  17. #include <linux/writeback.h>
  18. #include <linux/compat.h>
  19. #include <linux/xattr.h>
  20. #include <linux/posix_acl.h>
  21. #include <linux/falloc.h>
  22. #include <linux/slab.h>
  23. #include <linux/ratelimit.h>
  24. #include <linux/btrfs.h>
  25. #include <linux/blkdev.h>
  26. #include <linux/posix_acl_xattr.h>
  27. #include <linux/uio.h>
  28. #include <linux/magic.h>
  29. #include <linux/iversion.h>
  30. #include <linux/swap.h>
  31. #include <linux/migrate.h>
  32. #include <linux/sched/mm.h>
  33. #include <linux/iomap.h>
  34. #include <asm/unaligned.h>
  35. #include <linux/fsverity.h>
  36. #include "misc.h"
  37. #include "ctree.h"
  38. #include "disk-io.h"
  39. #include "transaction.h"
  40. #include "btrfs_inode.h"
  41. #include "print-tree.h"
  42. #include "ordered-data.h"
  43. #include "xattr.h"
  44. #include "tree-log.h"
  45. #include "volumes.h"
  46. #include "compression.h"
  47. #include "locking.h"
  48. #include "free-space-cache.h"
  49. #include "props.h"
  50. #include "qgroup.h"
  51. #include "delalloc-space.h"
  52. #include "block-group.h"
  53. #include "space-info.h"
  54. #include "zoned.h"
  55. #include "subpage.h"
  56. #include "inode-item.h"
  57. struct btrfs_iget_args {
  58. u64 ino;
  59. struct btrfs_root *root;
  60. };
  61. struct btrfs_dio_data {
  62. ssize_t submitted;
  63. struct extent_changeset *data_reserved;
  64. bool data_space_reserved;
  65. bool nocow_done;
  66. };
  67. struct btrfs_dio_private {
  68. struct inode *inode;
  69. /*
  70. * Since DIO can use anonymous page, we cannot use page_offset() to
  71. * grab the file offset, thus need a dedicated member for file offset.
  72. */
  73. u64 file_offset;
  74. /* Used for bio::bi_size */
  75. u32 bytes;
  76. /*
  77. * References to this structure. There is one reference per in-flight
  78. * bio plus one while we're still setting up.
  79. */
  80. refcount_t refs;
  81. /* Array of checksums */
  82. u8 *csums;
  83. /* This must be last */
  84. struct bio bio;
  85. };
  86. static struct bio_set btrfs_dio_bioset;
  87. struct btrfs_rename_ctx {
  88. /* Output field. Stores the index number of the old directory entry. */
  89. u64 index;
  90. };
  91. static const struct inode_operations btrfs_dir_inode_operations;
  92. static const struct inode_operations btrfs_symlink_inode_operations;
  93. static const struct inode_operations btrfs_special_inode_operations;
  94. static const struct inode_operations btrfs_file_inode_operations;
  95. static const struct address_space_operations btrfs_aops;
  96. static const struct file_operations btrfs_dir_file_operations;
  97. static struct kmem_cache *btrfs_inode_cachep;
  98. struct kmem_cache *btrfs_trans_handle_cachep;
  99. struct kmem_cache *btrfs_path_cachep;
  100. struct kmem_cache *btrfs_free_space_cachep;
  101. struct kmem_cache *btrfs_free_space_bitmap_cachep;
  102. static int btrfs_setsize(struct inode *inode, struct iattr *attr);
  103. static int btrfs_truncate(struct inode *inode, bool skip_writeback);
  104. static noinline int cow_file_range(struct btrfs_inode *inode,
  105. struct page *locked_page,
  106. u64 start, u64 end, int *page_started,
  107. unsigned long *nr_written, int unlock,
  108. u64 *done_offset);
  109. static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
  110. u64 len, u64 orig_start, u64 block_start,
  111. u64 block_len, u64 orig_block_len,
  112. u64 ram_bytes, int compress_type,
  113. int type);
  114. /*
  115. * btrfs_inode_lock - lock inode i_rwsem based on arguments passed
  116. *
  117. * ilock_flags can have the following bit set:
  118. *
  119. * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
  120. * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
  121. * return -EAGAIN
  122. * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
  123. */
  124. int btrfs_inode_lock(struct inode *inode, unsigned int ilock_flags)
  125. {
  126. if (ilock_flags & BTRFS_ILOCK_SHARED) {
  127. if (ilock_flags & BTRFS_ILOCK_TRY) {
  128. if (!inode_trylock_shared(inode))
  129. return -EAGAIN;
  130. else
  131. return 0;
  132. }
  133. inode_lock_shared(inode);
  134. } else {
  135. if (ilock_flags & BTRFS_ILOCK_TRY) {
  136. if (!inode_trylock(inode))
  137. return -EAGAIN;
  138. else
  139. return 0;
  140. }
  141. inode_lock(inode);
  142. }
  143. if (ilock_flags & BTRFS_ILOCK_MMAP)
  144. down_write(&BTRFS_I(inode)->i_mmap_lock);
  145. return 0;
  146. }
  147. /*
  148. * btrfs_inode_unlock - unock inode i_rwsem
  149. *
  150. * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
  151. * to decide whether the lock acquired is shared or exclusive.
  152. */
  153. void btrfs_inode_unlock(struct inode *inode, unsigned int ilock_flags)
  154. {
  155. if (ilock_flags & BTRFS_ILOCK_MMAP)
  156. up_write(&BTRFS_I(inode)->i_mmap_lock);
  157. if (ilock_flags & BTRFS_ILOCK_SHARED)
  158. inode_unlock_shared(inode);
  159. else
  160. inode_unlock(inode);
  161. }
  162. /*
  163. * Cleanup all submitted ordered extents in specified range to handle errors
  164. * from the btrfs_run_delalloc_range() callback.
  165. *
  166. * NOTE: caller must ensure that when an error happens, it can not call
  167. * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
  168. * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
  169. * to be released, which we want to happen only when finishing the ordered
  170. * extent (btrfs_finish_ordered_io()).
  171. */
  172. static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
  173. struct page *locked_page,
  174. u64 offset, u64 bytes)
  175. {
  176. unsigned long index = offset >> PAGE_SHIFT;
  177. unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
  178. u64 page_start, page_end;
  179. struct page *page;
  180. if (locked_page) {
  181. page_start = page_offset(locked_page);
  182. page_end = page_start + PAGE_SIZE - 1;
  183. }
  184. while (index <= end_index) {
  185. /*
  186. * For locked page, we will call end_extent_writepage() on it
  187. * in run_delalloc_range() for the error handling. That
  188. * end_extent_writepage() function will call
  189. * btrfs_mark_ordered_io_finished() to clear page Ordered and
  190. * run the ordered extent accounting.
  191. *
  192. * Here we can't just clear the Ordered bit, or
  193. * btrfs_mark_ordered_io_finished() would skip the accounting
  194. * for the page range, and the ordered extent will never finish.
  195. */
  196. if (locked_page && index == (page_start >> PAGE_SHIFT)) {
  197. index++;
  198. continue;
  199. }
  200. page = find_get_page(inode->vfs_inode.i_mapping, index);
  201. index++;
  202. if (!page)
  203. continue;
  204. /*
  205. * Here we just clear all Ordered bits for every page in the
  206. * range, then btrfs_mark_ordered_io_finished() will handle
  207. * the ordered extent accounting for the range.
  208. */
  209. btrfs_page_clamp_clear_ordered(inode->root->fs_info, page,
  210. offset, bytes);
  211. put_page(page);
  212. }
  213. if (locked_page) {
  214. /* The locked page covers the full range, nothing needs to be done */
  215. if (bytes + offset <= page_start + PAGE_SIZE)
  216. return;
  217. /*
  218. * In case this page belongs to the delalloc range being
  219. * instantiated then skip it, since the first page of a range is
  220. * going to be properly cleaned up by the caller of
  221. * run_delalloc_range
  222. */
  223. if (page_start >= offset && page_end <= (offset + bytes - 1)) {
  224. bytes = offset + bytes - page_offset(locked_page) - PAGE_SIZE;
  225. offset = page_offset(locked_page) + PAGE_SIZE;
  226. }
  227. }
  228. return btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes, false);
  229. }
  230. static int btrfs_dirty_inode(struct inode *inode);
  231. static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
  232. struct btrfs_new_inode_args *args)
  233. {
  234. int err;
  235. if (args->default_acl) {
  236. err = __btrfs_set_acl(trans, args->inode, args->default_acl,
  237. ACL_TYPE_DEFAULT);
  238. if (err)
  239. return err;
  240. }
  241. if (args->acl) {
  242. err = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
  243. if (err)
  244. return err;
  245. }
  246. if (!args->default_acl && !args->acl)
  247. cache_no_acl(args->inode);
  248. return btrfs_xattr_security_init(trans, args->inode, args->dir,
  249. &args->dentry->d_name);
  250. }
  251. /*
  252. * this does all the hard work for inserting an inline extent into
  253. * the btree. The caller should have done a btrfs_drop_extents so that
  254. * no overlapping inline items exist in the btree
  255. */
  256. static int insert_inline_extent(struct btrfs_trans_handle *trans,
  257. struct btrfs_path *path,
  258. struct btrfs_inode *inode, bool extent_inserted,
  259. size_t size, size_t compressed_size,
  260. int compress_type,
  261. struct page **compressed_pages,
  262. bool update_i_size)
  263. {
  264. struct btrfs_root *root = inode->root;
  265. struct extent_buffer *leaf;
  266. struct page *page = NULL;
  267. char *kaddr;
  268. unsigned long ptr;
  269. struct btrfs_file_extent_item *ei;
  270. int ret;
  271. size_t cur_size = size;
  272. u64 i_size;
  273. ASSERT((compressed_size > 0 && compressed_pages) ||
  274. (compressed_size == 0 && !compressed_pages));
  275. if (compressed_size && compressed_pages)
  276. cur_size = compressed_size;
  277. if (!extent_inserted) {
  278. struct btrfs_key key;
  279. size_t datasize;
  280. key.objectid = btrfs_ino(inode);
  281. key.offset = 0;
  282. key.type = BTRFS_EXTENT_DATA_KEY;
  283. datasize = btrfs_file_extent_calc_inline_size(cur_size);
  284. ret = btrfs_insert_empty_item(trans, root, path, &key,
  285. datasize);
  286. if (ret)
  287. goto fail;
  288. }
  289. leaf = path->nodes[0];
  290. ei = btrfs_item_ptr(leaf, path->slots[0],
  291. struct btrfs_file_extent_item);
  292. btrfs_set_file_extent_generation(leaf, ei, trans->transid);
  293. btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
  294. btrfs_set_file_extent_encryption(leaf, ei, 0);
  295. btrfs_set_file_extent_other_encoding(leaf, ei, 0);
  296. btrfs_set_file_extent_ram_bytes(leaf, ei, size);
  297. ptr = btrfs_file_extent_inline_start(ei);
  298. if (compress_type != BTRFS_COMPRESS_NONE) {
  299. struct page *cpage;
  300. int i = 0;
  301. while (compressed_size > 0) {
  302. cpage = compressed_pages[i];
  303. cur_size = min_t(unsigned long, compressed_size,
  304. PAGE_SIZE);
  305. kaddr = kmap_local_page(cpage);
  306. write_extent_buffer(leaf, kaddr, ptr, cur_size);
  307. kunmap_local(kaddr);
  308. i++;
  309. ptr += cur_size;
  310. compressed_size -= cur_size;
  311. }
  312. btrfs_set_file_extent_compression(leaf, ei,
  313. compress_type);
  314. } else {
  315. page = find_get_page(inode->vfs_inode.i_mapping, 0);
  316. btrfs_set_file_extent_compression(leaf, ei, 0);
  317. kaddr = kmap_local_page(page);
  318. write_extent_buffer(leaf, kaddr, ptr, size);
  319. kunmap_local(kaddr);
  320. put_page(page);
  321. }
  322. btrfs_mark_buffer_dirty(leaf);
  323. btrfs_release_path(path);
  324. /*
  325. * We align size to sectorsize for inline extents just for simplicity
  326. * sake.
  327. */
  328. ret = btrfs_inode_set_file_extent_range(inode, 0,
  329. ALIGN(size, root->fs_info->sectorsize));
  330. if (ret)
  331. goto fail;
  332. /*
  333. * We're an inline extent, so nobody can extend the file past i_size
  334. * without locking a page we already have locked.
  335. *
  336. * We must do any i_size and inode updates before we unlock the pages.
  337. * Otherwise we could end up racing with unlink.
  338. */
  339. i_size = i_size_read(&inode->vfs_inode);
  340. if (update_i_size && size > i_size) {
  341. i_size_write(&inode->vfs_inode, size);
  342. i_size = size;
  343. }
  344. inode->disk_i_size = i_size;
  345. fail:
  346. return ret;
  347. }
  348. /*
  349. * conditionally insert an inline extent into the file. This
  350. * does the checks required to make sure the data is small enough
  351. * to fit as an inline extent.
  352. */
  353. static noinline int cow_file_range_inline(struct btrfs_inode *inode, u64 size,
  354. size_t compressed_size,
  355. int compress_type,
  356. struct page **compressed_pages,
  357. bool update_i_size)
  358. {
  359. struct btrfs_drop_extents_args drop_args = { 0 };
  360. struct btrfs_root *root = inode->root;
  361. struct btrfs_fs_info *fs_info = root->fs_info;
  362. struct btrfs_trans_handle *trans;
  363. u64 data_len = (compressed_size ?: size);
  364. int ret;
  365. struct btrfs_path *path;
  366. /*
  367. * We can create an inline extent if it ends at or beyond the current
  368. * i_size, is no larger than a sector (decompressed), and the (possibly
  369. * compressed) data fits in a leaf and the configured maximum inline
  370. * size.
  371. */
  372. if (size < i_size_read(&inode->vfs_inode) ||
  373. size > fs_info->sectorsize ||
  374. data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
  375. data_len > fs_info->max_inline)
  376. return 1;
  377. path = btrfs_alloc_path();
  378. if (!path)
  379. return -ENOMEM;
  380. trans = btrfs_join_transaction(root);
  381. if (IS_ERR(trans)) {
  382. btrfs_free_path(path);
  383. return PTR_ERR(trans);
  384. }
  385. trans->block_rsv = &inode->block_rsv;
  386. drop_args.path = path;
  387. drop_args.start = 0;
  388. drop_args.end = fs_info->sectorsize;
  389. drop_args.drop_cache = true;
  390. drop_args.replace_extent = true;
  391. drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
  392. ret = btrfs_drop_extents(trans, root, inode, &drop_args);
  393. if (ret) {
  394. btrfs_abort_transaction(trans, ret);
  395. goto out;
  396. }
  397. ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
  398. size, compressed_size, compress_type,
  399. compressed_pages, update_i_size);
  400. if (ret && ret != -ENOSPC) {
  401. btrfs_abort_transaction(trans, ret);
  402. goto out;
  403. } else if (ret == -ENOSPC) {
  404. ret = 1;
  405. goto out;
  406. }
  407. btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
  408. ret = btrfs_update_inode(trans, root, inode);
  409. if (ret && ret != -ENOSPC) {
  410. btrfs_abort_transaction(trans, ret);
  411. goto out;
  412. } else if (ret == -ENOSPC) {
  413. ret = 1;
  414. goto out;
  415. }
  416. btrfs_set_inode_full_sync(inode);
  417. out:
  418. /*
  419. * Don't forget to free the reserved space, as for inlined extent
  420. * it won't count as data extent, free them directly here.
  421. * And at reserve time, it's always aligned to page size, so
  422. * just free one page here.
  423. */
  424. btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE);
  425. btrfs_free_path(path);
  426. btrfs_end_transaction(trans);
  427. return ret;
  428. }
  429. struct async_extent {
  430. u64 start;
  431. u64 ram_size;
  432. u64 compressed_size;
  433. struct page **pages;
  434. unsigned long nr_pages;
  435. int compress_type;
  436. struct list_head list;
  437. };
  438. struct async_chunk {
  439. struct inode *inode;
  440. struct page *locked_page;
  441. u64 start;
  442. u64 end;
  443. blk_opf_t write_flags;
  444. struct list_head extents;
  445. struct cgroup_subsys_state *blkcg_css;
  446. struct btrfs_work work;
  447. struct async_cow *async_cow;
  448. };
  449. struct async_cow {
  450. atomic_t num_chunks;
  451. struct async_chunk chunks[];
  452. };
  453. static noinline int add_async_extent(struct async_chunk *cow,
  454. u64 start, u64 ram_size,
  455. u64 compressed_size,
  456. struct page **pages,
  457. unsigned long nr_pages,
  458. int compress_type)
  459. {
  460. struct async_extent *async_extent;
  461. async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
  462. BUG_ON(!async_extent); /* -ENOMEM */
  463. async_extent->start = start;
  464. async_extent->ram_size = ram_size;
  465. async_extent->compressed_size = compressed_size;
  466. async_extent->pages = pages;
  467. async_extent->nr_pages = nr_pages;
  468. async_extent->compress_type = compress_type;
  469. list_add_tail(&async_extent->list, &cow->extents);
  470. return 0;
  471. }
  472. /*
  473. * Check if the inode needs to be submitted to compression, based on mount
  474. * options, defragmentation, properties or heuristics.
  475. */
  476. static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
  477. u64 end)
  478. {
  479. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  480. if (!btrfs_inode_can_compress(inode)) {
  481. WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
  482. KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
  483. btrfs_ino(inode));
  484. return 0;
  485. }
  486. /*
  487. * Special check for subpage.
  488. *
  489. * We lock the full page then run each delalloc range in the page, thus
  490. * for the following case, we will hit some subpage specific corner case:
  491. *
  492. * 0 32K 64K
  493. * | |///////| |///////|
  494. * \- A \- B
  495. *
  496. * In above case, both range A and range B will try to unlock the full
  497. * page [0, 64K), causing the one finished later will have page
  498. * unlocked already, triggering various page lock requirement BUG_ON()s.
  499. *
  500. * So here we add an artificial limit that subpage compression can only
  501. * if the range is fully page aligned.
  502. *
  503. * In theory we only need to ensure the first page is fully covered, but
  504. * the tailing partial page will be locked until the full compression
  505. * finishes, delaying the write of other range.
  506. *
  507. * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
  508. * first to prevent any submitted async extent to unlock the full page.
  509. * By this, we can ensure for subpage case that only the last async_cow
  510. * will unlock the full page.
  511. */
  512. if (fs_info->sectorsize < PAGE_SIZE) {
  513. if (!PAGE_ALIGNED(start) ||
  514. !PAGE_ALIGNED(end + 1))
  515. return 0;
  516. }
  517. /* force compress */
  518. if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
  519. return 1;
  520. /* defrag ioctl */
  521. if (inode->defrag_compress)
  522. return 1;
  523. /* bad compression ratios */
  524. if (inode->flags & BTRFS_INODE_NOCOMPRESS)
  525. return 0;
  526. if (btrfs_test_opt(fs_info, COMPRESS) ||
  527. inode->flags & BTRFS_INODE_COMPRESS ||
  528. inode->prop_compress)
  529. return btrfs_compress_heuristic(&inode->vfs_inode, start, end);
  530. return 0;
  531. }
  532. static inline void inode_should_defrag(struct btrfs_inode *inode,
  533. u64 start, u64 end, u64 num_bytes, u32 small_write)
  534. {
  535. /* If this is a small write inside eof, kick off a defrag */
  536. if (num_bytes < small_write &&
  537. (start > 0 || end + 1 < inode->disk_i_size))
  538. btrfs_add_inode_defrag(NULL, inode, small_write);
  539. }
  540. /*
  541. * we create compressed extents in two phases. The first
  542. * phase compresses a range of pages that have already been
  543. * locked (both pages and state bits are locked).
  544. *
  545. * This is done inside an ordered work queue, and the compression
  546. * is spread across many cpus. The actual IO submission is step
  547. * two, and the ordered work queue takes care of making sure that
  548. * happens in the same order things were put onto the queue by
  549. * writepages and friends.
  550. *
  551. * If this code finds it can't get good compression, it puts an
  552. * entry onto the work queue to write the uncompressed bytes. This
  553. * makes sure that both compressed inodes and uncompressed inodes
  554. * are written in the same order that the flusher thread sent them
  555. * down.
  556. */
  557. static noinline int compress_file_range(struct async_chunk *async_chunk)
  558. {
  559. struct inode *inode = async_chunk->inode;
  560. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  561. u64 blocksize = fs_info->sectorsize;
  562. u64 start = async_chunk->start;
  563. u64 end = async_chunk->end;
  564. u64 actual_end;
  565. u64 i_size;
  566. int ret = 0;
  567. struct page **pages = NULL;
  568. unsigned long nr_pages;
  569. unsigned long total_compressed = 0;
  570. unsigned long total_in = 0;
  571. int i;
  572. int will_compress;
  573. int compress_type = fs_info->compress_type;
  574. int compressed_extents = 0;
  575. int redirty = 0;
  576. inode_should_defrag(BTRFS_I(inode), start, end, end - start + 1,
  577. SZ_16K);
  578. /*
  579. * We need to save i_size before now because it could change in between
  580. * us evaluating the size and assigning it. This is because we lock and
  581. * unlock the page in truncate and fallocate, and then modify the i_size
  582. * later on.
  583. *
  584. * The barriers are to emulate READ_ONCE, remove that once i_size_read
  585. * does that for us.
  586. */
  587. barrier();
  588. i_size = i_size_read(inode);
  589. barrier();
  590. actual_end = min_t(u64, i_size, end + 1);
  591. again:
  592. will_compress = 0;
  593. nr_pages = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
  594. nr_pages = min_t(unsigned long, nr_pages,
  595. BTRFS_MAX_COMPRESSED / PAGE_SIZE);
  596. /*
  597. * we don't want to send crud past the end of i_size through
  598. * compression, that's just a waste of CPU time. So, if the
  599. * end of the file is before the start of our current
  600. * requested range of bytes, we bail out to the uncompressed
  601. * cleanup code that can deal with all of this.
  602. *
  603. * It isn't really the fastest way to fix things, but this is a
  604. * very uncommon corner.
  605. */
  606. if (actual_end <= start)
  607. goto cleanup_and_bail_uncompressed;
  608. total_compressed = actual_end - start;
  609. /*
  610. * Skip compression for a small file range(<=blocksize) that
  611. * isn't an inline extent, since it doesn't save disk space at all.
  612. */
  613. if (total_compressed <= blocksize &&
  614. (start > 0 || end + 1 < BTRFS_I(inode)->disk_i_size))
  615. goto cleanup_and_bail_uncompressed;
  616. /*
  617. * For subpage case, we require full page alignment for the sector
  618. * aligned range.
  619. * Thus we must also check against @actual_end, not just @end.
  620. */
  621. if (blocksize < PAGE_SIZE) {
  622. if (!PAGE_ALIGNED(start) ||
  623. !PAGE_ALIGNED(round_up(actual_end, blocksize)))
  624. goto cleanup_and_bail_uncompressed;
  625. }
  626. total_compressed = min_t(unsigned long, total_compressed,
  627. BTRFS_MAX_UNCOMPRESSED);
  628. total_in = 0;
  629. ret = 0;
  630. /*
  631. * we do compression for mount -o compress and when the
  632. * inode has not been flagged as nocompress. This flag can
  633. * change at any time if we discover bad compression ratios.
  634. */
  635. if (inode_need_compress(BTRFS_I(inode), start, end)) {
  636. WARN_ON(pages);
  637. pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
  638. if (!pages) {
  639. /* just bail out to the uncompressed code */
  640. nr_pages = 0;
  641. goto cont;
  642. }
  643. if (BTRFS_I(inode)->defrag_compress)
  644. compress_type = BTRFS_I(inode)->defrag_compress;
  645. else if (BTRFS_I(inode)->prop_compress)
  646. compress_type = BTRFS_I(inode)->prop_compress;
  647. /*
  648. * we need to call clear_page_dirty_for_io on each
  649. * page in the range. Otherwise applications with the file
  650. * mmap'd can wander in and change the page contents while
  651. * we are compressing them.
  652. *
  653. * If the compression fails for any reason, we set the pages
  654. * dirty again later on.
  655. *
  656. * Note that the remaining part is redirtied, the start pointer
  657. * has moved, the end is the original one.
  658. */
  659. if (!redirty) {
  660. extent_range_clear_dirty_for_io(inode, start, end);
  661. redirty = 1;
  662. }
  663. /* Compression level is applied here and only here */
  664. ret = btrfs_compress_pages(
  665. compress_type | (fs_info->compress_level << 4),
  666. inode->i_mapping, start,
  667. pages,
  668. &nr_pages,
  669. &total_in,
  670. &total_compressed);
  671. if (!ret) {
  672. unsigned long offset = offset_in_page(total_compressed);
  673. struct page *page = pages[nr_pages - 1];
  674. /* zero the tail end of the last page, we might be
  675. * sending it down to disk
  676. */
  677. if (offset)
  678. memzero_page(page, offset, PAGE_SIZE - offset);
  679. will_compress = 1;
  680. }
  681. }
  682. cont:
  683. /*
  684. * Check cow_file_range() for why we don't even try to create inline
  685. * extent for subpage case.
  686. */
  687. if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
  688. /* lets try to make an inline extent */
  689. if (ret || total_in < actual_end) {
  690. /* we didn't compress the entire range, try
  691. * to make an uncompressed inline extent.
  692. */
  693. ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
  694. 0, BTRFS_COMPRESS_NONE,
  695. NULL, false);
  696. } else {
  697. /* try making a compressed inline extent */
  698. ret = cow_file_range_inline(BTRFS_I(inode), actual_end,
  699. total_compressed,
  700. compress_type, pages,
  701. false);
  702. }
  703. if (ret <= 0) {
  704. unsigned long clear_flags = EXTENT_DELALLOC |
  705. EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
  706. EXTENT_DO_ACCOUNTING;
  707. unsigned long page_error_op;
  708. page_error_op = ret < 0 ? PAGE_SET_ERROR : 0;
  709. /*
  710. * inline extent creation worked or returned error,
  711. * we don't need to create any more async work items.
  712. * Unlock and free up our temp pages.
  713. *
  714. * We use DO_ACCOUNTING here because we need the
  715. * delalloc_release_metadata to be done _after_ we drop
  716. * our outstanding extent for clearing delalloc for this
  717. * range.
  718. */
  719. extent_clear_unlock_delalloc(BTRFS_I(inode), start, end,
  720. NULL,
  721. clear_flags,
  722. PAGE_UNLOCK |
  723. PAGE_START_WRITEBACK |
  724. page_error_op |
  725. PAGE_END_WRITEBACK);
  726. /*
  727. * Ensure we only free the compressed pages if we have
  728. * them allocated, as we can still reach here with
  729. * inode_need_compress() == false.
  730. */
  731. if (pages) {
  732. for (i = 0; i < nr_pages; i++) {
  733. WARN_ON(pages[i]->mapping);
  734. put_page(pages[i]);
  735. }
  736. kfree(pages);
  737. }
  738. return 0;
  739. }
  740. }
  741. if (will_compress) {
  742. /*
  743. * we aren't doing an inline extent round the compressed size
  744. * up to a block size boundary so the allocator does sane
  745. * things
  746. */
  747. total_compressed = ALIGN(total_compressed, blocksize);
  748. /*
  749. * one last check to make sure the compression is really a
  750. * win, compare the page count read with the blocks on disk,
  751. * compression must free at least one sector size
  752. */
  753. total_in = round_up(total_in, fs_info->sectorsize);
  754. if (total_compressed + blocksize <= total_in) {
  755. compressed_extents++;
  756. /*
  757. * The async work queues will take care of doing actual
  758. * allocation on disk for these compressed pages, and
  759. * will submit them to the elevator.
  760. */
  761. add_async_extent(async_chunk, start, total_in,
  762. total_compressed, pages, nr_pages,
  763. compress_type);
  764. if (start + total_in < end) {
  765. start += total_in;
  766. pages = NULL;
  767. cond_resched();
  768. goto again;
  769. }
  770. return compressed_extents;
  771. }
  772. }
  773. if (pages) {
  774. /*
  775. * the compression code ran but failed to make things smaller,
  776. * free any pages it allocated and our page pointer array
  777. */
  778. for (i = 0; i < nr_pages; i++) {
  779. WARN_ON(pages[i]->mapping);
  780. put_page(pages[i]);
  781. }
  782. kfree(pages);
  783. pages = NULL;
  784. total_compressed = 0;
  785. nr_pages = 0;
  786. /* flag the file so we don't compress in the future */
  787. if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) &&
  788. !(BTRFS_I(inode)->prop_compress)) {
  789. BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
  790. }
  791. }
  792. cleanup_and_bail_uncompressed:
  793. /*
  794. * No compression, but we still need to write the pages in the file
  795. * we've been given so far. redirty the locked page if it corresponds
  796. * to our extent and set things up for the async work queue to run
  797. * cow_file_range to do the normal delalloc dance.
  798. */
  799. if (async_chunk->locked_page &&
  800. (page_offset(async_chunk->locked_page) >= start &&
  801. page_offset(async_chunk->locked_page)) <= end) {
  802. __set_page_dirty_nobuffers(async_chunk->locked_page);
  803. /* unlocked later on in the async handlers */
  804. }
  805. if (redirty)
  806. extent_range_redirty_for_io(inode, start, end);
  807. add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
  808. BTRFS_COMPRESS_NONE);
  809. compressed_extents++;
  810. return compressed_extents;
  811. }
  812. static void free_async_extent_pages(struct async_extent *async_extent)
  813. {
  814. int i;
  815. if (!async_extent->pages)
  816. return;
  817. for (i = 0; i < async_extent->nr_pages; i++) {
  818. WARN_ON(async_extent->pages[i]->mapping);
  819. put_page(async_extent->pages[i]);
  820. }
  821. kfree(async_extent->pages);
  822. async_extent->nr_pages = 0;
  823. async_extent->pages = NULL;
  824. }
  825. static int submit_uncompressed_range(struct btrfs_inode *inode,
  826. struct async_extent *async_extent,
  827. struct page *locked_page)
  828. {
  829. u64 start = async_extent->start;
  830. u64 end = async_extent->start + async_extent->ram_size - 1;
  831. unsigned long nr_written = 0;
  832. int page_started = 0;
  833. int ret;
  834. /*
  835. * Call cow_file_range() to run the delalloc range directly, since we
  836. * won't go to NOCOW or async path again.
  837. *
  838. * Also we call cow_file_range() with @unlock_page == 0, so that we
  839. * can directly submit them without interruption.
  840. */
  841. ret = cow_file_range(inode, locked_page, start, end, &page_started,
  842. &nr_written, 0, NULL);
  843. /* Inline extent inserted, page gets unlocked and everything is done */
  844. if (page_started) {
  845. ret = 0;
  846. goto out;
  847. }
  848. if (ret < 0) {
  849. btrfs_cleanup_ordered_extents(inode, locked_page, start, end - start + 1);
  850. if (locked_page) {
  851. const u64 page_start = page_offset(locked_page);
  852. const u64 page_end = page_start + PAGE_SIZE - 1;
  853. btrfs_page_set_error(inode->root->fs_info, locked_page,
  854. page_start, PAGE_SIZE);
  855. set_page_writeback(locked_page);
  856. end_page_writeback(locked_page);
  857. end_extent_writepage(locked_page, ret, page_start, page_end);
  858. unlock_page(locked_page);
  859. }
  860. goto out;
  861. }
  862. ret = extent_write_locked_range(&inode->vfs_inode, start, end);
  863. /* All pages will be unlocked, including @locked_page */
  864. out:
  865. kfree(async_extent);
  866. return ret;
  867. }
  868. static int submit_one_async_extent(struct btrfs_inode *inode,
  869. struct async_chunk *async_chunk,
  870. struct async_extent *async_extent,
  871. u64 *alloc_hint)
  872. {
  873. struct extent_io_tree *io_tree = &inode->io_tree;
  874. struct btrfs_root *root = inode->root;
  875. struct btrfs_fs_info *fs_info = root->fs_info;
  876. struct btrfs_key ins;
  877. struct page *locked_page = NULL;
  878. struct extent_map *em;
  879. int ret = 0;
  880. u64 start = async_extent->start;
  881. u64 end = async_extent->start + async_extent->ram_size - 1;
  882. /*
  883. * If async_chunk->locked_page is in the async_extent range, we need to
  884. * handle it.
  885. */
  886. if (async_chunk->locked_page) {
  887. u64 locked_page_start = page_offset(async_chunk->locked_page);
  888. u64 locked_page_end = locked_page_start + PAGE_SIZE - 1;
  889. if (!(start >= locked_page_end || end <= locked_page_start))
  890. locked_page = async_chunk->locked_page;
  891. }
  892. lock_extent(io_tree, start, end, NULL);
  893. /* We have fall back to uncompressed write */
  894. if (!async_extent->pages)
  895. return submit_uncompressed_range(inode, async_extent, locked_page);
  896. ret = btrfs_reserve_extent(root, async_extent->ram_size,
  897. async_extent->compressed_size,
  898. async_extent->compressed_size,
  899. 0, *alloc_hint, &ins, 1, 1);
  900. if (ret) {
  901. free_async_extent_pages(async_extent);
  902. /*
  903. * Here we used to try again by going back to non-compressed
  904. * path for ENOSPC. But we can't reserve space even for
  905. * compressed size, how could it work for uncompressed size
  906. * which requires larger size? So here we directly go error
  907. * path.
  908. */
  909. goto out_free;
  910. }
  911. /* Here we're doing allocation and writeback of the compressed pages */
  912. em = create_io_em(inode, start,
  913. async_extent->ram_size, /* len */
  914. start, /* orig_start */
  915. ins.objectid, /* block_start */
  916. ins.offset, /* block_len */
  917. ins.offset, /* orig_block_len */
  918. async_extent->ram_size, /* ram_bytes */
  919. async_extent->compress_type,
  920. BTRFS_ORDERED_COMPRESSED);
  921. if (IS_ERR(em)) {
  922. ret = PTR_ERR(em);
  923. goto out_free_reserve;
  924. }
  925. free_extent_map(em);
  926. ret = btrfs_add_ordered_extent(inode, start, /* file_offset */
  927. async_extent->ram_size, /* num_bytes */
  928. async_extent->ram_size, /* ram_bytes */
  929. ins.objectid, /* disk_bytenr */
  930. ins.offset, /* disk_num_bytes */
  931. 0, /* offset */
  932. 1 << BTRFS_ORDERED_COMPRESSED,
  933. async_extent->compress_type);
  934. if (ret) {
  935. btrfs_drop_extent_map_range(inode, start, end, false);
  936. goto out_free_reserve;
  937. }
  938. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  939. /* Clear dirty, set writeback and unlock the pages. */
  940. extent_clear_unlock_delalloc(inode, start, end,
  941. NULL, EXTENT_LOCKED | EXTENT_DELALLOC,
  942. PAGE_UNLOCK | PAGE_START_WRITEBACK);
  943. if (btrfs_submit_compressed_write(inode, start, /* file_offset */
  944. async_extent->ram_size, /* num_bytes */
  945. ins.objectid, /* disk_bytenr */
  946. ins.offset, /* compressed_len */
  947. async_extent->pages, /* compressed_pages */
  948. async_extent->nr_pages,
  949. async_chunk->write_flags,
  950. async_chunk->blkcg_css, true)) {
  951. const u64 start = async_extent->start;
  952. const u64 end = start + async_extent->ram_size - 1;
  953. btrfs_writepage_endio_finish_ordered(inode, NULL, start, end, 0);
  954. extent_clear_unlock_delalloc(inode, start, end, NULL, 0,
  955. PAGE_END_WRITEBACK | PAGE_SET_ERROR);
  956. free_async_extent_pages(async_extent);
  957. }
  958. *alloc_hint = ins.objectid + ins.offset;
  959. kfree(async_extent);
  960. return ret;
  961. out_free_reserve:
  962. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  963. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  964. out_free:
  965. extent_clear_unlock_delalloc(inode, start, end,
  966. NULL, EXTENT_LOCKED | EXTENT_DELALLOC |
  967. EXTENT_DELALLOC_NEW |
  968. EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
  969. PAGE_UNLOCK | PAGE_START_WRITEBACK |
  970. PAGE_END_WRITEBACK | PAGE_SET_ERROR);
  971. free_async_extent_pages(async_extent);
  972. kfree(async_extent);
  973. return ret;
  974. }
  975. /*
  976. * Phase two of compressed writeback. This is the ordered portion of the code,
  977. * which only gets called in the order the work was queued. We walk all the
  978. * async extents created by compress_file_range and send them down to the disk.
  979. */
  980. static noinline void submit_compressed_extents(struct async_chunk *async_chunk)
  981. {
  982. struct btrfs_inode *inode = BTRFS_I(async_chunk->inode);
  983. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  984. struct async_extent *async_extent;
  985. u64 alloc_hint = 0;
  986. int ret = 0;
  987. while (!list_empty(&async_chunk->extents)) {
  988. u64 extent_start;
  989. u64 ram_size;
  990. async_extent = list_entry(async_chunk->extents.next,
  991. struct async_extent, list);
  992. list_del(&async_extent->list);
  993. extent_start = async_extent->start;
  994. ram_size = async_extent->ram_size;
  995. ret = submit_one_async_extent(inode, async_chunk, async_extent,
  996. &alloc_hint);
  997. btrfs_debug(fs_info,
  998. "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
  999. inode->root->root_key.objectid,
  1000. btrfs_ino(inode), extent_start, ram_size, ret);
  1001. }
  1002. }
  1003. static u64 get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
  1004. u64 num_bytes)
  1005. {
  1006. struct extent_map_tree *em_tree = &inode->extent_tree;
  1007. struct extent_map *em;
  1008. u64 alloc_hint = 0;
  1009. read_lock(&em_tree->lock);
  1010. em = search_extent_mapping(em_tree, start, num_bytes);
  1011. if (em) {
  1012. /*
  1013. * if block start isn't an actual block number then find the
  1014. * first block in this inode and use that as a hint. If that
  1015. * block is also bogus then just don't worry about it.
  1016. */
  1017. if (em->block_start >= EXTENT_MAP_LAST_BYTE) {
  1018. free_extent_map(em);
  1019. em = search_extent_mapping(em_tree, 0, 0);
  1020. if (em && em->block_start < EXTENT_MAP_LAST_BYTE)
  1021. alloc_hint = em->block_start;
  1022. if (em)
  1023. free_extent_map(em);
  1024. } else {
  1025. alloc_hint = em->block_start;
  1026. free_extent_map(em);
  1027. }
  1028. }
  1029. read_unlock(&em_tree->lock);
  1030. return alloc_hint;
  1031. }
  1032. /*
  1033. * when extent_io.c finds a delayed allocation range in the file,
  1034. * the call backs end up in this code. The basic idea is to
  1035. * allocate extents on disk for the range, and create ordered data structs
  1036. * in ram to track those extents.
  1037. *
  1038. * locked_page is the page that writepage had locked already. We use
  1039. * it to make sure we don't do extra locks or unlocks.
  1040. *
  1041. * *page_started is set to one if we unlock locked_page and do everything
  1042. * required to start IO on it. It may be clean and already done with
  1043. * IO when we return.
  1044. *
  1045. * When unlock == 1, we unlock the pages in successfully allocated regions.
  1046. * When unlock == 0, we leave them locked for writing them out.
  1047. *
  1048. * However, we unlock all the pages except @locked_page in case of failure.
  1049. *
  1050. * In summary, page locking state will be as follow:
  1051. *
  1052. * - page_started == 1 (return value)
  1053. * - All the pages are unlocked. IO is started.
  1054. * - Note that this can happen only on success
  1055. * - unlock == 1
  1056. * - All the pages except @locked_page are unlocked in any case
  1057. * - unlock == 0
  1058. * - On success, all the pages are locked for writing out them
  1059. * - On failure, all the pages except @locked_page are unlocked
  1060. *
  1061. * When a failure happens in the second or later iteration of the
  1062. * while-loop, the ordered extents created in previous iterations are kept
  1063. * intact. So, the caller must clean them up by calling
  1064. * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
  1065. * example.
  1066. */
  1067. static noinline int cow_file_range(struct btrfs_inode *inode,
  1068. struct page *locked_page,
  1069. u64 start, u64 end, int *page_started,
  1070. unsigned long *nr_written, int unlock,
  1071. u64 *done_offset)
  1072. {
  1073. struct btrfs_root *root = inode->root;
  1074. struct btrfs_fs_info *fs_info = root->fs_info;
  1075. u64 alloc_hint = 0;
  1076. u64 orig_start = start;
  1077. u64 num_bytes;
  1078. unsigned long ram_size;
  1079. u64 cur_alloc_size = 0;
  1080. u64 min_alloc_size;
  1081. u64 blocksize = fs_info->sectorsize;
  1082. struct btrfs_key ins;
  1083. struct extent_map *em;
  1084. unsigned clear_bits;
  1085. unsigned long page_ops;
  1086. bool extent_reserved = false;
  1087. int ret = 0;
  1088. if (btrfs_is_free_space_inode(inode)) {
  1089. ret = -EINVAL;
  1090. goto out_unlock;
  1091. }
  1092. num_bytes = ALIGN(end - start + 1, blocksize);
  1093. num_bytes = max(blocksize, num_bytes);
  1094. ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
  1095. inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
  1096. /*
  1097. * Due to the page size limit, for subpage we can only trigger the
  1098. * writeback for the dirty sectors of page, that means data writeback
  1099. * is doing more writeback than what we want.
  1100. *
  1101. * This is especially unexpected for some call sites like fallocate,
  1102. * where we only increase i_size after everything is done.
  1103. * This means we can trigger inline extent even if we didn't want to.
  1104. * So here we skip inline extent creation completely.
  1105. */
  1106. if (start == 0 && fs_info->sectorsize == PAGE_SIZE) {
  1107. u64 actual_end = min_t(u64, i_size_read(&inode->vfs_inode),
  1108. end + 1);
  1109. /* lets try to make an inline extent */
  1110. ret = cow_file_range_inline(inode, actual_end, 0,
  1111. BTRFS_COMPRESS_NONE, NULL, false);
  1112. if (ret == 0) {
  1113. /*
  1114. * We use DO_ACCOUNTING here because we need the
  1115. * delalloc_release_metadata to be run _after_ we drop
  1116. * our outstanding extent for clearing delalloc for this
  1117. * range.
  1118. */
  1119. extent_clear_unlock_delalloc(inode, start, end,
  1120. locked_page,
  1121. EXTENT_LOCKED | EXTENT_DELALLOC |
  1122. EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
  1123. EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
  1124. PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
  1125. *nr_written = *nr_written +
  1126. (end - start + PAGE_SIZE) / PAGE_SIZE;
  1127. *page_started = 1;
  1128. /*
  1129. * locked_page is locked by the caller of
  1130. * writepage_delalloc(), not locked by
  1131. * __process_pages_contig().
  1132. *
  1133. * We can't let __process_pages_contig() to unlock it,
  1134. * as it doesn't have any subpage::writers recorded.
  1135. *
  1136. * Here we manually unlock the page, since the caller
  1137. * can't use page_started to determine if it's an
  1138. * inline extent or a compressed extent.
  1139. */
  1140. unlock_page(locked_page);
  1141. goto out;
  1142. } else if (ret < 0) {
  1143. goto out_unlock;
  1144. }
  1145. }
  1146. alloc_hint = get_extent_allocation_hint(inode, start, num_bytes);
  1147. /*
  1148. * Relocation relies on the relocated extents to have exactly the same
  1149. * size as the original extents. Normally writeback for relocation data
  1150. * extents follows a NOCOW path because relocation preallocates the
  1151. * extents. However, due to an operation such as scrub turning a block
  1152. * group to RO mode, it may fallback to COW mode, so we must make sure
  1153. * an extent allocated during COW has exactly the requested size and can
  1154. * not be split into smaller extents, otherwise relocation breaks and
  1155. * fails during the stage where it updates the bytenr of file extent
  1156. * items.
  1157. */
  1158. if (btrfs_is_data_reloc_root(root))
  1159. min_alloc_size = num_bytes;
  1160. else
  1161. min_alloc_size = fs_info->sectorsize;
  1162. while (num_bytes > 0) {
  1163. cur_alloc_size = num_bytes;
  1164. ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
  1165. min_alloc_size, 0, alloc_hint,
  1166. &ins, 1, 1);
  1167. if (ret < 0)
  1168. goto out_unlock;
  1169. cur_alloc_size = ins.offset;
  1170. extent_reserved = true;
  1171. ram_size = ins.offset;
  1172. em = create_io_em(inode, start, ins.offset, /* len */
  1173. start, /* orig_start */
  1174. ins.objectid, /* block_start */
  1175. ins.offset, /* block_len */
  1176. ins.offset, /* orig_block_len */
  1177. ram_size, /* ram_bytes */
  1178. BTRFS_COMPRESS_NONE, /* compress_type */
  1179. BTRFS_ORDERED_REGULAR /* type */);
  1180. if (IS_ERR(em)) {
  1181. ret = PTR_ERR(em);
  1182. goto out_reserve;
  1183. }
  1184. free_extent_map(em);
  1185. ret = btrfs_add_ordered_extent(inode, start, ram_size, ram_size,
  1186. ins.objectid, cur_alloc_size, 0,
  1187. 1 << BTRFS_ORDERED_REGULAR,
  1188. BTRFS_COMPRESS_NONE);
  1189. if (ret)
  1190. goto out_drop_extent_cache;
  1191. if (btrfs_is_data_reloc_root(root)) {
  1192. ret = btrfs_reloc_clone_csums(inode, start,
  1193. cur_alloc_size);
  1194. /*
  1195. * Only drop cache here, and process as normal.
  1196. *
  1197. * We must not allow extent_clear_unlock_delalloc()
  1198. * at out_unlock label to free meta of this ordered
  1199. * extent, as its meta should be freed by
  1200. * btrfs_finish_ordered_io().
  1201. *
  1202. * So we must continue until @start is increased to
  1203. * skip current ordered extent.
  1204. */
  1205. if (ret)
  1206. btrfs_drop_extent_map_range(inode, start,
  1207. start + ram_size - 1,
  1208. false);
  1209. }
  1210. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  1211. /*
  1212. * We're not doing compressed IO, don't unlock the first page
  1213. * (which the caller expects to stay locked), don't clear any
  1214. * dirty bits and don't set any writeback bits
  1215. *
  1216. * Do set the Ordered (Private2) bit so we know this page was
  1217. * properly setup for writepage.
  1218. */
  1219. page_ops = unlock ? PAGE_UNLOCK : 0;
  1220. page_ops |= PAGE_SET_ORDERED;
  1221. extent_clear_unlock_delalloc(inode, start, start + ram_size - 1,
  1222. locked_page,
  1223. EXTENT_LOCKED | EXTENT_DELALLOC,
  1224. page_ops);
  1225. if (num_bytes < cur_alloc_size)
  1226. num_bytes = 0;
  1227. else
  1228. num_bytes -= cur_alloc_size;
  1229. alloc_hint = ins.objectid + ins.offset;
  1230. start += cur_alloc_size;
  1231. extent_reserved = false;
  1232. /*
  1233. * btrfs_reloc_clone_csums() error, since start is increased
  1234. * extent_clear_unlock_delalloc() at out_unlock label won't
  1235. * free metadata of current ordered extent, we're OK to exit.
  1236. */
  1237. if (ret)
  1238. goto out_unlock;
  1239. }
  1240. out:
  1241. return ret;
  1242. out_drop_extent_cache:
  1243. btrfs_drop_extent_map_range(inode, start, start + ram_size - 1, false);
  1244. out_reserve:
  1245. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  1246. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  1247. out_unlock:
  1248. /*
  1249. * If done_offset is non-NULL and ret == -EAGAIN, we expect the
  1250. * caller to write out the successfully allocated region and retry.
  1251. */
  1252. if (done_offset && ret == -EAGAIN) {
  1253. if (orig_start < start)
  1254. *done_offset = start - 1;
  1255. else
  1256. *done_offset = start;
  1257. return ret;
  1258. } else if (ret == -EAGAIN) {
  1259. /* Convert to -ENOSPC since the caller cannot retry. */
  1260. ret = -ENOSPC;
  1261. }
  1262. /*
  1263. * Now, we have three regions to clean up:
  1264. *
  1265. * |-------(1)----|---(2)---|-------------(3)----------|
  1266. * `- orig_start `- start `- start + cur_alloc_size `- end
  1267. *
  1268. * We process each region below.
  1269. */
  1270. clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
  1271. EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
  1272. page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
  1273. /*
  1274. * For the range (1). We have already instantiated the ordered extents
  1275. * for this region. They are cleaned up by
  1276. * btrfs_cleanup_ordered_extents() in e.g,
  1277. * btrfs_run_delalloc_range(). EXTENT_LOCKED | EXTENT_DELALLOC are
  1278. * already cleared in the above loop. And, EXTENT_DELALLOC_NEW |
  1279. * EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV are handled by the cleanup
  1280. * function.
  1281. *
  1282. * However, in case of unlock == 0, we still need to unlock the pages
  1283. * (except @locked_page) to ensure all the pages are unlocked.
  1284. */
  1285. if (!unlock && orig_start < start) {
  1286. if (!locked_page)
  1287. mapping_set_error(inode->vfs_inode.i_mapping, ret);
  1288. extent_clear_unlock_delalloc(inode, orig_start, start - 1,
  1289. locked_page, 0, page_ops);
  1290. }
  1291. /*
  1292. * For the range (2). If we reserved an extent for our delalloc range
  1293. * (or a subrange) and failed to create the respective ordered extent,
  1294. * then it means that when we reserved the extent we decremented the
  1295. * extent's size from the data space_info's bytes_may_use counter and
  1296. * incremented the space_info's bytes_reserved counter by the same
  1297. * amount. We must make sure extent_clear_unlock_delalloc() does not try
  1298. * to decrement again the data space_info's bytes_may_use counter,
  1299. * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
  1300. */
  1301. if (extent_reserved) {
  1302. extent_clear_unlock_delalloc(inode, start,
  1303. start + cur_alloc_size - 1,
  1304. locked_page,
  1305. clear_bits,
  1306. page_ops);
  1307. start += cur_alloc_size;
  1308. }
  1309. /*
  1310. * For the range (3). We never touched the region. In addition to the
  1311. * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
  1312. * space_info's bytes_may_use counter, reserved in
  1313. * btrfs_check_data_free_space().
  1314. */
  1315. if (start < end) {
  1316. clear_bits |= EXTENT_CLEAR_DATA_RESV;
  1317. extent_clear_unlock_delalloc(inode, start, end, locked_page,
  1318. clear_bits, page_ops);
  1319. }
  1320. return ret;
  1321. }
  1322. /*
  1323. * work queue call back to started compression on a file and pages
  1324. */
  1325. static noinline void async_cow_start(struct btrfs_work *work)
  1326. {
  1327. struct async_chunk *async_chunk;
  1328. int compressed_extents;
  1329. async_chunk = container_of(work, struct async_chunk, work);
  1330. compressed_extents = compress_file_range(async_chunk);
  1331. if (compressed_extents == 0) {
  1332. btrfs_add_delayed_iput(async_chunk->inode);
  1333. async_chunk->inode = NULL;
  1334. }
  1335. }
  1336. /*
  1337. * work queue call back to submit previously compressed pages
  1338. */
  1339. static noinline void async_cow_submit(struct btrfs_work *work)
  1340. {
  1341. struct async_chunk *async_chunk = container_of(work, struct async_chunk,
  1342. work);
  1343. struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
  1344. unsigned long nr_pages;
  1345. nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
  1346. PAGE_SHIFT;
  1347. /*
  1348. * ->inode could be NULL if async_chunk_start has failed to compress,
  1349. * in which case we don't have anything to submit, yet we need to
  1350. * always adjust ->async_delalloc_pages as its paired with the init
  1351. * happening in cow_file_range_async
  1352. */
  1353. if (async_chunk->inode)
  1354. submit_compressed_extents(async_chunk);
  1355. /* atomic_sub_return implies a barrier */
  1356. if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
  1357. 5 * SZ_1M)
  1358. cond_wake_up_nomb(&fs_info->async_submit_wait);
  1359. }
  1360. static noinline void async_cow_free(struct btrfs_work *work)
  1361. {
  1362. struct async_chunk *async_chunk;
  1363. struct async_cow *async_cow;
  1364. async_chunk = container_of(work, struct async_chunk, work);
  1365. if (async_chunk->inode)
  1366. btrfs_add_delayed_iput(async_chunk->inode);
  1367. if (async_chunk->blkcg_css)
  1368. css_put(async_chunk->blkcg_css);
  1369. async_cow = async_chunk->async_cow;
  1370. if (atomic_dec_and_test(&async_cow->num_chunks))
  1371. kvfree(async_cow);
  1372. }
  1373. static int cow_file_range_async(struct btrfs_inode *inode,
  1374. struct writeback_control *wbc,
  1375. struct page *locked_page,
  1376. u64 start, u64 end, int *page_started,
  1377. unsigned long *nr_written)
  1378. {
  1379. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1380. struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
  1381. struct async_cow *ctx;
  1382. struct async_chunk *async_chunk;
  1383. unsigned long nr_pages;
  1384. u64 cur_end;
  1385. u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
  1386. int i;
  1387. bool should_compress;
  1388. unsigned nofs_flag;
  1389. const blk_opf_t write_flags = wbc_to_write_flags(wbc);
  1390. unlock_extent(&inode->io_tree, start, end, NULL);
  1391. if (inode->flags & BTRFS_INODE_NOCOMPRESS &&
  1392. !btrfs_test_opt(fs_info, FORCE_COMPRESS)) {
  1393. num_chunks = 1;
  1394. should_compress = false;
  1395. } else {
  1396. should_compress = true;
  1397. }
  1398. nofs_flag = memalloc_nofs_save();
  1399. ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
  1400. memalloc_nofs_restore(nofs_flag);
  1401. if (!ctx) {
  1402. unsigned clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC |
  1403. EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
  1404. EXTENT_DO_ACCOUNTING;
  1405. unsigned long page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK |
  1406. PAGE_END_WRITEBACK | PAGE_SET_ERROR;
  1407. extent_clear_unlock_delalloc(inode, start, end, locked_page,
  1408. clear_bits, page_ops);
  1409. return -ENOMEM;
  1410. }
  1411. async_chunk = ctx->chunks;
  1412. atomic_set(&ctx->num_chunks, num_chunks);
  1413. for (i = 0; i < num_chunks; i++) {
  1414. if (should_compress)
  1415. cur_end = min(end, start + SZ_512K - 1);
  1416. else
  1417. cur_end = end;
  1418. /*
  1419. * igrab is called higher up in the call chain, take only the
  1420. * lightweight reference for the callback lifetime
  1421. */
  1422. ihold(&inode->vfs_inode);
  1423. async_chunk[i].async_cow = ctx;
  1424. async_chunk[i].inode = &inode->vfs_inode;
  1425. async_chunk[i].start = start;
  1426. async_chunk[i].end = cur_end;
  1427. async_chunk[i].write_flags = write_flags;
  1428. INIT_LIST_HEAD(&async_chunk[i].extents);
  1429. /*
  1430. * The locked_page comes all the way from writepage and its
  1431. * the original page we were actually given. As we spread
  1432. * this large delalloc region across multiple async_chunk
  1433. * structs, only the first struct needs a pointer to locked_page
  1434. *
  1435. * This way we don't need racey decisions about who is supposed
  1436. * to unlock it.
  1437. */
  1438. if (locked_page) {
  1439. /*
  1440. * Depending on the compressibility, the pages might or
  1441. * might not go through async. We want all of them to
  1442. * be accounted against wbc once. Let's do it here
  1443. * before the paths diverge. wbc accounting is used
  1444. * only for foreign writeback detection and doesn't
  1445. * need full accuracy. Just account the whole thing
  1446. * against the first page.
  1447. */
  1448. wbc_account_cgroup_owner(wbc, locked_page,
  1449. cur_end - start);
  1450. async_chunk[i].locked_page = locked_page;
  1451. locked_page = NULL;
  1452. } else {
  1453. async_chunk[i].locked_page = NULL;
  1454. }
  1455. if (blkcg_css != blkcg_root_css) {
  1456. css_get(blkcg_css);
  1457. async_chunk[i].blkcg_css = blkcg_css;
  1458. } else {
  1459. async_chunk[i].blkcg_css = NULL;
  1460. }
  1461. btrfs_init_work(&async_chunk[i].work, async_cow_start,
  1462. async_cow_submit, async_cow_free);
  1463. nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
  1464. atomic_add(nr_pages, &fs_info->async_delalloc_pages);
  1465. btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
  1466. *nr_written += nr_pages;
  1467. start = cur_end + 1;
  1468. }
  1469. *page_started = 1;
  1470. return 0;
  1471. }
  1472. static noinline int run_delalloc_zoned(struct btrfs_inode *inode,
  1473. struct page *locked_page, u64 start,
  1474. u64 end, int *page_started,
  1475. unsigned long *nr_written)
  1476. {
  1477. u64 done_offset = end;
  1478. int ret;
  1479. bool locked_page_done = false;
  1480. while (start <= end) {
  1481. ret = cow_file_range(inode, locked_page, start, end, page_started,
  1482. nr_written, 0, &done_offset);
  1483. if (ret && ret != -EAGAIN)
  1484. return ret;
  1485. if (*page_started) {
  1486. ASSERT(ret == 0);
  1487. return 0;
  1488. }
  1489. if (ret == 0)
  1490. done_offset = end;
  1491. if (done_offset == start) {
  1492. wait_on_bit_io(&inode->root->fs_info->flags,
  1493. BTRFS_FS_NEED_ZONE_FINISH,
  1494. TASK_UNINTERRUPTIBLE);
  1495. continue;
  1496. }
  1497. if (!locked_page_done) {
  1498. __set_page_dirty_nobuffers(locked_page);
  1499. account_page_redirty(locked_page);
  1500. }
  1501. locked_page_done = true;
  1502. extent_write_locked_range(&inode->vfs_inode, start, done_offset);
  1503. start = done_offset + 1;
  1504. }
  1505. *page_started = 1;
  1506. return 0;
  1507. }
  1508. static noinline int csum_exist_in_range(struct btrfs_fs_info *fs_info,
  1509. u64 bytenr, u64 num_bytes, bool nowait)
  1510. {
  1511. struct btrfs_root *csum_root = btrfs_csum_root(fs_info, bytenr);
  1512. struct btrfs_ordered_sum *sums;
  1513. int ret;
  1514. LIST_HEAD(list);
  1515. ret = btrfs_lookup_csums_range(csum_root, bytenr,
  1516. bytenr + num_bytes - 1, &list, 0,
  1517. nowait);
  1518. if (ret == 0 && list_empty(&list))
  1519. return 0;
  1520. while (!list_empty(&list)) {
  1521. sums = list_entry(list.next, struct btrfs_ordered_sum, list);
  1522. list_del(&sums->list);
  1523. kfree(sums);
  1524. }
  1525. if (ret < 0)
  1526. return ret;
  1527. return 1;
  1528. }
  1529. static int fallback_to_cow(struct btrfs_inode *inode, struct page *locked_page,
  1530. const u64 start, const u64 end,
  1531. int *page_started, unsigned long *nr_written)
  1532. {
  1533. const bool is_space_ino = btrfs_is_free_space_inode(inode);
  1534. const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
  1535. const u64 range_bytes = end + 1 - start;
  1536. struct extent_io_tree *io_tree = &inode->io_tree;
  1537. u64 range_start = start;
  1538. u64 count;
  1539. /*
  1540. * If EXTENT_NORESERVE is set it means that when the buffered write was
  1541. * made we had not enough available data space and therefore we did not
  1542. * reserve data space for it, since we though we could do NOCOW for the
  1543. * respective file range (either there is prealloc extent or the inode
  1544. * has the NOCOW bit set).
  1545. *
  1546. * However when we need to fallback to COW mode (because for example the
  1547. * block group for the corresponding extent was turned to RO mode by a
  1548. * scrub or relocation) we need to do the following:
  1549. *
  1550. * 1) We increment the bytes_may_use counter of the data space info.
  1551. * If COW succeeds, it allocates a new data extent and after doing
  1552. * that it decrements the space info's bytes_may_use counter and
  1553. * increments its bytes_reserved counter by the same amount (we do
  1554. * this at btrfs_add_reserved_bytes()). So we need to increment the
  1555. * bytes_may_use counter to compensate (when space is reserved at
  1556. * buffered write time, the bytes_may_use counter is incremented);
  1557. *
  1558. * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
  1559. * that if the COW path fails for any reason, it decrements (through
  1560. * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
  1561. * data space info, which we incremented in the step above.
  1562. *
  1563. * If we need to fallback to cow and the inode corresponds to a free
  1564. * space cache inode or an inode of the data relocation tree, we must
  1565. * also increment bytes_may_use of the data space_info for the same
  1566. * reason. Space caches and relocated data extents always get a prealloc
  1567. * extent for them, however scrub or balance may have set the block
  1568. * group that contains that extent to RO mode and therefore force COW
  1569. * when starting writeback.
  1570. */
  1571. count = count_range_bits(io_tree, &range_start, end, range_bytes,
  1572. EXTENT_NORESERVE, 0);
  1573. if (count > 0 || is_space_ino || is_reloc_ino) {
  1574. u64 bytes = count;
  1575. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1576. struct btrfs_space_info *sinfo = fs_info->data_sinfo;
  1577. if (is_space_ino || is_reloc_ino)
  1578. bytes = range_bytes;
  1579. spin_lock(&sinfo->lock);
  1580. btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
  1581. spin_unlock(&sinfo->lock);
  1582. if (count > 0)
  1583. clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
  1584. NULL);
  1585. }
  1586. return cow_file_range(inode, locked_page, start, end, page_started,
  1587. nr_written, 1, NULL);
  1588. }
  1589. struct can_nocow_file_extent_args {
  1590. /* Input fields. */
  1591. /* Start file offset of the range we want to NOCOW. */
  1592. u64 start;
  1593. /* End file offset (inclusive) of the range we want to NOCOW. */
  1594. u64 end;
  1595. bool writeback_path;
  1596. bool strict;
  1597. /*
  1598. * Free the path passed to can_nocow_file_extent() once it's not needed
  1599. * anymore.
  1600. */
  1601. bool free_path;
  1602. /* Output fields. Only set when can_nocow_file_extent() returns 1. */
  1603. u64 disk_bytenr;
  1604. u64 disk_num_bytes;
  1605. u64 extent_offset;
  1606. /* Number of bytes that can be written to in NOCOW mode. */
  1607. u64 num_bytes;
  1608. };
  1609. /*
  1610. * Check if we can NOCOW the file extent that the path points to.
  1611. * This function may return with the path released, so the caller should check
  1612. * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
  1613. *
  1614. * Returns: < 0 on error
  1615. * 0 if we can not NOCOW
  1616. * 1 if we can NOCOW
  1617. */
  1618. static int can_nocow_file_extent(struct btrfs_path *path,
  1619. struct btrfs_key *key,
  1620. struct btrfs_inode *inode,
  1621. struct can_nocow_file_extent_args *args)
  1622. {
  1623. const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
  1624. struct extent_buffer *leaf = path->nodes[0];
  1625. struct btrfs_root *root = inode->root;
  1626. struct btrfs_file_extent_item *fi;
  1627. u64 extent_end;
  1628. u8 extent_type;
  1629. int can_nocow = 0;
  1630. int ret = 0;
  1631. bool nowait = path->nowait;
  1632. fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
  1633. extent_type = btrfs_file_extent_type(leaf, fi);
  1634. if (extent_type == BTRFS_FILE_EXTENT_INLINE)
  1635. goto out;
  1636. /* Can't access these fields unless we know it's not an inline extent. */
  1637. args->disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  1638. args->disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  1639. args->extent_offset = btrfs_file_extent_offset(leaf, fi);
  1640. if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
  1641. extent_type == BTRFS_FILE_EXTENT_REG)
  1642. goto out;
  1643. /*
  1644. * If the extent was created before the generation where the last snapshot
  1645. * for its subvolume was created, then this implies the extent is shared,
  1646. * hence we must COW.
  1647. */
  1648. if (!args->strict &&
  1649. btrfs_file_extent_generation(leaf, fi) <=
  1650. btrfs_root_last_snapshot(&root->root_item))
  1651. goto out;
  1652. /* An explicit hole, must COW. */
  1653. if (args->disk_bytenr == 0)
  1654. goto out;
  1655. /* Compressed/encrypted/encoded extents must be COWed. */
  1656. if (btrfs_file_extent_compression(leaf, fi) ||
  1657. btrfs_file_extent_encryption(leaf, fi) ||
  1658. btrfs_file_extent_other_encoding(leaf, fi))
  1659. goto out;
  1660. extent_end = btrfs_file_extent_end(path);
  1661. /*
  1662. * The following checks can be expensive, as they need to take other
  1663. * locks and do btree or rbtree searches, so release the path to avoid
  1664. * blocking other tasks for too long.
  1665. */
  1666. btrfs_release_path(path);
  1667. ret = btrfs_cross_ref_exist(root, btrfs_ino(inode),
  1668. key->offset - args->extent_offset,
  1669. args->disk_bytenr, args->strict, path);
  1670. WARN_ON_ONCE(ret > 0 && is_freespace_inode);
  1671. if (ret != 0)
  1672. goto out;
  1673. if (args->free_path) {
  1674. /*
  1675. * We don't need the path anymore, plus through the
  1676. * csum_exist_in_range() call below we will end up allocating
  1677. * another path. So free the path to avoid unnecessary extra
  1678. * memory usage.
  1679. */
  1680. btrfs_free_path(path);
  1681. path = NULL;
  1682. }
  1683. /* If there are pending snapshots for this root, we must COW. */
  1684. if (args->writeback_path && !is_freespace_inode &&
  1685. atomic_read(&root->snapshot_force_cow))
  1686. goto out;
  1687. args->disk_bytenr += args->extent_offset;
  1688. args->disk_bytenr += args->start - key->offset;
  1689. args->num_bytes = min(args->end + 1, extent_end) - args->start;
  1690. /*
  1691. * Force COW if csums exist in the range. This ensures that csums for a
  1692. * given extent are either valid or do not exist.
  1693. */
  1694. ret = csum_exist_in_range(root->fs_info, args->disk_bytenr, args->num_bytes,
  1695. nowait);
  1696. WARN_ON_ONCE(ret > 0 && is_freespace_inode);
  1697. if (ret != 0)
  1698. goto out;
  1699. can_nocow = 1;
  1700. out:
  1701. if (args->free_path && path)
  1702. btrfs_free_path(path);
  1703. return ret < 0 ? ret : can_nocow;
  1704. }
  1705. /*
  1706. * when nowcow writeback call back. This checks for snapshots or COW copies
  1707. * of the extents that exist in the file, and COWs the file as required.
  1708. *
  1709. * If no cow copies or snapshots exist, we write directly to the existing
  1710. * blocks on disk
  1711. */
  1712. static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
  1713. struct page *locked_page,
  1714. const u64 start, const u64 end,
  1715. int *page_started,
  1716. unsigned long *nr_written)
  1717. {
  1718. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1719. struct btrfs_root *root = inode->root;
  1720. struct btrfs_path *path;
  1721. u64 cow_start = (u64)-1;
  1722. u64 cur_offset = start;
  1723. int ret;
  1724. bool check_prev = true;
  1725. u64 ino = btrfs_ino(inode);
  1726. struct btrfs_block_group *bg;
  1727. bool nocow = false;
  1728. struct can_nocow_file_extent_args nocow_args = { 0 };
  1729. path = btrfs_alloc_path();
  1730. if (!path) {
  1731. extent_clear_unlock_delalloc(inode, start, end, locked_page,
  1732. EXTENT_LOCKED | EXTENT_DELALLOC |
  1733. EXTENT_DO_ACCOUNTING |
  1734. EXTENT_DEFRAG, PAGE_UNLOCK |
  1735. PAGE_START_WRITEBACK |
  1736. PAGE_END_WRITEBACK);
  1737. return -ENOMEM;
  1738. }
  1739. nocow_args.end = end;
  1740. nocow_args.writeback_path = true;
  1741. while (1) {
  1742. struct btrfs_key found_key;
  1743. struct btrfs_file_extent_item *fi;
  1744. struct extent_buffer *leaf;
  1745. u64 extent_end;
  1746. u64 ram_bytes;
  1747. u64 nocow_end;
  1748. int extent_type;
  1749. nocow = false;
  1750. ret = btrfs_lookup_file_extent(NULL, root, path, ino,
  1751. cur_offset, 0);
  1752. if (ret < 0)
  1753. goto error;
  1754. /*
  1755. * If there is no extent for our range when doing the initial
  1756. * search, then go back to the previous slot as it will be the
  1757. * one containing the search offset
  1758. */
  1759. if (ret > 0 && path->slots[0] > 0 && check_prev) {
  1760. leaf = path->nodes[0];
  1761. btrfs_item_key_to_cpu(leaf, &found_key,
  1762. path->slots[0] - 1);
  1763. if (found_key.objectid == ino &&
  1764. found_key.type == BTRFS_EXTENT_DATA_KEY)
  1765. path->slots[0]--;
  1766. }
  1767. check_prev = false;
  1768. next_slot:
  1769. /* Go to next leaf if we have exhausted the current one */
  1770. leaf = path->nodes[0];
  1771. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  1772. ret = btrfs_next_leaf(root, path);
  1773. if (ret < 0) {
  1774. if (cow_start != (u64)-1)
  1775. cur_offset = cow_start;
  1776. goto error;
  1777. }
  1778. if (ret > 0)
  1779. break;
  1780. leaf = path->nodes[0];
  1781. }
  1782. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  1783. /* Didn't find anything for our INO */
  1784. if (found_key.objectid > ino)
  1785. break;
  1786. /*
  1787. * Keep searching until we find an EXTENT_ITEM or there are no
  1788. * more extents for this inode
  1789. */
  1790. if (WARN_ON_ONCE(found_key.objectid < ino) ||
  1791. found_key.type < BTRFS_EXTENT_DATA_KEY) {
  1792. path->slots[0]++;
  1793. goto next_slot;
  1794. }
  1795. /* Found key is not EXTENT_DATA_KEY or starts after req range */
  1796. if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
  1797. found_key.offset > end)
  1798. break;
  1799. /*
  1800. * If the found extent starts after requested offset, then
  1801. * adjust extent_end to be right before this extent begins
  1802. */
  1803. if (found_key.offset > cur_offset) {
  1804. extent_end = found_key.offset;
  1805. extent_type = 0;
  1806. goto out_check;
  1807. }
  1808. /*
  1809. * Found extent which begins before our range and potentially
  1810. * intersect it
  1811. */
  1812. fi = btrfs_item_ptr(leaf, path->slots[0],
  1813. struct btrfs_file_extent_item);
  1814. extent_type = btrfs_file_extent_type(leaf, fi);
  1815. /* If this is triggered then we have a memory corruption. */
  1816. ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
  1817. if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
  1818. ret = -EUCLEAN;
  1819. goto error;
  1820. }
  1821. ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
  1822. extent_end = btrfs_file_extent_end(path);
  1823. /*
  1824. * If the extent we got ends before our current offset, skip to
  1825. * the next extent.
  1826. */
  1827. if (extent_end <= cur_offset) {
  1828. path->slots[0]++;
  1829. goto next_slot;
  1830. }
  1831. nocow_args.start = cur_offset;
  1832. ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
  1833. if (ret < 0) {
  1834. if (cow_start != (u64)-1)
  1835. cur_offset = cow_start;
  1836. goto error;
  1837. } else if (ret == 0) {
  1838. goto out_check;
  1839. }
  1840. ret = 0;
  1841. bg = btrfs_inc_nocow_writers(fs_info, nocow_args.disk_bytenr);
  1842. if (bg)
  1843. nocow = true;
  1844. out_check:
  1845. /*
  1846. * If nocow is false then record the beginning of the range
  1847. * that needs to be COWed
  1848. */
  1849. if (!nocow) {
  1850. if (cow_start == (u64)-1)
  1851. cow_start = cur_offset;
  1852. cur_offset = extent_end;
  1853. if (cur_offset > end)
  1854. break;
  1855. if (!path->nodes[0])
  1856. continue;
  1857. path->slots[0]++;
  1858. goto next_slot;
  1859. }
  1860. /*
  1861. * COW range from cow_start to found_key.offset - 1. As the key
  1862. * will contain the beginning of the first extent that can be
  1863. * NOCOW, following one which needs to be COW'ed
  1864. */
  1865. if (cow_start != (u64)-1) {
  1866. ret = fallback_to_cow(inode, locked_page,
  1867. cow_start, found_key.offset - 1,
  1868. page_started, nr_written);
  1869. if (ret)
  1870. goto error;
  1871. cow_start = (u64)-1;
  1872. }
  1873. nocow_end = cur_offset + nocow_args.num_bytes - 1;
  1874. if (extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  1875. u64 orig_start = found_key.offset - nocow_args.extent_offset;
  1876. struct extent_map *em;
  1877. em = create_io_em(inode, cur_offset, nocow_args.num_bytes,
  1878. orig_start,
  1879. nocow_args.disk_bytenr, /* block_start */
  1880. nocow_args.num_bytes, /* block_len */
  1881. nocow_args.disk_num_bytes, /* orig_block_len */
  1882. ram_bytes, BTRFS_COMPRESS_NONE,
  1883. BTRFS_ORDERED_PREALLOC);
  1884. if (IS_ERR(em)) {
  1885. ret = PTR_ERR(em);
  1886. goto error;
  1887. }
  1888. free_extent_map(em);
  1889. ret = btrfs_add_ordered_extent(inode,
  1890. cur_offset, nocow_args.num_bytes,
  1891. nocow_args.num_bytes,
  1892. nocow_args.disk_bytenr,
  1893. nocow_args.num_bytes, 0,
  1894. 1 << BTRFS_ORDERED_PREALLOC,
  1895. BTRFS_COMPRESS_NONE);
  1896. if (ret) {
  1897. btrfs_drop_extent_map_range(inode, cur_offset,
  1898. nocow_end, false);
  1899. goto error;
  1900. }
  1901. } else {
  1902. ret = btrfs_add_ordered_extent(inode, cur_offset,
  1903. nocow_args.num_bytes,
  1904. nocow_args.num_bytes,
  1905. nocow_args.disk_bytenr,
  1906. nocow_args.num_bytes,
  1907. 0,
  1908. 1 << BTRFS_ORDERED_NOCOW,
  1909. BTRFS_COMPRESS_NONE);
  1910. if (ret)
  1911. goto error;
  1912. }
  1913. if (nocow) {
  1914. btrfs_dec_nocow_writers(bg);
  1915. nocow = false;
  1916. }
  1917. if (btrfs_is_data_reloc_root(root))
  1918. /*
  1919. * Error handled later, as we must prevent
  1920. * extent_clear_unlock_delalloc() in error handler
  1921. * from freeing metadata of created ordered extent.
  1922. */
  1923. ret = btrfs_reloc_clone_csums(inode, cur_offset,
  1924. nocow_args.num_bytes);
  1925. extent_clear_unlock_delalloc(inode, cur_offset, nocow_end,
  1926. locked_page, EXTENT_LOCKED |
  1927. EXTENT_DELALLOC |
  1928. EXTENT_CLEAR_DATA_RESV,
  1929. PAGE_UNLOCK | PAGE_SET_ORDERED);
  1930. cur_offset = extent_end;
  1931. /*
  1932. * btrfs_reloc_clone_csums() error, now we're OK to call error
  1933. * handler, as metadata for created ordered extent will only
  1934. * be freed by btrfs_finish_ordered_io().
  1935. */
  1936. if (ret)
  1937. goto error;
  1938. if (cur_offset > end)
  1939. break;
  1940. }
  1941. btrfs_release_path(path);
  1942. if (cur_offset <= end && cow_start == (u64)-1)
  1943. cow_start = cur_offset;
  1944. if (cow_start != (u64)-1) {
  1945. cur_offset = end;
  1946. ret = fallback_to_cow(inode, locked_page, cow_start, end,
  1947. page_started, nr_written);
  1948. if (ret)
  1949. goto error;
  1950. }
  1951. error:
  1952. if (nocow)
  1953. btrfs_dec_nocow_writers(bg);
  1954. if (ret && cur_offset < end)
  1955. extent_clear_unlock_delalloc(inode, cur_offset, end,
  1956. locked_page, EXTENT_LOCKED |
  1957. EXTENT_DELALLOC | EXTENT_DEFRAG |
  1958. EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
  1959. PAGE_START_WRITEBACK |
  1960. PAGE_END_WRITEBACK);
  1961. btrfs_free_path(path);
  1962. return ret;
  1963. }
  1964. static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
  1965. {
  1966. if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
  1967. if (inode->defrag_bytes &&
  1968. test_range_bit(&inode->io_tree, start, end, EXTENT_DEFRAG,
  1969. 0, NULL))
  1970. return false;
  1971. return true;
  1972. }
  1973. return false;
  1974. }
  1975. /*
  1976. * Function to process delayed allocation (create CoW) for ranges which are
  1977. * being touched for the first time.
  1978. */
  1979. int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct page *locked_page,
  1980. u64 start, u64 end, int *page_started, unsigned long *nr_written,
  1981. struct writeback_control *wbc)
  1982. {
  1983. int ret;
  1984. const bool zoned = btrfs_is_zoned(inode->root->fs_info);
  1985. /*
  1986. * The range must cover part of the @locked_page, or the returned
  1987. * @page_started can confuse the caller.
  1988. */
  1989. ASSERT(!(end <= page_offset(locked_page) ||
  1990. start >= page_offset(locked_page) + PAGE_SIZE));
  1991. if (should_nocow(inode, start, end)) {
  1992. /*
  1993. * Normally on a zoned device we're only doing COW writes, but
  1994. * in case of relocation on a zoned filesystem we have taken
  1995. * precaution, that we're only writing sequentially. It's safe
  1996. * to use run_delalloc_nocow() here, like for regular
  1997. * preallocated inodes.
  1998. */
  1999. ASSERT(!zoned || btrfs_is_data_reloc_root(inode->root));
  2000. ret = run_delalloc_nocow(inode, locked_page, start, end,
  2001. page_started, nr_written);
  2002. } else if (!btrfs_inode_can_compress(inode) ||
  2003. !inode_need_compress(inode, start, end)) {
  2004. if (zoned)
  2005. ret = run_delalloc_zoned(inode, locked_page, start, end,
  2006. page_started, nr_written);
  2007. else
  2008. ret = cow_file_range(inode, locked_page, start, end,
  2009. page_started, nr_written, 1, NULL);
  2010. } else {
  2011. set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
  2012. ret = cow_file_range_async(inode, wbc, locked_page, start, end,
  2013. page_started, nr_written);
  2014. }
  2015. ASSERT(ret <= 0);
  2016. if (ret)
  2017. btrfs_cleanup_ordered_extents(inode, locked_page, start,
  2018. end - start + 1);
  2019. return ret;
  2020. }
  2021. void btrfs_split_delalloc_extent(struct inode *inode,
  2022. struct extent_state *orig, u64 split)
  2023. {
  2024. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2025. u64 size;
  2026. /* not delalloc, ignore it */
  2027. if (!(orig->state & EXTENT_DELALLOC))
  2028. return;
  2029. size = orig->end - orig->start + 1;
  2030. if (size > fs_info->max_extent_size) {
  2031. u32 num_extents;
  2032. u64 new_size;
  2033. /*
  2034. * See the explanation in btrfs_merge_delalloc_extent, the same
  2035. * applies here, just in reverse.
  2036. */
  2037. new_size = orig->end - split + 1;
  2038. num_extents = count_max_extents(fs_info, new_size);
  2039. new_size = split - orig->start;
  2040. num_extents += count_max_extents(fs_info, new_size);
  2041. if (count_max_extents(fs_info, size) >= num_extents)
  2042. return;
  2043. }
  2044. spin_lock(&BTRFS_I(inode)->lock);
  2045. btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
  2046. spin_unlock(&BTRFS_I(inode)->lock);
  2047. }
  2048. /*
  2049. * Handle merged delayed allocation extents so we can keep track of new extents
  2050. * that are just merged onto old extents, such as when we are doing sequential
  2051. * writes, so we can properly account for the metadata space we'll need.
  2052. */
  2053. void btrfs_merge_delalloc_extent(struct inode *inode, struct extent_state *new,
  2054. struct extent_state *other)
  2055. {
  2056. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2057. u64 new_size, old_size;
  2058. u32 num_extents;
  2059. /* not delalloc, ignore it */
  2060. if (!(other->state & EXTENT_DELALLOC))
  2061. return;
  2062. if (new->start > other->start)
  2063. new_size = new->end - other->start + 1;
  2064. else
  2065. new_size = other->end - new->start + 1;
  2066. /* we're not bigger than the max, unreserve the space and go */
  2067. if (new_size <= fs_info->max_extent_size) {
  2068. spin_lock(&BTRFS_I(inode)->lock);
  2069. btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
  2070. spin_unlock(&BTRFS_I(inode)->lock);
  2071. return;
  2072. }
  2073. /*
  2074. * We have to add up either side to figure out how many extents were
  2075. * accounted for before we merged into one big extent. If the number of
  2076. * extents we accounted for is <= the amount we need for the new range
  2077. * then we can return, otherwise drop. Think of it like this
  2078. *
  2079. * [ 4k][MAX_SIZE]
  2080. *
  2081. * So we've grown the extent by a MAX_SIZE extent, this would mean we
  2082. * need 2 outstanding extents, on one side we have 1 and the other side
  2083. * we have 1 so they are == and we can return. But in this case
  2084. *
  2085. * [MAX_SIZE+4k][MAX_SIZE+4k]
  2086. *
  2087. * Each range on their own accounts for 2 extents, but merged together
  2088. * they are only 3 extents worth of accounting, so we need to drop in
  2089. * this case.
  2090. */
  2091. old_size = other->end - other->start + 1;
  2092. num_extents = count_max_extents(fs_info, old_size);
  2093. old_size = new->end - new->start + 1;
  2094. num_extents += count_max_extents(fs_info, old_size);
  2095. if (count_max_extents(fs_info, new_size) >= num_extents)
  2096. return;
  2097. spin_lock(&BTRFS_I(inode)->lock);
  2098. btrfs_mod_outstanding_extents(BTRFS_I(inode), -1);
  2099. spin_unlock(&BTRFS_I(inode)->lock);
  2100. }
  2101. static void btrfs_add_delalloc_inodes(struct btrfs_root *root,
  2102. struct inode *inode)
  2103. {
  2104. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2105. spin_lock(&root->delalloc_lock);
  2106. if (list_empty(&BTRFS_I(inode)->delalloc_inodes)) {
  2107. list_add_tail(&BTRFS_I(inode)->delalloc_inodes,
  2108. &root->delalloc_inodes);
  2109. set_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  2110. &BTRFS_I(inode)->runtime_flags);
  2111. root->nr_delalloc_inodes++;
  2112. if (root->nr_delalloc_inodes == 1) {
  2113. spin_lock(&fs_info->delalloc_root_lock);
  2114. BUG_ON(!list_empty(&root->delalloc_root));
  2115. list_add_tail(&root->delalloc_root,
  2116. &fs_info->delalloc_roots);
  2117. spin_unlock(&fs_info->delalloc_root_lock);
  2118. }
  2119. }
  2120. spin_unlock(&root->delalloc_lock);
  2121. }
  2122. void __btrfs_del_delalloc_inode(struct btrfs_root *root,
  2123. struct btrfs_inode *inode)
  2124. {
  2125. struct btrfs_fs_info *fs_info = root->fs_info;
  2126. if (!list_empty(&inode->delalloc_inodes)) {
  2127. list_del_init(&inode->delalloc_inodes);
  2128. clear_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  2129. &inode->runtime_flags);
  2130. root->nr_delalloc_inodes--;
  2131. if (!root->nr_delalloc_inodes) {
  2132. ASSERT(list_empty(&root->delalloc_inodes));
  2133. spin_lock(&fs_info->delalloc_root_lock);
  2134. BUG_ON(list_empty(&root->delalloc_root));
  2135. list_del_init(&root->delalloc_root);
  2136. spin_unlock(&fs_info->delalloc_root_lock);
  2137. }
  2138. }
  2139. }
  2140. static void btrfs_del_delalloc_inode(struct btrfs_root *root,
  2141. struct btrfs_inode *inode)
  2142. {
  2143. spin_lock(&root->delalloc_lock);
  2144. __btrfs_del_delalloc_inode(root, inode);
  2145. spin_unlock(&root->delalloc_lock);
  2146. }
  2147. /*
  2148. * Properly track delayed allocation bytes in the inode and to maintain the
  2149. * list of inodes that have pending delalloc work to be done.
  2150. */
  2151. void btrfs_set_delalloc_extent(struct inode *inode, struct extent_state *state,
  2152. u32 bits)
  2153. {
  2154. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2155. if ((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC))
  2156. WARN_ON(1);
  2157. /*
  2158. * set_bit and clear bit hooks normally require _irqsave/restore
  2159. * but in this case, we are only testing for the DELALLOC
  2160. * bit, which is only set or cleared with irqs on
  2161. */
  2162. if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
  2163. struct btrfs_root *root = BTRFS_I(inode)->root;
  2164. u64 len = state->end + 1 - state->start;
  2165. u32 num_extents = count_max_extents(fs_info, len);
  2166. bool do_list = !btrfs_is_free_space_inode(BTRFS_I(inode));
  2167. spin_lock(&BTRFS_I(inode)->lock);
  2168. btrfs_mod_outstanding_extents(BTRFS_I(inode), num_extents);
  2169. spin_unlock(&BTRFS_I(inode)->lock);
  2170. /* For sanity tests */
  2171. if (btrfs_is_testing(fs_info))
  2172. return;
  2173. percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
  2174. fs_info->delalloc_batch);
  2175. spin_lock(&BTRFS_I(inode)->lock);
  2176. BTRFS_I(inode)->delalloc_bytes += len;
  2177. if (bits & EXTENT_DEFRAG)
  2178. BTRFS_I(inode)->defrag_bytes += len;
  2179. if (do_list && !test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  2180. &BTRFS_I(inode)->runtime_flags))
  2181. btrfs_add_delalloc_inodes(root, inode);
  2182. spin_unlock(&BTRFS_I(inode)->lock);
  2183. }
  2184. if (!(state->state & EXTENT_DELALLOC_NEW) &&
  2185. (bits & EXTENT_DELALLOC_NEW)) {
  2186. spin_lock(&BTRFS_I(inode)->lock);
  2187. BTRFS_I(inode)->new_delalloc_bytes += state->end + 1 -
  2188. state->start;
  2189. spin_unlock(&BTRFS_I(inode)->lock);
  2190. }
  2191. }
  2192. /*
  2193. * Once a range is no longer delalloc this function ensures that proper
  2194. * accounting happens.
  2195. */
  2196. void btrfs_clear_delalloc_extent(struct inode *vfs_inode,
  2197. struct extent_state *state, u32 bits)
  2198. {
  2199. struct btrfs_inode *inode = BTRFS_I(vfs_inode);
  2200. struct btrfs_fs_info *fs_info = btrfs_sb(vfs_inode->i_sb);
  2201. u64 len = state->end + 1 - state->start;
  2202. u32 num_extents = count_max_extents(fs_info, len);
  2203. if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
  2204. spin_lock(&inode->lock);
  2205. inode->defrag_bytes -= len;
  2206. spin_unlock(&inode->lock);
  2207. }
  2208. /*
  2209. * set_bit and clear bit hooks normally require _irqsave/restore
  2210. * but in this case, we are only testing for the DELALLOC
  2211. * bit, which is only set or cleared with irqs on
  2212. */
  2213. if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
  2214. struct btrfs_root *root = inode->root;
  2215. bool do_list = !btrfs_is_free_space_inode(inode);
  2216. spin_lock(&inode->lock);
  2217. btrfs_mod_outstanding_extents(inode, -num_extents);
  2218. spin_unlock(&inode->lock);
  2219. /*
  2220. * We don't reserve metadata space for space cache inodes so we
  2221. * don't need to call delalloc_release_metadata if there is an
  2222. * error.
  2223. */
  2224. if (bits & EXTENT_CLEAR_META_RESV &&
  2225. root != fs_info->tree_root)
  2226. btrfs_delalloc_release_metadata(inode, len, false);
  2227. /* For sanity tests. */
  2228. if (btrfs_is_testing(fs_info))
  2229. return;
  2230. if (!btrfs_is_data_reloc_root(root) &&
  2231. do_list && !(state->state & EXTENT_NORESERVE) &&
  2232. (bits & EXTENT_CLEAR_DATA_RESV))
  2233. btrfs_free_reserved_data_space_noquota(fs_info, len);
  2234. percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
  2235. fs_info->delalloc_batch);
  2236. spin_lock(&inode->lock);
  2237. inode->delalloc_bytes -= len;
  2238. if (do_list && inode->delalloc_bytes == 0 &&
  2239. test_bit(BTRFS_INODE_IN_DELALLOC_LIST,
  2240. &inode->runtime_flags))
  2241. btrfs_del_delalloc_inode(root, inode);
  2242. spin_unlock(&inode->lock);
  2243. }
  2244. if ((state->state & EXTENT_DELALLOC_NEW) &&
  2245. (bits & EXTENT_DELALLOC_NEW)) {
  2246. spin_lock(&inode->lock);
  2247. ASSERT(inode->new_delalloc_bytes >= len);
  2248. inode->new_delalloc_bytes -= len;
  2249. if (bits & EXTENT_ADD_INODE_BYTES)
  2250. inode_add_bytes(&inode->vfs_inode, len);
  2251. spin_unlock(&inode->lock);
  2252. }
  2253. }
  2254. /*
  2255. * in order to insert checksums into the metadata in large chunks,
  2256. * we wait until bio submission time. All the pages in the bio are
  2257. * checksummed and sums are attached onto the ordered extent record.
  2258. *
  2259. * At IO completion time the cums attached on the ordered extent record
  2260. * are inserted into the btree
  2261. */
  2262. static blk_status_t btrfs_submit_bio_start(struct inode *inode, struct bio *bio,
  2263. u64 dio_file_offset)
  2264. {
  2265. return btrfs_csum_one_bio(BTRFS_I(inode), bio, (u64)-1, false);
  2266. }
  2267. /*
  2268. * Split an extent_map at [start, start + len]
  2269. *
  2270. * This function is intended to be used only for extract_ordered_extent().
  2271. */
  2272. static int split_zoned_em(struct btrfs_inode *inode, u64 start, u64 len,
  2273. u64 pre, u64 post)
  2274. {
  2275. struct extent_map_tree *em_tree = &inode->extent_tree;
  2276. struct extent_map *em;
  2277. struct extent_map *split_pre = NULL;
  2278. struct extent_map *split_mid = NULL;
  2279. struct extent_map *split_post = NULL;
  2280. int ret = 0;
  2281. unsigned long flags;
  2282. /* Sanity check */
  2283. if (pre == 0 && post == 0)
  2284. return 0;
  2285. split_pre = alloc_extent_map();
  2286. if (pre)
  2287. split_mid = alloc_extent_map();
  2288. if (post)
  2289. split_post = alloc_extent_map();
  2290. if (!split_pre || (pre && !split_mid) || (post && !split_post)) {
  2291. ret = -ENOMEM;
  2292. goto out;
  2293. }
  2294. ASSERT(pre + post < len);
  2295. lock_extent(&inode->io_tree, start, start + len - 1, NULL);
  2296. write_lock(&em_tree->lock);
  2297. em = lookup_extent_mapping(em_tree, start, len);
  2298. if (!em) {
  2299. ret = -EIO;
  2300. goto out_unlock;
  2301. }
  2302. ASSERT(em->len == len);
  2303. ASSERT(!test_bit(EXTENT_FLAG_COMPRESSED, &em->flags));
  2304. ASSERT(em->block_start < EXTENT_MAP_LAST_BYTE);
  2305. ASSERT(test_bit(EXTENT_FLAG_PINNED, &em->flags));
  2306. ASSERT(!test_bit(EXTENT_FLAG_LOGGING, &em->flags));
  2307. ASSERT(!list_empty(&em->list));
  2308. flags = em->flags;
  2309. clear_bit(EXTENT_FLAG_PINNED, &em->flags);
  2310. /* First, replace the em with a new extent_map starting from * em->start */
  2311. split_pre->start = em->start;
  2312. split_pre->len = (pre ? pre : em->len - post);
  2313. split_pre->orig_start = split_pre->start;
  2314. split_pre->block_start = em->block_start;
  2315. split_pre->block_len = split_pre->len;
  2316. split_pre->orig_block_len = split_pre->block_len;
  2317. split_pre->ram_bytes = split_pre->len;
  2318. split_pre->flags = flags;
  2319. split_pre->compress_type = em->compress_type;
  2320. split_pre->generation = em->generation;
  2321. replace_extent_mapping(em_tree, em, split_pre, 1);
  2322. /*
  2323. * Now we only have an extent_map at:
  2324. * [em->start, em->start + pre] if pre != 0
  2325. * [em->start, em->start + em->len - post] if pre == 0
  2326. */
  2327. if (pre) {
  2328. /* Insert the middle extent_map */
  2329. split_mid->start = em->start + pre;
  2330. split_mid->len = em->len - pre - post;
  2331. split_mid->orig_start = split_mid->start;
  2332. split_mid->block_start = em->block_start + pre;
  2333. split_mid->block_len = split_mid->len;
  2334. split_mid->orig_block_len = split_mid->block_len;
  2335. split_mid->ram_bytes = split_mid->len;
  2336. split_mid->flags = flags;
  2337. split_mid->compress_type = em->compress_type;
  2338. split_mid->generation = em->generation;
  2339. add_extent_mapping(em_tree, split_mid, 1);
  2340. }
  2341. if (post) {
  2342. split_post->start = em->start + em->len - post;
  2343. split_post->len = post;
  2344. split_post->orig_start = split_post->start;
  2345. split_post->block_start = em->block_start + em->len - post;
  2346. split_post->block_len = split_post->len;
  2347. split_post->orig_block_len = split_post->block_len;
  2348. split_post->ram_bytes = split_post->len;
  2349. split_post->flags = flags;
  2350. split_post->compress_type = em->compress_type;
  2351. split_post->generation = em->generation;
  2352. add_extent_mapping(em_tree, split_post, 1);
  2353. }
  2354. /* Once for us */
  2355. free_extent_map(em);
  2356. /* Once for the tree */
  2357. free_extent_map(em);
  2358. out_unlock:
  2359. write_unlock(&em_tree->lock);
  2360. unlock_extent(&inode->io_tree, start, start + len - 1, NULL);
  2361. out:
  2362. free_extent_map(split_pre);
  2363. free_extent_map(split_mid);
  2364. free_extent_map(split_post);
  2365. return ret;
  2366. }
  2367. static blk_status_t extract_ordered_extent(struct btrfs_inode *inode,
  2368. struct bio *bio, loff_t file_offset)
  2369. {
  2370. struct btrfs_ordered_extent *ordered;
  2371. u64 start = (u64)bio->bi_iter.bi_sector << SECTOR_SHIFT;
  2372. u64 file_len;
  2373. u64 len = bio->bi_iter.bi_size;
  2374. u64 end = start + len;
  2375. u64 ordered_end;
  2376. u64 pre, post;
  2377. int ret = 0;
  2378. ordered = btrfs_lookup_ordered_extent(inode, file_offset);
  2379. if (WARN_ON_ONCE(!ordered))
  2380. return BLK_STS_IOERR;
  2381. /* No need to split */
  2382. if (ordered->disk_num_bytes == len)
  2383. goto out;
  2384. /* We cannot split once end_bio'd ordered extent */
  2385. if (WARN_ON_ONCE(ordered->bytes_left != ordered->disk_num_bytes)) {
  2386. ret = -EINVAL;
  2387. goto out;
  2388. }
  2389. /* We cannot split a compressed ordered extent */
  2390. if (WARN_ON_ONCE(ordered->disk_num_bytes != ordered->num_bytes)) {
  2391. ret = -EINVAL;
  2392. goto out;
  2393. }
  2394. ordered_end = ordered->disk_bytenr + ordered->disk_num_bytes;
  2395. /* bio must be in one ordered extent */
  2396. if (WARN_ON_ONCE(start < ordered->disk_bytenr || end > ordered_end)) {
  2397. ret = -EINVAL;
  2398. goto out;
  2399. }
  2400. /* Checksum list should be empty */
  2401. if (WARN_ON_ONCE(!list_empty(&ordered->list))) {
  2402. ret = -EINVAL;
  2403. goto out;
  2404. }
  2405. file_len = ordered->num_bytes;
  2406. pre = start - ordered->disk_bytenr;
  2407. post = ordered_end - end;
  2408. ret = btrfs_split_ordered_extent(ordered, pre, post);
  2409. if (ret)
  2410. goto out;
  2411. ret = split_zoned_em(inode, file_offset, file_len, pre, post);
  2412. out:
  2413. btrfs_put_ordered_extent(ordered);
  2414. return errno_to_blk_status(ret);
  2415. }
  2416. void btrfs_submit_data_write_bio(struct inode *inode, struct bio *bio, int mirror_num)
  2417. {
  2418. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2419. struct btrfs_inode *bi = BTRFS_I(inode);
  2420. blk_status_t ret;
  2421. if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
  2422. ret = extract_ordered_extent(bi, bio,
  2423. page_offset(bio_first_bvec_all(bio)->bv_page));
  2424. if (ret) {
  2425. btrfs_bio_end_io(btrfs_bio(bio), ret);
  2426. return;
  2427. }
  2428. }
  2429. /*
  2430. * If we need to checksum, and the I/O is not issued by fsync and
  2431. * friends, that is ->sync_writers != 0, defer the submission to a
  2432. * workqueue to parallelize it.
  2433. *
  2434. * Csum items for reloc roots have already been cloned at this point,
  2435. * so they are handled as part of the no-checksum case.
  2436. */
  2437. if (!(bi->flags & BTRFS_INODE_NODATASUM) &&
  2438. !test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state) &&
  2439. !btrfs_is_data_reloc_root(bi->root)) {
  2440. if (!atomic_read(&bi->sync_writers) &&
  2441. btrfs_wq_submit_bio(inode, bio, mirror_num, 0,
  2442. btrfs_submit_bio_start))
  2443. return;
  2444. ret = btrfs_csum_one_bio(bi, bio, (u64)-1, false);
  2445. if (ret) {
  2446. btrfs_bio_end_io(btrfs_bio(bio), ret);
  2447. return;
  2448. }
  2449. }
  2450. btrfs_submit_bio(fs_info, bio, mirror_num);
  2451. }
  2452. void btrfs_submit_data_read_bio(struct inode *inode, struct bio *bio,
  2453. int mirror_num, enum btrfs_compression_type compress_type)
  2454. {
  2455. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2456. blk_status_t ret;
  2457. if (compress_type != BTRFS_COMPRESS_NONE) {
  2458. /*
  2459. * btrfs_submit_compressed_read will handle completing the bio
  2460. * if there were any errors, so just return here.
  2461. */
  2462. btrfs_submit_compressed_read(inode, bio, mirror_num);
  2463. return;
  2464. }
  2465. /* Save the original iter for read repair */
  2466. btrfs_bio(bio)->iter = bio->bi_iter;
  2467. /*
  2468. * Lookup bio sums does extra checks around whether we need to csum or
  2469. * not, which is why we ignore skip_sum here.
  2470. */
  2471. ret = btrfs_lookup_bio_sums(inode, bio, NULL);
  2472. if (ret) {
  2473. btrfs_bio_end_io(btrfs_bio(bio), ret);
  2474. return;
  2475. }
  2476. btrfs_submit_bio(fs_info, bio, mirror_num);
  2477. }
  2478. /*
  2479. * given a list of ordered sums record them in the inode. This happens
  2480. * at IO completion time based on sums calculated at bio submission time.
  2481. */
  2482. static int add_pending_csums(struct btrfs_trans_handle *trans,
  2483. struct list_head *list)
  2484. {
  2485. struct btrfs_ordered_sum *sum;
  2486. struct btrfs_root *csum_root = NULL;
  2487. int ret;
  2488. list_for_each_entry(sum, list, list) {
  2489. trans->adding_csums = true;
  2490. if (!csum_root)
  2491. csum_root = btrfs_csum_root(trans->fs_info,
  2492. sum->bytenr);
  2493. ret = btrfs_csum_file_blocks(trans, csum_root, sum);
  2494. trans->adding_csums = false;
  2495. if (ret)
  2496. return ret;
  2497. }
  2498. return 0;
  2499. }
  2500. static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
  2501. const u64 start,
  2502. const u64 len,
  2503. struct extent_state **cached_state)
  2504. {
  2505. u64 search_start = start;
  2506. const u64 end = start + len - 1;
  2507. while (search_start < end) {
  2508. const u64 search_len = end - search_start + 1;
  2509. struct extent_map *em;
  2510. u64 em_len;
  2511. int ret = 0;
  2512. em = btrfs_get_extent(inode, NULL, 0, search_start, search_len);
  2513. if (IS_ERR(em))
  2514. return PTR_ERR(em);
  2515. if (em->block_start != EXTENT_MAP_HOLE)
  2516. goto next;
  2517. em_len = em->len;
  2518. if (em->start < search_start)
  2519. em_len -= search_start - em->start;
  2520. if (em_len > search_len)
  2521. em_len = search_len;
  2522. ret = set_extent_bit(&inode->io_tree, search_start,
  2523. search_start + em_len - 1,
  2524. EXTENT_DELALLOC_NEW, cached_state,
  2525. GFP_NOFS);
  2526. next:
  2527. search_start = extent_map_end(em);
  2528. free_extent_map(em);
  2529. if (ret)
  2530. return ret;
  2531. }
  2532. return 0;
  2533. }
  2534. int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
  2535. unsigned int extra_bits,
  2536. struct extent_state **cached_state)
  2537. {
  2538. WARN_ON(PAGE_ALIGNED(end));
  2539. if (start >= i_size_read(&inode->vfs_inode) &&
  2540. !(inode->flags & BTRFS_INODE_PREALLOC)) {
  2541. /*
  2542. * There can't be any extents following eof in this case so just
  2543. * set the delalloc new bit for the range directly.
  2544. */
  2545. extra_bits |= EXTENT_DELALLOC_NEW;
  2546. } else {
  2547. int ret;
  2548. ret = btrfs_find_new_delalloc_bytes(inode, start,
  2549. end + 1 - start,
  2550. cached_state);
  2551. if (ret)
  2552. return ret;
  2553. }
  2554. return set_extent_delalloc(&inode->io_tree, start, end, extra_bits,
  2555. cached_state);
  2556. }
  2557. /* see btrfs_writepage_start_hook for details on why this is required */
  2558. struct btrfs_writepage_fixup {
  2559. struct page *page;
  2560. struct inode *inode;
  2561. struct btrfs_work work;
  2562. };
  2563. static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
  2564. {
  2565. struct btrfs_writepage_fixup *fixup;
  2566. struct btrfs_ordered_extent *ordered;
  2567. struct extent_state *cached_state = NULL;
  2568. struct extent_changeset *data_reserved = NULL;
  2569. struct page *page;
  2570. struct btrfs_inode *inode;
  2571. u64 page_start;
  2572. u64 page_end;
  2573. int ret = 0;
  2574. bool free_delalloc_space = true;
  2575. fixup = container_of(work, struct btrfs_writepage_fixup, work);
  2576. page = fixup->page;
  2577. inode = BTRFS_I(fixup->inode);
  2578. page_start = page_offset(page);
  2579. page_end = page_offset(page) + PAGE_SIZE - 1;
  2580. /*
  2581. * This is similar to page_mkwrite, we need to reserve the space before
  2582. * we take the page lock.
  2583. */
  2584. ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
  2585. PAGE_SIZE);
  2586. again:
  2587. lock_page(page);
  2588. /*
  2589. * Before we queued this fixup, we took a reference on the page.
  2590. * page->mapping may go NULL, but it shouldn't be moved to a different
  2591. * address space.
  2592. */
  2593. if (!page->mapping || !PageDirty(page) || !PageChecked(page)) {
  2594. /*
  2595. * Unfortunately this is a little tricky, either
  2596. *
  2597. * 1) We got here and our page had already been dealt with and
  2598. * we reserved our space, thus ret == 0, so we need to just
  2599. * drop our space reservation and bail. This can happen the
  2600. * first time we come into the fixup worker, or could happen
  2601. * while waiting for the ordered extent.
  2602. * 2) Our page was already dealt with, but we happened to get an
  2603. * ENOSPC above from the btrfs_delalloc_reserve_space. In
  2604. * this case we obviously don't have anything to release, but
  2605. * because the page was already dealt with we don't want to
  2606. * mark the page with an error, so make sure we're resetting
  2607. * ret to 0. This is why we have this check _before_ the ret
  2608. * check, because we do not want to have a surprise ENOSPC
  2609. * when the page was already properly dealt with.
  2610. */
  2611. if (!ret) {
  2612. btrfs_delalloc_release_extents(inode, PAGE_SIZE);
  2613. btrfs_delalloc_release_space(inode, data_reserved,
  2614. page_start, PAGE_SIZE,
  2615. true);
  2616. }
  2617. ret = 0;
  2618. goto out_page;
  2619. }
  2620. /*
  2621. * We can't mess with the page state unless it is locked, so now that
  2622. * it is locked bail if we failed to make our space reservation.
  2623. */
  2624. if (ret)
  2625. goto out_page;
  2626. lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
  2627. /* already ordered? We're done */
  2628. if (PageOrdered(page))
  2629. goto out_reserved;
  2630. ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
  2631. if (ordered) {
  2632. unlock_extent(&inode->io_tree, page_start, page_end,
  2633. &cached_state);
  2634. unlock_page(page);
  2635. btrfs_start_ordered_extent(ordered, 1);
  2636. btrfs_put_ordered_extent(ordered);
  2637. goto again;
  2638. }
  2639. ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
  2640. &cached_state);
  2641. if (ret)
  2642. goto out_reserved;
  2643. /*
  2644. * Everything went as planned, we're now the owner of a dirty page with
  2645. * delayed allocation bits set and space reserved for our COW
  2646. * destination.
  2647. *
  2648. * The page was dirty when we started, nothing should have cleaned it.
  2649. */
  2650. BUG_ON(!PageDirty(page));
  2651. free_delalloc_space = false;
  2652. out_reserved:
  2653. btrfs_delalloc_release_extents(inode, PAGE_SIZE);
  2654. if (free_delalloc_space)
  2655. btrfs_delalloc_release_space(inode, data_reserved, page_start,
  2656. PAGE_SIZE, true);
  2657. unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
  2658. out_page:
  2659. if (ret) {
  2660. /*
  2661. * We hit ENOSPC or other errors. Update the mapping and page
  2662. * to reflect the errors and clean the page.
  2663. */
  2664. mapping_set_error(page->mapping, ret);
  2665. end_extent_writepage(page, ret, page_start, page_end);
  2666. clear_page_dirty_for_io(page);
  2667. SetPageError(page);
  2668. }
  2669. btrfs_page_clear_checked(inode->root->fs_info, page, page_start, PAGE_SIZE);
  2670. unlock_page(page);
  2671. put_page(page);
  2672. kfree(fixup);
  2673. extent_changeset_free(data_reserved);
  2674. /*
  2675. * As a precaution, do a delayed iput in case it would be the last iput
  2676. * that could need flushing space. Recursing back to fixup worker would
  2677. * deadlock.
  2678. */
  2679. btrfs_add_delayed_iput(&inode->vfs_inode);
  2680. }
  2681. /*
  2682. * There are a few paths in the higher layers of the kernel that directly
  2683. * set the page dirty bit without asking the filesystem if it is a
  2684. * good idea. This causes problems because we want to make sure COW
  2685. * properly happens and the data=ordered rules are followed.
  2686. *
  2687. * In our case any range that doesn't have the ORDERED bit set
  2688. * hasn't been properly setup for IO. We kick off an async process
  2689. * to fix it up. The async helper will wait for ordered extents, set
  2690. * the delalloc bit and make it safe to write the page.
  2691. */
  2692. int btrfs_writepage_cow_fixup(struct page *page)
  2693. {
  2694. struct inode *inode = page->mapping->host;
  2695. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  2696. struct btrfs_writepage_fixup *fixup;
  2697. /* This page has ordered extent covering it already */
  2698. if (PageOrdered(page))
  2699. return 0;
  2700. /*
  2701. * PageChecked is set below when we create a fixup worker for this page,
  2702. * don't try to create another one if we're already PageChecked()
  2703. *
  2704. * The extent_io writepage code will redirty the page if we send back
  2705. * EAGAIN.
  2706. */
  2707. if (PageChecked(page))
  2708. return -EAGAIN;
  2709. fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
  2710. if (!fixup)
  2711. return -EAGAIN;
  2712. /*
  2713. * We are already holding a reference to this inode from
  2714. * write_cache_pages. We need to hold it because the space reservation
  2715. * takes place outside of the page lock, and we can't trust
  2716. * page->mapping outside of the page lock.
  2717. */
  2718. ihold(inode);
  2719. btrfs_page_set_checked(fs_info, page, page_offset(page), PAGE_SIZE);
  2720. get_page(page);
  2721. btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL, NULL);
  2722. fixup->page = page;
  2723. fixup->inode = inode;
  2724. btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
  2725. return -EAGAIN;
  2726. }
  2727. static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
  2728. struct btrfs_inode *inode, u64 file_pos,
  2729. struct btrfs_file_extent_item *stack_fi,
  2730. const bool update_inode_bytes,
  2731. u64 qgroup_reserved)
  2732. {
  2733. struct btrfs_root *root = inode->root;
  2734. const u64 sectorsize = root->fs_info->sectorsize;
  2735. struct btrfs_path *path;
  2736. struct extent_buffer *leaf;
  2737. struct btrfs_key ins;
  2738. u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
  2739. u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
  2740. u64 offset = btrfs_stack_file_extent_offset(stack_fi);
  2741. u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
  2742. u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
  2743. struct btrfs_drop_extents_args drop_args = { 0 };
  2744. int ret;
  2745. path = btrfs_alloc_path();
  2746. if (!path)
  2747. return -ENOMEM;
  2748. /*
  2749. * we may be replacing one extent in the tree with another.
  2750. * The new extent is pinned in the extent map, and we don't want
  2751. * to drop it from the cache until it is completely in the btree.
  2752. *
  2753. * So, tell btrfs_drop_extents to leave this extent in the cache.
  2754. * the caller is expected to unpin it and allow it to be merged
  2755. * with the others.
  2756. */
  2757. drop_args.path = path;
  2758. drop_args.start = file_pos;
  2759. drop_args.end = file_pos + num_bytes;
  2760. drop_args.replace_extent = true;
  2761. drop_args.extent_item_size = sizeof(*stack_fi);
  2762. ret = btrfs_drop_extents(trans, root, inode, &drop_args);
  2763. if (ret)
  2764. goto out;
  2765. if (!drop_args.extent_inserted) {
  2766. ins.objectid = btrfs_ino(inode);
  2767. ins.offset = file_pos;
  2768. ins.type = BTRFS_EXTENT_DATA_KEY;
  2769. ret = btrfs_insert_empty_item(trans, root, path, &ins,
  2770. sizeof(*stack_fi));
  2771. if (ret)
  2772. goto out;
  2773. }
  2774. leaf = path->nodes[0];
  2775. btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
  2776. write_extent_buffer(leaf, stack_fi,
  2777. btrfs_item_ptr_offset(leaf, path->slots[0]),
  2778. sizeof(struct btrfs_file_extent_item));
  2779. btrfs_mark_buffer_dirty(leaf);
  2780. btrfs_release_path(path);
  2781. /*
  2782. * If we dropped an inline extent here, we know the range where it is
  2783. * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
  2784. * number of bytes only for that range containing the inline extent.
  2785. * The remaining of the range will be processed when clearning the
  2786. * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
  2787. */
  2788. if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
  2789. u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
  2790. inline_size = drop_args.bytes_found - inline_size;
  2791. btrfs_update_inode_bytes(inode, sectorsize, inline_size);
  2792. drop_args.bytes_found -= inline_size;
  2793. num_bytes -= sectorsize;
  2794. }
  2795. if (update_inode_bytes)
  2796. btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
  2797. ins.objectid = disk_bytenr;
  2798. ins.offset = disk_num_bytes;
  2799. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2800. ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
  2801. if (ret)
  2802. goto out;
  2803. ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
  2804. file_pos - offset,
  2805. qgroup_reserved, &ins);
  2806. out:
  2807. btrfs_free_path(path);
  2808. return ret;
  2809. }
  2810. static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
  2811. u64 start, u64 len)
  2812. {
  2813. struct btrfs_block_group *cache;
  2814. cache = btrfs_lookup_block_group(fs_info, start);
  2815. ASSERT(cache);
  2816. spin_lock(&cache->lock);
  2817. cache->delalloc_bytes -= len;
  2818. spin_unlock(&cache->lock);
  2819. btrfs_put_block_group(cache);
  2820. }
  2821. static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
  2822. struct btrfs_ordered_extent *oe)
  2823. {
  2824. struct btrfs_file_extent_item stack_fi;
  2825. bool update_inode_bytes;
  2826. u64 num_bytes = oe->num_bytes;
  2827. u64 ram_bytes = oe->ram_bytes;
  2828. memset(&stack_fi, 0, sizeof(stack_fi));
  2829. btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
  2830. btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
  2831. btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
  2832. oe->disk_num_bytes);
  2833. btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
  2834. if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags)) {
  2835. num_bytes = oe->truncated_len;
  2836. ram_bytes = num_bytes;
  2837. }
  2838. btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
  2839. btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
  2840. btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
  2841. /* Encryption and other encoding is reserved and all 0 */
  2842. /*
  2843. * For delalloc, when completing an ordered extent we update the inode's
  2844. * bytes when clearing the range in the inode's io tree, so pass false
  2845. * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
  2846. * except if the ordered extent was truncated.
  2847. */
  2848. update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
  2849. test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
  2850. test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
  2851. return insert_reserved_file_extent(trans, BTRFS_I(oe->inode),
  2852. oe->file_offset, &stack_fi,
  2853. update_inode_bytes, oe->qgroup_rsv);
  2854. }
  2855. /*
  2856. * As ordered data IO finishes, this gets called so we can finish
  2857. * an ordered extent if the range of bytes in the file it covers are
  2858. * fully written.
  2859. */
  2860. int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered_extent)
  2861. {
  2862. struct btrfs_inode *inode = BTRFS_I(ordered_extent->inode);
  2863. struct btrfs_root *root = inode->root;
  2864. struct btrfs_fs_info *fs_info = root->fs_info;
  2865. struct btrfs_trans_handle *trans = NULL;
  2866. struct extent_io_tree *io_tree = &inode->io_tree;
  2867. struct extent_state *cached_state = NULL;
  2868. u64 start, end;
  2869. int compress_type = 0;
  2870. int ret = 0;
  2871. u64 logical_len = ordered_extent->num_bytes;
  2872. bool freespace_inode;
  2873. bool truncated = false;
  2874. bool clear_reserved_extent = true;
  2875. unsigned int clear_bits = EXTENT_DEFRAG;
  2876. start = ordered_extent->file_offset;
  2877. end = start + ordered_extent->num_bytes - 1;
  2878. if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
  2879. !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
  2880. !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
  2881. !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
  2882. clear_bits |= EXTENT_DELALLOC_NEW;
  2883. freespace_inode = btrfs_is_free_space_inode(inode);
  2884. if (!freespace_inode)
  2885. btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
  2886. if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
  2887. ret = -EIO;
  2888. goto out;
  2889. }
  2890. /* A valid bdev implies a write on a sequential zone */
  2891. if (ordered_extent->bdev) {
  2892. btrfs_rewrite_logical_zoned(ordered_extent);
  2893. btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
  2894. ordered_extent->disk_num_bytes);
  2895. } else if (btrfs_is_data_reloc_root(inode->root)) {
  2896. btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
  2897. ordered_extent->disk_num_bytes);
  2898. }
  2899. btrfs_free_io_failure_record(inode, start, end);
  2900. if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
  2901. truncated = true;
  2902. logical_len = ordered_extent->truncated_len;
  2903. /* Truncated the entire extent, don't bother adding */
  2904. if (!logical_len)
  2905. goto out;
  2906. }
  2907. if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
  2908. BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
  2909. btrfs_inode_safe_disk_i_size_write(inode, 0);
  2910. if (freespace_inode)
  2911. trans = btrfs_join_transaction_spacecache(root);
  2912. else
  2913. trans = btrfs_join_transaction(root);
  2914. if (IS_ERR(trans)) {
  2915. ret = PTR_ERR(trans);
  2916. trans = NULL;
  2917. goto out;
  2918. }
  2919. trans->block_rsv = &inode->block_rsv;
  2920. ret = btrfs_update_inode_fallback(trans, root, inode);
  2921. if (ret) /* -ENOMEM or corruption */
  2922. btrfs_abort_transaction(trans, ret);
  2923. goto out;
  2924. }
  2925. clear_bits |= EXTENT_LOCKED;
  2926. lock_extent(io_tree, start, end, &cached_state);
  2927. if (freespace_inode)
  2928. trans = btrfs_join_transaction_spacecache(root);
  2929. else
  2930. trans = btrfs_join_transaction(root);
  2931. if (IS_ERR(trans)) {
  2932. ret = PTR_ERR(trans);
  2933. trans = NULL;
  2934. goto out;
  2935. }
  2936. trans->block_rsv = &inode->block_rsv;
  2937. if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
  2938. compress_type = ordered_extent->compress_type;
  2939. if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
  2940. BUG_ON(compress_type);
  2941. ret = btrfs_mark_extent_written(trans, inode,
  2942. ordered_extent->file_offset,
  2943. ordered_extent->file_offset +
  2944. logical_len);
  2945. btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
  2946. ordered_extent->disk_num_bytes);
  2947. } else {
  2948. BUG_ON(root == fs_info->tree_root);
  2949. ret = insert_ordered_extent_file_extent(trans, ordered_extent);
  2950. if (!ret) {
  2951. clear_reserved_extent = false;
  2952. btrfs_release_delalloc_bytes(fs_info,
  2953. ordered_extent->disk_bytenr,
  2954. ordered_extent->disk_num_bytes);
  2955. }
  2956. }
  2957. unpin_extent_cache(&inode->extent_tree, ordered_extent->file_offset,
  2958. ordered_extent->num_bytes, trans->transid);
  2959. if (ret < 0) {
  2960. btrfs_abort_transaction(trans, ret);
  2961. goto out;
  2962. }
  2963. ret = add_pending_csums(trans, &ordered_extent->list);
  2964. if (ret) {
  2965. btrfs_abort_transaction(trans, ret);
  2966. goto out;
  2967. }
  2968. /*
  2969. * If this is a new delalloc range, clear its new delalloc flag to
  2970. * update the inode's number of bytes. This needs to be done first
  2971. * before updating the inode item.
  2972. */
  2973. if ((clear_bits & EXTENT_DELALLOC_NEW) &&
  2974. !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
  2975. clear_extent_bit(&inode->io_tree, start, end,
  2976. EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
  2977. &cached_state);
  2978. btrfs_inode_safe_disk_i_size_write(inode, 0);
  2979. ret = btrfs_update_inode_fallback(trans, root, inode);
  2980. if (ret) { /* -ENOMEM or corruption */
  2981. btrfs_abort_transaction(trans, ret);
  2982. goto out;
  2983. }
  2984. ret = 0;
  2985. out:
  2986. clear_extent_bit(&inode->io_tree, start, end, clear_bits,
  2987. &cached_state);
  2988. if (trans)
  2989. btrfs_end_transaction(trans);
  2990. if (ret || truncated) {
  2991. u64 unwritten_start = start;
  2992. /*
  2993. * If we failed to finish this ordered extent for any reason we
  2994. * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
  2995. * extent, and mark the inode with the error if it wasn't
  2996. * already set. Any error during writeback would have already
  2997. * set the mapping error, so we need to set it if we're the ones
  2998. * marking this ordered extent as failed.
  2999. */
  3000. if (ret && !test_and_set_bit(BTRFS_ORDERED_IOERR,
  3001. &ordered_extent->flags))
  3002. mapping_set_error(ordered_extent->inode->i_mapping, -EIO);
  3003. if (truncated)
  3004. unwritten_start += logical_len;
  3005. clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
  3006. /* Drop extent maps for the part of the extent we didn't write. */
  3007. btrfs_drop_extent_map_range(inode, unwritten_start, end, false);
  3008. /*
  3009. * If the ordered extent had an IOERR or something else went
  3010. * wrong we need to return the space for this ordered extent
  3011. * back to the allocator. We only free the extent in the
  3012. * truncated case if we didn't write out the extent at all.
  3013. *
  3014. * If we made it past insert_reserved_file_extent before we
  3015. * errored out then we don't need to do this as the accounting
  3016. * has already been done.
  3017. */
  3018. if ((ret || !logical_len) &&
  3019. clear_reserved_extent &&
  3020. !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
  3021. !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
  3022. /*
  3023. * Discard the range before returning it back to the
  3024. * free space pool
  3025. */
  3026. if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
  3027. btrfs_discard_extent(fs_info,
  3028. ordered_extent->disk_bytenr,
  3029. ordered_extent->disk_num_bytes,
  3030. NULL);
  3031. btrfs_free_reserved_extent(fs_info,
  3032. ordered_extent->disk_bytenr,
  3033. ordered_extent->disk_num_bytes, 1);
  3034. /*
  3035. * Actually free the qgroup rsv which was released when
  3036. * the ordered extent was created.
  3037. */
  3038. btrfs_qgroup_free_refroot(fs_info, inode->root->root_key.objectid,
  3039. ordered_extent->qgroup_rsv,
  3040. BTRFS_QGROUP_RSV_DATA);
  3041. }
  3042. }
  3043. /*
  3044. * This needs to be done to make sure anybody waiting knows we are done
  3045. * updating everything for this ordered extent.
  3046. */
  3047. btrfs_remove_ordered_extent(inode, ordered_extent);
  3048. /* once for us */
  3049. btrfs_put_ordered_extent(ordered_extent);
  3050. /* once for the tree */
  3051. btrfs_put_ordered_extent(ordered_extent);
  3052. return ret;
  3053. }
  3054. void btrfs_writepage_endio_finish_ordered(struct btrfs_inode *inode,
  3055. struct page *page, u64 start,
  3056. u64 end, bool uptodate)
  3057. {
  3058. trace_btrfs_writepage_end_io_hook(inode, start, end, uptodate);
  3059. btrfs_mark_ordered_io_finished(inode, page, start, end + 1 - start, uptodate);
  3060. }
  3061. /*
  3062. * Verify the checksum for a single sector without any extra action that depend
  3063. * on the type of I/O.
  3064. */
  3065. int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
  3066. u32 pgoff, u8 *csum, const u8 * const csum_expected)
  3067. {
  3068. SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
  3069. char *kaddr;
  3070. ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
  3071. shash->tfm = fs_info->csum_shash;
  3072. kaddr = kmap_local_page(page) + pgoff;
  3073. crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
  3074. kunmap_local(kaddr);
  3075. if (memcmp(csum, csum_expected, fs_info->csum_size))
  3076. return -EIO;
  3077. return 0;
  3078. }
  3079. static u8 *btrfs_csum_ptr(const struct btrfs_fs_info *fs_info, u8 *csums, u64 offset)
  3080. {
  3081. u64 offset_in_sectors = offset >> fs_info->sectorsize_bits;
  3082. return csums + offset_in_sectors * fs_info->csum_size;
  3083. }
  3084. /*
  3085. * check_data_csum - verify checksum of one sector of uncompressed data
  3086. * @inode: inode
  3087. * @bbio: btrfs_bio which contains the csum
  3088. * @bio_offset: offset to the beginning of the bio (in bytes)
  3089. * @page: page where is the data to be verified
  3090. * @pgoff: offset inside the page
  3091. *
  3092. * The length of such check is always one sector size.
  3093. *
  3094. * When csum mismatch is detected, we will also report the error and fill the
  3095. * corrupted range with zero. (Thus it needs the extra parameters)
  3096. */
  3097. int btrfs_check_data_csum(struct inode *inode, struct btrfs_bio *bbio,
  3098. u32 bio_offset, struct page *page, u32 pgoff)
  3099. {
  3100. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3101. u32 len = fs_info->sectorsize;
  3102. u8 *csum_expected;
  3103. u8 csum[BTRFS_CSUM_SIZE];
  3104. ASSERT(pgoff + len <= PAGE_SIZE);
  3105. csum_expected = btrfs_csum_ptr(fs_info, bbio->csum, bio_offset);
  3106. if (btrfs_check_sector_csum(fs_info, page, pgoff, csum, csum_expected))
  3107. goto zeroit;
  3108. return 0;
  3109. zeroit:
  3110. btrfs_print_data_csum_error(BTRFS_I(inode),
  3111. bbio->file_offset + bio_offset,
  3112. csum, csum_expected, bbio->mirror_num);
  3113. if (bbio->device)
  3114. btrfs_dev_stat_inc_and_print(bbio->device,
  3115. BTRFS_DEV_STAT_CORRUPTION_ERRS);
  3116. memzero_page(page, pgoff, len);
  3117. return -EIO;
  3118. }
  3119. /*
  3120. * When reads are done, we need to check csums to verify the data is correct.
  3121. * if there's a match, we allow the bio to finish. If not, the code in
  3122. * extent_io.c will try to find good copies for us.
  3123. *
  3124. * @bio_offset: offset to the beginning of the bio (in bytes)
  3125. * @start: file offset of the range start
  3126. * @end: file offset of the range end (inclusive)
  3127. *
  3128. * Return a bitmap where bit set means a csum mismatch, and bit not set means
  3129. * csum match.
  3130. */
  3131. unsigned int btrfs_verify_data_csum(struct btrfs_bio *bbio,
  3132. u32 bio_offset, struct page *page,
  3133. u64 start, u64 end)
  3134. {
  3135. struct inode *inode = page->mapping->host;
  3136. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3137. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  3138. struct btrfs_root *root = BTRFS_I(inode)->root;
  3139. const u32 sectorsize = root->fs_info->sectorsize;
  3140. u32 pg_off;
  3141. unsigned int result = 0;
  3142. /*
  3143. * This only happens for NODATASUM or compressed read.
  3144. * Normally this should be covered by above check for compressed read
  3145. * or the next check for NODATASUM. Just do a quicker exit here.
  3146. */
  3147. if (bbio->csum == NULL)
  3148. return 0;
  3149. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
  3150. return 0;
  3151. if (unlikely(test_bit(BTRFS_FS_STATE_NO_CSUMS, &fs_info->fs_state)))
  3152. return 0;
  3153. ASSERT(page_offset(page) <= start &&
  3154. end <= page_offset(page) + PAGE_SIZE - 1);
  3155. for (pg_off = offset_in_page(start);
  3156. pg_off < offset_in_page(end);
  3157. pg_off += sectorsize, bio_offset += sectorsize) {
  3158. u64 file_offset = pg_off + page_offset(page);
  3159. int ret;
  3160. if (btrfs_is_data_reloc_root(root) &&
  3161. test_range_bit(io_tree, file_offset,
  3162. file_offset + sectorsize - 1,
  3163. EXTENT_NODATASUM, 1, NULL)) {
  3164. /* Skip the range without csum for data reloc inode */
  3165. clear_extent_bits(io_tree, file_offset,
  3166. file_offset + sectorsize - 1,
  3167. EXTENT_NODATASUM);
  3168. continue;
  3169. }
  3170. ret = btrfs_check_data_csum(inode, bbio, bio_offset, page, pg_off);
  3171. if (ret < 0) {
  3172. const int nr_bit = (pg_off - offset_in_page(start)) >>
  3173. root->fs_info->sectorsize_bits;
  3174. result |= (1U << nr_bit);
  3175. }
  3176. }
  3177. return result;
  3178. }
  3179. /*
  3180. * btrfs_add_delayed_iput - perform a delayed iput on @inode
  3181. *
  3182. * @inode: The inode we want to perform iput on
  3183. *
  3184. * This function uses the generic vfs_inode::i_count to track whether we should
  3185. * just decrement it (in case it's > 1) or if this is the last iput then link
  3186. * the inode to the delayed iput machinery. Delayed iputs are processed at
  3187. * transaction commit time/superblock commit/cleaner kthread.
  3188. */
  3189. void btrfs_add_delayed_iput(struct inode *inode)
  3190. {
  3191. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3192. struct btrfs_inode *binode = BTRFS_I(inode);
  3193. if (atomic_add_unless(&inode->i_count, -1, 1))
  3194. return;
  3195. atomic_inc(&fs_info->nr_delayed_iputs);
  3196. spin_lock(&fs_info->delayed_iput_lock);
  3197. ASSERT(list_empty(&binode->delayed_iput));
  3198. list_add_tail(&binode->delayed_iput, &fs_info->delayed_iputs);
  3199. spin_unlock(&fs_info->delayed_iput_lock);
  3200. if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
  3201. wake_up_process(fs_info->cleaner_kthread);
  3202. }
  3203. static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
  3204. struct btrfs_inode *inode)
  3205. {
  3206. list_del_init(&inode->delayed_iput);
  3207. spin_unlock(&fs_info->delayed_iput_lock);
  3208. iput(&inode->vfs_inode);
  3209. if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
  3210. wake_up(&fs_info->delayed_iputs_wait);
  3211. spin_lock(&fs_info->delayed_iput_lock);
  3212. }
  3213. static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
  3214. struct btrfs_inode *inode)
  3215. {
  3216. if (!list_empty(&inode->delayed_iput)) {
  3217. spin_lock(&fs_info->delayed_iput_lock);
  3218. if (!list_empty(&inode->delayed_iput))
  3219. run_delayed_iput_locked(fs_info, inode);
  3220. spin_unlock(&fs_info->delayed_iput_lock);
  3221. }
  3222. }
  3223. void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
  3224. {
  3225. spin_lock(&fs_info->delayed_iput_lock);
  3226. while (!list_empty(&fs_info->delayed_iputs)) {
  3227. struct btrfs_inode *inode;
  3228. inode = list_first_entry(&fs_info->delayed_iputs,
  3229. struct btrfs_inode, delayed_iput);
  3230. run_delayed_iput_locked(fs_info, inode);
  3231. cond_resched_lock(&fs_info->delayed_iput_lock);
  3232. }
  3233. spin_unlock(&fs_info->delayed_iput_lock);
  3234. }
  3235. /*
  3236. * Wait for flushing all delayed iputs
  3237. *
  3238. * @fs_info: the filesystem
  3239. *
  3240. * This will wait on any delayed iputs that are currently running with KILLABLE
  3241. * set. Once they are all done running we will return, unless we are killed in
  3242. * which case we return EINTR. This helps in user operations like fallocate etc
  3243. * that might get blocked on the iputs.
  3244. *
  3245. * Return EINTR if we were killed, 0 if nothing's pending
  3246. */
  3247. int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
  3248. {
  3249. int ret = wait_event_killable(fs_info->delayed_iputs_wait,
  3250. atomic_read(&fs_info->nr_delayed_iputs) == 0);
  3251. if (ret)
  3252. return -EINTR;
  3253. return 0;
  3254. }
  3255. /*
  3256. * This creates an orphan entry for the given inode in case something goes wrong
  3257. * in the middle of an unlink.
  3258. */
  3259. int btrfs_orphan_add(struct btrfs_trans_handle *trans,
  3260. struct btrfs_inode *inode)
  3261. {
  3262. int ret;
  3263. ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
  3264. if (ret && ret != -EEXIST) {
  3265. btrfs_abort_transaction(trans, ret);
  3266. return ret;
  3267. }
  3268. return 0;
  3269. }
  3270. /*
  3271. * We have done the delete so we can go ahead and remove the orphan item for
  3272. * this particular inode.
  3273. */
  3274. static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
  3275. struct btrfs_inode *inode)
  3276. {
  3277. return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
  3278. }
  3279. /*
  3280. * this cleans up any orphans that may be left on the list from the last use
  3281. * of this root.
  3282. */
  3283. int btrfs_orphan_cleanup(struct btrfs_root *root)
  3284. {
  3285. struct btrfs_fs_info *fs_info = root->fs_info;
  3286. struct btrfs_path *path;
  3287. struct extent_buffer *leaf;
  3288. struct btrfs_key key, found_key;
  3289. struct btrfs_trans_handle *trans;
  3290. struct inode *inode;
  3291. u64 last_objectid = 0;
  3292. int ret = 0, nr_unlink = 0;
  3293. if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
  3294. return 0;
  3295. path = btrfs_alloc_path();
  3296. if (!path) {
  3297. ret = -ENOMEM;
  3298. goto out;
  3299. }
  3300. path->reada = READA_BACK;
  3301. key.objectid = BTRFS_ORPHAN_OBJECTID;
  3302. key.type = BTRFS_ORPHAN_ITEM_KEY;
  3303. key.offset = (u64)-1;
  3304. while (1) {
  3305. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  3306. if (ret < 0)
  3307. goto out;
  3308. /*
  3309. * if ret == 0 means we found what we were searching for, which
  3310. * is weird, but possible, so only screw with path if we didn't
  3311. * find the key and see if we have stuff that matches
  3312. */
  3313. if (ret > 0) {
  3314. ret = 0;
  3315. if (path->slots[0] == 0)
  3316. break;
  3317. path->slots[0]--;
  3318. }
  3319. /* pull out the item */
  3320. leaf = path->nodes[0];
  3321. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  3322. /* make sure the item matches what we want */
  3323. if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
  3324. break;
  3325. if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
  3326. break;
  3327. /* release the path since we're done with it */
  3328. btrfs_release_path(path);
  3329. /*
  3330. * this is where we are basically btrfs_lookup, without the
  3331. * crossing root thing. we store the inode number in the
  3332. * offset of the orphan item.
  3333. */
  3334. if (found_key.offset == last_objectid) {
  3335. btrfs_err(fs_info,
  3336. "Error removing orphan entry, stopping orphan cleanup");
  3337. ret = -EINVAL;
  3338. goto out;
  3339. }
  3340. last_objectid = found_key.offset;
  3341. found_key.objectid = found_key.offset;
  3342. found_key.type = BTRFS_INODE_ITEM_KEY;
  3343. found_key.offset = 0;
  3344. inode = btrfs_iget(fs_info->sb, last_objectid, root);
  3345. ret = PTR_ERR_OR_ZERO(inode);
  3346. if (ret && ret != -ENOENT)
  3347. goto out;
  3348. if (ret == -ENOENT && root == fs_info->tree_root) {
  3349. struct btrfs_root *dead_root;
  3350. int is_dead_root = 0;
  3351. /*
  3352. * This is an orphan in the tree root. Currently these
  3353. * could come from 2 sources:
  3354. * a) a root (snapshot/subvolume) deletion in progress
  3355. * b) a free space cache inode
  3356. * We need to distinguish those two, as the orphan item
  3357. * for a root must not get deleted before the deletion
  3358. * of the snapshot/subvolume's tree completes.
  3359. *
  3360. * btrfs_find_orphan_roots() ran before us, which has
  3361. * found all deleted roots and loaded them into
  3362. * fs_info->fs_roots_radix. So here we can find if an
  3363. * orphan item corresponds to a deleted root by looking
  3364. * up the root from that radix tree.
  3365. */
  3366. spin_lock(&fs_info->fs_roots_radix_lock);
  3367. dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
  3368. (unsigned long)found_key.objectid);
  3369. if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
  3370. is_dead_root = 1;
  3371. spin_unlock(&fs_info->fs_roots_radix_lock);
  3372. if (is_dead_root) {
  3373. /* prevent this orphan from being found again */
  3374. key.offset = found_key.objectid - 1;
  3375. continue;
  3376. }
  3377. }
  3378. /*
  3379. * If we have an inode with links, there are a couple of
  3380. * possibilities:
  3381. *
  3382. * 1. We were halfway through creating fsverity metadata for the
  3383. * file. In that case, the orphan item represents incomplete
  3384. * fsverity metadata which must be cleaned up with
  3385. * btrfs_drop_verity_items and deleting the orphan item.
  3386. * 2. Old kernels (before v3.12) used to create an
  3387. * orphan item for truncate indicating that there were possibly
  3388. * extent items past i_size that needed to be deleted. In v3.12,
  3389. * truncate was changed to update i_size in sync with the extent
  3390. * items, but the (useless) orphan item was still created. Since
  3391. * v4.18, we don't create the orphan item for truncate at all.
  3392. *
  3393. * So, this item could mean that we need to do a truncate, but
  3394. * only if this filesystem was last used on a pre-v3.12 kernel
  3395. * and was not cleanly unmounted. The odds of that are quite
  3396. * slim, and it's a pain to do the truncate now, so just delete
  3397. * the orphan item.
  3398. *
  3399. * It's also possible that this orphan item was supposed to be
  3400. * deleted but wasn't. The inode number may have been reused,
  3401. * but either way, we can delete the orphan item.
  3402. */
  3403. if (ret == -ENOENT || inode->i_nlink) {
  3404. if (!ret) {
  3405. ret = btrfs_drop_verity_items(BTRFS_I(inode));
  3406. iput(inode);
  3407. if (ret)
  3408. goto out;
  3409. }
  3410. trans = btrfs_start_transaction(root, 1);
  3411. if (IS_ERR(trans)) {
  3412. ret = PTR_ERR(trans);
  3413. goto out;
  3414. }
  3415. btrfs_debug(fs_info, "auto deleting %Lu",
  3416. found_key.objectid);
  3417. ret = btrfs_del_orphan_item(trans, root,
  3418. found_key.objectid);
  3419. btrfs_end_transaction(trans);
  3420. if (ret)
  3421. goto out;
  3422. continue;
  3423. }
  3424. nr_unlink++;
  3425. /* this will do delete_inode and everything for us */
  3426. iput(inode);
  3427. }
  3428. /* release the path since we're done with it */
  3429. btrfs_release_path(path);
  3430. if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
  3431. trans = btrfs_join_transaction(root);
  3432. if (!IS_ERR(trans))
  3433. btrfs_end_transaction(trans);
  3434. }
  3435. if (nr_unlink)
  3436. btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
  3437. out:
  3438. if (ret)
  3439. btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
  3440. btrfs_free_path(path);
  3441. return ret;
  3442. }
  3443. /*
  3444. * very simple check to peek ahead in the leaf looking for xattrs. If we
  3445. * don't find any xattrs, we know there can't be any acls.
  3446. *
  3447. * slot is the slot the inode is in, objectid is the objectid of the inode
  3448. */
  3449. static noinline int acls_after_inode_item(struct extent_buffer *leaf,
  3450. int slot, u64 objectid,
  3451. int *first_xattr_slot)
  3452. {
  3453. u32 nritems = btrfs_header_nritems(leaf);
  3454. struct btrfs_key found_key;
  3455. static u64 xattr_access = 0;
  3456. static u64 xattr_default = 0;
  3457. int scanned = 0;
  3458. if (!xattr_access) {
  3459. xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
  3460. strlen(XATTR_NAME_POSIX_ACL_ACCESS));
  3461. xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
  3462. strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
  3463. }
  3464. slot++;
  3465. *first_xattr_slot = -1;
  3466. while (slot < nritems) {
  3467. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  3468. /* we found a different objectid, there must not be acls */
  3469. if (found_key.objectid != objectid)
  3470. return 0;
  3471. /* we found an xattr, assume we've got an acl */
  3472. if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
  3473. if (*first_xattr_slot == -1)
  3474. *first_xattr_slot = slot;
  3475. if (found_key.offset == xattr_access ||
  3476. found_key.offset == xattr_default)
  3477. return 1;
  3478. }
  3479. /*
  3480. * we found a key greater than an xattr key, there can't
  3481. * be any acls later on
  3482. */
  3483. if (found_key.type > BTRFS_XATTR_ITEM_KEY)
  3484. return 0;
  3485. slot++;
  3486. scanned++;
  3487. /*
  3488. * it goes inode, inode backrefs, xattrs, extents,
  3489. * so if there are a ton of hard links to an inode there can
  3490. * be a lot of backrefs. Don't waste time searching too hard,
  3491. * this is just an optimization
  3492. */
  3493. if (scanned >= 8)
  3494. break;
  3495. }
  3496. /* we hit the end of the leaf before we found an xattr or
  3497. * something larger than an xattr. We have to assume the inode
  3498. * has acls
  3499. */
  3500. if (*first_xattr_slot == -1)
  3501. *first_xattr_slot = slot;
  3502. return 1;
  3503. }
  3504. /*
  3505. * read an inode from the btree into the in-memory inode
  3506. */
  3507. static int btrfs_read_locked_inode(struct inode *inode,
  3508. struct btrfs_path *in_path)
  3509. {
  3510. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3511. struct btrfs_path *path = in_path;
  3512. struct extent_buffer *leaf;
  3513. struct btrfs_inode_item *inode_item;
  3514. struct btrfs_root *root = BTRFS_I(inode)->root;
  3515. struct btrfs_key location;
  3516. unsigned long ptr;
  3517. int maybe_acls;
  3518. u32 rdev;
  3519. int ret;
  3520. bool filled = false;
  3521. int first_xattr_slot;
  3522. ret = btrfs_fill_inode(inode, &rdev);
  3523. if (!ret)
  3524. filled = true;
  3525. if (!path) {
  3526. path = btrfs_alloc_path();
  3527. if (!path)
  3528. return -ENOMEM;
  3529. }
  3530. memcpy(&location, &BTRFS_I(inode)->location, sizeof(location));
  3531. ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
  3532. if (ret) {
  3533. if (path != in_path)
  3534. btrfs_free_path(path);
  3535. return ret;
  3536. }
  3537. leaf = path->nodes[0];
  3538. if (filled)
  3539. goto cache_index;
  3540. inode_item = btrfs_item_ptr(leaf, path->slots[0],
  3541. struct btrfs_inode_item);
  3542. inode->i_mode = btrfs_inode_mode(leaf, inode_item);
  3543. set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
  3544. i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
  3545. i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
  3546. btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
  3547. btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
  3548. round_up(i_size_read(inode), fs_info->sectorsize));
  3549. inode->i_atime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->atime);
  3550. inode->i_atime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->atime);
  3551. inode->i_mtime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->mtime);
  3552. inode->i_mtime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->mtime);
  3553. inode->i_ctime.tv_sec = btrfs_timespec_sec(leaf, &inode_item->ctime);
  3554. inode->i_ctime.tv_nsec = btrfs_timespec_nsec(leaf, &inode_item->ctime);
  3555. BTRFS_I(inode)->i_otime.tv_sec =
  3556. btrfs_timespec_sec(leaf, &inode_item->otime);
  3557. BTRFS_I(inode)->i_otime.tv_nsec =
  3558. btrfs_timespec_nsec(leaf, &inode_item->otime);
  3559. inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
  3560. BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
  3561. BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
  3562. inode_set_iversion_queried(inode,
  3563. btrfs_inode_sequence(leaf, inode_item));
  3564. inode->i_generation = BTRFS_I(inode)->generation;
  3565. inode->i_rdev = 0;
  3566. rdev = btrfs_inode_rdev(leaf, inode_item);
  3567. BTRFS_I(inode)->index_cnt = (u64)-1;
  3568. btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
  3569. &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
  3570. cache_index:
  3571. /*
  3572. * If we were modified in the current generation and evicted from memory
  3573. * and then re-read we need to do a full sync since we don't have any
  3574. * idea about which extents were modified before we were evicted from
  3575. * cache.
  3576. *
  3577. * This is required for both inode re-read from disk and delayed inode
  3578. * in delayed_nodes_tree.
  3579. */
  3580. if (BTRFS_I(inode)->last_trans == fs_info->generation)
  3581. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  3582. &BTRFS_I(inode)->runtime_flags);
  3583. /*
  3584. * We don't persist the id of the transaction where an unlink operation
  3585. * against the inode was last made. So here we assume the inode might
  3586. * have been evicted, and therefore the exact value of last_unlink_trans
  3587. * lost, and set it to last_trans to avoid metadata inconsistencies
  3588. * between the inode and its parent if the inode is fsync'ed and the log
  3589. * replayed. For example, in the scenario:
  3590. *
  3591. * touch mydir/foo
  3592. * ln mydir/foo mydir/bar
  3593. * sync
  3594. * unlink mydir/bar
  3595. * echo 2 > /proc/sys/vm/drop_caches # evicts inode
  3596. * xfs_io -c fsync mydir/foo
  3597. * <power failure>
  3598. * mount fs, triggers fsync log replay
  3599. *
  3600. * We must make sure that when we fsync our inode foo we also log its
  3601. * parent inode, otherwise after log replay the parent still has the
  3602. * dentry with the "bar" name but our inode foo has a link count of 1
  3603. * and doesn't have an inode ref with the name "bar" anymore.
  3604. *
  3605. * Setting last_unlink_trans to last_trans is a pessimistic approach,
  3606. * but it guarantees correctness at the expense of occasional full
  3607. * transaction commits on fsync if our inode is a directory, or if our
  3608. * inode is not a directory, logging its parent unnecessarily.
  3609. */
  3610. BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
  3611. /*
  3612. * Same logic as for last_unlink_trans. We don't persist the generation
  3613. * of the last transaction where this inode was used for a reflink
  3614. * operation, so after eviction and reloading the inode we must be
  3615. * pessimistic and assume the last transaction that modified the inode.
  3616. */
  3617. BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
  3618. path->slots[0]++;
  3619. if (inode->i_nlink != 1 ||
  3620. path->slots[0] >= btrfs_header_nritems(leaf))
  3621. goto cache_acl;
  3622. btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
  3623. if (location.objectid != btrfs_ino(BTRFS_I(inode)))
  3624. goto cache_acl;
  3625. ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
  3626. if (location.type == BTRFS_INODE_REF_KEY) {
  3627. struct btrfs_inode_ref *ref;
  3628. ref = (struct btrfs_inode_ref *)ptr;
  3629. BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
  3630. } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
  3631. struct btrfs_inode_extref *extref;
  3632. extref = (struct btrfs_inode_extref *)ptr;
  3633. BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
  3634. extref);
  3635. }
  3636. cache_acl:
  3637. /*
  3638. * try to precache a NULL acl entry for files that don't have
  3639. * any xattrs or acls
  3640. */
  3641. maybe_acls = acls_after_inode_item(leaf, path->slots[0],
  3642. btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
  3643. if (first_xattr_slot != -1) {
  3644. path->slots[0] = first_xattr_slot;
  3645. ret = btrfs_load_inode_props(inode, path);
  3646. if (ret)
  3647. btrfs_err(fs_info,
  3648. "error loading props for ino %llu (root %llu): %d",
  3649. btrfs_ino(BTRFS_I(inode)),
  3650. root->root_key.objectid, ret);
  3651. }
  3652. if (path != in_path)
  3653. btrfs_free_path(path);
  3654. if (!maybe_acls)
  3655. cache_no_acl(inode);
  3656. switch (inode->i_mode & S_IFMT) {
  3657. case S_IFREG:
  3658. inode->i_mapping->a_ops = &btrfs_aops;
  3659. inode->i_fop = &btrfs_file_operations;
  3660. inode->i_op = &btrfs_file_inode_operations;
  3661. break;
  3662. case S_IFDIR:
  3663. inode->i_fop = &btrfs_dir_file_operations;
  3664. inode->i_op = &btrfs_dir_inode_operations;
  3665. break;
  3666. case S_IFLNK:
  3667. inode->i_op = &btrfs_symlink_inode_operations;
  3668. inode_nohighmem(inode);
  3669. inode->i_mapping->a_ops = &btrfs_aops;
  3670. break;
  3671. default:
  3672. inode->i_op = &btrfs_special_inode_operations;
  3673. init_special_inode(inode, inode->i_mode, rdev);
  3674. break;
  3675. }
  3676. btrfs_sync_inode_flags_to_i_flags(inode);
  3677. return 0;
  3678. }
  3679. /*
  3680. * given a leaf and an inode, copy the inode fields into the leaf
  3681. */
  3682. static void fill_inode_item(struct btrfs_trans_handle *trans,
  3683. struct extent_buffer *leaf,
  3684. struct btrfs_inode_item *item,
  3685. struct inode *inode)
  3686. {
  3687. struct btrfs_map_token token;
  3688. u64 flags;
  3689. btrfs_init_map_token(&token, leaf);
  3690. btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
  3691. btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
  3692. btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
  3693. btrfs_set_token_inode_mode(&token, item, inode->i_mode);
  3694. btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
  3695. btrfs_set_token_timespec_sec(&token, &item->atime,
  3696. inode->i_atime.tv_sec);
  3697. btrfs_set_token_timespec_nsec(&token, &item->atime,
  3698. inode->i_atime.tv_nsec);
  3699. btrfs_set_token_timespec_sec(&token, &item->mtime,
  3700. inode->i_mtime.tv_sec);
  3701. btrfs_set_token_timespec_nsec(&token, &item->mtime,
  3702. inode->i_mtime.tv_nsec);
  3703. btrfs_set_token_timespec_sec(&token, &item->ctime,
  3704. inode->i_ctime.tv_sec);
  3705. btrfs_set_token_timespec_nsec(&token, &item->ctime,
  3706. inode->i_ctime.tv_nsec);
  3707. btrfs_set_token_timespec_sec(&token, &item->otime,
  3708. BTRFS_I(inode)->i_otime.tv_sec);
  3709. btrfs_set_token_timespec_nsec(&token, &item->otime,
  3710. BTRFS_I(inode)->i_otime.tv_nsec);
  3711. btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
  3712. btrfs_set_token_inode_generation(&token, item,
  3713. BTRFS_I(inode)->generation);
  3714. btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
  3715. btrfs_set_token_inode_transid(&token, item, trans->transid);
  3716. btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
  3717. flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
  3718. BTRFS_I(inode)->ro_flags);
  3719. btrfs_set_token_inode_flags(&token, item, flags);
  3720. btrfs_set_token_inode_block_group(&token, item, 0);
  3721. }
  3722. /*
  3723. * copy everything in the in-memory inode into the btree.
  3724. */
  3725. static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
  3726. struct btrfs_root *root,
  3727. struct btrfs_inode *inode)
  3728. {
  3729. struct btrfs_inode_item *inode_item;
  3730. struct btrfs_path *path;
  3731. struct extent_buffer *leaf;
  3732. int ret;
  3733. path = btrfs_alloc_path();
  3734. if (!path)
  3735. return -ENOMEM;
  3736. ret = btrfs_lookup_inode(trans, root, path, &inode->location, 1);
  3737. if (ret) {
  3738. if (ret > 0)
  3739. ret = -ENOENT;
  3740. goto failed;
  3741. }
  3742. leaf = path->nodes[0];
  3743. inode_item = btrfs_item_ptr(leaf, path->slots[0],
  3744. struct btrfs_inode_item);
  3745. fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
  3746. btrfs_mark_buffer_dirty(leaf);
  3747. btrfs_set_inode_last_trans(trans, inode);
  3748. ret = 0;
  3749. failed:
  3750. btrfs_free_path(path);
  3751. return ret;
  3752. }
  3753. /*
  3754. * copy everything in the in-memory inode into the btree.
  3755. */
  3756. noinline int btrfs_update_inode(struct btrfs_trans_handle *trans,
  3757. struct btrfs_root *root,
  3758. struct btrfs_inode *inode)
  3759. {
  3760. struct btrfs_fs_info *fs_info = root->fs_info;
  3761. int ret;
  3762. /*
  3763. * If the inode is a free space inode, we can deadlock during commit
  3764. * if we put it into the delayed code.
  3765. *
  3766. * The data relocation inode should also be directly updated
  3767. * without delay
  3768. */
  3769. if (!btrfs_is_free_space_inode(inode)
  3770. && !btrfs_is_data_reloc_root(root)
  3771. && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
  3772. btrfs_update_root_times(trans, root);
  3773. ret = btrfs_delayed_update_inode(trans, root, inode);
  3774. if (!ret)
  3775. btrfs_set_inode_last_trans(trans, inode);
  3776. return ret;
  3777. }
  3778. return btrfs_update_inode_item(trans, root, inode);
  3779. }
  3780. int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
  3781. struct btrfs_root *root, struct btrfs_inode *inode)
  3782. {
  3783. int ret;
  3784. ret = btrfs_update_inode(trans, root, inode);
  3785. if (ret == -ENOSPC)
  3786. return btrfs_update_inode_item(trans, root, inode);
  3787. return ret;
  3788. }
  3789. /*
  3790. * unlink helper that gets used here in inode.c and in the tree logging
  3791. * recovery code. It remove a link in a directory with a given name, and
  3792. * also drops the back refs in the inode to the directory
  3793. */
  3794. static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
  3795. struct btrfs_inode *dir,
  3796. struct btrfs_inode *inode,
  3797. const struct fscrypt_str *name,
  3798. struct btrfs_rename_ctx *rename_ctx)
  3799. {
  3800. struct btrfs_root *root = dir->root;
  3801. struct btrfs_fs_info *fs_info = root->fs_info;
  3802. struct btrfs_path *path;
  3803. int ret = 0;
  3804. struct btrfs_dir_item *di;
  3805. u64 index;
  3806. u64 ino = btrfs_ino(inode);
  3807. u64 dir_ino = btrfs_ino(dir);
  3808. path = btrfs_alloc_path();
  3809. if (!path) {
  3810. ret = -ENOMEM;
  3811. goto out;
  3812. }
  3813. di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
  3814. if (IS_ERR_OR_NULL(di)) {
  3815. ret = di ? PTR_ERR(di) : -ENOENT;
  3816. goto err;
  3817. }
  3818. ret = btrfs_delete_one_dir_name(trans, root, path, di);
  3819. if (ret)
  3820. goto err;
  3821. btrfs_release_path(path);
  3822. /*
  3823. * If we don't have dir index, we have to get it by looking up
  3824. * the inode ref, since we get the inode ref, remove it directly,
  3825. * it is unnecessary to do delayed deletion.
  3826. *
  3827. * But if we have dir index, needn't search inode ref to get it.
  3828. * Since the inode ref is close to the inode item, it is better
  3829. * that we delay to delete it, and just do this deletion when
  3830. * we update the inode item.
  3831. */
  3832. if (inode->dir_index) {
  3833. ret = btrfs_delayed_delete_inode_ref(inode);
  3834. if (!ret) {
  3835. index = inode->dir_index;
  3836. goto skip_backref;
  3837. }
  3838. }
  3839. ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
  3840. if (ret) {
  3841. btrfs_info(fs_info,
  3842. "failed to delete reference to %.*s, inode %llu parent %llu",
  3843. name->len, name->name, ino, dir_ino);
  3844. btrfs_abort_transaction(trans, ret);
  3845. goto err;
  3846. }
  3847. skip_backref:
  3848. if (rename_ctx)
  3849. rename_ctx->index = index;
  3850. ret = btrfs_delete_delayed_dir_index(trans, dir, index);
  3851. if (ret) {
  3852. btrfs_abort_transaction(trans, ret);
  3853. goto err;
  3854. }
  3855. /*
  3856. * If we are in a rename context, we don't need to update anything in the
  3857. * log. That will be done later during the rename by btrfs_log_new_name().
  3858. * Besides that, doing it here would only cause extra unnecessary btree
  3859. * operations on the log tree, increasing latency for applications.
  3860. */
  3861. if (!rename_ctx) {
  3862. btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
  3863. btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
  3864. }
  3865. /*
  3866. * If we have a pending delayed iput we could end up with the final iput
  3867. * being run in btrfs-cleaner context. If we have enough of these built
  3868. * up we can end up burning a lot of time in btrfs-cleaner without any
  3869. * way to throttle the unlinks. Since we're currently holding a ref on
  3870. * the inode we can run the delayed iput here without any issues as the
  3871. * final iput won't be done until after we drop the ref we're currently
  3872. * holding.
  3873. */
  3874. btrfs_run_delayed_iput(fs_info, inode);
  3875. err:
  3876. btrfs_free_path(path);
  3877. if (ret)
  3878. goto out;
  3879. btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
  3880. inode_inc_iversion(&inode->vfs_inode);
  3881. inode_inc_iversion(&dir->vfs_inode);
  3882. inode->vfs_inode.i_ctime = current_time(&inode->vfs_inode);
  3883. dir->vfs_inode.i_mtime = inode->vfs_inode.i_ctime;
  3884. dir->vfs_inode.i_ctime = inode->vfs_inode.i_ctime;
  3885. ret = btrfs_update_inode(trans, root, dir);
  3886. out:
  3887. return ret;
  3888. }
  3889. int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
  3890. struct btrfs_inode *dir, struct btrfs_inode *inode,
  3891. const struct fscrypt_str *name)
  3892. {
  3893. int ret;
  3894. ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
  3895. if (!ret) {
  3896. drop_nlink(&inode->vfs_inode);
  3897. ret = btrfs_update_inode(trans, inode->root, inode);
  3898. }
  3899. return ret;
  3900. }
  3901. /*
  3902. * helper to start transaction for unlink and rmdir.
  3903. *
  3904. * unlink and rmdir are special in btrfs, they do not always free space, so
  3905. * if we cannot make our reservations the normal way try and see if there is
  3906. * plenty of slack room in the global reserve to migrate, otherwise we cannot
  3907. * allow the unlink to occur.
  3908. */
  3909. static struct btrfs_trans_handle *__unlink_start_trans(struct inode *dir)
  3910. {
  3911. struct btrfs_root *root = BTRFS_I(dir)->root;
  3912. /*
  3913. * 1 for the possible orphan item
  3914. * 1 for the dir item
  3915. * 1 for the dir index
  3916. * 1 for the inode ref
  3917. * 1 for the inode
  3918. * 1 for the parent inode
  3919. */
  3920. return btrfs_start_transaction_fallback_global_rsv(root, 6);
  3921. }
  3922. static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
  3923. {
  3924. struct btrfs_trans_handle *trans;
  3925. struct inode *inode = d_inode(dentry);
  3926. int ret;
  3927. struct fscrypt_name fname;
  3928. ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
  3929. if (ret)
  3930. return ret;
  3931. /* This needs to handle no-key deletions later on */
  3932. trans = __unlink_start_trans(dir);
  3933. if (IS_ERR(trans)) {
  3934. ret = PTR_ERR(trans);
  3935. goto fscrypt_free;
  3936. }
  3937. btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
  3938. 0);
  3939. ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
  3940. &fname.disk_name);
  3941. if (ret)
  3942. goto end_trans;
  3943. if (inode->i_nlink == 0) {
  3944. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  3945. if (ret)
  3946. goto end_trans;
  3947. }
  3948. end_trans:
  3949. btrfs_end_transaction(trans);
  3950. btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
  3951. fscrypt_free:
  3952. fscrypt_free_filename(&fname);
  3953. return ret;
  3954. }
  3955. static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
  3956. struct inode *dir, struct dentry *dentry)
  3957. {
  3958. struct btrfs_root *root = BTRFS_I(dir)->root;
  3959. struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
  3960. struct btrfs_path *path;
  3961. struct extent_buffer *leaf;
  3962. struct btrfs_dir_item *di;
  3963. struct btrfs_key key;
  3964. u64 index;
  3965. int ret;
  3966. u64 objectid;
  3967. u64 dir_ino = btrfs_ino(BTRFS_I(dir));
  3968. struct fscrypt_name fname;
  3969. ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
  3970. if (ret)
  3971. return ret;
  3972. /* This needs to handle no-key deletions later on */
  3973. if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
  3974. objectid = inode->root->root_key.objectid;
  3975. } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
  3976. objectid = inode->location.objectid;
  3977. } else {
  3978. WARN_ON(1);
  3979. fscrypt_free_filename(&fname);
  3980. return -EINVAL;
  3981. }
  3982. path = btrfs_alloc_path();
  3983. if (!path) {
  3984. ret = -ENOMEM;
  3985. goto out;
  3986. }
  3987. di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
  3988. &fname.disk_name, -1);
  3989. if (IS_ERR_OR_NULL(di)) {
  3990. ret = di ? PTR_ERR(di) : -ENOENT;
  3991. goto out;
  3992. }
  3993. leaf = path->nodes[0];
  3994. btrfs_dir_item_key_to_cpu(leaf, di, &key);
  3995. WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
  3996. ret = btrfs_delete_one_dir_name(trans, root, path, di);
  3997. if (ret) {
  3998. btrfs_abort_transaction(trans, ret);
  3999. goto out;
  4000. }
  4001. btrfs_release_path(path);
  4002. /*
  4003. * This is a placeholder inode for a subvolume we didn't have a
  4004. * reference to at the time of the snapshot creation. In the meantime
  4005. * we could have renamed the real subvol link into our snapshot, so
  4006. * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
  4007. * Instead simply lookup the dir_index_item for this entry so we can
  4008. * remove it. Otherwise we know we have a ref to the root and we can
  4009. * call btrfs_del_root_ref, and it _shouldn't_ fail.
  4010. */
  4011. if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
  4012. di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
  4013. if (IS_ERR_OR_NULL(di)) {
  4014. if (!di)
  4015. ret = -ENOENT;
  4016. else
  4017. ret = PTR_ERR(di);
  4018. btrfs_abort_transaction(trans, ret);
  4019. goto out;
  4020. }
  4021. leaf = path->nodes[0];
  4022. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  4023. index = key.offset;
  4024. btrfs_release_path(path);
  4025. } else {
  4026. ret = btrfs_del_root_ref(trans, objectid,
  4027. root->root_key.objectid, dir_ino,
  4028. &index, &fname.disk_name);
  4029. if (ret) {
  4030. btrfs_abort_transaction(trans, ret);
  4031. goto out;
  4032. }
  4033. }
  4034. ret = btrfs_delete_delayed_dir_index(trans, BTRFS_I(dir), index);
  4035. if (ret) {
  4036. btrfs_abort_transaction(trans, ret);
  4037. goto out;
  4038. }
  4039. btrfs_i_size_write(BTRFS_I(dir), dir->i_size - fname.disk_name.len * 2);
  4040. inode_inc_iversion(dir);
  4041. dir->i_mtime = current_time(dir);
  4042. dir->i_ctime = dir->i_mtime;
  4043. ret = btrfs_update_inode_fallback(trans, root, BTRFS_I(dir));
  4044. if (ret)
  4045. btrfs_abort_transaction(trans, ret);
  4046. out:
  4047. btrfs_free_path(path);
  4048. fscrypt_free_filename(&fname);
  4049. return ret;
  4050. }
  4051. /*
  4052. * Helper to check if the subvolume references other subvolumes or if it's
  4053. * default.
  4054. */
  4055. static noinline int may_destroy_subvol(struct btrfs_root *root)
  4056. {
  4057. struct btrfs_fs_info *fs_info = root->fs_info;
  4058. struct btrfs_path *path;
  4059. struct btrfs_dir_item *di;
  4060. struct btrfs_key key;
  4061. struct fscrypt_str name = FSTR_INIT("default", 7);
  4062. u64 dir_id;
  4063. int ret;
  4064. path = btrfs_alloc_path();
  4065. if (!path)
  4066. return -ENOMEM;
  4067. /* Make sure this root isn't set as the default subvol */
  4068. dir_id = btrfs_super_root_dir(fs_info->super_copy);
  4069. di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
  4070. dir_id, &name, 0);
  4071. if (di && !IS_ERR(di)) {
  4072. btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
  4073. if (key.objectid == root->root_key.objectid) {
  4074. ret = -EPERM;
  4075. btrfs_err(fs_info,
  4076. "deleting default subvolume %llu is not allowed",
  4077. key.objectid);
  4078. goto out;
  4079. }
  4080. btrfs_release_path(path);
  4081. }
  4082. key.objectid = root->root_key.objectid;
  4083. key.type = BTRFS_ROOT_REF_KEY;
  4084. key.offset = (u64)-1;
  4085. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
  4086. if (ret < 0)
  4087. goto out;
  4088. BUG_ON(ret == 0);
  4089. ret = 0;
  4090. if (path->slots[0] > 0) {
  4091. path->slots[0]--;
  4092. btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
  4093. if (key.objectid == root->root_key.objectid &&
  4094. key.type == BTRFS_ROOT_REF_KEY)
  4095. ret = -ENOTEMPTY;
  4096. }
  4097. out:
  4098. btrfs_free_path(path);
  4099. return ret;
  4100. }
  4101. /* Delete all dentries for inodes belonging to the root */
  4102. static void btrfs_prune_dentries(struct btrfs_root *root)
  4103. {
  4104. struct btrfs_fs_info *fs_info = root->fs_info;
  4105. struct rb_node *node;
  4106. struct rb_node *prev;
  4107. struct btrfs_inode *entry;
  4108. struct inode *inode;
  4109. u64 objectid = 0;
  4110. if (!BTRFS_FS_ERROR(fs_info))
  4111. WARN_ON(btrfs_root_refs(&root->root_item) != 0);
  4112. spin_lock(&root->inode_lock);
  4113. again:
  4114. node = root->inode_tree.rb_node;
  4115. prev = NULL;
  4116. while (node) {
  4117. prev = node;
  4118. entry = rb_entry(node, struct btrfs_inode, rb_node);
  4119. if (objectid < btrfs_ino(entry))
  4120. node = node->rb_left;
  4121. else if (objectid > btrfs_ino(entry))
  4122. node = node->rb_right;
  4123. else
  4124. break;
  4125. }
  4126. if (!node) {
  4127. while (prev) {
  4128. entry = rb_entry(prev, struct btrfs_inode, rb_node);
  4129. if (objectid <= btrfs_ino(entry)) {
  4130. node = prev;
  4131. break;
  4132. }
  4133. prev = rb_next(prev);
  4134. }
  4135. }
  4136. while (node) {
  4137. entry = rb_entry(node, struct btrfs_inode, rb_node);
  4138. objectid = btrfs_ino(entry) + 1;
  4139. inode = igrab(&entry->vfs_inode);
  4140. if (inode) {
  4141. spin_unlock(&root->inode_lock);
  4142. if (atomic_read(&inode->i_count) > 1)
  4143. d_prune_aliases(inode);
  4144. /*
  4145. * btrfs_drop_inode will have it removed from the inode
  4146. * cache when its usage count hits zero.
  4147. */
  4148. iput(inode);
  4149. cond_resched();
  4150. spin_lock(&root->inode_lock);
  4151. goto again;
  4152. }
  4153. if (cond_resched_lock(&root->inode_lock))
  4154. goto again;
  4155. node = rb_next(node);
  4156. }
  4157. spin_unlock(&root->inode_lock);
  4158. }
  4159. int btrfs_delete_subvolume(struct inode *dir, struct dentry *dentry)
  4160. {
  4161. struct btrfs_fs_info *fs_info = btrfs_sb(dentry->d_sb);
  4162. struct btrfs_root *root = BTRFS_I(dir)->root;
  4163. struct inode *inode = d_inode(dentry);
  4164. struct btrfs_root *dest = BTRFS_I(inode)->root;
  4165. struct btrfs_trans_handle *trans;
  4166. struct btrfs_block_rsv block_rsv;
  4167. u64 root_flags;
  4168. int ret;
  4169. /*
  4170. * Don't allow to delete a subvolume with send in progress. This is
  4171. * inside the inode lock so the error handling that has to drop the bit
  4172. * again is not run concurrently.
  4173. */
  4174. spin_lock(&dest->root_item_lock);
  4175. if (dest->send_in_progress) {
  4176. spin_unlock(&dest->root_item_lock);
  4177. btrfs_warn(fs_info,
  4178. "attempt to delete subvolume %llu during send",
  4179. dest->root_key.objectid);
  4180. return -EPERM;
  4181. }
  4182. if (atomic_read(&dest->nr_swapfiles)) {
  4183. spin_unlock(&dest->root_item_lock);
  4184. btrfs_warn(fs_info,
  4185. "attempt to delete subvolume %llu with active swapfile",
  4186. root->root_key.objectid);
  4187. return -EPERM;
  4188. }
  4189. root_flags = btrfs_root_flags(&dest->root_item);
  4190. btrfs_set_root_flags(&dest->root_item,
  4191. root_flags | BTRFS_ROOT_SUBVOL_DEAD);
  4192. spin_unlock(&dest->root_item_lock);
  4193. down_write(&fs_info->subvol_sem);
  4194. ret = may_destroy_subvol(dest);
  4195. if (ret)
  4196. goto out_up_write;
  4197. btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
  4198. /*
  4199. * One for dir inode,
  4200. * two for dir entries,
  4201. * two for root ref/backref.
  4202. */
  4203. ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
  4204. if (ret)
  4205. goto out_up_write;
  4206. trans = btrfs_start_transaction(root, 0);
  4207. if (IS_ERR(trans)) {
  4208. ret = PTR_ERR(trans);
  4209. goto out_release;
  4210. }
  4211. trans->block_rsv = &block_rsv;
  4212. trans->bytes_reserved = block_rsv.size;
  4213. btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
  4214. ret = btrfs_unlink_subvol(trans, dir, dentry);
  4215. if (ret) {
  4216. btrfs_abort_transaction(trans, ret);
  4217. goto out_end_trans;
  4218. }
  4219. ret = btrfs_record_root_in_trans(trans, dest);
  4220. if (ret) {
  4221. btrfs_abort_transaction(trans, ret);
  4222. goto out_end_trans;
  4223. }
  4224. memset(&dest->root_item.drop_progress, 0,
  4225. sizeof(dest->root_item.drop_progress));
  4226. btrfs_set_root_drop_level(&dest->root_item, 0);
  4227. btrfs_set_root_refs(&dest->root_item, 0);
  4228. if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
  4229. ret = btrfs_insert_orphan_item(trans,
  4230. fs_info->tree_root,
  4231. dest->root_key.objectid);
  4232. if (ret) {
  4233. btrfs_abort_transaction(trans, ret);
  4234. goto out_end_trans;
  4235. }
  4236. }
  4237. ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
  4238. BTRFS_UUID_KEY_SUBVOL,
  4239. dest->root_key.objectid);
  4240. if (ret && ret != -ENOENT) {
  4241. btrfs_abort_transaction(trans, ret);
  4242. goto out_end_trans;
  4243. }
  4244. if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
  4245. ret = btrfs_uuid_tree_remove(trans,
  4246. dest->root_item.received_uuid,
  4247. BTRFS_UUID_KEY_RECEIVED_SUBVOL,
  4248. dest->root_key.objectid);
  4249. if (ret && ret != -ENOENT) {
  4250. btrfs_abort_transaction(trans, ret);
  4251. goto out_end_trans;
  4252. }
  4253. }
  4254. free_anon_bdev(dest->anon_dev);
  4255. dest->anon_dev = 0;
  4256. out_end_trans:
  4257. trans->block_rsv = NULL;
  4258. trans->bytes_reserved = 0;
  4259. ret = btrfs_end_transaction(trans);
  4260. inode->i_flags |= S_DEAD;
  4261. out_release:
  4262. btrfs_subvolume_release_metadata(root, &block_rsv);
  4263. out_up_write:
  4264. up_write(&fs_info->subvol_sem);
  4265. if (ret) {
  4266. spin_lock(&dest->root_item_lock);
  4267. root_flags = btrfs_root_flags(&dest->root_item);
  4268. btrfs_set_root_flags(&dest->root_item,
  4269. root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
  4270. spin_unlock(&dest->root_item_lock);
  4271. } else {
  4272. d_invalidate(dentry);
  4273. btrfs_prune_dentries(dest);
  4274. ASSERT(dest->send_in_progress == 0);
  4275. }
  4276. return ret;
  4277. }
  4278. static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
  4279. {
  4280. struct inode *inode = d_inode(dentry);
  4281. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  4282. int err = 0;
  4283. struct btrfs_trans_handle *trans;
  4284. u64 last_unlink_trans;
  4285. struct fscrypt_name fname;
  4286. if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
  4287. return -ENOTEMPTY;
  4288. if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
  4289. if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
  4290. btrfs_err(fs_info,
  4291. "extent tree v2 doesn't support snapshot deletion yet");
  4292. return -EOPNOTSUPP;
  4293. }
  4294. return btrfs_delete_subvolume(dir, dentry);
  4295. }
  4296. err = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
  4297. if (err)
  4298. return err;
  4299. /* This needs to handle no-key deletions later on */
  4300. trans = __unlink_start_trans(dir);
  4301. if (IS_ERR(trans)) {
  4302. err = PTR_ERR(trans);
  4303. goto out_notrans;
  4304. }
  4305. if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
  4306. err = btrfs_unlink_subvol(trans, dir, dentry);
  4307. goto out;
  4308. }
  4309. err = btrfs_orphan_add(trans, BTRFS_I(inode));
  4310. if (err)
  4311. goto out;
  4312. last_unlink_trans = BTRFS_I(inode)->last_unlink_trans;
  4313. /* now the directory is empty */
  4314. err = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
  4315. &fname.disk_name);
  4316. if (!err) {
  4317. btrfs_i_size_write(BTRFS_I(inode), 0);
  4318. /*
  4319. * Propagate the last_unlink_trans value of the deleted dir to
  4320. * its parent directory. This is to prevent an unrecoverable
  4321. * log tree in the case we do something like this:
  4322. * 1) create dir foo
  4323. * 2) create snapshot under dir foo
  4324. * 3) delete the snapshot
  4325. * 4) rmdir foo
  4326. * 5) mkdir foo
  4327. * 6) fsync foo or some file inside foo
  4328. */
  4329. if (last_unlink_trans >= trans->transid)
  4330. BTRFS_I(dir)->last_unlink_trans = last_unlink_trans;
  4331. }
  4332. out:
  4333. btrfs_end_transaction(trans);
  4334. out_notrans:
  4335. btrfs_btree_balance_dirty(fs_info);
  4336. fscrypt_free_filename(&fname);
  4337. return err;
  4338. }
  4339. /*
  4340. * btrfs_truncate_block - read, zero a chunk and write a block
  4341. * @inode - inode that we're zeroing
  4342. * @from - the offset to start zeroing
  4343. * @len - the length to zero, 0 to zero the entire range respective to the
  4344. * offset
  4345. * @front - zero up to the offset instead of from the offset on
  4346. *
  4347. * This will find the block for the "from" offset and cow the block and zero the
  4348. * part we want to zero. This is used with truncate and hole punching.
  4349. */
  4350. int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
  4351. int front)
  4352. {
  4353. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  4354. struct address_space *mapping = inode->vfs_inode.i_mapping;
  4355. struct extent_io_tree *io_tree = &inode->io_tree;
  4356. struct btrfs_ordered_extent *ordered;
  4357. struct extent_state *cached_state = NULL;
  4358. struct extent_changeset *data_reserved = NULL;
  4359. bool only_release_metadata = false;
  4360. u32 blocksize = fs_info->sectorsize;
  4361. pgoff_t index = from >> PAGE_SHIFT;
  4362. unsigned offset = from & (blocksize - 1);
  4363. struct page *page;
  4364. gfp_t mask = btrfs_alloc_write_mask(mapping);
  4365. size_t write_bytes = blocksize;
  4366. int ret = 0;
  4367. u64 block_start;
  4368. u64 block_end;
  4369. if (IS_ALIGNED(offset, blocksize) &&
  4370. (!len || IS_ALIGNED(len, blocksize)))
  4371. goto out;
  4372. block_start = round_down(from, blocksize);
  4373. block_end = block_start + blocksize - 1;
  4374. ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
  4375. blocksize, false);
  4376. if (ret < 0) {
  4377. if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
  4378. /* For nocow case, no need to reserve data space */
  4379. only_release_metadata = true;
  4380. } else {
  4381. goto out;
  4382. }
  4383. }
  4384. ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
  4385. if (ret < 0) {
  4386. if (!only_release_metadata)
  4387. btrfs_free_reserved_data_space(inode, data_reserved,
  4388. block_start, blocksize);
  4389. goto out;
  4390. }
  4391. again:
  4392. page = find_or_create_page(mapping, index, mask);
  4393. if (!page) {
  4394. btrfs_delalloc_release_space(inode, data_reserved, block_start,
  4395. blocksize, true);
  4396. btrfs_delalloc_release_extents(inode, blocksize);
  4397. ret = -ENOMEM;
  4398. goto out;
  4399. }
  4400. if (!PageUptodate(page)) {
  4401. ret = btrfs_read_folio(NULL, page_folio(page));
  4402. lock_page(page);
  4403. if (page->mapping != mapping) {
  4404. unlock_page(page);
  4405. put_page(page);
  4406. goto again;
  4407. }
  4408. if (!PageUptodate(page)) {
  4409. ret = -EIO;
  4410. goto out_unlock;
  4411. }
  4412. }
  4413. /*
  4414. * We unlock the page after the io is completed and then re-lock it
  4415. * above. release_folio() could have come in between that and cleared
  4416. * PagePrivate(), but left the page in the mapping. Set the page mapped
  4417. * here to make sure it's properly set for the subpage stuff.
  4418. */
  4419. ret = set_page_extent_mapped(page);
  4420. if (ret < 0)
  4421. goto out_unlock;
  4422. wait_on_page_writeback(page);
  4423. lock_extent(io_tree, block_start, block_end, &cached_state);
  4424. ordered = btrfs_lookup_ordered_extent(inode, block_start);
  4425. if (ordered) {
  4426. unlock_extent(io_tree, block_start, block_end, &cached_state);
  4427. unlock_page(page);
  4428. put_page(page);
  4429. btrfs_start_ordered_extent(ordered, 1);
  4430. btrfs_put_ordered_extent(ordered);
  4431. goto again;
  4432. }
  4433. clear_extent_bit(&inode->io_tree, block_start, block_end,
  4434. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  4435. &cached_state);
  4436. ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
  4437. &cached_state);
  4438. if (ret) {
  4439. unlock_extent(io_tree, block_start, block_end, &cached_state);
  4440. goto out_unlock;
  4441. }
  4442. if (offset != blocksize) {
  4443. if (!len)
  4444. len = blocksize - offset;
  4445. if (front)
  4446. memzero_page(page, (block_start - page_offset(page)),
  4447. offset);
  4448. else
  4449. memzero_page(page, (block_start - page_offset(page)) + offset,
  4450. len);
  4451. }
  4452. btrfs_page_clear_checked(fs_info, page, block_start,
  4453. block_end + 1 - block_start);
  4454. btrfs_page_set_dirty(fs_info, page, block_start, block_end + 1 - block_start);
  4455. unlock_extent(io_tree, block_start, block_end, &cached_state);
  4456. if (only_release_metadata)
  4457. set_extent_bit(&inode->io_tree, block_start, block_end,
  4458. EXTENT_NORESERVE, NULL, GFP_NOFS);
  4459. out_unlock:
  4460. if (ret) {
  4461. if (only_release_metadata)
  4462. btrfs_delalloc_release_metadata(inode, blocksize, true);
  4463. else
  4464. btrfs_delalloc_release_space(inode, data_reserved,
  4465. block_start, blocksize, true);
  4466. }
  4467. btrfs_delalloc_release_extents(inode, blocksize);
  4468. unlock_page(page);
  4469. put_page(page);
  4470. out:
  4471. if (only_release_metadata)
  4472. btrfs_check_nocow_unlock(inode);
  4473. extent_changeset_free(data_reserved);
  4474. return ret;
  4475. }
  4476. static int maybe_insert_hole(struct btrfs_root *root, struct btrfs_inode *inode,
  4477. u64 offset, u64 len)
  4478. {
  4479. struct btrfs_fs_info *fs_info = root->fs_info;
  4480. struct btrfs_trans_handle *trans;
  4481. struct btrfs_drop_extents_args drop_args = { 0 };
  4482. int ret;
  4483. /*
  4484. * If NO_HOLES is enabled, we don't need to do anything.
  4485. * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
  4486. * or btrfs_update_inode() will be called, which guarantee that the next
  4487. * fsync will know this inode was changed and needs to be logged.
  4488. */
  4489. if (btrfs_fs_incompat(fs_info, NO_HOLES))
  4490. return 0;
  4491. /*
  4492. * 1 - for the one we're dropping
  4493. * 1 - for the one we're adding
  4494. * 1 - for updating the inode.
  4495. */
  4496. trans = btrfs_start_transaction(root, 3);
  4497. if (IS_ERR(trans))
  4498. return PTR_ERR(trans);
  4499. drop_args.start = offset;
  4500. drop_args.end = offset + len;
  4501. drop_args.drop_cache = true;
  4502. ret = btrfs_drop_extents(trans, root, inode, &drop_args);
  4503. if (ret) {
  4504. btrfs_abort_transaction(trans, ret);
  4505. btrfs_end_transaction(trans);
  4506. return ret;
  4507. }
  4508. ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
  4509. if (ret) {
  4510. btrfs_abort_transaction(trans, ret);
  4511. } else {
  4512. btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
  4513. btrfs_update_inode(trans, root, inode);
  4514. }
  4515. btrfs_end_transaction(trans);
  4516. return ret;
  4517. }
  4518. /*
  4519. * This function puts in dummy file extents for the area we're creating a hole
  4520. * for. So if we are truncating this file to a larger size we need to insert
  4521. * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
  4522. * the range between oldsize and size
  4523. */
  4524. int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
  4525. {
  4526. struct btrfs_root *root = inode->root;
  4527. struct btrfs_fs_info *fs_info = root->fs_info;
  4528. struct extent_io_tree *io_tree = &inode->io_tree;
  4529. struct extent_map *em = NULL;
  4530. struct extent_state *cached_state = NULL;
  4531. u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
  4532. u64 block_end = ALIGN(size, fs_info->sectorsize);
  4533. u64 last_byte;
  4534. u64 cur_offset;
  4535. u64 hole_size;
  4536. int err = 0;
  4537. /*
  4538. * If our size started in the middle of a block we need to zero out the
  4539. * rest of the block before we expand the i_size, otherwise we could
  4540. * expose stale data.
  4541. */
  4542. err = btrfs_truncate_block(inode, oldsize, 0, 0);
  4543. if (err)
  4544. return err;
  4545. if (size <= hole_start)
  4546. return 0;
  4547. btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
  4548. &cached_state);
  4549. cur_offset = hole_start;
  4550. while (1) {
  4551. em = btrfs_get_extent(inode, NULL, 0, cur_offset,
  4552. block_end - cur_offset);
  4553. if (IS_ERR(em)) {
  4554. err = PTR_ERR(em);
  4555. em = NULL;
  4556. break;
  4557. }
  4558. last_byte = min(extent_map_end(em), block_end);
  4559. last_byte = ALIGN(last_byte, fs_info->sectorsize);
  4560. hole_size = last_byte - cur_offset;
  4561. if (!test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
  4562. struct extent_map *hole_em;
  4563. err = maybe_insert_hole(root, inode, cur_offset,
  4564. hole_size);
  4565. if (err)
  4566. break;
  4567. err = btrfs_inode_set_file_extent_range(inode,
  4568. cur_offset, hole_size);
  4569. if (err)
  4570. break;
  4571. hole_em = alloc_extent_map();
  4572. if (!hole_em) {
  4573. btrfs_drop_extent_map_range(inode, cur_offset,
  4574. cur_offset + hole_size - 1,
  4575. false);
  4576. btrfs_set_inode_full_sync(inode);
  4577. goto next;
  4578. }
  4579. hole_em->start = cur_offset;
  4580. hole_em->len = hole_size;
  4581. hole_em->orig_start = cur_offset;
  4582. hole_em->block_start = EXTENT_MAP_HOLE;
  4583. hole_em->block_len = 0;
  4584. hole_em->orig_block_len = 0;
  4585. hole_em->ram_bytes = hole_size;
  4586. hole_em->compress_type = BTRFS_COMPRESS_NONE;
  4587. hole_em->generation = fs_info->generation;
  4588. err = btrfs_replace_extent_map_range(inode, hole_em, true);
  4589. free_extent_map(hole_em);
  4590. } else {
  4591. err = btrfs_inode_set_file_extent_range(inode,
  4592. cur_offset, hole_size);
  4593. if (err)
  4594. break;
  4595. }
  4596. next:
  4597. free_extent_map(em);
  4598. em = NULL;
  4599. cur_offset = last_byte;
  4600. if (cur_offset >= block_end)
  4601. break;
  4602. }
  4603. free_extent_map(em);
  4604. unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
  4605. return err;
  4606. }
  4607. static int btrfs_setsize(struct inode *inode, struct iattr *attr)
  4608. {
  4609. struct btrfs_root *root = BTRFS_I(inode)->root;
  4610. struct btrfs_trans_handle *trans;
  4611. loff_t oldsize = i_size_read(inode);
  4612. loff_t newsize = attr->ia_size;
  4613. int mask = attr->ia_valid;
  4614. int ret;
  4615. /*
  4616. * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
  4617. * special case where we need to update the times despite not having
  4618. * these flags set. For all other operations the VFS set these flags
  4619. * explicitly if it wants a timestamp update.
  4620. */
  4621. if (newsize != oldsize) {
  4622. inode_inc_iversion(inode);
  4623. if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
  4624. inode->i_mtime = current_time(inode);
  4625. inode->i_ctime = inode->i_mtime;
  4626. }
  4627. }
  4628. if (newsize > oldsize) {
  4629. /*
  4630. * Don't do an expanding truncate while snapshotting is ongoing.
  4631. * This is to ensure the snapshot captures a fully consistent
  4632. * state of this file - if the snapshot captures this expanding
  4633. * truncation, it must capture all writes that happened before
  4634. * this truncation.
  4635. */
  4636. btrfs_drew_write_lock(&root->snapshot_lock);
  4637. ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
  4638. if (ret) {
  4639. btrfs_drew_write_unlock(&root->snapshot_lock);
  4640. return ret;
  4641. }
  4642. trans = btrfs_start_transaction(root, 1);
  4643. if (IS_ERR(trans)) {
  4644. btrfs_drew_write_unlock(&root->snapshot_lock);
  4645. return PTR_ERR(trans);
  4646. }
  4647. i_size_write(inode, newsize);
  4648. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
  4649. pagecache_isize_extended(inode, oldsize, newsize);
  4650. ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
  4651. btrfs_drew_write_unlock(&root->snapshot_lock);
  4652. btrfs_end_transaction(trans);
  4653. } else {
  4654. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  4655. if (btrfs_is_zoned(fs_info)) {
  4656. ret = btrfs_wait_ordered_range(inode,
  4657. ALIGN(newsize, fs_info->sectorsize),
  4658. (u64)-1);
  4659. if (ret)
  4660. return ret;
  4661. }
  4662. /*
  4663. * We're truncating a file that used to have good data down to
  4664. * zero. Make sure any new writes to the file get on disk
  4665. * on close.
  4666. */
  4667. if (newsize == 0)
  4668. set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
  4669. &BTRFS_I(inode)->runtime_flags);
  4670. truncate_setsize(inode, newsize);
  4671. inode_dio_wait(inode);
  4672. ret = btrfs_truncate(inode, newsize == oldsize);
  4673. if (ret && inode->i_nlink) {
  4674. int err;
  4675. /*
  4676. * Truncate failed, so fix up the in-memory size. We
  4677. * adjusted disk_i_size down as we removed extents, so
  4678. * wait for disk_i_size to be stable and then update the
  4679. * in-memory size to match.
  4680. */
  4681. err = btrfs_wait_ordered_range(inode, 0, (u64)-1);
  4682. if (err)
  4683. return err;
  4684. i_size_write(inode, BTRFS_I(inode)->disk_i_size);
  4685. }
  4686. }
  4687. return ret;
  4688. }
  4689. static int btrfs_setattr(struct user_namespace *mnt_userns, struct dentry *dentry,
  4690. struct iattr *attr)
  4691. {
  4692. struct inode *inode = d_inode(dentry);
  4693. struct btrfs_root *root = BTRFS_I(inode)->root;
  4694. int err;
  4695. if (btrfs_root_readonly(root))
  4696. return -EROFS;
  4697. err = setattr_prepare(mnt_userns, dentry, attr);
  4698. if (err)
  4699. return err;
  4700. if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
  4701. err = btrfs_setsize(inode, attr);
  4702. if (err)
  4703. return err;
  4704. }
  4705. if (attr->ia_valid) {
  4706. setattr_copy(mnt_userns, inode, attr);
  4707. inode_inc_iversion(inode);
  4708. err = btrfs_dirty_inode(inode);
  4709. if (!err && attr->ia_valid & ATTR_MODE)
  4710. err = posix_acl_chmod(mnt_userns, inode, inode->i_mode);
  4711. }
  4712. return err;
  4713. }
  4714. /*
  4715. * While truncating the inode pages during eviction, we get the VFS
  4716. * calling btrfs_invalidate_folio() against each folio of the inode. This
  4717. * is slow because the calls to btrfs_invalidate_folio() result in a
  4718. * huge amount of calls to lock_extent() and clear_extent_bit(),
  4719. * which keep merging and splitting extent_state structures over and over,
  4720. * wasting lots of time.
  4721. *
  4722. * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
  4723. * skip all those expensive operations on a per folio basis and do only
  4724. * the ordered io finishing, while we release here the extent_map and
  4725. * extent_state structures, without the excessive merging and splitting.
  4726. */
  4727. static void evict_inode_truncate_pages(struct inode *inode)
  4728. {
  4729. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  4730. struct rb_node *node;
  4731. ASSERT(inode->i_state & I_FREEING);
  4732. truncate_inode_pages_final(&inode->i_data);
  4733. btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
  4734. /*
  4735. * Keep looping until we have no more ranges in the io tree.
  4736. * We can have ongoing bios started by readahead that have
  4737. * their endio callback (extent_io.c:end_bio_extent_readpage)
  4738. * still in progress (unlocked the pages in the bio but did not yet
  4739. * unlocked the ranges in the io tree). Therefore this means some
  4740. * ranges can still be locked and eviction started because before
  4741. * submitting those bios, which are executed by a separate task (work
  4742. * queue kthread), inode references (inode->i_count) were not taken
  4743. * (which would be dropped in the end io callback of each bio).
  4744. * Therefore here we effectively end up waiting for those bios and
  4745. * anyone else holding locked ranges without having bumped the inode's
  4746. * reference count - if we don't do it, when they access the inode's
  4747. * io_tree to unlock a range it may be too late, leading to an
  4748. * use-after-free issue.
  4749. */
  4750. spin_lock(&io_tree->lock);
  4751. while (!RB_EMPTY_ROOT(&io_tree->state)) {
  4752. struct extent_state *state;
  4753. struct extent_state *cached_state = NULL;
  4754. u64 start;
  4755. u64 end;
  4756. unsigned state_flags;
  4757. node = rb_first(&io_tree->state);
  4758. state = rb_entry(node, struct extent_state, rb_node);
  4759. start = state->start;
  4760. end = state->end;
  4761. state_flags = state->state;
  4762. spin_unlock(&io_tree->lock);
  4763. lock_extent(io_tree, start, end, &cached_state);
  4764. /*
  4765. * If still has DELALLOC flag, the extent didn't reach disk,
  4766. * and its reserved space won't be freed by delayed_ref.
  4767. * So we need to free its reserved space here.
  4768. * (Refer to comment in btrfs_invalidate_folio, case 2)
  4769. *
  4770. * Note, end is the bytenr of last byte, so we need + 1 here.
  4771. */
  4772. if (state_flags & EXTENT_DELALLOC)
  4773. btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
  4774. end - start + 1);
  4775. clear_extent_bit(io_tree, start, end,
  4776. EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
  4777. &cached_state);
  4778. cond_resched();
  4779. spin_lock(&io_tree->lock);
  4780. }
  4781. spin_unlock(&io_tree->lock);
  4782. }
  4783. static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
  4784. struct btrfs_block_rsv *rsv)
  4785. {
  4786. struct btrfs_fs_info *fs_info = root->fs_info;
  4787. struct btrfs_trans_handle *trans;
  4788. u64 delayed_refs_extra = btrfs_calc_insert_metadata_size(fs_info, 1);
  4789. int ret;
  4790. /*
  4791. * Eviction should be taking place at some place safe because of our
  4792. * delayed iputs. However the normal flushing code will run delayed
  4793. * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
  4794. *
  4795. * We reserve the delayed_refs_extra here again because we can't use
  4796. * btrfs_start_transaction(root, 0) for the same deadlocky reason as
  4797. * above. We reserve our extra bit here because we generate a ton of
  4798. * delayed refs activity by truncating.
  4799. *
  4800. * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
  4801. * if we fail to make this reservation we can re-try without the
  4802. * delayed_refs_extra so we can make some forward progress.
  4803. */
  4804. ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
  4805. BTRFS_RESERVE_FLUSH_EVICT);
  4806. if (ret) {
  4807. ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
  4808. BTRFS_RESERVE_FLUSH_EVICT);
  4809. if (ret) {
  4810. btrfs_warn(fs_info,
  4811. "could not allocate space for delete; will truncate on mount");
  4812. return ERR_PTR(-ENOSPC);
  4813. }
  4814. delayed_refs_extra = 0;
  4815. }
  4816. trans = btrfs_join_transaction(root);
  4817. if (IS_ERR(trans))
  4818. return trans;
  4819. if (delayed_refs_extra) {
  4820. trans->block_rsv = &fs_info->trans_block_rsv;
  4821. trans->bytes_reserved = delayed_refs_extra;
  4822. btrfs_block_rsv_migrate(rsv, trans->block_rsv,
  4823. delayed_refs_extra, 1);
  4824. }
  4825. return trans;
  4826. }
  4827. void btrfs_evict_inode(struct inode *inode)
  4828. {
  4829. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  4830. struct btrfs_trans_handle *trans;
  4831. struct btrfs_root *root = BTRFS_I(inode)->root;
  4832. struct btrfs_block_rsv *rsv;
  4833. int ret;
  4834. trace_btrfs_inode_evict(inode);
  4835. if (!root) {
  4836. fsverity_cleanup_inode(inode);
  4837. clear_inode(inode);
  4838. return;
  4839. }
  4840. evict_inode_truncate_pages(inode);
  4841. if (inode->i_nlink &&
  4842. ((btrfs_root_refs(&root->root_item) != 0 &&
  4843. root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID) ||
  4844. btrfs_is_free_space_inode(BTRFS_I(inode))))
  4845. goto no_delete;
  4846. if (is_bad_inode(inode))
  4847. goto no_delete;
  4848. btrfs_free_io_failure_record(BTRFS_I(inode), 0, (u64)-1);
  4849. if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
  4850. goto no_delete;
  4851. if (inode->i_nlink > 0) {
  4852. BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
  4853. root->root_key.objectid != BTRFS_ROOT_TREE_OBJECTID);
  4854. goto no_delete;
  4855. }
  4856. /*
  4857. * This makes sure the inode item in tree is uptodate and the space for
  4858. * the inode update is released.
  4859. */
  4860. ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
  4861. if (ret)
  4862. goto no_delete;
  4863. /*
  4864. * This drops any pending insert or delete operations we have for this
  4865. * inode. We could have a delayed dir index deletion queued up, but
  4866. * we're removing the inode completely so that'll be taken care of in
  4867. * the truncate.
  4868. */
  4869. btrfs_kill_delayed_inode_items(BTRFS_I(inode));
  4870. rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
  4871. if (!rsv)
  4872. goto no_delete;
  4873. rsv->size = btrfs_calc_metadata_size(fs_info, 1);
  4874. rsv->failfast = true;
  4875. btrfs_i_size_write(BTRFS_I(inode), 0);
  4876. while (1) {
  4877. struct btrfs_truncate_control control = {
  4878. .inode = BTRFS_I(inode),
  4879. .ino = btrfs_ino(BTRFS_I(inode)),
  4880. .new_size = 0,
  4881. .min_type = 0,
  4882. };
  4883. trans = evict_refill_and_join(root, rsv);
  4884. if (IS_ERR(trans))
  4885. goto free_rsv;
  4886. trans->block_rsv = rsv;
  4887. ret = btrfs_truncate_inode_items(trans, root, &control);
  4888. trans->block_rsv = &fs_info->trans_block_rsv;
  4889. btrfs_end_transaction(trans);
  4890. btrfs_btree_balance_dirty(fs_info);
  4891. if (ret && ret != -ENOSPC && ret != -EAGAIN)
  4892. goto free_rsv;
  4893. else if (!ret)
  4894. break;
  4895. }
  4896. /*
  4897. * Errors here aren't a big deal, it just means we leave orphan items in
  4898. * the tree. They will be cleaned up on the next mount. If the inode
  4899. * number gets reused, cleanup deletes the orphan item without doing
  4900. * anything, and unlink reuses the existing orphan item.
  4901. *
  4902. * If it turns out that we are dropping too many of these, we might want
  4903. * to add a mechanism for retrying these after a commit.
  4904. */
  4905. trans = evict_refill_and_join(root, rsv);
  4906. if (!IS_ERR(trans)) {
  4907. trans->block_rsv = rsv;
  4908. btrfs_orphan_del(trans, BTRFS_I(inode));
  4909. trans->block_rsv = &fs_info->trans_block_rsv;
  4910. btrfs_end_transaction(trans);
  4911. }
  4912. free_rsv:
  4913. btrfs_free_block_rsv(fs_info, rsv);
  4914. no_delete:
  4915. /*
  4916. * If we didn't successfully delete, the orphan item will still be in
  4917. * the tree and we'll retry on the next mount. Again, we might also want
  4918. * to retry these periodically in the future.
  4919. */
  4920. btrfs_remove_delayed_node(BTRFS_I(inode));
  4921. fsverity_cleanup_inode(inode);
  4922. clear_inode(inode);
  4923. }
  4924. /*
  4925. * Return the key found in the dir entry in the location pointer, fill @type
  4926. * with BTRFS_FT_*, and return 0.
  4927. *
  4928. * If no dir entries were found, returns -ENOENT.
  4929. * If found a corrupted location in dir entry, returns -EUCLEAN.
  4930. */
  4931. static int btrfs_inode_by_name(struct inode *dir, struct dentry *dentry,
  4932. struct btrfs_key *location, u8 *type)
  4933. {
  4934. struct btrfs_dir_item *di;
  4935. struct btrfs_path *path;
  4936. struct btrfs_root *root = BTRFS_I(dir)->root;
  4937. int ret = 0;
  4938. struct fscrypt_name fname;
  4939. path = btrfs_alloc_path();
  4940. if (!path)
  4941. return -ENOMEM;
  4942. ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
  4943. if (ret)
  4944. goto out;
  4945. /* This needs to handle no-key deletions later on */
  4946. di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(BTRFS_I(dir)),
  4947. &fname.disk_name, 0);
  4948. if (IS_ERR_OR_NULL(di)) {
  4949. ret = di ? PTR_ERR(di) : -ENOENT;
  4950. goto out;
  4951. }
  4952. btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
  4953. if (location->type != BTRFS_INODE_ITEM_KEY &&
  4954. location->type != BTRFS_ROOT_ITEM_KEY) {
  4955. ret = -EUCLEAN;
  4956. btrfs_warn(root->fs_info,
  4957. "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
  4958. __func__, fname.disk_name.name, btrfs_ino(BTRFS_I(dir)),
  4959. location->objectid, location->type, location->offset);
  4960. }
  4961. if (!ret)
  4962. *type = btrfs_dir_type(path->nodes[0], di);
  4963. out:
  4964. fscrypt_free_filename(&fname);
  4965. btrfs_free_path(path);
  4966. return ret;
  4967. }
  4968. /*
  4969. * when we hit a tree root in a directory, the btrfs part of the inode
  4970. * needs to be changed to reflect the root directory of the tree root. This
  4971. * is kind of like crossing a mount point.
  4972. */
  4973. static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
  4974. struct inode *dir,
  4975. struct dentry *dentry,
  4976. struct btrfs_key *location,
  4977. struct btrfs_root **sub_root)
  4978. {
  4979. struct btrfs_path *path;
  4980. struct btrfs_root *new_root;
  4981. struct btrfs_root_ref *ref;
  4982. struct extent_buffer *leaf;
  4983. struct btrfs_key key;
  4984. int ret;
  4985. int err = 0;
  4986. struct fscrypt_name fname;
  4987. ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
  4988. if (ret)
  4989. return ret;
  4990. path = btrfs_alloc_path();
  4991. if (!path) {
  4992. err = -ENOMEM;
  4993. goto out;
  4994. }
  4995. err = -ENOENT;
  4996. key.objectid = BTRFS_I(dir)->root->root_key.objectid;
  4997. key.type = BTRFS_ROOT_REF_KEY;
  4998. key.offset = location->objectid;
  4999. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
  5000. if (ret) {
  5001. if (ret < 0)
  5002. err = ret;
  5003. goto out;
  5004. }
  5005. leaf = path->nodes[0];
  5006. ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
  5007. if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(BTRFS_I(dir)) ||
  5008. btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
  5009. goto out;
  5010. ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
  5011. (unsigned long)(ref + 1), fname.disk_name.len);
  5012. if (ret)
  5013. goto out;
  5014. btrfs_release_path(path);
  5015. new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
  5016. if (IS_ERR(new_root)) {
  5017. err = PTR_ERR(new_root);
  5018. goto out;
  5019. }
  5020. *sub_root = new_root;
  5021. location->objectid = btrfs_root_dirid(&new_root->root_item);
  5022. location->type = BTRFS_INODE_ITEM_KEY;
  5023. location->offset = 0;
  5024. err = 0;
  5025. out:
  5026. btrfs_free_path(path);
  5027. fscrypt_free_filename(&fname);
  5028. return err;
  5029. }
  5030. static void inode_tree_add(struct inode *inode)
  5031. {
  5032. struct btrfs_root *root = BTRFS_I(inode)->root;
  5033. struct btrfs_inode *entry;
  5034. struct rb_node **p;
  5035. struct rb_node *parent;
  5036. struct rb_node *new = &BTRFS_I(inode)->rb_node;
  5037. u64 ino = btrfs_ino(BTRFS_I(inode));
  5038. if (inode_unhashed(inode))
  5039. return;
  5040. parent = NULL;
  5041. spin_lock(&root->inode_lock);
  5042. p = &root->inode_tree.rb_node;
  5043. while (*p) {
  5044. parent = *p;
  5045. entry = rb_entry(parent, struct btrfs_inode, rb_node);
  5046. if (ino < btrfs_ino(entry))
  5047. p = &parent->rb_left;
  5048. else if (ino > btrfs_ino(entry))
  5049. p = &parent->rb_right;
  5050. else {
  5051. WARN_ON(!(entry->vfs_inode.i_state &
  5052. (I_WILL_FREE | I_FREEING)));
  5053. rb_replace_node(parent, new, &root->inode_tree);
  5054. RB_CLEAR_NODE(parent);
  5055. spin_unlock(&root->inode_lock);
  5056. return;
  5057. }
  5058. }
  5059. rb_link_node(new, parent, p);
  5060. rb_insert_color(new, &root->inode_tree);
  5061. spin_unlock(&root->inode_lock);
  5062. }
  5063. static void inode_tree_del(struct btrfs_inode *inode)
  5064. {
  5065. struct btrfs_root *root = inode->root;
  5066. int empty = 0;
  5067. spin_lock(&root->inode_lock);
  5068. if (!RB_EMPTY_NODE(&inode->rb_node)) {
  5069. rb_erase(&inode->rb_node, &root->inode_tree);
  5070. RB_CLEAR_NODE(&inode->rb_node);
  5071. empty = RB_EMPTY_ROOT(&root->inode_tree);
  5072. }
  5073. spin_unlock(&root->inode_lock);
  5074. if (empty && btrfs_root_refs(&root->root_item) == 0) {
  5075. spin_lock(&root->inode_lock);
  5076. empty = RB_EMPTY_ROOT(&root->inode_tree);
  5077. spin_unlock(&root->inode_lock);
  5078. if (empty)
  5079. btrfs_add_dead_root(root);
  5080. }
  5081. }
  5082. static int btrfs_init_locked_inode(struct inode *inode, void *p)
  5083. {
  5084. struct btrfs_iget_args *args = p;
  5085. inode->i_ino = args->ino;
  5086. BTRFS_I(inode)->location.objectid = args->ino;
  5087. BTRFS_I(inode)->location.type = BTRFS_INODE_ITEM_KEY;
  5088. BTRFS_I(inode)->location.offset = 0;
  5089. BTRFS_I(inode)->root = btrfs_grab_root(args->root);
  5090. BUG_ON(args->root && !BTRFS_I(inode)->root);
  5091. if (args->root && args->root == args->root->fs_info->tree_root &&
  5092. args->ino != BTRFS_BTREE_INODE_OBJECTID)
  5093. set_bit(BTRFS_INODE_FREE_SPACE_INODE,
  5094. &BTRFS_I(inode)->runtime_flags);
  5095. return 0;
  5096. }
  5097. static int btrfs_find_actor(struct inode *inode, void *opaque)
  5098. {
  5099. struct btrfs_iget_args *args = opaque;
  5100. return args->ino == BTRFS_I(inode)->location.objectid &&
  5101. args->root == BTRFS_I(inode)->root;
  5102. }
  5103. static struct inode *btrfs_iget_locked(struct super_block *s, u64 ino,
  5104. struct btrfs_root *root)
  5105. {
  5106. struct inode *inode;
  5107. struct btrfs_iget_args args;
  5108. unsigned long hashval = btrfs_inode_hash(ino, root);
  5109. args.ino = ino;
  5110. args.root = root;
  5111. inode = iget5_locked(s, hashval, btrfs_find_actor,
  5112. btrfs_init_locked_inode,
  5113. (void *)&args);
  5114. return inode;
  5115. }
  5116. /*
  5117. * Get an inode object given its inode number and corresponding root.
  5118. * Path can be preallocated to prevent recursing back to iget through
  5119. * allocator. NULL is also valid but may require an additional allocation
  5120. * later.
  5121. */
  5122. struct inode *btrfs_iget_path(struct super_block *s, u64 ino,
  5123. struct btrfs_root *root, struct btrfs_path *path)
  5124. {
  5125. struct inode *inode;
  5126. inode = btrfs_iget_locked(s, ino, root);
  5127. if (!inode)
  5128. return ERR_PTR(-ENOMEM);
  5129. if (inode->i_state & I_NEW) {
  5130. int ret;
  5131. ret = btrfs_read_locked_inode(inode, path);
  5132. if (!ret) {
  5133. inode_tree_add(inode);
  5134. unlock_new_inode(inode);
  5135. } else {
  5136. iget_failed(inode);
  5137. /*
  5138. * ret > 0 can come from btrfs_search_slot called by
  5139. * btrfs_read_locked_inode, this means the inode item
  5140. * was not found.
  5141. */
  5142. if (ret > 0)
  5143. ret = -ENOENT;
  5144. inode = ERR_PTR(ret);
  5145. }
  5146. }
  5147. return inode;
  5148. }
  5149. struct inode *btrfs_iget(struct super_block *s, u64 ino, struct btrfs_root *root)
  5150. {
  5151. return btrfs_iget_path(s, ino, root, NULL);
  5152. }
  5153. static struct inode *new_simple_dir(struct super_block *s,
  5154. struct btrfs_key *key,
  5155. struct btrfs_root *root)
  5156. {
  5157. struct inode *inode = new_inode(s);
  5158. if (!inode)
  5159. return ERR_PTR(-ENOMEM);
  5160. BTRFS_I(inode)->root = btrfs_grab_root(root);
  5161. memcpy(&BTRFS_I(inode)->location, key, sizeof(*key));
  5162. set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
  5163. inode->i_ino = BTRFS_EMPTY_SUBVOL_DIR_OBJECTID;
  5164. /*
  5165. * We only need lookup, the rest is read-only and there's no inode
  5166. * associated with the dentry
  5167. */
  5168. inode->i_op = &simple_dir_inode_operations;
  5169. inode->i_opflags &= ~IOP_XATTR;
  5170. inode->i_fop = &simple_dir_operations;
  5171. inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
  5172. inode->i_mtime = current_time(inode);
  5173. inode->i_atime = inode->i_mtime;
  5174. inode->i_ctime = inode->i_mtime;
  5175. BTRFS_I(inode)->i_otime = inode->i_mtime;
  5176. return inode;
  5177. }
  5178. static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
  5179. static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
  5180. static_assert(BTRFS_FT_DIR == FT_DIR);
  5181. static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
  5182. static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
  5183. static_assert(BTRFS_FT_FIFO == FT_FIFO);
  5184. static_assert(BTRFS_FT_SOCK == FT_SOCK);
  5185. static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
  5186. static inline u8 btrfs_inode_type(struct inode *inode)
  5187. {
  5188. return fs_umode_to_ftype(inode->i_mode);
  5189. }
  5190. struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
  5191. {
  5192. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  5193. struct inode *inode;
  5194. struct btrfs_root *root = BTRFS_I(dir)->root;
  5195. struct btrfs_root *sub_root = root;
  5196. struct btrfs_key location;
  5197. u8 di_type = 0;
  5198. int ret = 0;
  5199. if (dentry->d_name.len > BTRFS_NAME_LEN)
  5200. return ERR_PTR(-ENAMETOOLONG);
  5201. ret = btrfs_inode_by_name(dir, dentry, &location, &di_type);
  5202. if (ret < 0)
  5203. return ERR_PTR(ret);
  5204. if (location.type == BTRFS_INODE_ITEM_KEY) {
  5205. inode = btrfs_iget(dir->i_sb, location.objectid, root);
  5206. if (IS_ERR(inode))
  5207. return inode;
  5208. /* Do extra check against inode mode with di_type */
  5209. if (btrfs_inode_type(inode) != di_type) {
  5210. btrfs_crit(fs_info,
  5211. "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
  5212. inode->i_mode, btrfs_inode_type(inode),
  5213. di_type);
  5214. iput(inode);
  5215. return ERR_PTR(-EUCLEAN);
  5216. }
  5217. return inode;
  5218. }
  5219. ret = fixup_tree_root_location(fs_info, dir, dentry,
  5220. &location, &sub_root);
  5221. if (ret < 0) {
  5222. if (ret != -ENOENT)
  5223. inode = ERR_PTR(ret);
  5224. else
  5225. inode = new_simple_dir(dir->i_sb, &location, root);
  5226. } else {
  5227. inode = btrfs_iget(dir->i_sb, location.objectid, sub_root);
  5228. btrfs_put_root(sub_root);
  5229. if (IS_ERR(inode))
  5230. return inode;
  5231. down_read(&fs_info->cleanup_work_sem);
  5232. if (!sb_rdonly(inode->i_sb))
  5233. ret = btrfs_orphan_cleanup(sub_root);
  5234. up_read(&fs_info->cleanup_work_sem);
  5235. if (ret) {
  5236. iput(inode);
  5237. inode = ERR_PTR(ret);
  5238. }
  5239. }
  5240. return inode;
  5241. }
  5242. static int btrfs_dentry_delete(const struct dentry *dentry)
  5243. {
  5244. struct btrfs_root *root;
  5245. struct inode *inode = d_inode(dentry);
  5246. if (!inode && !IS_ROOT(dentry))
  5247. inode = d_inode(dentry->d_parent);
  5248. if (inode) {
  5249. root = BTRFS_I(inode)->root;
  5250. if (btrfs_root_refs(&root->root_item) == 0)
  5251. return 1;
  5252. if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
  5253. return 1;
  5254. }
  5255. return 0;
  5256. }
  5257. static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
  5258. unsigned int flags)
  5259. {
  5260. struct inode *inode = btrfs_lookup_dentry(dir, dentry);
  5261. if (inode == ERR_PTR(-ENOENT))
  5262. inode = NULL;
  5263. return d_splice_alias(inode, dentry);
  5264. }
  5265. /*
  5266. * All this infrastructure exists because dir_emit can fault, and we are holding
  5267. * the tree lock when doing readdir. For now just allocate a buffer and copy
  5268. * our information into that, and then dir_emit from the buffer. This is
  5269. * similar to what NFS does, only we don't keep the buffer around in pagecache
  5270. * because I'm afraid I'll mess that up. Long term we need to make filldir do
  5271. * copy_to_user_inatomic so we don't have to worry about page faulting under the
  5272. * tree lock.
  5273. */
  5274. static int btrfs_opendir(struct inode *inode, struct file *file)
  5275. {
  5276. struct btrfs_file_private *private;
  5277. private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
  5278. if (!private)
  5279. return -ENOMEM;
  5280. private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
  5281. if (!private->filldir_buf) {
  5282. kfree(private);
  5283. return -ENOMEM;
  5284. }
  5285. file->private_data = private;
  5286. return 0;
  5287. }
  5288. struct dir_entry {
  5289. u64 ino;
  5290. u64 offset;
  5291. unsigned type;
  5292. int name_len;
  5293. };
  5294. static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
  5295. {
  5296. while (entries--) {
  5297. struct dir_entry *entry = addr;
  5298. char *name = (char *)(entry + 1);
  5299. ctx->pos = get_unaligned(&entry->offset);
  5300. if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
  5301. get_unaligned(&entry->ino),
  5302. get_unaligned(&entry->type)))
  5303. return 1;
  5304. addr += sizeof(struct dir_entry) +
  5305. get_unaligned(&entry->name_len);
  5306. ctx->pos++;
  5307. }
  5308. return 0;
  5309. }
  5310. static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
  5311. {
  5312. struct inode *inode = file_inode(file);
  5313. struct btrfs_root *root = BTRFS_I(inode)->root;
  5314. struct btrfs_file_private *private = file->private_data;
  5315. struct btrfs_dir_item *di;
  5316. struct btrfs_key key;
  5317. struct btrfs_key found_key;
  5318. struct btrfs_path *path;
  5319. void *addr;
  5320. struct list_head ins_list;
  5321. struct list_head del_list;
  5322. int ret;
  5323. char *name_ptr;
  5324. int name_len;
  5325. int entries = 0;
  5326. int total_len = 0;
  5327. bool put = false;
  5328. struct btrfs_key location;
  5329. if (!dir_emit_dots(file, ctx))
  5330. return 0;
  5331. path = btrfs_alloc_path();
  5332. if (!path)
  5333. return -ENOMEM;
  5334. addr = private->filldir_buf;
  5335. path->reada = READA_FORWARD;
  5336. INIT_LIST_HEAD(&ins_list);
  5337. INIT_LIST_HEAD(&del_list);
  5338. put = btrfs_readdir_get_delayed_items(inode, &ins_list, &del_list);
  5339. again:
  5340. key.type = BTRFS_DIR_INDEX_KEY;
  5341. key.offset = ctx->pos;
  5342. key.objectid = btrfs_ino(BTRFS_I(inode));
  5343. btrfs_for_each_slot(root, &key, &found_key, path, ret) {
  5344. struct dir_entry *entry;
  5345. struct extent_buffer *leaf = path->nodes[0];
  5346. if (found_key.objectid != key.objectid)
  5347. break;
  5348. if (found_key.type != BTRFS_DIR_INDEX_KEY)
  5349. break;
  5350. if (found_key.offset < ctx->pos)
  5351. continue;
  5352. if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
  5353. continue;
  5354. di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
  5355. name_len = btrfs_dir_name_len(leaf, di);
  5356. if ((total_len + sizeof(struct dir_entry) + name_len) >=
  5357. PAGE_SIZE) {
  5358. btrfs_release_path(path);
  5359. ret = btrfs_filldir(private->filldir_buf, entries, ctx);
  5360. if (ret)
  5361. goto nopos;
  5362. addr = private->filldir_buf;
  5363. entries = 0;
  5364. total_len = 0;
  5365. goto again;
  5366. }
  5367. entry = addr;
  5368. put_unaligned(name_len, &entry->name_len);
  5369. name_ptr = (char *)(entry + 1);
  5370. read_extent_buffer(leaf, name_ptr, (unsigned long)(di + 1),
  5371. name_len);
  5372. put_unaligned(fs_ftype_to_dtype(btrfs_dir_type(leaf, di)),
  5373. &entry->type);
  5374. btrfs_dir_item_key_to_cpu(leaf, di, &location);
  5375. put_unaligned(location.objectid, &entry->ino);
  5376. put_unaligned(found_key.offset, &entry->offset);
  5377. entries++;
  5378. addr += sizeof(struct dir_entry) + name_len;
  5379. total_len += sizeof(struct dir_entry) + name_len;
  5380. }
  5381. /* Catch error encountered during iteration */
  5382. if (ret < 0)
  5383. goto err;
  5384. btrfs_release_path(path);
  5385. ret = btrfs_filldir(private->filldir_buf, entries, ctx);
  5386. if (ret)
  5387. goto nopos;
  5388. ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
  5389. if (ret)
  5390. goto nopos;
  5391. /*
  5392. * Stop new entries from being returned after we return the last
  5393. * entry.
  5394. *
  5395. * New directory entries are assigned a strictly increasing
  5396. * offset. This means that new entries created during readdir
  5397. * are *guaranteed* to be seen in the future by that readdir.
  5398. * This has broken buggy programs which operate on names as
  5399. * they're returned by readdir. Until we re-use freed offsets
  5400. * we have this hack to stop new entries from being returned
  5401. * under the assumption that they'll never reach this huge
  5402. * offset.
  5403. *
  5404. * This is being careful not to overflow 32bit loff_t unless the
  5405. * last entry requires it because doing so has broken 32bit apps
  5406. * in the past.
  5407. */
  5408. if (ctx->pos >= INT_MAX)
  5409. ctx->pos = LLONG_MAX;
  5410. else
  5411. ctx->pos = INT_MAX;
  5412. nopos:
  5413. ret = 0;
  5414. err:
  5415. if (put)
  5416. btrfs_readdir_put_delayed_items(inode, &ins_list, &del_list);
  5417. btrfs_free_path(path);
  5418. return ret;
  5419. }
  5420. /*
  5421. * This is somewhat expensive, updating the tree every time the
  5422. * inode changes. But, it is most likely to find the inode in cache.
  5423. * FIXME, needs more benchmarking...there are no reasons other than performance
  5424. * to keep or drop this code.
  5425. */
  5426. static int btrfs_dirty_inode(struct inode *inode)
  5427. {
  5428. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5429. struct btrfs_root *root = BTRFS_I(inode)->root;
  5430. struct btrfs_trans_handle *trans;
  5431. int ret;
  5432. if (test_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags))
  5433. return 0;
  5434. trans = btrfs_join_transaction(root);
  5435. if (IS_ERR(trans))
  5436. return PTR_ERR(trans);
  5437. ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
  5438. if (ret && (ret == -ENOSPC || ret == -EDQUOT)) {
  5439. /* whoops, lets try again with the full transaction */
  5440. btrfs_end_transaction(trans);
  5441. trans = btrfs_start_transaction(root, 1);
  5442. if (IS_ERR(trans))
  5443. return PTR_ERR(trans);
  5444. ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
  5445. }
  5446. btrfs_end_transaction(trans);
  5447. if (BTRFS_I(inode)->delayed_node)
  5448. btrfs_balance_delayed_items(fs_info);
  5449. return ret;
  5450. }
  5451. /*
  5452. * This is a copy of file_update_time. We need this so we can return error on
  5453. * ENOSPC for updating the inode in the case of file write and mmap writes.
  5454. */
  5455. static int btrfs_update_time(struct inode *inode, struct timespec64 *now,
  5456. int flags)
  5457. {
  5458. struct btrfs_root *root = BTRFS_I(inode)->root;
  5459. bool dirty = flags & ~S_VERSION;
  5460. if (btrfs_root_readonly(root))
  5461. return -EROFS;
  5462. if (flags & S_VERSION)
  5463. dirty |= inode_maybe_inc_iversion(inode, dirty);
  5464. if (flags & S_CTIME)
  5465. inode->i_ctime = *now;
  5466. if (flags & S_MTIME)
  5467. inode->i_mtime = *now;
  5468. if (flags & S_ATIME)
  5469. inode->i_atime = *now;
  5470. return dirty ? btrfs_dirty_inode(inode) : 0;
  5471. }
  5472. /*
  5473. * find the highest existing sequence number in a directory
  5474. * and then set the in-memory index_cnt variable to reflect
  5475. * free sequence numbers
  5476. */
  5477. static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
  5478. {
  5479. struct btrfs_root *root = inode->root;
  5480. struct btrfs_key key, found_key;
  5481. struct btrfs_path *path;
  5482. struct extent_buffer *leaf;
  5483. int ret;
  5484. key.objectid = btrfs_ino(inode);
  5485. key.type = BTRFS_DIR_INDEX_KEY;
  5486. key.offset = (u64)-1;
  5487. path = btrfs_alloc_path();
  5488. if (!path)
  5489. return -ENOMEM;
  5490. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  5491. if (ret < 0)
  5492. goto out;
  5493. /* FIXME: we should be able to handle this */
  5494. if (ret == 0)
  5495. goto out;
  5496. ret = 0;
  5497. if (path->slots[0] == 0) {
  5498. inode->index_cnt = BTRFS_DIR_START_INDEX;
  5499. goto out;
  5500. }
  5501. path->slots[0]--;
  5502. leaf = path->nodes[0];
  5503. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  5504. if (found_key.objectid != btrfs_ino(inode) ||
  5505. found_key.type != BTRFS_DIR_INDEX_KEY) {
  5506. inode->index_cnt = BTRFS_DIR_START_INDEX;
  5507. goto out;
  5508. }
  5509. inode->index_cnt = found_key.offset + 1;
  5510. out:
  5511. btrfs_free_path(path);
  5512. return ret;
  5513. }
  5514. /*
  5515. * helper to find a free sequence number in a given directory. This current
  5516. * code is very simple, later versions will do smarter things in the btree
  5517. */
  5518. int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
  5519. {
  5520. int ret = 0;
  5521. if (dir->index_cnt == (u64)-1) {
  5522. ret = btrfs_inode_delayed_dir_index_count(dir);
  5523. if (ret) {
  5524. ret = btrfs_set_inode_index_count(dir);
  5525. if (ret)
  5526. return ret;
  5527. }
  5528. }
  5529. *index = dir->index_cnt;
  5530. dir->index_cnt++;
  5531. return ret;
  5532. }
  5533. static int btrfs_insert_inode_locked(struct inode *inode)
  5534. {
  5535. struct btrfs_iget_args args;
  5536. args.ino = BTRFS_I(inode)->location.objectid;
  5537. args.root = BTRFS_I(inode)->root;
  5538. return insert_inode_locked4(inode,
  5539. btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
  5540. btrfs_find_actor, &args);
  5541. }
  5542. int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
  5543. unsigned int *trans_num_items)
  5544. {
  5545. struct inode *dir = args->dir;
  5546. struct inode *inode = args->inode;
  5547. int ret;
  5548. if (!args->orphan) {
  5549. ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
  5550. &args->fname);
  5551. if (ret)
  5552. return ret;
  5553. }
  5554. ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
  5555. if (ret) {
  5556. fscrypt_free_filename(&args->fname);
  5557. return ret;
  5558. }
  5559. /* 1 to add inode item */
  5560. *trans_num_items = 1;
  5561. /* 1 to add compression property */
  5562. if (BTRFS_I(dir)->prop_compress)
  5563. (*trans_num_items)++;
  5564. /* 1 to add default ACL xattr */
  5565. if (args->default_acl)
  5566. (*trans_num_items)++;
  5567. /* 1 to add access ACL xattr */
  5568. if (args->acl)
  5569. (*trans_num_items)++;
  5570. #ifdef CONFIG_SECURITY
  5571. /* 1 to add LSM xattr */
  5572. if (dir->i_security)
  5573. (*trans_num_items)++;
  5574. #endif
  5575. if (args->orphan) {
  5576. /* 1 to add orphan item */
  5577. (*trans_num_items)++;
  5578. } else {
  5579. /*
  5580. * 1 to add dir item
  5581. * 1 to add dir index
  5582. * 1 to update parent inode item
  5583. *
  5584. * No need for 1 unit for the inode ref item because it is
  5585. * inserted in a batch together with the inode item at
  5586. * btrfs_create_new_inode().
  5587. */
  5588. *trans_num_items += 3;
  5589. }
  5590. return 0;
  5591. }
  5592. void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
  5593. {
  5594. posix_acl_release(args->acl);
  5595. posix_acl_release(args->default_acl);
  5596. fscrypt_free_filename(&args->fname);
  5597. }
  5598. /*
  5599. * Inherit flags from the parent inode.
  5600. *
  5601. * Currently only the compression flags and the cow flags are inherited.
  5602. */
  5603. static void btrfs_inherit_iflags(struct inode *inode, struct inode *dir)
  5604. {
  5605. unsigned int flags;
  5606. flags = BTRFS_I(dir)->flags;
  5607. if (flags & BTRFS_INODE_NOCOMPRESS) {
  5608. BTRFS_I(inode)->flags &= ~BTRFS_INODE_COMPRESS;
  5609. BTRFS_I(inode)->flags |= BTRFS_INODE_NOCOMPRESS;
  5610. } else if (flags & BTRFS_INODE_COMPRESS) {
  5611. BTRFS_I(inode)->flags &= ~BTRFS_INODE_NOCOMPRESS;
  5612. BTRFS_I(inode)->flags |= BTRFS_INODE_COMPRESS;
  5613. }
  5614. if (flags & BTRFS_INODE_NODATACOW) {
  5615. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW;
  5616. if (S_ISREG(inode->i_mode))
  5617. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
  5618. }
  5619. btrfs_sync_inode_flags_to_i_flags(inode);
  5620. }
  5621. int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
  5622. struct btrfs_new_inode_args *args)
  5623. {
  5624. struct inode *dir = args->dir;
  5625. struct inode *inode = args->inode;
  5626. const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
  5627. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  5628. struct btrfs_root *root;
  5629. struct btrfs_inode_item *inode_item;
  5630. struct btrfs_key *location;
  5631. struct btrfs_path *path;
  5632. u64 objectid;
  5633. struct btrfs_inode_ref *ref;
  5634. struct btrfs_key key[2];
  5635. u32 sizes[2];
  5636. struct btrfs_item_batch batch;
  5637. unsigned long ptr;
  5638. int ret;
  5639. path = btrfs_alloc_path();
  5640. if (!path)
  5641. return -ENOMEM;
  5642. if (!args->subvol)
  5643. BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
  5644. root = BTRFS_I(inode)->root;
  5645. ret = btrfs_get_free_objectid(root, &objectid);
  5646. if (ret)
  5647. goto out;
  5648. inode->i_ino = objectid;
  5649. if (args->orphan) {
  5650. /*
  5651. * O_TMPFILE, set link count to 0, so that after this point, we
  5652. * fill in an inode item with the correct link count.
  5653. */
  5654. set_nlink(inode, 0);
  5655. } else {
  5656. trace_btrfs_inode_request(dir);
  5657. ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
  5658. if (ret)
  5659. goto out;
  5660. }
  5661. /* index_cnt is ignored for everything but a dir. */
  5662. BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
  5663. BTRFS_I(inode)->generation = trans->transid;
  5664. inode->i_generation = BTRFS_I(inode)->generation;
  5665. /*
  5666. * Subvolumes don't inherit flags from their parent directory.
  5667. * Originally this was probably by accident, but we probably can't
  5668. * change it now without compatibility issues.
  5669. */
  5670. if (!args->subvol)
  5671. btrfs_inherit_iflags(inode, dir);
  5672. if (S_ISREG(inode->i_mode)) {
  5673. if (btrfs_test_opt(fs_info, NODATASUM))
  5674. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
  5675. if (btrfs_test_opt(fs_info, NODATACOW))
  5676. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
  5677. BTRFS_INODE_NODATASUM;
  5678. }
  5679. location = &BTRFS_I(inode)->location;
  5680. location->objectid = objectid;
  5681. location->offset = 0;
  5682. location->type = BTRFS_INODE_ITEM_KEY;
  5683. ret = btrfs_insert_inode_locked(inode);
  5684. if (ret < 0) {
  5685. if (!args->orphan)
  5686. BTRFS_I(dir)->index_cnt--;
  5687. goto out;
  5688. }
  5689. /*
  5690. * We could have gotten an inode number from somebody who was fsynced
  5691. * and then removed in this same transaction, so let's just set full
  5692. * sync since it will be a full sync anyway and this will blow away the
  5693. * old info in the log.
  5694. */
  5695. btrfs_set_inode_full_sync(BTRFS_I(inode));
  5696. key[0].objectid = objectid;
  5697. key[0].type = BTRFS_INODE_ITEM_KEY;
  5698. key[0].offset = 0;
  5699. sizes[0] = sizeof(struct btrfs_inode_item);
  5700. if (!args->orphan) {
  5701. /*
  5702. * Start new inodes with an inode_ref. This is slightly more
  5703. * efficient for small numbers of hard links since they will
  5704. * be packed into one item. Extended refs will kick in if we
  5705. * add more hard links than can fit in the ref item.
  5706. */
  5707. key[1].objectid = objectid;
  5708. key[1].type = BTRFS_INODE_REF_KEY;
  5709. if (args->subvol) {
  5710. key[1].offset = objectid;
  5711. sizes[1] = 2 + sizeof(*ref);
  5712. } else {
  5713. key[1].offset = btrfs_ino(BTRFS_I(dir));
  5714. sizes[1] = name->len + sizeof(*ref);
  5715. }
  5716. }
  5717. batch.keys = &key[0];
  5718. batch.data_sizes = &sizes[0];
  5719. batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
  5720. batch.nr = args->orphan ? 1 : 2;
  5721. ret = btrfs_insert_empty_items(trans, root, path, &batch);
  5722. if (ret != 0) {
  5723. btrfs_abort_transaction(trans, ret);
  5724. goto discard;
  5725. }
  5726. inode->i_mtime = current_time(inode);
  5727. inode->i_atime = inode->i_mtime;
  5728. inode->i_ctime = inode->i_mtime;
  5729. BTRFS_I(inode)->i_otime = inode->i_mtime;
  5730. /*
  5731. * We're going to fill the inode item now, so at this point the inode
  5732. * must be fully initialized.
  5733. */
  5734. inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
  5735. struct btrfs_inode_item);
  5736. memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
  5737. sizeof(*inode_item));
  5738. fill_inode_item(trans, path->nodes[0], inode_item, inode);
  5739. if (!args->orphan) {
  5740. ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
  5741. struct btrfs_inode_ref);
  5742. ptr = (unsigned long)(ref + 1);
  5743. if (args->subvol) {
  5744. btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
  5745. btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
  5746. write_extent_buffer(path->nodes[0], "..", ptr, 2);
  5747. } else {
  5748. btrfs_set_inode_ref_name_len(path->nodes[0], ref,
  5749. name->len);
  5750. btrfs_set_inode_ref_index(path->nodes[0], ref,
  5751. BTRFS_I(inode)->dir_index);
  5752. write_extent_buffer(path->nodes[0], name->name, ptr,
  5753. name->len);
  5754. }
  5755. }
  5756. btrfs_mark_buffer_dirty(path->nodes[0]);
  5757. /*
  5758. * We don't need the path anymore, plus inheriting properties, adding
  5759. * ACLs, security xattrs, orphan item or adding the link, will result in
  5760. * allocating yet another path. So just free our path.
  5761. */
  5762. btrfs_free_path(path);
  5763. path = NULL;
  5764. if (args->subvol) {
  5765. struct inode *parent;
  5766. /*
  5767. * Subvolumes inherit properties from their parent subvolume,
  5768. * not the directory they were created in.
  5769. */
  5770. parent = btrfs_iget(fs_info->sb, BTRFS_FIRST_FREE_OBJECTID,
  5771. BTRFS_I(dir)->root);
  5772. if (IS_ERR(parent)) {
  5773. ret = PTR_ERR(parent);
  5774. } else {
  5775. ret = btrfs_inode_inherit_props(trans, inode, parent);
  5776. iput(parent);
  5777. }
  5778. } else {
  5779. ret = btrfs_inode_inherit_props(trans, inode, dir);
  5780. }
  5781. if (ret) {
  5782. btrfs_err(fs_info,
  5783. "error inheriting props for ino %llu (root %llu): %d",
  5784. btrfs_ino(BTRFS_I(inode)), root->root_key.objectid,
  5785. ret);
  5786. }
  5787. /*
  5788. * Subvolumes don't inherit ACLs or get passed to the LSM. This is
  5789. * probably a bug.
  5790. */
  5791. if (!args->subvol) {
  5792. ret = btrfs_init_inode_security(trans, args);
  5793. if (ret) {
  5794. btrfs_abort_transaction(trans, ret);
  5795. goto discard;
  5796. }
  5797. }
  5798. inode_tree_add(inode);
  5799. trace_btrfs_inode_new(inode);
  5800. btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
  5801. btrfs_update_root_times(trans, root);
  5802. if (args->orphan) {
  5803. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  5804. } else {
  5805. ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
  5806. 0, BTRFS_I(inode)->dir_index);
  5807. }
  5808. if (ret) {
  5809. btrfs_abort_transaction(trans, ret);
  5810. goto discard;
  5811. }
  5812. return 0;
  5813. discard:
  5814. /*
  5815. * discard_new_inode() calls iput(), but the caller owns the reference
  5816. * to the inode.
  5817. */
  5818. ihold(inode);
  5819. discard_new_inode(inode);
  5820. out:
  5821. btrfs_free_path(path);
  5822. return ret;
  5823. }
  5824. /*
  5825. * utility function to add 'inode' into 'parent_inode' with
  5826. * a give name and a given sequence number.
  5827. * if 'add_backref' is true, also insert a backref from the
  5828. * inode to the parent directory.
  5829. */
  5830. int btrfs_add_link(struct btrfs_trans_handle *trans,
  5831. struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
  5832. const struct fscrypt_str *name, int add_backref, u64 index)
  5833. {
  5834. int ret = 0;
  5835. struct btrfs_key key;
  5836. struct btrfs_root *root = parent_inode->root;
  5837. u64 ino = btrfs_ino(inode);
  5838. u64 parent_ino = btrfs_ino(parent_inode);
  5839. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5840. memcpy(&key, &inode->root->root_key, sizeof(key));
  5841. } else {
  5842. key.objectid = ino;
  5843. key.type = BTRFS_INODE_ITEM_KEY;
  5844. key.offset = 0;
  5845. }
  5846. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5847. ret = btrfs_add_root_ref(trans, key.objectid,
  5848. root->root_key.objectid, parent_ino,
  5849. index, name);
  5850. } else if (add_backref) {
  5851. ret = btrfs_insert_inode_ref(trans, root, name,
  5852. ino, parent_ino, index);
  5853. }
  5854. /* Nothing to clean up yet */
  5855. if (ret)
  5856. return ret;
  5857. ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
  5858. btrfs_inode_type(&inode->vfs_inode), index);
  5859. if (ret == -EEXIST || ret == -EOVERFLOW)
  5860. goto fail_dir_item;
  5861. else if (ret) {
  5862. btrfs_abort_transaction(trans, ret);
  5863. return ret;
  5864. }
  5865. btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
  5866. name->len * 2);
  5867. inode_inc_iversion(&parent_inode->vfs_inode);
  5868. /*
  5869. * If we are replaying a log tree, we do not want to update the mtime
  5870. * and ctime of the parent directory with the current time, since the
  5871. * log replay procedure is responsible for setting them to their correct
  5872. * values (the ones it had when the fsync was done).
  5873. */
  5874. if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags)) {
  5875. struct timespec64 now = current_time(&parent_inode->vfs_inode);
  5876. parent_inode->vfs_inode.i_mtime = now;
  5877. parent_inode->vfs_inode.i_ctime = now;
  5878. }
  5879. ret = btrfs_update_inode(trans, root, parent_inode);
  5880. if (ret)
  5881. btrfs_abort_transaction(trans, ret);
  5882. return ret;
  5883. fail_dir_item:
  5884. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5885. u64 local_index;
  5886. int err;
  5887. err = btrfs_del_root_ref(trans, key.objectid,
  5888. root->root_key.objectid, parent_ino,
  5889. &local_index, name);
  5890. if (err)
  5891. btrfs_abort_transaction(trans, err);
  5892. } else if (add_backref) {
  5893. u64 local_index;
  5894. int err;
  5895. err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
  5896. &local_index);
  5897. if (err)
  5898. btrfs_abort_transaction(trans, err);
  5899. }
  5900. /* Return the original error code */
  5901. return ret;
  5902. }
  5903. static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
  5904. struct inode *inode)
  5905. {
  5906. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  5907. struct btrfs_root *root = BTRFS_I(dir)->root;
  5908. struct btrfs_new_inode_args new_inode_args = {
  5909. .dir = dir,
  5910. .dentry = dentry,
  5911. .inode = inode,
  5912. };
  5913. unsigned int trans_num_items;
  5914. struct btrfs_trans_handle *trans;
  5915. int err;
  5916. err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
  5917. if (err)
  5918. goto out_inode;
  5919. trans = btrfs_start_transaction(root, trans_num_items);
  5920. if (IS_ERR(trans)) {
  5921. err = PTR_ERR(trans);
  5922. goto out_new_inode_args;
  5923. }
  5924. err = btrfs_create_new_inode(trans, &new_inode_args);
  5925. if (!err)
  5926. d_instantiate_new(dentry, inode);
  5927. btrfs_end_transaction(trans);
  5928. btrfs_btree_balance_dirty(fs_info);
  5929. out_new_inode_args:
  5930. btrfs_new_inode_args_destroy(&new_inode_args);
  5931. out_inode:
  5932. if (err)
  5933. iput(inode);
  5934. return err;
  5935. }
  5936. static int btrfs_mknod(struct user_namespace *mnt_userns, struct inode *dir,
  5937. struct dentry *dentry, umode_t mode, dev_t rdev)
  5938. {
  5939. struct inode *inode;
  5940. inode = new_inode(dir->i_sb);
  5941. if (!inode)
  5942. return -ENOMEM;
  5943. inode_init_owner(mnt_userns, inode, dir, mode);
  5944. inode->i_op = &btrfs_special_inode_operations;
  5945. init_special_inode(inode, inode->i_mode, rdev);
  5946. return btrfs_create_common(dir, dentry, inode);
  5947. }
  5948. static int btrfs_create(struct user_namespace *mnt_userns, struct inode *dir,
  5949. struct dentry *dentry, umode_t mode, bool excl)
  5950. {
  5951. struct inode *inode;
  5952. inode = new_inode(dir->i_sb);
  5953. if (!inode)
  5954. return -ENOMEM;
  5955. inode_init_owner(mnt_userns, inode, dir, mode);
  5956. inode->i_fop = &btrfs_file_operations;
  5957. inode->i_op = &btrfs_file_inode_operations;
  5958. inode->i_mapping->a_ops = &btrfs_aops;
  5959. return btrfs_create_common(dir, dentry, inode);
  5960. }
  5961. static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
  5962. struct dentry *dentry)
  5963. {
  5964. struct btrfs_trans_handle *trans = NULL;
  5965. struct btrfs_root *root = BTRFS_I(dir)->root;
  5966. struct inode *inode = d_inode(old_dentry);
  5967. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  5968. struct fscrypt_name fname;
  5969. u64 index;
  5970. int err;
  5971. int drop_inode = 0;
  5972. /* do not allow sys_link's with other subvols of the same device */
  5973. if (root->root_key.objectid != BTRFS_I(inode)->root->root_key.objectid)
  5974. return -EXDEV;
  5975. if (inode->i_nlink >= BTRFS_LINK_MAX)
  5976. return -EMLINK;
  5977. err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
  5978. if (err)
  5979. goto fail;
  5980. err = btrfs_set_inode_index(BTRFS_I(dir), &index);
  5981. if (err)
  5982. goto fail;
  5983. /*
  5984. * 2 items for inode and inode ref
  5985. * 2 items for dir items
  5986. * 1 item for parent inode
  5987. * 1 item for orphan item deletion if O_TMPFILE
  5988. */
  5989. trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
  5990. if (IS_ERR(trans)) {
  5991. err = PTR_ERR(trans);
  5992. trans = NULL;
  5993. goto fail;
  5994. }
  5995. /* There are several dir indexes for this inode, clear the cache. */
  5996. BTRFS_I(inode)->dir_index = 0ULL;
  5997. inc_nlink(inode);
  5998. inode_inc_iversion(inode);
  5999. inode->i_ctime = current_time(inode);
  6000. ihold(inode);
  6001. set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
  6002. err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
  6003. &fname.disk_name, 1, index);
  6004. if (err) {
  6005. drop_inode = 1;
  6006. } else {
  6007. struct dentry *parent = dentry->d_parent;
  6008. err = btrfs_update_inode(trans, root, BTRFS_I(inode));
  6009. if (err)
  6010. goto fail;
  6011. if (inode->i_nlink == 1) {
  6012. /*
  6013. * If new hard link count is 1, it's a file created
  6014. * with open(2) O_TMPFILE flag.
  6015. */
  6016. err = btrfs_orphan_del(trans, BTRFS_I(inode));
  6017. if (err)
  6018. goto fail;
  6019. }
  6020. d_instantiate(dentry, inode);
  6021. btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
  6022. }
  6023. fail:
  6024. fscrypt_free_filename(&fname);
  6025. if (trans)
  6026. btrfs_end_transaction(trans);
  6027. if (drop_inode) {
  6028. inode_dec_link_count(inode);
  6029. iput(inode);
  6030. }
  6031. btrfs_btree_balance_dirty(fs_info);
  6032. return err;
  6033. }
  6034. static int btrfs_mkdir(struct user_namespace *mnt_userns, struct inode *dir,
  6035. struct dentry *dentry, umode_t mode)
  6036. {
  6037. struct inode *inode;
  6038. inode = new_inode(dir->i_sb);
  6039. if (!inode)
  6040. return -ENOMEM;
  6041. inode_init_owner(mnt_userns, inode, dir, S_IFDIR | mode);
  6042. inode->i_op = &btrfs_dir_inode_operations;
  6043. inode->i_fop = &btrfs_dir_file_operations;
  6044. return btrfs_create_common(dir, dentry, inode);
  6045. }
  6046. static noinline int uncompress_inline(struct btrfs_path *path,
  6047. struct page *page,
  6048. size_t pg_offset, u64 extent_offset,
  6049. struct btrfs_file_extent_item *item)
  6050. {
  6051. int ret;
  6052. struct extent_buffer *leaf = path->nodes[0];
  6053. char *tmp;
  6054. size_t max_size;
  6055. unsigned long inline_size;
  6056. unsigned long ptr;
  6057. int compress_type;
  6058. WARN_ON(pg_offset != 0);
  6059. compress_type = btrfs_file_extent_compression(leaf, item);
  6060. max_size = btrfs_file_extent_ram_bytes(leaf, item);
  6061. inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
  6062. tmp = kmalloc(inline_size, GFP_NOFS);
  6063. if (!tmp)
  6064. return -ENOMEM;
  6065. ptr = btrfs_file_extent_inline_start(item);
  6066. read_extent_buffer(leaf, tmp, ptr, inline_size);
  6067. max_size = min_t(unsigned long, PAGE_SIZE, max_size);
  6068. ret = btrfs_decompress(compress_type, tmp, page,
  6069. extent_offset, inline_size, max_size);
  6070. /*
  6071. * decompression code contains a memset to fill in any space between the end
  6072. * of the uncompressed data and the end of max_size in case the decompressed
  6073. * data ends up shorter than ram_bytes. That doesn't cover the hole between
  6074. * the end of an inline extent and the beginning of the next block, so we
  6075. * cover that region here.
  6076. */
  6077. if (max_size + pg_offset < PAGE_SIZE)
  6078. memzero_page(page, pg_offset + max_size,
  6079. PAGE_SIZE - max_size - pg_offset);
  6080. kfree(tmp);
  6081. return ret;
  6082. }
  6083. /**
  6084. * btrfs_get_extent - Lookup the first extent overlapping a range in a file.
  6085. * @inode: file to search in
  6086. * @page: page to read extent data into if the extent is inline
  6087. * @pg_offset: offset into @page to copy to
  6088. * @start: file offset
  6089. * @len: length of range starting at @start
  6090. *
  6091. * This returns the first &struct extent_map which overlaps with the given
  6092. * range, reading it from the B-tree and caching it if necessary. Note that
  6093. * there may be more extents which overlap the given range after the returned
  6094. * extent_map.
  6095. *
  6096. * If @page is not NULL and the extent is inline, this also reads the extent
  6097. * data directly into the page and marks the extent up to date in the io_tree.
  6098. *
  6099. * Return: ERR_PTR on error, non-NULL extent_map on success.
  6100. */
  6101. struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
  6102. struct page *page, size_t pg_offset,
  6103. u64 start, u64 len)
  6104. {
  6105. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  6106. int ret = 0;
  6107. u64 extent_start = 0;
  6108. u64 extent_end = 0;
  6109. u64 objectid = btrfs_ino(inode);
  6110. int extent_type = -1;
  6111. struct btrfs_path *path = NULL;
  6112. struct btrfs_root *root = inode->root;
  6113. struct btrfs_file_extent_item *item;
  6114. struct extent_buffer *leaf;
  6115. struct btrfs_key found_key;
  6116. struct extent_map *em = NULL;
  6117. struct extent_map_tree *em_tree = &inode->extent_tree;
  6118. read_lock(&em_tree->lock);
  6119. em = lookup_extent_mapping(em_tree, start, len);
  6120. read_unlock(&em_tree->lock);
  6121. if (em) {
  6122. if (em->start > start || em->start + em->len <= start)
  6123. free_extent_map(em);
  6124. else if (em->block_start == EXTENT_MAP_INLINE && page)
  6125. free_extent_map(em);
  6126. else
  6127. goto out;
  6128. }
  6129. em = alloc_extent_map();
  6130. if (!em) {
  6131. ret = -ENOMEM;
  6132. goto out;
  6133. }
  6134. em->start = EXTENT_MAP_HOLE;
  6135. em->orig_start = EXTENT_MAP_HOLE;
  6136. em->len = (u64)-1;
  6137. em->block_len = (u64)-1;
  6138. path = btrfs_alloc_path();
  6139. if (!path) {
  6140. ret = -ENOMEM;
  6141. goto out;
  6142. }
  6143. /* Chances are we'll be called again, so go ahead and do readahead */
  6144. path->reada = READA_FORWARD;
  6145. /*
  6146. * The same explanation in load_free_space_cache applies here as well,
  6147. * we only read when we're loading the free space cache, and at that
  6148. * point the commit_root has everything we need.
  6149. */
  6150. if (btrfs_is_free_space_inode(inode)) {
  6151. path->search_commit_root = 1;
  6152. path->skip_locking = 1;
  6153. }
  6154. ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
  6155. if (ret < 0) {
  6156. goto out;
  6157. } else if (ret > 0) {
  6158. if (path->slots[0] == 0)
  6159. goto not_found;
  6160. path->slots[0]--;
  6161. ret = 0;
  6162. }
  6163. leaf = path->nodes[0];
  6164. item = btrfs_item_ptr(leaf, path->slots[0],
  6165. struct btrfs_file_extent_item);
  6166. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  6167. if (found_key.objectid != objectid ||
  6168. found_key.type != BTRFS_EXTENT_DATA_KEY) {
  6169. /*
  6170. * If we backup past the first extent we want to move forward
  6171. * and see if there is an extent in front of us, otherwise we'll
  6172. * say there is a hole for our whole search range which can
  6173. * cause problems.
  6174. */
  6175. extent_end = start;
  6176. goto next;
  6177. }
  6178. extent_type = btrfs_file_extent_type(leaf, item);
  6179. extent_start = found_key.offset;
  6180. extent_end = btrfs_file_extent_end(path);
  6181. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  6182. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6183. /* Only regular file could have regular/prealloc extent */
  6184. if (!S_ISREG(inode->vfs_inode.i_mode)) {
  6185. ret = -EUCLEAN;
  6186. btrfs_crit(fs_info,
  6187. "regular/prealloc extent found for non-regular inode %llu",
  6188. btrfs_ino(inode));
  6189. goto out;
  6190. }
  6191. trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
  6192. extent_start);
  6193. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  6194. trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
  6195. path->slots[0],
  6196. extent_start);
  6197. }
  6198. next:
  6199. if (start >= extent_end) {
  6200. path->slots[0]++;
  6201. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  6202. ret = btrfs_next_leaf(root, path);
  6203. if (ret < 0)
  6204. goto out;
  6205. else if (ret > 0)
  6206. goto not_found;
  6207. leaf = path->nodes[0];
  6208. }
  6209. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  6210. if (found_key.objectid != objectid ||
  6211. found_key.type != BTRFS_EXTENT_DATA_KEY)
  6212. goto not_found;
  6213. if (start + len <= found_key.offset)
  6214. goto not_found;
  6215. if (start > found_key.offset)
  6216. goto next;
  6217. /* New extent overlaps with existing one */
  6218. em->start = start;
  6219. em->orig_start = start;
  6220. em->len = found_key.offset - start;
  6221. em->block_start = EXTENT_MAP_HOLE;
  6222. goto insert;
  6223. }
  6224. btrfs_extent_item_to_extent_map(inode, path, item, !page, em);
  6225. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  6226. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6227. goto insert;
  6228. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  6229. unsigned long ptr;
  6230. char *map;
  6231. size_t size;
  6232. size_t extent_offset;
  6233. size_t copy_size;
  6234. if (!page)
  6235. goto out;
  6236. size = btrfs_file_extent_ram_bytes(leaf, item);
  6237. extent_offset = page_offset(page) + pg_offset - extent_start;
  6238. copy_size = min_t(u64, PAGE_SIZE - pg_offset,
  6239. size - extent_offset);
  6240. em->start = extent_start + extent_offset;
  6241. em->len = ALIGN(copy_size, fs_info->sectorsize);
  6242. em->orig_block_len = em->len;
  6243. em->orig_start = em->start;
  6244. ptr = btrfs_file_extent_inline_start(item) + extent_offset;
  6245. if (!PageUptodate(page)) {
  6246. if (btrfs_file_extent_compression(leaf, item) !=
  6247. BTRFS_COMPRESS_NONE) {
  6248. ret = uncompress_inline(path, page, pg_offset,
  6249. extent_offset, item);
  6250. if (ret)
  6251. goto out;
  6252. } else {
  6253. map = kmap_local_page(page);
  6254. read_extent_buffer(leaf, map + pg_offset, ptr,
  6255. copy_size);
  6256. if (pg_offset + copy_size < PAGE_SIZE) {
  6257. memset(map + pg_offset + copy_size, 0,
  6258. PAGE_SIZE - pg_offset -
  6259. copy_size);
  6260. }
  6261. kunmap_local(map);
  6262. }
  6263. flush_dcache_page(page);
  6264. }
  6265. goto insert;
  6266. }
  6267. not_found:
  6268. em->start = start;
  6269. em->orig_start = start;
  6270. em->len = len;
  6271. em->block_start = EXTENT_MAP_HOLE;
  6272. insert:
  6273. ret = 0;
  6274. btrfs_release_path(path);
  6275. if (em->start > start || extent_map_end(em) <= start) {
  6276. btrfs_err(fs_info,
  6277. "bad extent! em: [%llu %llu] passed [%llu %llu]",
  6278. em->start, em->len, start, len);
  6279. ret = -EIO;
  6280. goto out;
  6281. }
  6282. write_lock(&em_tree->lock);
  6283. ret = btrfs_add_extent_mapping(fs_info, em_tree, &em, start, len);
  6284. write_unlock(&em_tree->lock);
  6285. out:
  6286. btrfs_free_path(path);
  6287. trace_btrfs_get_extent(root, inode, em);
  6288. if (ret) {
  6289. free_extent_map(em);
  6290. return ERR_PTR(ret);
  6291. }
  6292. return em;
  6293. }
  6294. static struct extent_map *btrfs_create_dio_extent(struct btrfs_inode *inode,
  6295. const u64 start,
  6296. const u64 len,
  6297. const u64 orig_start,
  6298. const u64 block_start,
  6299. const u64 block_len,
  6300. const u64 orig_block_len,
  6301. const u64 ram_bytes,
  6302. const int type)
  6303. {
  6304. struct extent_map *em = NULL;
  6305. int ret;
  6306. if (type != BTRFS_ORDERED_NOCOW) {
  6307. em = create_io_em(inode, start, len, orig_start, block_start,
  6308. block_len, orig_block_len, ram_bytes,
  6309. BTRFS_COMPRESS_NONE, /* compress_type */
  6310. type);
  6311. if (IS_ERR(em))
  6312. goto out;
  6313. }
  6314. ret = btrfs_add_ordered_extent(inode, start, len, len, block_start,
  6315. block_len, 0,
  6316. (1 << type) |
  6317. (1 << BTRFS_ORDERED_DIRECT),
  6318. BTRFS_COMPRESS_NONE);
  6319. if (ret) {
  6320. if (em) {
  6321. free_extent_map(em);
  6322. btrfs_drop_extent_map_range(inode, start,
  6323. start + len - 1, false);
  6324. }
  6325. em = ERR_PTR(ret);
  6326. }
  6327. out:
  6328. return em;
  6329. }
  6330. static struct extent_map *btrfs_new_extent_direct(struct btrfs_inode *inode,
  6331. u64 start, u64 len)
  6332. {
  6333. struct btrfs_root *root = inode->root;
  6334. struct btrfs_fs_info *fs_info = root->fs_info;
  6335. struct extent_map *em;
  6336. struct btrfs_key ins;
  6337. u64 alloc_hint;
  6338. int ret;
  6339. alloc_hint = get_extent_allocation_hint(inode, start, len);
  6340. again:
  6341. ret = btrfs_reserve_extent(root, len, len, fs_info->sectorsize,
  6342. 0, alloc_hint, &ins, 1, 1);
  6343. if (ret == -EAGAIN) {
  6344. ASSERT(btrfs_is_zoned(fs_info));
  6345. wait_on_bit_io(&inode->root->fs_info->flags, BTRFS_FS_NEED_ZONE_FINISH,
  6346. TASK_UNINTERRUPTIBLE);
  6347. goto again;
  6348. }
  6349. if (ret)
  6350. return ERR_PTR(ret);
  6351. em = btrfs_create_dio_extent(inode, start, ins.offset, start,
  6352. ins.objectid, ins.offset, ins.offset,
  6353. ins.offset, BTRFS_ORDERED_REGULAR);
  6354. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  6355. if (IS_ERR(em))
  6356. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset,
  6357. 1);
  6358. return em;
  6359. }
  6360. static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
  6361. {
  6362. struct btrfs_block_group *block_group;
  6363. bool readonly = false;
  6364. block_group = btrfs_lookup_block_group(fs_info, bytenr);
  6365. if (!block_group || block_group->ro)
  6366. readonly = true;
  6367. if (block_group)
  6368. btrfs_put_block_group(block_group);
  6369. return readonly;
  6370. }
  6371. /*
  6372. * Check if we can do nocow write into the range [@offset, @offset + @len)
  6373. *
  6374. * @offset: File offset
  6375. * @len: The length to write, will be updated to the nocow writeable
  6376. * range
  6377. * @orig_start: (optional) Return the original file offset of the file extent
  6378. * @orig_len: (optional) Return the original on-disk length of the file extent
  6379. * @ram_bytes: (optional) Return the ram_bytes of the file extent
  6380. * @strict: if true, omit optimizations that might force us into unnecessary
  6381. * cow. e.g., don't trust generation number.
  6382. *
  6383. * Return:
  6384. * >0 and update @len if we can do nocow write
  6385. * 0 if we can't do nocow write
  6386. * <0 if error happened
  6387. *
  6388. * NOTE: This only checks the file extents, caller is responsible to wait for
  6389. * any ordered extents.
  6390. */
  6391. noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
  6392. u64 *orig_start, u64 *orig_block_len,
  6393. u64 *ram_bytes, bool nowait, bool strict)
  6394. {
  6395. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  6396. struct can_nocow_file_extent_args nocow_args = { 0 };
  6397. struct btrfs_path *path;
  6398. int ret;
  6399. struct extent_buffer *leaf;
  6400. struct btrfs_root *root = BTRFS_I(inode)->root;
  6401. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  6402. struct btrfs_file_extent_item *fi;
  6403. struct btrfs_key key;
  6404. int found_type;
  6405. path = btrfs_alloc_path();
  6406. if (!path)
  6407. return -ENOMEM;
  6408. path->nowait = nowait;
  6409. ret = btrfs_lookup_file_extent(NULL, root, path,
  6410. btrfs_ino(BTRFS_I(inode)), offset, 0);
  6411. if (ret < 0)
  6412. goto out;
  6413. if (ret == 1) {
  6414. if (path->slots[0] == 0) {
  6415. /* can't find the item, must cow */
  6416. ret = 0;
  6417. goto out;
  6418. }
  6419. path->slots[0]--;
  6420. }
  6421. ret = 0;
  6422. leaf = path->nodes[0];
  6423. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  6424. if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
  6425. key.type != BTRFS_EXTENT_DATA_KEY) {
  6426. /* not our file or wrong item type, must cow */
  6427. goto out;
  6428. }
  6429. if (key.offset > offset) {
  6430. /* Wrong offset, must cow */
  6431. goto out;
  6432. }
  6433. if (btrfs_file_extent_end(path) <= offset)
  6434. goto out;
  6435. fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
  6436. found_type = btrfs_file_extent_type(leaf, fi);
  6437. if (ram_bytes)
  6438. *ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
  6439. nocow_args.start = offset;
  6440. nocow_args.end = offset + *len - 1;
  6441. nocow_args.strict = strict;
  6442. nocow_args.free_path = true;
  6443. ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
  6444. /* can_nocow_file_extent() has freed the path. */
  6445. path = NULL;
  6446. if (ret != 1) {
  6447. /* Treat errors as not being able to NOCOW. */
  6448. ret = 0;
  6449. goto out;
  6450. }
  6451. ret = 0;
  6452. if (btrfs_extent_readonly(fs_info, nocow_args.disk_bytenr))
  6453. goto out;
  6454. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
  6455. found_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6456. u64 range_end;
  6457. range_end = round_up(offset + nocow_args.num_bytes,
  6458. root->fs_info->sectorsize) - 1;
  6459. ret = test_range_bit(io_tree, offset, range_end,
  6460. EXTENT_DELALLOC, 0, NULL);
  6461. if (ret) {
  6462. ret = -EAGAIN;
  6463. goto out;
  6464. }
  6465. }
  6466. if (orig_start)
  6467. *orig_start = key.offset - nocow_args.extent_offset;
  6468. if (orig_block_len)
  6469. *orig_block_len = nocow_args.disk_num_bytes;
  6470. *len = nocow_args.num_bytes;
  6471. ret = 1;
  6472. out:
  6473. btrfs_free_path(path);
  6474. return ret;
  6475. }
  6476. static int lock_extent_direct(struct inode *inode, u64 lockstart, u64 lockend,
  6477. struct extent_state **cached_state,
  6478. unsigned int iomap_flags)
  6479. {
  6480. const bool writing = (iomap_flags & IOMAP_WRITE);
  6481. const bool nowait = (iomap_flags & IOMAP_NOWAIT);
  6482. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  6483. struct btrfs_ordered_extent *ordered;
  6484. int ret = 0;
  6485. while (1) {
  6486. if (nowait) {
  6487. if (!try_lock_extent(io_tree, lockstart, lockend))
  6488. return -EAGAIN;
  6489. } else {
  6490. lock_extent(io_tree, lockstart, lockend, cached_state);
  6491. }
  6492. /*
  6493. * We're concerned with the entire range that we're going to be
  6494. * doing DIO to, so we need to make sure there's no ordered
  6495. * extents in this range.
  6496. */
  6497. ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), lockstart,
  6498. lockend - lockstart + 1);
  6499. /*
  6500. * We need to make sure there are no buffered pages in this
  6501. * range either, we could have raced between the invalidate in
  6502. * generic_file_direct_write and locking the extent. The
  6503. * invalidate needs to happen so that reads after a write do not
  6504. * get stale data.
  6505. */
  6506. if (!ordered &&
  6507. (!writing || !filemap_range_has_page(inode->i_mapping,
  6508. lockstart, lockend)))
  6509. break;
  6510. unlock_extent(io_tree, lockstart, lockend, cached_state);
  6511. if (ordered) {
  6512. if (nowait) {
  6513. btrfs_put_ordered_extent(ordered);
  6514. ret = -EAGAIN;
  6515. break;
  6516. }
  6517. /*
  6518. * If we are doing a DIO read and the ordered extent we
  6519. * found is for a buffered write, we can not wait for it
  6520. * to complete and retry, because if we do so we can
  6521. * deadlock with concurrent buffered writes on page
  6522. * locks. This happens only if our DIO read covers more
  6523. * than one extent map, if at this point has already
  6524. * created an ordered extent for a previous extent map
  6525. * and locked its range in the inode's io tree, and a
  6526. * concurrent write against that previous extent map's
  6527. * range and this range started (we unlock the ranges
  6528. * in the io tree only when the bios complete and
  6529. * buffered writes always lock pages before attempting
  6530. * to lock range in the io tree).
  6531. */
  6532. if (writing ||
  6533. test_bit(BTRFS_ORDERED_DIRECT, &ordered->flags))
  6534. btrfs_start_ordered_extent(ordered, 1);
  6535. else
  6536. ret = nowait ? -EAGAIN : -ENOTBLK;
  6537. btrfs_put_ordered_extent(ordered);
  6538. } else {
  6539. /*
  6540. * We could trigger writeback for this range (and wait
  6541. * for it to complete) and then invalidate the pages for
  6542. * this range (through invalidate_inode_pages2_range()),
  6543. * but that can lead us to a deadlock with a concurrent
  6544. * call to readahead (a buffered read or a defrag call
  6545. * triggered a readahead) on a page lock due to an
  6546. * ordered dio extent we created before but did not have
  6547. * yet a corresponding bio submitted (whence it can not
  6548. * complete), which makes readahead wait for that
  6549. * ordered extent to complete while holding a lock on
  6550. * that page.
  6551. */
  6552. ret = nowait ? -EAGAIN : -ENOTBLK;
  6553. }
  6554. if (ret)
  6555. break;
  6556. cond_resched();
  6557. }
  6558. return ret;
  6559. }
  6560. /* The callers of this must take lock_extent() */
  6561. static struct extent_map *create_io_em(struct btrfs_inode *inode, u64 start,
  6562. u64 len, u64 orig_start, u64 block_start,
  6563. u64 block_len, u64 orig_block_len,
  6564. u64 ram_bytes, int compress_type,
  6565. int type)
  6566. {
  6567. struct extent_map *em;
  6568. int ret;
  6569. ASSERT(type == BTRFS_ORDERED_PREALLOC ||
  6570. type == BTRFS_ORDERED_COMPRESSED ||
  6571. type == BTRFS_ORDERED_NOCOW ||
  6572. type == BTRFS_ORDERED_REGULAR);
  6573. em = alloc_extent_map();
  6574. if (!em)
  6575. return ERR_PTR(-ENOMEM);
  6576. em->start = start;
  6577. em->orig_start = orig_start;
  6578. em->len = len;
  6579. em->block_len = block_len;
  6580. em->block_start = block_start;
  6581. em->orig_block_len = orig_block_len;
  6582. em->ram_bytes = ram_bytes;
  6583. em->generation = -1;
  6584. set_bit(EXTENT_FLAG_PINNED, &em->flags);
  6585. if (type == BTRFS_ORDERED_PREALLOC) {
  6586. set_bit(EXTENT_FLAG_FILLING, &em->flags);
  6587. } else if (type == BTRFS_ORDERED_COMPRESSED) {
  6588. set_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
  6589. em->compress_type = compress_type;
  6590. }
  6591. ret = btrfs_replace_extent_map_range(inode, em, true);
  6592. if (ret) {
  6593. free_extent_map(em);
  6594. return ERR_PTR(ret);
  6595. }
  6596. /* em got 2 refs now, callers needs to do free_extent_map once. */
  6597. return em;
  6598. }
  6599. static int btrfs_get_blocks_direct_write(struct extent_map **map,
  6600. struct inode *inode,
  6601. struct btrfs_dio_data *dio_data,
  6602. u64 start, u64 *lenp,
  6603. unsigned int iomap_flags)
  6604. {
  6605. const bool nowait = (iomap_flags & IOMAP_NOWAIT);
  6606. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  6607. struct extent_map *em = *map;
  6608. int type;
  6609. u64 block_start, orig_start, orig_block_len, ram_bytes;
  6610. struct btrfs_block_group *bg;
  6611. bool can_nocow = false;
  6612. bool space_reserved = false;
  6613. u64 len = *lenp;
  6614. u64 prev_len;
  6615. int ret = 0;
  6616. /*
  6617. * We don't allocate a new extent in the following cases
  6618. *
  6619. * 1) The inode is marked as NODATACOW. In this case we'll just use the
  6620. * existing extent.
  6621. * 2) The extent is marked as PREALLOC. We're good to go here and can
  6622. * just use the extent.
  6623. *
  6624. */
  6625. if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) ||
  6626. ((BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
  6627. em->block_start != EXTENT_MAP_HOLE)) {
  6628. if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
  6629. type = BTRFS_ORDERED_PREALLOC;
  6630. else
  6631. type = BTRFS_ORDERED_NOCOW;
  6632. len = min(len, em->len - (start - em->start));
  6633. block_start = em->block_start + (start - em->start);
  6634. if (can_nocow_extent(inode, start, &len, &orig_start,
  6635. &orig_block_len, &ram_bytes, false, false) == 1) {
  6636. bg = btrfs_inc_nocow_writers(fs_info, block_start);
  6637. if (bg)
  6638. can_nocow = true;
  6639. }
  6640. }
  6641. prev_len = len;
  6642. if (can_nocow) {
  6643. struct extent_map *em2;
  6644. /* We can NOCOW, so only need to reserve metadata space. */
  6645. ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
  6646. nowait);
  6647. if (ret < 0) {
  6648. /* Our caller expects us to free the input extent map. */
  6649. free_extent_map(em);
  6650. *map = NULL;
  6651. btrfs_dec_nocow_writers(bg);
  6652. if (nowait && (ret == -ENOSPC || ret == -EDQUOT))
  6653. ret = -EAGAIN;
  6654. goto out;
  6655. }
  6656. space_reserved = true;
  6657. em2 = btrfs_create_dio_extent(BTRFS_I(inode), start, len,
  6658. orig_start, block_start,
  6659. len, orig_block_len,
  6660. ram_bytes, type);
  6661. btrfs_dec_nocow_writers(bg);
  6662. if (type == BTRFS_ORDERED_PREALLOC) {
  6663. free_extent_map(em);
  6664. *map = em2;
  6665. em = em2;
  6666. }
  6667. if (IS_ERR(em2)) {
  6668. ret = PTR_ERR(em2);
  6669. goto out;
  6670. }
  6671. dio_data->nocow_done = true;
  6672. } else {
  6673. /* Our caller expects us to free the input extent map. */
  6674. free_extent_map(em);
  6675. *map = NULL;
  6676. if (nowait) {
  6677. ret = -EAGAIN;
  6678. goto out;
  6679. }
  6680. /*
  6681. * If we could not allocate data space before locking the file
  6682. * range and we can't do a NOCOW write, then we have to fail.
  6683. */
  6684. if (!dio_data->data_space_reserved) {
  6685. ret = -ENOSPC;
  6686. goto out;
  6687. }
  6688. /*
  6689. * We have to COW and we have already reserved data space before,
  6690. * so now we reserve only metadata.
  6691. */
  6692. ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len, len,
  6693. false);
  6694. if (ret < 0)
  6695. goto out;
  6696. space_reserved = true;
  6697. em = btrfs_new_extent_direct(BTRFS_I(inode), start, len);
  6698. if (IS_ERR(em)) {
  6699. ret = PTR_ERR(em);
  6700. goto out;
  6701. }
  6702. *map = em;
  6703. len = min(len, em->len - (start - em->start));
  6704. if (len < prev_len)
  6705. btrfs_delalloc_release_metadata(BTRFS_I(inode),
  6706. prev_len - len, true);
  6707. }
  6708. /*
  6709. * We have created our ordered extent, so we can now release our reservation
  6710. * for an outstanding extent.
  6711. */
  6712. btrfs_delalloc_release_extents(BTRFS_I(inode), prev_len);
  6713. /*
  6714. * Need to update the i_size under the extent lock so buffered
  6715. * readers will get the updated i_size when we unlock.
  6716. */
  6717. if (start + len > i_size_read(inode))
  6718. i_size_write(inode, start + len);
  6719. out:
  6720. if (ret && space_reserved) {
  6721. btrfs_delalloc_release_extents(BTRFS_I(inode), len);
  6722. btrfs_delalloc_release_metadata(BTRFS_I(inode), len, true);
  6723. }
  6724. *lenp = len;
  6725. return ret;
  6726. }
  6727. static int btrfs_dio_iomap_begin(struct inode *inode, loff_t start,
  6728. loff_t length, unsigned int flags, struct iomap *iomap,
  6729. struct iomap *srcmap)
  6730. {
  6731. struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
  6732. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  6733. struct extent_map *em;
  6734. struct extent_state *cached_state = NULL;
  6735. struct btrfs_dio_data *dio_data = iter->private;
  6736. u64 lockstart, lockend;
  6737. const bool write = !!(flags & IOMAP_WRITE);
  6738. int ret = 0;
  6739. u64 len = length;
  6740. const u64 data_alloc_len = length;
  6741. bool unlock_extents = false;
  6742. /*
  6743. * We could potentially fault if we have a buffer > PAGE_SIZE, and if
  6744. * we're NOWAIT we may submit a bio for a partial range and return
  6745. * EIOCBQUEUED, which would result in an errant short read.
  6746. *
  6747. * The best way to handle this would be to allow for partial completions
  6748. * of iocb's, so we could submit the partial bio, return and fault in
  6749. * the rest of the pages, and then submit the io for the rest of the
  6750. * range. However we don't have that currently, so simply return
  6751. * -EAGAIN at this point so that the normal path is used.
  6752. */
  6753. if (!write && (flags & IOMAP_NOWAIT) && length > PAGE_SIZE)
  6754. return -EAGAIN;
  6755. /*
  6756. * Cap the size of reads to that usually seen in buffered I/O as we need
  6757. * to allocate a contiguous array for the checksums.
  6758. */
  6759. if (!write)
  6760. len = min_t(u64, len, fs_info->sectorsize * BTRFS_MAX_BIO_SECTORS);
  6761. lockstart = start;
  6762. lockend = start + len - 1;
  6763. /*
  6764. * iomap_dio_rw() only does filemap_write_and_wait_range(), which isn't
  6765. * enough if we've written compressed pages to this area, so we need to
  6766. * flush the dirty pages again to make absolutely sure that any
  6767. * outstanding dirty pages are on disk - the first flush only starts
  6768. * compression on the data, while keeping the pages locked, so by the
  6769. * time the second flush returns we know bios for the compressed pages
  6770. * were submitted and finished, and the pages no longer under writeback.
  6771. *
  6772. * If we have a NOWAIT request and we have any pages in the range that
  6773. * are locked, likely due to compression still in progress, we don't want
  6774. * to block on page locks. We also don't want to block on pages marked as
  6775. * dirty or under writeback (same as for the non-compression case).
  6776. * iomap_dio_rw() did the same check, but after that and before we got
  6777. * here, mmap'ed writes may have happened or buffered reads started
  6778. * (readpage() and readahead(), which lock pages), as we haven't locked
  6779. * the file range yet.
  6780. */
  6781. if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  6782. &BTRFS_I(inode)->runtime_flags)) {
  6783. if (flags & IOMAP_NOWAIT) {
  6784. if (filemap_range_needs_writeback(inode->i_mapping,
  6785. lockstart, lockend))
  6786. return -EAGAIN;
  6787. } else {
  6788. ret = filemap_fdatawrite_range(inode->i_mapping, start,
  6789. start + length - 1);
  6790. if (ret)
  6791. return ret;
  6792. }
  6793. }
  6794. memset(dio_data, 0, sizeof(*dio_data));
  6795. /*
  6796. * We always try to allocate data space and must do it before locking
  6797. * the file range, to avoid deadlocks with concurrent writes to the same
  6798. * range if the range has several extents and the writes don't expand the
  6799. * current i_size (the inode lock is taken in shared mode). If we fail to
  6800. * allocate data space here we continue and later, after locking the
  6801. * file range, we fail with ENOSPC only if we figure out we can not do a
  6802. * NOCOW write.
  6803. */
  6804. if (write && !(flags & IOMAP_NOWAIT)) {
  6805. ret = btrfs_check_data_free_space(BTRFS_I(inode),
  6806. &dio_data->data_reserved,
  6807. start, data_alloc_len, false);
  6808. if (!ret)
  6809. dio_data->data_space_reserved = true;
  6810. else if (ret && !(BTRFS_I(inode)->flags &
  6811. (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
  6812. goto err;
  6813. }
  6814. /*
  6815. * If this errors out it's because we couldn't invalidate pagecache for
  6816. * this range and we need to fallback to buffered IO, or we are doing a
  6817. * NOWAIT read/write and we need to block.
  6818. */
  6819. ret = lock_extent_direct(inode, lockstart, lockend, &cached_state, flags);
  6820. if (ret < 0)
  6821. goto err;
  6822. em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
  6823. if (IS_ERR(em)) {
  6824. ret = PTR_ERR(em);
  6825. goto unlock_err;
  6826. }
  6827. /*
  6828. * Ok for INLINE and COMPRESSED extents we need to fallback on buffered
  6829. * io. INLINE is special, and we could probably kludge it in here, but
  6830. * it's still buffered so for safety lets just fall back to the generic
  6831. * buffered path.
  6832. *
  6833. * For COMPRESSED we _have_ to read the entire extent in so we can
  6834. * decompress it, so there will be buffering required no matter what we
  6835. * do, so go ahead and fallback to buffered.
  6836. *
  6837. * We return -ENOTBLK because that's what makes DIO go ahead and go back
  6838. * to buffered IO. Don't blame me, this is the price we pay for using
  6839. * the generic code.
  6840. */
  6841. if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags) ||
  6842. em->block_start == EXTENT_MAP_INLINE) {
  6843. free_extent_map(em);
  6844. /*
  6845. * If we are in a NOWAIT context, return -EAGAIN in order to
  6846. * fallback to buffered IO. This is not only because we can
  6847. * block with buffered IO (no support for NOWAIT semantics at
  6848. * the moment) but also to avoid returning short reads to user
  6849. * space - this happens if we were able to read some data from
  6850. * previous non-compressed extents and then when we fallback to
  6851. * buffered IO, at btrfs_file_read_iter() by calling
  6852. * filemap_read(), we fail to fault in pages for the read buffer,
  6853. * in which case filemap_read() returns a short read (the number
  6854. * of bytes previously read is > 0, so it does not return -EFAULT).
  6855. */
  6856. ret = (flags & IOMAP_NOWAIT) ? -EAGAIN : -ENOTBLK;
  6857. goto unlock_err;
  6858. }
  6859. len = min(len, em->len - (start - em->start));
  6860. /*
  6861. * If we have a NOWAIT request and the range contains multiple extents
  6862. * (or a mix of extents and holes), then we return -EAGAIN to make the
  6863. * caller fallback to a context where it can do a blocking (without
  6864. * NOWAIT) request. This way we avoid doing partial IO and returning
  6865. * success to the caller, which is not optimal for writes and for reads
  6866. * it can result in unexpected behaviour for an application.
  6867. *
  6868. * When doing a read, because we use IOMAP_DIO_PARTIAL when calling
  6869. * iomap_dio_rw(), we can end up returning less data then what the caller
  6870. * asked for, resulting in an unexpected, and incorrect, short read.
  6871. * That is, the caller asked to read N bytes and we return less than that,
  6872. * which is wrong unless we are crossing EOF. This happens if we get a
  6873. * page fault error when trying to fault in pages for the buffer that is
  6874. * associated to the struct iov_iter passed to iomap_dio_rw(), and we
  6875. * have previously submitted bios for other extents in the range, in
  6876. * which case iomap_dio_rw() may return us EIOCBQUEUED if not all of
  6877. * those bios have completed by the time we get the page fault error,
  6878. * which we return back to our caller - we should only return EIOCBQUEUED
  6879. * after we have submitted bios for all the extents in the range.
  6880. */
  6881. if ((flags & IOMAP_NOWAIT) && len < length) {
  6882. free_extent_map(em);
  6883. ret = -EAGAIN;
  6884. goto unlock_err;
  6885. }
  6886. if (write) {
  6887. ret = btrfs_get_blocks_direct_write(&em, inode, dio_data,
  6888. start, &len, flags);
  6889. if (ret < 0)
  6890. goto unlock_err;
  6891. unlock_extents = true;
  6892. /* Recalc len in case the new em is smaller than requested */
  6893. len = min(len, em->len - (start - em->start));
  6894. if (dio_data->data_space_reserved) {
  6895. u64 release_offset;
  6896. u64 release_len = 0;
  6897. if (dio_data->nocow_done) {
  6898. release_offset = start;
  6899. release_len = data_alloc_len;
  6900. } else if (len < data_alloc_len) {
  6901. release_offset = start + len;
  6902. release_len = data_alloc_len - len;
  6903. }
  6904. if (release_len > 0)
  6905. btrfs_free_reserved_data_space(BTRFS_I(inode),
  6906. dio_data->data_reserved,
  6907. release_offset,
  6908. release_len);
  6909. }
  6910. } else {
  6911. /*
  6912. * We need to unlock only the end area that we aren't using.
  6913. * The rest is going to be unlocked by the endio routine.
  6914. */
  6915. lockstart = start + len;
  6916. if (lockstart < lockend)
  6917. unlock_extents = true;
  6918. }
  6919. if (unlock_extents)
  6920. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  6921. &cached_state);
  6922. else
  6923. free_extent_state(cached_state);
  6924. /*
  6925. * Translate extent map information to iomap.
  6926. * We trim the extents (and move the addr) even though iomap code does
  6927. * that, since we have locked only the parts we are performing I/O in.
  6928. */
  6929. if ((em->block_start == EXTENT_MAP_HOLE) ||
  6930. (test_bit(EXTENT_FLAG_PREALLOC, &em->flags) && !write)) {
  6931. iomap->addr = IOMAP_NULL_ADDR;
  6932. iomap->type = IOMAP_HOLE;
  6933. } else {
  6934. iomap->addr = em->block_start + (start - em->start);
  6935. iomap->type = IOMAP_MAPPED;
  6936. }
  6937. iomap->offset = start;
  6938. iomap->bdev = fs_info->fs_devices->latest_dev->bdev;
  6939. iomap->length = len;
  6940. if (write && btrfs_use_zone_append(BTRFS_I(inode), em->block_start))
  6941. iomap->flags |= IOMAP_F_ZONE_APPEND;
  6942. free_extent_map(em);
  6943. return 0;
  6944. unlock_err:
  6945. unlock_extent(&BTRFS_I(inode)->io_tree, lockstart, lockend,
  6946. &cached_state);
  6947. err:
  6948. if (dio_data->data_space_reserved) {
  6949. btrfs_free_reserved_data_space(BTRFS_I(inode),
  6950. dio_data->data_reserved,
  6951. start, data_alloc_len);
  6952. extent_changeset_free(dio_data->data_reserved);
  6953. }
  6954. return ret;
  6955. }
  6956. static int btrfs_dio_iomap_end(struct inode *inode, loff_t pos, loff_t length,
  6957. ssize_t written, unsigned int flags, struct iomap *iomap)
  6958. {
  6959. struct iomap_iter *iter = container_of(iomap, struct iomap_iter, iomap);
  6960. struct btrfs_dio_data *dio_data = iter->private;
  6961. size_t submitted = dio_data->submitted;
  6962. const bool write = !!(flags & IOMAP_WRITE);
  6963. int ret = 0;
  6964. if (!write && (iomap->type == IOMAP_HOLE)) {
  6965. /* If reading from a hole, unlock and return */
  6966. unlock_extent(&BTRFS_I(inode)->io_tree, pos, pos + length - 1,
  6967. NULL);
  6968. return 0;
  6969. }
  6970. if (submitted < length) {
  6971. pos += submitted;
  6972. length -= submitted;
  6973. if (write)
  6974. btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
  6975. pos, length, false);
  6976. else
  6977. unlock_extent(&BTRFS_I(inode)->io_tree, pos,
  6978. pos + length - 1, NULL);
  6979. ret = -ENOTBLK;
  6980. }
  6981. if (write)
  6982. extent_changeset_free(dio_data->data_reserved);
  6983. return ret;
  6984. }
  6985. static void btrfs_dio_private_put(struct btrfs_dio_private *dip)
  6986. {
  6987. /*
  6988. * This implies a barrier so that stores to dio_bio->bi_status before
  6989. * this and loads of dio_bio->bi_status after this are fully ordered.
  6990. */
  6991. if (!refcount_dec_and_test(&dip->refs))
  6992. return;
  6993. if (btrfs_op(&dip->bio) == BTRFS_MAP_WRITE) {
  6994. btrfs_mark_ordered_io_finished(BTRFS_I(dip->inode), NULL,
  6995. dip->file_offset, dip->bytes,
  6996. !dip->bio.bi_status);
  6997. } else {
  6998. unlock_extent(&BTRFS_I(dip->inode)->io_tree,
  6999. dip->file_offset,
  7000. dip->file_offset + dip->bytes - 1, NULL);
  7001. }
  7002. kfree(dip->csums);
  7003. bio_endio(&dip->bio);
  7004. }
  7005. static void submit_dio_repair_bio(struct inode *inode, struct bio *bio,
  7006. int mirror_num,
  7007. enum btrfs_compression_type compress_type)
  7008. {
  7009. struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
  7010. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7011. BUG_ON(bio_op(bio) == REQ_OP_WRITE);
  7012. refcount_inc(&dip->refs);
  7013. btrfs_submit_bio(fs_info, bio, mirror_num);
  7014. }
  7015. static blk_status_t btrfs_check_read_dio_bio(struct btrfs_dio_private *dip,
  7016. struct btrfs_bio *bbio,
  7017. const bool uptodate)
  7018. {
  7019. struct inode *inode = dip->inode;
  7020. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  7021. const bool csum = !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM);
  7022. blk_status_t err = BLK_STS_OK;
  7023. struct bvec_iter iter;
  7024. struct bio_vec bv;
  7025. u32 offset;
  7026. btrfs_bio_for_each_sector(fs_info, bv, bbio, iter, offset) {
  7027. u64 start = bbio->file_offset + offset;
  7028. if (uptodate &&
  7029. (!csum || !btrfs_check_data_csum(inode, bbio, offset, bv.bv_page,
  7030. bv.bv_offset))) {
  7031. btrfs_clean_io_failure(BTRFS_I(inode), start,
  7032. bv.bv_page, bv.bv_offset);
  7033. } else {
  7034. int ret;
  7035. ret = btrfs_repair_one_sector(inode, bbio, offset,
  7036. bv.bv_page, bv.bv_offset,
  7037. submit_dio_repair_bio);
  7038. if (ret)
  7039. err = errno_to_blk_status(ret);
  7040. }
  7041. }
  7042. return err;
  7043. }
  7044. static blk_status_t btrfs_submit_bio_start_direct_io(struct inode *inode,
  7045. struct bio *bio,
  7046. u64 dio_file_offset)
  7047. {
  7048. return btrfs_csum_one_bio(BTRFS_I(inode), bio, dio_file_offset, false);
  7049. }
  7050. static void btrfs_end_dio_bio(struct btrfs_bio *bbio)
  7051. {
  7052. struct btrfs_dio_private *dip = bbio->private;
  7053. struct bio *bio = &bbio->bio;
  7054. blk_status_t err = bio->bi_status;
  7055. if (err)
  7056. btrfs_warn(BTRFS_I(dip->inode)->root->fs_info,
  7057. "direct IO failed ino %llu rw %d,%u sector %#Lx len %u err no %d",
  7058. btrfs_ino(BTRFS_I(dip->inode)), bio_op(bio),
  7059. bio->bi_opf, bio->bi_iter.bi_sector,
  7060. bio->bi_iter.bi_size, err);
  7061. if (bio_op(bio) == REQ_OP_READ)
  7062. err = btrfs_check_read_dio_bio(dip, bbio, !err);
  7063. if (err)
  7064. dip->bio.bi_status = err;
  7065. btrfs_record_physical_zoned(dip->inode, bbio->file_offset, bio);
  7066. bio_put(bio);
  7067. btrfs_dio_private_put(dip);
  7068. }
  7069. static void btrfs_submit_dio_bio(struct bio *bio, struct inode *inode,
  7070. u64 file_offset, int async_submit)
  7071. {
  7072. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7073. struct btrfs_dio_private *dip = btrfs_bio(bio)->private;
  7074. blk_status_t ret;
  7075. /* Save the original iter for read repair */
  7076. if (btrfs_op(bio) == BTRFS_MAP_READ)
  7077. btrfs_bio(bio)->iter = bio->bi_iter;
  7078. if (BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)
  7079. goto map;
  7080. if (btrfs_op(bio) == BTRFS_MAP_WRITE) {
  7081. /* Check btrfs_submit_data_write_bio() for async submit rules */
  7082. if (async_submit && !atomic_read(&BTRFS_I(inode)->sync_writers) &&
  7083. btrfs_wq_submit_bio(inode, bio, 0, file_offset,
  7084. btrfs_submit_bio_start_direct_io))
  7085. return;
  7086. /*
  7087. * If we aren't doing async submit, calculate the csum of the
  7088. * bio now.
  7089. */
  7090. ret = btrfs_csum_one_bio(BTRFS_I(inode), bio, file_offset, false);
  7091. if (ret) {
  7092. btrfs_bio_end_io(btrfs_bio(bio), ret);
  7093. return;
  7094. }
  7095. } else {
  7096. btrfs_bio(bio)->csum = btrfs_csum_ptr(fs_info, dip->csums,
  7097. file_offset - dip->file_offset);
  7098. }
  7099. map:
  7100. btrfs_submit_bio(fs_info, bio, 0);
  7101. }
  7102. static void btrfs_submit_direct(const struct iomap_iter *iter,
  7103. struct bio *dio_bio, loff_t file_offset)
  7104. {
  7105. struct btrfs_dio_private *dip =
  7106. container_of(dio_bio, struct btrfs_dio_private, bio);
  7107. struct inode *inode = iter->inode;
  7108. const bool write = (btrfs_op(dio_bio) == BTRFS_MAP_WRITE);
  7109. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7110. const bool raid56 = (btrfs_data_alloc_profile(fs_info) &
  7111. BTRFS_BLOCK_GROUP_RAID56_MASK);
  7112. struct bio *bio;
  7113. u64 start_sector;
  7114. int async_submit = 0;
  7115. u64 submit_len;
  7116. u64 clone_offset = 0;
  7117. u64 clone_len;
  7118. u64 logical;
  7119. int ret;
  7120. blk_status_t status;
  7121. struct btrfs_io_geometry geom;
  7122. struct btrfs_dio_data *dio_data = iter->private;
  7123. struct extent_map *em = NULL;
  7124. dip->inode = inode;
  7125. dip->file_offset = file_offset;
  7126. dip->bytes = dio_bio->bi_iter.bi_size;
  7127. refcount_set(&dip->refs, 1);
  7128. dip->csums = NULL;
  7129. if (!write && !(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
  7130. unsigned int nr_sectors =
  7131. (dio_bio->bi_iter.bi_size >> fs_info->sectorsize_bits);
  7132. /*
  7133. * Load the csums up front to reduce csum tree searches and
  7134. * contention when submitting bios.
  7135. */
  7136. status = BLK_STS_RESOURCE;
  7137. dip->csums = kcalloc(nr_sectors, fs_info->csum_size, GFP_NOFS);
  7138. if (!dip->csums)
  7139. goto out_err;
  7140. status = btrfs_lookup_bio_sums(inode, dio_bio, dip->csums);
  7141. if (status != BLK_STS_OK)
  7142. goto out_err;
  7143. }
  7144. start_sector = dio_bio->bi_iter.bi_sector;
  7145. submit_len = dio_bio->bi_iter.bi_size;
  7146. do {
  7147. logical = start_sector << 9;
  7148. em = btrfs_get_chunk_map(fs_info, logical, submit_len);
  7149. if (IS_ERR(em)) {
  7150. status = errno_to_blk_status(PTR_ERR(em));
  7151. em = NULL;
  7152. goto out_err_em;
  7153. }
  7154. ret = btrfs_get_io_geometry(fs_info, em, btrfs_op(dio_bio),
  7155. logical, &geom);
  7156. if (ret) {
  7157. status = errno_to_blk_status(ret);
  7158. goto out_err_em;
  7159. }
  7160. clone_len = min(submit_len, geom.len);
  7161. ASSERT(clone_len <= UINT_MAX);
  7162. /*
  7163. * This will never fail as it's passing GPF_NOFS and
  7164. * the allocation is backed by btrfs_bioset.
  7165. */
  7166. bio = btrfs_bio_clone_partial(dio_bio, clone_offset, clone_len,
  7167. btrfs_end_dio_bio, dip);
  7168. btrfs_bio(bio)->file_offset = file_offset;
  7169. if (bio_op(bio) == REQ_OP_ZONE_APPEND) {
  7170. status = extract_ordered_extent(BTRFS_I(inode), bio,
  7171. file_offset);
  7172. if (status) {
  7173. bio_put(bio);
  7174. goto out_err;
  7175. }
  7176. }
  7177. ASSERT(submit_len >= clone_len);
  7178. submit_len -= clone_len;
  7179. /*
  7180. * Increase the count before we submit the bio so we know
  7181. * the end IO handler won't happen before we increase the
  7182. * count. Otherwise, the dip might get freed before we're
  7183. * done setting it up.
  7184. *
  7185. * We transfer the initial reference to the last bio, so we
  7186. * don't need to increment the reference count for the last one.
  7187. */
  7188. if (submit_len > 0) {
  7189. refcount_inc(&dip->refs);
  7190. /*
  7191. * If we are submitting more than one bio, submit them
  7192. * all asynchronously. The exception is RAID 5 or 6, as
  7193. * asynchronous checksums make it difficult to collect
  7194. * full stripe writes.
  7195. */
  7196. if (!raid56)
  7197. async_submit = 1;
  7198. }
  7199. btrfs_submit_dio_bio(bio, inode, file_offset, async_submit);
  7200. dio_data->submitted += clone_len;
  7201. clone_offset += clone_len;
  7202. start_sector += clone_len >> 9;
  7203. file_offset += clone_len;
  7204. free_extent_map(em);
  7205. } while (submit_len > 0);
  7206. return;
  7207. out_err_em:
  7208. free_extent_map(em);
  7209. out_err:
  7210. dio_bio->bi_status = status;
  7211. btrfs_dio_private_put(dip);
  7212. }
  7213. static const struct iomap_ops btrfs_dio_iomap_ops = {
  7214. .iomap_begin = btrfs_dio_iomap_begin,
  7215. .iomap_end = btrfs_dio_iomap_end,
  7216. };
  7217. static const struct iomap_dio_ops btrfs_dio_ops = {
  7218. .submit_io = btrfs_submit_direct,
  7219. .bio_set = &btrfs_dio_bioset,
  7220. };
  7221. ssize_t btrfs_dio_read(struct kiocb *iocb, struct iov_iter *iter, size_t done_before)
  7222. {
  7223. struct btrfs_dio_data data;
  7224. return iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
  7225. IOMAP_DIO_PARTIAL, &data, done_before);
  7226. }
  7227. struct iomap_dio *btrfs_dio_write(struct kiocb *iocb, struct iov_iter *iter,
  7228. size_t done_before)
  7229. {
  7230. struct btrfs_dio_data data;
  7231. return __iomap_dio_rw(iocb, iter, &btrfs_dio_iomap_ops, &btrfs_dio_ops,
  7232. IOMAP_DIO_PARTIAL, &data, done_before);
  7233. }
  7234. static int btrfs_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
  7235. u64 start, u64 len)
  7236. {
  7237. int ret;
  7238. ret = fiemap_prep(inode, fieinfo, start, &len, 0);
  7239. if (ret)
  7240. return ret;
  7241. /*
  7242. * fiemap_prep() called filemap_write_and_wait() for the whole possible
  7243. * file range (0 to LLONG_MAX), but that is not enough if we have
  7244. * compression enabled. The first filemap_fdatawrite_range() only kicks
  7245. * in the compression of data (in an async thread) and will return
  7246. * before the compression is done and writeback is started. A second
  7247. * filemap_fdatawrite_range() is needed to wait for the compression to
  7248. * complete and writeback to start. We also need to wait for ordered
  7249. * extents to complete, because our fiemap implementation uses mainly
  7250. * file extent items to list the extents, searching for extent maps
  7251. * only for file ranges with holes or prealloc extents to figure out
  7252. * if we have delalloc in those ranges.
  7253. */
  7254. if (fieinfo->fi_flags & FIEMAP_FLAG_SYNC) {
  7255. ret = btrfs_wait_ordered_range(inode, 0, LLONG_MAX);
  7256. if (ret)
  7257. return ret;
  7258. }
  7259. return extent_fiemap(BTRFS_I(inode), fieinfo, start, len);
  7260. }
  7261. static int btrfs_writepages(struct address_space *mapping,
  7262. struct writeback_control *wbc)
  7263. {
  7264. return extent_writepages(mapping, wbc);
  7265. }
  7266. static void btrfs_readahead(struct readahead_control *rac)
  7267. {
  7268. extent_readahead(rac);
  7269. }
  7270. /*
  7271. * For release_folio() and invalidate_folio() we have a race window where
  7272. * folio_end_writeback() is called but the subpage spinlock is not yet released.
  7273. * If we continue to release/invalidate the page, we could cause use-after-free
  7274. * for subpage spinlock. So this function is to spin and wait for subpage
  7275. * spinlock.
  7276. */
  7277. static void wait_subpage_spinlock(struct page *page)
  7278. {
  7279. struct btrfs_fs_info *fs_info = btrfs_sb(page->mapping->host->i_sb);
  7280. struct btrfs_subpage *subpage;
  7281. if (!btrfs_is_subpage(fs_info, page))
  7282. return;
  7283. ASSERT(PagePrivate(page) && page->private);
  7284. subpage = (struct btrfs_subpage *)page->private;
  7285. /*
  7286. * This may look insane as we just acquire the spinlock and release it,
  7287. * without doing anything. But we just want to make sure no one is
  7288. * still holding the subpage spinlock.
  7289. * And since the page is not dirty nor writeback, and we have page
  7290. * locked, the only possible way to hold a spinlock is from the endio
  7291. * function to clear page writeback.
  7292. *
  7293. * Here we just acquire the spinlock so that all existing callers
  7294. * should exit and we're safe to release/invalidate the page.
  7295. */
  7296. spin_lock_irq(&subpage->lock);
  7297. spin_unlock_irq(&subpage->lock);
  7298. }
  7299. static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
  7300. {
  7301. int ret = try_release_extent_mapping(&folio->page, gfp_flags);
  7302. if (ret == 1) {
  7303. wait_subpage_spinlock(&folio->page);
  7304. clear_page_extent_mapped(&folio->page);
  7305. }
  7306. return ret;
  7307. }
  7308. static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
  7309. {
  7310. if (folio_test_writeback(folio) || folio_test_dirty(folio))
  7311. return false;
  7312. return __btrfs_release_folio(folio, gfp_flags);
  7313. }
  7314. #ifdef CONFIG_MIGRATION
  7315. static int btrfs_migrate_folio(struct address_space *mapping,
  7316. struct folio *dst, struct folio *src,
  7317. enum migrate_mode mode)
  7318. {
  7319. int ret = filemap_migrate_folio(mapping, dst, src, mode);
  7320. if (ret != MIGRATEPAGE_SUCCESS)
  7321. return ret;
  7322. if (folio_test_ordered(src)) {
  7323. folio_clear_ordered(src);
  7324. folio_set_ordered(dst);
  7325. }
  7326. return MIGRATEPAGE_SUCCESS;
  7327. }
  7328. #else
  7329. #define btrfs_migrate_folio NULL
  7330. #endif
  7331. static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
  7332. size_t length)
  7333. {
  7334. struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
  7335. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  7336. struct extent_io_tree *tree = &inode->io_tree;
  7337. struct extent_state *cached_state = NULL;
  7338. u64 page_start = folio_pos(folio);
  7339. u64 page_end = page_start + folio_size(folio) - 1;
  7340. u64 cur;
  7341. int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
  7342. /*
  7343. * We have folio locked so no new ordered extent can be created on this
  7344. * page, nor bio can be submitted for this folio.
  7345. *
  7346. * But already submitted bio can still be finished on this folio.
  7347. * Furthermore, endio function won't skip folio which has Ordered
  7348. * (Private2) already cleared, so it's possible for endio and
  7349. * invalidate_folio to do the same ordered extent accounting twice
  7350. * on one folio.
  7351. *
  7352. * So here we wait for any submitted bios to finish, so that we won't
  7353. * do double ordered extent accounting on the same folio.
  7354. */
  7355. folio_wait_writeback(folio);
  7356. wait_subpage_spinlock(&folio->page);
  7357. /*
  7358. * For subpage case, we have call sites like
  7359. * btrfs_punch_hole_lock_range() which passes range not aligned to
  7360. * sectorsize.
  7361. * If the range doesn't cover the full folio, we don't need to and
  7362. * shouldn't clear page extent mapped, as folio->private can still
  7363. * record subpage dirty bits for other part of the range.
  7364. *
  7365. * For cases that invalidate the full folio even the range doesn't
  7366. * cover the full folio, like invalidating the last folio, we're
  7367. * still safe to wait for ordered extent to finish.
  7368. */
  7369. if (!(offset == 0 && length == folio_size(folio))) {
  7370. btrfs_release_folio(folio, GFP_NOFS);
  7371. return;
  7372. }
  7373. if (!inode_evicting)
  7374. lock_extent(tree, page_start, page_end, &cached_state);
  7375. cur = page_start;
  7376. while (cur < page_end) {
  7377. struct btrfs_ordered_extent *ordered;
  7378. u64 range_end;
  7379. u32 range_len;
  7380. u32 extra_flags = 0;
  7381. ordered = btrfs_lookup_first_ordered_range(inode, cur,
  7382. page_end + 1 - cur);
  7383. if (!ordered) {
  7384. range_end = page_end;
  7385. /*
  7386. * No ordered extent covering this range, we are safe
  7387. * to delete all extent states in the range.
  7388. */
  7389. extra_flags = EXTENT_CLEAR_ALL_BITS;
  7390. goto next;
  7391. }
  7392. if (ordered->file_offset > cur) {
  7393. /*
  7394. * There is a range between [cur, oe->file_offset) not
  7395. * covered by any ordered extent.
  7396. * We are safe to delete all extent states, and handle
  7397. * the ordered extent in the next iteration.
  7398. */
  7399. range_end = ordered->file_offset - 1;
  7400. extra_flags = EXTENT_CLEAR_ALL_BITS;
  7401. goto next;
  7402. }
  7403. range_end = min(ordered->file_offset + ordered->num_bytes - 1,
  7404. page_end);
  7405. ASSERT(range_end + 1 - cur < U32_MAX);
  7406. range_len = range_end + 1 - cur;
  7407. if (!btrfs_page_test_ordered(fs_info, &folio->page, cur, range_len)) {
  7408. /*
  7409. * If Ordered (Private2) is cleared, it means endio has
  7410. * already been executed for the range.
  7411. * We can't delete the extent states as
  7412. * btrfs_finish_ordered_io() may still use some of them.
  7413. */
  7414. goto next;
  7415. }
  7416. btrfs_page_clear_ordered(fs_info, &folio->page, cur, range_len);
  7417. /*
  7418. * IO on this page will never be started, so we need to account
  7419. * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
  7420. * here, must leave that up for the ordered extent completion.
  7421. *
  7422. * This will also unlock the range for incoming
  7423. * btrfs_finish_ordered_io().
  7424. */
  7425. if (!inode_evicting)
  7426. clear_extent_bit(tree, cur, range_end,
  7427. EXTENT_DELALLOC |
  7428. EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
  7429. EXTENT_DEFRAG, &cached_state);
  7430. spin_lock_irq(&inode->ordered_tree.lock);
  7431. set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
  7432. ordered->truncated_len = min(ordered->truncated_len,
  7433. cur - ordered->file_offset);
  7434. spin_unlock_irq(&inode->ordered_tree.lock);
  7435. /*
  7436. * If the ordered extent has finished, we're safe to delete all
  7437. * the extent states of the range, otherwise
  7438. * btrfs_finish_ordered_io() will get executed by endio for
  7439. * other pages, so we can't delete extent states.
  7440. */
  7441. if (btrfs_dec_test_ordered_pending(inode, &ordered,
  7442. cur, range_end + 1 - cur)) {
  7443. btrfs_finish_ordered_io(ordered);
  7444. /*
  7445. * The ordered extent has finished, now we're again
  7446. * safe to delete all extent states of the range.
  7447. */
  7448. extra_flags = EXTENT_CLEAR_ALL_BITS;
  7449. }
  7450. next:
  7451. if (ordered)
  7452. btrfs_put_ordered_extent(ordered);
  7453. /*
  7454. * Qgroup reserved space handler
  7455. * Sector(s) here will be either:
  7456. *
  7457. * 1) Already written to disk or bio already finished
  7458. * Then its QGROUP_RESERVED bit in io_tree is already cleared.
  7459. * Qgroup will be handled by its qgroup_record then.
  7460. * btrfs_qgroup_free_data() call will do nothing here.
  7461. *
  7462. * 2) Not written to disk yet
  7463. * Then btrfs_qgroup_free_data() call will clear the
  7464. * QGROUP_RESERVED bit of its io_tree, and free the qgroup
  7465. * reserved data space.
  7466. * Since the IO will never happen for this page.
  7467. */
  7468. btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur);
  7469. if (!inode_evicting) {
  7470. clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
  7471. EXTENT_DELALLOC | EXTENT_UPTODATE |
  7472. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
  7473. extra_flags, &cached_state);
  7474. }
  7475. cur = range_end + 1;
  7476. }
  7477. /*
  7478. * We have iterated through all ordered extents of the page, the page
  7479. * should not have Ordered (Private2) anymore, or the above iteration
  7480. * did something wrong.
  7481. */
  7482. ASSERT(!folio_test_ordered(folio));
  7483. btrfs_page_clear_checked(fs_info, &folio->page, folio_pos(folio), folio_size(folio));
  7484. if (!inode_evicting)
  7485. __btrfs_release_folio(folio, GFP_NOFS);
  7486. clear_page_extent_mapped(&folio->page);
  7487. }
  7488. /*
  7489. * btrfs_page_mkwrite() is not allowed to change the file size as it gets
  7490. * called from a page fault handler when a page is first dirtied. Hence we must
  7491. * be careful to check for EOF conditions here. We set the page up correctly
  7492. * for a written page which means we get ENOSPC checking when writing into
  7493. * holes and correct delalloc and unwritten extent mapping on filesystems that
  7494. * support these features.
  7495. *
  7496. * We are not allowed to take the i_mutex here so we have to play games to
  7497. * protect against truncate races as the page could now be beyond EOF. Because
  7498. * truncate_setsize() writes the inode size before removing pages, once we have
  7499. * the page lock we can determine safely if the page is beyond EOF. If it is not
  7500. * beyond EOF, then the page is guaranteed safe against truncation until we
  7501. * unlock the page.
  7502. */
  7503. vm_fault_t btrfs_page_mkwrite(struct vm_fault *vmf)
  7504. {
  7505. struct page *page = vmf->page;
  7506. struct inode *inode = file_inode(vmf->vma->vm_file);
  7507. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7508. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  7509. struct btrfs_ordered_extent *ordered;
  7510. struct extent_state *cached_state = NULL;
  7511. struct extent_changeset *data_reserved = NULL;
  7512. unsigned long zero_start;
  7513. loff_t size;
  7514. vm_fault_t ret;
  7515. int ret2;
  7516. int reserved = 0;
  7517. u64 reserved_space;
  7518. u64 page_start;
  7519. u64 page_end;
  7520. u64 end;
  7521. reserved_space = PAGE_SIZE;
  7522. sb_start_pagefault(inode->i_sb);
  7523. page_start = page_offset(page);
  7524. page_end = page_start + PAGE_SIZE - 1;
  7525. end = page_end;
  7526. /*
  7527. * Reserving delalloc space after obtaining the page lock can lead to
  7528. * deadlock. For example, if a dirty page is locked by this function
  7529. * and the call to btrfs_delalloc_reserve_space() ends up triggering
  7530. * dirty page write out, then the btrfs_writepages() function could
  7531. * end up waiting indefinitely to get a lock on the page currently
  7532. * being processed by btrfs_page_mkwrite() function.
  7533. */
  7534. ret2 = btrfs_delalloc_reserve_space(BTRFS_I(inode), &data_reserved,
  7535. page_start, reserved_space);
  7536. if (!ret2) {
  7537. ret2 = file_update_time(vmf->vma->vm_file);
  7538. reserved = 1;
  7539. }
  7540. if (ret2) {
  7541. ret = vmf_error(ret2);
  7542. if (reserved)
  7543. goto out;
  7544. goto out_noreserve;
  7545. }
  7546. ret = VM_FAULT_NOPAGE; /* make the VM retry the fault */
  7547. again:
  7548. down_read(&BTRFS_I(inode)->i_mmap_lock);
  7549. lock_page(page);
  7550. size = i_size_read(inode);
  7551. if ((page->mapping != inode->i_mapping) ||
  7552. (page_start >= size)) {
  7553. /* page got truncated out from underneath us */
  7554. goto out_unlock;
  7555. }
  7556. wait_on_page_writeback(page);
  7557. lock_extent(io_tree, page_start, page_end, &cached_state);
  7558. ret2 = set_page_extent_mapped(page);
  7559. if (ret2 < 0) {
  7560. ret = vmf_error(ret2);
  7561. unlock_extent(io_tree, page_start, page_end, &cached_state);
  7562. goto out_unlock;
  7563. }
  7564. /*
  7565. * we can't set the delalloc bits if there are pending ordered
  7566. * extents. Drop our locks and wait for them to finish
  7567. */
  7568. ordered = btrfs_lookup_ordered_range(BTRFS_I(inode), page_start,
  7569. PAGE_SIZE);
  7570. if (ordered) {
  7571. unlock_extent(io_tree, page_start, page_end, &cached_state);
  7572. unlock_page(page);
  7573. up_read(&BTRFS_I(inode)->i_mmap_lock);
  7574. btrfs_start_ordered_extent(ordered, 1);
  7575. btrfs_put_ordered_extent(ordered);
  7576. goto again;
  7577. }
  7578. if (page->index == ((size - 1) >> PAGE_SHIFT)) {
  7579. reserved_space = round_up(size - page_start,
  7580. fs_info->sectorsize);
  7581. if (reserved_space < PAGE_SIZE) {
  7582. end = page_start + reserved_space - 1;
  7583. btrfs_delalloc_release_space(BTRFS_I(inode),
  7584. data_reserved, page_start,
  7585. PAGE_SIZE - reserved_space, true);
  7586. }
  7587. }
  7588. /*
  7589. * page_mkwrite gets called when the page is firstly dirtied after it's
  7590. * faulted in, but write(2) could also dirty a page and set delalloc
  7591. * bits, thus in this case for space account reason, we still need to
  7592. * clear any delalloc bits within this page range since we have to
  7593. * reserve data&meta space before lock_page() (see above comments).
  7594. */
  7595. clear_extent_bit(&BTRFS_I(inode)->io_tree, page_start, end,
  7596. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
  7597. EXTENT_DEFRAG, &cached_state);
  7598. ret2 = btrfs_set_extent_delalloc(BTRFS_I(inode), page_start, end, 0,
  7599. &cached_state);
  7600. if (ret2) {
  7601. unlock_extent(io_tree, page_start, page_end, &cached_state);
  7602. ret = VM_FAULT_SIGBUS;
  7603. goto out_unlock;
  7604. }
  7605. /* page is wholly or partially inside EOF */
  7606. if (page_start + PAGE_SIZE > size)
  7607. zero_start = offset_in_page(size);
  7608. else
  7609. zero_start = PAGE_SIZE;
  7610. if (zero_start != PAGE_SIZE)
  7611. memzero_page(page, zero_start, PAGE_SIZE - zero_start);
  7612. btrfs_page_clear_checked(fs_info, page, page_start, PAGE_SIZE);
  7613. btrfs_page_set_dirty(fs_info, page, page_start, end + 1 - page_start);
  7614. btrfs_page_set_uptodate(fs_info, page, page_start, end + 1 - page_start);
  7615. btrfs_set_inode_last_sub_trans(BTRFS_I(inode));
  7616. unlock_extent(io_tree, page_start, page_end, &cached_state);
  7617. up_read(&BTRFS_I(inode)->i_mmap_lock);
  7618. btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
  7619. sb_end_pagefault(inode->i_sb);
  7620. extent_changeset_free(data_reserved);
  7621. return VM_FAULT_LOCKED;
  7622. out_unlock:
  7623. unlock_page(page);
  7624. up_read(&BTRFS_I(inode)->i_mmap_lock);
  7625. out:
  7626. btrfs_delalloc_release_extents(BTRFS_I(inode), PAGE_SIZE);
  7627. btrfs_delalloc_release_space(BTRFS_I(inode), data_reserved, page_start,
  7628. reserved_space, (ret != 0));
  7629. out_noreserve:
  7630. sb_end_pagefault(inode->i_sb);
  7631. extent_changeset_free(data_reserved);
  7632. return ret;
  7633. }
  7634. static int btrfs_truncate(struct inode *inode, bool skip_writeback)
  7635. {
  7636. struct btrfs_truncate_control control = {
  7637. .inode = BTRFS_I(inode),
  7638. .ino = btrfs_ino(BTRFS_I(inode)),
  7639. .min_type = BTRFS_EXTENT_DATA_KEY,
  7640. .clear_extent_range = true,
  7641. };
  7642. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  7643. struct btrfs_root *root = BTRFS_I(inode)->root;
  7644. struct btrfs_block_rsv *rsv;
  7645. int ret;
  7646. struct btrfs_trans_handle *trans;
  7647. u64 mask = fs_info->sectorsize - 1;
  7648. u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
  7649. if (!skip_writeback) {
  7650. ret = btrfs_wait_ordered_range(inode, inode->i_size & (~mask),
  7651. (u64)-1);
  7652. if (ret)
  7653. return ret;
  7654. }
  7655. /*
  7656. * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
  7657. * things going on here:
  7658. *
  7659. * 1) We need to reserve space to update our inode.
  7660. *
  7661. * 2) We need to have something to cache all the space that is going to
  7662. * be free'd up by the truncate operation, but also have some slack
  7663. * space reserved in case it uses space during the truncate (thank you
  7664. * very much snapshotting).
  7665. *
  7666. * And we need these to be separate. The fact is we can use a lot of
  7667. * space doing the truncate, and we have no earthly idea how much space
  7668. * we will use, so we need the truncate reservation to be separate so it
  7669. * doesn't end up using space reserved for updating the inode. We also
  7670. * need to be able to stop the transaction and start a new one, which
  7671. * means we need to be able to update the inode several times, and we
  7672. * have no idea of knowing how many times that will be, so we can't just
  7673. * reserve 1 item for the entirety of the operation, so that has to be
  7674. * done separately as well.
  7675. *
  7676. * So that leaves us with
  7677. *
  7678. * 1) rsv - for the truncate reservation, which we will steal from the
  7679. * transaction reservation.
  7680. * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
  7681. * updating the inode.
  7682. */
  7683. rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
  7684. if (!rsv)
  7685. return -ENOMEM;
  7686. rsv->size = min_size;
  7687. rsv->failfast = true;
  7688. /*
  7689. * 1 for the truncate slack space
  7690. * 1 for updating the inode.
  7691. */
  7692. trans = btrfs_start_transaction(root, 2);
  7693. if (IS_ERR(trans)) {
  7694. ret = PTR_ERR(trans);
  7695. goto out;
  7696. }
  7697. /* Migrate the slack space for the truncate to our reserve */
  7698. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
  7699. min_size, false);
  7700. BUG_ON(ret);
  7701. trans->block_rsv = rsv;
  7702. while (1) {
  7703. struct extent_state *cached_state = NULL;
  7704. const u64 new_size = inode->i_size;
  7705. const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
  7706. control.new_size = new_size;
  7707. lock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
  7708. &cached_state);
  7709. /*
  7710. * We want to drop from the next block forward in case this new
  7711. * size is not block aligned since we will be keeping the last
  7712. * block of the extent just the way it is.
  7713. */
  7714. btrfs_drop_extent_map_range(BTRFS_I(inode),
  7715. ALIGN(new_size, fs_info->sectorsize),
  7716. (u64)-1, false);
  7717. ret = btrfs_truncate_inode_items(trans, root, &control);
  7718. inode_sub_bytes(inode, control.sub_bytes);
  7719. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), control.last_size);
  7720. unlock_extent(&BTRFS_I(inode)->io_tree, lock_start, (u64)-1,
  7721. &cached_state);
  7722. trans->block_rsv = &fs_info->trans_block_rsv;
  7723. if (ret != -ENOSPC && ret != -EAGAIN)
  7724. break;
  7725. ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
  7726. if (ret)
  7727. break;
  7728. btrfs_end_transaction(trans);
  7729. btrfs_btree_balance_dirty(fs_info);
  7730. trans = btrfs_start_transaction(root, 2);
  7731. if (IS_ERR(trans)) {
  7732. ret = PTR_ERR(trans);
  7733. trans = NULL;
  7734. break;
  7735. }
  7736. btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
  7737. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
  7738. rsv, min_size, false);
  7739. BUG_ON(ret); /* shouldn't happen */
  7740. trans->block_rsv = rsv;
  7741. }
  7742. /*
  7743. * We can't call btrfs_truncate_block inside a trans handle as we could
  7744. * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
  7745. * know we've truncated everything except the last little bit, and can
  7746. * do btrfs_truncate_block and then update the disk_i_size.
  7747. */
  7748. if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
  7749. btrfs_end_transaction(trans);
  7750. btrfs_btree_balance_dirty(fs_info);
  7751. ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
  7752. if (ret)
  7753. goto out;
  7754. trans = btrfs_start_transaction(root, 1);
  7755. if (IS_ERR(trans)) {
  7756. ret = PTR_ERR(trans);
  7757. goto out;
  7758. }
  7759. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
  7760. }
  7761. if (trans) {
  7762. int ret2;
  7763. trans->block_rsv = &fs_info->trans_block_rsv;
  7764. ret2 = btrfs_update_inode(trans, root, BTRFS_I(inode));
  7765. if (ret2 && !ret)
  7766. ret = ret2;
  7767. ret2 = btrfs_end_transaction(trans);
  7768. if (ret2 && !ret)
  7769. ret = ret2;
  7770. btrfs_btree_balance_dirty(fs_info);
  7771. }
  7772. out:
  7773. btrfs_free_block_rsv(fs_info, rsv);
  7774. /*
  7775. * So if we truncate and then write and fsync we normally would just
  7776. * write the extents that changed, which is a problem if we need to
  7777. * first truncate that entire inode. So set this flag so we write out
  7778. * all of the extents in the inode to the sync log so we're completely
  7779. * safe.
  7780. *
  7781. * If no extents were dropped or trimmed we don't need to force the next
  7782. * fsync to truncate all the inode's items from the log and re-log them
  7783. * all. This means the truncate operation did not change the file size,
  7784. * or changed it to a smaller size but there was only an implicit hole
  7785. * between the old i_size and the new i_size, and there were no prealloc
  7786. * extents beyond i_size to drop.
  7787. */
  7788. if (control.extents_found > 0)
  7789. btrfs_set_inode_full_sync(BTRFS_I(inode));
  7790. return ret;
  7791. }
  7792. struct inode *btrfs_new_subvol_inode(struct user_namespace *mnt_userns,
  7793. struct inode *dir)
  7794. {
  7795. struct inode *inode;
  7796. inode = new_inode(dir->i_sb);
  7797. if (inode) {
  7798. /*
  7799. * Subvolumes don't inherit the sgid bit or the parent's gid if
  7800. * the parent's sgid bit is set. This is probably a bug.
  7801. */
  7802. inode_init_owner(mnt_userns, inode, NULL,
  7803. S_IFDIR | (~current_umask() & S_IRWXUGO));
  7804. inode->i_op = &btrfs_dir_inode_operations;
  7805. inode->i_fop = &btrfs_dir_file_operations;
  7806. }
  7807. return inode;
  7808. }
  7809. struct inode *btrfs_alloc_inode(struct super_block *sb)
  7810. {
  7811. struct btrfs_fs_info *fs_info = btrfs_sb(sb);
  7812. struct btrfs_inode *ei;
  7813. struct inode *inode;
  7814. ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
  7815. if (!ei)
  7816. return NULL;
  7817. ei->root = NULL;
  7818. ei->generation = 0;
  7819. ei->last_trans = 0;
  7820. ei->last_sub_trans = 0;
  7821. ei->logged_trans = 0;
  7822. ei->delalloc_bytes = 0;
  7823. ei->new_delalloc_bytes = 0;
  7824. ei->defrag_bytes = 0;
  7825. ei->disk_i_size = 0;
  7826. ei->flags = 0;
  7827. ei->ro_flags = 0;
  7828. ei->csum_bytes = 0;
  7829. ei->index_cnt = (u64)-1;
  7830. ei->dir_index = 0;
  7831. ei->last_unlink_trans = 0;
  7832. ei->last_reflink_trans = 0;
  7833. ei->last_log_commit = 0;
  7834. spin_lock_init(&ei->lock);
  7835. spin_lock_init(&ei->io_failure_lock);
  7836. ei->outstanding_extents = 0;
  7837. if (sb->s_magic != BTRFS_TEST_MAGIC)
  7838. btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
  7839. BTRFS_BLOCK_RSV_DELALLOC);
  7840. ei->runtime_flags = 0;
  7841. ei->prop_compress = BTRFS_COMPRESS_NONE;
  7842. ei->defrag_compress = BTRFS_COMPRESS_NONE;
  7843. ei->delayed_node = NULL;
  7844. ei->i_otime.tv_sec = 0;
  7845. ei->i_otime.tv_nsec = 0;
  7846. inode = &ei->vfs_inode;
  7847. extent_map_tree_init(&ei->extent_tree);
  7848. extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO, inode);
  7849. extent_io_tree_init(fs_info, &ei->file_extent_tree,
  7850. IO_TREE_INODE_FILE_EXTENT, NULL);
  7851. ei->io_failure_tree = RB_ROOT;
  7852. atomic_set(&ei->sync_writers, 0);
  7853. mutex_init(&ei->log_mutex);
  7854. btrfs_ordered_inode_tree_init(&ei->ordered_tree);
  7855. INIT_LIST_HEAD(&ei->delalloc_inodes);
  7856. INIT_LIST_HEAD(&ei->delayed_iput);
  7857. RB_CLEAR_NODE(&ei->rb_node);
  7858. init_rwsem(&ei->i_mmap_lock);
  7859. return inode;
  7860. }
  7861. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  7862. void btrfs_test_destroy_inode(struct inode *inode)
  7863. {
  7864. btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
  7865. kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
  7866. }
  7867. #endif
  7868. void btrfs_free_inode(struct inode *inode)
  7869. {
  7870. kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
  7871. }
  7872. void btrfs_destroy_inode(struct inode *vfs_inode)
  7873. {
  7874. struct btrfs_ordered_extent *ordered;
  7875. struct btrfs_inode *inode = BTRFS_I(vfs_inode);
  7876. struct btrfs_root *root = inode->root;
  7877. bool freespace_inode;
  7878. WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
  7879. WARN_ON(vfs_inode->i_data.nrpages);
  7880. WARN_ON(inode->block_rsv.reserved);
  7881. WARN_ON(inode->block_rsv.size);
  7882. WARN_ON(inode->outstanding_extents);
  7883. if (!S_ISDIR(vfs_inode->i_mode)) {
  7884. WARN_ON(inode->delalloc_bytes);
  7885. WARN_ON(inode->new_delalloc_bytes);
  7886. }
  7887. WARN_ON(inode->csum_bytes);
  7888. WARN_ON(inode->defrag_bytes);
  7889. /*
  7890. * This can happen where we create an inode, but somebody else also
  7891. * created the same inode and we need to destroy the one we already
  7892. * created.
  7893. */
  7894. if (!root)
  7895. return;
  7896. /*
  7897. * If this is a free space inode do not take the ordered extents lockdep
  7898. * map.
  7899. */
  7900. freespace_inode = btrfs_is_free_space_inode(inode);
  7901. while (1) {
  7902. ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
  7903. if (!ordered)
  7904. break;
  7905. else {
  7906. btrfs_err(root->fs_info,
  7907. "found ordered extent %llu %llu on inode cleanup",
  7908. ordered->file_offset, ordered->num_bytes);
  7909. if (!freespace_inode)
  7910. btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
  7911. btrfs_remove_ordered_extent(inode, ordered);
  7912. btrfs_put_ordered_extent(ordered);
  7913. btrfs_put_ordered_extent(ordered);
  7914. }
  7915. }
  7916. btrfs_qgroup_check_reserved_leak(inode);
  7917. inode_tree_del(inode);
  7918. btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
  7919. btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
  7920. btrfs_put_root(inode->root);
  7921. }
  7922. int btrfs_drop_inode(struct inode *inode)
  7923. {
  7924. struct btrfs_root *root = BTRFS_I(inode)->root;
  7925. if (root == NULL)
  7926. return 1;
  7927. /* the snap/subvol tree is on deleting */
  7928. if (btrfs_root_refs(&root->root_item) == 0)
  7929. return 1;
  7930. else
  7931. return generic_drop_inode(inode);
  7932. }
  7933. static void init_once(void *foo)
  7934. {
  7935. struct btrfs_inode *ei = foo;
  7936. inode_init_once(&ei->vfs_inode);
  7937. }
  7938. void __cold btrfs_destroy_cachep(void)
  7939. {
  7940. /*
  7941. * Make sure all delayed rcu free inodes are flushed before we
  7942. * destroy cache.
  7943. */
  7944. rcu_barrier();
  7945. bioset_exit(&btrfs_dio_bioset);
  7946. kmem_cache_destroy(btrfs_inode_cachep);
  7947. kmem_cache_destroy(btrfs_trans_handle_cachep);
  7948. kmem_cache_destroy(btrfs_path_cachep);
  7949. kmem_cache_destroy(btrfs_free_space_cachep);
  7950. kmem_cache_destroy(btrfs_free_space_bitmap_cachep);
  7951. }
  7952. int __init btrfs_init_cachep(void)
  7953. {
  7954. btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
  7955. sizeof(struct btrfs_inode), 0,
  7956. SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD | SLAB_ACCOUNT,
  7957. init_once);
  7958. if (!btrfs_inode_cachep)
  7959. goto fail;
  7960. btrfs_trans_handle_cachep = kmem_cache_create("btrfs_trans_handle",
  7961. sizeof(struct btrfs_trans_handle), 0,
  7962. SLAB_TEMPORARY | SLAB_MEM_SPREAD, NULL);
  7963. if (!btrfs_trans_handle_cachep)
  7964. goto fail;
  7965. btrfs_path_cachep = kmem_cache_create("btrfs_path",
  7966. sizeof(struct btrfs_path), 0,
  7967. SLAB_MEM_SPREAD, NULL);
  7968. if (!btrfs_path_cachep)
  7969. goto fail;
  7970. btrfs_free_space_cachep = kmem_cache_create("btrfs_free_space",
  7971. sizeof(struct btrfs_free_space), 0,
  7972. SLAB_MEM_SPREAD, NULL);
  7973. if (!btrfs_free_space_cachep)
  7974. goto fail;
  7975. btrfs_free_space_bitmap_cachep = kmem_cache_create("btrfs_free_space_bitmap",
  7976. PAGE_SIZE, PAGE_SIZE,
  7977. SLAB_MEM_SPREAD, NULL);
  7978. if (!btrfs_free_space_bitmap_cachep)
  7979. goto fail;
  7980. if (bioset_init(&btrfs_dio_bioset, BIO_POOL_SIZE,
  7981. offsetof(struct btrfs_dio_private, bio),
  7982. BIOSET_NEED_BVECS))
  7983. goto fail;
  7984. return 0;
  7985. fail:
  7986. btrfs_destroy_cachep();
  7987. return -ENOMEM;
  7988. }
  7989. static int btrfs_getattr(struct user_namespace *mnt_userns,
  7990. const struct path *path, struct kstat *stat,
  7991. u32 request_mask, unsigned int flags)
  7992. {
  7993. u64 delalloc_bytes;
  7994. u64 inode_bytes;
  7995. struct inode *inode = d_inode(path->dentry);
  7996. u32 blocksize = inode->i_sb->s_blocksize;
  7997. u32 bi_flags = BTRFS_I(inode)->flags;
  7998. u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
  7999. stat->result_mask |= STATX_BTIME;
  8000. stat->btime.tv_sec = BTRFS_I(inode)->i_otime.tv_sec;
  8001. stat->btime.tv_nsec = BTRFS_I(inode)->i_otime.tv_nsec;
  8002. if (bi_flags & BTRFS_INODE_APPEND)
  8003. stat->attributes |= STATX_ATTR_APPEND;
  8004. if (bi_flags & BTRFS_INODE_COMPRESS)
  8005. stat->attributes |= STATX_ATTR_COMPRESSED;
  8006. if (bi_flags & BTRFS_INODE_IMMUTABLE)
  8007. stat->attributes |= STATX_ATTR_IMMUTABLE;
  8008. if (bi_flags & BTRFS_INODE_NODUMP)
  8009. stat->attributes |= STATX_ATTR_NODUMP;
  8010. if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
  8011. stat->attributes |= STATX_ATTR_VERITY;
  8012. stat->attributes_mask |= (STATX_ATTR_APPEND |
  8013. STATX_ATTR_COMPRESSED |
  8014. STATX_ATTR_IMMUTABLE |
  8015. STATX_ATTR_NODUMP);
  8016. generic_fillattr(mnt_userns, inode, stat);
  8017. stat->dev = BTRFS_I(inode)->root->anon_dev;
  8018. spin_lock(&BTRFS_I(inode)->lock);
  8019. delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
  8020. inode_bytes = inode_get_bytes(inode);
  8021. spin_unlock(&BTRFS_I(inode)->lock);
  8022. stat->blocks = (ALIGN(inode_bytes, blocksize) +
  8023. ALIGN(delalloc_bytes, blocksize)) >> 9;
  8024. return 0;
  8025. }
  8026. static int btrfs_rename_exchange(struct inode *old_dir,
  8027. struct dentry *old_dentry,
  8028. struct inode *new_dir,
  8029. struct dentry *new_dentry)
  8030. {
  8031. struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
  8032. struct btrfs_trans_handle *trans;
  8033. unsigned int trans_num_items;
  8034. struct btrfs_root *root = BTRFS_I(old_dir)->root;
  8035. struct btrfs_root *dest = BTRFS_I(new_dir)->root;
  8036. struct inode *new_inode = new_dentry->d_inode;
  8037. struct inode *old_inode = old_dentry->d_inode;
  8038. struct timespec64 ctime = current_time(old_inode);
  8039. struct btrfs_rename_ctx old_rename_ctx;
  8040. struct btrfs_rename_ctx new_rename_ctx;
  8041. u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
  8042. u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
  8043. u64 old_idx = 0;
  8044. u64 new_idx = 0;
  8045. int ret;
  8046. int ret2;
  8047. bool need_abort = false;
  8048. struct fscrypt_name old_fname, new_fname;
  8049. struct fscrypt_str *old_name, *new_name;
  8050. /*
  8051. * For non-subvolumes allow exchange only within one subvolume, in the
  8052. * same inode namespace. Two subvolumes (represented as directory) can
  8053. * be exchanged as they're a logical link and have a fixed inode number.
  8054. */
  8055. if (root != dest &&
  8056. (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
  8057. new_ino != BTRFS_FIRST_FREE_OBJECTID))
  8058. return -EXDEV;
  8059. ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
  8060. if (ret)
  8061. return ret;
  8062. ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
  8063. if (ret) {
  8064. fscrypt_free_filename(&old_fname);
  8065. return ret;
  8066. }
  8067. old_name = &old_fname.disk_name;
  8068. new_name = &new_fname.disk_name;
  8069. /* close the race window with snapshot create/destroy ioctl */
  8070. if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
  8071. new_ino == BTRFS_FIRST_FREE_OBJECTID)
  8072. down_read(&fs_info->subvol_sem);
  8073. /*
  8074. * For each inode:
  8075. * 1 to remove old dir item
  8076. * 1 to remove old dir index
  8077. * 1 to add new dir item
  8078. * 1 to add new dir index
  8079. * 1 to update parent inode
  8080. *
  8081. * If the parents are the same, we only need to account for one
  8082. */
  8083. trans_num_items = (old_dir == new_dir ? 9 : 10);
  8084. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8085. /*
  8086. * 1 to remove old root ref
  8087. * 1 to remove old root backref
  8088. * 1 to add new root ref
  8089. * 1 to add new root backref
  8090. */
  8091. trans_num_items += 4;
  8092. } else {
  8093. /*
  8094. * 1 to update inode item
  8095. * 1 to remove old inode ref
  8096. * 1 to add new inode ref
  8097. */
  8098. trans_num_items += 3;
  8099. }
  8100. if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
  8101. trans_num_items += 4;
  8102. else
  8103. trans_num_items += 3;
  8104. trans = btrfs_start_transaction(root, trans_num_items);
  8105. if (IS_ERR(trans)) {
  8106. ret = PTR_ERR(trans);
  8107. goto out_notrans;
  8108. }
  8109. if (dest != root) {
  8110. ret = btrfs_record_root_in_trans(trans, dest);
  8111. if (ret)
  8112. goto out_fail;
  8113. }
  8114. /*
  8115. * We need to find a free sequence number both in the source and
  8116. * in the destination directory for the exchange.
  8117. */
  8118. ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
  8119. if (ret)
  8120. goto out_fail;
  8121. ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
  8122. if (ret)
  8123. goto out_fail;
  8124. BTRFS_I(old_inode)->dir_index = 0ULL;
  8125. BTRFS_I(new_inode)->dir_index = 0ULL;
  8126. /* Reference for the source. */
  8127. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8128. /* force full log commit if subvolume involved. */
  8129. btrfs_set_log_full_commit(trans);
  8130. } else {
  8131. ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
  8132. btrfs_ino(BTRFS_I(new_dir)),
  8133. old_idx);
  8134. if (ret)
  8135. goto out_fail;
  8136. need_abort = true;
  8137. }
  8138. /* And now for the dest. */
  8139. if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8140. /* force full log commit if subvolume involved. */
  8141. btrfs_set_log_full_commit(trans);
  8142. } else {
  8143. ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
  8144. btrfs_ino(BTRFS_I(old_dir)),
  8145. new_idx);
  8146. if (ret) {
  8147. if (need_abort)
  8148. btrfs_abort_transaction(trans, ret);
  8149. goto out_fail;
  8150. }
  8151. }
  8152. /* Update inode version and ctime/mtime. */
  8153. inode_inc_iversion(old_dir);
  8154. inode_inc_iversion(new_dir);
  8155. inode_inc_iversion(old_inode);
  8156. inode_inc_iversion(new_inode);
  8157. old_dir->i_mtime = ctime;
  8158. old_dir->i_ctime = ctime;
  8159. new_dir->i_mtime = ctime;
  8160. new_dir->i_ctime = ctime;
  8161. old_inode->i_ctime = ctime;
  8162. new_inode->i_ctime = ctime;
  8163. if (old_dentry->d_parent != new_dentry->d_parent) {
  8164. btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
  8165. BTRFS_I(old_inode), 1);
  8166. btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
  8167. BTRFS_I(new_inode), 1);
  8168. }
  8169. /* src is a subvolume */
  8170. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8171. ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
  8172. } else { /* src is an inode */
  8173. ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
  8174. BTRFS_I(old_dentry->d_inode),
  8175. old_name, &old_rename_ctx);
  8176. if (!ret)
  8177. ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
  8178. }
  8179. if (ret) {
  8180. btrfs_abort_transaction(trans, ret);
  8181. goto out_fail;
  8182. }
  8183. /* dest is a subvolume */
  8184. if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8185. ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
  8186. } else { /* dest is an inode */
  8187. ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
  8188. BTRFS_I(new_dentry->d_inode),
  8189. new_name, &new_rename_ctx);
  8190. if (!ret)
  8191. ret = btrfs_update_inode(trans, dest, BTRFS_I(new_inode));
  8192. }
  8193. if (ret) {
  8194. btrfs_abort_transaction(trans, ret);
  8195. goto out_fail;
  8196. }
  8197. ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
  8198. new_name, 0, old_idx);
  8199. if (ret) {
  8200. btrfs_abort_transaction(trans, ret);
  8201. goto out_fail;
  8202. }
  8203. ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
  8204. old_name, 0, new_idx);
  8205. if (ret) {
  8206. btrfs_abort_transaction(trans, ret);
  8207. goto out_fail;
  8208. }
  8209. if (old_inode->i_nlink == 1)
  8210. BTRFS_I(old_inode)->dir_index = old_idx;
  8211. if (new_inode->i_nlink == 1)
  8212. BTRFS_I(new_inode)->dir_index = new_idx;
  8213. /*
  8214. * Now pin the logs of the roots. We do it to ensure that no other task
  8215. * can sync the logs while we are in progress with the rename, because
  8216. * that could result in an inconsistency in case any of the inodes that
  8217. * are part of this rename operation were logged before.
  8218. */
  8219. if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
  8220. btrfs_pin_log_trans(root);
  8221. if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
  8222. btrfs_pin_log_trans(dest);
  8223. /* Do the log updates for all inodes. */
  8224. if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
  8225. btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
  8226. old_rename_ctx.index, new_dentry->d_parent);
  8227. if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
  8228. btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
  8229. new_rename_ctx.index, old_dentry->d_parent);
  8230. /* Now unpin the logs. */
  8231. if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
  8232. btrfs_end_log_trans(root);
  8233. if (new_ino != BTRFS_FIRST_FREE_OBJECTID)
  8234. btrfs_end_log_trans(dest);
  8235. out_fail:
  8236. ret2 = btrfs_end_transaction(trans);
  8237. ret = ret ? ret : ret2;
  8238. out_notrans:
  8239. if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
  8240. old_ino == BTRFS_FIRST_FREE_OBJECTID)
  8241. up_read(&fs_info->subvol_sem);
  8242. fscrypt_free_filename(&new_fname);
  8243. fscrypt_free_filename(&old_fname);
  8244. return ret;
  8245. }
  8246. static struct inode *new_whiteout_inode(struct user_namespace *mnt_userns,
  8247. struct inode *dir)
  8248. {
  8249. struct inode *inode;
  8250. inode = new_inode(dir->i_sb);
  8251. if (inode) {
  8252. inode_init_owner(mnt_userns, inode, dir,
  8253. S_IFCHR | WHITEOUT_MODE);
  8254. inode->i_op = &btrfs_special_inode_operations;
  8255. init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
  8256. }
  8257. return inode;
  8258. }
  8259. static int btrfs_rename(struct user_namespace *mnt_userns,
  8260. struct inode *old_dir, struct dentry *old_dentry,
  8261. struct inode *new_dir, struct dentry *new_dentry,
  8262. unsigned int flags)
  8263. {
  8264. struct btrfs_fs_info *fs_info = btrfs_sb(old_dir->i_sb);
  8265. struct btrfs_new_inode_args whiteout_args = {
  8266. .dir = old_dir,
  8267. .dentry = old_dentry,
  8268. };
  8269. struct btrfs_trans_handle *trans;
  8270. unsigned int trans_num_items;
  8271. struct btrfs_root *root = BTRFS_I(old_dir)->root;
  8272. struct btrfs_root *dest = BTRFS_I(new_dir)->root;
  8273. struct inode *new_inode = d_inode(new_dentry);
  8274. struct inode *old_inode = d_inode(old_dentry);
  8275. struct btrfs_rename_ctx rename_ctx;
  8276. u64 index = 0;
  8277. int ret;
  8278. int ret2;
  8279. u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
  8280. struct fscrypt_name old_fname, new_fname;
  8281. if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
  8282. return -EPERM;
  8283. /* we only allow rename subvolume link between subvolumes */
  8284. if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
  8285. return -EXDEV;
  8286. if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
  8287. (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
  8288. return -ENOTEMPTY;
  8289. if (S_ISDIR(old_inode->i_mode) && new_inode &&
  8290. new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
  8291. return -ENOTEMPTY;
  8292. ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
  8293. if (ret)
  8294. return ret;
  8295. ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
  8296. if (ret) {
  8297. fscrypt_free_filename(&old_fname);
  8298. return ret;
  8299. }
  8300. /* check for collisions, even if the name isn't there */
  8301. ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
  8302. if (ret) {
  8303. if (ret == -EEXIST) {
  8304. /* we shouldn't get
  8305. * eexist without a new_inode */
  8306. if (WARN_ON(!new_inode)) {
  8307. goto out_fscrypt_names;
  8308. }
  8309. } else {
  8310. /* maybe -EOVERFLOW */
  8311. goto out_fscrypt_names;
  8312. }
  8313. }
  8314. ret = 0;
  8315. /*
  8316. * we're using rename to replace one file with another. Start IO on it
  8317. * now so we don't add too much work to the end of the transaction
  8318. */
  8319. if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
  8320. filemap_flush(old_inode->i_mapping);
  8321. if (flags & RENAME_WHITEOUT) {
  8322. whiteout_args.inode = new_whiteout_inode(mnt_userns, old_dir);
  8323. if (!whiteout_args.inode) {
  8324. ret = -ENOMEM;
  8325. goto out_fscrypt_names;
  8326. }
  8327. ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
  8328. if (ret)
  8329. goto out_whiteout_inode;
  8330. } else {
  8331. /* 1 to update the old parent inode. */
  8332. trans_num_items = 1;
  8333. }
  8334. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  8335. /* Close the race window with snapshot create/destroy ioctl */
  8336. down_read(&fs_info->subvol_sem);
  8337. /*
  8338. * 1 to remove old root ref
  8339. * 1 to remove old root backref
  8340. * 1 to add new root ref
  8341. * 1 to add new root backref
  8342. */
  8343. trans_num_items += 4;
  8344. } else {
  8345. /*
  8346. * 1 to update inode
  8347. * 1 to remove old inode ref
  8348. * 1 to add new inode ref
  8349. */
  8350. trans_num_items += 3;
  8351. }
  8352. /*
  8353. * 1 to remove old dir item
  8354. * 1 to remove old dir index
  8355. * 1 to add new dir item
  8356. * 1 to add new dir index
  8357. */
  8358. trans_num_items += 4;
  8359. /* 1 to update new parent inode if it's not the same as the old parent */
  8360. if (new_dir != old_dir)
  8361. trans_num_items++;
  8362. if (new_inode) {
  8363. /*
  8364. * 1 to update inode
  8365. * 1 to remove inode ref
  8366. * 1 to remove dir item
  8367. * 1 to remove dir index
  8368. * 1 to possibly add orphan item
  8369. */
  8370. trans_num_items += 5;
  8371. }
  8372. trans = btrfs_start_transaction(root, trans_num_items);
  8373. if (IS_ERR(trans)) {
  8374. ret = PTR_ERR(trans);
  8375. goto out_notrans;
  8376. }
  8377. if (dest != root) {
  8378. ret = btrfs_record_root_in_trans(trans, dest);
  8379. if (ret)
  8380. goto out_fail;
  8381. }
  8382. ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
  8383. if (ret)
  8384. goto out_fail;
  8385. BTRFS_I(old_inode)->dir_index = 0ULL;
  8386. if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
  8387. /* force full log commit if subvolume involved. */
  8388. btrfs_set_log_full_commit(trans);
  8389. } else {
  8390. ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
  8391. old_ino, btrfs_ino(BTRFS_I(new_dir)),
  8392. index);
  8393. if (ret)
  8394. goto out_fail;
  8395. }
  8396. inode_inc_iversion(old_dir);
  8397. inode_inc_iversion(new_dir);
  8398. inode_inc_iversion(old_inode);
  8399. old_dir->i_mtime = current_time(old_dir);
  8400. old_dir->i_ctime = old_dir->i_mtime;
  8401. new_dir->i_mtime = old_dir->i_mtime;
  8402. new_dir->i_ctime = old_dir->i_mtime;
  8403. old_inode->i_ctime = old_dir->i_mtime;
  8404. if (old_dentry->d_parent != new_dentry->d_parent)
  8405. btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
  8406. BTRFS_I(old_inode), 1);
  8407. if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
  8408. ret = btrfs_unlink_subvol(trans, old_dir, old_dentry);
  8409. } else {
  8410. ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
  8411. BTRFS_I(d_inode(old_dentry)),
  8412. &old_fname.disk_name, &rename_ctx);
  8413. if (!ret)
  8414. ret = btrfs_update_inode(trans, root, BTRFS_I(old_inode));
  8415. }
  8416. if (ret) {
  8417. btrfs_abort_transaction(trans, ret);
  8418. goto out_fail;
  8419. }
  8420. if (new_inode) {
  8421. inode_inc_iversion(new_inode);
  8422. new_inode->i_ctime = current_time(new_inode);
  8423. if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
  8424. BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
  8425. ret = btrfs_unlink_subvol(trans, new_dir, new_dentry);
  8426. BUG_ON(new_inode->i_nlink == 0);
  8427. } else {
  8428. ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
  8429. BTRFS_I(d_inode(new_dentry)),
  8430. &new_fname.disk_name);
  8431. }
  8432. if (!ret && new_inode->i_nlink == 0)
  8433. ret = btrfs_orphan_add(trans,
  8434. BTRFS_I(d_inode(new_dentry)));
  8435. if (ret) {
  8436. btrfs_abort_transaction(trans, ret);
  8437. goto out_fail;
  8438. }
  8439. }
  8440. ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
  8441. &new_fname.disk_name, 0, index);
  8442. if (ret) {
  8443. btrfs_abort_transaction(trans, ret);
  8444. goto out_fail;
  8445. }
  8446. if (old_inode->i_nlink == 1)
  8447. BTRFS_I(old_inode)->dir_index = index;
  8448. if (old_ino != BTRFS_FIRST_FREE_OBJECTID)
  8449. btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
  8450. rename_ctx.index, new_dentry->d_parent);
  8451. if (flags & RENAME_WHITEOUT) {
  8452. ret = btrfs_create_new_inode(trans, &whiteout_args);
  8453. if (ret) {
  8454. btrfs_abort_transaction(trans, ret);
  8455. goto out_fail;
  8456. } else {
  8457. unlock_new_inode(whiteout_args.inode);
  8458. iput(whiteout_args.inode);
  8459. whiteout_args.inode = NULL;
  8460. }
  8461. }
  8462. out_fail:
  8463. ret2 = btrfs_end_transaction(trans);
  8464. ret = ret ? ret : ret2;
  8465. out_notrans:
  8466. if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
  8467. up_read(&fs_info->subvol_sem);
  8468. if (flags & RENAME_WHITEOUT)
  8469. btrfs_new_inode_args_destroy(&whiteout_args);
  8470. out_whiteout_inode:
  8471. if (flags & RENAME_WHITEOUT)
  8472. iput(whiteout_args.inode);
  8473. out_fscrypt_names:
  8474. fscrypt_free_filename(&old_fname);
  8475. fscrypt_free_filename(&new_fname);
  8476. return ret;
  8477. }
  8478. static int btrfs_rename2(struct user_namespace *mnt_userns, struct inode *old_dir,
  8479. struct dentry *old_dentry, struct inode *new_dir,
  8480. struct dentry *new_dentry, unsigned int flags)
  8481. {
  8482. int ret;
  8483. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
  8484. return -EINVAL;
  8485. if (flags & RENAME_EXCHANGE)
  8486. ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
  8487. new_dentry);
  8488. else
  8489. ret = btrfs_rename(mnt_userns, old_dir, old_dentry, new_dir,
  8490. new_dentry, flags);
  8491. btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
  8492. return ret;
  8493. }
  8494. struct btrfs_delalloc_work {
  8495. struct inode *inode;
  8496. struct completion completion;
  8497. struct list_head list;
  8498. struct btrfs_work work;
  8499. };
  8500. static void btrfs_run_delalloc_work(struct btrfs_work *work)
  8501. {
  8502. struct btrfs_delalloc_work *delalloc_work;
  8503. struct inode *inode;
  8504. delalloc_work = container_of(work, struct btrfs_delalloc_work,
  8505. work);
  8506. inode = delalloc_work->inode;
  8507. filemap_flush(inode->i_mapping);
  8508. if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  8509. &BTRFS_I(inode)->runtime_flags))
  8510. filemap_flush(inode->i_mapping);
  8511. iput(inode);
  8512. complete(&delalloc_work->completion);
  8513. }
  8514. static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
  8515. {
  8516. struct btrfs_delalloc_work *work;
  8517. work = kmalloc(sizeof(*work), GFP_NOFS);
  8518. if (!work)
  8519. return NULL;
  8520. init_completion(&work->completion);
  8521. INIT_LIST_HEAD(&work->list);
  8522. work->inode = inode;
  8523. btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL, NULL);
  8524. return work;
  8525. }
  8526. /*
  8527. * some fairly slow code that needs optimization. This walks the list
  8528. * of all the inodes with pending delalloc and forces them to disk.
  8529. */
  8530. static int start_delalloc_inodes(struct btrfs_root *root,
  8531. struct writeback_control *wbc, bool snapshot,
  8532. bool in_reclaim_context)
  8533. {
  8534. struct btrfs_inode *binode;
  8535. struct inode *inode;
  8536. struct btrfs_delalloc_work *work, *next;
  8537. struct list_head works;
  8538. struct list_head splice;
  8539. int ret = 0;
  8540. bool full_flush = wbc->nr_to_write == LONG_MAX;
  8541. INIT_LIST_HEAD(&works);
  8542. INIT_LIST_HEAD(&splice);
  8543. mutex_lock(&root->delalloc_mutex);
  8544. spin_lock(&root->delalloc_lock);
  8545. list_splice_init(&root->delalloc_inodes, &splice);
  8546. while (!list_empty(&splice)) {
  8547. binode = list_entry(splice.next, struct btrfs_inode,
  8548. delalloc_inodes);
  8549. list_move_tail(&binode->delalloc_inodes,
  8550. &root->delalloc_inodes);
  8551. if (in_reclaim_context &&
  8552. test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
  8553. continue;
  8554. inode = igrab(&binode->vfs_inode);
  8555. if (!inode) {
  8556. cond_resched_lock(&root->delalloc_lock);
  8557. continue;
  8558. }
  8559. spin_unlock(&root->delalloc_lock);
  8560. if (snapshot)
  8561. set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
  8562. &binode->runtime_flags);
  8563. if (full_flush) {
  8564. work = btrfs_alloc_delalloc_work(inode);
  8565. if (!work) {
  8566. iput(inode);
  8567. ret = -ENOMEM;
  8568. goto out;
  8569. }
  8570. list_add_tail(&work->list, &works);
  8571. btrfs_queue_work(root->fs_info->flush_workers,
  8572. &work->work);
  8573. } else {
  8574. ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
  8575. btrfs_add_delayed_iput(inode);
  8576. if (ret || wbc->nr_to_write <= 0)
  8577. goto out;
  8578. }
  8579. cond_resched();
  8580. spin_lock(&root->delalloc_lock);
  8581. }
  8582. spin_unlock(&root->delalloc_lock);
  8583. out:
  8584. list_for_each_entry_safe(work, next, &works, list) {
  8585. list_del_init(&work->list);
  8586. wait_for_completion(&work->completion);
  8587. kfree(work);
  8588. }
  8589. if (!list_empty(&splice)) {
  8590. spin_lock(&root->delalloc_lock);
  8591. list_splice_tail(&splice, &root->delalloc_inodes);
  8592. spin_unlock(&root->delalloc_lock);
  8593. }
  8594. mutex_unlock(&root->delalloc_mutex);
  8595. return ret;
  8596. }
  8597. int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
  8598. {
  8599. struct writeback_control wbc = {
  8600. .nr_to_write = LONG_MAX,
  8601. .sync_mode = WB_SYNC_NONE,
  8602. .range_start = 0,
  8603. .range_end = LLONG_MAX,
  8604. };
  8605. struct btrfs_fs_info *fs_info = root->fs_info;
  8606. if (BTRFS_FS_ERROR(fs_info))
  8607. return -EROFS;
  8608. return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
  8609. }
  8610. int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
  8611. bool in_reclaim_context)
  8612. {
  8613. struct writeback_control wbc = {
  8614. .nr_to_write = nr,
  8615. .sync_mode = WB_SYNC_NONE,
  8616. .range_start = 0,
  8617. .range_end = LLONG_MAX,
  8618. };
  8619. struct btrfs_root *root;
  8620. struct list_head splice;
  8621. int ret;
  8622. if (BTRFS_FS_ERROR(fs_info))
  8623. return -EROFS;
  8624. INIT_LIST_HEAD(&splice);
  8625. mutex_lock(&fs_info->delalloc_root_mutex);
  8626. spin_lock(&fs_info->delalloc_root_lock);
  8627. list_splice_init(&fs_info->delalloc_roots, &splice);
  8628. while (!list_empty(&splice)) {
  8629. /*
  8630. * Reset nr_to_write here so we know that we're doing a full
  8631. * flush.
  8632. */
  8633. if (nr == LONG_MAX)
  8634. wbc.nr_to_write = LONG_MAX;
  8635. root = list_first_entry(&splice, struct btrfs_root,
  8636. delalloc_root);
  8637. root = btrfs_grab_root(root);
  8638. BUG_ON(!root);
  8639. list_move_tail(&root->delalloc_root,
  8640. &fs_info->delalloc_roots);
  8641. spin_unlock(&fs_info->delalloc_root_lock);
  8642. ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
  8643. btrfs_put_root(root);
  8644. if (ret < 0 || wbc.nr_to_write <= 0)
  8645. goto out;
  8646. spin_lock(&fs_info->delalloc_root_lock);
  8647. }
  8648. spin_unlock(&fs_info->delalloc_root_lock);
  8649. ret = 0;
  8650. out:
  8651. if (!list_empty(&splice)) {
  8652. spin_lock(&fs_info->delalloc_root_lock);
  8653. list_splice_tail(&splice, &fs_info->delalloc_roots);
  8654. spin_unlock(&fs_info->delalloc_root_lock);
  8655. }
  8656. mutex_unlock(&fs_info->delalloc_root_mutex);
  8657. return ret;
  8658. }
  8659. static int btrfs_symlink(struct user_namespace *mnt_userns, struct inode *dir,
  8660. struct dentry *dentry, const char *symname)
  8661. {
  8662. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  8663. struct btrfs_trans_handle *trans;
  8664. struct btrfs_root *root = BTRFS_I(dir)->root;
  8665. struct btrfs_path *path;
  8666. struct btrfs_key key;
  8667. struct inode *inode;
  8668. struct btrfs_new_inode_args new_inode_args = {
  8669. .dir = dir,
  8670. .dentry = dentry,
  8671. };
  8672. unsigned int trans_num_items;
  8673. int err;
  8674. int name_len;
  8675. int datasize;
  8676. unsigned long ptr;
  8677. struct btrfs_file_extent_item *ei;
  8678. struct extent_buffer *leaf;
  8679. name_len = strlen(symname);
  8680. if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
  8681. return -ENAMETOOLONG;
  8682. inode = new_inode(dir->i_sb);
  8683. if (!inode)
  8684. return -ENOMEM;
  8685. inode_init_owner(mnt_userns, inode, dir, S_IFLNK | S_IRWXUGO);
  8686. inode->i_op = &btrfs_symlink_inode_operations;
  8687. inode_nohighmem(inode);
  8688. inode->i_mapping->a_ops = &btrfs_aops;
  8689. btrfs_i_size_write(BTRFS_I(inode), name_len);
  8690. inode_set_bytes(inode, name_len);
  8691. new_inode_args.inode = inode;
  8692. err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
  8693. if (err)
  8694. goto out_inode;
  8695. /* 1 additional item for the inline extent */
  8696. trans_num_items++;
  8697. trans = btrfs_start_transaction(root, trans_num_items);
  8698. if (IS_ERR(trans)) {
  8699. err = PTR_ERR(trans);
  8700. goto out_new_inode_args;
  8701. }
  8702. err = btrfs_create_new_inode(trans, &new_inode_args);
  8703. if (err)
  8704. goto out;
  8705. path = btrfs_alloc_path();
  8706. if (!path) {
  8707. err = -ENOMEM;
  8708. btrfs_abort_transaction(trans, err);
  8709. discard_new_inode(inode);
  8710. inode = NULL;
  8711. goto out;
  8712. }
  8713. key.objectid = btrfs_ino(BTRFS_I(inode));
  8714. key.offset = 0;
  8715. key.type = BTRFS_EXTENT_DATA_KEY;
  8716. datasize = btrfs_file_extent_calc_inline_size(name_len);
  8717. err = btrfs_insert_empty_item(trans, root, path, &key,
  8718. datasize);
  8719. if (err) {
  8720. btrfs_abort_transaction(trans, err);
  8721. btrfs_free_path(path);
  8722. discard_new_inode(inode);
  8723. inode = NULL;
  8724. goto out;
  8725. }
  8726. leaf = path->nodes[0];
  8727. ei = btrfs_item_ptr(leaf, path->slots[0],
  8728. struct btrfs_file_extent_item);
  8729. btrfs_set_file_extent_generation(leaf, ei, trans->transid);
  8730. btrfs_set_file_extent_type(leaf, ei,
  8731. BTRFS_FILE_EXTENT_INLINE);
  8732. btrfs_set_file_extent_encryption(leaf, ei, 0);
  8733. btrfs_set_file_extent_compression(leaf, ei, 0);
  8734. btrfs_set_file_extent_other_encoding(leaf, ei, 0);
  8735. btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
  8736. ptr = btrfs_file_extent_inline_start(ei);
  8737. write_extent_buffer(leaf, symname, ptr, name_len);
  8738. btrfs_mark_buffer_dirty(leaf);
  8739. btrfs_free_path(path);
  8740. d_instantiate_new(dentry, inode);
  8741. err = 0;
  8742. out:
  8743. btrfs_end_transaction(trans);
  8744. btrfs_btree_balance_dirty(fs_info);
  8745. out_new_inode_args:
  8746. btrfs_new_inode_args_destroy(&new_inode_args);
  8747. out_inode:
  8748. if (err)
  8749. iput(inode);
  8750. return err;
  8751. }
  8752. static struct btrfs_trans_handle *insert_prealloc_file_extent(
  8753. struct btrfs_trans_handle *trans_in,
  8754. struct btrfs_inode *inode,
  8755. struct btrfs_key *ins,
  8756. u64 file_offset)
  8757. {
  8758. struct btrfs_file_extent_item stack_fi;
  8759. struct btrfs_replace_extent_info extent_info;
  8760. struct btrfs_trans_handle *trans = trans_in;
  8761. struct btrfs_path *path;
  8762. u64 start = ins->objectid;
  8763. u64 len = ins->offset;
  8764. int qgroup_released;
  8765. int ret;
  8766. memset(&stack_fi, 0, sizeof(stack_fi));
  8767. btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
  8768. btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
  8769. btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
  8770. btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
  8771. btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
  8772. btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
  8773. /* Encryption and other encoding is reserved and all 0 */
  8774. qgroup_released = btrfs_qgroup_release_data(inode, file_offset, len);
  8775. if (qgroup_released < 0)
  8776. return ERR_PTR(qgroup_released);
  8777. if (trans) {
  8778. ret = insert_reserved_file_extent(trans, inode,
  8779. file_offset, &stack_fi,
  8780. true, qgroup_released);
  8781. if (ret)
  8782. goto free_qgroup;
  8783. return trans;
  8784. }
  8785. extent_info.disk_offset = start;
  8786. extent_info.disk_len = len;
  8787. extent_info.data_offset = 0;
  8788. extent_info.data_len = len;
  8789. extent_info.file_offset = file_offset;
  8790. extent_info.extent_buf = (char *)&stack_fi;
  8791. extent_info.is_new_extent = true;
  8792. extent_info.update_times = true;
  8793. extent_info.qgroup_reserved = qgroup_released;
  8794. extent_info.insertions = 0;
  8795. path = btrfs_alloc_path();
  8796. if (!path) {
  8797. ret = -ENOMEM;
  8798. goto free_qgroup;
  8799. }
  8800. ret = btrfs_replace_file_extents(inode, path, file_offset,
  8801. file_offset + len - 1, &extent_info,
  8802. &trans);
  8803. btrfs_free_path(path);
  8804. if (ret)
  8805. goto free_qgroup;
  8806. return trans;
  8807. free_qgroup:
  8808. /*
  8809. * We have released qgroup data range at the beginning of the function,
  8810. * and normally qgroup_released bytes will be freed when committing
  8811. * transaction.
  8812. * But if we error out early, we have to free what we have released
  8813. * or we leak qgroup data reservation.
  8814. */
  8815. btrfs_qgroup_free_refroot(inode->root->fs_info,
  8816. inode->root->root_key.objectid, qgroup_released,
  8817. BTRFS_QGROUP_RSV_DATA);
  8818. return ERR_PTR(ret);
  8819. }
  8820. static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
  8821. u64 start, u64 num_bytes, u64 min_size,
  8822. loff_t actual_len, u64 *alloc_hint,
  8823. struct btrfs_trans_handle *trans)
  8824. {
  8825. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  8826. struct extent_map *em;
  8827. struct btrfs_root *root = BTRFS_I(inode)->root;
  8828. struct btrfs_key ins;
  8829. u64 cur_offset = start;
  8830. u64 clear_offset = start;
  8831. u64 i_size;
  8832. u64 cur_bytes;
  8833. u64 last_alloc = (u64)-1;
  8834. int ret = 0;
  8835. bool own_trans = true;
  8836. u64 end = start + num_bytes - 1;
  8837. if (trans)
  8838. own_trans = false;
  8839. while (num_bytes > 0) {
  8840. cur_bytes = min_t(u64, num_bytes, SZ_256M);
  8841. cur_bytes = max(cur_bytes, min_size);
  8842. /*
  8843. * If we are severely fragmented we could end up with really
  8844. * small allocations, so if the allocator is returning small
  8845. * chunks lets make its job easier by only searching for those
  8846. * sized chunks.
  8847. */
  8848. cur_bytes = min(cur_bytes, last_alloc);
  8849. ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
  8850. min_size, 0, *alloc_hint, &ins, 1, 0);
  8851. if (ret)
  8852. break;
  8853. /*
  8854. * We've reserved this space, and thus converted it from
  8855. * ->bytes_may_use to ->bytes_reserved. Any error that happens
  8856. * from here on out we will only need to clear our reservation
  8857. * for the remaining unreserved area, so advance our
  8858. * clear_offset by our extent size.
  8859. */
  8860. clear_offset += ins.offset;
  8861. last_alloc = ins.offset;
  8862. trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
  8863. &ins, cur_offset);
  8864. /*
  8865. * Now that we inserted the prealloc extent we can finally
  8866. * decrement the number of reservations in the block group.
  8867. * If we did it before, we could race with relocation and have
  8868. * relocation miss the reserved extent, making it fail later.
  8869. */
  8870. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  8871. if (IS_ERR(trans)) {
  8872. ret = PTR_ERR(trans);
  8873. btrfs_free_reserved_extent(fs_info, ins.objectid,
  8874. ins.offset, 0);
  8875. break;
  8876. }
  8877. em = alloc_extent_map();
  8878. if (!em) {
  8879. btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
  8880. cur_offset + ins.offset - 1, false);
  8881. btrfs_set_inode_full_sync(BTRFS_I(inode));
  8882. goto next;
  8883. }
  8884. em->start = cur_offset;
  8885. em->orig_start = cur_offset;
  8886. em->len = ins.offset;
  8887. em->block_start = ins.objectid;
  8888. em->block_len = ins.offset;
  8889. em->orig_block_len = ins.offset;
  8890. em->ram_bytes = ins.offset;
  8891. set_bit(EXTENT_FLAG_PREALLOC, &em->flags);
  8892. em->generation = trans->transid;
  8893. ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
  8894. free_extent_map(em);
  8895. next:
  8896. num_bytes -= ins.offset;
  8897. cur_offset += ins.offset;
  8898. *alloc_hint = ins.objectid + ins.offset;
  8899. inode_inc_iversion(inode);
  8900. inode->i_ctime = current_time(inode);
  8901. BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
  8902. if (!(mode & FALLOC_FL_KEEP_SIZE) &&
  8903. (actual_len > inode->i_size) &&
  8904. (cur_offset > inode->i_size)) {
  8905. if (cur_offset > actual_len)
  8906. i_size = actual_len;
  8907. else
  8908. i_size = cur_offset;
  8909. i_size_write(inode, i_size);
  8910. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
  8911. }
  8912. ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
  8913. if (ret) {
  8914. btrfs_abort_transaction(trans, ret);
  8915. if (own_trans)
  8916. btrfs_end_transaction(trans);
  8917. break;
  8918. }
  8919. if (own_trans) {
  8920. btrfs_end_transaction(trans);
  8921. trans = NULL;
  8922. }
  8923. }
  8924. if (clear_offset < end)
  8925. btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
  8926. end - clear_offset + 1);
  8927. return ret;
  8928. }
  8929. int btrfs_prealloc_file_range(struct inode *inode, int mode,
  8930. u64 start, u64 num_bytes, u64 min_size,
  8931. loff_t actual_len, u64 *alloc_hint)
  8932. {
  8933. return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
  8934. min_size, actual_len, alloc_hint,
  8935. NULL);
  8936. }
  8937. int btrfs_prealloc_file_range_trans(struct inode *inode,
  8938. struct btrfs_trans_handle *trans, int mode,
  8939. u64 start, u64 num_bytes, u64 min_size,
  8940. loff_t actual_len, u64 *alloc_hint)
  8941. {
  8942. return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
  8943. min_size, actual_len, alloc_hint, trans);
  8944. }
  8945. static int btrfs_permission(struct user_namespace *mnt_userns,
  8946. struct inode *inode, int mask)
  8947. {
  8948. struct btrfs_root *root = BTRFS_I(inode)->root;
  8949. umode_t mode = inode->i_mode;
  8950. if (mask & MAY_WRITE &&
  8951. (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
  8952. if (btrfs_root_readonly(root))
  8953. return -EROFS;
  8954. if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
  8955. return -EACCES;
  8956. }
  8957. return generic_permission(mnt_userns, inode, mask);
  8958. }
  8959. static int btrfs_tmpfile(struct user_namespace *mnt_userns, struct inode *dir,
  8960. struct file *file, umode_t mode)
  8961. {
  8962. struct btrfs_fs_info *fs_info = btrfs_sb(dir->i_sb);
  8963. struct btrfs_trans_handle *trans;
  8964. struct btrfs_root *root = BTRFS_I(dir)->root;
  8965. struct inode *inode;
  8966. struct btrfs_new_inode_args new_inode_args = {
  8967. .dir = dir,
  8968. .dentry = file->f_path.dentry,
  8969. .orphan = true,
  8970. };
  8971. unsigned int trans_num_items;
  8972. int ret;
  8973. inode = new_inode(dir->i_sb);
  8974. if (!inode)
  8975. return -ENOMEM;
  8976. inode_init_owner(mnt_userns, inode, dir, mode);
  8977. inode->i_fop = &btrfs_file_operations;
  8978. inode->i_op = &btrfs_file_inode_operations;
  8979. inode->i_mapping->a_ops = &btrfs_aops;
  8980. new_inode_args.inode = inode;
  8981. ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
  8982. if (ret)
  8983. goto out_inode;
  8984. trans = btrfs_start_transaction(root, trans_num_items);
  8985. if (IS_ERR(trans)) {
  8986. ret = PTR_ERR(trans);
  8987. goto out_new_inode_args;
  8988. }
  8989. ret = btrfs_create_new_inode(trans, &new_inode_args);
  8990. /*
  8991. * We set number of links to 0 in btrfs_create_new_inode(), and here we
  8992. * set it to 1 because d_tmpfile() will issue a warning if the count is
  8993. * 0, through:
  8994. *
  8995. * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
  8996. */
  8997. set_nlink(inode, 1);
  8998. if (!ret) {
  8999. d_tmpfile(file, inode);
  9000. unlock_new_inode(inode);
  9001. mark_inode_dirty(inode);
  9002. }
  9003. btrfs_end_transaction(trans);
  9004. btrfs_btree_balance_dirty(fs_info);
  9005. out_new_inode_args:
  9006. btrfs_new_inode_args_destroy(&new_inode_args);
  9007. out_inode:
  9008. if (ret)
  9009. iput(inode);
  9010. return finish_open_simple(file, ret);
  9011. }
  9012. void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
  9013. {
  9014. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  9015. unsigned long index = start >> PAGE_SHIFT;
  9016. unsigned long end_index = end >> PAGE_SHIFT;
  9017. struct page *page;
  9018. u32 len;
  9019. ASSERT(end + 1 - start <= U32_MAX);
  9020. len = end + 1 - start;
  9021. while (index <= end_index) {
  9022. page = find_get_page(inode->vfs_inode.i_mapping, index);
  9023. ASSERT(page); /* Pages should be in the extent_io_tree */
  9024. btrfs_page_set_writeback(fs_info, page, start, len);
  9025. put_page(page);
  9026. index++;
  9027. }
  9028. }
  9029. int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
  9030. int compress_type)
  9031. {
  9032. switch (compress_type) {
  9033. case BTRFS_COMPRESS_NONE:
  9034. return BTRFS_ENCODED_IO_COMPRESSION_NONE;
  9035. case BTRFS_COMPRESS_ZLIB:
  9036. return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
  9037. case BTRFS_COMPRESS_LZO:
  9038. /*
  9039. * The LZO format depends on the sector size. 64K is the maximum
  9040. * sector size that we support.
  9041. */
  9042. if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
  9043. return -EINVAL;
  9044. return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
  9045. (fs_info->sectorsize_bits - 12);
  9046. case BTRFS_COMPRESS_ZSTD:
  9047. return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
  9048. default:
  9049. return -EUCLEAN;
  9050. }
  9051. }
  9052. static ssize_t btrfs_encoded_read_inline(
  9053. struct kiocb *iocb,
  9054. struct iov_iter *iter, u64 start,
  9055. u64 lockend,
  9056. struct extent_state **cached_state,
  9057. u64 extent_start, size_t count,
  9058. struct btrfs_ioctl_encoded_io_args *encoded,
  9059. bool *unlocked)
  9060. {
  9061. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  9062. struct btrfs_root *root = inode->root;
  9063. struct btrfs_fs_info *fs_info = root->fs_info;
  9064. struct extent_io_tree *io_tree = &inode->io_tree;
  9065. struct btrfs_path *path;
  9066. struct extent_buffer *leaf;
  9067. struct btrfs_file_extent_item *item;
  9068. u64 ram_bytes;
  9069. unsigned long ptr;
  9070. void *tmp;
  9071. ssize_t ret;
  9072. path = btrfs_alloc_path();
  9073. if (!path) {
  9074. ret = -ENOMEM;
  9075. goto out;
  9076. }
  9077. ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
  9078. extent_start, 0);
  9079. if (ret) {
  9080. if (ret > 0) {
  9081. /* The extent item disappeared? */
  9082. ret = -EIO;
  9083. }
  9084. goto out;
  9085. }
  9086. leaf = path->nodes[0];
  9087. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
  9088. ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
  9089. ptr = btrfs_file_extent_inline_start(item);
  9090. encoded->len = min_t(u64, extent_start + ram_bytes,
  9091. inode->vfs_inode.i_size) - iocb->ki_pos;
  9092. ret = btrfs_encoded_io_compression_from_extent(fs_info,
  9093. btrfs_file_extent_compression(leaf, item));
  9094. if (ret < 0)
  9095. goto out;
  9096. encoded->compression = ret;
  9097. if (encoded->compression) {
  9098. size_t inline_size;
  9099. inline_size = btrfs_file_extent_inline_item_len(leaf,
  9100. path->slots[0]);
  9101. if (inline_size > count) {
  9102. ret = -ENOBUFS;
  9103. goto out;
  9104. }
  9105. count = inline_size;
  9106. encoded->unencoded_len = ram_bytes;
  9107. encoded->unencoded_offset = iocb->ki_pos - extent_start;
  9108. } else {
  9109. count = min_t(u64, count, encoded->len);
  9110. encoded->len = count;
  9111. encoded->unencoded_len = count;
  9112. ptr += iocb->ki_pos - extent_start;
  9113. }
  9114. tmp = kmalloc(count, GFP_NOFS);
  9115. if (!tmp) {
  9116. ret = -ENOMEM;
  9117. goto out;
  9118. }
  9119. read_extent_buffer(leaf, tmp, ptr, count);
  9120. btrfs_release_path(path);
  9121. unlock_extent(io_tree, start, lockend, cached_state);
  9122. btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
  9123. *unlocked = true;
  9124. ret = copy_to_iter(tmp, count, iter);
  9125. if (ret != count)
  9126. ret = -EFAULT;
  9127. kfree(tmp);
  9128. out:
  9129. btrfs_free_path(path);
  9130. return ret;
  9131. }
  9132. struct btrfs_encoded_read_private {
  9133. struct btrfs_inode *inode;
  9134. u64 file_offset;
  9135. wait_queue_head_t wait;
  9136. atomic_t pending;
  9137. blk_status_t status;
  9138. bool skip_csum;
  9139. };
  9140. static blk_status_t submit_encoded_read_bio(struct btrfs_inode *inode,
  9141. struct bio *bio, int mirror_num)
  9142. {
  9143. struct btrfs_encoded_read_private *priv = btrfs_bio(bio)->private;
  9144. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  9145. blk_status_t ret;
  9146. if (!priv->skip_csum) {
  9147. ret = btrfs_lookup_bio_sums(&inode->vfs_inode, bio, NULL);
  9148. if (ret)
  9149. return ret;
  9150. }
  9151. atomic_inc(&priv->pending);
  9152. btrfs_submit_bio(fs_info, bio, mirror_num);
  9153. return BLK_STS_OK;
  9154. }
  9155. static blk_status_t btrfs_encoded_read_verify_csum(struct btrfs_bio *bbio)
  9156. {
  9157. const bool uptodate = (bbio->bio.bi_status == BLK_STS_OK);
  9158. struct btrfs_encoded_read_private *priv = bbio->private;
  9159. struct btrfs_inode *inode = priv->inode;
  9160. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  9161. u32 sectorsize = fs_info->sectorsize;
  9162. struct bio_vec *bvec;
  9163. struct bvec_iter_all iter_all;
  9164. u32 bio_offset = 0;
  9165. if (priv->skip_csum || !uptodate)
  9166. return bbio->bio.bi_status;
  9167. bio_for_each_segment_all(bvec, &bbio->bio, iter_all) {
  9168. unsigned int i, nr_sectors, pgoff;
  9169. nr_sectors = BTRFS_BYTES_TO_BLKS(fs_info, bvec->bv_len);
  9170. pgoff = bvec->bv_offset;
  9171. for (i = 0; i < nr_sectors; i++) {
  9172. ASSERT(pgoff < PAGE_SIZE);
  9173. if (btrfs_check_data_csum(&inode->vfs_inode, bbio, bio_offset,
  9174. bvec->bv_page, pgoff))
  9175. return BLK_STS_IOERR;
  9176. bio_offset += sectorsize;
  9177. pgoff += sectorsize;
  9178. }
  9179. }
  9180. return BLK_STS_OK;
  9181. }
  9182. static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
  9183. {
  9184. struct btrfs_encoded_read_private *priv = bbio->private;
  9185. blk_status_t status;
  9186. status = btrfs_encoded_read_verify_csum(bbio);
  9187. if (status) {
  9188. /*
  9189. * The memory barrier implied by the atomic_dec_return() here
  9190. * pairs with the memory barrier implied by the
  9191. * atomic_dec_return() or io_wait_event() in
  9192. * btrfs_encoded_read_regular_fill_pages() to ensure that this
  9193. * write is observed before the load of status in
  9194. * btrfs_encoded_read_regular_fill_pages().
  9195. */
  9196. WRITE_ONCE(priv->status, status);
  9197. }
  9198. if (!atomic_dec_return(&priv->pending))
  9199. wake_up(&priv->wait);
  9200. btrfs_bio_free_csum(bbio);
  9201. bio_put(&bbio->bio);
  9202. }
  9203. int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
  9204. u64 file_offset, u64 disk_bytenr,
  9205. u64 disk_io_size, struct page **pages)
  9206. {
  9207. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  9208. struct btrfs_encoded_read_private priv = {
  9209. .inode = inode,
  9210. .file_offset = file_offset,
  9211. .pending = ATOMIC_INIT(1),
  9212. .skip_csum = (inode->flags & BTRFS_INODE_NODATASUM),
  9213. };
  9214. unsigned long i = 0;
  9215. u64 cur = 0;
  9216. int ret;
  9217. init_waitqueue_head(&priv.wait);
  9218. /*
  9219. * Submit bios for the extent, splitting due to bio or stripe limits as
  9220. * necessary.
  9221. */
  9222. while (cur < disk_io_size) {
  9223. struct extent_map *em;
  9224. struct btrfs_io_geometry geom;
  9225. struct bio *bio = NULL;
  9226. u64 remaining;
  9227. em = btrfs_get_chunk_map(fs_info, disk_bytenr + cur,
  9228. disk_io_size - cur);
  9229. if (IS_ERR(em)) {
  9230. ret = PTR_ERR(em);
  9231. } else {
  9232. ret = btrfs_get_io_geometry(fs_info, em, BTRFS_MAP_READ,
  9233. disk_bytenr + cur, &geom);
  9234. free_extent_map(em);
  9235. }
  9236. if (ret) {
  9237. WRITE_ONCE(priv.status, errno_to_blk_status(ret));
  9238. break;
  9239. }
  9240. remaining = min(geom.len, disk_io_size - cur);
  9241. while (bio || remaining) {
  9242. size_t bytes = min_t(u64, remaining, PAGE_SIZE);
  9243. if (!bio) {
  9244. bio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ,
  9245. btrfs_encoded_read_endio,
  9246. &priv);
  9247. bio->bi_iter.bi_sector =
  9248. (disk_bytenr + cur) >> SECTOR_SHIFT;
  9249. }
  9250. if (!bytes ||
  9251. bio_add_page(bio, pages[i], bytes, 0) < bytes) {
  9252. blk_status_t status;
  9253. status = submit_encoded_read_bio(inode, bio, 0);
  9254. if (status) {
  9255. WRITE_ONCE(priv.status, status);
  9256. bio_put(bio);
  9257. goto out;
  9258. }
  9259. bio = NULL;
  9260. continue;
  9261. }
  9262. i++;
  9263. cur += bytes;
  9264. remaining -= bytes;
  9265. }
  9266. }
  9267. out:
  9268. if (atomic_dec_return(&priv.pending))
  9269. io_wait_event(priv.wait, !atomic_read(&priv.pending));
  9270. /* See btrfs_encoded_read_endio() for ordering. */
  9271. return blk_status_to_errno(READ_ONCE(priv.status));
  9272. }
  9273. static ssize_t btrfs_encoded_read_regular(struct kiocb *iocb,
  9274. struct iov_iter *iter,
  9275. u64 start, u64 lockend,
  9276. struct extent_state **cached_state,
  9277. u64 disk_bytenr, u64 disk_io_size,
  9278. size_t count, bool compressed,
  9279. bool *unlocked)
  9280. {
  9281. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  9282. struct extent_io_tree *io_tree = &inode->io_tree;
  9283. struct page **pages;
  9284. unsigned long nr_pages, i;
  9285. u64 cur;
  9286. size_t page_offset;
  9287. ssize_t ret;
  9288. nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
  9289. pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
  9290. if (!pages)
  9291. return -ENOMEM;
  9292. ret = btrfs_alloc_page_array(nr_pages, pages);
  9293. if (ret) {
  9294. ret = -ENOMEM;
  9295. goto out;
  9296. }
  9297. ret = btrfs_encoded_read_regular_fill_pages(inode, start, disk_bytenr,
  9298. disk_io_size, pages);
  9299. if (ret)
  9300. goto out;
  9301. unlock_extent(io_tree, start, lockend, cached_state);
  9302. btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
  9303. *unlocked = true;
  9304. if (compressed) {
  9305. i = 0;
  9306. page_offset = 0;
  9307. } else {
  9308. i = (iocb->ki_pos - start) >> PAGE_SHIFT;
  9309. page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
  9310. }
  9311. cur = 0;
  9312. while (cur < count) {
  9313. size_t bytes = min_t(size_t, count - cur,
  9314. PAGE_SIZE - page_offset);
  9315. if (copy_page_to_iter(pages[i], page_offset, bytes,
  9316. iter) != bytes) {
  9317. ret = -EFAULT;
  9318. goto out;
  9319. }
  9320. i++;
  9321. cur += bytes;
  9322. page_offset = 0;
  9323. }
  9324. ret = count;
  9325. out:
  9326. for (i = 0; i < nr_pages; i++) {
  9327. if (pages[i])
  9328. __free_page(pages[i]);
  9329. }
  9330. kfree(pages);
  9331. return ret;
  9332. }
  9333. ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
  9334. struct btrfs_ioctl_encoded_io_args *encoded)
  9335. {
  9336. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  9337. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  9338. struct extent_io_tree *io_tree = &inode->io_tree;
  9339. ssize_t ret;
  9340. size_t count = iov_iter_count(iter);
  9341. u64 start, lockend, disk_bytenr, disk_io_size;
  9342. struct extent_state *cached_state = NULL;
  9343. struct extent_map *em;
  9344. bool unlocked = false;
  9345. file_accessed(iocb->ki_filp);
  9346. btrfs_inode_lock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
  9347. if (iocb->ki_pos >= inode->vfs_inode.i_size) {
  9348. btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
  9349. return 0;
  9350. }
  9351. start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
  9352. /*
  9353. * We don't know how long the extent containing iocb->ki_pos is, but if
  9354. * it's compressed we know that it won't be longer than this.
  9355. */
  9356. lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
  9357. for (;;) {
  9358. struct btrfs_ordered_extent *ordered;
  9359. ret = btrfs_wait_ordered_range(&inode->vfs_inode, start,
  9360. lockend - start + 1);
  9361. if (ret)
  9362. goto out_unlock_inode;
  9363. lock_extent(io_tree, start, lockend, &cached_state);
  9364. ordered = btrfs_lookup_ordered_range(inode, start,
  9365. lockend - start + 1);
  9366. if (!ordered)
  9367. break;
  9368. btrfs_put_ordered_extent(ordered);
  9369. unlock_extent(io_tree, start, lockend, &cached_state);
  9370. cond_resched();
  9371. }
  9372. em = btrfs_get_extent(inode, NULL, 0, start, lockend - start + 1);
  9373. if (IS_ERR(em)) {
  9374. ret = PTR_ERR(em);
  9375. goto out_unlock_extent;
  9376. }
  9377. if (em->block_start == EXTENT_MAP_INLINE) {
  9378. u64 extent_start = em->start;
  9379. /*
  9380. * For inline extents we get everything we need out of the
  9381. * extent item.
  9382. */
  9383. free_extent_map(em);
  9384. em = NULL;
  9385. ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
  9386. &cached_state, extent_start,
  9387. count, encoded, &unlocked);
  9388. goto out;
  9389. }
  9390. /*
  9391. * We only want to return up to EOF even if the extent extends beyond
  9392. * that.
  9393. */
  9394. encoded->len = min_t(u64, extent_map_end(em),
  9395. inode->vfs_inode.i_size) - iocb->ki_pos;
  9396. if (em->block_start == EXTENT_MAP_HOLE ||
  9397. test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
  9398. disk_bytenr = EXTENT_MAP_HOLE;
  9399. count = min_t(u64, count, encoded->len);
  9400. encoded->len = count;
  9401. encoded->unencoded_len = count;
  9402. } else if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
  9403. disk_bytenr = em->block_start;
  9404. /*
  9405. * Bail if the buffer isn't large enough to return the whole
  9406. * compressed extent.
  9407. */
  9408. if (em->block_len > count) {
  9409. ret = -ENOBUFS;
  9410. goto out_em;
  9411. }
  9412. disk_io_size = em->block_len;
  9413. count = em->block_len;
  9414. encoded->unencoded_len = em->ram_bytes;
  9415. encoded->unencoded_offset = iocb->ki_pos - em->orig_start;
  9416. ret = btrfs_encoded_io_compression_from_extent(fs_info,
  9417. em->compress_type);
  9418. if (ret < 0)
  9419. goto out_em;
  9420. encoded->compression = ret;
  9421. } else {
  9422. disk_bytenr = em->block_start + (start - em->start);
  9423. if (encoded->len > count)
  9424. encoded->len = count;
  9425. /*
  9426. * Don't read beyond what we locked. This also limits the page
  9427. * allocations that we'll do.
  9428. */
  9429. disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
  9430. count = start + disk_io_size - iocb->ki_pos;
  9431. encoded->len = count;
  9432. encoded->unencoded_len = count;
  9433. disk_io_size = ALIGN(disk_io_size, fs_info->sectorsize);
  9434. }
  9435. free_extent_map(em);
  9436. em = NULL;
  9437. if (disk_bytenr == EXTENT_MAP_HOLE) {
  9438. unlock_extent(io_tree, start, lockend, &cached_state);
  9439. btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
  9440. unlocked = true;
  9441. ret = iov_iter_zero(count, iter);
  9442. if (ret != count)
  9443. ret = -EFAULT;
  9444. } else {
  9445. ret = btrfs_encoded_read_regular(iocb, iter, start, lockend,
  9446. &cached_state, disk_bytenr,
  9447. disk_io_size, count,
  9448. encoded->compression,
  9449. &unlocked);
  9450. }
  9451. out:
  9452. if (ret >= 0)
  9453. iocb->ki_pos += encoded->len;
  9454. out_em:
  9455. free_extent_map(em);
  9456. out_unlock_extent:
  9457. if (!unlocked)
  9458. unlock_extent(io_tree, start, lockend, &cached_state);
  9459. out_unlock_inode:
  9460. if (!unlocked)
  9461. btrfs_inode_unlock(&inode->vfs_inode, BTRFS_ILOCK_SHARED);
  9462. return ret;
  9463. }
  9464. ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
  9465. const struct btrfs_ioctl_encoded_io_args *encoded)
  9466. {
  9467. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  9468. struct btrfs_root *root = inode->root;
  9469. struct btrfs_fs_info *fs_info = root->fs_info;
  9470. struct extent_io_tree *io_tree = &inode->io_tree;
  9471. struct extent_changeset *data_reserved = NULL;
  9472. struct extent_state *cached_state = NULL;
  9473. int compression;
  9474. size_t orig_count;
  9475. u64 start, end;
  9476. u64 num_bytes, ram_bytes, disk_num_bytes;
  9477. unsigned long nr_pages, i;
  9478. struct page **pages;
  9479. struct btrfs_key ins;
  9480. bool extent_reserved = false;
  9481. struct extent_map *em;
  9482. ssize_t ret;
  9483. switch (encoded->compression) {
  9484. case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
  9485. compression = BTRFS_COMPRESS_ZLIB;
  9486. break;
  9487. case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
  9488. compression = BTRFS_COMPRESS_ZSTD;
  9489. break;
  9490. case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
  9491. case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
  9492. case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
  9493. case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
  9494. case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
  9495. /* The sector size must match for LZO. */
  9496. if (encoded->compression -
  9497. BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
  9498. fs_info->sectorsize_bits)
  9499. return -EINVAL;
  9500. compression = BTRFS_COMPRESS_LZO;
  9501. break;
  9502. default:
  9503. return -EINVAL;
  9504. }
  9505. if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
  9506. return -EINVAL;
  9507. orig_count = iov_iter_count(from);
  9508. /* The extent size must be sane. */
  9509. if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
  9510. orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
  9511. return -EINVAL;
  9512. /*
  9513. * The compressed data must be smaller than the decompressed data.
  9514. *
  9515. * It's of course possible for data to compress to larger or the same
  9516. * size, but the buffered I/O path falls back to no compression for such
  9517. * data, and we don't want to break any assumptions by creating these
  9518. * extents.
  9519. *
  9520. * Note that this is less strict than the current check we have that the
  9521. * compressed data must be at least one sector smaller than the
  9522. * decompressed data. We only want to enforce the weaker requirement
  9523. * from old kernels that it is at least one byte smaller.
  9524. */
  9525. if (orig_count >= encoded->unencoded_len)
  9526. return -EINVAL;
  9527. /* The extent must start on a sector boundary. */
  9528. start = iocb->ki_pos;
  9529. if (!IS_ALIGNED(start, fs_info->sectorsize))
  9530. return -EINVAL;
  9531. /*
  9532. * The extent must end on a sector boundary. However, we allow a write
  9533. * which ends at or extends i_size to have an unaligned length; we round
  9534. * up the extent size and set i_size to the unaligned end.
  9535. */
  9536. if (start + encoded->len < inode->vfs_inode.i_size &&
  9537. !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
  9538. return -EINVAL;
  9539. /* Finally, the offset in the unencoded data must be sector-aligned. */
  9540. if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
  9541. return -EINVAL;
  9542. num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
  9543. ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
  9544. end = start + num_bytes - 1;
  9545. /*
  9546. * If the extent cannot be inline, the compressed data on disk must be
  9547. * sector-aligned. For convenience, we extend it with zeroes if it
  9548. * isn't.
  9549. */
  9550. disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
  9551. nr_pages = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
  9552. pages = kvcalloc(nr_pages, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
  9553. if (!pages)
  9554. return -ENOMEM;
  9555. for (i = 0; i < nr_pages; i++) {
  9556. size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
  9557. char *kaddr;
  9558. pages[i] = alloc_page(GFP_KERNEL_ACCOUNT);
  9559. if (!pages[i]) {
  9560. ret = -ENOMEM;
  9561. goto out_pages;
  9562. }
  9563. kaddr = kmap_local_page(pages[i]);
  9564. if (copy_from_iter(kaddr, bytes, from) != bytes) {
  9565. kunmap_local(kaddr);
  9566. ret = -EFAULT;
  9567. goto out_pages;
  9568. }
  9569. if (bytes < PAGE_SIZE)
  9570. memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
  9571. kunmap_local(kaddr);
  9572. }
  9573. for (;;) {
  9574. struct btrfs_ordered_extent *ordered;
  9575. ret = btrfs_wait_ordered_range(&inode->vfs_inode, start, num_bytes);
  9576. if (ret)
  9577. goto out_pages;
  9578. ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
  9579. start >> PAGE_SHIFT,
  9580. end >> PAGE_SHIFT);
  9581. if (ret)
  9582. goto out_pages;
  9583. lock_extent(io_tree, start, end, &cached_state);
  9584. ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
  9585. if (!ordered &&
  9586. !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
  9587. break;
  9588. if (ordered)
  9589. btrfs_put_ordered_extent(ordered);
  9590. unlock_extent(io_tree, start, end, &cached_state);
  9591. cond_resched();
  9592. }
  9593. /*
  9594. * We don't use the higher-level delalloc space functions because our
  9595. * num_bytes and disk_num_bytes are different.
  9596. */
  9597. ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
  9598. if (ret)
  9599. goto out_unlock;
  9600. ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
  9601. if (ret)
  9602. goto out_free_data_space;
  9603. ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
  9604. false);
  9605. if (ret)
  9606. goto out_qgroup_free_data;
  9607. /* Try an inline extent first. */
  9608. if (start == 0 && encoded->unencoded_len == encoded->len &&
  9609. encoded->unencoded_offset == 0) {
  9610. ret = cow_file_range_inline(inode, encoded->len, orig_count,
  9611. compression, pages, true);
  9612. if (ret <= 0) {
  9613. if (ret == 0)
  9614. ret = orig_count;
  9615. goto out_delalloc_release;
  9616. }
  9617. }
  9618. ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
  9619. disk_num_bytes, 0, 0, &ins, 1, 1);
  9620. if (ret)
  9621. goto out_delalloc_release;
  9622. extent_reserved = true;
  9623. em = create_io_em(inode, start, num_bytes,
  9624. start - encoded->unencoded_offset, ins.objectid,
  9625. ins.offset, ins.offset, ram_bytes, compression,
  9626. BTRFS_ORDERED_COMPRESSED);
  9627. if (IS_ERR(em)) {
  9628. ret = PTR_ERR(em);
  9629. goto out_free_reserved;
  9630. }
  9631. free_extent_map(em);
  9632. ret = btrfs_add_ordered_extent(inode, start, num_bytes, ram_bytes,
  9633. ins.objectid, ins.offset,
  9634. encoded->unencoded_offset,
  9635. (1 << BTRFS_ORDERED_ENCODED) |
  9636. (1 << BTRFS_ORDERED_COMPRESSED),
  9637. compression);
  9638. if (ret) {
  9639. btrfs_drop_extent_map_range(inode, start, end, false);
  9640. goto out_free_reserved;
  9641. }
  9642. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  9643. if (start + encoded->len > inode->vfs_inode.i_size)
  9644. i_size_write(&inode->vfs_inode, start + encoded->len);
  9645. unlock_extent(io_tree, start, end, &cached_state);
  9646. btrfs_delalloc_release_extents(inode, num_bytes);
  9647. if (btrfs_submit_compressed_write(inode, start, num_bytes, ins.objectid,
  9648. ins.offset, pages, nr_pages, 0, NULL,
  9649. false)) {
  9650. btrfs_writepage_endio_finish_ordered(inode, pages[0], start, end, 0);
  9651. ret = -EIO;
  9652. goto out_pages;
  9653. }
  9654. ret = orig_count;
  9655. goto out;
  9656. out_free_reserved:
  9657. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  9658. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  9659. out_delalloc_release:
  9660. btrfs_delalloc_release_extents(inode, num_bytes);
  9661. btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
  9662. out_qgroup_free_data:
  9663. if (ret < 0)
  9664. btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes);
  9665. out_free_data_space:
  9666. /*
  9667. * If btrfs_reserve_extent() succeeded, then we already decremented
  9668. * bytes_may_use.
  9669. */
  9670. if (!extent_reserved)
  9671. btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
  9672. out_unlock:
  9673. unlock_extent(io_tree, start, end, &cached_state);
  9674. out_pages:
  9675. for (i = 0; i < nr_pages; i++) {
  9676. if (pages[i])
  9677. __free_page(pages[i]);
  9678. }
  9679. kvfree(pages);
  9680. out:
  9681. if (ret >= 0)
  9682. iocb->ki_pos += encoded->len;
  9683. return ret;
  9684. }
  9685. #ifdef CONFIG_SWAP
  9686. /*
  9687. * Add an entry indicating a block group or device which is pinned by a
  9688. * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
  9689. * negative errno on failure.
  9690. */
  9691. static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
  9692. bool is_block_group)
  9693. {
  9694. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  9695. struct btrfs_swapfile_pin *sp, *entry;
  9696. struct rb_node **p;
  9697. struct rb_node *parent = NULL;
  9698. sp = kmalloc(sizeof(*sp), GFP_NOFS);
  9699. if (!sp)
  9700. return -ENOMEM;
  9701. sp->ptr = ptr;
  9702. sp->inode = inode;
  9703. sp->is_block_group = is_block_group;
  9704. sp->bg_extent_count = 1;
  9705. spin_lock(&fs_info->swapfile_pins_lock);
  9706. p = &fs_info->swapfile_pins.rb_node;
  9707. while (*p) {
  9708. parent = *p;
  9709. entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
  9710. if (sp->ptr < entry->ptr ||
  9711. (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
  9712. p = &(*p)->rb_left;
  9713. } else if (sp->ptr > entry->ptr ||
  9714. (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
  9715. p = &(*p)->rb_right;
  9716. } else {
  9717. if (is_block_group)
  9718. entry->bg_extent_count++;
  9719. spin_unlock(&fs_info->swapfile_pins_lock);
  9720. kfree(sp);
  9721. return 1;
  9722. }
  9723. }
  9724. rb_link_node(&sp->node, parent, p);
  9725. rb_insert_color(&sp->node, &fs_info->swapfile_pins);
  9726. spin_unlock(&fs_info->swapfile_pins_lock);
  9727. return 0;
  9728. }
  9729. /* Free all of the entries pinned by this swapfile. */
  9730. static void btrfs_free_swapfile_pins(struct inode *inode)
  9731. {
  9732. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  9733. struct btrfs_swapfile_pin *sp;
  9734. struct rb_node *node, *next;
  9735. spin_lock(&fs_info->swapfile_pins_lock);
  9736. node = rb_first(&fs_info->swapfile_pins);
  9737. while (node) {
  9738. next = rb_next(node);
  9739. sp = rb_entry(node, struct btrfs_swapfile_pin, node);
  9740. if (sp->inode == inode) {
  9741. rb_erase(&sp->node, &fs_info->swapfile_pins);
  9742. if (sp->is_block_group) {
  9743. btrfs_dec_block_group_swap_extents(sp->ptr,
  9744. sp->bg_extent_count);
  9745. btrfs_put_block_group(sp->ptr);
  9746. }
  9747. kfree(sp);
  9748. }
  9749. node = next;
  9750. }
  9751. spin_unlock(&fs_info->swapfile_pins_lock);
  9752. }
  9753. struct btrfs_swap_info {
  9754. u64 start;
  9755. u64 block_start;
  9756. u64 block_len;
  9757. u64 lowest_ppage;
  9758. u64 highest_ppage;
  9759. unsigned long nr_pages;
  9760. int nr_extents;
  9761. };
  9762. static int btrfs_add_swap_extent(struct swap_info_struct *sis,
  9763. struct btrfs_swap_info *bsi)
  9764. {
  9765. unsigned long nr_pages;
  9766. unsigned long max_pages;
  9767. u64 first_ppage, first_ppage_reported, next_ppage;
  9768. int ret;
  9769. /*
  9770. * Our swapfile may have had its size extended after the swap header was
  9771. * written. In that case activating the swapfile should not go beyond
  9772. * the max size set in the swap header.
  9773. */
  9774. if (bsi->nr_pages >= sis->max)
  9775. return 0;
  9776. max_pages = sis->max - bsi->nr_pages;
  9777. first_ppage = ALIGN(bsi->block_start, PAGE_SIZE) >> PAGE_SHIFT;
  9778. next_ppage = ALIGN_DOWN(bsi->block_start + bsi->block_len,
  9779. PAGE_SIZE) >> PAGE_SHIFT;
  9780. if (first_ppage >= next_ppage)
  9781. return 0;
  9782. nr_pages = next_ppage - first_ppage;
  9783. nr_pages = min(nr_pages, max_pages);
  9784. first_ppage_reported = first_ppage;
  9785. if (bsi->start == 0)
  9786. first_ppage_reported++;
  9787. if (bsi->lowest_ppage > first_ppage_reported)
  9788. bsi->lowest_ppage = first_ppage_reported;
  9789. if (bsi->highest_ppage < (next_ppage - 1))
  9790. bsi->highest_ppage = next_ppage - 1;
  9791. ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
  9792. if (ret < 0)
  9793. return ret;
  9794. bsi->nr_extents += ret;
  9795. bsi->nr_pages += nr_pages;
  9796. return 0;
  9797. }
  9798. static void btrfs_swap_deactivate(struct file *file)
  9799. {
  9800. struct inode *inode = file_inode(file);
  9801. btrfs_free_swapfile_pins(inode);
  9802. atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
  9803. }
  9804. static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
  9805. sector_t *span)
  9806. {
  9807. struct inode *inode = file_inode(file);
  9808. struct btrfs_root *root = BTRFS_I(inode)->root;
  9809. struct btrfs_fs_info *fs_info = root->fs_info;
  9810. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  9811. struct extent_state *cached_state = NULL;
  9812. struct extent_map *em = NULL;
  9813. struct btrfs_device *device = NULL;
  9814. struct btrfs_swap_info bsi = {
  9815. .lowest_ppage = (sector_t)-1ULL,
  9816. };
  9817. int ret = 0;
  9818. u64 isize;
  9819. u64 start;
  9820. /*
  9821. * If the swap file was just created, make sure delalloc is done. If the
  9822. * file changes again after this, the user is doing something stupid and
  9823. * we don't really care.
  9824. */
  9825. ret = btrfs_wait_ordered_range(inode, 0, (u64)-1);
  9826. if (ret)
  9827. return ret;
  9828. /*
  9829. * The inode is locked, so these flags won't change after we check them.
  9830. */
  9831. if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
  9832. btrfs_warn(fs_info, "swapfile must not be compressed");
  9833. return -EINVAL;
  9834. }
  9835. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
  9836. btrfs_warn(fs_info, "swapfile must not be copy-on-write");
  9837. return -EINVAL;
  9838. }
  9839. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
  9840. btrfs_warn(fs_info, "swapfile must not be checksummed");
  9841. return -EINVAL;
  9842. }
  9843. /*
  9844. * Balance or device remove/replace/resize can move stuff around from
  9845. * under us. The exclop protection makes sure they aren't running/won't
  9846. * run concurrently while we are mapping the swap extents, and
  9847. * fs_info->swapfile_pins prevents them from running while the swap
  9848. * file is active and moving the extents. Note that this also prevents
  9849. * a concurrent device add which isn't actually necessary, but it's not
  9850. * really worth the trouble to allow it.
  9851. */
  9852. if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
  9853. btrfs_warn(fs_info,
  9854. "cannot activate swapfile while exclusive operation is running");
  9855. return -EBUSY;
  9856. }
  9857. /*
  9858. * Prevent snapshot creation while we are activating the swap file.
  9859. * We do not want to race with snapshot creation. If snapshot creation
  9860. * already started before we bumped nr_swapfiles from 0 to 1 and
  9861. * completes before the first write into the swap file after it is
  9862. * activated, than that write would fallback to COW.
  9863. */
  9864. if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
  9865. btrfs_exclop_finish(fs_info);
  9866. btrfs_warn(fs_info,
  9867. "cannot activate swapfile because snapshot creation is in progress");
  9868. return -EINVAL;
  9869. }
  9870. /*
  9871. * Snapshots can create extents which require COW even if NODATACOW is
  9872. * set. We use this counter to prevent snapshots. We must increment it
  9873. * before walking the extents because we don't want a concurrent
  9874. * snapshot to run after we've already checked the extents.
  9875. *
  9876. * It is possible that subvolume is marked for deletion but still not
  9877. * removed yet. To prevent this race, we check the root status before
  9878. * activating the swapfile.
  9879. */
  9880. spin_lock(&root->root_item_lock);
  9881. if (btrfs_root_dead(root)) {
  9882. spin_unlock(&root->root_item_lock);
  9883. btrfs_exclop_finish(fs_info);
  9884. btrfs_warn(fs_info,
  9885. "cannot activate swapfile because subvolume %llu is being deleted",
  9886. root->root_key.objectid);
  9887. return -EPERM;
  9888. }
  9889. atomic_inc(&root->nr_swapfiles);
  9890. spin_unlock(&root->root_item_lock);
  9891. isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
  9892. lock_extent(io_tree, 0, isize - 1, &cached_state);
  9893. start = 0;
  9894. while (start < isize) {
  9895. u64 logical_block_start, physical_block_start;
  9896. struct btrfs_block_group *bg;
  9897. u64 len = isize - start;
  9898. em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, start, len);
  9899. if (IS_ERR(em)) {
  9900. ret = PTR_ERR(em);
  9901. goto out;
  9902. }
  9903. if (em->block_start == EXTENT_MAP_HOLE) {
  9904. btrfs_warn(fs_info, "swapfile must not have holes");
  9905. ret = -EINVAL;
  9906. goto out;
  9907. }
  9908. if (em->block_start == EXTENT_MAP_INLINE) {
  9909. /*
  9910. * It's unlikely we'll ever actually find ourselves
  9911. * here, as a file small enough to fit inline won't be
  9912. * big enough to store more than the swap header, but in
  9913. * case something changes in the future, let's catch it
  9914. * here rather than later.
  9915. */
  9916. btrfs_warn(fs_info, "swapfile must not be inline");
  9917. ret = -EINVAL;
  9918. goto out;
  9919. }
  9920. if (test_bit(EXTENT_FLAG_COMPRESSED, &em->flags)) {
  9921. btrfs_warn(fs_info, "swapfile must not be compressed");
  9922. ret = -EINVAL;
  9923. goto out;
  9924. }
  9925. logical_block_start = em->block_start + (start - em->start);
  9926. len = min(len, em->len - (start - em->start));
  9927. free_extent_map(em);
  9928. em = NULL;
  9929. ret = can_nocow_extent(inode, start, &len, NULL, NULL, NULL, false, true);
  9930. if (ret < 0) {
  9931. goto out;
  9932. } else if (ret) {
  9933. ret = 0;
  9934. } else {
  9935. btrfs_warn(fs_info,
  9936. "swapfile must not be copy-on-write");
  9937. ret = -EINVAL;
  9938. goto out;
  9939. }
  9940. em = btrfs_get_chunk_map(fs_info, logical_block_start, len);
  9941. if (IS_ERR(em)) {
  9942. ret = PTR_ERR(em);
  9943. goto out;
  9944. }
  9945. if (em->map_lookup->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
  9946. btrfs_warn(fs_info,
  9947. "swapfile must have single data profile");
  9948. ret = -EINVAL;
  9949. goto out;
  9950. }
  9951. if (device == NULL) {
  9952. device = em->map_lookup->stripes[0].dev;
  9953. ret = btrfs_add_swapfile_pin(inode, device, false);
  9954. if (ret == 1)
  9955. ret = 0;
  9956. else if (ret)
  9957. goto out;
  9958. } else if (device != em->map_lookup->stripes[0].dev) {
  9959. btrfs_warn(fs_info, "swapfile must be on one device");
  9960. ret = -EINVAL;
  9961. goto out;
  9962. }
  9963. physical_block_start = (em->map_lookup->stripes[0].physical +
  9964. (logical_block_start - em->start));
  9965. len = min(len, em->len - (logical_block_start - em->start));
  9966. free_extent_map(em);
  9967. em = NULL;
  9968. bg = btrfs_lookup_block_group(fs_info, logical_block_start);
  9969. if (!bg) {
  9970. btrfs_warn(fs_info,
  9971. "could not find block group containing swapfile");
  9972. ret = -EINVAL;
  9973. goto out;
  9974. }
  9975. if (!btrfs_inc_block_group_swap_extents(bg)) {
  9976. btrfs_warn(fs_info,
  9977. "block group for swapfile at %llu is read-only%s",
  9978. bg->start,
  9979. atomic_read(&fs_info->scrubs_running) ?
  9980. " (scrub running)" : "");
  9981. btrfs_put_block_group(bg);
  9982. ret = -EINVAL;
  9983. goto out;
  9984. }
  9985. ret = btrfs_add_swapfile_pin(inode, bg, true);
  9986. if (ret) {
  9987. btrfs_put_block_group(bg);
  9988. if (ret == 1)
  9989. ret = 0;
  9990. else
  9991. goto out;
  9992. }
  9993. if (bsi.block_len &&
  9994. bsi.block_start + bsi.block_len == physical_block_start) {
  9995. bsi.block_len += len;
  9996. } else {
  9997. if (bsi.block_len) {
  9998. ret = btrfs_add_swap_extent(sis, &bsi);
  9999. if (ret)
  10000. goto out;
  10001. }
  10002. bsi.start = start;
  10003. bsi.block_start = physical_block_start;
  10004. bsi.block_len = len;
  10005. }
  10006. start += len;
  10007. }
  10008. if (bsi.block_len)
  10009. ret = btrfs_add_swap_extent(sis, &bsi);
  10010. out:
  10011. if (!IS_ERR_OR_NULL(em))
  10012. free_extent_map(em);
  10013. unlock_extent(io_tree, 0, isize - 1, &cached_state);
  10014. if (ret)
  10015. btrfs_swap_deactivate(file);
  10016. btrfs_drew_write_unlock(&root->snapshot_lock);
  10017. btrfs_exclop_finish(fs_info);
  10018. if (ret)
  10019. return ret;
  10020. if (device)
  10021. sis->bdev = device->bdev;
  10022. *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
  10023. sis->max = bsi.nr_pages;
  10024. sis->pages = bsi.nr_pages - 1;
  10025. sis->highest_bit = bsi.nr_pages - 1;
  10026. return bsi.nr_extents;
  10027. }
  10028. #else
  10029. static void btrfs_swap_deactivate(struct file *file)
  10030. {
  10031. }
  10032. static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
  10033. sector_t *span)
  10034. {
  10035. return -EOPNOTSUPP;
  10036. }
  10037. #endif
  10038. /*
  10039. * Update the number of bytes used in the VFS' inode. When we replace extents in
  10040. * a range (clone, dedupe, fallocate's zero range), we must update the number of
  10041. * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
  10042. * always get a correct value.
  10043. */
  10044. void btrfs_update_inode_bytes(struct btrfs_inode *inode,
  10045. const u64 add_bytes,
  10046. const u64 del_bytes)
  10047. {
  10048. if (add_bytes == del_bytes)
  10049. return;
  10050. spin_lock(&inode->lock);
  10051. if (del_bytes > 0)
  10052. inode_sub_bytes(&inode->vfs_inode, del_bytes);
  10053. if (add_bytes > 0)
  10054. inode_add_bytes(&inode->vfs_inode, add_bytes);
  10055. spin_unlock(&inode->lock);
  10056. }
  10057. /**
  10058. * Verify that there are no ordered extents for a given file range.
  10059. *
  10060. * @inode: The target inode.
  10061. * @start: Start offset of the file range, should be sector size aligned.
  10062. * @end: End offset (inclusive) of the file range, its value +1 should be
  10063. * sector size aligned.
  10064. *
  10065. * This should typically be used for cases where we locked an inode's VFS lock in
  10066. * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
  10067. * we have flushed all delalloc in the range, we have waited for all ordered
  10068. * extents in the range to complete and finally we have locked the file range in
  10069. * the inode's io_tree.
  10070. */
  10071. void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
  10072. {
  10073. struct btrfs_root *root = inode->root;
  10074. struct btrfs_ordered_extent *ordered;
  10075. if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
  10076. return;
  10077. ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
  10078. if (ordered) {
  10079. btrfs_err(root->fs_info,
  10080. "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
  10081. start, end, btrfs_ino(inode), root->root_key.objectid,
  10082. ordered->file_offset,
  10083. ordered->file_offset + ordered->num_bytes - 1);
  10084. btrfs_put_ordered_extent(ordered);
  10085. }
  10086. ASSERT(ordered == NULL);
  10087. }
  10088. static const struct inode_operations btrfs_dir_inode_operations = {
  10089. .getattr = btrfs_getattr,
  10090. .lookup = btrfs_lookup,
  10091. .create = btrfs_create,
  10092. .unlink = btrfs_unlink,
  10093. .link = btrfs_link,
  10094. .mkdir = btrfs_mkdir,
  10095. .rmdir = btrfs_rmdir,
  10096. .rename = btrfs_rename2,
  10097. .symlink = btrfs_symlink,
  10098. .setattr = btrfs_setattr,
  10099. .mknod = btrfs_mknod,
  10100. .listxattr = btrfs_listxattr,
  10101. .permission = btrfs_permission,
  10102. .get_acl = btrfs_get_acl,
  10103. .set_acl = btrfs_set_acl,
  10104. .update_time = btrfs_update_time,
  10105. .tmpfile = btrfs_tmpfile,
  10106. .fileattr_get = btrfs_fileattr_get,
  10107. .fileattr_set = btrfs_fileattr_set,
  10108. };
  10109. static const struct file_operations btrfs_dir_file_operations = {
  10110. .llseek = generic_file_llseek,
  10111. .read = generic_read_dir,
  10112. .iterate_shared = btrfs_real_readdir,
  10113. .open = btrfs_opendir,
  10114. .unlocked_ioctl = btrfs_ioctl,
  10115. #ifdef CONFIG_COMPAT
  10116. .compat_ioctl = btrfs_compat_ioctl,
  10117. #endif
  10118. .release = btrfs_release_file,
  10119. .fsync = btrfs_sync_file,
  10120. };
  10121. /*
  10122. * btrfs doesn't support the bmap operation because swapfiles
  10123. * use bmap to make a mapping of extents in the file. They assume
  10124. * these extents won't change over the life of the file and they
  10125. * use the bmap result to do IO directly to the drive.
  10126. *
  10127. * the btrfs bmap call would return logical addresses that aren't
  10128. * suitable for IO and they also will change frequently as COW
  10129. * operations happen. So, swapfile + btrfs == corruption.
  10130. *
  10131. * For now we're avoiding this by dropping bmap.
  10132. */
  10133. static const struct address_space_operations btrfs_aops = {
  10134. .read_folio = btrfs_read_folio,
  10135. .writepages = btrfs_writepages,
  10136. .readahead = btrfs_readahead,
  10137. .direct_IO = noop_direct_IO,
  10138. .invalidate_folio = btrfs_invalidate_folio,
  10139. .release_folio = btrfs_release_folio,
  10140. .migrate_folio = btrfs_migrate_folio,
  10141. .dirty_folio = filemap_dirty_folio,
  10142. .error_remove_page = generic_error_remove_page,
  10143. .swap_activate = btrfs_swap_activate,
  10144. .swap_deactivate = btrfs_swap_deactivate,
  10145. };
  10146. static const struct inode_operations btrfs_file_inode_operations = {
  10147. .getattr = btrfs_getattr,
  10148. .setattr = btrfs_setattr,
  10149. .listxattr = btrfs_listxattr,
  10150. .permission = btrfs_permission,
  10151. .fiemap = btrfs_fiemap,
  10152. .get_acl = btrfs_get_acl,
  10153. .set_acl = btrfs_set_acl,
  10154. .update_time = btrfs_update_time,
  10155. .fileattr_get = btrfs_fileattr_get,
  10156. .fileattr_set = btrfs_fileattr_set,
  10157. };
  10158. static const struct inode_operations btrfs_special_inode_operations = {
  10159. .getattr = btrfs_getattr,
  10160. .setattr = btrfs_setattr,
  10161. .permission = btrfs_permission,
  10162. .listxattr = btrfs_listxattr,
  10163. .get_acl = btrfs_get_acl,
  10164. .set_acl = btrfs_set_acl,
  10165. .update_time = btrfs_update_time,
  10166. };
  10167. static const struct inode_operations btrfs_symlink_inode_operations = {
  10168. .get_link = page_get_link,
  10169. .getattr = btrfs_getattr,
  10170. .setattr = btrfs_setattr,
  10171. .permission = btrfs_permission,
  10172. .listxattr = btrfs_listxattr,
  10173. .update_time = btrfs_update_time,
  10174. };
  10175. const struct dentry_operations btrfs_dentry_operations = {
  10176. .d_delete = btrfs_dentry_delete,
  10177. };