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