xref: /freebsd/sys/i386/i386/sys_machdep.c (revision 61e21613)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1990 The Regents of the University of California.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #include <sys/cdefs.h>
33 #include "opt_capsicum.h"
34 #include "opt_kstack_pages.h"
35 #include "opt_ktrace.h"
36 
37 #include <sys/param.h>
38 #include <sys/capsicum.h>
39 #include <sys/systm.h>
40 #include <sys/ktrace.h>
41 #include <sys/lock.h>
42 #include <sys/malloc.h>
43 #include <sys/mutex.h>
44 #include <sys/priv.h>
45 #include <sys/proc.h>
46 #include <sys/smp.h>
47 #include <sys/sysproto.h>
48 
49 #include <vm/vm.h>
50 #include <vm/pmap.h>
51 #include <vm/vm_map.h>
52 #include <vm/vm_extern.h>
53 
54 #include <machine/atomic.h>
55 #include <machine/cpu.h>
56 #include <machine/pcb.h>
57 #include <machine/pcb_ext.h>
58 #include <machine/proc.h>
59 #include <machine/sysarch.h>
60 
61 #include <security/audit/audit.h>
62 
63 #include <vm/vm_kern.h>		/* for kernel_map */
64 
65 #define MAX_LD 8192
66 #define LD_PER_PAGE 512
67 #define	NEW_MAX_LD(num)  rounddown2(num + LD_PER_PAGE, LD_PER_PAGE)
68 #define SIZE_FROM_LARGEST_LD(num) (NEW_MAX_LD(num) << 3)
69 #define	NULL_LDT_BASE	((caddr_t)NULL)
70 
71 #ifdef SMP
72 static void set_user_ldt_rv(void *arg);
73 #endif
74 static int i386_set_ldt_data(struct thread *, int start, int num,
75     union descriptor *descs);
76 static int i386_ldt_grow(struct thread *td, int len);
77 
78 void
79 fill_based_sd(struct segment_descriptor *sdp, uint32_t base)
80 {
81 
82 	sdp->sd_lobase = base & 0xffffff;
83 	sdp->sd_hibase = (base >> 24) & 0xff;
84 	sdp->sd_lolimit = 0xffff;	/* 4GB limit, wraps around */
85 	sdp->sd_hilimit = 0xf;
86 	sdp->sd_type = SDT_MEMRWA;
87 	sdp->sd_dpl = SEL_UPL;
88 	sdp->sd_p = 1;
89 	sdp->sd_xx = 0;
90 	sdp->sd_def32 = 1;
91 	sdp->sd_gran = 1;
92 }
93 
94 /*
95  * Construct special descriptors for "base" selectors.  Store them in
96  * the PCB for later use by cpu_switch().  Store them in the GDT for
97  * more immediate use.  The GDT entries are part of the current
98  * context.  Callers must load related segment registers to complete
99  * setting up the current context.
100  */
101 void
102 set_fsbase(struct thread *td, uint32_t base)
103 {
104 	struct segment_descriptor sd;
105 
106 	fill_based_sd(&sd, base);
107 	critical_enter();
108 	td->td_pcb->pcb_fsd = sd;
109 	if (td == curthread)
110 		PCPU_GET(fsgs_gdt)[0] = sd;
111 	critical_exit();
112 }
113 
114 void
115 set_gsbase(struct thread *td, uint32_t base)
116 {
117 	struct segment_descriptor sd;
118 
119 	fill_based_sd(&sd, base);
120 	critical_enter();
121 	td->td_pcb->pcb_gsd = sd;
122 	if (td == curthread)
123 		PCPU_GET(fsgs_gdt)[1] = sd;
124 	critical_exit();
125 }
126 
127 #ifndef _SYS_SYSPROTO_H_
128 struct sysarch_args {
129 	int op;
130 	char *parms;
131 };
132 #endif
133 
134 int
135 sysarch(struct thread *td, struct sysarch_args *uap)
136 {
137 	int error;
138 	union descriptor *lp;
139 	union {
140 		struct i386_ldt_args largs;
141 		struct i386_ioperm_args iargs;
142 		struct i386_get_xfpustate xfpu;
143 	} kargs;
144 	uint32_t base;
145 	struct segment_descriptor *sdp;
146 
147 	AUDIT_ARG_CMD(uap->op);
148 
149 #ifdef CAPABILITY_MODE
150 	/*
151 	 * When adding new operations, add a new case statement here to
152 	 * explicitly indicate whether or not the operation is safe to
153 	 * perform in capability mode.
154 	 */
155 	if (IN_CAPABILITY_MODE(td)) {
156 		switch (uap->op) {
157 		case I386_GET_LDT:
158 		case I386_SET_LDT:
159 		case I386_GET_IOPERM:
160 		case I386_GET_FSBASE:
161 		case I386_SET_FSBASE:
162 		case I386_GET_GSBASE:
163 		case I386_SET_GSBASE:
164 		case I386_GET_XFPUSTATE:
165 			break;
166 
167 		case I386_SET_IOPERM:
168 		default:
169 #ifdef KTRACE
170 			if (KTRPOINT(td, KTR_CAPFAIL))
171 				ktrcapfail(CAPFAIL_SYSCALL, NULL, NULL);
172 #endif
173 			return (ECAPMODE);
174 		}
175 	}
176 #endif
177 
178 	switch (uap->op) {
179 	case I386_GET_IOPERM:
180 	case I386_SET_IOPERM:
181 		if ((error = copyin(uap->parms, &kargs.iargs,
182 		    sizeof(struct i386_ioperm_args))) != 0)
183 			return (error);
184 		break;
185 	case I386_GET_LDT:
186 	case I386_SET_LDT:
187 		if ((error = copyin(uap->parms, &kargs.largs,
188 		    sizeof(struct i386_ldt_args))) != 0)
189 			return (error);
190 		break;
191 	case I386_GET_XFPUSTATE:
192 		if ((error = copyin(uap->parms, &kargs.xfpu,
193 		    sizeof(struct i386_get_xfpustate))) != 0)
194 			return (error);
195 		break;
196 	default:
197 		break;
198 	}
199 
200 	switch (uap->op) {
201 	case I386_GET_LDT:
202 		error = i386_get_ldt(td, &kargs.largs);
203 		break;
204 	case I386_SET_LDT:
205 		if (kargs.largs.descs != NULL) {
206 			if (kargs.largs.num > MAX_LD)
207 				return (EINVAL);
208 			lp = malloc(kargs.largs.num * sizeof(union descriptor),
209 			    M_TEMP, M_WAITOK);
210 			error = copyin(kargs.largs.descs, lp,
211 			    kargs.largs.num * sizeof(union descriptor));
212 			if (error == 0)
213 				error = i386_set_ldt(td, &kargs.largs, lp);
214 			free(lp, M_TEMP);
215 		} else {
216 			error = i386_set_ldt(td, &kargs.largs, NULL);
217 		}
218 		break;
219 	case I386_GET_IOPERM:
220 		error = i386_get_ioperm(td, &kargs.iargs);
221 		if (error == 0)
222 			error = copyout(&kargs.iargs, uap->parms,
223 			    sizeof(struct i386_ioperm_args));
224 		break;
225 	case I386_SET_IOPERM:
226 		error = i386_set_ioperm(td, &kargs.iargs);
227 		break;
228 	case I386_VM86:
229 		error = vm86_sysarch(td, uap->parms);
230 		break;
231 	case I386_GET_FSBASE:
232 		sdp = &td->td_pcb->pcb_fsd;
233 		base = sdp->sd_hibase << 24 | sdp->sd_lobase;
234 		error = copyout(&base, uap->parms, sizeof(base));
235 		break;
236 	case I386_SET_FSBASE:
237 		error = copyin(uap->parms, &base, sizeof(base));
238 		if (error == 0) {
239 			/*
240 			 * Construct the special descriptor for fsbase
241 			 * and arrange for doreti to load its selector
242 			 * soon enough.
243 			 */
244 			set_fsbase(td, base);
245 			td->td_frame->tf_fs = GSEL(GUFS_SEL, SEL_UPL);
246 		}
247 		break;
248 	case I386_GET_GSBASE:
249 		sdp = &td->td_pcb->pcb_gsd;
250 		base = sdp->sd_hibase << 24 | sdp->sd_lobase;
251 		error = copyout(&base, uap->parms, sizeof(base));
252 		break;
253 	case I386_SET_GSBASE:
254 		error = copyin(uap->parms, &base, sizeof(base));
255 		if (error == 0) {
256 			/*
257 			 * Construct the special descriptor for gsbase.
258 			 * The selector is loaded immediately, since we
259 			 * normally only reload %gs on context switches.
260 			 */
261 			set_gsbase(td, base);
262 			load_gs(GSEL(GUGS_SEL, SEL_UPL));
263 		}
264 		break;
265 	case I386_GET_XFPUSTATE:
266 		if (kargs.xfpu.len > cpu_max_ext_state_size -
267 		    sizeof(union savefpu))
268 			return (EINVAL);
269 		npxgetregs(td);
270 		error = copyout((char *)(get_pcb_user_save_td(td) + 1),
271 		    kargs.xfpu.addr, kargs.xfpu.len);
272 		break;
273 	default:
274 		error = EINVAL;
275 		break;
276 	}
277 	return (error);
278 }
279 
280 int
281 i386_extend_pcb(struct thread *td)
282 {
283 	int i, offset;
284 	u_long *addr;
285 	struct pcb_ext *ext;
286 	struct soft_segment_descriptor ssd = {
287 		0,			/* segment base address (overwritten) */
288 		ctob(IOPAGES + 1) - 1,	/* length */
289 		SDT_SYS386TSS,		/* segment type */
290 		0,			/* priority level */
291 		1,			/* descriptor present */
292 		0, 0,
293 		0,			/* default 32 size */
294 		0			/* granularity */
295 	};
296 
297 	ext = pmap_trm_alloc(ctob(IOPAGES + 1), M_WAITOK | M_ZERO);
298 	/* -16 is so we can convert a trapframe into vm86trapframe inplace */
299 	ext->ext_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
300 	/*
301 	 * The last byte of the i/o map must be followed by an 0xff byte.
302 	 * We arbitrarily allocate 16 bytes here, to keep the starting
303 	 * address on a doubleword boundary.
304 	 */
305 	offset = PAGE_SIZE - 16;
306 	ext->ext_tss.tss_ioopt =
307 	    (offset - ((unsigned)&ext->ext_tss - (unsigned)ext)) << 16;
308 	ext->ext_iomap = (caddr_t)ext + offset;
309 	ext->ext_vm86.vm86_intmap = (caddr_t)ext + offset - 32;
310 
311 	addr = (u_long *)ext->ext_vm86.vm86_intmap;
312 	for (i = 0; i < (ctob(IOPAGES) + 32 + 16) / sizeof(u_long); i++)
313 		*addr++ = ~0;
314 
315 	ssd.ssd_base = (unsigned)&ext->ext_tss;
316 	ssd.ssd_limit -= ((unsigned)&ext->ext_tss - (unsigned)ext);
317 	ssdtosd(&ssd, &ext->ext_tssd);
318 
319 	KASSERT(td == curthread, ("giving TSS to !curthread"));
320 	KASSERT(td->td_pcb->pcb_ext == 0, ("already have a TSS!"));
321 
322 	/* Switch to the new TSS. */
323 	critical_enter();
324 	ext->ext_tss.tss_esp0 = PCPU_GET(trampstk);
325 	td->td_pcb->pcb_ext = ext;
326 	PCPU_SET(private_tss, 1);
327 	*PCPU_GET(tss_gdt) = ext->ext_tssd;
328 	ltr(GSEL(GPROC0_SEL, SEL_KPL));
329 	critical_exit();
330 
331 	return 0;
332 }
333 
334 int
335 i386_set_ioperm(struct thread *td, struct i386_ioperm_args *uap)
336 {
337 	char *iomap;
338 	u_int i;
339 	int error;
340 
341 	if ((error = priv_check(td, PRIV_IO)) != 0)
342 		return (error);
343 	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
344 		return (error);
345 	/*
346 	 * XXX
347 	 * While this is restricted to root, we should probably figure out
348 	 * whether any other driver is using this i/o address, as so not to
349 	 * cause confusion.  This probably requires a global 'usage registry'.
350 	 */
351 
352 	if (td->td_pcb->pcb_ext == 0)
353 		if ((error = i386_extend_pcb(td)) != 0)
354 			return (error);
355 	iomap = (char *)td->td_pcb->pcb_ext->ext_iomap;
356 
357 	if (uap->start > uap->start + uap->length ||
358 	    uap->start + uap->length > IOPAGES * PAGE_SIZE * NBBY)
359 		return (EINVAL);
360 
361 	for (i = uap->start; i < uap->start + uap->length; i++) {
362 		if (uap->enable)
363 			iomap[i >> 3] &= ~(1 << (i & 7));
364 		else
365 			iomap[i >> 3] |= (1 << (i & 7));
366 	}
367 	return (error);
368 }
369 
370 int
371 i386_get_ioperm(struct thread *td, struct i386_ioperm_args *uap)
372 {
373 	int i, state;
374 	char *iomap;
375 
376 	if (uap->start >= IOPAGES * PAGE_SIZE * NBBY)
377 		return (EINVAL);
378 
379 	if (td->td_pcb->pcb_ext == 0) {
380 		uap->length = 0;
381 		goto done;
382 	}
383 
384 	iomap = (char *)td->td_pcb->pcb_ext->ext_iomap;
385 
386 	i = uap->start;
387 	state = (iomap[i >> 3] >> (i & 7)) & 1;
388 	uap->enable = !state;
389 	uap->length = 1;
390 
391 	for (i = uap->start + 1; i < IOPAGES * PAGE_SIZE * NBBY; i++) {
392 		if (state != ((iomap[i >> 3] >> (i & 7)) & 1))
393 			break;
394 		uap->length++;
395 	}
396 
397 done:
398 	return (0);
399 }
400 
401 /*
402  * Update the GDT entry pointing to the LDT to point to the LDT of the
403  * current process. Manage dt_lock holding/unholding autonomously.
404  */
405 static void
406 set_user_ldt_locked(struct mdproc *mdp)
407 {
408 	struct proc_ldt *pldt;
409 	int gdt_idx;
410 
411 	mtx_assert(&dt_lock, MA_OWNED);
412 
413 	pldt = mdp->md_ldt;
414 	gdt_idx = GUSERLDT_SEL;
415 	gdt_idx += PCPU_GET(cpuid) * NGDT;	/* always 0 on UP */
416 	gdt[gdt_idx].sd = pldt->ldt_sd;
417 	lldt(GSEL(GUSERLDT_SEL, SEL_KPL));
418 	PCPU_SET(currentldt, GSEL(GUSERLDT_SEL, SEL_KPL));
419 }
420 
421 void
422 set_user_ldt(struct mdproc *mdp)
423 {
424 
425 	mtx_lock_spin(&dt_lock);
426 	set_user_ldt_locked(mdp);
427 	mtx_unlock_spin(&dt_lock);
428 }
429 
430 #ifdef SMP
431 static void
432 set_user_ldt_rv(void *arg)
433 {
434 	struct proc *p;
435 
436 	p = curproc;
437 	if (arg == p->p_vmspace)
438 		set_user_ldt(&p->p_md);
439 }
440 #endif
441 
442 /*
443  * dt_lock must be held. Returns with dt_lock held.
444  */
445 struct proc_ldt *
446 user_ldt_alloc(struct mdproc *mdp, int len)
447 {
448 	struct proc_ldt *pldt, *new_ldt;
449 
450 	mtx_assert(&dt_lock, MA_OWNED);
451 	mtx_unlock_spin(&dt_lock);
452 	new_ldt = malloc(sizeof(struct proc_ldt), M_SUBPROC, M_WAITOK);
453 
454 	new_ldt->ldt_len = len = NEW_MAX_LD(len);
455 	new_ldt->ldt_base = pmap_trm_alloc(len * sizeof(union descriptor),
456 	    M_WAITOK | M_ZERO);
457 	new_ldt->ldt_refcnt = 1;
458 	new_ldt->ldt_active = 0;
459 
460 	mtx_lock_spin(&dt_lock);
461 	gdt_segs[GUSERLDT_SEL].ssd_base = (unsigned)new_ldt->ldt_base;
462 	gdt_segs[GUSERLDT_SEL].ssd_limit = len * sizeof(union descriptor) - 1;
463 	ssdtosd(&gdt_segs[GUSERLDT_SEL], &new_ldt->ldt_sd);
464 
465 	if ((pldt = mdp->md_ldt) != NULL) {
466 		if (len > pldt->ldt_len)
467 			len = pldt->ldt_len;
468 		bcopy(pldt->ldt_base, new_ldt->ldt_base,
469 		    len * sizeof(union descriptor));
470 	} else
471 		bcopy(ldt, new_ldt->ldt_base, sizeof(union descriptor) * NLDT);
472 
473 	return (new_ldt);
474 }
475 
476 /*
477  * Must be called with dt_lock held.  Returns with dt_lock unheld.
478  */
479 void
480 user_ldt_free(struct thread *td)
481 {
482 	struct mdproc *mdp;
483 	struct proc_ldt *pldt;
484 
485 	mtx_assert(&dt_lock, MA_OWNED);
486 	mdp = &td->td_proc->p_md;
487 	if ((pldt = mdp->md_ldt) == NULL) {
488 		mtx_unlock_spin(&dt_lock);
489 		return;
490 	}
491 
492 	if (td == curthread) {
493 		lldt(_default_ldt);
494 		PCPU_SET(currentldt, _default_ldt);
495 	}
496 
497 	mdp->md_ldt = NULL;
498 	user_ldt_deref(pldt);
499 }
500 
501 void
502 user_ldt_deref(struct proc_ldt *pldt)
503 {
504 
505 	mtx_assert(&dt_lock, MA_OWNED);
506 	if (--pldt->ldt_refcnt == 0) {
507 		mtx_unlock_spin(&dt_lock);
508 		pmap_trm_free(pldt->ldt_base, pldt->ldt_len *
509 		    sizeof(union descriptor));
510 		free(pldt, M_SUBPROC);
511 	} else
512 		mtx_unlock_spin(&dt_lock);
513 }
514 
515 /*
516  * Note for the authors of compat layers (linux, etc): copyout() in
517  * the function below is not a problem since it presents data in
518  * arch-specific format (i.e. i386-specific in this case), not in
519  * the OS-specific one.
520  */
521 int
522 i386_get_ldt(struct thread *td, struct i386_ldt_args *uap)
523 {
524 	struct proc_ldt *pldt;
525 	char *data;
526 	u_int nldt, num;
527 	int error;
528 
529 #ifdef DEBUG
530 	printf("i386_get_ldt: start=%u num=%u descs=%p\n",
531 	    uap->start, uap->num, (void *)uap->descs);
532 #endif
533 
534 	num = min(uap->num, MAX_LD);
535 	data = malloc(num * sizeof(union descriptor), M_TEMP, M_WAITOK);
536 	mtx_lock_spin(&dt_lock);
537 	pldt = td->td_proc->p_md.md_ldt;
538 	nldt = pldt != NULL ? pldt->ldt_len : NLDT;
539 	if (uap->start >= nldt) {
540 		num = 0;
541 	} else {
542 		num = min(num, nldt - uap->start);
543 		bcopy(pldt != NULL ?
544 		    &((union descriptor *)(pldt->ldt_base))[uap->start] :
545 		    &ldt[uap->start], data, num * sizeof(union descriptor));
546 	}
547 	mtx_unlock_spin(&dt_lock);
548 	error = copyout(data, uap->descs, num * sizeof(union descriptor));
549 	if (error == 0)
550 		td->td_retval[0] = num;
551 	free(data, M_TEMP);
552 	return (error);
553 }
554 
555 int
556 i386_set_ldt(struct thread *td, struct i386_ldt_args *uap,
557     union descriptor *descs)
558 {
559 	struct mdproc *mdp;
560 	struct proc_ldt *pldt;
561 	union descriptor *dp;
562 	u_int largest_ld, i;
563 	int error;
564 
565 #ifdef DEBUG
566 	printf("i386_set_ldt: start=%u num=%u descs=%p\n",
567 	    uap->start, uap->num, (void *)uap->descs);
568 #endif
569 	error = 0;
570 	mdp = &td->td_proc->p_md;
571 
572 	if (descs == NULL) {
573 		/* Free descriptors */
574 		if (uap->start == 0 && uap->num == 0) {
575 			/*
576 			 * Treat this as a special case, so userland needn't
577 			 * know magic number NLDT.
578 			 */
579 			uap->start = NLDT;
580 			uap->num = MAX_LD - NLDT;
581 		}
582 		mtx_lock_spin(&dt_lock);
583 		if ((pldt = mdp->md_ldt) == NULL ||
584 		    uap->start >= pldt->ldt_len) {
585 			mtx_unlock_spin(&dt_lock);
586 			return (0);
587 		}
588 		largest_ld = uap->start + uap->num;
589 		if (largest_ld > pldt->ldt_len)
590 			largest_ld = pldt->ldt_len;
591 		for (i = uap->start; i < largest_ld; i++)
592 			atomic_store_rel_64(&((uint64_t *)(pldt->ldt_base))[i],
593 			    0);
594 		mtx_unlock_spin(&dt_lock);
595 		return (0);
596 	}
597 
598 	if (uap->start != LDT_AUTO_ALLOC || uap->num != 1) {
599 		/* verify range of descriptors to modify */
600 		largest_ld = uap->start + uap->num;
601 		if (uap->start >= MAX_LD || largest_ld > MAX_LD)
602 			return (EINVAL);
603 	}
604 
605 	/* Check descriptors for access violations */
606 	for (i = 0; i < uap->num; i++) {
607 		dp = &descs[i];
608 
609 		switch (dp->sd.sd_type) {
610 		case SDT_SYSNULL:	/* system null */
611 			dp->sd.sd_p = 0;
612 			break;
613 		case SDT_SYS286TSS: /* system 286 TSS available */
614 		case SDT_SYSLDT:    /* system local descriptor table */
615 		case SDT_SYS286BSY: /* system 286 TSS busy */
616 		case SDT_SYSTASKGT: /* system task gate */
617 		case SDT_SYS286IGT: /* system 286 interrupt gate */
618 		case SDT_SYS286TGT: /* system 286 trap gate */
619 		case SDT_SYSNULL2:  /* undefined by Intel */
620 		case SDT_SYS386TSS: /* system 386 TSS available */
621 		case SDT_SYSNULL3:  /* undefined by Intel */
622 		case SDT_SYS386BSY: /* system 386 TSS busy */
623 		case SDT_SYSNULL4:  /* undefined by Intel */
624 		case SDT_SYS386IGT: /* system 386 interrupt gate */
625 		case SDT_SYS386TGT: /* system 386 trap gate */
626 		case SDT_SYS286CGT: /* system 286 call gate */
627 		case SDT_SYS386CGT: /* system 386 call gate */
628 			return (EACCES);
629 
630 		/* memory segment types */
631 		case SDT_MEMEC:   /* memory execute only conforming */
632 		case SDT_MEMEAC:  /* memory execute only accessed conforming */
633 		case SDT_MEMERC:  /* memory execute read conforming */
634 		case SDT_MEMERAC: /* memory execute read accessed conforming */
635 			 /* Must be "present" if executable and conforming. */
636 			if (dp->sd.sd_p == 0)
637 				return (EACCES);
638 			break;
639 		case SDT_MEMRO:   /* memory read only */
640 		case SDT_MEMROA:  /* memory read only accessed */
641 		case SDT_MEMRW:   /* memory read write */
642 		case SDT_MEMRWA:  /* memory read write accessed */
643 		case SDT_MEMROD:  /* memory read only expand dwn limit */
644 		case SDT_MEMRODA: /* memory read only expand dwn lim accessed */
645 		case SDT_MEMRWD:  /* memory read write expand dwn limit */
646 		case SDT_MEMRWDA: /* memory read write expand dwn lim acessed */
647 		case SDT_MEME:    /* memory execute only */
648 		case SDT_MEMEA:   /* memory execute only accessed */
649 		case SDT_MEMER:   /* memory execute read */
650 		case SDT_MEMERA:  /* memory execute read accessed */
651 			break;
652 		default:
653 			return (EINVAL);
654 		}
655 
656 		/* Only user (ring-3) descriptors may be present. */
657 		if (dp->sd.sd_p != 0 && dp->sd.sd_dpl != SEL_UPL)
658 			return (EACCES);
659 	}
660 
661 	if (uap->start == LDT_AUTO_ALLOC && uap->num == 1) {
662 		/* Allocate a free slot */
663 		mtx_lock_spin(&dt_lock);
664 		if ((pldt = mdp->md_ldt) == NULL) {
665 			if ((error = i386_ldt_grow(td, NLDT + 1))) {
666 				mtx_unlock_spin(&dt_lock);
667 				return (error);
668 			}
669 			pldt = mdp->md_ldt;
670 		}
671 again:
672 		/*
673 		 * start scanning a bit up to leave room for NVidia and
674 		 * Wine, which still user the "Blat" method of allocation.
675 		 */
676 		dp = &((union descriptor *)(pldt->ldt_base))[NLDT];
677 		for (i = NLDT; i < pldt->ldt_len; ++i) {
678 			if (dp->sd.sd_type == SDT_SYSNULL)
679 				break;
680 			dp++;
681 		}
682 		if (i >= pldt->ldt_len) {
683 			if ((error = i386_ldt_grow(td, pldt->ldt_len+1))) {
684 				mtx_unlock_spin(&dt_lock);
685 				return (error);
686 			}
687 			goto again;
688 		}
689 		uap->start = i;
690 		error = i386_set_ldt_data(td, i, 1, descs);
691 		mtx_unlock_spin(&dt_lock);
692 	} else {
693 		largest_ld = uap->start + uap->num;
694 		mtx_lock_spin(&dt_lock);
695 		if (!(error = i386_ldt_grow(td, largest_ld))) {
696 			error = i386_set_ldt_data(td, uap->start, uap->num,
697 			    descs);
698 		}
699 		mtx_unlock_spin(&dt_lock);
700 	}
701 	if (error == 0)
702 		td->td_retval[0] = uap->start;
703 	return (error);
704 }
705 
706 static int
707 i386_set_ldt_data(struct thread *td, int start, int num,
708     union descriptor *descs)
709 {
710 	struct mdproc *mdp;
711 	struct proc_ldt *pldt;
712 	uint64_t *dst, *src;
713 	int i;
714 
715 	mtx_assert(&dt_lock, MA_OWNED);
716 
717 	mdp = &td->td_proc->p_md;
718 	pldt = mdp->md_ldt;
719 	dst = (uint64_t *)(pldt->ldt_base);
720 	src = (uint64_t *)descs;
721 
722 	/*
723 	 * Atomic(9) is used only to get 64bit atomic store with
724 	 * cmpxchg8b when available.  There is no op without release
725 	 * semantic.
726 	 */
727 	for (i = 0; i < num; i++)
728 		atomic_store_rel_64(&dst[start + i], src[i]);
729 	return (0);
730 }
731 
732 static int
733 i386_ldt_grow(struct thread *td, int len)
734 {
735 	struct mdproc *mdp;
736 	struct proc_ldt *new_ldt, *pldt;
737 	caddr_t old_ldt_base;
738 	int old_ldt_len;
739 
740 	mtx_assert(&dt_lock, MA_OWNED);
741 
742 	if (len > MAX_LD)
743 		return (ENOMEM);
744 	if (len < NLDT + 1)
745 		len = NLDT + 1;
746 
747 	mdp = &td->td_proc->p_md;
748 	old_ldt_base = NULL_LDT_BASE;
749 	old_ldt_len = 0;
750 
751 	/* Allocate a user ldt. */
752 	if ((pldt = mdp->md_ldt) == NULL || len > pldt->ldt_len) {
753 		new_ldt = user_ldt_alloc(mdp, len);
754 		if (new_ldt == NULL)
755 			return (ENOMEM);
756 		pldt = mdp->md_ldt;
757 
758 		if (pldt != NULL) {
759 			if (new_ldt->ldt_len <= pldt->ldt_len) {
760 				/*
761 				 * We just lost the race for allocation, so
762 				 * free the new object and return.
763 				 */
764 				mtx_unlock_spin(&dt_lock);
765 				pmap_trm_free(new_ldt->ldt_base,
766 				   new_ldt->ldt_len * sizeof(union descriptor));
767 				free(new_ldt, M_SUBPROC);
768 				mtx_lock_spin(&dt_lock);
769 				return (0);
770 			}
771 
772 			/*
773 			 * We have to substitute the current LDT entry for
774 			 * curproc with the new one since its size grew.
775 			 */
776 			old_ldt_base = pldt->ldt_base;
777 			old_ldt_len = pldt->ldt_len;
778 			pldt->ldt_sd = new_ldt->ldt_sd;
779 			pldt->ldt_base = new_ldt->ldt_base;
780 			pldt->ldt_len = new_ldt->ldt_len;
781 		} else
782 			mdp->md_ldt = pldt = new_ldt;
783 #ifdef SMP
784 		/*
785 		 * Signal other cpus to reload ldt.  We need to unlock dt_lock
786 		 * here because other CPU will contest on it since their
787 		 * curthreads won't hold the lock and will block when trying
788 		 * to acquire it.
789 		 */
790 		mtx_unlock_spin(&dt_lock);
791 		smp_rendezvous(NULL, set_user_ldt_rv, NULL,
792 		    td->td_proc->p_vmspace);
793 #else
794 		set_user_ldt_locked(&td->td_proc->p_md);
795 		mtx_unlock_spin(&dt_lock);
796 #endif
797 		if (old_ldt_base != NULL_LDT_BASE) {
798 			pmap_trm_free(old_ldt_base, old_ldt_len *
799 			    sizeof(union descriptor));
800 			free(new_ldt, M_SUBPROC);
801 		}
802 		mtx_lock_spin(&dt_lock);
803 	}
804 	return (0);
805 }
806