Skip to contentSkip to conversation

ACPI, APEI, GHES, printk support for recoverable error via NMI

PATCH In review Huang Ying 2 participants 11 messages Apr 26, 2011 – Apr 29, 2011

Subsystems (12)
x86 PowerPC ACPI Library code +8 more subsystems
lore
Share & tools
lore
author
#1 lore raw

PATCH 1/4 Add Kconfig option ARCH_HAVE_NMI_SAFE_CMPXCHG

In reply to Huang Ying

cmpxchg() is widely used by lockless code, including NMI-safe lockless code. But on some architectures, the cmpxchg() implementation is not NMI-safe, on these architectures the lockless code may need to a spin_trylock_irqsave() based implementation.

This patch adds a Kconfig option: ARCH_HAVE_NMI_SAFE_CMPXCHG, so that NMI-safe lockless code can depend on it or provide different implementation according to it.

On many architectures, cmpxchg is only NMI-safe for several specific operand sizes. So, ARCH_HAVE_NMI_SAFE_CMPXCHG define in this patch only guarantees cmpxchg is NMI-safe for sizeof(unsigned long).

CC Richard Henderson <[email protected]>
CC Mikael Starvik <[email protected]>
CC David Howells <[email protected]>
CC Yoshinori Sato <[email protected]>
CC Tony Luck <[email protected]>
CC Hirokazu Takata <[email protected]>
CC Geert Uytterhoeven <[email protected]>
CC Michal Simek <[email protected]>
CC Ralf Baechle <[email protected]>
CC Kyle McMartin <[email protected]>
CC Martin Schwidefsky <[email protected]>
CC Chen Liqin <[email protected]>
CC "David S. Miller" <[email protected]>
CC Ingo Molnar <[email protected]>
CC Chris Zankel <[email protected]>
---
 arch/Kconfig         |    3 +++
 arch/alpha/Kconfig   |    1 +
 arch/avr32/Kconfig   |    1 +
 arch/frv/Kconfig     |    1 +
 arch/ia64/Kconfig    |    1 +
 arch/m68k/Kconfig    |    1 +
 arch/parisc/Kconfig  |    1 +
 arch/powerpc/Kconfig |    1 +
 arch/s390/Kconfig    |    1 +
 arch/sh/Kconfig      |    1 +
 arch/sparc/Kconfig   |    1 +
 arch/tile/Kconfig    |    1 +
 arch/x86/Kconfig     |    1 +
 13 files changed, 15 insertions(+)
arch/Kconfig +3 -0
@@ -178,4 +178,7 @@ config HAVE_ARCH_JUMP_LABEL
 config HAVE_ARCH_MUTEX_CPU_RELAX
 	bool
 
+config ARCH_HAVE_NMI_SAFE_CMPXCHG
+	bool
+
 source "kernel/gcov/Kconfig"
arch/alpha/Kconfig +1 -0
@@ -12,6 +12,7 @@ config ALPHA
 	select GENERIC_IRQ_PROBE
 	select AUTO_IRQ_AFFINITY if SMP
 	select GENERIC_IRQ_SHOW
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 	help
 	  The Alpha is a 64-bit general-purpose processor designed and
 	  marketed by the Digital Equipment Corporation of blessed memory,
arch/avr32/Kconfig +1 -0
@@ -10,6 +10,7 @@ config AVR32
 	select GENERIC_IRQ_PROBE
 	select HARDIRQS_SW_RESEND
 	select GENERIC_IRQ_SHOW
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 	help
 	  AVR32 is a high-performance 32-bit RISC microprocessor core,
 	  designed for cost-sensitive embedded applications, with particular
arch/frv/Kconfig +1 -0
@@ -7,6 +7,7 @@ config FRV
 	select HAVE_PERF_EVENTS
 	select HAVE_GENERIC_HARDIRQS
 	select GENERIC_IRQ_SHOW
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 
 config ZONE_DMA
 	bool
arch/ia64/Kconfig +1 -0
@@ -27,6 +27,7 @@ config IA64
 	select GENERIC_PENDING_IRQ if SMP
 	select IRQ_PER_CPU
 	select GENERIC_IRQ_SHOW
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 	default y
 	help
 	  The Itanium Processor Family is Intel's 64-bit successor to
arch/m68k/Kconfig +1 -0
@@ -5,6 +5,7 @@ config M68K
 	select HAVE_AOUT if MMU
 	select GENERIC_ATOMIC64 if MMU
 	select HAVE_GENERIC_HARDIRQS if !MMU
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG if RMW_INSNS
 
 config RWSEM_GENERIC_SPINLOCK
 	bool
arch/parisc/Kconfig +1 -0
@@ -15,6 +15,7 @@ config PARISC
 	select HAVE_GENERIC_HARDIRQS
 	select GENERIC_IRQ_PROBE
 	select IRQ_PER_CPU
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 
 	help
 	  The PA-RISC microprocessor is designed by Hewlett-Packard and used
arch/powerpc/Kconfig +1 -0
@@ -140,6 +140,7 @@ config PPC
 	select IRQ_PER_CPU
 	select GENERIC_IRQ_SHOW
 	select GENERIC_IRQ_SHOW_LEVEL
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 
 config EARLY_PRINTK
 	bool
arch/s390/Kconfig +1 -0
@@ -81,6 +81,7 @@ config S390
 	select INIT_ALL_POSSIBLE
 	select HAVE_IRQ_WORK
 	select HAVE_PERF_EVENTS
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 	select HAVE_KERNEL_GZIP
 	select HAVE_KERNEL_BZIP2
 	select HAVE_KERNEL_LZMA
arch/sh/Kconfig +1 -0
@@ -11,6 +11,7 @@ config SUPERH
 	select HAVE_DMA_ATTRS
 	select HAVE_IRQ_WORK
 	select HAVE_PERF_EVENTS
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG if (GUSA_RB || CPU_SH4A)
 	select PERF_USE_VMALLOC
 	select HAVE_KERNEL_GZIP
 	select HAVE_KERNEL_BZIP2
arch/sparc/Kconfig +1 -0
@@ -53,6 +53,7 @@ config SPARC64
 	select HAVE_GENERIC_HARDIRQS
 	select GENERIC_IRQ_SHOW
 	select IRQ_PREFLOW_FASTEOI
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 
 config ARCH_DEFCONFIG
 	string
arch/tile/Kconfig +1 -0
@@ -12,6 +12,7 @@ config TILE
 	select GENERIC_IRQ_PROBE
 	select GENERIC_PENDING_IRQ if SMP
 	select GENERIC_IRQ_SHOW
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG if !M386
 
 # FIXME: investigate whether we need/want these options.
 #	select HAVE_IOREMAP_PROT
arch/x86/Kconfig +1 -0
@@ -72,6 +72,7 @@ config X86
 	select IRQ_FORCED_THREADING
 	select USE_GENERIC_SMP_HELPERS if SMP
 	select ARCH_NO_SYSDEV_OPS
+	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 
 config INSTRUCTION_DECODER
 	def_bool (KPROBES || PERF_EVENTS)
author
#2 lore raw

PATCH 2/4 lib, Add lock-less NULL terminated single list

In reply to Huang Ying

Cmpxchg is used to implement adding new entry to the list, deleting all entries from the list, deleting first entry of the list and some other operations.

Because this is a single list, so the tail can not be accessed in O(1).

If there are multiple producers and multiple consumers, llist_add can be used in producers and llist_del_all can be used in consumers. They can work simultaneously without lock. But llist_del_first can not be used here. Because llist_del_first depends on list->first->next does not changed if list->first is not changed during its operation, but llist_del_first, llist_add, llist_add (or llist_del_all, llist_add, llist_add) sequence in another consumer may violate that.

If there are multiple producers and one consumer, llist_add can be used in producers and llist_del_all or llist_del_first can be used in the consumer.

This can be summarized as follow:

           |   add    | del_first |  del_all
 add       |    -     |     -     |     -
 del_first |          |     L     |     L
 del_all   |          |           |     -

Where "-" stands for no lock is needed, while "L" stands for lock is needed.

The list entries deleted via llist_del_all can be traversed with traversing function such as llist_for_each etc. But the list entries can not be traversed safely before deleted from the list. The order of deleted entries is from the newest to the oldest added one. If you want to traverse from the oldest to the newest, you must reverse the order by yourself before traversing.

The basic atomic operation of this list is cmpxchg on long. On architectures that don't have NMI-safe cmpxchg implementation, the list can NOT be used in NMI handler. So code uses the list in NMI handler should depend on CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG.

---
 include/linux/llist.h |  126 ++++++++++++++++++++++++++++++++++++++++++++++++
 lib/Kconfig           |    3 +
 lib/Makefile          |    2 
 lib/llist.c           |  129 ++++++++++++++++++++++++++++++++++++++++++++++++++
 4 files changed, 260 insertions(+)
 create mode 100644 include/linux/llist.h
 create mode 100644 lib/llist.c
