kern_thr.c revision 227674
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: head/sys/kern/kern_thr.c 227674 2011-11-18 19:14:42Z pho $");
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/racct.h>
40#include <sys/resourcevar.h>
41#include <sys/rwlock.h>
42#include <sys/sched.h>
43#include <sys/sysctl.h>
44#include <sys/smp.h>
45#include <sys/syscallsubr.h>
46#include <sys/sysent.h>
47#include <sys/systm.h>
48#include <sys/sysproto.h>
49#include <sys/signalvar.h>
50#include <sys/sysctl.h>
51#include <sys/ucontext.h>
52#include <sys/thr.h>
53#include <sys/rtprio.h>
54#include <sys/umtx.h>
55#include <sys/limits.h>
56
57#include <machine/frame.h>
58
59#include <security/audit/audit.h>
60
61static SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0,
62    "thread allocation");
63
64static int max_threads_per_proc = 1500;
65SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
66	&max_threads_per_proc, 0, "Limit on threads per proc");
67
68static int max_threads_hits;
69SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_hits, CTLFLAG_RD,
70	&max_threads_hits, 0, "");
71
72#ifdef COMPAT_FREEBSD32
73
74static inline int
75suword_lwpid(void *addr, lwpid_t lwpid)
76{
77	int error;
78
79	if (SV_CURPROC_FLAG(SV_LP64))
80		error = suword(addr, lwpid);
81	else
82		error = suword32(addr, lwpid);
83	return (error);
84}
85
86#else
87#define suword_lwpid	suword
88#endif
89
90static int create_thread(struct thread *td, mcontext_t *ctx,
91			 void (*start_func)(void *), void *arg,
92			 char *stack_base, size_t stack_size,
93			 char *tls_base,
94			 long *child_tid, long *parent_tid,
95			 int flags, struct rtprio *rtp);
96
97/*
98 * System call interface.
99 */
100int
101sys_thr_create(struct thread *td, struct thr_create_args *uap)
102    /* ucontext_t *ctx, long *id, int flags */
103{
104	ucontext_t ctx;
105	int error;
106
107	if ((error = copyin(uap->ctx, &ctx, sizeof(ctx))))
108		return (error);
109
110	error = create_thread(td, &ctx.uc_mcontext, NULL, NULL,
111		NULL, 0, NULL, uap->id, NULL, uap->flags, NULL);
112	return (error);
113}
114
115int
116sys_thr_new(struct thread *td, struct thr_new_args *uap)
117    /* struct thr_param * */
118{
119	struct thr_param param;
120	int error;
121
122	if (uap->param_size < 0 || uap->param_size > sizeof(param))
123		return (EINVAL);
124	bzero(&param, sizeof(param));
125	if ((error = copyin(uap->param, &param, uap->param_size)))
126		return (error);
127	return (kern_thr_new(td, &param));
128}
129
130int
131kern_thr_new(struct thread *td, struct thr_param *param)
132{
133	struct rtprio rtp, *rtpp;
134	int error;
135
136	rtpp = NULL;
137	if (param->rtp != 0) {
138		error = copyin(param->rtp, &rtp, sizeof(struct rtprio));
139		if (error)
140			return (error);
141		rtpp = &rtp;
142	}
143	error = create_thread(td, NULL, param->start_func, param->arg,
144		param->stack_base, param->stack_size, param->tls_base,
145		param->child_tid, param->parent_tid, param->flags,
146		rtpp);
147	return (error);
148}
149
150static int
151create_thread(struct thread *td, mcontext_t *ctx,
152	    void (*start_func)(void *), void *arg,
153	    char *stack_base, size_t stack_size,
154	    char *tls_base,
155	    long *child_tid, long *parent_tid,
156	    int flags, struct rtprio *rtp)
157{
158	stack_t stack;
159	struct thread *newtd;
160	struct proc *p;
161	int error;
162
163	p = td->td_proc;
164
165	/* Have race condition but it is cheap. */
166	if (p->p_numthreads >= max_threads_per_proc) {
167		++max_threads_hits;
168		return (EPROCLIM);
169	}
170
171	if (rtp != NULL) {
172		switch(rtp->type) {
173		case RTP_PRIO_REALTIME:
174		case RTP_PRIO_FIFO:
175			/* Only root can set scheduler policy */
176			if (priv_check(td, PRIV_SCHED_SETPOLICY) != 0)
177				return (EPERM);
178			if (rtp->prio > RTP_PRIO_MAX)
179				return (EINVAL);
180			break;
181		case RTP_PRIO_NORMAL:
182			rtp->prio = 0;
183			break;
184		default:
185			return (EINVAL);
186		}
187	}
188
189#ifdef RACCT
190	PROC_LOCK(td->td_proc);
191	error = racct_add(p, RACCT_NTHR, 1);
192	PROC_UNLOCK(td->td_proc);
193	if (error != 0)
194		return (EPROCLIM);
195#endif
196
197	/* Initialize our td */
198	newtd = thread_alloc(0);
199	if (newtd == NULL) {
200		error = ENOMEM;
201		goto fail;
202	}
203
204	/*
205	 * Try the copyout as soon as we allocate the td so we don't
206	 * have to tear things down in a failure case below.
207	 * Here we copy out tid to two places, one for child and one
208	 * for parent, because pthread can create a detached thread,
209	 * if parent wants to safely access child tid, it has to provide
210	 * its storage, because child thread may exit quickly and
211	 * memory is freed before parent thread can access it.
212	 */
213	if ((child_tid != NULL &&
214	    suword_lwpid(child_tid, newtd->td_tid)) ||
215	    (parent_tid != NULL &&
216	    suword_lwpid(parent_tid, newtd->td_tid))) {
217		thread_free(newtd);
218		error = EFAULT;
219		goto fail;
220	}
221
222	bzero(&newtd->td_startzero,
223	    __rangeof(struct thread, td_startzero, td_endzero));
224	bcopy(&td->td_startcopy, &newtd->td_startcopy,
225	    __rangeof(struct thread, td_startcopy, td_endcopy));
226	newtd->td_proc = td->td_proc;
227	newtd->td_ucred = crhold(td->td_ucred);
228
229	cpu_set_upcall(newtd, td);
230
231	if (ctx != NULL) { /* old way to set user context */
232		error = set_mcontext(newtd, ctx);
233		if (error != 0) {
234			thread_free(newtd);
235			crfree(td->td_ucred);
236			goto fail;
237		}
238	} else {
239		/* Set up our machine context. */
240		stack.ss_sp = stack_base;
241		stack.ss_size = stack_size;
242		/* Set upcall address to user thread entry function. */
243		cpu_set_upcall_kse(newtd, start_func, arg, &stack);
244		/* Setup user TLS address and TLS pointer register. */
245		error = cpu_set_user_tls(newtd, tls_base);
246		if (error != 0) {
247			thread_free(newtd);
248			crfree(td->td_ucred);
249			goto fail;
250		}
251	}
252
253	PROC_LOCK(td->td_proc);
254	td->td_proc->p_flag |= P_HADTHREADS;
255	newtd->td_sigmask = td->td_sigmask;
256	thread_link(newtd, p);
257	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
258	thread_lock(td);
259	/* let the scheduler know about these things. */
260	sched_fork_thread(td, newtd);
261	thread_unlock(td);
262	if (P_SHOULDSTOP(p))
263		newtd->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
264	PROC_UNLOCK(p);
265
266	tidhash_add(newtd);
267
268	thread_lock(newtd);
269	if (rtp != NULL) {
270		if (!(td->td_pri_class == PRI_TIMESHARE &&
271		      rtp->type == RTP_PRIO_NORMAL)) {
272			rtp_to_pri(rtp, newtd);
273			sched_prio(newtd, newtd->td_user_pri);
274		} /* ignore timesharing class */
275	}
276	TD_SET_CAN_RUN(newtd);
277	sched_add(newtd, SRQ_BORING);
278	thread_unlock(newtd);
279
280	return (0);
281
282fail:
283#ifdef RACCT
284	PROC_LOCK(p);
285	racct_sub(p, RACCT_NTHR, 1);
286	PROC_UNLOCK(p);
287#endif
288	return (error);
289}
290
291int
292sys_thr_self(struct thread *td, struct thr_self_args *uap)
293    /* long *id */
294{
295	int error;
296
297	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
298	if (error == -1)
299		return (EFAULT);
300	return (0);
301}
302
303int
304sys_thr_exit(struct thread *td, struct thr_exit_args *uap)
305    /* long *state */
306{
307	struct proc *p;
308
309	p = td->td_proc;
310
311	/* Signal userland that it can free the stack. */
312	if ((void *)uap->state != NULL) {
313		suword_lwpid(uap->state, 1);
314		kern_umtx_wake(td, uap->state, INT_MAX, 0);
315	}
316
317	rw_wlock(&tidhash_lock);
318
319	PROC_LOCK(p);
320	racct_sub(p, RACCT_NTHR, 1);
321
322	/*
323	 * Shutting down last thread in the proc.  This will actually
324	 * call exit() in the trampoline when it returns.
325	 */
326	if (p->p_numthreads != 1) {
327		LIST_REMOVE(td, td_hash);
328		rw_wunlock(&tidhash_lock);
329		tdsigcleanup(td);
330		PROC_SLOCK(p);
331		thread_stopped(p);
332		thread_exit();
333		/* NOTREACHED */
334	}
335	PROC_UNLOCK(p);
336	rw_wunlock(&tidhash_lock);
337	return (0);
338}
339
340int
341sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
342    /* long id, int sig */
343{
344	ksiginfo_t ksi;
345	struct thread *ttd;
346	struct proc *p;
347	int error;
348
349	p = td->td_proc;
350	ksiginfo_init(&ksi);
351	ksi.ksi_signo = uap->sig;
352	ksi.ksi_code = SI_LWP;
353	ksi.ksi_pid = p->p_pid;
354	ksi.ksi_uid = td->td_ucred->cr_ruid;
355	if (uap->id == -1) {
356		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
357			error = EINVAL;
358		} else {
359			error = ESRCH;
360			PROC_LOCK(p);
361			FOREACH_THREAD_IN_PROC(p, ttd) {
362				if (ttd != td) {
363					error = 0;
364					if (uap->sig == 0)
365						break;
366					tdksignal(ttd, uap->sig, &ksi);
367				}
368			}
369			PROC_UNLOCK(p);
370		}
371	} else {
372		error = 0;
373		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
374		if (ttd == NULL)
375			return (ESRCH);
376		if (uap->sig == 0)
377			;
378		else if (!_SIG_VALID(uap->sig))
379			error = EINVAL;
380		else
381			tdksignal(ttd, uap->sig, &ksi);
382		PROC_UNLOCK(ttd->td_proc);
383	}
384	return (error);
385}
386
387int
388sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
389    /* pid_t pid, long id, int sig */
390{
391	ksiginfo_t ksi;
392	struct thread *ttd;
393	struct proc *p;
394	int error;
395
396	AUDIT_ARG_SIGNUM(uap->sig);
397
398	ksiginfo_init(&ksi);
399	ksi.ksi_signo = uap->sig;
400	ksi.ksi_code = SI_LWP;
401	ksi.ksi_pid = td->td_proc->p_pid;
402	ksi.ksi_uid = td->td_ucred->cr_ruid;
403	if (uap->id == -1) {
404		if ((p = pfind(uap->pid)) == NULL)
405			return (ESRCH);
406		AUDIT_ARG_PROCESS(p);
407		error = p_cansignal(td, p, uap->sig);
408		if (error) {
409			PROC_UNLOCK(p);
410			return (error);
411		}
412		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
413			error = EINVAL;
414		} else {
415			error = ESRCH;
416			FOREACH_THREAD_IN_PROC(p, ttd) {
417				if (ttd != td) {
418					error = 0;
419					if (uap->sig == 0)
420						break;
421					tdksignal(ttd, uap->sig, &ksi);
422				}
423			}
424		}
425		PROC_UNLOCK(p);
426	} else {
427		ttd = tdfind((lwpid_t)uap->id, uap->pid);
428		if (ttd == NULL)
429			return (ESRCH);
430		p = ttd->td_proc;
431		AUDIT_ARG_PROCESS(p);
432		error = p_cansignal(td, p, uap->sig);
433		if (uap->sig == 0)
434			;
435		else if (!_SIG_VALID(uap->sig))
436			error = EINVAL;
437		else
438			tdksignal(ttd, uap->sig, &ksi);
439		PROC_UNLOCK(p);
440	}
441	return (error);
442}
443
444int
445sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
446	/* const struct timespec *timeout */
447{
448	struct timespec ts, *tsp;
449	int error;
450
451	tsp = NULL;
452	if (uap->timeout != NULL) {
453		error = copyin((const void *)uap->timeout, (void *)&ts,
454		    sizeof(struct timespec));
455		if (error != 0)
456			return (error);
457		tsp = &ts;
458	}
459
460	return (kern_thr_suspend(td, tsp));
461}
462
463int
464kern_thr_suspend(struct thread *td, struct timespec *tsp)
465{
466	struct proc *p = td->td_proc;
467	struct timeval tv;
468	int error = 0;
469	int timo = 0;
470
471	if (td->td_pflags & TDP_WAKEUP) {
472		td->td_pflags &= ~TDP_WAKEUP;
473		return (0);
474	}
475
476	if (tsp != NULL) {
477		if (tsp->tv_sec < 0 || tsp->tv_nsec < 0 ||
478		    tsp->tv_nsec > 1000000000)
479			return (EINVAL);
480		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
481			error = EWOULDBLOCK;
482		else {
483			TIMESPEC_TO_TIMEVAL(&tv, tsp);
484			timo = tvtohz(&tv);
485		}
486	}
487
488	PROC_LOCK(p);
489	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
490		error = msleep((void *)td, &p->p_mtx,
491			 PCATCH, "lthr", timo);
492
493	if (td->td_flags & TDF_THRWAKEUP) {
494		thread_lock(td);
495		td->td_flags &= ~TDF_THRWAKEUP;
496		thread_unlock(td);
497		PROC_UNLOCK(p);
498		return (0);
499	}
500	PROC_UNLOCK(p);
501	if (error == EWOULDBLOCK)
502		error = ETIMEDOUT;
503	else if (error == ERESTART) {
504		if (timo != 0)
505			error = EINTR;
506	}
507	return (error);
508}
509
510int
511sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
512	/* long id */
513{
514	struct proc *p;
515	struct thread *ttd;
516
517	if (uap->id == td->td_tid) {
518		td->td_pflags |= TDP_WAKEUP;
519		return (0);
520	}
521
522	p = td->td_proc;
523	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
524	if (ttd == NULL)
525		return (ESRCH);
526	thread_lock(ttd);
527	ttd->td_flags |= TDF_THRWAKEUP;
528	thread_unlock(ttd);
529	wakeup((void *)ttd);
530	PROC_UNLOCK(p);
531	return (0);
532}
533
534int
535sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
536{
537	struct proc *p;
538	char name[MAXCOMLEN + 1];
539	struct thread *ttd;
540	int error;
541
542	error = 0;
543	name[0] = '\0';
544	if (uap->name != NULL) {
545		error = copyinstr(uap->name, name, sizeof(name),
546			NULL);
547		if (error)
548			return (error);
549	}
550	p = td->td_proc;
551	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
552	if (ttd == NULL)
553		return (ESRCH);
554	strcpy(ttd->td_name, name);
555	PROC_UNLOCK(p);
556	return (error);
557}
558