ts.c revision 2712:f74a135872bc
1284990Scy/*
2284990Scy * CDDL HEADER START
3284990Scy *
4284990Scy * The contents of this file are subject to the terms of the
5284990Scy * Common Development and Distribution License (the "License").
6284990Scy * You may not use this file except in compliance with the License.
7284990Scy *
8284990Scy * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9284990Scy * or http://www.opensolaris.org/os/licensing.
10284990Scy * See the License for the specific language governing permissions
11284990Scy * and limitations under the License.
12284990Scy *
13284990Scy * When distributing Covered Code, include this CDDL HEADER in each
14284990Scy * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15284990Scy * If applicable, add the following below this CDDL HEADER, with the
16284990Scy * fields enclosed by brackets "[]" replaced with your own identifying
17284990Scy * information: Portions Copyright [yyyy] [name of copyright owner]
18284990Scy *
19284990Scy * CDDL HEADER END
20284990Scy */
21284990Scy
22284990Scy/*
23284990Scy * Copyright 2006 Sun Microsystems, Inc.  All rights reserved.
24284990Scy * Use is subject to license terms.
25290000Sglebius */
26290000Sglebius
27290000Sglebius/*	Copyright (c) 1984, 1986, 1987, 1988, 1989 AT&T	*/
28290000Sglebius/*	  All Rights Reserved  	*/
29284990Scy
30284990Scy
31284990Scy#pragma ident	"%Z%%M%	%I%	%E% SMI"	/* from SVr4.0 1.23 */
32284990Scy
33284990Scy#include <sys/types.h>
34284990Scy#include <sys/param.h>
35284990Scy#include <sys/sysmacros.h>
36284990Scy#include <sys/cred.h>
37284990Scy#include <sys/proc.h>
38284990Scy#include <sys/session.h>
39290000Sglebius#include <sys/strsubr.h>
40290000Sglebius#include <sys/signal.h>
41284990Scy#include <sys/user.h>
42284990Scy#include <sys/priocntl.h>
43284990Scy#include <sys/class.h>
44284990Scy#include <sys/disp.h>
45284990Scy#include <sys/procset.h>
46290000Sglebius#include <sys/debug.h>
47284990Scy#include <sys/ts.h>
48284990Scy#include <sys/tspriocntl.h>
49284990Scy#include <sys/iapriocntl.h>
50284990Scy#include <sys/kmem.h>
51284990Scy#include <sys/errno.h>
52284990Scy#include <sys/cpuvar.h>
53284990Scy#include <sys/systm.h>		/* for lbolt */
54284990Scy#include <sys/vtrace.h>
55290000Sglebius#include <sys/vmsystm.h>
56290000Sglebius#include <sys/schedctl.h>
57284990Scy#include <sys/tnf_probe.h>
58284990Scy#include <sys/atomic.h>
59284990Scy#include <sys/policy.h>
60#include <sys/sdt.h>
61#include <sys/cpupart.h>
62
63#include <vm/rm.h>
64#include <vm/seg_kmem.h>
65#include <sys/modctl.h>
66
67static pri_t ts_init(id_t, int, classfuncs_t **);
68
69static struct sclass csw = {
70	"TS",
71	ts_init,
72	0
73};
74
75static struct modlsched modlsched = {
76	&mod_schedops, "time sharing sched class", &csw
77};
78
79static struct modlinkage modlinkage = {
80	MODREV_1, (void *)&modlsched, NULL
81};
82
83int
84_init()
85{
86	return (mod_install(&modlinkage));
87}
88
89int
90_fini()
91{
92	return (EBUSY);		/* don't remove TS for now */
93}
94
95int
96_info(struct modinfo *modinfop)
97{
98	return (mod_info(&modlinkage, modinfop));
99}
100
101/*
102 * Class specific code for the time-sharing class
103 */
104
105
106/*
107 * Extern declarations for variables defined in the ts master file
108 */
109#define	TSMAXUPRI 60
110
111pri_t	ts_maxupri = TSMAXUPRI;	/* max time-sharing user priority */
112pri_t	ts_maxumdpri;		/* maximum user mode ts priority */
113
114pri_t	ia_maxupri = IAMAXUPRI;	/* max interactive user priority */
115pri_t	ia_boost = IA_BOOST;	/* boost value for interactive */
116
117tsdpent_t  *ts_dptbl;	/* time-sharing disp parameter table */
118pri_t	*ts_kmdpris;	/* array of global pris used by ts procs when */
119			/*  sleeping or running in kernel after sleep */
120
121static id_t ia_cid;
122
123int ts_sleep_promote = 1;
124
125#define	tsmedumdpri	(ts_maxumdpri >> 1)
126
127#define	TS_NEWUMDPRI(tspp) \
128{ \
129	pri_t pri; \
130	pri = (tspp)->ts_cpupri + (tspp)->ts_upri + (tspp)->ts_boost; \
131	if (pri > ts_maxumdpri) \
132		(tspp)->ts_umdpri = ts_maxumdpri; \
133	else if (pri < 0) \
134		(tspp)->ts_umdpri = 0; \
135	else \
136		(tspp)->ts_umdpri = pri; \
137	ASSERT((tspp)->ts_umdpri >= 0 && (tspp)->ts_umdpri <= ts_maxumdpri); \
138}
139
140/*
141 * The tsproc_t structures are kept in an array of circular doubly linked
142 * lists.  A hash on the thread pointer is used to determine which list
143 * each thread should be placed.  Each list has a dummy "head" which is
144 * never removed, so the list is never empty.  ts_update traverses these
145 * lists to update the priorities of threads that have been waiting on
146 * the run queue.
147 */
148
149#define	TS_LISTS 16		/* number of lists, must be power of 2 */
150
151/* hash function, argument is a thread pointer */
152#define	TS_LIST_HASH(tp)	(((uintptr_t)(tp) >> 9) & (TS_LISTS - 1))
153
154/* iterate to the next list */
155#define	TS_LIST_NEXT(i)		(((i) + 1) & (TS_LISTS - 1))
156
157/*
158 * Insert thread into the appropriate tsproc list.
159 */
160#define	TS_LIST_INSERT(tspp)				\
161{							\
162	int index = TS_LIST_HASH(tspp->ts_tp);		\
163	kmutex_t *lockp = &ts_list_lock[index];		\
164	tsproc_t *headp = &ts_plisthead[index];		\
165	mutex_enter(lockp);				\
166	tspp->ts_next = headp->ts_next;			\
167	tspp->ts_prev = headp;				\
168	headp->ts_next->ts_prev = tspp;			\
169	headp->ts_next = tspp;				\
170	mutex_exit(lockp);				\
171}
172
173/*
174 * Remove thread from tsproc list.
175 */
176#define	TS_LIST_DELETE(tspp)				\
177{							\
178	int index = TS_LIST_HASH(tspp->ts_tp);		\
179	kmutex_t *lockp = &ts_list_lock[index];		\
180	mutex_enter(lockp);				\
181	tspp->ts_prev->ts_next = tspp->ts_next;		\
182	tspp->ts_next->ts_prev = tspp->ts_prev;		\
183	mutex_exit(lockp);				\
184}
185
186
187static int	ts_admin(caddr_t, cred_t *);
188static int	ts_enterclass(kthread_t *, id_t, void *, cred_t *, void *);
189static int	ts_fork(kthread_t *, kthread_t *, void *);
190static int	ts_getclinfo(void *);
191static int	ts_getclpri(pcpri_t *);
192static int	ts_parmsin(void *);
193static int	ts_parmsout(void *, pc_vaparms_t *);
194static int	ts_vaparmsin(void *, pc_vaparms_t *);
195static int	ts_vaparmsout(void *, pc_vaparms_t *);
196static int	ts_parmsset(kthread_t *, void *, id_t, cred_t *);
197static int	ts_donice(kthread_t *, cred_t *, int, int *);
198static void	ts_exitclass(void *);
199static int	ts_canexit(kthread_t *, cred_t *);
200static void	ts_forkret(kthread_t *, kthread_t *);
201static void	ts_nullsys();
202static void	ts_parmsget(kthread_t *, void *);
203static void	ts_preempt(kthread_t *);
204static void	ts_setrun(kthread_t *);
205static void	ts_sleep(kthread_t *);
206static pri_t	ts_swapin(kthread_t *, int);
207static pri_t	ts_swapout(kthread_t *, int);
208static void	ts_tick(kthread_t *);
209static void	ts_trapret(kthread_t *);
210static void	ts_update(void *);
211static int	ts_update_list(int);
212static void	ts_wakeup(kthread_t *);
213static pri_t	ts_globpri(kthread_t *);
214static void	ts_yield(kthread_t *);
215extern tsdpent_t *ts_getdptbl(void);
216extern pri_t	*ts_getkmdpris(void);
217extern pri_t	td_getmaxumdpri(void);
218static int	ts_alloc(void **, int);
219static void	ts_free(void *);
220
221pri_t		ia_init(id_t, int, classfuncs_t **);
222static int	ia_getclinfo(void *);
223static int	ia_parmsin(void *);
224static int	ia_vaparmsin(void *, pc_vaparms_t *);
225static int	ia_vaparmsout(void *, pc_vaparms_t *);
226static int	ia_parmsset(kthread_t *, void *, id_t, cred_t *);
227static void	ia_parmsget(kthread_t *, void *);
228static void	ia_set_process_group(pid_t, pid_t, pid_t);
229
230static void	ts_change_priority(kthread_t *, tsproc_t *);
231
232extern pri_t	ts_maxkmdpri;	/* maximum kernel mode ts priority */
233static pri_t	ts_maxglobpri;	/* maximum global priority used by ts class */
234static kmutex_t	ts_dptblock;	/* protects time sharing dispatch table */
235static kmutex_t	ts_list_lock[TS_LISTS];	/* protects tsproc lists */
236static tsproc_t	ts_plisthead[TS_LISTS];	/* dummy tsproc at head of lists */
237
238static gid_t	IA_gid = 0;
239
240static struct classfuncs ts_classfuncs = {
241	/* class functions */
242	ts_admin,
243	ts_getclinfo,
244	ts_parmsin,
245	ts_parmsout,
246	ts_vaparmsin,
247	ts_vaparmsout,
248	ts_getclpri,
249	ts_alloc,
250	ts_free,
251
252	/* thread functions */
253	ts_enterclass,
254	ts_exitclass,
255	ts_canexit,
256	ts_fork,
257	ts_forkret,
258	ts_parmsget,
259	ts_parmsset,
260	ts_nullsys,	/* stop */
261	ts_nullsys,	/* exit */
262	ts_nullsys,	/* active */
263	ts_nullsys,	/* inactive */
264	ts_swapin,
265	ts_swapout,
266	ts_trapret,
267	ts_preempt,
268	ts_setrun,
269	ts_sleep,
270	ts_tick,
271	ts_wakeup,
272	ts_donice,
273	ts_globpri,
274	ts_nullsys,	/* set_process_group */
275	ts_yield,
276};
277
278/*
279 * ia_classfuncs is used for interactive class threads; IA threads are stored
280 * on the same class list as TS threads, and most of the class functions are
281 * identical, but a few have different enough functionality to require their
282 * own functions.
283 */
284static struct classfuncs ia_classfuncs = {
285	/* class functions */
286	ts_admin,
287	ia_getclinfo,
288	ia_parmsin,
289	ts_parmsout,
290	ia_vaparmsin,
291	ia_vaparmsout,
292	ts_getclpri,
293	ts_alloc,
294	ts_free,
295
296	/* thread functions */
297	ts_enterclass,
298	ts_exitclass,
299	ts_canexit,
300	ts_fork,
301	ts_forkret,
302	ia_parmsget,
303	ia_parmsset,
304	ts_nullsys,	/* stop */
305	ts_nullsys,	/* exit */
306	ts_nullsys,	/* active */
307	ts_nullsys,	/* inactive */
308	ts_swapin,
309	ts_swapout,
310	ts_trapret,
311	ts_preempt,
312	ts_setrun,
313	ts_sleep,
314	ts_tick,
315	ts_wakeup,
316	ts_donice,
317	ts_globpri,
318	ia_set_process_group,
319	ts_yield,
320};
321
322
323/*
324 * Time sharing class initialization.  Called by dispinit() at boot time.
325 * We can ignore the clparmsz argument since we know that the smallest
326 * possible parameter buffer is big enough for us.
327 */
328/* ARGSUSED */
329static pri_t
330ts_init(id_t cid, int clparmsz, classfuncs_t **clfuncspp)
331{
332	int i;
333	extern pri_t ts_getmaxumdpri(void);
334
335	ts_dptbl = ts_getdptbl();
336	ts_kmdpris = ts_getkmdpris();
337	ts_maxumdpri = ts_getmaxumdpri();
338	ts_maxglobpri = MAX(ts_kmdpris[0], ts_dptbl[ts_maxumdpri].ts_globpri);
339
340	/*
341	 * Initialize the tsproc lists.
342	 */
343	for (i = 0; i < TS_LISTS; i++) {
344		ts_plisthead[i].ts_next = ts_plisthead[i].ts_prev =
345		    &ts_plisthead[i];
346	}
347
348	/*
349	 * We're required to return a pointer to our classfuncs
350	 * structure and the highest global priority value we use.
351	 */
352	*clfuncspp = &ts_classfuncs;
353	return (ts_maxglobpri);
354}
355
356
357/*
358 * Interactive class scheduler initialization
359 */
360/* ARGSUSED */
361pri_t
362ia_init(id_t cid, int clparmsz, classfuncs_t **clfuncspp)
363{
364	/*
365	 * We're required to return a pointer to our classfuncs
366	 * structure and the highest global priority value we use.
367	 */
368	ia_cid = cid;
369	*clfuncspp = &ia_classfuncs;
370	return (ts_maxglobpri);
371}
372
373
374/*
375 * Get or reset the ts_dptbl values per the user's request.
376 */
377static int
378ts_admin(caddr_t uaddr, cred_t *reqpcredp)
379{
380	tsadmin_t	tsadmin;
381	tsdpent_t	*tmpdpp;
382	int		userdpsz;
383	int		i;
384	size_t		tsdpsz;
385
386	if (get_udatamodel() == DATAMODEL_NATIVE) {
387		if (copyin(uaddr, &tsadmin, sizeof (tsadmin_t)))
388			return (EFAULT);
389	}
390#ifdef _SYSCALL32_IMPL
391	else {
392		/* get tsadmin struct from ILP32 caller */
393		tsadmin32_t tsadmin32;
394		if (copyin(uaddr, &tsadmin32, sizeof (tsadmin32_t)))
395			return (EFAULT);
396		tsadmin.ts_dpents =
397		    (struct tsdpent *)(uintptr_t)tsadmin32.ts_dpents;
398		tsadmin.ts_ndpents = tsadmin32.ts_ndpents;
399		tsadmin.ts_cmd = tsadmin32.ts_cmd;
400	}
401#endif /* _SYSCALL32_IMPL */
402
403	tsdpsz = (ts_maxumdpri + 1) * sizeof (tsdpent_t);
404
405	switch (tsadmin.ts_cmd) {
406	case TS_GETDPSIZE:
407		tsadmin.ts_ndpents = ts_maxumdpri + 1;
408
409		if (get_udatamodel() == DATAMODEL_NATIVE) {
410			if (copyout(&tsadmin, uaddr, sizeof (tsadmin_t)))
411				return (EFAULT);
412		}
413#ifdef _SYSCALL32_IMPL
414		else {
415			/* return tsadmin struct to ILP32 caller */
416			tsadmin32_t tsadmin32;
417			tsadmin32.ts_dpents =
418			    (caddr32_t)(uintptr_t)tsadmin.ts_dpents;
419			tsadmin32.ts_ndpents = tsadmin.ts_ndpents;
420			tsadmin32.ts_cmd = tsadmin.ts_cmd;
421			if (copyout(&tsadmin32, uaddr, sizeof (tsadmin32_t)))
422				return (EFAULT);
423		}
424#endif /* _SYSCALL32_IMPL */
425		break;
426
427	case TS_GETDPTBL:
428		userdpsz = MIN(tsadmin.ts_ndpents * sizeof (tsdpent_t),
429		    tsdpsz);
430		if (copyout(ts_dptbl, tsadmin.ts_dpents, userdpsz))
431			return (EFAULT);
432
433		tsadmin.ts_ndpents = userdpsz / sizeof (tsdpent_t);
434
435		if (get_udatamodel() == DATAMODEL_NATIVE) {
436			if (copyout(&tsadmin, uaddr, sizeof (tsadmin_t)))
437				return (EFAULT);
438		}
439#ifdef _SYSCALL32_IMPL
440		else {
441			/* return tsadmin struct to ILP32 callers */
442			tsadmin32_t tsadmin32;
443			tsadmin32.ts_dpents =
444			    (caddr32_t)(uintptr_t)tsadmin.ts_dpents;
445			tsadmin32.ts_ndpents = tsadmin.ts_ndpents;
446			tsadmin32.ts_cmd = tsadmin.ts_cmd;
447			if (copyout(&tsadmin32, uaddr, sizeof (tsadmin32_t)))
448				return (EFAULT);
449		}
450#endif /* _SYSCALL32_IMPL */
451		break;
452
453	case TS_SETDPTBL:
454		/*
455		 * We require that the requesting process has sufficient
456		 * priveleges.  We also require that the table supplied by
457		 * the user exactly match the current ts_dptbl in size.
458		 */
459		if (secpolicy_dispadm(reqpcredp) != 0)
460			return (EPERM);
461
462		if (tsadmin.ts_ndpents * sizeof (tsdpent_t) != tsdpsz) {
463			return (EINVAL);
464		}
465
466		/*
467		 * We read the user supplied table into a temporary buffer
468		 * where it is validated before being copied over the
469		 * ts_dptbl.
470		 */
471		tmpdpp = kmem_alloc(tsdpsz, KM_SLEEP);
472		if (copyin((caddr_t)tsadmin.ts_dpents, (caddr_t)tmpdpp,
473		    tsdpsz)) {
474			kmem_free(tmpdpp, tsdpsz);
475			return (EFAULT);
476		}
477		for (i = 0; i < tsadmin.ts_ndpents; i++) {
478
479			/*
480			 * Validate the user supplied values.  All we are doing
481			 * here is verifying that the values are within their
482			 * allowable ranges and will not panic the system.  We
483			 * make no attempt to ensure that the resulting
484			 * configuration makes sense or results in reasonable
485			 * performance.
486			 */
487			if (tmpdpp[i].ts_quantum <= 0) {
488				kmem_free(tmpdpp, tsdpsz);
489				return (EINVAL);
490			}
491			if (tmpdpp[i].ts_tqexp > ts_maxumdpri ||
492			    tmpdpp[i].ts_tqexp < 0) {
493				kmem_free(tmpdpp, tsdpsz);
494				return (EINVAL);
495			}
496			if (tmpdpp[i].ts_slpret > ts_maxumdpri ||
497			    tmpdpp[i].ts_slpret < 0) {
498				kmem_free(tmpdpp, tsdpsz);
499				return (EINVAL);
500			}
501			if (tmpdpp[i].ts_maxwait < 0) {
502				kmem_free(tmpdpp, tsdpsz);
503				return (EINVAL);
504			}
505			if (tmpdpp[i].ts_lwait > ts_maxumdpri ||
506			    tmpdpp[i].ts_lwait < 0) {
507				kmem_free(tmpdpp, tsdpsz);
508				return (EINVAL);
509			}
510		}
511
512		/*
513		 * Copy the user supplied values over the current ts_dptbl
514		 * values.  The ts_globpri member is read-only so we don't
515		 * overwrite it.
516		 */
517		mutex_enter(&ts_dptblock);
518		for (i = 0; i < tsadmin.ts_ndpents; i++) {
519			ts_dptbl[i].ts_quantum = tmpdpp[i].ts_quantum;
520			ts_dptbl[i].ts_tqexp = tmpdpp[i].ts_tqexp;
521			ts_dptbl[i].ts_slpret = tmpdpp[i].ts_slpret;
522			ts_dptbl[i].ts_maxwait = tmpdpp[i].ts_maxwait;
523			ts_dptbl[i].ts_lwait = tmpdpp[i].ts_lwait;
524		}
525		mutex_exit(&ts_dptblock);
526		kmem_free(tmpdpp, tsdpsz);
527		break;
528
529	default:
530		return (EINVAL);
531	}
532	return (0);
533}
534
535
536/*
537 * Allocate a time-sharing class specific thread structure and
538 * initialize it with the parameters supplied. Also move the thread
539 * to specified time-sharing priority.
540 */
541static int
542ts_enterclass(kthread_t *t, id_t cid, void *parmsp,
543	cred_t *reqpcredp, void *bufp)
544{
545	tsparms_t	*tsparmsp = (tsparms_t *)parmsp;
546	tsproc_t	*tspp;
547	pri_t		reqtsuprilim;
548	pri_t		reqtsupri;
549	static uint32_t	tspexists = 0;	/* set on first occurrence of */
550					/*   a time-sharing process */
551
552	tspp = (tsproc_t *)bufp;
553	ASSERT(tspp != NULL);
554
555	/*
556	 * Initialize the tsproc structure.
557	 */
558	tspp->ts_cpupri = tsmedumdpri;
559	if (cid == ia_cid) {
560		/*
561		 * Check to make sure caller is either privileged or the
562		 * window system.  When the window system is converted
563		 * to using privileges, the second check can go away.
564		 */
565		if (reqpcredp != NULL && !groupmember(IA_gid, reqpcredp) &&
566		    secpolicy_setpriority(reqpcredp) != 0)
567			return (EPERM);
568		/*
569		 * Belongs to IA "class", so set appropriate flags.
570		 * Mark as 'on' so it will not be a swap victim
571		 * while forking.
572		 */
573		tspp->ts_flags = TSIA | TSIASET;
574		tspp->ts_boost = ia_boost;
575	} else {
576		tspp->ts_flags = 0;
577		tspp->ts_boost = 0;
578	}
579
580	if (tsparmsp == NULL) {
581		/*
582		 * Use default values.
583		 */
584		tspp->ts_uprilim = tspp->ts_upri = 0;
585		tspp->ts_nice = NZERO;
586	} else {
587		/*
588		 * Use supplied values.
589		 */
590		if (tsparmsp->ts_uprilim == TS_NOCHANGE)
591			reqtsuprilim = 0;
592		else {
593			if (tsparmsp->ts_uprilim > 0 &&
594			    secpolicy_setpriority(reqpcredp) != 0)
595				return (EPERM);
596			reqtsuprilim = tsparmsp->ts_uprilim;
597		}
598
599		if (tsparmsp->ts_upri == TS_NOCHANGE) {
600			reqtsupri = reqtsuprilim;
601		} else {
602			if (tsparmsp->ts_upri > 0 &&
603			    secpolicy_setpriority(reqpcredp) != 0)
604				return (EPERM);
605			/*
606			 * Set the user priority to the requested value
607			 * or the upri limit, whichever is lower.
608			 */
609			reqtsupri = tsparmsp->ts_upri;
610			if (reqtsupri > reqtsuprilim)
611				reqtsupri = reqtsuprilim;
612		}
613
614
615		tspp->ts_uprilim = reqtsuprilim;
616		tspp->ts_upri = reqtsupri;
617		tspp->ts_nice = NZERO - (NZERO * reqtsupri)
618			/ ts_maxupri;
619	}
620	TS_NEWUMDPRI(tspp);
621
622	tspp->ts_dispwait = 0;
623	tspp->ts_timeleft = ts_dptbl[tspp->ts_cpupri].ts_quantum;
624	tspp->ts_tp = t;
625
626	/*
627	 * Reset priority. Process goes to a "user mode" priority
628	 * here regardless of whether or not it has slept since
629	 * entering the kernel.
630	 */
631	thread_lock(t);			/* get dispatcher lock on thread */
632	t->t_clfuncs = &(sclass[cid].cl_funcs->thread);
633	t->t_cid = cid;
634	t->t_cldata = (void *)tspp;
635	t->t_schedflag &= ~TS_RUNQMATCH;
636	ts_change_priority(t, tspp);
637	thread_unlock(t);
638
639	/*
640	 * Link new structure into tsproc list.
641	 */
642	TS_LIST_INSERT(tspp);
643
644	/*
645	 * If this is the first time-sharing thread to occur since
646	 * boot we set up the initial call to ts_update() here.
647	 * Use an atomic compare-and-swap since that's easier and
648	 * faster than a mutex (but check with an ordinary load first
649	 * since most of the time this will already be done).
650	 */
651	if (tspexists == 0 && cas32(&tspexists, 0, 1) == 0)
652		(void) timeout(ts_update, NULL, hz);
653
654	return (0);
655}
656
657
658/*
659 * Free tsproc structure of thread.
660 */
661static void
662ts_exitclass(void *procp)
663{
664	tsproc_t *tspp = (tsproc_t *)procp;
665
666	/* Remove tsproc_t structure from list */
667	TS_LIST_DELETE(tspp);
668	kmem_free(tspp, sizeof (tsproc_t));
669}
670
671/* ARGSUSED */
672static int
673ts_canexit(kthread_t *t, cred_t *cred)
674{
675	/*
676	 * A thread can always leave a TS/IA class
677	 */
678	return (0);
679}
680
681static int
682ts_fork(kthread_t *t, kthread_t *ct, void *bufp)
683{
684	tsproc_t	*ptspp;		/* ptr to parent's tsproc structure */
685	tsproc_t	*ctspp;		/* ptr to child's tsproc structure */
686
687	ASSERT(MUTEX_HELD(&ttoproc(t)->p_lock));
688
689	ctspp = (tsproc_t *)bufp;
690	ASSERT(ctspp != NULL);
691	ptspp = (tsproc_t *)t->t_cldata;
692	/*
693	 * Initialize child's tsproc structure.
694	 */
695	thread_lock(t);
696	ctspp->ts_timeleft = ts_dptbl[ptspp->ts_cpupri].ts_quantum;
697	ctspp->ts_cpupri = ptspp->ts_cpupri;
698	ctspp->ts_boost = ptspp->ts_boost;
699	ctspp->ts_uprilim = ptspp->ts_uprilim;
700	ctspp->ts_upri = ptspp->ts_upri;
701	TS_NEWUMDPRI(ctspp);
702	ctspp->ts_nice = ptspp->ts_nice;
703	ctspp->ts_dispwait = 0;
704	ctspp->ts_flags = ptspp->ts_flags & ~(TSKPRI | TSBACKQ | TSRESTORE);
705	ctspp->ts_tp = ct;
706	thread_unlock(t);
707
708	/*
709	 * Link new structure into tsproc list.
710	 */
711	ct->t_cldata = (void *)ctspp;
712	TS_LIST_INSERT(ctspp);
713	return (0);
714}
715
716
717/*
718 * Child is placed at back of dispatcher queue and parent gives
719 * up processor so that the child runs first after the fork.
720 * This allows the child immediately execing to break the multiple
721 * use of copy on write pages with no disk home. The parent will
722 * get to steal them back rather than uselessly copying them.
723 */
724static void
725ts_forkret(kthread_t *t, kthread_t *ct)
726{
727	proc_t	*pp = ttoproc(t);
728	proc_t	*cp = ttoproc(ct);
729	tsproc_t *tspp;
730
731	ASSERT(t == curthread);
732	ASSERT(MUTEX_HELD(&pidlock));
733
734	/*
735	 * Grab the child's p_lock before dropping pidlock to ensure
736	 * the process does not disappear before we set it running.
737	 */
738	mutex_enter(&cp->p_lock);
739	mutex_exit(&pidlock);
740	continuelwps(cp);
741	mutex_exit(&cp->p_lock);
742
743	mutex_enter(&pp->p_lock);
744	continuelwps(pp);
745	mutex_exit(&pp->p_lock);
746
747	thread_lock(t);
748	tspp = (tsproc_t *)(t->t_cldata);
749	tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_tqexp;
750	TS_NEWUMDPRI(tspp);
751	tspp->ts_timeleft = ts_dptbl[tspp->ts_cpupri].ts_quantum;
752	tspp->ts_dispwait = 0;
753	t->t_pri = ts_dptbl[tspp->ts_umdpri].ts_globpri;
754	ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
755	tspp->ts_flags &= ~TSKPRI;
756	THREAD_TRANSITION(t);
757	ts_setrun(t);
758	thread_unlock(t);
759
760	swtch();
761}
762
763
764/*
765 * Get information about the time-sharing class into the buffer
766 * pointed to by tsinfop. The maximum configured user priority
767 * is the only information we supply.  ts_getclinfo() is called
768 * for TS threads, and ia_getclinfo() is called for IA threads.
769 */
770static int
771ts_getclinfo(void *infop)
772{
773	tsinfo_t *tsinfop = (tsinfo_t *)infop;
774	tsinfop->ts_maxupri = ts_maxupri;
775	return (0);
776}
777
778static int
779ia_getclinfo(void *infop)
780{
781	iainfo_t *iainfop = (iainfo_t *)infop;
782	iainfop->ia_maxupri = ia_maxupri;
783	return (0);
784}
785
786
787/*
788 * Return the global scheduling priority ranges for the timesharing
789 * class in pcpri_t structure.
790 */
791static int
792ts_getclpri(pcpri_t *pcprip)
793{
794	pcprip->pc_clpmax = ts_dptbl[ts_maxumdpri].ts_globpri;
795	pcprip->pc_clpmin = ts_dptbl[0].ts_globpri;
796	return (0);
797}
798
799
800static void
801ts_nullsys()
802{}
803
804
805/*
806 * Get the time-sharing parameters of the thread pointed to by
807 * tsprocp into the buffer pointed to by tsparmsp.  ts_parmsget()
808 * is called for TS threads, and ia_parmsget() is called for IA
809 * threads.
810 */
811static void
812ts_parmsget(kthread_t *t, void *parmsp)
813{
814	tsproc_t *tspp = (tsproc_t *)t->t_cldata;
815	tsparms_t *tsparmsp = (tsparms_t *)parmsp;
816
817	tsparmsp->ts_uprilim = tspp->ts_uprilim;
818	tsparmsp->ts_upri = tspp->ts_upri;
819}
820
821static void
822ia_parmsget(kthread_t *t, void *parmsp)
823{
824	tsproc_t *tspp = (tsproc_t *)t->t_cldata;
825	iaparms_t *iaparmsp = (iaparms_t *)parmsp;
826
827	iaparmsp->ia_uprilim = tspp->ts_uprilim;
828	iaparmsp->ia_upri = tspp->ts_upri;
829	if (tspp->ts_flags & TSIASET)
830		iaparmsp->ia_mode = IA_SET_INTERACTIVE;
831	else
832		iaparmsp->ia_mode = IA_INTERACTIVE_OFF;
833	iaparmsp->ia_nice = tspp->ts_nice;
834}
835
836
837/*
838 * Check the validity of the time-sharing parameters in the buffer
839 * pointed to by tsparmsp.
840 * ts_parmsin() is called for TS threads, and ia_parmsin() is called
841 * for IA threads.
842 */
843static int
844ts_parmsin(void *parmsp)
845{
846	tsparms_t	*tsparmsp = (tsparms_t *)parmsp;
847	/*
848	 * Check validity of parameters.
849	 */
850	if ((tsparmsp->ts_uprilim > ts_maxupri ||
851	    tsparmsp->ts_uprilim < -ts_maxupri) &&
852	    tsparmsp->ts_uprilim != TS_NOCHANGE)
853		return (EINVAL);
854
855	if ((tsparmsp->ts_upri > ts_maxupri ||
856	    tsparmsp->ts_upri < -ts_maxupri) &&
857	    tsparmsp->ts_upri != TS_NOCHANGE)
858		return (EINVAL);
859
860	return (0);
861}
862
863static int
864ia_parmsin(void *parmsp)
865{
866	iaparms_t	*iaparmsp = (iaparms_t *)parmsp;
867
868	if ((iaparmsp->ia_uprilim > ia_maxupri ||
869	    iaparmsp->ia_uprilim < -ia_maxupri) &&
870	    iaparmsp->ia_uprilim != IA_NOCHANGE) {
871		return (EINVAL);
872	}
873
874	if ((iaparmsp->ia_upri > ia_maxupri ||
875	    iaparmsp->ia_upri < -ia_maxupri) &&
876	    iaparmsp->ia_upri != IA_NOCHANGE) {
877		return (EINVAL);
878	}
879
880	return (0);
881}
882
883
884/*
885 * Check the validity of the time-sharing parameters in the pc_vaparms_t
886 * structure vaparmsp and put them in the buffer pointed to by tsparmsp.
887 * pc_vaparms_t contains (key, value) pairs of parameter.
888 * ts_vaparmsin() is called for TS threads, and ia_vaparmsin() is called
889 * for IA threads. ts_vaparmsin() is the variable parameter version of
890 * ts_parmsin() and ia_vaparmsin() is the variable parameter version of
891 * ia_parmsin().
892 */
893static int
894ts_vaparmsin(void *parmsp, pc_vaparms_t *vaparmsp)
895{
896	tsparms_t	*tsparmsp = (tsparms_t *)parmsp;
897	int		priflag = 0;
898	int		limflag = 0;
899	uint_t		cnt;
900	pc_vaparm_t	*vpp = &vaparmsp->pc_parms[0];
901
902
903	/*
904	 * TS_NOCHANGE (-32768) is outside of the range of values for
905	 * ts_uprilim and ts_upri. If the structure tsparms_t is changed,
906	 * TS_NOCHANGE should be replaced by a flag word (in the same manner
907	 * as in rt.c).
908	 */
909	tsparmsp->ts_uprilim = TS_NOCHANGE;
910	tsparmsp->ts_upri = TS_NOCHANGE;
911
912	/*
913	 * Get the varargs parameter and check validity of parameters.
914	 */
915	if (vaparmsp->pc_vaparmscnt > PC_VAPARMCNT)
916		return (EINVAL);
917
918	for (cnt = 0; cnt < vaparmsp->pc_vaparmscnt; cnt++, vpp++) {
919
920		switch (vpp->pc_key) {
921		case TS_KY_UPRILIM:
922			if (limflag++)
923				return (EINVAL);
924			tsparmsp->ts_uprilim = (pri_t)vpp->pc_parm;
925			if (tsparmsp->ts_uprilim > ts_maxupri ||
926			    tsparmsp->ts_uprilim < -ts_maxupri)
927				return (EINVAL);
928			break;
929
930		case TS_KY_UPRI:
931			if (priflag++)
932				return (EINVAL);
933			tsparmsp->ts_upri = (pri_t)vpp->pc_parm;
934			if (tsparmsp->ts_upri > ts_maxupri ||
935			    tsparmsp->ts_upri < -ts_maxupri)
936				return (EINVAL);
937			break;
938
939		default:
940			return (EINVAL);
941		}
942	}
943
944	if (vaparmsp->pc_vaparmscnt == 0) {
945		/*
946		 * Use default parameters.
947		 */
948		tsparmsp->ts_upri = tsparmsp->ts_uprilim = 0;
949	}
950
951	return (0);
952}
953
954static int
955ia_vaparmsin(void *parmsp, pc_vaparms_t *vaparmsp)
956{
957	iaparms_t	*iaparmsp = (iaparms_t *)parmsp;
958	int		priflag = 0;
959	int		limflag = 0;
960	int		mflag = 0;
961	uint_t		cnt;
962	pc_vaparm_t	*vpp = &vaparmsp->pc_parms[0];
963
964	/*
965	 * IA_NOCHANGE (-32768) is outside of the range of values for
966	 * ia_uprilim, ia_upri and ia_mode. If the structure iaparms_t is
967	 * changed, IA_NOCHANGE should be replaced by a flag word (in the
968	 * same manner as in rt.c).
969	 */
970	iaparmsp->ia_uprilim = IA_NOCHANGE;
971	iaparmsp->ia_upri = IA_NOCHANGE;
972	iaparmsp->ia_mode = IA_NOCHANGE;
973
974	/*
975	 * Get the varargs parameter and check validity of parameters.
976	 */
977	if (vaparmsp->pc_vaparmscnt > PC_VAPARMCNT)
978		return (EINVAL);
979
980	for (cnt = 0; cnt < vaparmsp->pc_vaparmscnt; cnt++, vpp++) {
981
982		switch (vpp->pc_key) {
983		case IA_KY_UPRILIM:
984			if (limflag++)
985				return (EINVAL);
986			iaparmsp->ia_uprilim = (pri_t)vpp->pc_parm;
987			if (iaparmsp->ia_uprilim > ia_maxupri ||
988			    iaparmsp->ia_uprilim < -ia_maxupri)
989				return (EINVAL);
990			break;
991
992		case IA_KY_UPRI:
993			if (priflag++)
994				return (EINVAL);
995			iaparmsp->ia_upri = (pri_t)vpp->pc_parm;
996			if (iaparmsp->ia_upri > ia_maxupri ||
997			    iaparmsp->ia_upri < -ia_maxupri)
998				return (EINVAL);
999			break;
1000
1001		case IA_KY_MODE:
1002			if (mflag++)
1003				return (EINVAL);
1004			iaparmsp->ia_mode = (int)vpp->pc_parm;
1005			if (iaparmsp->ia_mode != IA_SET_INTERACTIVE &&
1006			    iaparmsp->ia_mode != IA_INTERACTIVE_OFF)
1007				return (EINVAL);
1008			break;
1009
1010		default:
1011			return (EINVAL);
1012		}
1013	}
1014
1015	if (vaparmsp->pc_vaparmscnt == 0) {
1016		/*
1017		 * Use default parameters.
1018		 */
1019		iaparmsp->ia_upri = iaparmsp->ia_uprilim = 0;
1020		iaparmsp->ia_mode = IA_SET_INTERACTIVE;
1021	}
1022
1023	return (0);
1024}
1025
1026/*
1027 * Nothing to do here but return success.
1028 */
1029/* ARGSUSED */
1030static int
1031ts_parmsout(void *parmsp, pc_vaparms_t *vaparmsp)
1032{
1033	return (0);
1034}
1035
1036
1037/*
1038 * Copy all selected time-sharing class parameters to the user.
1039 * The parameters are specified by a key.
1040 */
1041static int
1042ts_vaparmsout(void *prmsp, pc_vaparms_t *vaparmsp)
1043{
1044	tsparms_t	*tsprmsp = (tsparms_t *)prmsp;
1045	int		priflag = 0;
1046	int		limflag = 0;
1047	uint_t		cnt;
1048	pc_vaparm_t	*vpp = &vaparmsp->pc_parms[0];
1049
1050	ASSERT(MUTEX_NOT_HELD(&curproc->p_lock));
1051
1052	if (vaparmsp->pc_vaparmscnt > PC_VAPARMCNT)
1053		return (EINVAL);
1054
1055	for (cnt = 0; cnt < vaparmsp->pc_vaparmscnt; cnt++, vpp++) {
1056
1057		switch (vpp->pc_key) {
1058		case TS_KY_UPRILIM:
1059			if (limflag++)
1060				return (EINVAL);
1061			if (copyout(&tsprmsp->ts_uprilim,
1062			    (caddr_t)(uintptr_t)vpp->pc_parm, sizeof (pri_t)))
1063				return (EFAULT);
1064			break;
1065
1066		case TS_KY_UPRI:
1067			if (priflag++)
1068				return (EINVAL);
1069			if (copyout(&tsprmsp->ts_upri,
1070			    (caddr_t)(uintptr_t)vpp->pc_parm, sizeof (pri_t)))
1071				return (EFAULT);
1072			break;
1073
1074		default:
1075			return (EINVAL);
1076		}
1077	}
1078
1079	return (0);
1080}
1081
1082
1083/*
1084 * Copy all selected interactive class parameters to the user.
1085 * The parameters are specified by a key.
1086 */
1087static int
1088ia_vaparmsout(void *prmsp, pc_vaparms_t *vaparmsp)
1089{
1090	iaparms_t	*iaprmsp = (iaparms_t *)prmsp;
1091	int		priflag = 0;
1092	int		limflag = 0;
1093	int		mflag = 0;
1094	uint_t		cnt;
1095	pc_vaparm_t	*vpp = &vaparmsp->pc_parms[0];
1096
1097	ASSERT(MUTEX_NOT_HELD(&curproc->p_lock));
1098
1099	if (vaparmsp->pc_vaparmscnt > PC_VAPARMCNT)
1100		return (EINVAL);
1101
1102	for (cnt = 0; cnt < vaparmsp->pc_vaparmscnt; cnt++, vpp++) {
1103
1104		switch (vpp->pc_key) {
1105		case IA_KY_UPRILIM:
1106			if (limflag++)
1107				return (EINVAL);
1108			if (copyout(&iaprmsp->ia_uprilim,
1109			    (caddr_t)(uintptr_t)vpp->pc_parm, sizeof (pri_t)))
1110				return (EFAULT);
1111			break;
1112
1113		case IA_KY_UPRI:
1114			if (priflag++)
1115				return (EINVAL);
1116			if (copyout(&iaprmsp->ia_upri,
1117			    (caddr_t)(uintptr_t)vpp->pc_parm, sizeof (pri_t)))
1118				return (EFAULT);
1119			break;
1120
1121		case IA_KY_MODE:
1122			if (mflag++)
1123				return (EINVAL);
1124			if (copyout(&iaprmsp->ia_mode,
1125			    (caddr_t)(uintptr_t)vpp->pc_parm, sizeof (int)))
1126				return (EFAULT);
1127			break;
1128
1129		default:
1130			return (EINVAL);
1131		}
1132	}
1133	return (0);
1134}
1135
1136
1137/*
1138 * Set the scheduling parameters of the thread pointed to by tsprocp
1139 * to those specified in the buffer pointed to by tsparmsp.
1140 * ts_parmsset() is called for TS threads, and ia_parmsset() is
1141 * called for IA threads.
1142 */
1143/* ARGSUSED */
1144static int
1145ts_parmsset(kthread_t *tx, void *parmsp, id_t reqpcid, cred_t *reqpcredp)
1146{
1147	char		nice;
1148	pri_t		reqtsuprilim;
1149	pri_t		reqtsupri;
1150	tsparms_t	*tsparmsp = (tsparms_t *)parmsp;
1151	tsproc_t	*tspp = (tsproc_t *)tx->t_cldata;
1152
1153	ASSERT(MUTEX_HELD(&(ttoproc(tx))->p_lock));
1154
1155	if (tsparmsp->ts_uprilim == TS_NOCHANGE)
1156		reqtsuprilim = tspp->ts_uprilim;
1157	else
1158		reqtsuprilim = tsparmsp->ts_uprilim;
1159
1160	if (tsparmsp->ts_upri == TS_NOCHANGE)
1161		reqtsupri = tspp->ts_upri;
1162	else
1163		reqtsupri = tsparmsp->ts_upri;
1164
1165	/*
1166	 * Make sure the user priority doesn't exceed the upri limit.
1167	 */
1168	if (reqtsupri > reqtsuprilim)
1169		reqtsupri = reqtsuprilim;
1170
1171	/*
1172	 * Basic permissions enforced by generic kernel code
1173	 * for all classes require that a thread attempting
1174	 * to change the scheduling parameters of a target
1175	 * thread be privileged or have a real or effective
1176	 * UID matching that of the target thread. We are not
1177	 * called unless these basic permission checks have
1178	 * already passed. The time-sharing class requires in
1179	 * addition that the calling thread be privileged if it
1180	 * is attempting to raise the upri limit above its current
1181	 * value This may have been checked previously but if our
1182	 * caller passed us a non-NULL credential pointer we assume
1183	 * it hasn't and we check it here.
1184	 */
1185	if (reqpcredp != NULL &&
1186	    reqtsuprilim > tspp->ts_uprilim &&
1187	    secpolicy_setpriority(reqpcredp) != 0)
1188		return (EPERM);
1189
1190	/*
1191	 * Set ts_nice to the nice value corresponding to the user
1192	 * priority we are setting.  Note that setting the nice field
1193	 * of the parameter struct won't affect upri or nice.
1194	 */
1195	nice = NZERO - (reqtsupri * NZERO) / ts_maxupri;
1196	if (nice >= 2 * NZERO)
1197		nice = 2 * NZERO - 1;
1198
1199	thread_lock(tx);
1200
1201	tspp->ts_uprilim = reqtsuprilim;
1202	tspp->ts_upri = reqtsupri;
1203	TS_NEWUMDPRI(tspp);
1204	tspp->ts_nice = nice;
1205
1206	if ((tspp->ts_flags & TSKPRI) != 0) {
1207		thread_unlock(tx);
1208		return (0);
1209	}
1210
1211	tspp->ts_dispwait = 0;
1212	ts_change_priority(tx, tspp);
1213	thread_unlock(tx);
1214	return (0);
1215}
1216
1217
1218static int
1219ia_parmsset(kthread_t *tx, void *parmsp, id_t reqpcid, cred_t *reqpcredp)
1220{
1221	tsproc_t	*tspp = (tsproc_t *)tx->t_cldata;
1222	iaparms_t	*iaparmsp = (iaparms_t *)parmsp;
1223	proc_t		*p;
1224	pid_t		pid, pgid, sid;
1225	pid_t		on, off;
1226	struct stdata 	*stp;
1227	int		sess_held;
1228
1229	/*
1230	 * Handle user priority changes
1231	 */
1232	if (iaparmsp->ia_mode == IA_NOCHANGE)
1233		return (ts_parmsset(tx, parmsp, reqpcid, reqpcredp));
1234
1235	/*
1236	 * Check permissions for changing modes.
1237	 */
1238
1239	if (reqpcredp != NULL && !groupmember(IA_gid, reqpcredp) &&
1240	    secpolicy_setpriority(reqpcredp) != 0) {
1241		/*
1242		 * Silently fail in case this is just a priocntl
1243		 * call with upri and uprilim set to IA_NOCHANGE.
1244		 */
1245		return (0);
1246	}
1247
1248	ASSERT(MUTEX_HELD(&pidlock));
1249	if ((p = ttoproc(tx)) == NULL) {
1250		return (0);
1251	}
1252	ASSERT(MUTEX_HELD(&p->p_lock));
1253	if (p->p_stat == SIDL) {
1254		return (0);
1255	}
1256	pid = p->p_pid;
1257	sid = p->p_sessp->s_sid;
1258	pgid = p->p_pgrp;
1259	if (iaparmsp->ia_mode == IA_SET_INTERACTIVE) {
1260		/*
1261		 * session leaders must be turned on now so all processes
1262		 * in the group controlling the tty will be turned on or off.
1263		 * if the ia_mode is off for the session leader,
1264		 * ia_set_process_group will return without setting the
1265		 * processes in the group controlling the tty on.
1266		 */
1267		thread_lock(tx);
1268		tspp->ts_flags |= TSIASET;
1269		thread_unlock(tx);
1270	}
1271	mutex_enter(&p->p_sessp->s_lock);
1272	sess_held = 1;
1273	if ((pid == sid) && (p->p_sessp->s_vp != NULL) &&
1274	    ((stp = p->p_sessp->s_vp->v_stream) != NULL)) {
1275		if ((stp->sd_pgidp != NULL) && (stp->sd_sidp != NULL)) {
1276			pgid = stp->sd_pgidp->pid_id;
1277			sess_held = 0;
1278			mutex_exit(&p->p_sessp->s_lock);
1279			if (iaparmsp->ia_mode ==
1280			    IA_SET_INTERACTIVE) {
1281				off = 0;
1282				on = pgid;
1283			} else {
1284				off = pgid;
1285				on = 0;
1286			}
1287			TRACE_3(TR_FAC_IA, TR_ACTIVE_CHAIN,
1288			    "active chain:pid %d gid %d %p",
1289			    pid, pgid, p);
1290			ia_set_process_group(sid, off, on);
1291		}
1292	}
1293	if (sess_held)
1294		mutex_exit(&p->p_sessp->s_lock);
1295
1296	thread_lock(tx);
1297
1298	if (iaparmsp->ia_mode == IA_SET_INTERACTIVE) {
1299		tspp->ts_flags |= TSIASET;
1300		tspp->ts_boost = ia_boost;
1301	} else {
1302		tspp->ts_flags &= ~TSIASET;
1303		tspp->ts_boost = -ia_boost;
1304	}
1305	thread_unlock(tx);
1306
1307	return (ts_parmsset(tx, parmsp, reqpcid, reqpcredp));
1308}
1309
1310/*
1311 * Return the global scheduling priority that would be assigned
1312 * to a thread entering the time-sharing class with the ts_upri.
1313 */
1314static pri_t
1315ts_globpri(kthread_t *t)
1316{
1317	tsproc_t *tspp;
1318	pri_t	tspri;
1319
1320	ASSERT(MUTEX_HELD(&ttoproc(t)->p_lock));
1321	tspp = (tsproc_t *)t->t_cldata;
1322	tspri = tsmedumdpri + tspp->ts_upri;
1323	if (tspri > ts_maxumdpri)
1324		tspri = ts_maxumdpri;
1325	else if (tspri < 0)
1326		tspri = 0;
1327	return (ts_dptbl[tspri].ts_globpri);
1328}
1329
1330/*
1331 * Arrange for thread to be placed in appropriate location
1332 * on dispatcher queue.
1333 *
1334 * This is called with the current thread in TS_ONPROC and locked.
1335 */
1336static void
1337ts_preempt(kthread_t *t)
1338{
1339	tsproc_t	*tspp = (tsproc_t *)(t->t_cldata);
1340	klwp_t		*lwp;
1341#ifdef KSLICE
1342	extern int	kslice;
1343#endif
1344	pri_t		oldpri = t->t_pri;
1345
1346	ASSERT(t == curthread);
1347	ASSERT(THREAD_LOCK_HELD(curthread));
1348
1349	/*
1350	 * If preempted in the kernel, make sure the thread has
1351	 * a kernel priority if needed.
1352	 */
1353	lwp = curthread->t_lwp;
1354	if (!(tspp->ts_flags & TSKPRI) && lwp != NULL && t->t_kpri_req) {
1355		tspp->ts_flags |= TSKPRI;
1356		THREAD_CHANGE_PRI(t, ts_kmdpris[0]);
1357		ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
1358		t->t_trapret = 1;		/* so ts_trapret will run */
1359		aston(t);
1360	}
1361	/*
1362	 * If preempted in user-land mark the thread
1363	 * as swappable because I know it isn't holding any locks.
1364	 */
1365	ASSERT(t->t_schedflag & TS_DONT_SWAP);
1366	if (lwp != NULL && lwp->lwp_state == LWP_USER)
1367		t->t_schedflag &= ~TS_DONT_SWAP;
1368
1369	/*
1370	 * Check to see if we're doing "preemption control" here.  If
1371	 * we are, and if the user has requested that this thread not
1372	 * be preempted, and if preemptions haven't been put off for
1373	 * too long, let the preemption happen here but try to make
1374	 * sure the thread is rescheduled as soon as possible.  We do
1375	 * this by putting it on the front of the highest priority run
1376	 * queue in the TS class.  If the preemption has been put off
1377	 * for too long, clear the "nopreempt" bit and let the thread
1378	 * be preempted.
1379	 */
1380	if (t->t_schedctl && schedctl_get_nopreempt(t)) {
1381		if (tspp->ts_timeleft > -SC_MAX_TICKS) {
1382			DTRACE_SCHED1(schedctl__nopreempt, kthread_t *, t);
1383			if (!(tspp->ts_flags & TSKPRI)) {
1384				/*
1385				 * If not already remembered, remember current
1386				 * priority for restoration in ts_yield().
1387				 */
1388				if (!(tspp->ts_flags & TSRESTORE)) {
1389					tspp->ts_scpri = t->t_pri;
1390					tspp->ts_flags |= TSRESTORE;
1391				}
1392				THREAD_CHANGE_PRI(t, ts_maxumdpri);
1393				t->t_schedflag |= TS_DONT_SWAP;
1394			}
1395			schedctl_set_yield(t, 1);
1396			setfrontdq(t);
1397			goto done;
1398		} else {
1399			if (tspp->ts_flags & TSRESTORE) {
1400				THREAD_CHANGE_PRI(t, tspp->ts_scpri);
1401				tspp->ts_flags &= ~TSRESTORE;
1402			}
1403			schedctl_set_nopreempt(t, 0);
1404			DTRACE_SCHED1(schedctl__preempt, kthread_t *, t);
1405			TNF_PROBE_2(schedctl_preempt, "schedctl TS ts_preempt",
1406			    /* CSTYLED */, tnf_pid, pid, ttoproc(t)->p_pid,
1407			    tnf_lwpid, lwpid, t->t_tid);
1408			/*
1409			 * Fall through and be preempted below.
1410			 */
1411		}
1412	}
1413
1414	if ((tspp->ts_flags & (TSBACKQ|TSKPRI)) == TSBACKQ) {
1415		tspp->ts_timeleft = ts_dptbl[tspp->ts_cpupri].ts_quantum;
1416		tspp->ts_dispwait = 0;
1417		tspp->ts_flags &= ~TSBACKQ;
1418		setbackdq(t);
1419	} else if ((tspp->ts_flags & (TSBACKQ|TSKPRI)) == (TSBACKQ|TSKPRI)) {
1420		tspp->ts_flags &= ~TSBACKQ;
1421		setbackdq(t);
1422	} else {
1423#ifdef KSLICE
1424		if (kslice)
1425			setbackdq(t);
1426		else
1427#endif
1428			setfrontdq(t);
1429	}
1430
1431done:
1432	TRACE_2(TR_FAC_DISP, TR_PREEMPT,
1433	    "preempt:tid %p old pri %d", t, oldpri);
1434}
1435
1436static void
1437ts_setrun(kthread_t *t)
1438{
1439	tsproc_t *tspp = (tsproc_t *)(t->t_cldata);
1440
1441	ASSERT(THREAD_LOCK_HELD(t));	/* t should be in transition */
1442
1443	if (tspp->ts_dispwait > ts_dptbl[tspp->ts_umdpri].ts_maxwait) {
1444		tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_slpret;
1445		TS_NEWUMDPRI(tspp);
1446		tspp->ts_timeleft = ts_dptbl[tspp->ts_cpupri].ts_quantum;
1447		tspp->ts_dispwait = 0;
1448		if ((tspp->ts_flags & TSKPRI) == 0) {
1449			THREAD_CHANGE_PRI(t,
1450			    ts_dptbl[tspp->ts_umdpri].ts_globpri);
1451			ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
1452		}
1453	}
1454
1455	tspp->ts_flags &= ~TSBACKQ;
1456
1457	if (tspp->ts_flags & TSIA) {
1458		if (tspp->ts_flags & TSIASET)
1459			setfrontdq(t);
1460		else
1461			setbackdq(t);
1462	} else {
1463		if (t->t_disp_time != lbolt)
1464			setbackdq(t);
1465		else
1466			setfrontdq(t);
1467	}
1468}
1469
1470
1471/*
1472 * Prepare thread for sleep. We reset the thread priority so it will
1473 * run at the kernel priority level when it wakes up.
1474 */
1475static void
1476ts_sleep(kthread_t *t)
1477{
1478	tsproc_t	*tspp = (tsproc_t *)(t->t_cldata);
1479	int		flags;
1480	pri_t		old_pri = t->t_pri;
1481
1482	ASSERT(t == curthread);
1483	ASSERT(THREAD_LOCK_HELD(t));
1484
1485	flags = tspp->ts_flags;
1486	if (t->t_kpri_req) {
1487		tspp->ts_flags = flags | TSKPRI;
1488		THREAD_CHANGE_PRI(t, ts_kmdpris[0]);
1489		ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
1490		t->t_trapret = 1;		/* so ts_trapret will run */
1491		aston(t);
1492	} else if (tspp->ts_dispwait > ts_dptbl[tspp->ts_umdpri].ts_maxwait) {
1493		/*
1494		 * If thread has blocked in the kernel (as opposed to
1495		 * being merely preempted), recompute the user mode priority.
1496		 */
1497		tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_slpret;
1498		TS_NEWUMDPRI(tspp);
1499		tspp->ts_timeleft = ts_dptbl[tspp->ts_cpupri].ts_quantum;
1500		tspp->ts_dispwait = 0;
1501
1502		THREAD_CHANGE_PRI(curthread,
1503		    ts_dptbl[tspp->ts_umdpri].ts_globpri);
1504		ASSERT(curthread->t_pri >= 0 &&
1505		    curthread->t_pri <= ts_maxglobpri);
1506		tspp->ts_flags = flags & ~TSKPRI;
1507
1508		if (DISP_MUST_SURRENDER(curthread))
1509			cpu_surrender(curthread);
1510	} else if (flags & TSKPRI) {
1511		THREAD_CHANGE_PRI(curthread,
1512		    ts_dptbl[tspp->ts_umdpri].ts_globpri);
1513		ASSERT(curthread->t_pri >= 0 &&
1514		    curthread->t_pri <= ts_maxglobpri);
1515		tspp->ts_flags = flags & ~TSKPRI;
1516
1517		if (DISP_MUST_SURRENDER(curthread))
1518			cpu_surrender(curthread);
1519	}
1520	t->t_stime = lbolt;		/* time stamp for the swapper */
1521	TRACE_2(TR_FAC_DISP, TR_SLEEP,
1522	    "sleep:tid %p old pri %d", t, old_pri);
1523}
1524
1525
1526/*
1527 * Return Values:
1528 *
1529 *	-1 if the thread is loaded or is not eligible to be swapped in.
1530 *
1531 *	effective priority of the specified thread based on swapout time
1532 *		and size of process (epri >= 0 , epri <= SHRT_MAX).
1533 */
1534/* ARGSUSED */
1535static pri_t
1536ts_swapin(kthread_t *t, int flags)
1537{
1538	tsproc_t	*tspp = (tsproc_t *)(t->t_cldata);
1539	long		epri = -1;
1540	proc_t		*pp = ttoproc(t);
1541
1542	ASSERT(THREAD_LOCK_HELD(t));
1543
1544	/*
1545	 * We know that pri_t is a short.
1546	 * Be sure not to overrun its range.
1547	 */
1548	if (t->t_state == TS_RUN && (t->t_schedflag & TS_LOAD) == 0) {
1549		time_t swapout_time;
1550
1551		swapout_time = (lbolt - t->t_stime) / hz;
1552		if (INHERITED(t) || (tspp->ts_flags & (TSKPRI | TSIASET)))
1553			epri = (long)DISP_PRIO(t) + swapout_time;
1554		else {
1555			/*
1556			 * Threads which have been out for a long time,
1557			 * have high user mode priority and are associated
1558			 * with a small address space are more deserving
1559			 */
1560			epri = ts_dptbl[tspp->ts_umdpri].ts_globpri;
1561			ASSERT(epri >= 0 && epri <= ts_maxumdpri);
1562			epri += swapout_time - pp->p_swrss / nz(maxpgio)/2;
1563		}
1564		/*
1565		 * Scale epri so SHRT_MAX/2 represents zero priority.
1566		 */
1567		epri += SHRT_MAX/2;
1568		if (epri < 0)
1569			epri = 0;
1570		else if (epri > SHRT_MAX)
1571			epri = SHRT_MAX;
1572	}
1573	return ((pri_t)epri);
1574}
1575
1576/*
1577 * Return Values
1578 *	-1 if the thread isn't loaded or is not eligible to be swapped out.
1579 *
1580 *	effective priority of the specified thread based on if the swapper
1581 *		is in softswap or hardswap mode.
1582 *
1583 *		Softswap:  Return a low effective priority for threads
1584 *			   sleeping for more than maxslp secs.
1585 *
1586 *		Hardswap:  Return an effective priority such that threads
1587 *			   which have been in memory for a while and are
1588 *			   associated with a small address space are swapped
1589 *			   in before others.
1590 *
1591 *		(epri >= 0 , epri <= SHRT_MAX).
1592 */
1593time_t	ts_minrun = 2;		/* XXX - t_pri becomes 59 within 2 secs */
1594time_t	ts_minslp = 2;		/* min time on sleep queue for hardswap */
1595
1596static pri_t
1597ts_swapout(kthread_t *t, int flags)
1598{
1599	tsproc_t	*tspp = (tsproc_t *)(t->t_cldata);
1600	long		epri = -1;
1601	proc_t		*pp = ttoproc(t);
1602	time_t		swapin_time;
1603
1604	ASSERT(THREAD_LOCK_HELD(t));
1605
1606	if (INHERITED(t) || (tspp->ts_flags & (TSKPRI | TSIASET)) ||
1607	    (t->t_proc_flag & TP_LWPEXIT) ||
1608	    (t->t_state & (TS_ZOMB | TS_FREE | TS_STOPPED | TS_ONPROC)) ||
1609	    !(t->t_schedflag & TS_LOAD) || !SWAP_OK(t))
1610		return (-1);
1611
1612	ASSERT(t->t_state & (TS_SLEEP | TS_RUN));
1613
1614	/*
1615	 * We know that pri_t is a short.
1616	 * Be sure not to overrun its range.
1617	 */
1618	swapin_time = (lbolt - t->t_stime) / hz;
1619	if (flags == SOFTSWAP) {
1620		if (t->t_state == TS_SLEEP && swapin_time > maxslp) {
1621			epri = 0;
1622		} else {
1623			return ((pri_t)epri);
1624		}
1625	} else {
1626		pri_t pri;
1627
1628		if ((t->t_state == TS_SLEEP && swapin_time > ts_minslp) ||
1629		    (t->t_state == TS_RUN && swapin_time > ts_minrun)) {
1630			pri = ts_dptbl[tspp->ts_umdpri].ts_globpri;
1631			ASSERT(pri >= 0 && pri <= ts_maxumdpri);
1632			epri = swapin_time -
1633			    (rm_asrss(pp->p_as) / nz(maxpgio)/2) - (long)pri;
1634		} else {
1635			return ((pri_t)epri);
1636		}
1637	}
1638
1639	/*
1640	 * Scale epri so SHRT_MAX/2 represents zero priority.
1641	 */
1642	epri += SHRT_MAX/2;
1643	if (epri < 0)
1644		epri = 0;
1645	else if (epri > SHRT_MAX)
1646		epri = SHRT_MAX;
1647
1648	return ((pri_t)epri);
1649}
1650
1651/*
1652 * Check for time slice expiration.  If time slice has expired
1653 * move thread to priority specified in tsdptbl for time slice expiration
1654 * and set runrun to cause preemption.
1655 */
1656
1657static void
1658ts_tick(kthread_t *t)
1659{
1660	tsproc_t *tspp = (tsproc_t *)(t->t_cldata);
1661	klwp_t *lwp;
1662	pri_t	oldpri = t->t_pri;
1663
1664	ASSERT(MUTEX_HELD(&(ttoproc(t))->p_lock));
1665
1666	thread_lock(t);
1667	if ((tspp->ts_flags & TSKPRI) == 0) {
1668		if (--tspp->ts_timeleft <= 0) {
1669			pri_t	new_pri;
1670
1671			/*
1672			 * If we're doing preemption control and trying to
1673			 * avoid preempting this thread, just note that
1674			 * the thread should yield soon and let it keep
1675			 * running (unless it's been a while).
1676			 */
1677			if (t->t_schedctl && schedctl_get_nopreempt(t)) {
1678				if (tspp->ts_timeleft > -SC_MAX_TICKS) {
1679					DTRACE_SCHED1(schedctl__nopreempt,
1680					    kthread_t *, t);
1681					schedctl_set_yield(t, 1);
1682					thread_unlock_nopreempt(t);
1683					return;
1684				}
1685
1686				TNF_PROBE_2(schedctl_failsafe,
1687				    "schedctl TS ts_tick", /* CSTYLED */,
1688				    tnf_pid, pid, ttoproc(t)->p_pid,
1689				    tnf_lwpid, lwpid, t->t_tid);
1690			}
1691			tspp->ts_flags &= ~TSRESTORE;
1692			tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_tqexp;
1693			TS_NEWUMDPRI(tspp);
1694			tspp->ts_dispwait = 0;
1695			new_pri = ts_dptbl[tspp->ts_umdpri].ts_globpri;
1696			ASSERT(new_pri >= 0 && new_pri <= ts_maxglobpri);
1697			/*
1698			 * When the priority of a thread is changed,
1699			 * it may be necessary to adjust its position
1700			 * on a sleep queue or dispatch queue.
1701			 * The function thread_change_pri accomplishes
1702			 * this.
1703			 */
1704			if (thread_change_pri(t, new_pri, 0)) {
1705				if ((t->t_schedflag & TS_LOAD) &&
1706				    (lwp = t->t_lwp) &&
1707				    lwp->lwp_state == LWP_USER)
1708					t->t_schedflag &= ~TS_DONT_SWAP;
1709				tspp->ts_timeleft =
1710				    ts_dptbl[tspp->ts_cpupri].ts_quantum;
1711			} else {
1712				tspp->ts_flags |= TSBACKQ;
1713				cpu_surrender(t);
1714			}
1715			TRACE_2(TR_FAC_DISP, TR_TICK,
1716			    "tick:tid %p old pri %d", t, oldpri);
1717		} else if (t->t_state == TS_ONPROC &&
1718			    t->t_pri < t->t_disp_queue->disp_maxrunpri) {
1719			tspp->ts_flags |= TSBACKQ;
1720			cpu_surrender(t);
1721		}
1722	}
1723	thread_unlock_nopreempt(t);	/* clock thread can't be preempted */
1724}
1725
1726
1727/*
1728 * If thread is currently at a kernel mode priority (has slept)
1729 * we assign it the appropriate user mode priority and time quantum
1730 * here.  If we are lowering the thread's priority below that of
1731 * other runnable threads we will normally set runrun via cpu_surrender() to
1732 * cause preemption.
1733 */
1734static void
1735ts_trapret(kthread_t *t)
1736{
1737	tsproc_t	*tspp = (tsproc_t *)t->t_cldata;
1738	cpu_t		*cp = CPU;
1739	pri_t		old_pri = curthread->t_pri;
1740
1741	ASSERT(THREAD_LOCK_HELD(t));
1742	ASSERT(t == curthread);
1743	ASSERT(cp->cpu_dispthread == t);
1744	ASSERT(t->t_state == TS_ONPROC);
1745
1746	t->t_kpri_req = 0;
1747	if (tspp->ts_dispwait > ts_dptbl[tspp->ts_umdpri].ts_maxwait) {
1748		tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_slpret;
1749		TS_NEWUMDPRI(tspp);
1750		tspp->ts_timeleft = ts_dptbl[tspp->ts_cpupri].ts_quantum;
1751		tspp->ts_dispwait = 0;
1752
1753		/*
1754		 * If thread has blocked in the kernel (as opposed to
1755		 * being merely preempted), recompute the user mode priority.
1756		 */
1757		THREAD_CHANGE_PRI(t, ts_dptbl[tspp->ts_umdpri].ts_globpri);
1758		cp->cpu_dispatch_pri = DISP_PRIO(t);
1759		ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
1760		tspp->ts_flags &= ~TSKPRI;
1761
1762		if (DISP_MUST_SURRENDER(t))
1763			cpu_surrender(t);
1764	} else if (tspp->ts_flags & TSKPRI) {
1765		/*
1766		 * If thread has blocked in the kernel (as opposed to
1767		 * being merely preempted), recompute the user mode priority.
1768		 */
1769		THREAD_CHANGE_PRI(t, ts_dptbl[tspp->ts_umdpri].ts_globpri);
1770		cp->cpu_dispatch_pri = DISP_PRIO(t);
1771		ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
1772		tspp->ts_flags &= ~TSKPRI;
1773
1774		if (DISP_MUST_SURRENDER(t))
1775			cpu_surrender(t);
1776	}
1777
1778	/*
1779	 * Swapout lwp if the swapper is waiting for this thread to
1780	 * reach a safe point.
1781	 */
1782	if ((t->t_schedflag & TS_SWAPENQ) && !(tspp->ts_flags & TSIASET)) {
1783		thread_unlock(t);
1784		swapout_lwp(ttolwp(t));
1785		thread_lock(t);
1786	}
1787
1788	TRACE_2(TR_FAC_DISP, TR_TRAPRET,
1789	    "trapret:tid %p old pri %d", t, old_pri);
1790}
1791
1792
1793/*
1794 * Update the ts_dispwait values of all time sharing threads that
1795 * are currently runnable at a user mode priority and bump the priority
1796 * if ts_dispwait exceeds ts_maxwait.  Called once per second via
1797 * timeout which we reset here.
1798 *
1799 * There are several lists of time sharing threads broken up by a hash on
1800 * the thread pointer.  Each list has its own lock.  This avoids blocking
1801 * all ts_enterclass, ts_fork, and ts_exitclass operations while ts_update
1802 * runs.  ts_update traverses each list in turn.
1803 *
1804 * If multiple threads have their priorities updated to the same value,
1805 * the system implicitly favors the one that is updated first (since it
1806 * winds up first on the run queue).  To avoid this unfairness, the
1807 * traversal of threads starts at the list indicated by a marker.  When
1808 * threads in more than one list have their priorities updated, the marker
1809 * is moved.  This changes the order the threads will be placed on the run
1810 * queue the next time ts_update is called and preserves fairness over the
1811 * long run.  The marker doesn't need to be protected by a lock since it's
1812 * only accessed by ts_update, which is inherently single-threaded (only
1813 * one instance can be running at a time).
1814 */
1815static void
1816ts_update(void *arg)
1817{
1818	int		i;
1819	int		new_marker = -1;
1820	static int	ts_update_marker;
1821
1822	/*
1823	 * Start with the ts_update_marker list, then do the rest.
1824	 */
1825	i = ts_update_marker;
1826	do {
1827		/*
1828		 * If this is the first list after the current marker to
1829		 * have threads with priorities updated, advance the marker
1830		 * to this list for the next time ts_update runs.
1831		 */
1832		if (ts_update_list(i) && new_marker == -1 &&
1833		    i != ts_update_marker) {
1834			new_marker = i;
1835		}
1836	} while ((i = TS_LIST_NEXT(i)) != ts_update_marker);
1837
1838	/* advance marker for next ts_update call */
1839	if (new_marker != -1)
1840		ts_update_marker = new_marker;
1841
1842	(void) timeout(ts_update, arg, hz);
1843}
1844
1845/*
1846 * Updates priority for a list of threads.  Returns 1 if the priority of
1847 * one of the threads was actually updated, 0 if none were for various
1848 * reasons (thread is no longer in the TS or IA class, isn't runnable,
1849 * hasn't waited long enough, has the preemption control no-preempt bit
1850 * set, etc.)
1851 */
1852static int
1853ts_update_list(int i)
1854{
1855	tsproc_t *tspp;
1856	kthread_t *tx;
1857	int updated = 0;
1858
1859	mutex_enter(&ts_list_lock[i]);
1860	for (tspp = ts_plisthead[i].ts_next; tspp != &ts_plisthead[i];
1861	    tspp = tspp->ts_next) {
1862		tx = tspp->ts_tp;
1863		/*
1864		 * Lock the thread and verify state.
1865		 */
1866		thread_lock(tx);
1867		/*
1868		 * Skip the thread if it is no longer in the TS (or IA) class.
1869		 */
1870		if (tx->t_clfuncs != &ts_classfuncs.thread &&
1871		    tx->t_clfuncs != &ia_classfuncs.thread)
1872			goto next;
1873		tspp->ts_dispwait++;
1874		if ((tspp->ts_flags & TSKPRI) != 0)
1875			goto next;
1876		if (tspp->ts_dispwait <= ts_dptbl[tspp->ts_umdpri].ts_maxwait)
1877			goto next;
1878		if (tx->t_schedctl && schedctl_get_nopreempt(tx))
1879			goto next;
1880		if (tx->t_state != TS_RUN && (tx->t_state != TS_SLEEP ||
1881		    !ts_sleep_promote)) {
1882			/* make next syscall/trap do CL_TRAPRET */
1883			tx->t_trapret = 1;
1884			aston(tx);
1885			goto next;
1886		}
1887		tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_lwait;
1888		TS_NEWUMDPRI(tspp);
1889		tspp->ts_dispwait = 0;
1890		updated = 1;
1891
1892		/*
1893		 * Only dequeue it if needs to move; otherwise it should
1894		 * just round-robin here.
1895		 */
1896		if (tx->t_pri != ts_dptbl[tspp->ts_umdpri].ts_globpri) {
1897			pri_t oldpri = tx->t_pri;
1898			ts_change_priority(tx, tspp);
1899			TRACE_2(TR_FAC_DISP, TR_UPDATE,
1900			    "update:tid %p old pri %d", tx, oldpri);
1901		}
1902next:
1903		thread_unlock(tx);
1904	}
1905	mutex_exit(&ts_list_lock[i]);
1906
1907	return (updated);
1908}
1909
1910
1911/*
1912 * Processes waking up go to the back of their queue.  We don't
1913 * need to assign a time quantum here because thread is still
1914 * at a kernel mode priority and the time slicing is not done
1915 * for threads running in the kernel after sleeping.  The proper
1916 * time quantum will be assigned by ts_trapret before the thread
1917 * returns to user mode.
1918 */
1919static void
1920ts_wakeup(kthread_t *t)
1921{
1922	tsproc_t	*tspp = (tsproc_t *)(t->t_cldata);
1923
1924	ASSERT(THREAD_LOCK_HELD(t));
1925
1926	t->t_stime = lbolt;		/* time stamp for the swapper */
1927
1928	if (tspp->ts_flags & TSKPRI) {
1929		tspp->ts_flags &= ~TSBACKQ;
1930		if (tspp->ts_flags & TSIASET)
1931			setfrontdq(t);
1932		else
1933			setbackdq(t);
1934	} else if (t->t_kpri_req) {
1935		/*
1936		 * Give thread a priority boost if we were asked.
1937		 */
1938		tspp->ts_flags |= TSKPRI;
1939		THREAD_CHANGE_PRI(t, ts_kmdpris[0]);
1940		setbackdq(t);
1941		t->t_trapret = 1;	/* so that ts_trapret will run */
1942		aston(t);
1943	} else {
1944		if (tspp->ts_dispwait > ts_dptbl[tspp->ts_umdpri].ts_maxwait) {
1945			tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_slpret;
1946			TS_NEWUMDPRI(tspp);
1947			tspp->ts_timeleft =
1948			    ts_dptbl[tspp->ts_cpupri].ts_quantum;
1949			tspp->ts_dispwait = 0;
1950			THREAD_CHANGE_PRI(t,
1951			    ts_dptbl[tspp->ts_umdpri].ts_globpri);
1952			ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
1953		}
1954
1955		tspp->ts_flags &= ~TSBACKQ;
1956
1957		if (tspp->ts_flags & TSIA) {
1958			if (tspp->ts_flags & TSIASET)
1959				setfrontdq(t);
1960			else
1961				setbackdq(t);
1962		} else {
1963			if (t->t_disp_time != lbolt)
1964				setbackdq(t);
1965			else
1966				setfrontdq(t);
1967		}
1968	}
1969}
1970
1971
1972/*
1973 * When a thread yields, put it on the back of the run queue.
1974 */
1975static void
1976ts_yield(kthread_t *t)
1977{
1978	tsproc_t	*tspp = (tsproc_t *)(t->t_cldata);
1979
1980	ASSERT(t == curthread);
1981	ASSERT(THREAD_LOCK_HELD(t));
1982
1983	/*
1984	 * Clear the preemption control "yield" bit since the user is
1985	 * doing a yield.
1986	 */
1987	if (t->t_schedctl)
1988		schedctl_set_yield(t, 0);
1989	/*
1990	 * If ts_preempt() artifically increased the thread's priority
1991	 * to avoid preemption, restore the original priority now.
1992	 */
1993	if (tspp->ts_flags & TSRESTORE) {
1994		THREAD_CHANGE_PRI(t, tspp->ts_scpri);
1995		tspp->ts_flags &= ~TSRESTORE;
1996	}
1997	if (tspp->ts_timeleft <= 0) {
1998		/*
1999		 * Time slice was artificially extended to avoid
2000		 * preemption, so pretend we're preempting it now.
2001		 */
2002		DTRACE_SCHED1(schedctl__yield, int, -tspp->ts_timeleft);
2003		tspp->ts_cpupri = ts_dptbl[tspp->ts_cpupri].ts_tqexp;
2004		TS_NEWUMDPRI(tspp);
2005		tspp->ts_timeleft = ts_dptbl[tspp->ts_cpupri].ts_quantum;
2006		tspp->ts_dispwait = 0;
2007		THREAD_CHANGE_PRI(t, ts_dptbl[tspp->ts_umdpri].ts_globpri);
2008		ASSERT(t->t_pri >= 0 && t->t_pri <= ts_maxglobpri);
2009	}
2010	tspp->ts_flags &= ~TSBACKQ;
2011	setbackdq(t);
2012}
2013
2014
2015/*
2016 * Increment the nice value of the specified thread by incr and
2017 * return the new value in *retvalp.
2018 */
2019static int
2020ts_donice(kthread_t *t, cred_t *cr, int incr, int *retvalp)
2021{
2022	int		newnice;
2023	tsproc_t	*tspp = (tsproc_t *)(t->t_cldata);
2024	tsparms_t	tsparms;
2025
2026	ASSERT(MUTEX_HELD(&(ttoproc(t))->p_lock));
2027
2028	/* If there's no change to priority, just return current setting */
2029	if (incr == 0) {
2030		if (retvalp) {
2031			*retvalp = tspp->ts_nice - NZERO;
2032		}
2033		return (0);
2034	}
2035
2036	if ((incr < 0 || incr > 2 * NZERO) &&
2037	    secpolicy_setpriority(cr) != 0)
2038		return (EPERM);
2039
2040	/*
2041	 * Specifying a nice increment greater than the upper limit of
2042	 * 2 * NZERO - 1 will result in the thread's nice value being
2043	 * set to the upper limit.  We check for this before computing
2044	 * the new value because otherwise we could get overflow
2045	 * if a privileged process specified some ridiculous increment.
2046	 */
2047	if (incr > 2 * NZERO - 1)
2048		incr = 2 * NZERO - 1;
2049
2050	newnice = tspp->ts_nice + incr;
2051	if (newnice >= 2 * NZERO)
2052		newnice = 2 * NZERO - 1;
2053	else if (newnice < 0)
2054		newnice = 0;
2055
2056	tsparms.ts_uprilim = tsparms.ts_upri =
2057		-((newnice - NZERO) * ts_maxupri) / NZERO;
2058	/*
2059	 * Reset the uprilim and upri values of the thread.
2060	 * Call ts_parmsset even if thread is interactive since we're
2061	 * not changing mode.
2062	 */
2063	(void) ts_parmsset(t, (void *)&tsparms, (id_t)0, (cred_t *)NULL);
2064
2065	/*
2066	 * Although ts_parmsset already reset ts_nice it may
2067	 * not have been set to precisely the value calculated above
2068	 * because ts_parmsset determines the nice value from the
2069	 * user priority and we may have truncated during the integer
2070	 * conversion from nice value to user priority and back.
2071	 * We reset ts_nice to the value we calculated above.
2072	 */
2073	tspp->ts_nice = (char)newnice;
2074
2075	if (retvalp)
2076		*retvalp = newnice - NZERO;
2077	return (0);
2078}
2079
2080
2081/*
2082 * ia_set_process_group marks foreground processes as interactive
2083 * and background processes as non-interactive iff the session
2084 * leader is interactive.  This routine is called from two places:
2085 *	strioctl:SPGRP when a new process group gets
2086 * 		control of the tty.
2087 *	ia_parmsset-when the process in question is a session leader.
2088 * ia_set_process_group assumes that pidlock is held by the caller,
2089 * either strioctl or priocntlsys.  If the caller is priocntlsys
2090 * (via ia_parmsset) then the p_lock of the session leader is held
2091 * and the code needs to be careful about acquiring other p_locks.
2092 */
2093static void
2094ia_set_process_group(pid_t sid, pid_t bg_pgid, pid_t fg_pgid)
2095{
2096	proc_t 		*leader, *fg, *bg;
2097	tsproc_t	*tspp;
2098	kthread_t	*tx;
2099	int		plocked = 0;
2100
2101	ASSERT(MUTEX_HELD(&pidlock));
2102
2103	/*
2104	 * see if the session leader is interactive AND
2105	 * if it is currently "on" AND controlling a tty
2106	 * iff it is then make the processes in the foreground
2107	 * group interactive and the processes in the background
2108	 * group non-interactive.
2109	 */
2110	if ((leader = (proc_t *)prfind(sid)) == NULL) {
2111		return;
2112	}
2113	if (leader->p_stat == SIDL) {
2114		return;
2115	}
2116	if ((tx = proctot(leader)) == NULL) {
2117		return;
2118	}
2119	/*
2120	 * XXX do all the threads in the leader
2121	 */
2122	if (tx->t_cid != ia_cid) {
2123		return;
2124	}
2125	tspp = tx->t_cldata;
2126	/*
2127	 * session leaders that are not interactive need not have
2128	 * any processing done for them.  They are typically shells
2129	 * that do not have focus and are changing the process group
2130	 * attatched to the tty, e.g. a process that is exiting
2131	 */
2132	mutex_enter(&leader->p_sessp->s_lock);
2133	if (!(tspp->ts_flags & TSIASET) ||
2134	    (leader->p_sessp->s_vp == NULL) ||
2135	    (leader->p_sessp->s_vp->v_stream == NULL)) {
2136		mutex_exit(&leader->p_sessp->s_lock);
2137		return;
2138	}
2139	mutex_exit(&leader->p_sessp->s_lock);
2140
2141	/*
2142	 * If we're already holding the leader's p_lock, we should use
2143	 * mutex_tryenter instead of mutex_enter to avoid deadlocks from
2144	 * lock ordering violations.
2145	 */
2146	if (mutex_owned(&leader->p_lock))
2147		plocked = 1;
2148
2149	if (fg_pgid == 0)
2150		goto skip;
2151	/*
2152	 * now look for all processes in the foreground group and
2153	 * make them interactive
2154	 */
2155	for (fg = (proc_t *)pgfind(fg_pgid); fg != NULL; fg = fg->p_pglink) {
2156		/*
2157		 * if the process is SIDL it's begin forked, ignore it
2158		 */
2159		if (fg->p_stat == SIDL) {
2160			continue;
2161		}
2162		/*
2163		 * sesssion leaders must be turned on/off explicitly
2164		 * not implicitly as happens to other members of
2165		 * the process group.
2166		 */
2167		if (fg->p_pid  == fg->p_sessp->s_sid) {
2168			continue;
2169		}
2170
2171		TRACE_1(TR_FAC_IA, TR_GROUP_ON,
2172		    "group on:proc %p", fg);
2173
2174		if (plocked) {
2175			if (mutex_tryenter(&fg->p_lock) == 0)
2176				continue;
2177		} else {
2178			mutex_enter(&fg->p_lock);
2179		}
2180
2181		if ((tx = proctot(fg)) == NULL) {
2182			mutex_exit(&fg->p_lock);
2183			continue;
2184		}
2185		do {
2186			thread_lock(tx);
2187			/*
2188			 * if this thread is not interactive continue
2189			 */
2190			if (tx->t_cid != ia_cid) {
2191				thread_unlock(tx);
2192				continue;
2193			}
2194			tspp = tx->t_cldata;
2195			tspp->ts_flags |= TSIASET;
2196			tspp->ts_boost = ia_boost;
2197			TS_NEWUMDPRI(tspp);
2198			if ((tspp->ts_flags & TSKPRI) != 0) {
2199				thread_unlock(tx);
2200				continue;
2201			}
2202			tspp->ts_dispwait = 0;
2203			ts_change_priority(tx, tspp);
2204			thread_unlock(tx);
2205		} while ((tx = tx->t_forw) != fg->p_tlist);
2206		mutex_exit(&fg->p_lock);
2207	}
2208skip:
2209	if (bg_pgid == 0)
2210		return;
2211	for (bg = (proc_t *)pgfind(bg_pgid); bg != NULL; bg = bg->p_pglink) {
2212		if (bg->p_stat == SIDL) {
2213			continue;
2214		}
2215		/*
2216		 * sesssion leaders must be turned off explicitly
2217		 * not implicitly as happens to other members of
2218		 * the process group.
2219		 */
2220		if (bg->p_pid == bg->p_sessp->s_sid) {
2221			continue;
2222		}
2223
2224		TRACE_1(TR_FAC_IA, TR_GROUP_OFF,
2225		    "group off:proc %p", bg);
2226
2227		if (plocked) {
2228			if (mutex_tryenter(&bg->p_lock) == 0)
2229				continue;
2230		} else {
2231			mutex_enter(&bg->p_lock);
2232		}
2233
2234		if ((tx = proctot(bg)) == NULL) {
2235			mutex_exit(&bg->p_lock);
2236			continue;
2237		}
2238		do {
2239			thread_lock(tx);
2240			/*
2241			 * if this thread is not interactive continue
2242			 */
2243			if (tx->t_cid != ia_cid) {
2244				thread_unlock(tx);
2245				continue;
2246			}
2247			tspp = tx->t_cldata;
2248			tspp->ts_flags &= ~TSIASET;
2249			tspp->ts_boost = -ia_boost;
2250			TS_NEWUMDPRI(tspp);
2251			if ((tspp->ts_flags & TSKPRI) != 0) {
2252				thread_unlock(tx);
2253				continue;
2254			}
2255
2256			tspp->ts_dispwait = 0;
2257			ts_change_priority(tx, tspp);
2258			thread_unlock(tx);
2259		} while ((tx = tx->t_forw) != bg->p_tlist);
2260		mutex_exit(&bg->p_lock);
2261	}
2262}
2263
2264
2265static void
2266ts_change_priority(kthread_t *t, tsproc_t *tspp)
2267{
2268	pri_t	new_pri;
2269
2270	ASSERT(THREAD_LOCK_HELD(t));
2271	new_pri = ts_dptbl[tspp->ts_umdpri].ts_globpri;
2272	ASSERT(new_pri >= 0 && new_pri <= ts_maxglobpri);
2273	tspp->ts_flags &= ~TSRESTORE;
2274	if (t == curthread || t->t_state == TS_ONPROC) {
2275		/* curthread is always onproc */
2276		cpu_t	*cp = t->t_disp_queue->disp_cpu;
2277		THREAD_CHANGE_PRI(t, new_pri);
2278		if (t == cp->cpu_dispthread)
2279			cp->cpu_dispatch_pri = DISP_PRIO(t);
2280		if (DISP_MUST_SURRENDER(t)) {
2281			tspp->ts_flags |= TSBACKQ;
2282			cpu_surrender(t);
2283		} else {
2284			tspp->ts_timeleft =
2285			    ts_dptbl[tspp->ts_cpupri].ts_quantum;
2286		}
2287	} else {
2288		int	frontq;
2289
2290		frontq = (tspp->ts_flags & TSIASET) != 0;
2291		/*
2292		 * When the priority of a thread is changed,
2293		 * it may be necessary to adjust its position
2294		 * on a sleep queue or dispatch queue.
2295		 * The function thread_change_pri accomplishes
2296		 * this.
2297		 */
2298		if (thread_change_pri(t, new_pri, frontq)) {
2299			/*
2300			 * The thread was on a run queue. Reset
2301			 * its CPU timeleft from the quantum
2302			 * associated with the new priority.
2303			 */
2304			tspp->ts_timeleft =
2305			    ts_dptbl[tspp->ts_cpupri].ts_quantum;
2306		} else {
2307			tspp->ts_flags |= TSBACKQ;
2308		}
2309	}
2310}
2311
2312static int
2313ts_alloc(void **p, int flag)
2314{
2315	void *bufp;
2316	bufp = kmem_alloc(sizeof (tsproc_t), flag);
2317	if (bufp == NULL) {
2318		return (ENOMEM);
2319	} else {
2320		*p = bufp;
2321		return (0);
2322	}
2323}
2324
2325static void
2326ts_free(void *bufp)
2327{
2328	if (bufp)
2329		kmem_free(bufp, sizeof (tsproc_t));
2330}
2331