k_page_table.cpp 131 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212
  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_} {}
  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;
  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;
  372. AddRegionToPages(src_address, num_pages, pg);
  373. // Reprotect the source as kernel-read/not mapped.
  374. const auto new_perm = static_cast<KMemoryPermission>(KMemoryPermission::KernelRead |
  375. KMemoryPermission::NotMapped);
  376. R_TRY(Operate(src_address, num_pages, new_perm, OperationType::ChangePermissions));
  377. // Ensure that we unprotect the source pages on failure.
  378. auto unprot_guard = SCOPE_GUARD({
  379. ASSERT(this->Operate(src_address, num_pages, src_perm, OperationType::ChangePermissions)
  380. .IsSuccess());
  381. });
  382. // Map the alias pages.
  383. R_TRY(MapPages(dst_address, pg, new_perm));
  384. // We successfully mapped the alias pages, so we don't need to unprotect the src pages on
  385. // failure.
  386. unprot_guard.Cancel();
  387. // Apply the memory block updates.
  388. m_memory_block_manager.Update(std::addressof(src_allocator), src_address, num_pages,
  389. src_state, new_perm, KMemoryAttribute::Locked,
  390. KMemoryBlockDisableMergeAttribute::Locked,
  391. KMemoryBlockDisableMergeAttribute::None);
  392. m_memory_block_manager.Update(std::addressof(dst_allocator), dst_address, num_pages,
  393. KMemoryState::AliasCode, new_perm, KMemoryAttribute::None,
  394. KMemoryBlockDisableMergeAttribute::Normal,
  395. KMemoryBlockDisableMergeAttribute::None);
  396. }
  397. R_SUCCEED();
  398. }
  399. Result KPageTable::UnmapCodeMemory(VAddr dst_address, VAddr src_address, size_t size,
  400. ICacheInvalidationStrategy icache_invalidation_strategy) {
  401. // Validate the mapping request.
  402. R_UNLESS(this->CanContain(dst_address, size, KMemoryState::AliasCode),
  403. ResultInvalidMemoryRegion);
  404. // Lock the table.
  405. KScopedLightLock lk(m_general_lock);
  406. // Verify that the source memory is locked normal heap.
  407. size_t num_src_allocator_blocks{};
  408. R_TRY(this->CheckMemoryState(std::addressof(num_src_allocator_blocks), src_address, size,
  409. KMemoryState::All, KMemoryState::Normal, KMemoryPermission::None,
  410. KMemoryPermission::None, KMemoryAttribute::All,
  411. KMemoryAttribute::Locked));
  412. // Verify that the destination memory is aliasable code.
  413. size_t num_dst_allocator_blocks{};
  414. R_TRY(this->CheckMemoryStateContiguous(
  415. std::addressof(num_dst_allocator_blocks), dst_address, size, KMemoryState::FlagCanCodeAlias,
  416. KMemoryState::FlagCanCodeAlias, KMemoryPermission::None, KMemoryPermission::None,
  417. KMemoryAttribute::All, KMemoryAttribute::None));
  418. // Determine whether any pages being unmapped are code.
  419. bool any_code_pages = false;
  420. {
  421. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(dst_address);
  422. while (true) {
  423. // Get the memory info.
  424. const KMemoryInfo info = it->GetMemoryInfo();
  425. // Check if the memory has code flag.
  426. if ((info.GetState() & KMemoryState::FlagCode) != KMemoryState::None) {
  427. any_code_pages = true;
  428. break;
  429. }
  430. // Check if we're done.
  431. if (dst_address + size - 1 <= info.GetLastAddress()) {
  432. break;
  433. }
  434. // Advance.
  435. ++it;
  436. }
  437. }
  438. // Ensure that we maintain the instruction cache.
  439. bool reprotected_pages = false;
  440. SCOPE_EXIT({
  441. if (reprotected_pages && any_code_pages) {
  442. if (icache_invalidation_strategy == ICacheInvalidationStrategy::InvalidateRange) {
  443. m_system.InvalidateCpuInstructionCacheRange(dst_address, size);
  444. } else {
  445. m_system.InvalidateCpuInstructionCaches();
  446. }
  447. }
  448. });
  449. // Unmap.
  450. {
  451. // Determine the number of pages being operated on.
  452. const size_t num_pages = size / PageSize;
  453. // Create an update allocator for the source.
  454. Result src_allocator_result{ResultSuccess};
  455. KMemoryBlockManagerUpdateAllocator src_allocator(std::addressof(src_allocator_result),
  456. m_memory_block_slab_manager,
  457. num_src_allocator_blocks);
  458. R_TRY(src_allocator_result);
  459. // Create an update allocator for the destination.
  460. Result dst_allocator_result{ResultSuccess};
  461. KMemoryBlockManagerUpdateAllocator dst_allocator(std::addressof(dst_allocator_result),
  462. m_memory_block_slab_manager,
  463. num_dst_allocator_blocks);
  464. R_TRY(dst_allocator_result);
  465. // Unmap the aliased copy of the pages.
  466. R_TRY(Operate(dst_address, num_pages, KMemoryPermission::None, OperationType::Unmap));
  467. // Try to set the permissions for the source pages back to what they should be.
  468. R_TRY(Operate(src_address, num_pages, KMemoryPermission::UserReadWrite,
  469. OperationType::ChangePermissions));
  470. // Apply the memory block updates.
  471. m_memory_block_manager.Update(
  472. std::addressof(dst_allocator), dst_address, num_pages, KMemoryState::None,
  473. KMemoryPermission::None, KMemoryAttribute::None,
  474. KMemoryBlockDisableMergeAttribute::None, KMemoryBlockDisableMergeAttribute::Normal);
  475. m_memory_block_manager.Update(
  476. std::addressof(src_allocator), src_address, num_pages, KMemoryState::Normal,
  477. KMemoryPermission::UserReadWrite, KMemoryAttribute::None,
  478. KMemoryBlockDisableMergeAttribute::None, KMemoryBlockDisableMergeAttribute::Locked);
  479. // Note that we reprotected pages.
  480. reprotected_pages = true;
  481. }
  482. R_SUCCEED();
  483. }
  484. VAddr KPageTable::FindFreeArea(VAddr region_start, size_t region_num_pages, size_t num_pages,
  485. size_t alignment, size_t offset, size_t guard_pages) {
  486. VAddr address = 0;
  487. if (num_pages <= region_num_pages) {
  488. if (this->IsAslrEnabled()) {
  489. UNIMPLEMENTED();
  490. }
  491. // Find the first free area.
  492. if (address == 0) {
  493. address = m_memory_block_manager.FindFreeArea(region_start, region_num_pages, num_pages,
  494. alignment, offset, guard_pages);
  495. }
  496. }
  497. return address;
  498. }
  499. Result KPageTable::MakePageGroup(KPageGroup& pg, VAddr addr, size_t num_pages) {
  500. ASSERT(this->IsLockedByCurrentThread());
  501. const size_t size = num_pages * PageSize;
  502. // We're making a new group, not adding to an existing one.
  503. R_UNLESS(pg.Empty(), ResultInvalidCurrentMemory);
  504. // Begin traversal.
  505. Common::PageTable::TraversalContext context;
  506. Common::PageTable::TraversalEntry next_entry;
  507. R_UNLESS(m_page_table_impl->BeginTraversal(next_entry, context, addr),
  508. ResultInvalidCurrentMemory);
  509. // Prepare tracking variables.
  510. PAddr cur_addr = next_entry.phys_addr;
  511. size_t cur_size = next_entry.block_size - (cur_addr & (next_entry.block_size - 1));
  512. size_t tot_size = cur_size;
  513. // Iterate, adding to group as we go.
  514. const auto& memory_layout = m_system.Kernel().MemoryLayout();
  515. while (tot_size < size) {
  516. R_UNLESS(m_page_table_impl->ContinueTraversal(next_entry, context),
  517. ResultInvalidCurrentMemory);
  518. if (next_entry.phys_addr != (cur_addr + cur_size)) {
  519. const size_t cur_pages = cur_size / PageSize;
  520. R_UNLESS(IsHeapPhysicalAddress(memory_layout, cur_addr), ResultInvalidCurrentMemory);
  521. R_TRY(pg.AddBlock(cur_addr, cur_pages));
  522. cur_addr = next_entry.phys_addr;
  523. cur_size = next_entry.block_size;
  524. } else {
  525. cur_size += next_entry.block_size;
  526. }
  527. tot_size += next_entry.block_size;
  528. }
  529. // Ensure we add the right amount for the last block.
  530. if (tot_size > size) {
  531. cur_size -= (tot_size - size);
  532. }
  533. // Add the last block.
  534. const size_t cur_pages = cur_size / PageSize;
  535. R_UNLESS(IsHeapPhysicalAddress(memory_layout, cur_addr), ResultInvalidCurrentMemory);
  536. R_TRY(pg.AddBlock(cur_addr, cur_pages));
  537. R_SUCCEED();
  538. }
  539. bool KPageTable::IsValidPageGroup(const KPageGroup& pg_ll, VAddr addr, size_t num_pages) {
  540. ASSERT(this->IsLockedByCurrentThread());
  541. const size_t size = num_pages * PageSize;
  542. const auto& pg = pg_ll.Nodes();
  543. const auto& memory_layout = m_system.Kernel().MemoryLayout();
  544. // Empty groups are necessarily invalid.
  545. if (pg.empty()) {
  546. return false;
  547. }
  548. // We're going to validate that the group we'd expect is the group we see.
  549. auto cur_it = pg.begin();
  550. PAddr cur_block_address = cur_it->GetAddress();
  551. size_t cur_block_pages = cur_it->GetNumPages();
  552. auto UpdateCurrentIterator = [&]() {
  553. if (cur_block_pages == 0) {
  554. if ((++cur_it) == pg.end()) {
  555. return false;
  556. }
  557. cur_block_address = cur_it->GetAddress();
  558. cur_block_pages = cur_it->GetNumPages();
  559. }
  560. return true;
  561. };
  562. // Begin traversal.
  563. Common::PageTable::TraversalContext context;
  564. Common::PageTable::TraversalEntry next_entry;
  565. if (!m_page_table_impl->BeginTraversal(next_entry, context, addr)) {
  566. return false;
  567. }
  568. // Prepare tracking variables.
  569. PAddr cur_addr = next_entry.phys_addr;
  570. size_t cur_size = next_entry.block_size - (cur_addr & (next_entry.block_size - 1));
  571. size_t tot_size = cur_size;
  572. // Iterate, comparing expected to actual.
  573. while (tot_size < size) {
  574. if (!m_page_table_impl->ContinueTraversal(next_entry, context)) {
  575. return false;
  576. }
  577. if (next_entry.phys_addr != (cur_addr + cur_size)) {
  578. const size_t cur_pages = cur_size / PageSize;
  579. if (!IsHeapPhysicalAddress(memory_layout, cur_addr)) {
  580. return false;
  581. }
  582. if (!UpdateCurrentIterator()) {
  583. return false;
  584. }
  585. if (cur_block_address != cur_addr || cur_block_pages < cur_pages) {
  586. return false;
  587. }
  588. cur_block_address += cur_size;
  589. cur_block_pages -= cur_pages;
  590. cur_addr = next_entry.phys_addr;
  591. cur_size = next_entry.block_size;
  592. } else {
  593. cur_size += next_entry.block_size;
  594. }
  595. tot_size += next_entry.block_size;
  596. }
  597. // Ensure we compare the right amount for the last block.
  598. if (tot_size > size) {
  599. cur_size -= (tot_size - size);
  600. }
  601. if (!IsHeapPhysicalAddress(memory_layout, cur_addr)) {
  602. return false;
  603. }
  604. if (!UpdateCurrentIterator()) {
  605. return false;
  606. }
  607. return cur_block_address == cur_addr && cur_block_pages == (cur_size / PageSize);
  608. }
  609. Result KPageTable::UnmapProcessMemory(VAddr dst_addr, size_t size, KPageTable& src_page_table,
  610. VAddr src_addr) {
  611. // Acquire the table locks.
  612. KScopedLightLockPair lk(src_page_table.m_general_lock, m_general_lock);
  613. const size_t num_pages{size / PageSize};
  614. // Check that the memory is mapped in the destination process.
  615. size_t num_allocator_blocks;
  616. R_TRY(CheckMemoryState(&num_allocator_blocks, dst_addr, size, KMemoryState::All,
  617. KMemoryState::SharedCode, KMemoryPermission::UserReadWrite,
  618. KMemoryPermission::UserReadWrite, KMemoryAttribute::All,
  619. KMemoryAttribute::None));
  620. // Check that the memory is mapped in the source process.
  621. R_TRY(src_page_table.CheckMemoryState(src_addr, size, KMemoryState::FlagCanMapProcess,
  622. KMemoryState::FlagCanMapProcess, KMemoryPermission::None,
  623. KMemoryPermission::None, KMemoryAttribute::All,
  624. KMemoryAttribute::None));
  625. // Create an update allocator.
  626. Result allocator_result{ResultSuccess};
  627. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  628. m_memory_block_slab_manager, num_allocator_blocks);
  629. R_TRY(allocator_result);
  630. CASCADE_CODE(Operate(dst_addr, num_pages, KMemoryPermission::None, OperationType::Unmap));
  631. // Apply the memory block update.
  632. m_memory_block_manager.Update(std::addressof(allocator), dst_addr, num_pages,
  633. KMemoryState::Free, KMemoryPermission::None,
  634. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  635. KMemoryBlockDisableMergeAttribute::Normal);
  636. m_system.InvalidateCpuInstructionCaches();
  637. R_SUCCEED();
  638. }
  639. Result KPageTable::SetupForIpcClient(PageLinkedList* page_list, size_t* out_blocks_needed,
  640. VAddr address, size_t size, KMemoryPermission test_perm,
  641. KMemoryState dst_state) {
  642. // Validate pre-conditions.
  643. ASSERT(this->IsLockedByCurrentThread());
  644. ASSERT(test_perm == KMemoryPermission::UserReadWrite ||
  645. test_perm == KMemoryPermission::UserRead);
  646. // Check that the address is in range.
  647. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  648. // Get the source permission.
  649. const auto src_perm = (test_perm == KMemoryPermission::UserReadWrite)
  650. ? KMemoryPermission::KernelReadWrite | KMemoryPermission::NotMapped
  651. : KMemoryPermission::UserRead;
  652. // Get aligned extents.
  653. const VAddr aligned_src_start = Common::AlignDown((address), PageSize);
  654. const VAddr aligned_src_end = Common::AlignUp((address) + size, PageSize);
  655. const VAddr mapping_src_start = Common::AlignUp((address), PageSize);
  656. const VAddr mapping_src_end = Common::AlignDown((address) + size, PageSize);
  657. const auto aligned_src_last = (aligned_src_end)-1;
  658. const auto mapping_src_last = (mapping_src_end)-1;
  659. // Get the test state and attribute mask.
  660. KMemoryState test_state;
  661. KMemoryAttribute test_attr_mask;
  662. switch (dst_state) {
  663. case KMemoryState::Ipc:
  664. test_state = KMemoryState::FlagCanUseIpc;
  665. test_attr_mask =
  666. KMemoryAttribute::Uncached | KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked;
  667. break;
  668. case KMemoryState::NonSecureIpc:
  669. test_state = KMemoryState::FlagCanUseNonSecureIpc;
  670. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  671. break;
  672. case KMemoryState::NonDeviceIpc:
  673. test_state = KMemoryState::FlagCanUseNonDeviceIpc;
  674. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  675. break;
  676. default:
  677. R_THROW(ResultInvalidCombination);
  678. }
  679. // Ensure that on failure, we roll back appropriately.
  680. size_t mapped_size = 0;
  681. ON_RESULT_FAILURE {
  682. if (mapped_size > 0) {
  683. this->CleanupForIpcClientOnServerSetupFailure(page_list, mapping_src_start, mapped_size,
  684. src_perm);
  685. }
  686. };
  687. size_t blocks_needed = 0;
  688. // Iterate, mapping as needed.
  689. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(aligned_src_start);
  690. while (true) {
  691. const KMemoryInfo info = it->GetMemoryInfo();
  692. // Validate the current block.
  693. R_TRY(this->CheckMemoryState(info, test_state, test_state, test_perm, test_perm,
  694. test_attr_mask, KMemoryAttribute::None));
  695. if (mapping_src_start < mapping_src_end && (mapping_src_start) < info.GetEndAddress() &&
  696. info.GetAddress() < (mapping_src_end)) {
  697. const auto cur_start =
  698. info.GetAddress() >= (mapping_src_start) ? info.GetAddress() : (mapping_src_start);
  699. const auto cur_end = mapping_src_last >= info.GetLastAddress() ? info.GetEndAddress()
  700. : (mapping_src_end);
  701. const size_t cur_size = cur_end - cur_start;
  702. if (info.GetAddress() < (mapping_src_start)) {
  703. ++blocks_needed;
  704. }
  705. if (mapping_src_last < info.GetLastAddress()) {
  706. ++blocks_needed;
  707. }
  708. // Set the permissions on the block, if we need to.
  709. if ((info.GetPermission() & KMemoryPermission::IpcLockChangeMask) != src_perm) {
  710. R_TRY(Operate(cur_start, cur_size / PageSize, src_perm,
  711. OperationType::ChangePermissions));
  712. }
  713. // Note that we mapped this part.
  714. mapped_size += cur_size;
  715. }
  716. // If the block is at the end, we're done.
  717. if (aligned_src_last <= info.GetLastAddress()) {
  718. break;
  719. }
  720. // Advance.
  721. ++it;
  722. ASSERT(it != m_memory_block_manager.end());
  723. }
  724. if (out_blocks_needed != nullptr) {
  725. ASSERT(blocks_needed <= KMemoryBlockManagerUpdateAllocator::MaxBlocks);
  726. *out_blocks_needed = blocks_needed;
  727. }
  728. R_SUCCEED();
  729. }
  730. Result KPageTable::SetupForIpcServer(VAddr* out_addr, size_t size, VAddr src_addr,
  731. KMemoryPermission test_perm, KMemoryState dst_state,
  732. KPageTable& src_page_table, bool send) {
  733. ASSERT(this->IsLockedByCurrentThread());
  734. ASSERT(src_page_table.IsLockedByCurrentThread());
  735. // Check that we can theoretically map.
  736. const VAddr region_start = m_alias_region_start;
  737. const size_t region_size = m_alias_region_end - m_alias_region_start;
  738. R_UNLESS(size < region_size, ResultOutOfAddressSpace);
  739. // Get aligned source extents.
  740. const VAddr src_start = src_addr;
  741. const VAddr src_end = src_addr + size;
  742. const VAddr aligned_src_start = Common::AlignDown((src_start), PageSize);
  743. const VAddr aligned_src_end = Common::AlignUp((src_start) + size, PageSize);
  744. const VAddr mapping_src_start = Common::AlignUp((src_start), PageSize);
  745. const VAddr mapping_src_end = Common::AlignDown((src_start) + size, PageSize);
  746. const size_t aligned_src_size = aligned_src_end - aligned_src_start;
  747. const size_t mapping_src_size =
  748. (mapping_src_start < mapping_src_end) ? (mapping_src_end - mapping_src_start) : 0;
  749. // Select a random address to map at.
  750. VAddr dst_addr =
  751. this->FindFreeArea(region_start, region_size / PageSize, aligned_src_size / PageSize,
  752. PageSize, 0, this->GetNumGuardPages());
  753. R_UNLESS(dst_addr != 0, ResultOutOfAddressSpace);
  754. // Check that we can perform the operation we're about to perform.
  755. ASSERT(this->CanContain(dst_addr, aligned_src_size, dst_state));
  756. // Create an update allocator.
  757. Result allocator_result;
  758. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  759. m_memory_block_slab_manager);
  760. R_TRY(allocator_result);
  761. // We're going to perform an update, so create a helper.
  762. KScopedPageTableUpdater updater(this);
  763. // Reserve space for any partial pages we allocate.
  764. const size_t unmapped_size = aligned_src_size - mapping_src_size;
  765. KScopedResourceReservation memory_reservation(m_resource_limit,
  766. LimitableResource::PhysicalMemory, unmapped_size);
  767. R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
  768. // Ensure that we manage page references correctly.
  769. PAddr start_partial_page = 0;
  770. PAddr end_partial_page = 0;
  771. VAddr cur_mapped_addr = dst_addr;
  772. // If the partial pages are mapped, an extra reference will have been opened. Otherwise, they'll
  773. // free on scope exit.
  774. SCOPE_EXIT({
  775. if (start_partial_page != 0) {
  776. m_system.Kernel().MemoryManager().Close(start_partial_page, 1);
  777. }
  778. if (end_partial_page != 0) {
  779. m_system.Kernel().MemoryManager().Close(end_partial_page, 1);
  780. }
  781. });
  782. ON_RESULT_FAILURE {
  783. if (cur_mapped_addr != dst_addr) {
  784. // HACK: Manually close the pages.
  785. HACK_ClosePages(dst_addr, (cur_mapped_addr - dst_addr) / PageSize);
  786. ASSERT(Operate(dst_addr, (cur_mapped_addr - dst_addr) / PageSize,
  787. KMemoryPermission::None, OperationType::Unmap)
  788. .IsSuccess());
  789. }
  790. };
  791. // Allocate the start page as needed.
  792. if (aligned_src_start < mapping_src_start) {
  793. start_partial_page =
  794. m_system.Kernel().MemoryManager().AllocateAndOpenContinuous(1, 1, m_allocate_option);
  795. R_UNLESS(start_partial_page != 0, ResultOutOfMemory);
  796. }
  797. // Allocate the end page as needed.
  798. if (mapping_src_end < aligned_src_end &&
  799. (aligned_src_start < mapping_src_end || aligned_src_start == mapping_src_start)) {
  800. end_partial_page =
  801. m_system.Kernel().MemoryManager().AllocateAndOpenContinuous(1, 1, m_allocate_option);
  802. R_UNLESS(end_partial_page != 0, ResultOutOfMemory);
  803. }
  804. // Get the implementation.
  805. auto& src_impl = src_page_table.PageTableImpl();
  806. // Get the fill value for partial pages.
  807. const auto fill_val = m_ipc_fill_value;
  808. // Begin traversal.
  809. Common::PageTable::TraversalContext context;
  810. Common::PageTable::TraversalEntry next_entry;
  811. bool traverse_valid = src_impl.BeginTraversal(next_entry, context, aligned_src_start);
  812. ASSERT(traverse_valid);
  813. // Prepare tracking variables.
  814. PAddr cur_block_addr = next_entry.phys_addr;
  815. size_t cur_block_size =
  816. next_entry.block_size - ((cur_block_addr) & (next_entry.block_size - 1));
  817. size_t tot_block_size = cur_block_size;
  818. // Map the start page, if we have one.
  819. if (start_partial_page != 0) {
  820. // Ensure the page holds correct data.
  821. const VAddr start_partial_virt =
  822. GetHeapVirtualAddress(m_system.Kernel().MemoryLayout(), start_partial_page);
  823. if (send) {
  824. const size_t partial_offset = src_start - aligned_src_start;
  825. size_t copy_size, clear_size;
  826. if (src_end < mapping_src_start) {
  827. copy_size = size;
  828. clear_size = mapping_src_start - src_end;
  829. } else {
  830. copy_size = mapping_src_start - src_start;
  831. clear_size = 0;
  832. }
  833. std::memset(m_system.Memory().GetPointer<void>(start_partial_virt), fill_val,
  834. partial_offset);
  835. std::memcpy(
  836. m_system.Memory().GetPointer<void>(start_partial_virt + partial_offset),
  837. m_system.Memory().GetPointer<void>(
  838. GetHeapVirtualAddress(m_system.Kernel().MemoryLayout(), cur_block_addr) +
  839. partial_offset),
  840. copy_size);
  841. if (clear_size > 0) {
  842. std::memset(m_system.Memory().GetPointer<void>(start_partial_virt + partial_offset +
  843. copy_size),
  844. fill_val, clear_size);
  845. }
  846. } else {
  847. std::memset(m_system.Memory().GetPointer<void>(start_partial_virt), fill_val, PageSize);
  848. }
  849. // Map the page.
  850. R_TRY(Operate(cur_mapped_addr, 1, test_perm, OperationType::Map, start_partial_page));
  851. // HACK: Manually open the pages.
  852. HACK_OpenPages(start_partial_page, 1);
  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. // HACK: Manually open the pages.
  877. HACK_OpenPages(cur_block_addr, cur_block_size / PageSize);
  878. // Update tracking extents.
  879. cur_mapped_addr += cur_block_size;
  880. cur_block_addr = next_entry.phys_addr;
  881. cur_block_size = next_entry.block_size;
  882. } else {
  883. cur_block_size += next_entry.block_size;
  884. }
  885. tot_block_size += next_entry.block_size;
  886. }
  887. // Handle the last direct-mapped page.
  888. if (const VAddr mapped_block_end = aligned_src_start + tot_block_size - cur_block_size;
  889. mapped_block_end < mapping_src_end) {
  890. const size_t last_block_size = mapping_src_end - mapped_block_end;
  891. // Map the last block.
  892. R_TRY(Operate(cur_mapped_addr, last_block_size / PageSize, test_perm, OperationType::Map,
  893. cur_block_addr));
  894. // HACK: Manually open the pages.
  895. HACK_OpenPages(cur_block_addr, last_block_size / PageSize);
  896. // Update tracking extents.
  897. cur_mapped_addr += last_block_size;
  898. cur_block_addr += last_block_size;
  899. if (mapped_block_end + cur_block_size < aligned_src_end &&
  900. cur_block_size == last_block_size) {
  901. traverse_valid = src_impl.ContinueTraversal(next_entry, context);
  902. ASSERT(traverse_valid);
  903. cur_block_addr = next_entry.phys_addr;
  904. }
  905. }
  906. // Map the end page, if we have one.
  907. if (end_partial_page != 0) {
  908. // Ensure the page holds correct data.
  909. const VAddr end_partial_virt =
  910. GetHeapVirtualAddress(m_system.Kernel().MemoryLayout(), end_partial_page);
  911. if (send) {
  912. const size_t copy_size = src_end - mapping_src_end;
  913. std::memcpy(m_system.Memory().GetPointer<void>(end_partial_virt),
  914. m_system.Memory().GetPointer<void>(GetHeapVirtualAddress(
  915. m_system.Kernel().MemoryLayout(), cur_block_addr)),
  916. copy_size);
  917. std::memset(m_system.Memory().GetPointer<void>(end_partial_virt + copy_size), fill_val,
  918. PageSize - copy_size);
  919. } else {
  920. std::memset(m_system.Memory().GetPointer<void>(end_partial_virt), fill_val, PageSize);
  921. }
  922. // Map the page.
  923. R_TRY(Operate(cur_mapped_addr, 1, test_perm, OperationType::Map, end_partial_page));
  924. // HACK: Manually open the pages.
  925. HACK_OpenPages(end_partial_page, 1);
  926. }
  927. // Update memory blocks to reflect our changes
  928. m_memory_block_manager.Update(std::addressof(allocator), dst_addr, aligned_src_size / PageSize,
  929. dst_state, test_perm, KMemoryAttribute::None,
  930. KMemoryBlockDisableMergeAttribute::Normal,
  931. KMemoryBlockDisableMergeAttribute::None);
  932. // Set the output address.
  933. *out_addr = dst_addr + (src_start - aligned_src_start);
  934. // We succeeded.
  935. memory_reservation.Commit();
  936. R_SUCCEED();
  937. }
  938. Result KPageTable::SetupForIpc(VAddr* out_dst_addr, size_t size, VAddr src_addr,
  939. KPageTable& src_page_table, KMemoryPermission test_perm,
  940. KMemoryState dst_state, bool send) {
  941. // For convenience, alias this.
  942. KPageTable& dst_page_table = *this;
  943. // Acquire the table locks.
  944. KScopedLightLockPair lk(src_page_table.m_general_lock, dst_page_table.m_general_lock);
  945. // We're going to perform an update, so create a helper.
  946. KScopedPageTableUpdater updater(std::addressof(src_page_table));
  947. // Perform client setup.
  948. size_t num_allocator_blocks;
  949. R_TRY(src_page_table.SetupForIpcClient(updater.GetPageList(),
  950. std::addressof(num_allocator_blocks), src_addr, size,
  951. test_perm, dst_state));
  952. // Create an update allocator.
  953. Result allocator_result;
  954. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  955. src_page_table.m_memory_block_slab_manager,
  956. num_allocator_blocks);
  957. R_TRY(allocator_result);
  958. // Get the mapped extents.
  959. const VAddr src_map_start = Common::AlignUp((src_addr), PageSize);
  960. const VAddr src_map_end = Common::AlignDown((src_addr) + size, PageSize);
  961. const size_t src_map_size = src_map_end - src_map_start;
  962. // Ensure that we clean up appropriately if we fail after this.
  963. const auto src_perm = (test_perm == KMemoryPermission::UserReadWrite)
  964. ? KMemoryPermission::KernelReadWrite | KMemoryPermission::NotMapped
  965. : KMemoryPermission::UserRead;
  966. ON_RESULT_FAILURE {
  967. if (src_map_end > src_map_start) {
  968. src_page_table.CleanupForIpcClientOnServerSetupFailure(
  969. updater.GetPageList(), src_map_start, src_map_size, src_perm);
  970. }
  971. };
  972. // Perform server setup.
  973. R_TRY(dst_page_table.SetupForIpcServer(out_dst_addr, size, src_addr, test_perm, dst_state,
  974. src_page_table, send));
  975. // If anything was mapped, ipc-lock the pages.
  976. if (src_map_start < src_map_end) {
  977. // Get the source permission.
  978. src_page_table.m_memory_block_manager.UpdateLock(std::addressof(allocator), src_map_start,
  979. (src_map_end - src_map_start) / PageSize,
  980. &KMemoryBlock::LockForIpc, src_perm);
  981. }
  982. R_SUCCEED();
  983. }
  984. Result KPageTable::CleanupForIpcServer(VAddr address, size_t size, KMemoryState dst_state) {
  985. // Validate the address.
  986. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  987. // Lock the table.
  988. KScopedLightLock lk(m_general_lock);
  989. // Validate the memory state.
  990. size_t num_allocator_blocks;
  991. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), address, size,
  992. KMemoryState::All, dst_state, KMemoryPermission::UserRead,
  993. KMemoryPermission::UserRead, KMemoryAttribute::All,
  994. KMemoryAttribute::None));
  995. // Create an update allocator.
  996. Result allocator_result;
  997. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  998. m_memory_block_slab_manager, num_allocator_blocks);
  999. R_TRY(allocator_result);
  1000. // We're going to perform an update, so create a helper.
  1001. KScopedPageTableUpdater updater(this);
  1002. // Get aligned extents.
  1003. const VAddr aligned_start = Common::AlignDown((address), PageSize);
  1004. const VAddr aligned_end = Common::AlignUp((address) + size, PageSize);
  1005. const size_t aligned_size = aligned_end - aligned_start;
  1006. const size_t aligned_num_pages = aligned_size / PageSize;
  1007. // HACK: Manually close the pages.
  1008. HACK_ClosePages(aligned_start, aligned_num_pages);
  1009. // Unmap the pages.
  1010. R_TRY(Operate(aligned_start, aligned_num_pages, KMemoryPermission::None, OperationType::Unmap));
  1011. // Update memory blocks.
  1012. m_memory_block_manager.Update(std::addressof(allocator), aligned_start, aligned_num_pages,
  1013. KMemoryState::None, KMemoryPermission::None,
  1014. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  1015. KMemoryBlockDisableMergeAttribute::Normal);
  1016. // Release from the resource limit as relevant.
  1017. const VAddr mapping_start = Common::AlignUp((address), PageSize);
  1018. const VAddr mapping_end = Common::AlignDown((address) + size, PageSize);
  1019. const size_t mapping_size = (mapping_start < mapping_end) ? mapping_end - mapping_start : 0;
  1020. m_resource_limit->Release(LimitableResource::PhysicalMemory, aligned_size - mapping_size);
  1021. R_SUCCEED();
  1022. }
  1023. Result KPageTable::CleanupForIpcClient(VAddr address, size_t size, KMemoryState dst_state) {
  1024. // Validate the address.
  1025. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  1026. // Get aligned source extents.
  1027. const VAddr mapping_start = Common::AlignUp((address), PageSize);
  1028. const VAddr mapping_end = Common::AlignDown((address) + size, PageSize);
  1029. const VAddr mapping_last = mapping_end - 1;
  1030. const size_t mapping_size = (mapping_start < mapping_end) ? (mapping_end - mapping_start) : 0;
  1031. // If nothing was mapped, we're actually done immediately.
  1032. R_SUCCEED_IF(mapping_size == 0);
  1033. // Get the test state and attribute mask.
  1034. KMemoryState test_state;
  1035. KMemoryAttribute test_attr_mask;
  1036. switch (dst_state) {
  1037. case KMemoryState::Ipc:
  1038. test_state = KMemoryState::FlagCanUseIpc;
  1039. test_attr_mask =
  1040. KMemoryAttribute::Uncached | KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked;
  1041. break;
  1042. case KMemoryState::NonSecureIpc:
  1043. test_state = KMemoryState::FlagCanUseNonSecureIpc;
  1044. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  1045. break;
  1046. case KMemoryState::NonDeviceIpc:
  1047. test_state = KMemoryState::FlagCanUseNonDeviceIpc;
  1048. test_attr_mask = KMemoryAttribute::Uncached | KMemoryAttribute::Locked;
  1049. break;
  1050. default:
  1051. R_THROW(ResultInvalidCombination);
  1052. }
  1053. // Lock the table.
  1054. // NOTE: Nintendo does this *after* creating the updater below, but this does not follow
  1055. // convention elsewhere in KPageTable.
  1056. KScopedLightLock lk(m_general_lock);
  1057. // We're going to perform an update, so create a helper.
  1058. KScopedPageTableUpdater updater(this);
  1059. // Ensure that on failure, we roll back appropriately.
  1060. size_t mapped_size = 0;
  1061. ON_RESULT_FAILURE {
  1062. if (mapped_size > 0) {
  1063. // Determine where the mapping ends.
  1064. const auto mapped_end = (mapping_start) + mapped_size;
  1065. const auto mapped_last = mapped_end - 1;
  1066. // Get current and next iterators.
  1067. KMemoryBlockManager::const_iterator start_it =
  1068. m_memory_block_manager.FindIterator(mapping_start);
  1069. KMemoryBlockManager::const_iterator next_it = start_it;
  1070. ++next_it;
  1071. // Get the current block info.
  1072. KMemoryInfo cur_info = start_it->GetMemoryInfo();
  1073. // Create tracking variables.
  1074. VAddr cur_address = cur_info.GetAddress();
  1075. size_t cur_size = cur_info.GetSize();
  1076. bool cur_perm_eq = cur_info.GetPermission() == cur_info.GetOriginalPermission();
  1077. bool cur_needs_set_perm = !cur_perm_eq && cur_info.GetIpcLockCount() == 1;
  1078. bool first =
  1079. cur_info.GetIpcDisableMergeCount() == 1 &&
  1080. (cur_info.GetDisableMergeAttribute() & KMemoryBlockDisableMergeAttribute::Locked) ==
  1081. KMemoryBlockDisableMergeAttribute::None;
  1082. while (((cur_address) + cur_size - 1) < mapped_last) {
  1083. // Check that we have a next block.
  1084. ASSERT(next_it != m_memory_block_manager.end());
  1085. // Get the next info.
  1086. const KMemoryInfo next_info = next_it->GetMemoryInfo();
  1087. // Check if we can consolidate the next block's permission set with the current one.
  1088. const bool next_perm_eq =
  1089. next_info.GetPermission() == next_info.GetOriginalPermission();
  1090. const bool next_needs_set_perm = !next_perm_eq && next_info.GetIpcLockCount() == 1;
  1091. if (cur_perm_eq == next_perm_eq && cur_needs_set_perm == next_needs_set_perm &&
  1092. cur_info.GetOriginalPermission() == next_info.GetOriginalPermission()) {
  1093. // We can consolidate the reprotection for the current and next block into a
  1094. // single call.
  1095. cur_size += next_info.GetSize();
  1096. } else {
  1097. // We have to operate on the current block.
  1098. if ((cur_needs_set_perm || first) && !cur_perm_eq) {
  1099. ASSERT(Operate(cur_address, cur_size / PageSize, cur_info.GetPermission(),
  1100. OperationType::ChangePermissions)
  1101. .IsSuccess());
  1102. }
  1103. // Advance.
  1104. cur_address = next_info.GetAddress();
  1105. cur_size = next_info.GetSize();
  1106. first = false;
  1107. }
  1108. // Advance.
  1109. cur_info = next_info;
  1110. cur_perm_eq = next_perm_eq;
  1111. cur_needs_set_perm = next_needs_set_perm;
  1112. ++next_it;
  1113. }
  1114. // Process the last block.
  1115. if ((first || cur_needs_set_perm) && !cur_perm_eq) {
  1116. ASSERT(Operate(cur_address, cur_size / PageSize, cur_info.GetPermission(),
  1117. OperationType::ChangePermissions)
  1118. .IsSuccess());
  1119. }
  1120. }
  1121. };
  1122. // Iterate, reprotecting as needed.
  1123. {
  1124. // Get current and next iterators.
  1125. KMemoryBlockManager::const_iterator start_it =
  1126. m_memory_block_manager.FindIterator(mapping_start);
  1127. KMemoryBlockManager::const_iterator next_it = start_it;
  1128. ++next_it;
  1129. // Validate the current block.
  1130. KMemoryInfo cur_info = start_it->GetMemoryInfo();
  1131. ASSERT(this->CheckMemoryState(cur_info, test_state, test_state, KMemoryPermission::None,
  1132. KMemoryPermission::None,
  1133. test_attr_mask | KMemoryAttribute::IpcLocked,
  1134. KMemoryAttribute::IpcLocked)
  1135. .IsSuccess());
  1136. // Create tracking variables.
  1137. VAddr cur_address = cur_info.GetAddress();
  1138. size_t cur_size = cur_info.GetSize();
  1139. bool cur_perm_eq = cur_info.GetPermission() == cur_info.GetOriginalPermission();
  1140. bool cur_needs_set_perm = !cur_perm_eq && cur_info.GetIpcLockCount() == 1;
  1141. bool first =
  1142. cur_info.GetIpcDisableMergeCount() == 1 &&
  1143. (cur_info.GetDisableMergeAttribute() & KMemoryBlockDisableMergeAttribute::Locked) ==
  1144. KMemoryBlockDisableMergeAttribute::None;
  1145. while ((cur_address + cur_size - 1) < mapping_last) {
  1146. // Check that we have a next block.
  1147. ASSERT(next_it != m_memory_block_manager.end());
  1148. // Get the next info.
  1149. const KMemoryInfo next_info = next_it->GetMemoryInfo();
  1150. // Validate the next block.
  1151. ASSERT(this->CheckMemoryState(next_info, test_state, test_state,
  1152. KMemoryPermission::None, KMemoryPermission::None,
  1153. test_attr_mask | KMemoryAttribute::IpcLocked,
  1154. KMemoryAttribute::IpcLocked)
  1155. .IsSuccess());
  1156. // Check if we can consolidate the next block's permission set with the current one.
  1157. const bool next_perm_eq =
  1158. next_info.GetPermission() == next_info.GetOriginalPermission();
  1159. const bool next_needs_set_perm = !next_perm_eq && next_info.GetIpcLockCount() == 1;
  1160. if (cur_perm_eq == next_perm_eq && cur_needs_set_perm == next_needs_set_perm &&
  1161. cur_info.GetOriginalPermission() == next_info.GetOriginalPermission()) {
  1162. // We can consolidate the reprotection for the current and next block into a single
  1163. // call.
  1164. cur_size += next_info.GetSize();
  1165. } else {
  1166. // We have to operate on the current block.
  1167. if ((cur_needs_set_perm || first) && !cur_perm_eq) {
  1168. R_TRY(Operate(cur_address, cur_size / PageSize,
  1169. cur_needs_set_perm ? cur_info.GetOriginalPermission()
  1170. : cur_info.GetPermission(),
  1171. OperationType::ChangePermissions));
  1172. }
  1173. // Mark that we mapped the block.
  1174. mapped_size += cur_size;
  1175. // Advance.
  1176. cur_address = next_info.GetAddress();
  1177. cur_size = next_info.GetSize();
  1178. first = false;
  1179. }
  1180. // Advance.
  1181. cur_info = next_info;
  1182. cur_perm_eq = next_perm_eq;
  1183. cur_needs_set_perm = next_needs_set_perm;
  1184. ++next_it;
  1185. }
  1186. // Process the last block.
  1187. const auto lock_count =
  1188. cur_info.GetIpcLockCount() +
  1189. (next_it != m_memory_block_manager.end()
  1190. ? (next_it->GetIpcDisableMergeCount() - next_it->GetIpcLockCount())
  1191. : 0);
  1192. if ((first || cur_needs_set_perm || (lock_count == 1)) && !cur_perm_eq) {
  1193. R_TRY(Operate(cur_address, cur_size / PageSize,
  1194. cur_needs_set_perm ? cur_info.GetOriginalPermission()
  1195. : cur_info.GetPermission(),
  1196. OperationType::ChangePermissions));
  1197. }
  1198. }
  1199. // Create an update allocator.
  1200. // NOTE: Guaranteed zero blocks needed here.
  1201. Result allocator_result;
  1202. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1203. m_memory_block_slab_manager, 0);
  1204. R_TRY(allocator_result);
  1205. // Unlock the pages.
  1206. m_memory_block_manager.UpdateLock(std::addressof(allocator), mapping_start,
  1207. mapping_size / PageSize, &KMemoryBlock::UnlockForIpc,
  1208. KMemoryPermission::None);
  1209. R_SUCCEED();
  1210. }
  1211. void KPageTable::CleanupForIpcClientOnServerSetupFailure([[maybe_unused]] PageLinkedList* page_list,
  1212. VAddr address, size_t size,
  1213. KMemoryPermission prot_perm) {
  1214. ASSERT(this->IsLockedByCurrentThread());
  1215. ASSERT(Common::IsAligned(address, PageSize));
  1216. ASSERT(Common::IsAligned(size, PageSize));
  1217. // Get the mapped extents.
  1218. const VAddr src_map_start = address;
  1219. const VAddr src_map_end = address + size;
  1220. const VAddr src_map_last = src_map_end - 1;
  1221. // This function is only invoked when there's something to do.
  1222. ASSERT(src_map_end > src_map_start);
  1223. // Iterate over blocks, fixing permissions.
  1224. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(address);
  1225. while (true) {
  1226. const KMemoryInfo info = it->GetMemoryInfo();
  1227. const auto cur_start =
  1228. info.GetAddress() >= src_map_start ? info.GetAddress() : src_map_start;
  1229. const auto cur_end =
  1230. src_map_last <= info.GetLastAddress() ? src_map_end : info.GetEndAddress();
  1231. // If we can, fix the protections on the block.
  1232. if ((info.GetIpcLockCount() == 0 &&
  1233. (info.GetPermission() & KMemoryPermission::IpcLockChangeMask) != prot_perm) ||
  1234. (info.GetIpcLockCount() != 0 &&
  1235. (info.GetOriginalPermission() & KMemoryPermission::IpcLockChangeMask) != prot_perm)) {
  1236. // Check if we actually need to fix the protections on the block.
  1237. if (cur_end == src_map_end || info.GetAddress() <= src_map_start ||
  1238. (info.GetPermission() & KMemoryPermission::IpcLockChangeMask) != prot_perm) {
  1239. ASSERT(Operate(cur_start, (cur_end - cur_start) / PageSize, info.GetPermission(),
  1240. OperationType::ChangePermissions)
  1241. .IsSuccess());
  1242. }
  1243. }
  1244. // If we're past the end of the region, we're done.
  1245. if (src_map_last <= info.GetLastAddress()) {
  1246. break;
  1247. }
  1248. // Advance.
  1249. ++it;
  1250. ASSERT(it != m_memory_block_manager.end());
  1251. }
  1252. }
  1253. void KPageTable::HACK_OpenPages(PAddr phys_addr, size_t num_pages) {
  1254. m_system.Kernel().MemoryManager().OpenFirst(phys_addr, num_pages);
  1255. }
  1256. void KPageTable::HACK_ClosePages(VAddr virt_addr, size_t num_pages) {
  1257. for (size_t index = 0; index < num_pages; ++index) {
  1258. const auto paddr = GetPhysicalAddr(virt_addr + (index * PageSize));
  1259. m_system.Kernel().MemoryManager().Close(paddr, 1);
  1260. }
  1261. }
  1262. Result KPageTable::MapPhysicalMemory(VAddr address, size_t size) {
  1263. // Lock the physical memory lock.
  1264. KScopedLightLock phys_lk(m_map_physical_memory_lock);
  1265. // Calculate the last address for convenience.
  1266. const VAddr last_address = address + size - 1;
  1267. // Define iteration variables.
  1268. VAddr cur_address;
  1269. size_t mapped_size;
  1270. // The entire mapping process can be retried.
  1271. while (true) {
  1272. // Check if the memory is already mapped.
  1273. {
  1274. // Lock the table.
  1275. KScopedLightLock lk(m_general_lock);
  1276. // Iterate over the memory.
  1277. cur_address = address;
  1278. mapped_size = 0;
  1279. auto it = m_memory_block_manager.FindIterator(cur_address);
  1280. while (true) {
  1281. // Check that the iterator is valid.
  1282. ASSERT(it != m_memory_block_manager.end());
  1283. // Get the memory info.
  1284. const KMemoryInfo info = it->GetMemoryInfo();
  1285. // Check if we're done.
  1286. if (last_address <= info.GetLastAddress()) {
  1287. if (info.GetState() != KMemoryState::Free) {
  1288. mapped_size += (last_address + 1 - cur_address);
  1289. }
  1290. break;
  1291. }
  1292. // Track the memory if it's mapped.
  1293. if (info.GetState() != KMemoryState::Free) {
  1294. mapped_size += VAddr(info.GetEndAddress()) - cur_address;
  1295. }
  1296. // Advance.
  1297. cur_address = info.GetEndAddress();
  1298. ++it;
  1299. }
  1300. // If the size mapped is the size requested, we've nothing to do.
  1301. R_SUCCEED_IF(size == mapped_size);
  1302. }
  1303. // Allocate and map the memory.
  1304. {
  1305. // Reserve the memory from the process resource limit.
  1306. KScopedResourceReservation memory_reservation(
  1307. m_resource_limit, LimitableResource::PhysicalMemory, size - mapped_size);
  1308. R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
  1309. // Allocate pages for the new memory.
  1310. KPageGroup pg;
  1311. R_TRY(m_system.Kernel().MemoryManager().AllocateForProcess(
  1312. &pg, (size - mapped_size) / PageSize, m_allocate_option, 0, 0));
  1313. // If we fail in the next bit (or retry), we need to cleanup the pages.
  1314. // auto pg_guard = SCOPE_GUARD {
  1315. // pg.OpenFirst();
  1316. // pg.Close();
  1317. //};
  1318. // Map the memory.
  1319. {
  1320. // Lock the table.
  1321. KScopedLightLock lk(m_general_lock);
  1322. size_t num_allocator_blocks = 0;
  1323. // Verify that nobody has mapped memory since we first checked.
  1324. {
  1325. // Iterate over the memory.
  1326. size_t checked_mapped_size = 0;
  1327. cur_address = address;
  1328. auto it = m_memory_block_manager.FindIterator(cur_address);
  1329. while (true) {
  1330. // Check that the iterator is valid.
  1331. ASSERT(it != m_memory_block_manager.end());
  1332. // Get the memory info.
  1333. const KMemoryInfo info = it->GetMemoryInfo();
  1334. const bool is_free = info.GetState() == KMemoryState::Free;
  1335. if (is_free) {
  1336. if (info.GetAddress() < address) {
  1337. ++num_allocator_blocks;
  1338. }
  1339. if (last_address < info.GetLastAddress()) {
  1340. ++num_allocator_blocks;
  1341. }
  1342. }
  1343. // Check if we're done.
  1344. if (last_address <= info.GetLastAddress()) {
  1345. if (!is_free) {
  1346. checked_mapped_size += (last_address + 1 - cur_address);
  1347. }
  1348. break;
  1349. }
  1350. // Track the memory if it's mapped.
  1351. if (!is_free) {
  1352. checked_mapped_size += VAddr(info.GetEndAddress()) - cur_address;
  1353. }
  1354. // Advance.
  1355. cur_address = info.GetEndAddress();
  1356. ++it;
  1357. }
  1358. // If the size now isn't what it was before, somebody mapped or unmapped
  1359. // concurrently. If this happened, retry.
  1360. if (mapped_size != checked_mapped_size) {
  1361. continue;
  1362. }
  1363. }
  1364. // Create an update allocator.
  1365. ASSERT(num_allocator_blocks <= KMemoryBlockManagerUpdateAllocator::MaxBlocks);
  1366. Result allocator_result;
  1367. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1368. m_memory_block_slab_manager,
  1369. num_allocator_blocks);
  1370. R_TRY(allocator_result);
  1371. // We're going to perform an update, so create a helper.
  1372. KScopedPageTableUpdater updater(this);
  1373. // Prepare to iterate over the memory.
  1374. auto pg_it = pg.Nodes().begin();
  1375. PAddr pg_phys_addr = pg_it->GetAddress();
  1376. size_t pg_pages = pg_it->GetNumPages();
  1377. // Reset the current tracking address, and make sure we clean up on failure.
  1378. // pg_guard.Cancel();
  1379. cur_address = address;
  1380. ON_RESULT_FAILURE {
  1381. if (cur_address > address) {
  1382. const VAddr last_unmap_address = cur_address - 1;
  1383. // Iterate, unmapping the pages.
  1384. cur_address = address;
  1385. auto it = m_memory_block_manager.FindIterator(cur_address);
  1386. while (true) {
  1387. // Check that the iterator is valid.
  1388. ASSERT(it != m_memory_block_manager.end());
  1389. // Get the memory info.
  1390. const KMemoryInfo info = it->GetMemoryInfo();
  1391. // If the memory state is free, we mapped it and need to unmap it.
  1392. if (info.GetState() == KMemoryState::Free) {
  1393. // Determine the range to unmap.
  1394. const size_t cur_pages =
  1395. std::min(VAddr(info.GetEndAddress()) - cur_address,
  1396. last_unmap_address + 1 - cur_address) /
  1397. PageSize;
  1398. // HACK: Manually close the pages.
  1399. HACK_ClosePages(cur_address, cur_pages);
  1400. // Unmap.
  1401. ASSERT(Operate(cur_address, cur_pages, KMemoryPermission::None,
  1402. OperationType::Unmap)
  1403. .IsSuccess());
  1404. }
  1405. // Check if we're done.
  1406. if (last_unmap_address <= info.GetLastAddress()) {
  1407. break;
  1408. }
  1409. // Advance.
  1410. cur_address = info.GetEndAddress();
  1411. ++it;
  1412. }
  1413. }
  1414. // Release any remaining unmapped memory.
  1415. m_system.Kernel().MemoryManager().OpenFirst(pg_phys_addr, pg_pages);
  1416. m_system.Kernel().MemoryManager().Close(pg_phys_addr, pg_pages);
  1417. for (++pg_it; pg_it != pg.Nodes().end(); ++pg_it) {
  1418. m_system.Kernel().MemoryManager().OpenFirst(pg_it->GetAddress(),
  1419. pg_it->GetNumPages());
  1420. m_system.Kernel().MemoryManager().Close(pg_it->GetAddress(),
  1421. pg_it->GetNumPages());
  1422. }
  1423. };
  1424. auto it = m_memory_block_manager.FindIterator(cur_address);
  1425. while (true) {
  1426. // Check that the iterator is valid.
  1427. ASSERT(it != m_memory_block_manager.end());
  1428. // Get the memory info.
  1429. const KMemoryInfo info = it->GetMemoryInfo();
  1430. // If it's unmapped, we need to map it.
  1431. if (info.GetState() == KMemoryState::Free) {
  1432. // Determine the range to map.
  1433. size_t map_pages = std::min(VAddr(info.GetEndAddress()) - cur_address,
  1434. last_address + 1 - cur_address) /
  1435. PageSize;
  1436. // While we have pages to map, map them.
  1437. while (map_pages > 0) {
  1438. // Check if we're at the end of the physical block.
  1439. if (pg_pages == 0) {
  1440. // Ensure there are more pages to map.
  1441. ASSERT(pg_it != pg.Nodes().end());
  1442. // Advance our physical block.
  1443. ++pg_it;
  1444. pg_phys_addr = pg_it->GetAddress();
  1445. pg_pages = pg_it->GetNumPages();
  1446. }
  1447. // Map whatever we can.
  1448. const size_t cur_pages = std::min(pg_pages, map_pages);
  1449. R_TRY(Operate(cur_address, cur_pages, KMemoryPermission::UserReadWrite,
  1450. OperationType::Map, pg_phys_addr));
  1451. // HACK: Manually open the pages.
  1452. HACK_OpenPages(pg_phys_addr, cur_pages);
  1453. // Advance.
  1454. cur_address += cur_pages * PageSize;
  1455. map_pages -= cur_pages;
  1456. pg_phys_addr += cur_pages * PageSize;
  1457. pg_pages -= cur_pages;
  1458. }
  1459. }
  1460. // Check if we're done.
  1461. if (last_address <= info.GetLastAddress()) {
  1462. break;
  1463. }
  1464. // Advance.
  1465. cur_address = info.GetEndAddress();
  1466. ++it;
  1467. }
  1468. // We succeeded, so commit the memory reservation.
  1469. memory_reservation.Commit();
  1470. // Increase our tracked mapped size.
  1471. m_mapped_physical_memory_size += (size - mapped_size);
  1472. // Update the relevant memory blocks.
  1473. m_memory_block_manager.UpdateIfMatch(
  1474. std::addressof(allocator), address, size / PageSize, KMemoryState::Free,
  1475. KMemoryPermission::None, KMemoryAttribute::None, KMemoryState::Normal,
  1476. KMemoryPermission::UserReadWrite, KMemoryAttribute::None);
  1477. R_SUCCEED();
  1478. }
  1479. }
  1480. }
  1481. }
  1482. Result KPageTable::UnmapPhysicalMemory(VAddr address, size_t size) {
  1483. // Lock the physical memory lock.
  1484. KScopedLightLock phys_lk(m_map_physical_memory_lock);
  1485. // Lock the table.
  1486. KScopedLightLock lk(m_general_lock);
  1487. // Calculate the last address for convenience.
  1488. const VAddr last_address = address + size - 1;
  1489. // Define iteration variables.
  1490. VAddr map_start_address = 0;
  1491. VAddr map_last_address = 0;
  1492. VAddr cur_address;
  1493. size_t mapped_size;
  1494. size_t num_allocator_blocks = 0;
  1495. // Check if the memory is mapped.
  1496. {
  1497. // Iterate over the memory.
  1498. cur_address = address;
  1499. mapped_size = 0;
  1500. auto it = m_memory_block_manager.FindIterator(cur_address);
  1501. while (true) {
  1502. // Check that the iterator is valid.
  1503. ASSERT(it != m_memory_block_manager.end());
  1504. // Get the memory info.
  1505. const KMemoryInfo info = it->GetMemoryInfo();
  1506. // Verify the memory's state.
  1507. const bool is_normal = info.GetState() == KMemoryState::Normal &&
  1508. info.GetAttribute() == KMemoryAttribute::None;
  1509. const bool is_free = info.GetState() == KMemoryState::Free;
  1510. R_UNLESS(is_normal || is_free, ResultInvalidCurrentMemory);
  1511. if (is_normal) {
  1512. R_UNLESS(info.GetAttribute() == KMemoryAttribute::None, ResultInvalidCurrentMemory);
  1513. if (map_start_address == 0) {
  1514. map_start_address = cur_address;
  1515. }
  1516. map_last_address =
  1517. (last_address >= info.GetLastAddress()) ? info.GetLastAddress() : last_address;
  1518. if (info.GetAddress() < address) {
  1519. ++num_allocator_blocks;
  1520. }
  1521. if (last_address < info.GetLastAddress()) {
  1522. ++num_allocator_blocks;
  1523. }
  1524. mapped_size += (map_last_address + 1 - cur_address);
  1525. }
  1526. // Check if we're done.
  1527. if (last_address <= info.GetLastAddress()) {
  1528. break;
  1529. }
  1530. // Advance.
  1531. cur_address = info.GetEndAddress();
  1532. ++it;
  1533. }
  1534. // If there's nothing mapped, we've nothing to do.
  1535. R_SUCCEED_IF(mapped_size == 0);
  1536. }
  1537. // Create an update allocator.
  1538. ASSERT(num_allocator_blocks <= KMemoryBlockManagerUpdateAllocator::MaxBlocks);
  1539. Result allocator_result;
  1540. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1541. m_memory_block_slab_manager, num_allocator_blocks);
  1542. R_TRY(allocator_result);
  1543. // We're going to perform an update, so create a helper.
  1544. KScopedPageTableUpdater updater(this);
  1545. // Separate the mapping.
  1546. R_TRY(Operate(map_start_address, (map_last_address + 1 - map_start_address) / PageSize,
  1547. KMemoryPermission::None, OperationType::Separate));
  1548. // Reset the current tracking address, and make sure we clean up on failure.
  1549. cur_address = address;
  1550. // Iterate over the memory, unmapping as we go.
  1551. auto it = m_memory_block_manager.FindIterator(cur_address);
  1552. while (true) {
  1553. // Check that the iterator is valid.
  1554. ASSERT(it != m_memory_block_manager.end());
  1555. // Get the memory info.
  1556. const KMemoryInfo info = it->GetMemoryInfo();
  1557. // If the memory state is normal, we need to unmap it.
  1558. if (info.GetState() == KMemoryState::Normal) {
  1559. // Determine the range to unmap.
  1560. const size_t cur_pages = std::min(VAddr(info.GetEndAddress()) - cur_address,
  1561. last_address + 1 - cur_address) /
  1562. PageSize;
  1563. // HACK: Manually close the pages.
  1564. HACK_ClosePages(cur_address, cur_pages);
  1565. // Unmap.
  1566. ASSERT(Operate(cur_address, cur_pages, KMemoryPermission::None, OperationType::Unmap)
  1567. .IsSuccess());
  1568. }
  1569. // Check if we're done.
  1570. if (last_address <= info.GetLastAddress()) {
  1571. break;
  1572. }
  1573. // Advance.
  1574. cur_address = info.GetEndAddress();
  1575. ++it;
  1576. }
  1577. // Release the memory resource.
  1578. m_mapped_physical_memory_size -= mapped_size;
  1579. m_resource_limit->Release(LimitableResource::PhysicalMemory, mapped_size);
  1580. // Update memory blocks.
  1581. m_memory_block_manager.Update(std::addressof(allocator), address, size / PageSize,
  1582. KMemoryState::Free, KMemoryPermission::None,
  1583. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  1584. KMemoryBlockDisableMergeAttribute::None);
  1585. // We succeeded.
  1586. R_SUCCEED();
  1587. }
  1588. Result KPageTable::MapMemory(VAddr dst_address, VAddr src_address, size_t size) {
  1589. // Lock the table.
  1590. KScopedLightLock lk(m_general_lock);
  1591. // Validate that the source address's state is valid.
  1592. KMemoryState src_state;
  1593. size_t num_src_allocator_blocks;
  1594. R_TRY(this->CheckMemoryState(std::addressof(src_state), nullptr, nullptr,
  1595. std::addressof(num_src_allocator_blocks), src_address, size,
  1596. KMemoryState::FlagCanAlias, KMemoryState::FlagCanAlias,
  1597. KMemoryPermission::All, KMemoryPermission::UserReadWrite,
  1598. KMemoryAttribute::All, KMemoryAttribute::None));
  1599. // Validate that the dst address's state is valid.
  1600. size_t num_dst_allocator_blocks;
  1601. R_TRY(this->CheckMemoryState(std::addressof(num_dst_allocator_blocks), dst_address, size,
  1602. KMemoryState::All, KMemoryState::Free, KMemoryPermission::None,
  1603. KMemoryPermission::None, KMemoryAttribute::None,
  1604. KMemoryAttribute::None));
  1605. // Create an update allocator for the source.
  1606. Result src_allocator_result{ResultSuccess};
  1607. KMemoryBlockManagerUpdateAllocator src_allocator(std::addressof(src_allocator_result),
  1608. m_memory_block_slab_manager,
  1609. num_src_allocator_blocks);
  1610. R_TRY(src_allocator_result);
  1611. // Create an update allocator for the destination.
  1612. Result dst_allocator_result{ResultSuccess};
  1613. KMemoryBlockManagerUpdateAllocator dst_allocator(std::addressof(dst_allocator_result),
  1614. m_memory_block_slab_manager,
  1615. num_dst_allocator_blocks);
  1616. R_TRY(dst_allocator_result);
  1617. // Map the memory.
  1618. KPageGroup page_linked_list;
  1619. const size_t num_pages{size / PageSize};
  1620. const KMemoryPermission new_src_perm = static_cast<KMemoryPermission>(
  1621. KMemoryPermission::KernelRead | KMemoryPermission::NotMapped);
  1622. const KMemoryAttribute new_src_attr = KMemoryAttribute::Locked;
  1623. AddRegionToPages(src_address, num_pages, page_linked_list);
  1624. {
  1625. // Reprotect the source as kernel-read/not mapped.
  1626. auto block_guard = detail::ScopeExit([&] {
  1627. Operate(src_address, num_pages, KMemoryPermission::UserReadWrite,
  1628. OperationType::ChangePermissions);
  1629. });
  1630. R_TRY(Operate(src_address, num_pages, new_src_perm, OperationType::ChangePermissions));
  1631. R_TRY(MapPages(dst_address, page_linked_list, KMemoryPermission::UserReadWrite));
  1632. block_guard.Cancel();
  1633. }
  1634. // Apply the memory block updates.
  1635. m_memory_block_manager.Update(std::addressof(src_allocator), src_address, num_pages, src_state,
  1636. new_src_perm, new_src_attr,
  1637. KMemoryBlockDisableMergeAttribute::Locked,
  1638. KMemoryBlockDisableMergeAttribute::None);
  1639. m_memory_block_manager.Update(std::addressof(dst_allocator), dst_address, num_pages,
  1640. KMemoryState::Stack, KMemoryPermission::UserReadWrite,
  1641. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  1642. KMemoryBlockDisableMergeAttribute::None);
  1643. R_SUCCEED();
  1644. }
  1645. Result KPageTable::UnmapMemory(VAddr dst_address, VAddr src_address, size_t size) {
  1646. // Lock the table.
  1647. KScopedLightLock lk(m_general_lock);
  1648. // Validate that the source address's state is valid.
  1649. KMemoryState src_state;
  1650. size_t num_src_allocator_blocks;
  1651. R_TRY(this->CheckMemoryState(
  1652. std::addressof(src_state), nullptr, nullptr, std::addressof(num_src_allocator_blocks),
  1653. src_address, size, KMemoryState::FlagCanAlias, KMemoryState::FlagCanAlias,
  1654. KMemoryPermission::All, KMemoryPermission::NotMapped | KMemoryPermission::KernelRead,
  1655. KMemoryAttribute::All, KMemoryAttribute::Locked));
  1656. // Validate that the dst address's state is valid.
  1657. KMemoryPermission dst_perm;
  1658. size_t num_dst_allocator_blocks;
  1659. R_TRY(this->CheckMemoryState(
  1660. nullptr, std::addressof(dst_perm), nullptr, std::addressof(num_dst_allocator_blocks),
  1661. dst_address, size, KMemoryState::All, KMemoryState::Stack, KMemoryPermission::None,
  1662. KMemoryPermission::None, KMemoryAttribute::All, KMemoryAttribute::None));
  1663. // Create an update allocator for the source.
  1664. Result src_allocator_result{ResultSuccess};
  1665. KMemoryBlockManagerUpdateAllocator src_allocator(std::addressof(src_allocator_result),
  1666. m_memory_block_slab_manager,
  1667. num_src_allocator_blocks);
  1668. R_TRY(src_allocator_result);
  1669. // Create an update allocator for the destination.
  1670. Result dst_allocator_result{ResultSuccess};
  1671. KMemoryBlockManagerUpdateAllocator dst_allocator(std::addressof(dst_allocator_result),
  1672. m_memory_block_slab_manager,
  1673. num_dst_allocator_blocks);
  1674. R_TRY(dst_allocator_result);
  1675. KPageGroup src_pages;
  1676. KPageGroup dst_pages;
  1677. const size_t num_pages{size / PageSize};
  1678. AddRegionToPages(src_address, num_pages, src_pages);
  1679. AddRegionToPages(dst_address, num_pages, dst_pages);
  1680. R_UNLESS(dst_pages.IsEqual(src_pages), ResultInvalidMemoryRegion);
  1681. {
  1682. auto block_guard = detail::ScopeExit([&] { MapPages(dst_address, dst_pages, dst_perm); });
  1683. R_TRY(Operate(dst_address, num_pages, KMemoryPermission::None, OperationType::Unmap));
  1684. R_TRY(Operate(src_address, num_pages, KMemoryPermission::UserReadWrite,
  1685. OperationType::ChangePermissions));
  1686. block_guard.Cancel();
  1687. }
  1688. // Apply the memory block updates.
  1689. m_memory_block_manager.Update(std::addressof(src_allocator), src_address, num_pages, src_state,
  1690. KMemoryPermission::UserReadWrite, KMemoryAttribute::None,
  1691. KMemoryBlockDisableMergeAttribute::None,
  1692. KMemoryBlockDisableMergeAttribute::Locked);
  1693. m_memory_block_manager.Update(std::addressof(dst_allocator), dst_address, num_pages,
  1694. KMemoryState::None, KMemoryPermission::None,
  1695. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  1696. KMemoryBlockDisableMergeAttribute::Normal);
  1697. R_SUCCEED();
  1698. }
  1699. Result KPageTable::MapPages(VAddr addr, const KPageGroup& page_linked_list,
  1700. KMemoryPermission perm) {
  1701. ASSERT(this->IsLockedByCurrentThread());
  1702. VAddr cur_addr{addr};
  1703. for (const auto& node : page_linked_list.Nodes()) {
  1704. if (const auto result{
  1705. Operate(cur_addr, node.GetNumPages(), perm, OperationType::Map, node.GetAddress())};
  1706. result.IsError()) {
  1707. const size_t num_pages{(addr - cur_addr) / PageSize};
  1708. ASSERT(Operate(addr, num_pages, KMemoryPermission::None, OperationType::Unmap)
  1709. .IsSuccess());
  1710. R_RETURN(result);
  1711. }
  1712. cur_addr += node.GetNumPages() * PageSize;
  1713. }
  1714. R_SUCCEED();
  1715. }
  1716. Result KPageTable::MapPages(VAddr address, KPageGroup& page_linked_list, KMemoryState state,
  1717. KMemoryPermission perm) {
  1718. // Check that the map is in range.
  1719. const size_t num_pages{page_linked_list.GetNumPages()};
  1720. const size_t size{num_pages * PageSize};
  1721. R_UNLESS(this->CanContain(address, size, state), ResultInvalidCurrentMemory);
  1722. // Lock the table.
  1723. KScopedLightLock lk(m_general_lock);
  1724. // Check the memory state.
  1725. R_TRY(this->CheckMemoryState(address, size, KMemoryState::All, KMemoryState::Free,
  1726. KMemoryPermission::None, KMemoryPermission::None,
  1727. KMemoryAttribute::None, KMemoryAttribute::None));
  1728. // Create an update allocator.
  1729. Result allocator_result{ResultSuccess};
  1730. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1731. m_memory_block_slab_manager);
  1732. // Map the pages.
  1733. R_TRY(MapPages(address, page_linked_list, perm));
  1734. // Update the blocks.
  1735. m_memory_block_manager.Update(std::addressof(allocator), address, num_pages, state, perm,
  1736. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  1737. KMemoryBlockDisableMergeAttribute::None);
  1738. R_SUCCEED();
  1739. }
  1740. Result KPageTable::MapPages(VAddr* out_addr, size_t num_pages, size_t alignment, PAddr phys_addr,
  1741. bool is_pa_valid, VAddr region_start, size_t region_num_pages,
  1742. KMemoryState state, KMemoryPermission perm) {
  1743. ASSERT(Common::IsAligned(alignment, PageSize) && alignment >= PageSize);
  1744. // Ensure this is a valid map request.
  1745. R_UNLESS(this->CanContain(region_start, region_num_pages * PageSize, state),
  1746. ResultInvalidCurrentMemory);
  1747. R_UNLESS(num_pages < region_num_pages, ResultOutOfMemory);
  1748. // Lock the table.
  1749. KScopedLightLock lk(m_general_lock);
  1750. // Find a random address to map at.
  1751. VAddr addr = this->FindFreeArea(region_start, region_num_pages, num_pages, alignment, 0,
  1752. this->GetNumGuardPages());
  1753. R_UNLESS(addr != 0, ResultOutOfMemory);
  1754. ASSERT(Common::IsAligned(addr, alignment));
  1755. ASSERT(this->CanContain(addr, num_pages * PageSize, state));
  1756. ASSERT(this->CheckMemoryState(addr, num_pages * PageSize, KMemoryState::All, KMemoryState::Free,
  1757. KMemoryPermission::None, KMemoryPermission::None,
  1758. KMemoryAttribute::None, KMemoryAttribute::None)
  1759. .IsSuccess());
  1760. // Create an update allocator.
  1761. Result allocator_result{ResultSuccess};
  1762. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1763. m_memory_block_slab_manager);
  1764. // Perform mapping operation.
  1765. if (is_pa_valid) {
  1766. R_TRY(this->Operate(addr, num_pages, perm, OperationType::Map, phys_addr));
  1767. } else {
  1768. UNIMPLEMENTED();
  1769. }
  1770. // Update the blocks.
  1771. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, state, perm,
  1772. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  1773. KMemoryBlockDisableMergeAttribute::None);
  1774. // We successfully mapped the pages.
  1775. *out_addr = addr;
  1776. R_SUCCEED();
  1777. }
  1778. Result KPageTable::UnmapPages(VAddr addr, const KPageGroup& page_linked_list) {
  1779. ASSERT(this->IsLockedByCurrentThread());
  1780. VAddr cur_addr{addr};
  1781. for (const auto& node : page_linked_list.Nodes()) {
  1782. if (const auto result{Operate(cur_addr, node.GetNumPages(), KMemoryPermission::None,
  1783. OperationType::Unmap)};
  1784. result.IsError()) {
  1785. R_RETURN(result);
  1786. }
  1787. cur_addr += node.GetNumPages() * PageSize;
  1788. }
  1789. R_SUCCEED();
  1790. }
  1791. Result KPageTable::UnmapPages(VAddr address, KPageGroup& page_linked_list, KMemoryState state) {
  1792. // Check that the unmap is in range.
  1793. const size_t num_pages{page_linked_list.GetNumPages()};
  1794. const size_t size{num_pages * PageSize};
  1795. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  1796. // Lock the table.
  1797. KScopedLightLock lk(m_general_lock);
  1798. // Check the memory state.
  1799. size_t num_allocator_blocks;
  1800. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), address, size,
  1801. KMemoryState::All, state, KMemoryPermission::None,
  1802. KMemoryPermission::None, KMemoryAttribute::All,
  1803. KMemoryAttribute::None));
  1804. // Create an update allocator.
  1805. Result allocator_result{ResultSuccess};
  1806. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1807. m_memory_block_slab_manager, num_allocator_blocks);
  1808. R_TRY(allocator_result);
  1809. // Perform the unmap.
  1810. R_TRY(UnmapPages(address, page_linked_list));
  1811. // Update the blocks.
  1812. m_memory_block_manager.Update(std::addressof(allocator), address, num_pages, KMemoryState::Free,
  1813. KMemoryPermission::None, KMemoryAttribute::None,
  1814. KMemoryBlockDisableMergeAttribute::None,
  1815. KMemoryBlockDisableMergeAttribute::Normal);
  1816. R_SUCCEED();
  1817. }
  1818. Result KPageTable::UnmapPages(VAddr address, size_t num_pages, KMemoryState state) {
  1819. // Check that the unmap is in range.
  1820. const size_t size = num_pages * PageSize;
  1821. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  1822. // Lock the table.
  1823. KScopedLightLock lk(m_general_lock);
  1824. // Check the memory state.
  1825. size_t num_allocator_blocks{};
  1826. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), address, size,
  1827. KMemoryState::All, state, KMemoryPermission::None,
  1828. KMemoryPermission::None, KMemoryAttribute::All,
  1829. KMemoryAttribute::None));
  1830. // Create an update allocator.
  1831. Result allocator_result{ResultSuccess};
  1832. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1833. m_memory_block_slab_manager, num_allocator_blocks);
  1834. R_TRY(allocator_result);
  1835. // Perform the unmap.
  1836. R_TRY(Operate(address, num_pages, KMemoryPermission::None, OperationType::Unmap));
  1837. // Update the blocks.
  1838. m_memory_block_manager.Update(std::addressof(allocator), address, num_pages, KMemoryState::Free,
  1839. KMemoryPermission::None, KMemoryAttribute::None,
  1840. KMemoryBlockDisableMergeAttribute::None,
  1841. KMemoryBlockDisableMergeAttribute::Normal);
  1842. R_SUCCEED();
  1843. }
  1844. Result KPageTable::MakeAndOpenPageGroup(KPageGroup* out, VAddr address, size_t num_pages,
  1845. KMemoryState state_mask, KMemoryState state,
  1846. KMemoryPermission perm_mask, KMemoryPermission perm,
  1847. KMemoryAttribute attr_mask, KMemoryAttribute attr) {
  1848. // Ensure that the page group isn't null.
  1849. ASSERT(out != nullptr);
  1850. // Make sure that the region we're mapping is valid for the table.
  1851. const size_t size = num_pages * PageSize;
  1852. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  1853. // Lock the table.
  1854. KScopedLightLock lk(m_general_lock);
  1855. // Check if state allows us to create the group.
  1856. R_TRY(this->CheckMemoryState(address, size, state_mask | KMemoryState::FlagReferenceCounted,
  1857. state | KMemoryState::FlagReferenceCounted, perm_mask, perm,
  1858. attr_mask, attr));
  1859. // Create a new page group for the region.
  1860. R_TRY(this->MakePageGroup(*out, address, num_pages));
  1861. R_SUCCEED();
  1862. }
  1863. Result KPageTable::SetProcessMemoryPermission(VAddr addr, size_t size,
  1864. Svc::MemoryPermission svc_perm) {
  1865. const size_t num_pages = size / PageSize;
  1866. // Lock the table.
  1867. KScopedLightLock lk(m_general_lock);
  1868. // Verify we can change the memory permission.
  1869. KMemoryState old_state;
  1870. KMemoryPermission old_perm;
  1871. size_t num_allocator_blocks;
  1872. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm), nullptr,
  1873. std::addressof(num_allocator_blocks), addr, size,
  1874. KMemoryState::FlagCode, KMemoryState::FlagCode,
  1875. KMemoryPermission::None, KMemoryPermission::None,
  1876. KMemoryAttribute::All, KMemoryAttribute::None));
  1877. // Determine new perm/state.
  1878. const KMemoryPermission new_perm = ConvertToKMemoryPermission(svc_perm);
  1879. KMemoryState new_state = old_state;
  1880. const bool is_w = (new_perm & KMemoryPermission::UserWrite) == KMemoryPermission::UserWrite;
  1881. const bool is_x = (new_perm & KMemoryPermission::UserExecute) == KMemoryPermission::UserExecute;
  1882. const bool was_x =
  1883. (old_perm & KMemoryPermission::UserExecute) == KMemoryPermission::UserExecute;
  1884. ASSERT(!(is_w && is_x));
  1885. if (is_w) {
  1886. switch (old_state) {
  1887. case KMemoryState::Code:
  1888. new_state = KMemoryState::CodeData;
  1889. break;
  1890. case KMemoryState::AliasCode:
  1891. new_state = KMemoryState::AliasCodeData;
  1892. break;
  1893. default:
  1894. ASSERT(false);
  1895. }
  1896. }
  1897. // Succeed if there's nothing to do.
  1898. R_SUCCEED_IF(old_perm == new_perm && old_state == new_state);
  1899. // Create an update allocator.
  1900. Result allocator_result{ResultSuccess};
  1901. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1902. m_memory_block_slab_manager, num_allocator_blocks);
  1903. R_TRY(allocator_result);
  1904. // Perform mapping operation.
  1905. const auto operation =
  1906. was_x ? OperationType::ChangePermissionsAndRefresh : OperationType::ChangePermissions;
  1907. R_TRY(Operate(addr, num_pages, new_perm, operation));
  1908. // Update the blocks.
  1909. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, new_state, new_perm,
  1910. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  1911. KMemoryBlockDisableMergeAttribute::None);
  1912. // Ensure cache coherency, if we're setting pages as executable.
  1913. if (is_x) {
  1914. m_system.InvalidateCpuInstructionCacheRange(addr, size);
  1915. }
  1916. R_SUCCEED();
  1917. }
  1918. KMemoryInfo KPageTable::QueryInfoImpl(VAddr addr) {
  1919. KScopedLightLock lk(m_general_lock);
  1920. return m_memory_block_manager.FindBlock(addr)->GetMemoryInfo();
  1921. }
  1922. KMemoryInfo KPageTable::QueryInfo(VAddr addr) {
  1923. if (!Contains(addr, 1)) {
  1924. return {
  1925. .m_address = m_address_space_end,
  1926. .m_size = 0 - m_address_space_end,
  1927. .m_state = static_cast<KMemoryState>(Svc::MemoryState::Inaccessible),
  1928. .m_device_disable_merge_left_count = 0,
  1929. .m_device_disable_merge_right_count = 0,
  1930. .m_ipc_lock_count = 0,
  1931. .m_device_use_count = 0,
  1932. .m_ipc_disable_merge_count = 0,
  1933. .m_permission = KMemoryPermission::None,
  1934. .m_attribute = KMemoryAttribute::None,
  1935. .m_original_permission = KMemoryPermission::None,
  1936. .m_disable_merge_attribute = KMemoryBlockDisableMergeAttribute::None,
  1937. };
  1938. }
  1939. return QueryInfoImpl(addr);
  1940. }
  1941. Result KPageTable::SetMemoryPermission(VAddr addr, size_t size, Svc::MemoryPermission svc_perm) {
  1942. const size_t num_pages = size / PageSize;
  1943. // Lock the table.
  1944. KScopedLightLock lk(m_general_lock);
  1945. // Verify we can change the memory permission.
  1946. KMemoryState old_state;
  1947. KMemoryPermission old_perm;
  1948. size_t num_allocator_blocks;
  1949. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm), nullptr,
  1950. std::addressof(num_allocator_blocks), addr, size,
  1951. KMemoryState::FlagCanReprotect, KMemoryState::FlagCanReprotect,
  1952. KMemoryPermission::None, KMemoryPermission::None,
  1953. KMemoryAttribute::All, KMemoryAttribute::None));
  1954. // Determine new perm.
  1955. const KMemoryPermission new_perm = ConvertToKMemoryPermission(svc_perm);
  1956. R_SUCCEED_IF(old_perm == new_perm);
  1957. // Create an update allocator.
  1958. Result allocator_result{ResultSuccess};
  1959. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1960. m_memory_block_slab_manager, num_allocator_blocks);
  1961. R_TRY(allocator_result);
  1962. // Perform mapping operation.
  1963. R_TRY(Operate(addr, num_pages, new_perm, OperationType::ChangePermissions));
  1964. // Update the blocks.
  1965. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, new_perm,
  1966. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::None,
  1967. KMemoryBlockDisableMergeAttribute::None);
  1968. R_SUCCEED();
  1969. }
  1970. Result KPageTable::SetMemoryAttribute(VAddr addr, size_t size, u32 mask, u32 attr) {
  1971. const size_t num_pages = size / PageSize;
  1972. ASSERT((static_cast<KMemoryAttribute>(mask) | KMemoryAttribute::SetMask) ==
  1973. KMemoryAttribute::SetMask);
  1974. // Lock the table.
  1975. KScopedLightLock lk(m_general_lock);
  1976. // Verify we can change the memory attribute.
  1977. KMemoryState old_state;
  1978. KMemoryPermission old_perm;
  1979. KMemoryAttribute old_attr;
  1980. size_t num_allocator_blocks;
  1981. constexpr auto AttributeTestMask =
  1982. ~(KMemoryAttribute::SetMask | KMemoryAttribute::DeviceShared);
  1983. R_TRY(this->CheckMemoryState(
  1984. std::addressof(old_state), std::addressof(old_perm), std::addressof(old_attr),
  1985. std::addressof(num_allocator_blocks), addr, size, KMemoryState::FlagCanChangeAttribute,
  1986. KMemoryState::FlagCanChangeAttribute, KMemoryPermission::None, KMemoryPermission::None,
  1987. AttributeTestMask, KMemoryAttribute::None, ~AttributeTestMask));
  1988. // Create an update allocator.
  1989. Result allocator_result{ResultSuccess};
  1990. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  1991. m_memory_block_slab_manager, num_allocator_blocks);
  1992. R_TRY(allocator_result);
  1993. // Determine the new attribute.
  1994. const KMemoryAttribute new_attr =
  1995. static_cast<KMemoryAttribute>(((old_attr & static_cast<KMemoryAttribute>(~mask)) |
  1996. static_cast<KMemoryAttribute>(attr & mask)));
  1997. // Perform operation.
  1998. this->Operate(addr, num_pages, old_perm, OperationType::ChangePermissionsAndRefresh);
  1999. // Update the blocks.
  2000. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, old_perm,
  2001. new_attr, KMemoryBlockDisableMergeAttribute::None,
  2002. KMemoryBlockDisableMergeAttribute::None);
  2003. R_SUCCEED();
  2004. }
  2005. Result KPageTable::SetMaxHeapSize(size_t size) {
  2006. // Lock the table.
  2007. KScopedLightLock lk(m_general_lock);
  2008. // Only process page tables are allowed to set heap size.
  2009. ASSERT(!this->IsKernel());
  2010. m_max_heap_size = size;
  2011. R_SUCCEED();
  2012. }
  2013. Result KPageTable::SetHeapSize(VAddr* out, size_t size) {
  2014. // Lock the physical memory mutex.
  2015. KScopedLightLock map_phys_mem_lk(m_map_physical_memory_lock);
  2016. // Try to perform a reduction in heap, instead of an extension.
  2017. VAddr cur_address{};
  2018. size_t allocation_size{};
  2019. {
  2020. // Lock the table.
  2021. KScopedLightLock lk(m_general_lock);
  2022. // Validate that setting heap size is possible at all.
  2023. R_UNLESS(!m_is_kernel, ResultOutOfMemory);
  2024. R_UNLESS(size <= static_cast<size_t>(m_heap_region_end - m_heap_region_start),
  2025. ResultOutOfMemory);
  2026. R_UNLESS(size <= m_max_heap_size, ResultOutOfMemory);
  2027. if (size < GetHeapSize()) {
  2028. // The size being requested is less than the current size, so we need to free the end of
  2029. // the heap.
  2030. // Validate memory state.
  2031. size_t num_allocator_blocks;
  2032. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks),
  2033. m_heap_region_start + size, GetHeapSize() - size,
  2034. KMemoryState::All, KMemoryState::Normal,
  2035. KMemoryPermission::All, KMemoryPermission::UserReadWrite,
  2036. KMemoryAttribute::All, KMemoryAttribute::None));
  2037. // Create an update allocator.
  2038. Result allocator_result{ResultSuccess};
  2039. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2040. m_memory_block_slab_manager,
  2041. num_allocator_blocks);
  2042. R_TRY(allocator_result);
  2043. // Unmap the end of the heap.
  2044. const auto num_pages = (GetHeapSize() - size) / PageSize;
  2045. R_TRY(Operate(m_heap_region_start + size, num_pages, KMemoryPermission::None,
  2046. OperationType::Unmap));
  2047. // Release the memory from the resource limit.
  2048. m_resource_limit->Release(LimitableResource::PhysicalMemory, num_pages * PageSize);
  2049. // Apply the memory block update.
  2050. m_memory_block_manager.Update(std::addressof(allocator), m_heap_region_start + size,
  2051. num_pages, KMemoryState::Free, KMemoryPermission::None,
  2052. KMemoryAttribute::None,
  2053. KMemoryBlockDisableMergeAttribute::None,
  2054. size == 0 ? KMemoryBlockDisableMergeAttribute::Normal
  2055. : KMemoryBlockDisableMergeAttribute::None);
  2056. // Update the current heap end.
  2057. m_current_heap_end = m_heap_region_start + size;
  2058. // Set the output.
  2059. *out = m_heap_region_start;
  2060. R_SUCCEED();
  2061. } else if (size == GetHeapSize()) {
  2062. // The size requested is exactly the current size.
  2063. *out = m_heap_region_start;
  2064. R_SUCCEED();
  2065. } else {
  2066. // We have to allocate memory. Determine how much to allocate and where while the table
  2067. // is locked.
  2068. cur_address = m_current_heap_end;
  2069. allocation_size = size - GetHeapSize();
  2070. }
  2071. }
  2072. // Reserve memory for the heap extension.
  2073. KScopedResourceReservation memory_reservation(
  2074. m_resource_limit, LimitableResource::PhysicalMemory, allocation_size);
  2075. R_UNLESS(memory_reservation.Succeeded(), ResultLimitReached);
  2076. // Allocate pages for the heap extension.
  2077. KPageGroup pg;
  2078. R_TRY(m_system.Kernel().MemoryManager().AllocateAndOpen(
  2079. &pg, allocation_size / PageSize,
  2080. KMemoryManager::EncodeOption(m_memory_pool, m_allocation_option)));
  2081. // Clear all the newly allocated pages.
  2082. for (const auto& it : pg.Nodes()) {
  2083. std::memset(m_system.DeviceMemory().GetPointer<void>(it.GetAddress()), m_heap_fill_value,
  2084. it.GetSize());
  2085. }
  2086. // Map the pages.
  2087. {
  2088. // Lock the table.
  2089. KScopedLightLock lk(m_general_lock);
  2090. // Ensure that the heap hasn't changed since we began executing.
  2091. ASSERT(cur_address == m_current_heap_end);
  2092. // Check the memory state.
  2093. size_t num_allocator_blocks{};
  2094. R_TRY(this->CheckMemoryState(std::addressof(num_allocator_blocks), m_current_heap_end,
  2095. allocation_size, KMemoryState::All, KMemoryState::Free,
  2096. KMemoryPermission::None, KMemoryPermission::None,
  2097. KMemoryAttribute::None, KMemoryAttribute::None));
  2098. // Create an update allocator.
  2099. Result allocator_result{ResultSuccess};
  2100. KMemoryBlockManagerUpdateAllocator allocator(
  2101. std::addressof(allocator_result), m_memory_block_slab_manager, num_allocator_blocks);
  2102. R_TRY(allocator_result);
  2103. // Map the pages.
  2104. const auto num_pages = allocation_size / PageSize;
  2105. R_TRY(Operate(m_current_heap_end, num_pages, pg, OperationType::MapGroup));
  2106. // Clear all the newly allocated pages.
  2107. for (size_t cur_page = 0; cur_page < num_pages; ++cur_page) {
  2108. std::memset(m_system.Memory().GetPointer(m_current_heap_end + (cur_page * PageSize)), 0,
  2109. PageSize);
  2110. }
  2111. // We succeeded, so commit our memory reservation.
  2112. memory_reservation.Commit();
  2113. // Apply the memory block update.
  2114. m_memory_block_manager.Update(
  2115. std::addressof(allocator), m_current_heap_end, num_pages, KMemoryState::Normal,
  2116. KMemoryPermission::UserReadWrite, KMemoryAttribute::None,
  2117. m_heap_region_start == m_current_heap_end ? KMemoryBlockDisableMergeAttribute::Normal
  2118. : KMemoryBlockDisableMergeAttribute::None,
  2119. KMemoryBlockDisableMergeAttribute::None);
  2120. // Update the current heap end.
  2121. m_current_heap_end = m_heap_region_start + size;
  2122. // Set the output.
  2123. *out = m_heap_region_start;
  2124. R_SUCCEED();
  2125. }
  2126. }
  2127. ResultVal<VAddr> KPageTable::AllocateAndMapMemory(size_t needed_num_pages, size_t align,
  2128. bool is_map_only, VAddr region_start,
  2129. size_t region_num_pages, KMemoryState state,
  2130. KMemoryPermission perm, PAddr map_addr) {
  2131. KScopedLightLock lk(m_general_lock);
  2132. R_UNLESS(CanContain(region_start, region_num_pages * PageSize, state),
  2133. ResultInvalidCurrentMemory);
  2134. R_UNLESS(region_num_pages > needed_num_pages, ResultOutOfMemory);
  2135. const VAddr addr{
  2136. AllocateVirtualMemory(region_start, region_num_pages, needed_num_pages, align)};
  2137. R_UNLESS(addr, ResultOutOfMemory);
  2138. // Create an update allocator.
  2139. Result allocator_result{ResultSuccess};
  2140. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2141. m_memory_block_slab_manager);
  2142. if (is_map_only) {
  2143. R_TRY(Operate(addr, needed_num_pages, perm, OperationType::Map, map_addr));
  2144. } else {
  2145. KPageGroup page_group;
  2146. R_TRY(m_system.Kernel().MemoryManager().AllocateForProcess(
  2147. &page_group, needed_num_pages,
  2148. KMemoryManager::EncodeOption(m_memory_pool, m_allocation_option), 0, 0));
  2149. R_TRY(Operate(addr, needed_num_pages, page_group, OperationType::MapGroup));
  2150. }
  2151. // Update the blocks.
  2152. m_memory_block_manager.Update(std::addressof(allocator), addr, needed_num_pages, state, perm,
  2153. KMemoryAttribute::None, KMemoryBlockDisableMergeAttribute::Normal,
  2154. KMemoryBlockDisableMergeAttribute::None);
  2155. return addr;
  2156. }
  2157. Result KPageTable::LockForMapDeviceAddressSpace(bool* out_is_io, VAddr address, size_t size,
  2158. KMemoryPermission perm, bool is_aligned,
  2159. bool check_heap) {
  2160. // Lightly validate the range before doing anything else.
  2161. const size_t num_pages = size / PageSize;
  2162. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  2163. // Lock the table.
  2164. KScopedLightLock lk(m_general_lock);
  2165. // Check the memory state.
  2166. const auto test_state =
  2167. (is_aligned ? KMemoryState::FlagCanAlignedDeviceMap : KMemoryState::FlagCanDeviceMap) |
  2168. (check_heap ? KMemoryState::FlagReferenceCounted : KMemoryState::None);
  2169. size_t num_allocator_blocks;
  2170. KMemoryState old_state;
  2171. R_TRY(this->CheckMemoryState(std::addressof(old_state), nullptr, nullptr,
  2172. std::addressof(num_allocator_blocks), address, size, test_state,
  2173. test_state, perm, perm,
  2174. KMemoryAttribute::IpcLocked | KMemoryAttribute::Locked,
  2175. KMemoryAttribute::None, KMemoryAttribute::DeviceShared));
  2176. // Create an update allocator.
  2177. Result allocator_result;
  2178. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2179. m_memory_block_slab_manager, num_allocator_blocks);
  2180. R_TRY(allocator_result);
  2181. // Update the memory blocks.
  2182. m_memory_block_manager.UpdateLock(std::addressof(allocator), address, num_pages,
  2183. &KMemoryBlock::ShareToDevice, KMemoryPermission::None);
  2184. // Set whether the locked memory was io.
  2185. *out_is_io = old_state == KMemoryState::Io;
  2186. R_SUCCEED();
  2187. }
  2188. Result KPageTable::LockForUnmapDeviceAddressSpace(VAddr address, size_t size, bool check_heap) {
  2189. // Lightly validate the range before doing anything else.
  2190. const size_t num_pages = size / PageSize;
  2191. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  2192. // Lock the table.
  2193. KScopedLightLock lk(m_general_lock);
  2194. // Check the memory state.
  2195. const auto test_state = KMemoryState::FlagCanDeviceMap |
  2196. (check_heap ? KMemoryState::FlagReferenceCounted : KMemoryState::None);
  2197. size_t num_allocator_blocks;
  2198. R_TRY(this->CheckMemoryStateContiguous(
  2199. std::addressof(num_allocator_blocks), address, size, test_state, test_state,
  2200. KMemoryPermission::None, KMemoryPermission::None,
  2201. KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked, KMemoryAttribute::DeviceShared));
  2202. // Create an update allocator.
  2203. Result allocator_result;
  2204. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2205. m_memory_block_slab_manager, num_allocator_blocks);
  2206. R_TRY(allocator_result);
  2207. // Update the memory blocks.
  2208. const KMemoryBlockManager::MemoryBlockLockFunction lock_func =
  2209. m_enable_device_address_space_merge
  2210. ? &KMemoryBlock::UpdateDeviceDisableMergeStateForShare
  2211. : &KMemoryBlock::UpdateDeviceDisableMergeStateForShareRight;
  2212. m_memory_block_manager.UpdateLock(std::addressof(allocator), address, num_pages, lock_func,
  2213. KMemoryPermission::None);
  2214. R_SUCCEED();
  2215. }
  2216. Result KPageTable::UnlockForDeviceAddressSpace(VAddr address, size_t size) {
  2217. // Lightly validate the range before doing anything else.
  2218. const size_t num_pages = size / PageSize;
  2219. R_UNLESS(this->Contains(address, size), ResultInvalidCurrentMemory);
  2220. // Lock the table.
  2221. KScopedLightLock lk(m_general_lock);
  2222. // Check the memory state.
  2223. size_t num_allocator_blocks;
  2224. R_TRY(this->CheckMemoryStateContiguous(
  2225. std::addressof(num_allocator_blocks), address, size, KMemoryState::FlagCanDeviceMap,
  2226. KMemoryState::FlagCanDeviceMap, KMemoryPermission::None, KMemoryPermission::None,
  2227. KMemoryAttribute::DeviceShared | KMemoryAttribute::Locked, KMemoryAttribute::DeviceShared));
  2228. // Create an update allocator.
  2229. Result allocator_result{ResultSuccess};
  2230. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2231. m_memory_block_slab_manager, num_allocator_blocks);
  2232. R_TRY(allocator_result);
  2233. // Update the memory blocks.
  2234. m_memory_block_manager.UpdateLock(std::addressof(allocator), address, num_pages,
  2235. &KMemoryBlock::UnshareToDevice, KMemoryPermission::None);
  2236. R_SUCCEED();
  2237. }
  2238. Result KPageTable::LockForIpcUserBuffer(PAddr* out, VAddr address, size_t size) {
  2239. R_RETURN(this->LockMemoryAndOpen(
  2240. nullptr, out, address, size, KMemoryState::FlagCanIpcUserBuffer,
  2241. KMemoryState::FlagCanIpcUserBuffer, KMemoryPermission::All,
  2242. KMemoryPermission::UserReadWrite, KMemoryAttribute::All, KMemoryAttribute::None,
  2243. KMemoryPermission::NotMapped | KMemoryPermission::KernelReadWrite,
  2244. KMemoryAttribute::Locked));
  2245. }
  2246. Result KPageTable::UnlockForIpcUserBuffer(VAddr address, size_t size) {
  2247. R_RETURN(this->UnlockMemory(address, size, KMemoryState::FlagCanIpcUserBuffer,
  2248. KMemoryState::FlagCanIpcUserBuffer, KMemoryPermission::None,
  2249. KMemoryPermission::None, KMemoryAttribute::All,
  2250. KMemoryAttribute::Locked, KMemoryPermission::UserReadWrite,
  2251. KMemoryAttribute::Locked, nullptr));
  2252. }
  2253. Result KPageTable::LockForCodeMemory(KPageGroup* out, VAddr addr, size_t size) {
  2254. R_RETURN(this->LockMemoryAndOpen(
  2255. out, nullptr, addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory,
  2256. KMemoryPermission::All, KMemoryPermission::UserReadWrite, KMemoryAttribute::All,
  2257. KMemoryAttribute::None, KMemoryPermission::NotMapped | KMemoryPermission::KernelReadWrite,
  2258. KMemoryAttribute::Locked));
  2259. }
  2260. Result KPageTable::UnlockForCodeMemory(VAddr addr, size_t size, const KPageGroup& pg) {
  2261. R_RETURN(this->UnlockMemory(
  2262. addr, size, KMemoryState::FlagCanCodeMemory, KMemoryState::FlagCanCodeMemory,
  2263. KMemoryPermission::None, KMemoryPermission::None, KMemoryAttribute::All,
  2264. KMemoryAttribute::Locked, KMemoryPermission::UserReadWrite, KMemoryAttribute::Locked, &pg));
  2265. }
  2266. bool KPageTable::IsRegionContiguous(VAddr addr, u64 size) const {
  2267. auto start_ptr = m_system.DeviceMemory().GetPointer<u8>(addr);
  2268. for (u64 offset{}; offset < size; offset += PageSize) {
  2269. if (start_ptr != m_system.DeviceMemory().GetPointer<u8>(addr + offset)) {
  2270. return false;
  2271. }
  2272. start_ptr += PageSize;
  2273. }
  2274. return true;
  2275. }
  2276. void KPageTable::AddRegionToPages(VAddr start, size_t num_pages, KPageGroup& page_linked_list) {
  2277. VAddr addr{start};
  2278. while (addr < start + (num_pages * PageSize)) {
  2279. const PAddr paddr{GetPhysicalAddr(addr)};
  2280. ASSERT(paddr != 0);
  2281. page_linked_list.AddBlock(paddr, 1);
  2282. addr += PageSize;
  2283. }
  2284. }
  2285. VAddr KPageTable::AllocateVirtualMemory(VAddr start, size_t region_num_pages, u64 needed_num_pages,
  2286. size_t align) {
  2287. if (m_enable_aslr) {
  2288. UNIMPLEMENTED();
  2289. }
  2290. return m_memory_block_manager.FindFreeArea(start, region_num_pages, needed_num_pages, align, 0,
  2291. IsKernel() ? 1 : 4);
  2292. }
  2293. Result KPageTable::Operate(VAddr addr, size_t num_pages, const KPageGroup& page_group,
  2294. OperationType operation) {
  2295. ASSERT(this->IsLockedByCurrentThread());
  2296. ASSERT(Common::IsAligned(addr, PageSize));
  2297. ASSERT(num_pages > 0);
  2298. ASSERT(num_pages == page_group.GetNumPages());
  2299. for (const auto& node : page_group.Nodes()) {
  2300. const size_t size{node.GetNumPages() * PageSize};
  2301. switch (operation) {
  2302. case OperationType::MapGroup:
  2303. m_system.Memory().MapMemoryRegion(*m_page_table_impl, addr, size, node.GetAddress());
  2304. break;
  2305. default:
  2306. ASSERT(false);
  2307. }
  2308. addr += size;
  2309. }
  2310. R_SUCCEED();
  2311. }
  2312. Result KPageTable::Operate(VAddr addr, size_t num_pages, KMemoryPermission perm,
  2313. OperationType operation, PAddr map_addr) {
  2314. ASSERT(this->IsLockedByCurrentThread());
  2315. ASSERT(num_pages > 0);
  2316. ASSERT(Common::IsAligned(addr, PageSize));
  2317. ASSERT(ContainsPages(addr, num_pages));
  2318. switch (operation) {
  2319. case OperationType::Unmap:
  2320. m_system.Memory().UnmapRegion(*m_page_table_impl, addr, num_pages * PageSize);
  2321. break;
  2322. case OperationType::Map: {
  2323. ASSERT(map_addr);
  2324. ASSERT(Common::IsAligned(map_addr, PageSize));
  2325. m_system.Memory().MapMemoryRegion(*m_page_table_impl, addr, num_pages * PageSize, map_addr);
  2326. break;
  2327. }
  2328. case OperationType::Separate: {
  2329. // HACK: Unimplemented.
  2330. break;
  2331. }
  2332. case OperationType::ChangePermissions:
  2333. case OperationType::ChangePermissionsAndRefresh:
  2334. break;
  2335. default:
  2336. ASSERT(false);
  2337. }
  2338. R_SUCCEED();
  2339. }
  2340. void KPageTable::FinalizeUpdate(PageLinkedList* page_list) {
  2341. while (page_list->Peek()) {
  2342. [[maybe_unused]] auto page = page_list->Pop();
  2343. // TODO(bunnei): Free pages once they are allocated in guest memory
  2344. // ASSERT(this->GetPageTableManager().IsInPageTableHeap(page));
  2345. // ASSERT(this->GetPageTableManager().GetRefCount(page) == 0);
  2346. // this->GetPageTableManager().Free(page);
  2347. }
  2348. }
  2349. VAddr KPageTable::GetRegionAddress(KMemoryState state) const {
  2350. switch (state) {
  2351. case KMemoryState::Free:
  2352. case KMemoryState::Kernel:
  2353. return m_address_space_start;
  2354. case KMemoryState::Normal:
  2355. return m_heap_region_start;
  2356. case KMemoryState::Ipc:
  2357. case KMemoryState::NonSecureIpc:
  2358. case KMemoryState::NonDeviceIpc:
  2359. return m_alias_region_start;
  2360. case KMemoryState::Stack:
  2361. return m_stack_region_start;
  2362. case KMemoryState::Static:
  2363. case KMemoryState::ThreadLocal:
  2364. return m_kernel_map_region_start;
  2365. case KMemoryState::Io:
  2366. case KMemoryState::Shared:
  2367. case KMemoryState::AliasCode:
  2368. case KMemoryState::AliasCodeData:
  2369. case KMemoryState::Transfered:
  2370. case KMemoryState::SharedTransfered:
  2371. case KMemoryState::SharedCode:
  2372. case KMemoryState::GeneratedCode:
  2373. case KMemoryState::CodeOut:
  2374. case KMemoryState::Coverage:
  2375. case KMemoryState::Insecure:
  2376. return m_alias_code_region_start;
  2377. case KMemoryState::Code:
  2378. case KMemoryState::CodeData:
  2379. return m_code_region_start;
  2380. default:
  2381. UNREACHABLE();
  2382. }
  2383. }
  2384. size_t KPageTable::GetRegionSize(KMemoryState state) const {
  2385. switch (state) {
  2386. case KMemoryState::Free:
  2387. case KMemoryState::Kernel:
  2388. return m_address_space_end - m_address_space_start;
  2389. case KMemoryState::Normal:
  2390. return m_heap_region_end - m_heap_region_start;
  2391. case KMemoryState::Ipc:
  2392. case KMemoryState::NonSecureIpc:
  2393. case KMemoryState::NonDeviceIpc:
  2394. return m_alias_region_end - m_alias_region_start;
  2395. case KMemoryState::Stack:
  2396. return m_stack_region_end - m_stack_region_start;
  2397. case KMemoryState::Static:
  2398. case KMemoryState::ThreadLocal:
  2399. return m_kernel_map_region_end - m_kernel_map_region_start;
  2400. case KMemoryState::Io:
  2401. case KMemoryState::Shared:
  2402. case KMemoryState::AliasCode:
  2403. case KMemoryState::AliasCodeData:
  2404. case KMemoryState::Transfered:
  2405. case KMemoryState::SharedTransfered:
  2406. case KMemoryState::SharedCode:
  2407. case KMemoryState::GeneratedCode:
  2408. case KMemoryState::CodeOut:
  2409. case KMemoryState::Coverage:
  2410. case KMemoryState::Insecure:
  2411. return m_alias_code_region_end - m_alias_code_region_start;
  2412. case KMemoryState::Code:
  2413. case KMemoryState::CodeData:
  2414. return m_code_region_end - m_code_region_start;
  2415. default:
  2416. UNREACHABLE();
  2417. }
  2418. }
  2419. bool KPageTable::CanContain(VAddr addr, size_t size, KMemoryState state) const {
  2420. const VAddr end = addr + size;
  2421. const VAddr last = end - 1;
  2422. const VAddr region_start = this->GetRegionAddress(state);
  2423. const size_t region_size = this->GetRegionSize(state);
  2424. const bool is_in_region =
  2425. region_start <= addr && addr < end && last <= region_start + region_size - 1;
  2426. const bool is_in_heap = !(end <= m_heap_region_start || m_heap_region_end <= addr ||
  2427. m_heap_region_start == m_heap_region_end);
  2428. const bool is_in_alias = !(end <= m_alias_region_start || m_alias_region_end <= addr ||
  2429. m_alias_region_start == m_alias_region_end);
  2430. switch (state) {
  2431. case KMemoryState::Free:
  2432. case KMemoryState::Kernel:
  2433. return is_in_region;
  2434. case KMemoryState::Io:
  2435. case KMemoryState::Static:
  2436. case KMemoryState::Code:
  2437. case KMemoryState::CodeData:
  2438. case KMemoryState::Shared:
  2439. case KMemoryState::AliasCode:
  2440. case KMemoryState::AliasCodeData:
  2441. case KMemoryState::Stack:
  2442. case KMemoryState::ThreadLocal:
  2443. case KMemoryState::Transfered:
  2444. case KMemoryState::SharedTransfered:
  2445. case KMemoryState::SharedCode:
  2446. case KMemoryState::GeneratedCode:
  2447. case KMemoryState::CodeOut:
  2448. case KMemoryState::Coverage:
  2449. case KMemoryState::Insecure:
  2450. return is_in_region && !is_in_heap && !is_in_alias;
  2451. case KMemoryState::Normal:
  2452. ASSERT(is_in_heap);
  2453. return is_in_region && !is_in_alias;
  2454. case KMemoryState::Ipc:
  2455. case KMemoryState::NonSecureIpc:
  2456. case KMemoryState::NonDeviceIpc:
  2457. ASSERT(is_in_alias);
  2458. return is_in_region && !is_in_heap;
  2459. default:
  2460. return false;
  2461. }
  2462. }
  2463. Result KPageTable::CheckMemoryState(const KMemoryInfo& info, KMemoryState state_mask,
  2464. KMemoryState state, KMemoryPermission perm_mask,
  2465. KMemoryPermission perm, KMemoryAttribute attr_mask,
  2466. KMemoryAttribute attr) const {
  2467. // Validate the states match expectation.
  2468. R_UNLESS((info.m_state & state_mask) == state, ResultInvalidCurrentMemory);
  2469. R_UNLESS((info.m_permission & perm_mask) == perm, ResultInvalidCurrentMemory);
  2470. R_UNLESS((info.m_attribute & attr_mask) == attr, ResultInvalidCurrentMemory);
  2471. R_SUCCEED();
  2472. }
  2473. Result KPageTable::CheckMemoryStateContiguous(size_t* out_blocks_needed, VAddr addr, size_t size,
  2474. KMemoryState state_mask, KMemoryState state,
  2475. KMemoryPermission perm_mask, KMemoryPermission perm,
  2476. KMemoryAttribute attr_mask,
  2477. KMemoryAttribute attr) const {
  2478. ASSERT(this->IsLockedByCurrentThread());
  2479. // Get information about the first block.
  2480. const VAddr last_addr = addr + size - 1;
  2481. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(addr);
  2482. KMemoryInfo info = it->GetMemoryInfo();
  2483. // If the start address isn't aligned, we need a block.
  2484. const size_t blocks_for_start_align =
  2485. (Common::AlignDown(addr, PageSize) != info.GetAddress()) ? 1 : 0;
  2486. while (true) {
  2487. // Validate against the provided masks.
  2488. R_TRY(this->CheckMemoryState(info, state_mask, state, perm_mask, perm, attr_mask, attr));
  2489. // Break once we're done.
  2490. if (last_addr <= info.GetLastAddress()) {
  2491. break;
  2492. }
  2493. // Advance our iterator.
  2494. it++;
  2495. ASSERT(it != m_memory_block_manager.cend());
  2496. info = it->GetMemoryInfo();
  2497. }
  2498. // If the end address isn't aligned, we need a block.
  2499. const size_t blocks_for_end_align =
  2500. (Common::AlignUp(addr + size, PageSize) != info.GetEndAddress()) ? 1 : 0;
  2501. if (out_blocks_needed != nullptr) {
  2502. *out_blocks_needed = blocks_for_start_align + blocks_for_end_align;
  2503. }
  2504. R_SUCCEED();
  2505. }
  2506. Result KPageTable::CheckMemoryState(KMemoryState* out_state, KMemoryPermission* out_perm,
  2507. KMemoryAttribute* out_attr, size_t* out_blocks_needed,
  2508. VAddr addr, size_t size, KMemoryState state_mask,
  2509. KMemoryState state, KMemoryPermission perm_mask,
  2510. KMemoryPermission perm, KMemoryAttribute attr_mask,
  2511. KMemoryAttribute attr, KMemoryAttribute ignore_attr) const {
  2512. ASSERT(this->IsLockedByCurrentThread());
  2513. // Get information about the first block.
  2514. const VAddr last_addr = addr + size - 1;
  2515. KMemoryBlockManager::const_iterator it = m_memory_block_manager.FindIterator(addr);
  2516. KMemoryInfo info = it->GetMemoryInfo();
  2517. // If the start address isn't aligned, we need a block.
  2518. const size_t blocks_for_start_align =
  2519. (Common::AlignDown(addr, PageSize) != info.GetAddress()) ? 1 : 0;
  2520. // Validate all blocks in the range have correct state.
  2521. const KMemoryState first_state = info.m_state;
  2522. const KMemoryPermission first_perm = info.m_permission;
  2523. const KMemoryAttribute first_attr = info.m_attribute;
  2524. while (true) {
  2525. // Validate the current block.
  2526. R_UNLESS(info.m_state == first_state, ResultInvalidCurrentMemory);
  2527. R_UNLESS(info.m_permission == first_perm, ResultInvalidCurrentMemory);
  2528. R_UNLESS((info.m_attribute | ignore_attr) == (first_attr | ignore_attr),
  2529. ResultInvalidCurrentMemory);
  2530. // Validate against the provided masks.
  2531. R_TRY(this->CheckMemoryState(info, state_mask, state, perm_mask, perm, attr_mask, attr));
  2532. // Break once we're done.
  2533. if (last_addr <= info.GetLastAddress()) {
  2534. break;
  2535. }
  2536. // Advance our iterator.
  2537. it++;
  2538. ASSERT(it != m_memory_block_manager.cend());
  2539. info = it->GetMemoryInfo();
  2540. }
  2541. // If the end address isn't aligned, we need a block.
  2542. const size_t blocks_for_end_align =
  2543. (Common::AlignUp(addr + size, PageSize) != info.GetEndAddress()) ? 1 : 0;
  2544. // Write output state.
  2545. if (out_state != nullptr) {
  2546. *out_state = first_state;
  2547. }
  2548. if (out_perm != nullptr) {
  2549. *out_perm = first_perm;
  2550. }
  2551. if (out_attr != nullptr) {
  2552. *out_attr = static_cast<KMemoryAttribute>(first_attr & ~ignore_attr);
  2553. }
  2554. if (out_blocks_needed != nullptr) {
  2555. *out_blocks_needed = blocks_for_start_align + blocks_for_end_align;
  2556. }
  2557. R_SUCCEED();
  2558. }
  2559. Result KPageTable::LockMemoryAndOpen(KPageGroup* out_pg, PAddr* out_paddr, VAddr addr, size_t size,
  2560. KMemoryState state_mask, KMemoryState state,
  2561. KMemoryPermission perm_mask, KMemoryPermission perm,
  2562. KMemoryAttribute attr_mask, KMemoryAttribute attr,
  2563. KMemoryPermission new_perm, KMemoryAttribute lock_attr) {
  2564. // Validate basic preconditions.
  2565. ASSERT((lock_attr & attr) == KMemoryAttribute::None);
  2566. ASSERT((lock_attr & (KMemoryAttribute::IpcLocked | KMemoryAttribute::DeviceShared)) ==
  2567. KMemoryAttribute::None);
  2568. // Validate the lock request.
  2569. const size_t num_pages = size / PageSize;
  2570. R_UNLESS(this->Contains(addr, size), ResultInvalidCurrentMemory);
  2571. // Lock the table.
  2572. KScopedLightLock lk(m_general_lock);
  2573. // Check that the output page group is empty, if it exists.
  2574. if (out_pg) {
  2575. ASSERT(out_pg->GetNumPages() == 0);
  2576. }
  2577. // Check the state.
  2578. KMemoryState old_state{};
  2579. KMemoryPermission old_perm{};
  2580. KMemoryAttribute old_attr{};
  2581. size_t num_allocator_blocks{};
  2582. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm),
  2583. std::addressof(old_attr), std::addressof(num_allocator_blocks),
  2584. addr, size, state_mask | KMemoryState::FlagReferenceCounted,
  2585. state | KMemoryState::FlagReferenceCounted, perm_mask, perm,
  2586. attr_mask, attr));
  2587. // Get the physical address, if we're supposed to.
  2588. if (out_paddr != nullptr) {
  2589. ASSERT(this->GetPhysicalAddressLocked(out_paddr, addr));
  2590. }
  2591. // Make the page group, if we're supposed to.
  2592. if (out_pg != nullptr) {
  2593. R_TRY(this->MakePageGroup(*out_pg, addr, num_pages));
  2594. }
  2595. // Create an update allocator.
  2596. Result allocator_result{ResultSuccess};
  2597. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2598. m_memory_block_slab_manager, num_allocator_blocks);
  2599. R_TRY(allocator_result);
  2600. // Decide on new perm and attr.
  2601. new_perm = (new_perm != KMemoryPermission::None) ? new_perm : old_perm;
  2602. KMemoryAttribute new_attr = static_cast<KMemoryAttribute>(old_attr | lock_attr);
  2603. // Update permission, if we need to.
  2604. if (new_perm != old_perm) {
  2605. R_TRY(Operate(addr, num_pages, new_perm, OperationType::ChangePermissions));
  2606. }
  2607. // Apply the memory block updates.
  2608. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, new_perm,
  2609. new_attr, KMemoryBlockDisableMergeAttribute::Locked,
  2610. KMemoryBlockDisableMergeAttribute::None);
  2611. R_SUCCEED();
  2612. }
  2613. Result KPageTable::UnlockMemory(VAddr addr, size_t size, KMemoryState state_mask,
  2614. KMemoryState state, KMemoryPermission perm_mask,
  2615. KMemoryPermission perm, KMemoryAttribute attr_mask,
  2616. KMemoryAttribute attr, KMemoryPermission new_perm,
  2617. KMemoryAttribute lock_attr, const KPageGroup* pg) {
  2618. // Validate basic preconditions.
  2619. ASSERT((attr_mask & lock_attr) == lock_attr);
  2620. ASSERT((attr & lock_attr) == lock_attr);
  2621. // Validate the unlock request.
  2622. const size_t num_pages = size / PageSize;
  2623. R_UNLESS(this->Contains(addr, size), ResultInvalidCurrentMemory);
  2624. // Lock the table.
  2625. KScopedLightLock lk(m_general_lock);
  2626. // Check the state.
  2627. KMemoryState old_state{};
  2628. KMemoryPermission old_perm{};
  2629. KMemoryAttribute old_attr{};
  2630. size_t num_allocator_blocks{};
  2631. R_TRY(this->CheckMemoryState(std::addressof(old_state), std::addressof(old_perm),
  2632. std::addressof(old_attr), std::addressof(num_allocator_blocks),
  2633. addr, size, state_mask | KMemoryState::FlagReferenceCounted,
  2634. state | KMemoryState::FlagReferenceCounted, perm_mask, perm,
  2635. attr_mask, attr));
  2636. // Check the page group.
  2637. if (pg != nullptr) {
  2638. R_UNLESS(this->IsValidPageGroup(*pg, addr, num_pages), ResultInvalidMemoryRegion);
  2639. }
  2640. // Decide on new perm and attr.
  2641. new_perm = (new_perm != KMemoryPermission::None) ? new_perm : old_perm;
  2642. KMemoryAttribute new_attr = static_cast<KMemoryAttribute>(old_attr & ~lock_attr);
  2643. // Create an update allocator.
  2644. Result allocator_result{ResultSuccess};
  2645. KMemoryBlockManagerUpdateAllocator allocator(std::addressof(allocator_result),
  2646. m_memory_block_slab_manager, num_allocator_blocks);
  2647. R_TRY(allocator_result);
  2648. // Update permission, if we need to.
  2649. if (new_perm != old_perm) {
  2650. R_TRY(Operate(addr, num_pages, new_perm, OperationType::ChangePermissions));
  2651. }
  2652. // Apply the memory block updates.
  2653. m_memory_block_manager.Update(std::addressof(allocator), addr, num_pages, old_state, new_perm,
  2654. new_attr, KMemoryBlockDisableMergeAttribute::None,
  2655. KMemoryBlockDisableMergeAttribute::Locked);
  2656. R_SUCCEED();
  2657. }
  2658. } // namespace Kernel