linux 内核list head,Linux内核链表list_head扩展---klist

看SPI驱动核心模块时,看到用到很多klist,之前没多深入理解,现在来一步步分析源码。klist是对list_head的扩展,实现代码很少。内核代码:

include/linux/klist.h

lib/klist.c

----------------------

先要有一点点预备知识——list_head

----------------------

先看看头文件如何定义klist,以及一些基本操作方法接口。

----------------------

klist头文件    /* 头文件 */

1/*

2 *      klist.h - Some generic list helpers, extending struct list_head a bit.

3 *

4 *      Implementations are found in lib/klist.c

5 *

6 *

7 *      Copyright (C) 2005 Patrick Mochel

8 *

9 *      This file is rleased under the GPL v2.

10 */

11

12#ifndef _LINUX_KLIST_H

13#define _LINUX_KLIST_H

14

/* 自旋锁,这个过几天认真看下实现,具体作用就是多处理器的临界操作锁

* 对于嵌入式单处理器比较少用到

*/

15#include

/* 这个是内核引用次数的原子变量定义和原子操作

* 操作接口就是原子变量的增加get、减少put,以此实现内核对象引用次数操作

*/

16#include

/* 内核链表list_head */

17#include

18

/* 先声明klist_node节点,在后面定义 */

19struct klist_node;

/* klist结构体定义 */

20struct klist {

/* klist操作自旋锁 */

21        spinlock_t              k_lock;

/* 内核链表 */

22        struct list_head        k_list;

/* 获取klist_node节点方法 */

23        void                    (*get)(struct klist_node *);

/* 添加klist_node节点方法 */

24        void                    (*put)(struct klist_node *);

25} __attribute__ ((aligned (sizeof(void *))));/* 按指针大小对齐 */

26

/* 定义klist链表初始化宏

* 名字初始化锁、链表、get、put方法

*/

27#define KLIST_INIT(_name, _get, _put)                                   \

/* 初始化为解锁状态 */

28        { .k_lock       = __SPIN_LOCK_UNLOCKED(_name.k_lock),           \

/* 初始化链表 */

29          .k_list       = LIST_HEAD_INIT(_name.k_list),                 \

/* get方法 */

30          .get          = _get,                                         \

/* put方法 */

31          .put          = _put, }

32

/* 定义并初始化链表 */

33#define DEFINE_KLIST(_name, _get, _put)                                 \

34        struct klist _name = KLIST_INIT(_name, _get, _put)

35

/* klist初始化接口,在klist.c里具体分析 */

36extern void klist_init(struct klist *k, void (*get)(struct klist_node *),

37                       void (*put)(struct klist_node *));

38

/* 节点结构体 */

39struct klist_node {

40        void                    *n_klist;       /* never access directly */

/* 节点链表入口 */

41        struct list_head        n_node;

/* 引用次数的一个原子变量 */

42        struct kref             n_ref;

43};

44

/* 下面是链表操作方法声明,在klist.c具体分析 */

45extern void klist_add_tail(struct klist_node *n, struct klist *k);

46extern void klist_add_head(struct klist_node *n, struct klist *k);

47extern void klist_add_after(struct klist_node *n, struct klist_node *pos);

48extern void klist_add_before(struct klist_node *n, struct klist_node *pos);

49

50extern void klist_del(struct klist_node *n);

51extern void klist_remove(struct klist_node *n);

52

53extern int klist_node_attached(struct klist_node *n);

54

55

/* klist迭代器和操作方法,关于迭代器比较难理解,先看klist.c再说 */

56struct klist_iter {

57        struct klist            *i_klist;

58        struct klist_node       *i_cur;

59};

60

61

62extern void klist_iter_init(struct klist *k, struct klist_iter *i);

63extern void klist_iter_init_node(struct klist *k, struct klist_iter *i,

64                                 struct klist_node *n);

65extern void klist_iter_exit(struct klist_iter *i);

66extern struct klist_node *klist_next(struct klist_iter *i);

67

68#endif

69----------------------

