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