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