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 * 4. 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/capability.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#ifdef XEN
63#include <machine/xen/xenfunc.h>
64
65void i386_reset_ldt(struct proc_ldt *pldt);
66
67void
68i386_reset_ldt(struct proc_ldt *pldt)
69{
70        xen_set_ldt((vm_offset_t)pldt->ldt_base, pldt->ldt_len);
71}
72#else
73#define i386_reset_ldt(x)
74#endif
75
76#include <vm/vm_kern.h>		/* for kernel_map */
77
78#define MAX_LD 8192
79#define LD_PER_PAGE 512
80#define NEW_MAX_LD(num)  ((num + LD_PER_PAGE) & ~(LD_PER_PAGE-1))
81#define SIZE_FROM_LARGEST_LD(num) (NEW_MAX_LD(num) << 3)
82#define	NULL_LDT_BASE	((caddr_t)NULL)
83
84#ifdef SMP
85static void set_user_ldt_rv(struct vmspace *vmsp);
86#endif
87static int i386_set_ldt_data(struct thread *, int start, int num,
88	union descriptor *descs);
89static int i386_ldt_grow(struct thread *td, int len);
90
91#ifndef _SYS_SYSPROTO_H_
92struct sysarch_args {
93	int op;
94	char *parms;
95};
96#endif
97
98int
99sysarch(td, uap)
100	struct thread *td;
101	register 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	} kargs;
109	uint32_t base;
110	struct segment_descriptor sd, *sdp;
111
112	AUDIT_ARG_CMD(uap->op);
113
114#ifdef CAPABILITY_MODE
115	/*
116	 * When adding new operations, add a new case statement here to
117	 * explicitly indicate whether or not the operation is safe to
118	 * perform in capability mode.
119	 */
120	if (IN_CAPABILITY_MODE(td)) {
121		switch (uap->op) {
122		case I386_GET_LDT:
123		case I386_SET_LDT:
124		case I386_GET_IOPERM:
125		case I386_GET_FSBASE:
126		case I386_SET_FSBASE:
127		case I386_GET_GSBASE:
128		case I386_SET_GSBASE:
129			break;
130
131		case I386_SET_IOPERM:
132		default:
133			return (ECAPMODE);
134		}
135	}
136#endif
137
138	switch (uap->op) {
139	case I386_GET_IOPERM:
140	case I386_SET_IOPERM:
141		if ((error = copyin(uap->parms, &kargs.iargs,
142		    sizeof(struct i386_ioperm_args))) != 0)
143			return (error);
144		break;
145	case I386_GET_LDT:
146	case I386_SET_LDT:
147		if ((error = copyin(uap->parms, &kargs.largs,
148		    sizeof(struct i386_ldt_args))) != 0)
149			return (error);
150		if (kargs.largs.num > MAX_LD || kargs.largs.num <= 0)
151			return (EINVAL);
152		break;
153	default:
154		break;
155	}
156
157	switch(uap->op) {
158	case I386_GET_LDT:
159		error = i386_get_ldt(td, &kargs.largs);
160		break;
161	case I386_SET_LDT:
162		if (kargs.largs.descs != NULL) {
163			lp = (union descriptor *)kmem_alloc(kernel_map,
164			    kargs.largs.num * sizeof(union descriptor));
165			if (lp == NULL) {
166				error = ENOMEM;
167				break;
168			}
169			error = copyin(kargs.largs.descs, lp,
170			    kargs.largs.num * sizeof(union descriptor));
171			if (error == 0)
172				error = i386_set_ldt(td, &kargs.largs, lp);
173			kmem_free(kernel_map, (vm_offset_t)lp,
174			    kargs.largs.num * sizeof(union descriptor));
175		} else {
176			error = i386_set_ldt(td, &kargs.largs, NULL);
177		}
178		break;
179	case I386_GET_IOPERM:
180		error = i386_get_ioperm(td, &kargs.iargs);
181		if (error == 0)
182			error = copyout(&kargs.iargs, uap->parms,
183			    sizeof(struct i386_ioperm_args));
184		break;
185	case I386_SET_IOPERM:
186		error = i386_set_ioperm(td, &kargs.iargs);
187		break;
188	case I386_VM86:
189		error = vm86_sysarch(td, uap->parms);
190		break;
191	case I386_GET_FSBASE:
192		sdp = &td->td_pcb->pcb_fsd;
193		base = sdp->sd_hibase << 24 | sdp->sd_lobase;
194		error = copyout(&base, uap->parms, sizeof(base));
195		break;
196	case I386_SET_FSBASE:
197		error = copyin(uap->parms, &base, sizeof(base));
198		if (!error) {
199			/*
200			 * Construct a descriptor and store it in the pcb for
201			 * the next context switch.  Also store it in the gdt
202			 * so that the load of tf_fs into %fs will activate it
203			 * at return to userland.
204			 */
205			sd.sd_lobase = base & 0xffffff;
206			sd.sd_hibase = (base >> 24) & 0xff;
207#ifdef XEN
208			/* need to do nosegneg like Linux */
209			sd.sd_lolimit = (HYPERVISOR_VIRT_START >> 12) & 0xffff;
210#else
211			sd.sd_lolimit = 0xffff;	/* 4GB limit, wraps around */
212#endif
213			sd.sd_hilimit = 0xf;
214			sd.sd_type  = SDT_MEMRWA;
215			sd.sd_dpl   = SEL_UPL;
216			sd.sd_p     = 1;
217			sd.sd_xx    = 0;
218			sd.sd_def32 = 1;
219			sd.sd_gran  = 1;
220			critical_enter();
221			td->td_pcb->pcb_fsd = sd;
222#ifdef XEN
223			HYPERVISOR_update_descriptor(vtomach(&PCPU_GET(fsgs_gdt)[0]),
224			    *(uint64_t *)&sd);
225#else
226			PCPU_GET(fsgs_gdt)[0] = sd;
227#endif
228			critical_exit();
229			td->td_frame->tf_fs = GSEL(GUFS_SEL, SEL_UPL);
230		}
231		break;
232	case I386_GET_GSBASE:
233		sdp = &td->td_pcb->pcb_gsd;
234		base = sdp->sd_hibase << 24 | sdp->sd_lobase;
235		error = copyout(&base, uap->parms, sizeof(base));
236		break;
237	case I386_SET_GSBASE:
238		error = copyin(uap->parms, &base, sizeof(base));
239		if (!error) {
240			/*
241			 * Construct a descriptor and store it in the pcb for
242			 * the next context switch.  Also store it in the gdt
243			 * because we have to do a load_gs() right now.
244			 */
245			sd.sd_lobase = base & 0xffffff;
246			sd.sd_hibase = (base >> 24) & 0xff;
247
248#ifdef XEN
249			/* need to do nosegneg like Linux */
250			sd.sd_lolimit = (HYPERVISOR_VIRT_START >> 12) & 0xffff;
251#else
252			sd.sd_lolimit = 0xffff;	/* 4GB limit, wraps around */
253#endif
254			sd.sd_hilimit = 0xf;
255			sd.sd_type  = SDT_MEMRWA;
256			sd.sd_dpl   = SEL_UPL;
257			sd.sd_p     = 1;
258			sd.sd_xx    = 0;
259			sd.sd_def32 = 1;
260			sd.sd_gran  = 1;
261			critical_enter();
262			td->td_pcb->pcb_gsd = sd;
263#ifdef XEN
264			HYPERVISOR_update_descriptor(vtomach(&PCPU_GET(fsgs_gdt)[1]),
265			    *(uint64_t *)&sd);
266#else
267			PCPU_GET(fsgs_gdt)[1] = sd;
268#endif
269			critical_exit();
270			load_gs(GSEL(GUGS_SEL, SEL_UPL));
271		}
272		break;
273	default:
274		error = EINVAL;
275		break;
276	}
277	return (error);
278}
279
280int
281i386_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 = (struct pcb_ext *)kmem_alloc(kernel_map, ctob(IOPAGES+1));
298	if (ext == 0)
299		return (ENOMEM);
300	bzero(ext, sizeof(struct pcb_ext));
301	/* -16 is so we can convert a trapframe into vm86trapframe inplace */
302	ext->ext_tss.tss_esp0 = td->td_kstack + ctob(KSTACK_PAGES) -
303	    sizeof(struct pcb) - 16;
304	ext->ext_tss.tss_ss0 = GSEL(GDATA_SEL, SEL_KPL);
305	/*
306	 * The last byte of the i/o map must be followed by an 0xff byte.
307	 * We arbitrarily allocate 16 bytes here, to keep the starting
308	 * address on a doubleword boundary.
309	 */
310	offset = PAGE_SIZE - 16;
311	ext->ext_tss.tss_ioopt =
312	    (offset - ((unsigned)&ext->ext_tss - (unsigned)ext)) << 16;
313	ext->ext_iomap = (caddr_t)ext + offset;
314	ext->ext_vm86.vm86_intmap = (caddr_t)ext + offset - 32;
315
316	addr = (u_long *)ext->ext_vm86.vm86_intmap;
317	for (i = 0; i < (ctob(IOPAGES) + 32 + 16) / sizeof(u_long); i++)
318		*addr++ = ~0;
319
320	ssd.ssd_base = (unsigned)&ext->ext_tss;
321	ssd.ssd_limit -= ((unsigned)&ext->ext_tss - (unsigned)ext);
322	ssdtosd(&ssd, &ext->ext_tssd);
323
324	KASSERT(td == curthread, ("giving TSS to !curthread"));
325	KASSERT(td->td_pcb->pcb_ext == 0, ("already have a TSS!"));
326
327	/* Switch to the new TSS. */
328	critical_enter();
329	td->td_pcb->pcb_ext = ext;
330	PCPU_SET(private_tss, 1);
331	*PCPU_GET(tss_gdt) = ext->ext_tssd;
332	ltr(GSEL(GPROC0_SEL, SEL_KPL));
333	critical_exit();
334
335	return 0;
336}
337
338int
339i386_set_ioperm(td, uap)
340	struct thread *td;
341	struct i386_ioperm_args *uap;
342{
343	int i, error;
344	char *iomap;
345
346	if ((error = priv_check(td, PRIV_IO)) != 0)
347		return (error);
348	if ((error = securelevel_gt(td->td_ucred, 0)) != 0)
349		return (error);
350	/*
351	 * XXX
352	 * While this is restricted to root, we should probably figure out
353	 * whether any other driver is using this i/o address, as so not to
354	 * cause confusion.  This probably requires a global 'usage registry'.
355	 */
356
357	if (td->td_pcb->pcb_ext == 0)
358		if ((error = i386_extend_pcb(td)) != 0)
359			return (error);
360	iomap = (char *)td->td_pcb->pcb_ext->ext_iomap;
361
362	if (uap->start + uap->length > IOPAGES * PAGE_SIZE * NBBY)
363		return (EINVAL);
364
365	for (i = uap->start; i < uap->start + uap->length; i++) {
366		if (uap->enable)
367			iomap[i >> 3] &= ~(1 << (i & 7));
368		else
369			iomap[i >> 3] |= (1 << (i & 7));
370	}
371	return (error);
372}
373
374int
375i386_get_ioperm(td, uap)
376	struct thread *td;
377	struct i386_ioperm_args *uap;
378{
379	int i, state;
380	char *iomap;
381
382	if (uap->start >= IOPAGES * PAGE_SIZE * NBBY)
383		return (EINVAL);
384
385	if (td->td_pcb->pcb_ext == 0) {
386		uap->length = 0;
387		goto done;
388	}
389
390	iomap = (char *)td->td_pcb->pcb_ext->ext_iomap;
391
392	i = uap->start;
393	state = (iomap[i >> 3] >> (i & 7)) & 1;
394	uap->enable = !state;
395	uap->length = 1;
396
397	for (i = uap->start + 1; i < IOPAGES * PAGE_SIZE * NBBY; i++) {
398		if (state != ((iomap[i >> 3] >> (i & 7)) & 1))
399			break;
400		uap->length++;
401	}
402
403done:
404	return (0);
405}
406
407/*
408 * Update the GDT entry pointing to the LDT to point to the LDT of the
409 * current process. Manage dt_lock holding/unholding autonomously.
410 */
411void
412set_user_ldt(struct mdproc *mdp)
413{
414	struct proc_ldt *pldt;
415	int dtlocked;
416
417	dtlocked = 0;
418	if (!mtx_owned(&dt_lock)) {
419		mtx_lock_spin(&dt_lock);
420		dtlocked = 1;
421	}
422
423	pldt = mdp->md_ldt;
424#ifdef XEN
425	i386_reset_ldt(pldt);
426	PCPU_SET(currentldt, (int)pldt);
427#else
428#ifdef SMP
429	gdt[PCPU_GET(cpuid) * NGDT + GUSERLDT_SEL].sd = pldt->ldt_sd;
430#else
431	gdt[GUSERLDT_SEL].sd = pldt->ldt_sd;
432#endif
433	lldt(GSEL(GUSERLDT_SEL, SEL_KPL));
434	PCPU_SET(currentldt, GSEL(GUSERLDT_SEL, SEL_KPL));
435#endif /* XEN */
436	if (dtlocked)
437		mtx_unlock_spin(&dt_lock);
438}
439
440#ifdef SMP
441static void
442set_user_ldt_rv(struct vmspace *vmsp)
443{
444	struct thread *td;
445
446	td = curthread;
447	if (vmsp != td->td_proc->p_vmspace)
448		return;
449
450	set_user_ldt(&td->td_proc->p_md);
451}
452#endif
453
454#ifdef XEN
455
456/*
457 * dt_lock must be held. Returns with dt_lock held.
458 */
459struct proc_ldt *
460user_ldt_alloc(struct mdproc *mdp, int len)
461{
462        struct proc_ldt *pldt, *new_ldt;
463
464        mtx_assert(&dt_lock, MA_OWNED);
465        mtx_unlock_spin(&dt_lock);
466        new_ldt = malloc(sizeof(struct proc_ldt),
467                M_SUBPROC, M_WAITOK);
468
469        new_ldt->ldt_len = len = NEW_MAX_LD(len);
470        new_ldt->ldt_base = (caddr_t)kmem_alloc(kernel_map,
471                round_page(len * sizeof(union descriptor)));
472        if (new_ldt->ldt_base == NULL) {
473                free(new_ldt, M_SUBPROC);
474		mtx_lock_spin(&dt_lock);
475                return (NULL);
476        }
477        new_ldt->ldt_refcnt = 1;
478        new_ldt->ldt_active = 0;
479
480	mtx_lock_spin(&dt_lock);
481        if ((pldt = mdp->md_ldt)) {
482                if (len > pldt->ldt_len)
483                        len = pldt->ldt_len;
484                bcopy(pldt->ldt_base, new_ldt->ldt_base,
485                    len * sizeof(union descriptor));
486        } else {
487                bcopy(ldt, new_ldt->ldt_base, PAGE_SIZE);
488        }
489        mtx_unlock_spin(&dt_lock);  /* XXX kill once pmap locking fixed. */
490        pmap_map_readonly(kernel_pmap, (vm_offset_t)new_ldt->ldt_base,
491                          new_ldt->ldt_len*sizeof(union descriptor));
492        mtx_lock_spin(&dt_lock);  /* XXX kill once pmap locking fixed. */
493        return (new_ldt);
494}
495#else
496/*
497 * dt_lock must be held. Returns with dt_lock held.
498 */
499struct proc_ldt *
500user_ldt_alloc(struct mdproc *mdp, int len)
501{
502	struct proc_ldt *pldt, *new_ldt;
503
504	mtx_assert(&dt_lock, MA_OWNED);
505	mtx_unlock_spin(&dt_lock);
506	new_ldt = malloc(sizeof(struct proc_ldt),
507		M_SUBPROC, M_WAITOK);
508
509	new_ldt->ldt_len = len = NEW_MAX_LD(len);
510	new_ldt->ldt_base = (caddr_t)kmem_alloc(kernel_map,
511		len * sizeof(union descriptor));
512	if (new_ldt->ldt_base == NULL) {
513		free(new_ldt, M_SUBPROC);
514		mtx_lock_spin(&dt_lock);
515		return (NULL);
516	}
517	new_ldt->ldt_refcnt = 1;
518	new_ldt->ldt_active = 0;
519
520	mtx_lock_spin(&dt_lock);
521	gdt_segs[GUSERLDT_SEL].ssd_base = (unsigned)new_ldt->ldt_base;
522	gdt_segs[GUSERLDT_SEL].ssd_limit = len * sizeof(union descriptor) - 1;
523	ssdtosd(&gdt_segs[GUSERLDT_SEL], &new_ldt->ldt_sd);
524
525	if ((pldt = mdp->md_ldt) != NULL) {
526		if (len > pldt->ldt_len)
527			len = pldt->ldt_len;
528		bcopy(pldt->ldt_base, new_ldt->ldt_base,
529		    len * sizeof(union descriptor));
530	} else
531		bcopy(ldt, new_ldt->ldt_base, sizeof(ldt));
532
533	return (new_ldt);
534}
535#endif /* !XEN */
536
537/*
538 * Must be called with dt_lock held.  Returns with dt_lock unheld.
539 */
540void
541user_ldt_free(struct thread *td)
542{
543	struct mdproc *mdp = &td->td_proc->p_md;
544	struct proc_ldt *pldt;
545
546	mtx_assert(&dt_lock, MA_OWNED);
547	if ((pldt = mdp->md_ldt) == NULL) {
548		mtx_unlock_spin(&dt_lock);
549		return;
550	}
551
552	if (td == curthread) {
553#ifdef XEN
554		i386_reset_ldt(&default_proc_ldt);
555		PCPU_SET(currentldt, (int)&default_proc_ldt);
556#else
557		lldt(_default_ldt);
558		PCPU_SET(currentldt, _default_ldt);
559#endif
560	}
561
562	mdp->md_ldt = NULL;
563	user_ldt_deref(pldt);
564}
565
566void
567user_ldt_deref(struct proc_ldt *pldt)
568{
569
570	mtx_assert(&dt_lock, MA_OWNED);
571	if (--pldt->ldt_refcnt == 0) {
572		mtx_unlock_spin(&dt_lock);
573		kmem_free(kernel_map, (vm_offset_t)pldt->ldt_base,
574			pldt->ldt_len * sizeof(union descriptor));
575		free(pldt, M_SUBPROC);
576	} else
577		mtx_unlock_spin(&dt_lock);
578}
579
580/*
581 * Note for the authors of compat layers (linux, etc): copyout() in
582 * the function below is not a problem since it presents data in
583 * arch-specific format (i.e. i386-specific in this case), not in
584 * the OS-specific one.
585 */
586int
587i386_get_ldt(td, uap)
588	struct thread *td;
589	struct i386_ldt_args *uap;
590{
591	int error = 0;
592	struct proc_ldt *pldt;
593	int nldt, num;
594	union descriptor *lp;
595
596#ifdef	DEBUG
597	printf("i386_get_ldt: start=%d num=%d descs=%p\n",
598	    uap->start, uap->num, (void *)uap->descs);
599#endif
600
601	mtx_lock_spin(&dt_lock);
602	if ((pldt = td->td_proc->p_md.md_ldt) != NULL) {
603		nldt = pldt->ldt_len;
604		lp = &((union descriptor *)(pldt->ldt_base))[uap->start];
605		mtx_unlock_spin(&dt_lock);
606		num = min(uap->num, nldt);
607	} else {
608		mtx_unlock_spin(&dt_lock);
609		nldt = sizeof(ldt)/sizeof(ldt[0]);
610		num = min(uap->num, nldt);
611		lp = &ldt[uap->start];
612	}
613
614	if ((uap->start > (unsigned int)nldt) ||
615	    ((unsigned int)num > (unsigned int)nldt) ||
616	    ((unsigned int)(uap->start + num) > (unsigned int)nldt))
617		return(EINVAL);
618
619	error = copyout(lp, uap->descs, num * sizeof(union descriptor));
620	if (!error)
621		td->td_retval[0] = num;
622
623	return(error);
624}
625
626int
627i386_set_ldt(td, uap, descs)
628	struct thread *td;
629	struct i386_ldt_args *uap;
630	union descriptor *descs;
631{
632	int error = 0, i;
633	int largest_ld;
634	struct mdproc *mdp = &td->td_proc->p_md;
635	struct proc_ldt *pldt;
636	union descriptor *dp;
637
638#ifdef	DEBUG
639	printf("i386_set_ldt: start=%d num=%d descs=%p\n",
640	    uap->start, uap->num, (void *)uap->descs);
641#endif
642
643	if (descs == NULL) {
644		/* Free descriptors */
645		if (uap->start == 0 && uap->num == 0) {
646			/*
647			 * Treat this as a special case, so userland needn't
648			 * know magic number NLDT.
649			 */
650			uap->start = NLDT;
651			uap->num = MAX_LD - NLDT;
652		}
653		if (uap->num == 0)
654			return (EINVAL);
655		mtx_lock_spin(&dt_lock);
656		if ((pldt = mdp->md_ldt) == NULL ||
657		    uap->start >= pldt->ldt_len) {
658			mtx_unlock_spin(&dt_lock);
659			return (0);
660		}
661		largest_ld = uap->start + uap->num;
662		if (largest_ld > pldt->ldt_len)
663			largest_ld = pldt->ldt_len;
664		i = largest_ld - uap->start;
665		bzero(&((union descriptor *)(pldt->ldt_base))[uap->start],
666		    sizeof(union descriptor) * i);
667		mtx_unlock_spin(&dt_lock);
668		return (0);
669	}
670
671	if (!(uap->start == LDT_AUTO_ALLOC && uap->num == 1)) {
672		/* verify range of descriptors to modify */
673		largest_ld = uap->start + uap->num;
674		if (uap->start >= MAX_LD || largest_ld > MAX_LD) {
675			return (EINVAL);
676		}
677	}
678
679	/* Check descriptors for access violations */
680	for (i = 0; i < uap->num; i++) {
681		dp = &descs[i];
682
683		switch (dp->sd.sd_type) {
684		case SDT_SYSNULL:	/* system null */
685			dp->sd.sd_p = 0;
686			break;
687		case SDT_SYS286TSS: /* system 286 TSS available */
688		case SDT_SYSLDT:    /* system local descriptor table */
689		case SDT_SYS286BSY: /* system 286 TSS busy */
690		case SDT_SYSTASKGT: /* system task gate */
691		case SDT_SYS286IGT: /* system 286 interrupt gate */
692		case SDT_SYS286TGT: /* system 286 trap gate */
693		case SDT_SYSNULL2:  /* undefined by Intel */
694		case SDT_SYS386TSS: /* system 386 TSS available */
695		case SDT_SYSNULL3:  /* undefined by Intel */
696		case SDT_SYS386BSY: /* system 386 TSS busy */
697		case SDT_SYSNULL4:  /* undefined by Intel */
698		case SDT_SYS386IGT: /* system 386 interrupt gate */
699		case SDT_SYS386TGT: /* system 386 trap gate */
700		case SDT_SYS286CGT: /* system 286 call gate */
701		case SDT_SYS386CGT: /* system 386 call gate */
702			/* I can't think of any reason to allow a user proc
703			 * to create a segment of these types.  They are
704			 * for OS use only.
705			 */
706			return (EACCES);
707			/*NOTREACHED*/
708
709		/* memory segment types */
710		case SDT_MEMEC:   /* memory execute only conforming */
711		case SDT_MEMEAC:  /* memory execute only accessed conforming */
712		case SDT_MEMERC:  /* memory execute read conforming */
713		case SDT_MEMERAC: /* memory execute read accessed conforming */
714			 /* Must be "present" if executable and conforming. */
715			if (dp->sd.sd_p == 0)
716				return (EACCES);
717			break;
718		case SDT_MEMRO:   /* memory read only */
719		case SDT_MEMROA:  /* memory read only accessed */
720		case SDT_MEMRW:   /* memory read write */
721		case SDT_MEMRWA:  /* memory read write accessed */
722		case SDT_MEMROD:  /* memory read only expand dwn limit */
723		case SDT_MEMRODA: /* memory read only expand dwn lim accessed */
724		case SDT_MEMRWD:  /* memory read write expand dwn limit */
725		case SDT_MEMRWDA: /* memory read write expand dwn lim acessed */
726		case SDT_MEME:    /* memory execute only */
727		case SDT_MEMEA:   /* memory execute only accessed */
728		case SDT_MEMER:   /* memory execute read */
729		case SDT_MEMERA:  /* memory execute read accessed */
730			break;
731		default:
732			return(EINVAL);
733			/*NOTREACHED*/
734		}
735
736		/* Only user (ring-3) descriptors may be present. */
737		if ((dp->sd.sd_p != 0) && (dp->sd.sd_dpl != SEL_UPL))
738			return (EACCES);
739	}
740
741	if (uap->start == LDT_AUTO_ALLOC && uap->num == 1) {
742		/* Allocate a free slot */
743		mtx_lock_spin(&dt_lock);
744		if ((pldt = mdp->md_ldt) == NULL) {
745			if ((error = i386_ldt_grow(td, NLDT + 1))) {
746				mtx_unlock_spin(&dt_lock);
747				return (error);
748			}
749			pldt = mdp->md_ldt;
750		}
751again:
752		/*
753		 * start scanning a bit up to leave room for NVidia and
754		 * Wine, which still user the "Blat" method of allocation.
755		 */
756		dp = &((union descriptor *)(pldt->ldt_base))[NLDT];
757		for (i = NLDT; i < pldt->ldt_len; ++i) {
758			if (dp->sd.sd_type == SDT_SYSNULL)
759				break;
760			dp++;
761		}
762		if (i >= pldt->ldt_len) {
763			if ((error = i386_ldt_grow(td, pldt->ldt_len+1))) {
764				mtx_unlock_spin(&dt_lock);
765				return (error);
766			}
767			goto again;
768		}
769		uap->start = i;
770		error = i386_set_ldt_data(td, i, 1, descs);
771		mtx_unlock_spin(&dt_lock);
772	} else {
773		largest_ld = uap->start + uap->num;
774		mtx_lock_spin(&dt_lock);
775		if (!(error = i386_ldt_grow(td, largest_ld))) {
776			error = i386_set_ldt_data(td, uap->start, uap->num,
777			    descs);
778		}
779		mtx_unlock_spin(&dt_lock);
780	}
781	if (error == 0)
782		td->td_retval[0] = uap->start;
783	return (error);
784}
785#ifdef XEN
786static int
787i386_set_ldt_data(struct thread *td, int start, int num,
788	union descriptor *descs)
789{
790	struct mdproc *mdp = &td->td_proc->p_md;
791	struct proc_ldt *pldt = mdp->md_ldt;
792
793	mtx_assert(&dt_lock, MA_OWNED);
794
795	while (num) {
796		xen_update_descriptor(
797		    &((union descriptor *)(pldt->ldt_base))[start],
798		    descs);
799		num--;
800		start++;
801		descs++;
802	}
803	return (0);
804}
805#else
806static int
807i386_set_ldt_data(struct thread *td, int start, int num,
808	union descriptor *descs)
809{
810	struct mdproc *mdp = &td->td_proc->p_md;
811	struct proc_ldt *pldt = mdp->md_ldt;
812
813	mtx_assert(&dt_lock, MA_OWNED);
814
815	/* Fill in range */
816	bcopy(descs,
817	    &((union descriptor *)(pldt->ldt_base))[start],
818	    num * sizeof(union descriptor));
819	return (0);
820}
821#endif /* !XEN */
822
823static int
824i386_ldt_grow(struct thread *td, int len)
825{
826	struct mdproc *mdp = &td->td_proc->p_md;
827	struct proc_ldt *new_ldt, *pldt;
828	caddr_t old_ldt_base = NULL_LDT_BASE;
829	int old_ldt_len = 0;
830
831	mtx_assert(&dt_lock, MA_OWNED);
832
833	if (len > MAX_LD)
834		return (ENOMEM);
835	if (len < NLDT + 1)
836		len = NLDT + 1;
837
838	/* Allocate a user ldt. */
839	if ((pldt = mdp->md_ldt) == NULL || len > pldt->ldt_len) {
840		new_ldt = user_ldt_alloc(mdp, len);
841		if (new_ldt == NULL)
842			return (ENOMEM);
843		pldt = mdp->md_ldt;
844
845		if (pldt != NULL) {
846			if (new_ldt->ldt_len <= pldt->ldt_len) {
847				/*
848				 * We just lost the race for allocation, so
849				 * free the new object and return.
850				 */
851				mtx_unlock_spin(&dt_lock);
852				kmem_free(kernel_map,
853				   (vm_offset_t)new_ldt->ldt_base,
854				   new_ldt->ldt_len * sizeof(union descriptor));
855				free(new_ldt, M_SUBPROC);
856				mtx_lock_spin(&dt_lock);
857				return (0);
858			}
859
860			/*
861			 * We have to substitute the current LDT entry for
862			 * curproc with the new one since its size grew.
863			 */
864			old_ldt_base = pldt->ldt_base;
865			old_ldt_len = pldt->ldt_len;
866			pldt->ldt_sd = new_ldt->ldt_sd;
867			pldt->ldt_base = new_ldt->ldt_base;
868			pldt->ldt_len = new_ldt->ldt_len;
869		} else
870			mdp->md_ldt = pldt = new_ldt;
871#ifdef SMP
872		/*
873		 * Signal other cpus to reload ldt.  We need to unlock dt_lock
874		 * here because other CPU will contest on it since their
875		 * curthreads won't hold the lock and will block when trying
876		 * to acquire it.
877		 */
878		mtx_unlock_spin(&dt_lock);
879		smp_rendezvous(NULL, (void (*)(void *))set_user_ldt_rv,
880		    NULL, td->td_proc->p_vmspace);
881#else
882		set_user_ldt(&td->td_proc->p_md);
883		mtx_unlock_spin(&dt_lock);
884#endif
885		if (old_ldt_base != NULL_LDT_BASE) {
886			kmem_free(kernel_map, (vm_offset_t)old_ldt_base,
887			    old_ldt_len * sizeof(union descriptor));
888			free(new_ldt, M_SUBPROC);
889		}
890		mtx_lock_spin(&dt_lock);
891	}
892	return (0);
893}
894