vmalloc.c 134 KB

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