klist实现代码   1/*

2 * klist.c - Routines for manipulating klists.

3 *

4 * Copyright (C) 2005 Patrick Mochel

5 *

6 * This file is released under the GPL v2.

7 *

8 * This klist interface provides a couple of structures that wrap around

9 * struct list_head to provide explicit list "head" (struct klist) and list

10 * "node" (struct klist_node) objects. For struct klist, a spinlock is

11 * included that protects access to the actual list itself. struct

12 * klist_node provides a pointer to the klist that owns it and a kref

13 * reference count that indicates the number of current users of that node

14 * in the list.

15 *

16 * The entire point is to provide an interface for iterating over a list

17 * that is safe and allows for modification of the list during the

18 * iteration (e.g. insertion and removal), including modification of the

19 * current node on the list.

20 *

21 * It works using a 3rd object type - struct klist_iter - that is declared

22 * and initialized before an iteration. klist_next() is used to acquire the

23 * next element in the list. It returns NULL if there are no more items.

24 * Internally, that routine takes the klist's lock, decrements the

25 * reference count of the previous klist_node and increments the count of

26 * the next klist_node. It then drops the lock and returns.

27 *

28 * There are primitives for adding and removing nodes to/from a klist.

29 * When deleting, klist_del() will simply decrement the reference count.

30 * Only when the count goes to 0 is the node removed from the list.

31 * klist_remove() will try to delete the node from the list and block until

32 * it is actually removed. This is useful for objects (like devices) that

33 * have been removed from the system and must be freed (but must wait until

34 * all accessors have finished).

35 */

36

37#include

38#include

39#include

40

/* 下面定义一些节点操作方法,先看下去,再来理解这些操作真正作用 */

41/*

42 * Use the lowest bit of n_klist to mark deleted nodes and exclude

43 * dead ones from iteration.

44 */

45#define KNODE_DEAD              1LU

46#define KNODE_KLIST_MASK        ~KNODE_DEAD

47

/* 由节点获取链表头 */

48static struct klist *knode_klist(struct klist_node *knode)

49{

50        return (struct klist *)

51                ((unsigned long)knode->n_klist & KNODE_KLIST_MASK);

52}

53

/* 判断节点“死了” */

54static bool knode_dead(struct klist_node *knode)

55{

56        return (unsigned long)knode->n_klist & KNODE_DEAD;

57}

58

/* 设置节点的链表 */

59static void knode_set_klist(struct klist_node *knode, struct klist *klist)

60{

61        knode->n_klist = klist;

62        /* no knode deserves to start its life dead */

/* 没有节点刚开始就是“死的” */

63        WARN_ON(knode_dead(knode));

64}

65

/* “杀死”节点 */

66static void knode_kill(struct klist_node *knode)

67{

68        /* and no knode should die twice ever either, see we're very humane */

/* 没有节点能“死”两次,瞧我们多人性化 */

69        WARN_ON(knode_dead(knode));

70        *(unsigned long *)&knode->n_klist |= KNODE_DEAD;

71}

72

73/**

74 * klist_init - Initialize a klist structure.

75 * @k: The klist we're initializing.

76 * @get: The get function for the embedding object (NULL if none)

77 * @put: The put function for the embedding object (NULL if none)

78 *

79 * Initialises the klist structure.  If the klist_node structures are

80 * going to be embedded in refcounted objects (necessary for safe

81 * deletion) then the get/put arguments are used to initialise

82 * functions that take and release references on the embedding

83 * objects.

84 */

/* klist初始化接口

* get/put方法用来操作klist_node

*/

85void klist_init(struct klist *k, void (*get)(struct klist_node *),

86                void (*put)(struct klist_node *))

87{

88        INIT_LIST_HEAD(&k->k_list);

89        spin_lock_init(&k->k_lock);

90        k->get = get;

91        k->put = put;

92}

93EXPORT_SYMBOL_GPL(klist_init);

94

/* 将节点加入到链表头 */

95static void add_head(struct klist *k, struct klist_node *n)

96{

97        spin_lock(&k->k_lock);

98        list_add(&n->n_node, &k->k_list);

99        spin_unlock(&k->k_lock);

100}

101

/* 将节点加入到链表尾 */

102static void add_tail(struct klist *k, struct klist_node *n)

103{

104        spin_lock(&k->k_lock);

105        list_add_tail(&n->n_node, &k->k_list);

106        spin_unlock(&k->k_lock);

107}

108

/* 节点初始化

* 包括初始化链表、引用计数、设置指向klist

*/

109static void klist_node_init(struct klist *k, struct klist_node *n)

110{

111        INIT_LIST_HEAD(&n->n_node);

112        kref_init(&n->n_ref);

113        knode_set_klist(n, k);

/* 如果klist的get方法存在,则调用获取节点 */

114        if (k->get)

115                k->get(n);

116}

