Re: [PATCH v4 bpf-next 1/3] bpf: Add kmem_cache iterator

From: Namhyung Kim
Date: Fri Oct 04 2024 - 17:38:01 EST


Hi Song,

On Fri, Oct 04, 2024 at 01:33:19PM -0700, Song Liu wrote:
> On Wed, Oct 2, 2024 at 11:09 AM Namhyung Kim <namhyung@xxxxxxxxxx> wrote:
> >
> [...]
> > +
> > + mutex_lock(&slab_mutex);
> > +
> > + /*
> > + * Find an entry at the given position in the slab_caches list instead
>
> Nit: style of multi-line comment: "/* Find ...".

Ok, will update.

>
> > + * of keeping a reference (of the last visited entry, if any) out of
> > + * slab_mutex. It might miss something if one is deleted in the middle
> > + * while it releases the lock. But it should be rare and there's not
> > + * much we can do about it.
> > + */
> > + list_for_each_entry(s, &slab_caches, list) {
> > + if (cnt == *pos) {
> > + /*
> > + * Make sure this entry remains in the list by getting
> > + * a new reference count. Note that boot_cache entries
> > + * have a negative refcount, so don't touch them.
> > + */
> > + if (s->refcount > 0)
> > + s->refcount++;
> > + found = true;
> > + break;
> > + }
> > + cnt++;
> > + }
> > + mutex_unlock(&slab_mutex);
> > +
> > + if (!found)
> > + return NULL;
> > +
> > + ++*pos;
> > + return s;
> > +}
> > +
> > +static void kmem_cache_iter_seq_stop(struct seq_file *seq, void *v)
> > +{
> > + struct bpf_iter_meta meta;
> > + struct bpf_iter__kmem_cache ctx = {
> > + .meta = &meta,
> > + .s = v,
> > + };
> > + struct bpf_prog *prog;
> > + bool destroy = false;
> > +
> > + meta.seq = seq;
> > + prog = bpf_iter_get_info(&meta, true);
> > + if (prog)
> > + bpf_iter_run_prog(prog, &ctx);
> > +
> > + if (ctx.s == NULL)
> > + return;
> > +
> > + mutex_lock(&slab_mutex);
> > +
> > + /* Skip kmem_cache_destroy() for active entries */
> > + if (ctx.s->refcount > 1)
> > + ctx.s->refcount--;
> > + else if (ctx.s->refcount == 1)
> > + destroy = true;
> > +
> > + mutex_unlock(&slab_mutex);
> > +
> > + if (destroy)
> > + kmem_cache_destroy(ctx.s);
> > +}
> > +
> > +static void *kmem_cache_iter_seq_next(struct seq_file *seq, void *v, loff_t *pos)
> > +{
> > + struct kmem_cache *s = v;
> > + struct kmem_cache *next = NULL;
> > + bool destroy = false;
> > +
> > + ++*pos;
> > +
> > + mutex_lock(&slab_mutex);
> > +
> > + if (list_last_entry(&slab_caches, struct kmem_cache, list) != s) {
> > + next = list_next_entry(s, list);
> > + if (next->refcount > 0)
> > + next->refcount++;
>
> What if next->refcount <=0? Shall we find next of next?

The slab_mutex should protect refcount == 0 case so it won't see that.
The negative refcount means it's a boot_cache and we shouldn't touch the
refcount.

Thanks,
Namhyung

>
> > + }
> > +
> > + /* Skip kmem_cache_destroy() for active entries */
> > + if (s->refcount > 1)
> > + s->refcount--;
> > + else if (s->refcount == 1)
> > + destroy = true;
> > +
> > + mutex_unlock(&slab_mutex);
> > +
> > + if (destroy)
> > + kmem_cache_destroy(s);
> > +
> > + return next;
> > +}
> [...]