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