k_page_table.cpp 131 KB

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