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