kern_thr.c revision 304188
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 304188 2016-08-15 21:10:41Z jhb $");
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	bcopy(&td->td_startcopy, &newtd->td_startcopy,
233	    __rangeof(struct thread, td_startcopy, td_endcopy));
234	newtd->td_proc = td->td_proc;
235	newtd->td_ucred = crhold(td->td_ucred);
236	newtd->td_dbg_sc_code = td->td_dbg_sc_code;
237	newtd->td_dbg_sc_narg = td->td_dbg_sc_narg;
238
239	error = initialize_thread(newtd, thunk);
240	if (error != 0) {
241		thread_free(newtd);
242		crfree(td->td_ucred);
243		goto fail;
244	}
245
246	PROC_LOCK(td->td_proc);
247	td->td_proc->p_flag |= P_HADTHREADS;
248	thread_link(newtd, p);
249	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
250	thread_lock(td);
251	/* let the scheduler know about these things. */
252	sched_fork_thread(td, newtd);
253	thread_unlock(td);
254	if (P_SHOULDSTOP(p))
255		newtd->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
256	if (p->p_ptevents & PTRACE_LWP)
257		newtd->td_dbgflags |= TDB_BORN;
258	PROC_UNLOCK(p);
259
260	tidhash_add(newtd);
261
262	thread_lock(newtd);
263	if (rtp != NULL) {
264		if (!(td->td_pri_class == PRI_TIMESHARE &&
265		      rtp->type == RTP_PRIO_NORMAL)) {
266			rtp_to_pri(rtp, newtd);
267			sched_prio(newtd, newtd->td_user_pri);
268		} /* ignore timesharing class */
269	}
270	TD_SET_CAN_RUN(newtd);
271	sched_add(newtd, SRQ_BORING);
272	thread_unlock(newtd);
273
274	return (0);
275
276fail:
277#ifdef RACCT
278	if (racct_enable) {
279		PROC_LOCK(p);
280		racct_sub(p, RACCT_NTHR, 1);
281		PROC_UNLOCK(p);
282	}
283#endif
284	return (error);
285}
286
287int
288sys_thr_self(struct thread *td, struct thr_self_args *uap)
289    /* long *id */
290{
291	int error;
292
293	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
294	if (error == -1)
295		return (EFAULT);
296	return (0);
297}
298
299int
300sys_thr_exit(struct thread *td, struct thr_exit_args *uap)
301    /* long *state */
302{
303
304	/* Signal userland that it can free the stack. */
305	if ((void *)uap->state != NULL) {
306		suword_lwpid(uap->state, 1);
307		kern_umtx_wake(td, uap->state, INT_MAX, 0);
308	}
309
310	return (kern_thr_exit(td));
311}
312
313int
314kern_thr_exit(struct thread *td)
315{
316	struct proc *p;
317
318	p = td->td_proc;
319
320	/*
321	 * If all of the threads in a process call this routine to
322	 * exit (e.g. all threads call pthread_exit()), exactly one
323	 * thread should return to the caller to terminate the process
324	 * instead of the thread.
325	 *
326	 * Checking p_numthreads alone is not sufficient since threads
327	 * might be committed to terminating while the PROC_LOCK is
328	 * dropped in either ptracestop() or while removing this thread
329	 * from the tidhash.  Instead, the p_pendingexits field holds
330	 * the count of threads in either of those states and a thread
331	 * is considered the "last" thread if all of the other threads
332	 * in a process are already terminating.
333	 */
334	PROC_LOCK(p);
335	if (p->p_numthreads == p->p_pendingexits + 1) {
336		/*
337		 * Ignore attempts to shut down last thread in the
338		 * proc.  This will actually call _exit(2) in the
339		 * usermode trampoline when it returns.
340		 */
341		PROC_UNLOCK(p);
342		return (0);
343	}
344
345	p->p_pendingexits++;
346	td->td_dbgflags |= TDB_EXIT;
347	if (p->p_ptevents & PTRACE_LWP)
348		ptracestop(td, SIGTRAP);
349	PROC_UNLOCK(p);
350	tidhash_remove(td);
351	PROC_LOCK(p);
352	p->p_pendingexits--;
353
354	/*
355	 * The check above should prevent all other threads from this
356	 * process from exiting while the PROC_LOCK is dropped, so
357	 * there must be at least one other thread other than the
358	 * current thread.
359	 */
360	KASSERT(p->p_numthreads > 1, ("too few threads"));
361	racct_sub(p, RACCT_NTHR, 1);
362	tdsigcleanup(td);
363	umtx_thread_exit(td);
364	PROC_SLOCK(p);
365	thread_stopped(p);
366	thread_exit();
367	/* NOTREACHED */
368}
369
370int
371sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
372    /* long id, int sig */
373{
374	ksiginfo_t ksi;
375	struct thread *ttd;
376	struct proc *p;
377	int error;
378
379	p = td->td_proc;
380	ksiginfo_init(&ksi);
381	ksi.ksi_signo = uap->sig;
382	ksi.ksi_code = SI_LWP;
383	ksi.ksi_pid = p->p_pid;
384	ksi.ksi_uid = td->td_ucred->cr_ruid;
385	if (uap->id == -1) {
386		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
387			error = EINVAL;
388		} else {
389			error = ESRCH;
390			PROC_LOCK(p);
391			FOREACH_THREAD_IN_PROC(p, ttd) {
392				if (ttd != td) {
393					error = 0;
394					if (uap->sig == 0)
395						break;
396					tdksignal(ttd, uap->sig, &ksi);
397				}
398			}
399			PROC_UNLOCK(p);
400		}
401	} else {
402		error = 0;
403		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
404		if (ttd == NULL)
405			return (ESRCH);
406		if (uap->sig == 0)
407			;
408		else if (!_SIG_VALID(uap->sig))
409			error = EINVAL;
410		else
411			tdksignal(ttd, uap->sig, &ksi);
412		PROC_UNLOCK(ttd->td_proc);
413	}
414	return (error);
415}
416
417int
418sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
419    /* pid_t pid, long id, int sig */
420{
421	ksiginfo_t ksi;
422	struct thread *ttd;
423	struct proc *p;
424	int error;
425
426	AUDIT_ARG_SIGNUM(uap->sig);
427
428	ksiginfo_init(&ksi);
429	ksi.ksi_signo = uap->sig;
430	ksi.ksi_code = SI_LWP;
431	ksi.ksi_pid = td->td_proc->p_pid;
432	ksi.ksi_uid = td->td_ucred->cr_ruid;
433	if (uap->id == -1) {
434		if ((p = pfind(uap->pid)) == NULL)
435			return (ESRCH);
436		AUDIT_ARG_PROCESS(p);
437		error = p_cansignal(td, p, uap->sig);
438		if (error) {
439			PROC_UNLOCK(p);
440			return (error);
441		}
442		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
443			error = EINVAL;
444		} else {
445			error = ESRCH;
446			FOREACH_THREAD_IN_PROC(p, ttd) {
447				if (ttd != td) {
448					error = 0;
449					if (uap->sig == 0)
450						break;
451					tdksignal(ttd, uap->sig, &ksi);
452				}
453			}
454		}
455		PROC_UNLOCK(p);
456	} else {
457		ttd = tdfind((lwpid_t)uap->id, uap->pid);
458		if (ttd == NULL)
459			return (ESRCH);
460		p = ttd->td_proc;
461		AUDIT_ARG_PROCESS(p);
462		error = p_cansignal(td, p, uap->sig);
463		if (uap->sig == 0)
464			;
465		else if (!_SIG_VALID(uap->sig))
466			error = EINVAL;
467		else
468			tdksignal(ttd, uap->sig, &ksi);
469		PROC_UNLOCK(p);
470	}
471	return (error);
472}
473
474int
475sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
476	/* const struct timespec *timeout */
477{
478	struct timespec ts, *tsp;
479	int error;
480
481	tsp = NULL;
482	if (uap->timeout != NULL) {
483		error = umtx_copyin_timeout(uap->timeout, &ts);
484		if (error != 0)
485			return (error);
486		tsp = &ts;
487	}
488
489	return (kern_thr_suspend(td, tsp));
490}
491
492int
493kern_thr_suspend(struct thread *td, struct timespec *tsp)
494{
495	struct proc *p = td->td_proc;
496	struct timeval tv;
497	int error = 0;
498	int timo = 0;
499
500	if (td->td_pflags & TDP_WAKEUP) {
501		td->td_pflags &= ~TDP_WAKEUP;
502		return (0);
503	}
504
505	if (tsp != NULL) {
506		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
507			error = EWOULDBLOCK;
508		else {
509			TIMESPEC_TO_TIMEVAL(&tv, tsp);
510			timo = tvtohz(&tv);
511		}
512	}
513
514	PROC_LOCK(p);
515	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
516		error = msleep((void *)td, &p->p_mtx,
517			 PCATCH, "lthr", timo);
518
519	if (td->td_flags & TDF_THRWAKEUP) {
520		thread_lock(td);
521		td->td_flags &= ~TDF_THRWAKEUP;
522		thread_unlock(td);
523		PROC_UNLOCK(p);
524		return (0);
525	}
526	PROC_UNLOCK(p);
527	if (error == EWOULDBLOCK)
528		error = ETIMEDOUT;
529	else if (error == ERESTART) {
530		if (timo != 0)
531			error = EINTR;
532	}
533	return (error);
534}
535
536int
537sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
538	/* long id */
539{
540	struct proc *p;
541	struct thread *ttd;
542
543	if (uap->id == td->td_tid) {
544		td->td_pflags |= TDP_WAKEUP;
545		return (0);
546	}
547
548	p = td->td_proc;
549	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
550	if (ttd == NULL)
551		return (ESRCH);
552	thread_lock(ttd);
553	ttd->td_flags |= TDF_THRWAKEUP;
554	thread_unlock(ttd);
555	wakeup((void *)ttd);
556	PROC_UNLOCK(p);
557	return (0);
558}
559
560int
561sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
562{
563	struct proc *p;
564	char name[MAXCOMLEN + 1];
565	struct thread *ttd;
566	int error;
567
568	error = 0;
569	name[0] = '\0';
570	if (uap->name != NULL) {
571		error = copyinstr(uap->name, name, sizeof(name),
572			NULL);
573		if (error)
574			return (error);
575	}
576	p = td->td_proc;
577	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
578	if (ttd == NULL)
579		return (ESRCH);
580	strcpy(ttd->td_name, name);
581#ifdef KTR
582	sched_clear_tdname(ttd);
583#endif
584	PROC_UNLOCK(p);
585	return (error);
586}
587
588int
589kern_thr_alloc(struct proc *p, int pages, struct thread **ntd)
590{
591
592	/* Have race condition but it is cheap. */
593	if (p->p_numthreads >= max_threads_per_proc) {
594		++max_threads_hits;
595		return (EPROCLIM);
596	}
597
598	*ntd = thread_alloc(pages);
599	if (*ntd == NULL)
600		return (ENOMEM);
601
602	return (0);
603}
604