inode.c 290 KB

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