resource.texi 64 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690
  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.
  7. @menu
  8. * Resource Usage:: Measuring various resources used.
  9. * Limits on Resources:: Specifying limits on resource usage.
  10. * Priority:: Reading or setting process run priority.
  11. * Memory Resources:: Querying memory available resources.
  12. * Processor Resources:: Learn about the processors available.
  13. @end menu
  14. @node Resource Usage
  15. @section Resource Usage
  16. @pindex sys/resource.h
  17. The function @code{getrusage} and the data type @code{struct rusage}
  18. are used to examine the resource usage of a process. They are declared
  19. in @file{sys/resource.h}.
  20. @deftypefun int getrusage (int @var{processes}, struct rusage *@var{rusage})
  21. @standards{BSD, sys/resource.h}
  22. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  23. @c On HURD, this calls task_info 3 times. On UNIX, it's a syscall.
  24. This function reports resource usage totals for processes specified by
  25. @var{processes}, storing the information in @code{*@var{rusage}}.
  26. In most systems, @var{processes} has only two valid values:
  27. @vtable @code
  28. @item RUSAGE_SELF
  29. @standards{BSD, sys/resource.h}
  30. Just the current process.
  31. @item RUSAGE_CHILDREN
  32. @standards{BSD, sys/resource.h}
  33. All child processes (direct and indirect) that have already terminated.
  34. @end vtable
  35. The return value of @code{getrusage} is zero for success, and @code{-1}
  36. for failure.
  37. @table @code
  38. @item EINVAL
  39. The argument @var{processes} is not valid.
  40. @end table
  41. @end deftypefun
  42. One way of getting resource usage for a particular child process is with
  43. the function @code{wait4}, which returns totals for a child when it
  44. terminates. @xref{BSD Wait Functions}.
  45. @deftp {Data Type} {struct rusage}
  46. @standards{BSD, sys/resource.h}
  47. This data type stores various resource usage statistics. It has the
  48. following members, and possibly others:
  49. @table @code
  50. @item struct timeval ru_utime
  51. Time spent executing user instructions.
  52. @item struct timeval ru_stime
  53. Time spent in operating system code on behalf of @var{processes}.
  54. @item long int ru_maxrss
  55. The maximum resident set size used, in kilobytes. That is, the maximum
  56. number of kilobytes of physical memory that @var{processes} used
  57. simultaneously.
  58. @item long int ru_ixrss
  59. An integral value expressed in kilobytes times ticks of execution, which
  60. indicates the amount of memory used by text that was shared with other
  61. processes.
  62. @item long int ru_idrss
  63. An integral value expressed the same way, which is the amount of
  64. unshared memory used for data.
  65. @item long int ru_isrss
  66. An integral value expressed the same way, which is the amount of
  67. unshared memory used for stack space.
  68. @item long int ru_minflt
  69. The number of page faults which were serviced without requiring any I/O.
  70. @item long int ru_majflt
  71. The number of page faults which were serviced by doing I/O.
  72. @item long int ru_nswap
  73. The number of times @var{processes} was swapped entirely out of main memory.
  74. @item long int ru_inblock
  75. The number of times the file system had to read from the disk on behalf
  76. of @var{processes}.
  77. @item long int ru_oublock
  78. The number of times the file system had to write to the disk on behalf
  79. of @var{processes}.
  80. @item long int ru_msgsnd
  81. Number of IPC messages sent.
  82. @item long int ru_msgrcv
  83. Number of IPC messages received.
  84. @item long int ru_nsignals
  85. Number of signals received.
  86. @item long int ru_nvcsw
  87. The number of times @var{processes} voluntarily invoked a context switch
  88. (usually to wait for some service).
  89. @item long int ru_nivcsw
  90. The number of times an involuntary context switch took place (because
  91. a time slice expired, or another process of higher priority was
  92. scheduled).
  93. @end table
  94. @end deftp
  95. @code{vtimes} is a historical function that does some of what
  96. @code{getrusage} does. @code{getrusage} is a better choice.
  97. @code{vtimes} and its @code{vtimes} data structure are declared in
  98. @file{sys/vtimes.h}.
  99. @pindex sys/vtimes.h
  100. @deftypefun int vtimes (struct vtimes *@var{current}, struct vtimes *@var{child})
  101. @standards{???, sys/vtimes.h}
  102. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  103. @c Calls getrusage twice.
  104. @code{vtimes} reports resource usage totals for a process.
  105. If @var{current} is non-null, @code{vtimes} stores resource usage totals for
  106. the invoking process alone in the structure to which it points. If
  107. @var{child} is non-null, @code{vtimes} stores resource usage totals for all
  108. past children (which have terminated) of the invoking process in the structure
  109. to which it points.
  110. @deftp {Data Type} {struct vtimes}
  111. This data type contains information about the resource usage of a process.
  112. Each member corresponds to a member of the @code{struct rusage} data type
  113. described above.
  114. @table @code
  115. @item vm_utime
  116. User CPU time. Analogous to @code{ru_utime} in @code{struct rusage}
  117. @item vm_stime
  118. System CPU time. Analogous to @code{ru_stime} in @code{struct rusage}
  119. @item vm_idsrss
  120. Data and stack memory. The sum of the values that would be reported as
  121. @code{ru_idrss} and @code{ru_isrss} in @code{struct rusage}
  122. @item vm_ixrss
  123. Shared memory. Analogous to @code{ru_ixrss} in @code{struct rusage}
  124. @item vm_maxrss
  125. Maximent resident set size. Analogous to @code{ru_maxrss} in
  126. @code{struct rusage}
  127. @item vm_majflt
  128. Major page faults. Analogous to @code{ru_majflt} in @code{struct rusage}
  129. @item vm_minflt
  130. Minor page faults. Analogous to @code{ru_minflt} in @code{struct rusage}
  131. @item vm_nswap
  132. Swap count. Analogous to @code{ru_nswap} in @code{struct rusage}
  133. @item vm_inblk
  134. Disk reads. Analogous to @code{ru_inblk} in @code{struct rusage}
  135. @item vm_oublk
  136. Disk writes. Analogous to @code{ru_oublk} in @code{struct rusage}
  137. @end table
  138. @end deftp
  139. The return value is zero if the function succeeds; @code{-1} otherwise.
  140. @end deftypefun
  141. An additional historical function for examining resource usage,
  142. @code{vtimes}, is supported but not documented here. It is declared in
  143. @file{sys/vtimes.h}.
  144. @node Limits on Resources
  145. @section Limiting Resource Usage
  146. @cindex resource limits
  147. @cindex limits on resource usage
  148. @cindex usage limits
  149. You can specify limits for the resource usage of a process. When the
  150. process tries to exceed a limit, it may get a signal, or the system call
  151. by which it tried to do so may fail, depending on the resource. Each
  152. process initially inherits its limit values from its parent, but it can
  153. subsequently change them.
  154. There are two per-process limits associated with a resource:
  155. @cindex limit
  156. @table @dfn
  157. @item current limit
  158. The current limit is the value the system will not allow usage to
  159. exceed. It is also called the ``soft limit'' because the process being
  160. limited can generally raise the current limit at will.
  161. @cindex current limit
  162. @cindex soft limit
  163. @item maximum limit
  164. The maximum limit is the maximum value to which a process is allowed to
  165. set its current limit. It is also called the ``hard limit'' because
  166. there is no way for a process to get around it. A process may lower
  167. its own maximum limit, but only the superuser may increase a maximum
  168. limit.
  169. @cindex maximum limit
  170. @cindex hard limit
  171. @end table
  172. @pindex sys/resource.h
  173. The symbols for use with @code{getrlimit}, @code{setrlimit},
  174. @code{getrlimit64}, and @code{setrlimit64} are defined in
  175. @file{sys/resource.h}.
  176. @deftypefun int getrlimit (int @var{resource}, struct rlimit *@var{rlp})
  177. @standards{BSD, sys/resource.h}
  178. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  179. @c Direct syscall on most systems.
  180. Read the current and maximum limits for the resource @var{resource}
  181. and store them in @code{*@var{rlp}}.
  182. The return value is @code{0} on success and @code{-1} on failure. The
  183. only possible @code{errno} error condition is @code{EFAULT}.
  184. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  185. 32-bit system this function is in fact @code{getrlimit64}. Thus, the
  186. LFS interface transparently replaces the old interface.
  187. @end deftypefun
  188. @deftypefun int getrlimit64 (int @var{resource}, struct rlimit64 *@var{rlp})
  189. @standards{Unix98, sys/resource.h}
  190. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  191. @c Direct syscall on most systems, wrapper to getrlimit otherwise.
  192. This function is similar to @code{getrlimit} but its second parameter is
  193. a pointer to a variable of type @code{struct rlimit64}, which allows it
  194. to read values which wouldn't fit in the member of a @code{struct
  195. rlimit}.
  196. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  197. 32-bit machine, this function is available under the name
  198. @code{getrlimit} and so transparently replaces the old interface.
  199. @end deftypefun
  200. @deftypefun int setrlimit (int @var{resource}, const struct rlimit *@var{rlp})
  201. @standards{BSD, sys/resource.h}
  202. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  203. @c Direct syscall on most systems; lock-taking critical section on HURD.
  204. Store the current and maximum limits for the resource @var{resource}
  205. in @code{*@var{rlp}}.
  206. The return value is @code{0} on success and @code{-1} on failure. The
  207. following @code{errno} error condition is possible:
  208. @table @code
  209. @item EPERM
  210. @itemize @bullet
  211. @item
  212. The process tried to raise a current limit beyond the maximum limit.
  213. @item
  214. The process tried to raise a maximum limit, but is not superuser.
  215. @end itemize
  216. @end table
  217. When the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  218. 32-bit system this function is in fact @code{setrlimit64}. Thus, the
  219. LFS interface transparently replaces the old interface.
  220. @end deftypefun
  221. @deftypefun int setrlimit64 (int @var{resource}, const struct rlimit64 *@var{rlp})
  222. @standards{Unix98, sys/resource.h}
  223. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  224. @c Wrapper for setrlimit or direct syscall.
  225. This function is similar to @code{setrlimit} but its second parameter is
  226. a pointer to a variable of type @code{struct rlimit64} which allows it
  227. to set values which wouldn't fit in the member of a @code{struct
  228. rlimit}.
  229. If the sources are compiled with @code{_FILE_OFFSET_BITS == 64} on a
  230. 32-bit machine this function is available under the name
  231. @code{setrlimit} and so transparently replaces the old interface.
  232. @end deftypefun
  233. @deftp {Data Type} {struct rlimit}
  234. @standards{BSD, sys/resource.h}
  235. This structure is used with @code{getrlimit} to receive limit values,
  236. and with @code{setrlimit} to specify limit values for a particular process
  237. and resource. It has two fields:
  238. @table @code
  239. @item rlim_t rlim_cur
  240. The current limit
  241. @item rlim_t rlim_max
  242. The maximum limit.
  243. @end table
  244. For @code{getrlimit}, the structure is an output; it receives the current
  245. values. For @code{setrlimit}, it specifies the new values.
  246. @end deftp
  247. For the LFS functions a similar type is defined in @file{sys/resource.h}.
  248. @deftp {Data Type} {struct rlimit64}
  249. @standards{Unix98, sys/resource.h}
  250. This structure is analogous to the @code{rlimit} structure above, but
  251. its components have wider ranges. It has two fields:
  252. @table @code
  253. @item rlim64_t rlim_cur
  254. This is analogous to @code{rlimit.rlim_cur}, but with a different type.
  255. @item rlim64_t rlim_max
  256. This is analogous to @code{rlimit.rlim_max}, but with a different type.
  257. @end table
  258. @end deftp
  259. Here is a list of resources for which you can specify a limit. Memory
  260. and file sizes are measured in bytes.
  261. @vtable @code
  262. @item RLIMIT_CPU
  263. @standards{BSD, sys/resource.h}
  264. The maximum amount of CPU time the process can use. If it runs for
  265. longer than this, it gets a signal: @code{SIGXCPU}. The value is
  266. measured in seconds. @xref{Operation Error Signals}.
  267. @item RLIMIT_FSIZE
  268. @standards{BSD, sys/resource.h}
  269. The maximum size of file the process can create. Trying to write a
  270. larger file causes a signal: @code{SIGXFSZ}. @xref{Operation Error
  271. Signals}.
  272. @item RLIMIT_DATA
  273. @standards{BSD, sys/resource.h}
  274. The maximum size of data memory for the process. If the process tries
  275. to allocate data memory beyond this amount, the allocation function
  276. fails.
  277. @item RLIMIT_STACK
  278. @standards{BSD, sys/resource.h}
  279. The maximum stack size for the process. If the process tries to extend
  280. its stack past this size, it gets a @code{SIGSEGV} signal.
  281. @xref{Program Error Signals}.
  282. @item RLIMIT_CORE
  283. @standards{BSD, sys/resource.h}
  284. The maximum size core file that this process can create. If the process
  285. terminates and would dump a core file larger than this, then no core
  286. file is created. So setting this limit to zero prevents core files from
  287. ever being created.
  288. @item RLIMIT_RSS
  289. @standards{BSD, sys/resource.h}
  290. The maximum amount of physical memory that this process should get.
  291. This parameter is a guide for the system's scheduler and memory
  292. allocator; the system may give the process more memory when there is a
  293. surplus.
  294. @item RLIMIT_MEMLOCK
  295. @standards{BSD, sys/resource.h}
  296. The maximum amount of memory that can be locked into physical memory (so
  297. it will never be paged out).
  298. @item RLIMIT_NPROC
  299. @standards{BSD, sys/resource.h}
  300. The maximum number of processes that can be created with the same user ID.
  301. If you have reached the limit for your user ID, @code{fork} will fail
  302. with @code{EAGAIN}. @xref{Creating a Process}.
  303. @item RLIMIT_NOFILE
  304. @itemx RLIMIT_OFILE
  305. @standardsx{RLIMIT_NOFILE, BSD, sys/resource.h}
  306. The maximum number of files that the process can open. If it tries to
  307. open more files than this, its open attempt fails with @code{errno}
  308. @code{EMFILE}. @xref{Error Codes}. Not all systems support this limit;
  309. GNU does, and 4.4 BSD does.
  310. @item RLIMIT_AS
  311. @standards{Unix98, sys/resource.h}
  312. The maximum size of total memory that this process should get. If the
  313. process tries to allocate more memory beyond this amount with, for
  314. example, @code{brk}, @code{malloc}, @code{mmap} or @code{sbrk}, the
  315. allocation function fails.
  316. @item RLIM_NLIMITS
  317. @standards{BSD, sys/resource.h}
  318. The number of different resource limits. Any valid @var{resource}
  319. operand must be less than @code{RLIM_NLIMITS}.
  320. @end vtable
  321. @deftypevr Constant rlim_t RLIM_INFINITY
  322. @standards{BSD, sys/resource.h}
  323. This constant stands for a value of ``infinity'' when supplied as
  324. the limit value in @code{setrlimit}.
  325. @end deftypevr
  326. The following are historical functions to do some of what the functions
  327. above do. The functions above are better choices.
  328. @code{ulimit} and the command symbols are declared in @file{ulimit.h}.
  329. @pindex ulimit.h
  330. @deftypefun {long int} ulimit (int @var{cmd}, @dots{})
  331. @standards{BSD, ulimit.h}
  332. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  333. @c Wrapper for getrlimit, setrlimit or
  334. @c sysconf(_SC_OPEN_MAX)->getdtablesize->getrlimit.
  335. @code{ulimit} gets the current limit or sets the current and maximum
  336. limit for a particular resource for the calling process according to the
  337. command @var{cmd}.
  338. If you are getting a limit, the command argument is the only argument.
  339. If you are setting a limit, there is a second argument:
  340. @code{long int} @var{limit} which is the value to which you are setting
  341. the limit.
  342. The @var{cmd} values and the operations they specify are:
  343. @vtable @code
  344. @item GETFSIZE
  345. Get the current limit on the size of a file, in units of 512 bytes.
  346. @item SETFSIZE
  347. Set the current and maximum limit on the size of a file to @var{limit} *
  348. 512 bytes.
  349. @end vtable
  350. There are also some other @var{cmd} values that may do things on some
  351. systems, but they are not supported.
  352. Only the superuser may increase a maximum limit.
  353. When you successfully get a limit, the return value of @code{ulimit} is
  354. that limit, which is never negative. When you successfully set a limit,
  355. the return value is zero. When the function fails, the return value is
  356. @code{-1} and @code{errno} is set according to the reason:
  357. @table @code
  358. @item EPERM
  359. A process tried to increase a maximum limit, but is not superuser.
  360. @end table
  361. @end deftypefun
  362. @code{vlimit} and its resource symbols are declared in @file{sys/vlimit.h}.
  363. @pindex sys/vlimit.h
  364. @deftypefun int vlimit (int @var{resource}, int @var{limit})
  365. @standards{BSD, sys/vlimit.h}
  366. @safety{@prelim{}@mtunsafe{@mtasurace{:setrlimit}}@asunsafe{}@acsafe{}}
  367. @c It calls getrlimit and modifies the rlim_cur field before calling
  368. @c setrlimit. There's a window for a concurrent call to setrlimit that
  369. @c modifies e.g. rlim_max, which will be lost if running as super-user.
  370. @code{vlimit} sets the current limit for a resource for a process.
  371. @var{resource} identifies the resource:
  372. @vtable @code
  373. @item LIM_CPU
  374. Maximum CPU time. Same as @code{RLIMIT_CPU} for @code{setrlimit}.
  375. @item LIM_FSIZE
  376. Maximum file size. Same as @code{RLIMIT_FSIZE} for @code{setrlimit}.
  377. @item LIM_DATA
  378. Maximum data memory. Same as @code{RLIMIT_DATA} for @code{setrlimit}.
  379. @item LIM_STACK
  380. Maximum stack size. Same as @code{RLIMIT_STACK} for @code{setrlimit}.
  381. @item LIM_CORE
  382. Maximum core file size. Same as @code{RLIMIT_COR} for @code{setrlimit}.
  383. @item LIM_MAXRSS
  384. Maximum physical memory. Same as @code{RLIMIT_RSS} for @code{setrlimit}.
  385. @end vtable
  386. The return value is zero for success, and @code{-1} with @code{errno} set
  387. accordingly for failure:
  388. @table @code
  389. @item EPERM
  390. The process tried to set its current limit beyond its maximum limit.
  391. @end table
  392. @end deftypefun
  393. @node Priority
  394. @section Process CPU Priority And Scheduling
  395. @cindex process priority
  396. @cindex cpu priority
  397. @cindex priority of a process
  398. When multiple processes simultaneously require CPU time, the system's
  399. scheduling policy and process CPU priorities determine which processes
  400. get it. This section describes how that determination is made and
  401. @glibcadj{} functions to control it.
  402. It is common to refer to CPU scheduling simply as scheduling and a
  403. process' CPU priority simply as the process' priority, with the CPU
  404. resource being implied. Bear in mind, though, that CPU time is not the
  405. only resource a process uses or that processes contend for. In some
  406. cases, it is not even particularly important. Giving a process a high
  407. ``priority'' may have very little effect on how fast a process runs with
  408. respect to other processes. The priorities discussed in this section
  409. apply only to CPU time.
  410. CPU scheduling is a complex issue and different systems do it in wildly
  411. different ways. New ideas continually develop and find their way into
  412. the intricacies of the various systems' scheduling algorithms. This
  413. section discusses the general concepts, some specifics of systems
  414. that commonly use @theglibc{}, and some standards.
  415. For simplicity, we talk about CPU contention as if there is only one CPU
  416. in the system. But all the same principles apply when a processor has
  417. multiple CPUs, and knowing that the number of processes that can run at
  418. any one time is equal to the number of CPUs, you can easily extrapolate
  419. the information.
  420. The functions described in this section are all defined by the POSIX.1
  421. and POSIX.1b standards (the @code{sched@dots{}} functions are POSIX.1b).
  422. However, POSIX does not define any semantics for the values that these
  423. functions get and set. In this chapter, the semantics are based on the
  424. Linux kernel's implementation of the POSIX standard. As you will see,
  425. the Linux implementation is quite the inverse of what the authors of the
  426. POSIX syntax had in mind.
  427. @menu
  428. * Absolute Priority:: The first tier of priority. Posix
  429. * Realtime Scheduling:: Scheduling among the process nobility
  430. * Basic Scheduling Functions:: Get/set scheduling policy, priority
  431. * Traditional Scheduling:: Scheduling among the vulgar masses
  432. * CPU Affinity:: Limiting execution to certain CPUs
  433. @end menu
  434. @node Absolute Priority
  435. @subsection Absolute Priority
  436. @cindex absolute priority
  437. @cindex priority, absolute
  438. Every process has an absolute priority, and it is represented by a number.
  439. The higher the number, the higher the absolute priority.
  440. @cindex realtime CPU scheduling
  441. On systems of the past, and most systems today, all processes have
  442. absolute priority 0 and this section is irrelevant. In that case,
  443. @xref{Traditional Scheduling}. Absolute priorities were invented to
  444. accommodate realtime systems, in which it is vital that certain processes
  445. be able to respond to external events happening in real time, which
  446. means they cannot wait around while some other process that @emph{wants
  447. to}, but doesn't @emph{need to} run occupies the CPU.
  448. @cindex ready to run
  449. @cindex preemptive scheduling
  450. When two processes are in contention to use the CPU at any instant, the
  451. one with the higher absolute priority always gets it. This is true even if the
  452. process with the lower priority is already using the CPU (i.e., the
  453. scheduling is preemptive). Of course, we're only talking about
  454. processes that are running or ``ready to run,'' which means they are
  455. ready to execute instructions right now. When a process blocks to wait
  456. for something like I/O, its absolute priority is irrelevant.
  457. @cindex runnable process
  458. @strong{NB:} The term ``runnable'' is a synonym for ``ready to run.''
  459. When two processes are running or ready to run and both have the same
  460. absolute priority, it's more interesting. In that case, who gets the
  461. CPU is determined by the scheduling policy. If the processes have
  462. absolute priority 0, the traditional scheduling policy described in
  463. @ref{Traditional Scheduling} applies. Otherwise, the policies described
  464. in @ref{Realtime Scheduling} apply.
  465. You normally give an absolute priority above 0 only to a process that
  466. can be trusted not to hog the CPU. Such processes are designed to block
  467. (or terminate) after relatively short CPU runs.
  468. A process begins life with the same absolute priority as its parent
  469. process. Functions described in @ref{Basic Scheduling Functions} can
  470. change it.
  471. Only a privileged process can change a process' absolute priority to
  472. something other than @code{0}. Only a privileged process or the
  473. target process' owner can change its absolute priority at all.
  474. POSIX requires absolute priority values used with the realtime
  475. scheduling policies to be consecutive with a range of at least 32. On
  476. Linux, they are 1 through 99. The functions
  477. @code{sched_get_priority_max} and @code{sched_set_priority_min} portably
  478. tell you what the range is on a particular system.
  479. @subsubsection Using Absolute Priority
  480. One thing you must keep in mind when designing real time applications is
  481. that having higher absolute priority than any other process doesn't
  482. guarantee the process can run continuously. Two things that can wreck a
  483. good CPU run are interrupts and page faults.
  484. Interrupt handlers live in that limbo between processes. The CPU is
  485. executing instructions, but they aren't part of any process. An
  486. interrupt will stop even the highest priority process. So you must
  487. allow for slight delays and make sure that no device in the system has
  488. an interrupt handler that could cause too long a delay between
  489. instructions for your process.
  490. Similarly, a page fault causes what looks like a straightforward
  491. sequence of instructions to take a long time. The fact that other
  492. processes get to run while the page faults in is of no consequence,
  493. because as soon as the I/O is complete, the higher priority process will
  494. kick them out and run again, but the wait for the I/O itself could be a
  495. problem. To neutralize this threat, use @code{mlock} or
  496. @code{mlockall}.
  497. There are a few ramifications of the absoluteness of this priority on a
  498. single-CPU system that you need to keep in mind when you choose to set a
  499. priority and also when you're working on a program that runs with high
  500. absolute priority. Consider a process that has higher absolute priority
  501. than any other process in the system and due to a bug in its program, it
  502. gets into an infinite loop. It will never cede the CPU. You can't run
  503. a command to kill it because your command would need to get the CPU in
  504. order to run. The errant program is in complete control. It controls
  505. the vertical, it controls the horizontal.
  506. There are two ways to avoid this: 1) keep a shell running somewhere with
  507. a higher absolute priority or 2) keep a controlling terminal attached to
  508. the high priority process group. All the priority in the world won't
  509. stop an interrupt handler from running and delivering a signal to the
  510. process if you hit Control-C.
  511. Some systems use absolute priority as a means of allocating a fixed
  512. percentage of CPU time to a process. To do this, a super high priority
  513. privileged process constantly monitors the process' CPU usage and raises
  514. its absolute priority when the process isn't getting its entitled share
  515. and lowers it when the process is exceeding it.
  516. @strong{NB:} The absolute priority is sometimes called the ``static
  517. priority.'' We don't use that term in this manual because it misses the
  518. most important feature of the absolute priority: its absoluteness.
  519. @node Realtime Scheduling
  520. @subsection Realtime Scheduling
  521. @cindex realtime scheduling
  522. Whenever two processes with the same absolute priority are ready to run,
  523. the kernel has a decision to make, because only one can run at a time.
  524. If the processes have absolute priority 0, the kernel makes this decision
  525. as described in @ref{Traditional Scheduling}. Otherwise, the decision
  526. is as described in this section.
  527. If two processes are ready to run but have different absolute priorities,
  528. the decision is much simpler, and is described in @ref{Absolute
  529. Priority}.
  530. Each process has a scheduling policy. For processes with absolute
  531. priority other than zero, there are two available:
  532. @enumerate
  533. @item
  534. First Come First Served
  535. @item
  536. Round Robin
  537. @end enumerate
  538. The most sensible case is where all the processes with a certain
  539. absolute priority have the same scheduling policy. We'll discuss that
  540. first.
  541. In Round Robin, processes share the CPU, each one running for a small
  542. quantum of time (``time slice'') and then yielding to another in a
  543. circular fashion. Of course, only processes that are ready to run and
  544. have the same absolute priority are in this circle.
  545. In First Come First Served, the process that has been waiting the
  546. longest to run gets the CPU, and it keeps it until it voluntarily
  547. relinquishes the CPU, runs out of things to do (blocks), or gets
  548. preempted by a higher priority process.
  549. First Come First Served, along with maximal absolute priority and
  550. careful control of interrupts and page faults, is the one to use when a
  551. process absolutely, positively has to run at full CPU speed or not at
  552. all.
  553. Judicious use of @code{sched_yield} function invocations by processes
  554. with First Come First Served scheduling policy forms a good compromise
  555. between Round Robin and First Come First Served.
  556. To understand how scheduling works when processes of different scheduling
  557. policies occupy the same absolute priority, you have to know the nitty
  558. gritty details of how processes enter and exit the ready to run list.
  559. In both cases, the ready to run list is organized as a true queue, where
  560. a process gets pushed onto the tail when it becomes ready to run and is
  561. popped off the head when the scheduler decides to run it. Note that
  562. ready to run and running are two mutually exclusive states. When the
  563. scheduler runs a process, that process is no longer ready to run and no
  564. longer in the ready to run list. When the process stops running, it
  565. may go back to being ready to run again.
  566. The only difference between a process that is assigned the Round Robin
  567. scheduling policy and a process that is assigned First Come First Serve
  568. is that in the former case, the process is automatically booted off the
  569. CPU after a certain amount of time. When that happens, the process goes
  570. back to being ready to run, which means it enters the queue at the tail.
  571. The time quantum we're talking about is small. Really small. This is
  572. not your father's timesharing. For example, with the Linux kernel, the
  573. round robin time slice is a thousand times shorter than its typical
  574. time slice for traditional scheduling.
  575. A process begins life with the same scheduling policy as its parent process.
  576. Functions described in @ref{Basic Scheduling Functions} can change it.
  577. Only a privileged process can set the scheduling policy of a process
  578. that has absolute priority higher than 0.
  579. @node Basic Scheduling Functions
  580. @subsection Basic Scheduling Functions
  581. This section describes functions in @theglibc{} for setting the
  582. absolute priority and scheduling policy of a process.
  583. @strong{Portability Note:} On systems that have the functions in this
  584. section, the macro _POSIX_PRIORITY_SCHEDULING is defined in
  585. @file{<unistd.h>}.
  586. For the case that the scheduling policy is traditional scheduling, more
  587. functions to fine tune the scheduling are in @ref{Traditional Scheduling}.
  588. Don't try to make too much out of the naming and structure of these
  589. functions. They don't match the concepts described in this manual
  590. because the functions are as defined by POSIX.1b, but the implementation
  591. on systems that use @theglibc{} is the inverse of what the POSIX
  592. structure contemplates. The POSIX scheme assumes that the primary
  593. scheduling parameter is the scheduling policy and that the priority
  594. value, if any, is a parameter of the scheduling policy. In the
  595. implementation, though, the priority value is king and the scheduling
  596. policy, if anything, only fine tunes the effect of that priority.
  597. The symbols in this section are declared by including file @file{sched.h}.
  598. @deftp {Data Type} {struct sched_param}
  599. @standards{POSIX, sched.h}
  600. This structure describes an absolute priority.
  601. @table @code
  602. @item int sched_priority
  603. absolute priority value
  604. @end table
  605. @end deftp
  606. @deftypefun int sched_setscheduler (pid_t @var{pid}, int @var{policy}, const struct sched_param *@var{param})
  607. @standards{POSIX, sched.h}
  608. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  609. @c Direct syscall, Linux only.
  610. This function sets both the absolute priority and the scheduling policy
  611. for a process.
  612. It assigns the absolute priority value given by @var{param} and the
  613. scheduling policy @var{policy} to the process with Process ID @var{pid},
  614. or the calling process if @var{pid} is zero. If @var{policy} is
  615. negative, @code{sched_setscheduler} keeps the existing scheduling policy.
  616. The following macros represent the valid values for @var{policy}:
  617. @vtable @code
  618. @item SCHED_OTHER
  619. Traditional Scheduling
  620. @item SCHED_FIFO
  621. First In First Out
  622. @item SCHED_RR
  623. Round Robin
  624. @end vtable
  625. @c The Linux kernel code (in sched.c) actually reschedules the process,
  626. @c but it puts it at the head of the run queue, so I'm not sure just what
  627. @c the effect is, but it must be subtle.
  628. On success, the return value is @code{0}. Otherwise, it is @code{-1}
  629. and @code{ERRNO} is set accordingly. The @code{errno} values specific
  630. to this function are:
  631. @table @code
  632. @item EPERM
  633. @itemize @bullet
  634. @item
  635. The calling process does not have @code{CAP_SYS_NICE} permission and
  636. @var{policy} is not @code{SCHED_OTHER} (or it's negative and the
  637. existing policy is not @code{SCHED_OTHER}.
  638. @item
  639. The calling process does not have @code{CAP_SYS_NICE} permission and its
  640. owner is not the target process' owner. I.e., the effective uid of the
  641. calling process is neither the effective nor the real uid of process
  642. @var{pid}.
  643. @c We need a cross reference to the capabilities section, when written.
  644. @end itemize
  645. @item ESRCH
  646. There is no process with pid @var{pid} and @var{pid} is not zero.
  647. @item EINVAL
  648. @itemize @bullet
  649. @item
  650. @var{policy} does not identify an existing scheduling policy.
  651. @item
  652. The absolute priority value identified by *@var{param} is outside the
  653. valid range for the scheduling policy @var{policy} (or the existing
  654. scheduling policy if @var{policy} is negative) or @var{param} is
  655. null. @code{sched_get_priority_max} and @code{sched_get_priority_min}
  656. tell you what the valid range is.
  657. @item
  658. @var{pid} is negative.
  659. @end itemize
  660. @end table
  661. @end deftypefun
  662. @deftypefun int sched_getscheduler (pid_t @var{pid})
  663. @standards{POSIX, sched.h}
  664. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  665. @c Direct syscall, Linux only.
  666. This function returns the scheduling policy assigned to the process with
  667. Process ID (pid) @var{pid}, or the calling process if @var{pid} is zero.
  668. The return value is the scheduling policy. See
  669. @code{sched_setscheduler} for the possible values.
  670. If the function fails, the return value is instead @code{-1} and
  671. @code{errno} is set accordingly.
  672. The @code{errno} values specific to this function are:
  673. @table @code
  674. @item ESRCH
  675. There is no process with pid @var{pid} and it is not zero.
  676. @item EINVAL
  677. @var{pid} is negative.
  678. @end table
  679. Note that this function is not an exact mate to @code{sched_setscheduler}
  680. because while that function sets the scheduling policy and the absolute
  681. priority, this function gets only the scheduling policy. To get the
  682. absolute priority, use @code{sched_getparam}.
  683. @end deftypefun
  684. @deftypefun int sched_setparam (pid_t @var{pid}, const struct sched_param *@var{param})
  685. @standards{POSIX, sched.h}
  686. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  687. @c Direct syscall, Linux only.
  688. This function sets a process' absolute priority.
  689. It is functionally identical to @code{sched_setscheduler} with
  690. @var{policy} = @code{-1}.
  691. @c in fact, that's how it's implemented in Linux.
  692. @end deftypefun
  693. @deftypefun int sched_getparam (pid_t @var{pid}, struct sched_param *@var{param})
  694. @standards{POSIX, sched.h}
  695. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  696. @c Direct syscall, Linux only.
  697. This function returns a process' absolute priority.
  698. @var{pid} is the Process ID (pid) of the process whose absolute priority
  699. you want to know.
  700. @var{param} is a pointer to a structure in which the function stores the
  701. absolute priority of the process.
  702. On success, the return value is @code{0}. Otherwise, it is @code{-1}
  703. and @code{errno} is set accordingly. The @code{errno} values specific
  704. to this function are:
  705. @table @code
  706. @item ESRCH
  707. There is no process with pid @var{pid} and it is not zero.
  708. @item EINVAL
  709. @var{pid} is negative.
  710. @end table
  711. @end deftypefun
  712. @deftypefun int sched_get_priority_min (int @var{policy})
  713. @standards{POSIX, sched.h}
  714. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  715. @c Direct syscall, Linux only.
  716. This function returns the lowest absolute priority value that is
  717. allowable for a process with scheduling policy @var{policy}.
  718. On Linux, it is 0 for SCHED_OTHER and 1 for everything else.
  719. On success, the return value is @code{0}. Otherwise, it is @code{-1}
  720. and @code{ERRNO} is set accordingly. The @code{errno} values specific
  721. to this function are:
  722. @table @code
  723. @item EINVAL
  724. @var{policy} does not identify an existing scheduling policy.
  725. @end table
  726. @end deftypefun
  727. @deftypefun int sched_get_priority_max (int @var{policy})
  728. @standards{POSIX, sched.h}
  729. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  730. @c Direct syscall, Linux only.
  731. This function returns the highest absolute priority value that is
  732. allowable for a process that with scheduling policy @var{policy}.
  733. On Linux, it is 0 for SCHED_OTHER and 99 for everything else.
  734. On success, the return value is @code{0}. Otherwise, it is @code{-1}
  735. and @code{ERRNO} is set accordingly. The @code{errno} values specific
  736. to this function are:
  737. @table @code
  738. @item EINVAL
  739. @var{policy} does not identify an existing scheduling policy.
  740. @end table
  741. @end deftypefun
  742. @deftypefun int sched_rr_get_interval (pid_t @var{pid}, struct timespec *@var{interval})
  743. @standards{POSIX, sched.h}
  744. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  745. @c Direct syscall, Linux only.
  746. This function returns the length of the quantum (time slice) used with
  747. the Round Robin scheduling policy, if it is used, for the process with
  748. Process ID @var{pid}.
  749. It returns the length of time as @var{interval}.
  750. @c We need a cross-reference to where timespec is explained. But that
  751. @c section doesn't exist yet, and the time chapter needs to be slightly
  752. @c reorganized so there is a place to put it (which will be right next
  753. @c to timeval, which is presently misplaced). 2000.05.07.
  754. With a Linux kernel, the round robin time slice is always 150
  755. microseconds, and @var{pid} need not even be a real pid.
  756. The return value is @code{0} on success and in the pathological case
  757. that it fails, the return value is @code{-1} and @code{errno} is set
  758. accordingly. There is nothing specific that can go wrong with this
  759. function, so there are no specific @code{errno} values.
  760. @end deftypefun
  761. @deftypefun int sched_yield (void)
  762. @standards{POSIX, sched.h}
  763. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  764. @c Direct syscall on Linux; alias to swtch on HURD.
  765. This function voluntarily gives up the process' claim on the CPU.
  766. Technically, @code{sched_yield} causes the calling process to be made
  767. immediately ready to run (as opposed to running, which is what it was
  768. before). This means that if it has absolute priority higher than 0, it
  769. gets pushed onto the tail of the queue of processes that share its
  770. absolute priority and are ready to run, and it will run again when its
  771. turn next arrives. If its absolute priority is 0, it is more
  772. complicated, but still has the effect of yielding the CPU to other
  773. processes.
  774. If there are no other processes that share the calling process' absolute
  775. priority, this function doesn't have any effect.
  776. To the extent that the containing program is oblivious to what other
  777. processes in the system are doing and how fast it executes, this
  778. function appears as a no-op.
  779. The return value is @code{0} on success and in the pathological case
  780. that it fails, the return value is @code{-1} and @code{errno} is set
  781. accordingly. There is nothing specific that can go wrong with this
  782. function, so there are no specific @code{errno} values.
  783. @end deftypefun
  784. @node Traditional Scheduling
  785. @subsection Traditional Scheduling
  786. @cindex scheduling, traditional
  787. This section is about the scheduling among processes whose absolute
  788. priority is 0. When the system hands out the scraps of CPU time that
  789. are left over after the processes with higher absolute priority have
  790. taken all they want, the scheduling described herein determines who
  791. among the great unwashed processes gets them.
  792. @menu
  793. * Traditional Scheduling Intro::
  794. * Traditional Scheduling Functions::
  795. @end menu
  796. @node Traditional Scheduling Intro
  797. @subsubsection Introduction To Traditional Scheduling
  798. Long before there was absolute priority (See @ref{Absolute Priority}),
  799. Unix systems were scheduling the CPU using this system. When POSIX came
  800. in like the Romans and imposed absolute priorities to accommodate the
  801. needs of realtime processing, it left the indigenous Absolute Priority
  802. Zero processes to govern themselves by their own familiar scheduling
  803. policy.
  804. Indeed, absolute priorities higher than zero are not available on many
  805. systems today and are not typically used when they are, being intended
  806. mainly for computers that do realtime processing. So this section
  807. describes the only scheduling many programmers need to be concerned
  808. about.
  809. But just to be clear about the scope of this scheduling: Any time a
  810. process with an absolute priority of 0 and a process with an absolute
  811. priority higher than 0 are ready to run at the same time, the one with
  812. absolute priority 0 does not run. If it's already running when the
  813. higher priority ready-to-run process comes into existence, it stops
  814. immediately.
  815. In addition to its absolute priority of zero, every process has another
  816. priority, which we will refer to as "dynamic priority" because it changes
  817. over time. The dynamic priority is meaningless for processes with
  818. an absolute priority higher than zero.
  819. The dynamic priority sometimes determines who gets the next turn on the
  820. CPU. Sometimes it determines how long turns last. Sometimes it
  821. determines whether a process can kick another off the CPU.
  822. In Linux, the value is a combination of these things, but mostly it
  823. just determines the length of the time slice. The higher a process'
  824. dynamic priority, the longer a shot it gets on the CPU when it gets one.
  825. If it doesn't use up its time slice before giving up the CPU to do
  826. something like wait for I/O, it is favored for getting the CPU back when
  827. it's ready for it, to finish out its time slice. Other than that,
  828. selection of processes for new time slices is basically round robin.
  829. But the scheduler does throw a bone to the low priority processes: A
  830. process' dynamic priority rises every time it is snubbed in the
  831. scheduling process. In Linux, even the fat kid gets to play.
  832. The fluctuation of a process' dynamic priority is regulated by another
  833. value: The ``nice'' value. The nice value is an integer, usually in the
  834. range -20 to 20, and represents an upper limit on a process' dynamic
  835. priority. The higher the nice number, the lower that limit.
  836. On a typical Linux system, for example, a process with a nice value of
  837. 20 can get only 10 milliseconds on the CPU at a time, whereas a process
  838. with a nice value of -20 can achieve a high enough priority to get 400
  839. milliseconds.
  840. The idea of the nice value is deferential courtesy. In the beginning,
  841. in the Unix garden of Eden, all processes shared equally in the bounty
  842. of the computer system. But not all processes really need the same
  843. share of CPU time, so the nice value gave a courteous process the
  844. ability to refuse its equal share of CPU time that others might prosper.
  845. Hence, the higher a process' nice value, the nicer the process is.
  846. (Then a snake came along and offered some process a negative nice value
  847. and the system became the crass resource allocation system we know
  848. today.)
  849. Dynamic priorities tend upward and downward with an objective of
  850. smoothing out allocation of CPU time and giving quick response time to
  851. infrequent requests. But they never exceed their nice limits, so on a
  852. heavily loaded CPU, the nice value effectively determines how fast a
  853. process runs.
  854. In keeping with the socialistic heritage of Unix process priority, a
  855. process begins life with the same nice value as its parent process and
  856. can raise it at will. A process can also raise the nice value of any
  857. other process owned by the same user (or effective user). But only a
  858. privileged process can lower its nice value. A privileged process can
  859. also raise or lower another process' nice value.
  860. @glibcadj{} functions for getting and setting nice values are described in
  861. @xref{Traditional Scheduling Functions}.
  862. @node Traditional Scheduling Functions
  863. @subsubsection Functions For Traditional Scheduling
  864. @pindex sys/resource.h
  865. This section describes how you can read and set the nice value of a
  866. process. All these symbols are declared in @file{sys/resource.h}.
  867. The function and macro names are defined by POSIX, and refer to
  868. "priority," but the functions actually have to do with nice values, as
  869. the terms are used both in the manual and POSIX.
  870. The range of valid nice values depends on the kernel, but typically it
  871. runs from @code{-20} to @code{20}. A lower nice value corresponds to
  872. higher priority for the process. These constants describe the range of
  873. priority values:
  874. @vtable @code
  875. @item PRIO_MIN
  876. @standards{BSD, sys/resource.h}
  877. The lowest valid nice value.
  878. @item PRIO_MAX
  879. @standards{BSD, sys/resource.h}
  880. The highest valid nice value.
  881. @end vtable
  882. @deftypefun int getpriority (int @var{class}, int @var{id})
  883. @standards{BSD, sys/resource.h}
  884. @standards{POSIX, sys/resource.h}
  885. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  886. @c Direct syscall on UNIX. On HURD, calls _hurd_priority_which_map.
  887. Return the nice value of a set of processes; @var{class} and @var{id}
  888. specify which ones (see below). If the processes specified do not all
  889. have the same nice value, this returns the lowest value that any of them
  890. has.
  891. On success, the return value is @code{0}. Otherwise, it is @code{-1}
  892. and @code{errno} is set accordingly. The @code{errno} values specific
  893. to this function are:
  894. @table @code
  895. @item ESRCH
  896. The combination of @var{class} and @var{id} does not match any existing
  897. process.
  898. @item EINVAL
  899. The value of @var{class} is not valid.
  900. @end table
  901. If the return value is @code{-1}, it could indicate failure, or it could
  902. be the nice value. The only way to make certain is to set @code{errno =
  903. 0} before calling @code{getpriority}, then use @code{errno != 0}
  904. afterward as the criterion for failure.
  905. @end deftypefun
  906. @deftypefun int setpriority (int @var{class}, int @var{id}, int @var{niceval})
  907. @standards{BSD, sys/resource.h}
  908. @standards{POSIX, sys/resource.h}
  909. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  910. @c Direct syscall on UNIX. On HURD, calls _hurd_priority_which_map.
  911. Set the nice value of a set of processes to @var{niceval}; @var{class}
  912. and @var{id} specify which ones (see below).
  913. The return value is @code{0} on success, and @code{-1} on
  914. failure. The following @code{errno} error condition are possible for
  915. this function:
  916. @table @code
  917. @item ESRCH
  918. The combination of @var{class} and @var{id} does not match any existing
  919. process.
  920. @item EINVAL
  921. The value of @var{class} is not valid.
  922. @item EPERM
  923. The call would set the nice value of a process which is owned by a different
  924. user than the calling process (i.e., the target process' real or effective
  925. uid does not match the calling process' effective uid) and the calling
  926. process does not have @code{CAP_SYS_NICE} permission.
  927. @item EACCES
  928. The call would lower the process' nice value and the process does not have
  929. @code{CAP_SYS_NICE} permission.
  930. @end table
  931. @end deftypefun
  932. The arguments @var{class} and @var{id} together specify a set of
  933. processes in which you are interested. These are the possible values of
  934. @var{class}:
  935. @vtable @code
  936. @item PRIO_PROCESS
  937. @standards{BSD, sys/resource.h}
  938. One particular process. The argument @var{id} is a process ID (pid).
  939. @item PRIO_PGRP
  940. @standards{BSD, sys/resource.h}
  941. All the processes in a particular process group. The argument @var{id} is
  942. a process group ID (pgid).
  943. @item PRIO_USER
  944. @standards{BSD, sys/resource.h}
  945. All the processes owned by a particular user (i.e., whose real uid
  946. indicates the user). The argument @var{id} is a user ID (uid).
  947. @end vtable
  948. If the argument @var{id} is 0, it stands for the calling process, its
  949. process group, or its owner (real uid), according to @var{class}.
  950. @deftypefun int nice (int @var{increment})
  951. @standards{BSD, unistd.h}
  952. @safety{@prelim{}@mtunsafe{@mtasurace{:setpriority}}@asunsafe{}@acsafe{}}
  953. @c Calls getpriority before and after setpriority, using the result of
  954. @c the first call to compute the argument for setpriority. This creates
  955. @c a window for a concurrent setpriority (or nice) call to be lost or
  956. @c exhibit surprising behavior.
  957. Increment the nice value of the calling process by @var{increment}.
  958. The return value is the new nice value on success, and @code{-1} on
  959. failure. In the case of failure, @code{errno} will be set to the
  960. same values as for @code{setpriority}.
  961. Here is an equivalent definition of @code{nice}:
  962. @smallexample
  963. int
  964. nice (int increment)
  965. @{
  966. int result, old = getpriority (PRIO_PROCESS, 0);
  967. result = setpriority (PRIO_PROCESS, 0, old + increment);
  968. if (result != -1)
  969. return old + increment;
  970. else
  971. return -1;
  972. @}
  973. @end smallexample
  974. @end deftypefun
  975. @node CPU Affinity
  976. @subsection Limiting execution to certain CPUs
  977. On a multi-processor system the operating system usually distributes
  978. the different processes which are runnable on all available CPUs in a
  979. way which allows the system to work most efficiently. Which processes
  980. and threads run can be to some extend be control with the scheduling
  981. functionality described in the last sections. But which CPU finally
  982. executes which process or thread is not covered.
  983. There are a number of reasons why a program might want to have control
  984. over this aspect of the system as well:
  985. @itemize @bullet
  986. @item
  987. One thread or process is responsible for absolutely critical work
  988. which under no circumstances must be interrupted or hindered from
  989. making progress by other processes or threads using CPU resources. In
  990. this case the special process would be confined to a CPU which no
  991. other process or thread is allowed to use.
  992. @item
  993. The access to certain resources (RAM, I/O ports) has different costs
  994. from different CPUs. This is the case in NUMA (Non-Uniform Memory
  995. Architecture) machines. Preferably memory should be accessed locally
  996. but this requirement is usually not visible to the scheduler.
  997. Therefore forcing a process or thread to the CPUs which have local
  998. access to the most-used memory helps to significantly boost the
  999. performance.
  1000. @item
  1001. In controlled runtimes resource allocation and book-keeping work (for
  1002. instance garbage collection) is performance local to processors. This
  1003. can help to reduce locking costs if the resources do not have to be
  1004. protected from concurrent accesses from different processors.
  1005. @end itemize
  1006. The POSIX standard up to this date is of not much help to solve this
  1007. problem. The Linux kernel provides a set of interfaces to allow
  1008. specifying @emph{affinity sets} for a process. The scheduler will
  1009. schedule the thread or process on CPUs specified by the affinity
  1010. masks. The interfaces which @theglibc{} define follow to some
  1011. extent the Linux kernel interface.
  1012. @deftp {Data Type} cpu_set_t
  1013. @standards{GNU, sched.h}
  1014. This data set is a bitset where each bit represents a CPU. How the
  1015. system's CPUs are mapped to bits in the bitset is system dependent.
  1016. The data type has a fixed size; in the unlikely case that the number
  1017. of bits are not sufficient to describe the CPUs of the system a
  1018. different interface has to be used.
  1019. This type is a GNU extension and is defined in @file{sched.h}.
  1020. @end deftp
  1021. To manipulate the bitset, to set and reset bits, a number of macros are
  1022. defined. Some of the macros take a CPU number as a parameter. Here
  1023. it is important to never exceed the size of the bitset. The following
  1024. macro specifies the number of bits in the @code{cpu_set_t} bitset.
  1025. @deftypevr Macro int CPU_SETSIZE
  1026. @standards{GNU, sched.h}
  1027. The value of this macro is the maximum number of CPUs which can be
  1028. handled with a @code{cpu_set_t} object.
  1029. @end deftypevr
  1030. The type @code{cpu_set_t} should be considered opaque; all
  1031. manipulation should happen via the next four macros.
  1032. @deftypefn Macro void CPU_ZERO (cpu_set_t *@var{set})
  1033. @standards{GNU, sched.h}
  1034. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1035. @c CPU_ZERO ok
  1036. @c __CPU_ZERO_S ok
  1037. @c memset dup ok
  1038. This macro initializes the CPU set @var{set} to be the empty set.
  1039. This macro is a GNU extension and is defined in @file{sched.h}.
  1040. @end deftypefn
  1041. @deftypefn Macro void CPU_SET (int @var{cpu}, cpu_set_t *@var{set})
  1042. @standards{GNU, sched.h}
  1043. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1044. @c CPU_SET ok
  1045. @c __CPU_SET_S ok
  1046. @c __CPUELT ok
  1047. @c __CPUMASK ok
  1048. This macro adds @var{cpu} to the CPU set @var{set}.
  1049. The @var{cpu} parameter must not have side effects since it is
  1050. evaluated more than once.
  1051. This macro is a GNU extension and is defined in @file{sched.h}.
  1052. @end deftypefn
  1053. @deftypefn Macro void CPU_CLR (int @var{cpu}, cpu_set_t *@var{set})
  1054. @standards{GNU, sched.h}
  1055. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1056. @c CPU_CLR ok
  1057. @c __CPU_CLR_S ok
  1058. @c __CPUELT dup ok
  1059. @c __CPUMASK dup ok
  1060. This macro removes @var{cpu} from the CPU set @var{set}.
  1061. The @var{cpu} parameter must not have side effects since it is
  1062. evaluated more than once.
  1063. This macro is a GNU extension and is defined in @file{sched.h}.
  1064. @end deftypefn
  1065. @deftypefn Macro int CPU_ISSET (int @var{cpu}, const cpu_set_t *@var{set})
  1066. @standards{GNU, sched.h}
  1067. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1068. @c CPU_ISSET ok
  1069. @c __CPU_ISSET_S ok
  1070. @c __CPUELT dup ok
  1071. @c __CPUMASK dup ok
  1072. This macro returns a nonzero value (true) if @var{cpu} is a member
  1073. of the CPU set @var{set}, and zero (false) otherwise.
  1074. The @var{cpu} parameter must not have side effects since it is
  1075. evaluated more than once.
  1076. This macro is a GNU extension and is defined in @file{sched.h}.
  1077. @end deftypefn
  1078. CPU bitsets can be constructed from scratch or the currently installed
  1079. affinity mask can be retrieved from the system.
  1080. @deftypefun int sched_getaffinity (pid_t @var{pid}, size_t @var{cpusetsize}, cpu_set_t *@var{cpuset})
  1081. @standards{GNU, sched.h}
  1082. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1083. @c Wrapped syscall to zero out past the kernel cpu set size; Linux
  1084. @c only.
  1085. This function stores the CPU affinity mask for the process or thread
  1086. with the ID @var{pid} in the @var{cpusetsize} bytes long bitmap
  1087. pointed to by @var{cpuset}. If successful, the function always
  1088. initializes all bits in the @code{cpu_set_t} object and returns zero.
  1089. If @var{pid} does not correspond to a process or thread on the system
  1090. the or the function fails for some other reason, it returns @code{-1}
  1091. and @code{errno} is set to represent the error condition.
  1092. @table @code
  1093. @item ESRCH
  1094. No process or thread with the given ID found.
  1095. @item EFAULT
  1096. The pointer @var{cpuset} does not point to a valid object.
  1097. @end table
  1098. This function is a GNU extension and is declared in @file{sched.h}.
  1099. @end deftypefun
  1100. Note that it is not portably possible to use this information to
  1101. retrieve the information for different POSIX threads. A separate
  1102. interface must be provided for that.
  1103. @deftypefun int sched_setaffinity (pid_t @var{pid}, size_t @var{cpusetsize}, const cpu_set_t *@var{cpuset})
  1104. @standards{GNU, sched.h}
  1105. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1106. @c Wrapped syscall to detect attempts to set bits past the kernel cpu
  1107. @c set size; Linux only.
  1108. This function installs the @var{cpusetsize} bytes long affinity mask
  1109. pointed to by @var{cpuset} for the process or thread with the ID @var{pid}.
  1110. If successful the function returns zero and the scheduler will in the future
  1111. take the affinity information into account.
  1112. If the function fails it will return @code{-1} and @code{errno} is set
  1113. to the error code:
  1114. @table @code
  1115. @item ESRCH
  1116. No process or thread with the given ID found.
  1117. @item EFAULT
  1118. The pointer @var{cpuset} does not point to a valid object.
  1119. @item EINVAL
  1120. The bitset is not valid. This might mean that the affinity set might
  1121. not leave a processor for the process or thread to run on.
  1122. @end table
  1123. This function is a GNU extension and is declared in @file{sched.h}.
  1124. @end deftypefun
  1125. @deftypefun int getcpu (unsigned int *cpu, unsigned int *node)
  1126. @standards{Linux, <sched.h>}
  1127. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1128. The @code{getcpu} function identifies the processor and node on which
  1129. the calling thread or process is currently running and writes them into
  1130. the integers pointed to by the @var{cpu} and @var{node} arguments. The
  1131. processor is a unique nonnegative integer identifying a CPU. The node
  1132. is a unique nonnegative integer identifying a NUMA node. When either
  1133. @var{cpu} or @var{node} is @code{NULL}, nothing is written to the
  1134. respective pointer.
  1135. The return value is @code{0} on success and @code{-1} on failure. The
  1136. following @code{errno} error condition is defined for this function:
  1137. @table @code
  1138. @item ENOSYS
  1139. The operating system does not support this function.
  1140. @end table
  1141. This function is Linux-specific and is declared in @file{sched.h}.
  1142. @end deftypefun
  1143. @node Memory Resources
  1144. @section Querying memory available resources
  1145. The amount of memory available in the system and the way it is organized
  1146. determines oftentimes the way programs can and have to work. For
  1147. functions like @code{mmap} it is necessary to know about the size of
  1148. individual memory pages and knowing how much memory is available enables
  1149. a program to select appropriate sizes for, say, caches. Before we get
  1150. into these details a few words about memory subsystems in traditional
  1151. Unix systems will be given.
  1152. @menu
  1153. * Memory Subsystem:: Overview about traditional Unix memory handling.
  1154. * Query Memory Parameters:: How to get information about the memory
  1155. subsystem?
  1156. @end menu
  1157. @node Memory Subsystem
  1158. @subsection Overview about traditional Unix memory handling
  1159. @cindex address space
  1160. @cindex physical memory
  1161. @cindex physical address
  1162. Unix systems normally provide processes virtual address spaces. This
  1163. means that the addresses of the memory regions do not have to correspond
  1164. directly to the addresses of the actual physical memory which stores the
  1165. data. An extra level of indirection is introduced which translates
  1166. virtual addresses into physical addresses. This is normally done by the
  1167. hardware of the processor.
  1168. @cindex shared memory
  1169. Using a virtual address space has several advantages. The most important
  1170. is process isolation. The different processes running on the system
  1171. cannot interfere directly with each other. No process can write into
  1172. the address space of another process (except when shared memory is used
  1173. but then it is wanted and controlled).
  1174. Another advantage of virtual memory is that the address space the
  1175. processes see can actually be larger than the physical memory available.
  1176. The physical memory can be extended by storage on an external media
  1177. where the content of currently unused memory regions is stored. The
  1178. address translation can then intercept accesses to these memory regions
  1179. and make memory content available again by loading the data back into
  1180. memory. This concept makes it necessary that programs which have to use
  1181. lots of memory know the difference between available virtual address
  1182. space and available physical memory. If the working set of virtual
  1183. memory of all the processes is larger than the available physical memory
  1184. the system will slow down dramatically due to constant swapping of
  1185. memory content from the memory to the storage media and back. This is
  1186. called ``thrashing''.
  1187. @cindex thrashing
  1188. @cindex memory page
  1189. @cindex page, memory
  1190. A final aspect of virtual memory which is important and follows from
  1191. what is said in the last paragraph is the granularity of the virtual
  1192. address space handling. When we said that the virtual address handling
  1193. stores memory content externally it cannot do this on a byte-by-byte
  1194. basis. The administrative overhead does not allow this (leaving alone
  1195. the processor hardware). Instead several thousand bytes are handled
  1196. together and form a @dfn{page}. The size of each page is always a power
  1197. of two bytes. The smallest page size in use today is 4096, with 8192,
  1198. 16384, and 65536 being other popular sizes.
  1199. @node Query Memory Parameters
  1200. @subsection How to get information about the memory subsystem?
  1201. The page size of the virtual memory the process sees is essential to
  1202. know in several situations. Some programming interfaces (e.g.,
  1203. @code{mmap}, @pxref{Memory-mapped I/O}) require the user to provide
  1204. information adjusted to the page size. In the case of @code{mmap} it is
  1205. necessary to provide a length argument which is a multiple of the page
  1206. size. Another place where the knowledge about the page size is useful
  1207. is in memory allocation. If one allocates pieces of memory in larger
  1208. chunks which are then subdivided by the application code it is useful to
  1209. adjust the size of the larger blocks to the page size. If the total
  1210. memory requirement for the block is close (but not larger) to a multiple
  1211. of the page size the kernel's memory handling can work more effectively
  1212. since it only has to allocate memory pages which are fully used. (To do
  1213. this optimization it is necessary to know a bit about the memory
  1214. allocator which will require a bit of memory itself for each block and
  1215. this overhead must not push the total size over the page size multiple.)
  1216. The page size traditionally was a compile time constant. But recent
  1217. development of processors changed this. Processors now support
  1218. different page sizes and they can possibly even vary among different
  1219. processes on the same system. Therefore the system should be queried at
  1220. runtime about the current page size and no assumptions (except about it
  1221. being a power of two) should be made.
  1222. @vindex _SC_PAGESIZE
  1223. The correct interface to query about the page size is @code{sysconf}
  1224. (@pxref{Sysconf Definition}) with the parameter @code{_SC_PAGESIZE}.
  1225. There is a much older interface available, too.
  1226. @deftypefun int getpagesize (void)
  1227. @standards{BSD, unistd.h}
  1228. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{}}
  1229. @c Obtained from the aux vec at program startup time. GNU/Linux/m68k is
  1230. @c the exception, with the possibility of a syscall.
  1231. The @code{getpagesize} function returns the page size of the process.
  1232. This value is fixed for the runtime of the process but can vary in
  1233. different runs of the application.
  1234. The function is declared in @file{unistd.h}.
  1235. @end deftypefun
  1236. Widely available on @w{System V} derived systems is a method to get
  1237. information about the physical memory the system has. The call
  1238. @vindex _SC_PHYS_PAGES
  1239. @cindex sysconf
  1240. @smallexample
  1241. sysconf (_SC_PHYS_PAGES)
  1242. @end smallexample
  1243. @noindent
  1244. returns the total number of pages of physical memory the system has.
  1245. This does not mean all this memory is available. This information can
  1246. be found using
  1247. @vindex _SC_AVPHYS_PAGES
  1248. @cindex sysconf
  1249. @smallexample
  1250. sysconf (_SC_AVPHYS_PAGES)
  1251. @end smallexample
  1252. These two values help to optimize applications. The value returned for
  1253. @code{_SC_AVPHYS_PAGES} is the amount of memory the application can use
  1254. without hindering any other process (given that no other process
  1255. increases its memory usage). The value returned for
  1256. @code{_SC_PHYS_PAGES} is more or less a hard limit for the working set.
  1257. If all applications together constantly use more than that amount of
  1258. memory the system is in trouble.
  1259. @Theglibc{} provides in addition to these already described way to
  1260. get this information two functions. They are declared in the file
  1261. @file{sys/sysinfo.h}. Programmers should prefer to use the
  1262. @code{sysconf} method described above.
  1263. @deftypefun {long int} get_phys_pages (void)
  1264. @standards{GNU, sys/sysinfo.h}
  1265. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  1266. @c This fopens a /proc file and scans it for the requested information.
  1267. The @code{get_phys_pages} function returns the total number of pages of
  1268. physical memory the system has. To get the amount of memory this number has to
  1269. be multiplied by the page size.
  1270. This function is a GNU extension.
  1271. @end deftypefun
  1272. @deftypefun {long int} get_avphys_pages (void)
  1273. @standards{GNU, sys/sysinfo.h}
  1274. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  1275. The @code{get_avphys_pages} function returns the number of available pages of
  1276. physical memory the system has. To get the amount of memory this number has to
  1277. be multiplied by the page size.
  1278. This function is a GNU extension.
  1279. @end deftypefun
  1280. @node Processor Resources
  1281. @section Learn about the processors available
  1282. The use of threads or processes with shared memory allows an application
  1283. to take advantage of all the processing power a system can provide. If
  1284. the task can be parallelized the optimal way to write an application is
  1285. to have at any time as many processes running as there are processors.
  1286. To determine the number of processors available to the system one can
  1287. run
  1288. @vindex _SC_NPROCESSORS_CONF
  1289. @cindex sysconf
  1290. @smallexample
  1291. sysconf (_SC_NPROCESSORS_CONF)
  1292. @end smallexample
  1293. @noindent
  1294. which returns the number of processors the operating system configured.
  1295. But it might be possible for the operating system to disable individual
  1296. processors and so the call
  1297. @vindex _SC_NPROCESSORS_ONLN
  1298. @cindex sysconf
  1299. @smallexample
  1300. sysconf (_SC_NPROCESSORS_ONLN)
  1301. @end smallexample
  1302. @noindent
  1303. returns the number of processors which are currently online (i.e.,
  1304. available).
  1305. For these two pieces of information @theglibc{} also provides
  1306. functions to get the information directly. The functions are declared
  1307. in @file{sys/sysinfo.h}.
  1308. @deftypefun int get_nprocs_conf (void)
  1309. @standards{GNU, sys/sysinfo.h}
  1310. @safety{@prelim{}@mtsafe{}@asunsafe{@ascuheap{} @asulock{}}@acunsafe{@aculock{} @acsfd{} @acsmem{}}}
  1311. @c This function reads from from /sys using dir streams (single user, so
  1312. @c no @mtasurace issue), and on some arches, from /proc using streams.
  1313. The @code{get_nprocs_conf} function returns the number of processors the
  1314. operating system configured.
  1315. This function is a GNU extension.
  1316. @end deftypefun
  1317. @deftypefun int get_nprocs (void)
  1318. @standards{GNU, sys/sysinfo.h}
  1319. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
  1320. @c This function reads from /proc using file descriptor I/O.
  1321. The @code{get_nprocs} function returns the number of available processors.
  1322. This function is a GNU extension.
  1323. @end deftypefun
  1324. @cindex load average
  1325. Before starting more threads it should be checked whether the processors
  1326. are not already overused. Unix systems calculate something called the
  1327. @dfn{load average}. This is a number indicating how many processes were
  1328. running. This number is an average over different periods of time
  1329. (normally 1, 5, and 15 minutes).
  1330. @deftypefun int getloadavg (double @var{loadavg}[], int @var{nelem})
  1331. @standards{BSD, stdlib.h}
  1332. @safety{@prelim{}@mtsafe{}@assafe{}@acsafe{@acsfd{}}}
  1333. @c Calls host_info on HURD; on Linux, opens /proc/loadavg, reads from
  1334. @c it, closes it, without cancellation point, and calls strtod_l with
  1335. @c the C locale to convert the strings to doubles.
  1336. This function gets the 1, 5 and 15 minute load averages of the
  1337. system. The values are placed in @var{loadavg}. @code{getloadavg} will
  1338. place at most @var{nelem} elements into the array but never more than
  1339. three elements. The return value is the number of elements written to
  1340. @var{loadavg}, or -1 on error.
  1341. This function is declared in @file{stdlib.h}.
  1342. @end deftypefun