include/linux/llist.h new file +126 -0
@@ -0,0 +1,126 @@
+#ifndef LLIST_H
+#define LLIST_H
+/*
+ * Lock-less NULL terminated single linked list
+ *
+ * If there are multiple producers and multiple consumers, llist_add
+ * can be used in producers and llist_del_all can be used in
+ * consumers.  They can work simultaneously without lock.  But
+ * llist_del_first can not be used here.  Because llist_del_first
+ * depends on list->first->next does not changed if list->first is not
+ * changed during its operation, but llist_del_first, llist_add,
+ * llist_add (or llist_del_all, llist_add, llist_add) sequence in
+ * another consumer may violate that.
+ *
+ * If there are multiple producers and one consumer, llist_add can be
+ * used in producers and llist_del_all or llist_del_first can be used
+ * in the consumer.
+ *
+ * This can be summarized as follow:
+ *
+ *           |   add    | del_first |  del_all
+ * add       |    -     |     -     |     -
+ * del_first |          |     L     |     L
+ * del_all   |          |           |     -
+ *
+ * Where "-" stands for no lock is needed, while "L" stands for lock
+ * is needed.
+ *
+ * The list entries deleted via llist_del_all can be traversed with
+ * traversing function such as llist_for_each etc.  But the list
+ * entries can not be traversed safely before deleted from the list.
+ * The order of deleted entries is from the newest to the oldest added
+ * one.  If you want to traverse from the oldest to the newest, you
+ * must reverse the order by yourself before traversing.
+ *
+ * The basic atomic operation of this list is cmpxchg on long.  On
+ * architectures that don't have NMI-safe cmpxchg implementation, the
+ * list can NOT be used in NMI handler.  So code uses the list in NMI
+ * handler should depend on CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG.
+ */
+
+struct llist_head {
+	struct llist_node *first;
+};
+
+struct llist_node {
+	struct llist_node *next;
+};
+
+#define LLIST_HEAD_INIT(name)	{ NULL }
+#define LLIST_HEAD(name)	struct llist_head name = LLIST_HEAD_INIT(name)
+
+/**
+ * init_llist_head - initialize lock-less list head
+ * @head:	the head for your lock-less list
+ */
+static inline void init_llist_head(struct llist_head *list)
+{
+	list->first = NULL;
+}
+
+/**
+ * llist_entry - get the struct of this entry
+ * @ptr:	the &struct llist_node pointer.
+ * @type:	the type of the struct this is embedded in.
+ * @member:	the name of the llist_node within the struct.
+ */
+#define llist_entry(ptr, type, member)		\
+	container_of(ptr, type, member)
+
+/**
+ * llist_for_each - iterate over some deleted entries of a lock-less list
+ * @pos:	the &struct llist_node to use as a loop cursor
+ * @node:	the first entry of deleted list entries
+ *
+ * In general, some entries of the lock-less list can be traversed
+ * safely only after being deleted from list, so start with an entry
+ * instead of list head.
+ *
+ * If being used on entries deleted from lock-less list directly, the
+ * traverse order is from the newest to the oldest added entry.  If
+ * you want to traverse from the oldest to the newest, you must
+ * reverse the order by yourself before traversing.
+ */
+#define llist_for_each(pos, node)			\
+	for ((pos) = (node); pos; (pos) = (pos)->next)
+
+/**
+ * llist_for_each_entry - iterate over some deleted entries of lock-less list of given type
+ * @pos:	the type * to use as a loop cursor.
+ * @node:	the fist entry of deleted list entries.
+ * @member:	the name of the llist_node with the struct.
+ *
+ * In general, some entries of the lock-less list can be traversed
+ * safely only after being removed from list, so start with an entry
+ * instead of list head.
+ *
+ * If being used on entries deleted from lock-less list directly, the
+ * traverse order is from the newest to the oldest added entry.  If
+ * you want to traverse from the oldest to the newest, you must
+ * reverse the order by yourself before traversing.
+ */
+#define llist_for_each_entry(pos, node, member)				\
+	for ((pos) = llist_entry((node), typeof(*(pos)), member);	\
+	     &(pos)->member != NULL;					\
+	     (pos) = llist_entry((pos)->member.next, typeof(*(pos)), member))
+
+/**
+ * llist_empty - tests whether a lock-less list is empty
+ * @head:	the list to test
+ *
+ * Not guaranteed to be accurate or up to date.  Just a quick way to
+ * test whether the list is empty without deleting something from the
+ * list.
+ */
+static inline int llist_empty(const struct llist_head *head)
+{
+	return ACCESS_ONCE(head->first) == NULL;
+}
+
+void llist_add(struct llist_node *new, struct llist_head *head);
+void llist_add_batch(struct llist_node *new_first, struct llist_node *new_last,
+		     struct llist_head *head);
+struct llist_node *llist_del_first(struct llist_head *head);
+struct llist_node *llist_del_all(struct llist_head *head);
+#endif /* LLIST_H */
lib/Kconfig +3 -0
@@ -272,4 +272,7 @@ config AVERAGE
 
 	  If unsure, say N.
 
+config LLIST
+	bool
+
 endmenu
lib/Makefile +2 -0
@@ -115,6 +115,8 @@ obj-$(CONFIG_AVERAGE) += average.o
 
 obj-$(CONFIG_CPU_RMAP) += cpu_rmap.o
 
+obj-$(CONFIG_LLIST) += llist.o
+
 hostprogs-y	:= gen_crc32table
 clean-files	:= crc32table.h
 
lib/llist.c new file +129 -0

129 lines not on this page · raw message

author
#3 lore raw

PATCH 3/4 lib, Make gen_pool memory allocator lockless

In reply to Huang Ying

This version of the gen_pool memory allocator supports lockless operation.

This makes it safe to use in NMI handlers and other special unblockable contexts that could otherwise deadlock on locks. This is implemented by using atomic operations and retries on any conflicts. The disadvantage is that there may be livelocks in extreme cases. For better scalability, one gen_pool allocator can be used for each CPU.

The lockless operation only works if there is enough memory available. If new memory is added to the pool a lock has to be still taken. So any user relying on locklessness has to ensure that sufficient memory is preallocated.

The basic atomic operation of this allocator is cmpxchg on long. On architectures that don't have NMI-safe cmpxchg implementation, the allocator can NOT be used in NMI handler. So code uses the allocator in NMI handler should depend on CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG.

Cc Mathieu Desnoyers <[email protected]>
Cc Andrew Morton <[email protected]>
---
 include/linux/bitmap.h   |    1 
 include/linux/genalloc.h |   46 +++++++-
 lib/bitmap.c             |    2 
 lib/genalloc.c           |  259 ++++++++++++++++++++++++++++++++++++++---------
 4 files changed, 253 insertions(+), 55 deletions(-)
