kfuncs.rst 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. .. SPDX-License-Identifier: GPL-2.0
  2. .. _kfuncs-header-label:
  3. =============================
  4. BPF Kernel Functions (kfuncs)
  5. =============================
  6. 1. Introduction
  7. ===============
  8. BPF Kernel Functions or more commonly known as kfuncs are functions in the Linux
  9. kernel which are exposed for use by BPF programs. Unlike normal BPF helpers,
  10. kfuncs do not have a stable interface and can change from one kernel release to
  11. another. Hence, BPF programs need to be updated in response to changes in the
  12. kernel. See :ref:`BPF_kfunc_lifecycle_expectations` for more information.
  13. 2. Defining a kfunc
  14. ===================
  15. There are two ways to expose a kernel function to BPF programs, either make an
  16. existing function in the kernel visible, or add a new wrapper for BPF. In both
  17. cases, care must be taken that BPF program can only call such function in a
  18. valid context. To enforce this, visibility of a kfunc can be per program type.
  19. If you are not creating a BPF wrapper for existing kernel function, skip ahead
  20. to :ref:`BPF_kfunc_nodef`.
  21. 2.1 Creating a wrapper kfunc
  22. ----------------------------
  23. When defining a wrapper kfunc, the wrapper function should have extern linkage.
  24. This prevents the compiler from optimizing away dead code, as this wrapper kfunc
  25. is not invoked anywhere in the kernel itself. It is not necessary to provide a
  26. prototype in a header for the wrapper kfunc.
  27. An example is given below::
  28. /* Disables missing prototype warnings */
  29. __bpf_kfunc_start_defs();
  30. __bpf_kfunc struct task_struct *bpf_find_get_task_by_vpid(pid_t nr)
  31. {
  32. return find_get_task_by_vpid(nr);
  33. }
  34. __bpf_kfunc_end_defs();
  35. A wrapper kfunc is often needed when we need to annotate parameters of the
  36. kfunc. Otherwise one may directly make the kfunc visible to the BPF program by
  37. registering it with the BPF subsystem. See :ref:`BPF_kfunc_nodef`.
  38. 2.2 kfunc Parameters
  39. --------------------
  40. All kfuncs now require trusted arguments by default. This means that all
  41. pointer arguments must be valid, and all pointers to BTF objects must be
  42. passed in their unmodified form (at a zero offset, and without having been
  43. obtained from walking another pointer, with exceptions described below).
  44. There are two types of pointers to kernel objects which are considered "trusted":
  45. 1. Pointers which are passed as tracepoint or struct_ops callback arguments.
  46. 2. Pointers which were returned from a KF_ACQUIRE kfunc.
  47. Pointers to non-BTF objects (e.g. scalar pointers) may also be passed to
  48. kfuncs, and may have a non-zero offset.
  49. The definition of "valid" pointers is subject to change at any time, and has
  50. absolutely no ABI stability guarantees.
  51. As mentioned above, a nested pointer obtained from walking a trusted pointer is
  52. no longer trusted, with one exception. If a struct type has a field that is
  53. guaranteed to be valid (trusted or rcu, as in KF_RCU description below) as long
  54. as its parent pointer is valid, the following macros can be used to express
  55. that to the verifier:
  56. * ``BTF_TYPE_SAFE_TRUSTED``
  57. * ``BTF_TYPE_SAFE_RCU``
  58. * ``BTF_TYPE_SAFE_RCU_OR_NULL``
  59. For example,
  60. .. code-block:: c
  61. BTF_TYPE_SAFE_TRUSTED(struct socket) {
  62. struct sock *sk;
  63. };
  64. or
  65. .. code-block:: c
  66. BTF_TYPE_SAFE_RCU(struct task_struct) {
  67. const cpumask_t *cpus_ptr;
  68. struct css_set __rcu *cgroups;
  69. struct task_struct __rcu *real_parent;
  70. struct task_struct *group_leader;
  71. };
  72. In other words, you must:
  73. 1. Wrap the valid pointer type in a ``BTF_TYPE_SAFE_*`` macro.
  74. 2. Specify the type and name of the valid nested field. This field must match
  75. the field in the original type definition exactly.
  76. A new type declared by a ``BTF_TYPE_SAFE_*`` macro also needs to be emitted so
  77. that it appears in BTF. For example, ``BTF_TYPE_SAFE_TRUSTED(struct socket)``
  78. is emitted in the ``type_is_trusted()`` function as follows:
  79. .. code-block:: c
  80. BTF_TYPE_EMIT(BTF_TYPE_SAFE_TRUSTED(struct socket));
  81. 2.3 Annotating kfunc parameters
  82. -------------------------------
  83. Similar to BPF helpers, there is sometime need for additional context required
  84. by the verifier to make the usage of kernel functions safer and more useful.
  85. Hence, we can annotate a parameter by suffixing the name of the argument of the
  86. kfunc with a __tag, where tag may be one of the supported annotations.
  87. 2.3.1 __sz Annotation
  88. ---------------------
  89. This annotation is used to indicate a memory and size pair in the argument list.
  90. An example is given below::
  91. __bpf_kfunc void bpf_memzero(void *mem, int mem__sz)
  92. {
  93. ...
  94. }
  95. Here, the verifier will treat first argument as a PTR_TO_MEM, and second
  96. argument as its size. By default, without __sz annotation, the size of the type
  97. of the pointer is used. Without __sz annotation, a kfunc cannot accept a void
  98. pointer.
  99. 2.3.2 __k Annotation
  100. --------------------
  101. This annotation is only understood for scalar arguments, where it indicates that
  102. the verifier must check the scalar argument to be a known constant, which does
  103. not indicate a size parameter, and the value of the constant is relevant to the
  104. safety of the program.
  105. An example is given below::
  106. __bpf_kfunc void *bpf_obj_new(u32 local_type_id__k, ...)
  107. {
  108. ...
  109. }
  110. Here, bpf_obj_new uses local_type_id argument to find out the size of that type
  111. ID in program's BTF and return a sized pointer to it. Each type ID will have a
  112. distinct size, hence it is crucial to treat each such call as distinct when
  113. values don't match during verifier state pruning checks.
  114. Hence, whenever a constant scalar argument is accepted by a kfunc which is not a
  115. size parameter, and the value of the constant matters for program safety, __k
  116. suffix should be used.
  117. 2.3.3 __uninit Annotation
  118. -------------------------
  119. This annotation is used to indicate that the argument will be treated as
  120. uninitialized.
  121. An example is given below::
  122. __bpf_kfunc int bpf_dynptr_from_skb(..., struct bpf_dynptr_kern *ptr__uninit)
  123. {
  124. ...
  125. }
  126. Here, the dynptr will be treated as an uninitialized dynptr. Without this
  127. annotation, the verifier will reject the program if the dynptr passed in is
  128. not initialized.
  129. 2.3.4 __nullable Annotation
  130. ---------------------------
  131. This annotation is used to indicate that the pointer argument may be NULL.
  132. The verifier will allow passing NULL for such arguments.
  133. An example is given below::
  134. __bpf_kfunc void bpf_task_release(struct task_struct *task__nullable)
  135. {
  136. ...
  137. }
  138. Here, the task pointer may be NULL. The kfunc is responsible for checking if
  139. the pointer is NULL before dereferencing it.
  140. The __nullable annotation can be combined with other annotations. For example,
  141. when used with __sz or __szk annotations for memory and size pairs, the
  142. verifier will skip size validation when a NULL pointer is passed, but will
  143. still process the size argument to extract constant size information when
  144. needed::
  145. __bpf_kfunc void *bpf_dynptr_slice(..., void *buffer__nullable,
  146. u32 buffer__szk)
  147. Here, the buffer may be NULL. If the buffer is not NULL, it must be at least
  148. buffer__szk bytes in size. The kfunc is responsible for checking if the buffer
  149. is NULL before using it.
  150. 2.3.5 __str Annotation
  151. ----------------------------
  152. This annotation is used to indicate that the argument is a constant string.
  153. An example is given below::
  154. __bpf_kfunc bpf_get_file_xattr(..., const char *name__str, ...)
  155. {
  156. ...
  157. }
  158. In this case, ``bpf_get_file_xattr()`` can be called as::
  159. bpf_get_file_xattr(..., "xattr_name", ...);
  160. Or::
  161. const char name[] = "xattr_name"; /* This need to be global */
  162. int BPF_PROG(...)
  163. {
  164. ...
  165. bpf_get_file_xattr(..., name, ...);
  166. ...
  167. }
  168. .. _BPF_kfunc_nodef:
  169. 2.4 Using an existing kernel function
  170. -------------------------------------
  171. When an existing function in the kernel is fit for consumption by BPF programs,
  172. it can be directly registered with the BPF subsystem. However, care must still
  173. be taken to review the context in which it will be invoked by the BPF program
  174. and whether it is safe to do so.
  175. 2.5 Annotating kfuncs
  176. ---------------------
  177. In addition to kfuncs' arguments, verifier may need more information about the
  178. type of kfunc(s) being registered with the BPF subsystem. To do so, we define
  179. flags on a set of kfuncs as follows::
  180. BTF_KFUNCS_START(bpf_task_set)
  181. BTF_ID_FLAGS(func, bpf_get_task_pid, KF_ACQUIRE | KF_RET_NULL)
  182. BTF_ID_FLAGS(func, bpf_put_pid, KF_RELEASE)
  183. BTF_KFUNCS_END(bpf_task_set)
  184. This set encodes the BTF ID of each kfunc listed above, and encodes the flags
  185. along with it. Ofcourse, it is also allowed to specify no flags.
  186. kfunc definitions should also always be annotated with the ``__bpf_kfunc``
  187. macro. This prevents issues such as the compiler inlining the kfunc if it's a
  188. static kernel function, or the function being elided in an LTO build as it's
  189. not used in the rest of the kernel. Developers should not manually add
  190. annotations to their kfunc to prevent these issues. If an annotation is
  191. required to prevent such an issue with your kfunc, it is a bug and should be
  192. added to the definition of the macro so that other kfuncs are similarly
  193. protected. An example is given below::
  194. __bpf_kfunc struct task_struct *bpf_get_task_pid(s32 pid)
  195. {
  196. ...
  197. }
  198. 2.5.1 KF_ACQUIRE flag
  199. ---------------------
  200. The KF_ACQUIRE flag is used to indicate that the kfunc returns a pointer to a
  201. refcounted object. The verifier will then ensure that the pointer to the object
  202. is eventually released using a release kfunc, or transferred to a map using a
  203. referenced kptr (by invoking bpf_kptr_xchg). If not, the verifier fails the
  204. loading of the BPF program until no lingering references remain in all possible
  205. explored states of the program.
  206. 2.5.2 KF_RET_NULL flag
  207. ----------------------
  208. The KF_RET_NULL flag is used to indicate that the pointer returned by the kfunc
  209. may be NULL. Hence, it forces the user to do a NULL check on the pointer
  210. returned from the kfunc before making use of it (dereferencing or passing to
  211. another helper). This flag is often used in pairing with KF_ACQUIRE flag, but
  212. both are orthogonal to each other.
  213. 2.5.3 KF_RELEASE flag
  214. ---------------------
  215. The KF_RELEASE flag is used to indicate that the kfunc releases the pointer
  216. passed in to it. There can be only one referenced pointer that can be passed
  217. in. All copies of the pointer being released are invalidated as a result of
  218. invoking kfunc with this flag.
  219. 2.5.4 KF_SLEEPABLE flag
  220. -----------------------
  221. The KF_SLEEPABLE flag is used for kfuncs that may sleep. Such kfuncs can only
  222. be called by sleepable BPF programs (BPF_F_SLEEPABLE).
  223. 2.5.5 KF_DESTRUCTIVE flag
  224. --------------------------
  225. The KF_DESTRUCTIVE flag is used to indicate functions calling which is
  226. destructive to the system. For example such a call can result in system
  227. rebooting or panicking. Due to this additional restrictions apply to these
  228. calls. At the moment they only require CAP_SYS_BOOT capability, but more can be
  229. added later.
  230. 2.5.6 KF_RCU flag
  231. -----------------
  232. The KF_RCU flag allows kfuncs to opt out of the default trusted args
  233. requirement and accept RCU pointers with weaker guarantees. The kfuncs marked
  234. with KF_RCU expect either PTR_TRUSTED or MEM_RCU arguments. The verifier
  235. guarantees that the objects are valid and there is no use-after-free. The
  236. pointers are not NULL, but the object's refcount could have reached zero. The
  237. kfuncs need to consider doing refcnt != 0 check, especially when returning a
  238. KF_ACQUIRE pointer. Note as well that a KF_ACQUIRE kfunc that is KF_RCU should
  239. very likely also be KF_RET_NULL.
  240. 2.5.7 KF_RCU_PROTECTED flag
  241. ---------------------------
  242. The KF_RCU_PROTECTED flag is used to indicate that the kfunc must be invoked in
  243. an RCU critical section. This is assumed by default in non-sleepable programs,
  244. and must be explicitly ensured by calling ``bpf_rcu_read_lock`` for sleepable
  245. ones.
  246. If the kfunc returns a pointer value, this flag also enforces that the returned
  247. pointer is RCU protected, and can only be used while the RCU critical section is
  248. active.
  249. The flag is distinct from the ``KF_RCU`` flag, which only ensures that its
  250. arguments are at least RCU protected pointers. This may transitively imply that
  251. RCU protection is ensured, but it does not work in cases of kfuncs which require
  252. RCU protection but do not take RCU protected arguments.
  253. .. _KF_deprecated_flag:
  254. 2.5.8 KF_DEPRECATED flag
  255. ------------------------
  256. The KF_DEPRECATED flag is used for kfuncs which are scheduled to be
  257. changed or removed in a subsequent kernel release. A kfunc that is
  258. marked with KF_DEPRECATED should also have any relevant information
  259. captured in its kernel doc. Such information typically includes the
  260. kfunc's expected remaining lifespan, a recommendation for new
  261. functionality that can replace it if any is available, and possibly a
  262. rationale for why it is being removed.
  263. Note that while on some occasions, a KF_DEPRECATED kfunc may continue to be
  264. supported and have its KF_DEPRECATED flag removed, it is likely to be far more
  265. difficult to remove a KF_DEPRECATED flag after it's been added than it is to
  266. prevent it from being added in the first place. As described in
  267. :ref:`BPF_kfunc_lifecycle_expectations`, users that rely on specific kfuncs are
  268. encouraged to make their use-cases known as early as possible, and participate
  269. in upstream discussions regarding whether to keep, change, deprecate, or remove
  270. those kfuncs if and when such discussions occur.
  271. 2.5.9 KF_IMPLICIT_ARGS flag
  272. ------------------------------------
  273. The KF_IMPLICIT_ARGS flag is used to indicate that the BPF signature
  274. of the kfunc is different from it's kernel signature, and the values
  275. for implicit arguments are provided at load time by the verifier.
  276. Only arguments of specific types are implicit.
  277. Currently only ``struct bpf_prog_aux *`` type is supported.
  278. A kfunc with KF_IMPLICIT_ARGS flag therefore has two types in BTF: one
  279. function matching the kernel declaration (with _impl suffix in the
  280. name by convention), and another matching the intended BPF API.
  281. Verifier only allows calls to the non-_impl version of a kfunc, that
  282. uses a signature without the implicit arguments.
  283. Example declaration:
  284. .. code-block:: c
  285. __bpf_kfunc int bpf_task_work_schedule_signal(struct task_struct *task, struct bpf_task_work *tw,
  286. void *map__map, bpf_task_work_callback_t callback,
  287. struct bpf_prog_aux *aux) { ... }
  288. Example usage in BPF program:
  289. .. code-block:: c
  290. /* note that the last argument is omitted */
  291. bpf_task_work_schedule_signal(task, &work->tw, &arrmap, task_work_callback);
  292. 2.6 Registering the kfuncs
  293. --------------------------
  294. Once the kfunc is prepared for use, the final step to making it visible is
  295. registering it with the BPF subsystem. Registration is done per BPF program
  296. type. An example is shown below::
  297. BTF_KFUNCS_START(bpf_task_set)
  298. BTF_ID_FLAGS(func, bpf_get_task_pid, KF_ACQUIRE | KF_RET_NULL)
  299. BTF_ID_FLAGS(func, bpf_put_pid, KF_RELEASE)
  300. BTF_KFUNCS_END(bpf_task_set)
  301. static const struct btf_kfunc_id_set bpf_task_kfunc_set = {
  302. .owner = THIS_MODULE,
  303. .set = &bpf_task_set,
  304. };
  305. static int init_subsystem(void)
  306. {
  307. return register_btf_kfunc_id_set(BPF_PROG_TYPE_TRACING, &bpf_task_kfunc_set);
  308. }
  309. late_initcall(init_subsystem);
  310. 2.7 Specifying no-cast aliases with ___init
  311. --------------------------------------------
  312. The verifier will always enforce that the BTF type of a pointer passed to a
  313. kfunc by a BPF program, matches the type of pointer specified in the kfunc
  314. definition. The verifier, does, however, allow types that are equivalent
  315. according to the C standard to be passed to the same kfunc arg, even if their
  316. BTF_IDs differ.
  317. For example, for the following type definition:
  318. .. code-block:: c
  319. struct bpf_cpumask {
  320. cpumask_t cpumask;
  321. refcount_t usage;
  322. };
  323. The verifier would allow a ``struct bpf_cpumask *`` to be passed to a kfunc
  324. taking a ``cpumask_t *`` (which is a typedef of ``struct cpumask *``). For
  325. instance, both ``struct cpumask *`` and ``struct bpf_cpmuask *`` can be passed
  326. to bpf_cpumask_test_cpu().
  327. In some cases, this type-aliasing behavior is not desired. ``struct
  328. nf_conn___init`` is one such example:
  329. .. code-block:: c
  330. struct nf_conn___init {
  331. struct nf_conn ct;
  332. };
  333. The C standard would consider these types to be equivalent, but it would not
  334. always be safe to pass either type to a trusted kfunc. ``struct
  335. nf_conn___init`` represents an allocated ``struct nf_conn`` object that has
  336. *not yet been initialized*, so it would therefore be unsafe to pass a ``struct
  337. nf_conn___init *`` to a kfunc that's expecting a fully initialized ``struct
  338. nf_conn *`` (e.g. ``bpf_ct_change_timeout()``).
  339. In order to accommodate such requirements, the verifier will enforce strict
  340. PTR_TO_BTF_ID type matching if two types have the exact same name, with one
  341. being suffixed with ``___init``.
  342. .. _BPF_kfunc_lifecycle_expectations:
  343. 3. kfunc lifecycle expectations
  344. ===============================
  345. kfuncs provide a kernel <-> kernel API, and thus are not bound by any of the
  346. strict stability restrictions associated with kernel <-> user UAPIs. This means
  347. they can be thought of as similar to EXPORT_SYMBOL_GPL, and can therefore be
  348. modified or removed by a maintainer of the subsystem they're defined in when
  349. it's deemed necessary.
  350. Like any other change to the kernel, maintainers will not change or remove a
  351. kfunc without having a reasonable justification. Whether or not they'll choose
  352. to change a kfunc will ultimately depend on a variety of factors, such as how
  353. widely used the kfunc is, how long the kfunc has been in the kernel, whether an
  354. alternative kfunc exists, what the norm is in terms of stability for the
  355. subsystem in question, and of course what the technical cost is of continuing
  356. to support the kfunc.
  357. There are several implications of this:
  358. a) kfuncs that are widely used or have been in the kernel for a long time will
  359. be more difficult to justify being changed or removed by a maintainer. In
  360. other words, kfuncs that are known to have a lot of users and provide
  361. significant value provide stronger incentives for maintainers to invest the
  362. time and complexity in supporting them. It is therefore important for
  363. developers that are using kfuncs in their BPF programs to communicate and
  364. explain how and why those kfuncs are being used, and to participate in
  365. discussions regarding those kfuncs when they occur upstream.
  366. b) Unlike regular kernel symbols marked with EXPORT_SYMBOL_GPL, BPF programs
  367. that call kfuncs are generally not part of the kernel tree. This means that
  368. refactoring cannot typically change callers in-place when a kfunc changes,
  369. as is done for e.g. an upstreamed driver being updated in place when a
  370. kernel symbol is changed.
  371. Unlike with regular kernel symbols, this is expected behavior for BPF
  372. symbols, and out-of-tree BPF programs that use kfuncs should be considered
  373. relevant to discussions and decisions around modifying and removing those
  374. kfuncs. The BPF community will take an active role in participating in
  375. upstream discussions when necessary to ensure that the perspectives of such
  376. users are taken into account.
  377. c) A kfunc will never have any hard stability guarantees. BPF APIs cannot and
  378. will not ever hard-block a change in the kernel purely for stability
  379. reasons. That being said, kfuncs are features that are meant to solve
  380. problems and provide value to users. The decision of whether to change or
  381. remove a kfunc is a multivariate technical decision that is made on a
  382. case-by-case basis, and which is informed by data points such as those
  383. mentioned above. It is expected that a kfunc being removed or changed with
  384. no warning will not be a common occurrence or take place without sound
  385. justification, but it is a possibility that must be accepted if one is to
  386. use kfuncs.
  387. 3.1 kfunc deprecation
  388. ---------------------
  389. As described above, while sometimes a maintainer may find that a kfunc must be
  390. changed or removed immediately to accommodate some changes in their subsystem,
  391. usually kfuncs will be able to accommodate a longer and more measured
  392. deprecation process. For example, if a new kfunc comes along which provides
  393. superior functionality to an existing kfunc, the existing kfunc may be
  394. deprecated for some period of time to allow users to migrate their BPF programs
  395. to use the new one. Or, if a kfunc has no known users, a decision may be made
  396. to remove the kfunc (without providing an alternative API) after some
  397. deprecation period so as to provide users with a window to notify the kfunc
  398. maintainer if it turns out that the kfunc is actually being used.
  399. It's expected that the common case will be that kfuncs will go through a
  400. deprecation period rather than being changed or removed without warning. As
  401. described in :ref:`KF_deprecated_flag`, the kfunc framework provides the
  402. KF_DEPRECATED flag to kfunc developers to signal to users that a kfunc has been
  403. deprecated. Once a kfunc has been marked with KF_DEPRECATED, the following
  404. procedure is followed for removal:
  405. 1. Any relevant information for deprecated kfuncs is documented in the kfunc's
  406. kernel docs. This documentation will typically include the kfunc's expected
  407. remaining lifespan, a recommendation for new functionality that can replace
  408. the usage of the deprecated function (or an explanation as to why no such
  409. replacement exists), etc.
  410. 2. The deprecated kfunc is kept in the kernel for some period of time after it
  411. was first marked as deprecated. This time period will be chosen on a
  412. case-by-case basis, and will typically depend on how widespread the use of
  413. the kfunc is, how long it has been in the kernel, and how hard it is to move
  414. to alternatives. This deprecation time period is "best effort", and as
  415. described :ref:`above<BPF_kfunc_lifecycle_expectations>`, circumstances may
  416. sometimes dictate that the kfunc be removed before the full intended
  417. deprecation period has elapsed.
  418. 3. After the deprecation period the kfunc will be removed. At this point, BPF
  419. programs calling the kfunc will be rejected by the verifier.
  420. 4. Core kfuncs
  421. ==============
  422. The BPF subsystem provides a number of "core" kfuncs that are potentially
  423. applicable to a wide variety of different possible use cases and programs.
  424. Those kfuncs are documented here.
  425. 4.1 struct task_struct * kfuncs
  426. -------------------------------
  427. There are a number of kfuncs that allow ``struct task_struct *`` objects to be
  428. used as kptrs:
  429. .. kernel-doc:: kernel/bpf/helpers.c
  430. :identifiers: bpf_task_acquire bpf_task_release
  431. These kfuncs are useful when you want to acquire or release a reference to a
  432. ``struct task_struct *`` that was passed as e.g. a tracepoint arg, or a
  433. struct_ops callback arg. For example:
  434. .. code-block:: c
  435. /**
  436. * A trivial example tracepoint program that shows how to
  437. * acquire and release a struct task_struct * pointer.
  438. */
  439. SEC("tp_btf/task_newtask")
  440. int BPF_PROG(task_acquire_release_example, struct task_struct *task, u64 clone_flags)
  441. {
  442. struct task_struct *acquired;
  443. acquired = bpf_task_acquire(task);
  444. if (acquired)
  445. /*
  446. * In a typical program you'd do something like store
  447. * the task in a map, and the map will automatically
  448. * release it later. Here, we release it manually.
  449. */
  450. bpf_task_release(acquired);
  451. return 0;
  452. }
  453. References acquired on ``struct task_struct *`` objects are RCU protected.
  454. Therefore, when in an RCU read region, you can obtain a pointer to a task
  455. embedded in a map value without having to acquire a reference:
  456. .. code-block:: c
  457. #define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
  458. private(TASK) static struct task_struct *global;
  459. /**
  460. * A trivial example showing how to access a task stored
  461. * in a map using RCU.
  462. */
  463. SEC("tp_btf/task_newtask")
  464. int BPF_PROG(task_rcu_read_example, struct task_struct *task, u64 clone_flags)
  465. {
  466. struct task_struct *local_copy;
  467. bpf_rcu_read_lock();
  468. local_copy = global;
  469. if (local_copy)
  470. /*
  471. * We could also pass local_copy to kfuncs or helper functions here,
  472. * as we're guaranteed that local_copy will be valid until we exit
  473. * the RCU read region below.
  474. */
  475. bpf_printk("Global task %s is valid", local_copy->comm);
  476. else
  477. bpf_printk("No global task found");
  478. bpf_rcu_read_unlock();
  479. /* At this point we can no longer reference local_copy. */
  480. return 0;
  481. }
  482. ----
  483. A BPF program can also look up a task from a pid. This can be useful if the
  484. caller doesn't have a trusted pointer to a ``struct task_struct *`` object that
  485. it can acquire a reference on with bpf_task_acquire().
  486. .. kernel-doc:: kernel/bpf/helpers.c
  487. :identifiers: bpf_task_from_pid
  488. Here is an example of it being used:
  489. .. code-block:: c
  490. SEC("tp_btf/task_newtask")
  491. int BPF_PROG(task_get_pid_example, struct task_struct *task, u64 clone_flags)
  492. {
  493. struct task_struct *lookup;
  494. lookup = bpf_task_from_pid(task->pid);
  495. if (!lookup)
  496. /* A task should always be found, as %task is a tracepoint arg. */
  497. return -ENOENT;
  498. if (lookup->pid != task->pid) {
  499. /* bpf_task_from_pid() looks up the task via its
  500. * globally-unique pid from the init_pid_ns. Thus,
  501. * the pid of the lookup task should always be the
  502. * same as the input task.
  503. */
  504. bpf_task_release(lookup);
  505. return -EINVAL;
  506. }
  507. /* bpf_task_from_pid() returns an acquired reference,
  508. * so it must be dropped before returning from the
  509. * tracepoint handler.
  510. */
  511. bpf_task_release(lookup);
  512. return 0;
  513. }
  514. 4.2 struct cgroup * kfuncs
  515. --------------------------
  516. ``struct cgroup *`` objects also have acquire and release functions:
  517. .. kernel-doc:: kernel/bpf/helpers.c
  518. :identifiers: bpf_cgroup_acquire bpf_cgroup_release
  519. These kfuncs are used in exactly the same manner as bpf_task_acquire() and
  520. bpf_task_release() respectively, so we won't provide examples for them.
  521. ----
  522. Other kfuncs available for interacting with ``struct cgroup *`` objects are
  523. bpf_cgroup_ancestor() and bpf_cgroup_from_id(), allowing callers to access
  524. the ancestor of a cgroup and find a cgroup by its ID, respectively. Both
  525. return a cgroup kptr.
  526. .. kernel-doc:: kernel/bpf/helpers.c
  527. :identifiers: bpf_cgroup_ancestor
  528. .. kernel-doc:: kernel/bpf/helpers.c
  529. :identifiers: bpf_cgroup_from_id
  530. Eventually, BPF should be updated to allow this to happen with a normal memory
  531. load in the program itself. This is currently not possible without more work in
  532. the verifier. bpf_cgroup_ancestor() can be used as follows:
  533. .. code-block:: c
  534. /**
  535. * Simple tracepoint example that illustrates how a cgroup's
  536. * ancestor can be accessed using bpf_cgroup_ancestor().
  537. */
  538. SEC("tp_btf/cgroup_mkdir")
  539. int BPF_PROG(cgrp_ancestor_example, struct cgroup *cgrp, const char *path)
  540. {
  541. struct cgroup *parent;
  542. /* The parent cgroup resides at the level before the current cgroup's level. */
  543. parent = bpf_cgroup_ancestor(cgrp, cgrp->level - 1);
  544. if (!parent)
  545. return -ENOENT;
  546. bpf_printk("Parent id is %d", parent->self.id);
  547. /* Return the parent cgroup that was acquired above. */
  548. bpf_cgroup_release(parent);
  549. return 0;
  550. }
  551. 4.3 struct cpumask * kfuncs
  552. ---------------------------
  553. BPF provides a set of kfuncs that can be used to query, allocate, mutate, and
  554. destroy struct cpumask * objects. Please refer to :ref:`cpumasks-header-label`
  555. for more details.