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