mmu.c 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 2012 - Virtual Open Systems and Columbia University
  4. * Author: Christoffer Dall <c.dall@virtualopensystems.com>
  5. */
  6. #include <linux/acpi.h>
  7. #include <linux/mman.h>
  8. #include <linux/kvm_host.h>
  9. #include <linux/io.h>
  10. #include <linux/hugetlb.h>
  11. #include <linux/sched/signal.h>
  12. #include <trace/events/kvm.h>
  13. #include <asm/acpi.h>
  14. #include <asm/pgalloc.h>
  15. #include <asm/cacheflush.h>
  16. #include <asm/kvm_arm.h>
  17. #include <asm/kvm_mmu.h>
  18. #include <asm/kvm_pgtable.h>
  19. #include <asm/kvm_pkvm.h>
  20. #include <asm/kvm_asm.h>
  21. #include <asm/kvm_emulate.h>
  22. #include <asm/virt.h>
  23. #include "trace.h"
  24. static struct kvm_pgtable *hyp_pgtable;
  25. static DEFINE_MUTEX(kvm_hyp_pgd_mutex);
  26. static unsigned long __ro_after_init hyp_idmap_start;
  27. static unsigned long __ro_after_init hyp_idmap_end;
  28. static phys_addr_t __ro_after_init hyp_idmap_vector;
  29. u32 __ro_after_init __hyp_va_bits;
  30. static unsigned long __ro_after_init io_map_base;
  31. #define KVM_PGT_FN(fn) (!is_protected_kvm_enabled() ? fn : p ## fn)
  32. static phys_addr_t __stage2_range_addr_end(phys_addr_t addr, phys_addr_t end,
  33. phys_addr_t size)
  34. {
  35. phys_addr_t boundary = ALIGN_DOWN(addr + size, size);
  36. return (boundary - 1 < end - 1) ? boundary : end;
  37. }
  38. static phys_addr_t stage2_range_addr_end(phys_addr_t addr, phys_addr_t end)
  39. {
  40. phys_addr_t size = kvm_granule_size(KVM_PGTABLE_MIN_BLOCK_LEVEL);
  41. return __stage2_range_addr_end(addr, end, size);
  42. }
  43. /*
  44. * Release kvm_mmu_lock periodically if the memory region is large. Otherwise,
  45. * we may see kernel panics with CONFIG_DETECT_HUNG_TASK,
  46. * CONFIG_LOCKUP_DETECTOR, CONFIG_LOCKDEP. Additionally, holding the lock too
  47. * long will also starve other vCPUs. We have to also make sure that the page
  48. * tables are not freed while we released the lock.
  49. */
  50. static int stage2_apply_range(struct kvm_s2_mmu *mmu, phys_addr_t addr,
  51. phys_addr_t end,
  52. int (*fn)(struct kvm_pgtable *, u64, u64),
  53. bool resched)
  54. {
  55. struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
  56. int ret;
  57. u64 next;
  58. do {
  59. struct kvm_pgtable *pgt = mmu->pgt;
  60. if (!pgt)
  61. return -EINVAL;
  62. next = stage2_range_addr_end(addr, end);
  63. ret = fn(pgt, addr, next - addr);
  64. if (ret)
  65. break;
  66. if (resched && next != end)
  67. cond_resched_rwlock_write(&kvm->mmu_lock);
  68. } while (addr = next, addr != end);
  69. return ret;
  70. }
  71. #define stage2_apply_range_resched(mmu, addr, end, fn) \
  72. stage2_apply_range(mmu, addr, end, fn, true)
  73. /*
  74. * Get the maximum number of page-tables pages needed to split a range
  75. * of blocks into PAGE_SIZE PTEs. It assumes the range is already
  76. * mapped at level 2, or at level 1 if allowed.
  77. */
  78. static int kvm_mmu_split_nr_page_tables(u64 range)
  79. {
  80. int n = 0;
  81. if (KVM_PGTABLE_MIN_BLOCK_LEVEL < 2)
  82. n += DIV_ROUND_UP(range, PUD_SIZE);
  83. n += DIV_ROUND_UP(range, PMD_SIZE);
  84. return n;
  85. }
  86. static bool need_split_memcache_topup_or_resched(struct kvm *kvm)
  87. {
  88. struct kvm_mmu_memory_cache *cache;
  89. u64 chunk_size, min;
  90. if (need_resched() || rwlock_needbreak(&kvm->mmu_lock))
  91. return true;
  92. chunk_size = kvm->arch.mmu.split_page_chunk_size;
  93. min = kvm_mmu_split_nr_page_tables(chunk_size);
  94. cache = &kvm->arch.mmu.split_page_cache;
  95. return kvm_mmu_memory_cache_nr_free_objects(cache) < min;
  96. }
  97. static int kvm_mmu_split_huge_pages(struct kvm *kvm, phys_addr_t addr,
  98. phys_addr_t end)
  99. {
  100. struct kvm_mmu_memory_cache *cache;
  101. struct kvm_pgtable *pgt;
  102. int ret, cache_capacity;
  103. u64 next, chunk_size;
  104. lockdep_assert_held_write(&kvm->mmu_lock);
  105. chunk_size = kvm->arch.mmu.split_page_chunk_size;
  106. cache_capacity = kvm_mmu_split_nr_page_tables(chunk_size);
  107. if (chunk_size == 0)
  108. return 0;
  109. cache = &kvm->arch.mmu.split_page_cache;
  110. do {
  111. if (need_split_memcache_topup_or_resched(kvm)) {
  112. write_unlock(&kvm->mmu_lock);
  113. cond_resched();
  114. /* Eager page splitting is best-effort. */
  115. ret = __kvm_mmu_topup_memory_cache(cache,
  116. cache_capacity,
  117. cache_capacity);
  118. write_lock(&kvm->mmu_lock);
  119. if (ret)
  120. break;
  121. }
  122. pgt = kvm->arch.mmu.pgt;
  123. if (!pgt)
  124. return -EINVAL;
  125. next = __stage2_range_addr_end(addr, end, chunk_size);
  126. ret = KVM_PGT_FN(kvm_pgtable_stage2_split)(pgt, addr, next - addr, cache);
  127. if (ret)
  128. break;
  129. } while (addr = next, addr != end);
  130. return ret;
  131. }
  132. static bool memslot_is_logging(struct kvm_memory_slot *memslot)
  133. {
  134. return memslot->dirty_bitmap && !(memslot->flags & KVM_MEM_READONLY);
  135. }
  136. /**
  137. * kvm_arch_flush_remote_tlbs() - flush all VM TLB entries for v7/8
  138. * @kvm: pointer to kvm structure.
  139. *
  140. * Interface to HYP function to flush all VM TLB entries
  141. */
  142. int kvm_arch_flush_remote_tlbs(struct kvm *kvm)
  143. {
  144. if (is_protected_kvm_enabled())
  145. kvm_call_hyp_nvhe(__pkvm_tlb_flush_vmid, kvm->arch.pkvm.handle);
  146. else
  147. kvm_call_hyp(__kvm_tlb_flush_vmid, &kvm->arch.mmu);
  148. return 0;
  149. }
  150. int kvm_arch_flush_remote_tlbs_range(struct kvm *kvm,
  151. gfn_t gfn, u64 nr_pages)
  152. {
  153. u64 size = nr_pages << PAGE_SHIFT;
  154. u64 addr = gfn << PAGE_SHIFT;
  155. if (is_protected_kvm_enabled())
  156. kvm_call_hyp_nvhe(__pkvm_tlb_flush_vmid, kvm->arch.pkvm.handle);
  157. else
  158. kvm_tlb_flush_vmid_range(&kvm->arch.mmu, addr, size);
  159. return 0;
  160. }
  161. static void *stage2_memcache_zalloc_page(void *arg)
  162. {
  163. struct kvm_mmu_memory_cache *mc = arg;
  164. void *virt;
  165. /* Allocated with __GFP_ZERO, so no need to zero */
  166. virt = kvm_mmu_memory_cache_alloc(mc);
  167. if (virt)
  168. kvm_account_pgtable_pages(virt, 1);
  169. return virt;
  170. }
  171. static void *kvm_host_zalloc_pages_exact(size_t size)
  172. {
  173. return alloc_pages_exact(size, GFP_KERNEL_ACCOUNT | __GFP_ZERO);
  174. }
  175. static void *kvm_s2_zalloc_pages_exact(size_t size)
  176. {
  177. void *virt = kvm_host_zalloc_pages_exact(size);
  178. if (virt)
  179. kvm_account_pgtable_pages(virt, (size >> PAGE_SHIFT));
  180. return virt;
  181. }
  182. static void kvm_s2_free_pages_exact(void *virt, size_t size)
  183. {
  184. kvm_account_pgtable_pages(virt, -(size >> PAGE_SHIFT));
  185. free_pages_exact(virt, size);
  186. }
  187. static struct kvm_pgtable_mm_ops kvm_s2_mm_ops;
  188. static void stage2_free_unlinked_table_rcu_cb(struct rcu_head *head)
  189. {
  190. struct page *page = container_of(head, struct page, rcu_head);
  191. void *pgtable = page_to_virt(page);
  192. s8 level = page_private(page);
  193. KVM_PGT_FN(kvm_pgtable_stage2_free_unlinked)(&kvm_s2_mm_ops, pgtable, level);
  194. }
  195. static void stage2_free_unlinked_table(void *addr, s8 level)
  196. {
  197. struct page *page = virt_to_page(addr);
  198. set_page_private(page, (unsigned long)level);
  199. call_rcu(&page->rcu_head, stage2_free_unlinked_table_rcu_cb);
  200. }
  201. static void kvm_host_get_page(void *addr)
  202. {
  203. get_page(virt_to_page(addr));
  204. }
  205. static void kvm_host_put_page(void *addr)
  206. {
  207. put_page(virt_to_page(addr));
  208. }
  209. static void kvm_s2_put_page(void *addr)
  210. {
  211. struct page *p = virt_to_page(addr);
  212. /* Dropping last refcount, the page will be freed */
  213. if (page_count(p) == 1)
  214. kvm_account_pgtable_pages(addr, -1);
  215. put_page(p);
  216. }
  217. static int kvm_host_page_count(void *addr)
  218. {
  219. return page_count(virt_to_page(addr));
  220. }
  221. static phys_addr_t kvm_host_pa(void *addr)
  222. {
  223. return __pa(addr);
  224. }
  225. static void *kvm_host_va(phys_addr_t phys)
  226. {
  227. return __va(phys);
  228. }
  229. static void clean_dcache_guest_page(void *va, size_t size)
  230. {
  231. __clean_dcache_guest_page(va, size);
  232. }
  233. static void invalidate_icache_guest_page(void *va, size_t size)
  234. {
  235. __invalidate_icache_guest_page(va, size);
  236. }
  237. /*
  238. * Unmapping vs dcache management:
  239. *
  240. * If a guest maps certain memory pages as uncached, all writes will
  241. * bypass the data cache and go directly to RAM. However, the CPUs
  242. * can still speculate reads (not writes) and fill cache lines with
  243. * data.
  244. *
  245. * Those cache lines will be *clean* cache lines though, so a
  246. * clean+invalidate operation is equivalent to an invalidate
  247. * operation, because no cache lines are marked dirty.
  248. *
  249. * Those clean cache lines could be filled prior to an uncached write
  250. * by the guest, and the cache coherent IO subsystem would therefore
  251. * end up writing old data to disk.
  252. *
  253. * This is why right after unmapping a page/section and invalidating
  254. * the corresponding TLBs, we flush to make sure the IO subsystem will
  255. * never hit in the cache.
  256. *
  257. * This is all avoided on systems that have ARM64_HAS_STAGE2_FWB, as
  258. * we then fully enforce cacheability of RAM, no matter what the guest
  259. * does.
  260. */
  261. /**
  262. * __unmap_stage2_range -- Clear stage2 page table entries to unmap a range
  263. * @mmu: The KVM stage-2 MMU pointer
  264. * @start: The intermediate physical base address of the range to unmap
  265. * @size: The size of the area to unmap
  266. * @may_block: Whether or not we are permitted to block
  267. *
  268. * Clear a range of stage-2 mappings, lowering the various ref-counts. Must
  269. * be called while holding mmu_lock (unless for freeing the stage2 pgd before
  270. * destroying the VM), otherwise another faulting VCPU may come in and mess
  271. * with things behind our backs.
  272. */
  273. static void __unmap_stage2_range(struct kvm_s2_mmu *mmu, phys_addr_t start, u64 size,
  274. bool may_block)
  275. {
  276. struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
  277. phys_addr_t end = start + size;
  278. lockdep_assert_held_write(&kvm->mmu_lock);
  279. WARN_ON(size & ~PAGE_MASK);
  280. WARN_ON(stage2_apply_range(mmu, start, end, KVM_PGT_FN(kvm_pgtable_stage2_unmap),
  281. may_block));
  282. }
  283. void kvm_stage2_unmap_range(struct kvm_s2_mmu *mmu, phys_addr_t start,
  284. u64 size, bool may_block)
  285. {
  286. __unmap_stage2_range(mmu, start, size, may_block);
  287. }
  288. void kvm_stage2_flush_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
  289. {
  290. stage2_apply_range_resched(mmu, addr, end, KVM_PGT_FN(kvm_pgtable_stage2_flush));
  291. }
  292. static void stage2_flush_memslot(struct kvm *kvm,
  293. struct kvm_memory_slot *memslot)
  294. {
  295. phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
  296. phys_addr_t end = addr + PAGE_SIZE * memslot->npages;
  297. kvm_stage2_flush_range(&kvm->arch.mmu, addr, end);
  298. }
  299. /**
  300. * stage2_flush_vm - Invalidate cache for pages mapped in stage 2
  301. * @kvm: The struct kvm pointer
  302. *
  303. * Go through the stage 2 page tables and invalidate any cache lines
  304. * backing memory already mapped to the VM.
  305. */
  306. static void stage2_flush_vm(struct kvm *kvm)
  307. {
  308. struct kvm_memslots *slots;
  309. struct kvm_memory_slot *memslot;
  310. int idx, bkt;
  311. idx = srcu_read_lock(&kvm->srcu);
  312. write_lock(&kvm->mmu_lock);
  313. slots = kvm_memslots(kvm);
  314. kvm_for_each_memslot(memslot, bkt, slots)
  315. stage2_flush_memslot(kvm, memslot);
  316. kvm_nested_s2_flush(kvm);
  317. write_unlock(&kvm->mmu_lock);
  318. srcu_read_unlock(&kvm->srcu, idx);
  319. }
  320. /**
  321. * free_hyp_pgds - free Hyp-mode page tables
  322. */
  323. void __init free_hyp_pgds(void)
  324. {
  325. mutex_lock(&kvm_hyp_pgd_mutex);
  326. if (hyp_pgtable) {
  327. kvm_pgtable_hyp_destroy(hyp_pgtable);
  328. kfree(hyp_pgtable);
  329. hyp_pgtable = NULL;
  330. }
  331. mutex_unlock(&kvm_hyp_pgd_mutex);
  332. }
  333. static bool kvm_host_owns_hyp_mappings(void)
  334. {
  335. if (is_kernel_in_hyp_mode())
  336. return false;
  337. if (static_branch_likely(&kvm_protected_mode_initialized))
  338. return false;
  339. /*
  340. * This can happen at boot time when __create_hyp_mappings() is called
  341. * after the hyp protection has been enabled, but the static key has
  342. * not been flipped yet.
  343. */
  344. if (!hyp_pgtable && is_protected_kvm_enabled())
  345. return false;
  346. WARN_ON(!hyp_pgtable);
  347. return true;
  348. }
  349. int __create_hyp_mappings(unsigned long start, unsigned long size,
  350. unsigned long phys, enum kvm_pgtable_prot prot)
  351. {
  352. int err;
  353. if (WARN_ON(!kvm_host_owns_hyp_mappings()))
  354. return -EINVAL;
  355. mutex_lock(&kvm_hyp_pgd_mutex);
  356. err = kvm_pgtable_hyp_map(hyp_pgtable, start, size, phys, prot);
  357. mutex_unlock(&kvm_hyp_pgd_mutex);
  358. return err;
  359. }
  360. static phys_addr_t kvm_kaddr_to_phys(void *kaddr)
  361. {
  362. if (!is_vmalloc_addr(kaddr)) {
  363. BUG_ON(!virt_addr_valid(kaddr));
  364. return __pa(kaddr);
  365. } else {
  366. return page_to_phys(vmalloc_to_page(kaddr)) +
  367. offset_in_page(kaddr);
  368. }
  369. }
  370. struct hyp_shared_pfn {
  371. u64 pfn;
  372. int count;
  373. struct rb_node node;
  374. };
  375. static DEFINE_MUTEX(hyp_shared_pfns_lock);
  376. static struct rb_root hyp_shared_pfns = RB_ROOT;
  377. static struct hyp_shared_pfn *find_shared_pfn(u64 pfn, struct rb_node ***node,
  378. struct rb_node **parent)
  379. {
  380. struct hyp_shared_pfn *this;
  381. *node = &hyp_shared_pfns.rb_node;
  382. *parent = NULL;
  383. while (**node) {
  384. this = container_of(**node, struct hyp_shared_pfn, node);
  385. *parent = **node;
  386. if (this->pfn < pfn)
  387. *node = &((**node)->rb_left);
  388. else if (this->pfn > pfn)
  389. *node = &((**node)->rb_right);
  390. else
  391. return this;
  392. }
  393. return NULL;
  394. }
  395. static int share_pfn_hyp(u64 pfn)
  396. {
  397. struct rb_node **node, *parent;
  398. struct hyp_shared_pfn *this;
  399. int ret = 0;
  400. mutex_lock(&hyp_shared_pfns_lock);
  401. this = find_shared_pfn(pfn, &node, &parent);
  402. if (this) {
  403. this->count++;
  404. goto unlock;
  405. }
  406. this = kzalloc_obj(*this);
  407. if (!this) {
  408. ret = -ENOMEM;
  409. goto unlock;
  410. }
  411. this->pfn = pfn;
  412. this->count = 1;
  413. rb_link_node(&this->node, parent, node);
  414. rb_insert_color(&this->node, &hyp_shared_pfns);
  415. ret = kvm_call_hyp_nvhe(__pkvm_host_share_hyp, pfn);
  416. unlock:
  417. mutex_unlock(&hyp_shared_pfns_lock);
  418. return ret;
  419. }
  420. static int unshare_pfn_hyp(u64 pfn)
  421. {
  422. struct rb_node **node, *parent;
  423. struct hyp_shared_pfn *this;
  424. int ret = 0;
  425. mutex_lock(&hyp_shared_pfns_lock);
  426. this = find_shared_pfn(pfn, &node, &parent);
  427. if (WARN_ON(!this)) {
  428. ret = -ENOENT;
  429. goto unlock;
  430. }
  431. this->count--;
  432. if (this->count)
  433. goto unlock;
  434. rb_erase(&this->node, &hyp_shared_pfns);
  435. kfree(this);
  436. ret = kvm_call_hyp_nvhe(__pkvm_host_unshare_hyp, pfn);
  437. unlock:
  438. mutex_unlock(&hyp_shared_pfns_lock);
  439. return ret;
  440. }
  441. int kvm_share_hyp(void *from, void *to)
  442. {
  443. phys_addr_t start, end, cur;
  444. u64 pfn;
  445. int ret;
  446. if (is_kernel_in_hyp_mode())
  447. return 0;
  448. /*
  449. * The share hcall maps things in the 'fixed-offset' region of the hyp
  450. * VA space, so we can only share physically contiguous data-structures
  451. * for now.
  452. */
  453. if (is_vmalloc_or_module_addr(from) || is_vmalloc_or_module_addr(to))
  454. return -EINVAL;
  455. if (kvm_host_owns_hyp_mappings())
  456. return create_hyp_mappings(from, to, PAGE_HYP);
  457. start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
  458. end = PAGE_ALIGN(__pa(to));
  459. for (cur = start; cur < end; cur += PAGE_SIZE) {
  460. pfn = __phys_to_pfn(cur);
  461. ret = share_pfn_hyp(pfn);
  462. if (ret)
  463. return ret;
  464. }
  465. return 0;
  466. }
  467. void kvm_unshare_hyp(void *from, void *to)
  468. {
  469. phys_addr_t start, end, cur;
  470. u64 pfn;
  471. if (is_kernel_in_hyp_mode() || kvm_host_owns_hyp_mappings() || !from)
  472. return;
  473. start = ALIGN_DOWN(__pa(from), PAGE_SIZE);
  474. end = PAGE_ALIGN(__pa(to));
  475. for (cur = start; cur < end; cur += PAGE_SIZE) {
  476. pfn = __phys_to_pfn(cur);
  477. WARN_ON(unshare_pfn_hyp(pfn));
  478. }
  479. }
  480. /**
  481. * create_hyp_mappings - duplicate a kernel virtual address range in Hyp mode
  482. * @from: The virtual kernel start address of the range
  483. * @to: The virtual kernel end address of the range (exclusive)
  484. * @prot: The protection to be applied to this range
  485. *
  486. * The same virtual address as the kernel virtual address is also used
  487. * in Hyp-mode mapping (modulo HYP_PAGE_OFFSET) to the same underlying
  488. * physical pages.
  489. */
  490. int create_hyp_mappings(void *from, void *to, enum kvm_pgtable_prot prot)
  491. {
  492. phys_addr_t phys_addr;
  493. unsigned long virt_addr;
  494. unsigned long start = kern_hyp_va((unsigned long)from);
  495. unsigned long end = kern_hyp_va((unsigned long)to);
  496. if (is_kernel_in_hyp_mode())
  497. return 0;
  498. if (!kvm_host_owns_hyp_mappings())
  499. return -EPERM;
  500. start = start & PAGE_MASK;
  501. end = PAGE_ALIGN(end);
  502. for (virt_addr = start; virt_addr < end; virt_addr += PAGE_SIZE) {
  503. int err;
  504. phys_addr = kvm_kaddr_to_phys(from + virt_addr - start);
  505. err = __create_hyp_mappings(virt_addr, PAGE_SIZE, phys_addr,
  506. prot);
  507. if (err)
  508. return err;
  509. }
  510. return 0;
  511. }
  512. static int __hyp_alloc_private_va_range(unsigned long base)
  513. {
  514. lockdep_assert_held(&kvm_hyp_pgd_mutex);
  515. if (!PAGE_ALIGNED(base))
  516. return -EINVAL;
  517. /*
  518. * Verify that BIT(VA_BITS - 1) hasn't been flipped by
  519. * allocating the new area, as it would indicate we've
  520. * overflowed the idmap/IO address range.
  521. */
  522. if ((base ^ io_map_base) & BIT(VA_BITS - 1))
  523. return -ENOMEM;
  524. io_map_base = base;
  525. return 0;
  526. }
  527. /**
  528. * hyp_alloc_private_va_range - Allocates a private VA range.
  529. * @size: The size of the VA range to reserve.
  530. * @haddr: The hypervisor virtual start address of the allocation.
  531. *
  532. * The private virtual address (VA) range is allocated below io_map_base
  533. * and aligned based on the order of @size.
  534. *
  535. * Return: 0 on success or negative error code on failure.
  536. */
  537. int hyp_alloc_private_va_range(size_t size, unsigned long *haddr)
  538. {
  539. unsigned long base;
  540. int ret = 0;
  541. mutex_lock(&kvm_hyp_pgd_mutex);
  542. /*
  543. * This assumes that we have enough space below the idmap
  544. * page to allocate our VAs. If not, the check in
  545. * __hyp_alloc_private_va_range() will kick. A potential
  546. * alternative would be to detect that overflow and switch
  547. * to an allocation above the idmap.
  548. *
  549. * The allocated size is always a multiple of PAGE_SIZE.
  550. */
  551. size = PAGE_ALIGN(size);
  552. base = io_map_base - size;
  553. ret = __hyp_alloc_private_va_range(base);
  554. mutex_unlock(&kvm_hyp_pgd_mutex);
  555. if (!ret)
  556. *haddr = base;
  557. return ret;
  558. }
  559. static int __create_hyp_private_mapping(phys_addr_t phys_addr, size_t size,
  560. unsigned long *haddr,
  561. enum kvm_pgtable_prot prot)
  562. {
  563. unsigned long addr;
  564. int ret = 0;
  565. if (!kvm_host_owns_hyp_mappings()) {
  566. addr = kvm_call_hyp_nvhe(__pkvm_create_private_mapping,
  567. phys_addr, size, prot);
  568. if (IS_ERR_VALUE(addr))
  569. return addr;
  570. *haddr = addr;
  571. return 0;
  572. }
  573. size = PAGE_ALIGN(size + offset_in_page(phys_addr));
  574. ret = hyp_alloc_private_va_range(size, &addr);
  575. if (ret)
  576. return ret;
  577. ret = __create_hyp_mappings(addr, size, phys_addr, prot);
  578. if (ret)
  579. return ret;
  580. *haddr = addr + offset_in_page(phys_addr);
  581. return ret;
  582. }
  583. int create_hyp_stack(phys_addr_t phys_addr, unsigned long *haddr)
  584. {
  585. unsigned long base;
  586. size_t size;
  587. int ret;
  588. mutex_lock(&kvm_hyp_pgd_mutex);
  589. /*
  590. * Efficient stack verification using the NVHE_STACK_SHIFT bit implies
  591. * an alignment of our allocation on the order of the size.
  592. */
  593. size = NVHE_STACK_SIZE * 2;
  594. base = ALIGN_DOWN(io_map_base - size, size);
  595. ret = __hyp_alloc_private_va_range(base);
  596. mutex_unlock(&kvm_hyp_pgd_mutex);
  597. if (ret) {
  598. kvm_err("Cannot allocate hyp stack guard page\n");
  599. return ret;
  600. }
  601. /*
  602. * Since the stack grows downwards, map the stack to the page
  603. * at the higher address and leave the lower guard page
  604. * unbacked.
  605. *
  606. * Any valid stack address now has the NVHE_STACK_SHIFT bit as 1
  607. * and addresses corresponding to the guard page have the
  608. * NVHE_STACK_SHIFT bit as 0 - this is used for overflow detection.
  609. */
  610. ret = __create_hyp_mappings(base + NVHE_STACK_SIZE, NVHE_STACK_SIZE,
  611. phys_addr, PAGE_HYP);
  612. if (ret)
  613. kvm_err("Cannot map hyp stack\n");
  614. *haddr = base + size;
  615. return ret;
  616. }
  617. /**
  618. * create_hyp_io_mappings - Map IO into both kernel and HYP
  619. * @phys_addr: The physical start address which gets mapped
  620. * @size: Size of the region being mapped
  621. * @kaddr: Kernel VA for this mapping
  622. * @haddr: HYP VA for this mapping
  623. */
  624. int create_hyp_io_mappings(phys_addr_t phys_addr, size_t size,
  625. void __iomem **kaddr,
  626. void __iomem **haddr)
  627. {
  628. unsigned long addr;
  629. int ret;
  630. if (is_protected_kvm_enabled())
  631. return -EPERM;
  632. *kaddr = ioremap(phys_addr, size);
  633. if (!*kaddr)
  634. return -ENOMEM;
  635. if (is_kernel_in_hyp_mode()) {
  636. *haddr = *kaddr;
  637. return 0;
  638. }
  639. ret = __create_hyp_private_mapping(phys_addr, size,
  640. &addr, PAGE_HYP_DEVICE);
  641. if (ret) {
  642. iounmap(*kaddr);
  643. *kaddr = NULL;
  644. *haddr = NULL;
  645. return ret;
  646. }
  647. *haddr = (void __iomem *)addr;
  648. return 0;
  649. }
  650. /**
  651. * create_hyp_exec_mappings - Map an executable range into HYP
  652. * @phys_addr: The physical start address which gets mapped
  653. * @size: Size of the region being mapped
  654. * @haddr: HYP VA for this mapping
  655. */
  656. int create_hyp_exec_mappings(phys_addr_t phys_addr, size_t size,
  657. void **haddr)
  658. {
  659. unsigned long addr;
  660. int ret;
  661. BUG_ON(is_kernel_in_hyp_mode());
  662. ret = __create_hyp_private_mapping(phys_addr, size,
  663. &addr, PAGE_HYP_EXEC);
  664. if (ret) {
  665. *haddr = NULL;
  666. return ret;
  667. }
  668. *haddr = (void *)addr;
  669. return 0;
  670. }
  671. static struct kvm_pgtable_mm_ops kvm_user_mm_ops = {
  672. /* We shouldn't need any other callback to walk the PT */
  673. .phys_to_virt = kvm_host_va,
  674. };
  675. static int get_user_mapping_size(struct kvm *kvm, u64 addr)
  676. {
  677. struct kvm_pgtable pgt = {
  678. .pgd = (kvm_pteref_t)kvm->mm->pgd,
  679. .ia_bits = vabits_actual,
  680. .start_level = (KVM_PGTABLE_LAST_LEVEL -
  681. ARM64_HW_PGTABLE_LEVELS(pgt.ia_bits) + 1),
  682. .mm_ops = &kvm_user_mm_ops,
  683. };
  684. unsigned long flags;
  685. kvm_pte_t pte = 0; /* Keep GCC quiet... */
  686. s8 level = S8_MAX;
  687. int ret;
  688. /*
  689. * Disable IRQs so that we hazard against a concurrent
  690. * teardown of the userspace page tables (which relies on
  691. * IPI-ing threads).
  692. */
  693. local_irq_save(flags);
  694. ret = kvm_pgtable_get_leaf(&pgt, addr, &pte, &level);
  695. local_irq_restore(flags);
  696. if (ret)
  697. return ret;
  698. /*
  699. * Not seeing an error, but not updating level? Something went
  700. * deeply wrong...
  701. */
  702. if (WARN_ON(level > KVM_PGTABLE_LAST_LEVEL))
  703. return -EFAULT;
  704. if (WARN_ON(level < KVM_PGTABLE_FIRST_LEVEL))
  705. return -EFAULT;
  706. /* Oops, the userspace PTs are gone... Replay the fault */
  707. if (!kvm_pte_valid(pte))
  708. return -EAGAIN;
  709. return BIT(ARM64_HW_PGTABLE_LEVEL_SHIFT(level));
  710. }
  711. static struct kvm_pgtable_mm_ops kvm_s2_mm_ops = {
  712. .zalloc_page = stage2_memcache_zalloc_page,
  713. .zalloc_pages_exact = kvm_s2_zalloc_pages_exact,
  714. .free_pages_exact = kvm_s2_free_pages_exact,
  715. .free_unlinked_table = stage2_free_unlinked_table,
  716. .get_page = kvm_host_get_page,
  717. .put_page = kvm_s2_put_page,
  718. .page_count = kvm_host_page_count,
  719. .phys_to_virt = kvm_host_va,
  720. .virt_to_phys = kvm_host_pa,
  721. .dcache_clean_inval_poc = clean_dcache_guest_page,
  722. .icache_inval_pou = invalidate_icache_guest_page,
  723. };
  724. static int kvm_init_ipa_range(struct kvm_s2_mmu *mmu, unsigned long type)
  725. {
  726. u32 kvm_ipa_limit = get_kvm_ipa_limit();
  727. u64 mmfr0, mmfr1;
  728. u32 phys_shift;
  729. if (type & ~KVM_VM_TYPE_ARM_IPA_SIZE_MASK)
  730. return -EINVAL;
  731. phys_shift = KVM_VM_TYPE_ARM_IPA_SIZE(type);
  732. if (is_protected_kvm_enabled()) {
  733. phys_shift = kvm_ipa_limit;
  734. } else if (phys_shift) {
  735. if (phys_shift > kvm_ipa_limit ||
  736. phys_shift < ARM64_MIN_PARANGE_BITS)
  737. return -EINVAL;
  738. } else {
  739. phys_shift = KVM_PHYS_SHIFT;
  740. if (phys_shift > kvm_ipa_limit) {
  741. pr_warn_once("%s using unsupported default IPA limit, upgrade your VMM\n",
  742. current->comm);
  743. return -EINVAL;
  744. }
  745. }
  746. mmfr0 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR0_EL1);
  747. mmfr1 = read_sanitised_ftr_reg(SYS_ID_AA64MMFR1_EL1);
  748. mmu->vtcr = kvm_get_vtcr(mmfr0, mmfr1, phys_shift);
  749. return 0;
  750. }
  751. /*
  752. * Assume that @pgt is valid and unlinked from the KVM MMU to free the
  753. * page-table without taking the kvm_mmu_lock and without performing any
  754. * TLB invalidations.
  755. *
  756. * Also, the range of addresses can be large enough to cause need_resched
  757. * warnings, for instance on CONFIG_PREEMPT_NONE kernels. Hence, invoke
  758. * cond_resched() periodically to prevent hogging the CPU for a long time
  759. * and schedule something else, if required.
  760. */
  761. static void stage2_destroy_range(struct kvm_pgtable *pgt, phys_addr_t addr,
  762. phys_addr_t end)
  763. {
  764. u64 next;
  765. do {
  766. next = stage2_range_addr_end(addr, end);
  767. KVM_PGT_FN(kvm_pgtable_stage2_destroy_range)(pgt, addr,
  768. next - addr);
  769. if (next != end)
  770. cond_resched();
  771. } while (addr = next, addr != end);
  772. }
  773. static void kvm_stage2_destroy(struct kvm_pgtable *pgt)
  774. {
  775. unsigned int ia_bits = VTCR_EL2_IPA(pgt->mmu->vtcr);
  776. stage2_destroy_range(pgt, 0, BIT(ia_bits));
  777. KVM_PGT_FN(kvm_pgtable_stage2_destroy_pgd)(pgt);
  778. }
  779. /**
  780. * kvm_init_stage2_mmu - Initialise a S2 MMU structure
  781. * @kvm: The pointer to the KVM structure
  782. * @mmu: The pointer to the s2 MMU structure
  783. * @type: The machine type of the virtual machine
  784. *
  785. * Allocates only the stage-2 HW PGD level table(s).
  786. * Note we don't need locking here as this is only called in two cases:
  787. *
  788. * - when the VM is created, which can't race against anything
  789. *
  790. * - when secondary kvm_s2_mmu structures are initialised for NV
  791. * guests, and the caller must hold kvm->lock as this is called on a
  792. * per-vcpu basis.
  793. */
  794. int kvm_init_stage2_mmu(struct kvm *kvm, struct kvm_s2_mmu *mmu, unsigned long type)
  795. {
  796. int cpu, err;
  797. struct kvm_pgtable *pgt;
  798. /*
  799. * If we already have our page tables in place, and that the
  800. * MMU context is the canonical one, we have a bug somewhere,
  801. * as this is only supposed to ever happen once per VM.
  802. *
  803. * Otherwise, we're building nested page tables, and that's
  804. * probably because userspace called KVM_ARM_VCPU_INIT more
  805. * than once on the same vcpu. Since that's actually legal,
  806. * don't kick a fuss and leave gracefully.
  807. */
  808. if (mmu->pgt != NULL) {
  809. if (kvm_is_nested_s2_mmu(kvm, mmu))
  810. return 0;
  811. kvm_err("kvm_arch already initialized?\n");
  812. return -EINVAL;
  813. }
  814. err = kvm_init_ipa_range(mmu, type);
  815. if (err)
  816. return err;
  817. pgt = kzalloc_obj(*pgt, GFP_KERNEL_ACCOUNT);
  818. if (!pgt)
  819. return -ENOMEM;
  820. mmu->arch = &kvm->arch;
  821. err = KVM_PGT_FN(kvm_pgtable_stage2_init)(pgt, mmu, &kvm_s2_mm_ops);
  822. if (err)
  823. goto out_free_pgtable;
  824. mmu->pgt = pgt;
  825. if (is_protected_kvm_enabled())
  826. return 0;
  827. mmu->last_vcpu_ran = alloc_percpu(typeof(*mmu->last_vcpu_ran));
  828. if (!mmu->last_vcpu_ran) {
  829. err = -ENOMEM;
  830. goto out_destroy_pgtable;
  831. }
  832. for_each_possible_cpu(cpu)
  833. *per_cpu_ptr(mmu->last_vcpu_ran, cpu) = -1;
  834. /* The eager page splitting is disabled by default */
  835. mmu->split_page_chunk_size = KVM_ARM_EAGER_SPLIT_CHUNK_SIZE_DEFAULT;
  836. mmu->split_page_cache.gfp_zero = __GFP_ZERO;
  837. mmu->pgd_phys = __pa(pgt->pgd);
  838. if (kvm_is_nested_s2_mmu(kvm, mmu))
  839. kvm_init_nested_s2_mmu(mmu);
  840. return 0;
  841. out_destroy_pgtable:
  842. kvm_stage2_destroy(pgt);
  843. out_free_pgtable:
  844. kfree(pgt);
  845. return err;
  846. }
  847. void kvm_uninit_stage2_mmu(struct kvm *kvm)
  848. {
  849. kvm_free_stage2_pgd(&kvm->arch.mmu);
  850. kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
  851. }
  852. static void stage2_unmap_memslot(struct kvm *kvm,
  853. struct kvm_memory_slot *memslot)
  854. {
  855. hva_t hva = memslot->userspace_addr;
  856. phys_addr_t addr = memslot->base_gfn << PAGE_SHIFT;
  857. phys_addr_t size = PAGE_SIZE * memslot->npages;
  858. hva_t reg_end = hva + size;
  859. /*
  860. * A memory region could potentially cover multiple VMAs, and any holes
  861. * between them, so iterate over all of them to find out if we should
  862. * unmap any of them.
  863. *
  864. * +--------------------------------------------+
  865. * +---------------+----------------+ +----------------+
  866. * | : VMA 1 | VMA 2 | | VMA 3 : |
  867. * +---------------+----------------+ +----------------+
  868. * | memory region |
  869. * +--------------------------------------------+
  870. */
  871. do {
  872. struct vm_area_struct *vma;
  873. hva_t vm_start, vm_end;
  874. vma = find_vma_intersection(current->mm, hva, reg_end);
  875. if (!vma)
  876. break;
  877. /*
  878. * Take the intersection of this VMA with the memory region
  879. */
  880. vm_start = max(hva, vma->vm_start);
  881. vm_end = min(reg_end, vma->vm_end);
  882. if (!(vma->vm_flags & VM_PFNMAP)) {
  883. gpa_t gpa = addr + (vm_start - memslot->userspace_addr);
  884. kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, vm_end - vm_start, true);
  885. }
  886. hva = vm_end;
  887. } while (hva < reg_end);
  888. }
  889. /**
  890. * stage2_unmap_vm - Unmap Stage-2 RAM mappings
  891. * @kvm: The struct kvm pointer
  892. *
  893. * Go through the memregions and unmap any regular RAM
  894. * backing memory already mapped to the VM.
  895. */
  896. void stage2_unmap_vm(struct kvm *kvm)
  897. {
  898. struct kvm_memslots *slots;
  899. struct kvm_memory_slot *memslot;
  900. int idx, bkt;
  901. idx = srcu_read_lock(&kvm->srcu);
  902. mmap_read_lock(current->mm);
  903. write_lock(&kvm->mmu_lock);
  904. slots = kvm_memslots(kvm);
  905. kvm_for_each_memslot(memslot, bkt, slots)
  906. stage2_unmap_memslot(kvm, memslot);
  907. kvm_nested_s2_unmap(kvm, true);
  908. write_unlock(&kvm->mmu_lock);
  909. mmap_read_unlock(current->mm);
  910. srcu_read_unlock(&kvm->srcu, idx);
  911. }
  912. void kvm_free_stage2_pgd(struct kvm_s2_mmu *mmu)
  913. {
  914. struct kvm *kvm = kvm_s2_mmu_to_kvm(mmu);
  915. struct kvm_pgtable *pgt = NULL;
  916. write_lock(&kvm->mmu_lock);
  917. pgt = mmu->pgt;
  918. if (pgt) {
  919. mmu->pgd_phys = 0;
  920. mmu->pgt = NULL;
  921. free_percpu(mmu->last_vcpu_ran);
  922. }
  923. if (kvm_is_nested_s2_mmu(kvm, mmu))
  924. kvm_init_nested_s2_mmu(mmu);
  925. write_unlock(&kvm->mmu_lock);
  926. if (pgt) {
  927. kvm_stage2_destroy(pgt);
  928. kfree(pgt);
  929. }
  930. }
  931. static void hyp_mc_free_fn(void *addr, void *mc)
  932. {
  933. struct kvm_hyp_memcache *memcache = mc;
  934. if (memcache->flags & HYP_MEMCACHE_ACCOUNT_STAGE2)
  935. kvm_account_pgtable_pages(addr, -1);
  936. free_page((unsigned long)addr);
  937. }
  938. static void *hyp_mc_alloc_fn(void *mc)
  939. {
  940. struct kvm_hyp_memcache *memcache = mc;
  941. void *addr;
  942. addr = (void *)__get_free_page(GFP_KERNEL_ACCOUNT);
  943. if (addr && memcache->flags & HYP_MEMCACHE_ACCOUNT_STAGE2)
  944. kvm_account_pgtable_pages(addr, 1);
  945. return addr;
  946. }
  947. void free_hyp_memcache(struct kvm_hyp_memcache *mc)
  948. {
  949. if (!is_protected_kvm_enabled())
  950. return;
  951. kfree(mc->mapping);
  952. __free_hyp_memcache(mc, hyp_mc_free_fn, kvm_host_va, mc);
  953. }
  954. int topup_hyp_memcache(struct kvm_hyp_memcache *mc, unsigned long min_pages)
  955. {
  956. if (!is_protected_kvm_enabled())
  957. return 0;
  958. if (!mc->mapping) {
  959. mc->mapping = kzalloc_obj(struct pkvm_mapping,
  960. GFP_KERNEL_ACCOUNT);
  961. if (!mc->mapping)
  962. return -ENOMEM;
  963. }
  964. return __topup_hyp_memcache(mc, min_pages, hyp_mc_alloc_fn,
  965. kvm_host_pa, mc);
  966. }
  967. /**
  968. * kvm_phys_addr_ioremap - map a device range to guest IPA
  969. *
  970. * @kvm: The KVM pointer
  971. * @guest_ipa: The IPA at which to insert the mapping
  972. * @pa: The physical address of the device
  973. * @size: The size of the mapping
  974. * @writable: Whether or not to create a writable mapping
  975. */
  976. int kvm_phys_addr_ioremap(struct kvm *kvm, phys_addr_t guest_ipa,
  977. phys_addr_t pa, unsigned long size, bool writable)
  978. {
  979. phys_addr_t addr;
  980. int ret = 0;
  981. struct kvm_mmu_memory_cache cache = { .gfp_zero = __GFP_ZERO };
  982. struct kvm_s2_mmu *mmu = &kvm->arch.mmu;
  983. struct kvm_pgtable *pgt = mmu->pgt;
  984. enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_DEVICE |
  985. KVM_PGTABLE_PROT_R |
  986. (writable ? KVM_PGTABLE_PROT_W : 0);
  987. if (is_protected_kvm_enabled())
  988. return -EPERM;
  989. size += offset_in_page(guest_ipa);
  990. guest_ipa &= PAGE_MASK;
  991. for (addr = guest_ipa; addr < guest_ipa + size; addr += PAGE_SIZE) {
  992. ret = kvm_mmu_topup_memory_cache(&cache,
  993. kvm_mmu_cache_min_pages(mmu));
  994. if (ret)
  995. break;
  996. write_lock(&kvm->mmu_lock);
  997. ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, addr, PAGE_SIZE,
  998. pa, prot, &cache, 0);
  999. write_unlock(&kvm->mmu_lock);
  1000. if (ret)
  1001. break;
  1002. pa += PAGE_SIZE;
  1003. }
  1004. kvm_mmu_free_memory_cache(&cache);
  1005. return ret;
  1006. }
  1007. /**
  1008. * kvm_stage2_wp_range() - write protect stage2 memory region range
  1009. * @mmu: The KVM stage-2 MMU pointer
  1010. * @addr: Start address of range
  1011. * @end: End address of range
  1012. */
  1013. void kvm_stage2_wp_range(struct kvm_s2_mmu *mmu, phys_addr_t addr, phys_addr_t end)
  1014. {
  1015. stage2_apply_range_resched(mmu, addr, end, KVM_PGT_FN(kvm_pgtable_stage2_wrprotect));
  1016. }
  1017. /**
  1018. * kvm_mmu_wp_memory_region() - write protect stage 2 entries for memory slot
  1019. * @kvm: The KVM pointer
  1020. * @slot: The memory slot to write protect
  1021. *
  1022. * Called to start logging dirty pages after memory region
  1023. * KVM_MEM_LOG_DIRTY_PAGES operation is called. After this function returns
  1024. * all present PUD, PMD and PTEs are write protected in the memory region.
  1025. * Afterwards read of dirty page log can be called.
  1026. *
  1027. * Acquires kvm_mmu_lock. Called with kvm->slots_lock mutex acquired,
  1028. * serializing operations for VM memory regions.
  1029. */
  1030. static void kvm_mmu_wp_memory_region(struct kvm *kvm, int slot)
  1031. {
  1032. struct kvm_memslots *slots = kvm_memslots(kvm);
  1033. struct kvm_memory_slot *memslot = id_to_memslot(slots, slot);
  1034. phys_addr_t start, end;
  1035. if (WARN_ON_ONCE(!memslot))
  1036. return;
  1037. start = memslot->base_gfn << PAGE_SHIFT;
  1038. end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
  1039. write_lock(&kvm->mmu_lock);
  1040. kvm_stage2_wp_range(&kvm->arch.mmu, start, end);
  1041. kvm_nested_s2_wp(kvm);
  1042. write_unlock(&kvm->mmu_lock);
  1043. kvm_flush_remote_tlbs_memslot(kvm, memslot);
  1044. }
  1045. /**
  1046. * kvm_mmu_split_memory_region() - split the stage 2 blocks into PAGE_SIZE
  1047. * pages for memory slot
  1048. * @kvm: The KVM pointer
  1049. * @slot: The memory slot to split
  1050. *
  1051. * Acquires kvm->mmu_lock. Called with kvm->slots_lock mutex acquired,
  1052. * serializing operations for VM memory regions.
  1053. */
  1054. static void kvm_mmu_split_memory_region(struct kvm *kvm, int slot)
  1055. {
  1056. struct kvm_memslots *slots;
  1057. struct kvm_memory_slot *memslot;
  1058. phys_addr_t start, end;
  1059. lockdep_assert_held(&kvm->slots_lock);
  1060. slots = kvm_memslots(kvm);
  1061. memslot = id_to_memslot(slots, slot);
  1062. start = memslot->base_gfn << PAGE_SHIFT;
  1063. end = (memslot->base_gfn + memslot->npages) << PAGE_SHIFT;
  1064. write_lock(&kvm->mmu_lock);
  1065. kvm_mmu_split_huge_pages(kvm, start, end);
  1066. write_unlock(&kvm->mmu_lock);
  1067. }
  1068. /*
  1069. * kvm_arch_mmu_enable_log_dirty_pt_masked() - enable dirty logging for selected pages.
  1070. * @kvm: The KVM pointer
  1071. * @slot: The memory slot associated with mask
  1072. * @gfn_offset: The gfn offset in memory slot
  1073. * @mask: The mask of pages at offset 'gfn_offset' in this memory
  1074. * slot to enable dirty logging on
  1075. *
  1076. * Writes protect selected pages to enable dirty logging, and then
  1077. * splits them to PAGE_SIZE. Caller must acquire kvm->mmu_lock.
  1078. */
  1079. void kvm_arch_mmu_enable_log_dirty_pt_masked(struct kvm *kvm,
  1080. struct kvm_memory_slot *slot,
  1081. gfn_t gfn_offset, unsigned long mask)
  1082. {
  1083. phys_addr_t base_gfn = slot->base_gfn + gfn_offset;
  1084. phys_addr_t start = (base_gfn + __ffs(mask)) << PAGE_SHIFT;
  1085. phys_addr_t end = (base_gfn + __fls(mask) + 1) << PAGE_SHIFT;
  1086. lockdep_assert_held_write(&kvm->mmu_lock);
  1087. kvm_stage2_wp_range(&kvm->arch.mmu, start, end);
  1088. /*
  1089. * Eager-splitting is done when manual-protect is set. We
  1090. * also check for initially-all-set because we can avoid
  1091. * eager-splitting if initially-all-set is false.
  1092. * Initially-all-set equal false implies that huge-pages were
  1093. * already split when enabling dirty logging: no need to do it
  1094. * again.
  1095. */
  1096. if (kvm_dirty_log_manual_protect_and_init_set(kvm))
  1097. kvm_mmu_split_huge_pages(kvm, start, end);
  1098. kvm_nested_s2_wp(kvm);
  1099. }
  1100. static void kvm_send_hwpoison_signal(unsigned long address, short lsb)
  1101. {
  1102. send_sig_mceerr(BUS_MCEERR_AR, (void __user *)address, lsb, current);
  1103. }
  1104. static bool fault_supports_stage2_huge_mapping(struct kvm_memory_slot *memslot,
  1105. unsigned long hva,
  1106. unsigned long map_size)
  1107. {
  1108. gpa_t gpa_start;
  1109. hva_t uaddr_start, uaddr_end;
  1110. size_t size;
  1111. /* The memslot and the VMA are guaranteed to be aligned to PAGE_SIZE */
  1112. if (map_size == PAGE_SIZE)
  1113. return true;
  1114. /* pKVM only supports PMD_SIZE huge-mappings */
  1115. if (is_protected_kvm_enabled() && map_size != PMD_SIZE)
  1116. return false;
  1117. size = memslot->npages * PAGE_SIZE;
  1118. gpa_start = memslot->base_gfn << PAGE_SHIFT;
  1119. uaddr_start = memslot->userspace_addr;
  1120. uaddr_end = uaddr_start + size;
  1121. /*
  1122. * Pages belonging to memslots that don't have the same alignment
  1123. * within a PMD/PUD for userspace and IPA cannot be mapped with stage-2
  1124. * PMD/PUD entries, because we'll end up mapping the wrong pages.
  1125. *
  1126. * Consider a layout like the following:
  1127. *
  1128. * memslot->userspace_addr:
  1129. * +-----+--------------------+--------------------+---+
  1130. * |abcde|fgh Stage-1 block | Stage-1 block tv|xyz|
  1131. * +-----+--------------------+--------------------+---+
  1132. *
  1133. * memslot->base_gfn << PAGE_SHIFT:
  1134. * +---+--------------------+--------------------+-----+
  1135. * |abc|def Stage-2 block | Stage-2 block |tvxyz|
  1136. * +---+--------------------+--------------------+-----+
  1137. *
  1138. * If we create those stage-2 blocks, we'll end up with this incorrect
  1139. * mapping:
  1140. * d -> f
  1141. * e -> g
  1142. * f -> h
  1143. */
  1144. if ((gpa_start & (map_size - 1)) != (uaddr_start & (map_size - 1)))
  1145. return false;
  1146. /*
  1147. * Next, let's make sure we're not trying to map anything not covered
  1148. * by the memslot. This means we have to prohibit block size mappings
  1149. * for the beginning and end of a non-block aligned and non-block sized
  1150. * memory slot (illustrated by the head and tail parts of the
  1151. * userspace view above containing pages 'abcde' and 'xyz',
  1152. * respectively).
  1153. *
  1154. * Note that it doesn't matter if we do the check using the
  1155. * userspace_addr or the base_gfn, as both are equally aligned (per
  1156. * the check above) and equally sized.
  1157. */
  1158. return (hva & ~(map_size - 1)) >= uaddr_start &&
  1159. (hva & ~(map_size - 1)) + map_size <= uaddr_end;
  1160. }
  1161. /*
  1162. * Check if the given hva is backed by a transparent huge page (THP) and
  1163. * whether it can be mapped using block mapping in stage2. If so, adjust
  1164. * the stage2 PFN and IPA accordingly. Only PMD_SIZE THPs are currently
  1165. * supported. This will need to be updated to support other THP sizes.
  1166. *
  1167. * Returns the size of the mapping.
  1168. */
  1169. static long
  1170. transparent_hugepage_adjust(struct kvm *kvm, struct kvm_memory_slot *memslot,
  1171. unsigned long hva, kvm_pfn_t *pfnp,
  1172. phys_addr_t *ipap)
  1173. {
  1174. kvm_pfn_t pfn = *pfnp;
  1175. /*
  1176. * Make sure the adjustment is done only for THP pages. Also make
  1177. * sure that the HVA and IPA are sufficiently aligned and that the
  1178. * block map is contained within the memslot.
  1179. */
  1180. if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE)) {
  1181. int sz = get_user_mapping_size(kvm, hva);
  1182. if (sz < 0)
  1183. return sz;
  1184. if (sz < PMD_SIZE)
  1185. return PAGE_SIZE;
  1186. *ipap &= PMD_MASK;
  1187. pfn &= ~(PTRS_PER_PMD - 1);
  1188. *pfnp = pfn;
  1189. return PMD_SIZE;
  1190. }
  1191. /* Use page mapping if we cannot use block mapping. */
  1192. return PAGE_SIZE;
  1193. }
  1194. static int get_vma_page_shift(struct vm_area_struct *vma, unsigned long hva)
  1195. {
  1196. unsigned long pa;
  1197. if (is_vm_hugetlb_page(vma) && !(vma->vm_flags & VM_PFNMAP))
  1198. return huge_page_shift(hstate_vma(vma));
  1199. if (!(vma->vm_flags & VM_PFNMAP))
  1200. return PAGE_SHIFT;
  1201. VM_BUG_ON(is_vm_hugetlb_page(vma));
  1202. pa = (vma->vm_pgoff << PAGE_SHIFT) + (hva - vma->vm_start);
  1203. #ifndef __PAGETABLE_PMD_FOLDED
  1204. if ((hva & (PUD_SIZE - 1)) == (pa & (PUD_SIZE - 1)) &&
  1205. ALIGN_DOWN(hva, PUD_SIZE) >= vma->vm_start &&
  1206. ALIGN(hva, PUD_SIZE) <= vma->vm_end)
  1207. return PUD_SHIFT;
  1208. #endif
  1209. if ((hva & (PMD_SIZE - 1)) == (pa & (PMD_SIZE - 1)) &&
  1210. ALIGN_DOWN(hva, PMD_SIZE) >= vma->vm_start &&
  1211. ALIGN(hva, PMD_SIZE) <= vma->vm_end)
  1212. return PMD_SHIFT;
  1213. return PAGE_SHIFT;
  1214. }
  1215. /*
  1216. * The page will be mapped in stage 2 as Normal Cacheable, so the VM will be
  1217. * able to see the page's tags and therefore they must be initialised first. If
  1218. * PG_mte_tagged is set, tags have already been initialised.
  1219. *
  1220. * Must be called with kvm->mmu_lock held to ensure the memory remains mapped
  1221. * while the tags are zeroed.
  1222. */
  1223. static void sanitise_mte_tags(struct kvm *kvm, kvm_pfn_t pfn,
  1224. unsigned long size)
  1225. {
  1226. unsigned long i, nr_pages = size >> PAGE_SHIFT;
  1227. struct page *page = pfn_to_page(pfn);
  1228. struct folio *folio = page_folio(page);
  1229. if (!kvm_has_mte(kvm))
  1230. return;
  1231. if (folio_test_hugetlb(folio)) {
  1232. /* Hugetlb has MTE flags set on head page only */
  1233. if (folio_try_hugetlb_mte_tagging(folio)) {
  1234. for (i = 0; i < nr_pages; i++, page++)
  1235. mte_clear_page_tags(page_address(page));
  1236. folio_set_hugetlb_mte_tagged(folio);
  1237. }
  1238. return;
  1239. }
  1240. for (i = 0; i < nr_pages; i++, page++) {
  1241. if (try_page_mte_tagging(page)) {
  1242. mte_clear_page_tags(page_address(page));
  1243. set_page_mte_tagged(page);
  1244. }
  1245. }
  1246. }
  1247. static bool kvm_vma_mte_allowed(struct vm_area_struct *vma)
  1248. {
  1249. return vma->vm_flags & VM_MTE_ALLOWED;
  1250. }
  1251. static bool kvm_vma_is_cacheable(struct vm_area_struct *vma)
  1252. {
  1253. switch (FIELD_GET(PTE_ATTRINDX_MASK, pgprot_val(vma->vm_page_prot))) {
  1254. case MT_NORMAL_NC:
  1255. case MT_DEVICE_nGnRnE:
  1256. case MT_DEVICE_nGnRE:
  1257. return false;
  1258. default:
  1259. return true;
  1260. }
  1261. }
  1262. static int prepare_mmu_memcache(struct kvm_vcpu *vcpu, bool topup_memcache,
  1263. void **memcache)
  1264. {
  1265. int min_pages;
  1266. if (!is_protected_kvm_enabled())
  1267. *memcache = &vcpu->arch.mmu_page_cache;
  1268. else
  1269. *memcache = &vcpu->arch.pkvm_memcache;
  1270. if (!topup_memcache)
  1271. return 0;
  1272. min_pages = kvm_mmu_cache_min_pages(vcpu->arch.hw_mmu);
  1273. if (!is_protected_kvm_enabled())
  1274. return kvm_mmu_topup_memory_cache(*memcache, min_pages);
  1275. return topup_hyp_memcache(*memcache, min_pages);
  1276. }
  1277. /*
  1278. * Potentially reduce shadow S2 permissions to match the guest's own S2. For
  1279. * exec faults, we'd only reach this point if the guest actually allowed it (see
  1280. * kvm_s2_handle_perm_fault).
  1281. *
  1282. * Also encode the level of the original translation in the SW bits of the leaf
  1283. * entry as a proxy for the span of that translation. This will be retrieved on
  1284. * TLB invalidation from the guest and used to limit the invalidation scope if a
  1285. * TTL hint or a range isn't provided.
  1286. */
  1287. static void adjust_nested_fault_perms(struct kvm_s2_trans *nested,
  1288. enum kvm_pgtable_prot *prot,
  1289. bool *writable)
  1290. {
  1291. *writable &= kvm_s2_trans_writable(nested);
  1292. if (!kvm_s2_trans_readable(nested))
  1293. *prot &= ~KVM_PGTABLE_PROT_R;
  1294. *prot |= kvm_encode_nested_level(nested);
  1295. }
  1296. static void adjust_nested_exec_perms(struct kvm *kvm,
  1297. struct kvm_s2_trans *nested,
  1298. enum kvm_pgtable_prot *prot)
  1299. {
  1300. if (!kvm_s2_trans_exec_el0(kvm, nested))
  1301. *prot &= ~KVM_PGTABLE_PROT_UX;
  1302. if (!kvm_s2_trans_exec_el1(kvm, nested))
  1303. *prot &= ~KVM_PGTABLE_PROT_PX;
  1304. }
  1305. static int gmem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
  1306. struct kvm_s2_trans *nested,
  1307. struct kvm_memory_slot *memslot, bool is_perm)
  1308. {
  1309. bool write_fault, exec_fault, writable;
  1310. enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
  1311. enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
  1312. struct kvm_pgtable *pgt = vcpu->arch.hw_mmu->pgt;
  1313. unsigned long mmu_seq;
  1314. struct page *page;
  1315. struct kvm *kvm = vcpu->kvm;
  1316. void *memcache;
  1317. kvm_pfn_t pfn;
  1318. gfn_t gfn;
  1319. int ret;
  1320. ret = prepare_mmu_memcache(vcpu, true, &memcache);
  1321. if (ret)
  1322. return ret;
  1323. if (nested)
  1324. gfn = kvm_s2_trans_output(nested) >> PAGE_SHIFT;
  1325. else
  1326. gfn = fault_ipa >> PAGE_SHIFT;
  1327. write_fault = kvm_is_write_fault(vcpu);
  1328. exec_fault = kvm_vcpu_trap_is_exec_fault(vcpu);
  1329. VM_WARN_ON_ONCE(write_fault && exec_fault);
  1330. mmu_seq = kvm->mmu_invalidate_seq;
  1331. /* Pairs with the smp_wmb() in kvm_mmu_invalidate_end(). */
  1332. smp_rmb();
  1333. ret = kvm_gmem_get_pfn(kvm, memslot, gfn, &pfn, &page, NULL);
  1334. if (ret) {
  1335. kvm_prepare_memory_fault_exit(vcpu, fault_ipa, PAGE_SIZE,
  1336. write_fault, exec_fault, false);
  1337. return ret;
  1338. }
  1339. writable = !(memslot->flags & KVM_MEM_READONLY);
  1340. if (nested)
  1341. adjust_nested_fault_perms(nested, &prot, &writable);
  1342. if (writable)
  1343. prot |= KVM_PGTABLE_PROT_W;
  1344. if (exec_fault || cpus_have_final_cap(ARM64_HAS_CACHE_DIC))
  1345. prot |= KVM_PGTABLE_PROT_X;
  1346. if (nested)
  1347. adjust_nested_exec_perms(kvm, nested, &prot);
  1348. kvm_fault_lock(kvm);
  1349. if (mmu_invalidate_retry(kvm, mmu_seq)) {
  1350. ret = -EAGAIN;
  1351. goto out_unlock;
  1352. }
  1353. ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, fault_ipa, PAGE_SIZE,
  1354. __pfn_to_phys(pfn), prot,
  1355. memcache, flags);
  1356. out_unlock:
  1357. kvm_release_faultin_page(kvm, page, !!ret, writable);
  1358. kvm_fault_unlock(kvm);
  1359. if (writable && !ret)
  1360. mark_page_dirty_in_slot(kvm, memslot, gfn);
  1361. return ret != -EAGAIN ? ret : 0;
  1362. }
  1363. static int user_mem_abort(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa,
  1364. struct kvm_s2_trans *nested,
  1365. struct kvm_memory_slot *memslot, unsigned long hva,
  1366. bool fault_is_perm)
  1367. {
  1368. int ret = 0;
  1369. bool topup_memcache;
  1370. bool write_fault, writable;
  1371. bool exec_fault, mte_allowed, is_vma_cacheable;
  1372. bool s2_force_noncacheable = false, vfio_allow_any_uc = false;
  1373. unsigned long mmu_seq;
  1374. phys_addr_t ipa = fault_ipa;
  1375. struct kvm *kvm = vcpu->kvm;
  1376. struct vm_area_struct *vma;
  1377. short vma_shift;
  1378. void *memcache;
  1379. gfn_t gfn;
  1380. kvm_pfn_t pfn;
  1381. bool logging_active = memslot_is_logging(memslot);
  1382. bool force_pte = logging_active;
  1383. long vma_pagesize, fault_granule;
  1384. enum kvm_pgtable_prot prot = KVM_PGTABLE_PROT_R;
  1385. struct kvm_pgtable *pgt;
  1386. struct page *page;
  1387. vm_flags_t vm_flags;
  1388. enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
  1389. if (fault_is_perm)
  1390. fault_granule = kvm_vcpu_trap_get_perm_fault_granule(vcpu);
  1391. write_fault = kvm_is_write_fault(vcpu);
  1392. exec_fault = kvm_vcpu_trap_is_exec_fault(vcpu);
  1393. VM_WARN_ON_ONCE(write_fault && exec_fault);
  1394. /*
  1395. * Permission faults just need to update the existing leaf entry,
  1396. * and so normally don't require allocations from the memcache. The
  1397. * only exception to this is when dirty logging is enabled at runtime
  1398. * and a write fault needs to collapse a block entry into a table.
  1399. */
  1400. topup_memcache = !fault_is_perm || (logging_active && write_fault);
  1401. ret = prepare_mmu_memcache(vcpu, topup_memcache, &memcache);
  1402. if (ret)
  1403. return ret;
  1404. /*
  1405. * Let's check if we will get back a huge page backed by hugetlbfs, or
  1406. * get block mapping for device MMIO region.
  1407. */
  1408. mmap_read_lock(current->mm);
  1409. vma = vma_lookup(current->mm, hva);
  1410. if (unlikely(!vma)) {
  1411. kvm_err("Failed to find VMA for hva 0x%lx\n", hva);
  1412. mmap_read_unlock(current->mm);
  1413. return -EFAULT;
  1414. }
  1415. if (force_pte)
  1416. vma_shift = PAGE_SHIFT;
  1417. else
  1418. vma_shift = get_vma_page_shift(vma, hva);
  1419. switch (vma_shift) {
  1420. #ifndef __PAGETABLE_PMD_FOLDED
  1421. case PUD_SHIFT:
  1422. if (fault_supports_stage2_huge_mapping(memslot, hva, PUD_SIZE))
  1423. break;
  1424. fallthrough;
  1425. #endif
  1426. case CONT_PMD_SHIFT:
  1427. vma_shift = PMD_SHIFT;
  1428. fallthrough;
  1429. case PMD_SHIFT:
  1430. if (fault_supports_stage2_huge_mapping(memslot, hva, PMD_SIZE))
  1431. break;
  1432. fallthrough;
  1433. case CONT_PTE_SHIFT:
  1434. vma_shift = PAGE_SHIFT;
  1435. force_pte = true;
  1436. fallthrough;
  1437. case PAGE_SHIFT:
  1438. break;
  1439. default:
  1440. WARN_ONCE(1, "Unknown vma_shift %d", vma_shift);
  1441. }
  1442. vma_pagesize = 1UL << vma_shift;
  1443. if (nested) {
  1444. unsigned long max_map_size;
  1445. max_map_size = force_pte ? PAGE_SIZE : PUD_SIZE;
  1446. ipa = kvm_s2_trans_output(nested);
  1447. /*
  1448. * If we're about to create a shadow stage 2 entry, then we
  1449. * can only create a block mapping if the guest stage 2 page
  1450. * table uses at least as big a mapping.
  1451. */
  1452. max_map_size = min(kvm_s2_trans_size(nested), max_map_size);
  1453. /*
  1454. * Be careful that if the mapping size falls between
  1455. * two host sizes, take the smallest of the two.
  1456. */
  1457. if (max_map_size >= PMD_SIZE && max_map_size < PUD_SIZE)
  1458. max_map_size = PMD_SIZE;
  1459. else if (max_map_size >= PAGE_SIZE && max_map_size < PMD_SIZE)
  1460. max_map_size = PAGE_SIZE;
  1461. force_pte = (max_map_size == PAGE_SIZE);
  1462. vma_pagesize = min_t(long, vma_pagesize, max_map_size);
  1463. vma_shift = __ffs(vma_pagesize);
  1464. }
  1465. /*
  1466. * Both the canonical IPA and fault IPA must be aligned to the
  1467. * mapping size to ensure we find the right PFN and lay down the
  1468. * mapping in the right place.
  1469. */
  1470. fault_ipa = ALIGN_DOWN(fault_ipa, vma_pagesize);
  1471. ipa = ALIGN_DOWN(ipa, vma_pagesize);
  1472. gfn = ipa >> PAGE_SHIFT;
  1473. mte_allowed = kvm_vma_mte_allowed(vma);
  1474. vfio_allow_any_uc = vma->vm_flags & VM_ALLOW_ANY_UNCACHED;
  1475. vm_flags = vma->vm_flags;
  1476. is_vma_cacheable = kvm_vma_is_cacheable(vma);
  1477. /* Don't use the VMA after the unlock -- it may have vanished */
  1478. vma = NULL;
  1479. /*
  1480. * Read mmu_invalidate_seq so that KVM can detect if the results of
  1481. * vma_lookup() or __kvm_faultin_pfn() become stale prior to
  1482. * acquiring kvm->mmu_lock.
  1483. *
  1484. * Rely on mmap_read_unlock() for an implicit smp_rmb(), which pairs
  1485. * with the smp_wmb() in kvm_mmu_invalidate_end().
  1486. */
  1487. mmu_seq = kvm->mmu_invalidate_seq;
  1488. mmap_read_unlock(current->mm);
  1489. pfn = __kvm_faultin_pfn(memslot, gfn, write_fault ? FOLL_WRITE : 0,
  1490. &writable, &page);
  1491. if (pfn == KVM_PFN_ERR_HWPOISON) {
  1492. kvm_send_hwpoison_signal(hva, vma_shift);
  1493. return 0;
  1494. }
  1495. if (is_error_noslot_pfn(pfn))
  1496. return -EFAULT;
  1497. /*
  1498. * Check if this is non-struct page memory PFN, and cannot support
  1499. * CMOs. It could potentially be unsafe to access as cacheable.
  1500. */
  1501. if (vm_flags & (VM_PFNMAP | VM_MIXEDMAP) && !pfn_is_map_memory(pfn)) {
  1502. if (is_vma_cacheable) {
  1503. /*
  1504. * Whilst the VMA owner expects cacheable mapping to this
  1505. * PFN, hardware also has to support the FWB and CACHE DIC
  1506. * features.
  1507. *
  1508. * ARM64 KVM relies on kernel VA mapping to the PFN to
  1509. * perform cache maintenance as the CMO instructions work on
  1510. * virtual addresses. VM_PFNMAP region are not necessarily
  1511. * mapped to a KVA and hence the presence of hardware features
  1512. * S2FWB and CACHE DIC are mandatory to avoid the need for
  1513. * cache maintenance.
  1514. */
  1515. if (!kvm_supports_cacheable_pfnmap())
  1516. ret = -EFAULT;
  1517. } else {
  1518. /*
  1519. * If the page was identified as device early by looking at
  1520. * the VMA flags, vma_pagesize is already representing the
  1521. * largest quantity we can map. If instead it was mapped
  1522. * via __kvm_faultin_pfn(), vma_pagesize is set to PAGE_SIZE
  1523. * and must not be upgraded.
  1524. *
  1525. * In both cases, we don't let transparent_hugepage_adjust()
  1526. * change things at the last minute.
  1527. */
  1528. s2_force_noncacheable = true;
  1529. }
  1530. } else if (logging_active && !write_fault) {
  1531. /*
  1532. * Only actually map the page as writable if this was a write
  1533. * fault.
  1534. */
  1535. writable = false;
  1536. }
  1537. if (exec_fault && s2_force_noncacheable)
  1538. ret = -ENOEXEC;
  1539. if (ret)
  1540. goto out_put_page;
  1541. /*
  1542. * Guest performs atomic/exclusive operations on memory with unsupported
  1543. * attributes (e.g. ld64b/st64b on normal memory when no FEAT_LS64WB)
  1544. * and trigger the exception here. Since the memslot is valid, inject
  1545. * the fault back to the guest.
  1546. */
  1547. if (esr_fsc_is_excl_atomic_fault(kvm_vcpu_get_esr(vcpu))) {
  1548. kvm_inject_dabt_excl_atomic(vcpu, kvm_vcpu_get_hfar(vcpu));
  1549. ret = 1;
  1550. goto out_put_page;
  1551. }
  1552. if (nested)
  1553. adjust_nested_fault_perms(nested, &prot, &writable);
  1554. kvm_fault_lock(kvm);
  1555. pgt = vcpu->arch.hw_mmu->pgt;
  1556. if (mmu_invalidate_retry(kvm, mmu_seq)) {
  1557. ret = -EAGAIN;
  1558. goto out_unlock;
  1559. }
  1560. /*
  1561. * If we are not forced to use page mapping, check if we are
  1562. * backed by a THP and thus use block mapping if possible.
  1563. */
  1564. if (vma_pagesize == PAGE_SIZE && !(force_pte || s2_force_noncacheable)) {
  1565. if (fault_is_perm && fault_granule > PAGE_SIZE)
  1566. vma_pagesize = fault_granule;
  1567. else
  1568. vma_pagesize = transparent_hugepage_adjust(kvm, memslot,
  1569. hva, &pfn,
  1570. &fault_ipa);
  1571. if (vma_pagesize < 0) {
  1572. ret = vma_pagesize;
  1573. goto out_unlock;
  1574. }
  1575. }
  1576. if (!fault_is_perm && !s2_force_noncacheable && kvm_has_mte(kvm)) {
  1577. /* Check the VMM hasn't introduced a new disallowed VMA */
  1578. if (mte_allowed) {
  1579. sanitise_mte_tags(kvm, pfn, vma_pagesize);
  1580. } else {
  1581. ret = -EFAULT;
  1582. goto out_unlock;
  1583. }
  1584. }
  1585. if (writable)
  1586. prot |= KVM_PGTABLE_PROT_W;
  1587. if (exec_fault)
  1588. prot |= KVM_PGTABLE_PROT_X;
  1589. if (s2_force_noncacheable) {
  1590. if (vfio_allow_any_uc)
  1591. prot |= KVM_PGTABLE_PROT_NORMAL_NC;
  1592. else
  1593. prot |= KVM_PGTABLE_PROT_DEVICE;
  1594. } else if (cpus_have_final_cap(ARM64_HAS_CACHE_DIC)) {
  1595. prot |= KVM_PGTABLE_PROT_X;
  1596. }
  1597. if (nested)
  1598. adjust_nested_exec_perms(kvm, nested, &prot);
  1599. /*
  1600. * Under the premise of getting a FSC_PERM fault, we just need to relax
  1601. * permissions only if vma_pagesize equals fault_granule. Otherwise,
  1602. * kvm_pgtable_stage2_map() should be called to change block size.
  1603. */
  1604. if (fault_is_perm && vma_pagesize == fault_granule) {
  1605. /*
  1606. * Drop the SW bits in favour of those stored in the
  1607. * PTE, which will be preserved.
  1608. */
  1609. prot &= ~KVM_NV_GUEST_MAP_SZ;
  1610. ret = KVM_PGT_FN(kvm_pgtable_stage2_relax_perms)(pgt, fault_ipa, prot, flags);
  1611. } else {
  1612. ret = KVM_PGT_FN(kvm_pgtable_stage2_map)(pgt, fault_ipa, vma_pagesize,
  1613. __pfn_to_phys(pfn), prot,
  1614. memcache, flags);
  1615. }
  1616. out_unlock:
  1617. kvm_release_faultin_page(kvm, page, !!ret, writable);
  1618. kvm_fault_unlock(kvm);
  1619. /* Mark the page dirty only if the fault is handled successfully */
  1620. if (writable && !ret)
  1621. mark_page_dirty_in_slot(kvm, memslot, gfn);
  1622. return ret != -EAGAIN ? ret : 0;
  1623. out_put_page:
  1624. kvm_release_page_unused(page);
  1625. return ret;
  1626. }
  1627. /* Resolve the access fault by making the page young again. */
  1628. static void handle_access_fault(struct kvm_vcpu *vcpu, phys_addr_t fault_ipa)
  1629. {
  1630. enum kvm_pgtable_walk_flags flags = KVM_PGTABLE_WALK_SHARED;
  1631. struct kvm_s2_mmu *mmu;
  1632. trace_kvm_access_fault(fault_ipa);
  1633. read_lock(&vcpu->kvm->mmu_lock);
  1634. mmu = vcpu->arch.hw_mmu;
  1635. KVM_PGT_FN(kvm_pgtable_stage2_mkyoung)(mmu->pgt, fault_ipa, flags);
  1636. read_unlock(&vcpu->kvm->mmu_lock);
  1637. }
  1638. /*
  1639. * Returns true if the SEA should be handled locally within KVM if the abort
  1640. * is caused by a kernel memory allocation (e.g. stage-2 table memory).
  1641. */
  1642. static bool host_owns_sea(struct kvm_vcpu *vcpu, u64 esr)
  1643. {
  1644. /*
  1645. * Without FEAT_RAS HCR_EL2.TEA is RES0, meaning any external abort
  1646. * taken from a guest EL to EL2 is due to a host-imposed access (e.g.
  1647. * stage-2 PTW).
  1648. */
  1649. if (!cpus_have_final_cap(ARM64_HAS_RAS_EXTN))
  1650. return true;
  1651. /* KVM owns the VNCR when the vCPU isn't in a nested context. */
  1652. if (is_hyp_ctxt(vcpu) && !kvm_vcpu_trap_is_iabt(vcpu) && (esr & ESR_ELx_VNCR))
  1653. return true;
  1654. /*
  1655. * Determining if an external abort during a table walk happened at
  1656. * stage-2 is only possible with S1PTW is set. Otherwise, since KVM
  1657. * sets HCR_EL2.TEA, SEAs due to a stage-1 walk (i.e. accessing the
  1658. * PA of the stage-1 descriptor) can reach here and are reported
  1659. * with a TTW ESR value.
  1660. */
  1661. return (esr_fsc_is_sea_ttw(esr) && (esr & ESR_ELx_S1PTW));
  1662. }
  1663. int kvm_handle_guest_sea(struct kvm_vcpu *vcpu)
  1664. {
  1665. struct kvm *kvm = vcpu->kvm;
  1666. struct kvm_run *run = vcpu->run;
  1667. u64 esr = kvm_vcpu_get_esr(vcpu);
  1668. u64 esr_mask = ESR_ELx_EC_MASK |
  1669. ESR_ELx_IL |
  1670. ESR_ELx_FnV |
  1671. ESR_ELx_EA |
  1672. ESR_ELx_CM |
  1673. ESR_ELx_WNR |
  1674. ESR_ELx_FSC;
  1675. u64 ipa;
  1676. /*
  1677. * Give APEI the opportunity to claim the abort before handling it
  1678. * within KVM. apei_claim_sea() expects to be called with IRQs enabled.
  1679. */
  1680. lockdep_assert_irqs_enabled();
  1681. if (apei_claim_sea(NULL) == 0)
  1682. return 1;
  1683. if (host_owns_sea(vcpu, esr) ||
  1684. !test_bit(KVM_ARCH_FLAG_EXIT_SEA, &vcpu->kvm->arch.flags))
  1685. return kvm_inject_serror(vcpu);
  1686. /* ESR_ELx.SET is RES0 when FEAT_RAS isn't implemented. */
  1687. if (kvm_has_ras(kvm))
  1688. esr_mask |= ESR_ELx_SET_MASK;
  1689. /*
  1690. * Exit to userspace, and provide faulting guest virtual and physical
  1691. * addresses in case userspace wants to emulate SEA to guest by
  1692. * writing to FAR_ELx and HPFAR_ELx registers.
  1693. */
  1694. memset(&run->arm_sea, 0, sizeof(run->arm_sea));
  1695. run->exit_reason = KVM_EXIT_ARM_SEA;
  1696. run->arm_sea.esr = esr & esr_mask;
  1697. if (!(esr & ESR_ELx_FnV))
  1698. run->arm_sea.gva = kvm_vcpu_get_hfar(vcpu);
  1699. ipa = kvm_vcpu_get_fault_ipa(vcpu);
  1700. if (ipa != INVALID_GPA) {
  1701. run->arm_sea.flags |= KVM_EXIT_ARM_SEA_FLAG_GPA_VALID;
  1702. run->arm_sea.gpa = ipa;
  1703. }
  1704. return 0;
  1705. }
  1706. /**
  1707. * kvm_handle_guest_abort - handles all 2nd stage aborts
  1708. * @vcpu: the VCPU pointer
  1709. *
  1710. * Any abort that gets to the host is almost guaranteed to be caused by a
  1711. * missing second stage translation table entry, which can mean that either the
  1712. * guest simply needs more memory and we must allocate an appropriate page or it
  1713. * can mean that the guest tried to access I/O memory, which is emulated by user
  1714. * space. The distinction is based on the IPA causing the fault and whether this
  1715. * memory region has been registered as standard RAM by user space.
  1716. */
  1717. int kvm_handle_guest_abort(struct kvm_vcpu *vcpu)
  1718. {
  1719. struct kvm_s2_trans nested_trans, *nested = NULL;
  1720. unsigned long esr;
  1721. phys_addr_t fault_ipa; /* The address we faulted on */
  1722. phys_addr_t ipa; /* Always the IPA in the L1 guest phys space */
  1723. struct kvm_memory_slot *memslot;
  1724. unsigned long hva;
  1725. bool is_iabt, write_fault, writable;
  1726. gfn_t gfn;
  1727. int ret, idx;
  1728. if (kvm_vcpu_abt_issea(vcpu))
  1729. return kvm_handle_guest_sea(vcpu);
  1730. esr = kvm_vcpu_get_esr(vcpu);
  1731. /*
  1732. * The fault IPA should be reliable at this point as we're not dealing
  1733. * with an SEA.
  1734. */
  1735. ipa = fault_ipa = kvm_vcpu_get_fault_ipa(vcpu);
  1736. if (KVM_BUG_ON(ipa == INVALID_GPA, vcpu->kvm))
  1737. return -EFAULT;
  1738. is_iabt = kvm_vcpu_trap_is_iabt(vcpu);
  1739. if (esr_fsc_is_translation_fault(esr)) {
  1740. /* Beyond sanitised PARange (which is the IPA limit) */
  1741. if (fault_ipa >= BIT_ULL(get_kvm_ipa_limit())) {
  1742. kvm_inject_size_fault(vcpu);
  1743. return 1;
  1744. }
  1745. /* Falls between the IPA range and the PARange? */
  1746. if (fault_ipa >= BIT_ULL(VTCR_EL2_IPA(vcpu->arch.hw_mmu->vtcr))) {
  1747. fault_ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
  1748. return kvm_inject_sea(vcpu, is_iabt, fault_ipa);
  1749. }
  1750. }
  1751. trace_kvm_guest_fault(*vcpu_pc(vcpu), kvm_vcpu_get_esr(vcpu),
  1752. kvm_vcpu_get_hfar(vcpu), fault_ipa);
  1753. /* Check the stage-2 fault is trans. fault or write fault */
  1754. if (!esr_fsc_is_translation_fault(esr) &&
  1755. !esr_fsc_is_permission_fault(esr) &&
  1756. !esr_fsc_is_access_flag_fault(esr) &&
  1757. !esr_fsc_is_excl_atomic_fault(esr)) {
  1758. kvm_err("Unsupported FSC: EC=%#x xFSC=%#lx ESR_EL2=%#lx\n",
  1759. kvm_vcpu_trap_get_class(vcpu),
  1760. (unsigned long)kvm_vcpu_trap_get_fault(vcpu),
  1761. (unsigned long)kvm_vcpu_get_esr(vcpu));
  1762. return -EFAULT;
  1763. }
  1764. idx = srcu_read_lock(&vcpu->kvm->srcu);
  1765. /*
  1766. * We may have faulted on a shadow stage 2 page table if we are
  1767. * running a nested guest. In this case, we have to resolve the L2
  1768. * IPA to the L1 IPA first, before knowing what kind of memory should
  1769. * back the L1 IPA.
  1770. *
  1771. * If the shadow stage 2 page table walk faults, then we simply inject
  1772. * this to the guest and carry on.
  1773. *
  1774. * If there are no shadow S2 PTs because S2 is disabled, there is
  1775. * nothing to walk and we treat it as a 1:1 before going through the
  1776. * canonical translation.
  1777. */
  1778. if (kvm_is_nested_s2_mmu(vcpu->kvm,vcpu->arch.hw_mmu) &&
  1779. vcpu->arch.hw_mmu->nested_stage2_enabled) {
  1780. u32 esr;
  1781. ret = kvm_walk_nested_s2(vcpu, fault_ipa, &nested_trans);
  1782. if (ret == -EAGAIN) {
  1783. ret = 1;
  1784. goto out_unlock;
  1785. }
  1786. if (ret) {
  1787. esr = kvm_s2_trans_esr(&nested_trans);
  1788. kvm_inject_s2_fault(vcpu, esr);
  1789. goto out_unlock;
  1790. }
  1791. ret = kvm_s2_handle_perm_fault(vcpu, &nested_trans);
  1792. if (ret) {
  1793. esr = kvm_s2_trans_esr(&nested_trans);
  1794. kvm_inject_s2_fault(vcpu, esr);
  1795. goto out_unlock;
  1796. }
  1797. ipa = kvm_s2_trans_output(&nested_trans);
  1798. nested = &nested_trans;
  1799. }
  1800. gfn = ipa >> PAGE_SHIFT;
  1801. memslot = gfn_to_memslot(vcpu->kvm, gfn);
  1802. hva = gfn_to_hva_memslot_prot(memslot, gfn, &writable);
  1803. write_fault = kvm_is_write_fault(vcpu);
  1804. if (kvm_is_error_hva(hva) || (write_fault && !writable)) {
  1805. /*
  1806. * The guest has put either its instructions or its page-tables
  1807. * somewhere it shouldn't have. Userspace won't be able to do
  1808. * anything about this (there's no syndrome for a start), so
  1809. * re-inject the abort back into the guest.
  1810. */
  1811. if (is_iabt) {
  1812. ret = -ENOEXEC;
  1813. goto out;
  1814. }
  1815. if (kvm_vcpu_abt_iss1tw(vcpu)) {
  1816. ret = kvm_inject_sea_dabt(vcpu, kvm_vcpu_get_hfar(vcpu));
  1817. goto out_unlock;
  1818. }
  1819. /*
  1820. * Check for a cache maintenance operation. Since we
  1821. * ended-up here, we know it is outside of any memory
  1822. * slot. But we can't find out if that is for a device,
  1823. * or if the guest is just being stupid. The only thing
  1824. * we know for sure is that this range cannot be cached.
  1825. *
  1826. * So let's assume that the guest is just being
  1827. * cautious, and skip the instruction.
  1828. */
  1829. if (kvm_is_error_hva(hva) && kvm_vcpu_dabt_is_cm(vcpu)) {
  1830. kvm_incr_pc(vcpu);
  1831. ret = 1;
  1832. goto out_unlock;
  1833. }
  1834. /*
  1835. * The IPA is reported as [MAX:12], so we need to
  1836. * complement it with the bottom 12 bits from the
  1837. * faulting VA. This is always 12 bits, irrespective
  1838. * of the page size.
  1839. */
  1840. ipa |= FAR_TO_FIPA_OFFSET(kvm_vcpu_get_hfar(vcpu));
  1841. ret = io_mem_abort(vcpu, ipa);
  1842. goto out_unlock;
  1843. }
  1844. /* Userspace should not be able to register out-of-bounds IPAs */
  1845. VM_BUG_ON(ipa >= kvm_phys_size(vcpu->arch.hw_mmu));
  1846. if (esr_fsc_is_access_flag_fault(esr)) {
  1847. handle_access_fault(vcpu, fault_ipa);
  1848. ret = 1;
  1849. goto out_unlock;
  1850. }
  1851. VM_WARN_ON_ONCE(kvm_vcpu_trap_is_permission_fault(vcpu) &&
  1852. !write_fault && !kvm_vcpu_trap_is_exec_fault(vcpu));
  1853. if (kvm_slot_has_gmem(memslot))
  1854. ret = gmem_abort(vcpu, fault_ipa, nested, memslot,
  1855. esr_fsc_is_permission_fault(esr));
  1856. else
  1857. ret = user_mem_abort(vcpu, fault_ipa, nested, memslot, hva,
  1858. esr_fsc_is_permission_fault(esr));
  1859. if (ret == 0)
  1860. ret = 1;
  1861. out:
  1862. if (ret == -ENOEXEC)
  1863. ret = kvm_inject_sea_iabt(vcpu, kvm_vcpu_get_hfar(vcpu));
  1864. out_unlock:
  1865. srcu_read_unlock(&vcpu->kvm->srcu, idx);
  1866. return ret;
  1867. }
  1868. bool kvm_unmap_gfn_range(struct kvm *kvm, struct kvm_gfn_range *range)
  1869. {
  1870. if (!kvm->arch.mmu.pgt)
  1871. return false;
  1872. __unmap_stage2_range(&kvm->arch.mmu, range->start << PAGE_SHIFT,
  1873. (range->end - range->start) << PAGE_SHIFT,
  1874. range->may_block);
  1875. kvm_nested_s2_unmap(kvm, range->may_block);
  1876. return false;
  1877. }
  1878. bool kvm_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
  1879. {
  1880. u64 size = (range->end - range->start) << PAGE_SHIFT;
  1881. if (!kvm->arch.mmu.pgt)
  1882. return false;
  1883. return KVM_PGT_FN(kvm_pgtable_stage2_test_clear_young)(kvm->arch.mmu.pgt,
  1884. range->start << PAGE_SHIFT,
  1885. size, true);
  1886. /*
  1887. * TODO: Handle nested_mmu structures here using the reverse mapping in
  1888. * a later version of patch series.
  1889. */
  1890. }
  1891. bool kvm_test_age_gfn(struct kvm *kvm, struct kvm_gfn_range *range)
  1892. {
  1893. u64 size = (range->end - range->start) << PAGE_SHIFT;
  1894. if (!kvm->arch.mmu.pgt)
  1895. return false;
  1896. return KVM_PGT_FN(kvm_pgtable_stage2_test_clear_young)(kvm->arch.mmu.pgt,
  1897. range->start << PAGE_SHIFT,
  1898. size, false);
  1899. }
  1900. phys_addr_t kvm_mmu_get_httbr(void)
  1901. {
  1902. return __pa(hyp_pgtable->pgd);
  1903. }
  1904. phys_addr_t kvm_get_idmap_vector(void)
  1905. {
  1906. return hyp_idmap_vector;
  1907. }
  1908. static int kvm_map_idmap_text(void)
  1909. {
  1910. unsigned long size = hyp_idmap_end - hyp_idmap_start;
  1911. int err = __create_hyp_mappings(hyp_idmap_start, size, hyp_idmap_start,
  1912. PAGE_HYP_EXEC);
  1913. if (err)
  1914. kvm_err("Failed to idmap %lx-%lx\n",
  1915. hyp_idmap_start, hyp_idmap_end);
  1916. return err;
  1917. }
  1918. static void *kvm_hyp_zalloc_page(void *arg)
  1919. {
  1920. return (void *)get_zeroed_page(GFP_KERNEL);
  1921. }
  1922. static struct kvm_pgtable_mm_ops kvm_hyp_mm_ops = {
  1923. .zalloc_page = kvm_hyp_zalloc_page,
  1924. .get_page = kvm_host_get_page,
  1925. .put_page = kvm_host_put_page,
  1926. .phys_to_virt = kvm_host_va,
  1927. .virt_to_phys = kvm_host_pa,
  1928. };
  1929. int __init kvm_mmu_init(u32 hyp_va_bits)
  1930. {
  1931. int err;
  1932. hyp_idmap_start = __pa_symbol(__hyp_idmap_text_start);
  1933. hyp_idmap_start = ALIGN_DOWN(hyp_idmap_start, PAGE_SIZE);
  1934. hyp_idmap_end = __pa_symbol(__hyp_idmap_text_end);
  1935. hyp_idmap_end = ALIGN(hyp_idmap_end, PAGE_SIZE);
  1936. hyp_idmap_vector = __pa_symbol(__kvm_hyp_init);
  1937. /*
  1938. * We rely on the linker script to ensure at build time that the HYP
  1939. * init code does not cross a page boundary.
  1940. */
  1941. BUG_ON((hyp_idmap_start ^ (hyp_idmap_end - 1)) & PAGE_MASK);
  1942. kvm_debug("Using %u-bit virtual addresses at EL2\n", hyp_va_bits);
  1943. kvm_debug("IDMAP page: %lx\n", hyp_idmap_start);
  1944. kvm_debug("HYP VA range: %lx:%lx\n",
  1945. kern_hyp_va(PAGE_OFFSET),
  1946. kern_hyp_va((unsigned long)high_memory - 1));
  1947. if (hyp_idmap_start >= kern_hyp_va(PAGE_OFFSET) &&
  1948. hyp_idmap_start < kern_hyp_va((unsigned long)high_memory - 1) &&
  1949. hyp_idmap_start != (unsigned long)__hyp_idmap_text_start) {
  1950. /*
  1951. * The idmap page is intersecting with the VA space,
  1952. * it is not safe to continue further.
  1953. */
  1954. kvm_err("IDMAP intersecting with HYP VA, unable to continue\n");
  1955. err = -EINVAL;
  1956. goto out;
  1957. }
  1958. hyp_pgtable = kzalloc_obj(*hyp_pgtable);
  1959. if (!hyp_pgtable) {
  1960. kvm_err("Hyp mode page-table not allocated\n");
  1961. err = -ENOMEM;
  1962. goto out;
  1963. }
  1964. err = kvm_pgtable_hyp_init(hyp_pgtable, hyp_va_bits, &kvm_hyp_mm_ops);
  1965. if (err)
  1966. goto out_free_pgtable;
  1967. err = kvm_map_idmap_text();
  1968. if (err)
  1969. goto out_destroy_pgtable;
  1970. io_map_base = hyp_idmap_start;
  1971. __hyp_va_bits = hyp_va_bits;
  1972. return 0;
  1973. out_destroy_pgtable:
  1974. kvm_pgtable_hyp_destroy(hyp_pgtable);
  1975. out_free_pgtable:
  1976. kfree(hyp_pgtable);
  1977. hyp_pgtable = NULL;
  1978. out:
  1979. return err;
  1980. }
  1981. void kvm_arch_commit_memory_region(struct kvm *kvm,
  1982. struct kvm_memory_slot *old,
  1983. const struct kvm_memory_slot *new,
  1984. enum kvm_mr_change change)
  1985. {
  1986. bool log_dirty_pages = new && new->flags & KVM_MEM_LOG_DIRTY_PAGES;
  1987. /*
  1988. * At this point memslot has been committed and there is an
  1989. * allocated dirty_bitmap[], dirty pages will be tracked while the
  1990. * memory slot is write protected.
  1991. */
  1992. if (log_dirty_pages) {
  1993. if (change == KVM_MR_DELETE)
  1994. return;
  1995. /*
  1996. * Huge and normal pages are write-protected and split
  1997. * on either of these two cases:
  1998. *
  1999. * 1. with initial-all-set: gradually with CLEAR ioctls,
  2000. */
  2001. if (kvm_dirty_log_manual_protect_and_init_set(kvm))
  2002. return;
  2003. /*
  2004. * or
  2005. * 2. without initial-all-set: all in one shot when
  2006. * enabling dirty logging.
  2007. */
  2008. kvm_mmu_wp_memory_region(kvm, new->id);
  2009. kvm_mmu_split_memory_region(kvm, new->id);
  2010. } else {
  2011. /*
  2012. * Free any leftovers from the eager page splitting cache. Do
  2013. * this when deleting, moving, disabling dirty logging, or
  2014. * creating the memslot (a nop). Doing it for deletes makes
  2015. * sure we don't leak memory, and there's no need to keep the
  2016. * cache around for any of the other cases.
  2017. */
  2018. kvm_mmu_free_memory_cache(&kvm->arch.mmu.split_page_cache);
  2019. }
  2020. }
  2021. int kvm_arch_prepare_memory_region(struct kvm *kvm,
  2022. const struct kvm_memory_slot *old,
  2023. struct kvm_memory_slot *new,
  2024. enum kvm_mr_change change)
  2025. {
  2026. hva_t hva, reg_end;
  2027. int ret = 0;
  2028. if (change != KVM_MR_CREATE && change != KVM_MR_MOVE &&
  2029. change != KVM_MR_FLAGS_ONLY)
  2030. return 0;
  2031. /*
  2032. * Prevent userspace from creating a memory region outside of the IPA
  2033. * space addressable by the KVM guest IPA space.
  2034. */
  2035. if ((new->base_gfn + new->npages) > (kvm_phys_size(&kvm->arch.mmu) >> PAGE_SHIFT))
  2036. return -EFAULT;
  2037. /*
  2038. * Only support guest_memfd backed memslots with mappable memory, since
  2039. * there aren't any CoCo VMs that support only private memory on arm64.
  2040. */
  2041. if (kvm_slot_has_gmem(new) && !kvm_memslot_is_gmem_only(new))
  2042. return -EINVAL;
  2043. hva = new->userspace_addr;
  2044. reg_end = hva + (new->npages << PAGE_SHIFT);
  2045. mmap_read_lock(current->mm);
  2046. /*
  2047. * A memory region could potentially cover multiple VMAs, and any holes
  2048. * between them, so iterate over all of them.
  2049. *
  2050. * +--------------------------------------------+
  2051. * +---------------+----------------+ +----------------+
  2052. * | : VMA 1 | VMA 2 | | VMA 3 : |
  2053. * +---------------+----------------+ +----------------+
  2054. * | memory region |
  2055. * +--------------------------------------------+
  2056. */
  2057. do {
  2058. struct vm_area_struct *vma;
  2059. vma = find_vma_intersection(current->mm, hva, reg_end);
  2060. if (!vma)
  2061. break;
  2062. if (kvm_has_mte(kvm) && !kvm_vma_mte_allowed(vma)) {
  2063. ret = -EINVAL;
  2064. break;
  2065. }
  2066. if (vma->vm_flags & VM_PFNMAP) {
  2067. /* IO region dirty page logging not allowed */
  2068. if (new->flags & KVM_MEM_LOG_DIRTY_PAGES) {
  2069. ret = -EINVAL;
  2070. break;
  2071. }
  2072. /*
  2073. * Cacheable PFNMAP is allowed only if the hardware
  2074. * supports it.
  2075. */
  2076. if (kvm_vma_is_cacheable(vma) && !kvm_supports_cacheable_pfnmap()) {
  2077. ret = -EINVAL;
  2078. break;
  2079. }
  2080. }
  2081. hva = min(reg_end, vma->vm_end);
  2082. } while (hva < reg_end);
  2083. mmap_read_unlock(current->mm);
  2084. return ret;
  2085. }
  2086. void kvm_arch_free_memslot(struct kvm *kvm, struct kvm_memory_slot *slot)
  2087. {
  2088. }
  2089. void kvm_arch_memslots_updated(struct kvm *kvm, u64 gen)
  2090. {
  2091. }
  2092. void kvm_arch_flush_shadow_memslot(struct kvm *kvm,
  2093. struct kvm_memory_slot *slot)
  2094. {
  2095. gpa_t gpa = slot->base_gfn << PAGE_SHIFT;
  2096. phys_addr_t size = slot->npages << PAGE_SHIFT;
  2097. write_lock(&kvm->mmu_lock);
  2098. kvm_stage2_unmap_range(&kvm->arch.mmu, gpa, size, true);
  2099. kvm_nested_s2_unmap(kvm, true);
  2100. write_unlock(&kvm->mmu_lock);
  2101. }
  2102. /*
  2103. * See note at ARMv7 ARM B1.14.4 (TL;DR: S/W ops are not easily virtualized).
  2104. *
  2105. * Main problems:
  2106. * - S/W ops are local to a CPU (not broadcast)
  2107. * - We have line migration behind our back (speculation)
  2108. * - System caches don't support S/W at all (damn!)
  2109. *
  2110. * In the face of the above, the best we can do is to try and convert
  2111. * S/W ops to VA ops. Because the guest is not allowed to infer the
  2112. * S/W to PA mapping, it can only use S/W to nuke the whole cache,
  2113. * which is a rather good thing for us.
  2114. *
  2115. * Also, it is only used when turning caches on/off ("The expected
  2116. * usage of the cache maintenance instructions that operate by set/way
  2117. * is associated with the cache maintenance instructions associated
  2118. * with the powerdown and powerup of caches, if this is required by
  2119. * the implementation.").
  2120. *
  2121. * We use the following policy:
  2122. *
  2123. * - If we trap a S/W operation, we enable VM trapping to detect
  2124. * caches being turned on/off, and do a full clean.
  2125. *
  2126. * - We flush the caches on both caches being turned on and off.
  2127. *
  2128. * - Once the caches are enabled, we stop trapping VM ops.
  2129. */
  2130. void kvm_set_way_flush(struct kvm_vcpu *vcpu)
  2131. {
  2132. unsigned long hcr = *vcpu_hcr(vcpu);
  2133. /*
  2134. * If this is the first time we do a S/W operation
  2135. * (i.e. HCR_TVM not set) flush the whole memory, and set the
  2136. * VM trapping.
  2137. *
  2138. * Otherwise, rely on the VM trapping to wait for the MMU +
  2139. * Caches to be turned off. At that point, we'll be able to
  2140. * clean the caches again.
  2141. */
  2142. if (!(hcr & HCR_TVM)) {
  2143. trace_kvm_set_way_flush(*vcpu_pc(vcpu),
  2144. vcpu_has_cache_enabled(vcpu));
  2145. stage2_flush_vm(vcpu->kvm);
  2146. *vcpu_hcr(vcpu) = hcr | HCR_TVM;
  2147. }
  2148. }
  2149. void kvm_toggle_cache(struct kvm_vcpu *vcpu, bool was_enabled)
  2150. {
  2151. bool now_enabled = vcpu_has_cache_enabled(vcpu);
  2152. /*
  2153. * If switching the MMU+caches on, need to invalidate the caches.
  2154. * If switching it off, need to clean the caches.
  2155. * Clean + invalidate does the trick always.
  2156. */
  2157. if (now_enabled != was_enabled)
  2158. stage2_flush_vm(vcpu->kvm);
  2159. /* Caches are now on, stop trapping VM ops (until a S/W op) */
  2160. if (now_enabled)
  2161. *vcpu_hcr(vcpu) &= ~HCR_TVM;
  2162. trace_kvm_toggle_cache(*vcpu_pc(vcpu), was_enabled, now_enabled);
  2163. }