inode.c 291 KB

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