include/linux/bitmap.h +1 -0
@@ -142,6 +142,7 @@ extern void bitmap_release_region(unsign
 extern int bitmap_allocate_region(unsigned long *bitmap, int pos, int order);
 extern void bitmap_copy_le(void *dst, const unsigned long *src, int nbits);
 
+#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) % BITS_PER_LONG))
 #define BITMAP_LAST_WORD_MASK(nbits)					\
 (									\
 	((nbits) % BITS_PER_LONG) ?					\
include/linux/genalloc.h +40 -6

70 lines not on this page · raw message

lib/bitmap.c +0 -2
@@ -271,8 +271,6 @@ int __bitmap_weight(const unsigned long
 }
 EXPORT_SYMBOL(__bitmap_weight);
 
-#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) % BITS_PER_LONG))
-
 void bitmap_set(unsigned long *map, int start, int nr)
 {
 	unsigned long *p = map + BIT_WORD(start);
lib/genalloc.c +212 -47

333 lines not on this page · raw message

Huang Ying

author
#0 lore raw

cover ACPI, APEI, GHES, printk support for recoverable error via NMI

v4:

- Add rcu_read_lock/unlock in lockless gen_pool implementation, at least we need that for future pool shrinking support.

v3:

- Some changes to lock-less list based on Mathieu's comments

v2:

- Update some comments of llist per Mathieu's comments

[PATCH -v4 1/4] Add Kconfig option ARCH_HAVE_NMI_SAFE_CMPXCHG [PATCH -v4 2/4] lib, Add lock-less NULL terminated single list [PATCH -v4 3/4] lib, Make gen_pool memory allocator lockless [PATCH -v4 4/4] ACPI, APEI, GHES, printk support for recoverable error via NMI

author
#10 lore raw

PATCH 4/4 ACPI, APEI, GHES, printk support for recoverable error via NMI

Some APEI GHES recoverable errors are reported via NMI, but printk is not safe in NMI context.

To solve the issue, a lock-less memory allocator is used to allocate memory in NMI handler, save the error record into the allocated memory, put the error record into a lock-less list. On the other hand, a irq_work is used to delay the operation from NMI context to IRQ context. The irq_work IRQ handler will remove nodes from lock-less list, printk the error record and do some further processing include recovery operation, then free the memory.

---
 drivers/acpi/apei/Kconfig |    2 
 drivers/acpi/apei/ghes.c  |  188 ++++++++++++++++++++++++++++++++++++++++++----
 2 files changed, 176 insertions(+), 14 deletions(-)
drivers/acpi/apei/Kconfig +2 -0
@@ -12,6 +12,8 @@ config ACPI_APEI_GHES
 	tristate "APEI Generic Hardware Error Source"
 	depends on ACPI_APEI && X86
 	select ACPI_HED
+	select LLIST
+	select GENERIC_ALLOCATOR
 	help
 	  Generic Hardware Error Source provides a way to report
 	  platform hardware errors (such as that from chipset). It
drivers/acpi/apei/ghes.c +174 -14

327 lines not on this page · raw message

#4 lore raw

Re: [PATCH -v4 3/4] lib, Make gen_pool memory allocator lockless

In reply to Huang Ying
Quoted 14 lines · * Huang Ying ([email protected]) wrote:

This version of the gen_pool memory allocator supports lockless operation.

This makes it safe to use in NMI handlers and other special unblockable contexts that could otherwise deadlock on locks. This is implemented by using atomic operations and retries on any conflicts. The disadvantage is that there may be livelocks in extreme cases. For better scalability, one gen_pool allocator can be used for each CPU.

The lockless operation only works if there is enough memory available. If new memory is added to the pool a lock has to be still taken. So any user relying on locklessness has to ensure that sufficient memory is preallocated.

Quoted 4 lines

The basic atomic operation of this allocator is cmpxchg on long. On architectures that don't have NMI-safe cmpxchg implementation, the allocator can NOT be used in NMI handler. So code uses the allocator in NMI handler should depend on CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG.

Hi Huang,

Minor comment below,

Quoted 78 lines
Cc Mathieu Desnoyers <[email protected]>
Cc Andrew Morton <[email protected]>
---
 include/linux/bitmap.h   |    1 
 include/linux/genalloc.h |   46 +++++++-
 lib/bitmap.c             |    2 
 lib/genalloc.c           |  259 ++++++++++++++++++++++++++++++++++++++---------
 4 files changed, 253 insertions(+), 55 deletions(-)
include/linux/bitmap.h +1 -0
@@ -142,6 +142,7 @@ extern void bitmap_release_region(unsign
 extern int bitmap_allocate_region(unsigned long *bitmap, int pos, int order);
 extern void bitmap_copy_le(void *dst, const unsigned long *src, int nbits);
 
+#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) % BITS_PER_LONG))
 #define BITMAP_LAST_WORD_MASK(nbits)					\
 (									\
 	((nbits) % BITS_PER_LONG) ?					\
include/linux/genalloc.h +26 -6
@@ -1,8 +1,28 @@
+#ifndef GENALLOC_H
+#define GENALLOC_H
 /*
- * Basic general purpose allocator for managing special purpose memory
- * not managed by the regular kmalloc/kfree interface.
- * Uses for this includes on-device special memory, uncached memory
- * etc.
+ * Basic general purpose allocator for managing special purpose
+ * memory, for example, memory that is not managed by the regular
+ * kmalloc/kfree interface.  Uses for this includes on-device special
+ * memory, uncached memory etc.
+ *
+ * It is safe to use the allocator in NMI handlers and other special
+ * unblockable contexts that could otherwise deadlock on locks.  This
+ * is implemented by using atomic operations and retries on any
+ * conflicts.  The disadvantage is that there may be livelocks in
+ * extreme cases.  For better scalability, one allocator can be used
+ * for each CPU.
+ *
+ * The lockless operation only works if there is enough memory
+ * available.  If new memory is added to the pool a lock has to be
+ * still taken.  So any user relying on locklessness has to ensure
+ * that sufficient memory is preallocated.
+ *
+ * The basic atomic operation of this allocator is cmpxchg on long.
+ * On architectures that don't have NMI-safe cmpxchg implementation,
+ * the allocator can NOT be used in NMI handler.  So code uses the
+ * allocator in NMI handler should depend on
+ * CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG.
  *
  * This source code is licensed under the GNU General Public License,
  * Version 2.  See the file COPYING for more details.
@@ -13,7 +33,7 @@
  *  General purpose special memory pool descriptor.
  */
 struct gen_pool {
-	rwlock_t lock;
+	spinlock_t lock;
 	struct list_head chunks;	/* list of chunks in this pool */
 	int min_alloc_order;		/* minimum allocation order */
 };
@@ -22,15 +42,29 @@ struct gen_pool {
  *  General purpose special memory pool chunk descriptor.
  */
 struct gen_pool_chunk {
-	spinlock_t lock;
 	struct list_head next_chunk;	/* next chunk in pool */
+	atomic_t avail;
 	unsigned long start_addr;	/* starting address of memory chunk */
 	unsigned long end_addr;		/* ending address of memory chunk */
 	unsigned long bits[0];		/* bitmap for allocating memory chunk */
 };
 

include/linux/genalloc.h struct gen_pool { · line 61

Quoted 10 lines
include/linux/genalloc.h +10 -0
+/**
+ * gen_pool_for_each_chunk - iterate over chunks of generic memory pool
+ * @chunk:	the struct gen_pool_chunk * to use as a loop cursor
+ * @pool:	the generic memory pool
+ *
+ * Not lockless, proper mutual exclusion is needed to use this macro
+ * with other gen_pool function simultaneously.
+ */
+#define gen_pool_for_each_chunk(chunk, pool)			\
+	list_for_each_entry_rcu(chunk, &(pool)->chunks, next_chunk)

Is it just me or this macro is never used ? Maybe you should consider removing it.

Quoted 254 lines
include/linux/genalloc.h +4 -0
+
 extern struct gen_pool *gen_pool_create(int, int);
 extern int gen_pool_add(struct gen_pool *, unsigned long, size_t, int);
 extern void gen_pool_destroy(struct gen_pool *);
 extern unsigned long gen_pool_alloc(struct gen_pool *, size_t);
 extern void gen_pool_free(struct gen_pool *, unsigned long, size_t);
+extern size_t gen_pool_avail(struct gen_pool *);
+extern size_t gen_pool_size(struct gen_pool *);
+#endif /* GENALLOC_H */
lib/bitmap.c +0 -2
@@ -271,8 +271,6 @@ int __bitmap_weight(const unsigned long
 }
 EXPORT_SYMBOL(__bitmap_weight);
 
-#define BITMAP_FIRST_WORD_MASK(start) (~0UL << ((start) % BITS_PER_LONG))
-
 void bitmap_set(unsigned long *map, int start, int nr)
 {
 	unsigned long *p = map + BIT_WORD(start);
lib/genalloc.c +151 -25
@@ -1,8 +1,26 @@
 /*
- * Basic general purpose allocator for managing special purpose memory
- * not managed by the regular kmalloc/kfree interface.
- * Uses for this includes on-device special memory, uncached memory
- * etc.
+ * Basic general purpose allocator for managing special purpose
+ * memory, for example, memory that is not managed by the regular
+ * kmalloc/kfree interface.  Uses for this includes on-device special
+ * memory, uncached memory etc.
+ *
+ * It is safe to use the allocator in NMI handlers and other special
+ * unblockable contexts that could otherwise deadlock on locks.  This
+ * is implemented by using atomic operations and retries on any
+ * conflicts.  The disadvantage is that there may be livelocks in
+ * extreme cases.  For better scalability, one allocator can be used
+ * for each CPU.
+ *
+ * The lockless operation only works if there is enough memory
+ * available.  If new memory is added to the pool a lock has to be
+ * still taken.  So any user relying on locklessness has to ensure
+ * that sufficient memory is preallocated.
+ *
+ * The basic atomic operation of this allocator is cmpxchg on long.
+ * On architectures that don't have NMI-safe cmpxchg implementation,
+ * the allocator can NOT be used in NMI handler.  So code uses the
+ * allocator in NMI handler should depend on
+ * CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG.
  *
  * Copyright 2005 (C) Jes Sorensen <[email protected]>
  *
@@ -13,8 +31,109 @@
 #include <linux/slab.h>
 #include <linux/module.h>
 #include <linux/bitmap.h>
+#include <linux/rculist.h>
+#include <linux/interrupt.h>
 #include <linux/genalloc.h>
 
+static int set_bits_ll(unsigned long *addr, unsigned long mask_to_set)
+{
+	unsigned long val, nval;
+
+	nval = *addr;
+	do {
+		val = nval;
+		if (val & mask_to_set)
+			return -EBUSY;
+		cpu_relax();
+	} while ((nval = cmpxchg(addr, val, val | mask_to_set)) != val);
+
+	return 0;
+}
+
+static int clear_bits_ll(unsigned long *addr, unsigned long mask_to_clear)
+{
+	unsigned long val, nval;
+
+	nval = *addr;
+	do {
+		val = nval;
+		if ((val & mask_to_clear) != mask_to_clear)
+			return -EBUSY;
+		cpu_relax();
+	} while ((nval = cmpxchg(addr, val, val & ~mask_to_clear)) != val);
+
+	return 0;
+}
+
+/*
+ * bitmap_set_ll - set the specified number of bits at the specified position
+ * @map: pointer to a bitmap
+ * @start: a bit position in @map
+ * @nr: number of bits to set
+ *
+ * Set @nr bits start from @start in @map lock-lessly. Several users
+ * can set/clear the same bitmap simultaneously without lock. If two
+ * users set the same bit, one user will return remain bits, otherwise
+ * return 0.
+ */
+static int bitmap_set_ll(unsigned long *map, int start, int nr)
+{
+	unsigned long *p = map + BIT_WORD(start);
+	const int size = start + nr;
+	int bits_to_set = BITS_PER_LONG - (start % BITS_PER_LONG);
+	unsigned long mask_to_set = BITMAP_FIRST_WORD_MASK(start);
+
+	while (nr - bits_to_set >= 0) {
+		if (set_bits_ll(p, mask_to_set))
+			return nr;
+		nr -= bits_to_set;
+		bits_to_set = BITS_PER_LONG;
+		mask_to_set = ~0UL;
+		p++;
+	}
+	if (nr) {
+		mask_to_set &= BITMAP_LAST_WORD_MASK(size);
+		if (set_bits_ll(p, mask_to_set))
+			return nr;
+	}
+
+	return 0;
+}
+
+/*
+ * bitmap_clear_ll - clear the specified number of bits at the specified position
+ * @map: pointer to a bitmap
+ * @start: a bit position in @map
+ * @nr: number of bits to set
+ *
+ * Clear @nr bits start from @start in @map lock-lessly. Several users
+ * can set/clear the same bitmap simultaneously without lock. If two
+ * users clear the same bit, one user will return remain bits,
+ * otherwise return 0.
+ */
+static int bitmap_clear_ll(unsigned long *map, int start, int nr)
+{
+	unsigned long *p = map + BIT_WORD(start);
+	const int size = start + nr;
+	int bits_to_clear = BITS_PER_LONG - (start % BITS_PER_LONG);
+	unsigned long mask_to_clear = BITMAP_FIRST_WORD_MASK(start);
+
+	while (nr - bits_to_clear >= 0) {
+		if (clear_bits_ll(p, mask_to_clear))
+			return nr;
+		nr -= bits_to_clear;
+		bits_to_clear = BITS_PER_LONG;
+		mask_to_clear = ~0UL;
+		p++;
+	}
+	if (nr) {
+		mask_to_clear &= BITMAP_LAST_WORD_MASK(size);
+		if (clear_bits_ll(p, mask_to_clear))
+			return nr;
+	}
+
+	return 0;
+}
 
 /**
  * gen_pool_create - create a new special memory pool
@@ -30,7 +149,7 @@ struct gen_pool *gen_pool_create(int min
 
 	pool = kmalloc_node(sizeof(struct gen_pool), GFP_KERNEL, nid);
 	if (pool != NULL) {
-		rwlock_init(&pool->lock);
+		spin_lock_init(&pool->lock);
 		INIT_LIST_HEAD(&pool->chunks);
 		pool->min_alloc_order = min_alloc_order;
 	}
@@ -58,15 +177,15 @@ int gen_pool_add(struct gen_pool *pool,
 
 	chunk = kmalloc_node(nbytes, GFP_KERNEL | __GFP_ZERO, nid);
 	if (unlikely(chunk == NULL))
-		return -1;
+		return -ENOMEM;
 
-	spin_lock_init(&chunk->lock);
 	chunk->start_addr = addr;
 	chunk->end_addr = addr + size;
+	atomic_set(&chunk->avail, size);
 
-	write_lock(&pool->lock);
-	list_add(&chunk->next_chunk, &pool->chunks);
-	write_unlock(&pool->lock);
+	spin_lock(&pool->lock);
+	list_add_rcu(&chunk->next_chunk, &pool->chunks);
+	spin_unlock(&pool->lock);
 
 	return 0;
 }
@@ -86,7 +205,6 @@ void gen_pool_destroy(struct gen_pool *p
 	int order = pool->min_alloc_order;
 	int bit, end_bit;
 
-
 	list_for_each_safe(_chunk, _next_chunk, &pool->chunks) {
 		chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
 		list_del(&chunk->next_chunk);
@@ -108,43 +226,50 @@ EXPORT_SYMBOL(gen_pool_destroy);
  * @size: number of bytes to allocate from the pool
  *
  * Allocate the requested number of bytes from the specified pool.
- * Uses a first-fit algorithm.
+ * Uses a first-fit algorithm. Can not be used in NMI handler on
+ * architectures without NMI-safe cmpxchg implementation.
  */
 unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)
 {
-	struct list_head *_chunk;
 	struct gen_pool_chunk *chunk;
-	unsigned long addr, flags;
+	unsigned long addr;
 	int order = pool->min_alloc_order;
-	int nbits, start_bit, end_bit;
+	int nbits, start_bit = 0, end_bit, remain;
+
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+	BUG_ON(in_nmi());
+#endif
 
 	if (size == 0)
 		return 0;
 
 	nbits = (size + (1UL << order) - 1) >> order;
-
-	read_lock(&pool->lock);
-	list_for_each(_chunk, &pool->chunks) {
-		chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+	rcu_read_lock();
+	list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
+		if (size > atomic_read(&chunk->avail))
+			continue;
 
 		end_bit = (chunk->end_addr - chunk->start_addr) >> order;
-
-		spin_lock_irqsave(&chunk->lock, flags);
-		start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit, 0,
-						nbits, 0);
-		if (start_bit >= end_bit) {
-			spin_unlock_irqrestore(&chunk->lock, flags);
+retry:
+		start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit,
+						       start_bit, nbits, 0);
+		if (start_bit >= end_bit)
 			continue;
+		remain = bitmap_set_ll(chunk->bits, start_bit, nbits);
+		if (remain) {
+			remain = bitmap_clear_ll(chunk->bits, start_bit,
+						 nbits - remain);
+			BUG_ON(remain);
+			goto retry;

lib/genalloc.c EXPORT_SYMBOL(gen_pool_destroy); · line 269

Quoted 10 lines
lib/genalloc.c +3 -4
 		}
 
 		addr = chunk->start_addr + ((unsigned long)start_bit << order);
-
-		bitmap_set(chunk->bits, start_bit, nbits);
-		spin_unlock_irqrestore(&chunk->lock, flags);
-		read_unlock(&pool->lock);
+		size = nbits << order;
+		atomic_sub(size, &chunk->avail);
+		rcu_read_unlock();

I don't really like seeing a rcu_read_unlock() within a rcu list iteration (even if it comes right before a "return"). Doing:

unsigned long addr = 0;

rcu_read_lock();
list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
if (...)

    continue;

...
addr = ...;
break;
}
rcu_read_unlock();
return addr;

Would be more symmetric, and would remove one return path, which makes the code easier to modify in the future.

Quoted 41 lines
lib/genalloc.c +11 -12
 		return addr;
 	}
-	read_unlock(&pool->lock);
+	rcu_read_unlock();
 	return 0;
 }
 EXPORT_SYMBOL(gen_pool_alloc);
@@ -155,33 +280,73 @@ EXPORT_SYMBOL(gen_pool_alloc);
  * @addr: starting address of memory to free back to pool
  * @size: size in bytes of memory to free
  *
- * Free previously allocated special memory back to the specified pool.
+ * Free previously allocated special memory back to the specified
+ * pool.  Can not be used in NMI handler on architectures without
+ * NMI-safe cmpxchg implementation.
  */
 void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 {
-	struct list_head *_chunk;
 	struct gen_pool_chunk *chunk;
-	unsigned long flags;
 	int order = pool->min_alloc_order;
-	int bit, nbits;
+	int start_bit, nbits, remain;
 
-	nbits = (size + (1UL << order) - 1) >> order;
-
-	read_lock(&pool->lock);
-	list_for_each(_chunk, &pool->chunks) {
-		chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+	BUG_ON(in_nmi());
+#endif
 
+	nbits = (size + (1UL << order) - 1) >> order;
+	rcu_read_lock();
+	list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
 		if (addr >= chunk->start_addr && addr < chunk->end_addr) {
 			BUG_ON(addr + size > chunk->end_addr);
-			spin_lock_irqsave(&chunk->lock, flags);
-			bit = (addr - chunk->start_addr) >> order;

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 307

Quoted 10 lines
lib/genalloc.c +6 -4
-			while (nbits--)
-				__clear_bit(bit++, chunk->bits);
-			spin_unlock_irqrestore(&chunk->lock, flags);
-			break;
+			start_bit = (addr - chunk->start_addr) >> order;
+			remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
+			BUG_ON(remain);
+			size = nbits << order;
+			atomic_add(size, &chunk->avail);
+			rcu_read_unlock();

Same comment as above apply here.

Thanks,

Mathieu

Quoted 47 lines
lib/genalloc.c +41 -2
+			return;
 		}
 	}
-	BUG_ON(nbits > 0);
-	read_unlock(&pool->lock);
+	rcu_read_unlock();
+	BUG();
 }
 EXPORT_SYMBOL(gen_pool_free);
+
+/**
+ * gen_pool_avail - get available free space of the pool
+ * @pool: pool to get available free space
+ *
+ * Return available free space of the specified pool.
+ */
+size_t gen_pool_avail(struct gen_pool *pool)
+{
+	struct gen_pool_chunk *chunk;
+	size_t avail = 0;
+
+	rcu_read_lock();
+	list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk)
+		avail += atomic_read(&chunk->avail);
+	rcu_read_unlock();
+	return avail;
+}
+EXPORT_SYMBOL_GPL(gen_pool_avail);
+
+/**
+ * gen_pool_size - get size in bytes of memory managed by the pool
+ * @pool: pool to get size
+ *
+ * Return size in bytes of memory managed by the pool.
+ */
+size_t gen_pool_size(struct gen_pool *pool)
+{
+	struct gen_pool_chunk *chunk;
+	size_t size = 0;
+
+	rcu_read_lock();
+	list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk)
+		size += chunk->end_addr - chunk->start_addr;
+	rcu_read_unlock();
+	return size;
+}
+EXPORT_SYMBOL_GPL(gen_pool_size);
Signature · 4 lines
Mathieu Desnoyers
Operating System Efficiency R&D Consultant
EfficiOS Inc.
http://www.efficios.com
author
#5 lore raw

Re: [PATCH -v4 3/4] lib, Make gen_pool memory allocator lockless

Hi, Mathieu,

Thanks for your comments.

Quoted 1 line · Mathieu Desnoyers

* Huang Ying ([email protected]) wrote:

[snip]

Quoted 14 lines

include/linux/genalloc.h struct gen_pool { · line 61

Quoted 11 lines
include/linux/genalloc.h +10 -0
+/**
+ * gen_pool_for_each_chunk - iterate over chunks of generic memory pool
+ * @chunk:   the struct gen_pool_chunk * to use as a loop cursor
+ * @pool:    the generic memory pool
+ *
+ * Not lockless, proper mutual exclusion is needed to use this macro
+ * with other gen_pool function simultaneously.
+ */
+#define gen_pool_for_each_chunk(chunk, pool)                 \
+     list_for_each_entry_rcu(chunk, &(pool)->chunks, next_chunk)

Is it just me or this macro is never used ? Maybe you should consider removing it.

This macro is not used in this patch. But it is used in 4/4 of the patchset to free the backing pages before destroy the pool.

[snip]

Quoted 80 lines
Quoted 53 lines
lib/genalloc.c +22 -14
@@ -108,43 +226,50 @@ EXPORT_SYMBOL(gen_pool_destroy);
  * @size: number of bytes to allocate from the pool
  *
  * Allocate the requested number of bytes from the specified pool.
- * Uses a first-fit algorithm.
+ * Uses a first-fit algorithm. Can not be used in NMI handler on
+ * architectures without NMI-safe cmpxchg implementation.
  */
 unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long addr, flags;
+     unsigned long addr;
      int order = pool->min_alloc_order;
-     int nbits, start_bit, end_bit;
+     int nbits, start_bit = 0, end_bit, remain;
+
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
      if (size == 0)
              return 0;
 
      nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
+             if (size > atomic_read(&chunk->avail))
+                     continue;
 
              end_bit = (chunk->end_addr - chunk->start_addr) >> order;
-
-             spin_lock_irqsave(&chunk->lock, flags);
-             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit, 0,
-                                             nbits, 0);
-             if (start_bit >= end_bit) {
-                     spin_unlock_irqrestore(&chunk->lock, flags);
+retry:
+             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit,
+                                                    start_bit, nbits, 0);
+             if (start_bit >= end_bit)
                      continue;
+             remain = bitmap_set_ll(chunk->bits, start_bit, nbits);
+             if (remain) {
+                     remain = bitmap_clear_ll(chunk->bits, start_bit,
+                                              nbits - remain);
+                     BUG_ON(remain);
+                     goto retry;

lib/genalloc.c EXPORT_SYMBOL(gen_pool_destroy); · line 269

Quoted 10 lines
lib/genalloc.c +3 -4
              }
 
              addr = chunk->start_addr + ((unsigned long)start_bit << order);
-
-             bitmap_set(chunk->bits, start_bit, nbits);
-             spin_unlock_irqrestore(&chunk->lock, flags);
-             read_unlock(&pool->lock);
+             size = nbits << order;
+             atomic_sub(size, &chunk->avail);
+             rcu_read_unlock();

I don't really like seeing a rcu_read_unlock() within a rcu list iteration (even if it comes right before a "return"). Doing:

unsigned long addr = 0;

rcu_read_lock();
list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
if (...)

    continue;

...
addr = ...;
break;
}
rcu_read_unlock();
return addr;

Quoted 2 lines

Would be more symmetric, and would remove one return path, which makes the code easier to modify in the future.

Unlock in loop is common in Linux kernel. Sometimes it makes code cleaner (but not always). Yes, for this case, we can avoid unlock in loop easily. But for the next case it is not so clean.

Quoted 45 lines
Quoted 45 lines
lib/genalloc.c +11 -16
              return addr;
      }
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
      return 0;
 }
 EXPORT_SYMBOL(gen_pool_alloc);
