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