117

118/**

119 * klist_add_head - Initialize a klist_node and add it to front.

120 * @n: node we're adding.

121 * @k: klist it's going on.

122 */

/* 将节点n初始化并加入到klist的头 */

123void klist_add_head(struct klist_node *n, struct klist *k)

124{

125        klist_node_init(k, n);

126        add_head(k, n);

127}

128EXPORT_SYMBOL_GPL(klist_add_head);

129

130/**

131 * klist_add_tail - Initialize a klist_node and add it to back.

132 * @n: node we're adding.

133 * @k: klist it's going on.

134 */

/* 将节点n初始化并加入到klist的尾 */

135void klist_add_tail(struct klist_node *n, struct klist *k)

136{

137        klist_node_init(k, n);

138        add_tail(k, n);

139}

140EXPORT_SYMBOL_GPL(klist_add_tail);

141

142/**

143 * klist_add_after - Init a klist_node and add it after an existing node

144 * @n: node we're adding.

145 * @pos: node to put @n after

146 */

/* 在节点pos后面插入节点n */

147void klist_add_after(struct klist_node *n, struct klist_node *pos)

148{

149        struct klist *k = knode_klist(pos);

150

151        klist_node_init(k, n);

152        spin_lock(&k->k_lock);

153        list_add(&n->n_node, &pos->n_node);

154        spin_unlock(&k->k_lock);

155}

156EXPORT_SYMBOL_GPL(klist_add_after);

157

158/**

159 * klist_add_before - Init a klist_node and add it before an existing node

160 * @n: node we're adding.

161 * @pos: node to put @n after

162 */

/* 在节点pos前面插入节点n */

163void klist_add_before(struct klist_node *n, struct klist_node *pos)

164{

165        struct klist *k = knode_klist(pos);

166

167        klist_node_init(k, n);

168        spin_lock(&k->k_lock);

169        list_add_tail(&n->n_node, &pos->n_node);

170        spin_unlock(&k->k_lock);

171}

172EXPORT_SYMBOL_GPL(klist_add_before);

173

/* 等待者结构体,用于删除节点,删除完成唤醒进程 */

174struct klist_waiter {

175        struct list_head list;

176        struct klist_node *node;

177        struct task_struct *process;

178        int woken;

179};

180

/* 定义并初始化klist节点移除自旋锁 */

181static DEFINE_SPINLOCK(klist_remove_lock);

/* 定义一个等待器的链表 */

182static LIST_HEAD(klist_remove_waiters);

183

184static void klist_release(struct kref *kref)

185{

186        struct klist_waiter *waiter, *tmp;

187        struct klist_node *n = container_of(kref, struct klist_node, n_ref);

188

189        WARN_ON(!knode_dead(n));

/* 删除链表中的节点入口 */

190        list_del(&n->n_node);

191        spin_lock(&klist_remove_lock);

/* 内核链表操作宏include/linux/list.h,遍历klist节点移除等待链表 */

192        list_for_each_entry_safe(waiter, tmp, &klist_remove_waiters, list) {

/* 是要删除链表节点的等待器 */

193                if (waiter->node != n)

194                        continue;

195

/* 等待者唤醒标志 */

196                waiter->woken = 1;

197                mb();

/* 唤醒等待进程 */

198                wake_up_process(waiter->process);

/* 删除链表入口 */

199                list_del(&waiter->list);

200        }

201        spin_unlock(&klist_remove_lock);

/* 设置节点n指向的klist为空 */

202        knode_set_klist(n, NULL);

203}

204

/* 减引用次数并删除节点 */

205static int klist_dec_and_del(struct klist_node *n)

206{

/* n->nref减引用次数,若引用次数减完不为0,调用klist_release清除节点对象,返回1;为0,则返回0 */

207        return kref_put(&n->n_ref, klist_release);

208}

209

/* 带锁操作的节点删除,不判断是否成功,减引用次数 */

210static void klist_put(struct klist_node *n, bool kill)

211{

/* 获取节点的put方法 */

212        struct klist *k = knode_klist(n);

213        void (*put)(struct klist_node *) = k->put;

214

215        spin_lock(&k->k_lock);

/* “需要杀死节点” = = */

216        if (kill)

217                knode_kill(n);

/* 节点对象引用次数为0了,则不需要调用put方法 */

218        if (!klist_dec_and_del(n))

219                put = NULL;

220        spin_unlock(&k->k_lock);

/* 调用put方法 */

221        if (put)

222                put(n);

223}

