kern_thr.c revision 315949
1/*-
2 * Copyright (c) 2003, Jeffrey Roberson <jeff@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 unmodified, this list of conditions, and the following
10 *    disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 *    notice, this list of conditions and the following disclaimer in the
13 *    documentation and/or other materials provided with the distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 */
26
27#include <sys/cdefs.h>
28__FBSDID("$FreeBSD: stable/10/sys/kern/kern_thr.c 315949 2017-03-25 13:33:23Z badger $");
29
30#include "opt_compat.h"
31#include "opt_posix.h"
32#include <sys/param.h>
33#include <sys/kernel.h>
34#include <sys/lock.h>
35#include <sys/mutex.h>
36#include <sys/priv.h>
37#include <sys/proc.h>
38#include <sys/posix4.h>
39#include <sys/ptrace.h>
40#include <sys/racct.h>
41#include <sys/resourcevar.h>
42#include <sys/rwlock.h>
43#include <sys/sched.h>
44#include <sys/sysctl.h>
45#include <sys/smp.h>
46#include <sys/syscallsubr.h>
47#include <sys/sysent.h>
48#include <sys/systm.h>
49#include <sys/sysproto.h>
50#include <sys/signalvar.h>
51#include <sys/sysctl.h>
52#include <sys/ucontext.h>
53#include <sys/thr.h>
54#include <sys/rtprio.h>
55#include <sys/umtx.h>
56#include <sys/limits.h>
57
58#include <machine/frame.h>
59
60#include <security/audit/audit.h>
61
62static SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0,
63    "thread allocation");
64
65static int max_threads_per_proc = 1500;
66SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
67    &max_threads_per_proc, 0, "Limit on threads per proc");
68
69static int max_threads_hits;
70SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
71    &max_threads_hits, 0, "kern.threads.max_threads_per_proc hit count");
72
73#ifdef COMPAT_FREEBSD32
74
75static inline int
76suword_lwpid(void *addr, lwpid_t lwpid)
77{
78	int error;
79
80	if (SV_CURPROC_FLAG(SV_LP64))
81		error = suword(addr, lwpid);
82	else
83		error = suword32(addr, lwpid);
84	return (error);
85}
86
87#else
88#define suword_lwpid	suword
89#endif
90
91/*
92 * System call interface.
93 */
94
95struct thr_create_initthr_args {
96	ucontext_t ctx;
97	long *tid;
98};
99
100static int
101thr_create_initthr(struct thread *td, void *thunk)
102{
103	struct thr_create_initthr_args *args;
104
105	/* Copy out the child tid. */
106	args = thunk;
107	if (args->tid != NULL && suword_lwpid(args->tid, td->td_tid))
108		return (EFAULT);
109
110	return (set_mcontext(td, &args->ctx.uc_mcontext));
111}
112
113int
114sys_thr_create(struct thread *td, struct thr_create_args *uap)
115    /* ucontext_t *ctx, long *id, int flags */
116{
117	struct thr_create_initthr_args args;
118	int error;
119
120	if ((error = copyin(uap->ctx, &args.ctx, sizeof(args.ctx))))
121		return (error);
122	args.tid = uap->id;
123	return (thread_create(td, NULL, thr_create_initthr, &args));
124}
125
126int
127sys_thr_new(struct thread *td, struct thr_new_args *uap)
128    /* struct thr_param * */
129{
130	struct thr_param param;
131	int error;
132
133	if (uap->param_size < 0 || uap->param_size > sizeof(param))
134		return (EINVAL);
135	bzero(&param, sizeof(param));
136	if ((error = copyin(uap->param, &param, uap->param_size)))
137		return (error);
138	return (kern_thr_new(td, &param));
139}
140
141static int
142thr_new_initthr(struct thread *td, void *thunk)
143{
144	stack_t stack;
145	struct thr_param *param;
146
147	/*
148	 * Here we copy out tid to two places, one for child and one
149	 * for parent, because pthread can create a detached thread,
150	 * if parent wants to safely access child tid, it has to provide
151	 * its storage, because child thread may exit quickly and
152	 * memory is freed before parent thread can access it.
153	 */
154	param = thunk;
155	if ((param->child_tid != NULL &&
156	    suword_lwpid(param->child_tid, td->td_tid)) ||
157	    (param->parent_tid != NULL &&
158	    suword_lwpid(param->parent_tid, td->td_tid)))
159		return (EFAULT);
160
161	/* Set up our machine context. */
162	stack.ss_sp = param->stack_base;
163	stack.ss_size = param->stack_size;
164	/* Set upcall address to user thread entry function. */
165	cpu_set_upcall_kse(td, param->start_func, param->arg, &stack);
166	/* Setup user TLS address and TLS pointer register. */
167	return (cpu_set_user_tls(td, param->tls_base));
168}
169
170int
171kern_thr_new(struct thread *td, struct thr_param *param)
172{
173	struct rtprio rtp, *rtpp;
174	int error;
175
176	rtpp = NULL;
177	if (param->rtp != 0) {
178		error = copyin(param->rtp, &rtp, sizeof(struct rtprio));
179		if (error)
180			return (error);
181		rtpp = &rtp;
182	}
183	return (thread_create(td, rtpp, thr_new_initthr, param));
184}
185
186int
187thread_create(struct thread *td, struct rtprio *rtp,
188    int (*initialize_thread)(struct thread *, void *), void *thunk)
189{
190	struct thread *newtd;
191	struct proc *p;
192	int error;
193
194	p = td->td_proc;
195
196	if (rtp != NULL) {
197		switch(rtp->type) {
198		case RTP_PRIO_REALTIME:
199		case RTP_PRIO_FIFO:
200			/* Only root can set scheduler policy */
201			if (priv_check(td, PRIV_SCHED_SETPOLICY) != 0)
202				return (EPERM);
203			if (rtp->prio > RTP_PRIO_MAX)
204				return (EINVAL);
205			break;
206		case RTP_PRIO_NORMAL:
207			rtp->prio = 0;
208			break;
209		default:
210			return (EINVAL);
211		}
212	}
213
214#ifdef RACCT
215	PROC_LOCK(td->td_proc);
216	error = racct_add(p, RACCT_NTHR, 1);
217	PROC_UNLOCK(td->td_proc);
218	if (error != 0)
219		return (EPROCLIM);
220#endif
221
222	/* Initialize our td */
223	error = kern_thr_alloc(p, 0, &newtd);
224	if (error)
225		goto fail;
226
227	cpu_set_upcall(newtd, td);
228
229	bzero(&newtd->td_startzero,
230	    __rangeof(struct thread, td_startzero, td_endzero));
231	newtd->td_su = NULL;
232	newtd->td_sleeptimo = 0;
233	bcopy(&td->td_startcopy, &newtd->td_startcopy,
234	    __rangeof(struct thread, td_startcopy, td_endcopy));
235	newtd->td_proc = td->td_proc;
236	newtd->td_ucred = crhold(td->td_ucred);
237	newtd->td_dbg_sc_code = td->td_dbg_sc_code;
238	newtd->td_dbg_sc_narg = td->td_dbg_sc_narg;
239
240	error = initialize_thread(newtd, thunk);
241	if (error != 0) {
242		thread_free(newtd);
243		crfree(td->td_ucred);
244		goto fail;
245	}
246
247	PROC_LOCK(td->td_proc);
248	td->td_proc->p_flag |= P_HADTHREADS;
249	thread_link(newtd, p);
250	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
251	thread_lock(td);
252	/* let the scheduler know about these things. */
253	sched_fork_thread(td, newtd);
254	thread_unlock(td);
255	if (P_SHOULDSTOP(p))
256		newtd->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
257	if (p->p_ptevents & PTRACE_LWP)
258		newtd->td_dbgflags |= TDB_BORN;
259	PROC_UNLOCK(p);
260
261	tidhash_add(newtd);
262
263	thread_lock(newtd);
264	if (rtp != NULL) {
265		if (!(td->td_pri_class == PRI_TIMESHARE &&
266		      rtp->type == RTP_PRIO_NORMAL)) {
267			rtp_to_pri(rtp, newtd);
268			sched_prio(newtd, newtd->td_user_pri);
269		} /* ignore timesharing class */
270	}
271	TD_SET_CAN_RUN(newtd);
272	sched_add(newtd, SRQ_BORING);
273	thread_unlock(newtd);
274
275	return (0);
276
277fail:
278#ifdef RACCT
279	if (racct_enable) {
280		PROC_LOCK(p);
281		racct_sub(p, RACCT_NTHR, 1);
282		PROC_UNLOCK(p);
283	}
284#endif
285	return (error);
286}
287
288int
289sys_thr_self(struct thread *td, struct thr_self_args *uap)
290    /* long *id */
291{
292	int error;
293
294	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
295	if (error == -1)
296		return (EFAULT);
297	return (0);
298}
299
300int
301sys_thr_exit(struct thread *td, struct thr_exit_args *uap)
302    /* long *state */
303{
304
305	/* Signal userland that it can free the stack. */
306	if ((void *)uap->state != NULL) {
307		suword_lwpid(uap->state, 1);
308		kern_umtx_wake(td, uap->state, INT_MAX, 0);
309	}
310
311	return (kern_thr_exit(td));
312}
313
314int
315kern_thr_exit(struct thread *td)
316{
317	struct proc *p;
318
319	p = td->td_proc;
320
321	/*
322	 * If all of the threads in a process call this routine to
323	 * exit (e.g. all threads call pthread_exit()), exactly one
324	 * thread should return to the caller to terminate the process
325	 * instead of the thread.
326	 *
327	 * Checking p_numthreads alone is not sufficient since threads
328	 * might be committed to terminating while the PROC_LOCK is
329	 * dropped in either ptracestop() or while removing this thread
330	 * from the tidhash.  Instead, the p_pendingexits field holds
331	 * the count of threads in either of those states and a thread
332	 * is considered the "last" thread if all of the other threads
333	 * in a process are already terminating.
334	 */
335	PROC_LOCK(p);
336	if (p->p_numthreads == p->p_pendingexits + 1) {
337		/*
338		 * Ignore attempts to shut down last thread in the
339		 * proc.  This will actually call _exit(2) in the
340		 * usermode trampoline when it returns.
341		 */
342		PROC_UNLOCK(p);
343		return (0);
344	}
345
346	p->p_pendingexits++;
347	td->td_dbgflags |= TDB_EXIT;
348	if (p->p_ptevents & PTRACE_LWP)
349		ptracestop(td, SIGTRAP, NULL);
350	PROC_UNLOCK(p);
351	tidhash_remove(td);
352	PROC_LOCK(p);
353	p->p_pendingexits--;
354
355	/*
356	 * The check above should prevent all other threads from this
357	 * process from exiting while the PROC_LOCK is dropped, so
358	 * there must be at least one other thread other than the
359	 * current thread.
360	 */
361	KASSERT(p->p_numthreads > 1, ("too few threads"));
362	racct_sub(p, RACCT_NTHR, 1);
363	tdsigcleanup(td);
364	umtx_thread_exit(td);
365	PROC_SLOCK(p);
366	thread_stopped(p);
367	thread_exit();
368	/* NOTREACHED */
369}
370
371int
372sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
373    /* long id, int sig */
374{
375	ksiginfo_t ksi;
376	struct thread *ttd;
377	struct proc *p;
378	int error;
379
380	p = td->td_proc;
381	ksiginfo_init(&ksi);
382	ksi.ksi_signo = uap->sig;
383	ksi.ksi_code = SI_LWP;
384	ksi.ksi_pid = p->p_pid;
385	ksi.ksi_uid = td->td_ucred->cr_ruid;
386	if (uap->id == -1) {
387		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
388			error = EINVAL;
389		} else {
390			error = ESRCH;
391			PROC_LOCK(p);
392			FOREACH_THREAD_IN_PROC(p, ttd) {
393				if (ttd != td) {
394					error = 0;
395					if (uap->sig == 0)
396						break;
397					tdksignal(ttd, uap->sig, &ksi);
398				}
399			}
400			PROC_UNLOCK(p);
401		}
402	} else {
403		error = 0;
404		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
405		if (ttd == NULL)
406			return (ESRCH);
407		if (uap->sig == 0)
408			;
409		else if (!_SIG_VALID(uap->sig))
410			error = EINVAL;
411		else
412			tdksignal(ttd, uap->sig, &ksi);
413		PROC_UNLOCK(ttd->td_proc);
414	}
415	return (error);
416}
417
418int
419sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
420    /* pid_t pid, long id, int sig */
421{
422	ksiginfo_t ksi;
423	struct thread *ttd;
424	struct proc *p;
425	int error;
426
427	AUDIT_ARG_SIGNUM(uap->sig);
428
429	ksiginfo_init(&ksi);
430	ksi.ksi_signo = uap->sig;
431	ksi.ksi_code = SI_LWP;
432	ksi.ksi_pid = td->td_proc->p_pid;
433	ksi.ksi_uid = td->td_ucred->cr_ruid;
434	if (uap->id == -1) {
435		if ((p = pfind(uap->pid)) == NULL)
436			return (ESRCH);
437		AUDIT_ARG_PROCESS(p);
438		error = p_cansignal(td, p, uap->sig);
439		if (error) {
440			PROC_UNLOCK(p);
441			return (error);
442		}
443		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
444			error = EINVAL;
445		} else {
446			error = ESRCH;
447			FOREACH_THREAD_IN_PROC(p, ttd) {
448				if (ttd != td) {
449					error = 0;
450					if (uap->sig == 0)
451						break;
452					tdksignal(ttd, uap->sig, &ksi);
453				}
454			}
455		}
456		PROC_UNLOCK(p);
457	} else {
458		ttd = tdfind((lwpid_t)uap->id, uap->pid);
459		if (ttd == NULL)
460			return (ESRCH);
461		p = ttd->td_proc;
462		AUDIT_ARG_PROCESS(p);
463		error = p_cansignal(td, p, uap->sig);
464		if (uap->sig == 0)
465			;
466		else if (!_SIG_VALID(uap->sig))
467			error = EINVAL;
468		else
469			tdksignal(ttd, uap->sig, &ksi);
470		PROC_UNLOCK(p);
471	}
472	return (error);
473}
474
475int
476sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
477	/* const struct timespec *timeout */
478{
479	struct timespec ts, *tsp;
480	int error;
481
482	tsp = NULL;
483	if (uap->timeout != NULL) {
484		error = umtx_copyin_timeout(uap->timeout, &ts);
485		if (error != 0)
486			return (error);
487		tsp = &ts;
488	}
489
490	return (kern_thr_suspend(td, tsp));
491}
492
493int
494kern_thr_suspend(struct thread *td, struct timespec *tsp)
495{
496	struct proc *p = td->td_proc;
497	struct timeval tv;
498	int error = 0;
499	int timo = 0;
500
501	if (td->td_pflags & TDP_WAKEUP) {
502		td->td_pflags &= ~TDP_WAKEUP;
503		return (0);
504	}
505
506	if (tsp != NULL) {
507		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
508			error = EWOULDBLOCK;
509		else {
510			TIMESPEC_TO_TIMEVAL(&tv, tsp);
511			timo = tvtohz(&tv);
512		}
513	}
514
515	PROC_LOCK(p);
516	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
517		error = msleep((void *)td, &p->p_mtx,
518			 PCATCH, "lthr", timo);
519
520	if (td->td_flags & TDF_THRWAKEUP) {
521		thread_lock(td);
522		td->td_flags &= ~TDF_THRWAKEUP;
523		thread_unlock(td);
524		PROC_UNLOCK(p);
525		return (0);
526	}
527	PROC_UNLOCK(p);
528	if (error == EWOULDBLOCK)
529		error = ETIMEDOUT;
530	else if (error == ERESTART) {
531		if (timo != 0)
532			error = EINTR;
533	}
534	return (error);
535}
536
537int
538sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
539	/* long id */
540{
541	struct proc *p;
542	struct thread *ttd;
543
544	if (uap->id == td->td_tid) {
545		td->td_pflags |= TDP_WAKEUP;
546		return (0);
547	}
548
549	p = td->td_proc;
550	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
551	if (ttd == NULL)
552		return (ESRCH);
553	thread_lock(ttd);
554	ttd->td_flags |= TDF_THRWAKEUP;
555	thread_unlock(ttd);
556	wakeup((void *)ttd);
557	PROC_UNLOCK(p);
558	return (0);
559}
560
561int
562sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
563{
564	struct proc *p;
565	char name[MAXCOMLEN + 1];
566	struct thread *ttd;
567	int error;
568
569	error = 0;
570	name[0] = '\0';
571	if (uap->name != NULL) {
572		error = copyinstr(uap->name, name, sizeof(name), NULL);
573		if (error == ENAMETOOLONG) {
574			error = copyin(uap->name, name, sizeof(name) - 1);
575			name[sizeof(name) - 1] = '\0';
576		}
577		if (error)
578			return (error);
579	}
580	p = td->td_proc;
581	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
582	if (ttd == NULL)
583		return (ESRCH);
584	strcpy(ttd->td_name, name);
585#ifdef KTR
586	sched_clear_tdname(ttd);
587#endif
588	PROC_UNLOCK(p);
589	return (error);
590}
591
592int
593kern_thr_alloc(struct proc *p, int pages, struct thread **ntd)
594{
595
596	/* Have race condition but it is cheap. */
597	if (p->p_numthreads >= max_threads_per_proc) {
598		++max_threads_hits;
599		return (EPROCLIM);
600	}
601
602	*ntd = thread_alloc(pages);
603	if (*ntd == NULL)
604		return (ENOMEM);
605
606	return (0);
607}
608