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