k_page_table.cpp 131 KB

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