Define VERSYMIDX/VALIDX/ADDRIDX in ldsodefs.h
[glibc.git] / manual / resource.texi
blobcb25d2440c47927172c6ebd9fde517fe341444da
1 @node Resource Usage And Limitation, Non-Local Exits, Date and Time, Top
2 @c %MENU% Functions for examining resource usage and getting and setting limits
3 @chapter Resource Usage And Limitation
4 This chapter describes functions for examining how much of various kinds of
5 resources (CPU time, memory, etc.) a process has used and getting and setting
6 limits on future usage.
8 @menu
9 * Resource Usage::              Measuring various resources used.
10 * Limits on Resources::         Specifying limits on resource usage.
11 * Priority::                    Reading or setting process run priority.
12 * Memory Resources::            Querying memory available resources.
13 * Processor Resources::         Learn about the processors available.
14 @end menu
17 @node Resource Usage
18 @section Resource Usage
20 @pindex sys/resource.h
21 The function @code{getrusage} and the data type @code{struct rusage}
22 are used to examine the resource usage of a process.  They are declared
23 in @file{sys/resource.h}.
25 @comment sys/resource.h
26 @comment BSD
27 @deftypefun int getrusage (int @var{processes}, struct rusage *@var{rusage})
28 This function reports resource usage totals for processes specified by
29 @var{processes}, storing the information in @code{*@var{rusage}}.
31 In most systems, @var{processes} has only two valid values:
33 @table @code
34 @comment sys/resource.h
35 @comment BSD
36 @item RUSAGE_SELF
37 Just the current process.
39 @comment sys/resource.h
40 @comment BSD
41 @item RUSAGE_CHILDREN
42 All child processes (direct and indirect) that have already terminated.
43 @end table
45 The return value of @code{getrusage} is zero for success, and @code{-1}
46 for failure.
48 @table @code
49 @item EINVAL
50 The argument @var{processes} is not valid.
51 @end table
52 @end deftypefun
54 One way of getting resource usage for a particular child process is with
55 the function @code{wait4}, which returns totals for a child when it
56 terminates.  @xref{BSD Wait Functions}.
58 @comment sys/resource.h
59 @comment BSD
60 @deftp {Data Type} {struct rusage}
61 This data type stores various resource usage statistics.  It has the
62 following members, and possibly others:
64 @table @code
65 @item struct timeval ru_utime
66 Time spent executing user instructions.
68 @item struct timeval ru_stime
69 Time spent in operating system code on behalf of @var{processes}.
71 @item long int ru_maxrss
72 The maximum resident set size used, in kilobytes.  That is, the maximum
73 number of kilobytes of physical memory that @var{processes} used
74 simultaneously.
76 @item long int ru_ixrss
77 An integral value expressed in kilobytes times ticks of execution, which
78 indicates the amount of memory used by text that was shared with other
79 processes.
81 @item long int ru_idrss
82 An integral value expressed the same way, which is the amount of
83 unshared memory used for data.
85 @item long int ru_isrss
86 An integral value expressed the same way, which is the amount of
87 unshared memory used for stack space.
89 @item long int ru_minflt
90 The number of page faults which were serviced without requiring any I/O.
92 @item long int ru_majflt
93 The number of page faults which were serviced by doing I/O.
95 @item long int ru_nswap
96 The number of times @var{processes} was swapped entirely out of main memory.
98 @item long int ru_inblock
99 The number of times the file system had to read from the disk on behalf
100 of @var{processes}.
102 @item long int ru_oublock
103 The number of times the file system had to write to the disk on behalf
104 of @var{processes}.
106 @item long int ru_msgsnd
107 Number of IPC messages sent.
109 @item long int ru_msgrcv
110 Number of IPC messages received.
112 @item long int ru_nsignals
113 Number of signals received.
115 @item long int ru_nvcsw
116 The number of times @var{processes} voluntarily invoked a context switch
117 (usually to wait for some service).
119 @item long int ru_nivcsw
120 The number of times an involuntary context switch took place (because
121 a time slice expired, or another process of higher priority was
122 scheduled).
123 @end table
124 @end deftp
126 @code{vtimes} is a historical function that does some of what
127 @code{getrusage} does.  @code{getrusage} is a better choice.
129 @code{vtimes} and its @code{vtimes} data structure are declared in
130 @file{sys/vtimes.h}.
131 @pindex sys/vtimes.h
132 @comment vtimes.h
134 @deftypefun int vtimes (struct vtimes @var{current}, struct vtimes @var{child})
136 @code{vtimes} reports resource usage totals for a process.
138 If @var{current} is non-null, @code{vtimes} stores resource usage totals for
139 the invoking process alone in the structure to which it points.  If
140 @var{child} is non-null, @code{vtimes} stores resource usage totals for all
141 past children (which have terminated) of the invoking process in the structure
142 to which it points.
144 @deftp {Data Type} {struct vtimes}
145 This data type contains information about the resource usage of a process.
146 Each member corresponds to a member of the @code{struct rusage} data type
147 described above.
149 @table @code
150 @item vm_utime
151 User CPU time.  Analogous to @code{ru_utime} in @code{struct rusage}
152 @item vm_stime
153 System CPU time.  Analogous to @code{ru_stime} in @code{struct rusage}
154 @item vm_idsrss
155 Data and stack memory.  The sum of the values that would be reported as
156 @code{ru_idrss} and @code{ru_isrss} in @code{struct rusage}
157 @item vm_ixrss
158 Shared memory.  Analogous to @code{ru_ixrss} in @code{struct rusage}
159 @item vm_maxrss
160 Maximent resident set size.  Analogous to @code{ru_maxrss} in
161 @code{struct rusage}
162 @item vm_majflt
163 Major page faults.  Analogous to @code{ru_majflt} in @code{struct rusage}
164 @item vm_minflt
165 Minor page faults.  Analogous to @code{ru_minflt} in @code{struct rusage}
166 @item vm_nswap
167 Swap count.  Analogous to @code{ru_nswap} in @code{struct rusage}
168 @item vm_inblk
169 Disk reads.  Analogous to @code{ru_inblk} in @code{struct rusage}
170 @item vm_oublk
171 Disk writes.  Analogous to @code{ru_oublk} in @code{struct rusage}
172 @end table
173 @end deftp
176 The return value is zero if the function succeeds; @code{-1} otherwise.
180 @end deftypefun
181 An additional historical function for examining resource usage,
182 @code{vtimes}, is supported but not documented here.  It is declared in
183 @file{sys/vtimes.h}.
185 @node Limits on Resources
186 @section Limiting Resource Usage
187 @cindex resource limits
188 @cindex limits on resource usage
189 @cindex usage limits
191 You can specify limits for the resource usage of a process.  When the
192 process tries to exceed a limit, it may get a signal, or the system call
193 by which it tried to do so may fail, depending on the resource.  Each
194 process initially inherits its limit values from its parent, but it can
195 subsequently change them.
197 There are two per-process limits associated with a resource:
198 @cindex limit
200 @table @dfn
201 @item current limit
202 The current limit is the value the system will not allow usage to
203 exceed.  It is also called the ``soft limit'' because the process being
204 limited can generally raise the current limit at will.
205 @cindex current limit
206 @cindex soft limit
208 @item maximum limit
209 The maximum limit is the maximum value to which a process is allowed to
210 set its current limit.  It is also called the ``hard limit'' because
211 there is no way for a process to get around it.  A process may lower
212 its own maximum limit, but only the superuser may increase a maximum
213 limit.
214 @cindex maximum limit
215 @cindex hard limit
216 @end table
218 @pindex sys/resource.h
219 The symbols for use with @code{getrlimit}, @code{setrlimit},
220 @code{getrlimit64}, and @code{setrlimit64} are defined in
221 @file{sys/resource.h}.
223 @comment sys/resource.h
224 @comment BSD
225 @deftypefun int getrlimit (int @var{resource}, struct rlimit *@var{rlp})
226 Read the current and maximum limits for the resource @var{resource}
227 and store them in @code{*@var{rlp}}.
229 The return value is @code{0} on success and @code{-1} on failure.  The
230 only possible @code{errno} error condition is @code{EFAULT}.
232 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
233 32-bit system this function is in fact @code{getrlimit64}.  Thus, the
234 LFS interface transparently replaces the old interface.
235 @end deftypefun
237 @comment sys/resource.h
238 @comment Unix98
239 @deftypefun int getrlimit64 (int @var{resource}, struct rlimit64 *@var{rlp})
240 This function is similar to @code{getrlimit} but its second parameter is
241 a pointer to a variable of type @code{struct rlimit64}, which allows it
242 to read values which wouldn't fit in the member of a @code{struct
243 rlimit}.
245 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
246 32-bit machine, this function is available under the name
247 @code{getrlimit} and so transparently replaces the old interface.
248 @end deftypefun
250 @comment sys/resource.h
251 @comment BSD
252 @deftypefun int setrlimit (int @var{resource}, const struct rlimit *@var{rlp})
253 Store the current and maximum limits for the resource @var{resource}
254 in @code{*@var{rlp}}.
256 The return value is @code{0} on success and @code{-1} on failure.  The
257 following @code{errno} error condition is possible:
259 @table @code
260 @item EPERM
261 @itemize @bullet
262 @item
263 The process tried to raise a current limit beyond the maximum limit.
265 @item
266 The process tried to raise a maximum limit, but is not superuser.
267 @end itemize
268 @end table
270 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
271 32-bit system this function is in fact @code{setrlimit64}.  Thus, the
272 LFS interface transparently replaces the old interface.
273 @end deftypefun
275 @comment sys/resource.h
276 @comment Unix98
277 @deftypefun int setrlimit64 (int @var{resource}, const struct rlimit64 *@var{rlp})
278 This function is similar to @code{setrlimit} but its second parameter is
279 a pointer to a variable of type @code{struct rlimit64} which allows it
280 to set values which wouldn't fit in the member of a @code{struct
281 rlimit}.
283 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
284 32-bit machine this function is available under the name
285 @code{setrlimit} and so transparently replaces the old interface.
286 @end deftypefun
288 @comment sys/resource.h
289 @comment BSD
290 @deftp {Data Type} {struct rlimit}
291 This structure is used with @code{getrlimit} to receive limit values,
292 and with @code{setrlimit} to specify limit values for a particular process
293 and resource.  It has two fields:
295 @table @code
296 @item rlim_t rlim_cur
297 The current limit
299 @item rlim_t rlim_max
300 The maximum limit.
301 @end table
303 For @code{getrlimit}, the structure is an output; it receives the current
304 values.  For @code{setrlimit}, it specifies the new values.
305 @end deftp
307 For the LFS functions a similar type is defined in @file{sys/resource.h}.
309 @comment sys/resource.h
310 @comment Unix98
311 @deftp {Data Type} {struct rlimit64}
312 This structure is analogous to the @code{rlimit} structure above, but
313 its components have wider ranges.  It has two fields:
315 @table @code
316 @item rlim64_t rlim_cur
317 This is analogous to @code{rlimit.rlim_cur}, but with a different type.
319 @item rlim64_t rlim_max
320 This is analogous to @code{rlimit.rlim_max}, but with a different type.
321 @end table
323 @end deftp
325 Here is a list of resources for which you can specify a limit.  Memory
326 and file sizes are measured in bytes.
328 @table @code
329 @comment sys/resource.h
330 @comment BSD
331 @item RLIMIT_CPU
332 @vindex RLIMIT_CPU
333 The maximum amount of CPU time the process can use.  If it runs for
334 longer than this, it gets a signal: @code{SIGXCPU}.  The value is
335 measured in seconds.  @xref{Operation Error Signals}.
337 @comment sys/resource.h
338 @comment BSD
339 @item RLIMIT_FSIZE
340 @vindex RLIMIT_FSIZE
341 The maximum size of file the process can create.  Trying to write a
342 larger file causes a signal: @code{SIGXFSZ}.  @xref{Operation Error
343 Signals}.
345 @comment sys/resource.h
346 @comment BSD
347 @item RLIMIT_DATA
348 @vindex RLIMIT_DATA
349 The maximum size of data memory for the process.  If the process tries
350 to allocate data memory beyond this amount, the allocation function
351 fails.
353 @comment sys/resource.h
354 @comment BSD
355 @item RLIMIT_STACK
356 @vindex RLIMIT_STACK
357 The maximum stack size for the process.  If the process tries to extend
358 its stack past this size, it gets a @code{SIGSEGV} signal.
359 @xref{Program Error Signals}.
361 @comment sys/resource.h
362 @comment BSD
363 @item RLIMIT_CORE
364 @vindex RLIMIT_CORE
365 The maximum size core file that this process can create.  If the process
366 terminates and would dump a core file larger than this, then no core
367 file is created.  So setting this limit to zero prevents core files from
368 ever being created.
370 @comment sys/resource.h
371 @comment BSD
372 @item RLIMIT_RSS
373 @vindex RLIMIT_RSS
374 The maximum amount of physical memory that this process should get.
375 This parameter is a guide for the system's scheduler and memory
376 allocator; the system may give the process more memory when there is a
377 surplus.
379 @comment sys/resource.h
380 @comment BSD
381 @item RLIMIT_MEMLOCK
382 The maximum amount of memory that can be locked into physical memory (so
383 it will never be paged out).
385 @comment sys/resource.h
386 @comment BSD
387 @item RLIMIT_NPROC
388 The maximum number of processes that can be created with the same user ID.
389 If you have reached the limit for your user ID, @code{fork} will fail
390 with @code{EAGAIN}.  @xref{Creating a Process}.
392 @comment sys/resource.h
393 @comment BSD
394 @item RLIMIT_NOFILE
395 @vindex RLIMIT_NOFILE
396 @itemx RLIMIT_OFILE
397 @vindex RLIMIT_OFILE
398 The maximum number of files that the process can open.  If it tries to
399 open more files than this, its open attempt fails with @code{errno}
400 @code{EMFILE}.  @xref{Error Codes}.  Not all systems support this limit;
401 GNU does, and 4.4 BSD does.
403 @comment sys/resource.h
404 @comment Unix98
405 @item RLIMIT_AS
406 @vindex RLIMIT_AS
407 The maximum size of total memory that this process should get.  If the
408 process tries to allocate more memory beyond this amount with, for
409 example, @code{brk}, @code{malloc}, @code{mmap} or @code{sbrk}, the
410 allocation function fails.
412 @comment sys/resource.h
413 @comment BSD
414 @item RLIM_NLIMITS
415 @vindex RLIM_NLIMITS
416 The number of different resource limits.  Any valid @var{resource}
417 operand must be less than @code{RLIM_NLIMITS}.
418 @end table
420 @comment sys/resource.h
421 @comment BSD
422 @deftypevr Constant int RLIM_INFINITY
423 This constant stands for a value of ``infinity'' when supplied as
424 the limit value in @code{setrlimit}.
425 @end deftypevr
428 The following are historical functions to do some of what the functions
429 above do.  The functions above are better choices.
431 @code{ulimit} and the command symbols are declared in @file{ulimit.h}.
432 @pindex ulimit.h
434 @comment ulimit.h
435 @comment BSD
436 @deftypefun int ulimit (int @var{cmd}, @dots{})
438 @code{ulimit} gets the current limit or sets the current and maximum
439 limit for a particular resource for the calling process according to the
440 command @var{cmd}.a
442 If you are getting a limit, the command argument is the only argument.
443 If you are setting a limit, there is a second argument:
444 @code{long int} @var{limit} which is the value to which you are setting
445 the limit.
447 The @var{cmd} values and the operations they specify are:
448 @table @code
450 @item GETFSIZE
451 Get the current limit on the size of a file, in units of 512 bytes.
453 @item SETFSIZE
454 Set the current and maximum limit on the size of a file to @var{limit} *
455 512 bytes.
457 @end table
459 There are also some other @var{cmd} values that may do things on some
460 systems, but they are not supported.
462 Only the superuser may increase a maximum limit.
464 When you successfully get a limit, the return value of @code{ulimit} is
465 that limit, which is never negative.  When you successfully set a limit,
466 the return value is zero.  When the function fails, the return value is
467 @code{-1} and @code{errno} is set according to the reason:
469 @table @code
470 @item EPERM
471 A process tried to increase a maximum limit, but is not superuser.
472 @end table
475 @end deftypefun
477 @code{vlimit} and its resource symbols are declared in @file{sys/vlimit.h}.
478 @pindex sys/vlimit.h
480 @comment sys/vlimit.h
481 @comment BSD
482 @deftypefun int vlimit (int @var{resource}, int @var{limit})
484 @code{vlimit} sets the current limit for a resource for a process.
486 @var{resource} identifies the resource:
488 @table @code
489 @item LIM_CPU
490 Maximum CPU time.  Same as @code{RLIMIT_CPU} for @code{setrlimit}.
491 @item LIM_FSIZE
492 Maximum file size.  Same as @code{RLIMIT_FSIZE} for @code{setrlimit}.
493 @item LIM_DATA
494 Maximum data memory.  Same as @code{RLIMIT_DATA} for @code{setrlimit}.
495 @item LIM_STACK
496 Maximum stack size.  Same as @code{RLIMIT_STACK} for @code{setrlimit}.
497 @item LIM_CORE
498 Maximum core file size.  Same as @code{RLIMIT_COR} for @code{setrlimit}.
499 @item LIM_MAXRSS
500 Maximum physical memory.  Same as @code{RLIMIT_RSS} for @code{setrlimit}.
501 @end table
503 The return value is zero for success, and @code{-1} with @code{errno} set
504 accordingly for failure:
506 @table @code
507 @item EPERM
508 The process tried to set its current limit beyond its maximum limit.
509 @end table
511 @end deftypefun
513 @node Priority
514 @section Process CPU Priority And Scheduling
515 @cindex process priority
516 @cindex cpu priority
517 @cindex priority of a process
519 When multiple processes simultaneously require CPU time, the system's
520 scheduling policy and process CPU priorities determine which processes
521 get it.  This section describes how that determination is made and
522 @glibcadj{} functions to control it.
524 It is common to refer to CPU scheduling simply as scheduling and a
525 process' CPU priority simply as the process' priority, with the CPU
526 resource being implied.  Bear in mind, though, that CPU time is not the
527 only resource a process uses or that processes contend for.  In some
528 cases, it is not even particularly important.  Giving a process a high
529 ``priority'' may have very little effect on how fast a process runs with
530 respect to other processes.  The priorities discussed in this section
531 apply only to CPU time.
533 CPU scheduling is a complex issue and different systems do it in wildly
534 different ways.  New ideas continually develop and find their way into
535 the intricacies of the various systems' scheduling algorithms.  This
536 section discusses the general concepts, some specifics of systems
537 that commonly use @theglibc{}, and some standards.
539 For simplicity, we talk about CPU contention as if there is only one CPU
540 in the system.  But all the same principles apply when a processor has
541 multiple CPUs, and knowing that the number of processes that can run at
542 any one time is equal to the number of CPUs, you can easily extrapolate
543 the information.
545 The functions described in this section are all defined by the POSIX.1
546 and POSIX.1b standards (the @code{sched@dots{}} functions are POSIX.1b).
547 However, POSIX does not define any semantics for the values that these
548 functions get and set.  In this chapter, the semantics are based on the
549 Linux kernel's implementation of the POSIX standard.  As you will see,
550 the Linux implementation is quite the inverse of what the authors of the
551 POSIX syntax had in mind.
553 @menu
554 * Absolute Priority::               The first tier of priority.  Posix
555 * Realtime Scheduling::             Scheduling among the process nobility
556 * Basic Scheduling Functions::      Get/set scheduling policy, priority
557 * Traditional Scheduling::          Scheduling among the vulgar masses
558 * CPU Affinity::                    Limiting execution to certain CPUs
559 @end menu
563 @node Absolute Priority
564 @subsection Absolute Priority
565 @cindex absolute priority
566 @cindex priority, absolute
568 Every process has an absolute priority, and it is represented by a number.
569 The higher the number, the higher the absolute priority.
571 @cindex realtime CPU scheduling
572 On systems of the past, and most systems today, all processes have
573 absolute priority 0 and this section is irrelevant.  In that case,
574 @xref{Traditional Scheduling}.  Absolute priorities were invented to
575 accommodate realtime systems, in which it is vital that certain processes
576 be able to respond to external events happening in real time, which
577 means they cannot wait around while some other process that @emph{wants
578 to}, but doesn't @emph{need to} run occupies the CPU.
580 @cindex ready to run
581 @cindex preemptive scheduling
582 When two processes are in contention to use the CPU at any instant, the
583 one with the higher absolute priority always gets it.  This is true even if the
584 process with the lower priority is already using the CPU (i.e., the
585 scheduling is preemptive).  Of course, we're only talking about
586 processes that are running or ``ready to run,'' which means they are
587 ready to execute instructions right now.  When a process blocks to wait
588 for something like I/O, its absolute priority is irrelevant.
590 @cindex runnable process
591 @strong{NB:}  The term ``runnable'' is a synonym for ``ready to run.''
593 When two processes are running or ready to run and both have the same
594 absolute priority, it's more interesting.  In that case, who gets the
595 CPU is determined by the scheduling policy.  If the processes have
596 absolute priority 0, the traditional scheduling policy described in
597 @ref{Traditional Scheduling} applies.  Otherwise, the policies described
598 in @ref{Realtime Scheduling} apply.
600 You normally give an absolute priority above 0 only to a process that
601 can be trusted not to hog the CPU.  Such processes are designed to block
602 (or terminate) after relatively short CPU runs.
604 A process begins life with the same absolute priority as its parent
605 process.  Functions described in @ref{Basic Scheduling Functions} can
606 change it.
608 Only a privileged process can change a process' absolute priority to
609 something other than @code{0}.  Only a privileged process or the
610 target process' owner can change its absolute priority at all.
612 POSIX requires absolute priority values used with the realtime
613 scheduling policies to be consecutive with a range of at least 32.  On
614 Linux, they are 1 through 99.  The functions
615 @code{sched_get_priority_max} and @code{sched_set_priority_min} portably
616 tell you what the range is on a particular system.
619 @subsubsection Using Absolute Priority
621 One thing you must keep in mind when designing real time applications is
622 that having higher absolute priority than any other process doesn't
623 guarantee the process can run continuously.  Two things that can wreck a
624 good CPU run are interrupts and page faults.
626 Interrupt handlers live in that limbo between processes.  The CPU is
627 executing instructions, but they aren't part of any process.  An
628 interrupt will stop even the highest priority process.  So you must
629 allow for slight delays and make sure that no device in the system has
630 an interrupt handler that could cause too long a delay between
631 instructions for your process.
633 Similarly, a page fault causes what looks like a straightforward
634 sequence of instructions to take a long time.  The fact that other
635 processes get to run while the page faults in is of no consequence,
636 because as soon as the I/O is complete, the high priority process will
637 kick them out and run again, but the wait for the I/O itself could be a
638 problem.  To neutralize this threat, use @code{mlock} or
639 @code{mlockall}.
641 There are a few ramifications of the absoluteness of this priority on a
642 single-CPU system that you need to keep in mind when you choose to set a
643 priority and also when you're working on a program that runs with high
644 absolute priority.  Consider a process that has higher absolute priority
645 than any other process in the system and due to a bug in its program, it
646 gets into an infinite loop.  It will never cede the CPU.  You can't run
647 a command to kill it because your command would need to get the CPU in
648 order to run.  The errant program is in complete control.  It controls
649 the vertical, it controls the horizontal.
651 There are two ways to avoid this: 1) keep a shell running somewhere with
652 a higher absolute priority.  2) keep a controlling terminal attached to
653 the high priority process group.  All the priority in the world won't
654 stop an interrupt handler from running and delivering a signal to the
655 process if you hit Control-C.
657 Some systems use absolute priority as a means of allocating a fixed
658 percentage of CPU time to a process.  To do this, a super high priority
659 privileged process constantly monitors the process' CPU usage and raises
660 its absolute priority when the process isn't getting its entitled share
661 and lowers it when the process is exceeding it.
663 @strong{NB:}  The absolute priority is sometimes called the ``static
664 priority.''  We don't use that term in this manual because it misses the
665 most important feature of the absolute priority:  its absoluteness.
668 @node Realtime Scheduling
669 @subsection Realtime Scheduling
670 @cindex realtime scheduling
672 Whenever two processes with the same absolute priority are ready to run,
673 the kernel has a decision to make, because only one can run at a time.
674 If the processes have absolute priority 0, the kernel makes this decision
675 as described in @ref{Traditional Scheduling}.  Otherwise, the decision
676 is as described in this section.
678 If two processes are ready to run but have different absolute priorities,
679 the decision is much simpler, and is described in @ref{Absolute
680 Priority}.
682 Each process has a scheduling policy.  For processes with absolute
683 priority other than zero, there are two available:
685 @enumerate
686 @item
687 First Come First Served
688 @item
689 Round Robin
690 @end enumerate
692 The most sensible case is where all the processes with a certain
693 absolute priority have the same scheduling policy.  We'll discuss that
694 first.
696 In Round Robin, processes share the CPU, each one running for a small
697 quantum of time (``time slice'') and then yielding to another in a
698 circular fashion.  Of course, only processes that are ready to run and
699 have the same absolute priority are in this circle.
701 In First Come First Served, the process that has been waiting the
702 longest to run gets the CPU, and it keeps it until it voluntarily
703 relinquishes the CPU, runs out of things to do (blocks), or gets
704 preempted by a higher priority process.
706 First Come First Served, along with maximal absolute priority and
707 careful control of interrupts and page faults, is the one to use when a
708 process absolutely, positively has to run at full CPU speed or not at
709 all.
711 Judicious use of @code{sched_yield} function invocations by processes
712 with First Come First Served scheduling policy forms a good compromise
713 between Round Robin and First Come First Served.
715 To understand how scheduling works when processes of different scheduling
716 policies occupy the same absolute priority, you have to know the nitty
717 gritty details of how processes enter and exit the ready to run list:
719 In both cases, the ready to run list is organized as a true queue, where
720 a process gets pushed onto the tail when it becomes ready to run and is
721 popped off the head when the scheduler decides to run it.  Note that
722 ready to run and running are two mutually exclusive states.  When the
723 scheduler runs a process, that process is no longer ready to run and no
724 longer in the ready to run list.  When the process stops running, it
725 may go back to being ready to run again.
727 The only difference between a process that is assigned the Round Robin
728 scheduling policy and a process that is assigned First Come First Serve
729 is that in the former case, the process is automatically booted off the
730 CPU after a certain amount of time.  When that happens, the process goes
731 back to being ready to run, which means it enters the queue at the tail.
732 The time quantum we're talking about is small.  Really small.  This is
733 not your father's timesharing.  For example, with the Linux kernel, the
734 round robin time slice is a thousand times shorter than its typical
735 time slice for traditional scheduling.
737 A process begins life with the same scheduling policy as its parent process.
738 Functions described in @ref{Basic Scheduling Functions} can change it.
740 Only a privileged process can set the scheduling policy of a process
741 that has absolute priority higher than 0.
743 @node Basic Scheduling Functions
744 @subsection Basic Scheduling Functions
746 This section describes functions in @theglibc{} for setting the
747 absolute priority and scheduling policy of a process.
749 @strong{Portability Note:}  On systems that have the functions in this
750 section, the macro _POSIX_PRIORITY_SCHEDULING is defined in
751 @file{<unistd.h>}.
753 For the case that the scheduling policy is traditional scheduling, more
754 functions to fine tune the scheduling are in @ref{Traditional Scheduling}.
756 Don't try to make too much out of the naming and structure of these
757 functions.  They don't match the concepts described in this manual
758 because the functions are as defined by POSIX.1b, but the implementation
759 on systems that use @theglibc{} is the inverse of what the POSIX
760 structure contemplates.  The POSIX scheme assumes that the primary
761 scheduling parameter is the scheduling policy and that the priority
762 value, if any, is a parameter of the scheduling policy.  In the
763 implementation, though, the priority value is king and the scheduling
764 policy, if anything, only fine tunes the effect of that priority.
766 The symbols in this section are declared by including file @file{sched.h}.
768 @comment sched.h
769 @comment POSIX
770 @deftp {Data Type} {struct sched_param}
771 This structure describes an absolute priority.
772 @table @code
773 @item int sched_priority
774 absolute priority value
775 @end table
776 @end deftp
778 @comment sched.h
779 @comment POSIX
780 @deftypefun int sched_setscheduler (pid_t @var{pid}, int @var{policy}, const struct sched_param *@var{param})
782 This function sets both the absolute priority and the scheduling policy
783 for a process.
785 It assigns the absolute priority value given by @var{param} and the
786 scheduling policy @var{policy} to the process with Process ID @var{pid},
787 or the calling process if @var{pid} is zero.  If @var{policy} is
788 negative, @code{sched_setscheduler} keeps the existing scheduling policy.
790 The following macros represent the valid values for @var{policy}:
792 @table @code
793 @item SCHED_OTHER
794 Traditional Scheduling
795 @item SCHED_FIFO
796 First In First Out
797 @item SCHED_RR
798 Round Robin
799 @end table
801 @c The Linux kernel code (in sched.c) actually reschedules the process,
802 @c but it puts it at the head of the run queue, so I'm not sure just what
803 @c the effect is, but it must be subtle.
805 On success, the return value is @code{0}.  Otherwise, it is @code{-1}
806 and @code{ERRNO} is set accordingly.  The @code{errno} values specific
807 to this function are:
809 @table @code
810 @item EPERM
811 @itemize @bullet
812 @item
813 The calling process does not have @code{CAP_SYS_NICE} permission and
814 @var{policy} is not @code{SCHED_OTHER} (or it's negative and the
815 existing policy is not @code{SCHED_OTHER}.
817 @item
818 The calling process does not have @code{CAP_SYS_NICE} permission and its
819 owner is not the target process' owner.  I.e., the effective uid of the
820 calling process is neither the effective nor the real uid of process
821 @var{pid}.
822 @c We need a cross reference to the capabilities section, when written.
823 @end itemize
825 @item ESRCH
826 There is no process with pid @var{pid} and @var{pid} is not zero.
828 @item EINVAL
829 @itemize @bullet
830 @item
831 @var{policy} does not identify an existing scheduling policy.
833 @item
834 The absolute priority value identified by *@var{param} is outside the
835 valid range for the scheduling policy @var{policy} (or the existing
836 scheduling policy if @var{policy} is negative) or @var{param} is
837 null.  @code{sched_get_priority_max} and @code{sched_get_priority_min}
838 tell you what the valid range is.
840 @item
841 @var{pid} is negative.
842 @end itemize
843 @end table
845 @end deftypefun
848 @comment sched.h
849 @comment POSIX
850 @deftypefun int sched_getscheduler (pid_t @var{pid})
852 This function returns the scheduling policy assigned to the process with
853 Process ID (pid) @var{pid}, or the calling process if @var{pid} is zero.
855 The return value is the scheduling policy.  See
856 @code{sched_setscheduler} for the possible values.
858 If the function fails, the return value is instead @code{-1} and
859 @code{errno} is set accordingly.
861 The @code{errno} values specific to this function are:
863 @table @code
865 @item ESRCH
866 There is no process with pid @var{pid} and it is not zero.
868 @item EINVAL
869 @var{pid} is negative.
871 @end table
873 Note that this function is not an exact mate to @code{sched_setscheduler}
874 because while that function sets the scheduling policy and the absolute
875 priority, this function gets only the scheduling policy.  To get the
876 absolute priority, use @code{sched_getparam}.
878 @end deftypefun
881 @comment sched.h
882 @comment POSIX
883 @deftypefun int sched_setparam (pid_t @var{pid}, const struct sched_param *@var{param})
885 This function sets a process' absolute priority.
887 It is functionally identical to @code{sched_setscheduler} with
888 @var{policy} = @code{-1}.
890 @c in fact, that's how it's implemented in Linux.
892 @end deftypefun
894 @comment sched.h
895 @comment POSIX
896 @deftypefun int sched_getparam (pid_t @var{pid}, const struct sched_param *@var{param})
898 This function returns a process' absolute priority.
900 @var{pid} is the Process ID (pid) of the process whose absolute priority
901 you want to know.
903 @var{param} is a pointer to a structure in which the function stores the
904 absolute priority of the process.
906 On success, the return value is @code{0}.  Otherwise, it is @code{-1}
907 and @code{ERRNO} is set accordingly.  The @code{errno} values specific
908 to this function are:
910 @table @code
912 @item ESRCH
913 There is no process with pid @var{pid} and it is not zero.
915 @item EINVAL
916 @var{pid} is negative.
918 @end table
920 @end deftypefun
923 @comment sched.h
924 @comment POSIX
925 @deftypefun int sched_get_priority_min (int *@var{policy})
927 This function returns the lowest absolute priority value that is
928 allowable for a process with scheduling policy @var{policy}.
930 On Linux, it is 0 for SCHED_OTHER and 1 for everything else.
932 On success, the return value is @code{0}.  Otherwise, it is @code{-1}
933 and @code{ERRNO} is set accordingly.  The @code{errno} values specific
934 to this function are:
936 @table @code
937 @item EINVAL
938 @var{policy} does not identify an existing scheduling policy.
939 @end table
941 @end deftypefun
943 @comment sched.h
944 @comment POSIX
945 @deftypefun int sched_get_priority_max (int *@var{policy})
947 This function returns the highest absolute priority value that is
948 allowable for a process that with scheduling policy @var{policy}.
950 On Linux, it is 0 for SCHED_OTHER and 99 for everything else.
952 On success, the return value is @code{0}.  Otherwise, it is @code{-1}
953 and @code{ERRNO} is set accordingly.  The @code{errno} values specific
954 to this function are:
956 @table @code
957 @item EINVAL
958 @var{policy} does not identify an existing scheduling policy.
959 @end table
961 @end deftypefun
963 @comment sched.h
964 @comment POSIX
965 @deftypefun int sched_rr_get_interval (pid_t @var{pid}, struct timespec *@var{interval})
967 This function returns the length of the quantum (time slice) used with
968 the Round Robin scheduling policy, if it is used, for the process with
969 Process ID @var{pid}.
971 It returns the length of time as @var{interval}.
972 @c We need a cross-reference to where timespec is explained.  But that
973 @c section doesn't exist yet, and the time chapter needs to be slightly
974 @c reorganized so there is a place to put it (which will be right next
975 @c to timeval, which is presently misplaced).  2000.05.07.
977 With a Linux kernel, the round robin time slice is always 150
978 microseconds, and @var{pid} need not even be a real pid.
980 The return value is @code{0} on success and in the pathological case
981 that it fails, the return value is @code{-1} and @code{errno} is set
982 accordingly.  There is nothing specific that can go wrong with this
983 function, so there are no specific @code{errno} values.
985 @end deftypefun
987 @comment sched.h
988 @comment POSIX
989 @deftypefun int sched_yield (void)
991 This function voluntarily gives up the process' claim on the CPU.
993 Technically, @code{sched_yield} causes the calling process to be made
994 immediately ready to run (as opposed to running, which is what it was
995 before).  This means that if it has absolute priority higher than 0, it
996 gets pushed onto the tail of the queue of processes that share its
997 absolute priority and are ready to run, and it will run again when its
998 turn next arrives.  If its absolute priority is 0, it is more
999 complicated, but still has the effect of yielding the CPU to other
1000 processes.
1002 If there are no other processes that share the calling process' absolute
1003 priority, this function doesn't have any effect.
1005 To the extent that the containing program is oblivious to what other
1006 processes in the system are doing and how fast it executes, this
1007 function appears as a no-op.
1009 The return value is @code{0} on success and in the pathological case
1010 that it fails, the return value is @code{-1} and @code{errno} is set
1011 accordingly.  There is nothing specific that can go wrong with this
1012 function, so there are no specific @code{errno} values.
1014 @end deftypefun
1016 @node Traditional Scheduling
1017 @subsection Traditional Scheduling
1018 @cindex scheduling, traditional
1020 This section is about the scheduling among processes whose absolute
1021 priority is 0.  When the system hands out the scraps of CPU time that
1022 are left over after the processes with higher absolute priority have
1023 taken all they want, the scheduling described herein determines who
1024 among the great unwashed processes gets them.
1026 @menu
1027 * Traditional Scheduling Intro::
1028 * Traditional Scheduling Functions::
1029 @end menu
1031 @node Traditional Scheduling Intro
1032 @subsubsection Introduction To Traditional Scheduling
1034 Long before there was absolute priority (See @ref{Absolute Priority}),
1035 Unix systems were scheduling the CPU using this system.  When Posix came
1036 in like the Romans and imposed absolute priorities to accommodate the
1037 needs of realtime processing, it left the indigenous Absolute Priority
1038 Zero processes to govern themselves by their own familiar scheduling
1039 policy.
1041 Indeed, absolute priorities higher than zero are not available on many
1042 systems today and are not typically used when they are, being intended
1043 mainly for computers that do realtime processing.  So this section
1044 describes the only scheduling many programmers need to be concerned
1045 about.
1047 But just to be clear about the scope of this scheduling: Any time a
1048 process with a absolute priority of 0 and a process with an absolute
1049 priority higher than 0 are ready to run at the same time, the one with
1050 absolute priority 0 does not run.  If it's already running when the
1051 higher priority ready-to-run process comes into existence, it stops
1052 immediately.
1054 In addition to its absolute priority of zero, every process has another
1055 priority, which we will refer to as "dynamic priority" because it changes
1056 over time.  The dynamic priority is meaningless for processes with
1057 an absolute priority higher than zero.
1059 The dynamic priority sometimes determines who gets the next turn on the
1060 CPU.  Sometimes it determines how long turns last.  Sometimes it
1061 determines whether a process can kick another off the CPU.
1063 In Linux, the value is a combination of these things, but mostly it is
1064 just determines the length of the time slice.  The higher a process'
1065 dynamic priority, the longer a shot it gets on the CPU when it gets one.
1066 If it doesn't use up its time slice before giving up the CPU to do
1067 something like wait for I/O, it is favored for getting the CPU back when
1068 it's ready for it, to finish out its time slice.  Other than that,
1069 selection of processes for new time slices is basically round robin.
1070 But the scheduler does throw a bone to the low priority processes: A
1071 process' dynamic priority rises every time it is snubbed in the
1072 scheduling process.  In Linux, even the fat kid gets to play.
1074 The fluctuation of a process' dynamic priority is regulated by another
1075 value: The ``nice'' value.  The nice value is an integer, usually in the
1076 range -20 to 20, and represents an upper limit on a process' dynamic
1077 priority.  The higher the nice number, the lower that limit.
1079 On a typical Linux system, for example, a process with a nice value of
1080 20 can get only 10 milliseconds on the CPU at a time, whereas a process
1081 with a nice value of -20 can achieve a high enough priority to get 400
1082 milliseconds.
1084 The idea of the nice value is deferential courtesy.  In the beginning,
1085 in the Unix garden of Eden, all processes shared equally in the bounty
1086 of the computer system.  But not all processes really need the same
1087 share of CPU time, so the nice value gave a courteous process the
1088 ability to refuse its equal share of CPU time that others might prosper.
1089 Hence, the higher a process' nice value, the nicer the process is.
1090 (Then a snake came along and offered some process a negative nice value
1091 and the system became the crass resource allocation system we know
1092 today).
1094 Dynamic priorities tend upward and downward with an objective of
1095 smoothing out allocation of CPU time and giving quick response time to
1096 infrequent requests.  But they never exceed their nice limits, so on a
1097 heavily loaded CPU, the nice value effectively determines how fast a
1098 process runs.
1100 In keeping with the socialistic heritage of Unix process priority, a
1101 process begins life with the same nice value as its parent process and
1102 can raise it at will.  A process can also raise the nice value of any
1103 other process owned by the same user (or effective user).  But only a
1104 privileged process can lower its nice value.  A privileged process can
1105 also raise or lower another process' nice value.
1107 @glibcadj{} functions for getting and setting nice values are described in
1108 @xref{Traditional Scheduling Functions}.
1110 @node Traditional Scheduling Functions
1111 @subsubsection Functions For Traditional Scheduling
1113 @pindex sys/resource.h
1114 This section describes how you can read and set the nice value of a
1115 process.  All these symbols are declared in @file{sys/resource.h}.
1117 The function and macro names are defined by POSIX, and refer to
1118 "priority," but the functions actually have to do with nice values, as
1119 the terms are used both in the manual and POSIX.
1121 The range of valid nice values depends on the kernel, but typically it
1122 runs from @code{-20} to @code{20}.  A lower nice value corresponds to
1123 higher priority for the process.  These constants describe the range of
1124 priority values:
1126 @vtable @code
1127 @comment sys/resource.h
1128 @comment BSD
1129 @item PRIO_MIN
1130 The lowest valid nice value.
1132 @comment sys/resource.h
1133 @comment BSD
1134 @item PRIO_MAX
1135 The highest valid nice value.
1136 @end vtable
1138 @comment sys/resource.h
1139 @comment BSD,POSIX
1140 @deftypefun int getpriority (int @var{class}, int @var{id})
1141 Return the nice value of a set of processes; @var{class} and @var{id}
1142 specify which ones (see below).  If the processes specified do not all
1143 have the same nice value, this returns the lowest value that any of them
1144 has.
1146 On success, the return value is @code{0}.  Otherwise, it is @code{-1}
1147 and @code{ERRNO} is set accordingly.  The @code{errno} values specific
1148 to this function are:
1150 @table @code
1151 @item ESRCH
1152 The combination of @var{class} and @var{id} does not match any existing
1153 process.
1155 @item EINVAL
1156 The value of @var{class} is not valid.
1157 @end table
1159 If the return value is @code{-1}, it could indicate failure, or it could
1160 be the nice value.  The only way to make certain is to set @code{errno =
1161 0} before calling @code{getpriority}, then use @code{errno != 0}
1162 afterward as the criterion for failure.
1163 @end deftypefun
1165 @comment sys/resource.h
1166 @comment BSD,POSIX
1167 @deftypefun int setpriority (int @var{class}, int @var{id}, int @var{niceval})
1168 Set the nice value of a set of processes to @var{niceval}; @var{class}
1169 and @var{id} specify which ones (see below).
1171 The return value is @code{0} on success, and @code{-1} on
1172 failure.  The following @code{errno} error condition are possible for
1173 this function:
1175 @table @code
1176 @item ESRCH
1177 The combination of @var{class} and @var{id} does not match any existing
1178 process.
1180 @item EINVAL
1181 The value of @var{class} is not valid.
1183 @item EPERM
1184 The call would set the nice value of a process which is owned by a different
1185 user than the calling process (i.e., the target process' real or effective
1186 uid does not match the calling process' effective uid) and the calling
1187 process does not have @code{CAP_SYS_NICE} permission.
1189 @item EACCES
1190 The call would lower the process' nice value and the process does not have
1191 @code{CAP_SYS_NICE} permission.
1192 @end table
1194 @end deftypefun
1196 The arguments @var{class} and @var{id} together specify a set of
1197 processes in which you are interested.  These are the possible values of
1198 @var{class}:
1200 @vtable @code
1201 @comment sys/resource.h
1202 @comment BSD
1203 @item PRIO_PROCESS
1204 One particular process.  The argument @var{id} is a process ID (pid).
1206 @comment sys/resource.h
1207 @comment BSD
1208 @item PRIO_PGRP
1209 All the processes in a particular process group.  The argument @var{id} is
1210 a process group ID (pgid).
1212 @comment sys/resource.h
1213 @comment BSD
1214 @item PRIO_USER
1215 All the processes owned by a particular user (i.e., whose real uid
1216 indicates the user).  The argument @var{id} is a user ID (uid).
1217 @end vtable
1219 If the argument @var{id} is 0, it stands for the calling process, its
1220 process group, or its owner (real uid), according to @var{class}.
1222 @comment unistd.h
1223 @comment BSD
1224 @deftypefun int nice (int @var{increment})
1225 Increment the nice value of the calling process by @var{increment}.
1226 The return value is the new nice value on success, and @code{-1} on
1227 failure.  In the case of failure, @code{errno} will be set to the
1228 same values as for @code{setpriority}.
1231 Here is an equivalent definition of @code{nice}:
1233 @smallexample
1235 nice (int increment)
1237   int result, old = getpriority (PRIO_PROCESS, 0);
1238   result = setpriority (PRIO_PROCESS, 0, old + increment);
1239   if (result != -1)
1240       return old + increment;
1241   else
1242       return -1;
1244 @end smallexample
1245 @end deftypefun
1248 @node CPU Affinity
1249 @subsection Limiting execution to certain CPUs
1251 On a multi-processor system the operating system usually distributes
1252 the different processes which are runnable on all available CPUs in a
1253 way which allows the system to work most efficiently.  Which processes
1254 and threads run can be to some extend be control with the scheduling
1255 functionality described in the last sections.  But which CPU finally
1256 executes which process or thread is not covered.
1258 There are a number of reasons why a program might want to have control
1259 over this aspect of the system as well:
1261 @itemize @bullet
1262 @item
1263 One thread or process is responsible for absolutely critical work
1264 which under no circumstances must be interrupted or hindered from
1265 making process by other process or threads using CPU resources.  In
1266 this case the special process would be confined to a CPU which no
1267 other process or thread is allowed to use.
1269 @item
1270 The access to certain resources (RAM, I/O ports) has different costs
1271 from different CPUs.  This is the case in NUMA (Non-Uniform Memory
1272 Architecture) machines.  Preferably memory should be accessed locally
1273 but this requirement is usually not visible to the scheduler.
1274 Therefore forcing a process or thread to the CPUs which have local
1275 access to the mostly used memory helps to significantly boost the
1276 performance.
1278 @item
1279 In controlled runtimes resource allocation and book-keeping work (for
1280 instance garbage collection) is performance local to processors.  This
1281 can help to reduce locking costs if the resources do not have to be
1282 protected from concurrent accesses from different processors.
1283 @end itemize
1285 The POSIX standard up to this date is of not much help to solve this
1286 problem.  The Linux kernel provides a set of interfaces to allow
1287 specifying @emph{affinity sets} for a process.  The scheduler will
1288 schedule the thread or process on CPUs specified by the affinity
1289 masks.  The interfaces which @theglibc{} define follow to some
1290 extend the Linux kernel interface.
1292 @comment sched.h
1293 @comment GNU
1294 @deftp {Data Type} cpu_set_t
1295 This data set is a bitset where each bit represents a CPU.  How the
1296 system's CPUs are mapped to bits in the bitset is system dependent.
1297 The data type has a fixed size; in the unlikely case that the number
1298 of bits are not sufficient to describe the CPUs of the system a
1299 different interface has to be used.
1301 This type is a GNU extension and is defined in @file{sched.h}.
1302 @end deftp
1304 To manipulate the bitset, to set and reset bits, a number of macros is
1305 defined.  Some of the macros take a CPU number as a parameter.  Here
1306 it is important to never exceed the size of the bitset.  The following
1307 macro specifies the number of bits in the @code{cpu_set_t} bitset.
1309 @comment sched.h
1310 @comment GNU
1311 @deftypevr Macro int CPU_SETSIZE
1312 The value of this macro is the maximum number of CPUs which can be
1313 handled with a @code{cpu_set_t} object.
1314 @end deftypevr
1316 The type @code{cpu_set_t} should be considered opaque; all
1317 manipulation should happen via the next four macros.
1319 @comment sched.h
1320 @comment GNU
1321 @deftypefn Macro void CPU_ZERO (cpu_set_t *@var{set})
1322 This macro initializes the CPU set @var{set} to be the empty set.
1324 This macro is a GNU extension and is defined in @file{sched.h}.
1325 @end deftypefn
1327 @comment sched.h
1328 @comment GNU
1329 @deftypefn Macro void CPU_SET (int @var{cpu}, cpu_set_t *@var{set})
1330 This macro adds @var{cpu} to the CPU set @var{set}.
1332 The @var{cpu} parameter must not have side effects since it is
1333 evaluated more than once.
1335 This macro is a GNU extension and is defined in @file{sched.h}.
1336 @end deftypefn
1338 @comment sched.h
1339 @comment GNU
1340 @deftypefn Macro void CPU_CLR (int @var{cpu}, cpu_set_t *@var{set})
1341 This macro removes @var{cpu} from the CPU set @var{set}.
1343 The @var{cpu} parameter must not have side effects since it is
1344 evaluated more than once.
1346 This macro is a GNU extension and is defined in @file{sched.h}.
1347 @end deftypefn
1349 @comment sched.h
1350 @comment GNU
1351 @deftypefn Macro int CPU_ISSET (int @var{cpu}, const cpu_set_t *@var{set})
1352 This macro returns a nonzero value (true) if @var{cpu} is a member
1353 of the CPU set @var{set}, and zero (false) otherwise.
1355 The @var{cpu} parameter must not have side effects since it is
1356 evaluated more than once.
1358 This macro is a GNU extension and is defined in @file{sched.h}.
1359 @end deftypefn
1362 CPU bitsets can be constructed from scratch or the currently installed
1363 affinity mask can be retrieved from the system.
1365 @comment sched.h
1366 @comment GNU
1367 @deftypefun int sched_getaffinity (pid_t @var{pid}, size_t @var{cpusetsize}, cpu_set_t *@var{cpuset})
1369 This functions stores the CPU affinity mask for the process or thread
1370 with the ID @var{pid} in the @var{cpusetsize} bytes long bitmap
1371 pointed to by @var{cpuset}.  If successful, the function always
1372 initializes all bits in the @code{cpu_set_t} object and returns zero.
1374 If @var{pid} does not correspond to a process or thread on the system
1375 the or the function fails for some other reason, it returns @code{-1}
1376 and @code{errno} is set to represent the error condition.
1378 @table @code
1379 @item ESRCH
1380 No process or thread with the given ID found.
1382 @item EFAULT
1383 The pointer @var{cpuset} is does not point to a valid object.
1384 @end table
1386 This function is a GNU extension and is declared in @file{sched.h}.
1387 @end deftypefun
1389 Note that it is not portably possible to use this information to
1390 retrieve the information for different POSIX threads.  A separate
1391 interface must be provided for that.
1393 @comment sched.h
1394 @comment GNU
1395 @deftypefun int sched_setaffinity (pid_t @var{pid}, size_t @var{cpusetsize}, const cpu_set_t *@var{cpuset})
1397 This function installs the @var{cpusetsize} bytes long affinity mask
1398 pointed to by @var{cpuset} for the process or thread with the ID @var{pid}.
1399 If successful the function returns zero and the scheduler will in future
1400 take the affinity information into account.
1402 If the function fails it will return @code{-1} and @code{errno} is set
1403 to the error code:
1405 @table @code
1406 @item ESRCH
1407 No process or thread with the given ID found.
1409 @item EFAULT
1410 The pointer @var{cpuset} is does not point to a valid object.
1412 @item EINVAL
1413 The bitset is not valid.  This might mean that the affinity set might
1414 not leave a processor for the process or thread to run on.
1415 @end table
1417 This function is a GNU extension and is declared in @file{sched.h}.
1418 @end deftypefun
1421 @node Memory Resources
1422 @section Querying memory available resources
1424 The amount of memory available in the system and the way it is organized
1425 determines oftentimes the way programs can and have to work.  For
1426 functions like @code{mmap} it is necessary to know about the size of
1427 individual memory pages and knowing how much memory is available enables
1428 a program to select appropriate sizes for, say, caches.  Before we get
1429 into these details a few words about memory subsystems in traditional
1430 Unix systems will be given.
1432 @menu
1433 * Memory Subsystem::           Overview about traditional Unix memory handling.
1434 * Query Memory Parameters::    How to get information about the memory
1435                                 subsystem?
1436 @end menu
1438 @node Memory Subsystem
1439 @subsection Overview about traditional Unix memory handling
1441 @cindex address space
1442 @cindex physical memory
1443 @cindex physical address
1444 Unix systems normally provide processes virtual address spaces.  This
1445 means that the addresses of the memory regions do not have to correspond
1446 directly to the addresses of the actual physical memory which stores the
1447 data.  An extra level of indirection is introduced which translates
1448 virtual addresses into physical addresses.  This is normally done by the
1449 hardware of the processor.
1451 @cindex shared memory
1452 Using a virtual address space has several advantage.  The most important
1453 is process isolation.  The different processes running on the system
1454 cannot interfere directly with each other.  No process can write into
1455 the address space of another process (except when shared memory is used
1456 but then it is wanted and controlled).
1458 Another advantage of virtual memory is that the address space the
1459 processes see can actually be larger than the physical memory available.
1460 The physical memory can be extended by storage on an external media
1461 where the content of currently unused memory regions is stored.  The
1462 address translation can then intercept accesses to these memory regions
1463 and make memory content available again by loading the data back into
1464 memory.  This concept makes it necessary that programs which have to use
1465 lots of memory know the difference between available virtual address
1466 space and available physical memory.  If the working set of virtual
1467 memory of all the processes is larger than the available physical memory
1468 the system will slow down dramatically due to constant swapping of
1469 memory content from the memory to the storage media and back.  This is
1470 called ``thrashing''.
1471 @cindex thrashing
1473 @cindex memory page
1474 @cindex page, memory
1475 A final aspect of virtual memory which is important and follows from
1476 what is said in the last paragraph is the granularity of the virtual
1477 address space handling.  When we said that the virtual address handling
1478 stores memory content externally it cannot do this on a byte-by-byte
1479 basis.  The administrative overhead does not allow this (leaving alone
1480 the processor hardware).  Instead several thousand bytes are handled
1481 together and form a @dfn{page}.  The size of each page is always a power
1482 of two byte.  The smallest page size in use today is 4096, with 8192,
1483 16384, and 65536 being other popular sizes.
1485 @node Query Memory Parameters
1486 @subsection How to get information about the memory subsystem?
1488 The page size of the virtual memory the process sees is essential to
1489 know in several situations.  Some programming interface (e.g.,
1490 @code{mmap}, @pxref{Memory-mapped I/O}) require the user to provide
1491 information adjusted to the page size.  In the case of @code{mmap} is it
1492 necessary to provide a length argument which is a multiple of the page
1493 size.  Another place where the knowledge about the page size is useful
1494 is in memory allocation.  If one allocates pieces of memory in larger
1495 chunks which are then subdivided by the application code it is useful to
1496 adjust the size of the larger blocks to the page size.  If the total
1497 memory requirement for the block is close (but not larger) to a multiple
1498 of the page size the kernel's memory handling can work more effectively
1499 since it only has to allocate memory pages which are fully used.  (To do
1500 this optimization it is necessary to know a bit about the memory
1501 allocator which will require a bit of memory itself for each block and
1502 this overhead must not push the total size over the page size multiple.
1504 The page size traditionally was a compile time constant.  But recent
1505 development of processors changed this.  Processors now support
1506 different page sizes and they can possibly even vary among different
1507 processes on the same system.  Therefore the system should be queried at
1508 runtime about the current page size and no assumptions (except about it
1509 being a power of two) should be made.
1511 @vindex _SC_PAGESIZE
1512 The correct interface to query about the page size is @code{sysconf}
1513 (@pxref{Sysconf Definition}) with the parameter @code{_SC_PAGESIZE}.
1514 There is a much older interface available, too.
1516 @comment unistd.h
1517 @comment BSD
1518 @deftypefun int getpagesize (void)
1519 The @code{getpagesize} function returns the page size of the process.
1520 This value is fixed for the runtime of the process but can vary in
1521 different runs of the application.
1523 The function is declared in @file{unistd.h}.
1524 @end deftypefun
1526 Widely available on @w{System V} derived systems is a method to get
1527 information about the physical memory the system has.  The call
1529 @vindex _SC_PHYS_PAGES
1530 @cindex sysconf
1531 @smallexample
1532   sysconf (_SC_PHYS_PAGES)
1533 @end smallexample
1535 @noindent
1536 returns the total number of pages of physical the system has.
1537 This does not mean all this memory is available.  This information can
1538 be found using
1540 @vindex _SC_AVPHYS_PAGES
1541 @cindex sysconf
1542 @smallexample
1543   sysconf (_SC_AVPHYS_PAGES)
1544 @end smallexample
1546 These two values help to optimize applications.  The value returned for
1547 @code{_SC_AVPHYS_PAGES} is the amount of memory the application can use
1548 without hindering any other process (given that no other process
1549 increases its memory usage).  The value returned for
1550 @code{_SC_PHYS_PAGES} is more or less a hard limit for the working set.
1551 If all applications together constantly use more than that amount of
1552 memory the system is in trouble.
1554 @Theglibc{} provides in addition to these already described way to
1555 get this information two functions.  They are declared in the file
1556 @file{sys/sysinfo.h}.  Programmers should prefer to use the
1557 @code{sysconf} method described above.
1559 @comment sys/sysinfo.h
1560 @comment GNU
1561 @deftypefun {long int} get_phys_pages (void)
1562 The @code{get_phys_pages} function returns the total number of pages of
1563 physical the system has.  To get the amount of memory this number has to
1564 be multiplied by the page size.
1566 This function is a GNU extension.
1567 @end deftypefun
1569 @comment sys/sysinfo.h
1570 @comment GNU
1571 @deftypefun {long int} get_avphys_pages (void)
1572 The @code{get_phys_pages} function returns the number of available pages of
1573 physical the system has.  To get the amount of memory this number has to
1574 be multiplied by the page size.
1576 This function is a GNU extension.
1577 @end deftypefun
1579 @node Processor Resources
1580 @section Learn about the processors available
1582 The use of threads or processes with shared memory allows an application
1583 to take advantage of all the processing power a system can provide.  If
1584 the task can be parallelized the optimal way to write an application is
1585 to have at any time as many processes running as there are processors.
1586 To determine the number of processors available to the system one can
1589 @vindex _SC_NPROCESSORS_CONF
1590 @cindex sysconf
1591 @smallexample
1592   sysconf (_SC_NPROCESSORS_CONF)
1593 @end smallexample
1595 @noindent
1596 which returns the number of processors the operating system configured.
1597 But it might be possible for the operating system to disable individual
1598 processors and so the call
1600 @vindex _SC_NPROCESSORS_ONLN
1601 @cindex sysconf
1602 @smallexample
1603   sysconf (_SC_NPROCESSORS_ONLN)
1604 @end smallexample
1606 @noindent
1607 returns the number of processors which are currently online (i.e.,
1608 available).
1610 For these two pieces of information @theglibc{} also provides
1611 functions to get the information directly.  The functions are declared
1612 in @file{sys/sysinfo.h}.
1614 @comment sys/sysinfo.h
1615 @comment GNU
1616 @deftypefun int get_nprocs_conf (void)
1617 The @code{get_nprocs_conf} function returns the number of processors the
1618 operating system configured.
1620 This function is a GNU extension.
1621 @end deftypefun
1623 @comment sys/sysinfo.h
1624 @comment GNU
1625 @deftypefun int get_nprocs (void)
1626 The @code{get_nprocs} function returns the number of available processors.
1628 This function is a GNU extension.
1629 @end deftypefun
1631 @cindex load average
1632 Before starting more threads it should be checked whether the processors
1633 are not already overused.  Unix systems calculate something called the
1634 @dfn{load average}.  This is a number indicating how many processes were
1635 running.  This number is average over different periods of times
1636 (normally 1, 5, and 15 minutes).
1638 @comment stdlib.h
1639 @comment BSD
1640 @deftypefun int getloadavg (double @var{loadavg}[], int @var{nelem})
1641 This function gets the 1, 5 and 15 minute load averages of the
1642 system. The values are placed in @var{loadavg}.  @code{getloadavg} will
1643 place at most @var{nelem} elements into the array but never more than
1644 three elements.  The return value is the number of elements written to
1645 @var{loadavg}, or -1 on error.
1647 This function is declared in @file{stdlib.h}.
1648 @end deftypefun