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