@@ -155,33 +280,73 @@ EXPORT_SYMBOL(gen_pool_alloc);
  * @addr: starting address of memory to free back to pool
  * @size: size in bytes of memory to free
  *
- * Free previously allocated special memory back to the specified pool.
+ * Free previously allocated special memory back to the specified
+ * pool.  Can not be used in NMI handler on architectures without
+ * NMI-safe cmpxchg implementation.
  */
 void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long flags;
      int order = pool->min_alloc_order;
-     int bit, nbits;
+     int start_bit, nbits, remain;
 
-     nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
+     nbits = (size + (1UL << order) - 1) >> order;
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
              if (addr >= chunk->start_addr && addr < chunk->end_addr) {
                      BUG_ON(addr + size > chunk->end_addr);
-                     spin_lock_irqsave(&chunk->lock, flags);
-                     bit = (addr - chunk->start_addr) >> order;
-                     while (nbits--)
-                             __clear_bit(bit++, chunk->bits);
-                     spin_unlock_irqrestore(&chunk->lock, flags);
-                     break;
Quoted 8 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 307

Quoted 6 lines
lib/genalloc.c +6 -0
+                     start_bit = (addr - chunk->start_addr) >> order;
+                     remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
+                     BUG_ON(remain);
+                     size = nbits << order;
+                     atomic_add(size, &chunk->avail);
+                     rcu_read_unlock();

Same comment as above apply here.

It is harder to remove unlock in loop here. An extra variable should be used to indicate that something is freed from the pool. Do you think it is cleaner to just keep the unlock in loop here?

Best Regards,
Huang Ying

Quoted 8 lines
lib/genalloc.c +3 -2
+                     return;
              }
      }
