]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/kern_thread.c
Refactor select to reduce contention and hide internal implementation
[FreeBSD/FreeBSD.git] / sys / kern / kern_thread.c
1 /*-
2  * Copyright (C) 2001 Julian Elischer <julian@freebsd.org>.
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(s), this list of conditions and the following disclaimer as
10  *    the first lines of this file unmodified other than the possible
11  *    addition of one or more copyright notices.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice(s), this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) ``AS IS'' AND ANY
17  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19  * DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) BE LIABLE FOR ANY
20  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
23  * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
26  * DAMAGE.
27  */
28
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31
32 #include <sys/param.h>
33 #include <sys/systm.h>
34 #include <sys/kernel.h>
35 #include <sys/lock.h>
36 #include <sys/mutex.h>
37 #include <sys/proc.h>
38 #include <sys/resourcevar.h>
39 #include <sys/smp.h>
40 #include <sys/sysctl.h>
41 #include <sys/sched.h>
42 #include <sys/sleepqueue.h>
43 #include <sys/selinfo.h>
44 #include <sys/turnstile.h>
45 #include <sys/ktr.h>
46 #include <sys/umtx.h>
47
48 #include <security/audit/audit.h>
49
50 #include <vm/vm.h>
51 #include <vm/vm_extern.h>
52 #include <vm/uma.h>
53 #include <sys/eventhandler.h>
54
55 /*
56  * thread related storage.
57  */
58 static uma_zone_t thread_zone;
59
60 SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0, "thread allocation");
61
62 int max_threads_per_proc = 1500;
63 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
64         &max_threads_per_proc, 0, "Limit on threads per proc");
65
66 int max_threads_hits;
67 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
68         &max_threads_hits, 0, "");
69
70 #ifdef KSE
71 int virtual_cpu;
72
73 #endif
74 TAILQ_HEAD(, thread) zombie_threads = TAILQ_HEAD_INITIALIZER(zombie_threads);
75 static struct mtx zombie_lock;
76 MTX_SYSINIT(zombie_lock, &zombie_lock, "zombie lock", MTX_SPIN);
77
78 static void thread_zombie(struct thread *);
79
80 #ifdef KSE
81 static int
82 sysctl_kse_virtual_cpu(SYSCTL_HANDLER_ARGS)
83 {
84         int error, new_val;
85         int def_val;
86
87         def_val = mp_ncpus;
88         if (virtual_cpu == 0)
89                 new_val = def_val;
90         else
91                 new_val = virtual_cpu;
92         error = sysctl_handle_int(oidp, &new_val, 0, req);
93         if (error != 0 || req->newptr == NULL)
94                 return (error);
95         if (new_val < 0)
96                 return (EINVAL);
97         virtual_cpu = new_val;
98         return (0);
99 }
100
101 /* DEBUG ONLY */
102 SYSCTL_PROC(_kern_threads, OID_AUTO, virtual_cpu, CTLTYPE_INT|CTLFLAG_RW,
103         0, sizeof(virtual_cpu), sysctl_kse_virtual_cpu, "I",
104         "debug virtual cpus");
105 #endif
106
107 struct mtx tid_lock;
108 static struct unrhdr *tid_unrhdr;
109
110 /*
111  * Prepare a thread for use.
112  */
113 static int
114 thread_ctor(void *mem, int size, void *arg, int flags)
115 {
116         struct thread   *td;
117
118         td = (struct thread *)mem;
119         td->td_state = TDS_INACTIVE;
120         td->td_oncpu = NOCPU;
121
122         td->td_tid = alloc_unr(tid_unrhdr);
123         td->td_syscalls = 0;
124
125         /*
126          * Note that td_critnest begins life as 1 because the thread is not
127          * running and is thereby implicitly waiting to be on the receiving
128          * end of a context switch.
129          */
130         td->td_critnest = 1;
131         EVENTHANDLER_INVOKE(thread_ctor, td);
132 #ifdef AUDIT
133         audit_thread_alloc(td);
134 #endif
135         umtx_thread_alloc(td);
136         return (0);
137 }
138
139 /*
140  * Reclaim a thread after use.
141  */
142 static void
143 thread_dtor(void *mem, int size, void *arg)
144 {
145         struct thread *td;
146
147         td = (struct thread *)mem;
148
149 #ifdef INVARIANTS
150         /* Verify that this thread is in a safe state to free. */
151         switch (td->td_state) {
152         case TDS_INHIBITED:
153         case TDS_RUNNING:
154         case TDS_CAN_RUN:
155         case TDS_RUNQ:
156                 /*
157                  * We must never unlink a thread that is in one of
158                  * these states, because it is currently active.
159                  */
160                 panic("bad state for thread unlinking");
161                 /* NOTREACHED */
162         case TDS_INACTIVE:
163                 break;
164         default:
165                 panic("bad thread state");
166                 /* NOTREACHED */
167         }
168 #endif
169 #ifdef AUDIT
170         audit_thread_free(td);
171 #endif
172         EVENTHANDLER_INVOKE(thread_dtor, td);
173         free_unr(tid_unrhdr, td->td_tid);
174         sched_newthread(td);
175 }
176
177 /*
178  * Initialize type-stable parts of a thread (when newly created).
179  */
180 static int
181 thread_init(void *mem, int size, int flags)
182 {
183         struct thread *td;
184
185         td = (struct thread *)mem;
186
187         td->td_sleepqueue = sleepq_alloc();
188         td->td_turnstile = turnstile_alloc();
189         EVENTHANDLER_INVOKE(thread_init, td);
190         td->td_sched = (struct td_sched *)&td[1];
191         sched_newthread(td);
192         umtx_thread_init(td);
193         td->td_kstack = 0;
194         return (0);
195 }
196
197 /*
198  * Tear down type-stable parts of a thread (just before being discarded).
199  */
200 static void
201 thread_fini(void *mem, int size)
202 {
203         struct thread *td;
204
205         td = (struct thread *)mem;
206         EVENTHANDLER_INVOKE(thread_fini, td);
207         turnstile_free(td->td_turnstile);
208         sleepq_free(td->td_sleepqueue);
209         umtx_thread_fini(td);
210         seltdfini(td);
211 }
212
213 /*
214  * For a newly created process,
215  * link up all the structures and its initial threads etc.
216  * called from:
217  * {arch}/{arch}/machdep.c   ia64_init(), init386() etc.
218  * proc_dtor() (should go away)
219  * proc_init()
220  */
221 void
222 proc_linkup0(struct proc *p, struct thread *td)
223 {
224         TAILQ_INIT(&p->p_threads);           /* all threads in proc */
225         proc_linkup(p, td);
226 }
227
228 void
229 proc_linkup(struct proc *p, struct thread *td)
230 {
231
232 #ifdef KSE
233         TAILQ_INIT(&p->p_upcalls);           /* upcall list */
234 #endif
235         sigqueue_init(&p->p_sigqueue, p);
236         p->p_ksi = ksiginfo_alloc(1);
237         if (p->p_ksi != NULL) {
238                 /* XXX p_ksi may be null if ksiginfo zone is not ready */
239                 p->p_ksi->ksi_flags = KSI_EXT | KSI_INS;
240         }
241         LIST_INIT(&p->p_mqnotifier);
242         p->p_numthreads = 0;
243         thread_link(td, p);
244 }
245
246 /*
247  * Initialize global thread allocation resources.
248  */
249 void
250 threadinit(void)
251 {
252
253         mtx_init(&tid_lock, "TID lock", NULL, MTX_DEF);
254         tid_unrhdr = new_unrhdr(PID_MAX + 1, INT_MAX, &tid_lock);
255
256         thread_zone = uma_zcreate("THREAD", sched_sizeof_thread(),
257             thread_ctor, thread_dtor, thread_init, thread_fini,
258             16 - 1, 0);
259 #ifdef KSE
260         kseinit();      /* set up kse specific stuff  e.g. upcall zone*/
261 #endif
262 }
263
264 /*
265  * Place an unused thread on the zombie list.
266  * Use the slpq as that must be unused by now.
267  */
268 void
269 thread_zombie(struct thread *td)
270 {
271         mtx_lock_spin(&zombie_lock);
272         TAILQ_INSERT_HEAD(&zombie_threads, td, td_slpq);
273         mtx_unlock_spin(&zombie_lock);
274 }
275
276 /*
277  * Release a thread that has exited after cpu_throw().
278  */
279 void
280 thread_stash(struct thread *td)
281 {
282         atomic_subtract_rel_int(&td->td_proc->p_exitthreads, 1);
283         thread_zombie(td);
284 }
285
286 /*
287  * Reap zombie kse resource.
288  */
289 void
290 thread_reap(void)
291 {
292         struct thread *td_first, *td_next;
293
294         /*
295          * Don't even bother to lock if none at this instant,
296          * we really don't care about the next instant..
297          */
298         if (!TAILQ_EMPTY(&zombie_threads)) {
299                 mtx_lock_spin(&zombie_lock);
300                 td_first = TAILQ_FIRST(&zombie_threads);
301                 if (td_first)
302                         TAILQ_INIT(&zombie_threads);
303                 mtx_unlock_spin(&zombie_lock);
304                 while (td_first) {
305                         td_next = TAILQ_NEXT(td_first, td_slpq);
306                         if (td_first->td_ucred)
307                                 crfree(td_first->td_ucred);
308                         thread_free(td_first);
309                         td_first = td_next;
310                 }
311         }
312 #ifdef KSE
313         upcall_reap();
314 #endif
315 }
316
317 /*
318  * Allocate a thread.
319  */
320 struct thread *
321 thread_alloc(void)
322 {
323         struct thread *td;
324
325         thread_reap(); /* check if any zombies to get */
326
327         td = (struct thread *)uma_zalloc(thread_zone, M_WAITOK);
328         KASSERT(td->td_kstack == 0, ("thread_alloc got thread with kstack"));
329         if (!vm_thread_new(td, 0)) {
330                 uma_zfree(thread_zone, td);
331                 return (NULL);
332         }
333         cpu_thread_alloc(td);
334         return (td);
335 }
336
337
338 /*
339  * Deallocate a thread.
340  */
341 void
342 thread_free(struct thread *td)
343 {
344
345         cpu_thread_free(td);
346         if (td->td_altkstack != 0)
347                 vm_thread_dispose_altkstack(td);
348         if (td->td_kstack != 0)
349                 vm_thread_dispose(td);
350         uma_zfree(thread_zone, td);
351 }
352
353 /*
354  * Discard the current thread and exit from its context.
355  * Always called with scheduler locked.
356  *
357  * Because we can't free a thread while we're operating under its context,
358  * push the current thread into our CPU's deadthread holder. This means
359  * we needn't worry about someone else grabbing our context before we
360  * do a cpu_throw().  This may not be needed now as we are under schedlock.
361  * Maybe we can just do a thread_stash() as thr_exit1 does.
362  */
363 /*  XXX
364  * libthr expects its thread exit to return for the last
365  * thread, meaning that the program is back to non-threaded
366  * mode I guess. Because we do this (cpu_throw) unconditionally
367  * here, they have their own version of it. (thr_exit1()) 
368  * that doesn't do it all if this was the last thread.
369  * It is also called from thread_suspend_check().
370  * Of course in the end, they end up coming here through exit1
371  * anyhow..  After fixing 'thr' to play by the rules we should be able 
372  * to merge these two functions together.
373  *
374  * called from:
375  * exit1()
376  * kse_exit()
377  * thr_exit()
378  * ifdef KSE
379  * thread_user_enter()
380  * thread_userret()
381  * endif
382  * thread_suspend_check()
383  */
384 void
385 thread_exit(void)
386 {
387         uint64_t new_switchtime;
388         struct thread *td;
389         struct thread *td2;
390         struct proc *p;
391
392         td = curthread;
393         p = td->td_proc;
394
395         PROC_SLOCK_ASSERT(p, MA_OWNED);
396         mtx_assert(&Giant, MA_NOTOWNED);
397
398         PROC_LOCK_ASSERT(p, MA_OWNED);
399         KASSERT(p != NULL, ("thread exiting without a process"));
400         CTR3(KTR_PROC, "thread_exit: thread %p (pid %ld, %s)", td,
401             (long)p->p_pid, td->td_name);
402         KASSERT(TAILQ_EMPTY(&td->td_sigqueue.sq_list), ("signal pending"));
403
404 #ifdef AUDIT
405         AUDIT_SYSCALL_EXIT(0, td);
406 #endif
407
408 #ifdef KSE
409         if (td->td_standin != NULL) {
410                 /*
411                  * Note that we don't need to free the cred here as it
412                  * is done in thread_reap().
413                  */
414                 thread_zombie(td->td_standin);
415                 td->td_standin = NULL;
416         }
417 #endif
418
419         umtx_thread_exit(td);
420
421         /*
422          * drop FPU & debug register state storage, or any other
423          * architecture specific resources that
424          * would not be on a new untouched process.
425          */
426         cpu_thread_exit(td);    /* XXXSMP */
427
428         /* Do the same timestamp bookkeeping that mi_switch() would do. */
429         new_switchtime = cpu_ticks();
430         p->p_rux.rux_runtime += (new_switchtime - PCPU_GET(switchtime));
431         PCPU_SET(switchtime, new_switchtime);
432         PCPU_SET(switchticks, ticks);
433         PCPU_INC(cnt.v_swtch);
434         /* Save our resource usage in our process. */
435         td->td_ru.ru_nvcsw++;
436         rucollect(&p->p_ru, &td->td_ru);
437         /*
438          * The last thread is left attached to the process
439          * So that the whole bundle gets recycled. Skip
440          * all this stuff if we never had threads.
441          * EXIT clears all sign of other threads when
442          * it goes to single threading, so the last thread always
443          * takes the short path.
444          */
445         if (p->p_flag & P_HADTHREADS) {
446                 if (p->p_numthreads > 1) {
447                         thread_lock(td);
448 #ifdef KSE
449                         kse_unlink(td);
450 #else
451                         thread_unlink(td);
452 #endif
453                         thread_unlock(td);
454                         td2 = FIRST_THREAD_IN_PROC(p);
455                         sched_exit_thread(td2, td);
456
457                         /*
458                          * The test below is NOT true if we are the
459                          * sole exiting thread. P_STOPPED_SNGL is unset
460                          * in exit1() after it is the only survivor.
461                          */
462                         if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
463                                 if (p->p_numthreads == p->p_suspcount) {
464                                         thread_lock(p->p_singlethread);
465                                         thread_unsuspend_one(p->p_singlethread);
466                                         thread_unlock(p->p_singlethread);
467                                 }
468                         }
469
470                         atomic_add_int(&td->td_proc->p_exitthreads, 1);
471                         PCPU_SET(deadthread, td);
472                 } else {
473                         /*
474                          * The last thread is exiting.. but not through exit()
475                          * what should we do?
476                          * Theoretically this can't happen
477                          * exit1() - clears threading flags before coming here
478                          * kse_exit() - treats last thread specially
479                          * thr_exit() - treats last thread specially
480                          * ifdef KSE
481                          * thread_user_enter() - only if more exist
482                          * thread_userret() - only if more exist
483                          * endif
484                          * thread_suspend_check() - only if more exist
485                          */
486                         panic ("thread_exit: Last thread exiting on its own");
487                 }
488         } 
489         PROC_UNLOCK(p);
490         thread_lock(td);
491         /* Save our tick information with both the thread and proc locked */
492         ruxagg(&p->p_rux, td);
493         PROC_SUNLOCK(p);
494         td->td_state = TDS_INACTIVE;
495         CTR1(KTR_PROC, "thread_exit: cpu_throw() thread %p", td);
496         sched_throw(td);
497         panic("I'm a teapot!");
498         /* NOTREACHED */
499 }
500
501 /*
502  * Do any thread specific cleanups that may be needed in wait()
503  * called with Giant, proc and schedlock not held.
504  */
505 void
506 thread_wait(struct proc *p)
507 {
508         struct thread *td;
509
510         mtx_assert(&Giant, MA_NOTOWNED);
511         KASSERT((p->p_numthreads == 1), ("Multiple threads in wait1()"));
512         td = FIRST_THREAD_IN_PROC(p);
513 #ifdef KSE
514         if (td->td_standin != NULL) {
515                 if (td->td_standin->td_ucred != NULL) {
516                         crfree(td->td_standin->td_ucred);
517                         td->td_standin->td_ucred = NULL;
518                 }
519                 thread_free(td->td_standin);
520                 td->td_standin = NULL;
521         }
522 #endif
523         /* Lock the last thread so we spin until it exits cpu_throw(). */
524         thread_lock(td);
525         thread_unlock(td);
526         /* Wait for any remaining threads to exit cpu_throw(). */
527         while (p->p_exitthreads)
528                 sched_relinquish(curthread);
529         cpu_thread_clean(td);
530         crfree(td->td_ucred);
531         thread_reap();  /* check for zombie threads etc. */
532 }
533
534 /*
535  * Link a thread to a process.
536  * set up anything that needs to be initialized for it to
537  * be used by the process.
538  *
539  * Note that we do not link to the proc's ucred here.
540  * The thread is linked as if running but no KSE assigned.
541  * Called from:
542  *  proc_linkup()
543  *  thread_schedule_upcall()
544  *  thr_create()
545  */
546 void
547 thread_link(struct thread *td, struct proc *p)
548 {
549
550         /*
551          * XXX This can't be enabled because it's called for proc0 before
552          * it's spinlock has been created.
553          * PROC_SLOCK_ASSERT(p, MA_OWNED);
554          */
555         td->td_state    = TDS_INACTIVE;
556         td->td_proc     = p;
557         td->td_flags    = TDF_INMEM;
558
559         LIST_INIT(&td->td_contested);
560         LIST_INIT(&td->td_lprof[0]);
561         LIST_INIT(&td->td_lprof[1]);
562         sigqueue_init(&td->td_sigqueue, p);
563         callout_init(&td->td_slpcallout, CALLOUT_MPSAFE);
564         TAILQ_INSERT_HEAD(&p->p_threads, td, td_plist);
565         p->p_numthreads++;
566 }
567
568 /*
569  * Convert a process with one thread to an unthreaded process.
570  * Called from:
571  *  thread_single(exit)  (called from execve and exit)
572  *  kse_exit()          XXX may need cleaning up wrt KSE stuff
573  */
574 void
575 thread_unthread(struct thread *td)
576 {
577         struct proc *p = td->td_proc;
578
579         KASSERT((p->p_numthreads == 1), ("Unthreading with >1 threads"));
580 #ifdef KSE
581         thread_lock(td);
582         upcall_remove(td);
583         thread_unlock(td);
584         p->p_flag &= ~(P_SA|P_HADTHREADS);
585         td->td_mailbox = NULL;
586         td->td_pflags &= ~(TDP_SA | TDP_CAN_UNBIND);
587         if (td->td_standin != NULL) {
588                 thread_zombie(td->td_standin);
589                 td->td_standin = NULL;
590         }
591 #else
592         p->p_flag &= ~P_HADTHREADS;
593 #endif
594 }
595
596 /*
597  * Called from:
598  *  thread_exit()
599  */
600 void
601 thread_unlink(struct thread *td)
602 {
603         struct proc *p = td->td_proc;
604
605         PROC_SLOCK_ASSERT(p, MA_OWNED);
606         TAILQ_REMOVE(&p->p_threads, td, td_plist);
607         p->p_numthreads--;
608         /* could clear a few other things here */
609         /* Must  NOT clear links to proc! */
610 }
611
612 /*
613  * Enforce single-threading.
614  *
615  * Returns 1 if the caller must abort (another thread is waiting to
616  * exit the process or similar). Process is locked!
617  * Returns 0 when you are successfully the only thread running.
618  * A process has successfully single threaded in the suspend mode when
619  * There are no threads in user mode. Threads in the kernel must be
620  * allowed to continue until they get to the user boundary. They may even
621  * copy out their return values and data before suspending. They may however be
622  * accelerated in reaching the user boundary as we will wake up
623  * any sleeping threads that are interruptable. (PCATCH).
624  */
625 int
626 thread_single(int mode)
627 {
628         struct thread *td;
629         struct thread *td2;
630         struct proc *p;
631         int remaining;
632
633         td = curthread;
634         p = td->td_proc;
635         mtx_assert(&Giant, MA_NOTOWNED);
636         PROC_LOCK_ASSERT(p, MA_OWNED);
637         KASSERT((td != NULL), ("curthread is NULL"));
638
639         if ((p->p_flag & P_HADTHREADS) == 0)
640                 return (0);
641
642         /* Is someone already single threading? */
643         if (p->p_singlethread != NULL && p->p_singlethread != td)
644                 return (1);
645
646         if (mode == SINGLE_EXIT) {
647                 p->p_flag |= P_SINGLE_EXIT;
648                 p->p_flag &= ~P_SINGLE_BOUNDARY;
649         } else {
650                 p->p_flag &= ~P_SINGLE_EXIT;
651                 if (mode == SINGLE_BOUNDARY)
652                         p->p_flag |= P_SINGLE_BOUNDARY;
653                 else
654                         p->p_flag &= ~P_SINGLE_BOUNDARY;
655         }
656         p->p_flag |= P_STOPPED_SINGLE;
657         PROC_SLOCK(p);
658         p->p_singlethread = td;
659         if (mode == SINGLE_EXIT)
660                 remaining = p->p_numthreads;
661         else if (mode == SINGLE_BOUNDARY)
662                 remaining = p->p_numthreads - p->p_boundary_count;
663         else
664                 remaining = p->p_numthreads - p->p_suspcount;
665         while (remaining != 1) {
666                 if (P_SHOULDSTOP(p) != P_STOPPED_SINGLE)
667                         goto stopme;
668                 FOREACH_THREAD_IN_PROC(p, td2) {
669                         if (td2 == td)
670                                 continue;
671                         thread_lock(td2);
672                         td2->td_flags |= TDF_ASTPENDING;
673                         if (TD_IS_INHIBITED(td2)) {
674                                 switch (mode) {
675                                 case SINGLE_EXIT:
676                                         if (td->td_flags & TDF_DBSUSPEND)
677                                                 td->td_flags &= ~TDF_DBSUSPEND;
678                                         if (TD_IS_SUSPENDED(td2))
679                                                 thread_unsuspend_one(td2);
680                                         if (TD_ON_SLEEPQ(td2) &&
681                                             (td2->td_flags & TDF_SINTR))
682                                                 sleepq_abort(td2, EINTR);
683                                         break;
684                                 case SINGLE_BOUNDARY:
685                                         break;
686                                 default:        
687                                         if (TD_IS_SUSPENDED(td2)) {
688                                                 thread_unlock(td2);
689                                                 continue;
690                                         }
691                                         /*
692                                          * maybe other inhibited states too?
693                                          */
694                                         if ((td2->td_flags & TDF_SINTR) &&
695                                             (td2->td_inhibitors &
696                                             (TDI_SLEEPING | TDI_SWAPPED)))
697                                                 thread_suspend_one(td2);
698                                         break;
699                                 }
700                         }
701 #ifdef SMP
702                         else if (TD_IS_RUNNING(td2) && td != td2) {
703                                 forward_signal(td2);
704                         }
705 #endif
706                         thread_unlock(td2);
707                 }
708                 if (mode == SINGLE_EXIT)
709                         remaining = p->p_numthreads;
710                 else if (mode == SINGLE_BOUNDARY)
711                         remaining = p->p_numthreads - p->p_boundary_count;
712                 else
713                         remaining = p->p_numthreads - p->p_suspcount;
714
715                 /*
716                  * Maybe we suspended some threads.. was it enough?
717                  */
718                 if (remaining == 1)
719                         break;
720
721 stopme:
722                 /*
723                  * Wake us up when everyone else has suspended.
724                  * In the mean time we suspend as well.
725                  */
726                 thread_suspend_switch(td);
727                 if (mode == SINGLE_EXIT)
728                         remaining = p->p_numthreads;
729                 else if (mode == SINGLE_BOUNDARY)
730                         remaining = p->p_numthreads - p->p_boundary_count;
731                 else
732                         remaining = p->p_numthreads - p->p_suspcount;
733         }
734         if (mode == SINGLE_EXIT) {
735                 /*
736                  * We have gotten rid of all the other threads and we
737                  * are about to either exit or exec. In either case,
738                  * we try our utmost  to revert to being a non-threaded
739                  * process.
740                  */
741                 p->p_singlethread = NULL;
742                 p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT);
743                 thread_unthread(td);
744         }
745         PROC_SUNLOCK(p);
746         return (0);
747 }
748
749 /*
750  * Called in from locations that can safely check to see
751  * whether we have to suspend or at least throttle for a
752  * single-thread event (e.g. fork).
753  *
754  * Such locations include userret().
755  * If the "return_instead" argument is non zero, the thread must be able to
756  * accept 0 (caller may continue), or 1 (caller must abort) as a result.
757  *
758  * The 'return_instead' argument tells the function if it may do a
759  * thread_exit() or suspend, or whether the caller must abort and back
760  * out instead.
761  *
762  * If the thread that set the single_threading request has set the
763  * P_SINGLE_EXIT bit in the process flags then this call will never return
764  * if 'return_instead' is false, but will exit.
765  *
766  * P_SINGLE_EXIT | return_instead == 0| return_instead != 0
767  *---------------+--------------------+---------------------
768  *       0       | returns 0          |   returns 0 or 1
769  *               | when ST ends       |   immediatly
770  *---------------+--------------------+---------------------
771  *       1       | thread exits       |   returns 1
772  *               |                    |  immediatly
773  * 0 = thread_exit() or suspension ok,
774  * other = return error instead of stopping the thread.
775  *
776  * While a full suspension is under effect, even a single threading
777  * thread would be suspended if it made this call (but it shouldn't).
778  * This call should only be made from places where
779  * thread_exit() would be safe as that may be the outcome unless
780  * return_instead is set.
781  */
782 int
783 thread_suspend_check(int return_instead)
784 {
785         struct thread *td;
786         struct proc *p;
787
788         td = curthread;
789         p = td->td_proc;
790         mtx_assert(&Giant, MA_NOTOWNED);
791         PROC_LOCK_ASSERT(p, MA_OWNED);
792         while (P_SHOULDSTOP(p) ||
793               ((p->p_flag & P_TRACED) && (td->td_flags & TDF_DBSUSPEND))) {
794                 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
795                         KASSERT(p->p_singlethread != NULL,
796                             ("singlethread not set"));
797                         /*
798                          * The only suspension in action is a
799                          * single-threading. Single threader need not stop.
800                          * XXX Should be safe to access unlocked
801                          * as it can only be set to be true by us.
802                          */
803                         if (p->p_singlethread == td)
804                                 return (0);     /* Exempt from stopping. */
805                 }
806                 if ((p->p_flag & P_SINGLE_EXIT) && return_instead)
807                         return (EINTR);
808
809                 /* Should we goto user boundary if we didn't come from there? */
810                 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE &&
811                     (p->p_flag & P_SINGLE_BOUNDARY) && return_instead)
812                         return (ERESTART);
813
814                 /* If thread will exit, flush its pending signals */
815                 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td))
816                         sigqueue_flush(&td->td_sigqueue);
817
818                 PROC_SLOCK(p);
819                 thread_stopped(p);
820                 /*
821                  * If the process is waiting for us to exit,
822                  * this thread should just suicide.
823                  * Assumes that P_SINGLE_EXIT implies P_STOPPED_SINGLE.
824                  */
825                 if ((p->p_flag & P_SINGLE_EXIT) && (p->p_singlethread != td))
826                         thread_exit();
827                 if (P_SHOULDSTOP(p) == P_STOPPED_SINGLE) {
828                         if (p->p_numthreads == p->p_suspcount + 1) {
829                                 thread_lock(p->p_singlethread);
830                                 thread_unsuspend_one(p->p_singlethread);
831                                 thread_unlock(p->p_singlethread);
832                         }
833                 }
834                 PROC_UNLOCK(p);
835                 thread_lock(td);
836                 /*
837                  * When a thread suspends, it just
838                  * gets taken off all queues.
839                  */
840                 thread_suspend_one(td);
841                 if (return_instead == 0) {
842                         p->p_boundary_count++;
843                         td->td_flags |= TDF_BOUNDARY;
844                 }
845                 PROC_SUNLOCK(p);
846                 mi_switch(SW_INVOL, NULL);
847                 if (return_instead == 0)
848                         td->td_flags &= ~TDF_BOUNDARY;
849                 thread_unlock(td);
850                 PROC_LOCK(p);
851                 if (return_instead == 0)
852                         p->p_boundary_count--;
853         }
854         return (0);
855 }
856
857 void
858 thread_suspend_switch(struct thread *td)
859 {
860         struct proc *p;
861
862         p = td->td_proc;
863         KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
864         PROC_LOCK_ASSERT(p, MA_OWNED);
865         PROC_SLOCK_ASSERT(p, MA_OWNED);
866         /*
867          * We implement thread_suspend_one in stages here to avoid
868          * dropping the proc lock while the thread lock is owned.
869          */
870         thread_stopped(p);
871         p->p_suspcount++;
872         PROC_UNLOCK(p);
873         thread_lock(td);
874         sched_sleep(td);
875         TD_SET_SUSPENDED(td);
876         PROC_SUNLOCK(p);
877         DROP_GIANT();
878         mi_switch(SW_VOL, NULL);
879         thread_unlock(td);
880         PICKUP_GIANT();
881         PROC_LOCK(p);
882         PROC_SLOCK(p);
883 }
884
885 void
886 thread_suspend_one(struct thread *td)
887 {
888         struct proc *p = td->td_proc;
889
890         PROC_SLOCK_ASSERT(p, MA_OWNED);
891         THREAD_LOCK_ASSERT(td, MA_OWNED);
892         KASSERT(!TD_IS_SUSPENDED(td), ("already suspended"));
893         p->p_suspcount++;
894         sched_sleep(td);
895         TD_SET_SUSPENDED(td);
896 }
897
898 void
899 thread_unsuspend_one(struct thread *td)
900 {
901         struct proc *p = td->td_proc;
902
903         PROC_SLOCK_ASSERT(p, MA_OWNED);
904         THREAD_LOCK_ASSERT(td, MA_OWNED);
905         KASSERT(TD_IS_SUSPENDED(td), ("Thread not suspended"));
906         TD_CLR_SUSPENDED(td);
907         p->p_suspcount--;
908         setrunnable(td);
909 }
910
911 /*
912  * Allow all threads blocked by single threading to continue running.
913  */
914 void
915 thread_unsuspend(struct proc *p)
916 {
917         struct thread *td;
918
919         PROC_LOCK_ASSERT(p, MA_OWNED);
920         PROC_SLOCK_ASSERT(p, MA_OWNED);
921         if (!P_SHOULDSTOP(p)) {
922                 FOREACH_THREAD_IN_PROC(p, td) {
923                         thread_lock(td);
924                         if (TD_IS_SUSPENDED(td)) {
925                                 thread_unsuspend_one(td);
926                         }
927                         thread_unlock(td);
928                 }
929         } else if ((P_SHOULDSTOP(p) == P_STOPPED_SINGLE) &&
930             (p->p_numthreads == p->p_suspcount)) {
931                 /*
932                  * Stopping everything also did the job for the single
933                  * threading request. Now we've downgraded to single-threaded,
934                  * let it continue.
935                  */
936                 thread_lock(p->p_singlethread);
937                 thread_unsuspend_one(p->p_singlethread);
938                 thread_unlock(p->p_singlethread);
939         }
940 }
941
942 /*
943  * End the single threading mode..
944  */
945 void
946 thread_single_end(void)
947 {
948         struct thread *td;
949         struct proc *p;
950
951         td = curthread;
952         p = td->td_proc;
953         PROC_LOCK_ASSERT(p, MA_OWNED);
954         p->p_flag &= ~(P_STOPPED_SINGLE | P_SINGLE_EXIT | P_SINGLE_BOUNDARY);
955         PROC_SLOCK(p);
956         p->p_singlethread = NULL;
957         /*
958          * If there are other threads they mey now run,
959          * unless of course there is a blanket 'stop order'
960          * on the process. The single threader must be allowed
961          * to continue however as this is a bad place to stop.
962          */
963         if ((p->p_numthreads != 1) && (!P_SHOULDSTOP(p))) {
964                 FOREACH_THREAD_IN_PROC(p, td) {
965                         thread_lock(td);
966                         if (TD_IS_SUSPENDED(td)) {
967                                 thread_unsuspend_one(td);
968                         }
969                         thread_unlock(td);
970                 }
971         }
972         PROC_SUNLOCK(p);
973 }
974
975 struct thread *
976 thread_find(struct proc *p, lwpid_t tid)
977 {
978         struct thread *td;
979
980         PROC_LOCK_ASSERT(p, MA_OWNED);
981         PROC_SLOCK(p);
982         FOREACH_THREAD_IN_PROC(p, td) {
983                 if (td->td_tid == tid)
984                         break;
985         }
986         PROC_SUNLOCK(p);
987         return (td);
988 }