inode.c 291 KB

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