-     BUG_ON(nbits > 0);
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
+     BUG();
 }

[snip]

#6 lore raw

Re: [PATCH -v4 3/4] lib, Make gen_pool memory allocator lockless

Quoted 22 lines · * Huang Ying ([email protected]) wrote:

Hi, Mathieu,

Thanks for your comments.

Quoted 1 line · Mathieu Desnoyers

* Huang Ying ([email protected]) wrote:

[snip]

Quoted 14 lines

include/linux/genalloc.h struct gen_pool { · line 61

Quoted 11 lines
include/linux/genalloc.h +10 -0
+/**
+ * gen_pool_for_each_chunk - iterate over chunks of generic memory pool
+ * @chunk:   the struct gen_pool_chunk * to use as a loop cursor
+ * @pool:    the generic memory pool
+ *
+ * Not lockless, proper mutual exclusion is needed to use this macro
+ * with other gen_pool function simultaneously.
+ */
+#define gen_pool_for_each_chunk(chunk, pool)                 \
+     list_for_each_entry_rcu(chunk, &(pool)->chunks, next_chunk)

Is it just me or this macro is never used ? Maybe you should consider removing it.

Quoted 2 lines

This macro is not used in this patch. But it is used in 4/4 of the patchset to free the backing pages before destroy the pool.

Depending on how frequently you want to use it, you might want to use list_for_each_entry_rcu directly rather than a macro wrapper. E.g. for 2-3 uses, adding a macro just obfuscates the code IMHO (e.g. you don't know it iterates on a RCU list by looking at the caller code).

Quoted 82 lines

[snip]

Quoted 80 lines
Quoted 53 lines
lib/genalloc.c +22 -14
@@ -108,43 +226,50 @@ EXPORT_SYMBOL(gen_pool_destroy);
  * @size: number of bytes to allocate from the pool
  *
  * Allocate the requested number of bytes from the specified pool.
- * Uses a first-fit algorithm.
+ * Uses a first-fit algorithm. Can not be used in NMI handler on
+ * architectures without NMI-safe cmpxchg implementation.
  */
 unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long addr, flags;
+     unsigned long addr;
      int order = pool->min_alloc_order;
-     int nbits, start_bit, end_bit;
+     int nbits, start_bit = 0, end_bit, remain;
+
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
      if (size == 0)
              return 0;
 
      nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
+             if (size > atomic_read(&chunk->avail))
+                     continue;
 
              end_bit = (chunk->end_addr - chunk->start_addr) >> order;
-
-             spin_lock_irqsave(&chunk->lock, flags);
-             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit, 0,
-                                             nbits, 0);
-             if (start_bit >= end_bit) {
-                     spin_unlock_irqrestore(&chunk->lock, flags);
+retry:
+             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit,
+                                                    start_bit, nbits, 0);
+             if (start_bit >= end_bit)
                      continue;
+             remain = bitmap_set_ll(chunk->bits, start_bit, nbits);
+             if (remain) {
+                     remain = bitmap_clear_ll(chunk->bits, start_bit,
+                                              nbits - remain);
+                     BUG_ON(remain);
+                     goto retry;

lib/genalloc.c EXPORT_SYMBOL(gen_pool_destroy); · line 269

Quoted 10 lines
lib/genalloc.c +3 -4
              }
 
              addr = chunk->start_addr + ((unsigned long)start_bit << order);
-
-             bitmap_set(chunk->bits, start_bit, nbits);
-             spin_unlock_irqrestore(&chunk->lock, flags);
-             read_unlock(&pool->lock);
+             size = nbits << order;
+             atomic_sub(size, &chunk->avail);
+             rcu_read_unlock();

I don't really like seeing a rcu_read_unlock() within a rcu list iteration (even if it comes right before a "return"). Doing:

unsigned long addr = 0;

rcu_read_lock();
list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
if (...)

    continue;

...
addr = ...;
break;
}
rcu_read_unlock();
return addr;

Quoted 6 lines
Quoted 2 lines

Would be more symmetric, and would remove one return path, which makes the code easier to modify in the future.

Unlock in loop is common in Linux kernel. Sometimes it makes code cleaner (but not always). Yes, for this case, we can avoid unlock in loop easily. But for the next case it is not so clean.