224

225/**

226 * klist_del - Decrement the reference count of node and try to remove.

227 * @n: node we're deleting.

228 */

/* 删除节点“杀死死节点 */

229void klist_del(struct klist_node *n)

230{

231        klist_put(n, true);

232}

233EXPORT_SYMBOL_GPL(klist_del);

234

235/**

236 * klist_remove - Decrement the refcount of node and wait for it to go away.

237 * @n: node we're removing.

238 */

239void klist_remove(struct klist_node *n)

240{

/* 定义一个等待者,并加入等待者加入移除等待者链表 */

241        struct klist_waiter waiter;

242

243        waiter.node = n;

244        waiter.process = current;

245        waiter.woken = 0;

246        spin_lock(&klist_remove_lock);

247        list_add(&waiter.list, &klist_remove_waiters);

248        spin_unlock(&klist_remove_lock);

249

/* 清除节点,并设置等待者 */

250        klist_del(n);

251

252        for (;;) {

/* 设置进程状态不可中断,等待 */

253                set_current_state(TASK_UNINTERRUPTIBLE);

/* 节点被删除,进程被唤醒 */

254                if (waiter.woken)

255                        break;

/* 内核调度器 */

256                schedule();

257        }

/* 设置当前进程状态为运行 */

258        __set_current_state(TASK_RUNNING);

259}

260EXPORT_SYMBOL_GPL(klist_remove);

261

262/**

263 * klist_node_attached - Say whether a node is bound to a list or not.

264 * @n: Node that we're testing.

265 */

/* 判断节点是不是链表边界 */

266int klist_node_attached(struct klist_node *n)

267{

268        return (n->n_klist != NULL);

269}

270EXPORT_SYMBOL_GPL(klist_node_attached);

271

272/**

273 * klist_iter_init_node - Initialize a klist_iter structure.

274 * @k: klist we're iterating.

275 * @i: klist_iter we're filling.

276 * @n: node to start with.

277 *

278 * Similar to klist_iter_init(), but starts the action off with @n,

279 * instead of with the list head.

280 */

/* 初始化迭代器节点,使用链表节点n */

281void klist_iter_init_node(struct klist *k, struct klist_iter *i,

282                          struct klist_node *n)

283{

284        i->i_klist = k;

285        i->i_cur = n;

286        if (n)

287                kref_get(&n->n_ref);

288}

289EXPORT_SYMBOL_GPL(klist_iter_init_node);

290

291/**

292 * klist_iter_init - Iniitalize a klist_iter structure.

293 * @k: klist we're iterating.

294 * @i: klist_iter structure we're filling.

295 *

296 * Similar to klist_iter_init_node(), but start with the list head.

297 */

/* 初始化迭代器节点,使用链表头 */

298void klist_iter_init(struct klist *k, struct klist_iter *i)

299{

300        klist_iter_init_node(k, i, NULL);

301}

302EXPORT_SYMBOL_GPL(klist_iter_init);

303

304/**

305 * klist_iter_exit - Finish a list iteration.

306 * @i: Iterator structure.

307 *

308 * Must be called when done iterating over list, as it decrements the

309 * refcount of the current node. Necessary in case iteration exited before

310 * the end of the list was reached, and always good form.

311 */

/* 结束链表迭代,必须在结束迭代链表时调用 */

312void klist_iter_exit(struct klist_iter *i)

313{

314        if (i->i_cur) {

315                klist_put(i->i_cur, false);

316                i->i_cur = NULL;

317        }

318}

319EXPORT_SYMBOL_GPL(klist_iter_exit);

320

/* 由链表入口获取节点 */

321static struct klist_node *to_klist_node(struct list_head *n)

322{

323        return container_of(n, struct klist_node, n_node);

324}

325

326/**

327 * klist_next - Ante up next node in list.

328 * @i: Iterator structure.

329 *

330 * First grab list lock. Decrement the reference count of the previous

331 * node, if there was one. Grab the next node, increment its reference

332 * count, drop the lock, and return that next node.

333 */

/* “预下”链表中下一节点 */

334struct klist_node *klist_next(struct klist_iter *i)

