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.
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.
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 @deftypefun int getrusage (int @var{processes}, struct rusage *@var{rusage})
26 @standards{BSD, sys/resource.h}
27 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
28 @c On HURD, this calls task_info 3 times. On UNIX, it's a syscall.
29 This function reports resource usage totals for processes specified by
30 @var{processes}, storing the information in @code{*@var{rusage}}.
32 In most systems, @var{processes} has only two valid values:
36 @standards{BSD, sys/resource.h}
37 Just the current process.
40 @standards{BSD, sys/resource.h}
41 All child processes (direct and indirect) that have already terminated.
44 The return value of @code{getrusage} is zero for success, and @code{-1}
49 The argument @var{processes} is not valid.
53 One way of getting resource usage for a particular child process is with
54 the function @code{wait4}, which returns totals for a child when it
55 terminates. @xref{BSD Wait Functions}.
57 @deftp {Data Type} {struct rusage}
58 @standards{BSD, sys/resource.h}
59 This data type stores various resource usage statistics. It has the
60 following members, and possibly others:
63 @item struct timeval ru_utime
64 Time spent executing user instructions.
66 @item struct timeval ru_stime
67 Time spent in operating system code on behalf of @var{processes}.
69 @item long int ru_maxrss
70 The maximum resident set size used, in kilobytes. That is, the maximum
71 number of kilobytes of physical memory that @var{processes} used
74 @item long int ru_ixrss
75 An integral value expressed in kilobytes times ticks of execution, which
76 indicates the amount of memory used by text that was shared with other
79 @item long int ru_idrss
80 An integral value expressed the same way, which is the amount of
81 unshared memory used for data.
83 @item long int ru_isrss
84 An integral value expressed the same way, which is the amount of
85 unshared memory used for stack space.
87 @item long int ru_minflt
88 The number of page faults which were serviced without requiring any I/O.
90 @item long int ru_majflt
91 The number of page faults which were serviced by doing I/O.
93 @item long int ru_nswap
94 The number of times @var{processes} was swapped entirely out of main memory.
96 @item long int ru_inblock
97 The number of times the file system had to read from the disk on behalf
100 @item long int ru_oublock
101 The number of times the file system had to write to the disk on behalf
104 @item long int ru_msgsnd
105 Number of IPC messages sent.
107 @item long int ru_msgrcv
108 Number of IPC messages received.
110 @item long int ru_nsignals
111 Number of signals received.
113 @item long int ru_nvcsw
114 The number of times @var{processes} voluntarily invoked a context switch
115 (usually to wait for some service).
117 @item long int ru_nivcsw
118 The number of times an involuntary context switch took place (because
119 a time slice expired, or another process of higher priority was
124 @code{vtimes} is a historical function that does some of what
125 @code{getrusage} does. @code{getrusage} is a better choice.
127 @code{vtimes} and its @code{vtimes} data structure are declared in
131 @deftypefun int vtimes (struct vtimes *@var{current}, struct vtimes *@var{child})
132 @standards{???, sys/vtimes.h}
133 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
134 @c Calls getrusage twice.
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
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
151 User CPU time. Analogous to @code{ru_utime} in @code{struct rusage}
153 System CPU time. Analogous to @code{ru_stime} in @code{struct rusage}
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}
158 Shared memory. Analogous to @code{ru_ixrss} in @code{struct rusage}
160 Maximent resident set size. Analogous to @code{ru_maxrss} in
163 Major page faults. Analogous to @code{ru_majflt} in @code{struct rusage}
165 Minor page faults. Analogous to @code{ru_minflt} in @code{struct rusage}
167 Swap count. Analogous to @code{ru_nswap} in @code{struct rusage}
169 Disk reads. Analogous to @code{ru_inblk} in @code{struct rusage}
171 Disk writes. Analogous to @code{ru_oublk} in @code{struct rusage}
176 The return value is zero if the function succeeds; @code{-1} otherwise.
181 An additional historical function for examining resource usage,
182 @code{vtimes}, is supported but not documented here. It is declared in
185 @node Limits on Resources
186 @section Limiting Resource Usage
187 @cindex resource limits
188 @cindex limits on resource usage
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:
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
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
214 @cindex maximum limit
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 @deftypefun int getrlimit (int @var{resource}, struct rlimit *@var{rlp})
224 @standards{BSD, sys/resource.h}
225 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
226 @c Direct syscall on most systems.
227 Read the current and maximum limits for the resource @var{resource}
228 and store them in @code{*@var{rlp}}.
230 The return value is @code{0} on success and @code{-1} on failure. The
231 only possible @code{errno} error condition is @code{EFAULT}.
233 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
234 32-bit system this function is in fact @code{getrlimit64}. Thus, the
235 LFS interface transparently replaces the old interface.
238 @deftypefun int getrlimit64 (int @var{resource}, struct rlimit64 *@var{rlp})
239 @standards{Unix98, sys/resource.h}
240 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
241 @c Direct syscall on most systems, wrapper to getrlimit otherwise.
242 This function is similar to @code{getrlimit} but its second parameter is
243 a pointer to a variable of type @code{struct rlimit64}, which allows it
244 to read values which wouldn't fit in the member of a @code{struct
247 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
248 32-bit machine, this function is available under the name
249 @code{getrlimit} and so transparently replaces the old interface.
252 @deftypefun int setrlimit (int @var{resource}, const struct rlimit *@var{rlp})
253 @standards{BSD, sys/resource.h}
254 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
255 @c Direct syscall on most systems; lock-taking critical section on HURD.
256 Store the current and maximum limits for the resource @var{resource}
257 in @code{*@var{rlp}}.
259 The return value is @code{0} on success and @code{-1} on failure. The
260 following @code{errno} error condition is possible:
266 The process tried to raise a current limit beyond the maximum limit.
269 The process tried to raise a maximum limit, but is not superuser.
273 When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
274 32-bit system this function is in fact @code{setrlimit64}. Thus, the
275 LFS interface transparently replaces the old interface.
278 @deftypefun int setrlimit64 (int @var{resource}, const struct rlimit64 *@var{rlp})
279 @standards{Unix98, sys/resource.h}
280 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
281 @c Wrapper for setrlimit or direct syscall.
282 This function is similar to @code{setrlimit} but its second parameter is
283 a pointer to a variable of type @code{struct rlimit64} which allows it
284 to set values which wouldn't fit in the member of a @code{struct
287 If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
288 32-bit machine this function is available under the name
289 @code{setrlimit} and so transparently replaces the old interface.
292 @deftp {Data Type} {struct rlimit}
293 @standards{BSD, sys/resource.h}
294 This structure is used with @code{getrlimit} to receive limit values,
295 and with @code{setrlimit} to specify limit values for a particular process
296 and resource. It has two fields:
299 @item rlim_t rlim_cur
302 @item rlim_t rlim_max
306 For @code{getrlimit}, the structure is an output; it receives the current
307 values. For @code{setrlimit}, it specifies the new values.
310 For the LFS functions a similar type is defined in @file{sys/resource.h}.
312 @deftp {Data Type} {struct rlimit64}
313 @standards{Unix98, sys/resource.h}
314 This structure is analogous to the @code{rlimit} structure above, but
315 its components have wider ranges. It has two fields:
318 @item rlim64_t rlim_cur
319 This is analogous to @code{rlimit.rlim_cur}, but with a different type.
321 @item rlim64_t rlim_max
322 This is analogous to @code{rlimit.rlim_max}, but with a different type.
327 Here is a list of resources for which you can specify a limit. Memory
328 and file sizes are measured in bytes.
332 @standards{BSD, sys/resource.h}
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}.
338 @standards{BSD, sys/resource.h}
339 The maximum size of file the process can create. Trying to write a
340 larger file causes a signal: @code{SIGXFSZ}. @xref{Operation Error
344 @standards{BSD, sys/resource.h}
345 The maximum size of data memory for the process. If the process tries
346 to allocate data memory beyond this amount, the allocation function
350 @standards{BSD, sys/resource.h}
351 The maximum stack size for the process. If the process tries to extend
352 its stack past this size, it gets a @code{SIGSEGV} signal.
353 @xref{Program Error Signals}.
356 @standards{BSD, sys/resource.h}
357 The maximum size core file that this process can create. If the process
358 terminates and would dump a core file larger than this, then no core
359 file is created. So setting this limit to zero prevents core files from
363 @standards{BSD, sys/resource.h}
364 The maximum amount of physical memory that this process should get.
365 This parameter is a guide for the system's scheduler and memory
366 allocator; the system may give the process more memory when there is a
370 @standards{BSD, sys/resource.h}
371 The maximum amount of memory that can be locked into physical memory (so
372 it will never be paged out).
375 @standards{BSD, sys/resource.h}
376 The maximum number of processes that can be created with the same user ID.
377 If you have reached the limit for your user ID, @code{fork} will fail
378 with @code{EAGAIN}. @xref{Creating a Process}.
382 @standardsx{RLIMIT_NOFILE, BSD, sys/resource.h}
383 The maximum number of files that the process can open. If it tries to
384 open more files than this, its open attempt fails with @code{errno}
385 @code{EMFILE}. @xref{Error Codes}. Not all systems support this limit;
386 GNU does, and 4.4 BSD does.
389 @standards{Unix98, sys/resource.h}
390 The maximum size of total memory that this process should get. If the
391 process tries to allocate more memory beyond this amount with, for
392 example, @code{brk}, @code{malloc}, @code{mmap} or @code{sbrk}, the
393 allocation function fails.
396 @standards{BSD, sys/resource.h}
397 The number of different resource limits. Any valid @var{resource}
398 operand must be less than @code{RLIM_NLIMITS}.
401 @deftypevr Constant rlim_t RLIM_INFINITY
402 @standards{BSD, sys/resource.h}
403 This constant stands for a value of ``infinity'' when supplied as
404 the limit value in @code{setrlimit}.
408 The following are historical functions to do some of what the functions
409 above do. The functions above are better choices.
411 @code{ulimit} and the command symbols are declared in @file{ulimit.h}.
414 @deftypefun {long int} ulimit (int @var{cmd}, @dots{})
415 @standards{BSD, ulimit.h}
416 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
417 @c Wrapper for getrlimit, setrlimit or
418 @c sysconf(_SC_OPEN_MAX)->getdtablesize->getrlimit.
420 @code{ulimit} gets the current limit or sets the current and maximum
421 limit for a particular resource for the calling process according to the
424 If you are getting a limit, the command argument is the only argument.
425 If you are setting a limit, there is a second argument:
426 @code{long int} @var{limit} which is the value to which you are setting
429 The @var{cmd} values and the operations they specify are:
433 Get the current limit on the size of a file, in units of 512 bytes.
436 Set the current and maximum limit on the size of a file to @var{limit} *
441 There are also some other @var{cmd} values that may do things on some
442 systems, but they are not supported.
444 Only the superuser may increase a maximum limit.
446 When you successfully get a limit, the return value of @code{ulimit} is
447 that limit, which is never negative. When you successfully set a limit,
448 the return value is zero. When the function fails, the return value is
449 @code{-1} and @code{errno} is set according to the reason:
453 A process tried to increase a maximum limit, but is not superuser.
459 @code{vlimit} and its resource symbols are declared in @file{sys/vlimit.h}.
462 @deftypefun int vlimit (int @var{resource}, int @var{limit})
463 @standards{BSD, sys/vlimit.h}
464 @safety{@prelim{}@mtunsafe{@mtasurace{:setrlimit}}@asunsafe{}@acsafe{}}
465 @c It calls getrlimit and modifies the rlim_cur field before calling
466 @c setrlimit. There's a window for a concurrent call to setrlimit that
467 @c modifies e.g. rlim_max, which will be lost if running as super-user.
469 @code{vlimit} sets the current limit for a resource for a process.
471 @var{resource} identifies the resource:
475 Maximum CPU time. Same as @code{RLIMIT_CPU} for @code{setrlimit}.
477 Maximum file size. Same as @code{RLIMIT_FSIZE} for @code{setrlimit}.
479 Maximum data memory. Same as @code{RLIMIT_DATA} for @code{setrlimit}.
481 Maximum stack size. Same as @code{RLIMIT_STACK} for @code{setrlimit}.
483 Maximum core file size. Same as @code{RLIMIT_COR} for @code{setrlimit}.
485 Maximum physical memory. Same as @code{RLIMIT_RSS} for @code{setrlimit}.
488 The return value is zero for success, and @code{-1} with @code{errno} set
489 accordingly for failure:
493 The process tried to set its current limit beyond its maximum limit.
499 @section Process CPU Priority And Scheduling
500 @cindex process priority
502 @cindex priority of a process
504 When multiple processes simultaneously require CPU time, the system's
505 scheduling policy and process CPU priorities determine which processes
506 get it. This section describes how that determination is made and
507 @glibcadj{} functions to control it.
509 It is common to refer to CPU scheduling simply as scheduling and a
510 process' CPU priority simply as the process' priority, with the CPU
511 resource being implied. Bear in mind, though, that CPU time is not the
512 only resource a process uses or that processes contend for. In some
513 cases, it is not even particularly important. Giving a process a high
514 ``priority'' may have very little effect on how fast a process runs with
515 respect to other processes. The priorities discussed in this section
516 apply only to CPU time.
518 CPU scheduling is a complex issue and different systems do it in wildly
519 different ways. New ideas continually develop and find their way into
520 the intricacies of the various systems' scheduling algorithms. This
521 section discusses the general concepts, some specifics of systems
522 that commonly use @theglibc{}, and some standards.
524 For simplicity, we talk about CPU contention as if there is only one CPU
525 in the system. But all the same principles apply when a processor has
526 multiple CPUs, and knowing that the number of processes that can run at
527 any one time is equal to the number of CPUs, you can easily extrapolate
530 The functions described in this section are all defined by the POSIX.1
531 and POSIX.1b standards (the @code{sched@dots{}} functions are POSIX.1b).
532 However, POSIX does not define any semantics for the values that these
533 functions get and set. In this chapter, the semantics are based on the
534 Linux kernel's implementation of the POSIX standard. As you will see,
535 the Linux implementation is quite the inverse of what the authors of the
536 POSIX syntax had in mind.
539 * Absolute Priority:: The first tier of priority. Posix
540 * Realtime Scheduling:: Scheduling among the process nobility
541 * Basic Scheduling Functions:: Get/set scheduling policy, priority
542 * Traditional Scheduling:: Scheduling among the vulgar masses
543 * CPU Affinity:: Limiting execution to certain CPUs
548 @node Absolute Priority
549 @subsection Absolute Priority
550 @cindex absolute priority
551 @cindex priority, absolute
553 Every process has an absolute priority, and it is represented by a number.
554 The higher the number, the higher the absolute priority.
556 @cindex realtime CPU scheduling
557 On systems of the past, and most systems today, all processes have
558 absolute priority 0 and this section is irrelevant. In that case,
559 @xref{Traditional Scheduling}. Absolute priorities were invented to
560 accommodate realtime systems, in which it is vital that certain processes
561 be able to respond to external events happening in real time, which
562 means they cannot wait around while some other process that @emph{wants
563 to}, but doesn't @emph{need to} run occupies the CPU.
566 @cindex preemptive scheduling
567 When two processes are in contention to use the CPU at any instant, the
568 one with the higher absolute priority always gets it. This is true even if the
569 process with the lower priority is already using the CPU (i.e., the
570 scheduling is preemptive). Of course, we're only talking about
571 processes that are running or ``ready to run,'' which means they are
572 ready to execute instructions right now. When a process blocks to wait
573 for something like I/O, its absolute priority is irrelevant.
575 @cindex runnable process
576 @strong{NB:} The term ``runnable'' is a synonym for ``ready to run.''
578 When two processes are running or ready to run and both have the same
579 absolute priority, it's more interesting. In that case, who gets the
580 CPU is determined by the scheduling policy. If the processes have
581 absolute priority 0, the traditional scheduling policy described in
582 @ref{Traditional Scheduling} applies. Otherwise, the policies described
583 in @ref{Realtime Scheduling} apply.
585 You normally give an absolute priority above 0 only to a process that
586 can be trusted not to hog the CPU. Such processes are designed to block
587 (or terminate) after relatively short CPU runs.
589 A process begins life with the same absolute priority as its parent
590 process. Functions described in @ref{Basic Scheduling Functions} can
593 Only a privileged process can change a process' absolute priority to
594 something other than @code{0}. Only a privileged process or the
595 target process' owner can change its absolute priority at all.
597 POSIX requires absolute priority values used with the realtime
598 scheduling policies to be consecutive with a range of at least 32. On
599 Linux, they are 1 through 99. The functions
600 @code{sched_get_priority_max} and @code{sched_set_priority_min} portably
601 tell you what the range is on a particular system.
604 @subsubsection Using Absolute Priority
606 One thing you must keep in mind when designing real time applications is
607 that having higher absolute priority than any other process doesn't
608 guarantee the process can run continuously. Two things that can wreck a
609 good CPU run are interrupts and page faults.
611 Interrupt handlers live in that limbo between processes. The CPU is
612 executing instructions, but they aren't part of any process. An
613 interrupt will stop even the highest priority process. So you must
614 allow for slight delays and make sure that no device in the system has
615 an interrupt handler that could cause too long a delay between
616 instructions for your process.
618 Similarly, a page fault causes what looks like a straightforward
619 sequence of instructions to take a long time. The fact that other
620 processes get to run while the page faults in is of no consequence,
621 because as soon as the I/O is complete, the higher priority process will
622 kick them out and run again, but the wait for the I/O itself could be a
623 problem. To neutralize this threat, use @code{mlock} or
626 There are a few ramifications of the absoluteness of this priority on a
627 single-CPU system that you need to keep in mind when you choose to set a
628 priority and also when you're working on a program that runs with high
629 absolute priority. Consider a process that has higher absolute priority
630 than any other process in the system and due to a bug in its program, it
631 gets into an infinite loop. It will never cede the CPU. You can't run
632 a command to kill it because your command would need to get the CPU in
633 order to run. The errant program is in complete control. It controls
634 the vertical, it controls the horizontal.
636 There are two ways to avoid this: 1) keep a shell running somewhere with
637 a higher absolute priority or 2) keep a controlling terminal attached to
638 the high priority process group. All the priority in the world won't
639 stop an interrupt handler from running and delivering a signal to the
640 process if you hit Control-C.
642 Some systems use absolute priority as a means of allocating a fixed
643 percentage of CPU time to a process. To do this, a super high priority
644 privileged process constantly monitors the process' CPU usage and raises
645 its absolute priority when the process isn't getting its entitled share
646 and lowers it when the process is exceeding it.
648 @strong{NB:} The absolute priority is sometimes called the ``static
649 priority.'' We don't use that term in this manual because it misses the
650 most important feature of the absolute priority: its absoluteness.
653 @node Realtime Scheduling
654 @subsection Realtime Scheduling
655 @cindex realtime scheduling
657 Whenever two processes with the same absolute priority are ready to run,
658 the kernel has a decision to make, because only one can run at a time.
659 If the processes have absolute priority 0, the kernel makes this decision
660 as described in @ref{Traditional Scheduling}. Otherwise, the decision
661 is as described in this section.
663 If two processes are ready to run but have different absolute priorities,
664 the decision is much simpler, and is described in @ref{Absolute
667 Each process has a scheduling policy. For processes with absolute
668 priority other than zero, there are two available:
672 First Come First Served
677 The most sensible case is where all the processes with a certain
678 absolute priority have the same scheduling policy. We'll discuss that
681 In Round Robin, processes share the CPU, each one running for a small
682 quantum of time (``time slice'') and then yielding to another in a
683 circular fashion. Of course, only processes that are ready to run and
684 have the same absolute priority are in this circle.
686 In First Come First Served, the process that has been waiting the
687 longest to run gets the CPU, and it keeps it until it voluntarily
688 relinquishes the CPU, runs out of things to do (blocks), or gets
689 preempted by a higher priority process.
691 First Come First Served, along with maximal absolute priority and
692 careful control of interrupts and page faults, is the one to use when a
693 process absolutely, positively has to run at full CPU speed or not at
696 Judicious use of @code{sched_yield} function invocations by processes
697 with First Come First Served scheduling policy forms a good compromise
698 between Round Robin and First Come First Served.
700 To understand how scheduling works when processes of different scheduling
701 policies occupy the same absolute priority, you have to know the nitty
702 gritty details of how processes enter and exit the ready to run list.
704 In both cases, the ready to run list is organized as a true queue, where
705 a process gets pushed onto the tail when it becomes ready to run and is
706 popped off the head when the scheduler decides to run it. Note that
707 ready to run and running are two mutually exclusive states. When the
708 scheduler runs a process, that process is no longer ready to run and no
709 longer in the ready to run list. When the process stops running, it
710 may go back to being ready to run again.
712 The only difference between a process that is assigned the Round Robin
713 scheduling policy and a process that is assigned First Come First Serve
714 is that in the former case, the process is automatically booted off the
715 CPU after a certain amount of time. When that happens, the process goes
716 back to being ready to run, which means it enters the queue at the tail.
717 The time quantum we're talking about is small. Really small. This is
718 not your father's timesharing. For example, with the Linux kernel, the
719 round robin time slice is a thousand times shorter than its typical
720 time slice for traditional scheduling.
722 A process begins life with the same scheduling policy as its parent process.
723 Functions described in @ref{Basic Scheduling Functions} can change it.
725 Only a privileged process can set the scheduling policy of a process
726 that has absolute priority higher than 0.
728 @node Basic Scheduling Functions
729 @subsection Basic Scheduling Functions
731 This section describes functions in @theglibc{} for setting the
732 absolute priority and scheduling policy of a process.
734 @strong{Portability Note:} On systems that have the functions in this
735 section, the macro _POSIX_PRIORITY_SCHEDULING is defined in
738 For the case that the scheduling policy is traditional scheduling, more
739 functions to fine tune the scheduling are in @ref{Traditional Scheduling}.
741 Don't try to make too much out of the naming and structure of these
742 functions. They don't match the concepts described in this manual
743 because the functions are as defined by POSIX.1b, but the implementation
744 on systems that use @theglibc{} is the inverse of what the POSIX
745 structure contemplates. The POSIX scheme assumes that the primary
746 scheduling parameter is the scheduling policy and that the priority
747 value, if any, is a parameter of the scheduling policy. In the
748 implementation, though, the priority value is king and the scheduling
749 policy, if anything, only fine tunes the effect of that priority.
751 The symbols in this section are declared by including file @file{sched.h}.
753 @strong{Portability Note:} In POSIX, the @code{pid_t} arguments of the
754 functions below refer to process IDs. On Linux, they are actually
755 thread IDs, and control how specific threads are scheduled with
756 regards to the entire system. The resulting behavior does not conform
757 to POSIX. This is why the following description refers to tasks and
758 tasks IDs, and not processes and process IDs.
759 @c https://sourceware.org/bugzilla/show_bug.cgi?id=14829
761 @deftp {Data Type} {struct sched_param}
762 @standards{POSIX, sched.h}
763 This structure describes an absolute priority.
765 @item int sched_priority
766 absolute priority value
770 @deftypefun int sched_setscheduler (pid_t @var{pid}, int @var{policy}, const struct sched_param *@var{param})
771 @standards{POSIX, sched.h}
772 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
773 @c Direct syscall, Linux only.
775 This function sets both the absolute priority and the scheduling policy
778 It assigns the absolute priority value given by @var{param} and the
779 scheduling policy @var{policy} to the task with ID @var{pid},
780 or the calling task if @var{pid} is zero. If @var{policy} is
781 negative, @code{sched_setscheduler} keeps the existing scheduling policy.
783 The following macros represent the valid values for @var{policy}:
787 Traditional Scheduling
794 @c The Linux kernel code (in sched.c) actually reschedules the process,
795 @c but it puts it at the head of the run queue, so I'm not sure just what
796 @c the effect is, but it must be subtle.
798 On success, the return value is @code{0}. Otherwise, it is @code{-1}
799 and @code{ERRNO} is set accordingly. The @code{errno} values specific
800 to this function are:
806 The calling task does not have @code{CAP_SYS_NICE} permission and
807 @var{policy} is not @code{SCHED_OTHER} (or it's negative and the
808 existing policy is not @code{SCHED_OTHER}.
811 The calling task does not have @code{CAP_SYS_NICE} permission and its
812 owner is not the target task's owner. I.e., the effective uid of the
813 calling task is neither the effective nor the real uid of task
815 @c We need a cross reference to the capabilities section, when written.
819 There is no task with pid @var{pid} and @var{pid} is not zero.
824 @var{policy} does not identify an existing scheduling policy.
827 The absolute priority value identified by *@var{param} is outside the
828 valid range for the scheduling policy @var{policy} (or the existing
829 scheduling policy if @var{policy} is negative) or @var{param} is
830 null. @code{sched_get_priority_max} and @code{sched_get_priority_min}
831 tell you what the valid range is.
834 @var{pid} is negative.
841 @deftypefun int sched_getscheduler (pid_t @var{pid})
842 @standards{POSIX, sched.h}
843 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
844 @c Direct syscall, Linux only.
846 This function returns the scheduling policy assigned to the task with
847 ID @var{pid}, or the calling task if @var{pid} is zero.
849 The return value is the scheduling policy. See
850 @code{sched_setscheduler} for the possible values.
852 If the function fails, the return value is instead @code{-1} and
853 @code{errno} is set accordingly.
855 The @code{errno} values specific to this function are:
860 There is no task with pid @var{pid} and it is not zero.
863 @var{pid} is negative.
867 Note that this function is not an exact mate to @code{sched_setscheduler}
868 because while that function sets the scheduling policy and the absolute
869 priority, this function gets only the scheduling policy. To get the
870 absolute priority, use @code{sched_getparam}.
875 @deftypefun int sched_setparam (pid_t @var{pid}, const struct sched_param *@var{param})
876 @standards{POSIX, sched.h}
877 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
878 @c Direct syscall, Linux only.
880 This function sets a task's absolute priority.
882 It is functionally identical to @code{sched_setscheduler} with
883 @var{policy} = @code{-1}.
885 @c in fact, that's how it's implemented in Linux.
889 @deftypefun int sched_getparam (pid_t @var{pid}, struct sched_param *@var{param})
890 @standards{POSIX, sched.h}
891 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
892 @c Direct syscall, Linux only.
894 This function returns a task's absolute priority.
896 @var{pid} is the task ID of the task whose absolute priority you want
899 @var{param} is a pointer to a structure in which the function stores the
900 absolute priority of the task.
902 On success, the return value is @code{0}. Otherwise, it is @code{-1}
903 and @code{errno} is set accordingly. The @code{errno} values specific
904 to this function are:
909 There is no task with ID @var{pid} and it is not zero.
912 @var{pid} is negative.
919 @deftypefun int sched_get_priority_min (int @var{policy})
920 @standards{POSIX, sched.h}
921 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
922 @c Direct syscall, Linux only.
924 This function returns the lowest absolute priority value that is
925 allowable for a task with scheduling policy @var{policy}.
927 On Linux, it is 0 for SCHED_OTHER and 1 for everything else.
929 On success, the return value is @code{0}. Otherwise, it is @code{-1}
930 and @code{ERRNO} is set accordingly. The @code{errno} values specific
931 to this function are:
935 @var{policy} does not identify an existing scheduling policy.
940 @deftypefun int sched_get_priority_max (int @var{policy})
941 @standards{POSIX, sched.h}
942 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
943 @c Direct syscall, Linux only.
945 This function returns the highest absolute priority value that is
946 allowable for a task that with scheduling policy @var{policy}.
948 On Linux, it is 0 for SCHED_OTHER and 99 for everything else.
950 On success, the return value is @code{0}. Otherwise, it is @code{-1}
951 and @code{ERRNO} is set accordingly. The @code{errno} values specific
952 to this function are:
956 @var{policy} does not identify an existing scheduling policy.
961 @deftypefun int sched_rr_get_interval (pid_t @var{pid}, struct timespec *@var{interval})
962 @standards{POSIX, sched.h}
963 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
964 @c Direct syscall, Linux only.
966 This function returns the length of the quantum (time slice) used with
967 the Round Robin scheduling policy, if it is used, for the task with
970 It returns the length of time as @var{interval}.
971 @c We need a cross-reference to where timespec is explained. But that
972 @c section doesn't exist yet, and the time chapter needs to be slightly
973 @c reorganized so there is a place to put it (which will be right next
974 @c to timeval, which is presently misplaced). 2000.05.07.
976 With a Linux kernel, the round robin time slice is always 150
977 microseconds, and @var{pid} need not even be a real pid.
979 The return value is @code{0} on success and in the pathological case
980 that it fails, the return value is @code{-1} and @code{errno} is set
981 accordingly. There is nothing specific that can go wrong with this
982 function, so there are no specific @code{errno} values.
986 @deftypefun int sched_yield (void)
987 @standards{POSIX, sched.h}
988 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
989 @c Direct syscall on Linux; alias to swtch on HURD.
991 This function voluntarily gives up the task's claim on the CPU.
993 Technically, @code{sched_yield} causes the calling task 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 tasks 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
1002 If there are no other tasks that share the calling task's 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.
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.
1027 * Traditional Scheduling Intro::
1028 * Traditional Scheduling Functions::
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
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
1047 But just to be clear about the scope of this scheduling: Any time a
1048 process with an 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
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
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
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
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
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
1128 @standards{BSD, sys/resource.h}
1129 The lowest valid nice value.
1132 @standards{BSD, sys/resource.h}
1133 The highest valid nice value.
1136 @deftypefun int getpriority (int @var{class}, int @var{id})
1137 @standards{BSD, sys/resource.h}
1138 @standards{POSIX, sys/resource.h}
1139 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1140 @c Direct syscall on UNIX. On HURD, calls _hurd_priority_which_map.
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
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:
1152 The combination of @var{class} and @var{id} does not match any existing
1156 The value of @var{class} is not valid.
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.
1165 @deftypefun int setpriority (int @var{class}, int @var{id}, int @var{niceval})
1166 @standards{BSD, sys/resource.h}
1167 @standards{POSIX, sys/resource.h}
1168 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1169 @c Direct syscall on UNIX. On HURD, calls _hurd_priority_which_map.
1170 Set the nice value of a set of processes to @var{niceval}; @var{class}
1171 and @var{id} specify which ones (see below).
1173 The return value is @code{0} on success, and @code{-1} on
1174 failure. The following @code{errno} error condition are possible for
1179 The combination of @var{class} and @var{id} does not match any existing
1183 The value of @var{class} is not valid.
1186 The call would set the nice value of a process which is owned by a different
1187 user than the calling process (i.e., the target process' real or effective
1188 uid does not match the calling process' effective uid) and the calling
1189 process does not have @code{CAP_SYS_NICE} permission.
1192 The call would lower the process' nice value and the process does not have
1193 @code{CAP_SYS_NICE} permission.
1198 The arguments @var{class} and @var{id} together specify a set of
1199 processes in which you are interested. These are the possible values of
1204 @standards{BSD, sys/resource.h}
1205 One particular process. The argument @var{id} is a process ID (pid).
1208 @standards{BSD, sys/resource.h}
1209 All the processes in a particular process group. The argument @var{id} is
1210 a process group ID (pgid).
1213 @standards{BSD, sys/resource.h}
1214 All the processes owned by a particular user (i.e., whose real uid
1215 indicates the user). The argument @var{id} is a user ID (uid).
1218 If the argument @var{id} is 0, it stands for the calling process, its
1219 process group, or its owner (real uid), according to @var{class}.
1221 @deftypefun int nice (int @var{increment})
1222 @standards{BSD, unistd.h}
1223 @safety{@prelim{}@mtunsafe{@mtasurace{:setpriority}}@asunsafe{}@acsafe{}}
1224 @c Calls getpriority before and after setpriority, using the result of
1225 @c the first call to compute the argument for setpriority. This creates
1226 @c a window for a concurrent setpriority (or nice) call to be lost or
1227 @c exhibit surprising behavior.
1228 Increment the nice value of the calling process by @var{increment}.
1229 The return value is the new nice value on success, and @code{-1} on
1230 failure. In the case of failure, @code{errno} will be set to the
1231 same values as for @code{setpriority}.
1234 Here is an equivalent definition of @code{nice}:
1238 nice (int increment)
1240 int result, old = getpriority (PRIO_PROCESS, 0);
1241 result = setpriority (PRIO_PROCESS, 0, old + increment);
1243 return old + increment;
1252 @subsection Limiting execution to certain CPUs
1254 On a multi-processor system the operating system usually distributes
1255 the different processes which are runnable on all available CPUs in a
1256 way which allows the system to work most efficiently. Which processes
1257 and threads run can be to some extend be control with the scheduling
1258 functionality described in the last sections. But which CPU finally
1259 executes which process or thread is not covered.
1261 There are a number of reasons why a program might want to have control
1262 over this aspect of the system as well:
1266 One thread or process is responsible for absolutely critical work
1267 which under no circumstances must be interrupted or hindered from
1268 making progress by other processes or threads using CPU resources. In
1269 this case the special process would be confined to a CPU which no
1270 other process or thread is allowed to use.
1273 The access to certain resources (RAM, I/O ports) has different costs
1274 from different CPUs. This is the case in NUMA (Non-Uniform Memory
1275 Architecture) machines. Preferably memory should be accessed locally
1276 but this requirement is usually not visible to the scheduler.
1277 Therefore forcing a process or thread to the CPUs which have local
1278 access to the most-used memory helps to significantly boost the
1282 In controlled runtimes resource allocation and book-keeping work (for
1283 instance garbage collection) is performance local to processors. This
1284 can help to reduce locking costs if the resources do not have to be
1285 protected from concurrent accesses from different processors.
1288 The POSIX standard up to this date is of not much help to solve this
1289 problem. The Linux kernel provides a set of interfaces to allow
1290 specifying @emph{affinity sets} for a process. The scheduler will
1291 schedule the thread or process on CPUs specified by the affinity
1292 masks. The interfaces which @theglibc{} define follow to some
1293 extent the Linux kernel interface.
1295 @deftp {Data Type} cpu_set_t
1296 @standards{GNU, sched.h}
1297 This data set is a bitset where each bit represents a CPU. How the
1298 system's CPUs are mapped to bits in the bitset is system dependent.
1299 The data type has a fixed size; in the unlikely case that the number
1300 of bits are not sufficient to describe the CPUs of the system a
1301 different interface has to be used.
1303 This type is a GNU extension and is defined in @file{sched.h}.
1306 To manipulate the bitset, to set and reset bits, a number of macros are
1307 defined. Some of the macros take a CPU number as a parameter. Here
1308 it is important to never exceed the size of the bitset. The following
1309 macro specifies the number of bits in the @code{cpu_set_t} bitset.
1311 @deftypevr Macro int CPU_SETSIZE
1312 @standards{GNU, sched.h}
1313 The value of this macro is the maximum number of CPUs which can be
1314 handled with a @code{cpu_set_t} object.
1317 The type @code{cpu_set_t} should be considered opaque; all
1318 manipulation should happen via the next four macros.
1320 @deftypefn Macro void CPU_ZERO (cpu_set_t *@var{set})
1321 @standards{GNU, sched.h}
1322 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1326 This macro initializes the CPU set @var{set} to be the empty set.
1328 This macro is a GNU extension and is defined in @file{sched.h}.
1331 @deftypefn Macro void CPU_SET (int @var{cpu}, cpu_set_t *@var{set})
1332 @standards{GNU, sched.h}
1333 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1338 This macro adds @var{cpu} to the CPU set @var{set}.
1340 The @var{cpu} parameter must not have side effects since it is
1341 evaluated more than once.
1343 This macro is a GNU extension and is defined in @file{sched.h}.
1346 @deftypefn Macro void CPU_CLR (int @var{cpu}, cpu_set_t *@var{set})
1347 @standards{GNU, sched.h}
1348 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1353 This macro removes @var{cpu} from the CPU set @var{set}.
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}.
1361 @deftypefn Macro int CPU_ISSET (int @var{cpu}, const cpu_set_t *@var{set})
1362 @standards{GNU, sched.h}
1363 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1368 This macro returns a nonzero value (true) if @var{cpu} is a member
1369 of the CPU set @var{set}, and zero (false) otherwise.
1371 The @var{cpu} parameter must not have side effects since it is
1372 evaluated more than once.
1374 This macro is a GNU extension and is defined in @file{sched.h}.
1378 CPU bitsets can be constructed from scratch or the currently installed
1379 affinity mask can be retrieved from the system.
1381 @deftypefun int sched_getaffinity (pid_t @var{pid}, size_t @var{cpusetsize}, cpu_set_t *@var{cpuset})
1382 @standards{GNU, sched.h}
1383 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1384 @c Wrapped syscall to zero out past the kernel cpu set size; Linux
1387 This function stores the CPU affinity mask for the process or thread
1388 with the ID @var{pid} in the @var{cpusetsize} bytes long bitmap
1389 pointed to by @var{cpuset}. If successful, the function always
1390 initializes all bits in the @code{cpu_set_t} object and returns zero.
1392 If @var{pid} does not correspond to a process or thread on the system
1393 the or the function fails for some other reason, it returns @code{-1}
1394 and @code{errno} is set to represent the error condition.
1398 No process or thread with the given ID found.
1401 The pointer @var{cpuset} does not point to a valid object.
1404 This function is a GNU extension and is declared in @file{sched.h}.
1407 Note that it is not portably possible to use this information to
1408 retrieve the information for different POSIX threads. A separate
1409 interface must be provided for that.
1411 @deftypefun int sched_setaffinity (pid_t @var{pid}, size_t @var{cpusetsize}, const cpu_set_t *@var{cpuset})
1412 @standards{GNU, sched.h}
1413 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1414 @c Wrapped syscall to detect attempts to set bits past the kernel cpu
1415 @c set size; Linux only.
1417 This function installs the @var{cpusetsize} bytes long affinity mask
1418 pointed to by @var{cpuset} for the process or thread with the ID @var{pid}.
1419 If successful the function returns zero and the scheduler will in the future
1420 take the affinity information into account.
1422 If the function fails it will return @code{-1} and @code{errno} is set
1427 No process or thread with the given ID found.
1430 The pointer @var{cpuset} does not point to a valid object.
1433 The bitset is not valid. This might mean that the affinity set might
1434 not leave a processor for the process or thread to run on.
1437 This function is a GNU extension and is declared in @file{sched.h}.
1440 @deftypefun int getcpu (unsigned int *cpu, unsigned int *node)
1441 @standards{Linux, <sched.h>}
1442 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1443 The @code{getcpu} function identifies the processor and node on which
1444 the calling thread or process is currently running and writes them into
1445 the integers pointed to by the @var{cpu} and @var{node} arguments. The
1446 processor is a unique nonnegative integer identifying a CPU. The node
1447 is a unique nonnegative integer identifying a NUMA node. When either
1448 @var{cpu} or @var{node} is @code{NULL}, nothing is written to the
1451 The return value is @code{0} on success and @code{-1} on failure. The
1452 following @code{errno} error condition is defined for this function:
1456 The operating system does not support this function.
1459 This function is Linux-specific and is declared in @file{sched.h}.
1462 @node Memory Resources
1463 @section Querying memory available resources
1465 The amount of memory available in the system and the way it is organized
1466 determines oftentimes the way programs can and have to work. For
1467 functions like @code{mmap} it is necessary to know about the size of
1468 individual memory pages and knowing how much memory is available enables
1469 a program to select appropriate sizes for, say, caches. Before we get
1470 into these details a few words about memory subsystems in traditional
1471 Unix systems will be given.
1474 * Memory Subsystem:: Overview about traditional Unix memory handling.
1475 * Query Memory Parameters:: How to get information about the memory
1479 @node Memory Subsystem
1480 @subsection Overview about traditional Unix memory handling
1482 @cindex address space
1483 @cindex physical memory
1484 @cindex physical address
1485 Unix systems normally provide processes virtual address spaces. This
1486 means that the addresses of the memory regions do not have to correspond
1487 directly to the addresses of the actual physical memory which stores the
1488 data. An extra level of indirection is introduced which translates
1489 virtual addresses into physical addresses. This is normally done by the
1490 hardware of the processor.
1492 @cindex shared memory
1493 Using a virtual address space has several advantages. The most important
1494 is process isolation. The different processes running on the system
1495 cannot interfere directly with each other. No process can write into
1496 the address space of another process (except when shared memory is used
1497 but then it is wanted and controlled).
1499 Another advantage of virtual memory is that the address space the
1500 processes see can actually be larger than the physical memory available.
1501 The physical memory can be extended by storage on an external media
1502 where the content of currently unused memory regions is stored. The
1503 address translation can then intercept accesses to these memory regions
1504 and make memory content available again by loading the data back into
1505 memory. This concept makes it necessary that programs which have to use
1506 lots of memory know the difference between available virtual address
1507 space and available physical memory. If the working set of virtual
1508 memory of all the processes is larger than the available physical memory
1509 the system will slow down dramatically due to constant swapping of
1510 memory content from the memory to the storage media and back. This is
1511 called ``thrashing''.
1515 @cindex page, memory
1516 A final aspect of virtual memory which is important and follows from
1517 what is said in the last paragraph is the granularity of the virtual
1518 address space handling. When we said that the virtual address handling
1519 stores memory content externally it cannot do this on a byte-by-byte
1520 basis. The administrative overhead does not allow this (leaving alone
1521 the processor hardware). Instead several thousand bytes are handled
1522 together and form a @dfn{page}. The size of each page is always a power
1523 of two bytes. The smallest page size in use today is 4096, with 8192,
1524 16384, and 65536 being other popular sizes.
1526 @node Query Memory Parameters
1527 @subsection How to get information about the memory subsystem?
1529 The page size of the virtual memory the process sees is essential to
1530 know in several situations. Some programming interfaces (e.g.,
1531 @code{mmap}, @pxref{Memory-mapped I/O}) require the user to provide
1532 information adjusted to the page size. In the case of @code{mmap} it is
1533 necessary to provide a length argument which is a multiple of the page
1534 size. Another place where the knowledge about the page size is useful
1535 is in memory allocation. If one allocates pieces of memory in larger
1536 chunks which are then subdivided by the application code it is useful to
1537 adjust the size of the larger blocks to the page size. If the total
1538 memory requirement for the block is close (but not larger) to a multiple
1539 of the page size the kernel's memory handling can work more effectively
1540 since it only has to allocate memory pages which are fully used. (To do
1541 this optimization it is necessary to know a bit about the memory
1542 allocator which will require a bit of memory itself for each block and
1543 this overhead must not push the total size over the page size multiple.)
1545 The page size traditionally was a compile time constant. But recent
1546 development of processors changed this. Processors now support
1547 different page sizes and they can possibly even vary among different
1548 processes on the same system. Therefore the system should be queried at
1549 runtime about the current page size and no assumptions (except about it
1550 being a power of two) should be made.
1552 @vindex _SC_PAGESIZE
1553 The correct interface to query about the page size is @code{sysconf}
1554 (@pxref{Sysconf Definition}) with the parameter @code{_SC_PAGESIZE}.
1555 There is a much older interface available, too.
1557 @deftypefun int getpagesize (void)
1558 @standards{BSD, unistd.h}
1559 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
1560 @c Obtained from the aux vec at program startup time. GNU/Linux/m68k is
1561 @c the exception, with the possibility of a syscall.
1562 The @code{getpagesize} function returns the page size of the process.
1563 This value is fixed for the runtime of the process but can vary in
1564 different runs of the application.
1566 The function is declared in @file{unistd.h}.
1569 Widely available on @w{System V} derived systems is a method to get
1570 information about the physical memory the system has. The call
1572 @vindex _SC_PHYS_PAGES
1575 sysconf (_SC_PHYS_PAGES)
1579 returns the total number of pages of physical memory the system has.
1580 This does not mean all this memory is available. This information can
1583 @vindex _SC_AVPHYS_PAGES
1586 sysconf (_SC_AVPHYS_PAGES)
1589 These two values help to optimize applications. The value returned for
1590 @code{_SC_AVPHYS_PAGES} is the amount of memory the application can use
1591 without hindering any other process (given that no other process
1592 increases its memory usage). The value returned for
1593 @code{_SC_PHYS_PAGES} is more or less a hard limit for the working set.
1594 If all applications together constantly use more than that amount of
1595 memory the system is in trouble.
1597 @Theglibc{} provides in addition to these already described way to
1598 get this information two functions. They are declared in the file
1599 @file{sys/sysinfo.h}. Programmers should prefer to use the
1600 @code{sysconf} method described above.
1602 @deftypefun {long int} get_phys_pages (void)
1603 @standards{GNU, sys/sysinfo.h}
1604 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1605 @c This fopens a /proc file and scans it for the requested information.
1606 The @code{get_phys_pages} function returns the total number of pages of
1607 physical memory the system has. To get the amount of memory this number has to
1608 be multiplied by the page size.
1610 This function is a GNU extension.
1613 @deftypefun {long int} get_avphys_pages (void)
1614 @standards{GNU, sys/sysinfo.h}
1615 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1616 The @code{get_avphys_pages} function returns the number of available pages of
1617 physical memory the system has. To get the amount of memory this number has to
1618 be multiplied by the page size.
1620 This function is a GNU extension.
1623 @node Processor Resources
1624 @section Learn about the processors available
1626 The use of threads or processes with shared memory allows an application
1627 to take advantage of all the processing power a system can provide. If
1628 the task can be parallelized the optimal way to write an application is
1629 to have at any time as many processes running as there are processors.
1630 To determine the number of processors available to the system one can
1633 @vindex _SC_NPROCESSORS_CONF
1636 sysconf (_SC_NPROCESSORS_CONF)
1640 which returns the number of processors the operating system configured.
1641 But it might be possible for the operating system to disable individual
1642 processors and so the call
1644 @vindex _SC_NPROCESSORS_ONLN
1647 sysconf (_SC_NPROCESSORS_ONLN)
1651 returns the number of processors which are currently online (i.e.,
1654 For these two pieces of information @theglibc{} also provides
1655 functions to get the information directly. The functions are declared
1656 in @file{sys/sysinfo.h}.
1658 @deftypefun int get_nprocs_conf (void)
1659 @standards{GNU, sys/sysinfo.h}
1660 @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
1661 @c This function reads from from /sys using dir streams (single user, so
1662 @c no @mtasurace issue), and on some arches, from /proc using streams.
1663 The @code{get_nprocs_conf} function returns the number of processors the
1664 operating system configured.
1666 This function is a GNU extension.
1669 @deftypefun int get_nprocs (void)
1670 @standards{GNU, sys/sysinfo.h}
1671 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
1672 @c This function reads from /proc using file descriptor I/O.
1673 The @code{get_nprocs} function returns the number of available processors.
1675 This function is a GNU extension.
1678 @cindex load average
1679 Before starting more threads it should be checked whether the processors
1680 are not already overused. Unix systems calculate something called the
1681 @dfn{load average}. This is a number indicating how many processes were
1682 running. This number is an average over different periods of time
1683 (normally 1, 5, and 15 minutes).
1685 @deftypefun int getloadavg (double @var{loadavg}[], int @var{nelem})
1686 @standards{BSD, stdlib.h}
1687 @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
1688 @c Calls host_info on HURD; on Linux, opens /proc/loadavg, reads from
1689 @c it, closes it, without cancellation point, and calls strtod_l with
1690 @c the C locale to convert the strings to doubles.
1691 This function gets the 1, 5 and 15 minute load averages of the
1692 system. The values are placed in @var{loadavg}. @code{getloadavg} will
1693 place at most @var{nelem} elements into the array but never more than
1694 three elements. The return value is the number of elements written to
1695 @var{loadavg}, or -1 on error.
1697 This function is declared in @file{stdlib.h}.