See comment below,

Quoted 35 lines
Quoted 35 lines
Quoted 35 lines
lib/genalloc.c +8 -10
              return addr;
      }
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
      return 0;
 }
 EXPORT_SYMBOL(gen_pool_alloc);
@@ -155,33 +280,73 @@ EXPORT_SYMBOL(gen_pool_alloc);
  * @addr: starting address of memory to free back to pool
  * @size: size in bytes of memory to free
  *
- * Free previously allocated special memory back to the specified pool.
+ * Free previously allocated special memory back to the specified
+ * pool.  Can not be used in NMI handler on architectures without
+ * NMI-safe cmpxchg implementation.
  */
 void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long flags;
      int order = pool->min_alloc_order;
-     int bit, nbits;
+     int start_bit, nbits, remain;
 
-     nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
Quoted 1 line
Quoted 1 line

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 297

Quoted 1 line
lib/genalloc.c +1 -0
+     nbits = (size + (1UL << order) - 1) >> order;

you could add:

  remain = nbits;
Quoted 11 lines
Quoted 11 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 302

Quoted 11 lines
lib/genalloc.c +3 -6
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
              if (addr >= chunk->start_addr && addr < chunk->end_addr) {
                      BUG_ON(addr + size > chunk->end_addr);
-                     spin_lock_irqsave(&chunk->lock, flags);
-                     bit = (addr - chunk->start_addr) >> order;
-                     while (nbits--)
-                             __clear_bit(bit++, chunk->bits);
-                     spin_unlock_irqrestore(&chunk->lock, flags);
-                     break;
+                     start_bit = (addr - chunk->start_addr) >> order;

You could turn this:

Quoted 4 lines
Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 306

Quoted 4 lines
lib/genalloc.c +4 -0
+                     remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
+                     BUG_ON(remain);
+                     size = nbits << order;
+                     atomic_add(size, &chunk->avail);

into:

  remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
  size = nbits << order;
  atomic_add(size, &chunk->avail);
  break;
Quoted 14 lines
Quoted 3 lines

Review EXPORT_SYMBOL(gen_pool_alloc); · line 307

Quoted 1 line
(quoted diff) +1 -0
+                     rcu_read_unlock();

Same comment as above apply here.

It is harder to remove unlock in loop here. An extra variable should be used to indicate that something is freed from the pool. Do you think it is cleaner to just keep the unlock in loop here?

Best Regards,
Huang Ying

Quoted 3 lines
+                     return;
              }
      }

And turn this:

Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 312

Quoted 4 lines
lib/genalloc.c +2 -2
-     BUG_ON(nbits > 0);
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
+     BUG();

into:

  BUG_ON(remain);
  rcu_read_unlock();

Does that look OK to you ? On the plus side, you end up having a single BUG_ON() in the function.

Thanks,

Mathieu

Quoted 2 lines
Quoted 1 line

}

[snip]

Signature · 4 lines
Mathieu Desnoyers
Operating System Efficiency R&D Consultant
EfficiOS Inc.
http://www.efficios.com
author
#7 lore raw

Re: [PATCH -v4 3/4] lib, Make gen_pool memory allocator lockless

Quoted 23 lines · Mathieu Desnoyers
Quoted 22 lines · * Huang Ying ([email protected]) wrote:

Hi, Mathieu,

Thanks for your comments.

Quoted 1 line · Mathieu Desnoyers

* Huang Ying ([email protected]) wrote:

[snip]

Quoted 14 lines

include/linux/genalloc.h struct gen_pool { · line 61

Quoted 11 lines
include/linux/genalloc.h +10 -0
+/**
+ * gen_pool_for_each_chunk - iterate over chunks of generic memory pool
+ * @chunk:   the struct gen_pool_chunk * to use as a loop cursor
+ * @pool:    the generic memory pool
+ *
+ * Not lockless, proper mutual exclusion is needed to use this macro
+ * with other gen_pool function simultaneously.
+ */
+#define gen_pool_for_each_chunk(chunk, pool)                 \
+     list_for_each_entry_rcu(chunk, &(pool)->chunks, next_chunk)

Is it just me or this macro is never used ? Maybe you should consider removing it.

Quoted 7 lines
Quoted 2 lines

This macro is not used in this patch. But it is used in 4/4 of the patchset to free the backing pages before destroy the pool.

Depending on how frequently you want to use it, you might want to use list_for_each_entry_rcu directly rather than a macro wrapper. E.g. for 2-3 uses, adding a macro just obfuscates the code IMHO (e.g. you don't know it iterates on a RCU list by looking at the caller code).

Yes. gen_pool_for_each_chunk() is not a good wrapper. I just don't want to expose too much implementation details to users, after all, we are working on library code. Maybe something like below is better?

void gen_pool_for_each_chunk(struct gen_pool *pool, void (*func)(struct

gen_pool *pool, struct gen_pool_chunk *chunk)) {
	rcu_read_lock();
	list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk)
		func(pool, chunk);
	rcu_read_unlock();
}
Quoted 181 lines
Quoted 82 lines

[snip]

Quoted 80 lines
Quoted 53 lines
lib/genalloc.c +22 -14
@@ -108,43 +226,50 @@ EXPORT_SYMBOL(gen_pool_destroy);
  * @size: number of bytes to allocate from the pool
  *
  * Allocate the requested number of bytes from the specified pool.
- * Uses a first-fit algorithm.
+ * Uses a first-fit algorithm. Can not be used in NMI handler on
+ * architectures without NMI-safe cmpxchg implementation.
  */
 unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long addr, flags;
+     unsigned long addr;
      int order = pool->min_alloc_order;
-     int nbits, start_bit, end_bit;
+     int nbits, start_bit = 0, end_bit, remain;
+
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
      if (size == 0)
              return 0;
 
      nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
+             if (size > atomic_read(&chunk->avail))
+                     continue;
 
              end_bit = (chunk->end_addr - chunk->start_addr) >> order;
-
-             spin_lock_irqsave(&chunk->lock, flags);
-             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit, 0,
-                                             nbits, 0);
-             if (start_bit >= end_bit) {
-                     spin_unlock_irqrestore(&chunk->lock, flags);
+retry:
+             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit,
+                                                    start_bit, nbits, 0);
+             if (start_bit >= end_bit)
                      continue;
+             remain = bitmap_set_ll(chunk->bits, start_bit, nbits);
+             if (remain) {
+                     remain = bitmap_clear_ll(chunk->bits, start_bit,
+                                              nbits - remain);
+                     BUG_ON(remain);
+                     goto retry;

lib/genalloc.c EXPORT_SYMBOL(gen_pool_destroy); · line 269

Quoted 10 lines
lib/genalloc.c +3 -4
              }
 
              addr = chunk->start_addr + ((unsigned long)start_bit << order);
-
-             bitmap_set(chunk->bits, start_bit, nbits);
-             spin_unlock_irqrestore(&chunk->lock, flags);
-             read_unlock(&pool->lock);
+             size = nbits << order;
+             atomic_sub(size, &chunk->avail);
+             rcu_read_unlock();

I don't really like seeing a rcu_read_unlock() within a rcu list iteration (even if it comes right before a "return"). Doing:

unsigned long addr = 0;

rcu_read_lock();
list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
if (...)

    continue;

...
addr = ...;
break;
}
rcu_read_unlock();
return addr;

Quoted 6 lines
Quoted 2 lines

Would be more symmetric, and would remove one return path, which makes the code easier to modify in the future.

Unlock in loop is common in Linux kernel. Sometimes it makes code cleaner (but not always). Yes, for this case, we can avoid unlock in loop easily. But for the next case it is not so clean.

See comment below,

Quoted 35 lines
Quoted 35 lines
Quoted 35 lines
lib/genalloc.c +8 -10
              return addr;
      }
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
      return 0;
 }
 EXPORT_SYMBOL(gen_pool_alloc);
@@ -155,33 +280,73 @@ EXPORT_SYMBOL(gen_pool_alloc);
  * @addr: starting address of memory to free back to pool
  * @size: size in bytes of memory to free
  *
- * Free previously allocated special memory back to the specified pool.
+ * Free previously allocated special memory back to the specified
+ * pool.  Can not be used in NMI handler on architectures without
+ * NMI-safe cmpxchg implementation.
  */
 void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long flags;
      int order = pool->min_alloc_order;
-     int bit, nbits;
+     int start_bit, nbits, remain;
 
-     nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
Quoted 1 line
Quoted 1 line

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 297

Quoted 1 line
lib/genalloc.c +1 -0
+     nbits = (size + (1UL << order) - 1) >> order;

you could add:

  remain = nbits;
Quoted 11 lines
Quoted 11 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 302

Quoted 11 lines
lib/genalloc.c +3 -6
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
              if (addr >= chunk->start_addr && addr < chunk->end_addr) {
                      BUG_ON(addr + size > chunk->end_addr);
-                     spin_lock_irqsave(&chunk->lock, flags);
-                     bit = (addr - chunk->start_addr) >> order;
-                     while (nbits--)
-                             __clear_bit(bit++, chunk->bits);
-                     spin_unlock_irqrestore(&chunk->lock, flags);
-                     break;
+                     start_bit = (addr - chunk->start_addr) >> order;

You could turn this:

Quoted 4 lines
Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 306

Quoted 4 lines
lib/genalloc.c +4 -0
+                     remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
+                     BUG_ON(remain);
+                     size = nbits << order;
+                     atomic_add(size, &chunk->avail);

into:

  remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
  size = nbits << order;
  atomic_add(size, &chunk->avail);
  break;
Quoted 14 lines
Quoted 3 lines

Review EXPORT_SYMBOL(gen_pool_alloc); · line 307

Quoted 1 line
(quoted diff) +1 -0
+                     rcu_read_unlock();

Same comment as above apply here.

It is harder to remove unlock in loop here. An extra variable should be used to indicate that something is freed from the pool. Do you think it is cleaner to just keep the unlock in loop here?

Best Regards,
Huang Ying

Quoted 3 lines
+                     return;
              }
      }

