main.c 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* Copyright(c) 2016-20 Intel Corporation. */
  3. #include <linux/file.h>
  4. #include <linux/freezer.h>
  5. #include <linux/highmem.h>
  6. #include <linux/kthread.h>
  7. #include <linux/miscdevice.h>
  8. #include <linux/node.h>
  9. #include <linux/pagemap.h>
  10. #include <linux/ratelimit.h>
  11. #include <linux/sched/mm.h>
  12. #include <linux/sched/signal.h>
  13. #include <linux/slab.h>
  14. #include <linux/sysfs.h>
  15. #include <linux/vmalloc.h>
  16. #include <asm/sgx.h>
  17. #include "driver.h"
  18. #include "encl.h"
  19. #include "encls.h"
  20. struct sgx_epc_section sgx_epc_sections[SGX_MAX_EPC_SECTIONS];
  21. static int sgx_nr_epc_sections;
  22. static struct task_struct *ksgxd_tsk;
  23. static DECLARE_WAIT_QUEUE_HEAD(ksgxd_waitq);
  24. static DEFINE_XARRAY(sgx_epc_address_space);
  25. /*
  26. * These variables are part of the state of the reclaimer, and must be accessed
  27. * with sgx_reclaimer_lock acquired.
  28. */
  29. static LIST_HEAD(sgx_active_page_list);
  30. static DEFINE_SPINLOCK(sgx_reclaimer_lock);
  31. static atomic_long_t sgx_nr_free_pages = ATOMIC_LONG_INIT(0);
  32. /* Nodes with one or more EPC sections. */
  33. static nodemask_t sgx_numa_mask;
  34. /*
  35. * Array with one list_head for each possible NUMA node. Each
  36. * list contains all the sgx_epc_section's which are on that
  37. * node.
  38. */
  39. static struct sgx_numa_node *sgx_numa_nodes;
  40. static LIST_HEAD(sgx_dirty_page_list);
  41. /*
  42. * Reset post-kexec EPC pages to the uninitialized state. The pages are removed
  43. * from the input list, and made available for the page allocator. SECS pages
  44. * prepending their children in the input list are left intact.
  45. *
  46. * Return 0 when sanitization was successful or kthread was stopped, and the
  47. * number of unsanitized pages otherwise.
  48. */
  49. static unsigned long __sgx_sanitize_pages(struct list_head *dirty_page_list)
  50. {
  51. unsigned long left_dirty = 0;
  52. struct sgx_epc_page *page;
  53. LIST_HEAD(dirty);
  54. int ret;
  55. /* dirty_page_list is thread-local, no need for a lock: */
  56. while (!list_empty(dirty_page_list)) {
  57. if (kthread_should_stop())
  58. return 0;
  59. page = list_first_entry(dirty_page_list, struct sgx_epc_page, list);
  60. /*
  61. * Checking page->poison without holding the node->lock
  62. * is racy, but losing the race (i.e. poison is set just
  63. * after the check) just means __eremove() will be uselessly
  64. * called for a page that sgx_free_epc_page() will put onto
  65. * the node->sgx_poison_page_list later.
  66. */
  67. if (page->poison) {
  68. struct sgx_epc_section *section = &sgx_epc_sections[page->section];
  69. struct sgx_numa_node *node = section->node;
  70. spin_lock(&node->lock);
  71. list_move(&page->list, &node->sgx_poison_page_list);
  72. spin_unlock(&node->lock);
  73. continue;
  74. }
  75. ret = __eremove(sgx_get_epc_virt_addr(page));
  76. if (!ret) {
  77. /*
  78. * page is now sanitized. Make it available via the SGX
  79. * page allocator:
  80. */
  81. list_del(&page->list);
  82. sgx_free_epc_page(page);
  83. } else {
  84. /* The page is not yet clean - move to the dirty list. */
  85. list_move_tail(&page->list, &dirty);
  86. left_dirty++;
  87. }
  88. cond_resched();
  89. }
  90. list_splice(&dirty, dirty_page_list);
  91. return left_dirty;
  92. }
  93. static bool sgx_reclaimer_age(struct sgx_epc_page *epc_page)
  94. {
  95. struct sgx_encl_page *page = epc_page->owner;
  96. struct sgx_encl *encl = page->encl;
  97. struct sgx_encl_mm *encl_mm;
  98. bool ret = true;
  99. int idx;
  100. idx = srcu_read_lock(&encl->srcu);
  101. list_for_each_entry_rcu(encl_mm, &encl->mm_list, list) {
  102. if (!mmget_not_zero(encl_mm->mm))
  103. continue;
  104. mmap_read_lock(encl_mm->mm);
  105. ret = !sgx_encl_test_and_clear_young(encl_mm->mm, page);
  106. mmap_read_unlock(encl_mm->mm);
  107. mmput_async(encl_mm->mm);
  108. if (!ret)
  109. break;
  110. }
  111. srcu_read_unlock(&encl->srcu, idx);
  112. if (!ret)
  113. return false;
  114. return true;
  115. }
  116. static void sgx_reclaimer_block(struct sgx_epc_page *epc_page)
  117. {
  118. struct sgx_encl_page *page = epc_page->owner;
  119. unsigned long addr = page->desc & PAGE_MASK;
  120. struct sgx_encl *encl = page->encl;
  121. int ret;
  122. sgx_zap_enclave_ptes(encl, addr);
  123. mutex_lock(&encl->lock);
  124. ret = __eblock(sgx_get_epc_virt_addr(epc_page));
  125. if (encls_failed(ret))
  126. ENCLS_WARN(ret, "EBLOCK");
  127. mutex_unlock(&encl->lock);
  128. }
  129. static int __sgx_encl_ewb(struct sgx_epc_page *epc_page, void *va_slot,
  130. struct sgx_backing *backing)
  131. {
  132. struct sgx_pageinfo pginfo;
  133. int ret;
  134. pginfo.addr = 0;
  135. pginfo.secs = 0;
  136. pginfo.contents = (unsigned long)kmap_local_page(backing->contents);
  137. pginfo.metadata = (unsigned long)kmap_local_page(backing->pcmd) +
  138. backing->pcmd_offset;
  139. ret = __ewb(&pginfo, sgx_get_epc_virt_addr(epc_page), va_slot);
  140. set_page_dirty(backing->pcmd);
  141. set_page_dirty(backing->contents);
  142. kunmap_local((void *)(unsigned long)(pginfo.metadata -
  143. backing->pcmd_offset));
  144. kunmap_local((void *)(unsigned long)pginfo.contents);
  145. return ret;
  146. }
  147. void sgx_ipi_cb(void *info)
  148. {
  149. }
  150. /*
  151. * Swap page to the regular memory transformed to the blocked state by using
  152. * EBLOCK, which means that it can no longer be referenced (no new TLB entries).
  153. *
  154. * The first trial just tries to write the page assuming that some other thread
  155. * has reset the count for threads inside the enclave by using ETRACK, and
  156. * previous thread count has been zeroed out. The second trial calls ETRACK
  157. * before EWB. If that fails we kick all the HW threads out, and then do EWB,
  158. * which should be guaranteed the succeed.
  159. */
  160. static void sgx_encl_ewb(struct sgx_epc_page *epc_page,
  161. struct sgx_backing *backing)
  162. {
  163. struct sgx_encl_page *encl_page = epc_page->owner;
  164. struct sgx_encl *encl = encl_page->encl;
  165. struct sgx_va_page *va_page;
  166. unsigned int va_offset;
  167. void *va_slot;
  168. int ret;
  169. encl_page->desc &= ~SGX_ENCL_PAGE_BEING_RECLAIMED;
  170. va_page = list_first_entry(&encl->va_pages, struct sgx_va_page,
  171. list);
  172. va_offset = sgx_alloc_va_slot(va_page);
  173. va_slot = sgx_get_epc_virt_addr(va_page->epc_page) + va_offset;
  174. if (sgx_va_page_full(va_page))
  175. list_move_tail(&va_page->list, &encl->va_pages);
  176. ret = __sgx_encl_ewb(epc_page, va_slot, backing);
  177. if (ret == SGX_NOT_TRACKED) {
  178. ret = __etrack(sgx_get_epc_virt_addr(encl->secs.epc_page));
  179. if (ret) {
  180. if (encls_failed(ret))
  181. ENCLS_WARN(ret, "ETRACK");
  182. }
  183. ret = __sgx_encl_ewb(epc_page, va_slot, backing);
  184. if (ret == SGX_NOT_TRACKED) {
  185. /*
  186. * Slow path, send IPIs to kick cpus out of the
  187. * enclave. Note, it's imperative that the cpu
  188. * mask is generated *after* ETRACK, else we'll
  189. * miss cpus that entered the enclave between
  190. * generating the mask and incrementing epoch.
  191. */
  192. on_each_cpu_mask(sgx_encl_cpumask(encl),
  193. sgx_ipi_cb, NULL, 1);
  194. ret = __sgx_encl_ewb(epc_page, va_slot, backing);
  195. }
  196. }
  197. if (ret) {
  198. if (encls_failed(ret))
  199. ENCLS_WARN(ret, "EWB");
  200. sgx_free_va_slot(va_page, va_offset);
  201. } else {
  202. encl_page->desc |= va_offset;
  203. encl_page->va_page = va_page;
  204. }
  205. }
  206. static void sgx_reclaimer_write(struct sgx_epc_page *epc_page,
  207. struct sgx_backing *backing)
  208. {
  209. struct sgx_encl_page *encl_page = epc_page->owner;
  210. struct sgx_encl *encl = encl_page->encl;
  211. struct sgx_backing secs_backing;
  212. int ret;
  213. mutex_lock(&encl->lock);
  214. sgx_encl_ewb(epc_page, backing);
  215. encl_page->epc_page = NULL;
  216. encl->secs_child_cnt--;
  217. sgx_encl_put_backing(backing);
  218. if (!encl->secs_child_cnt && test_bit(SGX_ENCL_INITIALIZED, &encl->flags)) {
  219. ret = sgx_encl_alloc_backing(encl, PFN_DOWN(encl->size),
  220. &secs_backing);
  221. if (ret)
  222. goto out;
  223. sgx_encl_ewb(encl->secs.epc_page, &secs_backing);
  224. sgx_encl_free_epc_page(encl->secs.epc_page);
  225. encl->secs.epc_page = NULL;
  226. sgx_encl_put_backing(&secs_backing);
  227. }
  228. out:
  229. mutex_unlock(&encl->lock);
  230. }
  231. /*
  232. * Take a fixed number of pages from the head of the active page pool and
  233. * reclaim them to the enclave's private shmem files. Skip the pages, which have
  234. * been accessed since the last scan. Move those pages to the tail of active
  235. * page pool so that the pages get scanned in LRU like fashion.
  236. *
  237. * Batch process a chunk of pages (at the moment 16) in order to degrade amount
  238. * of IPI's and ETRACK's potentially required. sgx_encl_ewb() does degrade a bit
  239. * among the HW threads with three stage EWB pipeline (EWB, ETRACK + EWB and IPI
  240. * + EWB) but not sufficiently. Reclaiming one page at a time would also be
  241. * problematic as it would increase the lock contention too much, which would
  242. * halt forward progress.
  243. */
  244. static void sgx_reclaim_pages(void)
  245. {
  246. struct sgx_epc_page *chunk[SGX_NR_TO_SCAN];
  247. struct sgx_backing backing[SGX_NR_TO_SCAN];
  248. struct sgx_encl_page *encl_page;
  249. struct sgx_epc_page *epc_page;
  250. pgoff_t page_index;
  251. int cnt = 0;
  252. int ret;
  253. int i;
  254. spin_lock(&sgx_reclaimer_lock);
  255. for (i = 0; i < SGX_NR_TO_SCAN; i++) {
  256. if (list_empty(&sgx_active_page_list))
  257. break;
  258. epc_page = list_first_entry(&sgx_active_page_list,
  259. struct sgx_epc_page, list);
  260. list_del_init(&epc_page->list);
  261. encl_page = epc_page->owner;
  262. if (kref_get_unless_zero(&encl_page->encl->refcount) != 0)
  263. chunk[cnt++] = epc_page;
  264. else
  265. /* The owner is freeing the page. No need to add the
  266. * page back to the list of reclaimable pages.
  267. */
  268. epc_page->flags &= ~SGX_EPC_PAGE_RECLAIMER_TRACKED;
  269. }
  270. spin_unlock(&sgx_reclaimer_lock);
  271. for (i = 0; i < cnt; i++) {
  272. epc_page = chunk[i];
  273. encl_page = epc_page->owner;
  274. if (!sgx_reclaimer_age(epc_page))
  275. goto skip;
  276. page_index = PFN_DOWN(encl_page->desc - encl_page->encl->base);
  277. mutex_lock(&encl_page->encl->lock);
  278. ret = sgx_encl_alloc_backing(encl_page->encl, page_index, &backing[i]);
  279. if (ret) {
  280. mutex_unlock(&encl_page->encl->lock);
  281. goto skip;
  282. }
  283. encl_page->desc |= SGX_ENCL_PAGE_BEING_RECLAIMED;
  284. mutex_unlock(&encl_page->encl->lock);
  285. continue;
  286. skip:
  287. spin_lock(&sgx_reclaimer_lock);
  288. list_add_tail(&epc_page->list, &sgx_active_page_list);
  289. spin_unlock(&sgx_reclaimer_lock);
  290. kref_put(&encl_page->encl->refcount, sgx_encl_release);
  291. chunk[i] = NULL;
  292. }
  293. for (i = 0; i < cnt; i++) {
  294. epc_page = chunk[i];
  295. if (epc_page)
  296. sgx_reclaimer_block(epc_page);
  297. }
  298. for (i = 0; i < cnt; i++) {
  299. epc_page = chunk[i];
  300. if (!epc_page)
  301. continue;
  302. encl_page = epc_page->owner;
  303. sgx_reclaimer_write(epc_page, &backing[i]);
  304. kref_put(&encl_page->encl->refcount, sgx_encl_release);
  305. epc_page->flags &= ~SGX_EPC_PAGE_RECLAIMER_TRACKED;
  306. sgx_free_epc_page(epc_page);
  307. }
  308. }
  309. static bool sgx_should_reclaim(unsigned long watermark)
  310. {
  311. return atomic_long_read(&sgx_nr_free_pages) < watermark &&
  312. !list_empty(&sgx_active_page_list);
  313. }
  314. /*
  315. * sgx_reclaim_direct() should be called (without enclave's mutex held)
  316. * in locations where SGX memory resources might be low and might be
  317. * needed in order to make forward progress.
  318. */
  319. void sgx_reclaim_direct(void)
  320. {
  321. if (sgx_should_reclaim(SGX_NR_LOW_PAGES))
  322. sgx_reclaim_pages();
  323. }
  324. static int ksgxd(void *p)
  325. {
  326. set_freezable();
  327. /*
  328. * Sanitize pages in order to recover from kexec(). The 2nd pass is
  329. * required for SECS pages, whose child pages blocked EREMOVE.
  330. */
  331. __sgx_sanitize_pages(&sgx_dirty_page_list);
  332. WARN_ON(__sgx_sanitize_pages(&sgx_dirty_page_list));
  333. while (!kthread_should_stop()) {
  334. if (try_to_freeze())
  335. continue;
  336. wait_event_freezable(ksgxd_waitq,
  337. kthread_should_stop() ||
  338. sgx_should_reclaim(SGX_NR_HIGH_PAGES));
  339. if (sgx_should_reclaim(SGX_NR_HIGH_PAGES))
  340. sgx_reclaim_pages();
  341. cond_resched();
  342. }
  343. return 0;
  344. }
  345. static bool __init sgx_page_reclaimer_init(void)
  346. {
  347. struct task_struct *tsk;
  348. tsk = kthread_run(ksgxd, NULL, "ksgxd");
  349. if (IS_ERR(tsk))
  350. return false;
  351. ksgxd_tsk = tsk;
  352. return true;
  353. }
  354. bool current_is_ksgxd(void)
  355. {
  356. return current == ksgxd_tsk;
  357. }
  358. static struct sgx_epc_page *__sgx_alloc_epc_page_from_node(int nid)
  359. {
  360. struct sgx_numa_node *node = &sgx_numa_nodes[nid];
  361. struct sgx_epc_page *page = NULL;
  362. spin_lock(&node->lock);
  363. if (list_empty(&node->free_page_list)) {
  364. spin_unlock(&node->lock);
  365. return NULL;
  366. }
  367. page = list_first_entry(&node->free_page_list, struct sgx_epc_page, list);
  368. list_del_init(&page->list);
  369. page->flags = 0;
  370. spin_unlock(&node->lock);
  371. atomic_long_dec(&sgx_nr_free_pages);
  372. return page;
  373. }
  374. /**
  375. * __sgx_alloc_epc_page() - Allocate an EPC page
  376. *
  377. * Iterate through NUMA nodes and reserve ia free EPC page to the caller. Start
  378. * from the NUMA node, where the caller is executing.
  379. *
  380. * Return:
  381. * - an EPC page: A borrowed EPC pages were available.
  382. * - NULL: Out of EPC pages.
  383. */
  384. struct sgx_epc_page *__sgx_alloc_epc_page(void)
  385. {
  386. struct sgx_epc_page *page;
  387. int nid_of_current = numa_node_id();
  388. int nid_start, nid;
  389. /*
  390. * Try local node first. If it doesn't have an EPC section,
  391. * fall back to the non-local NUMA nodes.
  392. */
  393. if (node_isset(nid_of_current, sgx_numa_mask))
  394. nid_start = nid_of_current;
  395. else
  396. nid_start = next_node_in(nid_of_current, sgx_numa_mask);
  397. nid = nid_start;
  398. do {
  399. page = __sgx_alloc_epc_page_from_node(nid);
  400. if (page)
  401. return page;
  402. nid = next_node_in(nid, sgx_numa_mask);
  403. } while (nid != nid_start);
  404. return ERR_PTR(-ENOMEM);
  405. }
  406. /**
  407. * sgx_mark_page_reclaimable() - Mark a page as reclaimable
  408. * @page: EPC page
  409. *
  410. * Mark a page as reclaimable and add it to the active page list. Pages
  411. * are automatically removed from the active list when freed.
  412. */
  413. void sgx_mark_page_reclaimable(struct sgx_epc_page *page)
  414. {
  415. spin_lock(&sgx_reclaimer_lock);
  416. page->flags |= SGX_EPC_PAGE_RECLAIMER_TRACKED;
  417. list_add_tail(&page->list, &sgx_active_page_list);
  418. spin_unlock(&sgx_reclaimer_lock);
  419. }
  420. /**
  421. * sgx_unmark_page_reclaimable() - Remove a page from the reclaim list
  422. * @page: EPC page
  423. *
  424. * Clear the reclaimable flag and remove the page from the active page list.
  425. *
  426. * Return:
  427. * 0 on success,
  428. * -EBUSY if the page is in the process of being reclaimed
  429. */
  430. int sgx_unmark_page_reclaimable(struct sgx_epc_page *page)
  431. {
  432. spin_lock(&sgx_reclaimer_lock);
  433. if (page->flags & SGX_EPC_PAGE_RECLAIMER_TRACKED) {
  434. /* The page is being reclaimed. */
  435. if (list_empty(&page->list)) {
  436. spin_unlock(&sgx_reclaimer_lock);
  437. return -EBUSY;
  438. }
  439. list_del(&page->list);
  440. page->flags &= ~SGX_EPC_PAGE_RECLAIMER_TRACKED;
  441. }
  442. spin_unlock(&sgx_reclaimer_lock);
  443. return 0;
  444. }
  445. /**
  446. * sgx_alloc_epc_page() - Allocate an EPC page
  447. * @owner: the owner of the EPC page
  448. * @reclaim: reclaim pages if necessary
  449. *
  450. * Iterate through EPC sections and borrow a free EPC page to the caller. When a
  451. * page is no longer needed it must be released with sgx_free_epc_page(). If
  452. * @reclaim is set to true, directly reclaim pages when we are out of pages. No
  453. * mm's can be locked when @reclaim is set to true.
  454. *
  455. * Finally, wake up ksgxd when the number of pages goes below the watermark
  456. * before returning back to the caller.
  457. *
  458. * Return:
  459. * an EPC page,
  460. * -errno on error
  461. */
  462. struct sgx_epc_page *sgx_alloc_epc_page(void *owner, bool reclaim)
  463. {
  464. struct sgx_epc_page *page;
  465. for ( ; ; ) {
  466. page = __sgx_alloc_epc_page();
  467. if (!IS_ERR(page)) {
  468. page->owner = owner;
  469. break;
  470. }
  471. if (list_empty(&sgx_active_page_list))
  472. return ERR_PTR(-ENOMEM);
  473. if (!reclaim) {
  474. page = ERR_PTR(-EBUSY);
  475. break;
  476. }
  477. if (signal_pending(current)) {
  478. page = ERR_PTR(-ERESTARTSYS);
  479. break;
  480. }
  481. sgx_reclaim_pages();
  482. cond_resched();
  483. }
  484. if (sgx_should_reclaim(SGX_NR_LOW_PAGES))
  485. wake_up(&ksgxd_waitq);
  486. return page;
  487. }
  488. /**
  489. * sgx_free_epc_page() - Free an EPC page
  490. * @page: an EPC page
  491. *
  492. * Put the EPC page back to the list of free pages. It's the caller's
  493. * responsibility to make sure that the page is in uninitialized state. In other
  494. * words, do EREMOVE, EWB or whatever operation is necessary before calling
  495. * this function.
  496. */
  497. void sgx_free_epc_page(struct sgx_epc_page *page)
  498. {
  499. struct sgx_epc_section *section = &sgx_epc_sections[page->section];
  500. struct sgx_numa_node *node = section->node;
  501. spin_lock(&node->lock);
  502. page->owner = NULL;
  503. if (page->poison)
  504. list_add(&page->list, &node->sgx_poison_page_list);
  505. else
  506. list_add_tail(&page->list, &node->free_page_list);
  507. page->flags = SGX_EPC_PAGE_IS_FREE;
  508. spin_unlock(&node->lock);
  509. atomic_long_inc(&sgx_nr_free_pages);
  510. }
  511. static bool __init sgx_setup_epc_section(u64 phys_addr, u64 size,
  512. unsigned long index,
  513. struct sgx_epc_section *section)
  514. {
  515. unsigned long nr_pages = size >> PAGE_SHIFT;
  516. unsigned long i;
  517. section->virt_addr = memremap(phys_addr, size, MEMREMAP_WB);
  518. if (!section->virt_addr)
  519. return false;
  520. section->pages = vmalloc(nr_pages * sizeof(struct sgx_epc_page));
  521. if (!section->pages) {
  522. memunmap(section->virt_addr);
  523. return false;
  524. }
  525. section->phys_addr = phys_addr;
  526. xa_store_range(&sgx_epc_address_space, section->phys_addr,
  527. phys_addr + size - 1, section, GFP_KERNEL);
  528. for (i = 0; i < nr_pages; i++) {
  529. section->pages[i].section = index;
  530. section->pages[i].flags = 0;
  531. section->pages[i].owner = NULL;
  532. section->pages[i].poison = 0;
  533. list_add_tail(&section->pages[i].list, &sgx_dirty_page_list);
  534. }
  535. return true;
  536. }
  537. bool arch_is_platform_page(u64 paddr)
  538. {
  539. return !!xa_load(&sgx_epc_address_space, paddr);
  540. }
  541. EXPORT_SYMBOL_GPL(arch_is_platform_page);
  542. static struct sgx_epc_page *sgx_paddr_to_page(u64 paddr)
  543. {
  544. struct sgx_epc_section *section;
  545. section = xa_load(&sgx_epc_address_space, paddr);
  546. if (!section)
  547. return NULL;
  548. return &section->pages[PFN_DOWN(paddr - section->phys_addr)];
  549. }
  550. /*
  551. * Called in process context to handle a hardware reported
  552. * error in an SGX EPC page.
  553. * If the MF_ACTION_REQUIRED bit is set in flags, then the
  554. * context is the task that consumed the poison data. Otherwise
  555. * this is called from a kernel thread unrelated to the page.
  556. */
  557. int arch_memory_failure(unsigned long pfn, int flags)
  558. {
  559. struct sgx_epc_page *page = sgx_paddr_to_page(pfn << PAGE_SHIFT);
  560. struct sgx_epc_section *section;
  561. struct sgx_numa_node *node;
  562. /*
  563. * mm/memory-failure.c calls this routine for all errors
  564. * where there isn't a "struct page" for the address. But that
  565. * includes other address ranges besides SGX.
  566. */
  567. if (!page)
  568. return -ENXIO;
  569. /*
  570. * If poison was consumed synchronously. Send a SIGBUS to
  571. * the task. Hardware has already exited the SGX enclave and
  572. * will not allow re-entry to an enclave that has a memory
  573. * error. The signal may help the task understand why the
  574. * enclave is broken.
  575. */
  576. if (flags & MF_ACTION_REQUIRED)
  577. force_sig(SIGBUS);
  578. section = &sgx_epc_sections[page->section];
  579. node = section->node;
  580. spin_lock(&node->lock);
  581. /* Already poisoned? Nothing more to do */
  582. if (page->poison)
  583. goto out;
  584. page->poison = 1;
  585. /*
  586. * If the page is on a free list, move it to the per-node
  587. * poison page list.
  588. */
  589. if (page->flags & SGX_EPC_PAGE_IS_FREE) {
  590. list_move(&page->list, &node->sgx_poison_page_list);
  591. goto out;
  592. }
  593. sgx_unmark_page_reclaimable(page);
  594. /*
  595. * TBD: Add additional plumbing to enable pre-emptive
  596. * action for asynchronous poison notification. Until
  597. * then just hope that the poison:
  598. * a) is not accessed - sgx_free_epc_page() will deal with it
  599. * when the user gives it back
  600. * b) results in a recoverable machine check rather than
  601. * a fatal one
  602. */
  603. out:
  604. spin_unlock(&node->lock);
  605. return 0;
  606. }
  607. /*
  608. * A section metric is concatenated in a way that @low bits 12-31 define the
  609. * bits 12-31 of the metric and @high bits 0-19 define the bits 32-51 of the
  610. * metric.
  611. */
  612. static inline u64 __init sgx_calc_section_metric(u64 low, u64 high)
  613. {
  614. return (low & GENMASK_ULL(31, 12)) +
  615. ((high & GENMASK_ULL(19, 0)) << 32);
  616. }
  617. #ifdef CONFIG_NUMA
  618. static ssize_t sgx_total_bytes_show(struct device *dev, struct device_attribute *attr, char *buf)
  619. {
  620. return sysfs_emit(buf, "%lu\n", sgx_numa_nodes[dev->id].size);
  621. }
  622. static DEVICE_ATTR_RO(sgx_total_bytes);
  623. static umode_t arch_node_attr_is_visible(struct kobject *kobj,
  624. struct attribute *attr, int idx)
  625. {
  626. /* Make all x86/ attributes invisible when SGX is not initialized: */
  627. if (nodes_empty(sgx_numa_mask))
  628. return 0;
  629. return attr->mode;
  630. }
  631. static struct attribute *arch_node_dev_attrs[] = {
  632. &dev_attr_sgx_total_bytes.attr,
  633. NULL,
  634. };
  635. const struct attribute_group arch_node_dev_group = {
  636. .name = "x86",
  637. .attrs = arch_node_dev_attrs,
  638. .is_visible = arch_node_attr_is_visible,
  639. };
  640. static void __init arch_update_sysfs_visibility(int nid)
  641. {
  642. struct node *node = node_devices[nid];
  643. int ret;
  644. ret = sysfs_update_group(&node->dev.kobj, &arch_node_dev_group);
  645. if (ret)
  646. pr_err("sysfs update failed (%d), files may be invisible", ret);
  647. }
  648. #else /* !CONFIG_NUMA */
  649. static void __init arch_update_sysfs_visibility(int nid) {}
  650. #endif
  651. static bool __init sgx_page_cache_init(void)
  652. {
  653. u32 eax, ebx, ecx, edx, type;
  654. u64 pa, size;
  655. int nid;
  656. int i;
  657. sgx_numa_nodes = kmalloc_array(num_possible_nodes(), sizeof(*sgx_numa_nodes), GFP_KERNEL);
  658. if (!sgx_numa_nodes)
  659. return false;
  660. for (i = 0; i < ARRAY_SIZE(sgx_epc_sections); i++) {
  661. cpuid_count(SGX_CPUID, i + SGX_CPUID_EPC, &eax, &ebx, &ecx, &edx);
  662. type = eax & SGX_CPUID_EPC_MASK;
  663. if (type == SGX_CPUID_EPC_INVALID)
  664. break;
  665. if (type != SGX_CPUID_EPC_SECTION) {
  666. pr_err_once("Unknown EPC section type: %u\n", type);
  667. break;
  668. }
  669. pa = sgx_calc_section_metric(eax, ebx);
  670. size = sgx_calc_section_metric(ecx, edx);
  671. pr_info("EPC section 0x%llx-0x%llx\n", pa, pa + size - 1);
  672. if (!sgx_setup_epc_section(pa, size, i, &sgx_epc_sections[i])) {
  673. pr_err("No free memory for an EPC section\n");
  674. break;
  675. }
  676. nid = numa_map_to_online_node(phys_to_target_node(pa));
  677. if (nid == NUMA_NO_NODE) {
  678. /* The physical address is already printed above. */
  679. pr_warn(FW_BUG "Unable to map EPC section to online node. Fallback to the NUMA node 0.\n");
  680. nid = 0;
  681. }
  682. if (!node_isset(nid, sgx_numa_mask)) {
  683. spin_lock_init(&sgx_numa_nodes[nid].lock);
  684. INIT_LIST_HEAD(&sgx_numa_nodes[nid].free_page_list);
  685. INIT_LIST_HEAD(&sgx_numa_nodes[nid].sgx_poison_page_list);
  686. node_set(nid, sgx_numa_mask);
  687. sgx_numa_nodes[nid].size = 0;
  688. /* Make SGX-specific node sysfs files visible: */
  689. arch_update_sysfs_visibility(nid);
  690. }
  691. sgx_epc_sections[i].node = &sgx_numa_nodes[nid];
  692. sgx_numa_nodes[nid].size += size;
  693. sgx_nr_epc_sections++;
  694. }
  695. if (!sgx_nr_epc_sections) {
  696. pr_err("There are zero EPC sections.\n");
  697. return false;
  698. }
  699. for_each_online_node(nid) {
  700. if (!node_isset(nid, sgx_numa_mask) &&
  701. node_state(nid, N_MEMORY) && node_state(nid, N_CPU))
  702. pr_info("node%d has both CPUs and memory but doesn't have an EPC section\n",
  703. nid);
  704. }
  705. return true;
  706. }
  707. /*
  708. * Update the SGX_LEPUBKEYHASH MSRs to the values specified by caller.
  709. * Bare-metal driver requires to update them to hash of enclave's signer
  710. * before EINIT. KVM needs to update them to guest's virtual MSR values
  711. * before doing EINIT from guest.
  712. */
  713. void sgx_update_lepubkeyhash(u64 *lepubkeyhash)
  714. {
  715. int i;
  716. WARN_ON_ONCE(preemptible());
  717. for (i = 0; i < 4; i++)
  718. wrmsrl(MSR_IA32_SGXLEPUBKEYHASH0 + i, lepubkeyhash[i]);
  719. }
  720. const struct file_operations sgx_provision_fops = {
  721. .owner = THIS_MODULE,
  722. };
  723. static struct miscdevice sgx_dev_provision = {
  724. .minor = MISC_DYNAMIC_MINOR,
  725. .name = "sgx_provision",
  726. .nodename = "sgx_provision",
  727. .fops = &sgx_provision_fops,
  728. };
  729. /**
  730. * sgx_set_attribute() - Update allowed attributes given file descriptor
  731. * @allowed_attributes: Pointer to allowed enclave attributes
  732. * @attribute_fd: File descriptor for specific attribute
  733. *
  734. * Append enclave attribute indicated by file descriptor to allowed
  735. * attributes. Currently only SGX_ATTR_PROVISIONKEY indicated by
  736. * /dev/sgx_provision is supported.
  737. *
  738. * Return:
  739. * -0: SGX_ATTR_PROVISIONKEY is appended to allowed_attributes
  740. * -EINVAL: Invalid, or not supported file descriptor
  741. */
  742. int sgx_set_attribute(unsigned long *allowed_attributes,
  743. unsigned int attribute_fd)
  744. {
  745. struct fd f = fdget(attribute_fd);
  746. if (!fd_file(f))
  747. return -EINVAL;
  748. if (fd_file(f)->f_op != &sgx_provision_fops) {
  749. fdput(f);
  750. return -EINVAL;
  751. }
  752. *allowed_attributes |= SGX_ATTR_PROVISIONKEY;
  753. fdput(f);
  754. return 0;
  755. }
  756. EXPORT_SYMBOL_GPL(sgx_set_attribute);
  757. static int __init sgx_init(void)
  758. {
  759. int ret;
  760. int i;
  761. if (!cpu_feature_enabled(X86_FEATURE_SGX))
  762. return -ENODEV;
  763. if (!sgx_page_cache_init())
  764. return -ENOMEM;
  765. if (!sgx_page_reclaimer_init()) {
  766. ret = -ENOMEM;
  767. goto err_page_cache;
  768. }
  769. ret = misc_register(&sgx_dev_provision);
  770. if (ret)
  771. goto err_kthread;
  772. /*
  773. * Always try to initialize the native *and* KVM drivers.
  774. * The KVM driver is less picky than the native one and
  775. * can function if the native one is not supported on the
  776. * current system or fails to initialize.
  777. *
  778. * Error out only if both fail to initialize.
  779. */
  780. ret = sgx_drv_init();
  781. if (sgx_vepc_init() && ret)
  782. goto err_provision;
  783. return 0;
  784. err_provision:
  785. misc_deregister(&sgx_dev_provision);
  786. err_kthread:
  787. kthread_stop(ksgxd_tsk);
  788. err_page_cache:
  789. for (i = 0; i < sgx_nr_epc_sections; i++) {
  790. vfree(sgx_epc_sections[i].pages);
  791. memunmap(sgx_epc_sections[i].virt_addr);
  792. }
  793. return ret;
  794. }
  795. device_initcall(sgx_init);