title: eBPF - difference between loading, attaching, and linking?
body: <p>I'm very confused on <code>eBPF</code> terminology that is used in the <code>bpf</code> syscall and <code>libbpf</code> functions. Could someone break down where my understanding of loading/attaching a process using <code>bpf</code> is wrong?</p>
  <hr />
  <p>My understanding:</p>
  <p>I've been looking at code for <code>cgroups</code> so I'll use that as an example. I know that bpf programs for cgroups are stored in <code>cgroup_bpf-&gt;effective[bpf_attach_type]</code> (see <a href="https://elixir.bootlin.com/linux/latest/source/include/linux/bpf-cgroup.h#L81" rel="nofollow noreferrer">here</a> and <a href="https://elixir.bootlin.com/linux/v5.13/source/kernel/bpf/cgroup.c#L1274" rel="nofollow noreferrer">here</a>). I know that that these programs are accessed and run when functions like <code>__cgroup_bpf_run_filter_sysctl()</code> (in <a href="https://elixir.bootlin.com/linux/v5.13/source/kernel/bpf/cgroup.c#L1231" rel="nofollow noreferrer">cgroup.c</a>) are called from whatever handler calls them (e.g. in this case the function <code>proc_sys_call_handler()</code>). But how are these programs loaded/stored/attached/linked, and what is the difference between each term?</p>
  <p><strong>Loading</strong> - Apparently, this needs to happen <a href="https://elixir.bootlin.com/linux/v5.13/source/tools/lib/bpf/libbpf.c#L10284" rel="nofollow noreferrer">before attaching</a>. I'm guessing this is where a cgroup program is stored in a generic location (i.e. <em>not</em> in <code>cgroup_bpf-&gt;effective[bpf_attach_type]</code>) and therefore not yet attached/linked for execution in the kernel yet. Therefore, loading is completely separate from <code>bpf_attach_type</code>. If I'm correct, where is this generic load location for cgroup program types?</p>
  <p><strong>Attaching</strong> - Perhaps this is where a program gets associated with a <code>bpf_attach_type</code>. As in, now we take the generically stored program and now we can put it in the <code>cgroup_bpf-&gt;effective[bpf_attach_type]</code> array using whatever <code>bpf_attach_type</code> we want. Then, when the corresponding attach points in the kernel are reached, the program is run.</p>
  <p><strong>Linking</strong> - Is this just a special type of attachment? How is this different from normal attaching? I see that <a href="https://elixir.bootlin.com/linux/v5.13/source/kernel/bpf/syscall.c#L4078" rel="nofollow noreferrer"><code>link_create()</code></a> and <a href="https://elixir.bootlin.com/linux/v5.13/source/kernel/bpf/cgroup.c#L782" rel="nofollow noreferrer"><code>cgroup_bpf_prog_attach()</code></a> <em>both</em> end up calling <a href="https://elixir.bootlin.com/linux/v5.13/source/kernel/cgroup/cgroup.c#L6466" rel="nofollow noreferrer"><code>cgroup_bpf_attach()</code></a> when the cgroup program type is used.</p>