And turn this:

Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 312

Quoted 4 lines
lib/genalloc.c +2 -2
-     BUG_ON(nbits > 0);
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
+     BUG();
Quoted 7 lines

into:

  BUG_ON(remain);
  rcu_read_unlock();

Does that look OK to you ? On the plus side, you end up having a single BUG_ON() in the function.

I am afraid this make code a little harder to be understood. Why do you hate unlock in loop so much? It is common in kernel and I think most kernel developers are familiar with it.

Best Regards,
Huang Ying

#8 lore raw

Re: [PATCH -v4 3/4] lib, Make gen_pool memory allocator lockless

Quoted 36 lines · * Huang Ying ([email protected]) wrote:
Quoted 23 lines · Mathieu Desnoyers
Quoted 22 lines · * Huang Ying ([email protected]) wrote:

Hi, Mathieu,

Thanks for your comments.

Quoted 1 line · Mathieu Desnoyers

* Huang Ying ([email protected]) wrote:

[snip]

Quoted 14 lines

include/linux/genalloc.h struct gen_pool { · line 61

Quoted 11 lines
include/linux/genalloc.h +10 -0
+/**
+ * gen_pool_for_each_chunk - iterate over chunks of generic memory pool
+ * @chunk:   the struct gen_pool_chunk * to use as a loop cursor
+ * @pool:    the generic memory pool
+ *
+ * Not lockless, proper mutual exclusion is needed to use this macro
+ * with other gen_pool function simultaneously.
+ */
+#define gen_pool_for_each_chunk(chunk, pool)                 \
+     list_for_each_entry_rcu(chunk, &(pool)->chunks, next_chunk)

Is it just me or this macro is never used ? Maybe you should consider removing it.

Quoted 7 lines
Quoted 2 lines

This macro is not used in this patch. But it is used in 4/4 of the patchset to free the backing pages before destroy the pool.

Depending on how frequently you want to use it, you might want to use list_for_each_entry_rcu directly rather than a macro wrapper. E.g. for 2-3 uses, adding a macro just obfuscates the code IMHO (e.g. you don't know it iterates on a RCU list by looking at the caller code).

Yes. gen_pool_for_each_chunk() is not a good wrapper. I just don't want to expose too much implementation details to users, after all, we are working on library code. Maybe something like below is better?

Quoted 7 lines

void gen_pool_for_each_chunk(struct gen_pool *pool, void (*func)(struct

gen_pool *pool, struct gen_pool_chunk *chunk)) {
	rcu_read_lock();
	list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk)
		func(pool, chunk);
	rcu_read_unlock();
}

If it is expected to be exposed to other parts of the kernel, indeed we should not expect the caller to magically know they must hold the rcu read-side lock.

I'm not sure whether this iterator is necessary though. Just a comment could suffice.

Quoted 187 lines
Quoted 187 lines
Quoted 83 lines

[snip]

Quoted 80 lines
Quoted 53 lines
lib/genalloc.c +22 -14
@@ -108,43 +226,50 @@ EXPORT_SYMBOL(gen_pool_destroy);
  * @size: number of bytes to allocate from the pool
  *
  * Allocate the requested number of bytes from the specified pool.
- * Uses a first-fit algorithm.
+ * Uses a first-fit algorithm. Can not be used in NMI handler on
+ * architectures without NMI-safe cmpxchg implementation.
  */
 unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long addr, flags;
+     unsigned long addr;
      int order = pool->min_alloc_order;
-     int nbits, start_bit, end_bit;
+     int nbits, start_bit = 0, end_bit, remain;
+
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
      if (size == 0)
              return 0;
 
      nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
+             if (size > atomic_read(&chunk->avail))
+                     continue;
 
              end_bit = (chunk->end_addr - chunk->start_addr) >> order;
-
-             spin_lock_irqsave(&chunk->lock, flags);
-             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit, 0,
-                                             nbits, 0);
-             if (start_bit >= end_bit) {
-                     spin_unlock_irqrestore(&chunk->lock, flags);
+retry:
+             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit,
+                                                    start_bit, nbits, 0);
+             if (start_bit >= end_bit)
                      continue;
+             remain = bitmap_set_ll(chunk->bits, start_bit, nbits);
+             if (remain) {
+                     remain = bitmap_clear_ll(chunk->bits, start_bit,
+                                              nbits - remain);
+                     BUG_ON(remain);
+                     goto retry;

lib/genalloc.c EXPORT_SYMBOL(gen_pool_destroy); · line 269

Quoted 10 lines
lib/genalloc.c +3 -4
              }
 
              addr = chunk->start_addr + ((unsigned long)start_bit << order);
-
-             bitmap_set(chunk->bits, start_bit, nbits);
-             spin_unlock_irqrestore(&chunk->lock, flags);
-             read_unlock(&pool->lock);
+             size = nbits << order;
+             atomic_sub(size, &chunk->avail);
+             rcu_read_unlock();

I don't really like seeing a rcu_read_unlock() within a rcu list iteration (even if it comes right before a "return"). Doing:

unsigned long addr = 0;

rcu_read_lock();
list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
if (...)

    continue;

...
addr = ...;
break;
}
rcu_read_unlock();
return addr;

Quoted 6 lines
Quoted 2 lines

Would be more symmetric, and would remove one return path, which makes the code easier to modify in the future.

Unlock in loop is common in Linux kernel. Sometimes it makes code cleaner (but not always). Yes, for this case, we can avoid unlock in loop easily. But for the next case it is not so clean.

See comment below,

Quoted 35 lines
Quoted 35 lines
Quoted 35 lines
lib/genalloc.c +8 -10
              return addr;
      }
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
      return 0;
 }
 EXPORT_SYMBOL(gen_pool_alloc);
@@ -155,33 +280,73 @@ EXPORT_SYMBOL(gen_pool_alloc);
  * @addr: starting address of memory to free back to pool
  * @size: size in bytes of memory to free
  *
- * Free previously allocated special memory back to the specified pool.
+ * Free previously allocated special memory back to the specified
+ * pool.  Can not be used in NMI handler on architectures without
+ * NMI-safe cmpxchg implementation.
  */
 void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long flags;
      int order = pool->min_alloc_order;
-     int bit, nbits;
+     int start_bit, nbits, remain;
 
-     nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
Quoted 1 line
Quoted 1 line

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 297

Quoted 1 line
lib/genalloc.c +1 -0
+     nbits = (size + (1UL << order) - 1) >> order;

you could add:

  remain = nbits;
Quoted 11 lines
Quoted 11 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 302

Quoted 11 lines
lib/genalloc.c +3 -6
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
              if (addr >= chunk->start_addr && addr < chunk->end_addr) {
                      BUG_ON(addr + size > chunk->end_addr);
-                     spin_lock_irqsave(&chunk->lock, flags);
-                     bit = (addr - chunk->start_addr) >> order;
-                     while (nbits--)
-                             __clear_bit(bit++, chunk->bits);
-                     spin_unlock_irqrestore(&chunk->lock, flags);
-                     break;
+                     start_bit = (addr - chunk->start_addr) >> order;

You could turn this:

Quoted 4 lines
Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 306

Quoted 4 lines
lib/genalloc.c +4 -0
+                     remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
+                     BUG_ON(remain);
+                     size = nbits << order;
+                     atomic_add(size, &chunk->avail);

into:

  remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
  size = nbits << order;
  atomic_add(size, &chunk->avail);
  break;
Quoted 14 lines
Quoted 3 lines

Review EXPORT_SYMBOL(gen_pool_alloc); · line 307

Quoted 1 line
(quoted diff) +1 -0
+                     rcu_read_unlock();

Same comment as above apply here.

It is harder to remove unlock in loop here. An extra variable should be used to indicate that something is freed from the pool. Do you think it is cleaner to just keep the unlock in loop here?

Best Regards,
Huang Ying

Quoted 3 lines
+                     return;
              }
      }

And turn this:

Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 312

Quoted 4 lines
lib/genalloc.c +2 -2
-     BUG_ON(nbits > 0);
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
+     BUG();

into:

  BUG_ON(remain);
  rcu_read_unlock();
Quoted 6 lines
Quoted 2 lines

Does that look OK to you ? On the plus side, you end up having a single BUG_ON() in the function.

I am afraid this make code a little harder to be understood. Why do you hate unlock in loop so much? It is common in kernel and I think most kernel developers are familiar with it.

I'm fine either way for this function, no strong opinion on this one.

Thanks,

Mathieu

Quoted 3 lines

Best Regards,
Huang Ying

Signature · 4 lines
Mathieu Desnoyers
Operating System Efficiency R&D Consultant
EfficiOS Inc.
http://www.efficios.com
author
#9 lore raw

