Skip to content

Commit 58bc615

Browse files
gregkhwedsonaf
authored andcommitted
char example: use 'struct kref' instead of "raw" reference count
When using a reference count to control the lifetime of a structure, struct kref should be used instead of a raw reference count. Signed-off-by: Greg Kroah-Hartman <gregkh@linuxfoundation.org>
1 parent 33df7ba commit 58bc615

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

samples/rust/semaphore.c

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
#define IOCTL_SET_READ_COUNT _IOW('c', 1, u64)
1212

1313
struct semaphore_state {
14-
refcount_t ref;
14+
struct kref ref;
1515
struct miscdevice miscdev;
1616
wait_queue_head_t changed;
1717
struct mutex mutex;
@@ -55,7 +55,7 @@ static int semaphore_open(struct inode *nodp, struct file *filp)
5555
if (!state)
5656
return -ENOMEM;
5757

58-
refcount_inc(&shared->ref);
58+
kref_get(&shared->ref);
5959
state->shared = shared;
6060
atomic64_set(&state->read_count, 0);
6161

@@ -130,13 +130,19 @@ static long semaphore_ioctl(struct file *filp, unsigned int cmd, unsigned long a
130130
}
131131
}
132132

133+
static void semaphore_free(struct kref *kref)
134+
{
135+
struct semaphore_state *device;
136+
137+
device = container_of(kref, struct semaphore_state, ref);
138+
kfree(device);
139+
}
140+
133141
static int semaphore_release(struct inode *nodp, struct file *filp)
134142
{
135143
struct file_state *state = filp->private_data;
136144

137-
if (refcount_dec_and_test(&state->shared->ref))
138-
kfree(state->shared);
139-
145+
kref_put(&state->shared->ref, semaphore_free);
140146
kfree(state);
141147
return 0;
142148
}
@@ -162,7 +168,7 @@ static int __init semaphore_init(void)
162168
return -ENOMEM;
163169

164170
mutex_init(&state->mutex);
165-
refcount_set(&state->ref, 1);
171+
kref_init(&state->ref);
166172
init_waitqueue_head(&state->changed);
167173

168174
state->miscdev.fops = &semaphore_fops;
@@ -183,8 +189,7 @@ static int __init semaphore_init(void)
183189
static void __exit semaphore_exit(void)
184190
{
185191
misc_deregister(&device->miscdev);
186-
if (refcount_dec_and_test(&device->ref))
187-
kfree(device);
192+
kref_put(&device->ref, semaphore_free);
188193
}
189194

190195
module_init(semaphore_init);

0 commit comments

Comments
 (0)