inode.c 290 KB

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