inode.c 305 KB

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