shmem.c 159 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Resizable virtual memory filesystem for Linux.
  4. *
  5. * Copyright (C) 2000 Linus Torvalds.
  6. * 2000 Transmeta Corp.
  7. * 2000-2001 Christoph Rohland
  8. * 2000-2001 SAP AG
  9. * 2002 Red Hat Inc.
  10. * Copyright (C) 2002-2011 Hugh Dickins.
  11. * Copyright (C) 2011 Google Inc.
  12. * Copyright (C) 2002-2005 VERITAS Software Corporation.
  13. * Copyright (C) 2004 Andi Kleen, SuSE Labs
  14. *
  15. * Extended attribute support for tmpfs:
  16. * Copyright (c) 2004, Luke Kenneth Casson Leighton <lkcl@lkcl.net>
  17. * Copyright (c) 2004 Red Hat, Inc., James Morris <jmorris@redhat.com>
  18. *
  19. * tiny-shmem:
  20. * Copyright (c) 2004, 2008 Matt Mackall <mpm@selenic.com>
  21. */
  22. #include <linux/fs.h>
  23. #include <linux/init.h>
  24. #include <linux/vfs.h>
  25. #include <linux/mount.h>
  26. #include <linux/ramfs.h>
  27. #include <linux/pagemap.h>
  28. #include <linux/file.h>
  29. #include <linux/fileattr.h>
  30. #include <linux/filelock.h>
  31. #include <linux/mm.h>
  32. #include <linux/random.h>
  33. #include <linux/sched/signal.h>
  34. #include <linux/export.h>
  35. #include <linux/shmem_fs.h>
  36. #include <linux/swap.h>
  37. #include <linux/uio.h>
  38. #include <linux/hugetlb.h>
  39. #include <linux/fs_parser.h>
  40. #include <linux/swapfile.h>
  41. #include <linux/iversion.h>
  42. #include <linux/unicode.h>
  43. #include "swap.h"
  44. static struct vfsmount *shm_mnt __ro_after_init;
  45. #ifdef CONFIG_SHMEM
  46. /*
  47. * This virtual memory filesystem is heavily based on the ramfs. It
  48. * extends ramfs by the ability to use swap and honor resource limits
  49. * which makes it a completely usable filesystem.
  50. */
  51. #include <linux/xattr.h>
  52. #include <linux/exportfs.h>
  53. #include <linux/posix_acl.h>
  54. #include <linux/posix_acl_xattr.h>
  55. #include <linux/mman.h>
  56. #include <linux/string.h>
  57. #include <linux/slab.h>
  58. #include <linux/backing-dev.h>
  59. #include <linux/writeback.h>
  60. #include <linux/pagevec.h>
  61. #include <linux/percpu_counter.h>
  62. #include <linux/falloc.h>
  63. #include <linux/splice.h>
  64. #include <linux/security.h>
  65. #include <linux/leafops.h>
  66. #include <linux/mempolicy.h>
  67. #include <linux/namei.h>
  68. #include <linux/ctype.h>
  69. #include <linux/migrate.h>
  70. #include <linux/highmem.h>
  71. #include <linux/seq_file.h>
  72. #include <linux/magic.h>
  73. #include <linux/syscalls.h>
  74. #include <linux/fcntl.h>
  75. #include <uapi/linux/memfd.h>
  76. #include <linux/rmap.h>
  77. #include <linux/uuid.h>
  78. #include <linux/quotaops.h>
  79. #include <linux/rcupdate_wait.h>
  80. #include <linux/uaccess.h>
  81. #include "internal.h"
  82. #define VM_ACCT(size) (PAGE_ALIGN(size) >> PAGE_SHIFT)
  83. /* Pretend that each entry is of this size in directory's i_size */
  84. #define BOGO_DIRENT_SIZE 20
  85. /* Pretend that one inode + its dentry occupy this much memory */
  86. #define BOGO_INODE_SIZE 1024
  87. /* Symlink up to this size is kmalloc'ed instead of using a swappable page */
  88. #define SHORT_SYMLINK_LEN 128
  89. /*
  90. * shmem_fallocate communicates with shmem_fault or shmem_writeout via
  91. * inode->i_private (with i_rwsem making sure that it has only one user at
  92. * a time): we would prefer not to enlarge the shmem inode just for that.
  93. */
  94. struct shmem_falloc {
  95. wait_queue_head_t *waitq; /* faults into hole wait for punch to end */
  96. pgoff_t start; /* start of range currently being fallocated */
  97. pgoff_t next; /* the next page offset to be fallocated */
  98. pgoff_t nr_falloced; /* how many new pages have been fallocated */
  99. pgoff_t nr_unswapped; /* how often writeout refused to swap out */
  100. };
  101. struct shmem_options {
  102. unsigned long long blocks;
  103. unsigned long long inodes;
  104. struct mempolicy *mpol;
  105. kuid_t uid;
  106. kgid_t gid;
  107. umode_t mode;
  108. bool full_inums;
  109. int huge;
  110. int seen;
  111. bool noswap;
  112. unsigned short quota_types;
  113. struct shmem_quota_limits qlimits;
  114. #if IS_ENABLED(CONFIG_UNICODE)
  115. struct unicode_map *encoding;
  116. bool strict_encoding;
  117. #endif
  118. #define SHMEM_SEEN_BLOCKS 1
  119. #define SHMEM_SEEN_INODES 2
  120. #define SHMEM_SEEN_HUGE 4
  121. #define SHMEM_SEEN_INUMS 8
  122. #define SHMEM_SEEN_QUOTA 16
  123. };
  124. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  125. static unsigned long huge_shmem_orders_always __read_mostly;
  126. static unsigned long huge_shmem_orders_madvise __read_mostly;
  127. static unsigned long huge_shmem_orders_inherit __read_mostly;
  128. static unsigned long huge_shmem_orders_within_size __read_mostly;
  129. static bool shmem_orders_configured __initdata;
  130. #endif
  131. #ifdef CONFIG_TMPFS
  132. static unsigned long shmem_default_max_blocks(void)
  133. {
  134. return totalram_pages() / 2;
  135. }
  136. static unsigned long shmem_default_max_inodes(void)
  137. {
  138. unsigned long nr_pages = totalram_pages();
  139. return min3(nr_pages - totalhigh_pages(), nr_pages / 2,
  140. ULONG_MAX / BOGO_INODE_SIZE);
  141. }
  142. #endif
  143. static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
  144. struct folio **foliop, enum sgp_type sgp, gfp_t gfp,
  145. struct vm_area_struct *vma, vm_fault_t *fault_type);
  146. static inline struct shmem_sb_info *SHMEM_SB(struct super_block *sb)
  147. {
  148. return sb->s_fs_info;
  149. }
  150. /*
  151. * shmem_file_setup pre-accounts the whole fixed size of a VM object,
  152. * for shared memory and for shared anonymous (/dev/zero) mappings
  153. * (unless MAP_NORESERVE and sysctl_overcommit_memory <= 1),
  154. * consistent with the pre-accounting of private mappings ...
  155. */
  156. static inline int shmem_acct_size(unsigned long flags, loff_t size)
  157. {
  158. return (flags & SHMEM_F_NORESERVE) ?
  159. 0 : security_vm_enough_memory_mm(current->mm, VM_ACCT(size));
  160. }
  161. static inline void shmem_unacct_size(unsigned long flags, loff_t size)
  162. {
  163. if (!(flags & SHMEM_F_NORESERVE))
  164. vm_unacct_memory(VM_ACCT(size));
  165. }
  166. static inline int shmem_reacct_size(unsigned long flags,
  167. loff_t oldsize, loff_t newsize)
  168. {
  169. if (!(flags & SHMEM_F_NORESERVE)) {
  170. if (VM_ACCT(newsize) > VM_ACCT(oldsize))
  171. return security_vm_enough_memory_mm(current->mm,
  172. VM_ACCT(newsize) - VM_ACCT(oldsize));
  173. else if (VM_ACCT(newsize) < VM_ACCT(oldsize))
  174. vm_unacct_memory(VM_ACCT(oldsize) - VM_ACCT(newsize));
  175. }
  176. return 0;
  177. }
  178. /*
  179. * ... whereas tmpfs objects are accounted incrementally as
  180. * pages are allocated, in order to allow large sparse files.
  181. * shmem_get_folio reports shmem_acct_blocks failure as -ENOSPC not -ENOMEM,
  182. * so that a failure on a sparse tmpfs mapping will give SIGBUS not OOM.
  183. */
  184. static inline int shmem_acct_blocks(unsigned long flags, long pages)
  185. {
  186. if (!(flags & SHMEM_F_NORESERVE))
  187. return 0;
  188. return security_vm_enough_memory_mm(current->mm,
  189. pages * VM_ACCT(PAGE_SIZE));
  190. }
  191. static inline void shmem_unacct_blocks(unsigned long flags, long pages)
  192. {
  193. if (flags & SHMEM_F_NORESERVE)
  194. vm_unacct_memory(pages * VM_ACCT(PAGE_SIZE));
  195. }
  196. int shmem_inode_acct_blocks(struct inode *inode, long pages)
  197. {
  198. struct shmem_inode_info *info = SHMEM_I(inode);
  199. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  200. int err = -ENOSPC;
  201. if (shmem_acct_blocks(info->flags, pages))
  202. return err;
  203. might_sleep(); /* when quotas */
  204. if (sbinfo->max_blocks) {
  205. if (!percpu_counter_limited_add(&sbinfo->used_blocks,
  206. sbinfo->max_blocks, pages))
  207. goto unacct;
  208. err = dquot_alloc_block_nodirty(inode, pages);
  209. if (err) {
  210. percpu_counter_sub(&sbinfo->used_blocks, pages);
  211. goto unacct;
  212. }
  213. } else {
  214. err = dquot_alloc_block_nodirty(inode, pages);
  215. if (err)
  216. goto unacct;
  217. }
  218. return 0;
  219. unacct:
  220. shmem_unacct_blocks(info->flags, pages);
  221. return err;
  222. }
  223. static void shmem_inode_unacct_blocks(struct inode *inode, long pages)
  224. {
  225. struct shmem_inode_info *info = SHMEM_I(inode);
  226. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  227. might_sleep(); /* when quotas */
  228. dquot_free_block_nodirty(inode, pages);
  229. if (sbinfo->max_blocks)
  230. percpu_counter_sub(&sbinfo->used_blocks, pages);
  231. shmem_unacct_blocks(info->flags, pages);
  232. }
  233. static const struct super_operations shmem_ops;
  234. static const struct address_space_operations shmem_aops;
  235. static const struct file_operations shmem_file_operations;
  236. static const struct inode_operations shmem_inode_operations;
  237. static const struct inode_operations shmem_dir_inode_operations;
  238. static const struct inode_operations shmem_special_inode_operations;
  239. static const struct vm_operations_struct shmem_vm_ops;
  240. static const struct vm_operations_struct shmem_anon_vm_ops;
  241. static struct file_system_type shmem_fs_type;
  242. bool shmem_mapping(const struct address_space *mapping)
  243. {
  244. return mapping->a_ops == &shmem_aops;
  245. }
  246. EXPORT_SYMBOL_GPL(shmem_mapping);
  247. bool vma_is_anon_shmem(const struct vm_area_struct *vma)
  248. {
  249. return vma->vm_ops == &shmem_anon_vm_ops;
  250. }
  251. bool vma_is_shmem(const struct vm_area_struct *vma)
  252. {
  253. return vma_is_anon_shmem(vma) || vma->vm_ops == &shmem_vm_ops;
  254. }
  255. static LIST_HEAD(shmem_swaplist);
  256. static DEFINE_SPINLOCK(shmem_swaplist_lock);
  257. #ifdef CONFIG_TMPFS_QUOTA
  258. static int shmem_enable_quotas(struct super_block *sb,
  259. unsigned short quota_types)
  260. {
  261. int type, err = 0;
  262. sb_dqopt(sb)->flags |= DQUOT_QUOTA_SYS_FILE | DQUOT_NOLIST_DIRTY;
  263. for (type = 0; type < SHMEM_MAXQUOTAS; type++) {
  264. if (!(quota_types & (1 << type)))
  265. continue;
  266. err = dquot_load_quota_sb(sb, type, QFMT_SHMEM,
  267. DQUOT_USAGE_ENABLED |
  268. DQUOT_LIMITS_ENABLED);
  269. if (err)
  270. goto out_err;
  271. }
  272. return 0;
  273. out_err:
  274. pr_warn("tmpfs: failed to enable quota tracking (type=%d, err=%d)\n",
  275. type, err);
  276. for (type--; type >= 0; type--)
  277. dquot_quota_off(sb, type);
  278. return err;
  279. }
  280. static void shmem_disable_quotas(struct super_block *sb)
  281. {
  282. int type;
  283. for (type = 0; type < SHMEM_MAXQUOTAS; type++)
  284. dquot_quota_off(sb, type);
  285. }
  286. static struct dquot __rcu **shmem_get_dquots(struct inode *inode)
  287. {
  288. return SHMEM_I(inode)->i_dquot;
  289. }
  290. #endif /* CONFIG_TMPFS_QUOTA */
  291. /*
  292. * shmem_reserve_inode() performs bookkeeping to reserve a shmem inode, and
  293. * produces a novel ino for the newly allocated inode.
  294. *
  295. * It may also be called when making a hard link to permit the space needed by
  296. * each dentry. However, in that case, no new inode number is needed since that
  297. * internally draws from another pool of inode numbers (currently global
  298. * get_next_ino()). This case is indicated by passing NULL as inop.
  299. */
  300. #define SHMEM_INO_BATCH 1024
  301. static int shmem_reserve_inode(struct super_block *sb, ino_t *inop)
  302. {
  303. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  304. ino_t ino;
  305. if (!(sb->s_flags & SB_KERNMOUNT)) {
  306. raw_spin_lock(&sbinfo->stat_lock);
  307. if (sbinfo->max_inodes) {
  308. if (sbinfo->free_ispace < BOGO_INODE_SIZE) {
  309. raw_spin_unlock(&sbinfo->stat_lock);
  310. return -ENOSPC;
  311. }
  312. sbinfo->free_ispace -= BOGO_INODE_SIZE;
  313. }
  314. if (inop) {
  315. ino = sbinfo->next_ino++;
  316. if (unlikely(is_zero_ino(ino)))
  317. ino = sbinfo->next_ino++;
  318. if (unlikely(!sbinfo->full_inums &&
  319. ino > UINT_MAX)) {
  320. /*
  321. * Emulate get_next_ino uint wraparound for
  322. * compatibility
  323. */
  324. if (IS_ENABLED(CONFIG_64BIT))
  325. pr_warn("%s: inode number overflow on device %d, consider using inode64 mount option\n",
  326. __func__, MINOR(sb->s_dev));
  327. sbinfo->next_ino = 1;
  328. ino = sbinfo->next_ino++;
  329. }
  330. *inop = ino;
  331. }
  332. raw_spin_unlock(&sbinfo->stat_lock);
  333. } else if (inop) {
  334. /*
  335. * __shmem_file_setup, one of our callers, is lock-free: it
  336. * doesn't hold stat_lock in shmem_reserve_inode since
  337. * max_inodes is always 0, and is called from potentially
  338. * unknown contexts. As such, use a per-cpu batched allocator
  339. * which doesn't require the per-sb stat_lock unless we are at
  340. * the batch boundary.
  341. *
  342. * We don't need to worry about inode{32,64} since SB_KERNMOUNT
  343. * shmem mounts are not exposed to userspace, so we don't need
  344. * to worry about things like glibc compatibility.
  345. */
  346. ino_t *next_ino;
  347. next_ino = per_cpu_ptr(sbinfo->ino_batch, get_cpu());
  348. ino = *next_ino;
  349. if (unlikely(ino % SHMEM_INO_BATCH == 0)) {
  350. raw_spin_lock(&sbinfo->stat_lock);
  351. ino = sbinfo->next_ino;
  352. sbinfo->next_ino += SHMEM_INO_BATCH;
  353. raw_spin_unlock(&sbinfo->stat_lock);
  354. if (unlikely(is_zero_ino(ino)))
  355. ino++;
  356. }
  357. *inop = ino;
  358. *next_ino = ++ino;
  359. put_cpu();
  360. }
  361. return 0;
  362. }
  363. static void shmem_free_inode(struct super_block *sb, size_t freed_ispace)
  364. {
  365. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  366. if (sbinfo->max_inodes) {
  367. raw_spin_lock(&sbinfo->stat_lock);
  368. sbinfo->free_ispace += BOGO_INODE_SIZE + freed_ispace;
  369. raw_spin_unlock(&sbinfo->stat_lock);
  370. }
  371. }
  372. /**
  373. * shmem_recalc_inode - recalculate the block usage of an inode
  374. * @inode: inode to recalc
  375. * @alloced: the change in number of pages allocated to inode
  376. * @swapped: the change in number of pages swapped from inode
  377. *
  378. * We have to calculate the free blocks since the mm can drop
  379. * undirtied hole pages behind our back.
  380. *
  381. * But normally info->alloced == inode->i_mapping->nrpages + info->swapped
  382. * So mm freed is info->alloced - (inode->i_mapping->nrpages + info->swapped)
  383. *
  384. * Return: true if swapped was incremented from 0, for shmem_writeout().
  385. */
  386. bool shmem_recalc_inode(struct inode *inode, long alloced, long swapped)
  387. {
  388. struct shmem_inode_info *info = SHMEM_I(inode);
  389. bool first_swapped = false;
  390. long freed;
  391. spin_lock(&info->lock);
  392. info->alloced += alloced;
  393. info->swapped += swapped;
  394. freed = info->alloced - info->swapped -
  395. READ_ONCE(inode->i_mapping->nrpages);
  396. /*
  397. * Special case: whereas normally shmem_recalc_inode() is called
  398. * after i_mapping->nrpages has already been adjusted (up or down),
  399. * shmem_writeout() has to raise swapped before nrpages is lowered -
  400. * to stop a racing shmem_recalc_inode() from thinking that a page has
  401. * been freed. Compensate here, to avoid the need for a followup call.
  402. */
  403. if (swapped > 0) {
  404. if (info->swapped == swapped)
  405. first_swapped = true;
  406. freed += swapped;
  407. }
  408. if (freed > 0)
  409. info->alloced -= freed;
  410. spin_unlock(&info->lock);
  411. /* The quota case may block */
  412. if (freed > 0)
  413. shmem_inode_unacct_blocks(inode, freed);
  414. return first_swapped;
  415. }
  416. bool shmem_charge(struct inode *inode, long pages)
  417. {
  418. struct address_space *mapping = inode->i_mapping;
  419. if (shmem_inode_acct_blocks(inode, pages))
  420. return false;
  421. /* nrpages adjustment first, then shmem_recalc_inode() when balanced */
  422. xa_lock_irq(&mapping->i_pages);
  423. mapping->nrpages += pages;
  424. xa_unlock_irq(&mapping->i_pages);
  425. shmem_recalc_inode(inode, pages, 0);
  426. return true;
  427. }
  428. void shmem_uncharge(struct inode *inode, long pages)
  429. {
  430. /* pages argument is currently unused: keep it to help debugging */
  431. /* nrpages adjustment done by __filemap_remove_folio() or caller */
  432. shmem_recalc_inode(inode, 0, 0);
  433. }
  434. /*
  435. * Replace item expected in xarray by a new item, while holding xa_lock.
  436. */
  437. static int shmem_replace_entry(struct address_space *mapping,
  438. pgoff_t index, void *expected, void *replacement)
  439. {
  440. XA_STATE(xas, &mapping->i_pages, index);
  441. void *item;
  442. VM_BUG_ON(!expected);
  443. VM_BUG_ON(!replacement);
  444. item = xas_load(&xas);
  445. if (item != expected)
  446. return -ENOENT;
  447. xas_store(&xas, replacement);
  448. return 0;
  449. }
  450. /*
  451. * Sometimes, before we decide whether to proceed or to fail, we must check
  452. * that an entry was not already brought back or split by a racing thread.
  453. *
  454. * Checking folio is not enough: by the time a swapcache folio is locked, it
  455. * might be reused, and again be swapcache, using the same swap as before.
  456. * Returns the swap entry's order if it still presents, else returns -1.
  457. */
  458. static int shmem_confirm_swap(struct address_space *mapping, pgoff_t index,
  459. swp_entry_t swap)
  460. {
  461. XA_STATE(xas, &mapping->i_pages, index);
  462. int ret = -1;
  463. void *entry;
  464. rcu_read_lock();
  465. do {
  466. entry = xas_load(&xas);
  467. if (entry == swp_to_radix_entry(swap))
  468. ret = xas_get_order(&xas);
  469. } while (xas_retry(&xas, entry));
  470. rcu_read_unlock();
  471. return ret;
  472. }
  473. /*
  474. * Definitions for "huge tmpfs": tmpfs mounted with the huge= option
  475. *
  476. * SHMEM_HUGE_NEVER:
  477. * disables huge pages for the mount;
  478. * SHMEM_HUGE_ALWAYS:
  479. * enables huge pages for the mount;
  480. * SHMEM_HUGE_WITHIN_SIZE:
  481. * only allocate huge pages if the page will be fully within i_size,
  482. * also respect madvise() hints;
  483. * SHMEM_HUGE_ADVISE:
  484. * only allocate huge pages if requested with madvise();
  485. */
  486. #define SHMEM_HUGE_NEVER 0
  487. #define SHMEM_HUGE_ALWAYS 1
  488. #define SHMEM_HUGE_WITHIN_SIZE 2
  489. #define SHMEM_HUGE_ADVISE 3
  490. /*
  491. * Special values.
  492. * Only can be set via /sys/kernel/mm/transparent_hugepage/shmem_enabled:
  493. *
  494. * SHMEM_HUGE_DENY:
  495. * disables huge on shm_mnt and all mounts, for emergency use;
  496. * SHMEM_HUGE_FORCE:
  497. * enables huge on shm_mnt and all mounts, w/o needing option, for testing;
  498. *
  499. */
  500. #define SHMEM_HUGE_DENY (-1)
  501. #define SHMEM_HUGE_FORCE (-2)
  502. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  503. /* ifdef here to avoid bloating shmem.o when not necessary */
  504. #if defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_NEVER)
  505. #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_NEVER
  506. #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ALWAYS)
  507. #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_ALWAYS
  508. #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_WITHIN_SIZE)
  509. #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_WITHIN_SIZE
  510. #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_SHMEM_HUGE_ADVISE)
  511. #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_ADVISE
  512. #else
  513. #define SHMEM_HUGE_DEFAULT SHMEM_HUGE_NEVER
  514. #endif
  515. static int shmem_huge __read_mostly = SHMEM_HUGE_DEFAULT;
  516. #undef SHMEM_HUGE_DEFAULT
  517. #if defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_NEVER)
  518. #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_NEVER
  519. #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ALWAYS)
  520. #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_ALWAYS
  521. #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_WITHIN_SIZE)
  522. #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_WITHIN_SIZE
  523. #elif defined(CONFIG_TRANSPARENT_HUGEPAGE_TMPFS_HUGE_ADVISE)
  524. #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_ADVISE
  525. #else
  526. #define TMPFS_HUGE_DEFAULT SHMEM_HUGE_NEVER
  527. #endif
  528. static int tmpfs_huge __read_mostly = TMPFS_HUGE_DEFAULT;
  529. #undef TMPFS_HUGE_DEFAULT
  530. static unsigned int shmem_get_orders_within_size(struct inode *inode,
  531. unsigned long within_size_orders, pgoff_t index,
  532. loff_t write_end)
  533. {
  534. pgoff_t aligned_index;
  535. unsigned long order;
  536. loff_t i_size;
  537. order = highest_order(within_size_orders);
  538. while (within_size_orders) {
  539. aligned_index = round_up(index + 1, 1 << order);
  540. i_size = max(write_end, i_size_read(inode));
  541. i_size = round_up(i_size, PAGE_SIZE);
  542. if (i_size >> PAGE_SHIFT >= aligned_index)
  543. return within_size_orders;
  544. order = next_order(&within_size_orders, order);
  545. }
  546. return 0;
  547. }
  548. static unsigned int shmem_huge_global_enabled(struct inode *inode, pgoff_t index,
  549. loff_t write_end, bool shmem_huge_force,
  550. struct vm_area_struct *vma,
  551. vm_flags_t vm_flags)
  552. {
  553. unsigned int maybe_pmd_order = HPAGE_PMD_ORDER > MAX_PAGECACHE_ORDER ?
  554. 0 : BIT(HPAGE_PMD_ORDER);
  555. unsigned long within_size_orders;
  556. if (!S_ISREG(inode->i_mode))
  557. return 0;
  558. if (shmem_huge == SHMEM_HUGE_DENY)
  559. return 0;
  560. if (shmem_huge_force || shmem_huge == SHMEM_HUGE_FORCE)
  561. return maybe_pmd_order;
  562. /*
  563. * The huge order allocation for anon shmem is controlled through
  564. * the mTHP interface, so we still use PMD-sized huge order to
  565. * check whether global control is enabled.
  566. *
  567. * For tmpfs with 'huge=always' or 'huge=within_size' mount option,
  568. * we will always try PMD-sized order first. If that failed, it will
  569. * fall back to small large folios.
  570. */
  571. switch (SHMEM_SB(inode->i_sb)->huge) {
  572. case SHMEM_HUGE_ALWAYS:
  573. return THP_ORDERS_ALL_FILE_DEFAULT;
  574. case SHMEM_HUGE_WITHIN_SIZE:
  575. within_size_orders = shmem_get_orders_within_size(inode,
  576. THP_ORDERS_ALL_FILE_DEFAULT, index, write_end);
  577. if (within_size_orders > 0)
  578. return within_size_orders;
  579. fallthrough;
  580. case SHMEM_HUGE_ADVISE:
  581. if (vm_flags & VM_HUGEPAGE)
  582. return THP_ORDERS_ALL_FILE_DEFAULT;
  583. fallthrough;
  584. default:
  585. return 0;
  586. }
  587. }
  588. static int shmem_parse_huge(const char *str)
  589. {
  590. int huge;
  591. if (!str)
  592. return -EINVAL;
  593. if (!strcmp(str, "never"))
  594. huge = SHMEM_HUGE_NEVER;
  595. else if (!strcmp(str, "always"))
  596. huge = SHMEM_HUGE_ALWAYS;
  597. else if (!strcmp(str, "within_size"))
  598. huge = SHMEM_HUGE_WITHIN_SIZE;
  599. else if (!strcmp(str, "advise"))
  600. huge = SHMEM_HUGE_ADVISE;
  601. else if (!strcmp(str, "deny"))
  602. huge = SHMEM_HUGE_DENY;
  603. else if (!strcmp(str, "force"))
  604. huge = SHMEM_HUGE_FORCE;
  605. else
  606. return -EINVAL;
  607. if (!has_transparent_hugepage() &&
  608. huge != SHMEM_HUGE_NEVER && huge != SHMEM_HUGE_DENY)
  609. return -EINVAL;
  610. /* Do not override huge allocation policy with non-PMD sized mTHP */
  611. if (huge == SHMEM_HUGE_FORCE &&
  612. huge_shmem_orders_inherit != BIT(HPAGE_PMD_ORDER))
  613. return -EINVAL;
  614. return huge;
  615. }
  616. #if defined(CONFIG_SYSFS) || defined(CONFIG_TMPFS)
  617. static const char *shmem_format_huge(int huge)
  618. {
  619. switch (huge) {
  620. case SHMEM_HUGE_NEVER:
  621. return "never";
  622. case SHMEM_HUGE_ALWAYS:
  623. return "always";
  624. case SHMEM_HUGE_WITHIN_SIZE:
  625. return "within_size";
  626. case SHMEM_HUGE_ADVISE:
  627. return "advise";
  628. case SHMEM_HUGE_DENY:
  629. return "deny";
  630. case SHMEM_HUGE_FORCE:
  631. return "force";
  632. default:
  633. VM_BUG_ON(1);
  634. return "bad_val";
  635. }
  636. }
  637. #endif
  638. static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
  639. struct shrink_control *sc, unsigned long nr_to_free)
  640. {
  641. LIST_HEAD(list), *pos, *next;
  642. struct inode *inode;
  643. struct shmem_inode_info *info;
  644. struct folio *folio;
  645. unsigned long batch = sc ? sc->nr_to_scan : 128;
  646. unsigned long split = 0, freed = 0;
  647. if (list_empty(&sbinfo->shrinklist))
  648. return SHRINK_STOP;
  649. spin_lock(&sbinfo->shrinklist_lock);
  650. list_for_each_safe(pos, next, &sbinfo->shrinklist) {
  651. info = list_entry(pos, struct shmem_inode_info, shrinklist);
  652. /* pin the inode */
  653. inode = igrab(&info->vfs_inode);
  654. /* inode is about to be evicted */
  655. if (!inode) {
  656. list_del_init(&info->shrinklist);
  657. goto next;
  658. }
  659. list_move(&info->shrinklist, &list);
  660. next:
  661. sbinfo->shrinklist_len--;
  662. if (!--batch)
  663. break;
  664. }
  665. spin_unlock(&sbinfo->shrinklist_lock);
  666. list_for_each_safe(pos, next, &list) {
  667. pgoff_t next, end;
  668. loff_t i_size;
  669. int ret;
  670. info = list_entry(pos, struct shmem_inode_info, shrinklist);
  671. inode = &info->vfs_inode;
  672. if (nr_to_free && freed >= nr_to_free)
  673. goto move_back;
  674. i_size = i_size_read(inode);
  675. folio = filemap_get_entry(inode->i_mapping, i_size / PAGE_SIZE);
  676. if (!folio || xa_is_value(folio))
  677. goto drop;
  678. /* No large folio at the end of the file: nothing to split */
  679. if (!folio_test_large(folio)) {
  680. folio_put(folio);
  681. goto drop;
  682. }
  683. /* Check if there is anything to gain from splitting */
  684. next = folio_next_index(folio);
  685. end = shmem_fallocend(inode, DIV_ROUND_UP(i_size, PAGE_SIZE));
  686. if (end <= folio->index || end >= next) {
  687. folio_put(folio);
  688. goto drop;
  689. }
  690. /*
  691. * Move the inode on the list back to shrinklist if we failed
  692. * to lock the page at this time.
  693. *
  694. * Waiting for the lock may lead to deadlock in the
  695. * reclaim path.
  696. */
  697. if (!folio_trylock(folio)) {
  698. folio_put(folio);
  699. goto move_back;
  700. }
  701. ret = split_folio(folio);
  702. folio_unlock(folio);
  703. folio_put(folio);
  704. /* If split failed move the inode on the list back to shrinklist */
  705. if (ret)
  706. goto move_back;
  707. freed += next - end;
  708. split++;
  709. drop:
  710. list_del_init(&info->shrinklist);
  711. goto put;
  712. move_back:
  713. /*
  714. * Make sure the inode is either on the global list or deleted
  715. * from any local list before iput() since it could be deleted
  716. * in another thread once we put the inode (then the local list
  717. * is corrupted).
  718. */
  719. spin_lock(&sbinfo->shrinklist_lock);
  720. list_move(&info->shrinklist, &sbinfo->shrinklist);
  721. sbinfo->shrinklist_len++;
  722. spin_unlock(&sbinfo->shrinklist_lock);
  723. put:
  724. iput(inode);
  725. }
  726. return split;
  727. }
  728. static long shmem_unused_huge_scan(struct super_block *sb,
  729. struct shrink_control *sc)
  730. {
  731. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  732. if (!READ_ONCE(sbinfo->shrinklist_len))
  733. return SHRINK_STOP;
  734. return shmem_unused_huge_shrink(sbinfo, sc, 0);
  735. }
  736. static long shmem_unused_huge_count(struct super_block *sb,
  737. struct shrink_control *sc)
  738. {
  739. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  740. return READ_ONCE(sbinfo->shrinklist_len);
  741. }
  742. #else /* !CONFIG_TRANSPARENT_HUGEPAGE */
  743. #define shmem_huge SHMEM_HUGE_DENY
  744. static unsigned long shmem_unused_huge_shrink(struct shmem_sb_info *sbinfo,
  745. struct shrink_control *sc, unsigned long nr_to_free)
  746. {
  747. return 0;
  748. }
  749. static unsigned int shmem_huge_global_enabled(struct inode *inode, pgoff_t index,
  750. loff_t write_end, bool shmem_huge_force,
  751. struct vm_area_struct *vma,
  752. vm_flags_t vm_flags)
  753. {
  754. return 0;
  755. }
  756. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  757. static void shmem_update_stats(struct folio *folio, int nr_pages)
  758. {
  759. if (folio_test_pmd_mappable(folio))
  760. lruvec_stat_mod_folio(folio, NR_SHMEM_THPS, nr_pages);
  761. lruvec_stat_mod_folio(folio, NR_FILE_PAGES, nr_pages);
  762. lruvec_stat_mod_folio(folio, NR_SHMEM, nr_pages);
  763. }
  764. /*
  765. * Somewhat like filemap_add_folio, but error if expected item has gone.
  766. */
  767. int shmem_add_to_page_cache(struct folio *folio,
  768. struct address_space *mapping,
  769. pgoff_t index, void *expected, gfp_t gfp)
  770. {
  771. XA_STATE_ORDER(xas, &mapping->i_pages, index, folio_order(folio));
  772. unsigned long nr = folio_nr_pages(folio);
  773. swp_entry_t iter, swap;
  774. void *entry;
  775. VM_BUG_ON_FOLIO(index != round_down(index, nr), folio);
  776. VM_BUG_ON_FOLIO(!folio_test_locked(folio), folio);
  777. VM_BUG_ON_FOLIO(!folio_test_swapbacked(folio), folio);
  778. folio_ref_add(folio, nr);
  779. folio->mapping = mapping;
  780. folio->index = index;
  781. gfp &= GFP_RECLAIM_MASK;
  782. folio_throttle_swaprate(folio, gfp);
  783. swap = radix_to_swp_entry(expected);
  784. do {
  785. iter = swap;
  786. xas_lock_irq(&xas);
  787. xas_for_each_conflict(&xas, entry) {
  788. /*
  789. * The range must either be empty, or filled with
  790. * expected swap entries. Shmem swap entries are never
  791. * partially freed without split of both entry and
  792. * folio, so there shouldn't be any holes.
  793. */
  794. if (!expected || entry != swp_to_radix_entry(iter)) {
  795. xas_set_err(&xas, -EEXIST);
  796. goto unlock;
  797. }
  798. iter.val += 1 << xas_get_order(&xas);
  799. }
  800. if (expected && iter.val - nr != swap.val) {
  801. xas_set_err(&xas, -EEXIST);
  802. goto unlock;
  803. }
  804. xas_store(&xas, folio);
  805. if (xas_error(&xas))
  806. goto unlock;
  807. shmem_update_stats(folio, nr);
  808. mapping->nrpages += nr;
  809. unlock:
  810. xas_unlock_irq(&xas);
  811. } while (xas_nomem(&xas, gfp));
  812. if (xas_error(&xas)) {
  813. folio->mapping = NULL;
  814. folio_ref_sub(folio, nr);
  815. return xas_error(&xas);
  816. }
  817. return 0;
  818. }
  819. /*
  820. * Somewhat like filemap_remove_folio, but substitutes swap for @folio.
  821. */
  822. static void shmem_delete_from_page_cache(struct folio *folio, void *radswap)
  823. {
  824. struct address_space *mapping = folio->mapping;
  825. long nr = folio_nr_pages(folio);
  826. int error;
  827. xa_lock_irq(&mapping->i_pages);
  828. error = shmem_replace_entry(mapping, folio->index, folio, radswap);
  829. folio->mapping = NULL;
  830. mapping->nrpages -= nr;
  831. shmem_update_stats(folio, -nr);
  832. xa_unlock_irq(&mapping->i_pages);
  833. folio_put_refs(folio, nr);
  834. BUG_ON(error);
  835. }
  836. /*
  837. * Remove swap entry from page cache, free the swap and its page cache. Returns
  838. * the number of pages being freed. 0 means entry not found in XArray (0 pages
  839. * being freed).
  840. */
  841. static long shmem_free_swap(struct address_space *mapping,
  842. pgoff_t index, pgoff_t end, void *radswap)
  843. {
  844. XA_STATE(xas, &mapping->i_pages, index);
  845. unsigned int nr_pages = 0;
  846. pgoff_t base;
  847. void *entry;
  848. xas_lock_irq(&xas);
  849. entry = xas_load(&xas);
  850. if (entry == radswap) {
  851. nr_pages = 1 << xas_get_order(&xas);
  852. base = round_down(xas.xa_index, nr_pages);
  853. if (base < index || base + nr_pages - 1 > end)
  854. nr_pages = 0;
  855. else
  856. xas_store(&xas, NULL);
  857. }
  858. xas_unlock_irq(&xas);
  859. if (nr_pages)
  860. swap_put_entries_direct(radix_to_swp_entry(radswap), nr_pages);
  861. return nr_pages;
  862. }
  863. /*
  864. * Determine (in bytes) how many of the shmem object's pages mapped by the
  865. * given offsets are swapped out.
  866. *
  867. * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
  868. * as long as the inode doesn't go away and racy results are not a problem.
  869. */
  870. unsigned long shmem_partial_swap_usage(struct address_space *mapping,
  871. pgoff_t start, pgoff_t end)
  872. {
  873. XA_STATE(xas, &mapping->i_pages, start);
  874. struct folio *folio;
  875. unsigned long swapped = 0;
  876. unsigned long max = end - 1;
  877. rcu_read_lock();
  878. xas_for_each(&xas, folio, max) {
  879. if (xas_retry(&xas, folio))
  880. continue;
  881. if (xa_is_value(folio))
  882. swapped += 1 << xas_get_order(&xas);
  883. if (xas.xa_index == max)
  884. break;
  885. if (need_resched()) {
  886. xas_pause(&xas);
  887. cond_resched_rcu();
  888. }
  889. }
  890. rcu_read_unlock();
  891. return swapped << PAGE_SHIFT;
  892. }
  893. /*
  894. * Determine (in bytes) how many of the shmem object's pages mapped by the
  895. * given vma is swapped out.
  896. *
  897. * This is safe to call without i_rwsem or the i_pages lock thanks to RCU,
  898. * as long as the inode doesn't go away and racy results are not a problem.
  899. */
  900. unsigned long shmem_swap_usage(struct vm_area_struct *vma)
  901. {
  902. struct inode *inode = file_inode(vma->vm_file);
  903. struct shmem_inode_info *info = SHMEM_I(inode);
  904. struct address_space *mapping = inode->i_mapping;
  905. unsigned long swapped;
  906. /* Be careful as we don't hold info->lock */
  907. swapped = READ_ONCE(info->swapped);
  908. /*
  909. * The easier cases are when the shmem object has nothing in swap, or
  910. * the vma maps it whole. Then we can simply use the stats that we
  911. * already track.
  912. */
  913. if (!swapped)
  914. return 0;
  915. if (!vma->vm_pgoff && vma->vm_end - vma->vm_start >= inode->i_size)
  916. return swapped << PAGE_SHIFT;
  917. /* Here comes the more involved part */
  918. return shmem_partial_swap_usage(mapping, vma->vm_pgoff,
  919. vma->vm_pgoff + vma_pages(vma));
  920. }
  921. /*
  922. * SysV IPC SHM_UNLOCK restore Unevictable pages to their evictable lists.
  923. */
  924. void shmem_unlock_mapping(struct address_space *mapping)
  925. {
  926. struct folio_batch fbatch;
  927. pgoff_t index = 0;
  928. folio_batch_init(&fbatch);
  929. /*
  930. * Minor point, but we might as well stop if someone else SHM_LOCKs it.
  931. */
  932. while (!mapping_unevictable(mapping) &&
  933. filemap_get_folios(mapping, &index, ~0UL, &fbatch)) {
  934. check_move_unevictable_folios(&fbatch);
  935. folio_batch_release(&fbatch);
  936. cond_resched();
  937. }
  938. }
  939. static struct folio *shmem_get_partial_folio(struct inode *inode, pgoff_t index)
  940. {
  941. struct folio *folio;
  942. /*
  943. * At first avoid shmem_get_folio(,,,SGP_READ): that fails
  944. * beyond i_size, and reports fallocated folios as holes.
  945. */
  946. folio = filemap_get_entry(inode->i_mapping, index);
  947. if (!folio)
  948. return folio;
  949. if (!xa_is_value(folio)) {
  950. folio_lock(folio);
  951. if (folio->mapping == inode->i_mapping)
  952. return folio;
  953. /* The folio has been swapped out */
  954. folio_unlock(folio);
  955. folio_put(folio);
  956. }
  957. /*
  958. * But read a folio back from swap if any of it is within i_size
  959. * (although in some cases this is just a waste of time).
  960. */
  961. folio = NULL;
  962. shmem_get_folio(inode, index, 0, &folio, SGP_READ);
  963. return folio;
  964. }
  965. /*
  966. * Remove range of pages and swap entries from page cache, and free them.
  967. * If !unfalloc, truncate or punch hole; if unfalloc, undo failed fallocate.
  968. */
  969. static void shmem_undo_range(struct inode *inode, loff_t lstart, uoff_t lend,
  970. bool unfalloc)
  971. {
  972. struct address_space *mapping = inode->i_mapping;
  973. struct shmem_inode_info *info = SHMEM_I(inode);
  974. pgoff_t start = (lstart + PAGE_SIZE - 1) >> PAGE_SHIFT;
  975. pgoff_t end = (lend + 1) >> PAGE_SHIFT;
  976. struct folio_batch fbatch;
  977. pgoff_t indices[PAGEVEC_SIZE];
  978. struct folio *folio;
  979. bool same_folio;
  980. long nr_swaps_freed = 0;
  981. pgoff_t index;
  982. int i;
  983. if (lend == -1)
  984. end = -1; /* unsigned, so actually very big */
  985. if (info->fallocend > start && info->fallocend <= end && !unfalloc)
  986. info->fallocend = start;
  987. folio_batch_init(&fbatch);
  988. index = start;
  989. while (index < end && find_lock_entries(mapping, &index, end - 1,
  990. &fbatch, indices)) {
  991. for (i = 0; i < folio_batch_count(&fbatch); i++) {
  992. folio = fbatch.folios[i];
  993. if (xa_is_value(folio)) {
  994. if (unfalloc)
  995. continue;
  996. nr_swaps_freed += shmem_free_swap(mapping, indices[i],
  997. end - 1, folio);
  998. continue;
  999. }
  1000. if (!unfalloc || !folio_test_uptodate(folio))
  1001. truncate_inode_folio(mapping, folio);
  1002. folio_unlock(folio);
  1003. }
  1004. folio_batch_remove_exceptionals(&fbatch);
  1005. folio_batch_release(&fbatch);
  1006. cond_resched();
  1007. }
  1008. /*
  1009. * When undoing a failed fallocate, we want none of the partial folio
  1010. * zeroing and splitting below, but shall want to truncate the whole
  1011. * folio when !uptodate indicates that it was added by this fallocate,
  1012. * even when [lstart, lend] covers only a part of the folio.
  1013. */
  1014. if (unfalloc)
  1015. goto whole_folios;
  1016. same_folio = (lstart >> PAGE_SHIFT) == (lend >> PAGE_SHIFT);
  1017. folio = shmem_get_partial_folio(inode, lstart >> PAGE_SHIFT);
  1018. if (folio) {
  1019. same_folio = lend < folio_next_pos(folio);
  1020. folio_mark_dirty(folio);
  1021. if (!truncate_inode_partial_folio(folio, lstart, lend)) {
  1022. start = folio_next_index(folio);
  1023. if (same_folio)
  1024. end = folio->index;
  1025. }
  1026. folio_unlock(folio);
  1027. folio_put(folio);
  1028. folio = NULL;
  1029. }
  1030. if (!same_folio)
  1031. folio = shmem_get_partial_folio(inode, lend >> PAGE_SHIFT);
  1032. if (folio) {
  1033. folio_mark_dirty(folio);
  1034. if (!truncate_inode_partial_folio(folio, lstart, lend))
  1035. end = folio->index;
  1036. folio_unlock(folio);
  1037. folio_put(folio);
  1038. }
  1039. whole_folios:
  1040. index = start;
  1041. while (index < end) {
  1042. cond_resched();
  1043. if (!find_get_entries(mapping, &index, end - 1, &fbatch,
  1044. indices)) {
  1045. /* If all gone or hole-punch or unfalloc, we're done */
  1046. if (index == start || end != -1)
  1047. break;
  1048. /* But if truncating, restart to make sure all gone */
  1049. index = start;
  1050. continue;
  1051. }
  1052. for (i = 0; i < folio_batch_count(&fbatch); i++) {
  1053. folio = fbatch.folios[i];
  1054. if (xa_is_value(folio)) {
  1055. int order;
  1056. long swaps_freed;
  1057. if (unfalloc)
  1058. continue;
  1059. swaps_freed = shmem_free_swap(mapping, indices[i],
  1060. end - 1, folio);
  1061. if (!swaps_freed) {
  1062. pgoff_t base = indices[i];
  1063. order = shmem_confirm_swap(mapping, indices[i],
  1064. radix_to_swp_entry(folio));
  1065. /*
  1066. * If found a large swap entry cross the end or start
  1067. * border, skip it as the truncate_inode_partial_folio
  1068. * above should have at least zerod its content once.
  1069. */
  1070. if (order > 0) {
  1071. base = round_down(base, 1 << order);
  1072. if (base < start || base + (1 << order) > end)
  1073. continue;
  1074. }
  1075. /* Swap was replaced by page or extended, retry */
  1076. index = base;
  1077. break;
  1078. }
  1079. nr_swaps_freed += swaps_freed;
  1080. continue;
  1081. }
  1082. folio_lock(folio);
  1083. if (!unfalloc || !folio_test_uptodate(folio)) {
  1084. if (folio_mapping(folio) != mapping) {
  1085. /* Page was replaced by swap: retry */
  1086. folio_unlock(folio);
  1087. index = indices[i];
  1088. break;
  1089. }
  1090. VM_BUG_ON_FOLIO(folio_test_writeback(folio),
  1091. folio);
  1092. if (!folio_test_large(folio)) {
  1093. truncate_inode_folio(mapping, folio);
  1094. } else if (truncate_inode_partial_folio(folio, lstart, lend)) {
  1095. /*
  1096. * If we split a page, reset the loop so
  1097. * that we pick up the new sub pages.
  1098. * Otherwise the THP was entirely
  1099. * dropped or the target range was
  1100. * zeroed, so just continue the loop as
  1101. * is.
  1102. */
  1103. if (!folio_test_large(folio)) {
  1104. folio_unlock(folio);
  1105. index = start;
  1106. break;
  1107. }
  1108. }
  1109. }
  1110. folio_unlock(folio);
  1111. }
  1112. folio_batch_remove_exceptionals(&fbatch);
  1113. folio_batch_release(&fbatch);
  1114. }
  1115. shmem_recalc_inode(inode, 0, -nr_swaps_freed);
  1116. }
  1117. void shmem_truncate_range(struct inode *inode, loff_t lstart, uoff_t lend)
  1118. {
  1119. shmem_undo_range(inode, lstart, lend, false);
  1120. inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
  1121. inode_inc_iversion(inode);
  1122. }
  1123. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  1124. static int shmem_getattr(struct mnt_idmap *idmap,
  1125. const struct path *path, struct kstat *stat,
  1126. u32 request_mask, unsigned int query_flags)
  1127. {
  1128. struct inode *inode = path->dentry->d_inode;
  1129. struct shmem_inode_info *info = SHMEM_I(inode);
  1130. if (info->alloced - info->swapped != inode->i_mapping->nrpages)
  1131. shmem_recalc_inode(inode, 0, 0);
  1132. if (info->fsflags & FS_APPEND_FL)
  1133. stat->attributes |= STATX_ATTR_APPEND;
  1134. if (info->fsflags & FS_IMMUTABLE_FL)
  1135. stat->attributes |= STATX_ATTR_IMMUTABLE;
  1136. if (info->fsflags & FS_NODUMP_FL)
  1137. stat->attributes |= STATX_ATTR_NODUMP;
  1138. stat->attributes_mask |= (STATX_ATTR_APPEND |
  1139. STATX_ATTR_IMMUTABLE |
  1140. STATX_ATTR_NODUMP);
  1141. generic_fillattr(idmap, request_mask, inode, stat);
  1142. if (shmem_huge_global_enabled(inode, 0, 0, false, NULL, 0))
  1143. stat->blksize = HPAGE_PMD_SIZE;
  1144. if (request_mask & STATX_BTIME) {
  1145. stat->result_mask |= STATX_BTIME;
  1146. stat->btime.tv_sec = info->i_crtime.tv_sec;
  1147. stat->btime.tv_nsec = info->i_crtime.tv_nsec;
  1148. }
  1149. return 0;
  1150. }
  1151. static int shmem_setattr(struct mnt_idmap *idmap,
  1152. struct dentry *dentry, struct iattr *attr)
  1153. {
  1154. struct inode *inode = d_inode(dentry);
  1155. struct shmem_inode_info *info = SHMEM_I(inode);
  1156. int error;
  1157. bool update_mtime = false;
  1158. bool update_ctime = true;
  1159. error = setattr_prepare(idmap, dentry, attr);
  1160. if (error)
  1161. return error;
  1162. if ((info->seals & F_SEAL_EXEC) && (attr->ia_valid & ATTR_MODE)) {
  1163. if ((inode->i_mode ^ attr->ia_mode) & 0111) {
  1164. return -EPERM;
  1165. }
  1166. }
  1167. if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
  1168. loff_t oldsize = inode->i_size;
  1169. loff_t newsize = attr->ia_size;
  1170. /* protected by i_rwsem */
  1171. if ((newsize < oldsize && (info->seals & F_SEAL_SHRINK)) ||
  1172. (newsize > oldsize && (info->seals & F_SEAL_GROW)))
  1173. return -EPERM;
  1174. if (newsize != oldsize) {
  1175. if (info->flags & SHMEM_F_MAPPING_FROZEN)
  1176. return -EPERM;
  1177. error = shmem_reacct_size(SHMEM_I(inode)->flags,
  1178. oldsize, newsize);
  1179. if (error)
  1180. return error;
  1181. i_size_write(inode, newsize);
  1182. update_mtime = true;
  1183. } else {
  1184. update_ctime = false;
  1185. }
  1186. if (newsize <= oldsize) {
  1187. loff_t holebegin = round_up(newsize, PAGE_SIZE);
  1188. if (oldsize > holebegin)
  1189. unmap_mapping_range(inode->i_mapping,
  1190. holebegin, 0, 1);
  1191. if (info->alloced)
  1192. shmem_truncate_range(inode,
  1193. newsize, (loff_t)-1);
  1194. /* unmap again to remove racily COWed private pages */
  1195. if (oldsize > holebegin)
  1196. unmap_mapping_range(inode->i_mapping,
  1197. holebegin, 0, 1);
  1198. }
  1199. }
  1200. if (is_quota_modification(idmap, inode, attr)) {
  1201. error = dquot_initialize(inode);
  1202. if (error)
  1203. return error;
  1204. }
  1205. /* Transfer quota accounting */
  1206. if (i_uid_needs_update(idmap, attr, inode) ||
  1207. i_gid_needs_update(idmap, attr, inode)) {
  1208. error = dquot_transfer(idmap, inode, attr);
  1209. if (error)
  1210. return error;
  1211. }
  1212. setattr_copy(idmap, inode, attr);
  1213. if (attr->ia_valid & ATTR_MODE)
  1214. error = posix_acl_chmod(idmap, dentry, inode->i_mode);
  1215. if (!error && update_ctime) {
  1216. inode_set_ctime_current(inode);
  1217. if (update_mtime)
  1218. inode_set_mtime_to_ts(inode, inode_get_ctime(inode));
  1219. inode_inc_iversion(inode);
  1220. }
  1221. return error;
  1222. }
  1223. static void shmem_evict_inode(struct inode *inode)
  1224. {
  1225. struct shmem_inode_info *info = SHMEM_I(inode);
  1226. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  1227. size_t freed = 0;
  1228. if (shmem_mapping(inode->i_mapping)) {
  1229. shmem_unacct_size(info->flags, inode->i_size);
  1230. inode->i_size = 0;
  1231. mapping_set_exiting(inode->i_mapping);
  1232. shmem_truncate_range(inode, 0, (loff_t)-1);
  1233. if (!list_empty(&info->shrinklist)) {
  1234. spin_lock(&sbinfo->shrinklist_lock);
  1235. if (!list_empty(&info->shrinklist)) {
  1236. list_del_init(&info->shrinklist);
  1237. sbinfo->shrinklist_len--;
  1238. }
  1239. spin_unlock(&sbinfo->shrinklist_lock);
  1240. }
  1241. while (!list_empty(&info->swaplist)) {
  1242. /* Wait while shmem_unuse() is scanning this inode... */
  1243. wait_var_event(&info->stop_eviction,
  1244. !atomic_read(&info->stop_eviction));
  1245. spin_lock(&shmem_swaplist_lock);
  1246. /* ...but beware of the race if we peeked too early */
  1247. if (!atomic_read(&info->stop_eviction))
  1248. list_del_init(&info->swaplist);
  1249. spin_unlock(&shmem_swaplist_lock);
  1250. }
  1251. }
  1252. simple_xattrs_free(&info->xattrs, sbinfo->max_inodes ? &freed : NULL);
  1253. shmem_free_inode(inode->i_sb, freed);
  1254. WARN_ON(inode->i_blocks);
  1255. clear_inode(inode);
  1256. #ifdef CONFIG_TMPFS_QUOTA
  1257. dquot_free_inode(inode);
  1258. dquot_drop(inode);
  1259. #endif
  1260. }
  1261. static unsigned int shmem_find_swap_entries(struct address_space *mapping,
  1262. pgoff_t start, struct folio_batch *fbatch,
  1263. pgoff_t *indices, unsigned int type)
  1264. {
  1265. XA_STATE(xas, &mapping->i_pages, start);
  1266. struct folio *folio;
  1267. swp_entry_t entry;
  1268. rcu_read_lock();
  1269. xas_for_each(&xas, folio, ULONG_MAX) {
  1270. if (xas_retry(&xas, folio))
  1271. continue;
  1272. if (!xa_is_value(folio))
  1273. continue;
  1274. entry = radix_to_swp_entry(folio);
  1275. /*
  1276. * swapin error entries can be found in the mapping. But they're
  1277. * deliberately ignored here as we've done everything we can do.
  1278. */
  1279. if (swp_type(entry) != type)
  1280. continue;
  1281. indices[folio_batch_count(fbatch)] = xas.xa_index;
  1282. if (!folio_batch_add(fbatch, folio))
  1283. break;
  1284. if (need_resched()) {
  1285. xas_pause(&xas);
  1286. cond_resched_rcu();
  1287. }
  1288. }
  1289. rcu_read_unlock();
  1290. return folio_batch_count(fbatch);
  1291. }
  1292. /*
  1293. * Move the swapped pages for an inode to page cache. Returns the count
  1294. * of pages swapped in, or the error in case of failure.
  1295. */
  1296. static int shmem_unuse_swap_entries(struct inode *inode,
  1297. struct folio_batch *fbatch, pgoff_t *indices)
  1298. {
  1299. int i = 0;
  1300. int ret = 0;
  1301. int error = 0;
  1302. struct address_space *mapping = inode->i_mapping;
  1303. for (i = 0; i < folio_batch_count(fbatch); i++) {
  1304. struct folio *folio = fbatch->folios[i];
  1305. error = shmem_swapin_folio(inode, indices[i], &folio, SGP_CACHE,
  1306. mapping_gfp_mask(mapping), NULL, NULL);
  1307. if (error == 0) {
  1308. folio_unlock(folio);
  1309. folio_put(folio);
  1310. ret++;
  1311. }
  1312. if (error == -ENOMEM)
  1313. break;
  1314. error = 0;
  1315. }
  1316. return error ? error : ret;
  1317. }
  1318. /*
  1319. * If swap found in inode, free it and move page from swapcache to filecache.
  1320. */
  1321. static int shmem_unuse_inode(struct inode *inode, unsigned int type)
  1322. {
  1323. struct address_space *mapping = inode->i_mapping;
  1324. pgoff_t start = 0;
  1325. struct folio_batch fbatch;
  1326. pgoff_t indices[PAGEVEC_SIZE];
  1327. int ret = 0;
  1328. do {
  1329. folio_batch_init(&fbatch);
  1330. if (!shmem_find_swap_entries(mapping, start, &fbatch,
  1331. indices, type)) {
  1332. ret = 0;
  1333. break;
  1334. }
  1335. ret = shmem_unuse_swap_entries(inode, &fbatch, indices);
  1336. if (ret < 0)
  1337. break;
  1338. start = indices[folio_batch_count(&fbatch) - 1];
  1339. } while (true);
  1340. return ret;
  1341. }
  1342. /*
  1343. * Read all the shared memory data that resides in the swap
  1344. * device 'type' back into memory, so the swap device can be
  1345. * unused.
  1346. */
  1347. int shmem_unuse(unsigned int type)
  1348. {
  1349. struct shmem_inode_info *info, *next;
  1350. int error = 0;
  1351. if (list_empty(&shmem_swaplist))
  1352. return 0;
  1353. spin_lock(&shmem_swaplist_lock);
  1354. start_over:
  1355. list_for_each_entry_safe(info, next, &shmem_swaplist, swaplist) {
  1356. if (!info->swapped) {
  1357. list_del_init(&info->swaplist);
  1358. continue;
  1359. }
  1360. /*
  1361. * Drop the swaplist mutex while searching the inode for swap;
  1362. * but before doing so, make sure shmem_evict_inode() will not
  1363. * remove placeholder inode from swaplist, nor let it be freed
  1364. * (igrab() would protect from unlink, but not from unmount).
  1365. */
  1366. atomic_inc(&info->stop_eviction);
  1367. spin_unlock(&shmem_swaplist_lock);
  1368. error = shmem_unuse_inode(&info->vfs_inode, type);
  1369. cond_resched();
  1370. spin_lock(&shmem_swaplist_lock);
  1371. if (atomic_dec_and_test(&info->stop_eviction))
  1372. wake_up_var(&info->stop_eviction);
  1373. if (error)
  1374. break;
  1375. if (list_empty(&info->swaplist))
  1376. goto start_over;
  1377. next = list_next_entry(info, swaplist);
  1378. if (!info->swapped)
  1379. list_del_init(&info->swaplist);
  1380. }
  1381. spin_unlock(&shmem_swaplist_lock);
  1382. return error;
  1383. }
  1384. /**
  1385. * shmem_writeout - Write the folio to swap
  1386. * @folio: The folio to write
  1387. * @plug: swap plug
  1388. * @folio_list: list to put back folios on split
  1389. *
  1390. * Move the folio from the page cache to the swap cache.
  1391. */
  1392. int shmem_writeout(struct folio *folio, struct swap_iocb **plug,
  1393. struct list_head *folio_list)
  1394. {
  1395. struct address_space *mapping = folio->mapping;
  1396. struct inode *inode = mapping->host;
  1397. struct shmem_inode_info *info = SHMEM_I(inode);
  1398. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  1399. pgoff_t index;
  1400. int nr_pages;
  1401. bool split = false;
  1402. if ((info->flags & SHMEM_F_LOCKED) || sbinfo->noswap)
  1403. goto redirty;
  1404. if (!total_swap_pages)
  1405. goto redirty;
  1406. /*
  1407. * If CONFIG_THP_SWAP is not enabled, the large folio should be
  1408. * split when swapping.
  1409. *
  1410. * And shrinkage of pages beyond i_size does not split swap, so
  1411. * swapout of a large folio crossing i_size needs to split too
  1412. * (unless fallocate has been used to preallocate beyond EOF).
  1413. */
  1414. if (folio_test_large(folio)) {
  1415. index = shmem_fallocend(inode,
  1416. DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE));
  1417. if ((index > folio->index && index < folio_next_index(folio)) ||
  1418. !IS_ENABLED(CONFIG_THP_SWAP))
  1419. split = true;
  1420. }
  1421. if (split) {
  1422. int order;
  1423. try_split:
  1424. order = folio_order(folio);
  1425. /* Ensure the subpages are still dirty */
  1426. folio_test_set_dirty(folio);
  1427. if (split_folio_to_list(folio, folio_list))
  1428. goto redirty;
  1429. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1430. if (order >= HPAGE_PMD_ORDER) {
  1431. count_memcg_folio_events(folio, THP_SWPOUT_FALLBACK, 1);
  1432. count_vm_event(THP_SWPOUT_FALLBACK);
  1433. }
  1434. #endif
  1435. count_mthp_stat(order, MTHP_STAT_SWPOUT_FALLBACK);
  1436. folio_clear_dirty(folio);
  1437. }
  1438. index = folio->index;
  1439. nr_pages = folio_nr_pages(folio);
  1440. /*
  1441. * This is somewhat ridiculous, but without plumbing a SWAP_MAP_FALLOC
  1442. * value into swapfile.c, the only way we can correctly account for a
  1443. * fallocated folio arriving here is now to initialize it and write it.
  1444. *
  1445. * That's okay for a folio already fallocated earlier, but if we have
  1446. * not yet completed the fallocation, then (a) we want to keep track
  1447. * of this folio in case we have to undo it, and (b) it may not be a
  1448. * good idea to continue anyway, once we're pushing into swap. So
  1449. * reactivate the folio, and let shmem_fallocate() quit when too many.
  1450. */
  1451. if (!folio_test_uptodate(folio)) {
  1452. if (inode->i_private) {
  1453. struct shmem_falloc *shmem_falloc;
  1454. spin_lock(&inode->i_lock);
  1455. shmem_falloc = inode->i_private;
  1456. if (shmem_falloc &&
  1457. !shmem_falloc->waitq &&
  1458. index >= shmem_falloc->start &&
  1459. index < shmem_falloc->next)
  1460. shmem_falloc->nr_unswapped += nr_pages;
  1461. else
  1462. shmem_falloc = NULL;
  1463. spin_unlock(&inode->i_lock);
  1464. if (shmem_falloc)
  1465. goto redirty;
  1466. }
  1467. folio_zero_range(folio, 0, folio_size(folio));
  1468. flush_dcache_folio(folio);
  1469. folio_mark_uptodate(folio);
  1470. }
  1471. if (!folio_alloc_swap(folio)) {
  1472. bool first_swapped = shmem_recalc_inode(inode, 0, nr_pages);
  1473. int error;
  1474. /*
  1475. * Add inode to shmem_unuse()'s list of swapped-out inodes,
  1476. * if it's not already there. Do it now before the folio is
  1477. * removed from page cache, when its pagelock no longer
  1478. * protects the inode from eviction. And do it now, after
  1479. * we've incremented swapped, because shmem_unuse() will
  1480. * prune a !swapped inode from the swaplist.
  1481. */
  1482. if (first_swapped) {
  1483. spin_lock(&shmem_swaplist_lock);
  1484. if (list_empty(&info->swaplist))
  1485. list_add(&info->swaplist, &shmem_swaplist);
  1486. spin_unlock(&shmem_swaplist_lock);
  1487. }
  1488. folio_dup_swap(folio, NULL);
  1489. shmem_delete_from_page_cache(folio, swp_to_radix_entry(folio->swap));
  1490. BUG_ON(folio_mapped(folio));
  1491. error = swap_writeout(folio, plug);
  1492. if (error != AOP_WRITEPAGE_ACTIVATE) {
  1493. /* folio has been unlocked */
  1494. return error;
  1495. }
  1496. /*
  1497. * The intention here is to avoid holding on to the swap when
  1498. * zswap was unable to compress and unable to writeback; but
  1499. * it will be appropriate if other reactivate cases are added.
  1500. */
  1501. error = shmem_add_to_page_cache(folio, mapping, index,
  1502. swp_to_radix_entry(folio->swap),
  1503. __GFP_HIGH | __GFP_NOMEMALLOC | __GFP_NOWARN);
  1504. /* Swap entry might be erased by racing shmem_free_swap() */
  1505. if (!error) {
  1506. shmem_recalc_inode(inode, 0, -nr_pages);
  1507. folio_put_swap(folio, NULL);
  1508. }
  1509. /*
  1510. * The swap_cache_del_folio() below could be left for
  1511. * shrink_folio_list()'s folio_free_swap() to dispose of;
  1512. * but I'm a little nervous about letting this folio out of
  1513. * shmem_writeout() in a hybrid half-tmpfs-half-swap state
  1514. * e.g. folio_mapping(folio) might give an unexpected answer.
  1515. */
  1516. swap_cache_del_folio(folio);
  1517. goto redirty;
  1518. }
  1519. if (nr_pages > 1)
  1520. goto try_split;
  1521. redirty:
  1522. folio_mark_dirty(folio);
  1523. return AOP_WRITEPAGE_ACTIVATE; /* Return with folio locked */
  1524. }
  1525. EXPORT_SYMBOL_GPL(shmem_writeout);
  1526. #if defined(CONFIG_NUMA) && defined(CONFIG_TMPFS)
  1527. static void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  1528. {
  1529. char buffer[64];
  1530. if (!mpol || mpol->mode == MPOL_DEFAULT)
  1531. return; /* show nothing */
  1532. mpol_to_str(buffer, sizeof(buffer), mpol);
  1533. seq_printf(seq, ",mpol=%s", buffer);
  1534. }
  1535. static struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  1536. {
  1537. struct mempolicy *mpol = NULL;
  1538. if (sbinfo->mpol) {
  1539. raw_spin_lock(&sbinfo->stat_lock); /* prevent replace/use races */
  1540. mpol = sbinfo->mpol;
  1541. mpol_get(mpol);
  1542. raw_spin_unlock(&sbinfo->stat_lock);
  1543. }
  1544. return mpol;
  1545. }
  1546. #else /* !CONFIG_NUMA || !CONFIG_TMPFS */
  1547. static inline void shmem_show_mpol(struct seq_file *seq, struct mempolicy *mpol)
  1548. {
  1549. }
  1550. static inline struct mempolicy *shmem_get_sbmpol(struct shmem_sb_info *sbinfo)
  1551. {
  1552. return NULL;
  1553. }
  1554. #endif /* CONFIG_NUMA && CONFIG_TMPFS */
  1555. static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info,
  1556. pgoff_t index, unsigned int order, pgoff_t *ilx);
  1557. static struct folio *shmem_swapin_cluster(swp_entry_t swap, gfp_t gfp,
  1558. struct shmem_inode_info *info, pgoff_t index)
  1559. {
  1560. struct mempolicy *mpol;
  1561. pgoff_t ilx;
  1562. struct folio *folio;
  1563. mpol = shmem_get_pgoff_policy(info, index, 0, &ilx);
  1564. folio = swap_cluster_readahead(swap, gfp, mpol, ilx);
  1565. mpol_cond_put(mpol);
  1566. return folio;
  1567. }
  1568. /*
  1569. * Make sure huge_gfp is always more limited than limit_gfp.
  1570. * Some of the flags set permissions, while others set limitations.
  1571. */
  1572. static gfp_t limit_gfp_mask(gfp_t huge_gfp, gfp_t limit_gfp)
  1573. {
  1574. gfp_t allowflags = __GFP_IO | __GFP_FS | __GFP_RECLAIM;
  1575. gfp_t denyflags = __GFP_NOWARN | __GFP_NORETRY;
  1576. gfp_t zoneflags = limit_gfp & GFP_ZONEMASK;
  1577. gfp_t result = huge_gfp & ~(allowflags | GFP_ZONEMASK);
  1578. /* Allow allocations only from the originally specified zones. */
  1579. result |= zoneflags;
  1580. /*
  1581. * Minimize the result gfp by taking the union with the deny flags,
  1582. * and the intersection of the allow flags.
  1583. */
  1584. result |= (limit_gfp & denyflags);
  1585. result |= (huge_gfp & limit_gfp) & allowflags;
  1586. return result;
  1587. }
  1588. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1589. bool shmem_hpage_pmd_enabled(void)
  1590. {
  1591. if (shmem_huge == SHMEM_HUGE_DENY)
  1592. return false;
  1593. if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_always))
  1594. return true;
  1595. if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_madvise))
  1596. return true;
  1597. if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_within_size))
  1598. return true;
  1599. if (test_bit(HPAGE_PMD_ORDER, &huge_shmem_orders_inherit) &&
  1600. shmem_huge != SHMEM_HUGE_NEVER)
  1601. return true;
  1602. return false;
  1603. }
  1604. unsigned long shmem_allowable_huge_orders(struct inode *inode,
  1605. struct vm_area_struct *vma, pgoff_t index,
  1606. loff_t write_end, bool shmem_huge_force)
  1607. {
  1608. unsigned long mask = READ_ONCE(huge_shmem_orders_always);
  1609. unsigned long within_size_orders = READ_ONCE(huge_shmem_orders_within_size);
  1610. vm_flags_t vm_flags = vma ? vma->vm_flags : 0;
  1611. unsigned int global_orders;
  1612. if (thp_disabled_by_hw() || (vma && vma_thp_disabled(vma, vm_flags, shmem_huge_force)))
  1613. return 0;
  1614. global_orders = shmem_huge_global_enabled(inode, index, write_end,
  1615. shmem_huge_force, vma, vm_flags);
  1616. /* Tmpfs huge pages allocation */
  1617. if (!vma || !vma_is_anon_shmem(vma))
  1618. return global_orders;
  1619. /*
  1620. * Following the 'deny' semantics of the top level, force the huge
  1621. * option off from all mounts.
  1622. */
  1623. if (shmem_huge == SHMEM_HUGE_DENY)
  1624. return 0;
  1625. /*
  1626. * Only allow inherit orders if the top-level value is 'force', which
  1627. * means non-PMD sized THP can not override 'huge' mount option now.
  1628. */
  1629. if (shmem_huge == SHMEM_HUGE_FORCE)
  1630. return READ_ONCE(huge_shmem_orders_inherit);
  1631. /* Allow mTHP that will be fully within i_size. */
  1632. mask |= shmem_get_orders_within_size(inode, within_size_orders, index, 0);
  1633. if (vm_flags & VM_HUGEPAGE)
  1634. mask |= READ_ONCE(huge_shmem_orders_madvise);
  1635. if (global_orders > 0)
  1636. mask |= READ_ONCE(huge_shmem_orders_inherit);
  1637. return THP_ORDERS_ALL_FILE_DEFAULT & mask;
  1638. }
  1639. static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf,
  1640. struct address_space *mapping, pgoff_t index,
  1641. unsigned long orders)
  1642. {
  1643. struct vm_area_struct *vma = vmf ? vmf->vma : NULL;
  1644. pgoff_t aligned_index;
  1645. unsigned long pages;
  1646. int order;
  1647. if (vma) {
  1648. orders = thp_vma_suitable_orders(vma, vmf->address, orders);
  1649. if (!orders)
  1650. return 0;
  1651. }
  1652. /* Find the highest order that can add into the page cache */
  1653. order = highest_order(orders);
  1654. while (orders) {
  1655. pages = 1UL << order;
  1656. aligned_index = round_down(index, pages);
  1657. /*
  1658. * Check for conflict before waiting on a huge allocation.
  1659. * Conflict might be that a huge page has just been allocated
  1660. * and added to page cache by a racing thread, or that there
  1661. * is already at least one small page in the huge extent.
  1662. * Be careful to retry when appropriate, but not forever!
  1663. * Elsewhere -EEXIST would be the right code, but not here.
  1664. */
  1665. if (!xa_find(&mapping->i_pages, &aligned_index,
  1666. aligned_index + pages - 1, XA_PRESENT))
  1667. break;
  1668. order = next_order(&orders, order);
  1669. }
  1670. return orders;
  1671. }
  1672. #else
  1673. static unsigned long shmem_suitable_orders(struct inode *inode, struct vm_fault *vmf,
  1674. struct address_space *mapping, pgoff_t index,
  1675. unsigned long orders)
  1676. {
  1677. return 0;
  1678. }
  1679. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  1680. static struct folio *shmem_alloc_folio(gfp_t gfp, int order,
  1681. struct shmem_inode_info *info, pgoff_t index)
  1682. {
  1683. struct mempolicy *mpol;
  1684. pgoff_t ilx;
  1685. struct folio *folio;
  1686. mpol = shmem_get_pgoff_policy(info, index, order, &ilx);
  1687. folio = folio_alloc_mpol(gfp, order, mpol, ilx, numa_node_id());
  1688. mpol_cond_put(mpol);
  1689. return folio;
  1690. }
  1691. static struct folio *shmem_alloc_and_add_folio(struct vm_fault *vmf,
  1692. gfp_t gfp, struct inode *inode, pgoff_t index,
  1693. struct mm_struct *fault_mm, unsigned long orders)
  1694. {
  1695. struct address_space *mapping = inode->i_mapping;
  1696. struct shmem_inode_info *info = SHMEM_I(inode);
  1697. unsigned long suitable_orders = 0;
  1698. struct folio *folio = NULL;
  1699. pgoff_t aligned_index;
  1700. long pages;
  1701. int error, order;
  1702. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
  1703. orders = 0;
  1704. if (orders > 0) {
  1705. suitable_orders = shmem_suitable_orders(inode, vmf,
  1706. mapping, index, orders);
  1707. order = highest_order(suitable_orders);
  1708. while (suitable_orders) {
  1709. pages = 1UL << order;
  1710. aligned_index = round_down(index, pages);
  1711. folio = shmem_alloc_folio(gfp, order, info, aligned_index);
  1712. if (folio) {
  1713. index = aligned_index;
  1714. goto allocated;
  1715. }
  1716. if (pages == HPAGE_PMD_NR)
  1717. count_vm_event(THP_FILE_FALLBACK);
  1718. count_mthp_stat(order, MTHP_STAT_SHMEM_FALLBACK);
  1719. order = next_order(&suitable_orders, order);
  1720. }
  1721. } else {
  1722. pages = 1;
  1723. folio = shmem_alloc_folio(gfp, 0, info, index);
  1724. }
  1725. if (!folio)
  1726. return ERR_PTR(-ENOMEM);
  1727. allocated:
  1728. __folio_set_locked(folio);
  1729. __folio_set_swapbacked(folio);
  1730. gfp &= GFP_RECLAIM_MASK;
  1731. error = mem_cgroup_charge(folio, fault_mm, gfp);
  1732. if (error) {
  1733. if (xa_find(&mapping->i_pages, &index,
  1734. index + pages - 1, XA_PRESENT)) {
  1735. error = -EEXIST;
  1736. } else if (pages > 1) {
  1737. if (pages == HPAGE_PMD_NR) {
  1738. count_vm_event(THP_FILE_FALLBACK);
  1739. count_vm_event(THP_FILE_FALLBACK_CHARGE);
  1740. }
  1741. count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK);
  1742. count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_FALLBACK_CHARGE);
  1743. }
  1744. goto unlock;
  1745. }
  1746. error = shmem_add_to_page_cache(folio, mapping, index, NULL, gfp);
  1747. if (error)
  1748. goto unlock;
  1749. error = shmem_inode_acct_blocks(inode, pages);
  1750. if (error) {
  1751. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  1752. long freed;
  1753. /*
  1754. * Try to reclaim some space by splitting a few
  1755. * large folios beyond i_size on the filesystem.
  1756. */
  1757. shmem_unused_huge_shrink(sbinfo, NULL, pages);
  1758. /*
  1759. * And do a shmem_recalc_inode() to account for freed pages:
  1760. * except our folio is there in cache, so not quite balanced.
  1761. */
  1762. spin_lock(&info->lock);
  1763. freed = pages + info->alloced - info->swapped -
  1764. READ_ONCE(mapping->nrpages);
  1765. if (freed > 0)
  1766. info->alloced -= freed;
  1767. spin_unlock(&info->lock);
  1768. if (freed > 0)
  1769. shmem_inode_unacct_blocks(inode, freed);
  1770. error = shmem_inode_acct_blocks(inode, pages);
  1771. if (error) {
  1772. filemap_remove_folio(folio);
  1773. goto unlock;
  1774. }
  1775. }
  1776. shmem_recalc_inode(inode, pages, 0);
  1777. folio_add_lru(folio);
  1778. return folio;
  1779. unlock:
  1780. folio_unlock(folio);
  1781. folio_put(folio);
  1782. return ERR_PTR(error);
  1783. }
  1784. static struct folio *shmem_swap_alloc_folio(struct inode *inode,
  1785. struct vm_area_struct *vma, pgoff_t index,
  1786. swp_entry_t entry, int order, gfp_t gfp)
  1787. {
  1788. struct shmem_inode_info *info = SHMEM_I(inode);
  1789. struct folio *new, *swapcache;
  1790. int nr_pages = 1 << order;
  1791. gfp_t alloc_gfp;
  1792. /*
  1793. * We have arrived here because our zones are constrained, so don't
  1794. * limit chance of success with further cpuset and node constraints.
  1795. */
  1796. gfp &= ~GFP_CONSTRAINT_MASK;
  1797. alloc_gfp = gfp;
  1798. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE)) {
  1799. if (WARN_ON_ONCE(order))
  1800. return ERR_PTR(-EINVAL);
  1801. } else if (order) {
  1802. /*
  1803. * If uffd is active for the vma, we need per-page fault
  1804. * fidelity to maintain the uffd semantics, then fallback
  1805. * to swapin order-0 folio, as well as for zswap case.
  1806. * Any existing sub folio in the swap cache also blocks
  1807. * mTHP swapin.
  1808. */
  1809. if ((vma && unlikely(userfaultfd_armed(vma))) ||
  1810. !zswap_never_enabled() ||
  1811. non_swapcache_batch(entry, nr_pages) != nr_pages)
  1812. goto fallback;
  1813. alloc_gfp = limit_gfp_mask(vma_thp_gfp_mask(vma), gfp);
  1814. }
  1815. retry:
  1816. new = shmem_alloc_folio(alloc_gfp, order, info, index);
  1817. if (!new) {
  1818. new = ERR_PTR(-ENOMEM);
  1819. goto fallback;
  1820. }
  1821. if (mem_cgroup_swapin_charge_folio(new, vma ? vma->vm_mm : NULL,
  1822. alloc_gfp, entry)) {
  1823. folio_put(new);
  1824. new = ERR_PTR(-ENOMEM);
  1825. goto fallback;
  1826. }
  1827. swapcache = swapin_folio(entry, new);
  1828. if (swapcache != new) {
  1829. folio_put(new);
  1830. if (!swapcache) {
  1831. /*
  1832. * The new folio is charged already, swapin can
  1833. * only fail due to another raced swapin.
  1834. */
  1835. new = ERR_PTR(-EEXIST);
  1836. goto fallback;
  1837. }
  1838. }
  1839. return swapcache;
  1840. fallback:
  1841. /* Order 0 swapin failed, nothing to fallback to, abort */
  1842. if (!order)
  1843. return new;
  1844. entry.val += index - round_down(index, nr_pages);
  1845. alloc_gfp = gfp;
  1846. nr_pages = 1;
  1847. order = 0;
  1848. goto retry;
  1849. }
  1850. /*
  1851. * When a page is moved from swapcache to shmem filecache (either by the
  1852. * usual swapin of shmem_get_folio_gfp(), or by the less common swapoff of
  1853. * shmem_unuse_inode()), it may have been read in earlier from swap, in
  1854. * ignorance of the mapping it belongs to. If that mapping has special
  1855. * constraints (like the gma500 GEM driver, which requires RAM below 4GB),
  1856. * we may need to copy to a suitable page before moving to filecache.
  1857. *
  1858. * In a future release, this may well be extended to respect cpuset and
  1859. * NUMA mempolicy, and applied also to anonymous pages in do_swap_page();
  1860. * but for now it is a simple matter of zone.
  1861. */
  1862. static bool shmem_should_replace_folio(struct folio *folio, gfp_t gfp)
  1863. {
  1864. return folio_zonenum(folio) > gfp_zone(gfp);
  1865. }
  1866. static int shmem_replace_folio(struct folio **foliop, gfp_t gfp,
  1867. struct shmem_inode_info *info, pgoff_t index,
  1868. struct vm_area_struct *vma)
  1869. {
  1870. struct swap_cluster_info *ci;
  1871. struct folio *new, *old = *foliop;
  1872. swp_entry_t entry = old->swap;
  1873. int nr_pages = folio_nr_pages(old);
  1874. int error = 0;
  1875. /*
  1876. * We have arrived here because our zones are constrained, so don't
  1877. * limit chance of success by further cpuset and node constraints.
  1878. */
  1879. gfp &= ~GFP_CONSTRAINT_MASK;
  1880. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  1881. if (nr_pages > 1) {
  1882. gfp_t huge_gfp = vma_thp_gfp_mask(vma);
  1883. gfp = limit_gfp_mask(huge_gfp, gfp);
  1884. }
  1885. #endif
  1886. new = shmem_alloc_folio(gfp, folio_order(old), info, index);
  1887. if (!new)
  1888. return -ENOMEM;
  1889. folio_ref_add(new, nr_pages);
  1890. folio_copy(new, old);
  1891. flush_dcache_folio(new);
  1892. __folio_set_locked(new);
  1893. __folio_set_swapbacked(new);
  1894. folio_mark_uptodate(new);
  1895. new->swap = entry;
  1896. folio_set_swapcache(new);
  1897. ci = swap_cluster_get_and_lock_irq(old);
  1898. __swap_cache_replace_folio(ci, old, new);
  1899. mem_cgroup_replace_folio(old, new);
  1900. shmem_update_stats(new, nr_pages);
  1901. shmem_update_stats(old, -nr_pages);
  1902. swap_cluster_unlock_irq(ci);
  1903. folio_add_lru(new);
  1904. *foliop = new;
  1905. folio_clear_swapcache(old);
  1906. old->private = NULL;
  1907. folio_unlock(old);
  1908. /*
  1909. * The old folio are removed from swap cache, drop the 'nr_pages'
  1910. * reference, as well as one temporary reference getting from swap
  1911. * cache.
  1912. */
  1913. folio_put_refs(old, nr_pages + 1);
  1914. return error;
  1915. }
  1916. static void shmem_set_folio_swapin_error(struct inode *inode, pgoff_t index,
  1917. struct folio *folio, swp_entry_t swap)
  1918. {
  1919. struct address_space *mapping = inode->i_mapping;
  1920. swp_entry_t swapin_error;
  1921. void *old;
  1922. int nr_pages;
  1923. swapin_error = make_poisoned_swp_entry();
  1924. old = xa_cmpxchg_irq(&mapping->i_pages, index,
  1925. swp_to_radix_entry(swap),
  1926. swp_to_radix_entry(swapin_error), 0);
  1927. if (old != swp_to_radix_entry(swap))
  1928. return;
  1929. nr_pages = folio_nr_pages(folio);
  1930. folio_wait_writeback(folio);
  1931. folio_put_swap(folio, NULL);
  1932. swap_cache_del_folio(folio);
  1933. /*
  1934. * Don't treat swapin error folio as alloced. Otherwise inode->i_blocks
  1935. * won't be 0 when inode is released and thus trigger WARN_ON(i_blocks)
  1936. * in shmem_evict_inode().
  1937. */
  1938. shmem_recalc_inode(inode, -nr_pages, -nr_pages);
  1939. }
  1940. static int shmem_split_large_entry(struct inode *inode, pgoff_t index,
  1941. swp_entry_t swap, gfp_t gfp)
  1942. {
  1943. struct address_space *mapping = inode->i_mapping;
  1944. XA_STATE_ORDER(xas, &mapping->i_pages, index, 0);
  1945. int split_order = 0;
  1946. int i;
  1947. /* Convert user data gfp flags to xarray node gfp flags */
  1948. gfp &= GFP_RECLAIM_MASK;
  1949. for (;;) {
  1950. void *old = NULL;
  1951. int cur_order;
  1952. pgoff_t swap_index;
  1953. xas_lock_irq(&xas);
  1954. old = xas_load(&xas);
  1955. if (!xa_is_value(old) || swp_to_radix_entry(swap) != old) {
  1956. xas_set_err(&xas, -EEXIST);
  1957. goto unlock;
  1958. }
  1959. cur_order = xas_get_order(&xas);
  1960. if (!cur_order)
  1961. goto unlock;
  1962. /* Try to split large swap entry in pagecache */
  1963. swap_index = round_down(index, 1 << cur_order);
  1964. split_order = xas_try_split_min_order(cur_order);
  1965. while (cur_order > 0) {
  1966. pgoff_t aligned_index =
  1967. round_down(index, 1 << cur_order);
  1968. pgoff_t swap_offset = aligned_index - swap_index;
  1969. xas_set_order(&xas, index, split_order);
  1970. xas_try_split(&xas, old, cur_order);
  1971. if (xas_error(&xas))
  1972. goto unlock;
  1973. /*
  1974. * Re-set the swap entry after splitting, and the swap
  1975. * offset of the original large entry must be continuous.
  1976. */
  1977. for (i = 0; i < 1 << cur_order;
  1978. i += (1 << split_order)) {
  1979. swp_entry_t tmp;
  1980. tmp = swp_entry(swp_type(swap),
  1981. swp_offset(swap) + swap_offset +
  1982. i);
  1983. __xa_store(&mapping->i_pages, aligned_index + i,
  1984. swp_to_radix_entry(tmp), 0);
  1985. }
  1986. cur_order = split_order;
  1987. split_order = xas_try_split_min_order(split_order);
  1988. }
  1989. unlock:
  1990. xas_unlock_irq(&xas);
  1991. if (!xas_nomem(&xas, gfp))
  1992. break;
  1993. }
  1994. if (xas_error(&xas))
  1995. return xas_error(&xas);
  1996. return 0;
  1997. }
  1998. /*
  1999. * Swap in the folio pointed to by *foliop.
  2000. * Caller has to make sure that *foliop contains a valid swapped folio.
  2001. * Returns 0 and the folio in foliop if success. On failure, returns the
  2002. * error code and NULL in *foliop.
  2003. */
  2004. static int shmem_swapin_folio(struct inode *inode, pgoff_t index,
  2005. struct folio **foliop, enum sgp_type sgp,
  2006. gfp_t gfp, struct vm_area_struct *vma,
  2007. vm_fault_t *fault_type)
  2008. {
  2009. struct address_space *mapping = inode->i_mapping;
  2010. struct mm_struct *fault_mm = vma ? vma->vm_mm : NULL;
  2011. struct shmem_inode_info *info = SHMEM_I(inode);
  2012. swp_entry_t swap;
  2013. softleaf_t index_entry;
  2014. struct swap_info_struct *si;
  2015. struct folio *folio = NULL;
  2016. int error, nr_pages, order;
  2017. pgoff_t offset;
  2018. VM_BUG_ON(!*foliop || !xa_is_value(*foliop));
  2019. index_entry = radix_to_swp_entry(*foliop);
  2020. swap = index_entry;
  2021. *foliop = NULL;
  2022. if (softleaf_is_poison_marker(index_entry))
  2023. return -EIO;
  2024. si = get_swap_device(index_entry);
  2025. order = shmem_confirm_swap(mapping, index, index_entry);
  2026. if (unlikely(!si)) {
  2027. if (order < 0)
  2028. return -EEXIST;
  2029. else
  2030. return -EINVAL;
  2031. }
  2032. if (unlikely(order < 0)) {
  2033. put_swap_device(si);
  2034. return -EEXIST;
  2035. }
  2036. /* index may point to the middle of a large entry, get the sub entry */
  2037. if (order) {
  2038. offset = index - round_down(index, 1 << order);
  2039. swap = swp_entry(swp_type(swap), swp_offset(swap) + offset);
  2040. }
  2041. /* Look it up and read it in.. */
  2042. folio = swap_cache_get_folio(swap);
  2043. if (!folio) {
  2044. if (data_race(si->flags & SWP_SYNCHRONOUS_IO)) {
  2045. /* Direct swapin skipping swap cache & readahead */
  2046. folio = shmem_swap_alloc_folio(inode, vma, index,
  2047. index_entry, order, gfp);
  2048. if (IS_ERR(folio)) {
  2049. error = PTR_ERR(folio);
  2050. folio = NULL;
  2051. goto failed;
  2052. }
  2053. } else {
  2054. /* Cached swapin only supports order 0 folio */
  2055. folio = shmem_swapin_cluster(swap, gfp, info, index);
  2056. if (!folio) {
  2057. error = -ENOMEM;
  2058. goto failed;
  2059. }
  2060. }
  2061. if (fault_type) {
  2062. *fault_type |= VM_FAULT_MAJOR;
  2063. count_vm_event(PGMAJFAULT);
  2064. count_memcg_event_mm(fault_mm, PGMAJFAULT);
  2065. }
  2066. } else {
  2067. swap_update_readahead(folio, NULL, 0);
  2068. }
  2069. if (order > folio_order(folio)) {
  2070. /*
  2071. * Swapin may get smaller folios due to various reasons:
  2072. * It may fallback to order 0 due to memory pressure or race,
  2073. * swap readahead may swap in order 0 folios into swapcache
  2074. * asynchronously, while the shmem mapping can still stores
  2075. * large swap entries. In such cases, we should split the
  2076. * large swap entry to prevent possible data corruption.
  2077. */
  2078. error = shmem_split_large_entry(inode, index, index_entry, gfp);
  2079. if (error)
  2080. goto failed_nolock;
  2081. }
  2082. /*
  2083. * If the folio is large, round down swap and index by folio size.
  2084. * No matter what race occurs, the swap layer ensures we either get
  2085. * a valid folio that has its swap entry aligned by size, or a
  2086. * temporarily invalid one which we'll abort very soon and retry.
  2087. *
  2088. * shmem_add_to_page_cache ensures the whole range contains expected
  2089. * entries and prevents any corruption, so any race split is fine
  2090. * too, it will succeed as long as the entries are still there.
  2091. */
  2092. nr_pages = folio_nr_pages(folio);
  2093. if (nr_pages > 1) {
  2094. swap.val = round_down(swap.val, nr_pages);
  2095. index = round_down(index, nr_pages);
  2096. }
  2097. /*
  2098. * We have to do this with the folio locked to prevent races.
  2099. * The shmem_confirm_swap below only checks if the first swap
  2100. * entry matches the folio, that's enough to ensure the folio
  2101. * is not used outside of shmem, as shmem swap entries
  2102. * and swap cache folios are never partially freed.
  2103. */
  2104. folio_lock(folio);
  2105. if (!folio_matches_swap_entry(folio, swap) ||
  2106. shmem_confirm_swap(mapping, index, swap) < 0) {
  2107. error = -EEXIST;
  2108. goto unlock;
  2109. }
  2110. if (!folio_test_uptodate(folio)) {
  2111. error = -EIO;
  2112. goto failed;
  2113. }
  2114. folio_wait_writeback(folio);
  2115. /*
  2116. * Some architectures may have to restore extra metadata to the
  2117. * folio after reading from swap.
  2118. */
  2119. arch_swap_restore(folio_swap(swap, folio), folio);
  2120. if (shmem_should_replace_folio(folio, gfp)) {
  2121. error = shmem_replace_folio(&folio, gfp, info, index, vma);
  2122. if (error)
  2123. goto failed;
  2124. }
  2125. error = shmem_add_to_page_cache(folio, mapping, index,
  2126. swp_to_radix_entry(swap), gfp);
  2127. if (error)
  2128. goto failed;
  2129. shmem_recalc_inode(inode, 0, -nr_pages);
  2130. if (sgp == SGP_WRITE)
  2131. folio_mark_accessed(folio);
  2132. folio_put_swap(folio, NULL);
  2133. swap_cache_del_folio(folio);
  2134. folio_mark_dirty(folio);
  2135. put_swap_device(si);
  2136. *foliop = folio;
  2137. return 0;
  2138. failed:
  2139. if (shmem_confirm_swap(mapping, index, swap) < 0)
  2140. error = -EEXIST;
  2141. if (error == -EIO)
  2142. shmem_set_folio_swapin_error(inode, index, folio, swap);
  2143. unlock:
  2144. if (folio)
  2145. folio_unlock(folio);
  2146. failed_nolock:
  2147. if (folio)
  2148. folio_put(folio);
  2149. put_swap_device(si);
  2150. return error;
  2151. }
  2152. /*
  2153. * shmem_get_folio_gfp - find page in cache, or get from swap, or allocate
  2154. *
  2155. * If we allocate a new one we do not mark it dirty. That's up to the
  2156. * vm. If we swap it in we mark it dirty since we also free the swap
  2157. * entry since a page cannot live in both the swap and page cache.
  2158. *
  2159. * vmf and fault_type are only supplied by shmem_fault: otherwise they are NULL.
  2160. */
  2161. static int shmem_get_folio_gfp(struct inode *inode, pgoff_t index,
  2162. loff_t write_end, struct folio **foliop, enum sgp_type sgp,
  2163. gfp_t gfp, struct vm_fault *vmf, vm_fault_t *fault_type)
  2164. {
  2165. struct vm_area_struct *vma = vmf ? vmf->vma : NULL;
  2166. struct mm_struct *fault_mm;
  2167. struct folio *folio;
  2168. int error;
  2169. bool alloced;
  2170. unsigned long orders = 0;
  2171. if (WARN_ON_ONCE(!shmem_mapping(inode->i_mapping)))
  2172. return -EINVAL;
  2173. if (index > (MAX_LFS_FILESIZE >> PAGE_SHIFT))
  2174. return -EFBIG;
  2175. repeat:
  2176. if (sgp <= SGP_CACHE &&
  2177. ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode))
  2178. return -EINVAL;
  2179. alloced = false;
  2180. fault_mm = vma ? vma->vm_mm : NULL;
  2181. folio = filemap_get_entry(inode->i_mapping, index);
  2182. if (folio && vma && userfaultfd_minor(vma)) {
  2183. if (!xa_is_value(folio))
  2184. folio_put(folio);
  2185. *fault_type = handle_userfault(vmf, VM_UFFD_MINOR);
  2186. return 0;
  2187. }
  2188. if (xa_is_value(folio)) {
  2189. error = shmem_swapin_folio(inode, index, &folio,
  2190. sgp, gfp, vma, fault_type);
  2191. if (error == -EEXIST)
  2192. goto repeat;
  2193. *foliop = folio;
  2194. return error;
  2195. }
  2196. if (folio) {
  2197. folio_lock(folio);
  2198. /* Has the folio been truncated or swapped out? */
  2199. if (unlikely(folio->mapping != inode->i_mapping)) {
  2200. folio_unlock(folio);
  2201. folio_put(folio);
  2202. goto repeat;
  2203. }
  2204. if (sgp == SGP_WRITE)
  2205. folio_mark_accessed(folio);
  2206. if (folio_test_uptodate(folio))
  2207. goto out;
  2208. /* fallocated folio */
  2209. if (sgp != SGP_READ)
  2210. goto clear;
  2211. folio_unlock(folio);
  2212. folio_put(folio);
  2213. }
  2214. /*
  2215. * SGP_READ: succeed on hole, with NULL folio, letting caller zero.
  2216. * SGP_NOALLOC: fail on hole, with NULL folio, letting caller fail.
  2217. */
  2218. *foliop = NULL;
  2219. if (sgp == SGP_READ)
  2220. return 0;
  2221. if (sgp == SGP_NOALLOC)
  2222. return -ENOENT;
  2223. /*
  2224. * Fast cache lookup and swap lookup did not find it: allocate.
  2225. */
  2226. if (vma && userfaultfd_missing(vma)) {
  2227. *fault_type = handle_userfault(vmf, VM_UFFD_MISSING);
  2228. return 0;
  2229. }
  2230. /* Find hugepage orders that are allowed for anonymous shmem and tmpfs. */
  2231. orders = shmem_allowable_huge_orders(inode, vma, index, write_end, false);
  2232. if (orders > 0) {
  2233. gfp_t huge_gfp;
  2234. huge_gfp = vma_thp_gfp_mask(vma);
  2235. huge_gfp = limit_gfp_mask(huge_gfp, gfp);
  2236. folio = shmem_alloc_and_add_folio(vmf, huge_gfp,
  2237. inode, index, fault_mm, orders);
  2238. if (!IS_ERR(folio)) {
  2239. if (folio_test_pmd_mappable(folio))
  2240. count_vm_event(THP_FILE_ALLOC);
  2241. count_mthp_stat(folio_order(folio), MTHP_STAT_SHMEM_ALLOC);
  2242. goto alloced;
  2243. }
  2244. if (PTR_ERR(folio) == -EEXIST)
  2245. goto repeat;
  2246. }
  2247. folio = shmem_alloc_and_add_folio(vmf, gfp, inode, index, fault_mm, 0);
  2248. if (IS_ERR(folio)) {
  2249. error = PTR_ERR(folio);
  2250. if (error == -EEXIST)
  2251. goto repeat;
  2252. folio = NULL;
  2253. goto unlock;
  2254. }
  2255. alloced:
  2256. alloced = true;
  2257. if (folio_test_large(folio) &&
  2258. DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE) <
  2259. folio_next_index(folio)) {
  2260. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  2261. struct shmem_inode_info *info = SHMEM_I(inode);
  2262. /*
  2263. * Part of the large folio is beyond i_size: subject
  2264. * to shrink under memory pressure.
  2265. */
  2266. spin_lock(&sbinfo->shrinklist_lock);
  2267. /*
  2268. * _careful to defend against unlocked access to
  2269. * ->shrink_list in shmem_unused_huge_shrink()
  2270. */
  2271. if (list_empty_careful(&info->shrinklist)) {
  2272. list_add_tail(&info->shrinklist,
  2273. &sbinfo->shrinklist);
  2274. sbinfo->shrinklist_len++;
  2275. }
  2276. spin_unlock(&sbinfo->shrinklist_lock);
  2277. }
  2278. if (sgp == SGP_WRITE)
  2279. folio_set_referenced(folio);
  2280. /*
  2281. * Let SGP_FALLOC use the SGP_WRITE optimization on a new folio.
  2282. */
  2283. if (sgp == SGP_FALLOC)
  2284. sgp = SGP_WRITE;
  2285. clear:
  2286. /*
  2287. * Let SGP_WRITE caller clear ends if write does not fill folio;
  2288. * but SGP_FALLOC on a folio fallocated earlier must initialize
  2289. * it now, lest undo on failure cancel our earlier guarantee.
  2290. */
  2291. if (sgp != SGP_WRITE && !folio_test_uptodate(folio)) {
  2292. long i, n = folio_nr_pages(folio);
  2293. for (i = 0; i < n; i++)
  2294. clear_highpage(folio_page(folio, i));
  2295. flush_dcache_folio(folio);
  2296. folio_mark_uptodate(folio);
  2297. }
  2298. /* Perhaps the file has been truncated since we checked */
  2299. if (sgp <= SGP_CACHE &&
  2300. ((loff_t)index << PAGE_SHIFT) >= i_size_read(inode)) {
  2301. error = -EINVAL;
  2302. goto unlock;
  2303. }
  2304. out:
  2305. *foliop = folio;
  2306. return 0;
  2307. /*
  2308. * Error recovery.
  2309. */
  2310. unlock:
  2311. if (alloced)
  2312. filemap_remove_folio(folio);
  2313. shmem_recalc_inode(inode, 0, 0);
  2314. if (folio) {
  2315. folio_unlock(folio);
  2316. folio_put(folio);
  2317. }
  2318. return error;
  2319. }
  2320. /**
  2321. * shmem_get_folio - find, and lock a shmem folio.
  2322. * @inode: inode to search
  2323. * @index: the page index.
  2324. * @write_end: end of a write, could extend inode size
  2325. * @foliop: pointer to the folio if found
  2326. * @sgp: SGP_* flags to control behavior
  2327. *
  2328. * Looks up the page cache entry at @inode & @index. If a folio is
  2329. * present, it is returned locked with an increased refcount.
  2330. *
  2331. * If the caller modifies data in the folio, it must call folio_mark_dirty()
  2332. * before unlocking the folio to ensure that the folio is not reclaimed.
  2333. * There is no need to reserve space before calling folio_mark_dirty().
  2334. *
  2335. * When no folio is found, the behavior depends on @sgp:
  2336. * - for SGP_READ, *@foliop is %NULL and 0 is returned
  2337. * - for SGP_NOALLOC, *@foliop is %NULL and -ENOENT is returned
  2338. * - for all other flags a new folio is allocated, inserted into the
  2339. * page cache and returned locked in @foliop.
  2340. *
  2341. * Context: May sleep.
  2342. * Return: 0 if successful, else a negative error code.
  2343. */
  2344. int shmem_get_folio(struct inode *inode, pgoff_t index, loff_t write_end,
  2345. struct folio **foliop, enum sgp_type sgp)
  2346. {
  2347. return shmem_get_folio_gfp(inode, index, write_end, foliop, sgp,
  2348. mapping_gfp_mask(inode->i_mapping), NULL, NULL);
  2349. }
  2350. EXPORT_SYMBOL_GPL(shmem_get_folio);
  2351. /*
  2352. * This is like autoremove_wake_function, but it removes the wait queue
  2353. * entry unconditionally - even if something else had already woken the
  2354. * target.
  2355. */
  2356. static int synchronous_wake_function(wait_queue_entry_t *wait,
  2357. unsigned int mode, int sync, void *key)
  2358. {
  2359. int ret = default_wake_function(wait, mode, sync, key);
  2360. list_del_init(&wait->entry);
  2361. return ret;
  2362. }
  2363. /*
  2364. * Trinity finds that probing a hole which tmpfs is punching can
  2365. * prevent the hole-punch from ever completing: which in turn
  2366. * locks writers out with its hold on i_rwsem. So refrain from
  2367. * faulting pages into the hole while it's being punched. Although
  2368. * shmem_undo_range() does remove the additions, it may be unable to
  2369. * keep up, as each new page needs its own unmap_mapping_range() call,
  2370. * and the i_mmap tree grows ever slower to scan if new vmas are added.
  2371. *
  2372. * It does not matter if we sometimes reach this check just before the
  2373. * hole-punch begins, so that one fault then races with the punch:
  2374. * we just need to make racing faults a rare case.
  2375. *
  2376. * The implementation below would be much simpler if we just used a
  2377. * standard mutex or completion: but we cannot take i_rwsem in fault,
  2378. * and bloating every shmem inode for this unlikely case would be sad.
  2379. */
  2380. static vm_fault_t shmem_falloc_wait(struct vm_fault *vmf, struct inode *inode)
  2381. {
  2382. struct shmem_falloc *shmem_falloc;
  2383. struct file *fpin = NULL;
  2384. vm_fault_t ret = 0;
  2385. spin_lock(&inode->i_lock);
  2386. shmem_falloc = inode->i_private;
  2387. if (shmem_falloc &&
  2388. shmem_falloc->waitq &&
  2389. vmf->pgoff >= shmem_falloc->start &&
  2390. vmf->pgoff < shmem_falloc->next) {
  2391. wait_queue_head_t *shmem_falloc_waitq;
  2392. DEFINE_WAIT_FUNC(shmem_fault_wait, synchronous_wake_function);
  2393. ret = VM_FAULT_NOPAGE;
  2394. fpin = maybe_unlock_mmap_for_io(vmf, NULL);
  2395. shmem_falloc_waitq = shmem_falloc->waitq;
  2396. prepare_to_wait(shmem_falloc_waitq, &shmem_fault_wait,
  2397. TASK_UNINTERRUPTIBLE);
  2398. spin_unlock(&inode->i_lock);
  2399. schedule();
  2400. /*
  2401. * shmem_falloc_waitq points into the shmem_fallocate()
  2402. * stack of the hole-punching task: shmem_falloc_waitq
  2403. * is usually invalid by the time we reach here, but
  2404. * finish_wait() does not dereference it in that case;
  2405. * though i_lock needed lest racing with wake_up_all().
  2406. */
  2407. spin_lock(&inode->i_lock);
  2408. finish_wait(shmem_falloc_waitq, &shmem_fault_wait);
  2409. }
  2410. spin_unlock(&inode->i_lock);
  2411. if (fpin) {
  2412. fput(fpin);
  2413. ret = VM_FAULT_RETRY;
  2414. }
  2415. return ret;
  2416. }
  2417. static vm_fault_t shmem_fault(struct vm_fault *vmf)
  2418. {
  2419. struct inode *inode = file_inode(vmf->vma->vm_file);
  2420. gfp_t gfp = mapping_gfp_mask(inode->i_mapping);
  2421. struct folio *folio = NULL;
  2422. vm_fault_t ret = 0;
  2423. int err;
  2424. /*
  2425. * Trinity finds that probing a hole which tmpfs is punching can
  2426. * prevent the hole-punch from ever completing: noted in i_private.
  2427. */
  2428. if (unlikely(inode->i_private)) {
  2429. ret = shmem_falloc_wait(vmf, inode);
  2430. if (ret)
  2431. return ret;
  2432. }
  2433. WARN_ON_ONCE(vmf->page != NULL);
  2434. err = shmem_get_folio_gfp(inode, vmf->pgoff, 0, &folio, SGP_CACHE,
  2435. gfp, vmf, &ret);
  2436. if (err)
  2437. return vmf_error(err);
  2438. if (folio) {
  2439. vmf->page = folio_file_page(folio, vmf->pgoff);
  2440. ret |= VM_FAULT_LOCKED;
  2441. }
  2442. return ret;
  2443. }
  2444. unsigned long shmem_get_unmapped_area(struct file *file,
  2445. unsigned long uaddr, unsigned long len,
  2446. unsigned long pgoff, unsigned long flags)
  2447. {
  2448. unsigned long addr;
  2449. unsigned long offset;
  2450. unsigned long inflated_len;
  2451. unsigned long inflated_addr;
  2452. unsigned long inflated_offset;
  2453. unsigned long hpage_size;
  2454. if (len > TASK_SIZE)
  2455. return -ENOMEM;
  2456. addr = mm_get_unmapped_area(file, uaddr, len, pgoff, flags);
  2457. if (!IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE))
  2458. return addr;
  2459. if (IS_ERR_VALUE(addr))
  2460. return addr;
  2461. if (addr & ~PAGE_MASK)
  2462. return addr;
  2463. if (addr > TASK_SIZE - len)
  2464. return addr;
  2465. if (shmem_huge == SHMEM_HUGE_DENY)
  2466. return addr;
  2467. if (flags & MAP_FIXED)
  2468. return addr;
  2469. /*
  2470. * Our priority is to support MAP_SHARED mapped hugely;
  2471. * and support MAP_PRIVATE mapped hugely too, until it is COWed.
  2472. * But if caller specified an address hint and we allocated area there
  2473. * successfully, respect that as before.
  2474. */
  2475. if (uaddr == addr)
  2476. return addr;
  2477. hpage_size = HPAGE_PMD_SIZE;
  2478. if (shmem_huge != SHMEM_HUGE_FORCE) {
  2479. struct super_block *sb;
  2480. unsigned long __maybe_unused hpage_orders;
  2481. int order = 0;
  2482. if (file) {
  2483. VM_BUG_ON(file->f_op != &shmem_file_operations);
  2484. sb = file_inode(file)->i_sb;
  2485. } else {
  2486. /*
  2487. * Called directly from mm/mmap.c, or drivers/char/mem.c
  2488. * for "/dev/zero", to create a shared anonymous object.
  2489. */
  2490. if (IS_ERR(shm_mnt))
  2491. return addr;
  2492. sb = shm_mnt->mnt_sb;
  2493. /*
  2494. * Find the highest mTHP order used for anonymous shmem to
  2495. * provide a suitable alignment address.
  2496. */
  2497. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  2498. hpage_orders = READ_ONCE(huge_shmem_orders_always);
  2499. hpage_orders |= READ_ONCE(huge_shmem_orders_within_size);
  2500. hpage_orders |= READ_ONCE(huge_shmem_orders_madvise);
  2501. if (SHMEM_SB(sb)->huge != SHMEM_HUGE_NEVER)
  2502. hpage_orders |= READ_ONCE(huge_shmem_orders_inherit);
  2503. if (hpage_orders > 0) {
  2504. order = highest_order(hpage_orders);
  2505. hpage_size = PAGE_SIZE << order;
  2506. }
  2507. #endif
  2508. }
  2509. if (SHMEM_SB(sb)->huge == SHMEM_HUGE_NEVER && !order)
  2510. return addr;
  2511. }
  2512. if (len < hpage_size)
  2513. return addr;
  2514. offset = (pgoff << PAGE_SHIFT) & (hpage_size - 1);
  2515. if (offset && offset + len < 2 * hpage_size)
  2516. return addr;
  2517. if ((addr & (hpage_size - 1)) == offset)
  2518. return addr;
  2519. inflated_len = len + hpage_size - PAGE_SIZE;
  2520. if (inflated_len > TASK_SIZE)
  2521. return addr;
  2522. if (inflated_len < len)
  2523. return addr;
  2524. inflated_addr = mm_get_unmapped_area(NULL, uaddr, inflated_len, 0, flags);
  2525. if (IS_ERR_VALUE(inflated_addr))
  2526. return addr;
  2527. if (inflated_addr & ~PAGE_MASK)
  2528. return addr;
  2529. inflated_offset = inflated_addr & (hpage_size - 1);
  2530. inflated_addr += offset - inflated_offset;
  2531. if (inflated_offset > offset)
  2532. inflated_addr += hpage_size;
  2533. if (inflated_addr > TASK_SIZE - len)
  2534. return addr;
  2535. return inflated_addr;
  2536. }
  2537. #ifdef CONFIG_NUMA
  2538. static int shmem_set_policy(struct vm_area_struct *vma, struct mempolicy *mpol)
  2539. {
  2540. struct inode *inode = file_inode(vma->vm_file);
  2541. return mpol_set_shared_policy(&SHMEM_I(inode)->policy, vma, mpol);
  2542. }
  2543. static struct mempolicy *shmem_get_policy(struct vm_area_struct *vma,
  2544. unsigned long addr, pgoff_t *ilx)
  2545. {
  2546. struct inode *inode = file_inode(vma->vm_file);
  2547. pgoff_t index;
  2548. /*
  2549. * Bias interleave by inode number to distribute better across nodes;
  2550. * but this interface is independent of which page order is used, so
  2551. * supplies only that bias, letting caller apply the offset (adjusted
  2552. * by page order, as in shmem_get_pgoff_policy() and get_vma_policy()).
  2553. */
  2554. *ilx = inode->i_ino;
  2555. index = ((addr - vma->vm_start) >> PAGE_SHIFT) + vma->vm_pgoff;
  2556. return mpol_shared_policy_lookup(&SHMEM_I(inode)->policy, index);
  2557. }
  2558. static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info,
  2559. pgoff_t index, unsigned int order, pgoff_t *ilx)
  2560. {
  2561. struct mempolicy *mpol;
  2562. /* Bias interleave by inode number to distribute better across nodes */
  2563. *ilx = info->vfs_inode.i_ino + (index >> order);
  2564. mpol = mpol_shared_policy_lookup(&info->policy, index);
  2565. return mpol ? mpol : get_task_policy(current);
  2566. }
  2567. #else
  2568. static struct mempolicy *shmem_get_pgoff_policy(struct shmem_inode_info *info,
  2569. pgoff_t index, unsigned int order, pgoff_t *ilx)
  2570. {
  2571. *ilx = 0;
  2572. return NULL;
  2573. }
  2574. #endif /* CONFIG_NUMA */
  2575. int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
  2576. {
  2577. struct inode *inode = file_inode(file);
  2578. struct shmem_inode_info *info = SHMEM_I(inode);
  2579. int retval = -ENOMEM;
  2580. /*
  2581. * What serializes the accesses to info->flags?
  2582. * ipc_lock_object() when called from shmctl_do_lock(),
  2583. * no serialization needed when called from shm_destroy().
  2584. */
  2585. if (lock && !(info->flags & SHMEM_F_LOCKED)) {
  2586. if (!user_shm_lock(inode->i_size, ucounts))
  2587. goto out_nomem;
  2588. info->flags |= SHMEM_F_LOCKED;
  2589. mapping_set_unevictable(file->f_mapping);
  2590. }
  2591. if (!lock && (info->flags & SHMEM_F_LOCKED) && ucounts) {
  2592. user_shm_unlock(inode->i_size, ucounts);
  2593. info->flags &= ~SHMEM_F_LOCKED;
  2594. mapping_clear_unevictable(file->f_mapping);
  2595. }
  2596. retval = 0;
  2597. out_nomem:
  2598. return retval;
  2599. }
  2600. static int shmem_mmap_prepare(struct vm_area_desc *desc)
  2601. {
  2602. struct file *file = desc->file;
  2603. struct inode *inode = file_inode(file);
  2604. file_accessed(file);
  2605. /* This is anonymous shared memory if it is unlinked at the time of mmap */
  2606. if (inode->i_nlink)
  2607. desc->vm_ops = &shmem_vm_ops;
  2608. else
  2609. desc->vm_ops = &shmem_anon_vm_ops;
  2610. return 0;
  2611. }
  2612. static int shmem_file_open(struct inode *inode, struct file *file)
  2613. {
  2614. file->f_mode |= FMODE_CAN_ODIRECT;
  2615. return generic_file_open(inode, file);
  2616. }
  2617. #ifdef CONFIG_TMPFS_XATTR
  2618. static int shmem_initxattrs(struct inode *, const struct xattr *, void *);
  2619. #if IS_ENABLED(CONFIG_UNICODE)
  2620. /*
  2621. * shmem_inode_casefold_flags - Deal with casefold file attribute flag
  2622. *
  2623. * The casefold file attribute needs some special checks. I can just be added to
  2624. * an empty dir, and can't be removed from a non-empty dir.
  2625. */
  2626. static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags,
  2627. struct dentry *dentry, unsigned int *i_flags)
  2628. {
  2629. unsigned int old = inode->i_flags;
  2630. struct super_block *sb = inode->i_sb;
  2631. if (fsflags & FS_CASEFOLD_FL) {
  2632. if (!(old & S_CASEFOLD)) {
  2633. if (!sb->s_encoding)
  2634. return -EOPNOTSUPP;
  2635. if (!S_ISDIR(inode->i_mode))
  2636. return -ENOTDIR;
  2637. if (dentry && !simple_empty(dentry))
  2638. return -ENOTEMPTY;
  2639. }
  2640. *i_flags = *i_flags | S_CASEFOLD;
  2641. } else if (old & S_CASEFOLD) {
  2642. if (dentry && !simple_empty(dentry))
  2643. return -ENOTEMPTY;
  2644. }
  2645. return 0;
  2646. }
  2647. #else
  2648. static int shmem_inode_casefold_flags(struct inode *inode, unsigned int fsflags,
  2649. struct dentry *dentry, unsigned int *i_flags)
  2650. {
  2651. if (fsflags & FS_CASEFOLD_FL)
  2652. return -EOPNOTSUPP;
  2653. return 0;
  2654. }
  2655. #endif
  2656. /*
  2657. * chattr's fsflags are unrelated to extended attributes,
  2658. * but tmpfs has chosen to enable them under the same config option.
  2659. */
  2660. static int shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry)
  2661. {
  2662. unsigned int i_flags = 0;
  2663. int ret;
  2664. ret = shmem_inode_casefold_flags(inode, fsflags, dentry, &i_flags);
  2665. if (ret)
  2666. return ret;
  2667. if (fsflags & FS_NOATIME_FL)
  2668. i_flags |= S_NOATIME;
  2669. if (fsflags & FS_APPEND_FL)
  2670. i_flags |= S_APPEND;
  2671. if (fsflags & FS_IMMUTABLE_FL)
  2672. i_flags |= S_IMMUTABLE;
  2673. /*
  2674. * But FS_NODUMP_FL does not require any action in i_flags.
  2675. */
  2676. inode_set_flags(inode, i_flags, S_NOATIME | S_APPEND | S_IMMUTABLE | S_CASEFOLD);
  2677. return 0;
  2678. }
  2679. #else
  2680. static void shmem_set_inode_flags(struct inode *inode, unsigned int fsflags, struct dentry *dentry)
  2681. {
  2682. }
  2683. #define shmem_initxattrs NULL
  2684. #endif
  2685. static struct offset_ctx *shmem_get_offset_ctx(struct inode *inode)
  2686. {
  2687. return &SHMEM_I(inode)->dir_offsets;
  2688. }
  2689. static struct inode *__shmem_get_inode(struct mnt_idmap *idmap,
  2690. struct super_block *sb,
  2691. struct inode *dir, umode_t mode,
  2692. dev_t dev, vma_flags_t flags)
  2693. {
  2694. struct inode *inode;
  2695. struct shmem_inode_info *info;
  2696. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  2697. ino_t ino;
  2698. int err;
  2699. err = shmem_reserve_inode(sb, &ino);
  2700. if (err)
  2701. return ERR_PTR(err);
  2702. inode = new_inode(sb);
  2703. if (!inode) {
  2704. shmem_free_inode(sb, 0);
  2705. return ERR_PTR(-ENOSPC);
  2706. }
  2707. inode->i_ino = ino;
  2708. inode_init_owner(idmap, inode, dir, mode);
  2709. inode->i_blocks = 0;
  2710. simple_inode_init_ts(inode);
  2711. inode->i_generation = get_random_u32();
  2712. info = SHMEM_I(inode);
  2713. memset(info, 0, (char *)inode - (char *)info);
  2714. spin_lock_init(&info->lock);
  2715. atomic_set(&info->stop_eviction, 0);
  2716. info->seals = F_SEAL_SEAL;
  2717. info->flags = vma_flags_test(&flags, VMA_NORESERVE_BIT)
  2718. ? SHMEM_F_NORESERVE : 0;
  2719. info->i_crtime = inode_get_mtime(inode);
  2720. info->fsflags = (dir == NULL) ? 0 :
  2721. SHMEM_I(dir)->fsflags & SHMEM_FL_INHERITED;
  2722. if (info->fsflags)
  2723. shmem_set_inode_flags(inode, info->fsflags, NULL);
  2724. INIT_LIST_HEAD(&info->shrinklist);
  2725. INIT_LIST_HEAD(&info->swaplist);
  2726. simple_xattrs_init(&info->xattrs);
  2727. cache_no_acl(inode);
  2728. if (sbinfo->noswap)
  2729. mapping_set_unevictable(inode->i_mapping);
  2730. /* Don't consider 'deny' for emergencies and 'force' for testing */
  2731. if (sbinfo->huge)
  2732. mapping_set_large_folios(inode->i_mapping);
  2733. switch (mode & S_IFMT) {
  2734. default:
  2735. inode->i_op = &shmem_special_inode_operations;
  2736. init_special_inode(inode, mode, dev);
  2737. break;
  2738. case S_IFREG:
  2739. inode->i_mapping->a_ops = &shmem_aops;
  2740. inode->i_op = &shmem_inode_operations;
  2741. inode->i_fop = &shmem_file_operations;
  2742. mpol_shared_policy_init(&info->policy,
  2743. shmem_get_sbmpol(sbinfo));
  2744. break;
  2745. case S_IFDIR:
  2746. inc_nlink(inode);
  2747. /* Some things misbehave if size == 0 on a directory */
  2748. inode->i_size = 2 * BOGO_DIRENT_SIZE;
  2749. inode->i_op = &shmem_dir_inode_operations;
  2750. inode->i_fop = &simple_offset_dir_operations;
  2751. simple_offset_init(shmem_get_offset_ctx(inode));
  2752. break;
  2753. case S_IFLNK:
  2754. /*
  2755. * Must not load anything in the rbtree,
  2756. * mpol_free_shared_policy will not be called.
  2757. */
  2758. mpol_shared_policy_init(&info->policy, NULL);
  2759. break;
  2760. }
  2761. lockdep_annotate_inode_mutex_key(inode);
  2762. return inode;
  2763. }
  2764. #ifdef CONFIG_TMPFS_QUOTA
  2765. static struct inode *shmem_get_inode(struct mnt_idmap *idmap,
  2766. struct super_block *sb, struct inode *dir,
  2767. umode_t mode, dev_t dev, vma_flags_t flags)
  2768. {
  2769. int err;
  2770. struct inode *inode;
  2771. inode = __shmem_get_inode(idmap, sb, dir, mode, dev, flags);
  2772. if (IS_ERR(inode))
  2773. return inode;
  2774. err = dquot_initialize(inode);
  2775. if (err)
  2776. goto errout;
  2777. err = dquot_alloc_inode(inode);
  2778. if (err) {
  2779. dquot_drop(inode);
  2780. goto errout;
  2781. }
  2782. return inode;
  2783. errout:
  2784. inode->i_flags |= S_NOQUOTA;
  2785. iput(inode);
  2786. return ERR_PTR(err);
  2787. }
  2788. #else
  2789. static struct inode *shmem_get_inode(struct mnt_idmap *idmap,
  2790. struct super_block *sb, struct inode *dir,
  2791. umode_t mode, dev_t dev, vma_flags_t flags)
  2792. {
  2793. return __shmem_get_inode(idmap, sb, dir, mode, dev, flags);
  2794. }
  2795. #endif /* CONFIG_TMPFS_QUOTA */
  2796. #ifdef CONFIG_USERFAULTFD
  2797. int shmem_mfill_atomic_pte(pmd_t *dst_pmd,
  2798. struct vm_area_struct *dst_vma,
  2799. unsigned long dst_addr,
  2800. unsigned long src_addr,
  2801. uffd_flags_t flags,
  2802. struct folio **foliop)
  2803. {
  2804. struct inode *inode = file_inode(dst_vma->vm_file);
  2805. struct shmem_inode_info *info = SHMEM_I(inode);
  2806. struct address_space *mapping = inode->i_mapping;
  2807. gfp_t gfp = mapping_gfp_mask(mapping);
  2808. pgoff_t pgoff = linear_page_index(dst_vma, dst_addr);
  2809. void *page_kaddr;
  2810. struct folio *folio;
  2811. int ret;
  2812. pgoff_t max_off;
  2813. if (shmem_inode_acct_blocks(inode, 1)) {
  2814. /*
  2815. * We may have got a page, returned -ENOENT triggering a retry,
  2816. * and now we find ourselves with -ENOMEM. Release the page, to
  2817. * avoid a BUG_ON in our caller.
  2818. */
  2819. if (unlikely(*foliop)) {
  2820. folio_put(*foliop);
  2821. *foliop = NULL;
  2822. }
  2823. return -ENOMEM;
  2824. }
  2825. if (!*foliop) {
  2826. ret = -ENOMEM;
  2827. folio = shmem_alloc_folio(gfp, 0, info, pgoff);
  2828. if (!folio)
  2829. goto out_unacct_blocks;
  2830. if (uffd_flags_mode_is(flags, MFILL_ATOMIC_COPY)) {
  2831. page_kaddr = kmap_local_folio(folio, 0);
  2832. /*
  2833. * The read mmap_lock is held here. Despite the
  2834. * mmap_lock being read recursive a deadlock is still
  2835. * possible if a writer has taken a lock. For example:
  2836. *
  2837. * process A thread 1 takes read lock on own mmap_lock
  2838. * process A thread 2 calls mmap, blocks taking write lock
  2839. * process B thread 1 takes page fault, read lock on own mmap lock
  2840. * process B thread 2 calls mmap, blocks taking write lock
  2841. * process A thread 1 blocks taking read lock on process B
  2842. * process B thread 1 blocks taking read lock on process A
  2843. *
  2844. * Disable page faults to prevent potential deadlock
  2845. * and retry the copy outside the mmap_lock.
  2846. */
  2847. pagefault_disable();
  2848. ret = copy_from_user(page_kaddr,
  2849. (const void __user *)src_addr,
  2850. PAGE_SIZE);
  2851. pagefault_enable();
  2852. kunmap_local(page_kaddr);
  2853. /* fallback to copy_from_user outside mmap_lock */
  2854. if (unlikely(ret)) {
  2855. *foliop = folio;
  2856. ret = -ENOENT;
  2857. /* don't free the page */
  2858. goto out_unacct_blocks;
  2859. }
  2860. flush_dcache_folio(folio);
  2861. } else { /* ZEROPAGE */
  2862. clear_user_highpage(&folio->page, dst_addr);
  2863. }
  2864. } else {
  2865. folio = *foliop;
  2866. VM_BUG_ON_FOLIO(folio_test_large(folio), folio);
  2867. *foliop = NULL;
  2868. }
  2869. VM_BUG_ON(folio_test_locked(folio));
  2870. VM_BUG_ON(folio_test_swapbacked(folio));
  2871. __folio_set_locked(folio);
  2872. __folio_set_swapbacked(folio);
  2873. __folio_mark_uptodate(folio);
  2874. ret = -EFAULT;
  2875. max_off = DIV_ROUND_UP(i_size_read(inode), PAGE_SIZE);
  2876. if (unlikely(pgoff >= max_off))
  2877. goto out_release;
  2878. ret = mem_cgroup_charge(folio, dst_vma->vm_mm, gfp);
  2879. if (ret)
  2880. goto out_release;
  2881. ret = shmem_add_to_page_cache(folio, mapping, pgoff, NULL, gfp);
  2882. if (ret)
  2883. goto out_release;
  2884. ret = mfill_atomic_install_pte(dst_pmd, dst_vma, dst_addr,
  2885. &folio->page, true, flags);
  2886. if (ret)
  2887. goto out_delete_from_cache;
  2888. shmem_recalc_inode(inode, 1, 0);
  2889. folio_unlock(folio);
  2890. return 0;
  2891. out_delete_from_cache:
  2892. filemap_remove_folio(folio);
  2893. out_release:
  2894. folio_unlock(folio);
  2895. folio_put(folio);
  2896. out_unacct_blocks:
  2897. shmem_inode_unacct_blocks(inode, 1);
  2898. return ret;
  2899. }
  2900. #endif /* CONFIG_USERFAULTFD */
  2901. #ifdef CONFIG_TMPFS
  2902. static const struct inode_operations shmem_symlink_inode_operations;
  2903. static const struct inode_operations shmem_short_symlink_operations;
  2904. static int
  2905. shmem_write_begin(const struct kiocb *iocb, struct address_space *mapping,
  2906. loff_t pos, unsigned len,
  2907. struct folio **foliop, void **fsdata)
  2908. {
  2909. struct inode *inode = mapping->host;
  2910. struct shmem_inode_info *info = SHMEM_I(inode);
  2911. pgoff_t index = pos >> PAGE_SHIFT;
  2912. struct folio *folio;
  2913. int ret = 0;
  2914. /* i_rwsem is held by caller */
  2915. if (unlikely(info->seals & (F_SEAL_GROW |
  2916. F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))) {
  2917. if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE))
  2918. return -EPERM;
  2919. if ((info->seals & F_SEAL_GROW) && pos + len > inode->i_size)
  2920. return -EPERM;
  2921. }
  2922. if (unlikely((info->flags & SHMEM_F_MAPPING_FROZEN) &&
  2923. pos + len > inode->i_size))
  2924. return -EPERM;
  2925. ret = shmem_get_folio(inode, index, pos + len, &folio, SGP_WRITE);
  2926. if (ret)
  2927. return ret;
  2928. if (folio_contain_hwpoisoned_page(folio)) {
  2929. folio_unlock(folio);
  2930. folio_put(folio);
  2931. return -EIO;
  2932. }
  2933. *foliop = folio;
  2934. return 0;
  2935. }
  2936. static int
  2937. shmem_write_end(const struct kiocb *iocb, struct address_space *mapping,
  2938. loff_t pos, unsigned len, unsigned copied,
  2939. struct folio *folio, void *fsdata)
  2940. {
  2941. struct inode *inode = mapping->host;
  2942. if (pos + copied > inode->i_size)
  2943. i_size_write(inode, pos + copied);
  2944. if (!folio_test_uptodate(folio)) {
  2945. if (copied < folio_size(folio)) {
  2946. size_t from = offset_in_folio(folio, pos);
  2947. folio_zero_segments(folio, 0, from,
  2948. from + copied, folio_size(folio));
  2949. }
  2950. folio_mark_uptodate(folio);
  2951. }
  2952. folio_mark_dirty(folio);
  2953. folio_unlock(folio);
  2954. folio_put(folio);
  2955. return copied;
  2956. }
  2957. static ssize_t shmem_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
  2958. {
  2959. struct file *file = iocb->ki_filp;
  2960. struct inode *inode = file_inode(file);
  2961. struct address_space *mapping = inode->i_mapping;
  2962. pgoff_t index;
  2963. unsigned long offset;
  2964. int error = 0;
  2965. ssize_t retval = 0;
  2966. for (;;) {
  2967. struct folio *folio = NULL;
  2968. struct page *page = NULL;
  2969. unsigned long nr, ret;
  2970. loff_t end_offset, i_size = i_size_read(inode);
  2971. bool fallback_page_copy = false;
  2972. size_t fsize;
  2973. if (unlikely(iocb->ki_pos >= i_size))
  2974. break;
  2975. index = iocb->ki_pos >> PAGE_SHIFT;
  2976. error = shmem_get_folio(inode, index, 0, &folio, SGP_READ);
  2977. if (error) {
  2978. if (error == -EINVAL)
  2979. error = 0;
  2980. break;
  2981. }
  2982. if (folio) {
  2983. folio_unlock(folio);
  2984. page = folio_file_page(folio, index);
  2985. if (PageHWPoison(page)) {
  2986. folio_put(folio);
  2987. error = -EIO;
  2988. break;
  2989. }
  2990. if (folio_test_large(folio) &&
  2991. folio_test_has_hwpoisoned(folio))
  2992. fallback_page_copy = true;
  2993. }
  2994. /*
  2995. * We must evaluate after, since reads (unlike writes)
  2996. * are called without i_rwsem protection against truncate
  2997. */
  2998. i_size = i_size_read(inode);
  2999. if (unlikely(iocb->ki_pos >= i_size)) {
  3000. if (folio)
  3001. folio_put(folio);
  3002. break;
  3003. }
  3004. end_offset = min_t(loff_t, i_size, iocb->ki_pos + to->count);
  3005. if (folio && likely(!fallback_page_copy))
  3006. fsize = folio_size(folio);
  3007. else
  3008. fsize = PAGE_SIZE;
  3009. offset = iocb->ki_pos & (fsize - 1);
  3010. nr = min_t(loff_t, end_offset - iocb->ki_pos, fsize - offset);
  3011. if (folio) {
  3012. /*
  3013. * If users can be writing to this page using arbitrary
  3014. * virtual addresses, take care about potential aliasing
  3015. * before reading the page on the kernel side.
  3016. */
  3017. if (mapping_writably_mapped(mapping)) {
  3018. if (likely(!fallback_page_copy))
  3019. flush_dcache_folio(folio);
  3020. else
  3021. flush_dcache_page(page);
  3022. }
  3023. /*
  3024. * Mark the folio accessed if we read the beginning.
  3025. */
  3026. if (!offset)
  3027. folio_mark_accessed(folio);
  3028. /*
  3029. * Ok, we have the page, and it's up-to-date, so
  3030. * now we can copy it to user space...
  3031. */
  3032. if (likely(!fallback_page_copy))
  3033. ret = copy_folio_to_iter(folio, offset, nr, to);
  3034. else
  3035. ret = copy_page_to_iter(page, offset, nr, to);
  3036. folio_put(folio);
  3037. } else if (user_backed_iter(to)) {
  3038. /*
  3039. * Copy to user tends to be so well optimized, but
  3040. * clear_user() not so much, that it is noticeably
  3041. * faster to copy the zero page instead of clearing.
  3042. */
  3043. ret = copy_page_to_iter(ZERO_PAGE(0), offset, nr, to);
  3044. } else {
  3045. /*
  3046. * But submitting the same page twice in a row to
  3047. * splice() - or others? - can result in confusion:
  3048. * so don't attempt that optimization on pipes etc.
  3049. */
  3050. ret = iov_iter_zero(nr, to);
  3051. }
  3052. retval += ret;
  3053. iocb->ki_pos += ret;
  3054. if (!iov_iter_count(to))
  3055. break;
  3056. if (ret < nr) {
  3057. error = -EFAULT;
  3058. break;
  3059. }
  3060. cond_resched();
  3061. }
  3062. file_accessed(file);
  3063. return retval ? retval : error;
  3064. }
  3065. static ssize_t shmem_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
  3066. {
  3067. struct file *file = iocb->ki_filp;
  3068. struct inode *inode = file->f_mapping->host;
  3069. ssize_t ret;
  3070. inode_lock(inode);
  3071. ret = generic_write_checks(iocb, from);
  3072. if (ret <= 0)
  3073. goto unlock;
  3074. ret = file_remove_privs(file);
  3075. if (ret)
  3076. goto unlock;
  3077. ret = file_update_time(file);
  3078. if (ret)
  3079. goto unlock;
  3080. ret = generic_perform_write(iocb, from);
  3081. unlock:
  3082. inode_unlock(inode);
  3083. return ret;
  3084. }
  3085. static bool zero_pipe_buf_get(struct pipe_inode_info *pipe,
  3086. struct pipe_buffer *buf)
  3087. {
  3088. return true;
  3089. }
  3090. static void zero_pipe_buf_release(struct pipe_inode_info *pipe,
  3091. struct pipe_buffer *buf)
  3092. {
  3093. }
  3094. static bool zero_pipe_buf_try_steal(struct pipe_inode_info *pipe,
  3095. struct pipe_buffer *buf)
  3096. {
  3097. return false;
  3098. }
  3099. static const struct pipe_buf_operations zero_pipe_buf_ops = {
  3100. .release = zero_pipe_buf_release,
  3101. .try_steal = zero_pipe_buf_try_steal,
  3102. .get = zero_pipe_buf_get,
  3103. };
  3104. static size_t splice_zeropage_into_pipe(struct pipe_inode_info *pipe,
  3105. loff_t fpos, size_t size)
  3106. {
  3107. size_t offset = fpos & ~PAGE_MASK;
  3108. size = min_t(size_t, size, PAGE_SIZE - offset);
  3109. if (!pipe_is_full(pipe)) {
  3110. struct pipe_buffer *buf = pipe_head_buf(pipe);
  3111. *buf = (struct pipe_buffer) {
  3112. .ops = &zero_pipe_buf_ops,
  3113. .page = ZERO_PAGE(0),
  3114. .offset = offset,
  3115. .len = size,
  3116. };
  3117. pipe->head++;
  3118. }
  3119. return size;
  3120. }
  3121. static ssize_t shmem_file_splice_read(struct file *in, loff_t *ppos,
  3122. struct pipe_inode_info *pipe,
  3123. size_t len, unsigned int flags)
  3124. {
  3125. struct inode *inode = file_inode(in);
  3126. struct address_space *mapping = inode->i_mapping;
  3127. struct folio *folio = NULL;
  3128. size_t total_spliced = 0, used, npages, n, part;
  3129. loff_t isize;
  3130. int error = 0;
  3131. /* Work out how much data we can actually add into the pipe */
  3132. used = pipe_buf_usage(pipe);
  3133. npages = max_t(ssize_t, pipe->max_usage - used, 0);
  3134. len = min_t(size_t, len, npages * PAGE_SIZE);
  3135. do {
  3136. bool fallback_page_splice = false;
  3137. struct page *page = NULL;
  3138. pgoff_t index;
  3139. size_t size;
  3140. if (*ppos >= i_size_read(inode))
  3141. break;
  3142. index = *ppos >> PAGE_SHIFT;
  3143. error = shmem_get_folio(inode, index, 0, &folio, SGP_READ);
  3144. if (error) {
  3145. if (error == -EINVAL)
  3146. error = 0;
  3147. break;
  3148. }
  3149. if (folio) {
  3150. folio_unlock(folio);
  3151. page = folio_file_page(folio, index);
  3152. if (PageHWPoison(page)) {
  3153. error = -EIO;
  3154. break;
  3155. }
  3156. if (folio_test_large(folio) &&
  3157. folio_test_has_hwpoisoned(folio))
  3158. fallback_page_splice = true;
  3159. }
  3160. /*
  3161. * i_size must be checked after we know the pages are Uptodate.
  3162. *
  3163. * Checking i_size after the check allows us to calculate
  3164. * the correct value for "nr", which means the zero-filled
  3165. * part of the page is not copied back to userspace (unless
  3166. * another truncate extends the file - this is desired though).
  3167. */
  3168. isize = i_size_read(inode);
  3169. if (unlikely(*ppos >= isize))
  3170. break;
  3171. /*
  3172. * Fallback to PAGE_SIZE splice if the large folio has hwpoisoned
  3173. * pages.
  3174. */
  3175. size = len;
  3176. if (unlikely(fallback_page_splice)) {
  3177. size_t offset = *ppos & ~PAGE_MASK;
  3178. size = umin(size, PAGE_SIZE - offset);
  3179. }
  3180. part = min_t(loff_t, isize - *ppos, size);
  3181. if (folio) {
  3182. /*
  3183. * If users can be writing to this page using arbitrary
  3184. * virtual addresses, take care about potential aliasing
  3185. * before reading the page on the kernel side.
  3186. */
  3187. if (mapping_writably_mapped(mapping)) {
  3188. if (likely(!fallback_page_splice))
  3189. flush_dcache_folio(folio);
  3190. else
  3191. flush_dcache_page(page);
  3192. }
  3193. folio_mark_accessed(folio);
  3194. /*
  3195. * Ok, we have the page, and it's up-to-date, so we can
  3196. * now splice it into the pipe.
  3197. */
  3198. n = splice_folio_into_pipe(pipe, folio, *ppos, part);
  3199. folio_put(folio);
  3200. folio = NULL;
  3201. } else {
  3202. n = splice_zeropage_into_pipe(pipe, *ppos, part);
  3203. }
  3204. if (!n)
  3205. break;
  3206. len -= n;
  3207. total_spliced += n;
  3208. *ppos += n;
  3209. in->f_ra.prev_pos = *ppos;
  3210. if (pipe_is_full(pipe))
  3211. break;
  3212. cond_resched();
  3213. } while (len);
  3214. if (folio)
  3215. folio_put(folio);
  3216. file_accessed(in);
  3217. return total_spliced ? total_spliced : error;
  3218. }
  3219. static loff_t shmem_file_llseek(struct file *file, loff_t offset, int whence)
  3220. {
  3221. struct address_space *mapping = file->f_mapping;
  3222. struct inode *inode = mapping->host;
  3223. if (whence != SEEK_DATA && whence != SEEK_HOLE)
  3224. return generic_file_llseek_size(file, offset, whence,
  3225. MAX_LFS_FILESIZE, i_size_read(inode));
  3226. if (offset < 0)
  3227. return -ENXIO;
  3228. inode_lock(inode);
  3229. /* We're holding i_rwsem so we can access i_size directly */
  3230. offset = mapping_seek_hole_data(mapping, offset, inode->i_size, whence);
  3231. if (offset >= 0)
  3232. offset = vfs_setpos(file, offset, MAX_LFS_FILESIZE);
  3233. inode_unlock(inode);
  3234. return offset;
  3235. }
  3236. static long shmem_fallocate(struct file *file, int mode, loff_t offset,
  3237. loff_t len)
  3238. {
  3239. struct inode *inode = file_inode(file);
  3240. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  3241. struct shmem_inode_info *info = SHMEM_I(inode);
  3242. struct shmem_falloc shmem_falloc;
  3243. pgoff_t start, index, end, undo_fallocend;
  3244. int error;
  3245. if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE))
  3246. return -EOPNOTSUPP;
  3247. inode_lock(inode);
  3248. if (info->flags & SHMEM_F_MAPPING_FROZEN) {
  3249. error = -EPERM;
  3250. goto out;
  3251. }
  3252. if (mode & FALLOC_FL_PUNCH_HOLE) {
  3253. struct address_space *mapping = file->f_mapping;
  3254. loff_t unmap_start = round_up(offset, PAGE_SIZE);
  3255. loff_t unmap_end = round_down(offset + len, PAGE_SIZE) - 1;
  3256. DECLARE_WAIT_QUEUE_HEAD_ONSTACK(shmem_falloc_waitq);
  3257. /* protected by i_rwsem */
  3258. if (info->seals & (F_SEAL_WRITE | F_SEAL_FUTURE_WRITE)) {
  3259. error = -EPERM;
  3260. goto out;
  3261. }
  3262. shmem_falloc.waitq = &shmem_falloc_waitq;
  3263. shmem_falloc.start = (u64)unmap_start >> PAGE_SHIFT;
  3264. shmem_falloc.next = (unmap_end + 1) >> PAGE_SHIFT;
  3265. spin_lock(&inode->i_lock);
  3266. inode->i_private = &shmem_falloc;
  3267. spin_unlock(&inode->i_lock);
  3268. if ((u64)unmap_end > (u64)unmap_start)
  3269. unmap_mapping_range(mapping, unmap_start,
  3270. 1 + unmap_end - unmap_start, 0);
  3271. shmem_truncate_range(inode, offset, offset + len - 1);
  3272. /* No need to unmap again: hole-punching leaves COWed pages */
  3273. spin_lock(&inode->i_lock);
  3274. inode->i_private = NULL;
  3275. wake_up_all(&shmem_falloc_waitq);
  3276. WARN_ON_ONCE(!list_empty(&shmem_falloc_waitq.head));
  3277. spin_unlock(&inode->i_lock);
  3278. error = 0;
  3279. goto out;
  3280. }
  3281. /* We need to check rlimit even when FALLOC_FL_KEEP_SIZE */
  3282. error = inode_newsize_ok(inode, offset + len);
  3283. if (error)
  3284. goto out;
  3285. if ((info->seals & F_SEAL_GROW) && offset + len > inode->i_size) {
  3286. error = -EPERM;
  3287. goto out;
  3288. }
  3289. start = offset >> PAGE_SHIFT;
  3290. end = (offset + len + PAGE_SIZE - 1) >> PAGE_SHIFT;
  3291. /* Try to avoid a swapstorm if len is impossible to satisfy */
  3292. if (sbinfo->max_blocks && end - start > sbinfo->max_blocks) {
  3293. error = -ENOSPC;
  3294. goto out;
  3295. }
  3296. shmem_falloc.waitq = NULL;
  3297. shmem_falloc.start = start;
  3298. shmem_falloc.next = start;
  3299. shmem_falloc.nr_falloced = 0;
  3300. shmem_falloc.nr_unswapped = 0;
  3301. spin_lock(&inode->i_lock);
  3302. inode->i_private = &shmem_falloc;
  3303. spin_unlock(&inode->i_lock);
  3304. /*
  3305. * info->fallocend is only relevant when huge pages might be
  3306. * involved: to prevent split_huge_page() freeing fallocated
  3307. * pages when FALLOC_FL_KEEP_SIZE committed beyond i_size.
  3308. */
  3309. undo_fallocend = info->fallocend;
  3310. if (info->fallocend < end)
  3311. info->fallocend = end;
  3312. for (index = start; index < end; ) {
  3313. struct folio *folio;
  3314. /*
  3315. * Check for fatal signal so that we abort early in OOM
  3316. * situations. We don't want to abort in case of non-fatal
  3317. * signals as large fallocate can take noticeable time and
  3318. * e.g. periodic timers may result in fallocate constantly
  3319. * restarting.
  3320. */
  3321. if (fatal_signal_pending(current))
  3322. error = -EINTR;
  3323. else if (shmem_falloc.nr_unswapped > shmem_falloc.nr_falloced)
  3324. error = -ENOMEM;
  3325. else
  3326. error = shmem_get_folio(inode, index, offset + len,
  3327. &folio, SGP_FALLOC);
  3328. if (error) {
  3329. info->fallocend = undo_fallocend;
  3330. /* Remove the !uptodate folios we added */
  3331. if (index > start) {
  3332. shmem_undo_range(inode,
  3333. (loff_t)start << PAGE_SHIFT,
  3334. ((loff_t)index << PAGE_SHIFT) - 1, true);
  3335. }
  3336. goto undone;
  3337. }
  3338. /*
  3339. * Here is a more important optimization than it appears:
  3340. * a second SGP_FALLOC on the same large folio will clear it,
  3341. * making it uptodate and un-undoable if we fail later.
  3342. */
  3343. index = folio_next_index(folio);
  3344. /* Beware 32-bit wraparound */
  3345. if (!index)
  3346. index--;
  3347. /*
  3348. * Inform shmem_writeout() how far we have reached.
  3349. * No need for lock or barrier: we have the page lock.
  3350. */
  3351. if (!folio_test_uptodate(folio))
  3352. shmem_falloc.nr_falloced += index - shmem_falloc.next;
  3353. shmem_falloc.next = index;
  3354. /*
  3355. * If !uptodate, leave it that way so that freeable folios
  3356. * can be recognized if we need to rollback on error later.
  3357. * But mark it dirty so that memory pressure will swap rather
  3358. * than free the folios we are allocating (and SGP_CACHE folios
  3359. * might still be clean: we now need to mark those dirty too).
  3360. */
  3361. folio_mark_dirty(folio);
  3362. folio_unlock(folio);
  3363. folio_put(folio);
  3364. cond_resched();
  3365. }
  3366. if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size)
  3367. i_size_write(inode, offset + len);
  3368. undone:
  3369. spin_lock(&inode->i_lock);
  3370. inode->i_private = NULL;
  3371. spin_unlock(&inode->i_lock);
  3372. out:
  3373. if (!error)
  3374. file_modified(file);
  3375. inode_unlock(inode);
  3376. return error;
  3377. }
  3378. static int shmem_statfs(struct dentry *dentry, struct kstatfs *buf)
  3379. {
  3380. struct shmem_sb_info *sbinfo = SHMEM_SB(dentry->d_sb);
  3381. buf->f_type = TMPFS_MAGIC;
  3382. buf->f_bsize = PAGE_SIZE;
  3383. buf->f_namelen = NAME_MAX;
  3384. if (sbinfo->max_blocks) {
  3385. buf->f_blocks = sbinfo->max_blocks;
  3386. buf->f_bavail =
  3387. buf->f_bfree = sbinfo->max_blocks -
  3388. percpu_counter_sum(&sbinfo->used_blocks);
  3389. }
  3390. if (sbinfo->max_inodes) {
  3391. buf->f_files = sbinfo->max_inodes;
  3392. buf->f_ffree = sbinfo->free_ispace / BOGO_INODE_SIZE;
  3393. }
  3394. /* else leave those fields 0 like simple_statfs */
  3395. buf->f_fsid = uuid_to_fsid(dentry->d_sb->s_uuid.b);
  3396. return 0;
  3397. }
  3398. /*
  3399. * File creation. Allocate an inode, and we're done..
  3400. */
  3401. static int
  3402. shmem_mknod(struct mnt_idmap *idmap, struct inode *dir,
  3403. struct dentry *dentry, umode_t mode, dev_t dev)
  3404. {
  3405. struct inode *inode;
  3406. int error;
  3407. if (!generic_ci_validate_strict_name(dir, &dentry->d_name))
  3408. return -EINVAL;
  3409. inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, dev,
  3410. mk_vma_flags(VMA_NORESERVE_BIT));
  3411. if (IS_ERR(inode))
  3412. return PTR_ERR(inode);
  3413. error = simple_acl_create(dir, inode);
  3414. if (error)
  3415. goto out_iput;
  3416. error = security_inode_init_security(inode, dir, &dentry->d_name,
  3417. shmem_initxattrs, NULL);
  3418. if (error && error != -EOPNOTSUPP)
  3419. goto out_iput;
  3420. error = simple_offset_add(shmem_get_offset_ctx(dir), dentry);
  3421. if (error)
  3422. goto out_iput;
  3423. dir->i_size += BOGO_DIRENT_SIZE;
  3424. inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
  3425. inode_inc_iversion(dir);
  3426. d_make_persistent(dentry, inode);
  3427. return error;
  3428. out_iput:
  3429. iput(inode);
  3430. return error;
  3431. }
  3432. static int
  3433. shmem_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
  3434. struct file *file, umode_t mode)
  3435. {
  3436. struct inode *inode;
  3437. int error;
  3438. inode = shmem_get_inode(idmap, dir->i_sb, dir, mode, 0,
  3439. mk_vma_flags(VMA_NORESERVE_BIT));
  3440. if (IS_ERR(inode)) {
  3441. error = PTR_ERR(inode);
  3442. goto err_out;
  3443. }
  3444. error = security_inode_init_security(inode, dir, NULL,
  3445. shmem_initxattrs, NULL);
  3446. if (error && error != -EOPNOTSUPP)
  3447. goto out_iput;
  3448. error = simple_acl_create(dir, inode);
  3449. if (error)
  3450. goto out_iput;
  3451. d_tmpfile(file, inode);
  3452. err_out:
  3453. return finish_open_simple(file, error);
  3454. out_iput:
  3455. iput(inode);
  3456. return error;
  3457. }
  3458. static struct dentry *shmem_mkdir(struct mnt_idmap *idmap, struct inode *dir,
  3459. struct dentry *dentry, umode_t mode)
  3460. {
  3461. int error;
  3462. error = shmem_mknod(idmap, dir, dentry, mode | S_IFDIR, 0);
  3463. if (error)
  3464. return ERR_PTR(error);
  3465. inc_nlink(dir);
  3466. return NULL;
  3467. }
  3468. static int shmem_create(struct mnt_idmap *idmap, struct inode *dir,
  3469. struct dentry *dentry, umode_t mode, bool excl)
  3470. {
  3471. return shmem_mknod(idmap, dir, dentry, mode | S_IFREG, 0);
  3472. }
  3473. /*
  3474. * Link a file..
  3475. */
  3476. static int shmem_link(struct dentry *old_dentry, struct inode *dir,
  3477. struct dentry *dentry)
  3478. {
  3479. struct inode *inode = d_inode(old_dentry);
  3480. int ret;
  3481. /*
  3482. * No ordinary (disk based) filesystem counts links as inodes;
  3483. * but each new link needs a new dentry, pinning lowmem, and
  3484. * tmpfs dentries cannot be pruned until they are unlinked.
  3485. * But if an O_TMPFILE file is linked into the tmpfs, the
  3486. * first link must skip that, to get the accounting right.
  3487. */
  3488. if (inode->i_nlink) {
  3489. ret = shmem_reserve_inode(inode->i_sb, NULL);
  3490. if (ret)
  3491. return ret;
  3492. }
  3493. ret = simple_offset_add(shmem_get_offset_ctx(dir), dentry);
  3494. if (ret) {
  3495. if (inode->i_nlink)
  3496. shmem_free_inode(inode->i_sb, 0);
  3497. return ret;
  3498. }
  3499. dir->i_size += BOGO_DIRENT_SIZE;
  3500. inode_inc_iversion(dir);
  3501. return simple_link(old_dentry, dir, dentry);
  3502. }
  3503. static int shmem_unlink(struct inode *dir, struct dentry *dentry)
  3504. {
  3505. struct inode *inode = d_inode(dentry);
  3506. if (inode->i_nlink > 1 && !S_ISDIR(inode->i_mode))
  3507. shmem_free_inode(inode->i_sb, 0);
  3508. simple_offset_remove(shmem_get_offset_ctx(dir), dentry);
  3509. dir->i_size -= BOGO_DIRENT_SIZE;
  3510. inode_inc_iversion(dir);
  3511. simple_unlink(dir, dentry);
  3512. /*
  3513. * For now, VFS can't deal with case-insensitive negative dentries, so
  3514. * we invalidate them
  3515. */
  3516. if (IS_ENABLED(CONFIG_UNICODE) && IS_CASEFOLDED(dir))
  3517. d_invalidate(dentry);
  3518. return 0;
  3519. }
  3520. static int shmem_rmdir(struct inode *dir, struct dentry *dentry)
  3521. {
  3522. if (!simple_empty(dentry))
  3523. return -ENOTEMPTY;
  3524. drop_nlink(d_inode(dentry));
  3525. drop_nlink(dir);
  3526. return shmem_unlink(dir, dentry);
  3527. }
  3528. static int shmem_whiteout(struct mnt_idmap *idmap,
  3529. struct inode *old_dir, struct dentry *old_dentry)
  3530. {
  3531. struct dentry *whiteout;
  3532. int error;
  3533. whiteout = d_alloc(old_dentry->d_parent, &old_dentry->d_name);
  3534. if (!whiteout)
  3535. return -ENOMEM;
  3536. error = shmem_mknod(idmap, old_dir, whiteout,
  3537. S_IFCHR | WHITEOUT_MODE, WHITEOUT_DEV);
  3538. dput(whiteout);
  3539. return error;
  3540. }
  3541. /*
  3542. * The VFS layer already does all the dentry stuff for rename,
  3543. * we just have to decrement the usage count for the target if
  3544. * it exists so that the VFS layer correctly free's it when it
  3545. * gets overwritten.
  3546. */
  3547. static int shmem_rename2(struct mnt_idmap *idmap,
  3548. struct inode *old_dir, struct dentry *old_dentry,
  3549. struct inode *new_dir, struct dentry *new_dentry,
  3550. unsigned int flags)
  3551. {
  3552. struct inode *inode = d_inode(old_dentry);
  3553. int they_are_dirs = S_ISDIR(inode->i_mode);
  3554. bool had_offset = false;
  3555. int error;
  3556. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
  3557. return -EINVAL;
  3558. if (flags & RENAME_EXCHANGE)
  3559. return simple_offset_rename_exchange(old_dir, old_dentry,
  3560. new_dir, new_dentry);
  3561. if (!simple_empty(new_dentry))
  3562. return -ENOTEMPTY;
  3563. error = simple_offset_add(shmem_get_offset_ctx(new_dir), new_dentry);
  3564. if (error == -EBUSY)
  3565. had_offset = true;
  3566. else if (unlikely(error))
  3567. return error;
  3568. if (flags & RENAME_WHITEOUT) {
  3569. error = shmem_whiteout(idmap, old_dir, old_dentry);
  3570. if (error) {
  3571. if (!had_offset)
  3572. simple_offset_remove(shmem_get_offset_ctx(new_dir),
  3573. new_dentry);
  3574. return error;
  3575. }
  3576. }
  3577. simple_offset_rename(old_dir, old_dentry, new_dir, new_dentry);
  3578. if (d_really_is_positive(new_dentry)) {
  3579. (void) shmem_unlink(new_dir, new_dentry);
  3580. if (they_are_dirs) {
  3581. drop_nlink(d_inode(new_dentry));
  3582. drop_nlink(old_dir);
  3583. }
  3584. } else if (they_are_dirs) {
  3585. drop_nlink(old_dir);
  3586. inc_nlink(new_dir);
  3587. }
  3588. old_dir->i_size -= BOGO_DIRENT_SIZE;
  3589. new_dir->i_size += BOGO_DIRENT_SIZE;
  3590. simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
  3591. inode_inc_iversion(old_dir);
  3592. inode_inc_iversion(new_dir);
  3593. return 0;
  3594. }
  3595. static int shmem_symlink(struct mnt_idmap *idmap, struct inode *dir,
  3596. struct dentry *dentry, const char *symname)
  3597. {
  3598. int error;
  3599. int len;
  3600. struct inode *inode;
  3601. struct folio *folio;
  3602. char *link;
  3603. len = strlen(symname) + 1;
  3604. if (len > PAGE_SIZE)
  3605. return -ENAMETOOLONG;
  3606. inode = shmem_get_inode(idmap, dir->i_sb, dir, S_IFLNK | 0777, 0,
  3607. mk_vma_flags(VMA_NORESERVE_BIT));
  3608. if (IS_ERR(inode))
  3609. return PTR_ERR(inode);
  3610. error = security_inode_init_security(inode, dir, &dentry->d_name,
  3611. shmem_initxattrs, NULL);
  3612. if (error && error != -EOPNOTSUPP)
  3613. goto out_iput;
  3614. error = simple_offset_add(shmem_get_offset_ctx(dir), dentry);
  3615. if (error)
  3616. goto out_iput;
  3617. inode->i_size = len-1;
  3618. if (len <= SHORT_SYMLINK_LEN) {
  3619. link = kmemdup(symname, len, GFP_KERNEL);
  3620. if (!link) {
  3621. error = -ENOMEM;
  3622. goto out_remove_offset;
  3623. }
  3624. inode->i_op = &shmem_short_symlink_operations;
  3625. inode_set_cached_link(inode, link, len - 1);
  3626. } else {
  3627. inode_nohighmem(inode);
  3628. inode->i_mapping->a_ops = &shmem_aops;
  3629. error = shmem_get_folio(inode, 0, 0, &folio, SGP_WRITE);
  3630. if (error)
  3631. goto out_remove_offset;
  3632. inode->i_op = &shmem_symlink_inode_operations;
  3633. memcpy(folio_address(folio), symname, len);
  3634. folio_mark_uptodate(folio);
  3635. folio_mark_dirty(folio);
  3636. folio_unlock(folio);
  3637. folio_put(folio);
  3638. }
  3639. dir->i_size += BOGO_DIRENT_SIZE;
  3640. inode_set_mtime_to_ts(dir, inode_set_ctime_current(dir));
  3641. inode_inc_iversion(dir);
  3642. d_make_persistent(dentry, inode);
  3643. return 0;
  3644. out_remove_offset:
  3645. simple_offset_remove(shmem_get_offset_ctx(dir), dentry);
  3646. out_iput:
  3647. iput(inode);
  3648. return error;
  3649. }
  3650. static void shmem_put_link(void *arg)
  3651. {
  3652. folio_mark_accessed(arg);
  3653. folio_put(arg);
  3654. }
  3655. static const char *shmem_get_link(struct dentry *dentry, struct inode *inode,
  3656. struct delayed_call *done)
  3657. {
  3658. struct folio *folio = NULL;
  3659. int error;
  3660. if (!dentry) {
  3661. folio = filemap_get_folio(inode->i_mapping, 0);
  3662. if (IS_ERR(folio))
  3663. return ERR_PTR(-ECHILD);
  3664. if (PageHWPoison(folio_page(folio, 0)) ||
  3665. !folio_test_uptodate(folio)) {
  3666. folio_put(folio);
  3667. return ERR_PTR(-ECHILD);
  3668. }
  3669. } else {
  3670. error = shmem_get_folio(inode, 0, 0, &folio, SGP_READ);
  3671. if (error)
  3672. return ERR_PTR(error);
  3673. if (!folio)
  3674. return ERR_PTR(-ECHILD);
  3675. if (PageHWPoison(folio_page(folio, 0))) {
  3676. folio_unlock(folio);
  3677. folio_put(folio);
  3678. return ERR_PTR(-ECHILD);
  3679. }
  3680. folio_unlock(folio);
  3681. }
  3682. set_delayed_call(done, shmem_put_link, folio);
  3683. return folio_address(folio);
  3684. }
  3685. #ifdef CONFIG_TMPFS_XATTR
  3686. static int shmem_fileattr_get(struct dentry *dentry, struct file_kattr *fa)
  3687. {
  3688. struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
  3689. fileattr_fill_flags(fa, info->fsflags & SHMEM_FL_USER_VISIBLE);
  3690. return 0;
  3691. }
  3692. static int shmem_fileattr_set(struct mnt_idmap *idmap,
  3693. struct dentry *dentry, struct file_kattr *fa)
  3694. {
  3695. struct inode *inode = d_inode(dentry);
  3696. struct shmem_inode_info *info = SHMEM_I(inode);
  3697. int ret, flags;
  3698. if (fileattr_has_fsx(fa))
  3699. return -EOPNOTSUPP;
  3700. if (fa->flags & ~SHMEM_FL_USER_MODIFIABLE)
  3701. return -EOPNOTSUPP;
  3702. flags = (info->fsflags & ~SHMEM_FL_USER_MODIFIABLE) |
  3703. (fa->flags & SHMEM_FL_USER_MODIFIABLE);
  3704. ret = shmem_set_inode_flags(inode, flags, dentry);
  3705. if (ret)
  3706. return ret;
  3707. info->fsflags = flags;
  3708. inode_set_ctime_current(inode);
  3709. inode_inc_iversion(inode);
  3710. return 0;
  3711. }
  3712. /*
  3713. * Superblocks without xattr inode operations may get some security.* xattr
  3714. * support from the LSM "for free". As soon as we have any other xattrs
  3715. * like ACLs, we also need to implement the security.* handlers at
  3716. * filesystem level, though.
  3717. */
  3718. /*
  3719. * Callback for security_inode_init_security() for acquiring xattrs.
  3720. */
  3721. static int shmem_initxattrs(struct inode *inode,
  3722. const struct xattr *xattr_array, void *fs_info)
  3723. {
  3724. struct shmem_inode_info *info = SHMEM_I(inode);
  3725. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  3726. const struct xattr *xattr;
  3727. struct simple_xattr *new_xattr;
  3728. size_t ispace = 0;
  3729. size_t len;
  3730. if (sbinfo->max_inodes) {
  3731. for (xattr = xattr_array; xattr->name != NULL; xattr++) {
  3732. ispace += simple_xattr_space(xattr->name,
  3733. xattr->value_len + XATTR_SECURITY_PREFIX_LEN);
  3734. }
  3735. if (ispace) {
  3736. raw_spin_lock(&sbinfo->stat_lock);
  3737. if (sbinfo->free_ispace < ispace)
  3738. ispace = 0;
  3739. else
  3740. sbinfo->free_ispace -= ispace;
  3741. raw_spin_unlock(&sbinfo->stat_lock);
  3742. if (!ispace)
  3743. return -ENOSPC;
  3744. }
  3745. }
  3746. for (xattr = xattr_array; xattr->name != NULL; xattr++) {
  3747. new_xattr = simple_xattr_alloc(xattr->value, xattr->value_len);
  3748. if (!new_xattr)
  3749. break;
  3750. len = strlen(xattr->name) + 1;
  3751. new_xattr->name = kmalloc(XATTR_SECURITY_PREFIX_LEN + len,
  3752. GFP_KERNEL_ACCOUNT);
  3753. if (!new_xattr->name) {
  3754. kvfree(new_xattr);
  3755. break;
  3756. }
  3757. memcpy(new_xattr->name, XATTR_SECURITY_PREFIX,
  3758. XATTR_SECURITY_PREFIX_LEN);
  3759. memcpy(new_xattr->name + XATTR_SECURITY_PREFIX_LEN,
  3760. xattr->name, len);
  3761. simple_xattr_add(&info->xattrs, new_xattr);
  3762. }
  3763. if (xattr->name != NULL) {
  3764. if (ispace) {
  3765. raw_spin_lock(&sbinfo->stat_lock);
  3766. sbinfo->free_ispace += ispace;
  3767. raw_spin_unlock(&sbinfo->stat_lock);
  3768. }
  3769. simple_xattrs_free(&info->xattrs, NULL);
  3770. return -ENOMEM;
  3771. }
  3772. return 0;
  3773. }
  3774. static int shmem_xattr_handler_get(const struct xattr_handler *handler,
  3775. struct dentry *unused, struct inode *inode,
  3776. const char *name, void *buffer, size_t size)
  3777. {
  3778. struct shmem_inode_info *info = SHMEM_I(inode);
  3779. name = xattr_full_name(handler, name);
  3780. return simple_xattr_get(&info->xattrs, name, buffer, size);
  3781. }
  3782. static int shmem_xattr_handler_set(const struct xattr_handler *handler,
  3783. struct mnt_idmap *idmap,
  3784. struct dentry *unused, struct inode *inode,
  3785. const char *name, const void *value,
  3786. size_t size, int flags)
  3787. {
  3788. struct shmem_inode_info *info = SHMEM_I(inode);
  3789. struct shmem_sb_info *sbinfo = SHMEM_SB(inode->i_sb);
  3790. struct simple_xattr *old_xattr;
  3791. size_t ispace = 0;
  3792. name = xattr_full_name(handler, name);
  3793. if (value && sbinfo->max_inodes) {
  3794. ispace = simple_xattr_space(name, size);
  3795. raw_spin_lock(&sbinfo->stat_lock);
  3796. if (sbinfo->free_ispace < ispace)
  3797. ispace = 0;
  3798. else
  3799. sbinfo->free_ispace -= ispace;
  3800. raw_spin_unlock(&sbinfo->stat_lock);
  3801. if (!ispace)
  3802. return -ENOSPC;
  3803. }
  3804. old_xattr = simple_xattr_set(&info->xattrs, name, value, size, flags);
  3805. if (!IS_ERR(old_xattr)) {
  3806. ispace = 0;
  3807. if (old_xattr && sbinfo->max_inodes)
  3808. ispace = simple_xattr_space(old_xattr->name,
  3809. old_xattr->size);
  3810. simple_xattr_free(old_xattr);
  3811. old_xattr = NULL;
  3812. inode_set_ctime_current(inode);
  3813. inode_inc_iversion(inode);
  3814. }
  3815. if (ispace) {
  3816. raw_spin_lock(&sbinfo->stat_lock);
  3817. sbinfo->free_ispace += ispace;
  3818. raw_spin_unlock(&sbinfo->stat_lock);
  3819. }
  3820. return PTR_ERR(old_xattr);
  3821. }
  3822. static const struct xattr_handler shmem_security_xattr_handler = {
  3823. .prefix = XATTR_SECURITY_PREFIX,
  3824. .get = shmem_xattr_handler_get,
  3825. .set = shmem_xattr_handler_set,
  3826. };
  3827. static const struct xattr_handler shmem_trusted_xattr_handler = {
  3828. .prefix = XATTR_TRUSTED_PREFIX,
  3829. .get = shmem_xattr_handler_get,
  3830. .set = shmem_xattr_handler_set,
  3831. };
  3832. static const struct xattr_handler shmem_user_xattr_handler = {
  3833. .prefix = XATTR_USER_PREFIX,
  3834. .get = shmem_xattr_handler_get,
  3835. .set = shmem_xattr_handler_set,
  3836. };
  3837. static const struct xattr_handler * const shmem_xattr_handlers[] = {
  3838. &shmem_security_xattr_handler,
  3839. &shmem_trusted_xattr_handler,
  3840. &shmem_user_xattr_handler,
  3841. NULL
  3842. };
  3843. static ssize_t shmem_listxattr(struct dentry *dentry, char *buffer, size_t size)
  3844. {
  3845. struct shmem_inode_info *info = SHMEM_I(d_inode(dentry));
  3846. return simple_xattr_list(d_inode(dentry), &info->xattrs, buffer, size);
  3847. }
  3848. #endif /* CONFIG_TMPFS_XATTR */
  3849. static const struct inode_operations shmem_short_symlink_operations = {
  3850. .getattr = shmem_getattr,
  3851. .setattr = shmem_setattr,
  3852. .get_link = simple_get_link,
  3853. #ifdef CONFIG_TMPFS_XATTR
  3854. .listxattr = shmem_listxattr,
  3855. #endif
  3856. };
  3857. static const struct inode_operations shmem_symlink_inode_operations = {
  3858. .getattr = shmem_getattr,
  3859. .setattr = shmem_setattr,
  3860. .get_link = shmem_get_link,
  3861. #ifdef CONFIG_TMPFS_XATTR
  3862. .listxattr = shmem_listxattr,
  3863. #endif
  3864. };
  3865. static struct dentry *shmem_get_parent(struct dentry *child)
  3866. {
  3867. return ERR_PTR(-ESTALE);
  3868. }
  3869. static int shmem_match(struct inode *ino, void *vfh)
  3870. {
  3871. __u32 *fh = vfh;
  3872. __u64 inum = fh[2];
  3873. inum = (inum << 32) | fh[1];
  3874. return ino->i_ino == inum && fh[0] == ino->i_generation;
  3875. }
  3876. /* Find any alias of inode, but prefer a hashed alias */
  3877. static struct dentry *shmem_find_alias(struct inode *inode)
  3878. {
  3879. struct dentry *alias = d_find_alias(inode);
  3880. return alias ?: d_find_any_alias(inode);
  3881. }
  3882. static struct dentry *shmem_fh_to_dentry(struct super_block *sb,
  3883. struct fid *fid, int fh_len, int fh_type)
  3884. {
  3885. struct inode *inode;
  3886. struct dentry *dentry = NULL;
  3887. u64 inum;
  3888. if (fh_len < 3)
  3889. return NULL;
  3890. inum = fid->raw[2];
  3891. inum = (inum << 32) | fid->raw[1];
  3892. inode = ilookup5(sb, (unsigned long)(inum + fid->raw[0]),
  3893. shmem_match, fid->raw);
  3894. if (inode) {
  3895. dentry = shmem_find_alias(inode);
  3896. iput(inode);
  3897. }
  3898. return dentry;
  3899. }
  3900. static int shmem_encode_fh(struct inode *inode, __u32 *fh, int *len,
  3901. struct inode *parent)
  3902. {
  3903. if (*len < 3) {
  3904. *len = 3;
  3905. return FILEID_INVALID;
  3906. }
  3907. if (inode_unhashed(inode)) {
  3908. /* Unfortunately insert_inode_hash is not idempotent,
  3909. * so as we hash inodes here rather than at creation
  3910. * time, we need a lock to ensure we only try
  3911. * to do it once
  3912. */
  3913. static DEFINE_SPINLOCK(lock);
  3914. spin_lock(&lock);
  3915. if (inode_unhashed(inode))
  3916. __insert_inode_hash(inode,
  3917. inode->i_ino + inode->i_generation);
  3918. spin_unlock(&lock);
  3919. }
  3920. fh[0] = inode->i_generation;
  3921. fh[1] = inode->i_ino;
  3922. fh[2] = ((__u64)inode->i_ino) >> 32;
  3923. *len = 3;
  3924. return 1;
  3925. }
  3926. static const struct export_operations shmem_export_ops = {
  3927. .get_parent = shmem_get_parent,
  3928. .encode_fh = shmem_encode_fh,
  3929. .fh_to_dentry = shmem_fh_to_dentry,
  3930. };
  3931. enum shmem_param {
  3932. Opt_gid,
  3933. Opt_huge,
  3934. Opt_mode,
  3935. Opt_mpol,
  3936. Opt_nr_blocks,
  3937. Opt_nr_inodes,
  3938. Opt_size,
  3939. Opt_uid,
  3940. Opt_inode32,
  3941. Opt_inode64,
  3942. Opt_noswap,
  3943. Opt_quota,
  3944. Opt_usrquota,
  3945. Opt_grpquota,
  3946. Opt_usrquota_block_hardlimit,
  3947. Opt_usrquota_inode_hardlimit,
  3948. Opt_grpquota_block_hardlimit,
  3949. Opt_grpquota_inode_hardlimit,
  3950. Opt_casefold_version,
  3951. Opt_casefold,
  3952. Opt_strict_encoding,
  3953. };
  3954. static const struct constant_table shmem_param_enums_huge[] = {
  3955. {"never", SHMEM_HUGE_NEVER },
  3956. {"always", SHMEM_HUGE_ALWAYS },
  3957. {"within_size", SHMEM_HUGE_WITHIN_SIZE },
  3958. {"advise", SHMEM_HUGE_ADVISE },
  3959. {}
  3960. };
  3961. const struct fs_parameter_spec shmem_fs_parameters[] = {
  3962. fsparam_gid ("gid", Opt_gid),
  3963. fsparam_enum ("huge", Opt_huge, shmem_param_enums_huge),
  3964. fsparam_u32oct("mode", Opt_mode),
  3965. fsparam_string("mpol", Opt_mpol),
  3966. fsparam_string("nr_blocks", Opt_nr_blocks),
  3967. fsparam_string("nr_inodes", Opt_nr_inodes),
  3968. fsparam_string("size", Opt_size),
  3969. fsparam_uid ("uid", Opt_uid),
  3970. fsparam_flag ("inode32", Opt_inode32),
  3971. fsparam_flag ("inode64", Opt_inode64),
  3972. fsparam_flag ("noswap", Opt_noswap),
  3973. #ifdef CONFIG_TMPFS_QUOTA
  3974. fsparam_flag ("quota", Opt_quota),
  3975. fsparam_flag ("usrquota", Opt_usrquota),
  3976. fsparam_flag ("grpquota", Opt_grpquota),
  3977. fsparam_string("usrquota_block_hardlimit", Opt_usrquota_block_hardlimit),
  3978. fsparam_string("usrquota_inode_hardlimit", Opt_usrquota_inode_hardlimit),
  3979. fsparam_string("grpquota_block_hardlimit", Opt_grpquota_block_hardlimit),
  3980. fsparam_string("grpquota_inode_hardlimit", Opt_grpquota_inode_hardlimit),
  3981. #endif
  3982. fsparam_string("casefold", Opt_casefold_version),
  3983. fsparam_flag ("casefold", Opt_casefold),
  3984. fsparam_flag ("strict_encoding", Opt_strict_encoding),
  3985. {}
  3986. };
  3987. #if IS_ENABLED(CONFIG_UNICODE)
  3988. static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param,
  3989. bool latest_version)
  3990. {
  3991. struct shmem_options *ctx = fc->fs_private;
  3992. int version = UTF8_LATEST;
  3993. struct unicode_map *encoding;
  3994. char *version_str = param->string + 5;
  3995. if (!latest_version) {
  3996. if (strncmp(param->string, "utf8-", 5))
  3997. return invalfc(fc, "Only UTF-8 encodings are supported "
  3998. "in the format: utf8-<version number>");
  3999. version = utf8_parse_version(version_str);
  4000. if (version < 0)
  4001. return invalfc(fc, "Invalid UTF-8 version: %s", version_str);
  4002. }
  4003. encoding = utf8_load(version);
  4004. if (IS_ERR(encoding)) {
  4005. return invalfc(fc, "Failed loading UTF-8 version: utf8-%u.%u.%u\n",
  4006. unicode_major(version), unicode_minor(version),
  4007. unicode_rev(version));
  4008. }
  4009. pr_info("tmpfs: Using encoding : utf8-%u.%u.%u\n",
  4010. unicode_major(version), unicode_minor(version), unicode_rev(version));
  4011. ctx->encoding = encoding;
  4012. return 0;
  4013. }
  4014. #else
  4015. static int shmem_parse_opt_casefold(struct fs_context *fc, struct fs_parameter *param,
  4016. bool latest_version)
  4017. {
  4018. return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
  4019. }
  4020. #endif
  4021. static int shmem_parse_one(struct fs_context *fc, struct fs_parameter *param)
  4022. {
  4023. struct shmem_options *ctx = fc->fs_private;
  4024. struct fs_parse_result result;
  4025. unsigned long long size;
  4026. char *rest;
  4027. int opt;
  4028. kuid_t kuid;
  4029. kgid_t kgid;
  4030. opt = fs_parse(fc, shmem_fs_parameters, param, &result);
  4031. if (opt < 0)
  4032. return opt;
  4033. switch (opt) {
  4034. case Opt_size:
  4035. size = memparse(param->string, &rest);
  4036. if (*rest == '%') {
  4037. size <<= PAGE_SHIFT;
  4038. size *= totalram_pages();
  4039. do_div(size, 100);
  4040. rest++;
  4041. }
  4042. if (*rest)
  4043. goto bad_value;
  4044. ctx->blocks = DIV_ROUND_UP(size, PAGE_SIZE);
  4045. ctx->seen |= SHMEM_SEEN_BLOCKS;
  4046. break;
  4047. case Opt_nr_blocks:
  4048. ctx->blocks = memparse(param->string, &rest);
  4049. if (*rest || ctx->blocks > LONG_MAX)
  4050. goto bad_value;
  4051. ctx->seen |= SHMEM_SEEN_BLOCKS;
  4052. break;
  4053. case Opt_nr_inodes:
  4054. ctx->inodes = memparse(param->string, &rest);
  4055. if (*rest || ctx->inodes > ULONG_MAX / BOGO_INODE_SIZE)
  4056. goto bad_value;
  4057. ctx->seen |= SHMEM_SEEN_INODES;
  4058. break;
  4059. case Opt_mode:
  4060. ctx->mode = result.uint_32 & 07777;
  4061. break;
  4062. case Opt_uid:
  4063. kuid = result.uid;
  4064. /*
  4065. * The requested uid must be representable in the
  4066. * filesystem's idmapping.
  4067. */
  4068. if (!kuid_has_mapping(fc->user_ns, kuid))
  4069. goto bad_value;
  4070. ctx->uid = kuid;
  4071. break;
  4072. case Opt_gid:
  4073. kgid = result.gid;
  4074. /*
  4075. * The requested gid must be representable in the
  4076. * filesystem's idmapping.
  4077. */
  4078. if (!kgid_has_mapping(fc->user_ns, kgid))
  4079. goto bad_value;
  4080. ctx->gid = kgid;
  4081. break;
  4082. case Opt_huge:
  4083. ctx->huge = result.uint_32;
  4084. if (ctx->huge != SHMEM_HUGE_NEVER &&
  4085. !(IS_ENABLED(CONFIG_TRANSPARENT_HUGEPAGE) &&
  4086. has_transparent_hugepage()))
  4087. goto unsupported_parameter;
  4088. ctx->seen |= SHMEM_SEEN_HUGE;
  4089. break;
  4090. case Opt_mpol:
  4091. if (IS_ENABLED(CONFIG_NUMA)) {
  4092. mpol_put(ctx->mpol);
  4093. ctx->mpol = NULL;
  4094. if (mpol_parse_str(param->string, &ctx->mpol))
  4095. goto bad_value;
  4096. break;
  4097. }
  4098. goto unsupported_parameter;
  4099. case Opt_inode32:
  4100. ctx->full_inums = false;
  4101. ctx->seen |= SHMEM_SEEN_INUMS;
  4102. break;
  4103. case Opt_inode64:
  4104. if (sizeof(ino_t) < 8) {
  4105. return invalfc(fc,
  4106. "Cannot use inode64 with <64bit inums in kernel\n");
  4107. }
  4108. ctx->full_inums = true;
  4109. ctx->seen |= SHMEM_SEEN_INUMS;
  4110. break;
  4111. case Opt_noswap:
  4112. if ((fc->user_ns != &init_user_ns) || !capable(CAP_SYS_ADMIN)) {
  4113. return invalfc(fc,
  4114. "Turning off swap in unprivileged tmpfs mounts unsupported");
  4115. }
  4116. ctx->noswap = true;
  4117. break;
  4118. case Opt_quota:
  4119. if (fc->user_ns != &init_user_ns)
  4120. return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported");
  4121. ctx->seen |= SHMEM_SEEN_QUOTA;
  4122. ctx->quota_types |= (QTYPE_MASK_USR | QTYPE_MASK_GRP);
  4123. break;
  4124. case Opt_usrquota:
  4125. if (fc->user_ns != &init_user_ns)
  4126. return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported");
  4127. ctx->seen |= SHMEM_SEEN_QUOTA;
  4128. ctx->quota_types |= QTYPE_MASK_USR;
  4129. break;
  4130. case Opt_grpquota:
  4131. if (fc->user_ns != &init_user_ns)
  4132. return invalfc(fc, "Quotas in unprivileged tmpfs mounts are unsupported");
  4133. ctx->seen |= SHMEM_SEEN_QUOTA;
  4134. ctx->quota_types |= QTYPE_MASK_GRP;
  4135. break;
  4136. case Opt_usrquota_block_hardlimit:
  4137. size = memparse(param->string, &rest);
  4138. if (*rest || !size)
  4139. goto bad_value;
  4140. if (size > SHMEM_QUOTA_MAX_SPC_LIMIT)
  4141. return invalfc(fc,
  4142. "User quota block hardlimit too large.");
  4143. ctx->qlimits.usrquota_bhardlimit = size;
  4144. break;
  4145. case Opt_grpquota_block_hardlimit:
  4146. size = memparse(param->string, &rest);
  4147. if (*rest || !size)
  4148. goto bad_value;
  4149. if (size > SHMEM_QUOTA_MAX_SPC_LIMIT)
  4150. return invalfc(fc,
  4151. "Group quota block hardlimit too large.");
  4152. ctx->qlimits.grpquota_bhardlimit = size;
  4153. break;
  4154. case Opt_usrquota_inode_hardlimit:
  4155. size = memparse(param->string, &rest);
  4156. if (*rest || !size)
  4157. goto bad_value;
  4158. if (size > SHMEM_QUOTA_MAX_INO_LIMIT)
  4159. return invalfc(fc,
  4160. "User quota inode hardlimit too large.");
  4161. ctx->qlimits.usrquota_ihardlimit = size;
  4162. break;
  4163. case Opt_grpquota_inode_hardlimit:
  4164. size = memparse(param->string, &rest);
  4165. if (*rest || !size)
  4166. goto bad_value;
  4167. if (size > SHMEM_QUOTA_MAX_INO_LIMIT)
  4168. return invalfc(fc,
  4169. "Group quota inode hardlimit too large.");
  4170. ctx->qlimits.grpquota_ihardlimit = size;
  4171. break;
  4172. case Opt_casefold_version:
  4173. return shmem_parse_opt_casefold(fc, param, false);
  4174. case Opt_casefold:
  4175. return shmem_parse_opt_casefold(fc, param, true);
  4176. case Opt_strict_encoding:
  4177. #if IS_ENABLED(CONFIG_UNICODE)
  4178. ctx->strict_encoding = true;
  4179. break;
  4180. #else
  4181. return invalfc(fc, "tmpfs: Kernel not built with CONFIG_UNICODE\n");
  4182. #endif
  4183. }
  4184. return 0;
  4185. unsupported_parameter:
  4186. return invalfc(fc, "Unsupported parameter '%s'", param->key);
  4187. bad_value:
  4188. return invalfc(fc, "Bad value for '%s'", param->key);
  4189. }
  4190. static char *shmem_next_opt(char **s)
  4191. {
  4192. char *sbegin = *s;
  4193. char *p;
  4194. if (sbegin == NULL)
  4195. return NULL;
  4196. /*
  4197. * NUL-terminate this option: unfortunately,
  4198. * mount options form a comma-separated list,
  4199. * but mpol's nodelist may also contain commas.
  4200. */
  4201. for (;;) {
  4202. p = strchr(*s, ',');
  4203. if (p == NULL)
  4204. break;
  4205. *s = p + 1;
  4206. if (!isdigit(*(p+1))) {
  4207. *p = '\0';
  4208. return sbegin;
  4209. }
  4210. }
  4211. *s = NULL;
  4212. return sbegin;
  4213. }
  4214. static int shmem_parse_monolithic(struct fs_context *fc, void *data)
  4215. {
  4216. return vfs_parse_monolithic_sep(fc, data, shmem_next_opt);
  4217. }
  4218. /*
  4219. * Reconfigure a shmem filesystem.
  4220. */
  4221. static int shmem_reconfigure(struct fs_context *fc)
  4222. {
  4223. struct shmem_options *ctx = fc->fs_private;
  4224. struct shmem_sb_info *sbinfo = SHMEM_SB(fc->root->d_sb);
  4225. unsigned long used_isp;
  4226. struct mempolicy *mpol = NULL;
  4227. const char *err;
  4228. raw_spin_lock(&sbinfo->stat_lock);
  4229. used_isp = sbinfo->max_inodes * BOGO_INODE_SIZE - sbinfo->free_ispace;
  4230. if ((ctx->seen & SHMEM_SEEN_BLOCKS) && ctx->blocks) {
  4231. if (!sbinfo->max_blocks) {
  4232. err = "Cannot retroactively limit size";
  4233. goto out;
  4234. }
  4235. if (percpu_counter_compare(&sbinfo->used_blocks,
  4236. ctx->blocks) > 0) {
  4237. err = "Too small a size for current use";
  4238. goto out;
  4239. }
  4240. }
  4241. if ((ctx->seen & SHMEM_SEEN_INODES) && ctx->inodes) {
  4242. if (!sbinfo->max_inodes) {
  4243. err = "Cannot retroactively limit inodes";
  4244. goto out;
  4245. }
  4246. if (ctx->inodes * BOGO_INODE_SIZE < used_isp) {
  4247. err = "Too few inodes for current use";
  4248. goto out;
  4249. }
  4250. }
  4251. if ((ctx->seen & SHMEM_SEEN_INUMS) && !ctx->full_inums &&
  4252. sbinfo->next_ino > UINT_MAX) {
  4253. err = "Current inum too high to switch to 32-bit inums";
  4254. goto out;
  4255. }
  4256. /*
  4257. * "noswap" doesn't use fsparam_flag_no, i.e. there's no "swap"
  4258. * counterpart for (re-)enabling swap.
  4259. */
  4260. if (ctx->noswap && !sbinfo->noswap) {
  4261. err = "Cannot disable swap on remount";
  4262. goto out;
  4263. }
  4264. if (ctx->seen & SHMEM_SEEN_QUOTA &&
  4265. !sb_any_quota_loaded(fc->root->d_sb)) {
  4266. err = "Cannot enable quota on remount";
  4267. goto out;
  4268. }
  4269. #ifdef CONFIG_TMPFS_QUOTA
  4270. #define CHANGED_LIMIT(name) \
  4271. (ctx->qlimits.name## hardlimit && \
  4272. (ctx->qlimits.name## hardlimit != sbinfo->qlimits.name## hardlimit))
  4273. if (CHANGED_LIMIT(usrquota_b) || CHANGED_LIMIT(usrquota_i) ||
  4274. CHANGED_LIMIT(grpquota_b) || CHANGED_LIMIT(grpquota_i)) {
  4275. err = "Cannot change global quota limit on remount";
  4276. goto out;
  4277. }
  4278. #endif /* CONFIG_TMPFS_QUOTA */
  4279. if (ctx->seen & SHMEM_SEEN_HUGE)
  4280. sbinfo->huge = ctx->huge;
  4281. if (ctx->seen & SHMEM_SEEN_INUMS)
  4282. sbinfo->full_inums = ctx->full_inums;
  4283. if (ctx->seen & SHMEM_SEEN_BLOCKS)
  4284. sbinfo->max_blocks = ctx->blocks;
  4285. if (ctx->seen & SHMEM_SEEN_INODES) {
  4286. sbinfo->max_inodes = ctx->inodes;
  4287. sbinfo->free_ispace = ctx->inodes * BOGO_INODE_SIZE - used_isp;
  4288. }
  4289. /*
  4290. * Preserve previous mempolicy unless mpol remount option was specified.
  4291. */
  4292. if (ctx->mpol) {
  4293. mpol = sbinfo->mpol;
  4294. sbinfo->mpol = ctx->mpol; /* transfers initial ref */
  4295. ctx->mpol = NULL;
  4296. }
  4297. if (ctx->noswap)
  4298. sbinfo->noswap = true;
  4299. raw_spin_unlock(&sbinfo->stat_lock);
  4300. mpol_put(mpol);
  4301. return 0;
  4302. out:
  4303. raw_spin_unlock(&sbinfo->stat_lock);
  4304. return invalfc(fc, "%s", err);
  4305. }
  4306. static int shmem_show_options(struct seq_file *seq, struct dentry *root)
  4307. {
  4308. struct shmem_sb_info *sbinfo = SHMEM_SB(root->d_sb);
  4309. struct mempolicy *mpol;
  4310. if (sbinfo->max_blocks != shmem_default_max_blocks())
  4311. seq_printf(seq, ",size=%luk", K(sbinfo->max_blocks));
  4312. if (sbinfo->max_inodes != shmem_default_max_inodes())
  4313. seq_printf(seq, ",nr_inodes=%lu", sbinfo->max_inodes);
  4314. if (sbinfo->mode != (0777 | S_ISVTX))
  4315. seq_printf(seq, ",mode=%03ho", sbinfo->mode);
  4316. if (!uid_eq(sbinfo->uid, GLOBAL_ROOT_UID))
  4317. seq_printf(seq, ",uid=%u",
  4318. from_kuid_munged(&init_user_ns, sbinfo->uid));
  4319. if (!gid_eq(sbinfo->gid, GLOBAL_ROOT_GID))
  4320. seq_printf(seq, ",gid=%u",
  4321. from_kgid_munged(&init_user_ns, sbinfo->gid));
  4322. /*
  4323. * Showing inode{64,32} might be useful even if it's the system default,
  4324. * since then people don't have to resort to checking both here and
  4325. * /proc/config.gz to confirm 64-bit inums were successfully applied
  4326. * (which may not even exist if IKCONFIG_PROC isn't enabled).
  4327. *
  4328. * We hide it when inode64 isn't the default and we are using 32-bit
  4329. * inodes, since that probably just means the feature isn't even under
  4330. * consideration.
  4331. *
  4332. * As such:
  4333. *
  4334. * +-----------------+-----------------+
  4335. * | TMPFS_INODE64=y | TMPFS_INODE64=n |
  4336. * +------------------+-----------------+-----------------+
  4337. * | full_inums=true | show | show |
  4338. * | full_inums=false | show | hide |
  4339. * +------------------+-----------------+-----------------+
  4340. *
  4341. */
  4342. if (IS_ENABLED(CONFIG_TMPFS_INODE64) || sbinfo->full_inums)
  4343. seq_printf(seq, ",inode%d", (sbinfo->full_inums ? 64 : 32));
  4344. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4345. /* Rightly or wrongly, show huge mount option unmasked by shmem_huge */
  4346. if (sbinfo->huge)
  4347. seq_printf(seq, ",huge=%s", shmem_format_huge(sbinfo->huge));
  4348. #endif
  4349. mpol = shmem_get_sbmpol(sbinfo);
  4350. shmem_show_mpol(seq, mpol);
  4351. mpol_put(mpol);
  4352. if (sbinfo->noswap)
  4353. seq_printf(seq, ",noswap");
  4354. #ifdef CONFIG_TMPFS_QUOTA
  4355. if (sb_has_quota_active(root->d_sb, USRQUOTA))
  4356. seq_printf(seq, ",usrquota");
  4357. if (sb_has_quota_active(root->d_sb, GRPQUOTA))
  4358. seq_printf(seq, ",grpquota");
  4359. if (sbinfo->qlimits.usrquota_bhardlimit)
  4360. seq_printf(seq, ",usrquota_block_hardlimit=%lld",
  4361. sbinfo->qlimits.usrquota_bhardlimit);
  4362. if (sbinfo->qlimits.grpquota_bhardlimit)
  4363. seq_printf(seq, ",grpquota_block_hardlimit=%lld",
  4364. sbinfo->qlimits.grpquota_bhardlimit);
  4365. if (sbinfo->qlimits.usrquota_ihardlimit)
  4366. seq_printf(seq, ",usrquota_inode_hardlimit=%lld",
  4367. sbinfo->qlimits.usrquota_ihardlimit);
  4368. if (sbinfo->qlimits.grpquota_ihardlimit)
  4369. seq_printf(seq, ",grpquota_inode_hardlimit=%lld",
  4370. sbinfo->qlimits.grpquota_ihardlimit);
  4371. #endif
  4372. return 0;
  4373. }
  4374. #endif /* CONFIG_TMPFS */
  4375. static void shmem_put_super(struct super_block *sb)
  4376. {
  4377. struct shmem_sb_info *sbinfo = SHMEM_SB(sb);
  4378. #if IS_ENABLED(CONFIG_UNICODE)
  4379. if (sb->s_encoding)
  4380. utf8_unload(sb->s_encoding);
  4381. #endif
  4382. #ifdef CONFIG_TMPFS_QUOTA
  4383. shmem_disable_quotas(sb);
  4384. #endif
  4385. free_percpu(sbinfo->ino_batch);
  4386. percpu_counter_destroy(&sbinfo->used_blocks);
  4387. mpol_put(sbinfo->mpol);
  4388. kfree(sbinfo);
  4389. sb->s_fs_info = NULL;
  4390. }
  4391. #if IS_ENABLED(CONFIG_UNICODE) && defined(CONFIG_TMPFS)
  4392. static const struct dentry_operations shmem_ci_dentry_ops = {
  4393. .d_hash = generic_ci_d_hash,
  4394. .d_compare = generic_ci_d_compare,
  4395. };
  4396. #endif
  4397. static int shmem_fill_super(struct super_block *sb, struct fs_context *fc)
  4398. {
  4399. struct shmem_options *ctx = fc->fs_private;
  4400. struct inode *inode;
  4401. struct shmem_sb_info *sbinfo;
  4402. int error = -ENOMEM;
  4403. /* Round up to L1_CACHE_BYTES to resist false sharing */
  4404. sbinfo = kzalloc(max((int)sizeof(struct shmem_sb_info),
  4405. L1_CACHE_BYTES), GFP_KERNEL);
  4406. if (!sbinfo)
  4407. return error;
  4408. sb->s_fs_info = sbinfo;
  4409. #ifdef CONFIG_TMPFS
  4410. /*
  4411. * Per default we only allow half of the physical ram per
  4412. * tmpfs instance, limiting inodes to one per page of lowmem;
  4413. * but the internal instance is left unlimited.
  4414. */
  4415. if (!(sb->s_flags & SB_KERNMOUNT)) {
  4416. if (!(ctx->seen & SHMEM_SEEN_BLOCKS))
  4417. ctx->blocks = shmem_default_max_blocks();
  4418. if (!(ctx->seen & SHMEM_SEEN_INODES))
  4419. ctx->inodes = shmem_default_max_inodes();
  4420. if (!(ctx->seen & SHMEM_SEEN_INUMS))
  4421. ctx->full_inums = IS_ENABLED(CONFIG_TMPFS_INODE64);
  4422. sbinfo->noswap = ctx->noswap;
  4423. } else {
  4424. sb->s_flags |= SB_NOUSER;
  4425. }
  4426. sb->s_export_op = &shmem_export_ops;
  4427. sb->s_flags |= SB_NOSEC;
  4428. #if IS_ENABLED(CONFIG_UNICODE)
  4429. if (!ctx->encoding && ctx->strict_encoding) {
  4430. pr_err("tmpfs: strict_encoding option without encoding is forbidden\n");
  4431. error = -EINVAL;
  4432. goto failed;
  4433. }
  4434. if (ctx->encoding) {
  4435. sb->s_encoding = ctx->encoding;
  4436. set_default_d_op(sb, &shmem_ci_dentry_ops);
  4437. if (ctx->strict_encoding)
  4438. sb->s_encoding_flags = SB_ENC_STRICT_MODE_FL;
  4439. }
  4440. #endif
  4441. #else
  4442. sb->s_flags |= SB_NOUSER;
  4443. #endif /* CONFIG_TMPFS */
  4444. sb->s_d_flags |= DCACHE_DONTCACHE;
  4445. sbinfo->max_blocks = ctx->blocks;
  4446. sbinfo->max_inodes = ctx->inodes;
  4447. sbinfo->free_ispace = sbinfo->max_inodes * BOGO_INODE_SIZE;
  4448. if (sb->s_flags & SB_KERNMOUNT) {
  4449. sbinfo->ino_batch = alloc_percpu(ino_t);
  4450. if (!sbinfo->ino_batch)
  4451. goto failed;
  4452. }
  4453. sbinfo->uid = ctx->uid;
  4454. sbinfo->gid = ctx->gid;
  4455. sbinfo->full_inums = ctx->full_inums;
  4456. sbinfo->mode = ctx->mode;
  4457. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4458. if (ctx->seen & SHMEM_SEEN_HUGE)
  4459. sbinfo->huge = ctx->huge;
  4460. else
  4461. sbinfo->huge = tmpfs_huge;
  4462. #endif
  4463. sbinfo->mpol = ctx->mpol;
  4464. ctx->mpol = NULL;
  4465. raw_spin_lock_init(&sbinfo->stat_lock);
  4466. if (percpu_counter_init(&sbinfo->used_blocks, 0, GFP_KERNEL))
  4467. goto failed;
  4468. spin_lock_init(&sbinfo->shrinklist_lock);
  4469. INIT_LIST_HEAD(&sbinfo->shrinklist);
  4470. sb->s_maxbytes = MAX_LFS_FILESIZE;
  4471. sb->s_blocksize = PAGE_SIZE;
  4472. sb->s_blocksize_bits = PAGE_SHIFT;
  4473. sb->s_magic = TMPFS_MAGIC;
  4474. sb->s_op = &shmem_ops;
  4475. sb->s_time_gran = 1;
  4476. #ifdef CONFIG_TMPFS_XATTR
  4477. sb->s_xattr = shmem_xattr_handlers;
  4478. #endif
  4479. #ifdef CONFIG_TMPFS_POSIX_ACL
  4480. sb->s_flags |= SB_POSIXACL;
  4481. #endif
  4482. uuid_t uuid;
  4483. uuid_gen(&uuid);
  4484. super_set_uuid(sb, uuid.b, sizeof(uuid));
  4485. #ifdef CONFIG_TMPFS_QUOTA
  4486. if (ctx->seen & SHMEM_SEEN_QUOTA) {
  4487. sb->dq_op = &shmem_quota_operations;
  4488. sb->s_qcop = &dquot_quotactl_sysfile_ops;
  4489. sb->s_quota_types = QTYPE_MASK_USR | QTYPE_MASK_GRP;
  4490. /* Copy the default limits from ctx into sbinfo */
  4491. memcpy(&sbinfo->qlimits, &ctx->qlimits,
  4492. sizeof(struct shmem_quota_limits));
  4493. if (shmem_enable_quotas(sb, ctx->quota_types))
  4494. goto failed;
  4495. }
  4496. #endif /* CONFIG_TMPFS_QUOTA */
  4497. inode = shmem_get_inode(&nop_mnt_idmap, sb, NULL,
  4498. S_IFDIR | sbinfo->mode, 0,
  4499. mk_vma_flags(VMA_NORESERVE_BIT));
  4500. if (IS_ERR(inode)) {
  4501. error = PTR_ERR(inode);
  4502. goto failed;
  4503. }
  4504. inode->i_uid = sbinfo->uid;
  4505. inode->i_gid = sbinfo->gid;
  4506. sb->s_root = d_make_root(inode);
  4507. if (!sb->s_root)
  4508. goto failed;
  4509. return 0;
  4510. failed:
  4511. shmem_put_super(sb);
  4512. return error;
  4513. }
  4514. static int shmem_get_tree(struct fs_context *fc)
  4515. {
  4516. return get_tree_nodev(fc, shmem_fill_super);
  4517. }
  4518. static void shmem_free_fc(struct fs_context *fc)
  4519. {
  4520. struct shmem_options *ctx = fc->fs_private;
  4521. if (ctx) {
  4522. mpol_put(ctx->mpol);
  4523. kfree(ctx);
  4524. }
  4525. }
  4526. static const struct fs_context_operations shmem_fs_context_ops = {
  4527. .free = shmem_free_fc,
  4528. .get_tree = shmem_get_tree,
  4529. #ifdef CONFIG_TMPFS
  4530. .parse_monolithic = shmem_parse_monolithic,
  4531. .parse_param = shmem_parse_one,
  4532. .reconfigure = shmem_reconfigure,
  4533. #endif
  4534. };
  4535. static struct kmem_cache *shmem_inode_cachep __ro_after_init;
  4536. static struct inode *shmem_alloc_inode(struct super_block *sb)
  4537. {
  4538. struct shmem_inode_info *info;
  4539. info = alloc_inode_sb(sb, shmem_inode_cachep, GFP_KERNEL);
  4540. if (!info)
  4541. return NULL;
  4542. return &info->vfs_inode;
  4543. }
  4544. static void shmem_free_in_core_inode(struct inode *inode)
  4545. {
  4546. if (S_ISLNK(inode->i_mode))
  4547. kfree(inode->i_link);
  4548. kmem_cache_free(shmem_inode_cachep, SHMEM_I(inode));
  4549. }
  4550. static void shmem_destroy_inode(struct inode *inode)
  4551. {
  4552. if (S_ISREG(inode->i_mode))
  4553. mpol_free_shared_policy(&SHMEM_I(inode)->policy);
  4554. if (S_ISDIR(inode->i_mode))
  4555. simple_offset_destroy(shmem_get_offset_ctx(inode));
  4556. }
  4557. static void shmem_init_inode(void *foo)
  4558. {
  4559. struct shmem_inode_info *info = foo;
  4560. inode_init_once(&info->vfs_inode);
  4561. }
  4562. static void __init shmem_init_inodecache(void)
  4563. {
  4564. shmem_inode_cachep = kmem_cache_create("shmem_inode_cache",
  4565. sizeof(struct shmem_inode_info),
  4566. 0, SLAB_PANIC|SLAB_ACCOUNT, shmem_init_inode);
  4567. }
  4568. static void __init shmem_destroy_inodecache(void)
  4569. {
  4570. kmem_cache_destroy(shmem_inode_cachep);
  4571. }
  4572. /* Keep the page in page cache instead of truncating it */
  4573. static int shmem_error_remove_folio(struct address_space *mapping,
  4574. struct folio *folio)
  4575. {
  4576. return 0;
  4577. }
  4578. static const struct address_space_operations shmem_aops = {
  4579. .dirty_folio = noop_dirty_folio,
  4580. #ifdef CONFIG_TMPFS
  4581. .write_begin = shmem_write_begin,
  4582. .write_end = shmem_write_end,
  4583. #endif
  4584. #ifdef CONFIG_MIGRATION
  4585. .migrate_folio = migrate_folio,
  4586. #endif
  4587. .error_remove_folio = shmem_error_remove_folio,
  4588. };
  4589. static const struct file_operations shmem_file_operations = {
  4590. .mmap_prepare = shmem_mmap_prepare,
  4591. .open = shmem_file_open,
  4592. .get_unmapped_area = shmem_get_unmapped_area,
  4593. #ifdef CONFIG_TMPFS
  4594. .llseek = shmem_file_llseek,
  4595. .read_iter = shmem_file_read_iter,
  4596. .write_iter = shmem_file_write_iter,
  4597. .fsync = noop_fsync,
  4598. .splice_read = shmem_file_splice_read,
  4599. .splice_write = iter_file_splice_write,
  4600. .fallocate = shmem_fallocate,
  4601. .setlease = generic_setlease,
  4602. #endif
  4603. };
  4604. static const struct inode_operations shmem_inode_operations = {
  4605. .getattr = shmem_getattr,
  4606. .setattr = shmem_setattr,
  4607. #ifdef CONFIG_TMPFS_XATTR
  4608. .listxattr = shmem_listxattr,
  4609. .set_acl = simple_set_acl,
  4610. .fileattr_get = shmem_fileattr_get,
  4611. .fileattr_set = shmem_fileattr_set,
  4612. #endif
  4613. };
  4614. static const struct inode_operations shmem_dir_inode_operations = {
  4615. #ifdef CONFIG_TMPFS
  4616. .getattr = shmem_getattr,
  4617. .create = shmem_create,
  4618. .lookup = simple_lookup,
  4619. .link = shmem_link,
  4620. .unlink = shmem_unlink,
  4621. .symlink = shmem_symlink,
  4622. .mkdir = shmem_mkdir,
  4623. .rmdir = shmem_rmdir,
  4624. .mknod = shmem_mknod,
  4625. .rename = shmem_rename2,
  4626. .tmpfile = shmem_tmpfile,
  4627. .get_offset_ctx = shmem_get_offset_ctx,
  4628. #endif
  4629. #ifdef CONFIG_TMPFS_XATTR
  4630. .listxattr = shmem_listxattr,
  4631. .fileattr_get = shmem_fileattr_get,
  4632. .fileattr_set = shmem_fileattr_set,
  4633. #endif
  4634. #ifdef CONFIG_TMPFS_POSIX_ACL
  4635. .setattr = shmem_setattr,
  4636. .set_acl = simple_set_acl,
  4637. #endif
  4638. };
  4639. static const struct inode_operations shmem_special_inode_operations = {
  4640. .getattr = shmem_getattr,
  4641. #ifdef CONFIG_TMPFS_XATTR
  4642. .listxattr = shmem_listxattr,
  4643. #endif
  4644. #ifdef CONFIG_TMPFS_POSIX_ACL
  4645. .setattr = shmem_setattr,
  4646. .set_acl = simple_set_acl,
  4647. #endif
  4648. };
  4649. static const struct super_operations shmem_ops = {
  4650. .alloc_inode = shmem_alloc_inode,
  4651. .free_inode = shmem_free_in_core_inode,
  4652. .destroy_inode = shmem_destroy_inode,
  4653. #ifdef CONFIG_TMPFS
  4654. .statfs = shmem_statfs,
  4655. .show_options = shmem_show_options,
  4656. #endif
  4657. #ifdef CONFIG_TMPFS_QUOTA
  4658. .get_dquots = shmem_get_dquots,
  4659. #endif
  4660. .evict_inode = shmem_evict_inode,
  4661. .drop_inode = inode_just_drop,
  4662. .put_super = shmem_put_super,
  4663. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4664. .nr_cached_objects = shmem_unused_huge_count,
  4665. .free_cached_objects = shmem_unused_huge_scan,
  4666. #endif
  4667. };
  4668. static const struct vm_operations_struct shmem_vm_ops = {
  4669. .fault = shmem_fault,
  4670. .map_pages = filemap_map_pages,
  4671. #ifdef CONFIG_NUMA
  4672. .set_policy = shmem_set_policy,
  4673. .get_policy = shmem_get_policy,
  4674. #endif
  4675. };
  4676. static const struct vm_operations_struct shmem_anon_vm_ops = {
  4677. .fault = shmem_fault,
  4678. .map_pages = filemap_map_pages,
  4679. #ifdef CONFIG_NUMA
  4680. .set_policy = shmem_set_policy,
  4681. .get_policy = shmem_get_policy,
  4682. #endif
  4683. };
  4684. int shmem_init_fs_context(struct fs_context *fc)
  4685. {
  4686. struct shmem_options *ctx;
  4687. ctx = kzalloc_obj(struct shmem_options);
  4688. if (!ctx)
  4689. return -ENOMEM;
  4690. ctx->mode = 0777 | S_ISVTX;
  4691. ctx->uid = current_fsuid();
  4692. ctx->gid = current_fsgid();
  4693. #if IS_ENABLED(CONFIG_UNICODE)
  4694. ctx->encoding = NULL;
  4695. #endif
  4696. fc->fs_private = ctx;
  4697. fc->ops = &shmem_fs_context_ops;
  4698. #ifdef CONFIG_TMPFS
  4699. fc->sb_flags |= SB_I_VERSION;
  4700. #endif
  4701. return 0;
  4702. }
  4703. static struct file_system_type shmem_fs_type = {
  4704. .owner = THIS_MODULE,
  4705. .name = "tmpfs",
  4706. .init_fs_context = shmem_init_fs_context,
  4707. #ifdef CONFIG_TMPFS
  4708. .parameters = shmem_fs_parameters,
  4709. #endif
  4710. .kill_sb = kill_anon_super,
  4711. .fs_flags = FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME,
  4712. };
  4713. #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
  4714. #define __INIT_KOBJ_ATTR(_name, _mode, _show, _store) \
  4715. { \
  4716. .attr = { .name = __stringify(_name), .mode = _mode }, \
  4717. .show = _show, \
  4718. .store = _store, \
  4719. }
  4720. #define TMPFS_ATTR_W(_name, _store) \
  4721. static struct kobj_attribute tmpfs_attr_##_name = \
  4722. __INIT_KOBJ_ATTR(_name, 0200, NULL, _store)
  4723. #define TMPFS_ATTR_RW(_name, _show, _store) \
  4724. static struct kobj_attribute tmpfs_attr_##_name = \
  4725. __INIT_KOBJ_ATTR(_name, 0644, _show, _store)
  4726. #define TMPFS_ATTR_RO(_name, _show) \
  4727. static struct kobj_attribute tmpfs_attr_##_name = \
  4728. __INIT_KOBJ_ATTR(_name, 0444, _show, NULL)
  4729. #if IS_ENABLED(CONFIG_UNICODE)
  4730. static ssize_t casefold_show(struct kobject *kobj, struct kobj_attribute *a,
  4731. char *buf)
  4732. {
  4733. return sysfs_emit(buf, "supported\n");
  4734. }
  4735. TMPFS_ATTR_RO(casefold, casefold_show);
  4736. #endif
  4737. static struct attribute *tmpfs_attributes[] = {
  4738. #if IS_ENABLED(CONFIG_UNICODE)
  4739. &tmpfs_attr_casefold.attr,
  4740. #endif
  4741. NULL
  4742. };
  4743. static const struct attribute_group tmpfs_attribute_group = {
  4744. .attrs = tmpfs_attributes,
  4745. .name = "features"
  4746. };
  4747. static struct kobject *tmpfs_kobj;
  4748. static int __init tmpfs_sysfs_init(void)
  4749. {
  4750. int ret;
  4751. tmpfs_kobj = kobject_create_and_add("tmpfs", fs_kobj);
  4752. if (!tmpfs_kobj)
  4753. return -ENOMEM;
  4754. ret = sysfs_create_group(tmpfs_kobj, &tmpfs_attribute_group);
  4755. if (ret)
  4756. kobject_put(tmpfs_kobj);
  4757. return ret;
  4758. }
  4759. #endif /* CONFIG_SYSFS && CONFIG_TMPFS */
  4760. void __init shmem_init(void)
  4761. {
  4762. int error;
  4763. shmem_init_inodecache();
  4764. #ifdef CONFIG_TMPFS_QUOTA
  4765. register_quota_format(&shmem_quota_format);
  4766. #endif
  4767. error = register_filesystem(&shmem_fs_type);
  4768. if (error) {
  4769. pr_err("Could not register tmpfs\n");
  4770. goto out2;
  4771. }
  4772. shm_mnt = kern_mount(&shmem_fs_type);
  4773. if (IS_ERR(shm_mnt)) {
  4774. error = PTR_ERR(shm_mnt);
  4775. pr_err("Could not kern_mount tmpfs\n");
  4776. goto out1;
  4777. }
  4778. #if defined(CONFIG_SYSFS) && defined(CONFIG_TMPFS)
  4779. error = tmpfs_sysfs_init();
  4780. if (error) {
  4781. pr_err("Could not init tmpfs sysfs\n");
  4782. goto out1;
  4783. }
  4784. #endif
  4785. #ifdef CONFIG_TRANSPARENT_HUGEPAGE
  4786. if (has_transparent_hugepage() && shmem_huge > SHMEM_HUGE_DENY)
  4787. SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
  4788. else
  4789. shmem_huge = SHMEM_HUGE_NEVER; /* just in case it was patched */
  4790. /*
  4791. * Default to setting PMD-sized THP to inherit the global setting and
  4792. * disable all other multi-size THPs.
  4793. */
  4794. if (!shmem_orders_configured)
  4795. huge_shmem_orders_inherit = BIT(HPAGE_PMD_ORDER);
  4796. #endif
  4797. return;
  4798. out1:
  4799. unregister_filesystem(&shmem_fs_type);
  4800. out2:
  4801. #ifdef CONFIG_TMPFS_QUOTA
  4802. unregister_quota_format(&shmem_quota_format);
  4803. #endif
  4804. shmem_destroy_inodecache();
  4805. shm_mnt = ERR_PTR(error);
  4806. }
  4807. #if defined(CONFIG_TRANSPARENT_HUGEPAGE) && defined(CONFIG_SYSFS)
  4808. static ssize_t shmem_enabled_show(struct kobject *kobj,
  4809. struct kobj_attribute *attr, char *buf)
  4810. {
  4811. static const int values[] = {
  4812. SHMEM_HUGE_ALWAYS,
  4813. SHMEM_HUGE_WITHIN_SIZE,
  4814. SHMEM_HUGE_ADVISE,
  4815. SHMEM_HUGE_NEVER,
  4816. SHMEM_HUGE_DENY,
  4817. SHMEM_HUGE_FORCE,
  4818. };
  4819. int len = 0;
  4820. int i;
  4821. for (i = 0; i < ARRAY_SIZE(values); i++) {
  4822. len += sysfs_emit_at(buf, len,
  4823. shmem_huge == values[i] ? "%s[%s]" : "%s%s",
  4824. i ? " " : "", shmem_format_huge(values[i]));
  4825. }
  4826. len += sysfs_emit_at(buf, len, "\n");
  4827. return len;
  4828. }
  4829. static ssize_t shmem_enabled_store(struct kobject *kobj,
  4830. struct kobj_attribute *attr, const char *buf, size_t count)
  4831. {
  4832. char tmp[16];
  4833. int huge, err;
  4834. if (count + 1 > sizeof(tmp))
  4835. return -EINVAL;
  4836. memcpy(tmp, buf, count);
  4837. tmp[count] = '\0';
  4838. if (count && tmp[count - 1] == '\n')
  4839. tmp[count - 1] = '\0';
  4840. huge = shmem_parse_huge(tmp);
  4841. if (huge == -EINVAL)
  4842. return huge;
  4843. shmem_huge = huge;
  4844. if (shmem_huge > SHMEM_HUGE_DENY)
  4845. SHMEM_SB(shm_mnt->mnt_sb)->huge = shmem_huge;
  4846. err = start_stop_khugepaged();
  4847. return err ? err : count;
  4848. }
  4849. struct kobj_attribute shmem_enabled_attr = __ATTR_RW(shmem_enabled);
  4850. static DEFINE_SPINLOCK(huge_shmem_orders_lock);
  4851. static ssize_t thpsize_shmem_enabled_show(struct kobject *kobj,
  4852. struct kobj_attribute *attr, char *buf)
  4853. {
  4854. int order = to_thpsize(kobj)->order;
  4855. const char *output;
  4856. if (test_bit(order, &huge_shmem_orders_always))
  4857. output = "[always] inherit within_size advise never";
  4858. else if (test_bit(order, &huge_shmem_orders_inherit))
  4859. output = "always [inherit] within_size advise never";
  4860. else if (test_bit(order, &huge_shmem_orders_within_size))
  4861. output = "always inherit [within_size] advise never";
  4862. else if (test_bit(order, &huge_shmem_orders_madvise))
  4863. output = "always inherit within_size [advise] never";
  4864. else
  4865. output = "always inherit within_size advise [never]";
  4866. return sysfs_emit(buf, "%s\n", output);
  4867. }
  4868. static ssize_t thpsize_shmem_enabled_store(struct kobject *kobj,
  4869. struct kobj_attribute *attr,
  4870. const char *buf, size_t count)
  4871. {
  4872. int order = to_thpsize(kobj)->order;
  4873. ssize_t ret = count;
  4874. if (sysfs_streq(buf, "always")) {
  4875. spin_lock(&huge_shmem_orders_lock);
  4876. clear_bit(order, &huge_shmem_orders_inherit);
  4877. clear_bit(order, &huge_shmem_orders_madvise);
  4878. clear_bit(order, &huge_shmem_orders_within_size);
  4879. set_bit(order, &huge_shmem_orders_always);
  4880. spin_unlock(&huge_shmem_orders_lock);
  4881. } else if (sysfs_streq(buf, "inherit")) {
  4882. /* Do not override huge allocation policy with non-PMD sized mTHP */
  4883. if (shmem_huge == SHMEM_HUGE_FORCE &&
  4884. order != HPAGE_PMD_ORDER)
  4885. return -EINVAL;
  4886. spin_lock(&huge_shmem_orders_lock);
  4887. clear_bit(order, &huge_shmem_orders_always);
  4888. clear_bit(order, &huge_shmem_orders_madvise);
  4889. clear_bit(order, &huge_shmem_orders_within_size);
  4890. set_bit(order, &huge_shmem_orders_inherit);
  4891. spin_unlock(&huge_shmem_orders_lock);
  4892. } else if (sysfs_streq(buf, "within_size")) {
  4893. spin_lock(&huge_shmem_orders_lock);
  4894. clear_bit(order, &huge_shmem_orders_always);
  4895. clear_bit(order, &huge_shmem_orders_inherit);
  4896. clear_bit(order, &huge_shmem_orders_madvise);
  4897. set_bit(order, &huge_shmem_orders_within_size);
  4898. spin_unlock(&huge_shmem_orders_lock);
  4899. } else if (sysfs_streq(buf, "advise")) {
  4900. spin_lock(&huge_shmem_orders_lock);
  4901. clear_bit(order, &huge_shmem_orders_always);
  4902. clear_bit(order, &huge_shmem_orders_inherit);
  4903. clear_bit(order, &huge_shmem_orders_within_size);
  4904. set_bit(order, &huge_shmem_orders_madvise);
  4905. spin_unlock(&huge_shmem_orders_lock);
  4906. } else if (sysfs_streq(buf, "never")) {
  4907. spin_lock(&huge_shmem_orders_lock);
  4908. clear_bit(order, &huge_shmem_orders_always);
  4909. clear_bit(order, &huge_shmem_orders_inherit);
  4910. clear_bit(order, &huge_shmem_orders_within_size);
  4911. clear_bit(order, &huge_shmem_orders_madvise);
  4912. spin_unlock(&huge_shmem_orders_lock);
  4913. } else {
  4914. ret = -EINVAL;
  4915. }
  4916. if (ret > 0) {
  4917. int err = start_stop_khugepaged();
  4918. if (err)
  4919. ret = err;
  4920. }
  4921. return ret;
  4922. }
  4923. struct kobj_attribute thpsize_shmem_enabled_attr =
  4924. __ATTR(shmem_enabled, 0644, thpsize_shmem_enabled_show, thpsize_shmem_enabled_store);
  4925. #endif /* CONFIG_TRANSPARENT_HUGEPAGE && CONFIG_SYSFS */
  4926. #if defined(CONFIG_TRANSPARENT_HUGEPAGE)
  4927. static int __init setup_transparent_hugepage_shmem(char *str)
  4928. {
  4929. int huge;
  4930. huge = shmem_parse_huge(str);
  4931. if (huge == -EINVAL) {
  4932. pr_warn("transparent_hugepage_shmem= cannot parse, ignored\n");
  4933. return huge;
  4934. }
  4935. shmem_huge = huge;
  4936. return 1;
  4937. }
  4938. __setup("transparent_hugepage_shmem=", setup_transparent_hugepage_shmem);
  4939. static int __init setup_transparent_hugepage_tmpfs(char *str)
  4940. {
  4941. int huge;
  4942. huge = shmem_parse_huge(str);
  4943. if (huge < 0) {
  4944. pr_warn("transparent_hugepage_tmpfs= cannot parse, ignored\n");
  4945. return huge;
  4946. }
  4947. tmpfs_huge = huge;
  4948. return 1;
  4949. }
  4950. __setup("transparent_hugepage_tmpfs=", setup_transparent_hugepage_tmpfs);
  4951. static char str_dup[PAGE_SIZE] __initdata;
  4952. static int __init setup_thp_shmem(char *str)
  4953. {
  4954. char *token, *range, *policy, *subtoken;
  4955. unsigned long always, inherit, madvise, within_size;
  4956. char *start_size, *end_size;
  4957. int start, end, nr;
  4958. char *p;
  4959. if (!str || strlen(str) + 1 > PAGE_SIZE)
  4960. goto err;
  4961. strscpy(str_dup, str);
  4962. always = huge_shmem_orders_always;
  4963. inherit = huge_shmem_orders_inherit;
  4964. madvise = huge_shmem_orders_madvise;
  4965. within_size = huge_shmem_orders_within_size;
  4966. p = str_dup;
  4967. while ((token = strsep(&p, ";")) != NULL) {
  4968. range = strsep(&token, ":");
  4969. policy = token;
  4970. if (!policy)
  4971. goto err;
  4972. while ((subtoken = strsep(&range, ",")) != NULL) {
  4973. if (strchr(subtoken, '-')) {
  4974. start_size = strsep(&subtoken, "-");
  4975. end_size = subtoken;
  4976. start = get_order_from_str(start_size,
  4977. THP_ORDERS_ALL_FILE_DEFAULT);
  4978. end = get_order_from_str(end_size,
  4979. THP_ORDERS_ALL_FILE_DEFAULT);
  4980. } else {
  4981. start_size = end_size = subtoken;
  4982. start = end = get_order_from_str(subtoken,
  4983. THP_ORDERS_ALL_FILE_DEFAULT);
  4984. }
  4985. if (start < 0) {
  4986. pr_err("invalid size %s in thp_shmem boot parameter\n",
  4987. start_size);
  4988. goto err;
  4989. }
  4990. if (end < 0) {
  4991. pr_err("invalid size %s in thp_shmem boot parameter\n",
  4992. end_size);
  4993. goto err;
  4994. }
  4995. if (start > end)
  4996. goto err;
  4997. nr = end - start + 1;
  4998. if (!strcmp(policy, "always")) {
  4999. bitmap_set(&always, start, nr);
  5000. bitmap_clear(&inherit, start, nr);
  5001. bitmap_clear(&madvise, start, nr);
  5002. bitmap_clear(&within_size, start, nr);
  5003. } else if (!strcmp(policy, "advise")) {
  5004. bitmap_set(&madvise, start, nr);
  5005. bitmap_clear(&inherit, start, nr);
  5006. bitmap_clear(&always, start, nr);
  5007. bitmap_clear(&within_size, start, nr);
  5008. } else if (!strcmp(policy, "inherit")) {
  5009. bitmap_set(&inherit, start, nr);
  5010. bitmap_clear(&madvise, start, nr);
  5011. bitmap_clear(&always, start, nr);
  5012. bitmap_clear(&within_size, start, nr);
  5013. } else if (!strcmp(policy, "within_size")) {
  5014. bitmap_set(&within_size, start, nr);
  5015. bitmap_clear(&inherit, start, nr);
  5016. bitmap_clear(&madvise, start, nr);
  5017. bitmap_clear(&always, start, nr);
  5018. } else if (!strcmp(policy, "never")) {
  5019. bitmap_clear(&inherit, start, nr);
  5020. bitmap_clear(&madvise, start, nr);
  5021. bitmap_clear(&always, start, nr);
  5022. bitmap_clear(&within_size, start, nr);
  5023. } else {
  5024. pr_err("invalid policy %s in thp_shmem boot parameter\n", policy);
  5025. goto err;
  5026. }
  5027. }
  5028. }
  5029. huge_shmem_orders_always = always;
  5030. huge_shmem_orders_madvise = madvise;
  5031. huge_shmem_orders_inherit = inherit;
  5032. huge_shmem_orders_within_size = within_size;
  5033. shmem_orders_configured = true;
  5034. return 1;
  5035. err:
  5036. pr_warn("thp_shmem=%s: error parsing string, ignoring setting\n", str);
  5037. return 0;
  5038. }
  5039. __setup("thp_shmem=", setup_thp_shmem);
  5040. #endif /* CONFIG_TRANSPARENT_HUGEPAGE */
  5041. #else /* !CONFIG_SHMEM */
  5042. /*
  5043. * tiny-shmem: simple shmemfs and tmpfs using ramfs code
  5044. *
  5045. * This is intended for small system where the benefits of the full
  5046. * shmem code (swap-backed and resource-limited) are outweighed by
  5047. * their complexity. On systems without swap this code should be
  5048. * effectively equivalent, but much lighter weight.
  5049. */
  5050. static struct file_system_type shmem_fs_type = {
  5051. .name = "tmpfs",
  5052. .init_fs_context = ramfs_init_fs_context,
  5053. .parameters = ramfs_fs_parameters,
  5054. .kill_sb = ramfs_kill_sb,
  5055. .fs_flags = FS_USERNS_MOUNT,
  5056. };
  5057. void __init shmem_init(void)
  5058. {
  5059. BUG_ON(register_filesystem(&shmem_fs_type) != 0);
  5060. shm_mnt = kern_mount(&shmem_fs_type);
  5061. BUG_ON(IS_ERR(shm_mnt));
  5062. }
  5063. int shmem_unuse(unsigned int type)
  5064. {
  5065. return 0;
  5066. }
  5067. int shmem_lock(struct file *file, int lock, struct ucounts *ucounts)
  5068. {
  5069. return 0;
  5070. }
  5071. void shmem_unlock_mapping(struct address_space *mapping)
  5072. {
  5073. }
  5074. #ifdef CONFIG_MMU
  5075. unsigned long shmem_get_unmapped_area(struct file *file,
  5076. unsigned long addr, unsigned long len,
  5077. unsigned long pgoff, unsigned long flags)
  5078. {
  5079. return mm_get_unmapped_area(file, addr, len, pgoff, flags);
  5080. }
  5081. #endif
  5082. void shmem_truncate_range(struct inode *inode, loff_t lstart, uoff_t lend)
  5083. {
  5084. truncate_inode_pages_range(inode->i_mapping, lstart, lend);
  5085. }
  5086. EXPORT_SYMBOL_GPL(shmem_truncate_range);
  5087. #define shmem_vm_ops generic_file_vm_ops
  5088. #define shmem_anon_vm_ops generic_file_vm_ops
  5089. #define shmem_file_operations ramfs_file_operations
  5090. static inline int shmem_acct_size(unsigned long flags, loff_t size)
  5091. {
  5092. return 0;
  5093. }
  5094. static inline void shmem_unacct_size(unsigned long flags, loff_t size)
  5095. {
  5096. }
  5097. static inline struct inode *shmem_get_inode(struct mnt_idmap *idmap,
  5098. struct super_block *sb, struct inode *dir,
  5099. umode_t mode, dev_t dev, vma_flags_t flags)
  5100. {
  5101. struct inode *inode = ramfs_get_inode(sb, dir, mode, dev);
  5102. return inode ? inode : ERR_PTR(-ENOSPC);
  5103. }
  5104. #endif /* CONFIG_SHMEM */
  5105. /* common code */
  5106. static struct file *__shmem_file_setup(struct vfsmount *mnt, const char *name,
  5107. loff_t size, vma_flags_t flags,
  5108. unsigned int i_flags)
  5109. {
  5110. const unsigned long shmem_flags =
  5111. vma_flags_test(&flags, VMA_NORESERVE_BIT) ? SHMEM_F_NORESERVE : 0;
  5112. struct inode *inode;
  5113. struct file *res;
  5114. if (IS_ERR(mnt))
  5115. return ERR_CAST(mnt);
  5116. if (size < 0 || size > MAX_LFS_FILESIZE)
  5117. return ERR_PTR(-EINVAL);
  5118. if (is_idmapped_mnt(mnt))
  5119. return ERR_PTR(-EINVAL);
  5120. if (shmem_acct_size(shmem_flags, size))
  5121. return ERR_PTR(-ENOMEM);
  5122. inode = shmem_get_inode(&nop_mnt_idmap, mnt->mnt_sb, NULL,
  5123. S_IFREG | S_IRWXUGO, 0, flags);
  5124. if (IS_ERR(inode)) {
  5125. shmem_unacct_size(shmem_flags, size);
  5126. return ERR_CAST(inode);
  5127. }
  5128. inode->i_flags |= i_flags;
  5129. inode->i_size = size;
  5130. clear_nlink(inode); /* It is unlinked */
  5131. res = ERR_PTR(ramfs_nommu_expand_for_mapping(inode, size));
  5132. if (!IS_ERR(res))
  5133. res = alloc_file_pseudo(inode, mnt, name, O_RDWR,
  5134. &shmem_file_operations);
  5135. if (IS_ERR(res))
  5136. iput(inode);
  5137. return res;
  5138. }
  5139. /**
  5140. * shmem_kernel_file_setup - get an unlinked file living in tmpfs which must be
  5141. * kernel internal. There will be NO LSM permission checks against the
  5142. * underlying inode. So users of this interface must do LSM checks at a
  5143. * higher layer. The users are the big_key and shm implementations. LSM
  5144. * checks are provided at the key or shm level rather than the inode.
  5145. * @name: name for dentry (to be seen in /proc/<pid>/maps)
  5146. * @size: size to be set for the file
  5147. * @flags: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size
  5148. */
  5149. struct file *shmem_kernel_file_setup(const char *name, loff_t size,
  5150. vma_flags_t flags)
  5151. {
  5152. return __shmem_file_setup(shm_mnt, name, size, flags, S_PRIVATE);
  5153. }
  5154. EXPORT_SYMBOL_GPL(shmem_kernel_file_setup);
  5155. /**
  5156. * shmem_file_setup - get an unlinked file living in tmpfs
  5157. * @name: name for dentry (to be seen in /proc/<pid>/maps)
  5158. * @size: size to be set for the file
  5159. * @flags: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size
  5160. */
  5161. struct file *shmem_file_setup(const char *name, loff_t size, vma_flags_t flags)
  5162. {
  5163. return __shmem_file_setup(shm_mnt, name, size, flags, 0);
  5164. }
  5165. EXPORT_SYMBOL_GPL(shmem_file_setup);
  5166. /**
  5167. * shmem_file_setup_with_mnt - get an unlinked file living in tmpfs
  5168. * @mnt: the tmpfs mount where the file will be created
  5169. * @name: name for dentry (to be seen in /proc/<pid>/maps)
  5170. * @size: size to be set for the file
  5171. * @flags: VMA_NORESERVE_BIT suppresses pre-accounting of the entire object size
  5172. */
  5173. struct file *shmem_file_setup_with_mnt(struct vfsmount *mnt, const char *name,
  5174. loff_t size, vma_flags_t flags)
  5175. {
  5176. return __shmem_file_setup(mnt, name, size, flags, 0);
  5177. }
  5178. EXPORT_SYMBOL_GPL(shmem_file_setup_with_mnt);
  5179. static struct file *__shmem_zero_setup(unsigned long start, unsigned long end,
  5180. vma_flags_t flags)
  5181. {
  5182. loff_t size = end - start;
  5183. /*
  5184. * Cloning a new file under mmap_lock leads to a lock ordering conflict
  5185. * between XFS directory reading and selinux: since this file is only
  5186. * accessible to the user through its mapping, use S_PRIVATE flag to
  5187. * bypass file security, in the same way as shmem_kernel_file_setup().
  5188. */
  5189. return shmem_kernel_file_setup("dev/zero", size, flags);
  5190. }
  5191. /**
  5192. * shmem_zero_setup - setup a shared anonymous mapping
  5193. * @vma: the vma to be mmapped is prepared by do_mmap
  5194. * Returns: 0 on success, or error
  5195. */
  5196. int shmem_zero_setup(struct vm_area_struct *vma)
  5197. {
  5198. struct file *file = __shmem_zero_setup(vma->vm_start, vma->vm_end, vma->flags);
  5199. if (IS_ERR(file))
  5200. return PTR_ERR(file);
  5201. if (vma->vm_file)
  5202. fput(vma->vm_file);
  5203. vma->vm_file = file;
  5204. vma->vm_ops = &shmem_anon_vm_ops;
  5205. return 0;
  5206. }
  5207. /**
  5208. * shmem_zero_setup_desc - same as shmem_zero_setup, but determined by VMA
  5209. * descriptor for convenience.
  5210. * @desc: Describes VMA
  5211. * Returns: 0 on success, or error
  5212. */
  5213. int shmem_zero_setup_desc(struct vm_area_desc *desc)
  5214. {
  5215. struct file *file = __shmem_zero_setup(desc->start, desc->end, desc->vma_flags);
  5216. if (IS_ERR(file))
  5217. return PTR_ERR(file);
  5218. desc->vm_file = file;
  5219. desc->vm_ops = &shmem_anon_vm_ops;
  5220. return 0;
  5221. }
  5222. /**
  5223. * shmem_read_folio_gfp - read into page cache, using specified page allocation flags.
  5224. * @mapping: the folio's address_space
  5225. * @index: the folio index
  5226. * @gfp: the page allocator flags to use if allocating
  5227. *
  5228. * This behaves as a tmpfs "read_cache_page_gfp(mapping, index, gfp)",
  5229. * with any new page allocations done using the specified allocation flags.
  5230. * But read_cache_page_gfp() uses the ->read_folio() method: which does not
  5231. * suit tmpfs, since it may have pages in swapcache, and needs to find those
  5232. * for itself; although drivers/gpu/drm i915 and ttm rely upon this support.
  5233. *
  5234. * i915_gem_object_get_pages_gtt() mixes __GFP_NORETRY | __GFP_NOWARN in
  5235. * with the mapping_gfp_mask(), to avoid OOMing the machine unnecessarily.
  5236. */
  5237. struct folio *shmem_read_folio_gfp(struct address_space *mapping,
  5238. pgoff_t index, gfp_t gfp)
  5239. {
  5240. #ifdef CONFIG_SHMEM
  5241. struct inode *inode = mapping->host;
  5242. struct folio *folio;
  5243. int error;
  5244. error = shmem_get_folio_gfp(inode, index, i_size_read(inode),
  5245. &folio, SGP_CACHE, gfp, NULL, NULL);
  5246. if (error)
  5247. return ERR_PTR(error);
  5248. folio_unlock(folio);
  5249. return folio;
  5250. #else
  5251. /*
  5252. * The tiny !SHMEM case uses ramfs without swap
  5253. */
  5254. return mapping_read_folio_gfp(mapping, index, gfp);
  5255. #endif
  5256. }
  5257. EXPORT_SYMBOL_GPL(shmem_read_folio_gfp);
  5258. struct page *shmem_read_mapping_page_gfp(struct address_space *mapping,
  5259. pgoff_t index, gfp_t gfp)
  5260. {
  5261. struct folio *folio = shmem_read_folio_gfp(mapping, index, gfp);
  5262. struct page *page;
  5263. if (IS_ERR(folio))
  5264. return &folio->page;
  5265. page = folio_file_page(folio, index);
  5266. if (PageHWPoison(page)) {
  5267. folio_put(folio);
  5268. return ERR_PTR(-EIO);
  5269. }
  5270. return page;
  5271. }
  5272. EXPORT_SYMBOL_GPL(shmem_read_mapping_page_gfp);