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