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