Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Landlock LSM - Object management
0004  *
0005  * Copyright © 2016-2020 Mickaël Salaün <mic@digikod.net>
0006  * Copyright © 2018-2020 ANSSI
0007  */
0008 
0009 #include <linux/bug.h>
0010 #include <linux/compiler_types.h>
0011 #include <linux/err.h>
0012 #include <linux/kernel.h>
0013 #include <linux/rcupdate.h>
0014 #include <linux/refcount.h>
0015 #include <linux/slab.h>
0016 #include <linux/spinlock.h>
0017 
0018 #include "object.h"
0019 
0020 struct landlock_object *
0021 landlock_create_object(const struct landlock_object_underops *const underops,
0022                void *const underobj)
0023 {
0024     struct landlock_object *new_object;
0025 
0026     if (WARN_ON_ONCE(!underops || !underobj))
0027         return ERR_PTR(-ENOENT);
0028     new_object = kzalloc(sizeof(*new_object), GFP_KERNEL_ACCOUNT);
0029     if (!new_object)
0030         return ERR_PTR(-ENOMEM);
0031     refcount_set(&new_object->usage, 1);
0032     spin_lock_init(&new_object->lock);
0033     new_object->underops = underops;
0034     new_object->underobj = underobj;
0035     return new_object;
0036 }
0037 
0038 /*
0039  * The caller must own the object (i.e. thanks to object->usage) to safely put
0040  * it.
0041  */
0042 void landlock_put_object(struct landlock_object *const object)
0043 {
0044     /*
0045      * The call to @object->underops->release(object) might sleep, e.g.
0046      * because of iput().
0047      */
0048     might_sleep();
0049     if (!object)
0050         return;
0051 
0052     /*
0053      * If the @object's refcount cannot drop to zero, we can just decrement
0054      * the refcount without holding a lock. Otherwise, the decrement must
0055      * happen under @object->lock for synchronization with things like
0056      * get_inode_object().
0057      */
0058     if (refcount_dec_and_lock(&object->usage, &object->lock)) {
0059         __acquire(&object->lock);
0060         /*
0061          * With @object->lock initially held, remove the reference from
0062          * @object->underobj to @object (if it still exists).
0063          */
0064         object->underops->release(object);
0065         kfree_rcu(object, rcu_free);
0066     }
0067 }