xref: /freebsd/sys/kern/kern_thr.c (revision c6ec7d31830ab1c80edae95ad5e4b9dba10c47ac)
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$");
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 
61 static SYSCTL_NODE(_kern, OID_AUTO, threads, CTLFLAG_RW, 0,
62     "thread allocation");
63 
64 static int max_threads_per_proc = 1500;
65 SYSCTL_INT(_kern_threads, OID_AUTO, max_threads_per_proc, CTLFLAG_RW,
66     &max_threads_per_proc, 0, "Limit on threads per proc");
67 
68 static int max_threads_hits;
69 SYSCTL_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 
74 static inline int
75 suword_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 static 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  */
100 int
101 sys_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 
115 int
116 sys_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 
130 int
131 kern_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 
150 static int
151 create_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 	cpu_set_upcall(newtd, td);
205 
206 	/*
207 	 * Try the copyout as soon as we allocate the td so we don't
208 	 * have to tear things down in a failure case below.
209 	 * Here we copy out tid to two places, one for child and one
210 	 * for parent, because pthread can create a detached thread,
211 	 * if parent wants to safely access child tid, it has to provide
212 	 * its storage, because child thread may exit quickly and
213 	 * memory is freed before parent thread can access it.
214 	 */
215 	if ((child_tid != NULL &&
216 	    suword_lwpid(child_tid, newtd->td_tid)) ||
217 	    (parent_tid != NULL &&
218 	    suword_lwpid(parent_tid, newtd->td_tid))) {
219 		thread_free(newtd);
220 		error = EFAULT;
221 		goto fail;
222 	}
223 
224 	bzero(&newtd->td_startzero,
225 	    __rangeof(struct thread, td_startzero, td_endzero));
226 	bcopy(&td->td_startcopy, &newtd->td_startcopy,
227 	    __rangeof(struct thread, td_startcopy, td_endcopy));
228 	newtd->td_proc = td->td_proc;
229 	newtd->td_ucred = crhold(td->td_ucred);
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 	thread_link(newtd, p);
256 	bcopy(p->p_comm, newtd->td_name, sizeof(newtd->td_name));
257 	thread_lock(td);
258 	/* let the scheduler know about these things. */
259 	sched_fork_thread(td, newtd);
260 	thread_unlock(td);
261 	if (P_SHOULDSTOP(p))
262 		newtd->td_flags |= TDF_ASTPENDING | TDF_NEEDSUSPCHK;
263 	PROC_UNLOCK(p);
264 
265 	tidhash_add(newtd);
266 
267 	thread_lock(newtd);
268 	if (rtp != NULL) {
269 		if (!(td->td_pri_class == PRI_TIMESHARE &&
270 		      rtp->type == RTP_PRIO_NORMAL)) {
271 			rtp_to_pri(rtp, newtd);
272 			sched_prio(newtd, newtd->td_user_pri);
273 		} /* ignore timesharing class */
274 	}
275 	TD_SET_CAN_RUN(newtd);
276 	sched_add(newtd, SRQ_BORING);
277 	thread_unlock(newtd);
278 
279 	return (0);
280 
281 fail:
282 #ifdef RACCT
283 	PROC_LOCK(p);
284 	racct_sub(p, RACCT_NTHR, 1);
285 	PROC_UNLOCK(p);
286 #endif
287 	return (error);
288 }
289 
290 int
291 sys_thr_self(struct thread *td, struct thr_self_args *uap)
292     /* long *id */
293 {
294 	int error;
295 
296 	error = suword_lwpid(uap->id, (unsigned)td->td_tid);
297 	if (error == -1)
298 		return (EFAULT);
299 	return (0);
300 }
301 
302 int
303 sys_thr_exit(struct thread *td, struct thr_exit_args *uap)
304     /* long *state */
305 {
306 	struct proc *p;
307 
308 	p = td->td_proc;
309 
310 	/* Signal userland that it can free the stack. */
311 	if ((void *)uap->state != NULL) {
312 		suword_lwpid(uap->state, 1);
313 		kern_umtx_wake(td, uap->state, INT_MAX, 0);
314 	}
315 
316 	rw_wlock(&tidhash_lock);
317 
318 	PROC_LOCK(p);
319 
320 	/*
321 	 * Shutting down last thread in the proc.  This will actually
322 	 * call exit() in the trampoline when it returns.
323 	 */
324 	if (p->p_numthreads != 1) {
325 		racct_sub(p, RACCT_NTHR, 1);
326 		LIST_REMOVE(td, td_hash);
327 		rw_wunlock(&tidhash_lock);
328 		tdsigcleanup(td);
329 		PROC_SLOCK(p);
330 		thread_stopped(p);
331 		thread_exit();
332 		/* NOTREACHED */
333 	}
334 	PROC_UNLOCK(p);
335 	rw_wunlock(&tidhash_lock);
336 	return (0);
337 }
338 
339 int
340 sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
341     /* long id, int sig */
342 {
343 	ksiginfo_t ksi;
344 	struct thread *ttd;
345 	struct proc *p;
346 	int error;
347 
348 	p = td->td_proc;
349 	ksiginfo_init(&ksi);
350 	ksi.ksi_signo = uap->sig;
351 	ksi.ksi_code = SI_LWP;
352 	ksi.ksi_pid = p->p_pid;
353 	ksi.ksi_uid = td->td_ucred->cr_ruid;
354 	if (uap->id == -1) {
355 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
356 			error = EINVAL;
357 		} else {
358 			error = ESRCH;
359 			PROC_LOCK(p);
360 			FOREACH_THREAD_IN_PROC(p, ttd) {
361 				if (ttd != td) {
362 					error = 0;
363 					if (uap->sig == 0)
364 						break;
365 					tdksignal(ttd, uap->sig, &ksi);
366 				}
367 			}
368 			PROC_UNLOCK(p);
369 		}
370 	} else {
371 		error = 0;
372 		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
373 		if (ttd == NULL)
374 			return (ESRCH);
375 		if (uap->sig == 0)
376 			;
377 		else if (!_SIG_VALID(uap->sig))
378 			error = EINVAL;
379 		else
380 			tdksignal(ttd, uap->sig, &ksi);
381 		PROC_UNLOCK(ttd->td_proc);
382 	}
383 	return (error);
384 }
385 
386 int
387 sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
388     /* pid_t pid, long id, int sig */
389 {
390 	ksiginfo_t ksi;
391 	struct thread *ttd;
392 	struct proc *p;
393 	int error;
394 
395 	AUDIT_ARG_SIGNUM(uap->sig);
396 
397 	ksiginfo_init(&ksi);
398 	ksi.ksi_signo = uap->sig;
399 	ksi.ksi_code = SI_LWP;
400 	ksi.ksi_pid = td->td_proc->p_pid;
401 	ksi.ksi_uid = td->td_ucred->cr_ruid;
402 	if (uap->id == -1) {
403 		if ((p = pfind(uap->pid)) == NULL)
404 			return (ESRCH);
405 		AUDIT_ARG_PROCESS(p);
406 		error = p_cansignal(td, p, uap->sig);
407 		if (error) {
408 			PROC_UNLOCK(p);
409 			return (error);
410 		}
411 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
412 			error = EINVAL;
413 		} else {
414 			error = ESRCH;
415 			FOREACH_THREAD_IN_PROC(p, ttd) {
416 				if (ttd != td) {
417 					error = 0;
418 					if (uap->sig == 0)
419 						break;
420 					tdksignal(ttd, uap->sig, &ksi);
421 				}
422 			}
423 		}
424 		PROC_UNLOCK(p);
425 	} else {
426 		ttd = tdfind((lwpid_t)uap->id, uap->pid);
427 		if (ttd == NULL)
428 			return (ESRCH);
429 		p = ttd->td_proc;
430 		AUDIT_ARG_PROCESS(p);
431 		error = p_cansignal(td, p, uap->sig);
432 		if (uap->sig == 0)
433 			;
434 		else if (!_SIG_VALID(uap->sig))
435 			error = EINVAL;
436 		else
437 			tdksignal(ttd, uap->sig, &ksi);
438 		PROC_UNLOCK(p);
439 	}
440 	return (error);
441 }
442 
443 int
444 sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
445 	/* const struct timespec *timeout */
446 {
447 	struct timespec ts, *tsp;
448 	int error;
449 
450 	tsp = NULL;
451 	if (uap->timeout != NULL) {
452 		error = umtx_copyin_timeout(uap->timeout, &ts);
453 		if (error != 0)
454 			return (error);
455 		tsp = &ts;
456 	}
457 
458 	return (kern_thr_suspend(td, tsp));
459 }
460 
461 int
462 kern_thr_suspend(struct thread *td, struct timespec *tsp)
463 {
464 	struct proc *p = td->td_proc;
465 	struct timeval tv;
466 	int error = 0;
467 	int timo = 0;
468 
469 	if (td->td_pflags & TDP_WAKEUP) {
470 		td->td_pflags &= ~TDP_WAKEUP;
471 		return (0);
472 	}
473 
474 	if (tsp != NULL) {
475 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
476 			error = EWOULDBLOCK;
477 		else {
478 			TIMESPEC_TO_TIMEVAL(&tv, tsp);
479 			timo = tvtohz(&tv);
480 		}
481 	}
482 
483 	PROC_LOCK(p);
484 	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
485 		error = msleep((void *)td, &p->p_mtx,
486 			 PCATCH, "lthr", timo);
487 
488 	if (td->td_flags & TDF_THRWAKEUP) {
489 		thread_lock(td);
490 		td->td_flags &= ~TDF_THRWAKEUP;
491 		thread_unlock(td);
492 		PROC_UNLOCK(p);
493 		return (0);
494 	}
495 	PROC_UNLOCK(p);
496 	if (error == EWOULDBLOCK)
497 		error = ETIMEDOUT;
498 	else if (error == ERESTART) {
499 		if (timo != 0)
500 			error = EINTR;
501 	}
502 	return (error);
503 }
504 
505 int
506 sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
507 	/* long id */
508 {
509 	struct proc *p;
510 	struct thread *ttd;
511 
512 	if (uap->id == td->td_tid) {
513 		td->td_pflags |= TDP_WAKEUP;
514 		return (0);
515 	}
516 
517 	p = td->td_proc;
518 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
519 	if (ttd == NULL)
520 		return (ESRCH);
521 	thread_lock(ttd);
522 	ttd->td_flags |= TDF_THRWAKEUP;
523 	thread_unlock(ttd);
524 	wakeup((void *)ttd);
525 	PROC_UNLOCK(p);
526 	return (0);
527 }
528 
529 int
530 sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
531 {
532 	struct proc *p;
533 	char name[MAXCOMLEN + 1];
534 	struct thread *ttd;
535 	int error;
536 
537 	error = 0;
538 	name[0] = '\0';
539 	if (uap->name != NULL) {
540 		error = copyinstr(uap->name, name, sizeof(name),
541 			NULL);
542 		if (error)
543 			return (error);
544 	}
545 	p = td->td_proc;
546 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
547 	if (ttd == NULL)
548 		return (ESRCH);
549 	strcpy(ttd->td_name, name);
550 #ifdef KTR
551 	sched_clear_tdname(ttd);
552 #endif
553 	PROC_UNLOCK(p);
554 	return (error);
555 }
556