k_page_table.cpp 141 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419
  1. // SPDX-FileCopyrightText: Copyright 2020 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "common/alignment.h"
  4. #include "common/assert.h"
  5. #include "common/literals.h"
  6. #include "common/scope_exit.h"
  7. #include "core/core.h"
  8. #include "core/hle/kernel/k_address_space_info.h"
  9. #include "core/hle/kernel/k_memory_block.h"
  10. #include "core/hle/kernel/k_memory_block_manager.h"
  11. #include "core/hle/kernel/k_page_group.h"
  12. #include "core/hle/kernel/k_page_table.h"
  13. #include "core/hle/kernel/k_process.h"
  14. #include "core/hle/kernel/k_resource_limit.h"
  15. #include "core/hle/kernel/k_scoped_resource_reservation.h"
  16. #include "core/hle/kernel/k_system_control.h"
  17. #include "core/hle/kernel/k_system_resource.h"
  18. #include "core/hle/kernel/kernel.h"
  19. #include "core/hle/kernel/svc_results.h"
  20. #include "core/memory.h"
  21. namespace Kernel {
  22. namespace {
  23. class KScopedLightLockPair {
  24. YUZU_NON_COPYABLE(KScopedLightLockPair);
  25. YUZU_NON_MOVEABLE(KScopedLightLockPair);
  26. private:
  27. KLightLock* m_lower;
  28. KLightLock* m_upper;
  29. public:
  30. KScopedLightLockPair(KLightLock& lhs, KLightLock& rhs) {
  31. // Ensure our locks are in a consistent order.
  32. if (std::addressof(lhs) <= std::addressof(rhs)) {
  33. m_lower = std::addressof(lhs);
  34. m_upper = std::addressof(rhs);
  35. } else {
  36. m_lower = std::addressof(rhs);
  37. m_upper = std::addressof(lhs);
  38. }
  39. // Acquire both locks.
  40. m_lower->Lock();
  41. if (m_lower != m_upper) {
  42. m_upper->Lock();
  43. }
  44. }
  45. ~KScopedLightLockPair() {
  46. // Unlock the upper lock.
  47. if (m_upper != nullptr && m_upper != m_lower) {
  48. m_upper->Unlock();
  49. }
  50. // Unlock the lower lock.
  51. if (m_lower != nullptr) {
  52. m_lower->Unlock();
  53. }
  54. }
  55. public:
  56. // Utility.
  57. void TryUnlockHalf(KLightLock& lock) {
  58. // Only allow unlocking if the lock is half the pair.
  59. if (m_lower != m_upper) {
  60. // We want to be sure the lock is one we own.
  61. if (m_lower == std::addressof(lock)) {
  62. lock.Unlock();
  63. m_lower = nullptr;
  64. } else if (m_upper == std::addressof(lock)) {
  65. lock.Unlock();
  66. m_upper = nullptr;
  67. }
  68. }
  69. }
  70. };
  71. using namespace Common::Literals;
  72. constexpr size_t GetAddressSpaceWidthFromType(FileSys::ProgramAddressSpaceType as_type) {
  73. switch (as_type) {
  74. case FileSys::ProgramAddressSpaceType::Is32Bit:
  75. case FileSys::ProgramAddressSpaceType::Is32BitNoMap:
  76. return 32;
  77. case FileSys::ProgramAddressSpaceType::Is36Bit:
  78. return 36;
  79. case FileSys::ProgramAddressSpaceType::Is39Bit:
  80. return 39;
  81. default:
  82. ASSERT(false);
  83. return {};
  84. }
  85. }
  86. } // namespace
  87. KPageTable::KPageTable(Core::System& system_)
  88. : m_general_lock{system_.Kernel()},
  89. m_map_physical_memory_lock{system_.Kernel()}, m_system{system_}, m_kernel{system_.Kernel()} {}
  90. KPageTable::~KPageTable() = default;
  91. Result KPageTable::InitializeForProcess(FileSys::ProgramAddressSpaceType as_type, bool enable_aslr,
  92. bool enable_das_merge, bool from_back,
  93. KMemoryManager::Pool pool, VAddr code_addr,
  94. size_t code_size, KSystemResource* system_resource,
  95. KResourceLimit* resource_limit) {
  96. const auto GetSpaceStart = [this](KAddressSpaceInfo::Type type) {
  97. return KAddressSpaceInfo::GetAddressSpaceStart(m_address_space_width, type);
  98. };
  99. const auto GetSpaceSize = [this](KAddressSpaceInfo::Type type) {
  100. return KAddressSpaceInfo::GetAddressSpaceSize(m_address_space_width, type);
  101. };
  102. // Set our width and heap/alias sizes
  103. m_address_space_width = GetAddressSpaceWidthFromType(as_type);
  104. const VAddr start = 0;
  105. const VAddr end{1ULL << m_address_space_width};
  106. size_t alias_region_size{GetSpaceSize(KAddressSpaceInfo::Type::Alias)};
  107. size_t heap_region_size{GetSpaceSize(KAddressSpaceInfo::Type::Heap)};
  108. ASSERT(code_addr < code_addr + code_size);
  109. ASSERT(code_addr + code_size - 1 <= end - 1);
  110. // Adjust heap/alias size if we don't have an alias region
  111. if (as_type == FileSys::ProgramAddressSpaceType::Is32BitNoMap) {
  112. heap_region_size += alias_region_size;
  113. alias_region_size = 0;
  114. }
  115. // Set code regions and determine remaining
  116. constexpr size_t RegionAlignment{2_MiB};
  117. VAddr process_code_start{};
  118. VAddr process_code_end{};
  119. size_t stack_region_size{};
  120. size_t kernel_map_region_size{};
  121. if (m_address_space_width == 39) {
  122. alias_region_size = GetSpaceSize(KAddressSpaceInfo::Type::Alias);
  123. heap_region_size = GetSpaceSize(KAddressSpaceInfo::Type::Heap);
  124. stack_region_size = GetSpaceSize(KAddressSpaceInfo::Type::Stack);
  125. kernel_map_region_size = GetSpaceSize(KAddressSpaceInfo::Type::MapSmall);
  126. m_code_region_start = GetSpaceStart(KAddressSpaceInfo::Type::Map39Bit);
  127. m_code_region_end = m_code_region_start + GetSpaceSize(KAddressSpaceInfo::Type::Map39Bit);
  128. m_alias_code_region_start = m_code_region_start;
  129. m_alias_code_region_end = m_code_region_end;
  130. process_code_start = Common::AlignDown(code_addr, RegionAlignment);
  131. process_code_end = Common::AlignUp(code_addr + code_size, RegionAlignment);
  132. } else {
  133. stack_region_size = 0;
  134. kernel_map_region_size = 0;
  135. m_code_region_start = GetSpaceStart(KAddressSpaceInfo::Type::MapSmall);
  136. m_code_region_end = m_code_region_start + GetSpaceSize(KAddressSpaceInfo::Type::MapSmall);
  137. m_stack_region_start = m_code_region_start;
  138. m_alias_code_region_start = m_code_region_start;
  139. m_alias_code_region_end = GetSpaceStart(KAddressSpaceInfo::Type::MapLarge) +
  140. GetSpaceSize(KAddressSpaceInfo::Type::MapLarge);
  141. m_stack_region_end = m_code_region_end;
  142. m_kernel_map_region_start = m_code_region_start;
  143. m_kernel_map_region_end = m_code_region_end;
  144. process_code_start = m_code_region_start;
  145. process_code_end = m_code_region_end;
  146. }
  147. // Set other basic fields
  148. m_enable_aslr = enable_aslr;
  149. m_enable_device_address_space_merge = enable_das_merge;
  150. m_address_space_start = start;
  151. m_address_space_end = end;
  152. m_is_kernel = false;
  153. m_memory_block_slab_manager = system_resource->GetMemoryBlockSlabManagerPointer();
  154. m_block_info_manager = system_resource->GetBlockInfoManagerPointer();
  155. m_resource_limit = resource_limit;
  156. // Determine the region we can place our undetermineds in
  157. VAddr alloc_start{};
  158. size_t alloc_size{};
  159. if ((process_code_start - m_code_region_start) >= (end - process_code_end)) {
  160. alloc_start = m_code_region_start;
  161. alloc_size = process_code_start - m_code_region_start;
  162. } else {
  163. alloc_start = process_code_end;
  164. alloc_size = end - process_code_end;
  165. }
  166. const size_t needed_size =
  167. (alias_region_size + heap_region_size + stack_region_size + kernel_map_region_size);
  168. R_UNLESS(alloc_size >= needed_size, ResultOutOfMemory);
  169. const size_t remaining_size{alloc_size - needed_size};
  170. // Determine random placements for each region
  171. size_t alias_rnd{}, heap_rnd{}, stack_rnd{}, kmap_rnd{};
  172. if (enable_aslr) {
  173. alias_rnd = KSystemControl::GenerateRandomRange(0, remaining_size / RegionAlignment) *
  174. RegionAlignment;
  175. heap_rnd = KSystemControl::GenerateRandomRange(0, remaining_size / RegionAlignment) *
  176. RegionAlignment;
  177. stack_rnd = KSystemControl::GenerateRandomRange(0, remaining_size / RegionAlignment) *
  178. RegionAlignment;
  179. kmap_rnd = KSystemControl::GenerateRandomRange(0, remaining_size / RegionAlignment) *
  180. RegionAlignment;
  181. }
  182. // Setup heap and alias regions
  183. m_alias_region_start = alloc_start + alias_rnd;
  184. m_alias_region_end = m_alias_region_start + alias_region_size;
  185. m_heap_region_start = alloc_start + heap_rnd;
  186. m_heap_region_end = m_heap_region_start + heap_region_size;
  187. if (alias_rnd <= heap_rnd) {
  188. m_heap_region_start += alias_region_size;
  189. m_heap_region_end += alias_region_size;
  190. } else {
  191. m_alias_region_start += heap_region_size;
  192. m_alias_region_end += heap_region_size;
  193. }
  194. // Setup stack region
  195. if (stack_region_size) {
  196. m_stack_region_start = alloc_start + stack_rnd;
  197. m_stack_region_end = m_stack_region_start + stack_region_size;
  198. if (alias_rnd < stack_rnd) {
  199. m_stack_region_start += alias_region_size;
  200. m_stack_region_end += alias_region_size;
  201. } else {
  202. m_alias_region_start += stack_region_size;
  203. m_alias_region_end += stack_region_size;
  204. }
  205. if (heap_rnd < stack_rnd) {
  206. m_stack_region_start += heap_region_size;
  207. m_stack_region_end += heap_region_size;
  208. } else {
  209. m_heap_region_start += stack_region_size;
  210. m_heap_region_end += stack_region_size;
  211. }
  212. }
  213. // Setup kernel map region
  214. if (kernel_map_region_size) {
  215. m_kernel_map_region_start = alloc_start + kmap_rnd;
  216. m_kernel_map_region_end = m_kernel_map_region_start + kernel_map_region_size;
  217. if (alias_rnd < kmap_rnd) {
  218. m_kernel_map_region_start += alias_region_size;
  219. m_kernel_map_region_end += alias_region_size;
  220. } else {
  221. m_alias_region_start += kernel_map_region_size;
  222. m_alias_region_end += kernel_map_region_size;
  223. }
  224. if (heap_rnd < kmap_rnd) {
  225. m_kernel_map_region_start += heap_region_size;
  226. m_kernel_map_region_end += heap_region_size;
  227. } else {
  228. m_heap_region_start += kernel_map_region_size;
  229. m_heap_region_end += kernel_map_region_size;
  230. }
  231. if (stack_region_size) {
  232. if (stack_rnd < kmap_rnd) {
  233. m_kernel_map_region_start += stack_region_size;
  234. m_kernel_map_region_end += stack_region_size;
  235. } else {
  236. m_stack_region_start += kernel_map_region_size;
  237. m_stack_region_end += kernel_map_region_size;
  238. }
  239. }
  240. }
  241. // Set heap and fill members.
  242. m_current_heap_end = m_heap_region_start;
  243. m_max_heap_size = 0;
  244. m_mapped_physical_memory_size = 0;
  245. m_mapped_unsafe_physical_memory = 0;
  246. m_mapped_insecure_memory = 0;
  247. m_mapped_ipc_server_memory = 0;
  248. m_heap_fill_value = 0;
  249. m_ipc_fill_value = 0;
  250. m_stack_fill_value = 0;
  251. // Set allocation option.
  252. m_allocate_option =
  253. KMemoryManager::EncodeOption(pool, from_back ? KMemoryManager::Direction::FromBack
  254. : KMemoryManager::Direction::FromFront);
  255. // Ensure that we regions inside our address space
  256. auto IsInAddressSpace = [&](VAddr addr) {
  257. return m_address_space_start <= addr && addr <= m_address_space_end;
  258. };
  259. ASSERT(IsInAddressSpace(m_alias_region_start));
  260. ASSERT(IsInAddressSpace(m_alias_region_end));
  261. ASSERT(IsInAddressSpace(m_heap_region_start));
  262. ASSERT(IsInAddressSpace(m_heap_region_end));
  263. ASSERT(IsInAddressSpace(m_stack_region_start));
  264. ASSERT(IsInAddressSpace(m_stack_region_end));
  265. ASSERT(IsInAddressSpace(m_kernel_map_region_start));
  266. ASSERT(IsInAddressSpace(m_kernel_map_region_end));
  267. // Ensure that we selected regions that don't overlap
  268. const VAddr alias_start{m_alias_region_start};
  269. const VAddr alias_last{m_alias_region_end - 1};
  270. const VAddr heap_start{m_heap_region_start};
  271. const VAddr heap_last{m_heap_region_end - 1};
  272. const VAddr stack_start{m_stack_region_start};
  273. const VAddr stack_last{m_stack_region_end - 1};
  274. const VAddr kmap_start{m_kernel_map_region_start};
  275. const VAddr kmap_last{m_kernel_map_region_end - 1};
  276. ASSERT(alias_last < heap_start || heap_last < alias_start);
  277. ASSERT(alias_last < stack_start || stack_last < alias_start);
  278. ASSERT(alias_last < kmap_start || kmap_last < alias_start);
  279. ASSERT(heap_last < stack_start || stack_last < heap_start);
  280. ASSERT(heap_last < kmap_start || kmap_last < heap_start);
  281. m_current_heap_end = m_heap_region_start;
  282. m_max_heap_size = 0;
  283. m_mapped_physical_memory_size = 0;
  284. m_memory_pool = pool;
  285. m_page_table_impl = std::make_unique<Common::PageTable>();
  286. m_page_table_impl->Resize(m_address_space_width, PageBits);
  287. // Initialize our memory block manager.
  288. R_RETURN(m_memory_block_manager.Initialize(m_address_space_start, m_address_space_end,
  289. m_memory_block_slab_manager));
  290. }
  291. void KPageTable::Finalize() {
  292. // Finalize memory blocks.
  293. m_memory_block_manager.Finalize(m_memory_block_slab_manager, [&](VAddr addr, u64 size) {
  294. m_system.Memory().UnmapRegion(*m_page_table_impl, addr, size);
  295. });
  296. // Release any insecure mapped memory.
  297. if (m_mapped_insecure_memory) {
  298. UNIMPLEMENTED();
  299. }
  300. // Release any ipc server memory.
  301. if (m_mapped_ipc_server_memory) {
  302. UNIMPLEMENTED();
  303. }
  304. // Close the backing page table, as the destructor is not called for guest objects.
  305. m_page_table_impl.reset();
  306. }
  307. Result KPageTable::MapProcessCode(VAddr addr, size_t num_pages, KMemoryState state,
  308. KMemoryPermission perm) {
  309. const u64 size{num_pages * PageSize};
  310. // Validate the mapping request.
  311. R_UNLESS(this->CanContain(addr, size, state), ResultInvalidCurrentMemory);
  312. // Lock the table.
  313. KScopedLightLock lk(m_general_lock);
  314. // Verify that the destination memory is unmapped.
  315. R_TRY(this->CheckMemoryState(addr, size, KMemoryState::All, KMemoryState::Free,
  316. KMemoryPermission::None, KMemoryPermission::None,
  317. KMemoryAttribute::None, KMemoryAttribute::None));
  318. // Create an update allocator.
  319. Result allocator_result{ResultSuccess};
  320. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  321. m_memory_block_slab_manager);
  322. // Allocate and open.
  323. KPageGroup pg{m_kernel, m_block_info_manager};
  324. R_TRY(m_system.Kernel().MemoryManager().AllocateAndOpen(
  325. &pg, num_pages,
  326. KMemoryManager::EncodeOption(KMemoryManager::Pool::Application, m_allocation_option)));
  327. R_TRY(Operate(addr, num_pages, pg, OperationType::MapGroup));
  328. // Update the blocks.
  329. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, state, perm,
  330. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  331. KMemoryBlockDisableMergeAttribute::None);
  332. R_SUCCEED();
  333. }
  334. Result KPageTable::MapCodeMemory(VAddr dst_address, VAddr src_address, size_t size) {
  335. // Validate the mapping request.
  336. R_UNLESS(this->CanContain(dst_address, size, KMemoryState::AliasCode),
  337. ResultInvalidMemoryRegion);
  338. // Lock the table.
  339. KScopedLightLock lk(m_general_lock);
  340. // Verify that the source memory is normal heap.
  341. KMemoryState src_state{};
  342. KMemoryPermission src_perm{};
  343. size_t num_src_allocator_blocks{};
  344. R_TRY(this->CheckMemoryState(&src_state, &src_perm, nullptr, &num_src_allocator_blocks,
  345. src_address, size, KMemoryState::All, KMemoryState::Normal,
  346. KMemoryPermission::All, KMemoryPermission::UserReadWrite,
  347. KMemoryAttribute::All, KMemoryAttribute::None));
  348. // Verify that the destination memory is unmapped.
  349. size_t num_dst_allocator_blocks{};
  350. R_TRY(this->CheckMemoryState(&num_dst_allocator_blocks, dst_address, size, KMemoryState::All,
  351. KMemoryState::Free, KMemoryPermission::None,
  352. KMemoryPermission::None, KMemoryAttribute::None,
  353. KMemoryAttribute::None));
  354. // Create an update allocator for the source.
  355. Result src_allocator_result{ResultSuccess};
  356. KMemoryBlockManagerUpdateAllocator src_allocator(std::addressof(src_allocator_result),
  357. m_memory_block_slab_manager,
  358. num_src_allocator_blocks);
  359. R_TRY(src_allocator_result);
  360. // Create an update allocator for the destination.
  361. Result dst_allocator_result{ResultSuccess};
  362. KMemoryBlockManagerUpdateAllocator dst_allocator(std::addressof(dst_allocator_result),
  363. m_memory_block_slab_manager,
  364. num_dst_allocator_blocks);
  365. R_TRY(dst_allocator_result);
  366. // Map the code memory.
  367. {
  368. // Determine the number of pages being operated on.
  369. const size_t num_pages = size / PageSize;
  370. // Create page groups for the memory being mapped.
  371. KPageGroup pg{m_kernel, m_block_info_manager};
  372. AddRegionToPages(src_address, num_pages, pg);
  373. // We're going to perform an update, so create a helper.
  374. KScopedPageTableUpdater updater(this);
  375. // Reprotect the source as kernel-read/not mapped.
  376. const auto new_perm = static_cast<KMemoryPermission>(KMemoryPermission::KernelRead |
  377. KMemoryPermission::NotMapped);
  378. R_TRY(Operate(src_address, num_pages, new_perm, OperationType::ChangePermissions));
  379. // Ensure that we unprotect the source pages on failure.
  380. auto unprot_guard = SCOPE_GUARD({
  381. ASSERT(this->Operate(src_address, num_pages, src_perm, OperationType::ChangePermissions)
  382. .IsSuccess());
  383. });
  384. // Map the alias pages.
  385. const KPageProperties dst_properties = {new_perm, false, false,
  386. DisableMergeAttribute::DisableHead};
  387. R_TRY(
  388. this->MapPageGroupImpl(updater.GetPageList(), dst_address, pg, dst_properties, false));
  389. // We successfully mapped the alias pages, so we don't need to unprotect the src pages on
  390. // failure.
  391. unprot_guard.Cancel();
  392. // Apply the memory block updates.
  393. m_memory_block_manager.Update(std::addressof(src_allocator), src_address, num_pages,
  394. src_state, new_perm, KMemoryAttribute::Locked,
  395. KMemoryBlockDisableMergeAttribute::Locked,
  396. KMemoryBlockDisableMergeAttribute::None);
  397. m_memory_block_manager.Update(std::addressof(dst_allocator), dst_address, num_pages,
  398. KMemoryState::AliasCode, new_perm, KMemoryAttribute::None,
  399. KMemoryBlockDisableMergeAttribute::Normal,
  400. KMemoryBlockDisableMergeAttribute::None);
  401. }
  402. R_SUCCEED();
  403. }
  404. Result KPageTable::UnmapCodeMemory(VAddr dst_address, VAddr src_address, size_t size,
  405. ICacheInvalidationStrategy icache_invalidation_strategy) {
  406. // Validate the mapping request.
  407. R_UNLESS(this->CanContain(dst_address, size, KMemoryState::AliasCode),
  408. ResultInvalidMemoryRegion);
  409. // Lock the table.
  410. KScopedLightLock lk(m_general_lock);
  411. // Verify that the source memory is locked normal heap.
  412. size_t num_src_allocator_blocks{};
  413. R_TRY(this->CheckMemoryState(std::addressof(num_src_allocator_blocks), src_address, size,
  414. KMemoryState::All, KMemoryState::Normal, KMemoryPermission::None,
  415. KMemoryPermission::None, KMemoryAttribute::All,
  416. KMemoryAttribute::Locked));
  417. // Verify that the destination memory is aliasable code.
  418. size_t num_dst_allocator_blocks{};
  419. R_TRY(this->CheckMemoryStateContiguous(
  420. std::addressof(num_dst_allocator_blocks), dst_address, size, KMemoryState::FlagCanCodeAlias,
  421. KMemoryState::FlagCanCodeAlias, KMemoryPermission::None, KMemoryPermission::None,
  422. KMemoryAttribute::All, KMemoryAttribute::None));
  423. // Determine whether any pages being unmapped are code.
  424. bool any_code_pages = false;
  425. {
  426. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(dst_address);
  427. while (true) {
  428. // Get the memory info.
  429. const KMemoryInfo info = it->GetMemoryInfo();
  430. // Check if the memory has code flag.
  431. if ((info.GetState() & KMemoryState::FlagCode) != KMemoryState::None) {
  432. any_code_pages = true;
  433. break;
  434. }
  435. // Check if we're done.
  436. if (dst_address + size - 1 <= info.GetLastAddress()) {
  437. break;
  438. }
  439. // Advance.
  440. ++it;
  441. }
  442. }
  443. // Ensure that we maintain the instruction cache.
  444. bool reprotected_pages = false;
  445. SCOPE_EXIT({
  446. if (reprotected_pages && any_code_pages) {
  447. if (icache_invalidation_strategy == ICacheInvalidationStrategy::InvalidateRange) {
  448. m_system.InvalidateCpuInstructionCacheRange(dst_address, size);
  449. } else {
  450. m_system.InvalidateCpuInstructionCaches();
  451. }
  452. }
  453. });
  454. // Unmap.
  455. {
  456. // Determine the number of pages being operated on.
  457. const size_t num_pages = size / PageSize;
  458. // Create an update allocator for the source.
  459. Result src_allocator_result{ResultSuccess};
  460. KMemoryBlockManagerUpdateAllocator src_allocator(std::addressof(src_allocator_result),
  461. m_memory_block_slab_manager,
  462. num_src_allocator_blocks);
  463. R_TRY(src_allocator_result);
  464. // Create an update allocator for the destination.
  465. Result dst_allocator_result{ResultSuccess};
  466. KMemoryBlockManagerUpdateAllocator dst_allocator(std::addressof(dst_allocator_result),
  467. m_memory_block_slab_manager,
  468. num_dst_allocator_blocks);
  469. R_TRY(dst_allocator_result);
  470. // Unmap the aliased copy of the pages.
  471. R_TRY(Operate(dst_address, num_pages, KMemoryPermission::None, OperationType::Unmap));
  472. // Try to set the permissions for the source pages back to what they should be.
  473. R_TRY(Operate(src_address, num_pages, KMemoryPermission::UserReadWrite,
  474. OperationType::ChangePermissions));
  475. // Apply the memory block updates.
  476. m_memory_block_manager.Update(
  477. std::addressof(dst_allocator), dst_address, num_pages, KMemoryState::None,
  478. KMemoryPermission::None, KMemoryAttribute::None,
  479. KMemoryBlockDisableMergeAttribute::None, KMemoryBlockDisableMergeAttribute::Normal);
  480. m_memory_block_manager.Update(
  481. std::addressof(src_allocator), src_address, num_pages, KMemoryState::Normal,
  482. KMemoryPermission::UserReadWrite, KMemoryAttribute::None,
  483. KMemoryBlockDisableMergeAttribute::None, KMemoryBlockDisableMergeAttribute::Locked);
  484. // Note that we reprotected pages.
  485. reprotected_pages = true;
  486. }
  487. R_SUCCEED();
  488. }
  489. VAddr KPageTable::FindFreeArea(VAddr region_start, size_t region_num_pages, size_t num_pages,
  490. size_t alignment, size_t offset, size_t guard_pages) {
  491. VAddr address = 0;
  492. if (num_pages <= region_num_pages) {
  493. if (this->IsAslrEnabled()) {
  494. UNIMPLEMENTED();
  495. }
  496. // Find the first free area.
  497. if (address == 0) {
  498. address = m_memory_block_manager.FindFreeArea(region_start, region_num_pages, num_pages,
  499. alignment, offset, guard_pages);
  500. }
  501. }
  502. return address;
  503. }
  504. Result KPageTable::MakePageGroup(KPageGroup& pg, VAddr addr, size_t num_pages) {
  505. ASSERT(this->IsLockedByCurrentThread());
  506. const size_t size = num_pages * PageSize;
  507. // We're making a new group, not adding to an existing one.
  508. R_UNLESS(pg.empty(), ResultInvalidCurrentMemory);
  509. // Begin traversal.
  510. Common::PageTable::TraversalContext context;
  511. Common::PageTable::TraversalEntry next_entry;
  512. R_UNLESS(m_page_table_impl->BeginTraversal(next_entry, context, addr),
  513. ResultInvalidCurrentMemory);
  514. // Prepare tracking variables.
  515. PAddr cur_addr = next_entry.phys_addr;
  516. size_t cur_size = next_entry.block_size - (cur_addr & (next_entry.block_size - 1));
  517. size_t tot_size = cur_size;
  518. // Iterate, adding to group as we go.
  519. const auto& memory_layout = m_system.Kernel().MemoryLayout();
  520. while (tot_size < size) {
  521. R_UNLESS(m_page_table_impl->ContinueTraversal(next_entry, context),
  522. ResultInvalidCurrentMemory);
  523. if (next_entry.phys_addr != (cur_addr + cur_size)) {
  524. const size_t cur_pages = cur_size / PageSize;
  525. R_UNLESS(IsHeapPhysicalAddress(memory_layout, cur_addr), ResultInvalidCurrentMemory);
  526. R_TRY(pg.AddBlock(cur_addr, cur_pages));
  527. cur_addr = next_entry.phys_addr;
  528. cur_size = next_entry.block_size;
  529. } else {
  530. cur_size += next_entry.block_size;
  531. }
  532. tot_size += next_entry.block_size;
  533. }
  534. // Ensure we add the right amount for the last block.
  535. if (tot_size > size) {
  536. cur_size -= (tot_size - size);
  537. }
  538. // Add the last block.
  539. const size_t cur_pages = cur_size / PageSize;
  540. R_UNLESS(IsHeapPhysicalAddress(memory_layout, cur_addr), ResultInvalidCurrentMemory);
  541. R_TRY(pg.AddBlock(cur_addr, cur_pages));
  542. R_SUCCEED();
  543. }
  544. bool KPageTable::IsValidPageGroup(const KPageGroup& pg, VAddr addr, size_t num_pages) {
  545. ASSERT(this->IsLockedByCurrentThread());
  546. const size_t size = num_pages * PageSize;
  547. const auto& memory_layout = m_system.Kernel().MemoryLayout();
  548. // Empty groups are necessarily invalid.
  549. if (pg.empty()) {
  550. return false;
  551. }
  552. // We're going to validate that the group we'd expect is the group we see.
  553. auto cur_it = pg.begin();
  554. PAddr cur_block_address = cur_it->GetAddress();
  555. size_t cur_block_pages = cur_it->GetNumPages();
  556. auto UpdateCurrentIterator = [&]() {
  557. if (cur_block_pages == 0) {
  558. if ((++cur_it) == pg.end()) {
  559. return false;
  560. }
  561. cur_block_address = cur_it->GetAddress();
  562. cur_block_pages = cur_it->GetNumPages();
  563. }
  564. return true;
  565. };
  566. // Begin traversal.
  567. Common::PageTable::TraversalContext context;
  568. Common::PageTable::TraversalEntry next_entry;
  569. if (!m_page_table_impl->BeginTraversal(next_entry, context, addr)) {
  570. return false;
  571. }
  572. // Prepare tracking variables.
  573. PAddr cur_addr = next_entry.phys_addr;
  574. size_t cur_size = next_entry.block_size - (cur_addr & (next_entry.block_size - 1));
  575. size_t tot_size = cur_size;
  576. // Iterate, comparing expected to actual.
  577. while (tot_size < size) {
  578. if (!m_page_table_impl->ContinueTraversal(next_entry, context)) {
  579. return false;
  580. }
  581. if (next_entry.phys_addr != (cur_addr + cur_size)) {
  582. const size_t cur_pages = cur_size / PageSize;
  583. if (!IsHeapPhysicalAddress(memory_layout, cur_addr)) {
  584. return false;
  585. }
  586. if (!UpdateCurrentIterator()) {
  587. return false;
  588. }
  589. if (cur_block_address != cur_addr || cur_block_pages < cur_pages) {
  590. return false;
  591. }
  592. cur_block_address += cur_size;
  593. cur_block_pages -= cur_pages;
  594. cur_addr = next_entry.phys_addr;
  595. cur_size = next_entry.block_size;
  596. } else {
  597. cur_size += next_entry.block_size;
  598. }
  599. tot_size += next_entry.block_size;
  600. }
  601. // Ensure we compare the right amount for the last block.
  602. if (tot_size > size) {
  603. cur_size -= (tot_size - size);
  604. }
  605. if (!IsHeapPhysicalAddress(memory_layout, cur_addr)) {
  606. return false;
  607. }
  608. if (!UpdateCurrentIterator()) {
  609. return false;
  610. }
  611. return cur_block_address == cur_addr && cur_block_pages == (cur_size / PageSize);
  612. }
  613. Result KPageTable::UnmapProcessMemory(VAddr dst_addr, size_t size, KPageTable& src_page_table,
  614. VAddr src_addr) {
  615. // Acquire the table locks.
  616. KScopedLightLockPair lk(src_page_table.m_general_lock, m_general_lock);
  617. const size_t num_pages{size / PageSize};
  618. // Check that the memory is mapped in the destination process.
  619. size_t num_allocator_blocks;
  620. R_TRY(CheckMemoryState(&num_allocator_blocks, dst_addr, size, KMemoryState::All,
  621. KMemoryState::SharedCode, KMemoryPermission::UserReadWrite,
  622. KMemoryPermission::UserReadWrite, KMemoryAttribute::All,
  623. KMemoryAttribute::None));
  624. // Check that the memory is mapped in the source process.
  625. R_TRY(src_page_table.CheckMemoryState(src_addr, size, KMemoryState::FlagCanMapProcess,
  626. KMemoryState::FlagCanMapProcess, KMemoryPermission::None,
  627. KMemoryPermission::None, KMemoryAttribute::All,
  628. KMemoryAttribute::None));
  629. // Create an update allocator.
  630. Result allocator_result{ResultSuccess};
  631. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  632. m_memory_block_slab_manager, num_allocator_blocks);
  633. R_TRY(allocator_result);
  634. CASCADE_CODE(Operate(dst_addr, num_pages, KMemoryPermission::None, OperationType::Unmap));
  635. // Apply the memory block update.
  636. m_memory_block_manager.Update(std::addressof(allocator), dst_addr, num_pages,
  637. KMemoryState::Free, KMemoryPermission::None,
  638. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  639. KMemoryBlockDisableMergeAttribute::Normal);
  640. m_system.InvalidateCpuInstructionCaches();
  641. R_SUCCEED();
  642. }
  643. Result KPageTable::SetupForIpcClient(PageLinkedList* page_list, size_t* out_blocks_needed,
  644. VAddr address, size_t size, KMemoryPermission test_perm,
  645. KMemoryState dst_state) {
  646. // Validate pre-conditions.
  647. ASSERT(this->IsLockedByCurrentThread());
  648. ASSERT(test_perm == KMemoryPermission::UserReadWrite ||
  649. test_perm == KMemoryPermission::UserRead);
  650. // Check that the address is in range.
  651. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  652. // Get the source permission.
  653. const auto src_perm = (test_perm == KMemoryPermission::UserReadWrite)
  654. ? KMemoryPermission::KernelReadWrite | KMemoryPermission::NotMapped
  655. : KMemoryPermission::UserRead;
  656. // Get aligned extents.
  657. const VAddr aligned_src_start = Common::AlignDown((address), PageSize);
  658. const VAddr aligned_src_end = Common::AlignUp((address) + size, PageSize);
  659. const VAddr mapping_src_start = Common::AlignUp((address), PageSize);
  660. const VAddr mapping_src_end = Common::AlignDown((address) + size, PageSize);
  661. const auto aligned_src_last = (aligned_src_end)-1;
  662. const auto mapping_src_last = (mapping_src_end)-1;
  663. // Get the test state and attribute mask.
  664. KMemoryState test_state;
  665. KMemoryAttribute test_attr_mask;
  666. switch (dst_state) {
  667. case KMemoryState::Ipc:
  668. test_state = KMemoryState::FlagCanUseIpc;
  669. test_attr_mask =
  670. KMemoryAttribute::Uncached | KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked;
  671. break;
  672. case KMemoryState::NonSecureIpc:
  673. test_state = KMemoryState::FlagCanUseNonSecureIpc;
  674. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  675. break;
  676. case KMemoryState::NonDeviceIpc:
  677. test_state = KMemoryState::FlagCanUseNonDeviceIpc;
  678. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  679. break;
  680. default:
  681. R_THROW(ResultInvalidCombination);
  682. }
  683. // Ensure that on failure, we roll back appropriately.
  684. size_t mapped_size = 0;
  685. ON_RESULT_FAILURE {
  686. if (mapped_size > 0) {
  687. this->CleanupForIpcClientOnServerSetupFailure(page_list, mapping_src_start, mapped_size,
  688. src_perm);
  689. }
  690. };
  691. size_t blocks_needed = 0;
  692. // Iterate, mapping as needed.
  693. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(aligned_src_start);
  694. while (true) {
  695. const KMemoryInfo info = it->GetMemoryInfo();
  696. // Validate the current block.
  697. R_TRY(this->CheckMemoryState(info, test_state, test_state, test_perm, test_perm,
  698. test_attr_mask, KMemoryAttribute::None));
  699. if (mapping_src_start < mapping_src_end && (mapping_src_start) < info.GetEndAddress() &&
  700. info.GetAddress() < (mapping_src_end)) {
  701. const auto cur_start =
  702. info.GetAddress() >= (mapping_src_start) ? info.GetAddress() : (mapping_src_start);
  703. const auto cur_end = mapping_src_last >= info.GetLastAddress() ? info.GetEndAddress()
  704. : (mapping_src_end);
  705. const size_t cur_size = cur_end - cur_start;
  706. if (info.GetAddress() < (mapping_src_start)) {
  707. ++blocks_needed;
  708. }
  709. if (mapping_src_last < info.GetLastAddress()) {
  710. ++blocks_needed;
  711. }
  712. // Set the permissions on the block, if we need to.
  713. if ((info.GetPermission() & KMemoryPermission::IpcLockChangeMask) != src_perm) {
  714. R_TRY(Operate(cur_start, cur_size / PageSize, src_perm,
  715. OperationType::ChangePermissions));
  716. }
  717. // Note that we mapped this part.
  718. mapped_size += cur_size;
  719. }
  720. // If the block is at the end, we're done.
  721. if (aligned_src_last <= info.GetLastAddress()) {
  722. break;
  723. }
  724. // Advance.
  725. ++it;
  726. ASSERT(it != m_memory_block_manager.end());
  727. }
  728. if (out_blocks_needed != nullptr) {
  729. ASSERT(blocks_needed <= KMemoryBlockManagerUpdateAllocator::MaxBlocks);
  730. *out_blocks_needed = blocks_needed;
  731. }
  732. R_SUCCEED();
  733. }
  734. Result KPageTable::SetupForIpcServer(VAddr* out_addr, size_t size, VAddr src_addr,
  735. KMemoryPermission test_perm, KMemoryState dst_state,
  736. KPageTable& src_page_table, bool send) {
  737. ASSERT(this->IsLockedByCurrentThread());
  738. ASSERT(src_page_table.IsLockedByCurrentThread());
  739. // Check that we can theoretically map.
  740. const VAddr region_start = m_alias_region_start;
  741. const size_t region_size = m_alias_region_end - m_alias_region_start;
  742. R_UNLESS(size < region_size, ResultOutOfAddressSpace);
  743. // Get aligned source extents.
  744. const VAddr src_start = src_addr;
  745. const VAddr src_end = src_addr + size;
  746. const VAddr aligned_src_start = Common::AlignDown((src_start), PageSize);
  747. const VAddr aligned_src_end = Common::AlignUp((src_start) + size, PageSize);
  748. const VAddr mapping_src_start = Common::AlignUp((src_start), PageSize);
  749. const VAddr mapping_src_end = Common::AlignDown((src_start) + size, PageSize);
  750. const size_t aligned_src_size = aligned_src_end - aligned_src_start;
  751. const size_t mapping_src_size =
  752. (mapping_src_start < mapping_src_end) ? (mapping_src_end - mapping_src_start) : 0;
  753. // Select a random address to map at.
  754. VAddr dst_addr =
  755. this->FindFreeArea(region_start, region_size / PageSize, aligned_src_size / PageSize,
  756. PageSize, 0, this->GetNumGuardPages());
  757. R_UNLESS(dst_addr != 0, ResultOutOfAddressSpace);
  758. // Check that we can perform the operation we're about to perform.
  759. ASSERT(this->CanContain(dst_addr, aligned_src_size, dst_state));
  760. // Create an update allocator.
  761. Result allocator_result;
  762. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  763. m_memory_block_slab_manager);
  764. R_TRY(allocator_result);
  765. // We're going to perform an update, so create a helper.
  766. KScopedPageTableUpdater updater(this);
  767. // Reserve space for any partial pages we allocate.
  768. const size_t unmapped_size = aligned_src_size - mapping_src_size;
  769. KScopedResourceReservation memory_reservation(
  770. m_resource_limit, LimitableResource::PhysicalMemoryMax, unmapped_size);
  771. R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
  772. // Ensure that we manage page references correctly.
  773. PAddr start_partial_page = 0;
  774. PAddr end_partial_page = 0;
  775. VAddr cur_mapped_addr = dst_addr;
  776. // If the partial pages are mapped, an extra reference will have been opened. Otherwise, they'll
  777. // free on scope exit.
  778. SCOPE_EXIT({
  779. if (start_partial_page != 0) {
  780. m_system.Kernel().MemoryManager().Close(start_partial_page, 1);
  781. }
  782. if (end_partial_page != 0) {
  783. m_system.Kernel().MemoryManager().Close(end_partial_page, 1);
  784. }
  785. });
  786. ON_RESULT_FAILURE {
  787. if (cur_mapped_addr != dst_addr) {
  788. ASSERT(Operate(dst_addr, (cur_mapped_addr - dst_addr) / PageSize,
  789. KMemoryPermission::None, OperationType::Unmap)
  790. .IsSuccess());
  791. }
  792. };
  793. // Allocate the start page as needed.
  794. if (aligned_src_start < mapping_src_start) {
  795. start_partial_page =
  796. m_system.Kernel().MemoryManager().AllocateAndOpenContinuous(1, 1, m_allocate_option);
  797. R_UNLESS(start_partial_page != 0, ResultOutOfMemory);
  798. }
  799. // Allocate the end page as needed.
  800. if (mapping_src_end < aligned_src_end &&
  801. (aligned_src_start < mapping_src_end || aligned_src_start == mapping_src_start)) {
  802. end_partial_page =
  803. m_system.Kernel().MemoryManager().AllocateAndOpenContinuous(1, 1, m_allocate_option);
  804. R_UNLESS(end_partial_page != 0, ResultOutOfMemory);
  805. }
  806. // Get the implementation.
  807. auto& src_impl = src_page_table.PageTableImpl();
  808. // Get the fill value for partial pages.
  809. const auto fill_val = m_ipc_fill_value;
  810. // Begin traversal.
  811. Common::PageTable::TraversalContext context;
  812. Common::PageTable::TraversalEntry next_entry;
  813. bool traverse_valid = src_impl.BeginTraversal(next_entry, context, aligned_src_start);
  814. ASSERT(traverse_valid);
  815. // Prepare tracking variables.
  816. PAddr cur_block_addr = next_entry.phys_addr;
  817. size_t cur_block_size =
  818. next_entry.block_size - ((cur_block_addr) & (next_entry.block_size - 1));
  819. size_t tot_block_size = cur_block_size;
  820. // Map the start page, if we have one.
  821. if (start_partial_page != 0) {
  822. // Ensure the page holds correct data.
  823. const VAddr start_partial_virt =
  824. GetHeapVirtualAddress(m_system.Kernel().MemoryLayout(), start_partial_page);
  825. if (send) {
  826. const size_t partial_offset = src_start - aligned_src_start;
  827. size_t copy_size, clear_size;
  828. if (src_end < mapping_src_start) {
  829. copy_size = size;
  830. clear_size = mapping_src_start - src_end;
  831. } else {
  832. copy_size = mapping_src_start - src_start;
  833. clear_size = 0;
  834. }
  835. std::memset(m_system.Memory().GetPointer<void>(start_partial_virt), fill_val,
  836. partial_offset);
  837. std::memcpy(
  838. m_system.Memory().GetPointer<void>(start_partial_virt + partial_offset),
  839. m_system.Memory().GetPointer<void>(
  840. GetHeapVirtualAddress(m_system.Kernel().MemoryLayout(), cur_block_addr) +
  841. partial_offset),
  842. copy_size);
  843. if (clear_size > 0) {
  844. std::memset(m_system.Memory().GetPointer<void>(start_partial_virt + partial_offset +
  845. copy_size),
  846. fill_val, clear_size);
  847. }
  848. } else {
  849. std::memset(m_system.Memory().GetPointer<void>(start_partial_virt), fill_val, PageSize);
  850. }
  851. // Map the page.
  852. R_TRY(Operate(cur_mapped_addr, 1, test_perm, OperationType::Map, start_partial_page));
  853. // Update tracking extents.
  854. cur_mapped_addr += PageSize;
  855. cur_block_addr += PageSize;
  856. cur_block_size -= PageSize;
  857. // If the block's size was one page, we may need to continue traversal.
  858. if (cur_block_size == 0 && aligned_src_size > PageSize) {
  859. traverse_valid = src_impl.ContinueTraversal(next_entry, context);
  860. ASSERT(traverse_valid);
  861. cur_block_addr = next_entry.phys_addr;
  862. cur_block_size = next_entry.block_size;
  863. tot_block_size += next_entry.block_size;
  864. }
  865. }
  866. // Map the remaining pages.
  867. while (aligned_src_start + tot_block_size < mapping_src_end) {
  868. // Continue the traversal.
  869. traverse_valid = src_impl.ContinueTraversal(next_entry, context);
  870. ASSERT(traverse_valid);
  871. // Process the block.
  872. if (next_entry.phys_addr != cur_block_addr + cur_block_size) {
  873. // Map the block we've been processing so far.
  874. R_TRY(Operate(cur_mapped_addr, cur_block_size / PageSize, test_perm, OperationType::Map,
  875. cur_block_addr));
  876. // Update tracking extents.
  877. cur_mapped_addr += cur_block_size;
  878. cur_block_addr = next_entry.phys_addr;
  879. cur_block_size = next_entry.block_size;
  880. } else {
  881. cur_block_size += next_entry.block_size;
  882. }
  883. tot_block_size += next_entry.block_size;
  884. }
  885. // Handle the last direct-mapped page.
  886. if (const VAddr mapped_block_end = aligned_src_start + tot_block_size - cur_block_size;
  887. mapped_block_end < mapping_src_end) {
  888. const size_t last_block_size = mapping_src_end - mapped_block_end;
  889. // Map the last block.
  890. R_TRY(Operate(cur_mapped_addr, last_block_size / PageSize, test_perm, OperationType::Map,
  891. cur_block_addr));
  892. // Update tracking extents.
  893. cur_mapped_addr += last_block_size;
  894. cur_block_addr += last_block_size;
  895. if (mapped_block_end + cur_block_size < aligned_src_end &&
  896. cur_block_size == last_block_size) {
  897. traverse_valid = src_impl.ContinueTraversal(next_entry, context);
  898. ASSERT(traverse_valid);
  899. cur_block_addr = next_entry.phys_addr;
  900. }
  901. }
  902. // Map the end page, if we have one.
  903. if (end_partial_page != 0) {
  904. // Ensure the page holds correct data.
  905. const VAddr end_partial_virt =
  906. GetHeapVirtualAddress(m_system.Kernel().MemoryLayout(), end_partial_page);
  907. if (send) {
  908. const size_t copy_size = src_end - mapping_src_end;
  909. std::memcpy(m_system.Memory().GetPointer<void>(end_partial_virt),
  910. m_system.Memory().GetPointer<void>(GetHeapVirtualAddress(
  911. m_system.Kernel().MemoryLayout(), cur_block_addr)),
  912. copy_size);
  913. std::memset(m_system.Memory().GetPointer<void>(end_partial_virt + copy_size), fill_val,
  914. PageSize - copy_size);
  915. } else {
  916. std::memset(m_system.Memory().GetPointer<void>(end_partial_virt), fill_val, PageSize);
  917. }
  918. // Map the page.
  919. R_TRY(Operate(cur_mapped_addr, 1, test_perm, OperationType::Map, end_partial_page));
  920. }
  921. // Update memory blocks to reflect our changes
  922. m_memory_block_manager.Update(std::addressof(allocator), dst_addr, aligned_src_size / PageSize,
  923. dst_state, test_perm, KMemoryAttribute::None,
  924. KMemoryBlockDisableMergeAttribute::Normal,
  925. KMemoryBlockDisableMergeAttribute::None);
  926. // Set the output address.
  927. *out_addr = dst_addr + (src_start - aligned_src_start);
  928. // We succeeded.
  929. memory_reservation.Commit();
  930. R_SUCCEED();
  931. }
  932. Result KPageTable::SetupForIpc(VAddr* out_dst_addr, size_t size, VAddr src_addr,
  933. KPageTable& src_page_table, KMemoryPermission test_perm,
  934. KMemoryState dst_state, bool send) {
  935. // For convenience, alias this.
  936. KPageTable& dst_page_table = *this;
  937. // Acquire the table locks.
  938. KScopedLightLockPair lk(src_page_table.m_general_lock, dst_page_table.m_general_lock);
  939. // We're going to perform an update, so create a helper.
  940. KScopedPageTableUpdater updater(std::addressof(src_page_table));
  941. // Perform client setup.
  942. size_t num_allocator_blocks;
  943. R_TRY(src_page_table.SetupForIpcClient(updater.GetPageList(),
  944. std::addressof(num_allocator_blocks), src_addr, size,
  945. test_perm, dst_state));
  946. // Create an update allocator.
  947. Result allocator_result;
  948. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  949. src_page_table.m_memory_block_slab_manager,
  950. num_allocator_blocks);
  951. R_TRY(allocator_result);
  952. // Get the mapped extents.
  953. const VAddr src_map_start = Common::AlignUp((src_addr), PageSize);
  954. const VAddr src_map_end = Common::AlignDown((src_addr) + size, PageSize);
  955. const size_t src_map_size = src_map_end - src_map_start;
  956. // Ensure that we clean up appropriately if we fail after this.
  957. const auto src_perm = (test_perm == KMemoryPermission::UserReadWrite)
  958. ? KMemoryPermission::KernelReadWrite | KMemoryPermission::NotMapped
  959. : KMemoryPermission::UserRead;
  960. ON_RESULT_FAILURE {
  961. if (src_map_end > src_map_start) {
  962. src_page_table.CleanupForIpcClientOnServerSetupFailure(
  963. updater.GetPageList(), src_map_start, src_map_size, src_perm);
  964. }
  965. };
  966. // Perform server setup.
  967. R_TRY(dst_page_table.SetupForIpcServer(out_dst_addr, size, src_addr, test_perm, dst_state,
  968. src_page_table, send));
  969. // If anything was mapped, ipc-lock the pages.
  970. if (src_map_start < src_map_end) {
  971. // Get the source permission.
  972. src_page_table.m_memory_block_manager.UpdateLock(std::addressof(allocator), src_map_start,
  973. (src_map_end - src_map_start) / PageSize,
  974. &KMemoryBlock::LockForIpc, src_perm);
  975. }
  976. R_SUCCEED();
  977. }
  978. Result KPageTable::CleanupForIpcServer(VAddr address, size_t size, KMemoryState dst_state) {
  979. // Validate the address.
  980. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  981. // Lock the table.
  982. KScopedLightLock lk(m_general_lock);
  983. // Validate the memory state.
  984. size_t num_allocator_blocks;
  985. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), address, size,
  986. KMemoryState::All, dst_state, KMemoryPermission::UserRead,
  987. KMemoryPermission::UserRead, KMemoryAttribute::All,
  988. KMemoryAttribute::None));
  989. // Create an update allocator.
  990. Result allocator_result;
  991. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  992. m_memory_block_slab_manager, num_allocator_blocks);
  993. R_TRY(allocator_result);
  994. // We're going to perform an update, so create a helper.
  995. KScopedPageTableUpdater updater(this);
  996. // Get aligned extents.
  997. const VAddr aligned_start = Common::AlignDown((address), PageSize);
  998. const VAddr aligned_end = Common::AlignUp((address) + size, PageSize);
  999. const size_t aligned_size = aligned_end - aligned_start;
  1000. const size_t aligned_num_pages = aligned_size / PageSize;
  1001. // Unmap the pages.
  1002. R_TRY(Operate(aligned_start, aligned_num_pages, KMemoryPermission::None, OperationType::Unmap));
  1003. // Update memory blocks.
  1004. m_memory_block_manager.Update(std::addressof(allocator), aligned_start, aligned_num_pages,
  1005. KMemoryState::None, KMemoryPermission::None,
  1006. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  1007. KMemoryBlockDisableMergeAttribute::Normal);
  1008. // Release from the resource limit as relevant.
  1009. const VAddr mapping_start = Common::AlignUp((address), PageSize);
  1010. const VAddr mapping_end = Common::AlignDown((address) + size, PageSize);
  1011. const size_t mapping_size = (mapping_start < mapping_end) ? mapping_end - mapping_start : 0;
  1012. m_resource_limit->Release(LimitableResource::PhysicalMemoryMax, aligned_size - mapping_size);
  1013. R_SUCCEED();
  1014. }
  1015. Result KPageTable::CleanupForIpcClient(VAddr address, size_t size, KMemoryState dst_state) {
  1016. // Validate the address.
  1017. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  1018. // Get aligned source extents.
  1019. const VAddr mapping_start = Common::AlignUp((address), PageSize);
  1020. const VAddr mapping_end = Common::AlignDown((address) + size, PageSize);
  1021. const VAddr mapping_last = mapping_end - 1;
  1022. const size_t mapping_size = (mapping_start < mapping_end) ? (mapping_end - mapping_start) : 0;
  1023. // If nothing was mapped, we're actually done immediately.
  1024. R_SUCCEED_IF(mapping_size == 0);
  1025. // Get the test state and attribute mask.
  1026. KMemoryState test_state;
  1027. KMemoryAttribute test_attr_mask;
  1028. switch (dst_state) {
  1029. case KMemoryState::Ipc:
  1030. test_state = KMemoryState::FlagCanUseIpc;
  1031. test_attr_mask =
  1032. KMemoryAttribute::Uncached | KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked;
  1033. break;
  1034. case KMemoryState::NonSecureIpc:
  1035. test_state = KMemoryState::FlagCanUseNonSecureIpc;
  1036. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  1037. break;
  1038. case KMemoryState::NonDeviceIpc:
  1039. test_state = KMemoryState::FlagCanUseNonDeviceIpc;
  1040. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  1041. break;
  1042. default:
  1043. R_THROW(ResultInvalidCombination);
  1044. }
  1045. // Lock the table.
  1046. // NOTE: Nintendo does this *after* creating the updater below, but this does not follow
  1047. // convention elsewhere in KPageTable.
  1048. KScopedLightLock lk(m_general_lock);
  1049. // We're going to perform an update, so create a helper.
  1050. KScopedPageTableUpdater updater(this);
  1051. // Ensure that on failure, we roll back appropriately.
  1052. size_t mapped_size = 0;
  1053. ON_RESULT_FAILURE {
  1054. if (mapped_size > 0) {
  1055. // Determine where the mapping ends.
  1056. const auto mapped_end = (mapping_start) + mapped_size;
  1057. const auto mapped_last = mapped_end - 1;
  1058. // Get current and next iterators.
  1059. KMemoryBlockManager::const_iterator start_it =
  1060. m_memory_block_manager.FindIterator(mapping_start);
  1061. KMemoryBlockManager::const_iterator next_it = start_it;
  1062. ++next_it;
  1063. // Get the current block info.
  1064. KMemoryInfo cur_info = start_it->GetMemoryInfo();
  1065. // Create tracking variables.
  1066. VAddr cur_address = cur_info.GetAddress();
  1067. size_t cur_size = cur_info.GetSize();
  1068. bool cur_perm_eq = cur_info.GetPermission() == cur_info.GetOriginalPermission();
  1069. bool cur_needs_set_perm = !cur_perm_eq && cur_info.GetIpcLockCount() == 1;
  1070. bool first =
  1071. cur_info.GetIpcDisableMergeCount() == 1 &&
  1072. (cur_info.GetDisableMergeAttribute() & KMemoryBlockDisableMergeAttribute::Locked) ==
  1073. KMemoryBlockDisableMergeAttribute::None;
  1074. while (((cur_address) + cur_size - 1) < mapped_last) {
  1075. // Check that we have a next block.
  1076. ASSERT(next_it != m_memory_block_manager.end());
  1077. // Get the next info.
  1078. const KMemoryInfo next_info = next_it->GetMemoryInfo();
  1079. // Check if we can consolidate the next block's permission set with the current one.
  1080. const bool next_perm_eq =
  1081. next_info.GetPermission() == next_info.GetOriginalPermission();
  1082. const bool next_needs_set_perm = !next_perm_eq && next_info.GetIpcLockCount() == 1;
  1083. if (cur_perm_eq == next_perm_eq && cur_needs_set_perm == next_needs_set_perm &&
  1084. cur_info.GetOriginalPermission() == next_info.GetOriginalPermission()) {
  1085. // We can consolidate the reprotection for the current and next block into a
  1086. // single call.
  1087. cur_size += next_info.GetSize();
  1088. } else {
  1089. // We have to operate on the current block.
  1090. if ((cur_needs_set_perm || first) && !cur_perm_eq) {
  1091. ASSERT(Operate(cur_address, cur_size / PageSize, cur_info.GetPermission(),
  1092. OperationType::ChangePermissions)
  1093. .IsSuccess());
  1094. }
  1095. // Advance.
  1096. cur_address = next_info.GetAddress();
  1097. cur_size = next_info.GetSize();
  1098. first = false;
  1099. }
  1100. // Advance.
  1101. cur_info = next_info;
  1102. cur_perm_eq = next_perm_eq;
  1103. cur_needs_set_perm = next_needs_set_perm;
  1104. ++next_it;
  1105. }
  1106. // Process the last block.
  1107. if ((first || cur_needs_set_perm) && !cur_perm_eq) {
  1108. ASSERT(Operate(cur_address, cur_size / PageSize, cur_info.GetPermission(),
  1109. OperationType::ChangePermissions)
  1110. .IsSuccess());
  1111. }
  1112. }
  1113. };
  1114. // Iterate, reprotecting as needed.
  1115. {
  1116. // Get current and next iterators.
  1117. KMemoryBlockManager::const_iterator start_it =
  1118. m_memory_block_manager.FindIterator(mapping_start);
  1119. KMemoryBlockManager::const_iterator next_it = start_it;
  1120. ++next_it;
  1121. // Validate the current block.
  1122. KMemoryInfo cur_info = start_it->GetMemoryInfo();
  1123. ASSERT(this->CheckMemoryState(cur_info, test_state, test_state, KMemoryPermission::None,
  1124. KMemoryPermission::None,
  1125. test_attr_mask | KMemoryAttribute::IpcLocked,
  1126. KMemoryAttribute::IpcLocked)
  1127. .IsSuccess());
  1128. // Create tracking variables.
  1129. VAddr cur_address = cur_info.GetAddress();
  1130. size_t cur_size = cur_info.GetSize();
  1131. bool cur_perm_eq = cur_info.GetPermission() == cur_info.GetOriginalPermission();
  1132. bool cur_needs_set_perm = !cur_perm_eq && cur_info.GetIpcLockCount() == 1;
  1133. bool first =
  1134. cur_info.GetIpcDisableMergeCount() == 1 &&
  1135. (cur_info.GetDisableMergeAttribute() & KMemoryBlockDisableMergeAttribute::Locked) ==
  1136. KMemoryBlockDisableMergeAttribute::None;
  1137. while ((cur_address + cur_size - 1) < mapping_last) {
  1138. // Check that we have a next block.
  1139. ASSERT(next_it != m_memory_block_manager.end());
  1140. // Get the next info.
  1141. const KMemoryInfo next_info = next_it->GetMemoryInfo();
  1142. // Validate the next block.
  1143. ASSERT(this->CheckMemoryState(next_info, test_state, test_state,
  1144. KMemoryPermission::None, KMemoryPermission::None,
  1145. test_attr_mask | KMemoryAttribute::IpcLocked,
  1146. KMemoryAttribute::IpcLocked)
  1147. .IsSuccess());
  1148. // Check if we can consolidate the next block's permission set with the current one.
  1149. const bool next_perm_eq =
  1150. next_info.GetPermission() == next_info.GetOriginalPermission();
  1151. const bool next_needs_set_perm = !next_perm_eq && next_info.GetIpcLockCount() == 1;
  1152. if (cur_perm_eq == next_perm_eq && cur_needs_set_perm == next_needs_set_perm &&
  1153. cur_info.GetOriginalPermission() == next_info.GetOriginalPermission()) {
  1154. // We can consolidate the reprotection for the current and next block into a single
  1155. // call.
  1156. cur_size += next_info.GetSize();
  1157. } else {
  1158. // We have to operate on the current block.
  1159. if ((cur_needs_set_perm || first) && !cur_perm_eq) {
  1160. R_TRY(Operate(cur_address, cur_size / PageSize,
  1161. cur_needs_set_perm ? cur_info.GetOriginalPermission()
  1162. : cur_info.GetPermission(),
  1163. OperationType::ChangePermissions));
  1164. }
  1165. // Mark that we mapped the block.
  1166. mapped_size += cur_size;
  1167. // Advance.
  1168. cur_address = next_info.GetAddress();
  1169. cur_size = next_info.GetSize();
  1170. first = false;
  1171. }
  1172. // Advance.
  1173. cur_info = next_info;
  1174. cur_perm_eq = next_perm_eq;
  1175. cur_needs_set_perm = next_needs_set_perm;
  1176. ++next_it;
  1177. }
  1178. // Process the last block.
  1179. const auto lock_count =
  1180. cur_info.GetIpcLockCount() +
  1181. (next_it != m_memory_block_manager.end()
  1182. ? (next_it->GetIpcDisableMergeCount() - next_it->GetIpcLockCount())
  1183. : 0);
  1184. if ((first || cur_needs_set_perm || (lock_count == 1)) && !cur_perm_eq) {
  1185. R_TRY(Operate(cur_address, cur_size / PageSize,
  1186. cur_needs_set_perm ? cur_info.GetOriginalPermission()
  1187. : cur_info.GetPermission(),
  1188. OperationType::ChangePermissions));
  1189. }
  1190. }
  1191. // Create an update allocator.
  1192. // NOTE: Guaranteed zero blocks needed here.
  1193. Result allocator_result;
  1194. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1195. m_memory_block_slab_manager, 0);
  1196. R_TRY(allocator_result);
  1197. // Unlock the pages.
  1198. m_memory_block_manager.UpdateLock(std::addressof(allocator), mapping_start,
  1199. mapping_size / PageSize, &KMemoryBlock::UnlockForIpc,
  1200. KMemoryPermission::None);
  1201. R_SUCCEED();
  1202. }
  1203. void KPageTable::CleanupForIpcClientOnServerSetupFailure([[maybe_unused]] PageLinkedList* page_list,
  1204. VAddr address, size_t size,
  1205. KMemoryPermission prot_perm) {
  1206. ASSERT(this->IsLockedByCurrentThread());
  1207. ASSERT(Common::IsAligned(address, PageSize));
  1208. ASSERT(Common::IsAligned(size, PageSize));
  1209. // Get the mapped extents.
  1210. const VAddr src_map_start = address;
  1211. const VAddr src_map_end = address + size;
  1212. const VAddr src_map_last = src_map_end - 1;
  1213. // This function is only invoked when there's something to do.
  1214. ASSERT(src_map_end > src_map_start);
  1215. // Iterate over blocks, fixing permissions.
  1216. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(address);
  1217. while (true) {
  1218. const KMemoryInfo info = it->GetMemoryInfo();
  1219. const auto cur_start =
  1220. info.GetAddress() >= src_map_start ? info.GetAddress() : src_map_start;
  1221. const auto cur_end =
  1222. src_map_last <= info.GetLastAddress() ? src_map_end : info.GetEndAddress();
  1223. // If we can, fix the protections on the block.
  1224. if ((info.GetIpcLockCount() == 0 &&
  1225. (info.GetPermission() & KMemoryPermission::IpcLockChangeMask) != prot_perm) ||
  1226. (info.GetIpcLockCount() != 0 &&
  1227. (info.GetOriginalPermission() & KMemoryPermission::IpcLockChangeMask) != prot_perm)) {
  1228. // Check if we actually need to fix the protections on the block.
  1229. if (cur_end == src_map_end || info.GetAddress() <= src_map_start ||
  1230. (info.GetPermission() & KMemoryPermission::IpcLockChangeMask) != prot_perm) {
  1231. ASSERT(Operate(cur_start, (cur_end - cur_start) / PageSize, info.GetPermission(),
  1232. OperationType::ChangePermissions)
  1233. .IsSuccess());
  1234. }
  1235. }
  1236. // If we're past the end of the region, we're done.
  1237. if (src_map_last <= info.GetLastAddress()) {
  1238. break;
  1239. }
  1240. // Advance.
  1241. ++it;
  1242. ASSERT(it != m_memory_block_manager.end());
  1243. }
  1244. }
  1245. Result KPageTable::MapPhysicalMemory(VAddr address, size_t size) {
  1246. // Lock the physical memory lock.
  1247. KScopedLightLock phys_lk(m_map_physical_memory_lock);
  1248. // Calculate the last address for convenience.
  1249. const VAddr last_address = address + size - 1;
  1250. // Define iteration variables.
  1251. VAddr cur_address;
  1252. size_t mapped_size;
  1253. // The entire mapping process can be retried.
  1254. while (true) {
  1255. // Check if the memory is already mapped.
  1256. {
  1257. // Lock the table.
  1258. KScopedLightLock lk(m_general_lock);
  1259. // Iterate over the memory.
  1260. cur_address = address;
  1261. mapped_size = 0;
  1262. auto it = m_memory_block_manager.FindIterator(cur_address);
  1263. while (true) {
  1264. // Check that the iterator is valid.
  1265. ASSERT(it != m_memory_block_manager.end());
  1266. // Get the memory info.
  1267. const KMemoryInfo info = it->GetMemoryInfo();
  1268. // Check if we're done.
  1269. if (last_address <= info.GetLastAddress()) {
  1270. if (info.GetState() != KMemoryState::Free) {
  1271. mapped_size += (last_address + 1 - cur_address);
  1272. }
  1273. break;
  1274. }
  1275. // Track the memory if it's mapped.
  1276. if (info.GetState() != KMemoryState::Free) {
  1277. mapped_size += VAddr(info.GetEndAddress()) - cur_address;
  1278. }
  1279. // Advance.
  1280. cur_address = info.GetEndAddress();
  1281. ++it;
  1282. }
  1283. // If the size mapped is the size requested, we've nothing to do.
  1284. R_SUCCEED_IF(size == mapped_size);
  1285. }
  1286. // Allocate and map the memory.
  1287. {
  1288. // Reserve the memory from the process resource limit.
  1289. KScopedResourceReservation memory_reservation(
  1290. m_resource_limit, LimitableResource::PhysicalMemoryMax, size - mapped_size);
  1291. R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
  1292. // Allocate pages for the new memory.
  1293. KPageGroup pg{m_kernel, m_block_info_manager};
  1294. R_TRY(m_system.Kernel().MemoryManager().AllocateForProcess(
  1295. &pg, (size - mapped_size) / PageSize, m_allocate_option, 0, 0));
  1296. // If we fail in the next bit (or retry), we need to cleanup the pages.
  1297. // auto pg_guard = SCOPE_GUARD {
  1298. // pg.OpenFirst();
  1299. // pg.Close();
  1300. //};
  1301. // Map the memory.
  1302. {
  1303. // Lock the table.
  1304. KScopedLightLock lk(m_general_lock);
  1305. size_t num_allocator_blocks = 0;
  1306. // Verify that nobody has mapped memory since we first checked.
  1307. {
  1308. // Iterate over the memory.
  1309. size_t checked_mapped_size = 0;
  1310. cur_address = address;
  1311. auto it = m_memory_block_manager.FindIterator(cur_address);
  1312. while (true) {
  1313. // Check that the iterator is valid.
  1314. ASSERT(it != m_memory_block_manager.end());
  1315. // Get the memory info.
  1316. const KMemoryInfo info = it->GetMemoryInfo();
  1317. const bool is_free = info.GetState() == KMemoryState::Free;
  1318. if (is_free) {
  1319. if (info.GetAddress() < address) {
  1320. ++num_allocator_blocks;
  1321. }
  1322. if (last_address < info.GetLastAddress()) {
  1323. ++num_allocator_blocks;
  1324. }
  1325. }
  1326. // Check if we're done.
  1327. if (last_address <= info.GetLastAddress()) {
  1328. if (!is_free) {
  1329. checked_mapped_size += (last_address + 1 - cur_address);
  1330. }
  1331. break;
  1332. }
  1333. // Track the memory if it's mapped.
  1334. if (!is_free) {
  1335. checked_mapped_size += VAddr(info.GetEndAddress()) - cur_address;
  1336. }
  1337. // Advance.
  1338. cur_address = info.GetEndAddress();
  1339. ++it;
  1340. }
  1341. // If the size now isn't what it was before, somebody mapped or unmapped
  1342. // concurrently. If this happened, retry.
  1343. if (mapped_size != checked_mapped_size) {
  1344. continue;
  1345. }
  1346. }
  1347. // Create an update allocator.
  1348. ASSERT(num_allocator_blocks <= KMemoryBlockManagerUpdateAllocator::MaxBlocks);
  1349. Result allocator_result;
  1350. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1351. m_memory_block_slab_manager,
  1352. num_allocator_blocks);
  1353. R_TRY(allocator_result);
  1354. // We're going to perform an update, so create a helper.
  1355. KScopedPageTableUpdater updater(this);
  1356. // Prepare to iterate over the memory.
  1357. auto pg_it = pg.begin();
  1358. PAddr pg_phys_addr = pg_it->GetAddress();
  1359. size_t pg_pages = pg_it->GetNumPages();
  1360. // Reset the current tracking address, and make sure we clean up on failure.
  1361. // pg_guard.Cancel();
  1362. cur_address = address;
  1363. ON_RESULT_FAILURE {
  1364. if (cur_address > address) {
  1365. const VAddr last_unmap_address = cur_address - 1;
  1366. // Iterate, unmapping the pages.
  1367. cur_address = address;
  1368. auto it = m_memory_block_manager.FindIterator(cur_address);
  1369. while (true) {
  1370. // Check that the iterator is valid.
  1371. ASSERT(it != m_memory_block_manager.end());
  1372. // Get the memory info.
  1373. const KMemoryInfo info = it->GetMemoryInfo();
  1374. // If the memory state is free, we mapped it and need to unmap it.
  1375. if (info.GetState() == KMemoryState::Free) {
  1376. // Determine the range to unmap.
  1377. const size_t cur_pages =
  1378. std::min(VAddr(info.GetEndAddress()) - cur_address,
  1379. last_unmap_address + 1 - cur_address) /
  1380. PageSize;
  1381. // Unmap.
  1382. ASSERT(Operate(cur_address, cur_pages, KMemoryPermission::None,
  1383. OperationType::Unmap)
  1384. .IsSuccess());
  1385. }
  1386. // Check if we're done.
  1387. if (last_unmap_address <= info.GetLastAddress()) {
  1388. break;
  1389. }
  1390. // Advance.
  1391. cur_address = info.GetEndAddress();
  1392. ++it;
  1393. }
  1394. }
  1395. // Release any remaining unmapped memory.
  1396. m_system.Kernel().MemoryManager().OpenFirst(pg_phys_addr, pg_pages);
  1397. m_system.Kernel().MemoryManager().Close(pg_phys_addr, pg_pages);
  1398. for (++pg_it; pg_it != pg.end(); ++pg_it) {
  1399. m_system.Kernel().MemoryManager().OpenFirst(pg_it->GetAddress(),
  1400. pg_it->GetNumPages());
  1401. m_system.Kernel().MemoryManager().Close(pg_it->GetAddress(),
  1402. pg_it->GetNumPages());
  1403. }
  1404. };
  1405. auto it = m_memory_block_manager.FindIterator(cur_address);
  1406. while (true) {
  1407. // Check that the iterator is valid.
  1408. ASSERT(it != m_memory_block_manager.end());
  1409. // Get the memory info.
  1410. const KMemoryInfo info = it->GetMemoryInfo();
  1411. // If it's unmapped, we need to map it.
  1412. if (info.GetState() == KMemoryState::Free) {
  1413. // Determine the range to map.
  1414. size_t map_pages = std::min(VAddr(info.GetEndAddress()) - cur_address,
  1415. last_address + 1 - cur_address) /
  1416. PageSize;
  1417. // While we have pages to map, map them.
  1418. while (map_pages > 0) {
  1419. // Check if we're at the end of the physical block.
  1420. if (pg_pages == 0) {
  1421. // Ensure there are more pages to map.
  1422. ASSERT(pg_it != pg.end());
  1423. // Advance our physical block.
  1424. ++pg_it;
  1425. pg_phys_addr = pg_it->GetAddress();
  1426. pg_pages = pg_it->GetNumPages();
  1427. }
  1428. // Map whatever we can.
  1429. const size_t cur_pages = std::min(pg_pages, map_pages);
  1430. R_TRY(Operate(cur_address, cur_pages, KMemoryPermission::UserReadWrite,
  1431. OperationType::MapFirst, pg_phys_addr));
  1432. // Advance.
  1433. cur_address += cur_pages * PageSize;
  1434. map_pages -= cur_pages;
  1435. pg_phys_addr += cur_pages * PageSize;
  1436. pg_pages -= cur_pages;
  1437. }
  1438. }
  1439. // Check if we're done.
  1440. if (last_address <= info.GetLastAddress()) {
  1441. break;
  1442. }
  1443. // Advance.
  1444. cur_address = info.GetEndAddress();
  1445. ++it;
  1446. }
  1447. // We succeeded, so commit the memory reservation.
  1448. memory_reservation.Commit();
  1449. // Increase our tracked mapped size.
  1450. m_mapped_physical_memory_size += (size - mapped_size);
  1451. // Update the relevant memory blocks.
  1452. m_memory_block_manager.UpdateIfMatch(
  1453. std::addressof(allocator), address, size / PageSize, KMemoryState::Free,
  1454. KMemoryPermission::None, KMemoryAttribute::None, KMemoryState::Normal,
  1455. KMemoryPermission::UserReadWrite, KMemoryAttribute::None);
  1456. R_SUCCEED();
  1457. }
  1458. }
  1459. }
  1460. }
  1461. Result KPageTable::UnmapPhysicalMemory(VAddr address, size_t size) {
  1462. // Lock the physical memory lock.
  1463. KScopedLightLock phys_lk(m_map_physical_memory_lock);
  1464. // Lock the table.
  1465. KScopedLightLock lk(m_general_lock);
  1466. // Calculate the last address for convenience.
  1467. const VAddr last_address = address + size - 1;
  1468. // Define iteration variables.
  1469. VAddr map_start_address = 0;
  1470. VAddr map_last_address = 0;
  1471. VAddr cur_address;
  1472. size_t mapped_size;
  1473. size_t num_allocator_blocks = 0;
  1474. // Check if the memory is mapped.
  1475. {
  1476. // Iterate over the memory.
  1477. cur_address = address;
  1478. mapped_size = 0;
  1479. auto it = m_memory_block_manager.FindIterator(cur_address);
  1480. while (true) {
  1481. // Check that the iterator is valid.
  1482. ASSERT(it != m_memory_block_manager.end());
  1483. // Get the memory info.
  1484. const KMemoryInfo info = it->GetMemoryInfo();
  1485. // Verify the memory's state.
  1486. const bool is_normal = info.GetState() == KMemoryState::Normal &&
  1487. info.GetAttribute() == KMemoryAttribute::None;
  1488. const bool is_free = info.GetState() == KMemoryState::Free;
  1489. R_UNLESS(is_normal || is_free, ResultInvalidCurrentMemory);
  1490. if (is_normal) {
  1491. R_UNLESS(info.GetAttribute() == KMemoryAttribute::None, ResultInvalidCurrentMemory);
  1492. if (map_start_address == 0) {
  1493. map_start_address = cur_address;
  1494. }
  1495. map_last_address =
  1496. (last_address >= info.GetLastAddress()) ? info.GetLastAddress() : last_address;
  1497. if (info.GetAddress() < address) {
  1498. ++num_allocator_blocks;
  1499. }
  1500. if (last_address < info.GetLastAddress()) {
  1501. ++num_allocator_blocks;
  1502. }
  1503. mapped_size += (map_last_address + 1 - cur_address);
  1504. }
  1505. // Check if we're done.
  1506. if (last_address <= info.GetLastAddress()) {
  1507. break;
  1508. }
  1509. // Advance.
  1510. cur_address = info.GetEndAddress();
  1511. ++it;
  1512. }
  1513. // If there's nothing mapped, we've nothing to do.
  1514. R_SUCCEED_IF(mapped_size == 0);
  1515. }
  1516. // Create an update allocator.
  1517. ASSERT(num_allocator_blocks <= KMemoryBlockManagerUpdateAllocator::MaxBlocks);
  1518. Result allocator_result;
  1519. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1520. m_memory_block_slab_manager, num_allocator_blocks);
  1521. R_TRY(allocator_result);
  1522. // We're going to perform an update, so create a helper.
  1523. KScopedPageTableUpdater updater(this);
  1524. // Separate the mapping.
  1525. R_TRY(Operate(map_start_address, (map_last_address + 1 - map_start_address) / PageSize,
  1526. KMemoryPermission::None, OperationType::Separate));
  1527. // Reset the current tracking address, and make sure we clean up on failure.
  1528. cur_address = address;
  1529. // Iterate over the memory, unmapping as we go.
  1530. auto it = m_memory_block_manager.FindIterator(cur_address);
  1531. while (true) {
  1532. // Check that the iterator is valid.
  1533. ASSERT(it != m_memory_block_manager.end());
  1534. // Get the memory info.
  1535. const KMemoryInfo info = it->GetMemoryInfo();
  1536. // If the memory state is normal, we need to unmap it.
  1537. if (info.GetState() == KMemoryState::Normal) {
  1538. // Determine the range to unmap.
  1539. const size_t cur_pages = std::min(VAddr(info.GetEndAddress()) - cur_address,
  1540. last_address + 1 - cur_address) /
  1541. PageSize;
  1542. // Unmap.
  1543. ASSERT(Operate(cur_address, cur_pages, KMemoryPermission::None, OperationType::Unmap)
  1544. .IsSuccess());
  1545. }
  1546. // Check if we're done.
  1547. if (last_address <= info.GetLastAddress()) {
  1548. break;
  1549. }
  1550. // Advance.
  1551. cur_address = info.GetEndAddress();
  1552. ++it;
  1553. }
  1554. // Release the memory resource.
  1555. m_mapped_physical_memory_size -= mapped_size;
  1556. m_resource_limit->Release(LimitableResource::PhysicalMemoryMax, mapped_size);
  1557. // Update memory blocks.
  1558. m_memory_block_manager.Update(std::addressof(allocator), address, size / PageSize,
  1559. KMemoryState::Free, KMemoryPermission::None,
  1560. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  1561. KMemoryBlockDisableMergeAttribute::None);
  1562. // We succeeded.
  1563. R_SUCCEED();
  1564. }
  1565. Result KPageTable::MapMemory(KProcessAddress dst_address, KProcessAddress src_address,
  1566. size_t size) {
  1567. // Lock the table.
  1568. KScopedLightLock lk(m_general_lock);
  1569. // Validate that the source address's state is valid.
  1570. KMemoryState src_state;
  1571. size_t num_src_allocator_blocks;
  1572. R_TRY(this->CheckMemoryState(std::addressof(src_state), nullptr, nullptr,
  1573. std::addressof(num_src_allocator_blocks), src_address, size,
  1574. KMemoryState::FlagCanAlias, KMemoryState::FlagCanAlias,
  1575. KMemoryPermission::All, KMemoryPermission::UserReadWrite,
  1576. KMemoryAttribute::All, KMemoryAttribute::None));
  1577. // Validate that the dst address's state is valid.
  1578. size_t num_dst_allocator_blocks;
  1579. R_TRY(this->CheckMemoryState(std::addressof(num_dst_allocator_blocks), dst_address, size,
  1580. KMemoryState::All, KMemoryState::Free, KMemoryPermission::None,
  1581. KMemoryPermission::None, KMemoryAttribute::None,
  1582. KMemoryAttribute::None));
  1583. // Create an update allocator for the source.
  1584. Result src_allocator_result;
  1585. KMemoryBlockManagerUpdateAllocator src_allocator(std::addressof(src_allocator_result),
  1586. m_memory_block_slab_manager,
  1587. num_src_allocator_blocks);
  1588. R_TRY(src_allocator_result);
  1589. // Create an update allocator for the destination.
  1590. Result dst_allocator_result;
  1591. KMemoryBlockManagerUpdateAllocator dst_allocator(std::addressof(dst_allocator_result),
  1592. m_memory_block_slab_manager,
  1593. num_dst_allocator_blocks);
  1594. R_TRY(dst_allocator_result);
  1595. // Map the memory.
  1596. {
  1597. // Determine the number of pages being operated on.
  1598. const size_t num_pages = size / PageSize;
  1599. // Create page groups for the memory being unmapped.
  1600. KPageGroup pg{m_kernel, m_block_info_manager};
  1601. // Create the page group representing the source.
  1602. R_TRY(this->MakePageGroup(pg, src_address, num_pages));
  1603. // We're going to perform an update, so create a helper.
  1604. KScopedPageTableUpdater updater(this);
  1605. // Reprotect the source as kernel-read/not mapped.
  1606. const KMemoryPermission new_src_perm = static_cast<KMemoryPermission>(
  1607. KMemoryPermission::KernelRead | KMemoryPermission::NotMapped);
  1608. const KMemoryAttribute new_src_attr = KMemoryAttribute::Locked;
  1609. const KPageProperties src_properties = {new_src_perm, false, false,
  1610. DisableMergeAttribute::DisableHeadBodyTail};
  1611. R_TRY(this->Operate(src_address, num_pages, src_properties.perm,
  1612. OperationType::ChangePermissions));
  1613. // Ensure that we unprotect the source pages on failure.
  1614. ON_RESULT_FAILURE {
  1615. const KPageProperties unprotect_properties = {
  1616. KMemoryPermission::UserReadWrite, false, false,
  1617. DisableMergeAttribute::EnableHeadBodyTail};
  1618. ASSERT(this->Operate(src_address, num_pages, unprotect_properties.perm,
  1619. OperationType::ChangePermissions) == ResultSuccess);
  1620. };
  1621. // Map the alias pages.
  1622. const KPageProperties dst_map_properties = {KMemoryPermission::UserReadWrite, false, false,
  1623. DisableMergeAttribute::DisableHead};
  1624. R_TRY(this->MapPageGroupImpl(updater.GetPageList(), dst_address, pg, dst_map_properties,
  1625. false));
  1626. // Apply the memory block updates.
  1627. m_memory_block_manager.Update(std::addressof(src_allocator), src_address, num_pages,
  1628. src_state, new_src_perm, new_src_attr,
  1629. KMemoryBlockDisableMergeAttribute::Locked,
  1630. KMemoryBlockDisableMergeAttribute::None);
  1631. m_memory_block_manager.Update(
  1632. std::addressof(dst_allocator), dst_address, num_pages, KMemoryState::Stack,
  1633. KMemoryPermission::UserReadWrite, KMemoryAttribute::None,
  1634. KMemoryBlockDisableMergeAttribute::Normal, KMemoryBlockDisableMergeAttribute::None);
  1635. }
  1636. R_SUCCEED();
  1637. }
  1638. Result KPageTable::UnmapMemory(KProcessAddress dst_address, KProcessAddress src_address,
  1639. size_t size) {
  1640. // Lock the table.
  1641. KScopedLightLock lk(m_general_lock);
  1642. // Validate that the source address's state is valid.
  1643. KMemoryState src_state;
  1644. size_t num_src_allocator_blocks;
  1645. R_TRY(this->CheckMemoryState(
  1646. std::addressof(src_state), nullptr, nullptr, std::addressof(num_src_allocator_blocks),
  1647. src_address, size, KMemoryState::FlagCanAlias, KMemoryState::FlagCanAlias,
  1648. KMemoryPermission::All, KMemoryPermission::NotMapped | KMemoryPermission::KernelRead,
  1649. KMemoryAttribute::All, KMemoryAttribute::Locked));
  1650. // Validate that the dst address's state is valid.
  1651. KMemoryPermission dst_perm;
  1652. size_t num_dst_allocator_blocks;
  1653. R_TRY(this->CheckMemoryState(
  1654. nullptr, std::addressof(dst_perm), nullptr, std::addressof(num_dst_allocator_blocks),
  1655. dst_address, size, KMemoryState::All, KMemoryState::Stack, KMemoryPermission::None,
  1656. KMemoryPermission::None, KMemoryAttribute::All, KMemoryAttribute::None));
  1657. // Create an update allocator for the source.
  1658. Result src_allocator_result;
  1659. KMemoryBlockManagerUpdateAllocator src_allocator(std::addressof(src_allocator_result),
  1660. m_memory_block_slab_manager,
  1661. num_src_allocator_blocks);
  1662. R_TRY(src_allocator_result);
  1663. // Create an update allocator for the destination.
  1664. Result dst_allocator_result;
  1665. KMemoryBlockManagerUpdateAllocator dst_allocator(std::addressof(dst_allocator_result),
  1666. m_memory_block_slab_manager,
  1667. num_dst_allocator_blocks);
  1668. R_TRY(dst_allocator_result);
  1669. // Unmap the memory.
  1670. {
  1671. // Determine the number of pages being operated on.
  1672. const size_t num_pages = size / PageSize;
  1673. // Create page groups for the memory being unmapped.
  1674. KPageGroup pg{m_kernel, m_block_info_manager};
  1675. // Create the page group representing the destination.
  1676. R_TRY(this->MakePageGroup(pg, dst_address, num_pages));
  1677. // Ensure the page group is the valid for the source.
  1678. R_UNLESS(this->IsValidPageGroup(pg, src_address, num_pages), ResultInvalidMemoryRegion);
  1679. // We're going to perform an update, so create a helper.
  1680. KScopedPageTableUpdater updater(this);
  1681. // Unmap the aliased copy of the pages.
  1682. const KPageProperties dst_unmap_properties = {KMemoryPermission::None, false, false,
  1683. DisableMergeAttribute::None};
  1684. R_TRY(
  1685. this->Operate(dst_address, num_pages, dst_unmap_properties.perm, OperationType::Unmap));
  1686. // Ensure that we re-map the aliased pages on failure.
  1687. ON_RESULT_FAILURE {
  1688. this->RemapPageGroup(updater.GetPageList(), dst_address, size, pg);
  1689. };
  1690. // Try to set the permissions for the source pages back to what they should be.
  1691. const KPageProperties src_properties = {KMemoryPermission::UserReadWrite, false, false,
  1692. DisableMergeAttribute::EnableAndMergeHeadBodyTail};
  1693. R_TRY(this->Operate(src_address, num_pages, src_properties.perm,
  1694. OperationType::ChangePermissions));
  1695. // Apply the memory block updates.
  1696. m_memory_block_manager.Update(
  1697. std::addressof(src_allocator), src_address, num_pages, src_state,
  1698. KMemoryPermission::UserReadWrite, KMemoryAttribute::None,
  1699. KMemoryBlockDisableMergeAttribute::None, KMemoryBlockDisableMergeAttribute::Locked);
  1700. m_memory_block_manager.Update(
  1701. std::addressof(dst_allocator), dst_address, num_pages, KMemoryState::None,
  1702. KMemoryPermission::None, KMemoryAttribute::None,
  1703. KMemoryBlockDisableMergeAttribute::None, KMemoryBlockDisableMergeAttribute::Normal);
  1704. }
  1705. R_SUCCEED();
  1706. }
  1707. Result KPageTable::AllocateAndMapPagesImpl(PageLinkedList* page_list, KProcessAddress address,
  1708. size_t num_pages, KMemoryPermission perm) {
  1709. ASSERT(this->IsLockedByCurrentThread());
  1710. // Create a page group to hold the pages we allocate.
  1711. KPageGroup pg{m_kernel, m_block_info_manager};
  1712. // Allocate the pages.
  1713. R_TRY(
  1714. m_kernel.MemoryManager().AllocateAndOpen(std::addressof(pg), num_pages, m_allocate_option));
  1715. // Ensure that the page group is closed when we're done working with it.
  1716. SCOPE_EXIT({ pg.Close(); });
  1717. // Clear all pages.
  1718. for (const auto& it : pg) {
  1719. std::memset(m_system.DeviceMemory().GetPointer<void>(it.GetAddress()), m_heap_fill_value,
  1720. it.GetSize());
  1721. }
  1722. // Map the pages.
  1723. R_RETURN(this->Operate(address, num_pages, pg, OperationType::MapGroup));
  1724. }
  1725. Result KPageTable::MapPageGroupImpl(PageLinkedList* page_list, KProcessAddress address,
  1726. const KPageGroup& pg, const KPageProperties properties,
  1727. bool reuse_ll) {
  1728. ASSERT(this->IsLockedByCurrentThread());
  1729. // Note the current address, so that we can iterate.
  1730. const KProcessAddress start_address = address;
  1731. KProcessAddress cur_address = address;
  1732. // Ensure that we clean up on failure.
  1733. ON_RESULT_FAILURE {
  1734. ASSERT(!reuse_ll);
  1735. if (cur_address != start_address) {
  1736. const KPageProperties unmap_properties = {KMemoryPermission::None, false, false,
  1737. DisableMergeAttribute::None};
  1738. ASSERT(this->Operate(start_address, (cur_address - start_address) / PageSize,
  1739. unmap_properties.perm, OperationType::Unmap) == ResultSuccess);
  1740. }
  1741. };
  1742. // Iterate, mapping all pages in the group.
  1743. for (const auto& block : pg) {
  1744. // Map and advance.
  1745. const KPageProperties cur_properties =
  1746. (cur_address == start_address)
  1747. ? properties
  1748. : KPageProperties{properties.perm, properties.io, properties.uncached,
  1749. DisableMergeAttribute::None};
  1750. this->Operate(cur_address, block.GetNumPages(), cur_properties.perm, OperationType::Map,
  1751. block.GetAddress());
  1752. cur_address += block.GetSize();
  1753. }
  1754. // We succeeded!
  1755. R_SUCCEED();
  1756. }
  1757. void KPageTable::RemapPageGroup(PageLinkedList* page_list, KProcessAddress address, size_t size,
  1758. const KPageGroup& pg) {
  1759. ASSERT(this->IsLockedByCurrentThread());
  1760. // Note the current address, so that we can iterate.
  1761. const KProcessAddress start_address = address;
  1762. const KProcessAddress last_address = start_address + size - 1;
  1763. const KProcessAddress end_address = last_address + 1;
  1764. // Iterate over the memory.
  1765. auto pg_it = pg.begin();
  1766. ASSERT(pg_it != pg.end());
  1767. KPhysicalAddress pg_phys_addr = pg_it->GetAddress();
  1768. size_t pg_pages = pg_it->GetNumPages();
  1769. auto it = m_memory_block_manager.FindIterator(start_address);
  1770. while (true) {
  1771. // Check that the iterator is valid.
  1772. ASSERT(it != m_memory_block_manager.end());
  1773. // Get the memory info.
  1774. const KMemoryInfo info = it->GetMemoryInfo();
  1775. // Determine the range to map.
  1776. KProcessAddress map_address = std::max<VAddr>(info.GetAddress(), start_address);
  1777. const KProcessAddress map_end_address = std::min<VAddr>(info.GetEndAddress(), end_address);
  1778. ASSERT(map_end_address != map_address);
  1779. // Determine if we should disable head merge.
  1780. const bool disable_head_merge =
  1781. info.GetAddress() >= start_address &&
  1782. True(info.GetDisableMergeAttribute() & KMemoryBlockDisableMergeAttribute::Normal);
  1783. const KPageProperties map_properties = {
  1784. info.GetPermission(), false, false,
  1785. disable_head_merge ? DisableMergeAttribute::DisableHead : DisableMergeAttribute::None};
  1786. // While we have pages to map, map them.
  1787. size_t map_pages = (map_end_address - map_address) / PageSize;
  1788. while (map_pages > 0) {
  1789. // Check if we're at the end of the physical block.
  1790. if (pg_pages == 0) {
  1791. // Ensure there are more pages to map.
  1792. ASSERT(pg_it != pg.end());
  1793. // Advance our physical block.
  1794. ++pg_it;
  1795. pg_phys_addr = pg_it->GetAddress();
  1796. pg_pages = pg_it->GetNumPages();
  1797. }
  1798. // Map whatever we can.
  1799. const size_t cur_pages = std::min(pg_pages, map_pages);
  1800. ASSERT(this->Operate(map_address, map_pages, map_properties.perm, OperationType::Map,
  1801. pg_phys_addr) == ResultSuccess);
  1802. // Advance.
  1803. map_address += cur_pages * PageSize;
  1804. map_pages -= cur_pages;
  1805. pg_phys_addr += cur_pages * PageSize;
  1806. pg_pages -= cur_pages;
  1807. }
  1808. // Check if we're done.
  1809. if (last_address <= info.GetLastAddress()) {
  1810. break;
  1811. }
  1812. // Advance.
  1813. ++it;
  1814. }
  1815. // Check that we re-mapped precisely the page group.
  1816. ASSERT((++pg_it) == pg.end());
  1817. }
  1818. Result KPageTable::MapPages(KProcessAddress* out_addr, size_t num_pages, size_t alignment,
  1819. KPhysicalAddress phys_addr, bool is_pa_valid,
  1820. KProcessAddress region_start, size_t region_num_pages,
  1821. KMemoryState state, KMemoryPermission perm) {
  1822. ASSERT(Common::IsAligned(alignment, PageSize) && alignment >= PageSize);
  1823. // Ensure this is a valid map request.
  1824. R_UNLESS(this->CanContain(region_start, region_num_pages * PageSize, state),
  1825. ResultInvalidCurrentMemory);
  1826. R_UNLESS(num_pages < region_num_pages, ResultOutOfMemory);
  1827. // Lock the table.
  1828. KScopedLightLock lk(m_general_lock);
  1829. // Find a random address to map at.
  1830. KProcessAddress addr = this->FindFreeArea(region_start, region_num_pages, num_pages, alignment,
  1831. 0, this->GetNumGuardPages());
  1832. R_UNLESS(addr != 0, ResultOutOfMemory);
  1833. ASSERT(Common::IsAligned(addr, alignment));
  1834. ASSERT(this->CanContain(addr, num_pages * PageSize, state));
  1835. ASSERT(this->CheckMemoryState(addr, num_pages * PageSize, KMemoryState::All, KMemoryState::Free,
  1836. KMemoryPermission::None, KMemoryPermission::None,
  1837. KMemoryAttribute::None, KMemoryAttribute::None) == ResultSuccess);
  1838. // Create an update allocator.
  1839. Result allocator_result;
  1840. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1841. m_memory_block_slab_manager);
  1842. R_TRY(allocator_result);
  1843. // We're going to perform an update, so create a helper.
  1844. KScopedPageTableUpdater updater(this);
  1845. // Perform mapping operation.
  1846. if (is_pa_valid) {
  1847. const KPageProperties properties = {perm, false, false, DisableMergeAttribute::DisableHead};
  1848. R_TRY(this->Operate(addr, num_pages, properties.perm, OperationType::Map, phys_addr));
  1849. } else {
  1850. R_TRY(this->AllocateAndMapPagesImpl(updater.GetPageList(), addr, num_pages, perm));
  1851. }
  1852. // Update the blocks.
  1853. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, state, perm,
  1854. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  1855. KMemoryBlockDisableMergeAttribute::None);
  1856. // We successfully mapped the pages.
  1857. *out_addr = addr;
  1858. R_SUCCEED();
  1859. }
  1860. Result KPageTable::MapPages(KProcessAddress address, size_t num_pages, KMemoryState state,
  1861. KMemoryPermission perm) {
  1862. // Check that the map is in range.
  1863. const size_t size = num_pages * PageSize;
  1864. R_UNLESS(this->CanContain(address, size, state), ResultInvalidCurrentMemory);
  1865. // Lock the table.
  1866. KScopedLightLock lk(m_general_lock);
  1867. // Check the memory state.
  1868. size_t num_allocator_blocks;
  1869. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), address, size,
  1870. KMemoryState::All, KMemoryState::Free, KMemoryPermission::None,
  1871. KMemoryPermission::None, KMemoryAttribute::None,
  1872. KMemoryAttribute::None));
  1873. // Create an update allocator.
  1874. Result allocator_result;
  1875. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1876. m_memory_block_slab_manager, num_allocator_blocks);
  1877. R_TRY(allocator_result);
  1878. // We're going to perform an update, so create a helper.
  1879. KScopedPageTableUpdater updater(this);
  1880. // Map the pages.
  1881. R_TRY(this->AllocateAndMapPagesImpl(updater.GetPageList(), address, num_pages, perm));
  1882. // Update the blocks.
  1883. m_memory_block_manager.Update(std::addressof(allocator), address, num_pages, state, perm,
  1884. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  1885. KMemoryBlockDisableMergeAttribute::None);
  1886. R_SUCCEED();
  1887. }
  1888. Result KPageTable::UnmapPages(KProcessAddress address, size_t num_pages, KMemoryState state) {
  1889. // Check that the unmap is in range.
  1890. const size_t size = num_pages * PageSize;
  1891. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  1892. // Lock the table.
  1893. KScopedLightLock lk(m_general_lock);
  1894. // Check the memory state.
  1895. size_t num_allocator_blocks;
  1896. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), address, size,
  1897. KMemoryState::All, state, KMemoryPermission::None,
  1898. KMemoryPermission::None, KMemoryAttribute::All,
  1899. KMemoryAttribute::None));
  1900. // Create an update allocator.
  1901. Result allocator_result;
  1902. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1903. m_memory_block_slab_manager, num_allocator_blocks);
  1904. R_TRY(allocator_result);
  1905. // We're going to perform an update, so create a helper.
  1906. KScopedPageTableUpdater updater(this);
  1907. // Perform the unmap.
  1908. const KPageProperties unmap_properties = {KMemoryPermission::None, false, false,
  1909. DisableMergeAttribute::None};
  1910. R_TRY(this->Operate(address, num_pages, unmap_properties.perm, OperationType::Unmap));
  1911. // Update the blocks.
  1912. m_memory_block_manager.Update(std::addressof(allocator), address, num_pages, KMemoryState::Free,
  1913. KMemoryPermission::None, KMemoryAttribute::None,
  1914. KMemoryBlockDisableMergeAttribute::None,
  1915. KMemoryBlockDisableMergeAttribute::Normal);
  1916. R_SUCCEED();
  1917. }
  1918. Result KPageTable::MapPageGroup(KProcessAddress* out_addr, const KPageGroup& pg,
  1919. KProcessAddress region_start, size_t region_num_pages,
  1920. KMemoryState state, KMemoryPermission perm) {
  1921. ASSERT(!this->IsLockedByCurrentThread());
  1922. // Ensure this is a valid map request.
  1923. const size_t num_pages = pg.GetNumPages();
  1924. R_UNLESS(this->CanContain(region_start, region_num_pages * PageSize, state),
  1925. ResultInvalidCurrentMemory);
  1926. R_UNLESS(num_pages < region_num_pages, ResultOutOfMemory);
  1927. // Lock the table.
  1928. KScopedLightLock lk(m_general_lock);
  1929. // Find a random address to map at.
  1930. KProcessAddress addr = this->FindFreeArea(region_start, region_num_pages, num_pages, PageSize,
  1931. 0, this->GetNumGuardPages());
  1932. R_UNLESS(addr != 0, ResultOutOfMemory);
  1933. ASSERT(this->CanContain(addr, num_pages * PageSize, state));
  1934. ASSERT(this->CheckMemoryState(addr, num_pages * PageSize, KMemoryState::All, KMemoryState::Free,
  1935. KMemoryPermission::None, KMemoryPermission::None,
  1936. KMemoryAttribute::None, KMemoryAttribute::None) == ResultSuccess);
  1937. // Create an update allocator.
  1938. Result allocator_result;
  1939. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1940. m_memory_block_slab_manager);
  1941. R_TRY(allocator_result);
  1942. // We're going to perform an update, so create a helper.
  1943. KScopedPageTableUpdater updater(this);
  1944. // Perform mapping operation.
  1945. const KPageProperties properties = {perm, state == KMemoryState::Io, false,
  1946. DisableMergeAttribute::DisableHead};
  1947. R_TRY(this->MapPageGroupImpl(updater.GetPageList(), addr, pg, properties, false));
  1948. // Update the blocks.
  1949. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, state, perm,
  1950. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  1951. KMemoryBlockDisableMergeAttribute::None);
  1952. // We successfully mapped the pages.
  1953. *out_addr = addr;
  1954. R_SUCCEED();
  1955. }
  1956. Result KPageTable::MapPageGroup(KProcessAddress addr, const KPageGroup& pg, KMemoryState state,
  1957. KMemoryPermission perm) {
  1958. ASSERT(!this->IsLockedByCurrentThread());
  1959. // Ensure this is a valid map request.
  1960. const size_t num_pages = pg.GetNumPages();
  1961. const size_t size = num_pages * PageSize;
  1962. R_UNLESS(this->CanContain(addr, size, state), ResultInvalidCurrentMemory);
  1963. // Lock the table.
  1964. KScopedLightLock lk(m_general_lock);
  1965. // Check if state allows us to map.
  1966. size_t num_allocator_blocks;
  1967. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), addr, size,
  1968. KMemoryState::All, KMemoryState::Free, KMemoryPermission::None,
  1969. KMemoryPermission::None, KMemoryAttribute::None,
  1970. KMemoryAttribute::None));
  1971. // Create an update allocator.
  1972. Result allocator_result;
  1973. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1974. m_memory_block_slab_manager, num_allocator_blocks);
  1975. R_TRY(allocator_result);
  1976. // We're going to perform an update, so create a helper.
  1977. KScopedPageTableUpdater updater(this);
  1978. // Perform mapping operation.
  1979. const KPageProperties properties = {perm, state == KMemoryState::Io, false,
  1980. DisableMergeAttribute::DisableHead};
  1981. R_TRY(this->MapPageGroupImpl(updater.GetPageList(), addr, pg, properties, false));
  1982. // Update the blocks.
  1983. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, state, perm,
  1984. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  1985. KMemoryBlockDisableMergeAttribute::None);
  1986. // We successfully mapped the pages.
  1987. R_SUCCEED();
  1988. }
  1989. Result KPageTable::UnmapPageGroup(KProcessAddress address, const KPageGroup& pg,
  1990. KMemoryState state) {
  1991. ASSERT(!this->IsLockedByCurrentThread());
  1992. // Ensure this is a valid unmap request.
  1993. const size_t num_pages = pg.GetNumPages();
  1994. const size_t size = num_pages * PageSize;
  1995. R_UNLESS(this->CanContain(address, size, state), ResultInvalidCurrentMemory);
  1996. // Lock the table.
  1997. KScopedLightLock lk(m_general_lock);
  1998. // Check if state allows us to unmap.
  1999. size_t num_allocator_blocks;
  2000. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), address, size,
  2001. KMemoryState::All, state, KMemoryPermission::None,
  2002. KMemoryPermission::None, KMemoryAttribute::All,
  2003. KMemoryAttribute::None));
  2004. // Check that the page group is valid.
  2005. R_UNLESS(this->IsValidPageGroup(pg, address, num_pages), ResultInvalidCurrentMemory);
  2006. // Create an update allocator.
  2007. Result allocator_result;
  2008. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2009. m_memory_block_slab_manager, num_allocator_blocks);
  2010. R_TRY(allocator_result);
  2011. // We're going to perform an update, so create a helper.
  2012. KScopedPageTableUpdater updater(this);
  2013. // Perform unmapping operation.
  2014. const KPageProperties properties = {KMemoryPermission::None, false, false,
  2015. DisableMergeAttribute::None};
  2016. R_TRY(this->Operate(address, num_pages, properties.perm, OperationType::Unmap));
  2017. // Update the blocks.
  2018. m_memory_block_manager.Update(std::addressof(allocator), address, num_pages, KMemoryState::Free,
  2019. KMemoryPermission::None, KMemoryAttribute::None,
  2020. KMemoryBlockDisableMergeAttribute::None,
  2021. KMemoryBlockDisableMergeAttribute::Normal);
  2022. R_SUCCEED();
  2023. }
  2024. Result KPageTable::MakeAndOpenPageGroup(KPageGroup* out, VAddr address, size_t num_pages,
  2025. KMemoryState state_mask, KMemoryState state,
  2026. KMemoryPermission perm_mask, KMemoryPermission perm,
  2027. KMemoryAttribute attr_mask, KMemoryAttribute attr) {
  2028. // Ensure that the page group isn't null.
  2029. ASSERT(out != nullptr);
  2030. // Make sure that the region we're mapping is valid for the table.
  2031. const size_t size = num_pages * PageSize;
  2032. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  2033. // Lock the table.
  2034. KScopedLightLock lk(m_general_lock);
  2035. // Check if state allows us to create the group.
  2036. R_TRY(this->CheckMemoryState(address, size, state_mask | KMemoryState::FlagReferenceCounted,
  2037. state | KMemoryState::FlagReferenceCounted, perm_mask, perm,
  2038. attr_mask, attr));
  2039. // Create a new page group for the region.
  2040. R_TRY(this->MakePageGroup(*out, address, num_pages));
  2041. R_SUCCEED();
  2042. }
  2043. Result KPageTable::SetProcessMemoryPermission(VAddr addr, size_t size,
  2044. Svc::MemoryPermission svc_perm) {
  2045. const size_t num_pages = size / PageSize;
  2046. // Lock the table.
  2047. KScopedLightLock lk(m_general_lock);
  2048. // Verify we can change the memory permission.
  2049. KMemoryState old_state;
  2050. KMemoryPermission old_perm;
  2051. size_t num_allocator_blocks;
  2052. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm), nullptr,
  2053. std::addressof(num_allocator_blocks), addr, size,
  2054. KMemoryState::FlagCode, KMemoryState::FlagCode,
  2055. KMemoryPermission::None, KMemoryPermission::None,
  2056. KMemoryAttribute::All, KMemoryAttribute::None));
  2057. // Determine new perm/state.
  2058. const KMemoryPermission new_perm = ConvertToKMemoryPermission(svc_perm);
  2059. KMemoryState new_state = old_state;
  2060. const bool is_w = (new_perm & KMemoryPermission::UserWrite) == KMemoryPermission::UserWrite;
  2061. const bool is_x = (new_perm & KMemoryPermission::UserExecute) == KMemoryPermission::UserExecute;
  2062. const bool was_x =
  2063. (old_perm & KMemoryPermission::UserExecute) == KMemoryPermission::UserExecute;
  2064. ASSERT(!(is_w && is_x));
  2065. if (is_w) {
  2066. switch (old_state) {
  2067. case KMemoryState::Code:
  2068. new_state = KMemoryState::CodeData;
  2069. break;
  2070. case KMemoryState::AliasCode:
  2071. new_state = KMemoryState::AliasCodeData;
  2072. break;
  2073. default:
  2074. ASSERT(false);
  2075. break;
  2076. }
  2077. }
  2078. // Succeed if there's nothing to do.
  2079. R_SUCCEED_IF(old_perm == new_perm && old_state == new_state);
  2080. // Create an update allocator.
  2081. Result allocator_result{ResultSuccess};
  2082. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2083. m_memory_block_slab_manager, num_allocator_blocks);
  2084. R_TRY(allocator_result);
  2085. // Perform mapping operation.
  2086. const auto operation =
  2087. was_x ? OperationType::ChangePermissionsAndRefresh : OperationType::ChangePermissions;
  2088. R_TRY(Operate(addr, num_pages, new_perm, operation));
  2089. // Update the blocks.
  2090. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, new_state, new_perm,
  2091. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  2092. KMemoryBlockDisableMergeAttribute::None);
  2093. // Ensure cache coherency, if we're setting pages as executable.
  2094. if (is_x) {
  2095. m_system.InvalidateCpuInstructionCacheRange(addr, size);
  2096. }
  2097. R_SUCCEED();
  2098. }
  2099. KMemoryInfo KPageTable::QueryInfoImpl(VAddr addr) {
  2100. KScopedLightLock lk(m_general_lock);
  2101. return m_memory_block_manager.FindBlock(addr)->GetMemoryInfo();
  2102. }
  2103. KMemoryInfo KPageTable::QueryInfo(VAddr addr) {
  2104. if (!Contains(addr, 1)) {
  2105. return {
  2106. .m_address = m_address_space_end,
  2107. .m_size = 0 - m_address_space_end,
  2108. .m_state = static_cast<KMemoryState>(Svc::MemoryState::Inaccessible),
  2109. .m_device_disable_merge_left_count = 0,
  2110. .m_device_disable_merge_right_count = 0,
  2111. .m_ipc_lock_count = 0,
  2112. .m_device_use_count = 0,
  2113. .m_ipc_disable_merge_count = 0,
  2114. .m_permission = KMemoryPermission::None,
  2115. .m_attribute = KMemoryAttribute::None,
  2116. .m_original_permission = KMemoryPermission::None,
  2117. .m_disable_merge_attribute = KMemoryBlockDisableMergeAttribute::None,
  2118. };
  2119. }
  2120. return QueryInfoImpl(addr);
  2121. }
  2122. Result KPageTable::SetMemoryPermission(VAddr addr, size_t size, Svc::MemoryPermission svc_perm) {
  2123. const size_t num_pages = size / PageSize;
  2124. // Lock the table.
  2125. KScopedLightLock lk(m_general_lock);
  2126. // Verify we can change the memory permission.
  2127. KMemoryState old_state;
  2128. KMemoryPermission old_perm;
  2129. size_t num_allocator_blocks;
  2130. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm), nullptr,
  2131. std::addressof(num_allocator_blocks), addr, size,
  2132. KMemoryState::FlagCanReprotect, KMemoryState::FlagCanReprotect,
  2133. KMemoryPermission::None, KMemoryPermission::None,
  2134. KMemoryAttribute::All, KMemoryAttribute::None));
  2135. // Determine new perm.
  2136. const KMemoryPermission new_perm = ConvertToKMemoryPermission(svc_perm);
  2137. R_SUCCEED_IF(old_perm == new_perm);
  2138. // Create an update allocator.
  2139. Result allocator_result{ResultSuccess};
  2140. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2141. m_memory_block_slab_manager, num_allocator_blocks);
  2142. R_TRY(allocator_result);
  2143. // Perform mapping operation.
  2144. R_TRY(Operate(addr, num_pages, new_perm, OperationType::ChangePermissions));
  2145. // Update the blocks.
  2146. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, new_perm,
  2147. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  2148. KMemoryBlockDisableMergeAttribute::None);
  2149. R_SUCCEED();
  2150. }
  2151. Result KPageTable::SetMemoryAttribute(VAddr addr, size_t size, u32 mask, u32 attr) {
  2152. const size_t num_pages = size / PageSize;
  2153. ASSERT((static_cast<KMemoryAttribute>(mask) | KMemoryAttribute::SetMask) ==
  2154. KMemoryAttribute::SetMask);
  2155. // Lock the table.
  2156. KScopedLightLock lk(m_general_lock);
  2157. // Verify we can change the memory attribute.
  2158. KMemoryState old_state;
  2159. KMemoryPermission old_perm;
  2160. KMemoryAttribute old_attr;
  2161. size_t num_allocator_blocks;
  2162. constexpr auto AttributeTestMask =
  2163. ~(KMemoryAttribute::SetMask | KMemoryAttribute::DeviceShared);
  2164. R_TRY(this->CheckMemoryState(
  2165. std::addressof(old_state), std::addressof(old_perm), std::addressof(old_attr),
  2166. std::addressof(num_allocator_blocks), addr, size, KMemoryState::FlagCanChangeAttribute,
  2167. KMemoryState::FlagCanChangeAttribute, KMemoryPermission::None, KMemoryPermission::None,
  2168. AttributeTestMask, KMemoryAttribute::None, ~AttributeTestMask));
  2169. // Create an update allocator.
  2170. Result allocator_result{ResultSuccess};
  2171. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2172. m_memory_block_slab_manager, num_allocator_blocks);
  2173. R_TRY(allocator_result);
  2174. // Determine the new attribute.
  2175. const KMemoryAttribute new_attr =
  2176. static_cast<KMemoryAttribute>(((old_attr & static_cast<KMemoryAttribute>(~mask)) |
  2177. static_cast<KMemoryAttribute>(attr & mask)));
  2178. // Perform operation.
  2179. this->Operate(addr, num_pages, old_perm, OperationType::ChangePermissionsAndRefresh);
  2180. // Update the blocks.
  2181. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, old_perm,
  2182. new_attr, KMemoryBlockDisableMergeAttribute::None,
  2183. KMemoryBlockDisableMergeAttribute::None);
  2184. R_SUCCEED();
  2185. }
  2186. Result KPageTable::SetMaxHeapSize(size_t size) {
  2187. // Lock the table.
  2188. KScopedLightLock lk(m_general_lock);
  2189. // Only process page tables are allowed to set heap size.
  2190. ASSERT(!this->IsKernel());
  2191. m_max_heap_size = size;
  2192. R_SUCCEED();
  2193. }
  2194. Result KPageTable::SetHeapSize(VAddr* out, size_t size) {
  2195. // Lock the physical memory mutex.
  2196. KScopedLightLock map_phys_mem_lk(m_map_physical_memory_lock);
  2197. // Try to perform a reduction in heap, instead of an extension.
  2198. VAddr cur_address{};
  2199. size_t allocation_size{};
  2200. {
  2201. // Lock the table.
  2202. KScopedLightLock lk(m_general_lock);
  2203. // Validate that setting heap size is possible at all.
  2204. R_UNLESS(!m_is_kernel, ResultOutOfMemory);
  2205. R_UNLESS(size <= static_cast<size_t>(m_heap_region_end - m_heap_region_start),
  2206. ResultOutOfMemory);
  2207. R_UNLESS(size <= m_max_heap_size, ResultOutOfMemory);
  2208. if (size < GetHeapSize()) {
  2209. // The size being requested is less than the current size, so we need to free the end of
  2210. // the heap.
  2211. // Validate memory state.
  2212. size_t num_allocator_blocks;
  2213. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks),
  2214. m_heap_region_start + size, GetHeapSize() - size,
  2215. KMemoryState::All, KMemoryState::Normal,
  2216. KMemoryPermission::All, KMemoryPermission::UserReadWrite,
  2217. KMemoryAttribute::All, KMemoryAttribute::None));
  2218. // Create an update allocator.
  2219. Result allocator_result{ResultSuccess};
  2220. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2221. m_memory_block_slab_manager,
  2222. num_allocator_blocks);
  2223. R_TRY(allocator_result);
  2224. // Unmap the end of the heap.
  2225. const auto num_pages = (GetHeapSize() - size) / PageSize;
  2226. R_TRY(Operate(m_heap_region_start + size, num_pages, KMemoryPermission::None,
  2227. OperationType::Unmap));
  2228. // Release the memory from the resource limit.
  2229. m_resource_limit->Release(LimitableResource::PhysicalMemoryMax, num_pages * PageSize);
  2230. // Apply the memory block update.
  2231. m_memory_block_manager.Update(std::addressof(allocator), m_heap_region_start + size,
  2232. num_pages, KMemoryState::Free, KMemoryPermission::None,
  2233. KMemoryAttribute::None,
  2234. KMemoryBlockDisableMergeAttribute::None,
  2235. size == 0 ? KMemoryBlockDisableMergeAttribute::Normal
  2236. : KMemoryBlockDisableMergeAttribute::None);
  2237. // Update the current heap end.
  2238. m_current_heap_end = m_heap_region_start + size;
  2239. // Set the output.
  2240. *out = m_heap_region_start;
  2241. R_SUCCEED();
  2242. } else if (size == GetHeapSize()) {
  2243. // The size requested is exactly the current size.
  2244. *out = m_heap_region_start;
  2245. R_SUCCEED();
  2246. } else {
  2247. // We have to allocate memory. Determine how much to allocate and where while the table
  2248. // is locked.
  2249. cur_address = m_current_heap_end;
  2250. allocation_size = size - GetHeapSize();
  2251. }
  2252. }
  2253. // Reserve memory for the heap extension.
  2254. KScopedResourceReservation memory_reservation(
  2255. m_resource_limit, LimitableResource::PhysicalMemoryMax, allocation_size);
  2256. R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
  2257. // Allocate pages for the heap extension.
  2258. KPageGroup pg{m_kernel, m_block_info_manager};
  2259. R_TRY(m_system.Kernel().MemoryManager().AllocateAndOpen(
  2260. &pg, allocation_size / PageSize,
  2261. KMemoryManager::EncodeOption(m_memory_pool, m_allocation_option)));
  2262. // Clear all the newly allocated pages.
  2263. for (const auto& it : pg) {
  2264. std::memset(m_system.DeviceMemory().GetPointer<void>(it.GetAddress()), m_heap_fill_value,
  2265. it.GetSize());
  2266. }
  2267. // Map the pages.
  2268. {
  2269. // Lock the table.
  2270. KScopedLightLock lk(m_general_lock);
  2271. // Ensure that the heap hasn't changed since we began executing.
  2272. ASSERT(cur_address == m_current_heap_end);
  2273. // Check the memory state.
  2274. size_t num_allocator_blocks{};
  2275. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), m_current_heap_end,
  2276. allocation_size, KMemoryState::All, KMemoryState::Free,
  2277. KMemoryPermission::None, KMemoryPermission::None,
  2278. KMemoryAttribute::None, KMemoryAttribute::None));
  2279. // Create an update allocator.
  2280. Result allocator_result{ResultSuccess};
  2281. KMemoryBlockManagerUpdateAllocator allocator(
  2282. std::addressof(allocator_result), m_memory_block_slab_manager, num_allocator_blocks);
  2283. R_TRY(allocator_result);
  2284. // Map the pages.
  2285. const auto num_pages = allocation_size / PageSize;
  2286. R_TRY(Operate(m_current_heap_end, num_pages, pg, OperationType::MapGroup));
  2287. // Clear all the newly allocated pages.
  2288. for (size_t cur_page = 0; cur_page < num_pages; ++cur_page) {
  2289. std::memset(m_system.Memory().GetPointer(m_current_heap_end + (cur_page * PageSize)), 0,
  2290. PageSize);
  2291. }
  2292. // We succeeded, so commit our memory reservation.
  2293. memory_reservation.Commit();
  2294. // Apply the memory block update.
  2295. m_memory_block_manager.Update(
  2296. std::addressof(allocator), m_current_heap_end, num_pages, KMemoryState::Normal,
  2297. KMemoryPermission::UserReadWrite, KMemoryAttribute::None,
  2298. m_heap_region_start == m_current_heap_end ? KMemoryBlockDisableMergeAttribute::Normal
  2299. : KMemoryBlockDisableMergeAttribute::None,
  2300. KMemoryBlockDisableMergeAttribute::None);
  2301. // Update the current heap end.
  2302. m_current_heap_end = m_heap_region_start + size;
  2303. // Set the output.
  2304. *out = m_heap_region_start;
  2305. R_SUCCEED();
  2306. }
  2307. }
  2308. Result KPageTable::LockForMapDeviceAddressSpace(bool* out_is_io, VAddr address, size_t size,
  2309. KMemoryPermission perm, bool is_aligned,
  2310. bool check_heap) {
  2311. // Lightly validate the range before doing anything else.
  2312. const size_t num_pages = size / PageSize;
  2313. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  2314. // Lock the table.
  2315. KScopedLightLock lk(m_general_lock);
  2316. // Check the memory state.
  2317. const auto test_state =
  2318. (is_aligned ? KMemoryState::FlagCanAlignedDeviceMap : KMemoryState::FlagCanDeviceMap) |
  2319. (check_heap ? KMemoryState::FlagReferenceCounted : KMemoryState::None);
  2320. size_t num_allocator_blocks;
  2321. KMemoryState old_state;
  2322. R_TRY(this->CheckMemoryState(std::addressof(old_state), nullptr, nullptr,
  2323. std::addressof(num_allocator_blocks), address, size, test_state,
  2324. test_state, perm, perm,
  2325. KMemoryAttribute::IpcLocked | KMemoryAttribute::Locked,
  2326. KMemoryAttribute::None, KMemoryAttribute::DeviceShared));
  2327. // Create an update allocator.
  2328. Result allocator_result;
  2329. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2330. m_memory_block_slab_manager, num_allocator_blocks);
  2331. R_TRY(allocator_result);
  2332. // Update the memory blocks.
  2333. m_memory_block_manager.UpdateLock(std::addressof(allocator), address, num_pages,
  2334. &KMemoryBlock::ShareToDevice, KMemoryPermission::None);
  2335. // Set whether the locked memory was io.
  2336. *out_is_io = old_state == KMemoryState::Io;
  2337. R_SUCCEED();
  2338. }
  2339. Result KPageTable::LockForUnmapDeviceAddressSpace(VAddr address, size_t size, bool check_heap) {
  2340. // Lightly validate the range before doing anything else.
  2341. const size_t num_pages = size / PageSize;
  2342. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  2343. // Lock the table.
  2344. KScopedLightLock lk(m_general_lock);
  2345. // Check the memory state.
  2346. const auto test_state = KMemoryState::FlagCanDeviceMap |
  2347. (check_heap ? KMemoryState::FlagReferenceCounted : KMemoryState::None);
  2348. size_t num_allocator_blocks;
  2349. R_TRY(this->CheckMemoryStateContiguous(
  2350. std::addressof(num_allocator_blocks), address, size, test_state, test_state,
  2351. KMemoryPermission::None, KMemoryPermission::None,
  2352. KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked, KMemoryAttribute::DeviceShared));
  2353. // Create an update allocator.
  2354. Result allocator_result;
  2355. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2356. m_memory_block_slab_manager, num_allocator_blocks);
  2357. R_TRY(allocator_result);
  2358. // Update the memory blocks.
  2359. const KMemoryBlockManager::MemoryBlockLockFunction lock_func =
  2360. m_enable_device_address_space_merge
  2361. ? &KMemoryBlock::UpdateDeviceDisableMergeStateForShare
  2362. : &KMemoryBlock::UpdateDeviceDisableMergeStateForShareRight;
  2363. m_memory_block_manager.UpdateLock(std::addressof(allocator), address, num_pages, lock_func,
  2364. KMemoryPermission::None);
  2365. R_SUCCEED();
  2366. }
  2367. Result KPageTable::UnlockForDeviceAddressSpace(VAddr address, size_t size) {
  2368. // Lightly validate the range before doing anything else.
  2369. const size_t num_pages = size / PageSize;
  2370. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  2371. // Lock the table.
  2372. KScopedLightLock lk(m_general_lock);
  2373. // Check the memory state.
  2374. size_t num_allocator_blocks;
  2375. R_TRY(this->CheckMemoryStateContiguous(
  2376. std::addressof(num_allocator_blocks), address, size, KMemoryState::FlagCanDeviceMap,
  2377. KMemoryState::FlagCanDeviceMap, KMemoryPermission::None, KMemoryPermission::None,
  2378. KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked, KMemoryAttribute::DeviceShared));
  2379. // Create an update allocator.
  2380. Result allocator_result{ResultSuccess};
  2381. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2382. m_memory_block_slab_manager, num_allocator_blocks);
  2383. R_TRY(allocator_result);
  2384. // Update the memory blocks.
  2385. m_memory_block_manager.UpdateLock(std::addressof(allocator), address, num_pages,
  2386. &KMemoryBlock::UnshareToDevice, KMemoryPermission::None);
  2387. R_SUCCEED();
  2388. }
  2389. Result KPageTable::LockForIpcUserBuffer(PAddr* out, VAddr address, size_t size) {
  2390. R_RETURN(this->LockMemoryAndOpen(
  2391. nullptr, out, address, size, KMemoryState::FlagCanIpcUserBuffer,
  2392. KMemoryState::FlagCanIpcUserBuffer, KMemoryPermission::All,
  2393. KMemoryPermission::UserReadWrite, KMemoryAttribute::All, KMemoryAttribute::None,
  2394. KMemoryPermission::NotMapped | KMemoryPermission::KernelReadWrite,
  2395. KMemoryAttribute::Locked));
  2396. }
  2397. Result KPageTable::UnlockForIpcUserBuffer(VAddr address, size_t size) {
  2398. R_RETURN(this->UnlockMemory(address, size, KMemoryState::FlagCanIpcUserBuffer,
  2399. KMemoryState::FlagCanIpcUserBuffer, KMemoryPermission::None,
  2400. KMemoryPermission::None, KMemoryAttribute::All,
  2401. KMemoryAttribute::Locked, KMemoryPermission::UserReadWrite,
  2402. KMemoryAttribute::Locked, nullptr));
  2403. }
  2404. Result KPageTable::LockForCodeMemory(KPageGroup* out, VAddr addr, size_t size) {
  2405. R_RETURN(this->LockMemoryAndOpen(
  2406. out, nullptr, addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory,
  2407. KMemoryPermission::All, KMemoryPermission::UserReadWrite, KMemoryAttribute::All,
  2408. KMemoryAttribute::None, KMemoryPermission::NotMapped | KMemoryPermission::KernelReadWrite,
  2409. KMemoryAttribute::Locked));
  2410. }
  2411. Result KPageTable::UnlockForCodeMemory(VAddr addr, size_t size, const KPageGroup& pg) {
  2412. R_RETURN(this->UnlockMemory(
  2413. addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory,
  2414. KMemoryPermission::None, KMemoryPermission::None, KMemoryAttribute::All,
  2415. KMemoryAttribute::Locked, KMemoryPermission::UserReadWrite, KMemoryAttribute::Locked, &pg));
  2416. }
  2417. bool KPageTable::IsRegionContiguous(VAddr addr, u64 size) const {
  2418. auto start_ptr = m_system.DeviceMemory().GetPointer<u8>(addr);
  2419. for (u64 offset{}; offset < size; offset += PageSize) {
  2420. if (start_ptr != m_system.DeviceMemory().GetPointer<u8>(addr + offset)) {
  2421. return false;
  2422. }
  2423. start_ptr += PageSize;
  2424. }
  2425. return true;
  2426. }
  2427. void KPageTable::AddRegionToPages(VAddr start, size_t num_pages, KPageGroup& page_linked_list) {
  2428. VAddr addr{start};
  2429. while (addr < start + (num_pages * PageSize)) {
  2430. const PAddr paddr{GetPhysicalAddr(addr)};
  2431. ASSERT(paddr != 0);
  2432. page_linked_list.AddBlock(paddr, 1);
  2433. addr += PageSize;
  2434. }
  2435. }
  2436. VAddr KPageTable::AllocateVirtualMemory(VAddr start, size_t region_num_pages, u64 needed_num_pages,
  2437. size_t align) {
  2438. if (m_enable_aslr) {
  2439. UNIMPLEMENTED();
  2440. }
  2441. return m_memory_block_manager.FindFreeArea(start, region_num_pages, needed_num_pages, align, 0,
  2442. IsKernel() ? 1 : 4);
  2443. }
  2444. Result KPageTable::Operate(VAddr addr, size_t num_pages, const KPageGroup& page_group,
  2445. OperationType operation) {
  2446. ASSERT(this->IsLockedByCurrentThread());
  2447. ASSERT(Common::IsAligned(addr, PageSize));
  2448. ASSERT(num_pages > 0);
  2449. ASSERT(num_pages == page_group.GetNumPages());
  2450. switch (operation) {
  2451. case OperationType::MapGroup: {
  2452. // We want to maintain a new reference to every page in the group.
  2453. KScopedPageGroup spg(page_group);
  2454. for (const auto& node : page_group) {
  2455. const size_t size{node.GetNumPages() * PageSize};
  2456. // Map the pages.
  2457. m_system.Memory().MapMemoryRegion(*m_page_table_impl, addr, size, node.GetAddress());
  2458. addr += size;
  2459. }
  2460. // We succeeded! We want to persist the reference to the pages.
  2461. spg.CancelClose();
  2462. break;
  2463. }
  2464. default:
  2465. ASSERT(false);
  2466. break;
  2467. }
  2468. R_SUCCEED();
  2469. }
  2470. Result KPageTable::Operate(VAddr addr, size_t num_pages, KMemoryPermission perm,
  2471. OperationType operation, PAddr map_addr) {
  2472. ASSERT(this->IsLockedByCurrentThread());
  2473. ASSERT(num_pages > 0);
  2474. ASSERT(Common::IsAligned(addr, PageSize));
  2475. ASSERT(ContainsPages(addr, num_pages));
  2476. switch (operation) {
  2477. case OperationType::Unmap: {
  2478. // Ensure that any pages we track close on exit.
  2479. KPageGroup pages_to_close{m_kernel, this->GetBlockInfoManager()};
  2480. SCOPE_EXIT({ pages_to_close.CloseAndReset(); });
  2481. this->AddRegionToPages(addr, num_pages, pages_to_close);
  2482. m_system.Memory().UnmapRegion(*m_page_table_impl, addr, num_pages * PageSize);
  2483. break;
  2484. }
  2485. case OperationType::MapFirst:
  2486. case OperationType::Map: {
  2487. ASSERT(map_addr);
  2488. ASSERT(Common::IsAligned(map_addr, PageSize));
  2489. m_system.Memory().MapMemoryRegion(*m_page_table_impl, addr, num_pages * PageSize, map_addr);
  2490. // Open references to pages, if we should.
  2491. if (IsHeapPhysicalAddress(m_kernel.MemoryLayout(), map_addr)) {
  2492. if (operation == OperationType::MapFirst) {
  2493. m_kernel.MemoryManager().OpenFirst(map_addr, num_pages);
  2494. } else {
  2495. m_kernel.MemoryManager().Open(map_addr, num_pages);
  2496. }
  2497. }
  2498. break;
  2499. }
  2500. case OperationType::Separate: {
  2501. // HACK: Unimplemented.
  2502. break;
  2503. }
  2504. case OperationType::ChangePermissions:
  2505. case OperationType::ChangePermissionsAndRefresh:
  2506. break;
  2507. default:
  2508. ASSERT(false);
  2509. break;
  2510. }
  2511. R_SUCCEED();
  2512. }
  2513. void KPageTable::FinalizeUpdate(PageLinkedList* page_list) {
  2514. while (page_list->Peek()) {
  2515. [[maybe_unused]] auto page = page_list->Pop();
  2516. // TODO(bunnei): Free pages once they are allocated in guest memory
  2517. // ASSERT(this->GetPageTableManager().IsInPageTableHeap(page));
  2518. // ASSERT(this->GetPageTableManager().GetRefCount(page) == 0);
  2519. // this->GetPageTableManager().Free(page);
  2520. }
  2521. }
  2522. VAddr KPageTable::GetRegionAddress(KMemoryState state) const {
  2523. switch (state) {
  2524. case KMemoryState::Free:
  2525. case KMemoryState::Kernel:
  2526. return m_address_space_start;
  2527. case KMemoryState::Normal:
  2528. return m_heap_region_start;
  2529. case KMemoryState::Ipc:
  2530. case KMemoryState::NonSecureIpc:
  2531. case KMemoryState::NonDeviceIpc:
  2532. return m_alias_region_start;
  2533. case KMemoryState::Stack:
  2534. return m_stack_region_start;
  2535. case KMemoryState::Static:
  2536. case KMemoryState::ThreadLocal:
  2537. return m_kernel_map_region_start;
  2538. case KMemoryState::Io:
  2539. case KMemoryState::Shared:
  2540. case KMemoryState::AliasCode:
  2541. case KMemoryState::AliasCodeData:
  2542. case KMemoryState::Transfered:
  2543. case KMemoryState::SharedTransfered:
  2544. case KMemoryState::SharedCode:
  2545. case KMemoryState::GeneratedCode:
  2546. case KMemoryState::CodeOut:
  2547. case KMemoryState::Coverage:
  2548. case KMemoryState::Insecure:
  2549. return m_alias_code_region_start;
  2550. case KMemoryState::Code:
  2551. case KMemoryState::CodeData:
  2552. return m_code_region_start;
  2553. default:
  2554. UNREACHABLE();
  2555. }
  2556. }
  2557. size_t KPageTable::GetRegionSize(KMemoryState state) const {
  2558. switch (state) {
  2559. case KMemoryState::Free:
  2560. case KMemoryState::Kernel:
  2561. return m_address_space_end - m_address_space_start;
  2562. case KMemoryState::Normal:
  2563. return m_heap_region_end - m_heap_region_start;
  2564. case KMemoryState::Ipc:
  2565. case KMemoryState::NonSecureIpc:
  2566. case KMemoryState::NonDeviceIpc:
  2567. return m_alias_region_end - m_alias_region_start;
  2568. case KMemoryState::Stack:
  2569. return m_stack_region_end - m_stack_region_start;
  2570. case KMemoryState::Static:
  2571. case KMemoryState::ThreadLocal:
  2572. return m_kernel_map_region_end - m_kernel_map_region_start;
  2573. case KMemoryState::Io:
  2574. case KMemoryState::Shared:
  2575. case KMemoryState::AliasCode:
  2576. case KMemoryState::AliasCodeData:
  2577. case KMemoryState::Transfered:
  2578. case KMemoryState::SharedTransfered:
  2579. case KMemoryState::SharedCode:
  2580. case KMemoryState::GeneratedCode:
  2581. case KMemoryState::CodeOut:
  2582. case KMemoryState::Coverage:
  2583. case KMemoryState::Insecure:
  2584. return m_alias_code_region_end - m_alias_code_region_start;
  2585. case KMemoryState::Code:
  2586. case KMemoryState::CodeData:
  2587. return m_code_region_end - m_code_region_start;
  2588. default:
  2589. UNREACHABLE();
  2590. }
  2591. }
  2592. bool KPageTable::CanContain(VAddr addr, size_t size, KMemoryState state) const {
  2593. const VAddr end = addr + size;
  2594. const VAddr last = end - 1;
  2595. const VAddr region_start = this->GetRegionAddress(state);
  2596. const size_t region_size = this->GetRegionSize(state);
  2597. const bool is_in_region =
  2598. region_start <= addr && addr < end && last <= region_start + region_size - 1;
  2599. const bool is_in_heap = !(end <= m_heap_region_start || m_heap_region_end <= addr ||
  2600. m_heap_region_start == m_heap_region_end);
  2601. const bool is_in_alias = !(end <= m_alias_region_start || m_alias_region_end <= addr ||
  2602. m_alias_region_start == m_alias_region_end);
  2603. switch (state) {
  2604. case KMemoryState::Free:
  2605. case KMemoryState::Kernel:
  2606. return is_in_region;
  2607. case KMemoryState::Io:
  2608. case KMemoryState::Static:
  2609. case KMemoryState::Code:
  2610. case KMemoryState::CodeData:
  2611. case KMemoryState::Shared:
  2612. case KMemoryState::AliasCode:
  2613. case KMemoryState::AliasCodeData:
  2614. case KMemoryState::Stack:
  2615. case KMemoryState::ThreadLocal:
  2616. case KMemoryState::Transfered:
  2617. case KMemoryState::SharedTransfered:
  2618. case KMemoryState::SharedCode:
  2619. case KMemoryState::GeneratedCode:
  2620. case KMemoryState::CodeOut:
  2621. case KMemoryState::Coverage:
  2622. case KMemoryState::Insecure:
  2623. return is_in_region && !is_in_heap && !is_in_alias;
  2624. case KMemoryState::Normal:
  2625. ASSERT(is_in_heap);
  2626. return is_in_region && !is_in_alias;
  2627. case KMemoryState::Ipc:
  2628. case KMemoryState::NonSecureIpc:
  2629. case KMemoryState::NonDeviceIpc:
  2630. ASSERT(is_in_alias);
  2631. return is_in_region && !is_in_heap;
  2632. default:
  2633. return false;
  2634. }
  2635. }
  2636. Result KPageTable::CheckMemoryState(const KMemoryInfo& info, KMemoryState state_mask,
  2637. KMemoryState state, KMemoryPermission perm_mask,
  2638. KMemoryPermission perm, KMemoryAttribute attr_mask,
  2639. KMemoryAttribute attr) const {
  2640. // Validate the states match expectation.
  2641. R_UNLESS((info.m_state & state_mask) == state, ResultInvalidCurrentMemory);
  2642. R_UNLESS((info.m_permission & perm_mask) == perm, ResultInvalidCurrentMemory);
  2643. R_UNLESS((info.m_attribute & attr_mask) == attr, ResultInvalidCurrentMemory);
  2644. R_SUCCEED();
  2645. }
  2646. Result KPageTable::CheckMemoryStateContiguous(size_t* out_blocks_needed, VAddr addr, size_t size,
  2647. KMemoryState state_mask, KMemoryState state,
  2648. KMemoryPermission perm_mask, KMemoryPermission perm,
  2649. KMemoryAttribute attr_mask,
  2650. KMemoryAttribute attr) const {
  2651. ASSERT(this->IsLockedByCurrentThread());
  2652. // Get information about the first block.
  2653. const VAddr last_addr = addr + size - 1;
  2654. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(addr);
  2655. KMemoryInfo info = it->GetMemoryInfo();
  2656. // If the start address isn't aligned, we need a block.
  2657. const size_t blocks_for_start_align =
  2658. (Common::AlignDown(addr, PageSize) != info.GetAddress()) ? 1 : 0;
  2659. while (true) {
  2660. // Validate against the provided masks.
  2661. R_TRY(this->CheckMemoryState(info, state_mask, state, perm_mask, perm, attr_mask, attr));
  2662. // Break once we're done.
  2663. if (last_addr <= info.GetLastAddress()) {
  2664. break;
  2665. }
  2666. // Advance our iterator.
  2667. it++;
  2668. ASSERT(it != m_memory_block_manager.cend());
  2669. info = it->GetMemoryInfo();
  2670. }
  2671. // If the end address isn't aligned, we need a block.
  2672. const size_t blocks_for_end_align =
  2673. (Common::AlignUp(addr + size, PageSize) != info.GetEndAddress()) ? 1 : 0;
  2674. if (out_blocks_needed != nullptr) {
  2675. *out_blocks_needed = blocks_for_start_align + blocks_for_end_align;
  2676. }
  2677. R_SUCCEED();
  2678. }
  2679. Result KPageTable::CheckMemoryState(KMemoryState* out_state, KMemoryPermission* out_perm,
  2680. KMemoryAttribute* out_attr, size_t* out_blocks_needed,
  2681. VAddr addr, size_t size, KMemoryState state_mask,
  2682. KMemoryState state, KMemoryPermission perm_mask,
  2683. KMemoryPermission perm, KMemoryAttribute attr_mask,
  2684. KMemoryAttribute attr, KMemoryAttribute ignore_attr) const {
  2685. ASSERT(this->IsLockedByCurrentThread());
  2686. // Get information about the first block.
  2687. const VAddr last_addr = addr + size - 1;
  2688. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(addr);
  2689. KMemoryInfo info = it->GetMemoryInfo();
  2690. // If the start address isn't aligned, we need a block.
  2691. const size_t blocks_for_start_align =
  2692. (Common::AlignDown(addr, PageSize) != info.GetAddress()) ? 1 : 0;
  2693. // Validate all blocks in the range have correct state.
  2694. const KMemoryState first_state = info.m_state;
  2695. const KMemoryPermission first_perm = info.m_permission;
  2696. const KMemoryAttribute first_attr = info.m_attribute;
  2697. while (true) {
  2698. // Validate the current block.
  2699. R_UNLESS(info.m_state == first_state, ResultInvalidCurrentMemory);
  2700. R_UNLESS(info.m_permission == first_perm, ResultInvalidCurrentMemory);
  2701. R_UNLESS((info.m_attribute | ignore_attr) == (first_attr | ignore_attr),
  2702. ResultInvalidCurrentMemory);
  2703. // Validate against the provided masks.
  2704. R_TRY(this->CheckMemoryState(info, state_mask, state, perm_mask, perm, attr_mask, attr));
  2705. // Break once we're done.
  2706. if (last_addr <= info.GetLastAddress()) {
  2707. break;
  2708. }
  2709. // Advance our iterator.
  2710. it++;
  2711. ASSERT(it != m_memory_block_manager.cend());
  2712. info = it->GetMemoryInfo();
  2713. }
  2714. // If the end address isn't aligned, we need a block.
  2715. const size_t blocks_for_end_align =
  2716. (Common::AlignUp(addr + size, PageSize) != info.GetEndAddress()) ? 1 : 0;
  2717. // Write output state.
  2718. if (out_state != nullptr) {
  2719. *out_state = first_state;
  2720. }
  2721. if (out_perm != nullptr) {
  2722. *out_perm = first_perm;
  2723. }
  2724. if (out_attr != nullptr) {
  2725. *out_attr = static_cast<KMemoryAttribute>(first_attr & ~ignore_attr);
  2726. }
  2727. if (out_blocks_needed != nullptr) {
  2728. *out_blocks_needed = blocks_for_start_align + blocks_for_end_align;
  2729. }
  2730. R_SUCCEED();
  2731. }
  2732. Result KPageTable::LockMemoryAndOpen(KPageGroup* out_pg, PAddr* out_paddr, VAddr addr, size_t size,
  2733. KMemoryState state_mask, KMemoryState state,
  2734. KMemoryPermission perm_mask, KMemoryPermission perm,
  2735. KMemoryAttribute attr_mask, KMemoryAttribute attr,
  2736. KMemoryPermission new_perm, KMemoryAttribute lock_attr) {
  2737. // Validate basic preconditions.
  2738. ASSERT((lock_attr & attr) == KMemoryAttribute::None);
  2739. ASSERT((lock_attr & (KMemoryAttribute::IpcLocked | KMemoryAttribute::DeviceShared)) ==
  2740. KMemoryAttribute::None);
  2741. // Validate the lock request.
  2742. const size_t num_pages = size / PageSize;
  2743. R_UNLESS(this->Contains(addr, size), ResultInvalidCurrentMemory);
  2744. // Lock the table.
  2745. KScopedLightLock lk(m_general_lock);
  2746. // Check that the output page group is empty, if it exists.
  2747. if (out_pg) {
  2748. ASSERT(out_pg->GetNumPages() == 0);
  2749. }
  2750. // Check the state.
  2751. KMemoryState old_state{};
  2752. KMemoryPermission old_perm{};
  2753. KMemoryAttribute old_attr{};
  2754. size_t num_allocator_blocks{};
  2755. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm),
  2756. std::addressof(old_attr), std::addressof(num_allocator_blocks),
  2757. addr, size, state_mask | KMemoryState::FlagReferenceCounted,
  2758. state | KMemoryState::FlagReferenceCounted, perm_mask, perm,
  2759. attr_mask, attr));
  2760. // Get the physical address, if we're supposed to.
  2761. if (out_paddr != nullptr) {
  2762. ASSERT(this->GetPhysicalAddressLocked(out_paddr, addr));
  2763. }
  2764. // Make the page group, if we're supposed to.
  2765. if (out_pg != nullptr) {
  2766. R_TRY(this->MakePageGroup(*out_pg, addr, num_pages));
  2767. }
  2768. // Create an update allocator.
  2769. Result allocator_result{ResultSuccess};
  2770. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2771. m_memory_block_slab_manager, num_allocator_blocks);
  2772. R_TRY(allocator_result);
  2773. // Decide on new perm and attr.
  2774. new_perm = (new_perm != KMemoryPermission::None) ? new_perm : old_perm;
  2775. KMemoryAttribute new_attr = static_cast<KMemoryAttribute>(old_attr | lock_attr);
  2776. // Update permission, if we need to.
  2777. if (new_perm != old_perm) {
  2778. R_TRY(Operate(addr, num_pages, new_perm, OperationType::ChangePermissions));
  2779. }
  2780. // Apply the memory block updates.
  2781. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, new_perm,
  2782. new_attr, KMemoryBlockDisableMergeAttribute::Locked,
  2783. KMemoryBlockDisableMergeAttribute::None);
  2784. R_SUCCEED();
  2785. }
  2786. Result KPageTable::UnlockMemory(VAddr addr, size_t size, KMemoryState state_mask,
  2787. KMemoryState state, KMemoryPermission perm_mask,
  2788. KMemoryPermission perm, KMemoryAttribute attr_mask,
  2789. KMemoryAttribute attr, KMemoryPermission new_perm,
  2790. KMemoryAttribute lock_attr, const KPageGroup* pg) {
  2791. // Validate basic preconditions.
  2792. ASSERT((attr_mask & lock_attr) == lock_attr);
  2793. ASSERT((attr & lock_attr) == lock_attr);
  2794. // Validate the unlock request.
  2795. const size_t num_pages = size / PageSize;
  2796. R_UNLESS(this->Contains(addr, size), ResultInvalidCurrentMemory);
  2797. // Lock the table.
  2798. KScopedLightLock lk(m_general_lock);
  2799. // Check the state.
  2800. KMemoryState old_state{};
  2801. KMemoryPermission old_perm{};
  2802. KMemoryAttribute old_attr{};
  2803. size_t num_allocator_blocks{};
  2804. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm),
  2805. std::addressof(old_attr), std::addressof(num_allocator_blocks),
  2806. addr, size, state_mask | KMemoryState::FlagReferenceCounted,
  2807. state | KMemoryState::FlagReferenceCounted, perm_mask, perm,
  2808. attr_mask, attr));
  2809. // Check the page group.
  2810. if (pg != nullptr) {
  2811. R_UNLESS(this->IsValidPageGroup(*pg, addr, num_pages), ResultInvalidMemoryRegion);
  2812. }
  2813. // Decide on new perm and attr.
  2814. new_perm = (new_perm != KMemoryPermission::None) ? new_perm : old_perm;
  2815. KMemoryAttribute new_attr = static_cast<KMemoryAttribute>(old_attr & ~lock_attr);
  2816. // Create an update allocator.
  2817. Result allocator_result{ResultSuccess};
  2818. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2819. m_memory_block_slab_manager, num_allocator_blocks);
  2820. R_TRY(allocator_result);
  2821. // Update permission, if we need to.
  2822. if (new_perm != old_perm) {
  2823. R_TRY(Operate(addr, num_pages, new_perm, OperationType::ChangePermissions));
  2824. }
  2825. // Apply the memory block updates.
  2826. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, new_perm,
  2827. new_attr, KMemoryBlockDisableMergeAttribute::None,
  2828. KMemoryBlockDisableMergeAttribute::Locked);
  2829. R_SUCCEED();
  2830. }
  2831. } // namespace Kernel