kern_thr.c revision 304017
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 304017 2016-08-12 19:43:06Z 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/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, "kern.threads.max_threads_per_proc hit count");
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
90/*
91 * System call interface.
92 */
93
94struct thr_create_initthr_args {
95	ucontext_t ctx;
96	long *tid;
97};
98
99static int
100thr_create_initthr(struct thread *td, void *thunk)
101{
102	struct thr_create_initthr_args *args;
103
104	/* Copy out the child tid. */
105	args = thunk;
106	if (args->tid != NULL && suword_lwpid(args->tid, td->td_tid))
107		return (EFAULT);
108
109	return (set_mcontext(td, &args->ctx.uc_mcontext));
110}
111
112int
113sys_thr_create(struct thread *td, struct thr_create_args *uap)
114    /* ucontext_t *ctx, long *id, int flags */
115{
116	struct thr_create_initthr_args args;
117	int error;
118
119	if ((error = copyin(uap->ctx, &args.ctx, sizeof(args.ctx))))
120		return (error);
121	args.tid = uap->id;
122	return (thread_create(td, NULL, thr_create_initthr, &args));
123}
124
125int
126sys_thr_new(struct thread *td, struct thr_new_args *uap)
127    /* struct thr_param * */
128{
129	struct thr_param param;
130	int error;
131
132	if (uap->param_size < 0 || uap->param_size > sizeof(param))
133		return (EINVAL);
134	bzero(&param, sizeof(param));
135	if ((error = copyin(uap->param, &param, uap->param_size)))
136		return (error);
137	return (kern_thr_new(td, &param));
138}
139
140static int
141thr_new_initthr(struct thread *td, void *thunk)
142{
143	stack_t stack;
144	struct thr_param *param;
145
146	/*
147	 * Here we copy out tid to two places, one for child and one
148	 * for parent, because pthread can create a detached thread,
149	 * if parent wants to safely access child tid, it has to provide
150	 * its storage, because child thread may exit quickly and
151	 * memory is freed before parent thread can access it.
152	 */
153	param = thunk;
154	if ((param->child_tid != NULL &&
155	    suword_lwpid(param->child_tid, td->td_tid)) ||
156	    (param->parent_tid != NULL &&
157	    suword_lwpid(param->parent_tid, td->td_tid)))
158		return (EFAULT);
159
160	/* Set up our machine context. */
161	stack.ss_sp = param->stack_base;
162	stack.ss_size = param->stack_size;
163	/* Set upcall address to user thread entry function. */
164	cpu_set_upcall_kse(td, param->start_func, param->arg, &stack);
165	/* Setup user TLS address and TLS pointer register. */
166	return (cpu_set_user_tls(td, param->tls_base));
167}
168
169int
170kern_thr_new(struct thread *td, struct thr_param *param)
171{
172	struct rtprio rtp, *rtpp;
173	int error;
174
175	rtpp = NULL;
176	if (param->rtp != 0) {
177		error = copyin(param->rtp, &rtp, sizeof(struct rtprio));
178		if (error)
179			return (error);
180		rtpp = &rtp;
181	}
182	return (thread_create(td, rtpp, thr_new_initthr, param));
183}
184
185int
186thread_create(struct thread *td, struct rtprio *rtp,
187    int (*initialize_thread)(struct thread *, void *), void *thunk)
188{
189	struct thread *newtd;
190	struct proc *p;
191	int error;
192
193	p = td->td_proc;
194
195	if (rtp != NULL) {
196		switch(rtp->type) {
197		case RTP_PRIO_REALTIME:
198		case RTP_PRIO_FIFO:
199			/* Only root can set scheduler policy */
200			if (priv_check(td, PRIV_SCHED_SETPOLICY) != 0)
201				return (EPERM);
202			if (rtp->prio > RTP_PRIO_MAX)
203				return (EINVAL);
204			break;
205		case RTP_PRIO_NORMAL:
206			rtp->prio = 0;
207			break;
208		default:
209			return (EINVAL);
210		}
211	}
212
213#ifdef RACCT
214	PROC_LOCK(td->td_proc);
215	error = racct_add(p, RACCT_NTHR, 1);
216	PROC_UNLOCK(td->td_proc);
217	if (error != 0)
218		return (EPROCLIM);
219#endif
220
221	/* Initialize our td */
222	error = kern_thr_alloc(p, 0, &newtd);
223	if (error)
224		goto fail;
225
226	cpu_set_upcall(newtd, td);
227
228	bzero(&newtd->td_startzero,
229	    __rangeof(struct thread, td_startzero, td_endzero));
230	newtd->td_su = NULL;
231	bcopy(&td->td_startcopy, &newtd->td_startcopy,
232	    __rangeof(struct thread, td_startcopy, td_endcopy));
233	newtd->td_proc = td->td_proc;
234	newtd->td_ucred = crhold(td->td_ucred);
235	newtd->td_dbg_sc_code = td->td_dbg_sc_code;
236	newtd->td_dbg_sc_narg = td->td_dbg_sc_narg;
237
238	error = initialize_thread(newtd, thunk);
239	if (error != 0) {
240		thread_free(newtd);
241		crfree(td->td_ucred);
242		goto fail;
243	}
244
245	PROC_LOCK(td->td_proc);
246	td->td_proc->p_flag |= P_HADTHREADS;
247	thread_link(newtd, p);
248	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
249	thread_lock(td);
250	/* let the scheduler know about these things. */
251	sched_fork_thread(td, newtd);
252	thread_unlock(td);
253	if (P_SHOULDSTOP(p))
254		newtd->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
255	if (p->p_flag2 & P2_LWP_EVENTS)
256		newtd->td_dbgflags |= TDB_BORN;
257	PROC_UNLOCK(p);
258
259	tidhash_add(newtd);
260
261	thread_lock(newtd);
262	if (rtp != NULL) {
263		if (!(td->td_pri_class == PRI_TIMESHARE &&
264		      rtp->type == RTP_PRIO_NORMAL)) {
265			rtp_to_pri(rtp, newtd);
266			sched_prio(newtd, newtd->td_user_pri);
267		} /* ignore timesharing class */
268	}
269	TD_SET_CAN_RUN(newtd);
270	sched_add(newtd, SRQ_BORING);
271	thread_unlock(newtd);
272
273	return (0);
274
275fail:
276#ifdef RACCT
277	if (racct_enable) {
278		PROC_LOCK(p);
279		racct_sub(p, RACCT_NTHR, 1);
280		PROC_UNLOCK(p);
281	}
282#endif
283	return (error);
284}
285
286int
287sys_thr_self(struct thread *td, struct thr_self_args *uap)
288    /* long *id */
289{
290	int error;
291
292	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
293	if (error == -1)
294		return (EFAULT);
295	return (0);
296}
297
298int
299sys_thr_exit(struct thread *td, struct thr_exit_args *uap)
300    /* long *state */
301{
302
303	/* Signal userland that it can free the stack. */
304	if ((void *)uap->state != NULL) {
305		suword_lwpid(uap->state, 1);
306		kern_umtx_wake(td, uap->state, INT_MAX, 0);
307	}
308
309	return (kern_thr_exit(td));
310}
311
312int
313kern_thr_exit(struct thread *td)
314{
315	struct proc *p;
316
317	p = td->td_proc;
318
319	/*
320	 * If all of the threads in a process call this routine to
321	 * exit (e.g. all threads call pthread_exit()), exactly one
322	 * thread should return to the caller to terminate the process
323	 * instead of the thread.
324	 *
325	 * Checking p_numthreads alone is not sufficient since threads
326	 * might be committed to terminating while the PROC_LOCK is
327	 * dropped in either ptracestop() or while removing this thread
328	 * from the tidhash.  Instead, the p_pendingexits field holds
329	 * the count of threads in either of those states and a thread
330	 * is considered the "last" thread if all of the other threads
331	 * in a process are already terminating.
332	 */
333	PROC_LOCK(p);
334	if (p->p_numthreads == p->p_pendingexits + 1) {
335		/*
336		 * Ignore attempts to shut down last thread in the
337		 * proc.  This will actually call _exit(2) in the
338		 * usermode trampoline when it returns.
339		 */
340		PROC_UNLOCK(p);
341		return (0);
342	}
343
344	p->p_pendingexits++;
345	td->td_dbgflags |= TDB_EXIT;
346	if (p->p_flag & P_TRACED && p->p_flag2 & P2_LWP_EVENTS)
347		ptracestop(td, SIGTRAP);
348	PROC_UNLOCK(p);
349	tidhash_remove(td);
350	PROC_LOCK(p);
351	p->p_pendingexits--;
352
353	/*
354	 * The check above should prevent all other threads from this
355	 * process from exiting while the PROC_LOCK is dropped, so
356	 * there must be at least one other thread other than the
357	 * current thread.
358	 */
359	KASSERT(p->p_numthreads > 1, ("too few threads"));
360	racct_sub(p, RACCT_NTHR, 1);
361	tdsigcleanup(td);
362	umtx_thread_exit(td);
363	PROC_SLOCK(p);
364	thread_stopped(p);
365	thread_exit();
366	/* NOTREACHED */
367}
368
369int
370sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
371    /* long id, int sig */
372{
373	ksiginfo_t ksi;
374	struct thread *ttd;
375	struct proc *p;
376	int error;
377
378	p = td->td_proc;
379	ksiginfo_init(&ksi);
380	ksi.ksi_signo = uap->sig;
381	ksi.ksi_code = SI_LWP;
382	ksi.ksi_pid = p->p_pid;
383	ksi.ksi_uid = td->td_ucred->cr_ruid;
384	if (uap->id == -1) {
385		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
386			error = EINVAL;
387		} else {
388			error = ESRCH;
389			PROC_LOCK(p);
390			FOREACH_THREAD_IN_PROC(p, ttd) {
391				if (ttd != td) {
392					error = 0;
393					if (uap->sig == 0)
394						break;
395					tdksignal(ttd, uap->sig, &ksi);
396				}
397			}
398			PROC_UNLOCK(p);
399		}
400	} else {
401		error = 0;
402		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
403		if (ttd == NULL)
404			return (ESRCH);
405		if (uap->sig == 0)
406			;
407		else if (!_SIG_VALID(uap->sig))
408			error = EINVAL;
409		else
410			tdksignal(ttd, uap->sig, &ksi);
411		PROC_UNLOCK(ttd->td_proc);
412	}
413	return (error);
414}
415
416int
417sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
418    /* pid_t pid, long id, int sig */
419{
420	ksiginfo_t ksi;
421	struct thread *ttd;
422	struct proc *p;
423	int error;
424
425	AUDIT_ARG_SIGNUM(uap->sig);
426
427	ksiginfo_init(&ksi);
428	ksi.ksi_signo = uap->sig;
429	ksi.ksi_code = SI_LWP;
430	ksi.ksi_pid = td->td_proc->p_pid;
431	ksi.ksi_uid = td->td_ucred->cr_ruid;
432	if (uap->id == -1) {
433		if ((p = pfind(uap->pid)) == NULL)
434			return (ESRCH);
435		AUDIT_ARG_PROCESS(p);
436		error = p_cansignal(td, p, uap->sig);
437		if (error) {
438			PROC_UNLOCK(p);
439			return (error);
440		}
441		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
442			error = EINVAL;
443		} else {
444			error = ESRCH;
445			FOREACH_THREAD_IN_PROC(p, ttd) {
446				if (ttd != td) {
447					error = 0;
448					if (uap->sig == 0)
449						break;
450					tdksignal(ttd, uap->sig, &ksi);
451				}
452			}
453		}
454		PROC_UNLOCK(p);
455	} else {
456		ttd = tdfind((lwpid_t)uap->id, uap->pid);
457		if (ttd == NULL)
458			return (ESRCH);
459		p = ttd->td_proc;
460		AUDIT_ARG_PROCESS(p);
461		error = p_cansignal(td, p, uap->sig);
462		if (uap->sig == 0)
463			;
464		else if (!_SIG_VALID(uap->sig))
465			error = EINVAL;
466		else
467			tdksignal(ttd, uap->sig, &ksi);
468		PROC_UNLOCK(p);
469	}
470	return (error);
471}
472
473int
474sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
475	/* const struct timespec *timeout */
476{
477	struct timespec ts, *tsp;
478	int error;
479
480	tsp = NULL;
481	if (uap->timeout != NULL) {
482		error = umtx_copyin_timeout(uap->timeout, &ts);
483		if (error != 0)
484			return (error);
485		tsp = &ts;
486	}
487
488	return (kern_thr_suspend(td, tsp));
489}
490
491int
492kern_thr_suspend(struct thread *td, struct timespec *tsp)
493{
494	struct proc *p = td->td_proc;
495	struct timeval tv;
496	int error = 0;
497	int timo = 0;
498
499	if (td->td_pflags & TDP_WAKEUP) {
500		td->td_pflags &= ~TDP_WAKEUP;
501		return (0);
502	}
503
504	if (tsp != NULL) {
505		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
506			error = EWOULDBLOCK;
507		else {
508			TIMESPEC_TO_TIMEVAL(&tv, tsp);
509			timo = tvtohz(&tv);
510		}
511	}
512
513	PROC_LOCK(p);
514	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
515		error = msleep((void *)td, &p->p_mtx,
516			 PCATCH, "lthr", timo);
517
518	if (td->td_flags & TDF_THRWAKEUP) {
519		thread_lock(td);
520		td->td_flags &= ~TDF_THRWAKEUP;
521		thread_unlock(td);
522		PROC_UNLOCK(p);
523		return (0);
524	}
525	PROC_UNLOCK(p);
526	if (error == EWOULDBLOCK)
527		error = ETIMEDOUT;
528	else if (error == ERESTART) {
529		if (timo != 0)
530			error = EINTR;
531	}
532	return (error);
533}
534
535int
536sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
537	/* long id */
538{
539	struct proc *p;
540	struct thread *ttd;
541
542	if (uap->id == td->td_tid) {
543		td->td_pflags |= TDP_WAKEUP;
544		return (0);
545	}
546
547	p = td->td_proc;
548	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
549	if (ttd == NULL)
550		return (ESRCH);
551	thread_lock(ttd);
552	ttd->td_flags |= TDF_THRWAKEUP;
553	thread_unlock(ttd);
554	wakeup((void *)ttd);
555	PROC_UNLOCK(p);
556	return (0);
557}
558
559int
560sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
561{
562	struct proc *p;
563	char name[MAXCOMLEN + 1];
564	struct thread *ttd;
565	int error;
566
567	error = 0;
568	name[0] = '\0';
569	if (uap->name != NULL) {
570		error = copyinstr(uap->name, name, sizeof(name),
571			NULL);
572		if (error)
573			return (error);
574	}
575	p = td->td_proc;
576	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
577	if (ttd == NULL)
578		return (ESRCH);
579	strcpy(ttd->td_name, name);
580#ifdef KTR
581	sched_clear_tdname(ttd);
582#endif
583	PROC_UNLOCK(p);
584	return (error);
585}
586
587int
588kern_thr_alloc(struct proc *p, int pages, struct thread **ntd)
589{
590
591	/* Have race condition but it is cheap. */
592	if (p->p_numthreads >= max_threads_per_proc) {
593		++max_threads_hits;
594		return (EPROCLIM);
595	}
596
597	*ntd = thread_alloc(pages);
598	if (*ntd == NULL)
599		return (ENOMEM);
600
601	return (0);
602}
603