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