xref: /freebsd/sys/kern/kern_thr.c (revision 18849b5da0c5eaa88500b457be05b038813b51b1)
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 	umtx_thread_exit(td);
312 
313 	/* Signal userland that it can free the stack. */
314 	if ((void *)uap->state != NULL) {
315 		suword_lwpid(uap->state, 1);
316 		kern_umtx_wake(td, uap->state, INT_MAX, 0);
317 	}
318 
319 	return (kern_thr_exit(td));
320 }
321 
322 int
323 kern_thr_exit(struct thread *td)
324 {
325 	struct proc *p;
326 
327 	p = td->td_proc;
328 
329 	/*
330 	 * If all of the threads in a process call this routine to
331 	 * exit (e.g. all threads call pthread_exit()), exactly one
332 	 * thread should return to the caller to terminate the process
333 	 * instead of the thread.
334 	 *
335 	 * Checking p_numthreads alone is not sufficient since threads
336 	 * might be committed to terminating while the PROC_LOCK is
337 	 * dropped in either ptracestop() or while removing this thread
338 	 * from the tidhash.  Instead, the p_pendingexits field holds
339 	 * the count of threads in either of those states and a thread
340 	 * is considered the "last" thread if all of the other threads
341 	 * in a process are already terminating.
342 	 */
343 	PROC_LOCK(p);
344 	if (p->p_numthreads == p->p_pendingexits + 1) {
345 		/*
346 		 * Ignore attempts to shut down last thread in the
347 		 * proc.  This will actually call _exit(2) in the
348 		 * usermode trampoline when it returns.
349 		 */
350 		PROC_UNLOCK(p);
351 		return (0);
352 	}
353 
354 	p->p_pendingexits++;
355 	td->td_dbgflags |= TDB_EXIT;
356 	if (p->p_flag & P_TRACED && p->p_flag2 & P2_LWP_EVENTS)
357 		ptracestop(td, SIGTRAP);
358 	PROC_UNLOCK(p);
359 	tidhash_remove(td);
360 	PROC_LOCK(p);
361 	p->p_pendingexits--;
362 
363 	/*
364 	 * The check above should prevent all other threads from this
365 	 * process from exiting while the PROC_LOCK is dropped, so
366 	 * there must be at least one other thread other than the
367 	 * current thread.
368 	 */
369 	KASSERT(p->p_numthreads > 1, ("too few threads"));
370 	racct_sub(p, RACCT_NTHR, 1);
371 	tdsigcleanup(td);
372 	PROC_SLOCK(p);
373 	thread_stopped(p);
374 	thread_exit();
375 	/* NOTREACHED */
376 }
377 
378 int
379 sys_thr_kill(struct thread *td, struct thr_kill_args *uap)
380     /* long id, int sig */
381 {
382 	ksiginfo_t ksi;
383 	struct thread *ttd;
384 	struct proc *p;
385 	int error;
386 
387 	p = td->td_proc;
388 	ksiginfo_init(&ksi);
389 	ksi.ksi_signo = uap->sig;
390 	ksi.ksi_code = SI_LWP;
391 	ksi.ksi_pid = p->p_pid;
392 	ksi.ksi_uid = td->td_ucred->cr_ruid;
393 	if (uap->id == -1) {
394 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
395 			error = EINVAL;
396 		} else {
397 			error = ESRCH;
398 			PROC_LOCK(p);
399 			FOREACH_THREAD_IN_PROC(p, ttd) {
400 				if (ttd != td) {
401 					error = 0;
402 					if (uap->sig == 0)
403 						break;
404 					tdksignal(ttd, uap->sig, &ksi);
405 				}
406 			}
407 			PROC_UNLOCK(p);
408 		}
409 	} else {
410 		error = 0;
411 		ttd = tdfind((lwpid_t)uap->id, p->p_pid);
412 		if (ttd == NULL)
413 			return (ESRCH);
414 		if (uap->sig == 0)
415 			;
416 		else if (!_SIG_VALID(uap->sig))
417 			error = EINVAL;
418 		else
419 			tdksignal(ttd, uap->sig, &ksi);
420 		PROC_UNLOCK(ttd->td_proc);
421 	}
422 	return (error);
423 }
424 
425 int
426 sys_thr_kill2(struct thread *td, struct thr_kill2_args *uap)
427     /* pid_t pid, long id, int sig */
428 {
429 	ksiginfo_t ksi;
430 	struct thread *ttd;
431 	struct proc *p;
432 	int error;
433 
434 	AUDIT_ARG_SIGNUM(uap->sig);
435 
436 	ksiginfo_init(&ksi);
437 	ksi.ksi_signo = uap->sig;
438 	ksi.ksi_code = SI_LWP;
439 	ksi.ksi_pid = td->td_proc->p_pid;
440 	ksi.ksi_uid = td->td_ucred->cr_ruid;
441 	if (uap->id == -1) {
442 		if ((p = pfind(uap->pid)) == NULL)
443 			return (ESRCH);
444 		AUDIT_ARG_PROCESS(p);
445 		error = p_cansignal(td, p, uap->sig);
446 		if (error) {
447 			PROC_UNLOCK(p);
448 			return (error);
449 		}
450 		if (uap->sig != 0 && !_SIG_VALID(uap->sig)) {
451 			error = EINVAL;
452 		} else {
453 			error = ESRCH;
454 			FOREACH_THREAD_IN_PROC(p, ttd) {
455 				if (ttd != td) {
456 					error = 0;
457 					if (uap->sig == 0)
458 						break;
459 					tdksignal(ttd, uap->sig, &ksi);
460 				}
461 			}
462 		}
463 		PROC_UNLOCK(p);
464 	} else {
465 		ttd = tdfind((lwpid_t)uap->id, uap->pid);
466 		if (ttd == NULL)
467 			return (ESRCH);
468 		p = ttd->td_proc;
469 		AUDIT_ARG_PROCESS(p);
470 		error = p_cansignal(td, p, uap->sig);
471 		if (uap->sig == 0)
472 			;
473 		else if (!_SIG_VALID(uap->sig))
474 			error = EINVAL;
475 		else
476 			tdksignal(ttd, uap->sig, &ksi);
477 		PROC_UNLOCK(p);
478 	}
479 	return (error);
480 }
481 
482 int
483 sys_thr_suspend(struct thread *td, struct thr_suspend_args *uap)
484 	/* const struct timespec *timeout */
485 {
486 	struct timespec ts, *tsp;
487 	int error;
488 
489 	tsp = NULL;
490 	if (uap->timeout != NULL) {
491 		error = umtx_copyin_timeout(uap->timeout, &ts);
492 		if (error != 0)
493 			return (error);
494 		tsp = &ts;
495 	}
496 
497 	return (kern_thr_suspend(td, tsp));
498 }
499 
500 int
501 kern_thr_suspend(struct thread *td, struct timespec *tsp)
502 {
503 	struct proc *p = td->td_proc;
504 	struct timeval tv;
505 	int error = 0;
506 	int timo = 0;
507 
508 	if (td->td_pflags & TDP_WAKEUP) {
509 		td->td_pflags &= ~TDP_WAKEUP;
510 		return (0);
511 	}
512 
513 	if (tsp != NULL) {
514 		if (tsp->tv_sec == 0 && tsp->tv_nsec == 0)
515 			error = EWOULDBLOCK;
516 		else {
517 			TIMESPEC_TO_TIMEVAL(&tv, tsp);
518 			timo = tvtohz(&tv);
519 		}
520 	}
521 
522 	PROC_LOCK(p);
523 	if (error == 0 && (td->td_flags & TDF_THRWAKEUP) == 0)
524 		error = msleep((void *)td, &p->p_mtx,
525 			 PCATCH, "lthr", timo);
526 
527 	if (td->td_flags & TDF_THRWAKEUP) {
528 		thread_lock(td);
529 		td->td_flags &= ~TDF_THRWAKEUP;
530 		thread_unlock(td);
531 		PROC_UNLOCK(p);
532 		return (0);
533 	}
534 	PROC_UNLOCK(p);
535 	if (error == EWOULDBLOCK)
536 		error = ETIMEDOUT;
537 	else if (error == ERESTART) {
538 		if (timo != 0)
539 			error = EINTR;
540 	}
541 	return (error);
542 }
543 
544 int
545 sys_thr_wake(struct thread *td, struct thr_wake_args *uap)
546 	/* long id */
547 {
548 	struct proc *p;
549 	struct thread *ttd;
550 
551 	if (uap->id == td->td_tid) {
552 		td->td_pflags |= TDP_WAKEUP;
553 		return (0);
554 	}
555 
556 	p = td->td_proc;
557 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
558 	if (ttd == NULL)
559 		return (ESRCH);
560 	thread_lock(ttd);
561 	ttd->td_flags |= TDF_THRWAKEUP;
562 	thread_unlock(ttd);
563 	wakeup((void *)ttd);
564 	PROC_UNLOCK(p);
565 	return (0);
566 }
567 
568 int
569 sys_thr_set_name(struct thread *td, struct thr_set_name_args *uap)
570 {
571 	struct proc *p;
572 	char name[MAXCOMLEN + 1];
573 	struct thread *ttd;
574 	int error;
575 
576 	error = 0;
577 	name[0] = '\0';
578 	if (uap->name != NULL) {
579 		error = copyinstr(uap->name, name, sizeof(name),
580 			NULL);
581 		if (error)
582 			return (error);
583 	}
584 	p = td->td_proc;
585 	ttd = tdfind((lwpid_t)uap->id, p->p_pid);
586 	if (ttd == NULL)
587 		return (ESRCH);
588 	strcpy(ttd->td_name, name);
589 #ifdef KTR
590 	sched_clear_tdname(ttd);
591 #endif
592 	PROC_UNLOCK(p);
593 	return (error);
594 }
595 
596 int
597 kern_thr_alloc(struct proc *p, int pages, struct thread **ntd)
598 {
599 
600 	/* Have race condition but it is cheap. */
601 	if (p->p_numthreads >= max_threads_per_proc) {
602 		++max_threads_hits;
603 		return (EPROCLIM);
604 	}
605 
606 	*ntd = thread_alloc(pages);
607 	if (*ntd == NULL)
608 		return (ENOMEM);
609 
610 	return (0);
611 }
612