Re: [PATCH -v4 3/4] lib, Make gen_pool memory allocator lockless

Quoted 45 lines · Mathieu Desnoyers
Quoted 36 lines · * Huang Ying ([email protected]) wrote:
Quoted 23 lines · Mathieu Desnoyers
Quoted 22 lines · * Huang Ying ([email protected]) wrote:

Hi, Mathieu,

Thanks for your comments.

Quoted 1 line · Mathieu Desnoyers

* Huang Ying ([email protected]) wrote:

[snip]

Quoted 14 lines

include/linux/genalloc.h struct gen_pool { · line 61

Quoted 11 lines
include/linux/genalloc.h +10 -0
+/**
+ * gen_pool_for_each_chunk - iterate over chunks of generic memory pool
+ * @chunk:   the struct gen_pool_chunk * to use as a loop cursor
+ * @pool:    the generic memory pool
+ *
+ * Not lockless, proper mutual exclusion is needed to use this macro
+ * with other gen_pool function simultaneously.
+ */
+#define gen_pool_for_each_chunk(chunk, pool)                 \
+     list_for_each_entry_rcu(chunk, &(pool)->chunks, next_chunk)

Is it just me or this macro is never used ? Maybe you should consider removing it.

Quoted 7 lines
Quoted 2 lines

This macro is not used in this patch. But it is used in 4/4 of the patchset to free the backing pages before destroy the pool.

Depending on how frequently you want to use it, you might want to use list_for_each_entry_rcu directly rather than a macro wrapper. E.g. for 2-3 uses, adding a macro just obfuscates the code IMHO (e.g. you don't know it iterates on a RCU list by looking at the caller code).

Yes. gen_pool_for_each_chunk() is not a good wrapper. I just don't want to expose too much implementation details to users, after all, we are working on library code. Maybe something like below is better?

Quoted 7 lines

void gen_pool_for_each_chunk(struct gen_pool *pool, void (*func)(struct

gen_pool *pool, struct gen_pool_chunk *chunk)) {
	rcu_read_lock();
	list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk)
		func(pool, chunk);
	rcu_read_unlock();
}
Quoted 3 lines

If it is expected to be exposed to other parts of the kernel, indeed we should not expect the caller to magically know they must hold the rcu read-side lock.

Yes. So I want to help the users via acquiring/releasing the rcu read-side lock by ourselves.

Quoted 2 lines

I'm not sure whether this iterator is necessary though. Just a comment could suffice.

I try to hide some implementation details from the users here. So that we can change the implementation easier if necessary in the future. I will add comments to warn users that the callback function is executed in rcu_read_lock environment.

Quoted 186 lines
Quoted 186 lines
Quoted 186 lines
Quoted 82 lines

[snip]

Quoted 80 lines
Quoted 53 lines
lib/genalloc.c +22 -14
@@ -108,43 +226,50 @@ EXPORT_SYMBOL(gen_pool_destroy);
  * @size: number of bytes to allocate from the pool
  *
  * Allocate the requested number of bytes from the specified pool.
- * Uses a first-fit algorithm.
+ * Uses a first-fit algorithm. Can not be used in NMI handler on
+ * architectures without NMI-safe cmpxchg implementation.
  */
 unsigned long gen_pool_alloc(struct gen_pool *pool, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long addr, flags;
+     unsigned long addr;
      int order = pool->min_alloc_order;
-     int nbits, start_bit, end_bit;
+     int nbits, start_bit = 0, end_bit, remain;
+
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
      if (size == 0)
              return 0;
 
      nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
+             if (size > atomic_read(&chunk->avail))
+                     continue;
 
              end_bit = (chunk->end_addr - chunk->start_addr) >> order;
-
-             spin_lock_irqsave(&chunk->lock, flags);
-             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit, 0,
-                                             nbits, 0);
-             if (start_bit >= end_bit) {
-                     spin_unlock_irqrestore(&chunk->lock, flags);
+retry:
+             start_bit = bitmap_find_next_zero_area(chunk->bits, end_bit,
+                                                    start_bit, nbits, 0);
+             if (start_bit >= end_bit)
                      continue;
+             remain = bitmap_set_ll(chunk->bits, start_bit, nbits);
+             if (remain) {
+                     remain = bitmap_clear_ll(chunk->bits, start_bit,
+                                              nbits - remain);
+                     BUG_ON(remain);
+                     goto retry;

lib/genalloc.c EXPORT_SYMBOL(gen_pool_destroy); · line 269

Quoted 10 lines
lib/genalloc.c +3 -4
              }
 
              addr = chunk->start_addr + ((unsigned long)start_bit << order);
-
-             bitmap_set(chunk->bits, start_bit, nbits);
-             spin_unlock_irqrestore(&chunk->lock, flags);
-             read_unlock(&pool->lock);
+             size = nbits << order;
+             atomic_sub(size, &chunk->avail);
+             rcu_read_unlock();

I don't really like seeing a rcu_read_unlock() within a rcu list iteration (even if it comes right before a "return"). Doing:

unsigned long addr = 0;

rcu_read_lock();
list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
if (...)

    continue;

...
addr = ...;
break;
}
rcu_read_unlock();
return addr;

Quoted 6 lines
Quoted 2 lines

Would be more symmetric, and would remove one return path, which makes the code easier to modify in the future.

Unlock in loop is common in Linux kernel. Sometimes it makes code cleaner (but not always). Yes, for this case, we can avoid unlock in loop easily. But for the next case it is not so clean.

See comment below,

Quoted 35 lines
Quoted 35 lines
Quoted 35 lines
lib/genalloc.c +8 -10
              return addr;
      }
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
      return 0;
 }
 EXPORT_SYMBOL(gen_pool_alloc);
@@ -155,33 +280,73 @@ EXPORT_SYMBOL(gen_pool_alloc);
  * @addr: starting address of memory to free back to pool
  * @size: size in bytes of memory to free
  *
- * Free previously allocated special memory back to the specified pool.
+ * Free previously allocated special memory back to the specified
+ * pool.  Can not be used in NMI handler on architectures without
+ * NMI-safe cmpxchg implementation.
  */
 void gen_pool_free(struct gen_pool *pool, unsigned long addr, size_t size)
 {
-     struct list_head *_chunk;
      struct gen_pool_chunk *chunk;
-     unsigned long flags;
      int order = pool->min_alloc_order;
-     int bit, nbits;
+     int start_bit, nbits, remain;
 
-     nbits = (size + (1UL << order) - 1) >> order;
-
-     read_lock(&pool->lock);
-     list_for_each(_chunk, &pool->chunks) {
-             chunk = list_entry(_chunk, struct gen_pool_chunk, next_chunk);
+#ifndef CONFIG_ARCH_HAVE_NMI_SAFE_CMPXCHG
+     BUG_ON(in_nmi());
+#endif
 
Quoted 1 line
Quoted 1 line

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 297

Quoted 1 line
lib/genalloc.c +1 -0
+     nbits = (size + (1UL << order) - 1) >> order;

you could add:

  remain = nbits;
Quoted 11 lines
Quoted 11 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 302

Quoted 11 lines
lib/genalloc.c +3 -6
+     rcu_read_lock();
+     list_for_each_entry_rcu(chunk, &pool->chunks, next_chunk) {
              if (addr >= chunk->start_addr && addr < chunk->end_addr) {
                      BUG_ON(addr + size > chunk->end_addr);
-                     spin_lock_irqsave(&chunk->lock, flags);
-                     bit = (addr - chunk->start_addr) >> order;
-                     while (nbits--)
-                             __clear_bit(bit++, chunk->bits);
-                     spin_unlock_irqrestore(&chunk->lock, flags);
-                     break;
+                     start_bit = (addr - chunk->start_addr) >> order;

You could turn this:

Quoted 4 lines
Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 306

Quoted 4 lines
lib/genalloc.c +4 -0
+                     remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
+                     BUG_ON(remain);
+                     size = nbits << order;
+                     atomic_add(size, &chunk->avail);

into:

  remain = bitmap_clear_ll(chunk->bits, start_bit, nbits);
  size = nbits << order;
  atomic_add(size, &chunk->avail);
  break;
Quoted 14 lines
Quoted 3 lines

Review EXPORT_SYMBOL(gen_pool_alloc); · line 307

Quoted 1 line
(quoted diff) +1 -0
+                     rcu_read_unlock();

Same comment as above apply here.

It is harder to remove unlock in loop here. An extra variable should be used to indicate that something is freed from the pool. Do you think it is cleaner to just keep the unlock in loop here?

Best Regards,
Huang Ying

Quoted 3 lines
+                     return;
              }
      }

And turn this:

Quoted 4 lines

lib/genalloc.c EXPORT_SYMBOL(gen_pool_alloc); · line 312

Quoted 4 lines
lib/genalloc.c +2 -2
-     BUG_ON(nbits > 0);
-     read_unlock(&pool->lock);
+     rcu_read_unlock();
+     BUG();

into:

  BUG_ON(remain);
  rcu_read_unlock();
Quoted 8 lines
Quoted 6 lines
Quoted 2 lines

Does that look OK to you ? On the plus side, you end up having a single BUG_ON() in the function.

I am afraid this make code a little harder to be understood. Why do you hate unlock in loop so much? It is common in kernel and I think most kernel developers are familiar with it.

I'm fine either way for this function, no strong opinion on this one.

Thanks. I will keep this function and change the other one (gen_pool_alloc).

Best Regards,
Huang Ying