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