resource.texi 73 KB

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