{
    "mode": "man",
    "parameter": "BPF-HELPERS",
    "section": "7",
    "url": "https://www.chedong.com/phpMan.php/man/BPF-HELPERS/7/json",
    "generated": "2026-05-30T07:11:45Z",
    "sections": {
        "NAME": {
            "content": "BPF-HELPERS - list of eBPF helper functions\n",
            "subsections": []
        },
        "DESCRIPTION": {
            "content": "The  extended  Berkeley  Packet  Filter  (eBPF)  subsystem  consists in programs written in a\npseudo-assembly language, then attached to one of the several kernel hooks and run  in  reac‐\ntion  of specific events. This framework differs from the older, \"classic\" BPF (or \"cBPF\") in\nseveral aspects, one of them being the ability to call special functions (or \"helpers\")  from\nwithin  a  program.  These functions are restricted to a white-list of helpers defined in the\nkernel.\n\nThese helpers are used by eBPF programs to interact with the system, or with the  context  in\nwhich  they work. For instance, they can be used to print debugging messages, to get the time\nsince the system was booted, to interact with eBPF maps, or to  manipulate  network  packets.\nSince  there  are  several  eBPF program types, and that they do not run in the same context,\neach program type can only call a subset of those helpers.\n\nDue to eBPF conventions, a helper can not have more than five arguments.\n\nInternally, eBPF programs call directly into the compiled helper functions without  requiring\nany foreign-function interface. As a result, calling helpers introduces no overhead, thus of‐\nfering excellent performance.\n\nThis document is an attempt to list and document the helpers available  to  eBPF  developers.\nThey are sorted by chronological order (the oldest helpers in the kernel at the top).\n",
            "subsections": []
        },
        "HELPERS": {
            "content": "void *bpfmaplookupelem(struct bpfmap *map, const void *key)\n\nDescription\nPerform a lookup in map for an entry associated to key.\n\nReturn Map value associated to key, or NULL if no entry was found.\n\nlong bpfmapupdateelem(struct bpfmap *map, const void *key, const void *value, u64 flags)\n\nDescription\nAdd or update the value of the entry associated to key in map with value. flags\nis one of:\n\nBPFNOEXIST\nThe entry for key must not exist in the map.\n\nBPFEXIST\nThe entry for key must already exist in the map.\n\nBPFANY\nNo condition on the existence of the entry for key.\n\nFlag value BPFNOEXIST cannot be used for maps of types  BPFMAPTYPEARRAY  or\nBPFMAPTYPEPERCPUARRAY  (all elements always exist), the helper would return\nan error.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfmapdeleteelem(struct bpfmap *map, const void *key)\n\nDescription\nDelete entry with key from map.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfproberead(void *dst, u32 size, const void *unsafeptr)\n\nDescription\nFor tracing programs, safely attempt to read size bytes from kernel  space  ad‐\ndress unsafeptr and store the data in dst.\n\nGenerally, use bpfprobereaduser() or bpfprobereadkernel() instead.\n\nReturn 0 on success, or a negative error in case of failure.\n\nu64 bpfktimegetns(void)\n\nDescription\nReturn  the  time  elapsed since system boot, in nanoseconds.  Does not include\ntime the system was suspended.  See: clockgettime(CLOCKMONOTONIC)\n\nReturn Current ktime.\n\nlong bpftraceprintk(const char *fmt, u32 fmtsize, ...)\n\nDescription\nThis helper is a \"printk()-like\" facility for debugging. It  prints  a  message\ndefined  by  format  fmt  (of  size  fmtsize)  to file /sys/kernel/debug/trac‐\ning/trace from DebugFS, if available. It can take up to  three  additional  u64\narguments  (as  an  eBPF  helpers,  the total number of arguments is limited to\nfive).\n\nEach time the helper is called, it appends a line to the trace.  Lines are dis‐\ncarded  while  /sys/kernel/debug/tracing/trace  is  open,  use  /sys/kernel/de‐\nbug/tracing/tracepipe to avoid this.  The format of the trace is customizable,\nand the exact output one will get depends on the options set in /sys/kernel/de‐\nbug/tracing/traceoptions (see also the README file under the same  directory).\nHowever, it usually defaults to something like:\n\ntelnet-470   [001] .N.. 419421.045894: 0x00000001: <formatted msg>\n\nIn the above:\n\n• telnet is the name of the current task.\n\n• 470 is the PID of the current task.\n\n• 001 is the CPU number on which the task is running.\n\n• In  .N..,  each character refers to a set of options (whether irqs are en‐\nabled, scheduling options, whether hard/softirqs  are  running,  level  of\npreemptdisabled  respectively).  N  means  that TIFNEEDRESCHED and PRE‐‐\nEMPTNEEDRESCHED are set.\n\n• 419421.045894 is a timestamp.\n\n• 0x00000001 is a fake value used by BPF for the instruction pointer  regis‐\nter.\n\n• <formatted msg> is the message formatted with fmt.\n\nThe  conversion  specifiers supported by fmt are similar, but more limited than\nfor printk(). They are %d, %i, %u, %x, %ld, %li, %lu, %lx,  %lld,  %lli,  %llu,\n%llx,  %p, %s. No modifier (size of field, padding with zeroes, etc.) is avail‐\nable, and the helper will return -EINVAL (but print nothing) if  it  encounters\nan unknown specifier.\n\nAlso,  note that bpftraceprintk() is slow, and should only be used for debug‐\nging purposes. For this reason, a notice  block  (spanning  several  lines)  is\nprinted  to kernel logs and states that the helper should not be used \"for pro‐\nduction use\" the first time this  helper  is  used  (or  more  precisely,  when\ntraceprintk()  buffers  are allocated). For passing values to user space, perf\nevents should be preferred.\n\nReturn The number of bytes written to the buffer, or a negative error in case of fail‐\nure.\n\nu32 bpfgetprandomu32(void)\n\nDescription\nGet a pseudo-random number.\n\nFrom  a security point of view, this helper uses its own pseudo-random internal\nstate, and cannot be used to infer the seed of other random  functions  in  the\nkernel.  However, it is essential to note that the generator used by the helper\nis not cryptographically secure.\n\nReturn A random 32-bit unsigned value.\n\nu32 bpfgetsmpprocessorid(void)\n\nDescription\nGet the SMP (symmetric multiprocessing) processor id. Note  that  all  programs\nrun  with  preemption disabled, which means that the SMP processor id is stable\nduring all the execution of the program.\n\nReturn The SMP id of the processor running the program.\n\nlong bpfskbstorebytes(struct skbuff *skb, u32 offset, const  void  *from,  u32  len,  u64\nflags)\n\nDescription\nStore len bytes from address from into the packet associated to skb, at offset.\nflags are a combination of BPFFRECOMPUTECSUM  (automatically  recompute  the\nchecksum for the packet after storing the bytes) and BPFFINVALIDATEHASH (set\nskb->hash, skb->swhash and skb->l4hash to 0).\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfl3csumreplace(struct skbuff *skb, u32 offset, u64 from, u64 to, u64 size)\n\nDescription\nRecompute the layer 3 (e.g. IP) checksum for the packet associated to skb. Com‐\nputation is incremental, so the helper must know the former value of the header\nfield  that was modified (from), the new value of this field (to), and the num‐\nber of bytes (2 or 4) for this field, stored in  size.   Alternatively,  it  is\npossible to store the difference between the previous and the new values of the\nheader field in to, by setting from and size to 0. For both methods, offset in‐\ndicates the location of the IP checksum within the packet.\n\nThis  helper  works  in combination with bpfcsumdiff(), which does not update\nthe checksum in-place, but offers more flexibility and can handle sizes  larger\nthan 2 or 4 for the checksum to update.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfl4csumreplace(struct skbuff *skb, u32 offset, u64 from, u64 to, u64 flags)\n\nDescription\nRecompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the  packet  associ‐\nated  to  skb.  Computation  is incremental, so the helper must know the former\nvalue of the header field that was modified (from), the new value of this field\n(to),  and  the  number  of bytes (2 or 4) for this field, stored on the lowest\nfour bits of flags. Alternatively, it is possible to store the  difference  be‐\ntween  the  previous  and  the new values of the header field in to, by setting\nfrom and the four lowest bits of flags to 0. For both methods, offset indicates\nthe  location  of the IP checksum within the packet. In addition to the size of\nthe field, flags can be added (bitwise OR) actual flags.  With  BPFFMARKMAN‐‐\nGLED0,  a  null checksum is left untouched (unless BPFFMARKENFORCE is added\nas well), and for updates resulting in a null checksum  the  value  is  set  to\nCSUMMANGLED0  instead.  Flag BPFFPSEUDOHDR indicates the checksum is to be\ncomputed against a pseudo-header.\n\nThis helper works in combination with bpfcsumdiff(), which  does  not  update\nthe  checksum in-place, but offers more flexibility and can handle sizes larger\nthan 2 or 4 for the checksum to update.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpftailcall(void *ctx, struct bpfmap *progarraymap, u32 index)\n\nDescription\nThis  special  helper  is  used to trigger a \"tail call\", or in other words, to\njump into another eBPF program. The same stack frame is  used  (but  values  on\nstack  and  in registers for the caller are not accessible to the callee). This\nmechanism allows for program chaining, either for raising the maximum number of\navailable  eBPF  instructions,  or  to  execute  given  programs in conditional\nblocks. For security reasons, there is an upper limit to the number of  succes‐\nsive tail calls that can be performed.\n\nUpon  call  of  this helper, the program attempts to jump into a program refer‐\nenced  at  index   index   in   progarraymap,   a   special   map   of   type\nBPFMAPTYPEPROGARRAY, and passes ctx, a pointer to the context.\n\nIf  the call succeeds, the kernel immediately runs the first instruction of the\nnew program. This is not a function call, and it never returns to the  previous\nprogram.  If the call fails, then the helper has no effect, and the caller con‐\ntinues to run its subsequent instructions. A call can fail if  the  destination\nprogram  for  the  jump does not exist (i.e. index is superior to the number of\nentries in progarraymap), or if the maximum number of  tail  calls  has  been\nreached  for this chain of programs. This limit is defined in the kernel by the\nmacro MAXTAILCALLCNT (not accessible to user space), which is currently  set\nto 32.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfcloneredirect(struct skbuff *skb, u32 ifindex, u64 flags)\n\nDescription\nClone  and redirect the packet associated to skb to another net device of index\nifindex. Both ingress and egress interfaces can be used  for  redirection.  The\nBPFFINGRESS  value  in flags is used to make the distinction (ingress path is\nselected if the flag is present, egress path otherwise).  This is the only flag\nsupported for now.\n\nIn  comparison with bpfredirect() helper, bpfcloneredirect() has the associ‐\nated cost of duplicating the packet buffer, but this can be executed out of the\neBPF  program.  Conversely, bpfredirect() is more efficient, but it is handled\nthrough an action code where the redirection happens only after the  eBPF  pro‐\ngram has returned.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nu64 bpfgetcurrentpidtgid(void)\n\nReturn A 64-bit integer containing the current tgid and pid, and created as such: cur‐\nrenttask->tgid << 32 | currenttask->pid.\n\nu64 bpfgetcurrentuidgid(void)\n\nReturn A  64-bit integer containing the current GID and UID, and created as such: cur‐\nrentgid << 32 | currentuid.\n\nlong bpfgetcurrentcomm(void *buf, u32 sizeofbuf)\n\nDescription\nCopy the comm attribute of the current task into buf of sizeofbuf.  The  comm\nattribute contains the name of the executable (excluding the path) for the cur‐\nrent task. The sizeofbuf must be strictly positive. On  success,  the  helper\nmakes  sure  that  the buf is NUL-terminated. On failure, it is filled with ze‐\nroes.\n\nReturn 0 on success, or a negative error in case of failure.\n\nu32 bpfgetcgroupclassid(struct skbuff *skb)\n\nDescription\nRetrieve the classid for the current task, i.e. for the netcls cgroup to which\nskb belongs.\n\nThis helper can be used on TC egress path, but not on ingress.\n\nThe  netcls  cgroup  provides  an  interface to tag network packets based on a\nuser-provided identifier for all traffic coming from the tasks belonging to the\nrelated  cgroup.  See also the related kernel documentation, available from the\nLinux sources in file Documentation/admin-guide/cgroup-v1/netcls.rst.\n\nThe Linux kernel has two versions for cgroups: there are cgroups v1 and cgroups\nv2.  Both  are available to users, who can use a mixture of them, but note that\nthe netcls cgroup is for cgroup v1 only. This makes it incompatible  with  BPF\nprograms  run  on cgroups, which is a cgroup-v2-only feature (a socket can only\nhold data for one version of cgroups at a time).\n\nThis helper is only  available  is  the  kernel  was  compiled  with  the  CON‐‐\nFIGCGROUPNETCLASSID configuration option set to \"y\" or to \"m\".\n\nReturn The classid, or 0 for the default unconfigured classid.\n\nlong bpfskbvlanpush(struct skbuff *skb, be16 vlanproto, u16 vlantci)\n\nDescription\nPush  a  vlantci  (VLAN tag control information) of protocol vlanproto to the\npacket associated to skb, then update the checksum. Note that if vlanproto  is\ndifferent   from   ETHP8021Q   and  ETHP8021AD,  it  is  considered  to  be\nETHP8021Q.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbvlanpop(struct skbuff *skb)\n\nDescription\nPop a VLAN header from the packet associated to skb.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbgettunnelkey(struct skbuff *skb, struct bpftunnelkey *key,  u32  size,  u64\nflags)\n\nDescription\nGet  tunnel  metadata.  This  helper  takes  a  pointer  key to an empty struct\nbpftunnelkey of size, that will be filled with tunnel metadata for the packet\nassociated to skb.  The flags can be set to BPFFTUNINFOIPV6, which indicates\nthat the tunnel is based on IPv6 protocol instead of IPv4.\n\nThe struct bpftunnelkey is an object that generalizes the  principal  parame‐\nters used by various tunneling protocols into a single struct. This way, it can\nbe used to easily make a decision based on the contents  of  the  encapsulation\nheader,  \"summarized\" in this struct. In particular, it holds the IP address of\nthe remote end (IPv4 or IPv6, depending on the  case)  in  key->remoteipv4  or\nkey->remoteipv6. Also, this struct exposes the key->tunnelid, which is gener‐\nally mapped to a VNI (Virtual Network Identifier), making it  programmable  to‐\ngether with the bpfskbsettunnelkey() helper.\n\nLet's  imagine  that the following code is part of a program attached to the TC\ningress interface, on one end of a GRE tunnel, and is supposed  to  filter  out\nall messages coming from remote ends with IPv4 address other than 10.0.0.1:\n\nint ret;\nstruct bpftunnelkey key = {};\n\nret = bpfskbgettunnelkey(skb, &key, sizeof(key), 0);\nif (ret < 0)\nreturn TCACTSHOT;     // drop packet\n\nif (key.remoteipv4 != 0x0a000001)\nreturn TCACTSHOT;     // drop packet\n\nreturn TCACTOK;               // accept packet\n\nThis interface can also be used with all encapsulation devices that can operate\nin \"collect metadata\" mode: instead of having one network device  per  specific\nconfiguration,  the \"collect metadata\" mode only requires a single device where\nthe configuration can be extracted from this helper.\n\nThis can be used together with various tunnels such as VXLan, Geneve, GRE or IP\nin IP (IPIP).\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong  bpfskbsettunnelkey(struct  skbuff  *skb, struct bpftunnelkey *key, u32 size, u64\nflags)\n\nDescription\nPopulate tunnel metadata for packet associated to skb. The tunnel  metadata  is\nset  to  the contents of key, of size. The flags can be set to a combination of\nthe following values:\n\nBPFFTUNINFOIPV6\nIndicate that the tunnel is based on IPv6 protocol instead of IPv4.\n\nBPFFZEROCSUMTX\nFor IPv4 packets, add a flag to tunnel metadata indicating that checksum\ncomputation should be skipped and checksum set to zeroes.\n\nBPFFDONTFRAGMENT\nAdd  a  flag to tunnel metadata indicating that the packet should not be\nfragmented.\n\nBPFFSEQNUMBER\nAdd a flag to tunnel metadata indicating that a sequence  number  should\nbe added to tunnel header before sending the packet. This flag was added\nfor GRE encapsulation, but might be used with other protocols as well in\nthe future.\n\nHere is a typical usage on the transmit path:\n\nstruct bpftunnelkey key;\npopulate key ...\nbpfskbsettunnelkey(skb, &key, sizeof(key), 0);\nbpfcloneredirect(skb, vxlandevifindex, 0);\n\nSee  also the description of the bpfskbgettunnelkey() helper for additional\ninformation.\n\nReturn 0 on success, or a negative error in case of failure.\n\nu64 bpfperfeventread(struct bpfmap *map, u64 flags)\n\nDescription\nRead the value of a perf event counter. This helper relies on  a  map  of  type\nBPFMAPTYPEPERFEVENTARRAY. The nature of the perf event counter is selected\nwhen map is updated with perf event file descriptors. The map is an array whose\nsize  is  the number of available CPUs, and each cell contains a value relative\nto one CPU. The value to retrieve is indicated by flags, that contains the  in‐\ndex  of  the CPU to look up, masked with BPFFINDEXMASK. Alternatively, flags\ncan be set to BPFFCURRENTCPU to indicate that the value for the current  CPU\nshould be retrieved.\n\nNote that before Linux 4.13, only hardware perf event can be retrieved.\n\nAlso, be aware that the newer helper bpfperfeventreadvalue() is recommended\nover bpfperfeventread() in general. The latter has some ABI quirks where er‐\nror  and  counter  value  are used as a return code (which is wrong to do since\nranges may overlap). This  issue  is  fixed  with  bpfperfeventreadvalue(),\nwhich  at  the  same time provides more features over the bpfperfeventread()\ninterface. Please refer to the description of  bpfperfeventreadvalue()  for\ndetails.\n\nReturn The value of the perf event counter read from the map, or a negative error code\nin case of failure.\n\nlong bpfredirect(u32 ifindex, u64 flags)\n\nDescription\nRedirect the packet to another net device of index  ifindex.   This  helper  is\nsomewhat similar to bpfcloneredirect(), except that the packet is not cloned,\nwhich provides increased performance.\n\nExcept for XDP, both ingress and egress interfaces can be used for redirection.\nThe  BPFFINGRESS value in flags is used to make the distinction (ingress path\nis selected if the flag is present, egress path otherwise). Currently, XDP only\nsupports redirection to the egress interface, and accepts no flag at all.\n\nThe  same effect can also be attained with the more generic bpfredirectmap(),\nwhich uses a BPF map to store the redirect target instead of providing  it  di‐\nrectly to the helper.\n\nReturn For  XDP,  the  helper returns XDPREDIRECT on success or XDPABORTED on error.\nFor  other  program  types,  the  values  are  TCACTREDIRECT  on  success  or\nTCACTSHOT on error.\n\nu32 bpfgetrouterealm(struct skbuff *skb)\n\nDescription\nRetrieve  the realm or the route, that is to say the tclassid field of the des‐\ntination for the skb. The identifier retrieved is a user-provided tag,  similar\nto   the   one   used   with   the   netcls   cgroup   (see   description  for\nbpfgetcgroupclassid() helper), but here this tag is held by a route (a  des‐\ntination entry), not by a task.\n\nRetrieving  this  identifier  works  with  the  clsact TC egress hook (see also\ntc-bpf(8)), or alternatively on conventional classful egress qdiscs, but not on\nTC ingress path. In case of clsact TC egress hook, this has the advantage that,\ninternally, the destination entry has not been  dropped  yet  in  the  transmit\npath.  Therefore,  the  destination entry does not need to be artificially held\nvia netifkeepdst() for a classful qdisc until the skb is freed.\n\nThis  helper  is  available  only  if  the  kernel  was  compiled   with   CON‐‐\nFIGIPROUTECLASSID configuration option.\n\nReturn The  realm  of  the  route  for  the packet associated to skb, or 0 if none was\nfound.\n\nlong bpfperfeventoutput(void *ctx, struct bpfmap *map, u64 flags, void *data, u64 size)\n\nDescription\nWrite raw data blob into  a  special  BPF  perf  event  held  by  map  of  type\nBPFMAPTYPEPERFEVENTARRAY.  This  perf  event  must  have the following at‐\ntributes: PERFSAMPLERAW  as  sampletype,  PERFTYPESOFTWARE  as  type,  and\nPERFCOUNTSWBPFOUTPUT as config.\n\nThe  flags  are  used  to indicate the index in map for which the value must be\nput,  masked  with  BPFFINDEXMASK.   Alternatively,  flags  can  be  set  to\nBPFFCURRENTCPU  to indicate that the index of the current CPU core should be\nused.\n\nThe value to write, of size, is passed through eBPF stack and pointed by data.\n\nThe context of the program ctx needs also be passed to the helper.\n\nOn  user  space,  a  program  willing  to  read  the  values  needs   to   call\nperfeventopen()  on  the  perf  event (either for one or for all CPUs) and to\nstore the file descriptor into the map. This must be done before the eBPF  pro‐\ngram   can   send   data  into  it.  An  example  is  available  in  file  sam‐\nples/bpf/traceoutputuser.c in the Linux kernel source tree (the eBPF  program\ncounterpart is in samples/bpf/traceoutputkern.c).\n\nbpfperfeventoutput() achieves better performance than bpftraceprintk() for\nsharing data with user space, and is much better suitable  for  streaming  data\nfrom eBPF programs.\n\nNote  that  this  helper is not restricted to tracing use cases and can be used\nwith programs attached to TC or XDP as well, where it allows for  passing  data\nto user space listeners. Data can be:\n\n• Only custom structs,\n\n• Only the packet payload, or\n\n• A combination of both.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbloadbytes(const void *skb, u32 offset, void *to, u32 len)\n\nDescription\nThis  helper  was provided as an easy way to load data from a packet. It can be\nused to load len bytes from offset from the packet associated to skb, into  the\nbuffer pointed by to.\n\nSince  Linux  4.7,  usage  of  this  helper has mostly been replaced by \"direct\npacket access\", enabling packet data  to  be  manipulated  with  skb->data  and\nskb->dataend pointing respectively to the first byte of packet data and to the\nbyte after the last byte of packet data. However,  it  remains  useful  if  one\nwishes  to  read  large  quantities of data at once from a packet into the eBPF\nstack.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfgetstackid(void *ctx, struct bpfmap *map, u64 flags)\n\nDescription\nWalk a user or a kernel stack and return its id. To achieve  this,  the  helper\nneeds  ctx,  which  is a pointer to the context on which the tracing program is\nexecuted, and a pointer to a map of type BPFMAPTYPESTACKTRACE.\n\nThe last argument, flags, holds the number of stack frames to skip (from  0  to\n255),  masked  with  BPFFSKIPFIELDMASK.  The next bits can be used to set a\ncombination of the following flags:\n\nBPFFUSERSTACK\nCollect a user space stack instead of a kernel stack.\n\nBPFFFASTSTACKCMP\nCompare stacks by hash only.\n\nBPFFREUSESTACKID\nIf two different stacks hash into the same stackid, discard the old one.\n\nThe stack id retrieved is a 32 bit long integer handle  which  can  be  further\ncombined  with  other  data  (including other stack ids) and used as a key into\nmaps. This can be useful for generating a variety  of  graphs  (such  as  flame\ngraphs or off-cpu graphs).\n\nFor walking a stack, this helper is an improvement over bpfproberead(), which\ncan be used with unrolled loops but is not efficient and consumes a lot of eBPF\ninstructions.      Instead,     bpfgetstackid()    can    collect    up    to\nPERFMAXSTACKDEPTH both kernel and user frames. Note that this limit  can  be\ncontrolled with the sysctl program, and that it should be manually increased in\norder to profile long user stacks (such as stacks for Java programs). To do so,\nuse:\n\n# sysctl kernel.perfeventmaxstack=<new value>\n\nReturn The  positive or null stack id on success, or a negative error in case of fail‐\nure.\n\ns64 bpfcsumdiff(be32 *from, u32 fromsize, be32 *to, u32 tosize, wsum seed)\n\nDescription\nCompute a checksum difference, from the raw buffer pointed by from,  of  length\nfromsize (that must be a multiple of 4), towards the raw buffer pointed by to,\nof size tosize (same remark). An optional seed can be added to the value (this\ncan be cascaded, the seed may come from a previous call to the helper).\n\nThis is flexible enough to be used in several ways:\n\n• With  fromsize  ==  0,  tosize > 0 and seed set to checksum, it can be used\nwhen pushing new data.\n\n• With fromsize > 0, tosize == 0 and seed set to checksum,  it  can  be  used\nwhen removing data from a packet.\n\n• With  fromsize > 0, tosize > 0 and seed set to 0, it can be used to compute\na diff. Note that fromsize and tosize do not need to be equal.\n\nThis  helper  can  be  used  in  combination  with  bpfl3csumreplace()   and\nbpfl4csumreplace(),  to  which  one can feed in the difference computed with\nbpfcsumdiff().\n\nReturn The checksum result, or a negative error code in case of failure.\n\nlong bpfskbgettunnelopt(struct skbuff *skb, void *opt, u32 size)\n\nDescription\nRetrieve tunnel options metadata for the packet associated to  skb,  and  store\nthe raw tunnel option data to the buffer opt of size.\n\nThis helper can be used with encapsulation devices that can operate in \"collect\nmetadata\" mode (please  refer  to  the  related  note  in  the  description  of\nbpfskbgettunnelkey() for more details). A particular example where this can\nbe used is in combination with the Geneve encapsulation protocol, where it  al‐\nlows  for  pushing  (with bpfskbgettunnelopt() helper) and retrieving arbi‐\ntrary TLVs (Type-Length-Value headers) from the eBPF program. This  allows  for\nfull customization of these headers.\n\nReturn The size of the option data retrieved.\n\nlong bpfskbsettunnelopt(struct skbuff *skb, void *opt, u32 size)\n\nDescription\nSet tunnel options metadata for the packet associated to skb to the option data\ncontained in the raw buffer opt of size.\n\nSee also the description of the bpfskbgettunnelopt() helper for  additional\ninformation.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbchangeproto(struct skbuff *skb, be16 proto, u64 flags)\n\nDescription\nChange  the  protocol  of  the skb to proto. Currently supported are transition\nfrom IPv4 to IPv6, and from IPv6 to IPv4. The helper takes care of the  ground‐\nwork for the transition, including resizing the socket buffer. The eBPF program\nis expected to fill the new headers, if any, via skbstorebytes() and  to  re‐\ncompute the checksums with bpfl3csumreplace() and bpfl4csumreplace(). The\nmain case for this helper is to perform NAT64 operations out of  an  eBPF  pro‐\ngram.\n\nInternally,  the  GSO  type  is marked as dodgy so that headers are checked and\nsegments are recalculated by the GSO/GRO engine.  The size for  GSO  target  is\nadapted as well.\n\nAll values for flags are reserved for future usage, and must be left at zero.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbchangetype(struct skbuff *skb, u32 type)\n\nDescription\nChange the packet type for the packet associated to skb.  This  comes  down  to\nsetting  skb->pkttype  to  type, except the eBPF program does not have a write\naccess to skb->pkttype beside this helper. Using  a  helper  here  allows  for\ngraceful handling of errors.\n\nThe  major use case is to change incoming skb*s to PACKETHOST* in a program‐\nmatic way instead of having to recirculate  via  redirect(...,  BPFFINGRESS),\nfor example.\n\nNote that type only allows certain values. At this time, they are:\n\nPACKETHOST\nPacket is for us.\n\nPACKETBROADCAST\nSend packet to all.\n\nPACKETMULTICAST\nSend packet to group.\n\nPACKETOTHERHOST\nSend packet to someone else.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbundercgroup(struct skbuff *skb, struct bpfmap *map, u32 index)\n\nDescription\nCheck  whether  skb  is  a  descendant  of  the  cgroup2  held  by  map of type\nBPFMAPTYPECGROUPARRAY, at index.\n\nReturn The return value depends on the result of the test, and can be:\n\n• 0, if the skb failed the cgroup2 descendant test.\n\n• 1, if the skb succeeded the cgroup2 descendant test.\n\n• A negative error code, if an error occurred.\n\nu32 bpfgethashrecalc(struct skbuff *skb)\n\nDescription\nRetrieve the hash of the packet, skb->hash. If it is not set, in particular  if\nthe  hash  was  cleared due to mangling, recompute this hash. Later accesses to\nthe hash can be done directly with skb->hash.\n\nCalling   bpfsethashinvalid(),   changing   a    packet    prototype    with\nbpfskbchangeproto(), or calling bpfskbstorebytes() with the BPFFINVALI‐‐\nDATEHASH are actions susceptible to clear the hash and to trigger a new compu‐\ntation for the next call to bpfgethashrecalc().\n\nReturn The 32-bit hash.\n\nu64 bpfgetcurrenttask(void)\n\nReturn A pointer to the current task struct.\n\nlong bpfprobewriteuser(void *dst, const void *src, u32 len)\n\nDescription\nAttempt  in a safe way to write len bytes from the buffer src to dst in memory.\nIt only works for threads that are in user context, and dst  must  be  a  valid\nuser space address.\n\nThis  helper should not be used to implement any kind of security mechanism be‐\ncause of TOC-TOU attacks, but rather to debug, divert, and manipulate execution\nof semi-cooperative processes.\n\nKeep  in  mind that this feature is meant for experiments, and it has a risk of\ncrashing the system and running programs.  Therefore, when an eBPF program  us‐\ning  this  helper  is  attached,  a  warning  including PID and process name is\nprinted to kernel logs.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfcurrenttaskundercgroup(struct bpfmap *map, u32 index)\n\nDescription\nCheck whether the probe is being run is the context of a given  subset  of  the\ncgroup2   hierarchy.   The   cgroup2   to   test   is   held  by  map  of  type\nBPFMAPTYPECGROUPARRAY, at index.\n\nReturn The return value depends on the result of the test, and can be:\n\n• 0, if the skb task belongs to the cgroup2.\n\n• 1, if the skb task does not belong to the cgroup2.\n\n• A negative error code, if an error occurred.\n\nlong bpfskbchangetail(struct skbuff *skb, u32 len, u64 flags)\n\nDescription\nResize (trim or grow) the packet associated to skb to the new  len.  The  flags\nare reserved for future usage, and must be left at zero.\n\nThe  basic  idea is that the helper performs the needed work to change the size\nof the packet, then the  eBPF  program  rewrites  the  rest  via  helpers  like\nbpfskbstorebytes(), bpfl3csumreplace(), bpfl3csumreplace() and others.\nThis helper is a slow path utility intended for replies with control  messages.\nAnd  because  it  is targeted for slow path, the helper itself can afford to be\nslow: it implicitly linearizes, unclones and drops offloads from the skb.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbpulldata(struct skbuff *skb, u32 len)\n\nDescription\nPull  in  non-linear  data in case the skb is non-linear and not all of len are\npart of the linear section. Make len bytes from skb readable and writable. If a\nzero value is passed for len, then the whole length of the skb is pulled.\n\nThis helper is only needed for reading and writing with direct packet access.\n\nFor  direct  packet  access,  testing  that offsets to access are within packet\nboundaries (test on skb->dataend) is susceptible to fail if  offsets  are  in‐\nvalid,  or  if the requested data is in non-linear parts of the skb. On failure\nthe program can just bail out, or in the case of a  non-linear  buffer,  use  a\nhelper  to  make the data available. The bpfskbloadbytes() helper is a first\nsolution to access the data. Another one consists in using bpfskbpulldata to\npull  in  once  the  non-linear parts, then retesting and eventually access the\ndata.\n\nAt the same time, this also makes sure the skb is uncloned, which is  a  neces‐\nsary condition for direct write. As this needs to be an invariant for the write\npart only, the verifier detects writes and adds  a  prologue  that  is  calling\nbpfskbpulldata()  to  effectively unclone the skb from the very beginning in\ncase it is indeed cloned.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\ns64 bpfcsumupdate(struct skbuff *skb, wsum csum)\n\nDescription\nAdd the checksum csum into skb->csum in case the driver has supplied a checksum\nfor the entire packet into that field. Return an error otherwise.  This  helper\nis  intended to be used in combination with bpfcsumdiff(), in particular when\nthe checksum needs to be updated after data has been written  into  the  packet\nthrough direct packet access.\n\nReturn The checksum on success, or a negative error code in case of failure.\n\nvoid bpfsethashinvalid(struct skbuff *skb)\n\nDescription\nInvalidate  the  current  skb->hash.  It  can be used after mangling on headers\nthrough direct packet access, in order to indicate that the  hash  is  outdated\nand  to  trigger  a recalculation the next time the kernel tries to access this\nhash or when the bpfgethashrecalc() helper is called.\n\nlong bpfgetnumanodeid(void)\n\nDescription\nReturn the id of the current NUMA node. The primary use case for this helper is\nthe  selection of sockets for the local NUMA node, when the program is attached\nto sockets using the SOATTACHREUSEPORTEBPF option (see also socket(7)),  but\nthe  helper  is  also  available  to  other  eBPF  program  types, similarly to\nbpfgetsmpprocessorid().\n\nReturn The id of current NUMA node.\n\nlong bpfskbchangehead(struct skbuff *skb, u32 len, u64 flags)\n\nDescription\nGrows headroom of packet associated to skb and adjusts the offset  of  the  MAC\nheader accordingly, adding len bytes of space. It automatically extends and re‐\nallocates memory as required.\n\nThis helper can be used on a layer 3 skb to push a MAC header  for  redirection\ninto a layer 2 device.\n\nAll values for flags are reserved for future usage, and must be left at zero.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfxdpadjusthead(struct xdpbuff *xdpmd, int delta)\n\nDescription\nAdjust (move) xdpmd->data by delta bytes. Note that it is possible  to  use  a\nnegative  value  for  delta.  This helper can be used to prepare the packet for\npushing or popping headers.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfprobereadstr(void *dst, u32 size, const void *unsafeptr)\n\nDescription\nCopy  a  NUL terminated string from an unsafe kernel address unsafeptr to dst.\nSee bpfprobereadkernelstr() for more details.\n\nGenerally, use  bpfprobereaduserstr()  or  bpfprobereadkernelstr()  in‐\nstead.\n\nReturn On  success, the strictly positive length of the string, including the trailing\nNUL character. On error, a negative value.\n\nu64 bpfgetsocketcookie(struct skbuff *skb)\n\nDescription\nIf the struct skbuff pointed by skb has a known socket,  retrieve  the  cookie\n(generated  by the kernel) of this socket.  If no cookie has been set yet, gen‐\nerate a new cookie. Once generated, the socket cookie remains  stable  for  the\nlife  of  the  socket. This helper can be useful for monitoring per socket net‐\nworking traffic statistics as it provides a global socket identifier  that  can\nbe assumed unique.\n\nReturn A  8-byte  long  non-decreasing  number on success, or 0 if the socket field is\nmissing inside skb.\n\nu64 bpfgetsocketcookie(struct bpfsockaddr *ctx)\n\nDescription\nEquivalent to bpfgetsocketcookie() helper that accepts skb, but gets  socket\nfrom struct bpfsockaddr context.\n\nReturn A 8-byte long non-decreasing number.\n\nu64 bpfgetsocketcookie(struct bpfsockops *ctx)\n\nDescription\nEquivalent  to bpfgetsocketcookie() helper that accepts skb, but gets socket\nfrom struct bpfsockops context.\n\nReturn A 8-byte long non-decreasing number.\n\nu32 bpfgetsocketuid(struct skbuff *skb)\n\nReturn The owner UID of the socket associated to skb. If the socket is NULL, or if  it\nis  not  a full socket (i.e. if it is a time-wait or a request socket instead),\noverflowuid value is returned (note that overflowuid might also be  the  actual\nUID value for the socket).\n\nlong bpfsethash(struct skbuff *skb, u32 hash)\n\nDescription\nSet the full hash for skb (set the field skb->hash) to value hash.\n\nReturn 0\n\nlong bpfsetsockopt(void *bpfsocket, int level, int optname, void *optval, int optlen)\n\nDescription\nEmulate  a  call  to setsockopt() on the socket associated to bpfsocket, which\nmust be a full socket. The level at which the option resides and the name  opt‐\nname  of  the option must be specified, see setsockopt(2) for more information.\nThe option value of length optlen is pointed by optval.\n\nbpfsocket should be one of the following:\n\n• struct bpfsockops for BPFPROGTYPESOCKOPS.\n\n• struct bpfsockaddr for BPFCGROUPINET4CONNECT  and  BPFCGROUPINET6CON‐‐\nNECT.\n\nThis helper actually implements a subset of setsockopt().  It supports the fol‐\nlowing levels:\n\n• SOLSOCKET, which supports  the  following  optnames:  SORCVBUF,  SOSNDBUF,\nSOMAXPACINGRATE,   SOPRIORITY,   SORCVLOWAT,  SOMARK,  SOBINDTODEVICE,\nSOKEEPALIVE.\n\n• IPPROTOTCP,  which  supports   the   following   optnames:   TCPCONGESTION,\nTCPBPFIW, TCPBPFSNDCWNDCLAMP, TCPSAVESYN, TCPKEEPIDLE, TCPKEEPINTVL,\nTCPKEEPCNT, TCPSYNCNT, TCPUSERTIMEOUT.\n\n• IPPROTOIP, which supports optname IPTOS.\n\n• IPPROTOIPV6, which supports optname IPV6TCLASS.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfskbadjustroom(struct skbuff *skb, s32 lendiff, u32 mode, u64 flags)\n\nDescription\nGrow or shrink the room for data in the packet associated to skb  by  lendiff,\nand according to the selected mode.\n\nBy  default,  the helper will reset any offloaded checksum indicator of the skb\nto CHECKSUMNONE. This can be avoided by the following flag:\n\n• BPFFADJROOMNOCSUMRESET: Do not reset offloaded checksum data of the skb\nto CHECKSUMNONE.\n\nThere are two supported modes at this time:\n\n• BPFADJROOMMAC:  Adjust  room  at the mac layer (room space is added or re‐\nmoved below the layer 2 header).\n\n• BPFADJROOMNET: Adjust room at the network layer (room space  is  added  or\nremoved below the layer 3 header).\n\nThe following flags are supported at this time:\n\n• BPFFADJROOMFIXEDGSO:  Do not adjust gsosize.  Adjusting mss in this way\nis not allowed for datagrams.\n\n• BPFFADJROOMENCAPL3IPV4, BPFFADJROOMENCAPL3IPV6: Any new space  is\nreserved to hold a tunnel header.  Configure skb offsets and other fields ac‐\ncordingly.\n\n• BPFFADJROOMENCAPL4GRE, BPFFADJROOMENCAPL4UDP: Use  with  ENCAPL3\nflags to further specify the tunnel type.\n\n• BPFFADJROOMENCAPL2(len):  Use  with ENCAPL3/L4 flags to further specify\nthe tunnel type; len is the length of the inner MAC header.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfredirectmap(struct bpfmap *map, u32 key, u64 flags)\n\nDescription\nRedirect  the  packet to the endpoint referenced by map at index key. Depending\non its type, this map can contain references to  net  devices  (for  forwarding\npackets through other ports), or to CPUs (for redirecting XDP frames to another\nCPU; but this is only implemented for native XDP (with driver  support)  as  of\nthis writing).\n\nThe  lower  two  bits  of  flags  are used as the return code if the map lookup\nfails. This is so that the return value can be one of the  XDP  program  return\ncodes up to XDPTX, as chosen by the caller. Any higher bits in the flags argu‐\nment must be unset.\n\nSee also bpfredirect(), which only supports redirecting  to  an  ifindex,  but\ndoesn't require a map to do so.\n\nReturn XDPREDIRECT  on success, or the value of the two lower bits of the flags argu‐\nment on error.\n\nlong bpfskredirectmap(struct skbuff *skb, struct bpfmap *map, u32 key, u64 flags)\n\nDescription\nRedirect  the   packet   to   the   socket   referenced   by   map   (of   type\nBPFMAPTYPESOCKMAP)  at  index key. Both ingress and egress interfaces can be\nused for redirection. The BPFFINGRESS value in flags is used to make the dis‐\ntinction  (ingress  path is selected if the flag is present, egress path other‐\nwise). This is the only flag supported for now.\n\nReturn SKPASS on success, or SKDROP on error.\n\nlong bpfsockmapupdate(struct bpfsockops *skops, struct  bpfmap  *map,  void  *key,  u64\nflags)\n\nDescription\nAdd  an  entry  to, or update a map referencing sockets. The skops is used as a\nnew value for the entry associated to key. flags is one of:\n\nBPFNOEXIST\nThe entry for key must not exist in the map.\n\nBPFEXIST\nThe entry for key must already exist in the map.\n\nBPFANY\nNo condition on the existence of the entry for key.\n\nIf the map has eBPF programs (parser and verdict), those will be  inherited  by\nthe  socket  being  added.  If the socket is already attached to eBPF programs,\nthis results in an error.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfxdpadjustmeta(struct xdpbuff *xdpmd, int delta)\n\nDescription\nAdjust the address pointed by xdpmd->datameta by delta (which can be positive\nor  negative).  Note  that  this  operation  modifies  the  address  stored  in\nxdpmd->data, so the latter must be loaded  only  after  the  helper  has  been\ncalled.\n\nThe  use  of xdpmd->datameta is optional and programs are not required to use\nit. The rationale is that when the packet is processed with XDP  (e.g.  as  DoS\nfilter),  it is possible to push further meta data along with it before passing\nto the stack, and to give the guarantee that an ingress eBPF  program  attached\nas  a  TC  classifier on the same device can pick this up for further post-pro‐\ncessing. Since TC works with socket buffers, it remains possible  to  set  from\nXDP  the  mark  or  priority pointers, or other pointers for the socket buffer.\nHaving this scratch space generic and programmable allows for more  flexibility\nas the user is free to store whatever meta data they need.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfperfeventreadvalue(struct bpfmap *map, u64  flags,  struct  bpfperfeventvalue\n*buf, u32 bufsize)\n\nDescription\nRead the value of a perf event counter, and store it into buf of size bufsize.\nThis helper relies on a map of type BPFMAPTYPEPERFEVENTARRAY.  The  nature\nof  the perf event counter is selected when map is updated with perf event file\ndescriptors. The map is an array whose size is the number  of  available  CPUs,\nand  each  cell  contains a value relative to one CPU. The value to retrieve is\nindicated by flags, that contains the index of the CPU to look up, masked  with\nBPFFINDEXMASK. Alternatively, flags can be set to BPFFCURRENTCPU to indi‐\ncate that the value for the current CPU should be retrieved.\n\nThis helper behaves in a way close to bpfperfeventread() helper,  save  that\ninstead  of just returning the value observed, it fills the buf structure. This\nallows for additional data to be retrieved: in particular, the enabled and run‐\nning times (in buf->enabled and buf->running, respectively) are copied. In gen‐\neral, bpfperfeventreadvalue() is  recommended  over  bpfperfeventread(),\nwhich has some ABI issues and provides fewer functionalities.\n\nThese  values  are  interesting,  because  hardware PMU (Performance Monitoring\nUnit) counters are limited resources. When there are more PMU based perf events\nopened  than  available  counters,  kernel  will multiplex these events so each\nevent gets certain percentage (but not all) of the PMU time. In case that  mul‐\ntiplexing  happens, the number of samples or counter value will not reflect the\ncase compared to when no multiplexing occurs.  This  makes  comparison  between\ndifferent  runs  difficult.   Typically, the counter value should be normalized\nbefore comparing to other experiments. The usual normalization is done as  fol‐\nlows.\n\nnormalizedcounter = counter * tenabled / trunning\n\nWhere tenabled is the time enabled for event and trunning is the time running\nfor event since last normalization. The enabled and running times  are  accumu‐\nlated  since the perf event open. To achieve scaling factor between two invoca‐\ntions of an eBPF program, users can use CPU id as the key (which is typical for\nperf  array  usage model) to remember the previous value and do the calculation\ninside the eBPF program.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfperfprogreadvalue(struct bpfperfeventdata  *ctx,  struct  bpfperfeventvalue\n*buf, u32 bufsize)\n\nDescription\nFor  en  eBPF program attached to a perf event, retrieve the value of the event\ncounter associated to ctx and store it in the structure pointed by buf  and  of\nsize  bufsize. Enabled and running times are also stored in the structure (see\ndescription of helper bpfperfeventreadvalue() for more details).\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfgetsockopt(void *bpfsocket, int level, int optname, void *optval, int optlen)\n\nDescription\nEmulate a call to getsockopt() on the socket associated  to  bpfsocket,  which\nmust  be a full socket. The level at which the option resides and the name opt‐\nname of the option must be specified, see getsockopt(2) for  more  information.\nThe  retrieved  value is stored in the structure pointed by opval and of length\noptlen.\n\nbpfsocket should be one of the following:\n\n• struct bpfsockops for BPFPROGTYPESOCKOPS.\n\n• struct bpfsockaddr for BPFCGROUPINET4CONNECT  and  BPFCGROUPINET6CON‐‐\nNECT.\n\nThis helper actually implements a subset of getsockopt().  It supports the fol‐\nlowing levels:\n\n• IPPROTOTCP, which supports optname TCPCONGESTION.\n\n• IPPROTOIP, which supports optname IPTOS.\n\n• IPPROTOIPV6, which supports optname IPV6TCLASS.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfoverridereturn(struct ptregs *regs, u64 rc)\n\nDescription\nUsed for error injection, this helper uses kprobes to override the return value\nof the probed function, and to set it to rc.  The first argument is the context\nregs on which the kprobe works.\n\nThis helper works by setting the PC (program counter) to an  override  function\nwhich  is  run  in place of the original probed function. This means the probed\nfunction is not run at all. The replacement function just returns with the  re‐\nquired value.\n\nThis  helper has security implications, and thus is subject to restrictions. It\nis only available if the kernel was compiled with  the  CONFIGBPFKPROBEOVER‐‐\nRIDE  configuration  option, and in this case it only works on functions tagged\nwith ALLOWERRORINJECTION in the kernel code.\n\nAlso, the helper is only  available  for  the  architectures  having  the  CON‐\nFIGFUNCTIONERRORINJECTION  option.  As  of this writing, x86 architecture is\nthe only one to support this feature.\n\nReturn 0\n\nlong bpfsockopscbflagsset(struct bpfsockops *bpfsock, int argval)\n\nDescription\nAttempt to set the value of the bpfsockopscbflags field for  the  full  TCP\nsocket associated to bpfsockops to argval.\n\nThe  primary use of this field is to determine if there should be calls to eBPF\nprograms of type BPFPROGTYPESOCKOPS at various points in the  TCP  code.  A\nprogram of the same type can change its value, per connection and as necessary,\nwhen the connection is established. This field is directly accessible for read‐\ning, but this helper must be used for updates in order to return an error if an\neBPF program tries to set a callback that is not supported in the current  ker‐\nnel.\n\nargval is a flag array which can combine these flags:\n\n• BPFSOCKOPSRTOCBFLAG (retransmission time out)\n\n• BPFSOCKOPSRETRANSCBFLAG (retransmission)\n\n• BPFSOCKOPSSTATECBFLAG (TCP state change)\n\n• BPFSOCKOPSRTTCBFLAG (every RTT)\n\nTherefore,  this  function  can be used to clear a callback flag by setting the\nappropriate bit to zero. e.g. to disable the RTO callback:\n\nbpfsockopscbflagsset(bpfsock,\nbpfsock->bpfsockopscbflags & ~BPFSOCKOPSRTOCBFLAG)\n\nHere are some examples of where one could call such eBPF program:\n\n• When RTO fires.\n\n• When a packet is retransmitted.\n\n• When the connection terminates.\n\n• When a packet is sent.\n\n• When a packet is received.\n\nReturn Code -EINVAL if the socket is not a full TCP socket; otherwise, a positive num‐\nber  containing the bits that could not be set is returned (which comes down to\n0 if all bits were set as required).\n\nlong bpfmsgredirectmap(struct skmsgbuff *msg, struct bpfmap *map, u32 key, u64 flags)\n\nDescription\nThis helper is used in programs implementing policies at the socket  level.  If\nthe  message  msg  is allowed to pass (i.e. if the verdict eBPF program returns\nSKPASS),  redirect  it  to   the   socket   referenced   by   map   (of   type\nBPFMAPTYPESOCKMAP)  at  index key. Both ingress and egress interfaces can be\nused for redirection. The BPFFINGRESS value in flags is used to make the dis‐\ntinction  (ingress  path is selected if the flag is present, egress path other‐\nwise). This is the only flag supported for now.\n\nReturn SKPASS on success, or SKDROP on error.\n\nlong bpfmsgapplybytes(struct skmsgbuff *msg, u32 bytes)\n\nDescription\nFor socket policies, apply the verdict of the eBPF program to  the  next  bytes\n(number of bytes) of message msg.\n\nFor example, this helper can be used in the following cases:\n\n• A  single  sendmsg() or sendfile() system call contains multiple logical mes‐\nsages that the eBPF program is supposed to read and for which it should apply\na verdict.\n\n• An  eBPF  program only cares to read the first bytes of a msg. If the message\nhas a large payload, then setting up and calling the eBPF program  repeatedly\nfor  all bytes, even though the verdict is already known, would create unnec‐\nessary overhead.\n\nWhen called from within an eBPF program, the helper sets a counter internal  to\nthe  BPF  infrastructure,  that  is  used to apply the last verdict to the next\nbytes. If bytes is smaller  than  the  current  data  being  processed  from  a\nsendmsg()  or sendfile() system call, the first bytes will be sent and the eBPF\nprogram will be re-run with the pointer for start of data pointing to byte num‐\nber  bytes  + 1. If bytes is larger than the current data being processed, then\nthe eBPF verdict will be applied to multiple sendmsg() or sendfile() calls  un‐\ntil bytes are consumed.\n\nNote  that  if  a  socket  closes  with the internal counter holding a non-zero\nvalue, this is not a problem because data is not being buffered for  bytes  and\nis sent as it is received.\n\nReturn 0\n\nlong bpfmsgcorkbytes(struct skmsgbuff *msg, u32 bytes)\n\nDescription\nFor socket policies, prevent the execution of the verdict eBPF program for mes‐\nsage msg until bytes (byte number) have been accumulated.\n\nThis can be used when one needs a specific number of bytes before a verdict can\nbe assigned, even if the data spans multiple sendmsg() or sendfile() calls. The\nextreme case would be a user calling sendmsg() repeatedly with 1-byte long mes‐\nsage  segments.  Obviously, this is bad for performance, but it is still valid.\nIf the eBPF program needs bytes bytes to validate a header, this helper can  be\nused to prevent the eBPF program to be called again until bytes have been accu‐\nmulated.\n\nReturn 0\n\nlong bpfmsgpulldata(struct skmsgbuff *msg, u32 start, u32 end, u64 flags)\n\nDescription\nFor socket policies, pull in non-linear data from user space for  msg  and  set\npointers  msg->data  and msg->dataend to start and end bytes offsets into msg,\nrespectively.\n\nIf a program of type BPFPROGTYPESKMSG is run on a msg  it  can  only  parse\ndata  that  the  (data, dataend) pointers have already consumed. For sendmsg()\nhooks this is likely the first scatterlist element. But for  calls  relying  on\nthe  sendpage  handler  (e.g. sendfile()) this will be the range (0, 0) because\nthe data is shared with user space and by default the objective is to avoid al‐\nlowing  user  space  to  modify data while (or after) eBPF verdict is being de‐\ncided. This helper can be used to pull in data and to set  the  start  and  end\npointer to given values. Data will be copied if necessary (i.e. if data was not\nlinear and if start and end pointers do not point to the same chunk).\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nAll values for flags are reserved for future usage, and must be left at zero.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfbind(struct bpfsockaddr *ctx, struct sockaddr *addr, int addrlen)\n\nDescription\nBind  the  socket  associated  to ctx to the address pointed by addr, of length\naddrlen. This allows for making outgoing connection from the  desired  IP  ad‐\ndress,  which  can  be  useful  for  example when all processes inside a cgroup\nshould use one single IP address on a host that has multiple IP configured.\n\nThis helper  works  for  IPv4  and  IPv6,  TCP  and  UDP  sockets.  The  domain\n(addr->safamily) must be AFINET (or AFINET6). It's advised to pass zero port\n(sinport or sin6port) which  triggers  IPBINDADDRESSNOPORT-like  behavior\nand  lets  the  kernel efficiently pick up an unused port as long as 4-tuple is\nunique. Passing non-zero port might lead to degraded performance.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfxdpadjusttail(struct xdpbuff *xdpmd, int delta)\n\nDescription\nAdjust (move) xdpmd->dataend by delta bytes. It is possible  to  both  shrink\nand grow the packet tail.  Shrink done via delta being a negative integer.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong  bpfskbgetxfrmstate(struct  skbuff   *skb,   u32   index,   struct   bpfxfrmstate\n*xfrmstate, u32 size, u64 flags)\n\nDescription\nRetrieve  the XFRM state (IP transform framework, see also ip-xfrm(8)) at index\nin XFRM \"security path\" for skb.\n\nThe  retrieved  value  is  stored  in  the  struct  bpfxfrmstate  pointed  by\nxfrmstate and of length size.\n\nAll values for flags are reserved for future usage, and must be left at zero.\n\nThis  helper is available only if the kernel was compiled with CONFIGXFRM con‐\nfiguration option.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfgetstack(void *ctx, void *buf, u32 size, u64 flags)\n\nDescription\nReturn a user or a kernel stack in bpf program  provided  buffer.   To  achieve\nthis,  the  helper  needs  ctx,  which is a pointer to the context on which the\ntracing program is executed.  To store the stacktrace, the bpf program provides\nbuf with a nonnegative size.\n\nThe  last  argument, flags, holds the number of stack frames to skip (from 0 to\n255), masked with BPFFSKIPFIELDMASK. The next bits can be used to  set  the\nfollowing flags:\n\nBPFFUSERSTACK\nCollect a user space stack instead of a kernel stack.\n\nBPFFUSERBUILDID\nCollect  buildid+offset  instead  of  ips  for user stack, only valid if\nBPFFUSERSTACK is also specified.\n\nbpfgetstack() can collect up to PERFMAXSTACKDEPTH  both  kernel  and  user\nframes,  subject  to  sufficient large buffer size. Note that this limit can be\ncontrolled with the sysctl program, and that it should be manually increased in\norder to profile long user stacks (such as stacks for Java programs). To do so,\nuse:\n\n# sysctl kernel.perfeventmaxstack=<new value>\n\nReturn A non-negative value equal to or less than size on success, or a negative error\nin case of failure.\n\nlong  bpfskbloadbytesrelative(const  void  *skb,  u32  offset,  void  *to,  u32  len, u32\nstartheader)\n\nDescription\nThis helper is similar to bpfskbloadbytes() in that it provides an easy  way\nto  load len bytes from offset from the packet associated to skb, into the buf‐\nfer pointed by to. The difference to bpfskbloadbytes() is that a fifth argu‐\nment  startheader  exists  in  order  to  select  a base offset to start from.\nstartheader can be one of:\n\nBPFHDRSTARTMAC\nBase offset to load data from is skb's mac header.\n\nBPFHDRSTARTNET\nBase offset to load data from is skb's network header.\n\nIn general, \"direct packet access\" is the preferred  method  to  access  packet\ndata,  however,  this  helper  is  in particular useful in socket filters where\nskb->data does not always point to the start of the mac header and  where  \"di‐\nrect packet access\" is not available.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpffiblookup(void *ctx, struct bpffiblookup *params, int plen, u32 flags)\n\nDescription\nDo  FIB  lookup in kernel tables using parameters in params.  If lookup is suc‐\ncessful and result shows packet is to be forwarded,  the  neighbor  tables  are\nsearched  for the nexthop.  If successful (ie., FIB lookup shows forwarding and\nnexthop is resolved), the nexthop address is returned in ipv4dst  or  ipv6dst\nbased  on  family,  smac is set to mac address of egress device, dmac is set to\nnexthop mac address, rtmetric is set to metric from  route  (IPv4/IPv6  only),\nand ifindex is set to the device index of the nexthop from the FIB lookup.\n\nplen  argument  is  the  size of the passed in struct.  flags argument can be a\ncombination of one or more of the following values:\n\nBPFFIBLOOKUPDIRECT\nDo a direct table lookup vs full lookup using FIB rules.\n\nBPFFIBLOOKUPOUTPUT\nPerform lookup from an egress perspective (default is ingress).\n\nctx is either struct xdpmd for XDP programs or struct skbuff tc clsact  pro‐\ngrams.\n\nReturn\n\n• < 0 if any input argument is invalid\n\n• 0 on success (packet is forwarded, nexthop neighbor exists)\n\n• > 0 one of BPFFIBLKUPRET codes explaining why the packet is not forwarded\nor needs assist from full stack\n\nlong bpfsockhashupdate(struct bpfsockops *skops, struct bpfmap  *map,  void  *key,  u64\nflags)\n\nDescription\nAdd  an  entry  to, or update a sockhash map referencing sockets.  The skops is\nused as a new value for the entry associated to key. flags is one of:\n\nBPFNOEXIST\nThe entry for key must not exist in the map.\n\nBPFEXIST\nThe entry for key must already exist in the map.\n\nBPFANY\nNo condition on the existence of the entry for key.\n\nIf the map has eBPF programs (parser and verdict), those will be  inherited  by\nthe  socket  being  added.  If the socket is already attached to eBPF programs,\nthis results in an error.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfmsgredirecthash(struct skmsgbuff *msg,  struct  bpfmap  *map,  void  *key,  u64\nflags)\n\nDescription\nThis  helper  is used in programs implementing policies at the socket level. If\nthe message msg is allowed to pass (i.e. if the verdict  eBPF  program  returns\nSKPASS),   redirect   it   to   the   socket   referenced   by  map  (of  type\nBPFMAPTYPESOCKHASH) using hash key. Both ingress and egress  interfaces  can\nbe  used  for redirection. The BPFFINGRESS value in flags is used to make the\ndistinction (ingress path is selected if the flag is present, egress path  oth‐\nerwise). This is the only flag supported for now.\n\nReturn SKPASS on success, or SKDROP on error.\n\nlong bpfskredirecthash(struct skbuff *skb, struct bpfmap *map, void *key, u64 flags)\n\nDescription\nThis  helper is used in programs implementing policies at the skb socket level.\nIf the skbuff skb is allowed to pass (i.e.  if the verdict  eBPF  program  re‐\nturns  SKPASS),  redirect  it  to  the  socket  referenced  by  map  (of  type\nBPFMAPTYPESOCKHASH) using hash key. Both ingress and egress  interfaces  can\nbe  used  for redirection. The BPFFINGRESS value in flags is used to make the\ndistinction (ingress path is selected if the flag  is  present,  egress  other‐\nwise). This is the only flag supported for now.\n\nReturn SKPASS on success, or SKDROP on error.\n\nlong bpflwtpushencap(struct skbuff *skb, u32 type, void *hdr, u32 len)\n\nDescription\nEncapsulate the packet associated to skb within a Layer 3 protocol header. This\nheader is provided in the buffer at address hdr, with len its  size  in  bytes.\ntype indicates the protocol of the header and can be one of:\n\nBPFLWTENCAPSEG6\nIPv6 encapsulation with Segment Routing Header (struct ipv6srhdr). hdr\nonly contains the SRH, the IPv6 header is computed by the kernel.\n\nBPFLWTENCAPSEG6INLINE\nOnly works if skb contains an IPv6  packet.  Insert  a  Segment  Routing\nHeader (struct ipv6srhdr) inside the IPv6 header.\n\nBPFLWTENCAPIP\nIP  encapsulation  (GRE/GUE/IPIP/etc).  The outer header must be IPv4 or\nIPv6,  followed  by   zero   or   more   additional   headers,   up   to\nLWTBPFMAXHEADROOM  total  bytes in all prepended headers. Please note\nthat if skbisgso(skb) is  true,  no  more  than  two  headers  can  be\nprepended,  and  the  inner  header, if present, should be either GRE or\nUDP/GUE.\n\nBPFLWTENCAPSEG6*  types  can   be   called   by   BPF   programs   of   type\nBPFPROGTYPELWTIN;  BPFLWTENCAPIP  type  can be called by bpf programs of\ntypes BPFPROGTYPELWTIN and BPFPROGTYPELWTXMIT.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpflwtseg6storebytes(struct skbuff *skb, u32 offset, const void *from, u32 len)\n\nDescription\nStore len bytes from address from into the packet associated to skb, at offset.\nOnly the flags, tag and TLVs inside the outermost IPv6 Segment  Routing  Header\ncan be modified through this helper.\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpflwtseg6adjustsrh(struct skbuff *skb, u32 offset, s32 delta)\n\nDescription\nAdjust the size allocated to TLVs in the outermost IPv6 Segment Routing  Header\ncontained  in  the packet associated to skb, at position offset by delta bytes.\nOnly offsets after the segments are accepted. delta can  be  as  well  positive\n(growing) as negative (shrinking).\n\nA  call  to  this helper is susceptible to change the underlying packet buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare  invalidated and must be performed again, if the helper is used in combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpflwtseg6action(struct skbuff *skb, u32 action, void *param, u32 paramlen)\n\nDescription\nApply an IPv6 Segment Routing action of type action to the packet associated to\nskb.  Each  action  takes a parameter contained at address param, and of length\nparamlen bytes.  action can be one of:\n\nSEG6LOCALACTIONENDX\nEnd.X action: Endpoint  with  Layer-3  cross-connect.   Type  of  param:\nstruct in6addr.\n\nSEG6LOCALACTIONENDT\nEnd.T  action: Endpoint with specific IPv6 table lookup.  Type of param:\nint.\n\nSEG6LOCALACTIONENDB6\nEnd.B6 action: Endpoint bound to an SRv6 policy.  Type of param:  struct\nipv6srhdr.\n\nSEG6LOCALACTIONENDB6ENCAP\nEnd.B6.Encap  action:  Endpoint  bound  to an SRv6 encapsulation policy.\nType of param: struct ipv6srhdr.\n\nA call to this helper is susceptible to change the  underlying  packet  buffer.\nTherefore, at load time, all checks on pointers previously done by the verifier\nare invalidated and must be performed again, if the helper is used in  combina‐\ntion with direct packet access.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfrcrepeat(void *ctx)\n\nDescription\nThis  helper is used in programs implementing IR decoding, to report a success‐\nfully decoded repeat key message. This delays the generation of a key up  event\nfor previously generated key down event.\n\nSome IR protocols like NEC have a special IR message for repeating last button,\nfor when a button is held down.\n\nThe ctx should point to the lirc sample as passed into the program.\n\nThis helper is only  available  is  the  kernel  was  compiled  with  the  CON‐‐\nFIGBPFLIRCMODE2 configuration option set to \"y\".\n\nReturn 0\n\nlong bpfrckeydown(void *ctx, u32 protocol, u64 scancode, u32 toggle)\n\nDescription\nThis  helper is used in programs implementing IR decoding, to report a success‐\nfully decoded key press with scancode, toggle value in the given protocol.  The\nscancode  will  be translated to a keycode using the rc keymap, and reported as\nan input key down event. After a period a key up event is generated.  This  pe‐\nriod  can  be  extended  by calling either bpfrckeydown() again with the same\nvalues, or calling bpfrcrepeat().\n\nSome protocols include a toggle bit,  in  case  the  button  was  released  and\npressed again between consecutive scancodes.\n\nThe ctx should point to the lirc sample as passed into the program.\n\nThe  protocol is the decoded protocol number (see enum rcproto for some prede‐\nfined values).\n\nThis helper is only  available  is  the  kernel  was  compiled  with  the  CON‐‐\nFIGBPFLIRCMODE2 configuration option set to \"y\".\n\nReturn 0\n\nu64 bpfskbcgroupid(struct skbuff *skb)\n\nDescription\nReturn the cgroup v2 id of the socket associated with the skb.  This is roughly\nsimilar to the bpfgetcgroupclassid() helper for cgroup v1 by providing a tag\nresp.  identifier that can be matched on or used for map lookups e.g. to imple‐\nment policy. The cgroup v2 id of a given path in the hierarchy  is  exposed  in\nuser space through the fhandle API in order to get to the same 64-bit id.\n\nThis helper can be used on TC egress path, but not on ingress, and is available\nonly if the kernel was compiled with the CONFIGSOCKCGROUPDATA  configuration\noption.\n\nReturn The id is returned or 0 in case the id could not be retrieved.\n\nu64 bpfgetcurrentcgroupid(void)\n\nReturn A  64-bit  integer  containing the current cgroup id based on the cgroup within\nwhich the current task is running.\n\nvoid *bpfgetlocalstorage(void *map, u64 flags)\n\nDescription\nGet the pointer to the local storage area.  The type and the size of the  local\nstorage is defined by the map argument.  The flags meaning is specific for each\nmap type, and has to be 0 for cgroup local storage.\n\nDepending on the BPF program type, a local storage area can be  shared  between\nmultiple instances of the BPF program, running simultaneously.\n\nA user should care about the synchronization by himself.  For example, by using\nthe BPFSTXXADD instruction to alter the shared data.\n\nReturn A pointer to the local storage area.\n\nlong bpfskselectreuseport(struct skreuseportmd *reuse, struct bpfmap *map,  void  *key,\nu64 flags)\n\nDescription\nSelect  a  SOREUSEPORT  socket  from  a  BPFMAPTYPEREUSEPORTARRAY map.  It\nchecks the selected socket is matching the incoming request in the socket  buf‐\nfer.\n\nReturn 0 on success, or a negative error in case of failure.\n\nu64 bpfskbancestorcgroupid(struct skbuff *skb, int ancestorlevel)\n\nDescription\nReturn  id  of  cgroup v2 that is ancestor of cgroup associated with the skb at\nthe ancestorlevel.  The root cgroup is at ancestorlevel zero  and  each  step\ndown  the  hierarchy increments the level. If ancestorlevel == level of cgroup\nassociated  with  skb,  then  return  value   will   be   same   as   that   of\nbpfskbcgroupid().\n\nThe  helper  is useful to implement policies based on cgroups that are upper in\nhierarchy than immediate cgroup associated with skb.\n\nThe  format  of  returned  id  and  helper   limitations   are   same   as   in\nbpfskbcgroupid().\n\nReturn The id is returned or 0 in case the id could not be retrieved.\n\nstruct  bpfsock  *bpfsklookuptcp(void *ctx, struct bpfsocktuple *tuple, u32 tuplesize,\nu64 netns, u64 flags)\n\nDescription\nLook for TCP socket matching tuple, optionally in  a  child  network  namespace\nnetns.  The  return  value  must  be  checked,  and  if  non-NULL, released via\nbpfskrelease().\n\nThe ctx should point to the context of the program, such as the skb  or  socket\n(depending  on  the  hook  in  use). This is used to determine the base network\nnamespace for the lookup.\n\ntuplesize must be one of:\n\nsizeof(tuple->ipv4)\nLook for an IPv4 socket.\n\nsizeof(tuple->ipv6)\nLook for an IPv6 socket.\n\nIf the netns is a negative signed 32-bit integer, then the socket lookup  table\nin  the  netns  associated with the ctx will be used. For the TC hooks, this is\nthe netns of the device in the skb. For socket hooks, this is the netns of  the\nsocket.   If  netns  is  any other signed 32-bit value greater than or equal to\nzero then it specifies the ID of the netns relative  to  the  netns  associated\nwith the ctx. netns values beyond the range of 32-bit integers are reserved for\nfuture use.\n\nAll values for flags are reserved for future usage, and must be left at zero.\n\nThis helper is available only if the kernel was compiled with  CONFIGNET  con‐\nfiguration option.\n\nReturn Pointer  to  struct  bpfsock,  or  NULL  in case of failure.  For sockets with\nreuseport option, the struct bpfsock result is from reuse->socks[]  using  the\nhash of the tuple.\n\nstruct  bpfsock  *bpfsklookupudp(void *ctx, struct bpfsocktuple *tuple, u32 tuplesize,\nu64 netns, u64 flags)\n\nDescription\nLook for UDP socket matching tuple, optionally in  a  child  network  namespace\nnetns.  The  return  value  must  be  checked,  and  if  non-NULL, released via\nbpfskrelease().\n\nThe ctx should point to the context of the program, such as the skb  or  socket\n(depending  on  the  hook  in  use). This is used to determine the base network\nnamespace for the lookup.\n\ntuplesize must be one of:\n\nsizeof(tuple->ipv4)\nLook for an IPv4 socket.\n\nsizeof(tuple->ipv6)\nLook for an IPv6 socket.\n\nIf the netns is a negative signed 32-bit integer, then the socket lookup  table\nin  the  netns  associated with the ctx will be used. For the TC hooks, this is\nthe netns of the device in the skb. For socket hooks, this is the netns of  the\nsocket.   If  netns  is  any other signed 32-bit value greater than or equal to\nzero then it specifies the ID of the netns relative  to  the  netns  associated\nwith the ctx. netns values beyond the range of 32-bit integers are reserved for\nfuture use.\n\nAll values for flags are reserved for future usage, and must be left at zero.\n\nThis helper is available only if the kernel was compiled with  CONFIGNET  con‐\nfiguration option.\n\nReturn Pointer  to  struct  bpfsock,  or  NULL  in case of failure.  For sockets with\nreuseport option, the struct bpfsock result is from reuse->socks[]  using  the\nhash of the tuple.\n\nlong bpfskrelease(struct bpfsock *sock)\n\nDescription\nRelease  the  reference  held by sock. sock must be a non-NULL pointer that was\nreturned from bpfsklookupxxx().\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfmappushelem(struct bpfmap *map, const void *value, u64 flags)\n\nDescription\nPush an element value in map. flags is one of:\n\nBPFEXIST\nIf the queue/stack is full, the oldest element is removed to  make  room\nfor this.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfmappopelem(struct bpfmap *map, void *value)\n\nDescription\nPop an element from map.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfmappeekelem(struct bpfmap *map, void *value)\n\nDescription\nGet an element from map without removing it.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfmsgpushdata(struct skmsgbuff *msg, u32 start, u32 len, u64 flags)\n\nDescription\nFor socket policies, insert len bytes into msg at offset start.\n\nIf a program of type BPFPROGTYPESKMSG is run on a msg it may want to insert\nmetadata or options into the msg.  This can later be read and used  by  any  of\nthe lower layer BPF hooks.\n\nThis  helper  may fail if under memory pressure (a malloc fails) in these cases\nBPF programs will get an appropriate error and BPF programs will need to handle\nthem.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfmsgpopdata(struct skmsgbuff *msg, u32 start, u32 len, u64 flags)\n\nDescription\nWill  remove  len  bytes from a msg starting at byte start.  This may result in\nENOMEM errors under certain situations if an allocation and copy  are  required\ndue to a full ring buffer.  However, the helper will try to avoid doing the al‐\nlocation if possible. Other errors can occur if input  parameters  are  invalid\neither  due  to start byte not being valid part of msg payload and/or pop value\nbeing to large.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfrcpointerrel(void *ctx, s32 relx, s32 rely)\n\nDescription\nThis helper is used in programs implementing IR decoding, to report a  success‐\nfully decoded pointer movement.\n\nThe ctx should point to the lirc sample as passed into the program.\n\nThis  helper  is  only  available  is  the  kernel  was  compiled with the CON‐‐\nFIGBPFLIRCMODE2 configuration option set to \"y\".\n\nReturn 0\n\nlong bpfspinlock(struct bpfspinlock *lock)\n\nDescription\nAcquire a spinlock represented by the pointer lock, which is stored as part  of\na  value  of  a  map.  Taking  the lock allows to safely update the rest of the\nfields in that value. The spinlock can (and must) later be released with a call\nto bpfspinunlock(lock).\n\nSpinlocks in BPF programs come with a number of restrictions and constraints:\n\n• bpfspinlock objects are only allowed inside maps of types BPFMAPTYPEHASH\nand BPFMAPTYPEARRAY (this list could be extended in the future).\n\n• BTF description of the map is mandatory.\n\n• The BPF program can take ONE lock at a time, since taking two or  more  could\ncause dead locks.\n\n• Only one struct bpfspinlock is allowed per map element.\n\n• When the lock is taken, calls (either BPF to BPF or helpers) are not allowed.\n\n• The  BPFLDABS  and  BPFLDIND  instructions are not allowed inside a spin‐\nlock-ed region.\n\n• The BPF program MUST call bpfspinunlock() to release the lock, on all  exe‐\ncution paths, before it returns.\n\n• The  BPF program can access struct bpfspinlock only via the bpfspinlock()\nand bpfspinunlock() helpers.  Loading  or  storing  data  into  the  struct\nbpfspinlock lock; field of a map is not allowed.\n\n• To  use the bpfspinlock() helper, the BTF description of the map value must\nbe a struct and have struct bpfspinlock anyname; field at  the  top  level.\nNested lock inside another struct is not allowed.\n\n• The  struct bpfspinlock lock field in a map value must be aligned on a mul‐\ntiple of 4 bytes in that value.\n\n• Syscall with command BPFMAPLOOKUPELEM  does  not  copy  the  bpfspinlock\nfield to user space.\n\n• Syscall  with  command  BPFMAPUPDATEELEM, or update from a BPF program, do\nnot update the bpfspinlock field.\n\n• bpfspinlock cannot be on the stack or inside a networking  packet  (it  can\nonly be inside of a map values).\n\n• bpfspinlock is available to root only.\n\n• Tracing programs and socket filter programs cannot use bpfspinlock() due to\ninsufficient preemption checks (but this may change in the future).\n\n• bpfspinlock is not allowed in inner maps of map-in-map.\n\nReturn 0\n\nlong bpfspinunlock(struct bpfspinlock *lock)\n\nDescription\nRelease the lock previously locked by a call to bpfspinlock(lock).\n\nReturn 0\n\nstruct bpfsock *bpfskfullsock(struct bpfsock *sk)\n\nDescription\nThis helper gets a struct bpfsock pointer such that all  the  fields  in  this\nbpfsock can be accessed.\n\nReturn A struct bpfsock pointer on success, or NULL in case of failure.\n\nstruct bpftcpsock *bpftcpsock(struct bpfsock *sk)\n\nDescription\nThis helper gets a struct bpftcpsock pointer from a struct bpfsock pointer.\n\nReturn A struct bpftcpsock pointer on success, or NULL in case of failure.\n\nlong bpfskbecnsetce(struct skbuff *skb)\n\nDescription\nSet ECN (Explicit Congestion Notification) field of IP header to CE (Congestion\nEncountered) if current value is ECT (ECN  Capable  Transport).  Otherwise,  do\nnothing. Works with IPv6 and IPv4.\n\nReturn 1  if  the  CE flag is set (either by the current helper call or because it was\nalready present), 0 if it is not set.\n\nstruct bpfsock *bpfgetlistenersock(struct bpfsock *sk)\n\nDescription\nReturn a struct bpfsock pointer in TCPLISTEN state.  bpfskrelease() is  un‐\nnecessary and not allowed.\n\nReturn A struct bpfsock pointer on success, or NULL in case of failure.\n\nstruct  bpfsock *bpfskclookuptcp(void *ctx, struct bpfsocktuple *tuple, u32 tuplesize,\nu64 netns, u64 flags)\n\nDescription\nLook for TCP socket matching tuple, optionally in  a  child  network  namespace\nnetns.  The  return  value  must  be  checked,  and  if  non-NULL, released via\nbpfskrelease().\n\nThis function is identical to bpfsklookuptcp(), except that it also  returns\ntimewait  or request sockets. Use bpfskfullsock() or bpftcpsock() to access\nthe full structure.\n\nThis helper is available only if the kernel was compiled with  CONFIGNET  con‐\nfiguration option.\n\nReturn Pointer  to  struct  bpfsock,  or  NULL  in case of failure.  For sockets with\nreuseport option, the struct bpfsock result is from reuse->socks[]  using  the\nhash of the tuple.\n\nlong  bpftcpchecksyncookie(struct bpfsock *sk, void *iph, u32 iphlen, struct tcphdr *th,\nu32 thlen)\n\nDescription\nCheck whether iph and th contain a valid  SYN  cookie  ACK  for  the  listening\nsocket in sk.\n\niph  points  to  the  start  of the IPv4 or IPv6 header, while iphlen contains\nsizeof(struct iphdr) or sizeof(struct ip6hdr).\n\nth points to the start of the TCP header, while thlen  contains  sizeof(struct\ntcphdr).\n\nReturn 0 if iph and th are a valid SYN cookie ACK, or a negative error otherwise.\n\nlong bpfsysctlgetname(struct bpfsysctl *ctx, char *buf, sizet buflen, u64 flags)\n\nDescription\nGet  name  of  sysctl in /proc/sys/ and copy it into provided by program buffer\nbuf of size buflen.\n\nThe buffer is always NUL terminated, unless it's zero-sized.\n\nIf  flags  is  zero,  full  name  (e.g.  \"net/ipv4/tcpmem\")  is  copied.   Use\nBPFFSYSCTLBASENAME flag to copy base name only (e.g. \"tcpmem\").\n\nReturn Number of character copied (not including the trailing NUL).\n\n-E2BIG if the buffer wasn't big enough (buf will contain truncated name in this\ncase).\n\nlong bpfsysctlgetcurrentvalue(struct bpfsysctl *ctx, char *buf, sizet buflen)\n\nDescription\nGet current value of sysctl as it is presented  in  /proc/sys  (incl.  newline,\netc),  and  copy  it  as  a  string into provided by program buffer buf of size\nbuflen.\n\nThe whole value is copied, no matter what file position user space issued  e.g.\nsysread at.\n\nThe buffer is always NUL terminated, unless it's zero-sized.\n\nReturn Number of character copied (not including the trailing NUL).\n\n-E2BIG if the buffer wasn't big enough (buf will contain truncated name in this\ncase).\n\n-EINVAL if current value was unavailable, e.g. because sysctl is  uninitialized\nand read returns -EIO for it.\n\nlong bpfsysctlgetnewvalue(struct bpfsysctl *ctx, char *buf, sizet buflen)\n\nDescription\nGet  new  value  being written by user space to sysctl (before the actual write\nhappens) and copy it as a string into provided by program buffer  buf  of  size\nbuflen.\n\nUser space may write new value at file position > 0.\n\nThe buffer is always NUL terminated, unless it's zero-sized.\n\nReturn Number of character copied (not including the trailing NUL).\n\n-E2BIG if the buffer wasn't big enough (buf will contain truncated name in this\ncase).\n\n-EINVAL if sysctl is being read.\n\nlong bpfsysctlsetnewvalue(struct bpfsysctl *ctx, const char *buf, sizet buflen)\n\nDescription\nOverride new value being written by user space to sysctl with value provided by\nprogram in buffer buf of size buflen.\n\nbuf  should  contain  a string in same form as provided by user space on sysctl\nwrite.\n\nUser space may write new value at file position >  0.  To  override  the  whole\nsysctl value file position should be set to zero.\n\nReturn 0 on success.\n\n-E2BIG if the buflen is too big.\n\n-EINVAL if sysctl is being read.\n\nlong bpfstrtol(const char *buf, sizet buflen, u64 flags, long *res)\n\nDescription\nConvert  the  initial  part  of the string from buffer buf of size buflen to a\nlong integer according to the given base and save the result in res.\n\nThe string may begin with an arbitrary amount of white space (as determined  by\nisspace(3)) followed by a single optional '-' sign.\n\nFive  least significant bits of flags encode base, other bits are currently un‐\nused.\n\nBase must be either 8, 10, 16 or 0 to detect it automatically similar  to  user\nspace strtol(3).\n\nReturn Number  of  characters  consumed  on success. Must be positive but no more than\nbuflen.\n\n-EINVAL if no valid digits were found or unsupported base was provided.\n\n-ERANGE if resulting value was out of range.\n\nlong bpfstrtoul(const char *buf, sizet buflen, u64 flags, unsigned long *res)\n\nDescription\nConvert the initial part of the string from buffer buf of size  buflen  to  an\nunsigned long integer according to the given base and save the result in res.\n\nThe  string may begin with an arbitrary amount of white space (as determined by\nisspace(3)).\n\nFive least significant bits of flags encode base, other bits are currently  un‐\nused.\n\nBase  must  be either 8, 10, 16 or 0 to detect it automatically similar to user\nspace strtoul(3).\n\nReturn Number of characters consumed on success. Must be positive  but  no  more  than\nbuflen.\n\n-EINVAL if no valid digits were found or unsupported base was provided.\n\n-ERANGE if resulting value was out of range.\n\nvoid *bpfskstorageget(struct bpfmap *map, struct bpfsock *sk, void *value, u64 flags)\n\nDescription\nGet a bpf-local-storage from a sk.\n\nLogically,  it  could be thought of getting the value from a map with sk as the\nkey.   From  this  perspective,   the  usage  is  not   much   different   from\nbpfmaplookupelem(map,  &sk)  except  this  helper enforces the key must be a\nfull socket and the map must be a BPFMAPTYPESKSTORAGE also.\n\nUnderneath, the value is stored locally at sk instead of the map.  The  map  is\nused  as  the  bpf-local-storage \"type\". The bpf-local-storage \"type\" (i.e. the\nmap) is searched against all bpf-local-storages residing at sk.\n\nAn optional flags (BPFSKSTORAGEGETFCREATE) can be used  such  that  a  new\nbpf-local-storage will be created if one does not exist.  value can be used to‐\ngether with BPFSKSTORAGEGETFCREATE to  specify  the  initial  value  of  a\nbpf-local-storage.   If  value  is NULL, the new bpf-local-storage will be zero\ninitialized.\n\nReturn A bpf-local-storage pointer is returned on success.\n\nNULL if not found or there was an error in adding a new bpf-local-storage.\n\nlong bpfskstoragedelete(struct bpfmap *map, struct bpfsock *sk)\n\nDescription\nDelete a bpf-local-storage from a sk.\n\nReturn 0 on success.\n\n-ENOENT if the bpf-local-storage cannot be found.\n\nlong bpfsendsignal(u32 sig)\n\nDescription\nSend signal sig to the process of the current task.  The signal may  be  deliv‐\nered to any of this process's threads.\n\nReturn 0 on success or successfully queued.\n\n-EBUSY if work queue under nmi is full.\n\n-EINVAL if sig is invalid.\n\n-EPERM if no permission to send the sig.\n\n-EAGAIN if bpf program can try again.\n\ns64 bpftcpgensyncookie(struct bpfsock *sk, void *iph, u32 iphlen, struct tcphdr *th, u32\nthlen)\n\nDescription\nTry to issue a SYN cookie for the packet with corresponding IP/TCP headers, iph\nand th, on the listening socket in sk.\n\niph  points  to  the  start  of the IPv4 or IPv6 header, while iphlen contains\nsizeof(struct iphdr) or sizeof(struct ip6hdr).\n\nth points to the start of the TCP header, while thlen contains the  length  of\nthe TCP header.\n\nReturn On  success, lower 32 bits hold the generated SYN cookie in followed by 16 bits\nwhich hold the MSS value for that cookie, and the top 16 bits are unused.\n\nOn failure, the returned value is one of the following:\n\n-EINVAL SYN cookie cannot be issued due to error\n\n-ENOENT SYN cookie should not be issued (no SYN flood)\n\n-EOPNOTSUPP kernel configuration does not enable SYN cookies\n\n-EPROTONOSUPPORT IP packet version is not 4 or 6\n\nlong bpfskboutput(void *ctx, struct bpfmap *map, u64 flags, void *data, u64 size)\n\nDescription\nWrite raw data blob into  a  special  BPF  perf  event  held  by  map  of  type\nBPFMAPTYPEPERFEVENTARRAY.  This  perf  event  must  have the following at‐\ntributes: PERFSAMPLERAW  as  sampletype,  PERFTYPESOFTWARE  as  type,  and\nPERFCOUNTSWBPFOUTPUT as config.\n\nThe  flags  are  used  to indicate the index in map for which the value must be\nput,  masked  with  BPFFINDEXMASK.   Alternatively,  flags  can  be  set  to\nBPFFCURRENTCPU  to indicate that the index of the current CPU core should be\nused.\n\nThe value to write, of size, is passed through eBPF stack and pointed by data.\n\nctx is a pointer to in-kernel struct skbuff.\n\nThis helper is similar to bpfperfeventoutput() but restricted to  rawtrace‐\npoint bpf programs.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfprobereaduser(void *dst, u32 size, const void *unsafeptr)\n\nDescription\nSafely  attempt to read size bytes from user space address unsafeptr and store\nthe data in dst.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfprobereadkernel(void *dst, u32 size, const void *unsafeptr)\n\nDescription\nSafely attempt to read size bytes from  kernel  space  address  unsafeptr  and\nstore the data in dst.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfprobereaduserstr(void *dst, u32 size, const void *unsafeptr)\n\nDescription\nCopy a NUL terminated string from an unsafe user address unsafeptr to dst. The\nsize should include the terminating NUL byte. In  case  the  string  length  is\nsmaller  than  size,  the  target  is not padded with further NUL bytes. If the\nstring length is larger than size, just size-1 bytes are copied  and  the  last\nbyte is set to NUL.\n\nOn success, the length of the copied string is returned. This makes this helper\nuseful in tracing programs for reading strings, and more importantly to get its\nlength at runtime. See the following snippet:\n\nSEC(\"kprobe/sysopen\")\nvoid bpfsysopen(struct ptregs *ctx)\n{\nchar buf[PATHLEN]; // PATHLEN is defined to 256\nint res = bpfprobereaduserstr(buf, sizeof(buf),\nctx->di);\n\n// Consume buf, for example push it to\n// userspace via bpfperfeventoutput(); we\n// can use res (the string length) as event\n// size, after checking its boundaries.\n}\n\nIn  comparison,  using  bpfprobereaduser()  helper  here instead to read the\nstring would require to estimate the length at compile time,  and  would  often\nresult in copying more memory than necessary.\n\nAnother  useful  use case is when parsing individual process arguments or indi‐\nvidual  environment  variables  navigating  current->mm->argstart   and   cur‐\nrent->mm->envstart:  using  this  helper and the return value, one can quickly\niterate at the right offset of the memory area.\n\nReturn On success, the strictly positive length of the string, including the  trailing\nNUL character. On error, a negative value.\n\nlong bpfprobereadkernelstr(void *dst, u32 size, const void *unsafeptr)\n\nDescription\nCopy  a  NUL terminated string from an unsafe kernel address unsafeptr to dst.\nSame semantics as with bpfprobereaduserstr() apply.\n\nReturn On success, the strictly positive length of the string, including the  trailing\nNUL character. On error, a negative value.\n\nlong bpftcpsendack(void *tp, u32 rcvnxt)\n\nDescription\nSend  out  a  tcp-ack.  tp  is  the  in-kernel struct tcpsock.  rcvnxt is the\nackseq to be sent out.\n\nReturn 0 on success, or a negative error in case of failure.\n\nlong bpfsendsignalthread(u32 sig)\n\nDescription\nSend signal sig to the thread corresponding to the current task.\n\nReturn 0 on success or successfully queued.\n\n-EBUSY if work queue under nmi is full.\n\n-EINVAL if sig is invalid.\n\n-EPERM if no permission to send the sig.\n\n-EAGAIN if bpf program can try again.\n\nu64 bpfjiffies64(void)\n\nDescription\nObtain the 64bit jiffies\n\nReturn The 64 bit jiffies\n\nlong bpfreadbranchrecords(struct bpfperfeventdata *ctx, void *buf, u32 size, u64 flags)\n\nDescription\nFor an eBPF program attached to a  perf  event,  retrieve  the  branch  records\n(struct perfbranchentry) associated to ctx and store it in the buffer pointed\nby buf up to size size bytes.\n\nReturn On success, number of bytes written to buf. On error, a negative value.\n\nThe flags can be set to BPFFGETBRANCHRECORDSSIZE  to  instead  return  the\nnumber  of bytes required to store all the branch entries. If this flag is set,\nbuf may be NULL.\n\n-EINVAL  if  arguments  invalid  or  size  not  a  multiple  of   sizeof(struct\nperfbranchentry).\n\n-ENOENT if architecture does not support branch records.\n\nlong bpfgetnscurrentpidtgid(u64 dev, u64 ino, struct bpfpidnsinfo *nsdata, u32 size)\n\nDescription\nReturns  0  on  success, values for pid and tgid as seen from the current name‐\nspace will be returned in nsdata.\n\nReturn 0 on success, or one of the following in case of failure:\n\n-EINVAL if dev and inum supplied don't match devt and inode number  with  nsfs\nof current task, or if dev conversion to devt lost high bits.\n\n-ENOENT if pidns does not exists for the current task.\n\nlong bpfxdpoutput(void *ctx, struct bpfmap *map, u64 flags, void *data, u64 size)\n\nDescription\nWrite  raw  data  blob  into  a  special  BPF  perf  event  held by map of type\nBPFMAPTYPEPERFEVENTARRAY. This perf event  must  have  the  following  at‐\ntributes:  PERFSAMPLERAW  as  sampletype,  PERFTYPESOFTWARE  as  type, and\nPERFCOUNTSWBPFOUTPUT as config.\n\nThe flags are used to indicate the index in map for which  the  value  must  be\nput,  masked  with  BPFFINDEXMASK.   Alternatively,  flags  can  be  set  to\nBPFFCURRENTCPU to indicate that the index of the current CPU core should  be\nused.\n\nThe value to write, of size, is passed through eBPF stack and pointed by data.\n\nctx is a pointer to in-kernel struct xdpbuff.\n\nThis  helper  is similar to bpfperfeventoutput() but restricted to rawtrace‐\npoint bpf programs.\n\nReturn 0 on success, or a negative error in case of failure.\n\nu64 bpfgetnetnscookie(void *ctx)\n\nDescription\nRetrieve the cookie (generated by the kernel) of the network namespace the  in‐\nput ctx is associated with. The network namespace cookie remains stable for its\nlifetime and provides a global identifier that can be assumed unique. If ctx is\nNULL, then the helper returns the cookie for the initial network namespace. The\ncookie itself is very similar to that of  bpfgetsocketcookie()  helper,  but\nfor network namespaces instead of sockets.\n\nReturn A 8-byte long opaque number.\n\nu64 bpfgetcurrentancestorcgroupid(int ancestorlevel)\n\nDescription\nReturn  id of cgroup v2 that is ancestor of the cgroup associated with the cur‐\nrent task at the ancestorlevel. The root cgroup is at ancestorlevel zero  and\neach  step  down the hierarchy increments the level. If ancestorlevel == level\nof cgroup associated with the current task, then return value will be the  same\nas that of bpfgetcurrentcgroupid().\n\nThe  helper  is useful to implement policies based on cgroups that are upper in\nhierarchy than immediate cgroup associated with the current task.\n\nThe format of returned id and helper limitations are same  as  in  bpfgetcur‐‐\nrentcgroupid().\n\nReturn The id is returned or 0 in case the id could not be retrieved.\n\nlong bpfskassign(struct skbuff *skb, struct bpfsock *sk, u64 flags)\n\nDescription\nHelper is overloaded depending on BPF program type. This description applies to\nBPFPROGTYPESCHEDCLS and BPFPROGTYPESCHEDACT programs.\n\nAssign the sk to the skb. When combined with appropriate routing  configuration\nto receive the packet towards the socket, will cause skb to be delivered to the\nspecified  socket.   Subsequent  redirection  of   skb   via    bpfredirect(),\nbpfcloneredirect()  or  other  methods outside of BPF may interfere with suc‐\ncessful delivery to the socket.\n\nThis operation is only valid from TC ingress path.\n\nThe flags argument must be zero.\n\nReturn 0 on success, or a negative error in case of failure:\n\n-EINVAL if specified flags are not supported.\n\n-ENOENT if the socket is unavailable for assignment.\n\n-ENETUNREACH if the socket is unreachable (wrong netns).\n\n-EOPNOTSUPP if the operation is not supported, for example a call from  outside\nof TC ingress.\n\n-ESOCKTNOSUPPORT if the socket type is not supported (reuseport).\n\nlong bpfskassign(struct bpfsklookup *ctx, struct bpfsock *sk, u64 flags)\n\nDescription\nHelper is overloaded depending on BPF program type. This description applies to\nBPFPROGTYPESKLOOKUP programs.\n\nSelect the sk as a result of a socket lookup.\n\nFor the operation to succeed passed socket must be compatible with  the  packet\ndescription provided by the ctx object.\n\nL4  protocol (IPPROTOTCP or IPPROTOUDP) must be an exact match. While IP fam‐\nily (AFINET or AFINET6) must be compatible, that is IPv6 sockets that are not\nv6-only can be selected for IPv4 packets.\n\nOnly  TCP listeners and UDP unconnected sockets can be selected. sk can also be\nNULL to reset any previous selection.\n\nflags argument can combination of following values:\n\n• BPFSKLOOKUPFREPLACE to override the  previous  socket  selection,  poten‐\ntially done by a BPF program that ran before us.\n\n• BPFSKLOOKUPFNOREUSEPORT  to  skip  load-balancing within reuseport group\nfor the socket being selected.\n\nOn success ctx->sk will point to the selected socket.\n\nReturn 0 on success, or a negative errno in case of failure.\n\n• -EAFNOSUPPORT if socket family (sk->family) is  not  compatible  with  packet\nfamily (ctx->family).\n\n• -EEXIST  if socket has been already selected, potentially by another program,\nand BPFSKLOOKUPFREPLACE flag was not specified.\n\n• -EINVAL if unsupported flags were specified.\n\n• -EPROTOTYPE if socket L4 protocol (sk->protocol) doesn't match packet  proto‐\ncol (ctx->protocol).\n\n• -ESOCKTNOSUPPORT  if socket is not in allowed state (TCP listening or UDP un‐\nconnected).\n\nu64 bpfktimegetbootns(void)\n\nDescription\nReturn the time elapsed since system boot, in nanoseconds.   Does  include  the\ntime the system was suspended.  See: clockgettime(CLOCKBOOTTIME)\n\nReturn Current ktime.\n\nlong  bpfseqprintf(struct seqfile *m, const char *fmt, u32 fmtsize, const void *data, u32\ndatalen)\n\nDescription\nbpfseqprintf() uses seqfile seqprintf() to print  out  the  format  string.\nThe  m  represents the seqfile. The fmt and fmtsize are for the format string\nitself. The data and datalen are format string arguments. The data are  a  u64\narray  and  corresponding  format  string  values  are stored in the array. For\nstrings and pointers where pointees are accessed, only the pointer  values  are\nstored in the data array.  The datalen is the size of data in bytes.\n\nFormats %s, %p{i,I}{4,6} requires to read kernel memory.  Reading kernel memory\nmay fail due to either invalid address or valid address but requiring  a  major\nmemory  fault.  If  reading  kernel  memory fails, the string for %s will be an\nempty string, and the ip address for %p{i,I}{4,6} will be 0. Not returning  er‐\nror to bpf program is consistent with what bpftraceprintk() does for now.\n\nReturn 0 on success, or a negative error in case of failure:\n\n-EBUSY if per-CPU memory copy buffer is busy, can try again by returning 1 from\nbpf program.\n\n-EINVAL if arguments are invalid, or if fmt is invalid/unsupported.\n\n-E2BIG if fmt contains too many format specifiers.\n\n-EOVERFLOW if an overflow happened: The same object will be tried again.\n\nlong bpfseqwrite(struct seqfile *m, const void *data, u32 len)\n\nDescription\nbpfseqwrite() uses seqfile seqwrite() to write the data.  The m  represents\nthe seqfile. The data and len represent the data to write in bytes.\n\nReturn 0 on success, or a negative error in case of failure:\n\n-EOVERFLOW if an overflow happened: The same object will be tried again.\n\nu64 bpfskcgroupid(struct bpfsock *sk)\n\nDescription\nReturn the cgroup v2 id of the socket sk.\n\nsk  must  be  a  non-NULL  pointer  to  a  full  socket, e.g. one returned from\nbpfsklookupxxx(), bpfskfullsock(), etc. The format of returned id is  same\nas in bpfskbcgroupid().\n\nThis  helper  is  available  only  if  the  kernel  was  compiled with the CON‐‐\nFIGSOCKCGROUPDATA configuration option.\n\nReturn The id is returned or 0 in case the id could not be retrieved.\n\nu64 bpfskancestorcgroupid(struct bpfsock *sk, int ancestorlevel)\n\nDescription\nReturn id of cgroup v2 that is ancestor of cgroup associated with the sk at the\nancestorlevel.   The  root cgroup is at ancestorlevel zero and each step down\nthe hierarchy increments the level. If ancestorlevel == level of cgroup  asso‐\nciated with sk, then return value will be same as that of bpfskcgroupid().\n\nThe  helper  is useful to implement policies based on cgroups that are upper in\nhierarchy than immediate cgroup associated with sk.\n\nThe  format  of  returned  id  and  helper   limitations   are   same   as   in\nbpfskcgroupid().\n\nReturn The id is returned or 0 in case the id could not be retrieved.\n\nlong bpfringbufoutput(void *ringbuf, void *data, u64 size, u64 flags)\n\nDescription\nCopy  size  bytes from data into a ring buffer ringbuf.  If BPFRBNOWAKEUP is\nspecified in flags, no notification of  new  data  availability  is  sent.   If\nBPFRBFORCEWAKEUP  is specified in flags, notification of new data availabil‐\nity is sent unconditionally.\n\nReturn 0 on success, or a negative error in case of failure.\n\nvoid *bpfringbufreserve(void *ringbuf, u64 size, u64 flags)\n\nDescription\nReserve size bytes of payload in a ring buffer ringbuf.\n\nReturn Valid pointer with size bytes of memory available; NULL, otherwise.\n\nvoid bpfringbufsubmit(void *data, u64 flags)\n\nDescription\nSubmit reserved ring buffer sample, pointed to by data.  If BPFRBNOWAKEUP is\nspecified  in  flags,  no  notification  of  new data availability is sent.  If\nBPFRBFORCEWAKEUP is specified in flags, notification of new data  availabil‐\nity is sent unconditionally.\n\nReturn Nothing. Always succeeds.\n\nvoid bpfringbufdiscard(void *data, u64 flags)\n\nDescription\nDiscard  reserved  ring buffer sample, pointed to by data.  If BPFRBNOWAKEUP\nis specified in flags, no notification of new data availability  is  sent.   If\nBPFRBFORCEWAKEUP  is specified in flags, notification of new data availabil‐\nity is sent unconditionally.\n\nReturn Nothing. Always succeeds.\n\nu64 bpfringbufquery(void *ringbuf, u64 flags)\n\nDescription\nQuery various characteristics of provided ring buffer. What exactly is  queries\nis determined by flags:\n\n• BPFRBAVAILDATA: Amount of data not yet consumed.\n\n• BPFRBRINGSIZE: The size of ring buffer.\n\n• BPFRBCONSPOS: Consumer position (can wrap around).\n\n• BPFRBPRODPOS: Producer(s) position (can wrap around).\n\nData  returned is just a momentary snapshot of actual values and could be inac‐\ncurate, so this facility should be used to power heuristics and for  reporting,\nnot to make 100% correct calculation.\n\nReturn Requested value, or 0, if flags are not recognized.\n\nlong bpfcsumlevel(struct skbuff *skb, u64 level)\n\nDescription\nChange the skbs checksum level by one layer up or down, or reset it entirely to\nnone in order to have the stack perform checksum validation. The level  is  ap‐\nplicable  to the following protocols: TCP, UDP, GRE, SCTP, FCOE. For example, a\ndecap of | ETH | IP | UDP | GUE | IP | TCP | into | ETH | IP |  TCP  |  through\nbpfskbadjustroom()  helper with passing in BPFFADJROOMNOCSUMRESET flag\nwould require one call to bpfcsumlevel() with  BPFCSUMLEVELDEC  since  the\nUDP  header is removed. Similarly, an encap of the latter into the former could\nbe accompanied by a helper call to bpfcsumlevel() with BPFCSUMLEVELINC  if\nthe skb is still intended to be processed in higher layers of the stack instead\nof just egressing at tc.\n\nThere are three supported level settings at this time:\n\n• BPFCSUMLEVELINC: Increases skb->csumlevel for skbs with CHECKSUMUNNECES‐\nSARY.\n\n• BPFCSUMLEVELDEC: Decreases skb->csumlevel for skbs with CHECKSUMUNNECES‐\nSARY.\n\n• BPFCSUMLEVELRESET: Resets skb->csumlevel to 0 and sets  CHECKSUMNONE  to\nforce checksum validation by the stack.\n\n• BPFCSUMLEVELQUERY: No-op, returns the current skb->csumlevel.\n\nReturn 0  on  success,  or  a  negative  error  in  case  of  failure.  In the case of\nBPFCSUMLEVELQUERY, the current skb->csumlevel is returned or the error code\n-EACCES in case the skb is not subject to CHECKSUMUNNECESSARY.\n\nstruct tcp6sock *bpfskctotcp6sock(void *sk)\n\nDescription\nDynamically cast a sk pointer to a tcp6sock pointer.\n\nReturn sk if casting is valid, or NULL otherwise.\n\nstruct tcpsock *bpfskctotcpsock(void *sk)\n\nDescription\nDynamically cast a sk pointer to a tcpsock pointer.\n\nReturn sk if casting is valid, or NULL otherwise.\n\nstruct tcptimewaitsock *bpfskctotcptimewaitsock(void *sk)\n\nDescription\nDynamically cast a sk pointer to a tcptimewaitsock pointer.\n\nReturn sk if casting is valid, or NULL otherwise.\n\nstruct tcprequestsock *bpfskctotcprequestsock(void *sk)\n\nDescription\nDynamically cast a sk pointer to a tcprequestsock pointer.\n\nReturn sk if casting is valid, or NULL otherwise.\n\nstruct udp6sock *bpfskctoudp6sock(void *sk)\n\nDescription\nDynamically cast a sk pointer to a udp6sock pointer.\n\nReturn sk if casting is valid, or NULL otherwise.\n\nlong bpfgettaskstack(struct taskstruct *task, void *buf, u32 size, u64 flags)\n\nDescription\nReturn  a  user  or  a kernel stack in bpf program provided buffer.  To achieve\nthis, the helper needs task, which is a valid pointer to struct taskstruct. To\nstore the stacktrace, the bpf program provides buf with a nonnegative size.\n\nThe  last  argument, flags, holds the number of stack frames to skip (from 0 to\n255), masked with BPFFSKIPFIELDMASK. The next bits can be used to  set  the\nfollowing flags:\n\nBPFFUSERSTACK\nCollect a user space stack instead of a kernel stack.\n\nBPFFUSERBUILDID\nCollect  buildid+offset  instead  of  ips  for user stack, only valid if\nBPFFUSERSTACK is also specified.\n\nbpfgettaskstack() can collect up to  PERFMAXSTACKDEPTH  both  kernel  and\nuser  frames, subject to sufficient large buffer size. Note that this limit can\nbe controlled with the sysctl program, and that it should be manually increased\nin  order to profile long user stacks (such as stacks for Java programs). To do\nso, use:\n\n# sysctl kernel.perfeventmaxstack=<new value>\n\nReturn A non-negative value equal to or less than size on success, or a negative error\nin case of failure.\n",
            "subsections": []
        },
        "EXAMPLES": {
            "content": "Example  usage  for  most of the eBPF helpers listed in this manual page are available within\nthe Linux kernel sources, at the following locations:\n\n• samples/bpf/\n\n• tools/testing/selftests/bpf/\n",
            "subsections": []
        },
        "LICENSE": {
            "content": "eBPF programs can have an associated license, passed along with the bytecode instructions  to\nthe  kernel  when the programs are loaded. The format for that string is identical to the one\nin use for kernel modules (Dual licenses, such as \"Dual BSD/GPL\", may be used).  Some  helper\nfunctions  are  only  accessible to programs that are compatible with the GNU Privacy License\n(GPL).\n\nIn order to use such helpers, the eBPF program must be loaded with the correct license string\npassed  (via  attr) to the bpf() system call, and this generally translates into the C source\ncode of the program containing a line similar to the following:\n\nchar license[] attribute((section(\"license\"), used)) = \"GPL\";\n",
            "subsections": []
        },
        "IMPLEMENTATION": {
            "content": "This manual page is an effort to document the existing eBPF helper functions.  But as of this\nwriting,  the  BPF  sub-system  is under heavy development. New eBPF program or map types are\nadded, along with new helper functions. Some helpers are occasionally made available for  ad‐\nditional  program  types. So in spite of the efforts of the community, this page might not be\nup-to-date. If you want to check by yourself what helper functions exist in your  kernel,  or\nwhat  types  of programs they can support, here are some files among the kernel tree that you\nmay be interested in:\n\n• include/uapi/linux/bpf.h is the main BPF header. It contains the full list  of  all  helper\nfunctions,  as  well  as many other BPF definitions including most of the flags, structs or\nconstants used by the helpers.\n\n• net/core/filter.c contains the definition of most network-related helper functions, and the\nlist of program types from which they can be used.\n\n• kernel/trace/bpftrace.c is the equivalent for most tracing program-related helpers.\n\n• kernel/bpf/verifier.c  contains  the  functions used to check that valid types of eBPF maps\nare used with a given helper function.\n\n• kernel/bpf/ directory contains other files in which additional  helpers  are  defined  (for\ncgroups, sockmaps, etc.).\n\n• The bpftool utility can be used to probe the availability of helper functions on the system\n(as well as supported program and map types, and a number of other parameters). To  do  so,\nrun  bpftool  feature probe (see bpftool-feature(8) for details). Add the unprivileged key‐\nword to list features available to unprivileged users.\n\nCompatibility between helper functions and program types can generally be found in the  files\nwhere  helper functions are defined. Look for the struct bpffuncproto objects and for func‐\ntions returning them: these functions contain a list of helpers that a given program type can\ncall.  Note  that  the  default: label of the switch ... case used to filter helpers can call\nother functions, themselves allowing access to additional helpers. The  requirement  for  GPL\nlicense is also in those struct bpffuncproto.\n\nCompatibility  between helper functions and map types can be found in the checkmapfunccom‐‐\npatibility() function in file kernel/bpf/verifier.c.\n\nHelper functions that invalidate the checks on data and dataend pointers  for  network  pro‐\ncessing are listed in function bpfhelperchangespktdata() in file net/core/filter.c.\n",
            "subsections": []
        },
        "SEE ALSO": {
            "content": "bpf(2), bpftool(8), cgroups(7), ip(8), perfeventopen(2), sendmsg(2), socket(7), tc-bpf(8)\n",
            "subsections": []
        },
        "COLOPHON": {
            "content": "This  page  is  part  of  release  5.10 of the Linux man-pages project.  A description of the\nproject, information about reporting bugs, and the latest version of this page, can be  found\nat https://www.kernel.org/doc/man-pages/.\n\n\n\nBPF-HELPERS(7)",
            "subsections": []
        }
    },
    "summary": "BPF-HELPERS - list of eBPF helper functions",
    "flags": [],
    "examples": [
        "Example  usage  for  most of the eBPF helpers listed in this manual page are available within",
        "the Linux kernel sources, at the following locations:",
        "• samples/bpf/",
        "• tools/testing/selftests/bpf/"
    ],
    "see_also": [
        {
            "name": "bpf",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/bpf/2/json"
        },
        {
            "name": "bpftool",
            "section": "8",
            "url": "https://www.chedong.com/phpMan.php/man/bpftool/8/json"
        },
        {
            "name": "cgroups",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/cgroups/7/json"
        },
        {
            "name": "ip",
            "section": "8",
            "url": "https://www.chedong.com/phpMan.php/man/ip/8/json"
        },
        {
            "name": "perfeventopen",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/perfeventopen/2/json"
        },
        {
            "name": "sendmsg",
            "section": "2",
            "url": "https://www.chedong.com/phpMan.php/man/sendmsg/2/json"
        },
        {
            "name": "socket",
            "section": "7",
            "url": "https://www.chedong.com/phpMan.php/man/socket/7/json"
        },
        {
            "name": "tc-bpf",
            "section": "8",
            "url": "https://www.chedong.com/phpMan.php/man/tc-bpf/8/json"
        }
    ]
}