vmalloc.c 141 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 1993 Linus Torvalds
  4. * Support of BIGMEM added by Gerhard Wichert, Siemens AG, July 1999
  5. * SMP-safe vmalloc/vfree/ioremap, Tigran Aivazian <tigran@veritas.com>, May 2000
  6. * Major rework to support vmap/vunmap, Christoph Hellwig, SGI, August 2002
  7. * Numa awareness, Christoph Lameter, SGI, June 2005
  8. * Improving global KVA allocator, Uladzislau Rezki, Sony, May 2019
  9. */
  10. #include <linux/vmalloc.h>
  11. #include <linux/mm.h>
  12. #include <linux/module.h>
  13. #include <linux/highmem.h>
  14. #include <linux/sched/signal.h>
  15. #include <linux/slab.h>
  16. #include <linux/spinlock.h>
  17. #include <linux/interrupt.h>
  18. #include <linux/proc_fs.h>
  19. #include <linux/seq_file.h>
  20. #include <linux/set_memory.h>
  21. #include <linux/debugobjects.h>
  22. #include <linux/kallsyms.h>
  23. #include <linux/list.h>
  24. #include <linux/notifier.h>
  25. #include <linux/rbtree.h>
  26. #include <linux/xarray.h>
  27. #include <linux/io.h>
  28. #include <linux/rcupdate.h>
  29. #include <linux/pfn.h>
  30. #include <linux/kmemleak.h>
  31. #include <linux/atomic.h>
  32. #include <linux/compiler.h>
  33. #include <linux/memcontrol.h>
  34. #include <linux/llist.h>
  35. #include <linux/uio.h>
  36. #include <linux/bitops.h>
  37. #include <linux/rbtree_augmented.h>
  38. #include <linux/overflow.h>
  39. #include <linux/pgtable.h>
  40. #include <linux/hugetlb.h>
  41. #include <linux/sched/mm.h>
  42. #include <asm/tlbflush.h>
  43. #include <asm/shmparam.h>
  44. #include <linux/page_owner.h>
  45. #define CREATE_TRACE_POINTS
  46. #include <trace/events/vmalloc.h>
  47. #include "internal.h"
  48. #include "pgalloc-track.h"
  49. #ifdef CONFIG_HAVE_ARCH_HUGE_VMAP
  50. static unsigned int __ro_after_init ioremap_max_page_shift = BITS_PER_LONG - 1;
  51. static int __init set_nohugeiomap(char *str)
  52. {
  53. ioremap_max_page_shift = PAGE_SHIFT;
  54. return 0;
  55. }
  56. early_param("nohugeiomap", set_nohugeiomap);
  57. #else /* CONFIG_HAVE_ARCH_HUGE_VMAP */
  58. static const unsigned int ioremap_max_page_shift = PAGE_SHIFT;
  59. #endif /* CONFIG_HAVE_ARCH_HUGE_VMAP */
  60. #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
  61. static bool __ro_after_init vmap_allow_huge = true;
  62. static int __init set_nohugevmalloc(char *str)
  63. {
  64. vmap_allow_huge = false;
  65. return 0;
  66. }
  67. early_param("nohugevmalloc", set_nohugevmalloc);
  68. #else /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
  69. static const bool vmap_allow_huge = false;
  70. #endif /* CONFIG_HAVE_ARCH_HUGE_VMALLOC */
  71. bool is_vmalloc_addr(const void *x)
  72. {
  73. unsigned long addr = (unsigned long)kasan_reset_tag(x);
  74. return addr >= VMALLOC_START && addr < VMALLOC_END;
  75. }
  76. EXPORT_SYMBOL(is_vmalloc_addr);
  77. struct vfree_deferred {
  78. struct llist_head list;
  79. struct work_struct wq;
  80. };
  81. static DEFINE_PER_CPU(struct vfree_deferred, vfree_deferred);
  82. /*** Page table manipulation functions ***/
  83. static int vmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
  84. phys_addr_t phys_addr, pgprot_t prot,
  85. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  86. {
  87. pte_t *pte;
  88. u64 pfn;
  89. struct page *page;
  90. unsigned long size = PAGE_SIZE;
  91. if (WARN_ON_ONCE(!PAGE_ALIGNED(end - addr)))
  92. return -EINVAL;
  93. pfn = phys_addr >> PAGE_SHIFT;
  94. pte = pte_alloc_kernel_track(pmd, addr, mask);
  95. if (!pte)
  96. return -ENOMEM;
  97. lazy_mmu_mode_enable();
  98. do {
  99. if (unlikely(!pte_none(ptep_get(pte)))) {
  100. if (pfn_valid(pfn)) {
  101. page = pfn_to_page(pfn);
  102. dump_page(page, "remapping already mapped page");
  103. }
  104. BUG();
  105. }
  106. #ifdef CONFIG_HUGETLB_PAGE
  107. size = arch_vmap_pte_range_map_size(addr, end, pfn, max_page_shift);
  108. if (size != PAGE_SIZE) {
  109. pte_t entry = pfn_pte(pfn, prot);
  110. entry = arch_make_huge_pte(entry, ilog2(size), 0);
  111. set_huge_pte_at(&init_mm, addr, pte, entry, size);
  112. pfn += PFN_DOWN(size);
  113. continue;
  114. }
  115. #endif
  116. set_pte_at(&init_mm, addr, pte, pfn_pte(pfn, prot));
  117. pfn++;
  118. } while (pte += PFN_DOWN(size), addr += size, addr != end);
  119. lazy_mmu_mode_disable();
  120. *mask |= PGTBL_PTE_MODIFIED;
  121. return 0;
  122. }
  123. static int vmap_try_huge_pmd(pmd_t *pmd, unsigned long addr, unsigned long end,
  124. phys_addr_t phys_addr, pgprot_t prot,
  125. unsigned int max_page_shift)
  126. {
  127. if (max_page_shift < PMD_SHIFT)
  128. return 0;
  129. if (!arch_vmap_pmd_supported(prot))
  130. return 0;
  131. if ((end - addr) != PMD_SIZE)
  132. return 0;
  133. if (!IS_ALIGNED(addr, PMD_SIZE))
  134. return 0;
  135. if (!IS_ALIGNED(phys_addr, PMD_SIZE))
  136. return 0;
  137. if (pmd_present(*pmd) && !pmd_free_pte_page(pmd, addr))
  138. return 0;
  139. return pmd_set_huge(pmd, phys_addr, prot);
  140. }
  141. static int vmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
  142. phys_addr_t phys_addr, pgprot_t prot,
  143. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  144. {
  145. pmd_t *pmd;
  146. unsigned long next;
  147. int err = 0;
  148. pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
  149. if (!pmd)
  150. return -ENOMEM;
  151. do {
  152. next = pmd_addr_end(addr, end);
  153. if (vmap_try_huge_pmd(pmd, addr, next, phys_addr, prot,
  154. max_page_shift)) {
  155. *mask |= PGTBL_PMD_MODIFIED;
  156. continue;
  157. }
  158. err = vmap_pte_range(pmd, addr, next, phys_addr, prot, max_page_shift, mask);
  159. if (err)
  160. break;
  161. } while (pmd++, phys_addr += (next - addr), addr = next, addr != end);
  162. return err;
  163. }
  164. static int vmap_try_huge_pud(pud_t *pud, unsigned long addr, unsigned long end,
  165. phys_addr_t phys_addr, pgprot_t prot,
  166. unsigned int max_page_shift)
  167. {
  168. if (max_page_shift < PUD_SHIFT)
  169. return 0;
  170. if (!arch_vmap_pud_supported(prot))
  171. return 0;
  172. if ((end - addr) != PUD_SIZE)
  173. return 0;
  174. if (!IS_ALIGNED(addr, PUD_SIZE))
  175. return 0;
  176. if (!IS_ALIGNED(phys_addr, PUD_SIZE))
  177. return 0;
  178. if (pud_present(*pud) && !pud_free_pmd_page(pud, addr))
  179. return 0;
  180. return pud_set_huge(pud, phys_addr, prot);
  181. }
  182. static int vmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
  183. phys_addr_t phys_addr, pgprot_t prot,
  184. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  185. {
  186. pud_t *pud;
  187. unsigned long next;
  188. int err = 0;
  189. pud = pud_alloc_track(&init_mm, p4d, addr, mask);
  190. if (!pud)
  191. return -ENOMEM;
  192. do {
  193. next = pud_addr_end(addr, end);
  194. if (vmap_try_huge_pud(pud, addr, next, phys_addr, prot,
  195. max_page_shift)) {
  196. *mask |= PGTBL_PUD_MODIFIED;
  197. continue;
  198. }
  199. err = vmap_pmd_range(pud, addr, next, phys_addr, prot, max_page_shift, mask);
  200. if (err)
  201. break;
  202. } while (pud++, phys_addr += (next - addr), addr = next, addr != end);
  203. return err;
  204. }
  205. static int vmap_try_huge_p4d(p4d_t *p4d, unsigned long addr, unsigned long end,
  206. phys_addr_t phys_addr, pgprot_t prot,
  207. unsigned int max_page_shift)
  208. {
  209. if (max_page_shift < P4D_SHIFT)
  210. return 0;
  211. if (!arch_vmap_p4d_supported(prot))
  212. return 0;
  213. if ((end - addr) != P4D_SIZE)
  214. return 0;
  215. if (!IS_ALIGNED(addr, P4D_SIZE))
  216. return 0;
  217. if (!IS_ALIGNED(phys_addr, P4D_SIZE))
  218. return 0;
  219. if (p4d_present(*p4d) && !p4d_free_pud_page(p4d, addr))
  220. return 0;
  221. return p4d_set_huge(p4d, phys_addr, prot);
  222. }
  223. static int vmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
  224. phys_addr_t phys_addr, pgprot_t prot,
  225. unsigned int max_page_shift, pgtbl_mod_mask *mask)
  226. {
  227. p4d_t *p4d;
  228. unsigned long next;
  229. int err = 0;
  230. p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
  231. if (!p4d)
  232. return -ENOMEM;
  233. do {
  234. next = p4d_addr_end(addr, end);
  235. if (vmap_try_huge_p4d(p4d, addr, next, phys_addr, prot,
  236. max_page_shift)) {
  237. *mask |= PGTBL_P4D_MODIFIED;
  238. continue;
  239. }
  240. err = vmap_pud_range(p4d, addr, next, phys_addr, prot, max_page_shift, mask);
  241. if (err)
  242. break;
  243. } while (p4d++, phys_addr += (next - addr), addr = next, addr != end);
  244. return err;
  245. }
  246. static int vmap_range_noflush(unsigned long addr, unsigned long end,
  247. phys_addr_t phys_addr, pgprot_t prot,
  248. unsigned int max_page_shift)
  249. {
  250. pgd_t *pgd;
  251. unsigned long start;
  252. unsigned long next;
  253. int err;
  254. pgtbl_mod_mask mask = 0;
  255. /*
  256. * Might allocate pagetables (for most archs a more precise annotation
  257. * would be might_alloc(GFP_PGTABLE_KERNEL)). Also might shootdown TLB
  258. * (requires IRQs enabled on x86).
  259. */
  260. might_sleep();
  261. BUG_ON(addr >= end);
  262. start = addr;
  263. pgd = pgd_offset_k(addr);
  264. do {
  265. next = pgd_addr_end(addr, end);
  266. err = vmap_p4d_range(pgd, addr, next, phys_addr, prot,
  267. max_page_shift, &mask);
  268. if (err)
  269. break;
  270. } while (pgd++, phys_addr += (next - addr), addr = next, addr != end);
  271. if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
  272. arch_sync_kernel_mappings(start, end);
  273. return err;
  274. }
  275. int vmap_page_range(unsigned long addr, unsigned long end,
  276. phys_addr_t phys_addr, pgprot_t prot)
  277. {
  278. int err;
  279. err = vmap_range_noflush(addr, end, phys_addr, pgprot_nx(prot),
  280. ioremap_max_page_shift);
  281. flush_cache_vmap(addr, end);
  282. if (!err)
  283. err = kmsan_ioremap_page_range(addr, end, phys_addr, prot,
  284. ioremap_max_page_shift);
  285. return err;
  286. }
  287. int ioremap_page_range(unsigned long addr, unsigned long end,
  288. phys_addr_t phys_addr, pgprot_t prot)
  289. {
  290. struct vm_struct *area;
  291. area = find_vm_area((void *)addr);
  292. if (!area || !(area->flags & VM_IOREMAP)) {
  293. WARN_ONCE(1, "vm_area at addr %lx is not marked as VM_IOREMAP\n", addr);
  294. return -EINVAL;
  295. }
  296. if (addr != (unsigned long)area->addr ||
  297. (void *)end != area->addr + get_vm_area_size(area)) {
  298. WARN_ONCE(1, "ioremap request [%lx,%lx) doesn't match vm_area [%lx, %lx)\n",
  299. addr, end, (long)area->addr,
  300. (long)area->addr + get_vm_area_size(area));
  301. return -ERANGE;
  302. }
  303. return vmap_page_range(addr, end, phys_addr, prot);
  304. }
  305. static void vunmap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end,
  306. pgtbl_mod_mask *mask)
  307. {
  308. pte_t *pte;
  309. pte_t ptent;
  310. unsigned long size = PAGE_SIZE;
  311. pte = pte_offset_kernel(pmd, addr);
  312. lazy_mmu_mode_enable();
  313. do {
  314. #ifdef CONFIG_HUGETLB_PAGE
  315. size = arch_vmap_pte_range_unmap_size(addr, pte);
  316. if (size != PAGE_SIZE) {
  317. if (WARN_ON(!IS_ALIGNED(addr, size))) {
  318. addr = ALIGN_DOWN(addr, size);
  319. pte = PTR_ALIGN_DOWN(pte, sizeof(*pte) * (size >> PAGE_SHIFT));
  320. }
  321. ptent = huge_ptep_get_and_clear(&init_mm, addr, pte, size);
  322. if (WARN_ON(end - addr < size))
  323. size = end - addr;
  324. } else
  325. #endif
  326. ptent = ptep_get_and_clear(&init_mm, addr, pte);
  327. WARN_ON(!pte_none(ptent) && !pte_present(ptent));
  328. } while (pte += (size >> PAGE_SHIFT), addr += size, addr != end);
  329. lazy_mmu_mode_disable();
  330. *mask |= PGTBL_PTE_MODIFIED;
  331. }
  332. static void vunmap_pmd_range(pud_t *pud, unsigned long addr, unsigned long end,
  333. pgtbl_mod_mask *mask)
  334. {
  335. pmd_t *pmd;
  336. unsigned long next;
  337. int cleared;
  338. pmd = pmd_offset(pud, addr);
  339. do {
  340. next = pmd_addr_end(addr, end);
  341. cleared = pmd_clear_huge(pmd);
  342. if (cleared || pmd_bad(*pmd))
  343. *mask |= PGTBL_PMD_MODIFIED;
  344. if (cleared) {
  345. WARN_ON(next - addr < PMD_SIZE);
  346. continue;
  347. }
  348. if (pmd_none_or_clear_bad(pmd))
  349. continue;
  350. vunmap_pte_range(pmd, addr, next, mask);
  351. cond_resched();
  352. } while (pmd++, addr = next, addr != end);
  353. }
  354. static void vunmap_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end,
  355. pgtbl_mod_mask *mask)
  356. {
  357. pud_t *pud;
  358. unsigned long next;
  359. int cleared;
  360. pud = pud_offset(p4d, addr);
  361. do {
  362. next = pud_addr_end(addr, end);
  363. cleared = pud_clear_huge(pud);
  364. if (cleared || pud_bad(*pud))
  365. *mask |= PGTBL_PUD_MODIFIED;
  366. if (cleared) {
  367. WARN_ON(next - addr < PUD_SIZE);
  368. continue;
  369. }
  370. if (pud_none_or_clear_bad(pud))
  371. continue;
  372. vunmap_pmd_range(pud, addr, next, mask);
  373. } while (pud++, addr = next, addr != end);
  374. }
  375. static void vunmap_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end,
  376. pgtbl_mod_mask *mask)
  377. {
  378. p4d_t *p4d;
  379. unsigned long next;
  380. p4d = p4d_offset(pgd, addr);
  381. do {
  382. next = p4d_addr_end(addr, end);
  383. p4d_clear_huge(p4d);
  384. if (p4d_bad(*p4d))
  385. *mask |= PGTBL_P4D_MODIFIED;
  386. if (p4d_none_or_clear_bad(p4d))
  387. continue;
  388. vunmap_pud_range(p4d, addr, next, mask);
  389. } while (p4d++, addr = next, addr != end);
  390. }
  391. /*
  392. * vunmap_range_noflush is similar to vunmap_range, but does not
  393. * flush caches or TLBs.
  394. *
  395. * The caller is responsible for calling flush_cache_vmap() before calling
  396. * this function, and flush_tlb_kernel_range after it has returned
  397. * successfully (and before the addresses are expected to cause a page fault
  398. * or be re-mapped for something else, if TLB flushes are being delayed or
  399. * coalesced).
  400. *
  401. * This is an internal function only. Do not use outside mm/.
  402. */
  403. void __vunmap_range_noflush(unsigned long start, unsigned long end)
  404. {
  405. unsigned long next;
  406. pgd_t *pgd;
  407. unsigned long addr = start;
  408. pgtbl_mod_mask mask = 0;
  409. BUG_ON(addr >= end);
  410. pgd = pgd_offset_k(addr);
  411. do {
  412. next = pgd_addr_end(addr, end);
  413. if (pgd_bad(*pgd))
  414. mask |= PGTBL_PGD_MODIFIED;
  415. if (pgd_none_or_clear_bad(pgd))
  416. continue;
  417. vunmap_p4d_range(pgd, addr, next, &mask);
  418. } while (pgd++, addr = next, addr != end);
  419. if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
  420. arch_sync_kernel_mappings(start, end);
  421. }
  422. void vunmap_range_noflush(unsigned long start, unsigned long end)
  423. {
  424. kmsan_vunmap_range_noflush(start, end);
  425. __vunmap_range_noflush(start, end);
  426. }
  427. /**
  428. * vunmap_range - unmap kernel virtual addresses
  429. * @addr: start of the VM area to unmap
  430. * @end: end of the VM area to unmap (non-inclusive)
  431. *
  432. * Clears any present PTEs in the virtual address range, flushes TLBs and
  433. * caches. Any subsequent access to the address before it has been re-mapped
  434. * is a kernel bug.
  435. */
  436. void vunmap_range(unsigned long addr, unsigned long end)
  437. {
  438. flush_cache_vunmap(addr, end);
  439. vunmap_range_noflush(addr, end);
  440. flush_tlb_kernel_range(addr, end);
  441. }
  442. static int vmap_pages_pte_range(pmd_t *pmd, unsigned long addr,
  443. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  444. pgtbl_mod_mask *mask)
  445. {
  446. int err = 0;
  447. pte_t *pte;
  448. /*
  449. * nr is a running index into the array which helps higher level
  450. * callers keep track of where we're up to.
  451. */
  452. pte = pte_alloc_kernel_track(pmd, addr, mask);
  453. if (!pte)
  454. return -ENOMEM;
  455. lazy_mmu_mode_enable();
  456. do {
  457. struct page *page = pages[*nr];
  458. if (WARN_ON(!pte_none(ptep_get(pte)))) {
  459. err = -EBUSY;
  460. break;
  461. }
  462. if (WARN_ON(!page)) {
  463. err = -ENOMEM;
  464. break;
  465. }
  466. if (WARN_ON(!pfn_valid(page_to_pfn(page)))) {
  467. err = -EINVAL;
  468. break;
  469. }
  470. set_pte_at(&init_mm, addr, pte, mk_pte(page, prot));
  471. (*nr)++;
  472. } while (pte++, addr += PAGE_SIZE, addr != end);
  473. lazy_mmu_mode_disable();
  474. *mask |= PGTBL_PTE_MODIFIED;
  475. return err;
  476. }
  477. static int vmap_pages_pmd_range(pud_t *pud, unsigned long addr,
  478. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  479. pgtbl_mod_mask *mask)
  480. {
  481. pmd_t *pmd;
  482. unsigned long next;
  483. pmd = pmd_alloc_track(&init_mm, pud, addr, mask);
  484. if (!pmd)
  485. return -ENOMEM;
  486. do {
  487. next = pmd_addr_end(addr, end);
  488. if (vmap_pages_pte_range(pmd, addr, next, prot, pages, nr, mask))
  489. return -ENOMEM;
  490. } while (pmd++, addr = next, addr != end);
  491. return 0;
  492. }
  493. static int vmap_pages_pud_range(p4d_t *p4d, unsigned long addr,
  494. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  495. pgtbl_mod_mask *mask)
  496. {
  497. pud_t *pud;
  498. unsigned long next;
  499. pud = pud_alloc_track(&init_mm, p4d, addr, mask);
  500. if (!pud)
  501. return -ENOMEM;
  502. do {
  503. next = pud_addr_end(addr, end);
  504. if (vmap_pages_pmd_range(pud, addr, next, prot, pages, nr, mask))
  505. return -ENOMEM;
  506. } while (pud++, addr = next, addr != end);
  507. return 0;
  508. }
  509. static int vmap_pages_p4d_range(pgd_t *pgd, unsigned long addr,
  510. unsigned long end, pgprot_t prot, struct page **pages, int *nr,
  511. pgtbl_mod_mask *mask)
  512. {
  513. p4d_t *p4d;
  514. unsigned long next;
  515. p4d = p4d_alloc_track(&init_mm, pgd, addr, mask);
  516. if (!p4d)
  517. return -ENOMEM;
  518. do {
  519. next = p4d_addr_end(addr, end);
  520. if (vmap_pages_pud_range(p4d, addr, next, prot, pages, nr, mask))
  521. return -ENOMEM;
  522. } while (p4d++, addr = next, addr != end);
  523. return 0;
  524. }
  525. static int vmap_small_pages_range_noflush(unsigned long addr, unsigned long end,
  526. pgprot_t prot, struct page **pages)
  527. {
  528. unsigned long start = addr;
  529. pgd_t *pgd;
  530. unsigned long next;
  531. int err = 0;
  532. int nr = 0;
  533. pgtbl_mod_mask mask = 0;
  534. BUG_ON(addr >= end);
  535. pgd = pgd_offset_k(addr);
  536. do {
  537. next = pgd_addr_end(addr, end);
  538. if (pgd_bad(*pgd))
  539. mask |= PGTBL_PGD_MODIFIED;
  540. err = vmap_pages_p4d_range(pgd, addr, next, prot, pages, &nr, &mask);
  541. if (err)
  542. break;
  543. } while (pgd++, addr = next, addr != end);
  544. if (mask & ARCH_PAGE_TABLE_SYNC_MASK)
  545. arch_sync_kernel_mappings(start, end);
  546. return err;
  547. }
  548. /*
  549. * vmap_pages_range_noflush is similar to vmap_pages_range, but does not
  550. * flush caches.
  551. *
  552. * The caller is responsible for calling flush_cache_vmap() after this
  553. * function returns successfully and before the addresses are accessed.
  554. *
  555. * This is an internal function only. Do not use outside mm/.
  556. */
  557. int __vmap_pages_range_noflush(unsigned long addr, unsigned long end,
  558. pgprot_t prot, struct page **pages, unsigned int page_shift)
  559. {
  560. unsigned int i, nr = (end - addr) >> PAGE_SHIFT;
  561. WARN_ON(page_shift < PAGE_SHIFT);
  562. if (!IS_ENABLED(CONFIG_HAVE_ARCH_HUGE_VMALLOC) ||
  563. page_shift == PAGE_SHIFT)
  564. return vmap_small_pages_range_noflush(addr, end, prot, pages);
  565. for (i = 0; i < nr; i += 1U << (page_shift - PAGE_SHIFT)) {
  566. int err;
  567. err = vmap_range_noflush(addr, addr + (1UL << page_shift),
  568. page_to_phys(pages[i]), prot,
  569. page_shift);
  570. if (err)
  571. return err;
  572. addr += 1UL << page_shift;
  573. }
  574. return 0;
  575. }
  576. int vmap_pages_range_noflush(unsigned long addr, unsigned long end,
  577. pgprot_t prot, struct page **pages, unsigned int page_shift,
  578. gfp_t gfp_mask)
  579. {
  580. int ret = kmsan_vmap_pages_range_noflush(addr, end, prot, pages,
  581. page_shift, gfp_mask);
  582. if (ret)
  583. return ret;
  584. return __vmap_pages_range_noflush(addr, end, prot, pages, page_shift);
  585. }
  586. static int __vmap_pages_range(unsigned long addr, unsigned long end,
  587. pgprot_t prot, struct page **pages, unsigned int page_shift,
  588. gfp_t gfp_mask)
  589. {
  590. int err;
  591. err = vmap_pages_range_noflush(addr, end, prot, pages, page_shift, gfp_mask);
  592. flush_cache_vmap(addr, end);
  593. return err;
  594. }
  595. /**
  596. * vmap_pages_range - map pages to a kernel virtual address
  597. * @addr: start of the VM area to map
  598. * @end: end of the VM area to map (non-inclusive)
  599. * @prot: page protection flags to use
  600. * @pages: pages to map (always PAGE_SIZE pages)
  601. * @page_shift: maximum shift that the pages may be mapped with, @pages must
  602. * be aligned and contiguous up to at least this shift.
  603. *
  604. * RETURNS:
  605. * 0 on success, -errno on failure.
  606. */
  607. int vmap_pages_range(unsigned long addr, unsigned long end,
  608. pgprot_t prot, struct page **pages, unsigned int page_shift)
  609. {
  610. return __vmap_pages_range(addr, end, prot, pages, page_shift, GFP_KERNEL);
  611. }
  612. static int check_sparse_vm_area(struct vm_struct *area, unsigned long start,
  613. unsigned long end)
  614. {
  615. might_sleep();
  616. if (WARN_ON_ONCE(area->flags & VM_FLUSH_RESET_PERMS))
  617. return -EINVAL;
  618. if (WARN_ON_ONCE(area->flags & VM_NO_GUARD))
  619. return -EINVAL;
  620. if (WARN_ON_ONCE(!(area->flags & VM_SPARSE)))
  621. return -EINVAL;
  622. if ((end - start) >> PAGE_SHIFT > totalram_pages())
  623. return -E2BIG;
  624. if (start < (unsigned long)area->addr ||
  625. (void *)end > area->addr + get_vm_area_size(area))
  626. return -ERANGE;
  627. return 0;
  628. }
  629. /**
  630. * vm_area_map_pages - map pages inside given sparse vm_area
  631. * @area: vm_area
  632. * @start: start address inside vm_area
  633. * @end: end address inside vm_area
  634. * @pages: pages to map (always PAGE_SIZE pages)
  635. */
  636. int vm_area_map_pages(struct vm_struct *area, unsigned long start,
  637. unsigned long end, struct page **pages)
  638. {
  639. int err;
  640. err = check_sparse_vm_area(area, start, end);
  641. if (err)
  642. return err;
  643. return vmap_pages_range(start, end, PAGE_KERNEL, pages, PAGE_SHIFT);
  644. }
  645. /**
  646. * vm_area_unmap_pages - unmap pages inside given sparse vm_area
  647. * @area: vm_area
  648. * @start: start address inside vm_area
  649. * @end: end address inside vm_area
  650. */
  651. void vm_area_unmap_pages(struct vm_struct *area, unsigned long start,
  652. unsigned long end)
  653. {
  654. if (check_sparse_vm_area(area, start, end))
  655. return;
  656. vunmap_range(start, end);
  657. }
  658. int is_vmalloc_or_module_addr(const void *x)
  659. {
  660. /*
  661. * ARM, x86-64 and sparc64 put modules in a special place,
  662. * and fall back on vmalloc() if that fails. Others
  663. * just put it in the vmalloc space.
  664. */
  665. #if defined(CONFIG_EXECMEM) && defined(MODULES_VADDR)
  666. unsigned long addr = (unsigned long)kasan_reset_tag(x);
  667. if (addr >= MODULES_VADDR && addr < MODULES_END)
  668. return 1;
  669. #endif
  670. return is_vmalloc_addr(x);
  671. }
  672. EXPORT_SYMBOL_GPL(is_vmalloc_or_module_addr);
  673. /*
  674. * Walk a vmap address to the struct page it maps. Huge vmap mappings will
  675. * return the tail page that corresponds to the base page address, which
  676. * matches small vmap mappings.
  677. */
  678. struct page *vmalloc_to_page(const void *vmalloc_addr)
  679. {
  680. unsigned long addr = (unsigned long) vmalloc_addr;
  681. struct page *page = NULL;
  682. pgd_t *pgd = pgd_offset_k(addr);
  683. p4d_t *p4d;
  684. pud_t *pud;
  685. pmd_t *pmd;
  686. pte_t *ptep, pte;
  687. /*
  688. * XXX we might need to change this if we add VIRTUAL_BUG_ON for
  689. * architectures that do not vmalloc module space
  690. */
  691. VIRTUAL_BUG_ON(!is_vmalloc_or_module_addr(vmalloc_addr));
  692. if (pgd_none(*pgd))
  693. return NULL;
  694. if (WARN_ON_ONCE(pgd_leaf(*pgd)))
  695. return NULL; /* XXX: no allowance for huge pgd */
  696. if (WARN_ON_ONCE(pgd_bad(*pgd)))
  697. return NULL;
  698. p4d = p4d_offset(pgd, addr);
  699. if (p4d_none(*p4d))
  700. return NULL;
  701. if (p4d_leaf(*p4d))
  702. return p4d_page(*p4d) + ((addr & ~P4D_MASK) >> PAGE_SHIFT);
  703. if (WARN_ON_ONCE(p4d_bad(*p4d)))
  704. return NULL;
  705. pud = pud_offset(p4d, addr);
  706. if (pud_none(*pud))
  707. return NULL;
  708. if (pud_leaf(*pud))
  709. return pud_page(*pud) + ((addr & ~PUD_MASK) >> PAGE_SHIFT);
  710. if (WARN_ON_ONCE(pud_bad(*pud)))
  711. return NULL;
  712. pmd = pmd_offset(pud, addr);
  713. if (pmd_none(*pmd))
  714. return NULL;
  715. if (pmd_leaf(*pmd))
  716. return pmd_page(*pmd) + ((addr & ~PMD_MASK) >> PAGE_SHIFT);
  717. if (WARN_ON_ONCE(pmd_bad(*pmd)))
  718. return NULL;
  719. ptep = pte_offset_kernel(pmd, addr);
  720. pte = ptep_get(ptep);
  721. if (pte_present(pte))
  722. page = pte_page(pte);
  723. return page;
  724. }
  725. EXPORT_SYMBOL(vmalloc_to_page);
  726. /*
  727. * Map a vmalloc()-space virtual address to the physical page frame number.
  728. */
  729. unsigned long vmalloc_to_pfn(const void *vmalloc_addr)
  730. {
  731. return page_to_pfn(vmalloc_to_page(vmalloc_addr));
  732. }
  733. EXPORT_SYMBOL(vmalloc_to_pfn);
  734. /*** Global kva allocator ***/
  735. #define DEBUG_AUGMENT_PROPAGATE_CHECK 0
  736. #define DEBUG_AUGMENT_LOWEST_MATCH_CHECK 0
  737. static DEFINE_SPINLOCK(free_vmap_area_lock);
  738. static bool vmap_initialized __read_mostly;
  739. /*
  740. * This kmem_cache is used for vmap_area objects. Instead of
  741. * allocating from slab we reuse an object from this cache to
  742. * make things faster. Especially in "no edge" splitting of
  743. * free block.
  744. */
  745. static struct kmem_cache *vmap_area_cachep;
  746. /*
  747. * This linked list is used in pair with free_vmap_area_root.
  748. * It gives O(1) access to prev/next to perform fast coalescing.
  749. */
  750. static LIST_HEAD(free_vmap_area_list);
  751. /*
  752. * This augment red-black tree represents the free vmap space.
  753. * All vmap_area objects in this tree are sorted by va->va_start
  754. * address. It is used for allocation and merging when a vmap
  755. * object is released.
  756. *
  757. * Each vmap_area node contains a maximum available free block
  758. * of its sub-tree, right or left. Therefore it is possible to
  759. * find a lowest match of free area.
  760. */
  761. static struct rb_root free_vmap_area_root = RB_ROOT;
  762. /*
  763. * Preload a CPU with one object for "no edge" split case. The
  764. * aim is to get rid of allocations from the atomic context, thus
  765. * to use more permissive allocation masks.
  766. */
  767. static DEFINE_PER_CPU(struct vmap_area *, ne_fit_preload_node);
  768. /*
  769. * This structure defines a single, solid model where a list and
  770. * rb-tree are part of one entity protected by the lock. Nodes are
  771. * sorted in ascending order, thus for O(1) access to left/right
  772. * neighbors a list is used as well as for sequential traversal.
  773. */
  774. struct rb_list {
  775. struct rb_root root;
  776. struct list_head head;
  777. spinlock_t lock;
  778. };
  779. /*
  780. * A fast size storage contains VAs up to 1M size. A pool consists
  781. * of linked between each other ready to go VAs of certain sizes.
  782. * An index in the pool-array corresponds to number of pages + 1.
  783. */
  784. #define MAX_VA_SIZE_PAGES 256
  785. struct vmap_pool {
  786. struct list_head head;
  787. unsigned long len;
  788. };
  789. /*
  790. * An effective vmap-node logic. Users make use of nodes instead
  791. * of a global heap. It allows to balance an access and mitigate
  792. * contention.
  793. */
  794. static struct vmap_node {
  795. /* Simple size segregated storage. */
  796. struct vmap_pool pool[MAX_VA_SIZE_PAGES];
  797. spinlock_t pool_lock;
  798. bool skip_populate;
  799. /* Bookkeeping data of this node. */
  800. struct rb_list busy;
  801. struct rb_list lazy;
  802. /*
  803. * Ready-to-free areas.
  804. */
  805. struct list_head purge_list;
  806. struct work_struct purge_work;
  807. unsigned long nr_purged;
  808. } single;
  809. /*
  810. * Initial setup consists of one single node, i.e. a balancing
  811. * is fully disabled. Later on, after vmap is initialized these
  812. * parameters are updated based on a system capacity.
  813. */
  814. static struct vmap_node *vmap_nodes = &single;
  815. static __read_mostly unsigned int nr_vmap_nodes = 1;
  816. static __read_mostly unsigned int vmap_zone_size = 1;
  817. /* A simple iterator over all vmap-nodes. */
  818. #define for_each_vmap_node(vn) \
  819. for ((vn) = &vmap_nodes[0]; \
  820. (vn) < &vmap_nodes[nr_vmap_nodes]; (vn)++)
  821. static inline unsigned int
  822. addr_to_node_id(unsigned long addr)
  823. {
  824. return (addr / vmap_zone_size) % nr_vmap_nodes;
  825. }
  826. static inline struct vmap_node *
  827. addr_to_node(unsigned long addr)
  828. {
  829. return &vmap_nodes[addr_to_node_id(addr)];
  830. }
  831. static inline struct vmap_node *
  832. id_to_node(unsigned int id)
  833. {
  834. return &vmap_nodes[id % nr_vmap_nodes];
  835. }
  836. static inline unsigned int
  837. node_to_id(struct vmap_node *node)
  838. {
  839. /* Pointer arithmetic. */
  840. unsigned int id = node - vmap_nodes;
  841. if (likely(id < nr_vmap_nodes))
  842. return id;
  843. WARN_ONCE(1, "An address 0x%p is out-of-bounds.\n", node);
  844. return 0;
  845. }
  846. /*
  847. * We use the value 0 to represent "no node", that is why
  848. * an encoded value will be the node-id incremented by 1.
  849. * It is always greater then 0. A valid node_id which can
  850. * be encoded is [0:nr_vmap_nodes - 1]. If a passed node_id
  851. * is not valid 0 is returned.
  852. */
  853. static unsigned int
  854. encode_vn_id(unsigned int node_id)
  855. {
  856. /* Can store U8_MAX [0:254] nodes. */
  857. if (node_id < nr_vmap_nodes)
  858. return (node_id + 1) << BITS_PER_BYTE;
  859. /* Warn and no node encoded. */
  860. WARN_ONCE(1, "Encode wrong node id (%u)\n", node_id);
  861. return 0;
  862. }
  863. /*
  864. * Returns an encoded node-id, the valid range is within
  865. * [0:nr_vmap_nodes-1] values. Otherwise nr_vmap_nodes is
  866. * returned if extracted data is wrong.
  867. */
  868. static unsigned int
  869. decode_vn_id(unsigned int val)
  870. {
  871. unsigned int node_id = (val >> BITS_PER_BYTE) - 1;
  872. /* Can store U8_MAX [0:254] nodes. */
  873. if (node_id < nr_vmap_nodes)
  874. return node_id;
  875. /* If it was _not_ zero, warn. */
  876. WARN_ONCE(node_id != UINT_MAX,
  877. "Decode wrong node id (%d)\n", node_id);
  878. return nr_vmap_nodes;
  879. }
  880. static bool
  881. is_vn_id_valid(unsigned int node_id)
  882. {
  883. if (node_id < nr_vmap_nodes)
  884. return true;
  885. return false;
  886. }
  887. static __always_inline unsigned long
  888. va_size(struct vmap_area *va)
  889. {
  890. return (va->va_end - va->va_start);
  891. }
  892. static __always_inline unsigned long
  893. get_subtree_max_size(struct rb_node *node)
  894. {
  895. struct vmap_area *va;
  896. va = rb_entry_safe(node, struct vmap_area, rb_node);
  897. return va ? va->subtree_max_size : 0;
  898. }
  899. RB_DECLARE_CALLBACKS_MAX(static, free_vmap_area_rb_augment_cb,
  900. struct vmap_area, rb_node, unsigned long, subtree_max_size, va_size)
  901. static void reclaim_and_purge_vmap_areas(void);
  902. static BLOCKING_NOTIFIER_HEAD(vmap_notify_list);
  903. static void drain_vmap_area_work(struct work_struct *work);
  904. static DECLARE_WORK(drain_vmap_work, drain_vmap_area_work);
  905. static __cacheline_aligned_in_smp atomic_long_t nr_vmalloc_pages;
  906. static __cacheline_aligned_in_smp atomic_long_t vmap_lazy_nr;
  907. unsigned long vmalloc_nr_pages(void)
  908. {
  909. return atomic_long_read(&nr_vmalloc_pages);
  910. }
  911. static struct vmap_area *__find_vmap_area(unsigned long addr, struct rb_root *root)
  912. {
  913. struct rb_node *n = root->rb_node;
  914. addr = (unsigned long)kasan_reset_tag((void *)addr);
  915. while (n) {
  916. struct vmap_area *va;
  917. va = rb_entry(n, struct vmap_area, rb_node);
  918. if (addr < va->va_start)
  919. n = n->rb_left;
  920. else if (addr >= va->va_end)
  921. n = n->rb_right;
  922. else
  923. return va;
  924. }
  925. return NULL;
  926. }
  927. /* Look up the first VA which satisfies addr < va_end, NULL if none. */
  928. static struct vmap_area *
  929. __find_vmap_area_exceed_addr(unsigned long addr, struct rb_root *root)
  930. {
  931. struct vmap_area *va = NULL;
  932. struct rb_node *n = root->rb_node;
  933. addr = (unsigned long)kasan_reset_tag((void *)addr);
  934. while (n) {
  935. struct vmap_area *tmp;
  936. tmp = rb_entry(n, struct vmap_area, rb_node);
  937. if (tmp->va_end > addr) {
  938. va = tmp;
  939. if (tmp->va_start <= addr)
  940. break;
  941. n = n->rb_left;
  942. } else
  943. n = n->rb_right;
  944. }
  945. return va;
  946. }
  947. /*
  948. * Returns a node where a first VA, that satisfies addr < va_end, resides.
  949. * If success, a node is locked. A user is responsible to unlock it when a
  950. * VA is no longer needed to be accessed.
  951. *
  952. * Returns NULL if nothing found.
  953. */
  954. static struct vmap_node *
  955. find_vmap_area_exceed_addr_lock(unsigned long addr, struct vmap_area **va)
  956. {
  957. unsigned long va_start_lowest;
  958. struct vmap_node *vn;
  959. repeat:
  960. va_start_lowest = 0;
  961. for_each_vmap_node(vn) {
  962. spin_lock(&vn->busy.lock);
  963. *va = __find_vmap_area_exceed_addr(addr, &vn->busy.root);
  964. if (*va)
  965. if (!va_start_lowest || (*va)->va_start < va_start_lowest)
  966. va_start_lowest = (*va)->va_start;
  967. spin_unlock(&vn->busy.lock);
  968. }
  969. /*
  970. * Check if found VA exists, it might have gone away. In this case we
  971. * repeat the search because a VA has been removed concurrently and we
  972. * need to proceed to the next one, which is a rare case.
  973. */
  974. if (va_start_lowest) {
  975. vn = addr_to_node(va_start_lowest);
  976. spin_lock(&vn->busy.lock);
  977. *va = __find_vmap_area(va_start_lowest, &vn->busy.root);
  978. if (*va)
  979. return vn;
  980. spin_unlock(&vn->busy.lock);
  981. goto repeat;
  982. }
  983. return NULL;
  984. }
  985. /*
  986. * This function returns back addresses of parent node
  987. * and its left or right link for further processing.
  988. *
  989. * Otherwise NULL is returned. In that case all further
  990. * steps regarding inserting of conflicting overlap range
  991. * have to be declined and actually considered as a bug.
  992. */
  993. static __always_inline struct rb_node **
  994. find_va_links(struct vmap_area *va,
  995. struct rb_root *root, struct rb_node *from,
  996. struct rb_node **parent)
  997. {
  998. struct vmap_area *tmp_va;
  999. struct rb_node **link;
  1000. if (root) {
  1001. link = &root->rb_node;
  1002. if (unlikely(!*link)) {
  1003. *parent = NULL;
  1004. return link;
  1005. }
  1006. } else {
  1007. link = &from;
  1008. }
  1009. /*
  1010. * Go to the bottom of the tree. When we hit the last point
  1011. * we end up with parent rb_node and correct direction, i name
  1012. * it link, where the new va->rb_node will be attached to.
  1013. */
  1014. do {
  1015. tmp_va = rb_entry(*link, struct vmap_area, rb_node);
  1016. /*
  1017. * During the traversal we also do some sanity check.
  1018. * Trigger the BUG() if there are sides(left/right)
  1019. * or full overlaps.
  1020. */
  1021. if (va->va_end <= tmp_va->va_start)
  1022. link = &(*link)->rb_left;
  1023. else if (va->va_start >= tmp_va->va_end)
  1024. link = &(*link)->rb_right;
  1025. else {
  1026. WARN(1, "vmalloc bug: 0x%lx-0x%lx overlaps with 0x%lx-0x%lx\n",
  1027. va->va_start, va->va_end, tmp_va->va_start, tmp_va->va_end);
  1028. return NULL;
  1029. }
  1030. } while (*link);
  1031. *parent = &tmp_va->rb_node;
  1032. return link;
  1033. }
  1034. static __always_inline struct list_head *
  1035. get_va_next_sibling(struct rb_node *parent, struct rb_node **link)
  1036. {
  1037. struct list_head *list;
  1038. if (unlikely(!parent))
  1039. /*
  1040. * The red-black tree where we try to find VA neighbors
  1041. * before merging or inserting is empty, i.e. it means
  1042. * there is no free vmap space. Normally it does not
  1043. * happen but we handle this case anyway.
  1044. */
  1045. return NULL;
  1046. list = &rb_entry(parent, struct vmap_area, rb_node)->list;
  1047. return (&parent->rb_right == link ? list->next : list);
  1048. }
  1049. static __always_inline void
  1050. __link_va(struct vmap_area *va, struct rb_root *root,
  1051. struct rb_node *parent, struct rb_node **link,
  1052. struct list_head *head, bool augment)
  1053. {
  1054. /*
  1055. * VA is still not in the list, but we can
  1056. * identify its future previous list_head node.
  1057. */
  1058. if (likely(parent)) {
  1059. head = &rb_entry(parent, struct vmap_area, rb_node)->list;
  1060. if (&parent->rb_right != link)
  1061. head = head->prev;
  1062. }
  1063. /* Insert to the rb-tree */
  1064. rb_link_node(&va->rb_node, parent, link);
  1065. if (augment) {
  1066. /*
  1067. * Some explanation here. Just perform simple insertion
  1068. * to the tree. We do not set va->subtree_max_size to
  1069. * its current size before calling rb_insert_augmented().
  1070. * It is because we populate the tree from the bottom
  1071. * to parent levels when the node _is_ in the tree.
  1072. *
  1073. * Therefore we set subtree_max_size to zero after insertion,
  1074. * to let __augment_tree_propagate_from() puts everything to
  1075. * the correct order later on.
  1076. */
  1077. rb_insert_augmented(&va->rb_node,
  1078. root, &free_vmap_area_rb_augment_cb);
  1079. va->subtree_max_size = 0;
  1080. } else {
  1081. rb_insert_color(&va->rb_node, root);
  1082. }
  1083. /* Address-sort this list */
  1084. list_add(&va->list, head);
  1085. }
  1086. static __always_inline void
  1087. link_va(struct vmap_area *va, struct rb_root *root,
  1088. struct rb_node *parent, struct rb_node **link,
  1089. struct list_head *head)
  1090. {
  1091. __link_va(va, root, parent, link, head, false);
  1092. }
  1093. static __always_inline void
  1094. link_va_augment(struct vmap_area *va, struct rb_root *root,
  1095. struct rb_node *parent, struct rb_node **link,
  1096. struct list_head *head)
  1097. {
  1098. __link_va(va, root, parent, link, head, true);
  1099. }
  1100. static __always_inline void
  1101. __unlink_va(struct vmap_area *va, struct rb_root *root, bool augment)
  1102. {
  1103. if (WARN_ON(RB_EMPTY_NODE(&va->rb_node)))
  1104. return;
  1105. if (augment)
  1106. rb_erase_augmented(&va->rb_node,
  1107. root, &free_vmap_area_rb_augment_cb);
  1108. else
  1109. rb_erase(&va->rb_node, root);
  1110. list_del_init(&va->list);
  1111. RB_CLEAR_NODE(&va->rb_node);
  1112. }
  1113. static __always_inline void
  1114. unlink_va(struct vmap_area *va, struct rb_root *root)
  1115. {
  1116. __unlink_va(va, root, false);
  1117. }
  1118. static __always_inline void
  1119. unlink_va_augment(struct vmap_area *va, struct rb_root *root)
  1120. {
  1121. __unlink_va(va, root, true);
  1122. }
  1123. #if DEBUG_AUGMENT_PROPAGATE_CHECK
  1124. /*
  1125. * Gets called when remove the node and rotate.
  1126. */
  1127. static __always_inline unsigned long
  1128. compute_subtree_max_size(struct vmap_area *va)
  1129. {
  1130. return max3(va_size(va),
  1131. get_subtree_max_size(va->rb_node.rb_left),
  1132. get_subtree_max_size(va->rb_node.rb_right));
  1133. }
  1134. static void
  1135. augment_tree_propagate_check(void)
  1136. {
  1137. struct vmap_area *va;
  1138. unsigned long computed_size;
  1139. list_for_each_entry(va, &free_vmap_area_list, list) {
  1140. computed_size = compute_subtree_max_size(va);
  1141. if (computed_size != va->subtree_max_size)
  1142. pr_emerg("tree is corrupted: %lu, %lu\n",
  1143. va_size(va), va->subtree_max_size);
  1144. }
  1145. }
  1146. #endif
  1147. /*
  1148. * This function populates subtree_max_size from bottom to upper
  1149. * levels starting from VA point. The propagation must be done
  1150. * when VA size is modified by changing its va_start/va_end. Or
  1151. * in case of newly inserting of VA to the tree.
  1152. *
  1153. * It means that __augment_tree_propagate_from() must be called:
  1154. * - After VA has been inserted to the tree(free path);
  1155. * - After VA has been shrunk(allocation path);
  1156. * - After VA has been increased(merging path).
  1157. *
  1158. * Please note that, it does not mean that upper parent nodes
  1159. * and their subtree_max_size are recalculated all the time up
  1160. * to the root node.
  1161. *
  1162. * 4--8
  1163. * /\
  1164. * / \
  1165. * / \
  1166. * 2--2 8--8
  1167. *
  1168. * For example if we modify the node 4, shrinking it to 2, then
  1169. * no any modification is required. If we shrink the node 2 to 1
  1170. * its subtree_max_size is updated only, and set to 1. If we shrink
  1171. * the node 8 to 6, then its subtree_max_size is set to 6 and parent
  1172. * node becomes 4--6.
  1173. */
  1174. static __always_inline void
  1175. augment_tree_propagate_from(struct vmap_area *va)
  1176. {
  1177. /*
  1178. * Populate the tree from bottom towards the root until
  1179. * the calculated maximum available size of checked node
  1180. * is equal to its current one.
  1181. */
  1182. free_vmap_area_rb_augment_cb_propagate(&va->rb_node, NULL);
  1183. #if DEBUG_AUGMENT_PROPAGATE_CHECK
  1184. augment_tree_propagate_check();
  1185. #endif
  1186. }
  1187. static void
  1188. insert_vmap_area(struct vmap_area *va,
  1189. struct rb_root *root, struct list_head *head)
  1190. {
  1191. struct rb_node **link;
  1192. struct rb_node *parent;
  1193. link = find_va_links(va, root, NULL, &parent);
  1194. if (link)
  1195. link_va(va, root, parent, link, head);
  1196. }
  1197. static void
  1198. insert_vmap_area_augment(struct vmap_area *va,
  1199. struct rb_node *from, struct rb_root *root,
  1200. struct list_head *head)
  1201. {
  1202. struct rb_node **link;
  1203. struct rb_node *parent;
  1204. if (from)
  1205. link = find_va_links(va, NULL, from, &parent);
  1206. else
  1207. link = find_va_links(va, root, NULL, &parent);
  1208. if (link) {
  1209. link_va_augment(va, root, parent, link, head);
  1210. augment_tree_propagate_from(va);
  1211. }
  1212. }
  1213. /*
  1214. * Merge de-allocated chunk of VA memory with previous
  1215. * and next free blocks. If coalesce is not done a new
  1216. * free area is inserted. If VA has been merged, it is
  1217. * freed.
  1218. *
  1219. * Please note, it can return NULL in case of overlap
  1220. * ranges, followed by WARN() report. Despite it is a
  1221. * buggy behaviour, a system can be alive and keep
  1222. * ongoing.
  1223. */
  1224. static __always_inline struct vmap_area *
  1225. __merge_or_add_vmap_area(struct vmap_area *va,
  1226. struct rb_root *root, struct list_head *head, bool augment)
  1227. {
  1228. struct vmap_area *sibling;
  1229. struct list_head *next;
  1230. struct rb_node **link;
  1231. struct rb_node *parent;
  1232. bool merged = false;
  1233. /*
  1234. * Find a place in the tree where VA potentially will be
  1235. * inserted, unless it is merged with its sibling/siblings.
  1236. */
  1237. link = find_va_links(va, root, NULL, &parent);
  1238. if (!link)
  1239. return NULL;
  1240. /*
  1241. * Get next node of VA to check if merging can be done.
  1242. */
  1243. next = get_va_next_sibling(parent, link);
  1244. if (unlikely(next == NULL))
  1245. goto insert;
  1246. /*
  1247. * start end
  1248. * | |
  1249. * |<------VA------>|<-----Next----->|
  1250. * | |
  1251. * start end
  1252. */
  1253. if (next != head) {
  1254. sibling = list_entry(next, struct vmap_area, list);
  1255. if (sibling->va_start == va->va_end) {
  1256. sibling->va_start = va->va_start;
  1257. /* Free vmap_area object. */
  1258. kmem_cache_free(vmap_area_cachep, va);
  1259. /* Point to the new merged area. */
  1260. va = sibling;
  1261. merged = true;
  1262. }
  1263. }
  1264. /*
  1265. * start end
  1266. * | |
  1267. * |<-----Prev----->|<------VA------>|
  1268. * | |
  1269. * start end
  1270. */
  1271. if (next->prev != head) {
  1272. sibling = list_entry(next->prev, struct vmap_area, list);
  1273. if (sibling->va_end == va->va_start) {
  1274. /*
  1275. * If both neighbors are coalesced, it is important
  1276. * to unlink the "next" node first, followed by merging
  1277. * with "previous" one. Otherwise the tree might not be
  1278. * fully populated if a sibling's augmented value is
  1279. * "normalized" because of rotation operations.
  1280. */
  1281. if (merged)
  1282. __unlink_va(va, root, augment);
  1283. sibling->va_end = va->va_end;
  1284. /* Free vmap_area object. */
  1285. kmem_cache_free(vmap_area_cachep, va);
  1286. /* Point to the new merged area. */
  1287. va = sibling;
  1288. merged = true;
  1289. }
  1290. }
  1291. insert:
  1292. if (!merged)
  1293. __link_va(va, root, parent, link, head, augment);
  1294. return va;
  1295. }
  1296. static __always_inline struct vmap_area *
  1297. merge_or_add_vmap_area(struct vmap_area *va,
  1298. struct rb_root *root, struct list_head *head)
  1299. {
  1300. return __merge_or_add_vmap_area(va, root, head, false);
  1301. }
  1302. static __always_inline struct vmap_area *
  1303. merge_or_add_vmap_area_augment(struct vmap_area *va,
  1304. struct rb_root *root, struct list_head *head)
  1305. {
  1306. va = __merge_or_add_vmap_area(va, root, head, true);
  1307. if (va)
  1308. augment_tree_propagate_from(va);
  1309. return va;
  1310. }
  1311. static __always_inline bool
  1312. is_within_this_va(struct vmap_area *va, unsigned long size,
  1313. unsigned long align, unsigned long vstart)
  1314. {
  1315. unsigned long nva_start_addr;
  1316. if (va->va_start > vstart)
  1317. nva_start_addr = ALIGN(va->va_start, align);
  1318. else
  1319. nva_start_addr = ALIGN(vstart, align);
  1320. /* Can be overflowed due to big size or alignment. */
  1321. if (nva_start_addr + size < nva_start_addr ||
  1322. nva_start_addr < vstart)
  1323. return false;
  1324. return (nva_start_addr + size <= va->va_end);
  1325. }
  1326. /*
  1327. * Find the first free block(lowest start address) in the tree,
  1328. * that will accomplish the request corresponding to passing
  1329. * parameters. Please note, with an alignment bigger than PAGE_SIZE,
  1330. * a search length is adjusted to account for worst case alignment
  1331. * overhead.
  1332. */
  1333. static __always_inline struct vmap_area *
  1334. find_vmap_lowest_match(struct rb_root *root, unsigned long size,
  1335. unsigned long align, unsigned long vstart, bool adjust_search_size)
  1336. {
  1337. struct vmap_area *va;
  1338. struct rb_node *node;
  1339. unsigned long length;
  1340. /* Start from the root. */
  1341. node = root->rb_node;
  1342. /* Adjust the search size for alignment overhead. */
  1343. length = adjust_search_size ? size + align - 1 : size;
  1344. while (node) {
  1345. va = rb_entry(node, struct vmap_area, rb_node);
  1346. if (get_subtree_max_size(node->rb_left) >= length &&
  1347. vstart < va->va_start) {
  1348. node = node->rb_left;
  1349. } else {
  1350. if (is_within_this_va(va, size, align, vstart))
  1351. return va;
  1352. /*
  1353. * Does not make sense to go deeper towards the right
  1354. * sub-tree if it does not have a free block that is
  1355. * equal or bigger to the requested search length.
  1356. */
  1357. if (get_subtree_max_size(node->rb_right) >= length) {
  1358. node = node->rb_right;
  1359. continue;
  1360. }
  1361. /*
  1362. * OK. We roll back and find the first right sub-tree,
  1363. * that will satisfy the search criteria. It can happen
  1364. * due to "vstart" restriction or an alignment overhead
  1365. * that is bigger then PAGE_SIZE.
  1366. */
  1367. while ((node = rb_parent(node))) {
  1368. va = rb_entry(node, struct vmap_area, rb_node);
  1369. if (is_within_this_va(va, size, align, vstart))
  1370. return va;
  1371. if (get_subtree_max_size(node->rb_right) >= length &&
  1372. vstart <= va->va_start) {
  1373. /*
  1374. * Shift the vstart forward. Please note, we update it with
  1375. * parent's start address adding "1" because we do not want
  1376. * to enter same sub-tree after it has already been checked
  1377. * and no suitable free block found there.
  1378. */
  1379. vstart = va->va_start + 1;
  1380. node = node->rb_right;
  1381. break;
  1382. }
  1383. }
  1384. }
  1385. }
  1386. return NULL;
  1387. }
  1388. #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
  1389. #include <linux/random.h>
  1390. static struct vmap_area *
  1391. find_vmap_lowest_linear_match(struct list_head *head, unsigned long size,
  1392. unsigned long align, unsigned long vstart)
  1393. {
  1394. struct vmap_area *va;
  1395. list_for_each_entry(va, head, list) {
  1396. if (!is_within_this_va(va, size, align, vstart))
  1397. continue;
  1398. return va;
  1399. }
  1400. return NULL;
  1401. }
  1402. static void
  1403. find_vmap_lowest_match_check(struct rb_root *root, struct list_head *head,
  1404. unsigned long size, unsigned long align)
  1405. {
  1406. struct vmap_area *va_1, *va_2;
  1407. unsigned long vstart;
  1408. unsigned int rnd;
  1409. get_random_bytes(&rnd, sizeof(rnd));
  1410. vstart = VMALLOC_START + rnd;
  1411. va_1 = find_vmap_lowest_match(root, size, align, vstart, false);
  1412. va_2 = find_vmap_lowest_linear_match(head, size, align, vstart);
  1413. if (va_1 != va_2)
  1414. pr_emerg("not lowest: t: 0x%p, l: 0x%p, v: 0x%lx\n",
  1415. va_1, va_2, vstart);
  1416. }
  1417. #endif
  1418. enum fit_type {
  1419. NOTHING_FIT = 0,
  1420. FL_FIT_TYPE = 1, /* full fit */
  1421. LE_FIT_TYPE = 2, /* left edge fit */
  1422. RE_FIT_TYPE = 3, /* right edge fit */
  1423. NE_FIT_TYPE = 4 /* no edge fit */
  1424. };
  1425. static __always_inline enum fit_type
  1426. classify_va_fit_type(struct vmap_area *va,
  1427. unsigned long nva_start_addr, unsigned long size)
  1428. {
  1429. enum fit_type type;
  1430. /* Check if it is within VA. */
  1431. if (nva_start_addr < va->va_start ||
  1432. nva_start_addr + size > va->va_end)
  1433. return NOTHING_FIT;
  1434. /* Now classify. */
  1435. if (va->va_start == nva_start_addr) {
  1436. if (va->va_end == nva_start_addr + size)
  1437. type = FL_FIT_TYPE;
  1438. else
  1439. type = LE_FIT_TYPE;
  1440. } else if (va->va_end == nva_start_addr + size) {
  1441. type = RE_FIT_TYPE;
  1442. } else {
  1443. type = NE_FIT_TYPE;
  1444. }
  1445. return type;
  1446. }
  1447. static __always_inline int
  1448. va_clip(struct rb_root *root, struct list_head *head,
  1449. struct vmap_area *va, unsigned long nva_start_addr,
  1450. unsigned long size)
  1451. {
  1452. struct vmap_area *lva = NULL;
  1453. enum fit_type type = classify_va_fit_type(va, nva_start_addr, size);
  1454. if (type == FL_FIT_TYPE) {
  1455. /*
  1456. * No need to split VA, it fully fits.
  1457. *
  1458. * | |
  1459. * V NVA V
  1460. * |---------------|
  1461. */
  1462. unlink_va_augment(va, root);
  1463. kmem_cache_free(vmap_area_cachep, va);
  1464. } else if (type == LE_FIT_TYPE) {
  1465. /*
  1466. * Split left edge of fit VA.
  1467. *
  1468. * | |
  1469. * V NVA V R
  1470. * |-------|-------|
  1471. */
  1472. va->va_start += size;
  1473. } else if (type == RE_FIT_TYPE) {
  1474. /*
  1475. * Split right edge of fit VA.
  1476. *
  1477. * | |
  1478. * L V NVA V
  1479. * |-------|-------|
  1480. */
  1481. va->va_end = nva_start_addr;
  1482. } else if (type == NE_FIT_TYPE) {
  1483. /*
  1484. * Split no edge of fit VA.
  1485. *
  1486. * | |
  1487. * L V NVA V R
  1488. * |---|-------|---|
  1489. */
  1490. lva = __this_cpu_xchg(ne_fit_preload_node, NULL);
  1491. if (unlikely(!lva)) {
  1492. /*
  1493. * For percpu allocator we do not do any pre-allocation
  1494. * and leave it as it is. The reason is it most likely
  1495. * never ends up with NE_FIT_TYPE splitting. In case of
  1496. * percpu allocations offsets and sizes are aligned to
  1497. * fixed align request, i.e. RE_FIT_TYPE and FL_FIT_TYPE
  1498. * are its main fitting cases.
  1499. *
  1500. * There are a few exceptions though, as an example it is
  1501. * a first allocation (early boot up) when we have "one"
  1502. * big free space that has to be split.
  1503. *
  1504. * Also we can hit this path in case of regular "vmap"
  1505. * allocations, if "this" current CPU was not preloaded.
  1506. * See the comment in alloc_vmap_area() why. If so, then
  1507. * GFP_NOWAIT is used instead to get an extra object for
  1508. * split purpose. That is rare and most time does not
  1509. * occur.
  1510. *
  1511. * What happens if an allocation gets failed. Basically,
  1512. * an "overflow" path is triggered to purge lazily freed
  1513. * areas to free some memory, then, the "retry" path is
  1514. * triggered to repeat one more time. See more details
  1515. * in alloc_vmap_area() function.
  1516. */
  1517. lva = kmem_cache_alloc(vmap_area_cachep, GFP_NOWAIT);
  1518. if (!lva)
  1519. return -ENOMEM;
  1520. }
  1521. /*
  1522. * Build the remainder.
  1523. */
  1524. lva->va_start = va->va_start;
  1525. lva->va_end = nva_start_addr;
  1526. /*
  1527. * Shrink this VA to remaining size.
  1528. */
  1529. va->va_start = nva_start_addr + size;
  1530. } else {
  1531. return -EINVAL;
  1532. }
  1533. if (type != FL_FIT_TYPE) {
  1534. augment_tree_propagate_from(va);
  1535. if (lva) /* type == NE_FIT_TYPE */
  1536. insert_vmap_area_augment(lva, &va->rb_node, root, head);
  1537. }
  1538. return 0;
  1539. }
  1540. static unsigned long
  1541. va_alloc(struct vmap_area *va,
  1542. struct rb_root *root, struct list_head *head,
  1543. unsigned long size, unsigned long align,
  1544. unsigned long vstart, unsigned long vend)
  1545. {
  1546. unsigned long nva_start_addr;
  1547. int ret;
  1548. if (va->va_start > vstart)
  1549. nva_start_addr = ALIGN(va->va_start, align);
  1550. else
  1551. nva_start_addr = ALIGN(vstart, align);
  1552. /* Check the "vend" restriction. */
  1553. if (nva_start_addr + size > vend)
  1554. return -ERANGE;
  1555. /* Update the free vmap_area. */
  1556. ret = va_clip(root, head, va, nva_start_addr, size);
  1557. if (WARN_ON_ONCE(ret))
  1558. return ret;
  1559. return nva_start_addr;
  1560. }
  1561. /*
  1562. * Returns a start address of the newly allocated area, if success.
  1563. * Otherwise an error value is returned that indicates failure.
  1564. */
  1565. static __always_inline unsigned long
  1566. __alloc_vmap_area(struct rb_root *root, struct list_head *head,
  1567. unsigned long size, unsigned long align,
  1568. unsigned long vstart, unsigned long vend)
  1569. {
  1570. bool adjust_search_size = true;
  1571. unsigned long nva_start_addr;
  1572. struct vmap_area *va;
  1573. /*
  1574. * Do not adjust when:
  1575. * a) align <= PAGE_SIZE, because it does not make any sense.
  1576. * All blocks(their start addresses) are at least PAGE_SIZE
  1577. * aligned anyway;
  1578. * b) a short range where a requested size corresponds to exactly
  1579. * specified [vstart:vend] interval and an alignment > PAGE_SIZE.
  1580. * With adjusted search length an allocation would not succeed.
  1581. */
  1582. if (align <= PAGE_SIZE || (align > PAGE_SIZE && (vend - vstart) == size))
  1583. adjust_search_size = false;
  1584. va = find_vmap_lowest_match(root, size, align, vstart, adjust_search_size);
  1585. if (unlikely(!va))
  1586. return -ENOENT;
  1587. nva_start_addr = va_alloc(va, root, head, size, align, vstart, vend);
  1588. #if DEBUG_AUGMENT_LOWEST_MATCH_CHECK
  1589. if (!IS_ERR_VALUE(nva_start_addr))
  1590. find_vmap_lowest_match_check(root, head, size, align);
  1591. #endif
  1592. return nva_start_addr;
  1593. }
  1594. /*
  1595. * Free a region of KVA allocated by alloc_vmap_area
  1596. */
  1597. static void free_vmap_area(struct vmap_area *va)
  1598. {
  1599. struct vmap_node *vn = addr_to_node(va->va_start);
  1600. /*
  1601. * Remove from the busy tree/list.
  1602. */
  1603. spin_lock(&vn->busy.lock);
  1604. unlink_va(va, &vn->busy.root);
  1605. spin_unlock(&vn->busy.lock);
  1606. /*
  1607. * Insert/Merge it back to the free tree/list.
  1608. */
  1609. spin_lock(&free_vmap_area_lock);
  1610. merge_or_add_vmap_area_augment(va, &free_vmap_area_root, &free_vmap_area_list);
  1611. spin_unlock(&free_vmap_area_lock);
  1612. }
  1613. static inline void
  1614. preload_this_cpu_lock(spinlock_t *lock, gfp_t gfp_mask, int node)
  1615. {
  1616. struct vmap_area *va = NULL, *tmp;
  1617. /*
  1618. * Preload this CPU with one extra vmap_area object. It is used
  1619. * when fit type of free area is NE_FIT_TYPE. It guarantees that
  1620. * a CPU that does an allocation is preloaded.
  1621. *
  1622. * We do it in non-atomic context, thus it allows us to use more
  1623. * permissive allocation masks to be more stable under low memory
  1624. * condition and high memory pressure.
  1625. */
  1626. if (!this_cpu_read(ne_fit_preload_node))
  1627. va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
  1628. spin_lock(lock);
  1629. tmp = NULL;
  1630. if (va && !__this_cpu_try_cmpxchg(ne_fit_preload_node, &tmp, va))
  1631. kmem_cache_free(vmap_area_cachep, va);
  1632. }
  1633. static struct vmap_pool *
  1634. size_to_va_pool(struct vmap_node *vn, unsigned long size)
  1635. {
  1636. unsigned int idx = (size - 1) / PAGE_SIZE;
  1637. if (idx < MAX_VA_SIZE_PAGES)
  1638. return &vn->pool[idx];
  1639. return NULL;
  1640. }
  1641. static bool
  1642. node_pool_add_va(struct vmap_node *n, struct vmap_area *va)
  1643. {
  1644. struct vmap_pool *vp;
  1645. vp = size_to_va_pool(n, va_size(va));
  1646. if (!vp)
  1647. return false;
  1648. spin_lock(&n->pool_lock);
  1649. list_add(&va->list, &vp->head);
  1650. WRITE_ONCE(vp->len, vp->len + 1);
  1651. spin_unlock(&n->pool_lock);
  1652. return true;
  1653. }
  1654. static struct vmap_area *
  1655. node_pool_del_va(struct vmap_node *vn, unsigned long size,
  1656. unsigned long align, unsigned long vstart,
  1657. unsigned long vend)
  1658. {
  1659. struct vmap_area *va = NULL;
  1660. struct vmap_pool *vp;
  1661. int err = 0;
  1662. vp = size_to_va_pool(vn, size);
  1663. if (!vp || list_empty(&vp->head))
  1664. return NULL;
  1665. spin_lock(&vn->pool_lock);
  1666. if (!list_empty(&vp->head)) {
  1667. va = list_first_entry(&vp->head, struct vmap_area, list);
  1668. if (IS_ALIGNED(va->va_start, align)) {
  1669. /*
  1670. * Do some sanity check and emit a warning
  1671. * if one of below checks detects an error.
  1672. */
  1673. err |= (va_size(va) != size);
  1674. err |= (va->va_start < vstart);
  1675. err |= (va->va_end > vend);
  1676. if (!WARN_ON_ONCE(err)) {
  1677. list_del_init(&va->list);
  1678. WRITE_ONCE(vp->len, vp->len - 1);
  1679. } else {
  1680. va = NULL;
  1681. }
  1682. } else {
  1683. list_move_tail(&va->list, &vp->head);
  1684. va = NULL;
  1685. }
  1686. }
  1687. spin_unlock(&vn->pool_lock);
  1688. return va;
  1689. }
  1690. static struct vmap_area *
  1691. node_alloc(unsigned long size, unsigned long align,
  1692. unsigned long vstart, unsigned long vend,
  1693. unsigned long *addr, unsigned int *vn_id)
  1694. {
  1695. struct vmap_area *va;
  1696. *vn_id = 0;
  1697. *addr = -EINVAL;
  1698. /*
  1699. * Fallback to a global heap if not vmalloc or there
  1700. * is only one node.
  1701. */
  1702. if (vstart != VMALLOC_START || vend != VMALLOC_END ||
  1703. nr_vmap_nodes == 1)
  1704. return NULL;
  1705. *vn_id = raw_smp_processor_id() % nr_vmap_nodes;
  1706. va = node_pool_del_va(id_to_node(*vn_id), size, align, vstart, vend);
  1707. *vn_id = encode_vn_id(*vn_id);
  1708. if (va)
  1709. *addr = va->va_start;
  1710. return va;
  1711. }
  1712. static inline void setup_vmalloc_vm(struct vm_struct *vm,
  1713. struct vmap_area *va, unsigned long flags, const void *caller)
  1714. {
  1715. vm->flags = flags;
  1716. vm->addr = (void *)va->va_start;
  1717. vm->size = vm->requested_size = va_size(va);
  1718. vm->caller = caller;
  1719. va->vm = vm;
  1720. }
  1721. /*
  1722. * Allocate a region of KVA of the specified size and alignment, within the
  1723. * vstart and vend. If vm is passed in, the two will also be bound.
  1724. */
  1725. static struct vmap_area *alloc_vmap_area(unsigned long size,
  1726. unsigned long align,
  1727. unsigned long vstart, unsigned long vend,
  1728. int node, gfp_t gfp_mask,
  1729. unsigned long va_flags, struct vm_struct *vm)
  1730. {
  1731. struct vmap_node *vn;
  1732. struct vmap_area *va;
  1733. unsigned long freed;
  1734. unsigned long addr;
  1735. unsigned int vn_id;
  1736. bool allow_block;
  1737. int purged = 0;
  1738. int ret;
  1739. if (unlikely(!size || offset_in_page(size) || !is_power_of_2(align)))
  1740. return ERR_PTR(-EINVAL);
  1741. if (unlikely(!vmap_initialized))
  1742. return ERR_PTR(-EBUSY);
  1743. /* Only reclaim behaviour flags are relevant. */
  1744. gfp_mask = gfp_mask & GFP_RECLAIM_MASK;
  1745. allow_block = gfpflags_allow_blocking(gfp_mask);
  1746. might_sleep_if(allow_block);
  1747. /*
  1748. * If a VA is obtained from a global heap(if it fails here)
  1749. * it is anyway marked with this "vn_id" so it is returned
  1750. * to this pool's node later. Such way gives a possibility
  1751. * to populate pools based on users demand.
  1752. *
  1753. * On success a ready to go VA is returned.
  1754. */
  1755. va = node_alloc(size, align, vstart, vend, &addr, &vn_id);
  1756. if (!va) {
  1757. va = kmem_cache_alloc_node(vmap_area_cachep, gfp_mask, node);
  1758. if (unlikely(!va))
  1759. return ERR_PTR(-ENOMEM);
  1760. /*
  1761. * Only scan the relevant parts containing pointers to other objects
  1762. * to avoid false negatives.
  1763. */
  1764. kmemleak_scan_area(&va->rb_node, SIZE_MAX, gfp_mask);
  1765. }
  1766. retry:
  1767. if (IS_ERR_VALUE(addr)) {
  1768. preload_this_cpu_lock(&free_vmap_area_lock, gfp_mask, node);
  1769. addr = __alloc_vmap_area(&free_vmap_area_root, &free_vmap_area_list,
  1770. size, align, vstart, vend);
  1771. spin_unlock(&free_vmap_area_lock);
  1772. /*
  1773. * This is not a fast path. Check if yielding is needed. This
  1774. * is the only reschedule point in the vmalloc() path.
  1775. */
  1776. if (allow_block)
  1777. cond_resched();
  1778. }
  1779. trace_alloc_vmap_area(addr, size, align, vstart, vend, IS_ERR_VALUE(addr));
  1780. /*
  1781. * If an allocation fails, the error value is
  1782. * returned. Therefore trigger the overflow path.
  1783. */
  1784. if (IS_ERR_VALUE(addr)) {
  1785. if (allow_block)
  1786. goto overflow;
  1787. /*
  1788. * We can not trigger any reclaim logic because
  1789. * sleeping is not allowed, thus fail an allocation.
  1790. */
  1791. goto out_free_va;
  1792. }
  1793. va->va_start = addr;
  1794. va->va_end = addr + size;
  1795. va->vm = NULL;
  1796. va->flags = (va_flags | vn_id);
  1797. if (vm) {
  1798. vm->addr = (void *)va->va_start;
  1799. vm->size = va_size(va);
  1800. va->vm = vm;
  1801. }
  1802. vn = addr_to_node(va->va_start);
  1803. spin_lock(&vn->busy.lock);
  1804. insert_vmap_area(va, &vn->busy.root, &vn->busy.head);
  1805. spin_unlock(&vn->busy.lock);
  1806. BUG_ON(!IS_ALIGNED(va->va_start, align));
  1807. BUG_ON(va->va_start < vstart);
  1808. BUG_ON(va->va_end > vend);
  1809. ret = kasan_populate_vmalloc(addr, size, gfp_mask);
  1810. if (ret) {
  1811. free_vmap_area(va);
  1812. return ERR_PTR(ret);
  1813. }
  1814. return va;
  1815. overflow:
  1816. if (!purged) {
  1817. reclaim_and_purge_vmap_areas();
  1818. purged = 1;
  1819. goto retry;
  1820. }
  1821. freed = 0;
  1822. blocking_notifier_call_chain(&vmap_notify_list, 0, &freed);
  1823. if (freed > 0) {
  1824. purged = 0;
  1825. goto retry;
  1826. }
  1827. if (!(gfp_mask & __GFP_NOWARN) && printk_ratelimit())
  1828. pr_warn("vmalloc_node_range for size %lu failed: Address range restricted to %#lx - %#lx\n",
  1829. size, vstart, vend);
  1830. out_free_va:
  1831. kmem_cache_free(vmap_area_cachep, va);
  1832. return ERR_PTR(-EBUSY);
  1833. }
  1834. int register_vmap_purge_notifier(struct notifier_block *nb)
  1835. {
  1836. return blocking_notifier_chain_register(&vmap_notify_list, nb);
  1837. }
  1838. EXPORT_SYMBOL_GPL(register_vmap_purge_notifier);
  1839. int unregister_vmap_purge_notifier(struct notifier_block *nb)
  1840. {
  1841. return blocking_notifier_chain_unregister(&vmap_notify_list, nb);
  1842. }
  1843. EXPORT_SYMBOL_GPL(unregister_vmap_purge_notifier);
  1844. /*
  1845. * lazy_max_pages is the maximum amount of virtual address space we gather up
  1846. * before attempting to purge with a TLB flush.
  1847. *
  1848. * There is a tradeoff here: a larger number will cover more kernel page tables
  1849. * and take slightly longer to purge, but it will linearly reduce the number of
  1850. * global TLB flushes that must be performed. It would seem natural to scale
  1851. * this number up linearly with the number of CPUs (because vmapping activity
  1852. * could also scale linearly with the number of CPUs), however it is likely
  1853. * that in practice, workloads might be constrained in other ways that mean
  1854. * vmap activity will not scale linearly with CPUs. Also, I want to be
  1855. * conservative and not introduce a big latency on huge systems, so go with
  1856. * a less aggressive log scale. It will still be an improvement over the old
  1857. * code, and it will be simple to change the scale factor if we find that it
  1858. * becomes a problem on bigger systems.
  1859. */
  1860. static unsigned long lazy_max_pages(void)
  1861. {
  1862. unsigned int log;
  1863. log = fls(num_online_cpus());
  1864. return log * (32UL * 1024 * 1024 / PAGE_SIZE);
  1865. }
  1866. /*
  1867. * Serialize vmap purging. There is no actual critical section protected
  1868. * by this lock, but we want to avoid concurrent calls for performance
  1869. * reasons and to make the pcpu_get_vm_areas more deterministic.
  1870. */
  1871. static DEFINE_MUTEX(vmap_purge_lock);
  1872. /* for per-CPU blocks */
  1873. static void purge_fragmented_blocks_allcpus(void);
  1874. static void
  1875. reclaim_list_global(struct list_head *head)
  1876. {
  1877. struct vmap_area *va, *n;
  1878. if (list_empty(head))
  1879. return;
  1880. spin_lock(&free_vmap_area_lock);
  1881. list_for_each_entry_safe(va, n, head, list)
  1882. merge_or_add_vmap_area_augment(va,
  1883. &free_vmap_area_root, &free_vmap_area_list);
  1884. spin_unlock(&free_vmap_area_lock);
  1885. }
  1886. static void
  1887. decay_va_pool_node(struct vmap_node *vn, bool full_decay)
  1888. {
  1889. LIST_HEAD(decay_list);
  1890. struct rb_root decay_root = RB_ROOT;
  1891. struct vmap_area *va, *nva;
  1892. unsigned long n_decay, pool_len;
  1893. int i;
  1894. for (i = 0; i < MAX_VA_SIZE_PAGES; i++) {
  1895. LIST_HEAD(tmp_list);
  1896. if (list_empty(&vn->pool[i].head))
  1897. continue;
  1898. /* Detach the pool, so no-one can access it. */
  1899. spin_lock(&vn->pool_lock);
  1900. list_replace_init(&vn->pool[i].head, &tmp_list);
  1901. spin_unlock(&vn->pool_lock);
  1902. pool_len = n_decay = vn->pool[i].len;
  1903. WRITE_ONCE(vn->pool[i].len, 0);
  1904. /* Decay a pool by ~25% out of left objects. */
  1905. if (!full_decay)
  1906. n_decay >>= 2;
  1907. pool_len -= n_decay;
  1908. list_for_each_entry_safe(va, nva, &tmp_list, list) {
  1909. if (!n_decay--)
  1910. break;
  1911. list_del_init(&va->list);
  1912. merge_or_add_vmap_area(va, &decay_root, &decay_list);
  1913. }
  1914. /*
  1915. * Attach the pool back if it has been partly decayed.
  1916. * Please note, it is supposed that nobody(other contexts)
  1917. * can populate the pool therefore a simple list replace
  1918. * operation takes place here.
  1919. */
  1920. if (!list_empty(&tmp_list)) {
  1921. spin_lock(&vn->pool_lock);
  1922. list_replace_init(&tmp_list, &vn->pool[i].head);
  1923. WRITE_ONCE(vn->pool[i].len, pool_len);
  1924. spin_unlock(&vn->pool_lock);
  1925. }
  1926. }
  1927. reclaim_list_global(&decay_list);
  1928. }
  1929. #define KASAN_RELEASE_BATCH_SIZE 32
  1930. static void
  1931. kasan_release_vmalloc_node(struct vmap_node *vn)
  1932. {
  1933. struct vmap_area *va;
  1934. unsigned long start, end;
  1935. unsigned int batch_count = 0;
  1936. start = list_first_entry(&vn->purge_list, struct vmap_area, list)->va_start;
  1937. end = list_last_entry(&vn->purge_list, struct vmap_area, list)->va_end;
  1938. list_for_each_entry(va, &vn->purge_list, list) {
  1939. if (is_vmalloc_or_module_addr((void *) va->va_start))
  1940. kasan_release_vmalloc(va->va_start, va->va_end,
  1941. va->va_start, va->va_end,
  1942. KASAN_VMALLOC_PAGE_RANGE);
  1943. if (need_resched() || (++batch_count >= KASAN_RELEASE_BATCH_SIZE)) {
  1944. cond_resched();
  1945. batch_count = 0;
  1946. }
  1947. }
  1948. kasan_release_vmalloc(start, end, start, end, KASAN_VMALLOC_TLB_FLUSH);
  1949. }
  1950. static void purge_vmap_node(struct work_struct *work)
  1951. {
  1952. struct vmap_node *vn = container_of(work,
  1953. struct vmap_node, purge_work);
  1954. unsigned long nr_purged_pages = 0;
  1955. struct vmap_area *va, *n_va;
  1956. LIST_HEAD(local_list);
  1957. if (IS_ENABLED(CONFIG_KASAN_VMALLOC))
  1958. kasan_release_vmalloc_node(vn);
  1959. vn->nr_purged = 0;
  1960. list_for_each_entry_safe(va, n_va, &vn->purge_list, list) {
  1961. unsigned long nr = va_size(va) >> PAGE_SHIFT;
  1962. unsigned int vn_id = decode_vn_id(va->flags);
  1963. list_del_init(&va->list);
  1964. nr_purged_pages += nr;
  1965. vn->nr_purged++;
  1966. if (is_vn_id_valid(vn_id) && !vn->skip_populate)
  1967. if (node_pool_add_va(vn, va))
  1968. continue;
  1969. /* Go back to global. */
  1970. list_add(&va->list, &local_list);
  1971. }
  1972. atomic_long_sub(nr_purged_pages, &vmap_lazy_nr);
  1973. reclaim_list_global(&local_list);
  1974. }
  1975. /*
  1976. * Purges all lazily-freed vmap areas.
  1977. */
  1978. static bool __purge_vmap_area_lazy(unsigned long start, unsigned long end,
  1979. bool full_pool_decay)
  1980. {
  1981. unsigned long nr_purged_areas = 0;
  1982. unsigned int nr_purge_helpers;
  1983. static cpumask_t purge_nodes;
  1984. unsigned int nr_purge_nodes;
  1985. struct vmap_node *vn;
  1986. int i;
  1987. lockdep_assert_held(&vmap_purge_lock);
  1988. /*
  1989. * Use cpumask to mark which node has to be processed.
  1990. */
  1991. purge_nodes = CPU_MASK_NONE;
  1992. for_each_vmap_node(vn) {
  1993. INIT_LIST_HEAD(&vn->purge_list);
  1994. vn->skip_populate = full_pool_decay;
  1995. decay_va_pool_node(vn, full_pool_decay);
  1996. if (RB_EMPTY_ROOT(&vn->lazy.root))
  1997. continue;
  1998. spin_lock(&vn->lazy.lock);
  1999. WRITE_ONCE(vn->lazy.root.rb_node, NULL);
  2000. list_replace_init(&vn->lazy.head, &vn->purge_list);
  2001. spin_unlock(&vn->lazy.lock);
  2002. start = min(start, list_first_entry(&vn->purge_list,
  2003. struct vmap_area, list)->va_start);
  2004. end = max(end, list_last_entry(&vn->purge_list,
  2005. struct vmap_area, list)->va_end);
  2006. cpumask_set_cpu(node_to_id(vn), &purge_nodes);
  2007. }
  2008. nr_purge_nodes = cpumask_weight(&purge_nodes);
  2009. if (nr_purge_nodes > 0) {
  2010. flush_tlb_kernel_range(start, end);
  2011. /* One extra worker is per a lazy_max_pages() full set minus one. */
  2012. nr_purge_helpers = atomic_long_read(&vmap_lazy_nr) / lazy_max_pages();
  2013. nr_purge_helpers = clamp(nr_purge_helpers, 1U, nr_purge_nodes) - 1;
  2014. for_each_cpu(i, &purge_nodes) {
  2015. vn = &vmap_nodes[i];
  2016. if (nr_purge_helpers > 0) {
  2017. INIT_WORK(&vn->purge_work, purge_vmap_node);
  2018. if (cpumask_test_cpu(i, cpu_online_mask))
  2019. schedule_work_on(i, &vn->purge_work);
  2020. else
  2021. schedule_work(&vn->purge_work);
  2022. nr_purge_helpers--;
  2023. } else {
  2024. vn->purge_work.func = NULL;
  2025. purge_vmap_node(&vn->purge_work);
  2026. nr_purged_areas += vn->nr_purged;
  2027. }
  2028. }
  2029. for_each_cpu(i, &purge_nodes) {
  2030. vn = &vmap_nodes[i];
  2031. if (vn->purge_work.func) {
  2032. flush_work(&vn->purge_work);
  2033. nr_purged_areas += vn->nr_purged;
  2034. }
  2035. }
  2036. }
  2037. trace_purge_vmap_area_lazy(start, end, nr_purged_areas);
  2038. return nr_purged_areas > 0;
  2039. }
  2040. /*
  2041. * Reclaim vmap areas by purging fragmented blocks and purge_vmap_area_list.
  2042. */
  2043. static void reclaim_and_purge_vmap_areas(void)
  2044. {
  2045. mutex_lock(&vmap_purge_lock);
  2046. purge_fragmented_blocks_allcpus();
  2047. __purge_vmap_area_lazy(ULONG_MAX, 0, true);
  2048. mutex_unlock(&vmap_purge_lock);
  2049. }
  2050. static void drain_vmap_area_work(struct work_struct *work)
  2051. {
  2052. mutex_lock(&vmap_purge_lock);
  2053. __purge_vmap_area_lazy(ULONG_MAX, 0, false);
  2054. mutex_unlock(&vmap_purge_lock);
  2055. }
  2056. /*
  2057. * Free a vmap area, caller ensuring that the area has been unmapped,
  2058. * unlinked and flush_cache_vunmap had been called for the correct
  2059. * range previously.
  2060. */
  2061. static void free_vmap_area_noflush(struct vmap_area *va)
  2062. {
  2063. unsigned long nr_lazy_max = lazy_max_pages();
  2064. unsigned long va_start = va->va_start;
  2065. unsigned int vn_id = decode_vn_id(va->flags);
  2066. struct vmap_node *vn;
  2067. unsigned long nr_lazy;
  2068. if (WARN_ON_ONCE(!list_empty(&va->list)))
  2069. return;
  2070. nr_lazy = atomic_long_add_return_relaxed(va_size(va) >> PAGE_SHIFT,
  2071. &vmap_lazy_nr);
  2072. /*
  2073. * If it was request by a certain node we would like to
  2074. * return it to that node, i.e. its pool for later reuse.
  2075. */
  2076. vn = is_vn_id_valid(vn_id) ?
  2077. id_to_node(vn_id):addr_to_node(va->va_start);
  2078. spin_lock(&vn->lazy.lock);
  2079. insert_vmap_area(va, &vn->lazy.root, &vn->lazy.head);
  2080. spin_unlock(&vn->lazy.lock);
  2081. trace_free_vmap_area_noflush(va_start, nr_lazy, nr_lazy_max);
  2082. /* After this point, we may free va at any time */
  2083. if (unlikely(nr_lazy > nr_lazy_max))
  2084. schedule_work(&drain_vmap_work);
  2085. }
  2086. /*
  2087. * Free and unmap a vmap area
  2088. */
  2089. static void free_unmap_vmap_area(struct vmap_area *va)
  2090. {
  2091. flush_cache_vunmap(va->va_start, va->va_end);
  2092. vunmap_range_noflush(va->va_start, va->va_end);
  2093. if (debug_pagealloc_enabled_static())
  2094. flush_tlb_kernel_range(va->va_start, va->va_end);
  2095. free_vmap_area_noflush(va);
  2096. }
  2097. struct vmap_area *find_vmap_area(unsigned long addr)
  2098. {
  2099. struct vmap_node *vn;
  2100. struct vmap_area *va;
  2101. int i, j;
  2102. if (unlikely(!vmap_initialized))
  2103. return NULL;
  2104. /*
  2105. * An addr_to_node_id(addr) converts an address to a node index
  2106. * where a VA is located. If VA spans several zones and passed
  2107. * addr is not the same as va->va_start, what is not common, we
  2108. * may need to scan extra nodes. See an example:
  2109. *
  2110. * <----va---->
  2111. * -|-----|-----|-----|-----|-
  2112. * 1 2 0 1
  2113. *
  2114. * VA resides in node 1 whereas it spans 1, 2 an 0. If passed
  2115. * addr is within 2 or 0 nodes we should do extra work.
  2116. */
  2117. i = j = addr_to_node_id(addr);
  2118. do {
  2119. vn = &vmap_nodes[i];
  2120. spin_lock(&vn->busy.lock);
  2121. va = __find_vmap_area(addr, &vn->busy.root);
  2122. spin_unlock(&vn->busy.lock);
  2123. if (va)
  2124. return va;
  2125. } while ((i = (i + nr_vmap_nodes - 1) % nr_vmap_nodes) != j);
  2126. return NULL;
  2127. }
  2128. static struct vmap_area *find_unlink_vmap_area(unsigned long addr)
  2129. {
  2130. struct vmap_node *vn;
  2131. struct vmap_area *va;
  2132. int i, j;
  2133. /*
  2134. * Check the comment in the find_vmap_area() about the loop.
  2135. */
  2136. i = j = addr_to_node_id(addr);
  2137. do {
  2138. vn = &vmap_nodes[i];
  2139. spin_lock(&vn->busy.lock);
  2140. va = __find_vmap_area(addr, &vn->busy.root);
  2141. if (va)
  2142. unlink_va(va, &vn->busy.root);
  2143. spin_unlock(&vn->busy.lock);
  2144. if (va)
  2145. return va;
  2146. } while ((i = (i + nr_vmap_nodes - 1) % nr_vmap_nodes) != j);
  2147. return NULL;
  2148. }
  2149. /*** Per cpu kva allocator ***/
  2150. /*
  2151. * vmap space is limited especially on 32 bit architectures. Ensure there is
  2152. * room for at least 16 percpu vmap blocks per CPU.
  2153. */
  2154. /*
  2155. * If we had a constant VMALLOC_START and VMALLOC_END, we'd like to be able
  2156. * to #define VMALLOC_SPACE (VMALLOC_END-VMALLOC_START). Guess
  2157. * instead (we just need a rough idea)
  2158. */
  2159. #if BITS_PER_LONG == 32
  2160. #define VMALLOC_SPACE (128UL*1024*1024)
  2161. #else
  2162. #define VMALLOC_SPACE (128UL*1024*1024*1024)
  2163. #endif
  2164. #define VMALLOC_PAGES (VMALLOC_SPACE / PAGE_SIZE)
  2165. #define VMAP_MAX_ALLOC BITS_PER_LONG /* 256K with 4K pages */
  2166. #define VMAP_BBMAP_BITS_MAX 1024 /* 4MB with 4K pages */
  2167. #define VMAP_BBMAP_BITS_MIN (VMAP_MAX_ALLOC*2)
  2168. #define VMAP_MIN(x, y) ((x) < (y) ? (x) : (y)) /* can't use min() */
  2169. #define VMAP_MAX(x, y) ((x) > (y) ? (x) : (y)) /* can't use max() */
  2170. #define VMAP_BBMAP_BITS \
  2171. VMAP_MIN(VMAP_BBMAP_BITS_MAX, \
  2172. VMAP_MAX(VMAP_BBMAP_BITS_MIN, \
  2173. VMALLOC_PAGES / roundup_pow_of_two(NR_CPUS) / 16))
  2174. #define VMAP_BLOCK_SIZE (VMAP_BBMAP_BITS * PAGE_SIZE)
  2175. /*
  2176. * Purge threshold to prevent overeager purging of fragmented blocks for
  2177. * regular operations: Purge if vb->free is less than 1/4 of the capacity.
  2178. */
  2179. #define VMAP_PURGE_THRESHOLD (VMAP_BBMAP_BITS / 4)
  2180. #define VMAP_RAM 0x1 /* indicates vm_map_ram area*/
  2181. #define VMAP_BLOCK 0x2 /* mark out the vmap_block sub-type*/
  2182. #define VMAP_FLAGS_MASK 0x3
  2183. struct vmap_block_queue {
  2184. spinlock_t lock;
  2185. struct list_head free;
  2186. /*
  2187. * An xarray requires an extra memory dynamically to
  2188. * be allocated. If it is an issue, we can use rb-tree
  2189. * instead.
  2190. */
  2191. struct xarray vmap_blocks;
  2192. };
  2193. struct vmap_block {
  2194. spinlock_t lock;
  2195. struct vmap_area *va;
  2196. unsigned long free, dirty;
  2197. DECLARE_BITMAP(used_map, VMAP_BBMAP_BITS);
  2198. unsigned long dirty_min, dirty_max; /*< dirty range */
  2199. struct list_head free_list;
  2200. struct rcu_head rcu_head;
  2201. struct list_head purge;
  2202. unsigned int cpu;
  2203. };
  2204. /* Queue of free and dirty vmap blocks, for allocation and flushing purposes */
  2205. static DEFINE_PER_CPU(struct vmap_block_queue, vmap_block_queue);
  2206. /*
  2207. * In order to fast access to any "vmap_block" associated with a
  2208. * specific address, we use a hash.
  2209. *
  2210. * A per-cpu vmap_block_queue is used in both ways, to serialize
  2211. * an access to free block chains among CPUs(alloc path) and it
  2212. * also acts as a vmap_block hash(alloc/free paths). It means we
  2213. * overload it, since we already have the per-cpu array which is
  2214. * used as a hash table. When used as a hash a 'cpu' passed to
  2215. * per_cpu() is not actually a CPU but rather a hash index.
  2216. *
  2217. * A hash function is addr_to_vb_xa() which hashes any address
  2218. * to a specific index(in a hash) it belongs to. This then uses a
  2219. * per_cpu() macro to access an array with generated index.
  2220. *
  2221. * An example:
  2222. *
  2223. * CPU_1 CPU_2 CPU_0
  2224. * | | |
  2225. * V V V
  2226. * 0 10 20 30 40 50 60
  2227. * |------|------|------|------|------|------|...<vmap address space>
  2228. * CPU0 CPU1 CPU2 CPU0 CPU1 CPU2
  2229. *
  2230. * - CPU_1 invokes vm_unmap_ram(6), 6 belongs to CPU0 zone, thus
  2231. * it access: CPU0/INDEX0 -> vmap_blocks -> xa_lock;
  2232. *
  2233. * - CPU_2 invokes vm_unmap_ram(11), 11 belongs to CPU1 zone, thus
  2234. * it access: CPU1/INDEX1 -> vmap_blocks -> xa_lock;
  2235. *
  2236. * - CPU_0 invokes vm_unmap_ram(20), 20 belongs to CPU2 zone, thus
  2237. * it access: CPU2/INDEX2 -> vmap_blocks -> xa_lock.
  2238. *
  2239. * This technique almost always avoids lock contention on insert/remove,
  2240. * however xarray spinlocks protect against any contention that remains.
  2241. */
  2242. static struct xarray *
  2243. addr_to_vb_xa(unsigned long addr)
  2244. {
  2245. int index = (addr / VMAP_BLOCK_SIZE) % nr_cpu_ids;
  2246. /*
  2247. * Please note, nr_cpu_ids points on a highest set
  2248. * possible bit, i.e. we never invoke cpumask_next()
  2249. * if an index points on it which is nr_cpu_ids - 1.
  2250. */
  2251. if (!cpu_possible(index))
  2252. index = cpumask_next(index, cpu_possible_mask);
  2253. return &per_cpu(vmap_block_queue, index).vmap_blocks;
  2254. }
  2255. /*
  2256. * We should probably have a fallback mechanism to allocate virtual memory
  2257. * out of partially filled vmap blocks. However vmap block sizing should be
  2258. * fairly reasonable according to the vmalloc size, so it shouldn't be a
  2259. * big problem.
  2260. */
  2261. static unsigned long addr_to_vb_idx(unsigned long addr)
  2262. {
  2263. addr -= VMALLOC_START & ~(VMAP_BLOCK_SIZE-1);
  2264. addr /= VMAP_BLOCK_SIZE;
  2265. return addr;
  2266. }
  2267. static void *vmap_block_vaddr(unsigned long va_start, unsigned long pages_off)
  2268. {
  2269. unsigned long addr;
  2270. addr = va_start + (pages_off << PAGE_SHIFT);
  2271. BUG_ON(addr_to_vb_idx(addr) != addr_to_vb_idx(va_start));
  2272. return (void *)addr;
  2273. }
  2274. /**
  2275. * new_vmap_block - allocates new vmap_block and occupies 2^order pages in this
  2276. * block. Of course pages number can't exceed VMAP_BBMAP_BITS
  2277. * @order: how many 2^order pages should be occupied in newly allocated block
  2278. * @gfp_mask: flags for the page level allocator
  2279. *
  2280. * Return: virtual address in a newly allocated block or ERR_PTR(-errno)
  2281. */
  2282. static void *new_vmap_block(unsigned int order, gfp_t gfp_mask)
  2283. {
  2284. struct vmap_block_queue *vbq;
  2285. struct vmap_block *vb;
  2286. struct vmap_area *va;
  2287. struct xarray *xa;
  2288. unsigned long vb_idx;
  2289. int node, err;
  2290. void *vaddr;
  2291. node = numa_node_id();
  2292. vb = kmalloc_node(sizeof(struct vmap_block), gfp_mask, node);
  2293. if (unlikely(!vb))
  2294. return ERR_PTR(-ENOMEM);
  2295. va = alloc_vmap_area(VMAP_BLOCK_SIZE, VMAP_BLOCK_SIZE,
  2296. VMALLOC_START, VMALLOC_END,
  2297. node, gfp_mask,
  2298. VMAP_RAM|VMAP_BLOCK, NULL);
  2299. if (IS_ERR(va)) {
  2300. kfree(vb);
  2301. return ERR_CAST(va);
  2302. }
  2303. vaddr = vmap_block_vaddr(va->va_start, 0);
  2304. spin_lock_init(&vb->lock);
  2305. vb->va = va;
  2306. /* At least something should be left free */
  2307. BUG_ON(VMAP_BBMAP_BITS <= (1UL << order));
  2308. bitmap_zero(vb->used_map, VMAP_BBMAP_BITS);
  2309. vb->free = VMAP_BBMAP_BITS - (1UL << order);
  2310. vb->dirty = 0;
  2311. vb->dirty_min = VMAP_BBMAP_BITS;
  2312. vb->dirty_max = 0;
  2313. bitmap_set(vb->used_map, 0, (1UL << order));
  2314. INIT_LIST_HEAD(&vb->free_list);
  2315. vb->cpu = raw_smp_processor_id();
  2316. xa = addr_to_vb_xa(va->va_start);
  2317. vb_idx = addr_to_vb_idx(va->va_start);
  2318. err = xa_insert(xa, vb_idx, vb, gfp_mask);
  2319. if (err) {
  2320. kfree(vb);
  2321. free_vmap_area(va);
  2322. return ERR_PTR(err);
  2323. }
  2324. /*
  2325. * list_add_tail_rcu could happened in another core
  2326. * rather than vb->cpu due to task migration, which
  2327. * is safe as list_add_tail_rcu will ensure the list's
  2328. * integrity together with list_for_each_rcu from read
  2329. * side.
  2330. */
  2331. vbq = per_cpu_ptr(&vmap_block_queue, vb->cpu);
  2332. spin_lock(&vbq->lock);
  2333. list_add_tail_rcu(&vb->free_list, &vbq->free);
  2334. spin_unlock(&vbq->lock);
  2335. return vaddr;
  2336. }
  2337. static void free_vmap_block(struct vmap_block *vb)
  2338. {
  2339. struct vmap_node *vn;
  2340. struct vmap_block *tmp;
  2341. struct xarray *xa;
  2342. xa = addr_to_vb_xa(vb->va->va_start);
  2343. tmp = xa_erase(xa, addr_to_vb_idx(vb->va->va_start));
  2344. BUG_ON(tmp != vb);
  2345. vn = addr_to_node(vb->va->va_start);
  2346. spin_lock(&vn->busy.lock);
  2347. unlink_va(vb->va, &vn->busy.root);
  2348. spin_unlock(&vn->busy.lock);
  2349. free_vmap_area_noflush(vb->va);
  2350. kfree_rcu(vb, rcu_head);
  2351. }
  2352. static bool purge_fragmented_block(struct vmap_block *vb,
  2353. struct list_head *purge_list, bool force_purge)
  2354. {
  2355. struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, vb->cpu);
  2356. if (vb->free + vb->dirty != VMAP_BBMAP_BITS ||
  2357. vb->dirty == VMAP_BBMAP_BITS)
  2358. return false;
  2359. /* Don't overeagerly purge usable blocks unless requested */
  2360. if (!(force_purge || vb->free < VMAP_PURGE_THRESHOLD))
  2361. return false;
  2362. /* prevent further allocs after releasing lock */
  2363. WRITE_ONCE(vb->free, 0);
  2364. /* prevent purging it again */
  2365. WRITE_ONCE(vb->dirty, VMAP_BBMAP_BITS);
  2366. vb->dirty_min = 0;
  2367. vb->dirty_max = VMAP_BBMAP_BITS;
  2368. spin_lock(&vbq->lock);
  2369. list_del_rcu(&vb->free_list);
  2370. spin_unlock(&vbq->lock);
  2371. list_add_tail(&vb->purge, purge_list);
  2372. return true;
  2373. }
  2374. static void free_purged_blocks(struct list_head *purge_list)
  2375. {
  2376. struct vmap_block *vb, *n_vb;
  2377. list_for_each_entry_safe(vb, n_vb, purge_list, purge) {
  2378. list_del(&vb->purge);
  2379. free_vmap_block(vb);
  2380. }
  2381. }
  2382. static void purge_fragmented_blocks(int cpu)
  2383. {
  2384. LIST_HEAD(purge);
  2385. struct vmap_block *vb;
  2386. struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
  2387. rcu_read_lock();
  2388. list_for_each_entry_rcu(vb, &vbq->free, free_list) {
  2389. unsigned long free = READ_ONCE(vb->free);
  2390. unsigned long dirty = READ_ONCE(vb->dirty);
  2391. if (free + dirty != VMAP_BBMAP_BITS ||
  2392. dirty == VMAP_BBMAP_BITS)
  2393. continue;
  2394. spin_lock(&vb->lock);
  2395. purge_fragmented_block(vb, &purge, true);
  2396. spin_unlock(&vb->lock);
  2397. }
  2398. rcu_read_unlock();
  2399. free_purged_blocks(&purge);
  2400. }
  2401. static void purge_fragmented_blocks_allcpus(void)
  2402. {
  2403. int cpu;
  2404. for_each_possible_cpu(cpu)
  2405. purge_fragmented_blocks(cpu);
  2406. }
  2407. static void *vb_alloc(unsigned long size, gfp_t gfp_mask)
  2408. {
  2409. struct vmap_block_queue *vbq;
  2410. struct vmap_block *vb;
  2411. void *vaddr = NULL;
  2412. unsigned int order;
  2413. BUG_ON(offset_in_page(size));
  2414. BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
  2415. if (WARN_ON(size == 0)) {
  2416. /*
  2417. * Allocating 0 bytes isn't what caller wants since
  2418. * get_order(0) returns funny result. Just warn and terminate
  2419. * early.
  2420. */
  2421. return ERR_PTR(-EINVAL);
  2422. }
  2423. order = get_order(size);
  2424. rcu_read_lock();
  2425. vbq = raw_cpu_ptr(&vmap_block_queue);
  2426. list_for_each_entry_rcu(vb, &vbq->free, free_list) {
  2427. unsigned long pages_off;
  2428. if (READ_ONCE(vb->free) < (1UL << order))
  2429. continue;
  2430. spin_lock(&vb->lock);
  2431. if (vb->free < (1UL << order)) {
  2432. spin_unlock(&vb->lock);
  2433. continue;
  2434. }
  2435. pages_off = VMAP_BBMAP_BITS - vb->free;
  2436. vaddr = vmap_block_vaddr(vb->va->va_start, pages_off);
  2437. WRITE_ONCE(vb->free, vb->free - (1UL << order));
  2438. bitmap_set(vb->used_map, pages_off, (1UL << order));
  2439. if (vb->free == 0) {
  2440. spin_lock(&vbq->lock);
  2441. list_del_rcu(&vb->free_list);
  2442. spin_unlock(&vbq->lock);
  2443. }
  2444. spin_unlock(&vb->lock);
  2445. break;
  2446. }
  2447. rcu_read_unlock();
  2448. /* Allocate new block if nothing was found */
  2449. if (!vaddr)
  2450. vaddr = new_vmap_block(order, gfp_mask);
  2451. return vaddr;
  2452. }
  2453. static void vb_free(unsigned long addr, unsigned long size)
  2454. {
  2455. unsigned long offset;
  2456. unsigned int order;
  2457. struct vmap_block *vb;
  2458. struct xarray *xa;
  2459. BUG_ON(offset_in_page(size));
  2460. BUG_ON(size > PAGE_SIZE*VMAP_MAX_ALLOC);
  2461. flush_cache_vunmap(addr, addr + size);
  2462. order = get_order(size);
  2463. offset = (addr & (VMAP_BLOCK_SIZE - 1)) >> PAGE_SHIFT;
  2464. xa = addr_to_vb_xa(addr);
  2465. vb = xa_load(xa, addr_to_vb_idx(addr));
  2466. spin_lock(&vb->lock);
  2467. bitmap_clear(vb->used_map, offset, (1UL << order));
  2468. spin_unlock(&vb->lock);
  2469. vunmap_range_noflush(addr, addr + size);
  2470. if (debug_pagealloc_enabled_static())
  2471. flush_tlb_kernel_range(addr, addr + size);
  2472. spin_lock(&vb->lock);
  2473. /* Expand the not yet TLB flushed dirty range */
  2474. vb->dirty_min = min(vb->dirty_min, offset);
  2475. vb->dirty_max = max(vb->dirty_max, offset + (1UL << order));
  2476. WRITE_ONCE(vb->dirty, vb->dirty + (1UL << order));
  2477. if (vb->dirty == VMAP_BBMAP_BITS) {
  2478. BUG_ON(vb->free);
  2479. spin_unlock(&vb->lock);
  2480. free_vmap_block(vb);
  2481. } else
  2482. spin_unlock(&vb->lock);
  2483. }
  2484. static void _vm_unmap_aliases(unsigned long start, unsigned long end, int flush)
  2485. {
  2486. LIST_HEAD(purge_list);
  2487. int cpu;
  2488. if (unlikely(!vmap_initialized))
  2489. return;
  2490. mutex_lock(&vmap_purge_lock);
  2491. for_each_possible_cpu(cpu) {
  2492. struct vmap_block_queue *vbq = &per_cpu(vmap_block_queue, cpu);
  2493. struct vmap_block *vb;
  2494. unsigned long idx;
  2495. rcu_read_lock();
  2496. xa_for_each(&vbq->vmap_blocks, idx, vb) {
  2497. spin_lock(&vb->lock);
  2498. /*
  2499. * Try to purge a fragmented block first. If it's
  2500. * not purgeable, check whether there is dirty
  2501. * space to be flushed.
  2502. */
  2503. if (!purge_fragmented_block(vb, &purge_list, false) &&
  2504. vb->dirty_max && vb->dirty != VMAP_BBMAP_BITS) {
  2505. unsigned long va_start = vb->va->va_start;
  2506. unsigned long s, e;
  2507. s = va_start + (vb->dirty_min << PAGE_SHIFT);
  2508. e = va_start + (vb->dirty_max << PAGE_SHIFT);
  2509. start = min(s, start);
  2510. end = max(e, end);
  2511. /* Prevent that this is flushed again */
  2512. vb->dirty_min = VMAP_BBMAP_BITS;
  2513. vb->dirty_max = 0;
  2514. flush = 1;
  2515. }
  2516. spin_unlock(&vb->lock);
  2517. }
  2518. rcu_read_unlock();
  2519. }
  2520. free_purged_blocks(&purge_list);
  2521. if (!__purge_vmap_area_lazy(start, end, false) && flush)
  2522. flush_tlb_kernel_range(start, end);
  2523. mutex_unlock(&vmap_purge_lock);
  2524. }
  2525. /**
  2526. * vm_unmap_aliases - unmap outstanding lazy aliases in the vmap layer
  2527. *
  2528. * The vmap/vmalloc layer lazily flushes kernel virtual mappings primarily
  2529. * to amortize TLB flushing overheads. What this means is that any page you
  2530. * have now, may, in a former life, have been mapped into kernel virtual
  2531. * address by the vmap layer and so there might be some CPUs with TLB entries
  2532. * still referencing that page (additional to the regular 1:1 kernel mapping).
  2533. *
  2534. * vm_unmap_aliases flushes all such lazy mappings. After it returns, we can
  2535. * be sure that none of the pages we have control over will have any aliases
  2536. * from the vmap layer.
  2537. */
  2538. void vm_unmap_aliases(void)
  2539. {
  2540. _vm_unmap_aliases(ULONG_MAX, 0, 0);
  2541. }
  2542. EXPORT_SYMBOL_GPL(vm_unmap_aliases);
  2543. /**
  2544. * vm_unmap_ram - unmap linear kernel address space set up by vm_map_ram
  2545. * @mem: the pointer returned by vm_map_ram
  2546. * @count: the count passed to that vm_map_ram call (cannot unmap partial)
  2547. */
  2548. void vm_unmap_ram(const void *mem, unsigned int count)
  2549. {
  2550. unsigned long size = (unsigned long)count << PAGE_SHIFT;
  2551. unsigned long addr = (unsigned long)kasan_reset_tag(mem);
  2552. struct vmap_area *va;
  2553. might_sleep();
  2554. BUG_ON(!addr);
  2555. BUG_ON(addr < VMALLOC_START);
  2556. BUG_ON(addr > VMALLOC_END);
  2557. BUG_ON(!PAGE_ALIGNED(addr));
  2558. kasan_poison_vmalloc(mem, size);
  2559. if (likely(count <= VMAP_MAX_ALLOC)) {
  2560. debug_check_no_locks_freed(mem, size);
  2561. vb_free(addr, size);
  2562. return;
  2563. }
  2564. va = find_unlink_vmap_area(addr);
  2565. if (WARN_ON_ONCE(!va))
  2566. return;
  2567. debug_check_no_locks_freed((void *)va->va_start, va_size(va));
  2568. free_unmap_vmap_area(va);
  2569. }
  2570. EXPORT_SYMBOL(vm_unmap_ram);
  2571. /**
  2572. * vm_map_ram - map pages linearly into kernel virtual address (vmalloc space)
  2573. * @pages: an array of pointers to the pages to be mapped
  2574. * @count: number of pages
  2575. * @node: prefer to allocate data structures on this node
  2576. *
  2577. * If you use this function for less than VMAP_MAX_ALLOC pages, it could be
  2578. * faster than vmap so it's good. But if you mix long-life and short-life
  2579. * objects with vm_map_ram(), it could consume lots of address space through
  2580. * fragmentation (especially on a 32bit machine). You could see failures in
  2581. * the end. Please use this function for short-lived objects.
  2582. *
  2583. * Returns: a pointer to the address that has been mapped, or %NULL on failure
  2584. */
  2585. void *vm_map_ram(struct page **pages, unsigned int count, int node)
  2586. {
  2587. unsigned long size = (unsigned long)count << PAGE_SHIFT;
  2588. unsigned long addr;
  2589. void *mem;
  2590. if (likely(count <= VMAP_MAX_ALLOC)) {
  2591. mem = vb_alloc(size, GFP_KERNEL);
  2592. if (IS_ERR(mem))
  2593. return NULL;
  2594. addr = (unsigned long)mem;
  2595. } else {
  2596. struct vmap_area *va;
  2597. va = alloc_vmap_area(size, PAGE_SIZE,
  2598. VMALLOC_START, VMALLOC_END,
  2599. node, GFP_KERNEL, VMAP_RAM,
  2600. NULL);
  2601. if (IS_ERR(va))
  2602. return NULL;
  2603. addr = va->va_start;
  2604. mem = (void *)addr;
  2605. }
  2606. if (vmap_pages_range(addr, addr + size, PAGE_KERNEL,
  2607. pages, PAGE_SHIFT) < 0) {
  2608. vm_unmap_ram(mem, count);
  2609. return NULL;
  2610. }
  2611. /*
  2612. * Mark the pages as accessible, now that they are mapped.
  2613. * With hardware tag-based KASAN, marking is skipped for
  2614. * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
  2615. */
  2616. mem = kasan_unpoison_vmalloc(mem, size, KASAN_VMALLOC_PROT_NORMAL);
  2617. return mem;
  2618. }
  2619. EXPORT_SYMBOL(vm_map_ram);
  2620. static struct vm_struct *vmlist __initdata;
  2621. static inline unsigned int vm_area_page_order(struct vm_struct *vm)
  2622. {
  2623. #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
  2624. return vm->page_order;
  2625. #else
  2626. return 0;
  2627. #endif
  2628. }
  2629. unsigned int get_vm_area_page_order(struct vm_struct *vm)
  2630. {
  2631. return vm_area_page_order(vm);
  2632. }
  2633. static inline void set_vm_area_page_order(struct vm_struct *vm, unsigned int order)
  2634. {
  2635. #ifdef CONFIG_HAVE_ARCH_HUGE_VMALLOC
  2636. vm->page_order = order;
  2637. #else
  2638. BUG_ON(order != 0);
  2639. #endif
  2640. }
  2641. /**
  2642. * vm_area_add_early - add vmap area early during boot
  2643. * @vm: vm_struct to add
  2644. *
  2645. * This function is used to add fixed kernel vm area to vmlist before
  2646. * vmalloc_init() is called. @vm->addr, @vm->size, and @vm->flags
  2647. * should contain proper values and the other fields should be zero.
  2648. *
  2649. * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
  2650. */
  2651. void __init vm_area_add_early(struct vm_struct *vm)
  2652. {
  2653. struct vm_struct *tmp, **p;
  2654. BUG_ON(vmap_initialized);
  2655. for (p = &vmlist; (tmp = *p) != NULL; p = &tmp->next) {
  2656. if (tmp->addr >= vm->addr) {
  2657. BUG_ON(tmp->addr < vm->addr + vm->size);
  2658. break;
  2659. } else
  2660. BUG_ON(tmp->addr + tmp->size > vm->addr);
  2661. }
  2662. vm->next = *p;
  2663. *p = vm;
  2664. }
  2665. /**
  2666. * vm_area_register_early - register vmap area early during boot
  2667. * @vm: vm_struct to register
  2668. * @align: requested alignment
  2669. *
  2670. * This function is used to register kernel vm area before
  2671. * vmalloc_init() is called. @vm->size and @vm->flags should contain
  2672. * proper values on entry and other fields should be zero. On return,
  2673. * vm->addr contains the allocated address.
  2674. *
  2675. * DO NOT USE THIS FUNCTION UNLESS YOU KNOW WHAT YOU'RE DOING.
  2676. */
  2677. void __init vm_area_register_early(struct vm_struct *vm, size_t align)
  2678. {
  2679. unsigned long addr = ALIGN(VMALLOC_START, align);
  2680. struct vm_struct *cur, **p;
  2681. BUG_ON(vmap_initialized);
  2682. for (p = &vmlist; (cur = *p) != NULL; p = &cur->next) {
  2683. if ((unsigned long)cur->addr - addr >= vm->size)
  2684. break;
  2685. addr = ALIGN((unsigned long)cur->addr + cur->size, align);
  2686. }
  2687. BUG_ON(addr > VMALLOC_END - vm->size);
  2688. vm->addr = (void *)addr;
  2689. vm->next = *p;
  2690. *p = vm;
  2691. kasan_populate_early_vm_area_shadow(vm->addr, vm->size);
  2692. }
  2693. static void clear_vm_uninitialized_flag(struct vm_struct *vm)
  2694. {
  2695. /*
  2696. * Before removing VM_UNINITIALIZED,
  2697. * we should make sure that vm has proper values.
  2698. * Pair with smp_rmb() in vread_iter() and vmalloc_info_show().
  2699. */
  2700. smp_wmb();
  2701. vm->flags &= ~VM_UNINITIALIZED;
  2702. }
  2703. struct vm_struct *__get_vm_area_node(unsigned long size,
  2704. unsigned long align, unsigned long shift, unsigned long flags,
  2705. unsigned long start, unsigned long end, int node,
  2706. gfp_t gfp_mask, const void *caller)
  2707. {
  2708. struct vmap_area *va;
  2709. struct vm_struct *area;
  2710. unsigned long requested_size = size;
  2711. BUG_ON(in_interrupt());
  2712. size = ALIGN(size, 1ul << shift);
  2713. if (unlikely(!size))
  2714. return NULL;
  2715. if (flags & VM_IOREMAP)
  2716. align = 1ul << clamp_t(int, get_count_order_long(size),
  2717. PAGE_SHIFT, IOREMAP_MAX_ORDER);
  2718. area = kzalloc_node(sizeof(*area), gfp_mask & GFP_RECLAIM_MASK, node);
  2719. if (unlikely(!area))
  2720. return NULL;
  2721. if (!(flags & VM_NO_GUARD))
  2722. size += PAGE_SIZE;
  2723. area->flags = flags;
  2724. area->caller = caller;
  2725. area->requested_size = requested_size;
  2726. va = alloc_vmap_area(size, align, start, end, node, gfp_mask, 0, area);
  2727. if (IS_ERR(va)) {
  2728. kfree(area);
  2729. return NULL;
  2730. }
  2731. /*
  2732. * Mark pages for non-VM_ALLOC mappings as accessible. Do it now as a
  2733. * best-effort approach, as they can be mapped outside of vmalloc code.
  2734. * For VM_ALLOC mappings, the pages are marked as accessible after
  2735. * getting mapped in __vmalloc_node_range().
  2736. * With hardware tag-based KASAN, marking is skipped for
  2737. * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
  2738. */
  2739. if (!(flags & VM_ALLOC))
  2740. area->addr = kasan_unpoison_vmalloc(area->addr, requested_size,
  2741. KASAN_VMALLOC_PROT_NORMAL);
  2742. return area;
  2743. }
  2744. struct vm_struct *__get_vm_area_caller(unsigned long size, unsigned long flags,
  2745. unsigned long start, unsigned long end,
  2746. const void *caller)
  2747. {
  2748. return __get_vm_area_node(size, 1, PAGE_SHIFT, flags, start, end,
  2749. NUMA_NO_NODE, GFP_KERNEL, caller);
  2750. }
  2751. /**
  2752. * get_vm_area - reserve a contiguous kernel virtual area
  2753. * @size: size of the area
  2754. * @flags: %VM_IOREMAP for I/O mappings or VM_ALLOC
  2755. *
  2756. * Search an area of @size in the kernel virtual mapping area,
  2757. * and reserved it for out purposes. Returns the area descriptor
  2758. * on success or %NULL on failure.
  2759. *
  2760. * Return: the area descriptor on success or %NULL on failure.
  2761. */
  2762. struct vm_struct *get_vm_area(unsigned long size, unsigned long flags)
  2763. {
  2764. return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
  2765. VMALLOC_START, VMALLOC_END,
  2766. NUMA_NO_NODE, GFP_KERNEL,
  2767. __builtin_return_address(0));
  2768. }
  2769. struct vm_struct *get_vm_area_caller(unsigned long size, unsigned long flags,
  2770. const void *caller)
  2771. {
  2772. return __get_vm_area_node(size, 1, PAGE_SHIFT, flags,
  2773. VMALLOC_START, VMALLOC_END,
  2774. NUMA_NO_NODE, GFP_KERNEL, caller);
  2775. }
  2776. /**
  2777. * find_vm_area - find a continuous kernel virtual area
  2778. * @addr: base address
  2779. *
  2780. * Search for the kernel VM area starting at @addr, and return it.
  2781. * It is up to the caller to do all required locking to keep the returned
  2782. * pointer valid.
  2783. *
  2784. * Return: the area descriptor on success or %NULL on failure.
  2785. */
  2786. struct vm_struct *find_vm_area(const void *addr)
  2787. {
  2788. struct vmap_area *va;
  2789. va = find_vmap_area((unsigned long)addr);
  2790. if (!va)
  2791. return NULL;
  2792. return va->vm;
  2793. }
  2794. /**
  2795. * remove_vm_area - find and remove a continuous kernel virtual area
  2796. * @addr: base address
  2797. *
  2798. * Search for the kernel VM area starting at @addr, and remove it.
  2799. * This function returns the found VM area, but using it is NOT safe
  2800. * on SMP machines, except for its size or flags.
  2801. *
  2802. * Return: the area descriptor on success or %NULL on failure.
  2803. */
  2804. struct vm_struct *remove_vm_area(const void *addr)
  2805. {
  2806. struct vmap_area *va;
  2807. struct vm_struct *vm;
  2808. might_sleep();
  2809. if (WARN(!PAGE_ALIGNED(addr), "Trying to vfree() bad address (%p)\n",
  2810. addr))
  2811. return NULL;
  2812. va = find_unlink_vmap_area((unsigned long)addr);
  2813. if (!va || !va->vm)
  2814. return NULL;
  2815. vm = va->vm;
  2816. debug_check_no_locks_freed(vm->addr, get_vm_area_size(vm));
  2817. debug_check_no_obj_freed(vm->addr, get_vm_area_size(vm));
  2818. kasan_free_module_shadow(vm);
  2819. kasan_poison_vmalloc(vm->addr, get_vm_area_size(vm));
  2820. free_unmap_vmap_area(va);
  2821. return vm;
  2822. }
  2823. static inline void set_area_direct_map(const struct vm_struct *area,
  2824. int (*set_direct_map)(struct page *page))
  2825. {
  2826. int i;
  2827. /* HUGE_VMALLOC passes small pages to set_direct_map */
  2828. for (i = 0; i < area->nr_pages; i++)
  2829. if (page_address(area->pages[i]))
  2830. set_direct_map(area->pages[i]);
  2831. }
  2832. /*
  2833. * Flush the vm mapping and reset the direct map.
  2834. */
  2835. static void vm_reset_perms(struct vm_struct *area)
  2836. {
  2837. unsigned long start = ULONG_MAX, end = 0;
  2838. unsigned int page_order = vm_area_page_order(area);
  2839. int flush_dmap = 0;
  2840. int i;
  2841. /*
  2842. * Find the start and end range of the direct mappings to make sure that
  2843. * the vm_unmap_aliases() flush includes the direct map.
  2844. */
  2845. for (i = 0; i < area->nr_pages; i += 1U << page_order) {
  2846. unsigned long addr = (unsigned long)page_address(area->pages[i]);
  2847. if (addr) {
  2848. unsigned long page_size;
  2849. page_size = PAGE_SIZE << page_order;
  2850. start = min(addr, start);
  2851. end = max(addr + page_size, end);
  2852. flush_dmap = 1;
  2853. }
  2854. }
  2855. /*
  2856. * Set direct map to something invalid so that it won't be cached if
  2857. * there are any accesses after the TLB flush, then flush the TLB and
  2858. * reset the direct map permissions to the default.
  2859. */
  2860. set_area_direct_map(area, set_direct_map_invalid_noflush);
  2861. _vm_unmap_aliases(start, end, flush_dmap);
  2862. set_area_direct_map(area, set_direct_map_default_noflush);
  2863. }
  2864. static void delayed_vfree_work(struct work_struct *w)
  2865. {
  2866. struct vfree_deferred *p = container_of(w, struct vfree_deferred, wq);
  2867. struct llist_node *t, *llnode;
  2868. llist_for_each_safe(llnode, t, llist_del_all(&p->list))
  2869. vfree(llnode);
  2870. }
  2871. /**
  2872. * vfree_atomic - release memory allocated by vmalloc()
  2873. * @addr: memory base address
  2874. *
  2875. * This one is just like vfree() but can be called in any atomic context
  2876. * except NMIs.
  2877. */
  2878. void vfree_atomic(const void *addr)
  2879. {
  2880. struct vfree_deferred *p = raw_cpu_ptr(&vfree_deferred);
  2881. BUG_ON(in_nmi());
  2882. kmemleak_free(addr);
  2883. /*
  2884. * Use raw_cpu_ptr() because this can be called from preemptible
  2885. * context. Preemption is absolutely fine here, because the llist_add()
  2886. * implementation is lockless, so it works even if we are adding to
  2887. * another cpu's list. schedule_work() should be fine with this too.
  2888. */
  2889. if (addr && llist_add((struct llist_node *)addr, &p->list))
  2890. schedule_work(&p->wq);
  2891. }
  2892. /**
  2893. * vfree - Release memory allocated by vmalloc()
  2894. * @addr: Memory base address
  2895. *
  2896. * Free the virtually continuous memory area starting at @addr, as obtained
  2897. * from one of the vmalloc() family of APIs. This will usually also free the
  2898. * physical memory underlying the virtual allocation, but that memory is
  2899. * reference counted, so it will not be freed until the last user goes away.
  2900. *
  2901. * If @addr is NULL, no operation is performed.
  2902. *
  2903. * Context:
  2904. * May sleep if called *not* from interrupt context.
  2905. * Must not be called in NMI context (strictly speaking, it could be
  2906. * if we have CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG, but making the calling
  2907. * conventions for vfree() arch-dependent would be a really bad idea).
  2908. */
  2909. void vfree(const void *addr)
  2910. {
  2911. struct vm_struct *vm;
  2912. int i;
  2913. if (unlikely(in_interrupt())) {
  2914. vfree_atomic(addr);
  2915. return;
  2916. }
  2917. BUG_ON(in_nmi());
  2918. kmemleak_free(addr);
  2919. might_sleep();
  2920. if (!addr)
  2921. return;
  2922. vm = remove_vm_area(addr);
  2923. if (unlikely(!vm)) {
  2924. WARN(1, KERN_ERR "Trying to vfree() nonexistent vm area (%p)\n",
  2925. addr);
  2926. return;
  2927. }
  2928. if (unlikely(vm->flags & VM_FLUSH_RESET_PERMS))
  2929. vm_reset_perms(vm);
  2930. /* All pages of vm should be charged to same memcg, so use first one. */
  2931. if (vm->nr_pages && !(vm->flags & VM_MAP_PUT_PAGES))
  2932. mod_memcg_page_state(vm->pages[0], MEMCG_VMALLOC, -vm->nr_pages);
  2933. for (i = 0; i < vm->nr_pages; i++) {
  2934. struct page *page = vm->pages[i];
  2935. BUG_ON(!page);
  2936. /*
  2937. * High-order allocs for huge vmallocs are split, so
  2938. * can be freed as an array of order-0 allocations
  2939. */
  2940. __free_page(page);
  2941. cond_resched();
  2942. }
  2943. if (!(vm->flags & VM_MAP_PUT_PAGES))
  2944. atomic_long_sub(vm->nr_pages, &nr_vmalloc_pages);
  2945. kvfree(vm->pages);
  2946. kfree(vm);
  2947. }
  2948. EXPORT_SYMBOL(vfree);
  2949. /**
  2950. * vunmap - release virtual mapping obtained by vmap()
  2951. * @addr: memory base address
  2952. *
  2953. * Free the virtually contiguous memory area starting at @addr,
  2954. * which was created from the page array passed to vmap().
  2955. *
  2956. * Must not be called in interrupt context.
  2957. */
  2958. void vunmap(const void *addr)
  2959. {
  2960. struct vm_struct *vm;
  2961. BUG_ON(in_interrupt());
  2962. might_sleep();
  2963. if (!addr)
  2964. return;
  2965. vm = remove_vm_area(addr);
  2966. if (unlikely(!vm)) {
  2967. WARN(1, KERN_ERR "Trying to vunmap() nonexistent vm area (%p)\n",
  2968. addr);
  2969. return;
  2970. }
  2971. kfree(vm);
  2972. }
  2973. EXPORT_SYMBOL(vunmap);
  2974. /**
  2975. * vmap - map an array of pages into virtually contiguous space
  2976. * @pages: array of page pointers
  2977. * @count: number of pages to map
  2978. * @flags: vm_area->flags
  2979. * @prot: page protection for the mapping
  2980. *
  2981. * Maps @count pages from @pages into contiguous kernel virtual space.
  2982. * If @flags contains %VM_MAP_PUT_PAGES the ownership of the pages array itself
  2983. * (which must be kmalloc or vmalloc memory) and one reference per pages in it
  2984. * are transferred from the caller to vmap(), and will be freed / dropped when
  2985. * vfree() is called on the return value.
  2986. *
  2987. * Return: the address of the area or %NULL on failure
  2988. */
  2989. void *vmap(struct page **pages, unsigned int count,
  2990. unsigned long flags, pgprot_t prot)
  2991. {
  2992. struct vm_struct *area;
  2993. unsigned long addr;
  2994. unsigned long size; /* In bytes */
  2995. might_sleep();
  2996. if (WARN_ON_ONCE(flags & VM_FLUSH_RESET_PERMS))
  2997. return NULL;
  2998. /*
  2999. * Your top guard is someone else's bottom guard. Not having a top
  3000. * guard compromises someone else's mappings too.
  3001. */
  3002. if (WARN_ON_ONCE(flags & VM_NO_GUARD))
  3003. flags &= ~VM_NO_GUARD;
  3004. if (count > totalram_pages())
  3005. return NULL;
  3006. size = (unsigned long)count << PAGE_SHIFT;
  3007. area = get_vm_area_caller(size, flags, __builtin_return_address(0));
  3008. if (!area)
  3009. return NULL;
  3010. addr = (unsigned long)area->addr;
  3011. if (vmap_pages_range(addr, addr + size, pgprot_nx(prot),
  3012. pages, PAGE_SHIFT) < 0) {
  3013. vunmap(area->addr);
  3014. return NULL;
  3015. }
  3016. if (flags & VM_MAP_PUT_PAGES) {
  3017. area->pages = pages;
  3018. area->nr_pages = count;
  3019. }
  3020. return area->addr;
  3021. }
  3022. EXPORT_SYMBOL(vmap);
  3023. #ifdef CONFIG_VMAP_PFN
  3024. struct vmap_pfn_data {
  3025. unsigned long *pfns;
  3026. pgprot_t prot;
  3027. unsigned int idx;
  3028. };
  3029. static int vmap_pfn_apply(pte_t *pte, unsigned long addr, void *private)
  3030. {
  3031. struct vmap_pfn_data *data = private;
  3032. unsigned long pfn = data->pfns[data->idx];
  3033. pte_t ptent;
  3034. if (WARN_ON_ONCE(pfn_valid(pfn)))
  3035. return -EINVAL;
  3036. ptent = pte_mkspecial(pfn_pte(pfn, data->prot));
  3037. set_pte_at(&init_mm, addr, pte, ptent);
  3038. data->idx++;
  3039. return 0;
  3040. }
  3041. /**
  3042. * vmap_pfn - map an array of PFNs into virtually contiguous space
  3043. * @pfns: array of PFNs
  3044. * @count: number of pages to map
  3045. * @prot: page protection for the mapping
  3046. *
  3047. * Maps @count PFNs from @pfns into contiguous kernel virtual space and returns
  3048. * the start address of the mapping.
  3049. */
  3050. void *vmap_pfn(unsigned long *pfns, unsigned int count, pgprot_t prot)
  3051. {
  3052. struct vmap_pfn_data data = { .pfns = pfns, .prot = pgprot_nx(prot) };
  3053. struct vm_struct *area;
  3054. area = get_vm_area_caller(count * PAGE_SIZE, VM_IOREMAP,
  3055. __builtin_return_address(0));
  3056. if (!area)
  3057. return NULL;
  3058. if (apply_to_page_range(&init_mm, (unsigned long)area->addr,
  3059. count * PAGE_SIZE, vmap_pfn_apply, &data)) {
  3060. free_vm_area(area);
  3061. return NULL;
  3062. }
  3063. flush_cache_vmap((unsigned long)area->addr,
  3064. (unsigned long)area->addr + count * PAGE_SIZE);
  3065. return area->addr;
  3066. }
  3067. EXPORT_SYMBOL_GPL(vmap_pfn);
  3068. #endif /* CONFIG_VMAP_PFN */
  3069. /*
  3070. * Helper for vmalloc to adjust the gfp flags for certain allocations.
  3071. */
  3072. static inline gfp_t vmalloc_gfp_adjust(gfp_t flags, const bool large)
  3073. {
  3074. flags |= __GFP_NOWARN;
  3075. if (large)
  3076. flags &= ~__GFP_NOFAIL;
  3077. return flags;
  3078. }
  3079. static inline unsigned int
  3080. vm_area_alloc_pages(gfp_t gfp, int nid,
  3081. unsigned int order, unsigned int nr_pages, struct page **pages)
  3082. {
  3083. unsigned int nr_allocated = 0;
  3084. unsigned int nr_remaining = nr_pages;
  3085. unsigned int max_attempt_order = MAX_PAGE_ORDER;
  3086. struct page *page;
  3087. int i;
  3088. unsigned int large_order = ilog2(nr_remaining);
  3089. gfp_t large_gfp = vmalloc_gfp_adjust(gfp, large_order) & ~__GFP_DIRECT_RECLAIM;
  3090. large_order = min(max_attempt_order, large_order);
  3091. /*
  3092. * Initially, attempt to have the page allocator give us large order
  3093. * pages. Do not attempt allocating smaller than order chunks since
  3094. * __vmap_pages_range() expects physically contigous pages of exactly
  3095. * order long chunks.
  3096. */
  3097. while (large_order > order && nr_remaining) {
  3098. if (nid == NUMA_NO_NODE)
  3099. page = alloc_pages_noprof(large_gfp, large_order);
  3100. else
  3101. page = alloc_pages_node_noprof(nid, large_gfp, large_order);
  3102. if (unlikely(!page)) {
  3103. max_attempt_order = --large_order;
  3104. continue;
  3105. }
  3106. split_page(page, large_order);
  3107. for (i = 0; i < (1U << large_order); i++)
  3108. pages[nr_allocated + i] = page + i;
  3109. nr_allocated += 1U << large_order;
  3110. nr_remaining = nr_pages - nr_allocated;
  3111. large_order = ilog2(nr_remaining);
  3112. large_order = min(max_attempt_order, large_order);
  3113. }
  3114. /*
  3115. * For order-0 pages we make use of bulk allocator, if
  3116. * the page array is partly or not at all populated due
  3117. * to fails, fallback to a single page allocator that is
  3118. * more permissive.
  3119. */
  3120. if (!order) {
  3121. while (nr_allocated < nr_pages) {
  3122. unsigned int nr, nr_pages_request;
  3123. /*
  3124. * A maximum allowed request is hard-coded and is 100
  3125. * pages per call. That is done in order to prevent a
  3126. * long preemption off scenario in the bulk-allocator
  3127. * so the range is [1:100].
  3128. */
  3129. nr_pages_request = min(100U, nr_pages - nr_allocated);
  3130. /* memory allocation should consider mempolicy, we can't
  3131. * wrongly use nearest node when nid == NUMA_NO_NODE,
  3132. * otherwise memory may be allocated in only one node,
  3133. * but mempolicy wants to alloc memory by interleaving.
  3134. */
  3135. if (IS_ENABLED(CONFIG_NUMA) && nid == NUMA_NO_NODE)
  3136. nr = alloc_pages_bulk_mempolicy_noprof(gfp,
  3137. nr_pages_request,
  3138. pages + nr_allocated);
  3139. else
  3140. nr = alloc_pages_bulk_node_noprof(gfp, nid,
  3141. nr_pages_request,
  3142. pages + nr_allocated);
  3143. nr_allocated += nr;
  3144. /*
  3145. * If zero or pages were obtained partly,
  3146. * fallback to a single page allocator.
  3147. */
  3148. if (nr != nr_pages_request)
  3149. break;
  3150. }
  3151. }
  3152. /* High-order pages or fallback path if "bulk" fails. */
  3153. while (nr_allocated < nr_pages) {
  3154. if (!(gfp & __GFP_NOFAIL) && fatal_signal_pending(current))
  3155. break;
  3156. if (nid == NUMA_NO_NODE)
  3157. page = alloc_pages_noprof(gfp, order);
  3158. else
  3159. page = alloc_pages_node_noprof(nid, gfp, order);
  3160. if (unlikely(!page))
  3161. break;
  3162. /*
  3163. * High-order allocations must be able to be treated as
  3164. * independent small pages by callers (as they can with
  3165. * small-page vmallocs). Some drivers do their own refcounting
  3166. * on vmalloc_to_page() pages, some use page->mapping,
  3167. * page->lru, etc.
  3168. */
  3169. if (order)
  3170. split_page(page, order);
  3171. /*
  3172. * Careful, we allocate and map page-order pages, but
  3173. * tracking is done per PAGE_SIZE page so as to keep the
  3174. * vm_struct APIs independent of the physical/mapped size.
  3175. */
  3176. for (i = 0; i < (1U << order); i++)
  3177. pages[nr_allocated + i] = page + i;
  3178. nr_allocated += 1U << order;
  3179. }
  3180. return nr_allocated;
  3181. }
  3182. static LLIST_HEAD(pending_vm_area_cleanup);
  3183. static void cleanup_vm_area_work(struct work_struct *work)
  3184. {
  3185. struct vm_struct *area, *tmp;
  3186. struct llist_node *head;
  3187. head = llist_del_all(&pending_vm_area_cleanup);
  3188. if (!head)
  3189. return;
  3190. llist_for_each_entry_safe(area, tmp, head, llnode) {
  3191. if (!area->pages)
  3192. free_vm_area(area);
  3193. else
  3194. vfree(area->addr);
  3195. }
  3196. }
  3197. /*
  3198. * Helper for __vmalloc_area_node() to defer cleanup
  3199. * of partially initialized vm_struct in error paths.
  3200. */
  3201. static DECLARE_WORK(cleanup_vm_area, cleanup_vm_area_work);
  3202. static void defer_vm_area_cleanup(struct vm_struct *area)
  3203. {
  3204. if (llist_add(&area->llnode, &pending_vm_area_cleanup))
  3205. schedule_work(&cleanup_vm_area);
  3206. }
  3207. /*
  3208. * Page tables allocations ignore external GFP. Enforces it by
  3209. * the memalloc scope API. It is used by vmalloc internals and
  3210. * KASAN shadow population only.
  3211. *
  3212. * GFP to scope mapping:
  3213. *
  3214. * non-blocking (no __GFP_DIRECT_RECLAIM) - memalloc_noreclaim_save()
  3215. * GFP_NOFS - memalloc_nofs_save()
  3216. * GFP_NOIO - memalloc_noio_save()
  3217. *
  3218. * Returns a flag cookie to pair with restore.
  3219. */
  3220. unsigned int
  3221. memalloc_apply_gfp_scope(gfp_t gfp_mask)
  3222. {
  3223. unsigned int flags = 0;
  3224. if (!gfpflags_allow_blocking(gfp_mask))
  3225. flags = memalloc_noreclaim_save();
  3226. else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == __GFP_IO)
  3227. flags = memalloc_nofs_save();
  3228. else if ((gfp_mask & (__GFP_FS | __GFP_IO)) == 0)
  3229. flags = memalloc_noio_save();
  3230. /* 0 - no scope applied. */
  3231. return flags;
  3232. }
  3233. void
  3234. memalloc_restore_scope(unsigned int flags)
  3235. {
  3236. if (flags)
  3237. memalloc_flags_restore(flags);
  3238. }
  3239. static void *__vmalloc_area_node(struct vm_struct *area, gfp_t gfp_mask,
  3240. pgprot_t prot, unsigned int page_shift,
  3241. int node)
  3242. {
  3243. const gfp_t nested_gfp = (gfp_mask & GFP_RECLAIM_MASK) | __GFP_ZERO;
  3244. bool nofail = gfp_mask & __GFP_NOFAIL;
  3245. unsigned long addr = (unsigned long)area->addr;
  3246. unsigned long size = get_vm_area_size(area);
  3247. unsigned long array_size;
  3248. unsigned int nr_small_pages = size >> PAGE_SHIFT;
  3249. unsigned int page_order;
  3250. unsigned int flags;
  3251. int ret;
  3252. array_size = (unsigned long)nr_small_pages * sizeof(struct page *);
  3253. /* __GFP_NOFAIL and "noblock" flags are mutually exclusive. */
  3254. if (!gfpflags_allow_blocking(gfp_mask))
  3255. nofail = false;
  3256. if (!(gfp_mask & (GFP_DMA | GFP_DMA32)))
  3257. gfp_mask |= __GFP_HIGHMEM;
  3258. /* Please note that the recursion is strictly bounded. */
  3259. if (array_size > PAGE_SIZE) {
  3260. area->pages = __vmalloc_node_noprof(array_size, 1, nested_gfp, node,
  3261. area->caller);
  3262. } else {
  3263. area->pages = kmalloc_node_noprof(array_size, nested_gfp, node);
  3264. }
  3265. if (!area->pages) {
  3266. warn_alloc(gfp_mask, NULL,
  3267. "vmalloc error: size %lu, failed to allocated page array size %lu",
  3268. nr_small_pages * PAGE_SIZE, array_size);
  3269. goto fail;
  3270. }
  3271. set_vm_area_page_order(area, page_shift - PAGE_SHIFT);
  3272. page_order = vm_area_page_order(area);
  3273. /*
  3274. * High-order nofail allocations are really expensive and
  3275. * potentially dangerous (pre-mature OOM, disruptive reclaim
  3276. * and compaction etc.
  3277. *
  3278. * Please note, the __vmalloc_node_range_noprof() falls-back
  3279. * to order-0 pages if high-order attempt is unsuccessful.
  3280. */
  3281. area->nr_pages = vm_area_alloc_pages(
  3282. vmalloc_gfp_adjust(gfp_mask, page_order), node,
  3283. page_order, nr_small_pages, area->pages);
  3284. atomic_long_add(area->nr_pages, &nr_vmalloc_pages);
  3285. /* All pages of vm should be charged to same memcg, so use first one. */
  3286. if (gfp_mask & __GFP_ACCOUNT && area->nr_pages)
  3287. mod_memcg_page_state(area->pages[0], MEMCG_VMALLOC,
  3288. area->nr_pages);
  3289. /*
  3290. * If not enough pages were obtained to accomplish an
  3291. * allocation request, free them via vfree() if any.
  3292. */
  3293. if (area->nr_pages != nr_small_pages) {
  3294. /*
  3295. * vm_area_alloc_pages() can fail due to insufficient memory but
  3296. * also:-
  3297. *
  3298. * - a pending fatal signal
  3299. * - insufficient huge page-order pages
  3300. *
  3301. * Since we always retry allocations at order-0 in the huge page
  3302. * case a warning for either is spurious.
  3303. */
  3304. if (!fatal_signal_pending(current) && page_order == 0)
  3305. warn_alloc(gfp_mask, NULL,
  3306. "vmalloc error: size %lu, failed to allocate pages",
  3307. area->nr_pages * PAGE_SIZE);
  3308. goto fail;
  3309. }
  3310. /*
  3311. * page tables allocations ignore external gfp mask, enforce it
  3312. * by the scope API
  3313. */
  3314. flags = memalloc_apply_gfp_scope(gfp_mask);
  3315. do {
  3316. ret = __vmap_pages_range(addr, addr + size, prot, area->pages,
  3317. page_shift, nested_gfp);
  3318. if (nofail && (ret < 0))
  3319. schedule_timeout_uninterruptible(1);
  3320. } while (nofail && (ret < 0));
  3321. memalloc_restore_scope(flags);
  3322. if (ret < 0) {
  3323. warn_alloc(gfp_mask, NULL,
  3324. "vmalloc error: size %lu, failed to map pages",
  3325. area->nr_pages * PAGE_SIZE);
  3326. goto fail;
  3327. }
  3328. return area->addr;
  3329. fail:
  3330. defer_vm_area_cleanup(area);
  3331. return NULL;
  3332. }
  3333. /*
  3334. * See __vmalloc_node_range() for a clear list of supported vmalloc flags.
  3335. * This gfp lists all flags currently passed through vmalloc. Currently,
  3336. * __GFP_ZERO is used by BPF and __GFP_NORETRY is used by percpu. Both drm
  3337. * and BPF also use GFP_USER. Additionally, various users pass
  3338. * GFP_KERNEL_ACCOUNT. Xfs uses __GFP_NOLOCKDEP.
  3339. */
  3340. #define GFP_VMALLOC_SUPPORTED (GFP_KERNEL | GFP_ATOMIC | GFP_NOWAIT |\
  3341. __GFP_NOFAIL | __GFP_ZERO | __GFP_NORETRY |\
  3342. GFP_NOFS | GFP_NOIO | GFP_KERNEL_ACCOUNT |\
  3343. GFP_USER | __GFP_NOLOCKDEP)
  3344. static gfp_t vmalloc_fix_flags(gfp_t flags)
  3345. {
  3346. gfp_t invalid_mask = flags & ~GFP_VMALLOC_SUPPORTED;
  3347. flags &= GFP_VMALLOC_SUPPORTED;
  3348. WARN_ONCE(1, "Unexpected gfp: %#x (%pGg). Fixing up to gfp: %#x (%pGg). Fix your code!\n",
  3349. invalid_mask, &invalid_mask, flags, &flags);
  3350. return flags;
  3351. }
  3352. /**
  3353. * __vmalloc_node_range - allocate virtually contiguous memory
  3354. * @size: allocation size
  3355. * @align: desired alignment
  3356. * @start: vm area range start
  3357. * @end: vm area range end
  3358. * @gfp_mask: flags for the page level allocator
  3359. * @prot: protection mask for the allocated pages
  3360. * @vm_flags: additional vm area flags (e.g. %VM_NO_GUARD)
  3361. * @node: node to use for allocation or NUMA_NO_NODE
  3362. * @caller: caller's return address
  3363. *
  3364. * Allocate enough pages to cover @size from the page level
  3365. * allocator with @gfp_mask flags and map them into contiguous
  3366. * virtual range with protection @prot.
  3367. *
  3368. * Supported GFP classes: %GFP_KERNEL, %GFP_ATOMIC, %GFP_NOWAIT,
  3369. * %GFP_NOFS and %GFP_NOIO. Zone modifiers are not supported.
  3370. * Please note %GFP_ATOMIC and %GFP_NOWAIT are supported only
  3371. * by __vmalloc().
  3372. *
  3373. * Retry modifiers: only %__GFP_NOFAIL is supported; %__GFP_NORETRY
  3374. * and %__GFP_RETRY_MAYFAIL are not supported.
  3375. *
  3376. * %__GFP_NOWARN can be used to suppress failure messages.
  3377. *
  3378. * Can not be called from interrupt nor NMI contexts.
  3379. * Return: the address of the area or %NULL on failure
  3380. */
  3381. void *__vmalloc_node_range_noprof(unsigned long size, unsigned long align,
  3382. unsigned long start, unsigned long end, gfp_t gfp_mask,
  3383. pgprot_t prot, unsigned long vm_flags, int node,
  3384. const void *caller)
  3385. {
  3386. struct vm_struct *area;
  3387. void *ret;
  3388. kasan_vmalloc_flags_t kasan_flags = KASAN_VMALLOC_NONE;
  3389. unsigned long original_align = align;
  3390. unsigned int shift = PAGE_SHIFT;
  3391. if (WARN_ON_ONCE(!size))
  3392. return NULL;
  3393. if ((size >> PAGE_SHIFT) > totalram_pages()) {
  3394. warn_alloc(gfp_mask, NULL,
  3395. "vmalloc error: size %lu, exceeds total pages",
  3396. size);
  3397. return NULL;
  3398. }
  3399. if (vmap_allow_huge && (vm_flags & VM_ALLOW_HUGE_VMAP)) {
  3400. /*
  3401. * Try huge pages. Only try for PAGE_KERNEL allocations,
  3402. * others like modules don't yet expect huge pages in
  3403. * their allocations due to apply_to_page_range not
  3404. * supporting them.
  3405. */
  3406. if (arch_vmap_pmd_supported(prot) && size >= PMD_SIZE)
  3407. shift = PMD_SHIFT;
  3408. else
  3409. shift = arch_vmap_pte_supported_shift(size);
  3410. align = max(original_align, 1UL << shift);
  3411. }
  3412. again:
  3413. area = __get_vm_area_node(size, align, shift, VM_ALLOC |
  3414. VM_UNINITIALIZED | vm_flags, start, end, node,
  3415. gfp_mask, caller);
  3416. if (!area) {
  3417. bool nofail = gfp_mask & __GFP_NOFAIL;
  3418. warn_alloc(gfp_mask, NULL,
  3419. "vmalloc error: size %lu, vm_struct allocation failed%s",
  3420. size, (nofail) ? ". Retrying." : "");
  3421. if (nofail) {
  3422. schedule_timeout_uninterruptible(1);
  3423. goto again;
  3424. }
  3425. goto fail;
  3426. }
  3427. /*
  3428. * Prepare arguments for __vmalloc_area_node() and
  3429. * kasan_unpoison_vmalloc().
  3430. */
  3431. if (pgprot_val(prot) == pgprot_val(PAGE_KERNEL)) {
  3432. if (kasan_hw_tags_enabled()) {
  3433. /*
  3434. * Modify protection bits to allow tagging.
  3435. * This must be done before mapping.
  3436. */
  3437. prot = arch_vmap_pgprot_tagged(prot);
  3438. /*
  3439. * Skip page_alloc poisoning and zeroing for physical
  3440. * pages backing VM_ALLOC mapping. Memory is instead
  3441. * poisoned and zeroed by kasan_unpoison_vmalloc().
  3442. */
  3443. gfp_mask |= __GFP_SKIP_KASAN | __GFP_SKIP_ZERO;
  3444. }
  3445. /* Take note that the mapping is PAGE_KERNEL. */
  3446. kasan_flags |= KASAN_VMALLOC_PROT_NORMAL;
  3447. }
  3448. /* Allocate physical pages and map them into vmalloc space. */
  3449. ret = __vmalloc_area_node(area, gfp_mask, prot, shift, node);
  3450. if (!ret)
  3451. goto fail;
  3452. /*
  3453. * Mark the pages as accessible, now that they are mapped.
  3454. * The condition for setting KASAN_VMALLOC_INIT should complement the
  3455. * one in post_alloc_hook() with regards to the __GFP_SKIP_ZERO check
  3456. * to make sure that memory is initialized under the same conditions.
  3457. * Tag-based KASAN modes only assign tags to normal non-executable
  3458. * allocations, see __kasan_unpoison_vmalloc().
  3459. */
  3460. kasan_flags |= KASAN_VMALLOC_VM_ALLOC;
  3461. if (!want_init_on_free() && want_init_on_alloc(gfp_mask) &&
  3462. (gfp_mask & __GFP_SKIP_ZERO))
  3463. kasan_flags |= KASAN_VMALLOC_INIT;
  3464. /* KASAN_VMALLOC_PROT_NORMAL already set if required. */
  3465. area->addr = kasan_unpoison_vmalloc(area->addr, size, kasan_flags);
  3466. /*
  3467. * In this function, newly allocated vm_struct has VM_UNINITIALIZED
  3468. * flag. It means that vm_struct is not fully initialized.
  3469. * Now, it is fully initialized, so remove this flag here.
  3470. */
  3471. clear_vm_uninitialized_flag(area);
  3472. if (!(vm_flags & VM_DEFER_KMEMLEAK))
  3473. kmemleak_vmalloc(area, PAGE_ALIGN(size), gfp_mask);
  3474. return area->addr;
  3475. fail:
  3476. if (shift > PAGE_SHIFT) {
  3477. shift = PAGE_SHIFT;
  3478. align = original_align;
  3479. goto again;
  3480. }
  3481. return NULL;
  3482. }
  3483. /**
  3484. * __vmalloc_node - allocate virtually contiguous memory
  3485. * @size: allocation size
  3486. * @align: desired alignment
  3487. * @gfp_mask: flags for the page level allocator
  3488. * @node: node to use for allocation or NUMA_NO_NODE
  3489. * @caller: caller's return address
  3490. *
  3491. * Allocate enough pages to cover @size from the page level allocator with
  3492. * @gfp_mask flags. Map them into contiguous kernel virtual space.
  3493. *
  3494. * Semantics of @gfp_mask (including reclaim/retry modifiers such as
  3495. * __GFP_NOFAIL) are the same as in __vmalloc_node_range_noprof().
  3496. *
  3497. * Return: pointer to the allocated memory or %NULL on error
  3498. */
  3499. void *__vmalloc_node_noprof(unsigned long size, unsigned long align,
  3500. gfp_t gfp_mask, int node, const void *caller)
  3501. {
  3502. return __vmalloc_node_range_noprof(size, align, VMALLOC_START, VMALLOC_END,
  3503. gfp_mask, PAGE_KERNEL, 0, node, caller);
  3504. }
  3505. /*
  3506. * This is only for performance analysis of vmalloc and stress purpose.
  3507. * It is required by vmalloc test module, therefore do not use it other
  3508. * than that.
  3509. */
  3510. #ifdef CONFIG_TEST_VMALLOC_MODULE
  3511. EXPORT_SYMBOL_GPL(__vmalloc_node_noprof);
  3512. #endif
  3513. void *__vmalloc_noprof(unsigned long size, gfp_t gfp_mask)
  3514. {
  3515. if (unlikely(gfp_mask & ~GFP_VMALLOC_SUPPORTED))
  3516. gfp_mask = vmalloc_fix_flags(gfp_mask);
  3517. return __vmalloc_node_noprof(size, 1, gfp_mask, NUMA_NO_NODE,
  3518. __builtin_return_address(0));
  3519. }
  3520. EXPORT_SYMBOL(__vmalloc_noprof);
  3521. /**
  3522. * vmalloc - allocate virtually contiguous memory
  3523. * @size: allocation size
  3524. *
  3525. * Allocate enough pages to cover @size from the page level
  3526. * allocator and map them into contiguous kernel virtual space.
  3527. *
  3528. * For tight control over page level allocator and protection flags
  3529. * use __vmalloc() instead.
  3530. *
  3531. * Return: pointer to the allocated memory or %NULL on error
  3532. */
  3533. void *vmalloc_noprof(unsigned long size)
  3534. {
  3535. return __vmalloc_node_noprof(size, 1, GFP_KERNEL, NUMA_NO_NODE,
  3536. __builtin_return_address(0));
  3537. }
  3538. EXPORT_SYMBOL(vmalloc_noprof);
  3539. /**
  3540. * vmalloc_huge_node - allocate virtually contiguous memory, allow huge pages
  3541. * @size: allocation size
  3542. * @gfp_mask: flags for the page level allocator
  3543. * @node: node to use for allocation or NUMA_NO_NODE
  3544. *
  3545. * Allocate enough pages to cover @size from the page level
  3546. * allocator and map them into contiguous kernel virtual space.
  3547. * If @size is greater than or equal to PMD_SIZE, allow using
  3548. * huge pages for the memory
  3549. *
  3550. * Return: pointer to the allocated memory or %NULL on error
  3551. */
  3552. void *vmalloc_huge_node_noprof(unsigned long size, gfp_t gfp_mask, int node)
  3553. {
  3554. if (unlikely(gfp_mask & ~GFP_VMALLOC_SUPPORTED))
  3555. gfp_mask = vmalloc_fix_flags(gfp_mask);
  3556. return __vmalloc_node_range_noprof(size, 1, VMALLOC_START, VMALLOC_END,
  3557. gfp_mask, PAGE_KERNEL, VM_ALLOW_HUGE_VMAP,
  3558. node, __builtin_return_address(0));
  3559. }
  3560. EXPORT_SYMBOL_GPL(vmalloc_huge_node_noprof);
  3561. /**
  3562. * vzalloc - allocate virtually contiguous memory with zero fill
  3563. * @size: allocation size
  3564. *
  3565. * Allocate enough pages to cover @size from the page level
  3566. * allocator and map them into contiguous kernel virtual space.
  3567. * The memory allocated is set to zero.
  3568. *
  3569. * For tight control over page level allocator and protection flags
  3570. * use __vmalloc() instead.
  3571. *
  3572. * Return: pointer to the allocated memory or %NULL on error
  3573. */
  3574. void *vzalloc_noprof(unsigned long size)
  3575. {
  3576. return __vmalloc_node_noprof(size, 1, GFP_KERNEL | __GFP_ZERO, NUMA_NO_NODE,
  3577. __builtin_return_address(0));
  3578. }
  3579. EXPORT_SYMBOL(vzalloc_noprof);
  3580. /**
  3581. * vmalloc_user - allocate zeroed virtually contiguous memory for userspace
  3582. * @size: allocation size
  3583. *
  3584. * The resulting memory area is zeroed so it can be mapped to userspace
  3585. * without leaking data.
  3586. *
  3587. * Return: pointer to the allocated memory or %NULL on error
  3588. */
  3589. void *vmalloc_user_noprof(unsigned long size)
  3590. {
  3591. return __vmalloc_node_range_noprof(size, SHMLBA, VMALLOC_START, VMALLOC_END,
  3592. GFP_KERNEL | __GFP_ZERO, PAGE_KERNEL,
  3593. VM_USERMAP, NUMA_NO_NODE,
  3594. __builtin_return_address(0));
  3595. }
  3596. EXPORT_SYMBOL(vmalloc_user_noprof);
  3597. /**
  3598. * vmalloc_node - allocate memory on a specific node
  3599. * @size: allocation size
  3600. * @node: numa node
  3601. *
  3602. * Allocate enough pages to cover @size from the page level
  3603. * allocator and map them into contiguous kernel virtual space.
  3604. *
  3605. * For tight control over page level allocator and protection flags
  3606. * use __vmalloc() instead.
  3607. *
  3608. * Return: pointer to the allocated memory or %NULL on error
  3609. */
  3610. void *vmalloc_node_noprof(unsigned long size, int node)
  3611. {
  3612. return __vmalloc_node_noprof(size, 1, GFP_KERNEL, node,
  3613. __builtin_return_address(0));
  3614. }
  3615. EXPORT_SYMBOL(vmalloc_node_noprof);
  3616. /**
  3617. * vzalloc_node - allocate memory on a specific node with zero fill
  3618. * @size: allocation size
  3619. * @node: numa node
  3620. *
  3621. * Allocate enough pages to cover @size from the page level
  3622. * allocator and map them into contiguous kernel virtual space.
  3623. * The memory allocated is set to zero.
  3624. *
  3625. * Return: pointer to the allocated memory or %NULL on error
  3626. */
  3627. void *vzalloc_node_noprof(unsigned long size, int node)
  3628. {
  3629. return __vmalloc_node_noprof(size, 1, GFP_KERNEL | __GFP_ZERO, node,
  3630. __builtin_return_address(0));
  3631. }
  3632. EXPORT_SYMBOL(vzalloc_node_noprof);
  3633. /**
  3634. * vrealloc_node_align - reallocate virtually contiguous memory; contents
  3635. * remain unchanged
  3636. * @p: object to reallocate memory for
  3637. * @size: the size to reallocate
  3638. * @align: requested alignment
  3639. * @flags: the flags for the page level allocator
  3640. * @nid: node number of the target node
  3641. *
  3642. * If @p is %NULL, vrealloc_XXX() behaves exactly like vmalloc_XXX(). If @size
  3643. * is 0 and @p is not a %NULL pointer, the object pointed to is freed.
  3644. *
  3645. * If the caller wants the new memory to be on specific node *only*,
  3646. * __GFP_THISNODE flag should be set, otherwise the function will try to avoid
  3647. * reallocation and possibly disregard the specified @nid.
  3648. *
  3649. * If __GFP_ZERO logic is requested, callers must ensure that, starting with the
  3650. * initial memory allocation, every subsequent call to this API for the same
  3651. * memory allocation is flagged with __GFP_ZERO. Otherwise, it is possible that
  3652. * __GFP_ZERO is not fully honored by this API.
  3653. *
  3654. * Requesting an alignment that is bigger than the alignment of the existing
  3655. * allocation will fail.
  3656. *
  3657. * In any case, the contents of the object pointed to are preserved up to the
  3658. * lesser of the new and old sizes.
  3659. *
  3660. * This function must not be called concurrently with itself or vfree() for the
  3661. * same memory allocation.
  3662. *
  3663. * Return: pointer to the allocated memory; %NULL if @size is zero or in case of
  3664. * failure
  3665. */
  3666. void *vrealloc_node_align_noprof(const void *p, size_t size, unsigned long align,
  3667. gfp_t flags, int nid)
  3668. {
  3669. struct vm_struct *vm = NULL;
  3670. size_t alloced_size = 0;
  3671. size_t old_size = 0;
  3672. void *n;
  3673. if (!size) {
  3674. vfree(p);
  3675. return NULL;
  3676. }
  3677. if (p) {
  3678. vm = find_vm_area(p);
  3679. if (unlikely(!vm)) {
  3680. WARN(1, "Trying to vrealloc() nonexistent vm area (%p)\n", p);
  3681. return NULL;
  3682. }
  3683. alloced_size = get_vm_area_size(vm);
  3684. old_size = vm->requested_size;
  3685. if (WARN(alloced_size < old_size,
  3686. "vrealloc() has mismatched area vs requested sizes (%p)\n", p))
  3687. return NULL;
  3688. if (WARN(!IS_ALIGNED((unsigned long)p, align),
  3689. "will not reallocate with a bigger alignment (0x%lx)\n", align))
  3690. return NULL;
  3691. if (unlikely(flags & __GFP_THISNODE) && nid != NUMA_NO_NODE &&
  3692. nid != page_to_nid(vmalloc_to_page(p)))
  3693. goto need_realloc;
  3694. }
  3695. /*
  3696. * TODO: Shrink the vm_area, i.e. unmap and free unused pages. What
  3697. * would be a good heuristic for when to shrink the vm_area?
  3698. */
  3699. if (size <= old_size) {
  3700. /* Zero out "freed" memory, potentially for future realloc. */
  3701. if (want_init_on_free() || want_init_on_alloc(flags))
  3702. memset((void *)p + size, 0, old_size - size);
  3703. vm->requested_size = size;
  3704. kasan_vrealloc(p, old_size, size);
  3705. return (void *)p;
  3706. }
  3707. /*
  3708. * We already have the bytes available in the allocation; use them.
  3709. */
  3710. if (size <= alloced_size) {
  3711. /*
  3712. * No need to zero memory here, as unused memory will have
  3713. * already been zeroed at initial allocation time or during
  3714. * realloc shrink time.
  3715. */
  3716. vm->requested_size = size;
  3717. kasan_vrealloc(p, old_size, size);
  3718. return (void *)p;
  3719. }
  3720. need_realloc:
  3721. /* TODO: Grow the vm_area, i.e. allocate and map additional pages. */
  3722. n = __vmalloc_node_noprof(size, align, flags, nid, __builtin_return_address(0));
  3723. if (!n)
  3724. return NULL;
  3725. if (p) {
  3726. memcpy(n, p, old_size);
  3727. vfree(p);
  3728. }
  3729. return n;
  3730. }
  3731. EXPORT_SYMBOL(vrealloc_node_align_noprof);
  3732. #if defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA32)
  3733. #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
  3734. #elif defined(CONFIG_64BIT) && defined(CONFIG_ZONE_DMA)
  3735. #define GFP_VMALLOC32 (GFP_DMA | GFP_KERNEL)
  3736. #else
  3737. /*
  3738. * 64b systems should always have either DMA or DMA32 zones. For others
  3739. * GFP_DMA32 should do the right thing and use the normal zone.
  3740. */
  3741. #define GFP_VMALLOC32 (GFP_DMA32 | GFP_KERNEL)
  3742. #endif
  3743. /**
  3744. * vmalloc_32 - allocate virtually contiguous memory (32bit addressable)
  3745. * @size: allocation size
  3746. *
  3747. * Allocate enough 32bit PA addressable pages to cover @size from the
  3748. * page level allocator and map them into contiguous kernel virtual space.
  3749. *
  3750. * Return: pointer to the allocated memory or %NULL on error
  3751. */
  3752. void *vmalloc_32_noprof(unsigned long size)
  3753. {
  3754. return __vmalloc_node_noprof(size, 1, GFP_VMALLOC32, NUMA_NO_NODE,
  3755. __builtin_return_address(0));
  3756. }
  3757. EXPORT_SYMBOL(vmalloc_32_noprof);
  3758. /**
  3759. * vmalloc_32_user - allocate zeroed virtually contiguous 32bit memory
  3760. * @size: allocation size
  3761. *
  3762. * The resulting memory area is 32bit addressable and zeroed so it can be
  3763. * mapped to userspace without leaking data.
  3764. *
  3765. * Return: pointer to the allocated memory or %NULL on error
  3766. */
  3767. void *vmalloc_32_user_noprof(unsigned long size)
  3768. {
  3769. return __vmalloc_node_range_noprof(size, SHMLBA, VMALLOC_START, VMALLOC_END,
  3770. GFP_VMALLOC32 | __GFP_ZERO, PAGE_KERNEL,
  3771. VM_USERMAP, NUMA_NO_NODE,
  3772. __builtin_return_address(0));
  3773. }
  3774. EXPORT_SYMBOL(vmalloc_32_user_noprof);
  3775. /*
  3776. * Atomically zero bytes in the iterator.
  3777. *
  3778. * Returns the number of zeroed bytes.
  3779. */
  3780. static size_t zero_iter(struct iov_iter *iter, size_t count)
  3781. {
  3782. size_t remains = count;
  3783. while (remains > 0) {
  3784. size_t num, copied;
  3785. num = min_t(size_t, remains, PAGE_SIZE);
  3786. copied = copy_page_to_iter_nofault(ZERO_PAGE(0), 0, num, iter);
  3787. remains -= copied;
  3788. if (copied < num)
  3789. break;
  3790. }
  3791. return count - remains;
  3792. }
  3793. /*
  3794. * small helper routine, copy contents to iter from addr.
  3795. * If the page is not present, fill zero.
  3796. *
  3797. * Returns the number of copied bytes.
  3798. */
  3799. static size_t aligned_vread_iter(struct iov_iter *iter,
  3800. const char *addr, size_t count)
  3801. {
  3802. size_t remains = count;
  3803. struct page *page;
  3804. while (remains > 0) {
  3805. unsigned long offset, length;
  3806. size_t copied = 0;
  3807. offset = offset_in_page(addr);
  3808. length = PAGE_SIZE - offset;
  3809. if (length > remains)
  3810. length = remains;
  3811. page = vmalloc_to_page(addr);
  3812. /*
  3813. * To do safe access to this _mapped_ area, we need lock. But
  3814. * adding lock here means that we need to add overhead of
  3815. * vmalloc()/vfree() calls for this _debug_ interface, rarely
  3816. * used. Instead of that, we'll use an local mapping via
  3817. * copy_page_to_iter_nofault() and accept a small overhead in
  3818. * this access function.
  3819. */
  3820. if (page)
  3821. copied = copy_page_to_iter_nofault(page, offset,
  3822. length, iter);
  3823. else
  3824. copied = zero_iter(iter, length);
  3825. addr += copied;
  3826. remains -= copied;
  3827. if (copied != length)
  3828. break;
  3829. }
  3830. return count - remains;
  3831. }
  3832. /*
  3833. * Read from a vm_map_ram region of memory.
  3834. *
  3835. * Returns the number of copied bytes.
  3836. */
  3837. static size_t vmap_ram_vread_iter(struct iov_iter *iter, const char *addr,
  3838. size_t count, unsigned long flags)
  3839. {
  3840. char *start;
  3841. struct vmap_block *vb;
  3842. struct xarray *xa;
  3843. unsigned long offset;
  3844. unsigned int rs, re;
  3845. size_t remains, n;
  3846. /*
  3847. * If it's area created by vm_map_ram() interface directly, but
  3848. * not further subdividing and delegating management to vmap_block,
  3849. * handle it here.
  3850. */
  3851. if (!(flags & VMAP_BLOCK))
  3852. return aligned_vread_iter(iter, addr, count);
  3853. remains = count;
  3854. /*
  3855. * Area is split into regions and tracked with vmap_block, read out
  3856. * each region and zero fill the hole between regions.
  3857. */
  3858. xa = addr_to_vb_xa((unsigned long) addr);
  3859. vb = xa_load(xa, addr_to_vb_idx((unsigned long)addr));
  3860. if (!vb)
  3861. goto finished_zero;
  3862. spin_lock(&vb->lock);
  3863. if (bitmap_empty(vb->used_map, VMAP_BBMAP_BITS)) {
  3864. spin_unlock(&vb->lock);
  3865. goto finished_zero;
  3866. }
  3867. for_each_set_bitrange(rs, re, vb->used_map, VMAP_BBMAP_BITS) {
  3868. size_t copied;
  3869. if (remains == 0)
  3870. goto finished;
  3871. start = vmap_block_vaddr(vb->va->va_start, rs);
  3872. if (addr < start) {
  3873. size_t to_zero = min_t(size_t, start - addr, remains);
  3874. size_t zeroed = zero_iter(iter, to_zero);
  3875. addr += zeroed;
  3876. remains -= zeroed;
  3877. if (remains == 0 || zeroed != to_zero)
  3878. goto finished;
  3879. }
  3880. /*it could start reading from the middle of used region*/
  3881. offset = offset_in_page(addr);
  3882. n = ((re - rs + 1) << PAGE_SHIFT) - offset;
  3883. if (n > remains)
  3884. n = remains;
  3885. copied = aligned_vread_iter(iter, start + offset, n);
  3886. addr += copied;
  3887. remains -= copied;
  3888. if (copied != n)
  3889. goto finished;
  3890. }
  3891. spin_unlock(&vb->lock);
  3892. finished_zero:
  3893. /* zero-fill the left dirty or free regions */
  3894. return count - remains + zero_iter(iter, remains);
  3895. finished:
  3896. /* We couldn't copy/zero everything */
  3897. spin_unlock(&vb->lock);
  3898. return count - remains;
  3899. }
  3900. /**
  3901. * vread_iter() - read vmalloc area in a safe way to an iterator.
  3902. * @iter: the iterator to which data should be written.
  3903. * @addr: vm address.
  3904. * @count: number of bytes to be read.
  3905. *
  3906. * This function checks that addr is a valid vmalloc'ed area, and
  3907. * copy data from that area to a given buffer. If the given memory range
  3908. * of [addr...addr+count) includes some valid address, data is copied to
  3909. * proper area of @buf. If there are memory holes, they'll be zero-filled.
  3910. * IOREMAP area is treated as memory hole and no copy is done.
  3911. *
  3912. * If [addr...addr+count) doesn't includes any intersects with alive
  3913. * vm_struct area, returns 0. @buf should be kernel's buffer.
  3914. *
  3915. * Note: In usual ops, vread() is never necessary because the caller
  3916. * should know vmalloc() area is valid and can use memcpy().
  3917. * This is for routines which have to access vmalloc area without
  3918. * any information, as /proc/kcore.
  3919. *
  3920. * Return: number of bytes for which addr and buf should be increased
  3921. * (same number as @count) or %0 if [addr...addr+count) doesn't
  3922. * include any intersection with valid vmalloc area
  3923. */
  3924. long vread_iter(struct iov_iter *iter, const char *addr, size_t count)
  3925. {
  3926. struct vmap_node *vn;
  3927. struct vmap_area *va;
  3928. struct vm_struct *vm;
  3929. char *vaddr;
  3930. size_t n, size, flags, remains;
  3931. unsigned long next;
  3932. addr = kasan_reset_tag(addr);
  3933. /* Don't allow overflow */
  3934. if ((unsigned long) addr + count < count)
  3935. count = -(unsigned long) addr;
  3936. remains = count;
  3937. vn = find_vmap_area_exceed_addr_lock((unsigned long) addr, &va);
  3938. if (!vn)
  3939. goto finished_zero;
  3940. /* no intersects with alive vmap_area */
  3941. if ((unsigned long)addr + remains <= va->va_start)
  3942. goto finished_zero;
  3943. do {
  3944. size_t copied;
  3945. if (remains == 0)
  3946. goto finished;
  3947. vm = va->vm;
  3948. flags = va->flags & VMAP_FLAGS_MASK;
  3949. /*
  3950. * VMAP_BLOCK indicates a sub-type of vm_map_ram area, need
  3951. * be set together with VMAP_RAM.
  3952. */
  3953. WARN_ON(flags == VMAP_BLOCK);
  3954. if (!vm && !flags)
  3955. goto next_va;
  3956. if (vm && (vm->flags & VM_UNINITIALIZED))
  3957. goto next_va;
  3958. /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
  3959. smp_rmb();
  3960. vaddr = (char *) va->va_start;
  3961. size = vm ? get_vm_area_size(vm) : va_size(va);
  3962. if (addr >= vaddr + size)
  3963. goto next_va;
  3964. if (addr < vaddr) {
  3965. size_t to_zero = min_t(size_t, vaddr - addr, remains);
  3966. size_t zeroed = zero_iter(iter, to_zero);
  3967. addr += zeroed;
  3968. remains -= zeroed;
  3969. if (remains == 0 || zeroed != to_zero)
  3970. goto finished;
  3971. }
  3972. n = vaddr + size - addr;
  3973. if (n > remains)
  3974. n = remains;
  3975. if (flags & VMAP_RAM)
  3976. copied = vmap_ram_vread_iter(iter, addr, n, flags);
  3977. else if (!(vm && (vm->flags & (VM_IOREMAP | VM_SPARSE))))
  3978. copied = aligned_vread_iter(iter, addr, n);
  3979. else /* IOREMAP | SPARSE area is treated as memory hole */
  3980. copied = zero_iter(iter, n);
  3981. addr += copied;
  3982. remains -= copied;
  3983. if (copied != n)
  3984. goto finished;
  3985. next_va:
  3986. next = va->va_end;
  3987. spin_unlock(&vn->busy.lock);
  3988. } while ((vn = find_vmap_area_exceed_addr_lock(next, &va)));
  3989. finished_zero:
  3990. if (vn)
  3991. spin_unlock(&vn->busy.lock);
  3992. /* zero-fill memory holes */
  3993. return count - remains + zero_iter(iter, remains);
  3994. finished:
  3995. /* Nothing remains, or We couldn't copy/zero everything. */
  3996. if (vn)
  3997. spin_unlock(&vn->busy.lock);
  3998. return count - remains;
  3999. }
  4000. /**
  4001. * remap_vmalloc_range_partial - map vmalloc pages to userspace
  4002. * @vma: vma to cover
  4003. * @uaddr: target user address to start at
  4004. * @kaddr: virtual address of vmalloc kernel memory
  4005. * @pgoff: offset from @kaddr to start at
  4006. * @size: size of map area
  4007. *
  4008. * Returns: 0 for success, -Exxx on failure
  4009. *
  4010. * This function checks that @kaddr is a valid vmalloc'ed area,
  4011. * and that it is big enough to cover the range starting at
  4012. * @uaddr in @vma. Will return failure if that criteria isn't
  4013. * met.
  4014. *
  4015. * Similar to remap_pfn_range() (see mm/memory.c)
  4016. */
  4017. int remap_vmalloc_range_partial(struct vm_area_struct *vma, unsigned long uaddr,
  4018. void *kaddr, unsigned long pgoff,
  4019. unsigned long size)
  4020. {
  4021. struct vm_struct *area;
  4022. unsigned long off;
  4023. unsigned long end_index;
  4024. if (check_shl_overflow(pgoff, PAGE_SHIFT, &off))
  4025. return -EINVAL;
  4026. size = PAGE_ALIGN(size);
  4027. if (!PAGE_ALIGNED(uaddr) || !PAGE_ALIGNED(kaddr))
  4028. return -EINVAL;
  4029. area = find_vm_area(kaddr);
  4030. if (!area)
  4031. return -EINVAL;
  4032. if (!(area->flags & (VM_USERMAP | VM_DMA_COHERENT)))
  4033. return -EINVAL;
  4034. if (check_add_overflow(size, off, &end_index) ||
  4035. end_index > get_vm_area_size(area))
  4036. return -EINVAL;
  4037. kaddr += off;
  4038. do {
  4039. struct page *page = vmalloc_to_page(kaddr);
  4040. int ret;
  4041. ret = vm_insert_page(vma, uaddr, page);
  4042. if (ret)
  4043. return ret;
  4044. uaddr += PAGE_SIZE;
  4045. kaddr += PAGE_SIZE;
  4046. size -= PAGE_SIZE;
  4047. } while (size > 0);
  4048. vm_flags_set(vma, VM_DONTEXPAND | VM_DONTDUMP);
  4049. return 0;
  4050. }
  4051. /**
  4052. * remap_vmalloc_range - map vmalloc pages to userspace
  4053. * @vma: vma to cover (map full range of vma)
  4054. * @addr: vmalloc memory
  4055. * @pgoff: number of pages into addr before first page to map
  4056. *
  4057. * Returns: 0 for success, -Exxx on failure
  4058. *
  4059. * This function checks that addr is a valid vmalloc'ed area, and
  4060. * that it is big enough to cover the vma. Will return failure if
  4061. * that criteria isn't met.
  4062. *
  4063. * Similar to remap_pfn_range() (see mm/memory.c)
  4064. */
  4065. int remap_vmalloc_range(struct vm_area_struct *vma, void *addr,
  4066. unsigned long pgoff)
  4067. {
  4068. return remap_vmalloc_range_partial(vma, vma->vm_start,
  4069. addr, pgoff,
  4070. vma->vm_end - vma->vm_start);
  4071. }
  4072. EXPORT_SYMBOL(remap_vmalloc_range);
  4073. void free_vm_area(struct vm_struct *area)
  4074. {
  4075. struct vm_struct *ret;
  4076. ret = remove_vm_area(area->addr);
  4077. BUG_ON(ret != area);
  4078. kfree(area);
  4079. }
  4080. EXPORT_SYMBOL_GPL(free_vm_area);
  4081. #ifdef CONFIG_SMP
  4082. static struct vmap_area *node_to_va(struct rb_node *n)
  4083. {
  4084. return rb_entry_safe(n, struct vmap_area, rb_node);
  4085. }
  4086. /**
  4087. * pvm_find_va_enclose_addr - find the vmap_area @addr belongs to
  4088. * @addr: target address
  4089. *
  4090. * Returns: vmap_area if it is found. If there is no such area
  4091. * the first highest(reverse order) vmap_area is returned
  4092. * i.e. va->va_start < addr && va->va_end < addr or NULL
  4093. * if there are no any areas before @addr.
  4094. */
  4095. static struct vmap_area *
  4096. pvm_find_va_enclose_addr(unsigned long addr)
  4097. {
  4098. struct vmap_area *va, *tmp;
  4099. struct rb_node *n;
  4100. n = free_vmap_area_root.rb_node;
  4101. va = NULL;
  4102. while (n) {
  4103. tmp = rb_entry(n, struct vmap_area, rb_node);
  4104. if (tmp->va_start <= addr) {
  4105. va = tmp;
  4106. if (tmp->va_end >= addr)
  4107. break;
  4108. n = n->rb_right;
  4109. } else {
  4110. n = n->rb_left;
  4111. }
  4112. }
  4113. return va;
  4114. }
  4115. /**
  4116. * pvm_determine_end_from_reverse - find the highest aligned address
  4117. * of free block below VMALLOC_END
  4118. * @va:
  4119. * in - the VA we start the search(reverse order);
  4120. * out - the VA with the highest aligned end address.
  4121. * @align: alignment for required highest address
  4122. *
  4123. * Returns: determined end address within vmap_area
  4124. */
  4125. static unsigned long
  4126. pvm_determine_end_from_reverse(struct vmap_area **va, unsigned long align)
  4127. {
  4128. unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
  4129. unsigned long addr;
  4130. if (likely(*va)) {
  4131. list_for_each_entry_from_reverse((*va),
  4132. &free_vmap_area_list, list) {
  4133. addr = min((*va)->va_end & ~(align - 1), vmalloc_end);
  4134. if ((*va)->va_start < addr)
  4135. return addr;
  4136. }
  4137. }
  4138. return 0;
  4139. }
  4140. /**
  4141. * pcpu_get_vm_areas - allocate vmalloc areas for percpu allocator
  4142. * @offsets: array containing offset of each area
  4143. * @sizes: array containing size of each area
  4144. * @nr_vms: the number of areas to allocate
  4145. * @align: alignment, all entries in @offsets and @sizes must be aligned to this
  4146. *
  4147. * Returns: kmalloc'd vm_struct pointer array pointing to allocated
  4148. * vm_structs on success, %NULL on failure
  4149. *
  4150. * Percpu allocator wants to use congruent vm areas so that it can
  4151. * maintain the offsets among percpu areas. This function allocates
  4152. * congruent vmalloc areas for it with GFP_KERNEL. These areas tend to
  4153. * be scattered pretty far, distance between two areas easily going up
  4154. * to gigabytes. To avoid interacting with regular vmallocs, these
  4155. * areas are allocated from top.
  4156. *
  4157. * Despite its complicated look, this allocator is rather simple. It
  4158. * does everything top-down and scans free blocks from the end looking
  4159. * for matching base. While scanning, if any of the areas do not fit the
  4160. * base address is pulled down to fit the area. Scanning is repeated till
  4161. * all the areas fit and then all necessary data structures are inserted
  4162. * and the result is returned.
  4163. */
  4164. struct vm_struct **pcpu_get_vm_areas(const unsigned long *offsets,
  4165. const size_t *sizes, int nr_vms,
  4166. size_t align)
  4167. {
  4168. const unsigned long vmalloc_start = ALIGN(VMALLOC_START, align);
  4169. const unsigned long vmalloc_end = VMALLOC_END & ~(align - 1);
  4170. struct vmap_area **vas, *va;
  4171. struct vm_struct **vms;
  4172. int area, area2, last_area, term_area;
  4173. unsigned long base, start, size, end, last_end, orig_start, orig_end;
  4174. bool purged = false;
  4175. /* verify parameters and allocate data structures */
  4176. BUG_ON(offset_in_page(align) || !is_power_of_2(align));
  4177. for (last_area = 0, area = 0; area < nr_vms; area++) {
  4178. start = offsets[area];
  4179. end = start + sizes[area];
  4180. /* is everything aligned properly? */
  4181. BUG_ON(!IS_ALIGNED(offsets[area], align));
  4182. BUG_ON(!IS_ALIGNED(sizes[area], align));
  4183. /* detect the area with the highest address */
  4184. if (start > offsets[last_area])
  4185. last_area = area;
  4186. for (area2 = area + 1; area2 < nr_vms; area2++) {
  4187. unsigned long start2 = offsets[area2];
  4188. unsigned long end2 = start2 + sizes[area2];
  4189. BUG_ON(start2 < end && start < end2);
  4190. }
  4191. }
  4192. last_end = offsets[last_area] + sizes[last_area];
  4193. if (vmalloc_end - vmalloc_start < last_end) {
  4194. WARN_ON(true);
  4195. return NULL;
  4196. }
  4197. vms = kzalloc_objs(vms[0], nr_vms);
  4198. vas = kzalloc_objs(vas[0], nr_vms);
  4199. if (!vas || !vms)
  4200. goto err_free2;
  4201. for (area = 0; area < nr_vms; area++) {
  4202. vas[area] = kmem_cache_zalloc(vmap_area_cachep, GFP_KERNEL);
  4203. vms[area] = kzalloc_obj(struct vm_struct);
  4204. if (!vas[area] || !vms[area])
  4205. goto err_free;
  4206. }
  4207. retry:
  4208. spin_lock(&free_vmap_area_lock);
  4209. /* start scanning - we scan from the top, begin with the last area */
  4210. area = term_area = last_area;
  4211. start = offsets[area];
  4212. end = start + sizes[area];
  4213. va = pvm_find_va_enclose_addr(vmalloc_end);
  4214. base = pvm_determine_end_from_reverse(&va, align) - end;
  4215. while (true) {
  4216. /*
  4217. * base might have underflowed, add last_end before
  4218. * comparing.
  4219. */
  4220. if (base + last_end < vmalloc_start + last_end)
  4221. goto overflow;
  4222. /*
  4223. * Fitting base has not been found.
  4224. */
  4225. if (va == NULL)
  4226. goto overflow;
  4227. /*
  4228. * If required width exceeds current VA block, move
  4229. * base downwards and then recheck.
  4230. */
  4231. if (base + end > va->va_end) {
  4232. base = pvm_determine_end_from_reverse(&va, align) - end;
  4233. term_area = area;
  4234. continue;
  4235. }
  4236. /*
  4237. * If this VA does not fit, move base downwards and recheck.
  4238. */
  4239. if (base + start < va->va_start) {
  4240. va = node_to_va(rb_prev(&va->rb_node));
  4241. base = pvm_determine_end_from_reverse(&va, align) - end;
  4242. term_area = area;
  4243. continue;
  4244. }
  4245. /*
  4246. * This area fits, move on to the previous one. If
  4247. * the previous one is the terminal one, we're done.
  4248. */
  4249. area = (area + nr_vms - 1) % nr_vms;
  4250. if (area == term_area)
  4251. break;
  4252. start = offsets[area];
  4253. end = start + sizes[area];
  4254. va = pvm_find_va_enclose_addr(base + end);
  4255. }
  4256. /* we've found a fitting base, insert all va's */
  4257. for (area = 0; area < nr_vms; area++) {
  4258. int ret;
  4259. start = base + offsets[area];
  4260. size = sizes[area];
  4261. va = pvm_find_va_enclose_addr(start);
  4262. if (WARN_ON_ONCE(va == NULL))
  4263. /* It is a BUG(), but trigger recovery instead. */
  4264. goto recovery;
  4265. ret = va_clip(&free_vmap_area_root,
  4266. &free_vmap_area_list, va, start, size);
  4267. if (WARN_ON_ONCE(unlikely(ret)))
  4268. /* It is a BUG(), but trigger recovery instead. */
  4269. goto recovery;
  4270. /* Allocated area. */
  4271. va = vas[area];
  4272. va->va_start = start;
  4273. va->va_end = start + size;
  4274. }
  4275. spin_unlock(&free_vmap_area_lock);
  4276. /* populate the kasan shadow space */
  4277. for (area = 0; area < nr_vms; area++) {
  4278. if (kasan_populate_vmalloc(vas[area]->va_start, sizes[area], GFP_KERNEL))
  4279. goto err_free_shadow;
  4280. }
  4281. /* insert all vm's */
  4282. for (area = 0; area < nr_vms; area++) {
  4283. struct vmap_node *vn = addr_to_node(vas[area]->va_start);
  4284. spin_lock(&vn->busy.lock);
  4285. insert_vmap_area(vas[area], &vn->busy.root, &vn->busy.head);
  4286. setup_vmalloc_vm(vms[area], vas[area], VM_ALLOC,
  4287. pcpu_get_vm_areas);
  4288. spin_unlock(&vn->busy.lock);
  4289. }
  4290. /*
  4291. * Mark allocated areas as accessible. Do it now as a best-effort
  4292. * approach, as they can be mapped outside of vmalloc code.
  4293. * With hardware tag-based KASAN, marking is skipped for
  4294. * non-VM_ALLOC mappings, see __kasan_unpoison_vmalloc().
  4295. */
  4296. kasan_unpoison_vmap_areas(vms, nr_vms, KASAN_VMALLOC_PROT_NORMAL);
  4297. kfree(vas);
  4298. return vms;
  4299. recovery:
  4300. /*
  4301. * Remove previously allocated areas. There is no
  4302. * need in removing these areas from the busy tree,
  4303. * because they are inserted only on the final step
  4304. * and when pcpu_get_vm_areas() is success.
  4305. */
  4306. while (area--) {
  4307. orig_start = vas[area]->va_start;
  4308. orig_end = vas[area]->va_end;
  4309. va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
  4310. &free_vmap_area_list);
  4311. if (va)
  4312. kasan_release_vmalloc(orig_start, orig_end,
  4313. va->va_start, va->va_end,
  4314. KASAN_VMALLOC_PAGE_RANGE | KASAN_VMALLOC_TLB_FLUSH);
  4315. vas[area] = NULL;
  4316. }
  4317. overflow:
  4318. spin_unlock(&free_vmap_area_lock);
  4319. if (!purged) {
  4320. reclaim_and_purge_vmap_areas();
  4321. purged = true;
  4322. /* Before "retry", check if we recover. */
  4323. for (area = 0; area < nr_vms; area++) {
  4324. if (vas[area])
  4325. continue;
  4326. vas[area] = kmem_cache_zalloc(
  4327. vmap_area_cachep, GFP_KERNEL);
  4328. if (!vas[area])
  4329. goto err_free;
  4330. }
  4331. goto retry;
  4332. }
  4333. err_free:
  4334. for (area = 0; area < nr_vms; area++) {
  4335. if (vas[area])
  4336. kmem_cache_free(vmap_area_cachep, vas[area]);
  4337. kfree(vms[area]);
  4338. }
  4339. err_free2:
  4340. kfree(vas);
  4341. kfree(vms);
  4342. return NULL;
  4343. err_free_shadow:
  4344. spin_lock(&free_vmap_area_lock);
  4345. /*
  4346. * We release all the vmalloc shadows, even the ones for regions that
  4347. * hadn't been successfully added. This relies on kasan_release_vmalloc
  4348. * being able to tolerate this case.
  4349. */
  4350. for (area = 0; area < nr_vms; area++) {
  4351. orig_start = vas[area]->va_start;
  4352. orig_end = vas[area]->va_end;
  4353. va = merge_or_add_vmap_area_augment(vas[area], &free_vmap_area_root,
  4354. &free_vmap_area_list);
  4355. if (va)
  4356. kasan_release_vmalloc(orig_start, orig_end,
  4357. va->va_start, va->va_end,
  4358. KASAN_VMALLOC_PAGE_RANGE | KASAN_VMALLOC_TLB_FLUSH);
  4359. vas[area] = NULL;
  4360. kfree(vms[area]);
  4361. }
  4362. spin_unlock(&free_vmap_area_lock);
  4363. kfree(vas);
  4364. kfree(vms);
  4365. return NULL;
  4366. }
  4367. /**
  4368. * pcpu_free_vm_areas - free vmalloc areas for percpu allocator
  4369. * @vms: vm_struct pointer array returned by pcpu_get_vm_areas()
  4370. * @nr_vms: the number of allocated areas
  4371. *
  4372. * Free vm_structs and the array allocated by pcpu_get_vm_areas().
  4373. */
  4374. void pcpu_free_vm_areas(struct vm_struct **vms, int nr_vms)
  4375. {
  4376. int i;
  4377. for (i = 0; i < nr_vms; i++)
  4378. free_vm_area(vms[i]);
  4379. kfree(vms);
  4380. }
  4381. #endif /* CONFIG_SMP */
  4382. #ifdef CONFIG_PRINTK
  4383. bool vmalloc_dump_obj(void *object)
  4384. {
  4385. const void *caller;
  4386. struct vm_struct *vm;
  4387. struct vmap_area *va;
  4388. struct vmap_node *vn;
  4389. unsigned long addr;
  4390. unsigned int nr_pages;
  4391. addr = PAGE_ALIGN((unsigned long) object);
  4392. vn = addr_to_node(addr);
  4393. if (!spin_trylock(&vn->busy.lock))
  4394. return false;
  4395. va = __find_vmap_area(addr, &vn->busy.root);
  4396. if (!va || !va->vm) {
  4397. spin_unlock(&vn->busy.lock);
  4398. return false;
  4399. }
  4400. vm = va->vm;
  4401. addr = (unsigned long) vm->addr;
  4402. caller = vm->caller;
  4403. nr_pages = vm->nr_pages;
  4404. spin_unlock(&vn->busy.lock);
  4405. pr_cont(" %u-page vmalloc region starting at %#lx allocated at %pS\n",
  4406. nr_pages, addr, caller);
  4407. return true;
  4408. }
  4409. #endif
  4410. #ifdef CONFIG_PROC_FS
  4411. /*
  4412. * Print number of pages allocated on each memory node.
  4413. *
  4414. * This function can only be called if CONFIG_NUMA is enabled
  4415. * and VM_UNINITIALIZED bit in v->flags is disabled.
  4416. */
  4417. static void show_numa_info(struct seq_file *m, struct vm_struct *v,
  4418. unsigned int *counters)
  4419. {
  4420. unsigned int nr;
  4421. unsigned int step = 1U << vm_area_page_order(v);
  4422. if (!counters)
  4423. return;
  4424. memset(counters, 0, nr_node_ids * sizeof(unsigned int));
  4425. for (nr = 0; nr < v->nr_pages; nr += step)
  4426. counters[page_to_nid(v->pages[nr])] += step;
  4427. for_each_node_state(nr, N_HIGH_MEMORY)
  4428. if (counters[nr])
  4429. seq_printf(m, " N%u=%u", nr, counters[nr]);
  4430. }
  4431. static void show_purge_info(struct seq_file *m)
  4432. {
  4433. struct vmap_node *vn;
  4434. struct vmap_area *va;
  4435. for_each_vmap_node(vn) {
  4436. spin_lock(&vn->lazy.lock);
  4437. list_for_each_entry(va, &vn->lazy.head, list) {
  4438. seq_printf(m, "0x%pK-0x%pK %7ld unpurged vm_area\n",
  4439. (void *)va->va_start, (void *)va->va_end,
  4440. va_size(va));
  4441. }
  4442. spin_unlock(&vn->lazy.lock);
  4443. }
  4444. }
  4445. static int vmalloc_info_show(struct seq_file *m, void *p)
  4446. {
  4447. struct vmap_node *vn;
  4448. struct vmap_area *va;
  4449. struct vm_struct *v;
  4450. unsigned int *counters;
  4451. if (IS_ENABLED(CONFIG_NUMA))
  4452. counters = kmalloc_array(nr_node_ids, sizeof(unsigned int), GFP_KERNEL);
  4453. for_each_vmap_node(vn) {
  4454. spin_lock(&vn->busy.lock);
  4455. list_for_each_entry(va, &vn->busy.head, list) {
  4456. if (!va->vm) {
  4457. if (va->flags & VMAP_RAM)
  4458. seq_printf(m, "0x%pK-0x%pK %7ld vm_map_ram\n",
  4459. (void *)va->va_start, (void *)va->va_end,
  4460. va_size(va));
  4461. continue;
  4462. }
  4463. v = va->vm;
  4464. if (v->flags & VM_UNINITIALIZED)
  4465. continue;
  4466. /* Pair with smp_wmb() in clear_vm_uninitialized_flag() */
  4467. smp_rmb();
  4468. seq_printf(m, "0x%pK-0x%pK %7ld",
  4469. v->addr, v->addr + v->size, v->size);
  4470. if (v->caller)
  4471. seq_printf(m, " %pS", v->caller);
  4472. if (v->nr_pages)
  4473. seq_printf(m, " pages=%d", v->nr_pages);
  4474. if (v->phys_addr)
  4475. seq_printf(m, " phys=%pa", &v->phys_addr);
  4476. if (v->flags & VM_IOREMAP)
  4477. seq_puts(m, " ioremap");
  4478. if (v->flags & VM_SPARSE)
  4479. seq_puts(m, " sparse");
  4480. if (v->flags & VM_ALLOC)
  4481. seq_puts(m, " vmalloc");
  4482. if (v->flags & VM_MAP)
  4483. seq_puts(m, " vmap");
  4484. if (v->flags & VM_USERMAP)
  4485. seq_puts(m, " user");
  4486. if (v->flags & VM_DMA_COHERENT)
  4487. seq_puts(m, " dma-coherent");
  4488. if (is_vmalloc_addr(v->pages))
  4489. seq_puts(m, " vpages");
  4490. if (IS_ENABLED(CONFIG_NUMA))
  4491. show_numa_info(m, v, counters);
  4492. seq_putc(m, '\n');
  4493. }
  4494. spin_unlock(&vn->busy.lock);
  4495. }
  4496. /*
  4497. * As a final step, dump "unpurged" areas.
  4498. */
  4499. show_purge_info(m);
  4500. if (IS_ENABLED(CONFIG_NUMA))
  4501. kfree(counters);
  4502. return 0;
  4503. }
  4504. static int __init proc_vmalloc_init(void)
  4505. {
  4506. proc_create_single("vmallocinfo", 0400, NULL, vmalloc_info_show);
  4507. return 0;
  4508. }
  4509. module_init(proc_vmalloc_init);
  4510. #endif
  4511. static void __init vmap_init_free_space(void)
  4512. {
  4513. unsigned long vmap_start = 1;
  4514. const unsigned long vmap_end = ULONG_MAX;
  4515. struct vmap_area *free;
  4516. struct vm_struct *busy;
  4517. /*
  4518. * B F B B B F
  4519. * -|-----|.....|-----|-----|-----|.....|-
  4520. * | The KVA space |
  4521. * |<--------------------------------->|
  4522. */
  4523. for (busy = vmlist; busy; busy = busy->next) {
  4524. if ((unsigned long) busy->addr - vmap_start > 0) {
  4525. free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
  4526. if (!WARN_ON_ONCE(!free)) {
  4527. free->va_start = vmap_start;
  4528. free->va_end = (unsigned long) busy->addr;
  4529. insert_vmap_area_augment(free, NULL,
  4530. &free_vmap_area_root,
  4531. &free_vmap_area_list);
  4532. }
  4533. }
  4534. vmap_start = (unsigned long) busy->addr + busy->size;
  4535. }
  4536. if (vmap_end - vmap_start > 0) {
  4537. free = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
  4538. if (!WARN_ON_ONCE(!free)) {
  4539. free->va_start = vmap_start;
  4540. free->va_end = vmap_end;
  4541. insert_vmap_area_augment(free, NULL,
  4542. &free_vmap_area_root,
  4543. &free_vmap_area_list);
  4544. }
  4545. }
  4546. }
  4547. static void vmap_init_nodes(void)
  4548. {
  4549. struct vmap_node *vn;
  4550. int i;
  4551. #if BITS_PER_LONG == 64
  4552. /*
  4553. * A high threshold of max nodes is fixed and bound to 128,
  4554. * thus a scale factor is 1 for systems where number of cores
  4555. * are less or equal to specified threshold.
  4556. *
  4557. * As for NUMA-aware notes. For bigger systems, for example
  4558. * NUMA with multi-sockets, where we can end-up with thousands
  4559. * of cores in total, a "sub-numa-clustering" should be added.
  4560. *
  4561. * In this case a NUMA domain is considered as a single entity
  4562. * with dedicated sub-nodes in it which describe one group or
  4563. * set of cores. Therefore a per-domain purging is supposed to
  4564. * be added as well as a per-domain balancing.
  4565. */
  4566. int n = clamp_t(unsigned int, num_possible_cpus(), 1, 128);
  4567. if (n > 1) {
  4568. vn = kmalloc_objs(*vn, n, GFP_NOWAIT);
  4569. if (vn) {
  4570. /* Node partition is 16 pages. */
  4571. vmap_zone_size = (1 << 4) * PAGE_SIZE;
  4572. nr_vmap_nodes = n;
  4573. vmap_nodes = vn;
  4574. } else {
  4575. pr_err("Failed to allocate an array. Disable a node layer\n");
  4576. }
  4577. }
  4578. #endif
  4579. for_each_vmap_node(vn) {
  4580. vn->busy.root = RB_ROOT;
  4581. INIT_LIST_HEAD(&vn->busy.head);
  4582. spin_lock_init(&vn->busy.lock);
  4583. vn->lazy.root = RB_ROOT;
  4584. INIT_LIST_HEAD(&vn->lazy.head);
  4585. spin_lock_init(&vn->lazy.lock);
  4586. for (i = 0; i < MAX_VA_SIZE_PAGES; i++) {
  4587. INIT_LIST_HEAD(&vn->pool[i].head);
  4588. WRITE_ONCE(vn->pool[i].len, 0);
  4589. }
  4590. spin_lock_init(&vn->pool_lock);
  4591. }
  4592. }
  4593. static unsigned long
  4594. vmap_node_shrink_count(struct shrinker *shrink, struct shrink_control *sc)
  4595. {
  4596. unsigned long count = 0;
  4597. struct vmap_node *vn;
  4598. int i;
  4599. for_each_vmap_node(vn) {
  4600. for (i = 0; i < MAX_VA_SIZE_PAGES; i++)
  4601. count += READ_ONCE(vn->pool[i].len);
  4602. }
  4603. return count ? count : SHRINK_EMPTY;
  4604. }
  4605. static unsigned long
  4606. vmap_node_shrink_scan(struct shrinker *shrink, struct shrink_control *sc)
  4607. {
  4608. struct vmap_node *vn;
  4609. for_each_vmap_node(vn)
  4610. decay_va_pool_node(vn, true);
  4611. return SHRINK_STOP;
  4612. }
  4613. void __init vmalloc_init(void)
  4614. {
  4615. struct shrinker *vmap_node_shrinker;
  4616. struct vmap_area *va;
  4617. struct vmap_node *vn;
  4618. struct vm_struct *tmp;
  4619. int i;
  4620. /*
  4621. * Create the cache for vmap_area objects.
  4622. */
  4623. vmap_area_cachep = KMEM_CACHE(vmap_area, SLAB_PANIC);
  4624. for_each_possible_cpu(i) {
  4625. struct vmap_block_queue *vbq;
  4626. struct vfree_deferred *p;
  4627. vbq = &per_cpu(vmap_block_queue, i);
  4628. spin_lock_init(&vbq->lock);
  4629. INIT_LIST_HEAD(&vbq->free);
  4630. p = &per_cpu(vfree_deferred, i);
  4631. init_llist_head(&p->list);
  4632. INIT_WORK(&p->wq, delayed_vfree_work);
  4633. xa_init(&vbq->vmap_blocks);
  4634. }
  4635. /*
  4636. * Setup nodes before importing vmlist.
  4637. */
  4638. vmap_init_nodes();
  4639. /* Import existing vmlist entries. */
  4640. for (tmp = vmlist; tmp; tmp = tmp->next) {
  4641. va = kmem_cache_zalloc(vmap_area_cachep, GFP_NOWAIT);
  4642. if (WARN_ON_ONCE(!va))
  4643. continue;
  4644. va->va_start = (unsigned long)tmp->addr;
  4645. va->va_end = va->va_start + tmp->size;
  4646. va->vm = tmp;
  4647. vn = addr_to_node(va->va_start);
  4648. insert_vmap_area(va, &vn->busy.root, &vn->busy.head);
  4649. }
  4650. /*
  4651. * Now we can initialize a free vmap space.
  4652. */
  4653. vmap_init_free_space();
  4654. vmap_initialized = true;
  4655. vmap_node_shrinker = shrinker_alloc(0, "vmap-node");
  4656. if (!vmap_node_shrinker) {
  4657. pr_err("Failed to allocate vmap-node shrinker!\n");
  4658. return;
  4659. }
  4660. vmap_node_shrinker->count_objects = vmap_node_shrink_count;
  4661. vmap_node_shrinker->scan_objects = vmap_node_shrink_scan;
  4662. shrinker_register(vmap_node_shrinker);
  4663. }