xref: /illumos-gate/usr/src/uts/common/disp/fss.c (revision 4f9241761deff31c4840b1283ffc458661ee7dca)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 1994, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright 2019 Joyent, Inc.
25  */
26 
27 #include <sys/types.h>
28 #include <sys/param.h>
29 #include <sys/sysmacros.h>
30 #include <sys/cred.h>
31 #include <sys/proc.h>
32 #include <sys/strsubr.h>
33 #include <sys/priocntl.h>
34 #include <sys/class.h>
35 #include <sys/disp.h>
36 #include <sys/procset.h>
37 #include <sys/debug.h>
38 #include <sys/kmem.h>
39 #include <sys/errno.h>
40 #include <sys/systm.h>
41 #include <sys/schedctl.h>
42 #include <sys/vmsystm.h>
43 #include <sys/atomic.h>
44 #include <sys/project.h>
45 #include <sys/modctl.h>
46 #include <sys/fss.h>
47 #include <sys/fsspriocntl.h>
48 #include <sys/cpupart.h>
49 #include <sys/zone.h>
50 #include <vm/rm.h>
51 #include <vm/seg_kmem.h>
52 #include <sys/policy.h>
53 #include <sys/sdt.h>
54 #include <sys/cpucaps.h>
55 
56 /*
57  * The fair share scheduling class ensures that collections of processes
58  * (zones and projects) each get their configured share of CPU.  This is in
59  * contrast to the TS class which considers individual processes.
60  *
61  * The FSS cpu-share is set on zones using the zone.cpu-shares rctl and on
62  * projects using the project.cpu-shares rctl.  By default the value is 1
63  * and it can range from 0 - 64k.  A value of 0 means that processes in the
64  * collection will only get CPU resources when there are no other processes
65  * that need CPU. The cpu-share is used as one of the inputs to calculate a
66  * thread's "user-mode" priority (umdpri) for the scheduler.  The umdpri falls
67  * in the range 0-59.  FSS calculates other, internal, priorities which are not
68  * visible outside of the FSS class.
69  *
70  * The FSS class should approximate TS behavior when there are excess CPU
71  * resources.  When there is a backlog of runnable processes, then the share
72  * is used as input into the runnable process's priority calculation, where
73  * the final umdpri is used by the scheduler to determine when the process runs.
74  *
75  * Projects in a zone compete with each other for CPU time, receiving CPU
76  * allocation within a zone proportional to the project's share; at a higher
77  * level zones compete with each other, receiving allocation in a pset
78  * proportional to the zone's share.
79  *
80  * The FSS priority calculation consists of several parts.
81  *
82  * 1) Once per second the fss_update function runs. The first thing it does is
83  *    call fss_decay_usage. This function does three things.
84  *
85  * a) fss_decay_usage first decays the maxfsspri value for the pset.  This
86  *    value is used in the per-process priority calculation described in step
87  *    (2b).  The maxfsspri is decayed using the following formula:
88  *
89  *                      maxfsspri * fss_nice_decay[NZERO])
90  *        maxfsspri =  ------------------------------------
91  *                            FSS_DECAY_BASE
92  *
93  *
94  *     - NZERO is the default process priority (i.e. 20)
95  *
96  *    The fss_nice_decay array is a fixed set of values used to adjust the
97  *    decay rate of processes based on their nice value.  Entries in this
98  *    array are initialized in fss_init using the following formula:
99  *
100  *                        (FSS_DECAY_MAX - FSS_DECAY_MIN) * i
101  *       FSS_DECAY_MIN + -------------------------------------
102  *                               FSS_NICE_RANGE - 1
103  *
104  *     - FSS_DECAY_MIN is 82 = approximates 65% (82/128)
105  *     - FSS_DECAY_MAX is 108 = approximates 85% (108/128)
106  *     - FSS_NICE_RANGE is 40 (range is 0 - 39)
107  *
108  * b) The second thing fss_decay_usage does is update each project's "usage"
109  *    for the last second and then recalculates the project's "share usage".
110  *
111  *    The usage value is the recent CPU usage for all of the threads in the
112  *    project. It is decayed and updated this way:
113  *
114  *                  (usage * FSS_DECAY_USG)
115  *        usage =  ------------------------- + ticks;
116  *                       FSS_DECAY_BASE
117  *
118  *     - FSS_DECAY_BASE is 128 - used instead of 100 so we can shift vs divide
119  *     - FSS_DECAY_USG is 96 - approximates 75% (96/128)
120  *     - ticks is updated whenever a process in this project is running
121  *       when the scheduler's tick processing fires. This is not a simple
122  *       counter, the values are based on the entries in the fss_nice_tick
123  *       array (see section 3 below). ticks is then reset to 0 so it can track
124  *       the next seconds worth of nice-adjusted time for the project.
125  *
126  * c) The third thing fss_decay_usage does is update each project's "share
127  *    usage" (shusage). This is the normalized usage value for the project and
128  *    is calculated this way:
129  *
130  *                pset_shares^2    zone_int_shares^2
131  *        usage * ------------- * ------------------
132  *                kpj_shares^2	   zone_ext_shares^2
133  *
134  *    - usage - see (1b) for more details
135  *    - pset_shares is the total of all *active* zone shares in the pset (by
136  *      default there is only one pset)
137  *    - kpj_shares is the individual project's share (project.cpu-shares rctl)
138  *    - zone_int_shares is the sum of shares of all active projects within the
139  *      zone (the zone-internal total)
140  *    - zone_ext_shares is the share value for the zone (zone.cpu-shares rctl)
141  *
142  *    The shusage is used in step (2b) to calculate the thread's new internal
143  *    priority. A larger shusage value leads to a lower priority.
144  *
145  * 2) The fss_update function then calls fss_update_list to update the priority
146  *    of all threads. This does two things.
147  *
148  * a) First the thread's internal priority is decayed using the following
149  *    formula:
150  *
151  *                  fsspri * fss_nice_decay[nice_value])
152  *        fsspri =  ------------------------------------
153  *                            FSS_DECAY_BASE
154  *
155  *     - FSS_DECAY_BASE is 128 as described above
156  *
157  * b) Second, if the thread is runnable (TS_RUN or TS_WAIT) calls fss_newpri
158  *    to update the user-mode priority (umdpri) of the runnable thread.
159  *    Threads that are running (TS_ONPROC) or waiting for an event (TS_SLEEP)
160  *    are not updated at this time. The updated user-mode priority can cause
161  *    threads to change their position in the run queue.
162  *
163  *    The process's new internal fsspri is calculated using the following
164  *    formula. All runnable threads in the project will use the same shusage
165  *    and nrunnable values in their calculation.
166  *
167  *        fsspri += shusage * nrunnable * ticks
168  *
169  *     - shusage is the project's share usage, calculated in (1c)
170  *     - nrunnable is the number of runnable threads in the project
171  *     - ticks is the number of ticks this thread ran since the last fss_newpri
172  *       invocation.
173  *
174  *    Finally the process's new user-mode priority is calculated using the
175  *    following formula:
176  *
177  *                              (fsspri * umdprirange)
178  *        umdpri = maxumdpri - ------------------------
179  *                                    maxfsspri
180  *
181  *     - maxumdpri is MINCLSYSPRI - 1 (i.e. 59)
182  *     - umdprirange is maxumdpri - 1 (i.e. 58)
183  *     - maxfsspri is the largest fsspri seen so far, as we're iterating all
184  *       runnable processes
185  *
186  *    Thus, a higher internal priority (fsspri) leads to a lower user-mode
187  *    priority which means the thread runs less. The fsspri is higher when
188  *    the project's normalized share usage is higher, when the project has
189  *    more runnable threads, or when the thread has accumulated more run-time.
190  *
191  *    This code has various checks to ensure the resulting umdpri is in the
192  *    range 1-59.  See fss_newpri for more details.
193  *
194  * To reiterate, the above processing is performed once per second to recompute
195  * the runnable thread user-mode priorities.
196  *
197  * 3) The final major component in the priority calculation is the tick
198  *    processing which occurs on a thread that is running when the clock
199  *    calls fss_tick.
200  *
201  *    A thread can run continuously in user-land (compute-bound) for the
202  *    fss_quantum (see "dispadmin -c FSS -g" for the configurable properties).
203  *    The fss_quantum defaults to 11 (i.e. 11 ticks).
204  *
205  *    Once the quantum has been consumed, the thread will call fss_newpri to
206  *    recompute its umdpri priority, as described above in (2b). Threads that
207  *    were T_ONPROC at the one second interval when runnable thread priorities
208  *    were recalculated will have their umdpri priority recalculated when their
209  *    quanta expires.
210  *
211  *    To ensure that runnable threads within a project see the expected
212  *    round-robin behavior, there is a special case in fss_newpri for a thread
213  *    that has run for its quanta within the one second update interval.  See
214  *    the handling for the quanta_up parameter within fss_newpri.
215  *
216  *    Also of interest, the fss_tick code increments the project's tick value
217  *    using the fss_nice_tick array entry for the thread's nice value. The idea
218  *    behind the fss_nice_tick array is that the cost of a tick is lower at
219  *    positive nice values (so that it doesn't increase the project's usage
220  *    as much as normal) with a 50% drop at the maximum level and a 50%
221  *    increase at the minimum level. See (1b). The fss_nice_tick array is
222  *    initialized in fss_init using the following formula:
223  *
224  *         FSS_TICK_COST * (((3 * FSS_NICE_RANGE) / 2) - i)
225  *        --------------------------------------------------
226  *                          FSS_NICE_RANGE
227  *
228  *     - FSS_TICK_COST is 1000, the tick cost for threads with nice level 0
229  *
230  * FSS Data Structures:
231  *
232  *                 fsszone
233  *                  -----           -----
234  *  -----          |     |         |     |
235  * |     |-------->|     |<------->|     |<---->...
236  * |     |          -----           -----
237  * |     |          ^    ^            ^
238  * |     |---       |     \            \
239  *  -----    |      |      \            \
240  * fsspset   |      |       \            \
241  *           |      |        \            \
242  *           |    -----       -----       -----
243  *            -->|     |<--->|     |<--->|     |
244  *               |     |     |     |     |     |
245  *                -----       -----       -----
246  *               fssproj
247  *
248  * That is, fsspsets contain a list of fsszone's that are currently active in
249  * the pset, and a list of fssproj's, corresponding to projects with runnable
250  * threads on the pset.  fssproj's in turn point to the fsszone which they
251  * are a member of.
252  *
253  * An fssproj_t is removed when there are no threads in it.
254  *
255  * An fsszone_t is removed when there are no projects with threads in it.
256  */
257 
258 static pri_t fss_init(id_t, int, classfuncs_t **);
259 
260 static struct sclass fss = {
261 	"FSS",
262 	fss_init,
263 	0
264 };
265 
266 extern struct mod_ops mod_schedops;
267 
268 /*
269  * Module linkage information for the kernel.
270  */
271 static struct modlsched modlsched = {
272 	&mod_schedops, "fair share scheduling class", &fss
273 };
274 
275 static struct modlinkage modlinkage = {
276 	MODREV_1, (void *)&modlsched, NULL
277 };
278 
279 #define	FSS_MAXUPRI	60
280 
281 /*
282  * The fssproc_t structures are kept in an array of circular doubly linked
283  * lists.  A hash on the thread pointer is used to determine which list each
284  * thread should be placed in.  Each list has a dummy "head" which is never
285  * removed, so the list is never empty.  fss_update traverses these lists to
286  * update the priorities of threads that have been waiting on the run queue.
287  */
288 #define	FSS_LISTS		16 /* number of lists, must be power of 2 */
289 #define	FSS_LIST_HASH(t)	(((uintptr_t)(t) >> 9) & (FSS_LISTS - 1))
290 #define	FSS_LIST_NEXT(i)	(((i) + 1) & (FSS_LISTS - 1))
291 
292 #define	FSS_LIST_INSERT(fssproc)				\
293 {								\
294 	int index = FSS_LIST_HASH(fssproc->fss_tp);		\
295 	kmutex_t *lockp = &fss_listlock[index];			\
296 	fssproc_t *headp = &fss_listhead[index];		\
297 	mutex_enter(lockp);					\
298 	fssproc->fss_next = headp->fss_next;			\
299 	fssproc->fss_prev = headp;				\
300 	headp->fss_next->fss_prev = fssproc;			\
301 	headp->fss_next = fssproc;				\
302 	mutex_exit(lockp);					\
303 }
304 
305 #define	FSS_LIST_DELETE(fssproc)				\
306 {								\
307 	int index = FSS_LIST_HASH(fssproc->fss_tp);		\
308 	kmutex_t *lockp = &fss_listlock[index];			\
309 	mutex_enter(lockp);					\
310 	fssproc->fss_prev->fss_next = fssproc->fss_next;	\
311 	fssproc->fss_next->fss_prev = fssproc->fss_prev;	\
312 	mutex_exit(lockp);					\
313 }
314 
315 #define	FSS_TICK_COST	1000	/* tick cost for threads with nice level = 0 */
316 
317 /*
318  * Decay rate percentages are based on n/128 rather than n/100 so  that
319  * calculations can avoid having to do an integer divide by 100 (divide
320  * by FSS_DECAY_BASE == 128 optimizes to an arithmetic shift).
321  *
322  * FSS_DECAY_MIN	=  83/128 ~= 65%
323  * FSS_DECAY_MAX	= 108/128 ~= 85%
324  * FSS_DECAY_USG	=  96/128 ~= 75%
325  */
326 #define	FSS_DECAY_MIN	83	/* fsspri decay pct for threads w/ nice -20 */
327 #define	FSS_DECAY_MAX	108	/* fsspri decay pct for threads w/ nice +19 */
328 #define	FSS_DECAY_USG	96	/* fssusage decay pct for projects */
329 #define	FSS_DECAY_BASE	128	/* base for decay percentages above */
330 
331 #define	FSS_NICE_MIN	0
332 #define	FSS_NICE_MAX	(2 * NZERO - 1)
333 #define	FSS_NICE_RANGE	(FSS_NICE_MAX - FSS_NICE_MIN + 1)
334 
335 static int	fss_nice_tick[FSS_NICE_RANGE];
336 static int	fss_nice_decay[FSS_NICE_RANGE];
337 
338 static pri_t	fss_maxupri = FSS_MAXUPRI; /* maximum FSS user priority */
339 static pri_t	fss_maxumdpri; /* maximum user mode fss priority */
340 static pri_t	fss_maxglobpri;	/* maximum global priority used by fss class */
341 static pri_t	fss_minglobpri;	/* minimum global priority */
342 
343 static fssproc_t fss_listhead[FSS_LISTS];
344 static kmutex_t	fss_listlock[FSS_LISTS];
345 
346 static fsspset_t *fsspsets;
347 static kmutex_t fsspsets_lock;	/* protects fsspsets */
348 
349 static id_t	fss_cid;
350 
351 static time_t	fss_minrun = 2;	/* t_pri becomes 59 within 2 secs */
352 static time_t	fss_minslp = 2;	/* min time on sleep queue for hardswap */
353 static int	fss_quantum = 11;
354 
355 static void	fss_newpri(fssproc_t *, boolean_t);
356 static void	fss_update(void *);
357 static int	fss_update_list(int);
358 static void	fss_change_priority(kthread_t *, fssproc_t *);
359 
360 static int	fss_admin(caddr_t, cred_t *);
361 static int	fss_getclinfo(void *);
362 static int	fss_parmsin(void *);
363 static int	fss_parmsout(void *, pc_vaparms_t *);
364 static int	fss_vaparmsin(void *, pc_vaparms_t *);
365 static int	fss_vaparmsout(void *, pc_vaparms_t *);
366 static int	fss_getclpri(pcpri_t *);
367 static int	fss_alloc(void **, int);
368 static void	fss_free(void *);
369 
370 static int	fss_enterclass(kthread_t *, id_t, void *, cred_t *, void *);
371 static void	fss_exitclass(void *);
372 static int	fss_canexit(kthread_t *, cred_t *);
373 static int	fss_fork(kthread_t *, kthread_t *, void *);
374 static void	fss_forkret(kthread_t *, kthread_t *);
375 static void	fss_parmsget(kthread_t *, void *);
376 static int	fss_parmsset(kthread_t *, void *, id_t, cred_t *);
377 static void	fss_stop(kthread_t *, int, int);
378 static void	fss_exit(kthread_t *);
379 static void	fss_active(kthread_t *);
380 static void	fss_inactive(kthread_t *);
381 static pri_t	fss_swapin(kthread_t *, int);
382 static pri_t	fss_swapout(kthread_t *, int);
383 static void	fss_trapret(kthread_t *);
384 static void	fss_preempt(kthread_t *);
385 static void	fss_setrun(kthread_t *);
386 static void	fss_sleep(kthread_t *);
387 static void	fss_tick(kthread_t *);
388 static void	fss_wakeup(kthread_t *);
389 static int	fss_donice(kthread_t *, cred_t *, int, int *);
390 static int	fss_doprio(kthread_t *, cred_t *, int, int *);
391 static pri_t	fss_globpri(kthread_t *);
392 static void	fss_yield(kthread_t *);
393 static void	fss_nullsys();
394 
395 static struct classfuncs fss_classfuncs = {
396 	/* class functions */
397 	fss_admin,
398 	fss_getclinfo,
399 	fss_parmsin,
400 	fss_parmsout,
401 	fss_vaparmsin,
402 	fss_vaparmsout,
403 	fss_getclpri,
404 	fss_alloc,
405 	fss_free,
406 
407 	/* thread functions */
408 	fss_enterclass,
409 	fss_exitclass,
410 	fss_canexit,
411 	fss_fork,
412 	fss_forkret,
413 	fss_parmsget,
414 	fss_parmsset,
415 	fss_stop,
416 	fss_exit,
417 	fss_active,
418 	fss_inactive,
419 	fss_swapin,
420 	fss_swapout,
421 	fss_trapret,
422 	fss_preempt,
423 	fss_setrun,
424 	fss_sleep,
425 	fss_tick,
426 	fss_wakeup,
427 	fss_donice,
428 	fss_globpri,
429 	fss_nullsys,	/* set_process_group */
430 	fss_yield,
431 	fss_doprio,
432 };
433 
434 int
435 _init()
436 {
437 	return (mod_install(&modlinkage));
438 }
439 
440 int
441 _fini()
442 {
443 	return (EBUSY);
444 }
445 
446 int
447 _info(struct modinfo *modinfop)
448 {
449 	return (mod_info(&modlinkage, modinfop));
450 }
451 
452 /*ARGSUSED*/
453 static int
454 fss_project_walker(kproject_t *kpj, void *buf)
455 {
456 	return (0);
457 }
458 
459 void *
460 fss_allocbuf(int op, int type)
461 {
462 	fssbuf_t *fssbuf;
463 	void **fsslist;
464 	int cnt;
465 	int i;
466 	size_t size;
467 
468 	ASSERT(op == FSS_NPSET_BUF || op == FSS_NPROJ_BUF || op == FSS_ONE_BUF);
469 	ASSERT(type == FSS_ALLOC_PROJ || type == FSS_ALLOC_ZONE);
470 	ASSERT(MUTEX_HELD(&cpu_lock));
471 
472 	fssbuf = kmem_zalloc(sizeof (fssbuf_t), KM_SLEEP);
473 	switch (op) {
474 	case FSS_NPSET_BUF:
475 		cnt = cpupart_list(NULL, 0, CP_NONEMPTY);
476 		break;
477 	case FSS_NPROJ_BUF:
478 		cnt = project_walk_all(ALL_ZONES, fss_project_walker, NULL);
479 		break;
480 	case FSS_ONE_BUF:
481 		cnt = 1;
482 		break;
483 	}
484 
485 	switch (type) {
486 	case FSS_ALLOC_PROJ:
487 		size = sizeof (fssproj_t);
488 		break;
489 	case FSS_ALLOC_ZONE:
490 		size = sizeof (fsszone_t);
491 		break;
492 	}
493 	fsslist = kmem_zalloc(cnt * sizeof (void *), KM_SLEEP);
494 	fssbuf->fssb_size = cnt;
495 	fssbuf->fssb_list = fsslist;
496 	for (i = 0; i < cnt; i++)
497 		fsslist[i] = kmem_zalloc(size, KM_SLEEP);
498 	return (fssbuf);
499 }
500 
501 void
502 fss_freebuf(fssbuf_t *fssbuf, int type)
503 {
504 	void **fsslist;
505 	int i;
506 	size_t size;
507 
508 	ASSERT(fssbuf != NULL);
509 	ASSERT(type == FSS_ALLOC_PROJ || type == FSS_ALLOC_ZONE);
510 	fsslist = fssbuf->fssb_list;
511 
512 	switch (type) {
513 	case FSS_ALLOC_PROJ:
514 		size = sizeof (fssproj_t);
515 		break;
516 	case FSS_ALLOC_ZONE:
517 		size = sizeof (fsszone_t);
518 		break;
519 	}
520 
521 	for (i = 0; i < fssbuf->fssb_size; i++) {
522 		if (fsslist[i] != NULL)
523 			kmem_free(fsslist[i], size);
524 	}
525 	kmem_free(fsslist, sizeof (void *) * fssbuf->fssb_size);
526 	kmem_free(fssbuf, sizeof (fssbuf_t));
527 }
528 
529 static fsspset_t *
530 fss_find_fsspset(cpupart_t *cpupart)
531 {
532 	int i;
533 	fsspset_t *fsspset = NULL;
534 	int found = 0;
535 
536 	ASSERT(cpupart != NULL);
537 	ASSERT(MUTEX_HELD(&fsspsets_lock));
538 
539 	/*
540 	 * Search for the cpupart pointer in the array of fsspsets.
541 	 */
542 	for (i = 0; i < max_ncpus; i++) {
543 		fsspset = &fsspsets[i];
544 		if (fsspset->fssps_cpupart == cpupart) {
545 			ASSERT(fsspset->fssps_nproj > 0);
546 			found = 1;
547 			break;
548 		}
549 	}
550 	if (found == 0) {
551 		/*
552 		 * If we didn't find anything, then use the first
553 		 * available slot in the fsspsets array.
554 		 */
555 		for (i = 0; i < max_ncpus; i++) {
556 			fsspset = &fsspsets[i];
557 			if (fsspset->fssps_cpupart == NULL) {
558 				ASSERT(fsspset->fssps_nproj == 0);
559 				found = 1;
560 				break;
561 			}
562 		}
563 		fsspset->fssps_cpupart = cpupart;
564 	}
565 	ASSERT(found == 1);
566 	return (fsspset);
567 }
568 
569 static void
570 fss_del_fsspset(fsspset_t *fsspset)
571 {
572 	ASSERT(MUTEX_HELD(&fsspsets_lock));
573 	ASSERT(MUTEX_HELD(&fsspset->fssps_lock));
574 	ASSERT(fsspset->fssps_nproj == 0);
575 	ASSERT(fsspset->fssps_list == NULL);
576 	ASSERT(fsspset->fssps_zones == NULL);
577 	fsspset->fssps_cpupart = NULL;
578 	fsspset->fssps_maxfsspri = 0;
579 	fsspset->fssps_shares = 0;
580 }
581 
582 /*
583  * The following routine returns a pointer to the fsszone structure which
584  * belongs to zone "zone" and cpu partition fsspset, if such structure exists.
585  */
586 static fsszone_t *
587 fss_find_fsszone(fsspset_t *fsspset, zone_t *zone)
588 {
589 	fsszone_t *fsszone;
590 
591 	ASSERT(MUTEX_HELD(&fsspset->fssps_lock));
592 
593 	if (fsspset->fssps_list != NULL) {
594 		/*
595 		 * There are projects/zones active on this cpu partition
596 		 * already.  Try to find our zone among them.
597 		 */
598 		fsszone = fsspset->fssps_zones;
599 		do {
600 			if (fsszone->fssz_zone == zone) {
601 				return (fsszone);
602 			}
603 			fsszone = fsszone->fssz_next;
604 		} while (fsszone != fsspset->fssps_zones);
605 	}
606 	return (NULL);
607 }
608 
609 /*
610  * The following routine links new fsszone structure into doubly linked list of
611  * zones active on the specified cpu partition.
612  */
613 static void
614 fss_insert_fsszone(fsspset_t *fsspset, zone_t *zone, fsszone_t *fsszone)
615 {
616 	ASSERT(MUTEX_HELD(&fsspset->fssps_lock));
617 
618 	fsszone->fssz_zone = zone;
619 	fsszone->fssz_rshares = zone->zone_shares;
620 
621 	if (fsspset->fssps_zones == NULL) {
622 		/*
623 		 * This will be the first fsszone for this fsspset
624 		 */
625 		fsszone->fssz_next = fsszone->fssz_prev = fsszone;
626 		fsspset->fssps_zones = fsszone;
627 	} else {
628 		/*
629 		 * Insert this fsszone to the doubly linked list.
630 		 */
631 		fsszone_t *fssz_head = fsspset->fssps_zones;
632 
633 		fsszone->fssz_next = fssz_head;
634 		fsszone->fssz_prev = fssz_head->fssz_prev;
635 		fssz_head->fssz_prev->fssz_next = fsszone;
636 		fssz_head->fssz_prev = fsszone;
637 		fsspset->fssps_zones = fsszone;
638 	}
639 }
640 
641 /*
642  * The following routine removes a single fsszone structure from the doubly
643  * linked list of zones active on the specified cpu partition.  Note that
644  * global fsspsets_lock must be held in case this fsszone structure is the last
645  * on the above mentioned list.  Also note that the fsszone structure is not
646  * freed here, it is the responsibility of the caller to call kmem_free for it.
647  */
648 static void
649 fss_remove_fsszone(fsspset_t *fsspset, fsszone_t *fsszone)
650 {
651 	ASSERT(MUTEX_HELD(&fsspset->fssps_lock));
652 	ASSERT(fsszone->fssz_nproj == 0);
653 	ASSERT(fsszone->fssz_shares == 0);
654 	ASSERT(fsszone->fssz_runnable == 0);
655 
656 	if (fsszone->fssz_next != fsszone) {
657 		/*
658 		 * This is not the last zone in the list.
659 		 */
660 		fsszone->fssz_prev->fssz_next = fsszone->fssz_next;
661 		fsszone->fssz_next->fssz_prev = fsszone->fssz_prev;
662 		if (fsspset->fssps_zones == fsszone)
663 			fsspset->fssps_zones = fsszone->fssz_next;
664 	} else {
665 		/*
666 		 * This was the last zone active in this cpu partition.
667 		 */
668 		fsspset->fssps_zones = NULL;
669 	}
670 }
671 
672 /*
673  * The following routine returns a pointer to the fssproj structure
674  * which belongs to project kpj and cpu partition fsspset, if such structure
675  * exists.
676  */
677 static fssproj_t *
678 fss_find_fssproj(fsspset_t *fsspset, kproject_t *kpj)
679 {
680 	fssproj_t *fssproj;
681 
682 	ASSERT(MUTEX_HELD(&fsspset->fssps_lock));
683 
684 	if (fsspset->fssps_list != NULL) {
685 		/*
686 		 * There are projects running on this cpu partition already.
687 		 * Try to find our project among them.
688 		 */
689 		fssproj = fsspset->fssps_list;
690 		do {
691 			if (fssproj->fssp_proj == kpj) {
692 				ASSERT(fssproj->fssp_pset == fsspset);
693 				return (fssproj);
694 			}
695 			fssproj = fssproj->fssp_next;
696 		} while (fssproj != fsspset->fssps_list);
697 	}
698 	return (NULL);
699 }
700 
701 /*
702  * The following routine links new fssproj structure into doubly linked list
703  * of projects running on the specified cpu partition.
704  */
705 static void
706 fss_insert_fssproj(fsspset_t *fsspset, kproject_t *kpj, fsszone_t *fsszone,
707     fssproj_t *fssproj)
708 {
709 	ASSERT(MUTEX_HELD(&fsspset->fssps_lock));
710 
711 	fssproj->fssp_pset = fsspset;
712 	fssproj->fssp_proj = kpj;
713 	fssproj->fssp_shares = kpj->kpj_shares;
714 
715 	fsspset->fssps_nproj++;
716 
717 	if (fsspset->fssps_list == NULL) {
718 		/*
719 		 * This will be the first fssproj for this fsspset
720 		 */
721 		fssproj->fssp_next = fssproj->fssp_prev = fssproj;
722 		fsspset->fssps_list = fssproj;
723 	} else {
724 		/*
725 		 * Insert this fssproj to the doubly linked list.
726 		 */
727 		fssproj_t *fssp_head = fsspset->fssps_list;
728 
729 		fssproj->fssp_next = fssp_head;
730 		fssproj->fssp_prev = fssp_head->fssp_prev;
731 		fssp_head->fssp_prev->fssp_next = fssproj;
732 		fssp_head->fssp_prev = fssproj;
733 		fsspset->fssps_list = fssproj;
734 	}
735 	fssproj->fssp_fsszone = fsszone;
736 	fsszone->fssz_nproj++;
737 	ASSERT(fsszone->fssz_nproj != 0);
738 }
739 
740 /*
741  * The following routine removes a single fssproj structure from the doubly
742  * linked list of projects running on the specified cpu partition.  Note that
743  * global fsspsets_lock must be held in case if this fssproj structure is the
744  * last on the above mentioned list.  Also note that the fssproj structure is
745  * not freed here, it is the responsibility of the caller to call kmem_free
746  * for it.
747  */
748 static void
749 fss_remove_fssproj(fsspset_t *fsspset, fssproj_t *fssproj)
750 {
751 	fsszone_t *fsszone;
752 
753 	ASSERT(MUTEX_HELD(&fsspsets_lock));
754 	ASSERT(MUTEX_HELD(&fsspset->fssps_lock));
755 	ASSERT(fssproj->fssp_runnable == 0);
756 
757 	fsspset->fssps_nproj--;
758 
759 	fsszone = fssproj->fssp_fsszone;
760 	fsszone->fssz_nproj--;
761 
762 	if (fssproj->fssp_next != fssproj) {
763 		/*
764 		 * This is not the last part in the list.
765 		 */
766 		fssproj->fssp_prev->fssp_next = fssproj->fssp_next;
767 		fssproj->fssp_next->fssp_prev = fssproj->fssp_prev;
768 		if (fsspset->fssps_list == fssproj)
769 			fsspset->fssps_list = fssproj->fssp_next;
770 		if (fsszone->fssz_nproj == 0)
771 			fss_remove_fsszone(fsspset, fsszone);
772 	} else {
773 		/*
774 		 * This was the last project part running
775 		 * at this cpu partition.
776 		 */
777 		fsspset->fssps_list = NULL;
778 		ASSERT(fsspset->fssps_nproj == 0);
779 		ASSERT(fsszone->fssz_nproj == 0);
780 		fss_remove_fsszone(fsspset, fsszone);
781 		fss_del_fsspset(fsspset);
782 	}
783 }
784 
785 static void
786 fss_inactive(kthread_t *t)
787 {
788 	fssproc_t *fssproc;
789 	fssproj_t *fssproj;
790 	fsspset_t *fsspset;
791 	fsszone_t *fsszone;
792 
793 	ASSERT(THREAD_LOCK_HELD(t));
794 	fssproc = FSSPROC(t);
795 	fssproj = FSSPROC2FSSPROJ(fssproc);
796 	if (fssproj == NULL)	/* if this thread already exited */
797 		return;
798 	fsspset = FSSPROJ2FSSPSET(fssproj);
799 	fsszone = fssproj->fssp_fsszone;
800 	disp_lock_enter_high(&fsspset->fssps_displock);
801 	ASSERT(fssproj->fssp_runnable > 0);
802 	if (--fssproj->fssp_runnable == 0) {
803 		fsszone->fssz_shares -= fssproj->fssp_shares;
804 		if (--fsszone->fssz_runnable == 0)
805 			fsspset->fssps_shares -= fsszone->fssz_rshares;
806 	}
807 	ASSERT(fssproc->fss_runnable == 1);
808 	fssproc->fss_runnable = 0;
809 	disp_lock_exit_high(&fsspset->fssps_displock);
810 }
811 
812 static void
813 fss_active(kthread_t *t)
814 {
815 	fssproc_t *fssproc;
816 	fssproj_t *fssproj;
817 	fsspset_t *fsspset;
818 	fsszone_t *fsszone;
819 
820 	ASSERT(THREAD_LOCK_HELD(t));
821 	fssproc = FSSPROC(t);
822 	fssproj = FSSPROC2FSSPROJ(fssproc);
823 	if (fssproj == NULL)	/* if this thread already exited */
824 		return;
825 	fsspset = FSSPROJ2FSSPSET(fssproj);
826 	fsszone = fssproj->fssp_fsszone;
827 	disp_lock_enter_high(&fsspset->fssps_displock);
828 	if (++fssproj->fssp_runnable == 1) {
829 		fsszone->fssz_shares += fssproj->fssp_shares;
830 		if (++fsszone->fssz_runnable == 1)
831 			fsspset->fssps_shares += fsszone->fssz_rshares;
832 	}
833 	ASSERT(fssproc->fss_runnable == 0);
834 	fssproc->fss_runnable = 1;
835 	disp_lock_exit_high(&fsspset->fssps_displock);
836 }
837 
838 /*
839  * Fair share scheduler initialization. Called by dispinit() at boot time.
840  * We can ignore clparmsz argument since we know that the smallest possible
841  * parameter buffer is big enough for us.
842  */
843 /*ARGSUSED*/
844 static pri_t
845 fss_init(id_t cid, int clparmsz, classfuncs_t **clfuncspp)
846 {
847 	int i;
848 
849 	ASSERT(MUTEX_HELD(&cpu_lock));
850 
851 	fss_cid = cid;
852 	fss_maxumdpri = minclsyspri - 1;
853 	fss_maxglobpri = minclsyspri;
854 	fss_minglobpri = 0;
855 	fsspsets = kmem_zalloc(sizeof (fsspset_t) * max_ncpus, KM_SLEEP);
856 
857 	/*
858 	 * Initialize the fssproc hash table.
859 	 */
860 	for (i = 0; i < FSS_LISTS; i++)
861 		fss_listhead[i].fss_next = fss_listhead[i].fss_prev =
862 		    &fss_listhead[i];
863 
864 	*clfuncspp = &fss_classfuncs;
865 
866 	/*
867 	 * Fill in fss_nice_tick and fss_nice_decay arrays:
868 	 * The cost of a tick is lower at positive nice values (so that it
869 	 * will not increase its project's usage as much as normal) with 50%
870 	 * drop at the maximum level and 50% increase at the minimum level.
871 	 * The fsspri decay is slower at positive nice values.  fsspri values
872 	 * of processes with negative nice levels must decay faster to receive
873 	 * time slices more frequently than normal.
874 	 */
875 	for (i = 0; i < FSS_NICE_RANGE; i++) {
876 		fss_nice_tick[i] = (FSS_TICK_COST * (((3 * FSS_NICE_RANGE) / 2)
877 		    - i)) / FSS_NICE_RANGE;
878 		fss_nice_decay[i] = FSS_DECAY_MIN +
879 		    ((FSS_DECAY_MAX - FSS_DECAY_MIN) * i) /
880 		    (FSS_NICE_RANGE - 1);
881 	}
882 
883 	return (fss_maxglobpri);
884 }
885 
886 /*
887  * Calculate the new fss_umdpri based on the usage, the normalized share usage
888  * and the number of active threads.  Reset the tick counter for this thread.
889  *
890  * When calculating the new priority using the standard formula we can hit
891  * a scenario where we don't have good round-robin behavior.  This would be
892  * most commonly seen when there is a zone with lots of runnable threads.
893  * In the bad scenario we will see the following behavior when using the
894  * standard formula and these conditions:
895  *
896  *	- there are multiple runnable threads in the zone (project)
897  *	- the fssps_maxfsspri is a very large value
898  *	- (we also know all of these threads will use the project's
899  *	    fssp_shusage)
900  *
901  * Under these conditions, a thread with a low fss_fsspri value is chosen
902  * to run and the thread gets a high fss_umdpri.  This thread can run for
903  * its full quanta (fss_timeleft) at which time fss_newpri is called to
904  * calculate the thread's new priority.
905  *
906  * In this case, because the newly calculated fsspri value is much smaller
907  * (orders of magnitude) than the fssps_maxfsspri value, if we used the
908  * standard formula the thread will still get a high fss_umdpri value and
909  * will run again for another quanta, even though there are other runnable
910  * threads in the project.
911  *
912  * For a thread that is runnable for a long time, the thread can continue
913  * to run for many quanta (totaling many seconds) before the thread's fsspri
914  * exceeds the fssps_maxfsspri and the thread's fss_umdpri is reset back
915  * down to 1.  This behavior also keeps the fssps_maxfsspr at a high value,
916  * so that the next runnable thread might repeat this cycle.
917  *
918  * This leads to the case where we don't have round-robin behavior at quanta
919  * granularity, but instead, runnable threads within the project only run
920  * at several second intervals.
921  *
922  * To prevent this scenario from occuring, when a thread has consumed its
923  * quanta and there are multiple runnable threads in the project, we
924  * immediately cause the thread to hit fssps_maxfsspri so that it gets
925  * reset back to 1 and another runnable thread in the project can run.
926  */
927 static void
928 fss_newpri(fssproc_t *fssproc, boolean_t quanta_up)
929 {
930 	kthread_t *tp;
931 	fssproj_t *fssproj;
932 	fsspset_t *fsspset;
933 	fsszone_t *fsszone;
934 	fsspri_t fsspri, maxfsspri;
935 	uint32_t n_runnable;
936 	pri_t invpri;
937 	uint32_t ticks;
938 
939 	tp = fssproc->fss_tp;
940 	ASSERT(tp != NULL);
941 
942 	if (tp->t_cid != fss_cid)
943 		return;
944 
945 	ASSERT(THREAD_LOCK_HELD(tp));
946 
947 	fssproj = FSSPROC2FSSPROJ(fssproc);
948 	fsszone = FSSPROJ2FSSZONE(fssproj);
949 	if (fssproj == NULL)
950 		/*
951 		 * No need to change priority of exited threads.
952 		 */
953 		return;
954 
955 	fsspset = FSSPROJ2FSSPSET(fssproj);
956 	disp_lock_enter_high(&fsspset->fssps_displock);
957 
958 	ticks = fssproc->fss_ticks;
959 	fssproc->fss_ticks = 0;
960 
961 	if (fssproj->fssp_shares == 0 || fsszone->fssz_rshares == 0) {
962 		/*
963 		 * Special case: threads with no shares.
964 		 */
965 		fssproc->fss_umdpri = fss_minglobpri;
966 		disp_lock_exit_high(&fsspset->fssps_displock);
967 		return;
968 	}
969 
970 	maxfsspri = fsspset->fssps_maxfsspri;
971 	n_runnable = fssproj->fssp_runnable;
972 
973 	if (quanta_up && n_runnable > 1) {
974 		fsspri = maxfsspri;
975 	} else {
976 		/*
977 		 * fsspri += fssp_shusage * nrunnable * ticks
978 		 * If all three values are non-0, this typically calculates to
979 		 * a large number (sometimes > 1M, sometimes > 100B) due to
980 		 * fssp_shusage which can be > 1T.
981 		 */
982 		fsspri = fssproc->fss_fsspri;
983 		fsspri += fssproj->fssp_shusage * n_runnable * ticks;
984 	}
985 
986 	fssproc->fss_fsspri = fsspri;
987 
988 	/*
989 	 * fss_maxumdpri is normally 59, since FSS priorities are 0-59.
990 	 * If the previous calculation resulted in 0 (e.g. was 0 and added 0
991 	 * because ticks == 0), then instead of 0, we use the largest priority,
992 	 * which is still small in comparison to the large numbers we typically
993 	 * see.
994 	 */
995 	if (fsspri < fss_maxumdpri)
996 		fsspri = fss_maxumdpri;	/* so that maxfsspri is != 0 */
997 
998 	/*
999 	 * The general priority formula:
1000 	 *
1001 	 *			(fsspri * umdprirange)
1002 	 *   pri = maxumdpri - ------------------------
1003 	 *				maxfsspri
1004 	 *
1005 	 * If this thread's fsspri is greater than the previous largest
1006 	 * fsspri, then record it as the new high and priority for this
1007 	 * thread will be one (the lowest priority assigned to a thread
1008 	 * that has non-zero shares). Because of this check, maxfsspri can
1009 	 * change as this function is called via the
1010 	 * fss_update -> fss_update_list -> fss_newpri code path to update
1011 	 * all runnable threads. See the code in fss_update for how we
1012 	 * mitigate this issue.
1013 	 *
1014 	 * Note that this formula cannot produce out of bounds priority
1015 	 * values (0-59); if it is changed, additional checks may need to be
1016 	 * added.
1017 	 */
1018 	if (fsspri >= maxfsspri) {
1019 		fsspset->fssps_maxfsspri = fsspri;
1020 		disp_lock_exit_high(&fsspset->fssps_displock);
1021 		fssproc->fss_umdpri = 1;
1022 	} else {
1023 		disp_lock_exit_high(&fsspset->fssps_displock);
1024 		invpri = (fsspri * (fss_maxumdpri - 1)) / maxfsspri;
1025 		fssproc->fss_umdpri = fss_maxumdpri - invpri;
1026 	}
1027 }
1028 
1029 /*
1030  * Decays usages of all running projects, resets their tick counters and
1031  * calcluates the projects normalized share usage. Called once per second from
1032  * fss_update().
1033  */
1034 static void
1035 fss_decay_usage()
1036 {
1037 	uint32_t zone_ext_shares, zone_int_shares;
1038 	uint32_t kpj_shares, pset_shares;
1039 	fsspset_t *fsspset;
1040 	fssproj_t *fssproj;
1041 	fsszone_t *fsszone;
1042 	fsspri_t maxfsspri;
1043 	int psetid;
1044 	struct zone *zp;
1045 
1046 	mutex_enter(&fsspsets_lock);
1047 	/*
1048 	 * Go through all active processor sets and decay usages of projects
1049 	 * running on them.
1050 	 */
1051 	for (psetid = 0; psetid < max_ncpus; psetid++) {
1052 		fsspset = &fsspsets[psetid];
1053 		mutex_enter(&fsspset->fssps_lock);
1054 
1055 		fsspset->fssps_gen++;
1056 
1057 		if (fsspset->fssps_cpupart == NULL ||
1058 		    (fssproj = fsspset->fssps_list) == NULL) {
1059 			mutex_exit(&fsspset->fssps_lock);
1060 			continue;
1061 		}
1062 
1063 		/*
1064 		 * Decay maxfsspri for this cpu partition with the
1065 		 * fastest possible decay rate.
1066 		 */
1067 		disp_lock_enter(&fsspset->fssps_displock);
1068 
1069 		pset_shares = fsspset->fssps_shares;
1070 
1071 		maxfsspri = (fsspset->fssps_maxfsspri *
1072 		    fss_nice_decay[NZERO]) / FSS_DECAY_BASE;
1073 		if (maxfsspri < fss_maxumdpri)
1074 			maxfsspri = fss_maxumdpri;
1075 		fsspset->fssps_maxfsspri = maxfsspri;
1076 
1077 		do {
1078 			fsszone = fssproj->fssp_fsszone;
1079 			zp = fsszone->fssz_zone;
1080 
1081 			/*
1082 			 * Reset zone's FSS stats if they are from a
1083 			 * previous cycle.
1084 			 */
1085 			if (fsspset->fssps_gen != zp->zone_fss_gen) {
1086 				zp->zone_fss_gen = fsspset->fssps_gen;
1087 				zp->zone_run_ticks = 0;
1088 			}
1089 
1090 			/*
1091 			 * Decay project usage, then add in this cycle's
1092 			 * nice tick value.
1093 			 */
1094 			fssproj->fssp_usage =
1095 			    (fssproj->fssp_usage * FSS_DECAY_USG) /
1096 			    FSS_DECAY_BASE +
1097 			    fssproj->fssp_ticks;
1098 
1099 			fssproj->fssp_ticks = 0;
1100 			zp->zone_run_ticks += fssproj->fssp_tick_cnt;
1101 			fssproj->fssp_tick_cnt = 0;
1102 
1103 			/*
1104 			 * Readjust the project's number of shares if it has
1105 			 * changed since we checked it last time.
1106 			 */
1107 			kpj_shares = fssproj->fssp_proj->kpj_shares;
1108 			if (fssproj->fssp_shares != kpj_shares) {
1109 				if (fssproj->fssp_runnable != 0) {
1110 					fsszone->fssz_shares -=
1111 					    fssproj->fssp_shares;
1112 					fsszone->fssz_shares += kpj_shares;
1113 				}
1114 				fssproj->fssp_shares = kpj_shares;
1115 			}
1116 
1117 			/*
1118 			 * Readjust the zone's number of shares if it
1119 			 * has changed since we checked it last time.
1120 			 */
1121 			zone_ext_shares = zp->zone_shares;
1122 			if (fsszone->fssz_rshares != zone_ext_shares) {
1123 				if (fsszone->fssz_runnable != 0) {
1124 					fsspset->fssps_shares -=
1125 					    fsszone->fssz_rshares;
1126 					fsspset->fssps_shares +=
1127 					    zone_ext_shares;
1128 					pset_shares = fsspset->fssps_shares;
1129 				}
1130 				fsszone->fssz_rshares = zone_ext_shares;
1131 			}
1132 			zone_int_shares = fsszone->fssz_shares;
1133 
1134 			/*
1135 			 * If anything is runnable in the project, track the
1136 			 * overall project share percent for monitoring useage.
1137 			 */
1138 			if (fssproj->fssp_runnable > 0) {
1139 				uint32_t zone_shr_pct;
1140 				uint32_t int_shr_pct;
1141 
1142 				/*
1143 				 * Times 1000 to get tenths of a percent
1144 				 *
1145 				 *		  zone_ext_shares
1146 				 * zone_shr_pct = ---------------
1147 				 *		  pset_shares
1148 				 *
1149 				 *		  kpj_shares
1150 				 * int_shr_pct =  ---------------
1151 				 *		  zone_int_shares
1152 				 */
1153 				if (pset_shares == 0 || zone_int_shares == 0) {
1154 					fssproj->fssp_shr_pct = 0;
1155 				} else {
1156 					zone_shr_pct =
1157 					    (zone_ext_shares * 1000) /
1158 					    pset_shares;
1159 					int_shr_pct = (kpj_shares * 1000) /
1160 					    zone_int_shares;
1161 					fssproj->fssp_shr_pct =
1162 					    (zone_shr_pct * int_shr_pct) /
1163 					    1000;
1164 				}
1165 			} else {
1166 				DTRACE_PROBE1(fss__prj__norun, fssproj_t *,
1167 				    fssproj);
1168 			}
1169 
1170 			/*
1171 			 * Calculate fssp_shusage value to be used
1172 			 * for fsspri increments for the next second.
1173 			 */
1174 			if (kpj_shares == 0 || zone_ext_shares == 0) {
1175 				fssproj->fssp_shusage = 0;
1176 			} else if (FSSPROJ2KPROJ(fssproj) == proj0p) {
1177 				uint32_t zone_shr_pct;
1178 
1179 				/*
1180 				 * Project 0 in the global zone has 50%
1181 				 * of its zone. See calculation above for
1182 				 * the zone's share percent.
1183 				 */
1184 				if (pset_shares == 0)
1185 					zone_shr_pct = 1000;
1186 				else
1187 					zone_shr_pct =
1188 					    (zone_ext_shares * 1000) /
1189 					    pset_shares;
1190 
1191 				fssproj->fssp_shr_pct = zone_shr_pct / 2;
1192 
1193 				fssproj->fssp_shusage = (fssproj->fssp_usage *
1194 				    zone_int_shares * zone_int_shares) /
1195 				    (zone_ext_shares * zone_ext_shares);
1196 			} else {
1197 				/*
1198 				 * Thread's priority is based on its project's
1199 				 * normalized usage (shusage) value which gets
1200 				 * calculated this way:
1201 				 *
1202 				 *	   pset_shares^2    zone_int_shares^2
1203 				 * usage * ------------- * ------------------
1204 				 *	   kpj_shares^2	    zone_ext_shares^2
1205 				 *
1206 				 * Where zone_int_shares is the sum of shares
1207 				 * of all active projects within the zone (and
1208 				 * the pset), and zone_ext_shares is the number
1209 				 * of zone shares (ie, zone.cpu-shares).
1210 				 *
1211 				 * If there is only one zone active on the pset
1212 				 * the above reduces to:
1213 				 *
1214 				 *			zone_int_shares^2
1215 				 * shusage = usage * ---------------------
1216 				 *			kpj_shares^2
1217 				 *
1218 				 * If there's only one project active in the
1219 				 * zone this formula reduces to:
1220 				 *
1221 				 *			pset_shares^2
1222 				 * shusage = usage * ----------------------
1223 				 *			zone_ext_shares^2
1224 				 *
1225 				 * shusage is one input to calculating fss_pri
1226 				 * in fss_newpri(). Larger values tend toward
1227 				 * lower priorities for processes in the proj.
1228 				 */
1229 				fssproj->fssp_shusage = fssproj->fssp_usage *
1230 				    pset_shares * zone_int_shares;
1231 				fssproj->fssp_shusage /=
1232 				    kpj_shares * zone_ext_shares;
1233 				fssproj->fssp_shusage *=
1234 				    pset_shares * zone_int_shares;
1235 				fssproj->fssp_shusage /=
1236 				    kpj_shares * zone_ext_shares;
1237 			}
1238 			fssproj = fssproj->fssp_next;
1239 		} while (fssproj != fsspset->fssps_list);
1240 
1241 		disp_lock_exit(&fsspset->fssps_displock);
1242 		mutex_exit(&fsspset->fssps_lock);
1243 	}
1244 	mutex_exit(&fsspsets_lock);
1245 }
1246 
1247 static void
1248 fss_change_priority(kthread_t *t, fssproc_t *fssproc)
1249 {
1250 	pri_t new_pri;
1251 
1252 	ASSERT(THREAD_LOCK_HELD(t));
1253 	new_pri = fssproc->fss_umdpri;
1254 	ASSERT(new_pri >= 0 && new_pri <= fss_maxglobpri);
1255 
1256 	t->t_cpri = fssproc->fss_upri;
1257 	fssproc->fss_flags &= ~FSSRESTORE;
1258 	if (t == curthread || t->t_state == TS_ONPROC) {
1259 		/*
1260 		 * curthread is always onproc
1261 		 */
1262 		cpu_t *cp = t->t_disp_queue->disp_cpu;
1263 		THREAD_CHANGE_PRI(t, new_pri);
1264 		if (t == cp->cpu_dispthread)
1265 			cp->cpu_dispatch_pri = DISP_PRIO(t);
1266 		if (DISP_MUST_SURRENDER(t)) {
1267 			fssproc->fss_flags |= FSSBACKQ;
1268 			cpu_surrender(t);
1269 		} else {
1270 			fssproc->fss_timeleft = fss_quantum;
1271 		}
1272 	} else {
1273 		/*
1274 		 * When the priority of a thread is changed, it may be
1275 		 * necessary to adjust its position on a sleep queue or
1276 		 * dispatch queue.  The function thread_change_pri accomplishes
1277 		 * this.
1278 		 */
1279 		if (thread_change_pri(t, new_pri, 0)) {
1280 			/*
1281 			 * The thread was on a run queue.
1282 			 */
1283 			fssproc->fss_timeleft = fss_quantum;
1284 		} else {
1285 			fssproc->fss_flags |= FSSBACKQ;
1286 		}
1287 	}
1288 }
1289 
1290 /*
1291  * Update priorities of all fair-sharing threads that are currently runnable
1292  * at a user mode priority based on the number of shares and current usage.
1293  * Called once per second via timeout which we reset here.
1294  *
1295  * There are several lists of fair-sharing threads broken up by a hash on the
1296  * thread pointer.  Each list has its own lock.  This avoids blocking all
1297  * fss_enterclass, fss_fork, and fss_exitclass operations while fss_update runs.
1298  * fss_update traverses each list in turn.
1299  *
1300  * Each time we're run (once/second) we may start at the next list and iterate
1301  * through all of the lists. By starting with a different list, we mitigate any
1302  * effects we would see updating the fssps_maxfsspri value in fss_newpri.
1303  */
1304 static void
1305 fss_update(void *arg)
1306 {
1307 	int i;
1308 	int new_marker = -1;
1309 	static int fss_update_marker;
1310 
1311 	/*
1312 	 * Decay and update usages for all projects.
1313 	 */
1314 	fss_decay_usage();
1315 
1316 	/*
1317 	 * Start with the fss_update_marker list, then do the rest.
1318 	 */
1319 	i = fss_update_marker;
1320 
1321 	/*
1322 	 * Go around all threads, set new priorities and decay
1323 	 * per-thread CPU usages.
1324 	 */
1325 	do {
1326 		/*
1327 		 * If this is the first list after the current marker to have
1328 		 * threads with priority updates, advance the marker to this
1329 		 * list for the next time fss_update runs.
1330 		 */
1331 		if (fss_update_list(i) &&
1332 		    new_marker == -1 && i != fss_update_marker)
1333 			new_marker = i;
1334 	} while ((i = FSS_LIST_NEXT(i)) != fss_update_marker);
1335 
1336 	/*
1337 	 * Advance marker for the next fss_update call
1338 	 */
1339 	if (new_marker != -1)
1340 		fss_update_marker = new_marker;
1341 
1342 	(void) timeout(fss_update, arg, hz);
1343 }
1344 
1345 /*
1346  * Updates priority for a list of threads.  Returns 1 if the priority of one
1347  * of the threads was actually updated, 0 if none were for various reasons
1348  * (thread is no longer in the FSS class, is not runnable, has the preemption
1349  * control no-preempt bit set, etc.)
1350  */
1351 static int
1352 fss_update_list(int i)
1353 {
1354 	fssproc_t *fssproc;
1355 	fssproj_t *fssproj;
1356 	fsspri_t fsspri;
1357 	pri_t fss_umdpri;
1358 	kthread_t *t;
1359 	int updated = 0;
1360 
1361 	mutex_enter(&fss_listlock[i]);
1362 	for (fssproc = fss_listhead[i].fss_next; fssproc != &fss_listhead[i];
1363 	    fssproc = fssproc->fss_next) {
1364 		t = fssproc->fss_tp;
1365 		/*
1366 		 * Lock the thread and verify the state.
1367 		 */
1368 		thread_lock(t);
1369 		/*
1370 		 * Skip the thread if it is no longer in the FSS class or
1371 		 * is running with kernel mode priority.
1372 		 */
1373 		if (t->t_cid != fss_cid)
1374 			goto next;
1375 
1376 		fssproj = FSSPROC2FSSPROJ(fssproc);
1377 		if (fssproj == NULL)
1378 			goto next;
1379 
1380 		if (fssproj->fssp_shares != 0) {
1381 			/*
1382 			 * Decay fsspri value.
1383 			 */
1384 			fsspri = fssproc->fss_fsspri;
1385 			fsspri = (fsspri * fss_nice_decay[fssproc->fss_nice]) /
1386 			    FSS_DECAY_BASE;
1387 			fssproc->fss_fsspri = fsspri;
1388 		}
1389 
1390 		if (t->t_schedctl && schedctl_get_nopreempt(t))
1391 			goto next;
1392 		if (t->t_state != TS_RUN && t->t_state != TS_WAIT) {
1393 			/*
1394 			 * Make next syscall/trap call fss_trapret
1395 			 */
1396 			t->t_trapret = 1;
1397 			aston(t);
1398 			if (t->t_state == TS_ONPROC)
1399 				DTRACE_PROBE1(fss__onproc, fssproc_t *,
1400 				    fssproc);
1401 			goto next;
1402 		}
1403 		fss_newpri(fssproc, B_FALSE);
1404 		updated = 1;
1405 
1406 		fss_umdpri = fssproc->fss_umdpri;
1407 
1408 		/*
1409 		 * Only dequeue the thread if it needs to be moved; otherwise
1410 		 * it should just round-robin here.
1411 		 */
1412 		if (t->t_pri != fss_umdpri)
1413 			fss_change_priority(t, fssproc);
1414 next:
1415 		thread_unlock(t);
1416 	}
1417 	mutex_exit(&fss_listlock[i]);
1418 	return (updated);
1419 }
1420 
1421 /*ARGSUSED*/
1422 static int
1423 fss_admin(caddr_t uaddr, cred_t *reqpcredp)
1424 {
1425 	fssadmin_t fssadmin;
1426 
1427 	if (copyin(uaddr, &fssadmin, sizeof (fssadmin_t)))
1428 		return (EFAULT);
1429 
1430 	switch (fssadmin.fss_cmd) {
1431 	case FSS_SETADMIN:
1432 		if (secpolicy_dispadm(reqpcredp) != 0)
1433 			return (EPERM);
1434 		if (fssadmin.fss_quantum <= 0 || fssadmin.fss_quantum >= hz)
1435 			return (EINVAL);
1436 		fss_quantum = fssadmin.fss_quantum;
1437 		break;
1438 	case FSS_GETADMIN:
1439 		fssadmin.fss_quantum = fss_quantum;
1440 		if (copyout(&fssadmin, uaddr, sizeof (fssadmin_t)))
1441 			return (EFAULT);
1442 		break;
1443 	default:
1444 		return (EINVAL);
1445 	}
1446 	return (0);
1447 }
1448 
1449 static int
1450 fss_getclinfo(void *infop)
1451 {
1452 	fssinfo_t *fssinfo = (fssinfo_t *)infop;
1453 	fssinfo->fss_maxupri = fss_maxupri;
1454 	return (0);
1455 }
1456 
1457 static int
1458 fss_parmsin(void *parmsp)
1459 {
1460 	fssparms_t *fssparmsp = (fssparms_t *)parmsp;
1461 
1462 	/*
1463 	 * Check validity of parameters.
1464 	 */
1465 	if ((fssparmsp->fss_uprilim > fss_maxupri ||
1466 	    fssparmsp->fss_uprilim < -fss_maxupri) &&
1467 	    fssparmsp->fss_uprilim != FSS_NOCHANGE)
1468 		return (EINVAL);
1469 
1470 	if ((fssparmsp->fss_upri > fss_maxupri ||
1471 	    fssparmsp->fss_upri < -fss_maxupri) &&
1472 	    fssparmsp->fss_upri != FSS_NOCHANGE)
1473 		return (EINVAL);
1474 
1475 	return (0);
1476 }
1477 
1478 /*ARGSUSED*/
1479 static int
1480 fss_parmsout(void *parmsp, pc_vaparms_t *vaparmsp)
1481 {
1482 	return (0);
1483 }
1484 
1485 static int
1486 fss_vaparmsin(void *parmsp, pc_vaparms_t *vaparmsp)
1487 {
1488 	fssparms_t *fssparmsp = (fssparms_t *)parmsp;
1489 	int priflag = 0;
1490 	int limflag = 0;
1491 	uint_t cnt;
1492 	pc_vaparm_t *vpp = &vaparmsp->pc_parms[0];
1493 
1494 	/*
1495 	 * FSS_NOCHANGE (-32768) is outside of the range of values for
1496 	 * fss_uprilim and fss_upri.  If the structure fssparms_t is changed,
1497 	 * FSS_NOCHANGE should be replaced by a flag word.
1498 	 */
1499 	fssparmsp->fss_uprilim = FSS_NOCHANGE;
1500 	fssparmsp->fss_upri = FSS_NOCHANGE;
1501 
1502 	/*
1503 	 * Get the varargs parameter and check validity of parameters.
1504 	 */
1505 	if (vaparmsp->pc_vaparmscnt > PC_VAPARMCNT)
1506 		return (EINVAL);
1507 
1508 	for (cnt = 0; cnt < vaparmsp->pc_vaparmscnt; cnt++, vpp++) {
1509 		switch (vpp->pc_key) {
1510 		case FSS_KY_UPRILIM:
1511 			if (limflag++)
1512 				return (EINVAL);
1513 			fssparmsp->fss_uprilim = (pri_t)vpp->pc_parm;
1514 			if (fssparmsp->fss_uprilim > fss_maxupri ||
1515 			    fssparmsp->fss_uprilim < -fss_maxupri)
1516 				return (EINVAL);
1517 			break;
1518 		case FSS_KY_UPRI:
1519 			if (priflag++)
1520 				return (EINVAL);
1521 			fssparmsp->fss_upri = (pri_t)vpp->pc_parm;
1522 			if (fssparmsp->fss_upri > fss_maxupri ||
1523 			    fssparmsp->fss_upri < -fss_maxupri)
1524 				return (EINVAL);
1525 			break;
1526 		default:
1527 			return (EINVAL);
1528 		}
1529 	}
1530 
1531 	if (vaparmsp->pc_vaparmscnt == 0) {
1532 		/*
1533 		 * Use default parameters.
1534 		 */
1535 		fssparmsp->fss_upri = fssparmsp->fss_uprilim = 0;
1536 	}
1537 
1538 	return (0);
1539 }
1540 
1541 /*
1542  * Copy all selected fair-sharing class parameters to the user.  The parameters
1543  * are specified by a key.
1544  */
1545 static int
1546 fss_vaparmsout(void *parmsp, pc_vaparms_t *vaparmsp)
1547 {
1548 	fssparms_t *fssparmsp = (fssparms_t *)parmsp;
1549 	int priflag = 0;
1550 	int limflag = 0;
1551 	uint_t cnt;
1552 	pc_vaparm_t *vpp = &vaparmsp->pc_parms[0];
1553 
1554 	ASSERT(MUTEX_NOT_HELD(&curproc->p_lock));
1555 
1556 	if (vaparmsp->pc_vaparmscnt > PC_VAPARMCNT)
1557 		return (EINVAL);
1558 
1559 	for (cnt = 0; cnt < vaparmsp->pc_vaparmscnt; cnt++, vpp++) {
1560 		switch (vpp->pc_key) {
1561 		case FSS_KY_UPRILIM:
1562 			if (limflag++)
1563 				return (EINVAL);
1564 			if (copyout(&fssparmsp->fss_uprilim,
1565 			    (caddr_t)(uintptr_t)vpp->pc_parm, sizeof (pri_t)))
1566 				return (EFAULT);
1567 			break;
1568 		case FSS_KY_UPRI:
1569 			if (priflag++)
1570 				return (EINVAL);
1571 			if (copyout(&fssparmsp->fss_upri,
1572 			    (caddr_t)(uintptr_t)vpp->pc_parm, sizeof (pri_t)))
1573 				return (EFAULT);
1574 			break;
1575 		default:
1576 			return (EINVAL);
1577 		}
1578 	}
1579 
1580 	return (0);
1581 }
1582 
1583 /*
1584  * Return the user mode scheduling priority range.
1585  */
1586 static int
1587 fss_getclpri(pcpri_t *pcprip)
1588 {
1589 	pcprip->pc_clpmax = fss_maxupri;
1590 	pcprip->pc_clpmin = -fss_maxupri;
1591 	return (0);
1592 }
1593 
1594 static int
1595 fss_alloc(void **p, int flag)
1596 {
1597 	void *bufp;
1598 
1599 	if ((bufp = kmem_zalloc(sizeof (fssproc_t), flag)) == NULL) {
1600 		return (ENOMEM);
1601 	} else {
1602 		*p = bufp;
1603 		return (0);
1604 	}
1605 }
1606 
1607 static void
1608 fss_free(void *bufp)
1609 {
1610 	if (bufp)
1611 		kmem_free(bufp, sizeof (fssproc_t));
1612 }
1613 
1614 /*
1615  * Thread functions
1616  */
1617 static int
1618 fss_enterclass(kthread_t *t, id_t cid, void *parmsp, cred_t *reqpcredp,
1619     void *bufp)
1620 {
1621 	fssparms_t	*fssparmsp = (fssparms_t *)parmsp;
1622 	fssproc_t	*fssproc;
1623 	pri_t		reqfssuprilim;
1624 	pri_t		reqfssupri;
1625 	static uint32_t fssexists = 0;
1626 	fsspset_t	*fsspset;
1627 	fssproj_t	*fssproj;
1628 	fsszone_t	*fsszone;
1629 	kproject_t	*kpj;
1630 	zone_t		*zone;
1631 	int		fsszone_allocated = 0;
1632 
1633 	fssproc = (fssproc_t *)bufp;
1634 	ASSERT(fssproc != NULL);
1635 
1636 	ASSERT(MUTEX_HELD(&ttoproc(t)->p_lock));
1637 
1638 	/*
1639 	 * Only root can move threads to FSS class.
1640 	 */
1641 	if (reqpcredp != NULL && secpolicy_setpriority(reqpcredp) != 0)
1642 		return (EPERM);
1643 	/*
1644 	 * Initialize the fssproc structure.
1645 	 */
1646 	fssproc->fss_umdpri = fss_maxumdpri / 2;
1647 
1648 	if (fssparmsp == NULL) {
1649 		/*
1650 		 * Use default values.
1651 		 */
1652 		fssproc->fss_nice = NZERO;
1653 		fssproc->fss_uprilim = fssproc->fss_upri = 0;
1654 	} else {
1655 		/*
1656 		 * Use supplied values.
1657 		 */
1658 		if (fssparmsp->fss_uprilim == FSS_NOCHANGE) {
1659 			reqfssuprilim = 0;
1660 		} else {
1661 			if (fssparmsp->fss_uprilim > 0 &&
1662 			    secpolicy_setpriority(reqpcredp) != 0)
1663 				return (EPERM);
1664 			reqfssuprilim = fssparmsp->fss_uprilim;
1665 		}
1666 		if (fssparmsp->fss_upri == FSS_NOCHANGE) {
1667 			reqfssupri = reqfssuprilim;
1668 		} else {
1669 			if (fssparmsp->fss_upri > 0 &&
1670 			    secpolicy_setpriority(reqpcredp) != 0)
1671 				return (EPERM);
1672 			/*
1673 			 * Set the user priority to the requested value or
1674 			 * the upri limit, whichever is lower.
1675 			 */
1676 			reqfssupri = fssparmsp->fss_upri;
1677 			if (reqfssupri > reqfssuprilim)
1678 				reqfssupri = reqfssuprilim;
1679 		}
1680 		fssproc->fss_uprilim = reqfssuprilim;
1681 		fssproc->fss_upri = reqfssupri;
1682 		fssproc->fss_nice = NZERO - (NZERO * reqfssupri) / fss_maxupri;
1683 		if (fssproc->fss_nice > FSS_NICE_MAX)
1684 			fssproc->fss_nice = FSS_NICE_MAX;
1685 	}
1686 
1687 	fssproc->fss_timeleft = fss_quantum;
1688 	fssproc->fss_tp = t;
1689 	cpucaps_sc_init(&fssproc->fss_caps);
1690 
1691 	/*
1692 	 * Put a lock on our fsspset structure.
1693 	 */
1694 	mutex_enter(&fsspsets_lock);
1695 	fsspset = fss_find_fsspset(t->t_cpupart);
1696 	mutex_enter(&fsspset->fssps_lock);
1697 	mutex_exit(&fsspsets_lock);
1698 
1699 	zone = ttoproc(t)->p_zone;
1700 	if ((fsszone = fss_find_fsszone(fsspset, zone)) == NULL) {
1701 		if ((fsszone = kmem_zalloc(sizeof (fsszone_t), KM_NOSLEEP))
1702 		    == NULL) {
1703 			mutex_exit(&fsspset->fssps_lock);
1704 			return (ENOMEM);
1705 		} else {
1706 			fsszone_allocated = 1;
1707 			fss_insert_fsszone(fsspset, zone, fsszone);
1708 		}
1709 	}
1710 	kpj = ttoproj(t);
1711 	if ((fssproj = fss_find_fssproj(fsspset, kpj)) == NULL) {
1712 		if ((fssproj = kmem_zalloc(sizeof (fssproj_t), KM_NOSLEEP))
1713 		    == NULL) {
1714 			if (fsszone_allocated) {
1715 				fss_remove_fsszone(fsspset, fsszone);
1716 				kmem_free(fsszone, sizeof (fsszone_t));
1717 			}
1718 			mutex_exit(&fsspset->fssps_lock);
1719 			return (ENOMEM);
1720 		} else {
1721 			fss_insert_fssproj(fsspset, kpj, fsszone, fssproj);
1722 		}
1723 	}
1724 	fssproj->fssp_threads++;
1725 	fssproc->fss_proj = fssproj;
1726 
1727 	/*
1728 	 * Reset priority. Process goes to a "user mode" priority here
1729 	 * regardless of whether or not it has slept since entering the kernel.
1730 	 */
1731 	thread_lock(t);
1732 	t->t_clfuncs = &(sclass[cid].cl_funcs->thread);
1733 	t->t_cid = cid;
1734 	t->t_cldata = (void *)fssproc;
1735 	t->t_schedflag |= TS_RUNQMATCH;
1736 	fss_change_priority(t, fssproc);
1737 	if (t->t_state == TS_RUN || t->t_state == TS_ONPROC ||
1738 	    t->t_state == TS_WAIT)
1739 		fss_active(t);
1740 	thread_unlock(t);
1741 
1742 	mutex_exit(&fsspset->fssps_lock);
1743 
1744 	/*
1745 	 * Link new structure into fssproc list.
1746 	 */
1747 	FSS_LIST_INSERT(fssproc);
1748 
1749 	/*
1750 	 * If this is the first fair-sharing thread to occur since boot,
1751 	 * we set up the initial call to fss_update() here. Use an atomic
1752 	 * compare-and-swap since that's easier and faster than a mutex
1753 	 * (but check with an ordinary load first since most of the time
1754 	 * this will already be done).
1755 	 */
1756 	if (fssexists == 0 && atomic_cas_32(&fssexists, 0, 1) == 0)
1757 		(void) timeout(fss_update, NULL, hz);
1758 
1759 	return (0);
1760 }
1761 
1762 /*
1763  * Remove fssproc_t from the list.
1764  */
1765 static void
1766 fss_exitclass(void *procp)
1767 {
1768 	fssproc_t *fssproc = (fssproc_t *)procp;
1769 	fssproj_t *fssproj;
1770 	fsspset_t *fsspset;
1771 	fsszone_t *fsszone;
1772 	kthread_t *t = fssproc->fss_tp;
1773 
1774 	/*
1775 	 * We should be either getting this thread off the deathrow or
1776 	 * this thread has already moved to another scheduling class and
1777 	 * we're being called with its old cldata buffer pointer.  In both
1778 	 * cases, the content of this buffer can not be changed while we're
1779 	 * here.
1780 	 */
1781 	mutex_enter(&fsspsets_lock);
1782 	thread_lock(t);
1783 	if (t->t_cid != fss_cid) {
1784 		/*
1785 		 * We're being called as a result of the priocntl() system
1786 		 * call -- someone is trying to move our thread to another
1787 		 * scheduling class. We can't call fss_inactive() here
1788 		 * because our thread's t_cldata pointer already points
1789 		 * to another scheduling class specific data.
1790 		 */
1791 		ASSERT(MUTEX_HELD(&ttoproc(t)->p_lock));
1792 
1793 		fssproj = FSSPROC2FSSPROJ(fssproc);
1794 		fsspset = FSSPROJ2FSSPSET(fssproj);
1795 		fsszone = fssproj->fssp_fsszone;
1796 
1797 		if (fssproc->fss_runnable) {
1798 			disp_lock_enter_high(&fsspset->fssps_displock);
1799 			if (--fssproj->fssp_runnable == 0) {
1800 				fsszone->fssz_shares -= fssproj->fssp_shares;
1801 				if (--fsszone->fssz_runnable == 0)
1802 					fsspset->fssps_shares -=
1803 					    fsszone->fssz_rshares;
1804 			}
1805 			disp_lock_exit_high(&fsspset->fssps_displock);
1806 		}
1807 		thread_unlock(t);
1808 
1809 		mutex_enter(&fsspset->fssps_lock);
1810 		if (--fssproj->fssp_threads == 0) {
1811 			fss_remove_fssproj(fsspset, fssproj);
1812 			if (fsszone->fssz_nproj == 0)
1813 				kmem_free(fsszone, sizeof (fsszone_t));
1814 			kmem_free(fssproj, sizeof (fssproj_t));
1815 		}
1816 		mutex_exit(&fsspset->fssps_lock);
1817 
1818 	} else {
1819 		ASSERT(t->t_state == TS_FREE);
1820 		/*
1821 		 * We're being called from thread_free() when our thread
1822 		 * is removed from the deathrow. There is nothing we need
1823 		 * do here since everything should've been done earlier
1824 		 * in fss_exit().
1825 		 */
1826 		thread_unlock(t);
1827 	}
1828 	mutex_exit(&fsspsets_lock);
1829 
1830 	FSS_LIST_DELETE(fssproc);
1831 	fss_free(fssproc);
1832 }
1833 
1834 /*ARGSUSED*/
1835 static int
1836 fss_canexit(kthread_t *t, cred_t *credp)
1837 {
1838 	/*
1839 	 * A thread is allowed to exit FSS only if we have sufficient
1840 	 * privileges.
1841 	 */
1842 	if (credp != NULL && secpolicy_setpriority(credp) != 0)
1843 		return (EPERM);
1844 	else
1845 		return (0);
1846 }
1847 
1848 /*
1849  * Initialize fair-share class specific proc structure for a child.
1850  */
1851 static int
1852 fss_fork(kthread_t *pt, kthread_t *ct, void *bufp)
1853 {
1854 	fssproc_t *pfssproc;	/* ptr to parent's fssproc structure	*/
1855 	fssproc_t *cfssproc;	/* ptr to child's fssproc structure	*/
1856 	fssproj_t *fssproj;
1857 	fsspset_t *fsspset;
1858 
1859 	ASSERT(MUTEX_HELD(&ttoproc(pt)->p_lock));
1860 	ASSERT(ct->t_state == TS_STOPPED);
1861 
1862 	cfssproc = (fssproc_t *)bufp;
1863 	ASSERT(cfssproc != NULL);
1864 	bzero(cfssproc, sizeof (fssproc_t));
1865 
1866 	thread_lock(pt);
1867 	pfssproc = FSSPROC(pt);
1868 	fssproj = FSSPROC2FSSPROJ(pfssproc);
1869 	fsspset = FSSPROJ2FSSPSET(fssproj);
1870 	thread_unlock(pt);
1871 
1872 	mutex_enter(&fsspset->fssps_lock);
1873 	/*
1874 	 * Initialize child's fssproc structure.
1875 	 */
1876 	thread_lock(pt);
1877 	ASSERT(FSSPROJ(pt) == fssproj);
1878 	cfssproc->fss_proj = fssproj;
1879 	cfssproc->fss_timeleft = fss_quantum;
1880 	cfssproc->fss_umdpri = pfssproc->fss_umdpri;
1881 	cfssproc->fss_fsspri = 0;
1882 	cfssproc->fss_uprilim = pfssproc->fss_uprilim;
1883 	cfssproc->fss_upri = pfssproc->fss_upri;
1884 	cfssproc->fss_tp = ct;
1885 	cfssproc->fss_nice = pfssproc->fss_nice;
1886 	cpucaps_sc_init(&cfssproc->fss_caps);
1887 
1888 	cfssproc->fss_flags =
1889 	    pfssproc->fss_flags & ~(FSSBACKQ | FSSRESTORE);
1890 	ct->t_cldata = (void *)cfssproc;
1891 	ct->t_schedflag |= TS_RUNQMATCH;
1892 	thread_unlock(pt);
1893 
1894 	fssproj->fssp_threads++;
1895 	mutex_exit(&fsspset->fssps_lock);
1896 
1897 	/*
1898 	 * Link new structure into fssproc hash table.
1899 	 */
1900 	FSS_LIST_INSERT(cfssproc);
1901 	return (0);
1902 }
1903 
1904 /*
1905  * Child is placed at back of dispatcher queue and parent gives up processor
1906  * so that the child runs first after the fork. This allows the child
1907  * immediately execing to break the multiple use of copy on write pages with no
1908  * disk home. The parent will get to steal them back rather than uselessly
1909  * copying them.
1910  */
1911 static void
1912 fss_forkret(kthread_t *t, kthread_t *ct)
1913 {
1914 	proc_t *pp = ttoproc(t);
1915 	proc_t *cp = ttoproc(ct);
1916 	fssproc_t *fssproc;
1917 
1918 	ASSERT(t == curthread);
1919 	ASSERT(MUTEX_HELD(&pidlock));
1920 
1921 	/*
1922 	 * Grab the child's p_lock before dropping pidlock to ensure the
1923 	 * process does not disappear before we set it running.
1924 	 */
1925 	mutex_enter(&cp->p_lock);
1926 	continuelwps(cp);
1927 	mutex_exit(&cp->p_lock);
1928 
1929 	mutex_enter(&pp->p_lock);
1930 	mutex_exit(&pidlock);
1931 	continuelwps(pp);
1932 
1933 	thread_lock(t);
1934 
1935 	fssproc = FSSPROC(t);
1936 	fss_newpri(fssproc, B_FALSE);
1937 	fssproc->fss_timeleft = fss_quantum;
1938 	t->t_pri = fssproc->fss_umdpri;
1939 	ASSERT(t->t_pri >= 0 && t->t_pri <= fss_maxglobpri);
1940 	THREAD_TRANSITION(t);
1941 
1942 	/*
1943 	 * We don't want to call fss_setrun(t) here because it may call
1944 	 * fss_active, which we don't need.
1945 	 */
1946 	fssproc->fss_flags &= ~FSSBACKQ;
1947 
1948 	if (t->t_disp_time != ddi_get_lbolt())
1949 		setbackdq(t);
1950 	else
1951 		setfrontdq(t);
1952 
1953 	thread_unlock(t);
1954 	/*
1955 	 * Safe to drop p_lock now since it is safe to change
1956 	 * the scheduling class after this point.
1957 	 */
1958 	mutex_exit(&pp->p_lock);
1959 
1960 	swtch();
1961 }
1962 
1963 /*
1964  * Get the fair-sharing parameters of the thread pointed to by fssprocp into
1965  * the buffer pointed by fssparmsp.
1966  */
1967 static void
1968 fss_parmsget(kthread_t *t, void *parmsp)
1969 {
1970 	fssproc_t *fssproc = FSSPROC(t);
1971 	fssparms_t *fssparmsp = (fssparms_t *)parmsp;
1972 
1973 	fssparmsp->fss_uprilim = fssproc->fss_uprilim;
1974 	fssparmsp->fss_upri = fssproc->fss_upri;
1975 }
1976 
1977 /*ARGSUSED*/
1978 static int
1979 fss_parmsset(kthread_t *t, void *parmsp, id_t reqpcid, cred_t *reqpcredp)
1980 {
1981 	char		nice;
1982 	pri_t		reqfssuprilim;
1983 	pri_t		reqfssupri;
1984 	fssproc_t	*fssproc = FSSPROC(t);
1985 	fssparms_t	*fssparmsp = (fssparms_t *)parmsp;
1986 
1987 	ASSERT(MUTEX_HELD(&(ttoproc(t))->p_lock));
1988 
1989 	if (fssparmsp->fss_uprilim == FSS_NOCHANGE)
1990 		reqfssuprilim = fssproc->fss_uprilim;
1991 	else
1992 		reqfssuprilim = fssparmsp->fss_uprilim;
1993 
1994 	if (fssparmsp->fss_upri == FSS_NOCHANGE)
1995 		reqfssupri = fssproc->fss_upri;
1996 	else
1997 		reqfssupri = fssparmsp->fss_upri;
1998 
1999 	/*
2000 	 * Make sure the user priority doesn't exceed the upri limit.
2001 	 */
2002 	if (reqfssupri > reqfssuprilim)
2003 		reqfssupri = reqfssuprilim;
2004 
2005 	/*
2006 	 * Basic permissions enforced by generic kernel code for all classes
2007 	 * require that a thread attempting to change the scheduling parameters
2008 	 * of a target thread be privileged or have a real or effective UID
2009 	 * matching that of the target thread. We are not called unless these
2010 	 * basic permission checks have already passed. The fair-sharing class
2011 	 * requires in addition that the calling thread be privileged if it
2012 	 * is attempting to raise the upri limit above its current value.
2013 	 * This may have been checked previously but if our caller passed us
2014 	 * a non-NULL credential pointer we assume it hasn't and we check it
2015 	 * here.
2016 	 */
2017 	if ((reqpcredp != NULL) &&
2018 	    (reqfssuprilim > fssproc->fss_uprilim) &&
2019 	    secpolicy_raisepriority(reqpcredp) != 0)
2020 		return (EPERM);
2021 
2022 	/*
2023 	 * Set fss_nice to the nice value corresponding to the user priority we
2024 	 * are setting.  Note that setting the nice field of the parameter
2025 	 * struct won't affect upri or nice.
2026 	 */
2027 	nice = NZERO - (reqfssupri * NZERO) / fss_maxupri;
2028 	if (nice > FSS_NICE_MAX)
2029 		nice = FSS_NICE_MAX;
2030 
2031 	thread_lock(t);
2032 
2033 	fssproc->fss_uprilim = reqfssuprilim;
2034 	fssproc->fss_upri = reqfssupri;
2035 	fssproc->fss_nice = nice;
2036 	fss_newpri(fssproc, B_FALSE);
2037 
2038 	fss_change_priority(t, fssproc);
2039 	thread_unlock(t);
2040 	return (0);
2041 
2042 }
2043 
2044 /*
2045  * The thread is being stopped.
2046  */
2047 /*ARGSUSED*/
2048 static void
2049 fss_stop(kthread_t *t, int why, int what)
2050 {
2051 	ASSERT(THREAD_LOCK_HELD(t));
2052 	ASSERT(t == curthread);
2053 
2054 	fss_inactive(t);
2055 }
2056 
2057 /*
2058  * The current thread is exiting, do necessary adjustments to its project
2059  */
2060 static void
2061 fss_exit(kthread_t *t)
2062 {
2063 	fsspset_t *fsspset;
2064 	fssproj_t *fssproj;
2065 	fssproc_t *fssproc;
2066 	fsszone_t *fsszone;
2067 	int free = 0;
2068 
2069 	/*
2070 	 * Thread t here is either a current thread (in which case we hold
2071 	 * its process' p_lock), or a thread being destroyed by forklwp_fail(),
2072 	 * in which case we hold pidlock and thread is no longer on the
2073 	 * thread list.
2074 	 */
2075 	ASSERT(MUTEX_HELD(&(ttoproc(t))->p_lock) || MUTEX_HELD(&pidlock));
2076 
2077 	fssproc = FSSPROC(t);
2078 	fssproj = FSSPROC2FSSPROJ(fssproc);
2079 	fsspset = FSSPROJ2FSSPSET(fssproj);
2080 	fsszone = fssproj->fssp_fsszone;
2081 
2082 	mutex_enter(&fsspsets_lock);
2083 	mutex_enter(&fsspset->fssps_lock);
2084 
2085 	thread_lock(t);
2086 	disp_lock_enter_high(&fsspset->fssps_displock);
2087 	if (t->t_state == TS_ONPROC || t->t_state == TS_RUN) {
2088 		if (--fssproj->fssp_runnable == 0) {
2089 			fsszone->fssz_shares -= fssproj->fssp_shares;
2090 			if (--fsszone->fssz_runnable == 0)
2091 				fsspset->fssps_shares -= fsszone->fssz_rshares;
2092 		}
2093 		ASSERT(fssproc->fss_runnable == 1);
2094 		fssproc->fss_runnable = 0;
2095 	}
2096 	if (--fssproj->fssp_threads == 0) {
2097 		fss_remove_fssproj(fsspset, fssproj);
2098 		free = 1;
2099 	}
2100 	disp_lock_exit_high(&fsspset->fssps_displock);
2101 	fssproc->fss_proj = NULL;	/* mark this thread as already exited */
2102 	thread_unlock(t);
2103 
2104 	if (free) {
2105 		if (fsszone->fssz_nproj == 0)
2106 			kmem_free(fsszone, sizeof (fsszone_t));
2107 		kmem_free(fssproj, sizeof (fssproj_t));
2108 	}
2109 	mutex_exit(&fsspset->fssps_lock);
2110 	mutex_exit(&fsspsets_lock);
2111 
2112 	/*
2113 	 * A thread could be exiting in between clock ticks, so we need to
2114 	 * calculate how much CPU time it used since it was charged last time.
2115 	 *
2116 	 * CPU caps are not enforced on exiting processes - it is usually
2117 	 * desirable to exit as soon as possible to free resources.
2118 	 */
2119 	if (CPUCAPS_ON()) {
2120 		thread_lock(t);
2121 		fssproc = FSSPROC(t);
2122 		(void) cpucaps_charge(t, &fssproc->fss_caps,
2123 		    CPUCAPS_CHARGE_ONLY);
2124 		thread_unlock(t);
2125 	}
2126 }
2127 
2128 static void
2129 fss_nullsys()
2130 {
2131 }
2132 
2133 /*
2134  * fss_swapin() returns -1 if the thread is loaded or is not eligible to be
2135  * swapped in. Otherwise, it returns the thread's effective priority based
2136  * on swapout time and size of process (0 <= epri <= 0 SHRT_MAX).
2137  */
2138 /*ARGSUSED*/
2139 static pri_t
2140 fss_swapin(kthread_t *t, int flags)
2141 {
2142 	fssproc_t *fssproc = FSSPROC(t);
2143 	long epri = -1;
2144 	proc_t *pp = ttoproc(t);
2145 
2146 	ASSERT(THREAD_LOCK_HELD(t));
2147 
2148 	if (t->t_state == TS_RUN && (t->t_schedflag & TS_LOAD) == 0) {
2149 		time_t swapout_time;
2150 
2151 		swapout_time = (ddi_get_lbolt() - t->t_stime) / hz;
2152 		if (INHERITED(t)) {
2153 			epri = (long)DISP_PRIO(t) + swapout_time;
2154 		} else {
2155 			/*
2156 			 * Threads which have been out for a long time,
2157 			 * have high user mode priority and are associated
2158 			 * with a small address space are more deserving.
2159 			 */
2160 			epri = fssproc->fss_umdpri;
2161 			ASSERT(epri >= 0 && epri <= fss_maxumdpri);
2162 			epri += swapout_time - pp->p_swrss / nz(maxpgio)/2;
2163 		}
2164 		/*
2165 		 * Scale epri so that SHRT_MAX / 2 represents zero priority.
2166 		 */
2167 		epri += SHRT_MAX / 2;
2168 		if (epri < 0)
2169 			epri = 0;
2170 		else if (epri > SHRT_MAX)
2171 			epri = SHRT_MAX;
2172 	}
2173 	return ((pri_t)epri);
2174 }
2175 
2176 /*
2177  * fss_swapout() returns -1 if the thread isn't loaded or is not eligible to
2178  * be swapped out. Otherwise, it returns the thread's effective priority
2179  * based on if the swapper is in softswap or hardswap mode.
2180  */
2181 static pri_t
2182 fss_swapout(kthread_t *t, int flags)
2183 {
2184 	long epri = -1;
2185 	proc_t *pp = ttoproc(t);
2186 	time_t swapin_time;
2187 
2188 	ASSERT(THREAD_LOCK_HELD(t));
2189 
2190 	if (INHERITED(t) ||
2191 	    (t->t_proc_flag & TP_LWPEXIT) ||
2192 	    (t->t_state & (TS_ZOMB|TS_FREE|TS_STOPPED|TS_ONPROC|TS_WAIT)) ||
2193 	    !(t->t_schedflag & TS_LOAD) ||
2194 	    !(SWAP_OK(t)))
2195 		return (-1);
2196 
2197 	ASSERT(t->t_state & (TS_SLEEP | TS_RUN));
2198 
2199 	swapin_time = (ddi_get_lbolt() - t->t_stime) / hz;
2200 
2201 	if (flags == SOFTSWAP) {
2202 		if (t->t_state == TS_SLEEP && swapin_time > maxslp) {
2203 			epri = 0;
2204 		} else {
2205 			return ((pri_t)epri);
2206 		}
2207 	} else {
2208 		pri_t pri;
2209 
2210 		if ((t->t_state == TS_SLEEP && swapin_time > fss_minslp) ||
2211 		    (t->t_state == TS_RUN && swapin_time > fss_minrun)) {
2212 			pri = fss_maxumdpri;
2213 			epri = swapin_time -
2214 			    (rm_asrss(pp->p_as) / nz(maxpgio)/2) - (long)pri;
2215 		} else {
2216 			return ((pri_t)epri);
2217 		}
2218 	}
2219 
2220 	/*
2221 	 * Scale epri so that SHRT_MAX / 2 represents zero priority.
2222 	 */
2223 	epri += SHRT_MAX / 2;
2224 	if (epri < 0)
2225 		epri = 0;
2226 	else if (epri > SHRT_MAX)
2227 		epri = SHRT_MAX;
2228 
2229 	return ((pri_t)epri);
2230 }
2231 
2232 /*
2233  * Run swap-out checks when returning to userspace.
2234  */
2235 static void
2236 fss_trapret(kthread_t *t)
2237 {
2238 	cpu_t *cp = CPU;
2239 
2240 	ASSERT(THREAD_LOCK_HELD(t));
2241 	ASSERT(t == curthread);
2242 	ASSERT(cp->cpu_dispthread == t);
2243 	ASSERT(t->t_state == TS_ONPROC);
2244 
2245 	/*
2246 	 * Swapout lwp if the swapper is waiting for this thread to reach
2247 	 * a safe point.
2248 	 */
2249 	if (t->t_schedflag & TS_SWAPENQ) {
2250 		thread_unlock(t);
2251 		swapout_lwp(ttolwp(t));
2252 		thread_lock(t);
2253 	}
2254 }
2255 
2256 /*
2257  * Arrange for thread to be placed in appropriate location on dispatcher queue.
2258  * This is called with the current thread in TS_ONPROC and locked.
2259  */
2260 static void
2261 fss_preempt(kthread_t *t)
2262 {
2263 	fssproc_t *fssproc = FSSPROC(t);
2264 	klwp_t *lwp;
2265 	uint_t flags;
2266 
2267 	ASSERT(t == curthread);
2268 	ASSERT(THREAD_LOCK_HELD(curthread));
2269 	ASSERT(t->t_state == TS_ONPROC);
2270 
2271 	/*
2272 	 * This thread may be placed on wait queue by CPU Caps. In this case we
2273 	 * do not need to do anything until it is removed from the wait queue.
2274 	 * Do not enforce CPU caps on threads running at a kernel priority
2275 	 */
2276 	if (CPUCAPS_ON()) {
2277 		(void) cpucaps_charge(t, &fssproc->fss_caps,
2278 		    CPUCAPS_CHARGE_ENFORCE);
2279 
2280 		if (CPUCAPS_ENFORCE(t))
2281 			return;
2282 	}
2283 
2284 	/*
2285 	 * If preempted in user-land mark the thread as swappable because it
2286 	 * cannot be holding any kernel locks.
2287 	 */
2288 	ASSERT(t->t_schedflag & TS_DONT_SWAP);
2289 	lwp = ttolwp(t);
2290 	if (lwp != NULL && lwp->lwp_state == LWP_USER)
2291 		t->t_schedflag &= ~TS_DONT_SWAP;
2292 
2293 	/*
2294 	 * Check to see if we're doing "preemption control" here.  If
2295 	 * we are, and if the user has requested that this thread not
2296 	 * be preempted, and if preemptions haven't been put off for
2297 	 * too long, let the preemption happen here but try to make
2298 	 * sure the thread is rescheduled as soon as possible.  We do
2299 	 * this by putting it on the front of the highest priority run
2300 	 * queue in the FSS class.  If the preemption has been put off
2301 	 * for too long, clear the "nopreempt" bit and let the thread
2302 	 * be preempted.
2303 	 */
2304 	if (t->t_schedctl && schedctl_get_nopreempt(t)) {
2305 		if (fssproc->fss_timeleft > -SC_MAX_TICKS) {
2306 			DTRACE_SCHED1(schedctl__nopreempt, kthread_t *, t);
2307 			/*
2308 			 * If not already remembered, remember current
2309 			 * priority for restoration in fss_yield().
2310 			 */
2311 			if (!(fssproc->fss_flags & FSSRESTORE)) {
2312 				fssproc->fss_scpri = t->t_pri;
2313 				fssproc->fss_flags |= FSSRESTORE;
2314 			}
2315 			THREAD_CHANGE_PRI(t, fss_maxumdpri);
2316 			t->t_schedflag |= TS_DONT_SWAP;
2317 			schedctl_set_yield(t, 1);
2318 			setfrontdq(t);
2319 			return;
2320 		} else {
2321 			if (fssproc->fss_flags & FSSRESTORE) {
2322 				THREAD_CHANGE_PRI(t, fssproc->fss_scpri);
2323 				fssproc->fss_flags &= ~FSSRESTORE;
2324 			}
2325 			schedctl_set_nopreempt(t, 0);
2326 			DTRACE_SCHED1(schedctl__preempt, kthread_t *, t);
2327 			/*
2328 			 * Fall through and be preempted below.
2329 			 */
2330 		}
2331 	}
2332 
2333 	flags = fssproc->fss_flags & FSSBACKQ;
2334 
2335 	if (flags == FSSBACKQ) {
2336 		fssproc->fss_timeleft = fss_quantum;
2337 		fssproc->fss_flags &= ~FSSBACKQ;
2338 		setbackdq(t);
2339 	} else {
2340 		setfrontdq(t);
2341 	}
2342 }
2343 
2344 /*
2345  * Called when a thread is waking up and is to be placed on the run queue.
2346  */
2347 static void
2348 fss_setrun(kthread_t *t)
2349 {
2350 	fssproc_t *fssproc = FSSPROC(t);
2351 
2352 	ASSERT(THREAD_LOCK_HELD(t));	/* t should be in transition */
2353 
2354 	if (t->t_state == TS_SLEEP || t->t_state == TS_STOPPED)
2355 		fss_active(t);
2356 
2357 	fssproc->fss_timeleft = fss_quantum;
2358 
2359 	fssproc->fss_flags &= ~FSSBACKQ;
2360 	THREAD_CHANGE_PRI(t, fssproc->fss_umdpri);
2361 
2362 	if (t->t_disp_time != ddi_get_lbolt())
2363 		setbackdq(t);
2364 	else
2365 		setfrontdq(t);
2366 }
2367 
2368 /*
2369  * Prepare thread for sleep.
2370  */
2371 static void
2372 fss_sleep(kthread_t *t)
2373 {
2374 	fssproc_t *fssproc = FSSPROC(t);
2375 
2376 	ASSERT(t == curthread);
2377 	ASSERT(THREAD_LOCK_HELD(t));
2378 
2379 	ASSERT(t->t_state == TS_ONPROC);
2380 
2381 	/*
2382 	 * Account for time spent on CPU before going to sleep.
2383 	 */
2384 	(void) CPUCAPS_CHARGE(t, &fssproc->fss_caps, CPUCAPS_CHARGE_ENFORCE);
2385 
2386 	fss_inactive(t);
2387 	t->t_stime = ddi_get_lbolt();	/* time stamp for the swapper */
2388 }
2389 
2390 /*
2391  * A tick interrupt has ocurrend on a running thread. Check to see if our
2392  * time slice has expired.  We must also clear the TS_DONT_SWAP flag in
2393  * t_schedflag if the thread is eligible to be swapped out.
2394  */
2395 static void
2396 fss_tick(kthread_t *t)
2397 {
2398 	fssproc_t *fssproc;
2399 	fssproj_t *fssproj;
2400 	klwp_t *lwp;
2401 	boolean_t call_cpu_surrender = B_FALSE;
2402 	boolean_t cpucaps_enforce = B_FALSE;
2403 
2404 	ASSERT(MUTEX_HELD(&(ttoproc(t))->p_lock));
2405 
2406 	/*
2407 	 * It's safe to access fsspset and fssproj structures because we're
2408 	 * holding our p_lock here.
2409 	 */
2410 	thread_lock(t);
2411 	fssproc = FSSPROC(t);
2412 	fssproj = FSSPROC2FSSPROJ(fssproc);
2413 	if (fssproj != NULL) {
2414 		fsspset_t *fsspset = FSSPROJ2FSSPSET(fssproj);
2415 		disp_lock_enter_high(&fsspset->fssps_displock);
2416 		fssproj->fssp_ticks += fss_nice_tick[fssproc->fss_nice];
2417 		fssproj->fssp_tick_cnt++;
2418 		fssproc->fss_ticks++;
2419 		disp_lock_exit_high(&fsspset->fssps_displock);
2420 	}
2421 
2422 	/*
2423 	 * Keep track of thread's project CPU usage.  Note that projects
2424 	 * get charged even when threads are running in the kernel.
2425 	 * Do not surrender CPU if running in the SYS class.
2426 	 */
2427 	if (CPUCAPS_ON()) {
2428 		cpucaps_enforce = cpucaps_charge(t, &fssproc->fss_caps,
2429 		    CPUCAPS_CHARGE_ENFORCE);
2430 	}
2431 
2432 	if (--fssproc->fss_timeleft <= 0) {
2433 		pri_t new_pri;
2434 
2435 		/*
2436 		 * If we're doing preemption control and trying to avoid
2437 		 * preempting this thread, just note that the thread should
2438 		 * yield soon and let it keep running (unless it's been a
2439 		 * while).
2440 		 */
2441 		if (t->t_schedctl && schedctl_get_nopreempt(t)) {
2442 			if (fssproc->fss_timeleft > -SC_MAX_TICKS) {
2443 				DTRACE_SCHED1(schedctl__nopreempt,
2444 				    kthread_t *, t);
2445 				schedctl_set_yield(t, 1);
2446 				thread_unlock_nopreempt(t);
2447 				return;
2448 			}
2449 		}
2450 		fssproc->fss_flags &= ~FSSRESTORE;
2451 
2452 		fss_newpri(fssproc, B_TRUE);
2453 		new_pri = fssproc->fss_umdpri;
2454 		ASSERT(new_pri >= 0 && new_pri <= fss_maxglobpri);
2455 
2456 		/*
2457 		 * When the priority of a thread is changed, it may be
2458 		 * necessary to adjust its position on a sleep queue or
2459 		 * dispatch queue. The function thread_change_pri accomplishes
2460 		 * this.
2461 		 */
2462 		if (thread_change_pri(t, new_pri, 0)) {
2463 			if ((t->t_schedflag & TS_LOAD) &&
2464 			    (lwp = t->t_lwp) &&
2465 			    lwp->lwp_state == LWP_USER)
2466 				t->t_schedflag &= ~TS_DONT_SWAP;
2467 			fssproc->fss_timeleft = fss_quantum;
2468 		} else {
2469 			call_cpu_surrender = B_TRUE;
2470 		}
2471 	} else if (t->t_state == TS_ONPROC &&
2472 	    t->t_pri < t->t_disp_queue->disp_maxrunpri) {
2473 		/*
2474 		 * If there is a higher-priority thread which is waiting for a
2475 		 * processor, then thread surrenders the processor.
2476 		 */
2477 		call_cpu_surrender = B_TRUE;
2478 	}
2479 
2480 	if (cpucaps_enforce && 2 * fssproc->fss_timeleft > fss_quantum) {
2481 		/*
2482 		 * The thread used more than half of its quantum, so assume that
2483 		 * it used the whole quantum.
2484 		 *
2485 		 * Update thread's priority just before putting it on the wait
2486 		 * queue so that it gets charged for the CPU time from its
2487 		 * quantum even before that quantum expires.
2488 		 */
2489 		fss_newpri(fssproc, B_FALSE);
2490 		if (t->t_pri != fssproc->fss_umdpri)
2491 			fss_change_priority(t, fssproc);
2492 
2493 		/*
2494 		 * We need to call cpu_surrender for this thread due to cpucaps
2495 		 * enforcement, but fss_change_priority may have already done
2496 		 * so. In this case FSSBACKQ is set and there is no need to call
2497 		 * cpu-surrender again.
2498 		 */
2499 		if (!(fssproc->fss_flags & FSSBACKQ))
2500 			call_cpu_surrender = B_TRUE;
2501 	}
2502 
2503 	if (call_cpu_surrender) {
2504 		fssproc->fss_flags |= FSSBACKQ;
2505 		cpu_surrender(t);
2506 	}
2507 
2508 	thread_unlock_nopreempt(t);	/* clock thread can't be preempted */
2509 }
2510 
2511 /*
2512  * Processes waking up go to the back of their queue.  We don't need to assign
2513  * a time quantum here because thread is still at a kernel mode priority and
2514  * the time slicing is not done for threads running in the kernel after
2515  * sleeping.  The proper time quantum will be assigned by fss_trapret before the
2516  * thread returns to user mode.
2517  */
2518 static void
2519 fss_wakeup(kthread_t *t)
2520 {
2521 	fssproc_t *fssproc;
2522 
2523 	ASSERT(THREAD_LOCK_HELD(t));
2524 	ASSERT(t->t_state == TS_SLEEP);
2525 
2526 	fss_active(t);
2527 
2528 	t->t_stime = ddi_get_lbolt();		/* time stamp for the swapper */
2529 	fssproc = FSSPROC(t);
2530 	fssproc->fss_flags &= ~FSSBACKQ;
2531 
2532 	/* Recalculate the priority. */
2533 	if (t->t_disp_time == ddi_get_lbolt()) {
2534 		setfrontdq(t);
2535 	} else {
2536 		fssproc->fss_timeleft = fss_quantum;
2537 		THREAD_CHANGE_PRI(t, fssproc->fss_umdpri);
2538 		setbackdq(t);
2539 	}
2540 }
2541 
2542 /*
2543  * fss_donice() is called when a nice(1) command is issued on the thread to
2544  * alter the priority. The nice(1) command exists in Solaris for compatibility.
2545  * Thread priority adjustments should be done via priocntl(1).
2546  */
2547 static int
2548 fss_donice(kthread_t *t, cred_t *cr, int incr, int *retvalp)
2549 {
2550 	int newnice;
2551 	fssproc_t *fssproc = FSSPROC(t);
2552 	fssparms_t fssparms;
2553 
2554 	/*
2555 	 * If there is no change to priority, just return current setting.
2556 	 */
2557 	if (incr == 0) {
2558 		if (retvalp)
2559 			*retvalp = fssproc->fss_nice - NZERO;
2560 		return (0);
2561 	}
2562 
2563 	if ((incr < 0 || incr > 2 * NZERO) && secpolicy_raisepriority(cr) != 0)
2564 		return (EPERM);
2565 
2566 	/*
2567 	 * Specifying a nice increment greater than the upper limit of
2568 	 * FSS_NICE_MAX (== 2 * NZERO - 1) will result in the thread's nice
2569 	 * value being set to the upper limit.  We check for this before
2570 	 * computing the new value because otherwise we could get overflow
2571 	 * if a privileged user specified some ridiculous increment.
2572 	 */
2573 	if (incr > FSS_NICE_MAX)
2574 		incr = FSS_NICE_MAX;
2575 
2576 	newnice = fssproc->fss_nice + incr;
2577 	if (newnice > FSS_NICE_MAX)
2578 		newnice = FSS_NICE_MAX;
2579 	else if (newnice < FSS_NICE_MIN)
2580 		newnice = FSS_NICE_MIN;
2581 
2582 	fssparms.fss_uprilim = fssparms.fss_upri =
2583 	    -((newnice - NZERO) * fss_maxupri) / NZERO;
2584 
2585 	/*
2586 	 * Reset the uprilim and upri values of the thread.
2587 	 */
2588 	(void) fss_parmsset(t, (void *)&fssparms, (id_t)0, (cred_t *)NULL);
2589 
2590 	/*
2591 	 * Although fss_parmsset already reset fss_nice it may not have been
2592 	 * set to precisely the value calculated above because fss_parmsset
2593 	 * determines the nice value from the user priority and we may have
2594 	 * truncated during the integer conversion from nice value to user
2595 	 * priority and back. We reset fss_nice to the value we calculated
2596 	 * above.
2597 	 */
2598 	fssproc->fss_nice = (char)newnice;
2599 
2600 	if (retvalp)
2601 		*retvalp = newnice - NZERO;
2602 	return (0);
2603 }
2604 
2605 /*
2606  * Increment the priority of the specified thread by incr and
2607  * return the new value in *retvalp.
2608  */
2609 static int
2610 fss_doprio(kthread_t *t, cred_t *cr, int incr, int *retvalp)
2611 {
2612 	int newpri;
2613 	fssproc_t *fssproc = FSSPROC(t);
2614 	fssparms_t fssparms;
2615 
2616 	/*
2617 	 * If there is no change to priority, just return current setting.
2618 	 */
2619 	if (incr == 0) {
2620 		*retvalp = fssproc->fss_upri;
2621 		return (0);
2622 	}
2623 
2624 	newpri = fssproc->fss_upri + incr;
2625 	if (newpri > fss_maxupri || newpri < -fss_maxupri)
2626 		return (EINVAL);
2627 
2628 	*retvalp = newpri;
2629 	fssparms.fss_uprilim = fssparms.fss_upri = newpri;
2630 
2631 	/*
2632 	 * Reset the uprilim and upri values of the thread.
2633 	 */
2634 	return (fss_parmsset(t, &fssparms, (id_t)0, cr));
2635 }
2636 
2637 /*
2638  * Return the global scheduling priority that would be assigned to a thread
2639  * entering the fair-sharing class with the fss_upri.
2640  */
2641 /*ARGSUSED*/
2642 static pri_t
2643 fss_globpri(kthread_t *t)
2644 {
2645 	ASSERT(MUTEX_HELD(&ttoproc(t)->p_lock));
2646 
2647 	return (fss_maxumdpri / 2);
2648 }
2649 
2650 /*
2651  * Called from the yield(2) system call when a thread is yielding (surrendering)
2652  * the processor. The kernel thread is placed at the back of a dispatch queue.
2653  */
2654 static void
2655 fss_yield(kthread_t *t)
2656 {
2657 	fssproc_t *fssproc = FSSPROC(t);
2658 
2659 	ASSERT(t == curthread);
2660 	ASSERT(THREAD_LOCK_HELD(t));
2661 
2662 	/*
2663 	 * Collect CPU usage spent before yielding
2664 	 */
2665 	(void) CPUCAPS_CHARGE(t, &fssproc->fss_caps, CPUCAPS_CHARGE_ENFORCE);
2666 
2667 	/*
2668 	 * Clear the preemption control "yield" bit since the user is
2669 	 * doing a yield.
2670 	 */
2671 	if (t->t_schedctl)
2672 		schedctl_set_yield(t, 0);
2673 	/*
2674 	 * If fss_preempt() artifically increased the thread's priority
2675 	 * to avoid preemption, restore the original priority now.
2676 	 */
2677 	if (fssproc->fss_flags & FSSRESTORE) {
2678 		THREAD_CHANGE_PRI(t, fssproc->fss_scpri);
2679 		fssproc->fss_flags &= ~FSSRESTORE;
2680 	}
2681 	if (fssproc->fss_timeleft < 0) {
2682 		/*
2683 		 * Time slice was artificially extended to avoid preemption,
2684 		 * so pretend we're preempting it now.
2685 		 */
2686 		DTRACE_SCHED1(schedctl__yield, int, -fssproc->fss_timeleft);
2687 		fssproc->fss_timeleft = fss_quantum;
2688 	}
2689 	fssproc->fss_flags &= ~FSSBACKQ;
2690 	setbackdq(t);
2691 }
2692 
2693 void
2694 fss_changeproj(kthread_t *t, void *kp, void *zp, fssbuf_t *projbuf,
2695     fssbuf_t *zonebuf)
2696 {
2697 	kproject_t *kpj_new = kp;
2698 	zone_t *zone = zp;
2699 	fssproj_t *fssproj_old, *fssproj_new;
2700 	fsspset_t *fsspset;
2701 	kproject_t *kpj_old;
2702 	fssproc_t *fssproc;
2703 	fsszone_t *fsszone_old, *fsszone_new;
2704 	int free = 0;
2705 	int id;
2706 
2707 	ASSERT(MUTEX_HELD(&cpu_lock));
2708 	ASSERT(MUTEX_HELD(&pidlock));
2709 	ASSERT(MUTEX_HELD(&ttoproc(t)->p_lock));
2710 
2711 	if (t->t_cid != fss_cid)
2712 		return;
2713 
2714 	fssproc = FSSPROC(t);
2715 	mutex_enter(&fsspsets_lock);
2716 	fssproj_old = FSSPROC2FSSPROJ(fssproc);
2717 	if (fssproj_old == NULL) {
2718 		mutex_exit(&fsspsets_lock);
2719 		return;
2720 	}
2721 
2722 	fsspset = FSSPROJ2FSSPSET(fssproj_old);
2723 	mutex_enter(&fsspset->fssps_lock);
2724 	kpj_old = FSSPROJ2KPROJ(fssproj_old);
2725 	fsszone_old = fssproj_old->fssp_fsszone;
2726 
2727 	ASSERT(t->t_cpupart == fsspset->fssps_cpupart);
2728 
2729 	if (kpj_old == kpj_new) {
2730 		mutex_exit(&fsspset->fssps_lock);
2731 		mutex_exit(&fsspsets_lock);
2732 		return;
2733 	}
2734 
2735 	if ((fsszone_new = fss_find_fsszone(fsspset, zone)) == NULL) {
2736 		/*
2737 		 * If the zone for the new project is not currently active on
2738 		 * the cpu partition we're on, get one of the pre-allocated
2739 		 * buffers and link it in our per-pset zone list.  Such buffers
2740 		 * should already exist.
2741 		 */
2742 		for (id = 0; id < zonebuf->fssb_size; id++) {
2743 			if ((fsszone_new = zonebuf->fssb_list[id]) != NULL) {
2744 				fss_insert_fsszone(fsspset, zone, fsszone_new);
2745 				zonebuf->fssb_list[id] = NULL;
2746 				break;
2747 			}
2748 		}
2749 	}
2750 	ASSERT(fsszone_new != NULL);
2751 	if ((fssproj_new = fss_find_fssproj(fsspset, kpj_new)) == NULL) {
2752 		/*
2753 		 * If our new project is not currently running
2754 		 * on the cpu partition we're on, get one of the
2755 		 * pre-allocated buffers and link it in our new cpu
2756 		 * partition doubly linked list. Such buffers should already
2757 		 * exist.
2758 		 */
2759 		for (id = 0; id < projbuf->fssb_size; id++) {
2760 			if ((fssproj_new = projbuf->fssb_list[id]) != NULL) {
2761 				fss_insert_fssproj(fsspset, kpj_new,
2762 				    fsszone_new, fssproj_new);
2763 				projbuf->fssb_list[id] = NULL;
2764 				break;
2765 			}
2766 		}
2767 	}
2768 	ASSERT(fssproj_new != NULL);
2769 
2770 	thread_lock(t);
2771 	if (t->t_state == TS_RUN || t->t_state == TS_ONPROC ||
2772 	    t->t_state == TS_WAIT)
2773 		fss_inactive(t);
2774 	ASSERT(fssproj_old->fssp_threads > 0);
2775 	if (--fssproj_old->fssp_threads == 0) {
2776 		fss_remove_fssproj(fsspset, fssproj_old);
2777 		free = 1;
2778 	}
2779 	fssproc->fss_proj = fssproj_new;
2780 	fssproc->fss_fsspri = 0;
2781 	fssproj_new->fssp_threads++;
2782 	if (t->t_state == TS_RUN || t->t_state == TS_ONPROC ||
2783 	    t->t_state == TS_WAIT)
2784 		fss_active(t);
2785 	thread_unlock(t);
2786 	if (free) {
2787 		if (fsszone_old->fssz_nproj == 0)
2788 			kmem_free(fsszone_old, sizeof (fsszone_t));
2789 		kmem_free(fssproj_old, sizeof (fssproj_t));
2790 	}
2791 
2792 	mutex_exit(&fsspset->fssps_lock);
2793 	mutex_exit(&fsspsets_lock);
2794 }
2795 
2796 void
2797 fss_changepset(kthread_t *t, void *newcp, fssbuf_t *projbuf,
2798     fssbuf_t *zonebuf)
2799 {
2800 	fsspset_t *fsspset_old, *fsspset_new;
2801 	fssproj_t *fssproj_old, *fssproj_new;
2802 	fsszone_t *fsszone_old, *fsszone_new;
2803 	fssproc_t *fssproc;
2804 	kproject_t *kpj;
2805 	zone_t *zone;
2806 	int id;
2807 
2808 	ASSERT(MUTEX_HELD(&cpu_lock));
2809 	ASSERT(MUTEX_HELD(&pidlock));
2810 	ASSERT(MUTEX_HELD(&ttoproc(t)->p_lock));
2811 
2812 	if (t->t_cid != fss_cid)
2813 		return;
2814 
2815 	fssproc = FSSPROC(t);
2816 	zone = ttoproc(t)->p_zone;
2817 	mutex_enter(&fsspsets_lock);
2818 	fssproj_old = FSSPROC2FSSPROJ(fssproc);
2819 	if (fssproj_old == NULL) {
2820 		mutex_exit(&fsspsets_lock);
2821 		return;
2822 	}
2823 	fsszone_old = fssproj_old->fssp_fsszone;
2824 	fsspset_old = FSSPROJ2FSSPSET(fssproj_old);
2825 	kpj = FSSPROJ2KPROJ(fssproj_old);
2826 
2827 	if (fsspset_old->fssps_cpupart == newcp) {
2828 		mutex_exit(&fsspsets_lock);
2829 		return;
2830 	}
2831 
2832 	ASSERT(ttoproj(t) == kpj);
2833 
2834 	fsspset_new = fss_find_fsspset(newcp);
2835 
2836 	mutex_enter(&fsspset_new->fssps_lock);
2837 	if ((fsszone_new = fss_find_fsszone(fsspset_new, zone)) == NULL) {
2838 		for (id = 0; id < zonebuf->fssb_size; id++) {
2839 			if ((fsszone_new = zonebuf->fssb_list[id]) != NULL) {
2840 				fss_insert_fsszone(fsspset_new, zone,
2841 				    fsszone_new);
2842 				zonebuf->fssb_list[id] = NULL;
2843 				break;
2844 			}
2845 		}
2846 	}
2847 	ASSERT(fsszone_new != NULL);
2848 	if ((fssproj_new = fss_find_fssproj(fsspset_new, kpj)) == NULL) {
2849 		for (id = 0; id < projbuf->fssb_size; id++) {
2850 			if ((fssproj_new = projbuf->fssb_list[id]) != NULL) {
2851 				fss_insert_fssproj(fsspset_new, kpj,
2852 				    fsszone_new, fssproj_new);
2853 				projbuf->fssb_list[id] = NULL;
2854 				break;
2855 			}
2856 		}
2857 	}
2858 	ASSERT(fssproj_new != NULL);
2859 
2860 	fssproj_new->fssp_threads++;
2861 	thread_lock(t);
2862 	if (t->t_state == TS_RUN || t->t_state == TS_ONPROC ||
2863 	    t->t_state == TS_WAIT)
2864 		fss_inactive(t);
2865 	fssproc->fss_proj = fssproj_new;
2866 	fssproc->fss_fsspri = 0;
2867 	if (t->t_state == TS_RUN || t->t_state == TS_ONPROC ||
2868 	    t->t_state == TS_WAIT)
2869 		fss_active(t);
2870 	thread_unlock(t);
2871 	mutex_exit(&fsspset_new->fssps_lock);
2872 
2873 	mutex_enter(&fsspset_old->fssps_lock);
2874 	if (--fssproj_old->fssp_threads == 0) {
2875 		fss_remove_fssproj(fsspset_old, fssproj_old);
2876 		if (fsszone_old->fssz_nproj == 0)
2877 			kmem_free(fsszone_old, sizeof (fsszone_t));
2878 		kmem_free(fssproj_old, sizeof (fssproj_t));
2879 	}
2880 	mutex_exit(&fsspset_old->fssps_lock);
2881 
2882 	mutex_exit(&fsspsets_lock);
2883 }
2884