335{

336        void (*put)(struct klist_node *) = i->i_klist->put;

337        struct klist_node *last = i->i_cur;

338        struct klist_node *next;

339

/* 抢占锁 */

340        spin_lock(&i->i_klist->k_lock);

341

/* 获取下一节点 */

342        if (last) {

343                next = to_klist_node(last->n_node.next);

/* 减上一节点引用次数 */

344                if (!klist_dec_and_del(last))

345                        put = NULL;

346        } else

347                next = to_klist_node(i->i_klist->k_list.next);

348

349        i->i_cur = NULL;

/* 链表中有节点“没死”,增加引用次数 */

350        while (next != to_klist_node(&i->i_klist->k_list)) {

351                if (likely(!knode_dead(next))) {

352                        kref_get(&next->n_ref);

353                        i->i_cur = next;

354                        break;

355                }

356                next = to_klist_node(next->n_node.next);

357        }

358

/* 丢弃锁 */

359        spin_unlock(&i->i_klist->k_lock);

360

361        if (put && last)

362                put(last);

363        return i->i_cur;

364}

365EXPORT_SYMBOL_GPL(klist_next);

366----------------------

总结:

按面向对象的思想

klist是一个链表操作类,klist->k_list是链表入口,get/put是节点操作的方法。

knode是链表节点,knode->n_klist包括节点状态、链表入口, kref节点引用次数, n_node是节点链表入口

klist_iter是迭代器,是作为klist链表中查找特定对象的辅助结构体。查找特定的n_node

----------------------

结合内核驱动模型说明下klist的用法,实现代码在/drivers/base/core.c。

----------------------

klist的应用1178/**

1179 * device_for_each_child - device child iterator.

1180 * @parent: parent struct device.

1181 * @data: data for the callback.

1182 * @fn: function to be called for each device.

1183 *

1184 * Iterate over @parent's child devices, and call @fn for each,

1185 * passing it @data.

1186 *

1187 * We check the return of @fn each time. If it returns anything

1188 * other than 0, we break out and return that value.

1189 */

1190int device_for_each_child(struct device *parent, void *data,

1191                          int (*fn)(struct device *dev, void *data))

1192{

1193        struct klist_iter i;

1194        struct device *child;

1195        int error = 0;

1196

1197        if (!parent->p)

1198                return 0;

1199

/* 用链表头初始化迭代器 */

1200        klist_iter_init(&parent->p->klist_children, &i);

/* 使用迭代器的方法查找下一个设备 */

1201        while ((child = next_device(&i)) && !error)

1202                error = fn(child, data);

/* 结束迭代必须调用 */

1203        klist_iter_exit(&i);

1204        return error;

1205}

/*-------------------------------------------------------------------------------*/

/* 内核驱动中用于查找下一设备 */

1122static struct device *next_device(struct klist_iter *i)

1123{

/* 使用迭代查找下一链表节点 */

1124        struct klist_node *n = klist_next(i);

1125        struct device *dev = NULL;

1126        struct device_private *p;

1127

1128        if (n) {

/* 根据节点入口获取该节点上的设备 */

1129                p = to_device_private_parent(n);

1130                dev = p->device;

1131        }

1132        return dev;

1133}

/*-------------------------------------------------------------------------------*/

/* 其中device_private是设备私有数据结构,一下代码不难看出

* 想要由链表节点迭代查找设备非常容易

*/

66/**

67 * struct device_private - structure to hold the private to the driver core portions of the device structure.

68 *

69 * @klist_children - klist containing all children of this device

70 * @knode_parent - node in sibling list

71 * @knode_driver - node in driver list

72 * @knode_bus - node in bus list

73 * @driver_data - private pointer for driver specific info.  Will turn into a

74 * list soon.

75 * @device - pointer back to the struct class that this structure is

76 * associated with.

77 *

78 * Nothing outside of the driver core should ever touch these fields.

79 */

80struct device_private {

81        struct klist klist_children;

82        struct klist_node knode_parent;

83        struct klist_node knode_driver;

84        struct klist_node knode_bus;

85        void *driver_data;

86        struct device *device;

87};

88#define to_device_private_parent(obj)   \

89        container_of(obj, struct device_private, knode_parent)

90#define to_device_private_driver(obj)   \

91        container_of(obj, struct device_private, knode_driver)

92#define to_device_private_bus(obj)      \

93        container_of(obj, struct device_private, knode_bus)

  940b1331709591d260c1c78e86d0c51c18.png

你可能感兴趣的:(linux,内核list,head)