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