Skip to contentSkip to conversation

incoming

PATCH In review Andrew Morton 13 participants 218 messages Jul 1, 2021 – Jul 12, 2021 Page 2 of 2

Subsystems (102)
lore
Share & tools
lore
author maintainer
#97 lore raw

PATCH 91/192 mm: rmap: make try_to_unmap() void function

In reply to Andrew Morton

From: Yang Shi <[email protected]>
Subject: mm: rmap: make try_to_unmap() void function

Currently try_to_unmap() return bool value by checking page_mapcount(), however this may return false positive since page_mapcount() doesn't check all subpages of compound page. The total_mapcount() could be used instead, but its cost is higher since it traverses all subpages.

Actually the most callers of try_to_unmap() don't care about the return value at all. So just need check if page is still mapped by page_mapped() when necessary. And page_mapped() does bail out early when it finds mapped subpage.

---

 include/linux/rmap.h |    2 +-
 mm/memory-failure.c  |   15 +++++++--------
 mm/rmap.c            |   15 ++++-----------
 mm/vmscan.c          |    3 ++-
 4 files changed, 14 insertions(+), 21 deletions(-)
include/linux/rmap.h renamed from include/linux/rmap.h~mm-rmap-make-try_to_unmap-void-function +1 -1
@@ -195,7 +195,7 @@ static inline void page_dup_rmap(struct
 int page_referenced(struct page *, int is_locked,
 			struct mem_cgroup *memcg, unsigned long *vm_flags);
 
-bool try_to_unmap(struct page *, enum ttu_flags flags);
+void try_to_unmap(struct page *, enum ttu_flags flags);
 
 /* Avoid racy checks */
 #define PVMW_SYNC		(1 << 0)
mm/memory-failure.c renamed from mm/memory-failure.c~mm-rmap-make-try_to_unmap-void-function +7 -8
@@ -1269,7 +1269,7 @@ static bool hwpoison_user_mappings(struc
 	enum ttu_flags ttu = TTU_IGNORE_MLOCK;
 	struct address_space *mapping;
 	LIST_HEAD(tokill);
-	bool unmap_success = true;
+	bool unmap_success;
 	int kill = 1, forcekill;
 	struct page *hpage = *hpagep;
 	bool mlocked = PageMlocked(hpage);
@@ -1332,7 +1332,7 @@ static bool hwpoison_user_mappings(struc
 		collect_procs(hpage, &tokill, flags & MF_ACTION_REQUIRED);
 
 	if (!PageHuge(hpage)) {
-		unmap_success = try_to_unmap(hpage, ttu);
+		try_to_unmap(hpage, ttu);
 	} else {
 		if (!PageAnon(hpage)) {
 			/*
@@ -1344,17 +1344,16 @@ static bool hwpoison_user_mappings(struc
 			 */
 			mapping = hugetlb_page_mapping_lock_write(hpage);
 			if (mapping) {
-				unmap_success = try_to_unmap(hpage,
-						     ttu|TTU_RMAP_LOCKED);
+				try_to_unmap(hpage, ttu|TTU_RMAP_LOCKED);
 				i_mmap_unlock_write(mapping);
-			} else {
+			} else
 				pr_info("Memory failure: %#lx: could not lock mapping for mapped huge page\n", pfn);
-				unmap_success = false;
-			}
 		} else {
-			unmap_success = try_to_unmap(hpage, ttu);
+			try_to_unmap(hpage, ttu);
 		}
 	}
+
+	unmap_success = !page_mapped(hpage);
 	if (!unmap_success)
 		pr_err("Memory failure: %#lx: failed to unmap page (mapcount=%d)\n",
 		       pfn, page_mapcount(hpage));
mm/rmap.c renamed from mm/rmap.c~mm-rmap-make-try_to_unmap-void-function +4 -11
@@ -1405,7 +1405,7 @@ static bool try_to_unmap_one(struct page
 	/*
 	 * When racing against e.g. zap_pte_range() on another cpu,
 	 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
-	 * try_to_unmap() may return false when it is about to become true,
+	 * try_to_unmap() may return before page_mapped() has become false,
 	 * if page table locking is skipped: use TTU_SYNC to wait for that.
 	 */
 	if (flags & TTU_SYNC)
@@ -1756,9 +1756,10 @@ static int page_not_mapped(struct page *
  * Tries to remove all the page table entries which are mapping this
  * page, used in the pageout path.  Caller must hold the page lock.
  *
- * If unmap is successful, return true. Otherwise, false.
+ * It is the caller's responsibility to check if the page is still
+ * mapped when needed (use TTU_SYNC to prevent accounting races).
  */
-bool try_to_unmap(struct page *page, enum ttu_flags flags)
+void try_to_unmap(struct page *page, enum ttu_flags flags)
 {
 	struct rmap_walk_control rwc = {
 		.rmap_one = try_to_unmap_one,
@@ -1783,14 +1784,6 @@ bool try_to_unmap(struct page *page, enu
 		rmap_walk_locked(page, &rwc);
 	else
 		rmap_walk(page, &rwc);
-
-	/*
-	 * When racing against e.g. zap_pte_range() on another cpu,
-	 * in between its ptep_get_and_clear_full() and page_remove_rmap(),
-	 * try_to_unmap() may return false when it is about to become true,
-	 * if page table locking is skipped: use TTU_SYNC to wait for that.
-	 */
-	return !page_mapcount(page);
 }
 
 /**
mm/vmscan.c renamed from mm/vmscan.c~mm-rmap-make-try_to_unmap-void-function +2 -1
@@ -1499,7 +1499,8 @@ static unsigned int shrink_page_list(str
 			if (unlikely(PageTransHuge(page)))
 				flags |= TTU_SPLIT_HUGE_PMD;
 
-			if (!try_to_unmap(page, flags)) {
+			try_to_unmap(page, flags);
+			if (page_mapped(page)) {
 				stat->nr_unmap_fail += nr_pages;
 				if (!was_swapbacked && PageSwapBacked(page))
 					stat->nr_lazyfree_fail += nr_pages;

_

author maintainer
#98 lore raw

PATCH 92/192 mm/thp: remap_page() is only needed on anonymous THP

In reply to Andrew Morton

From: Hugh Dickins <[email protected]>
Subject: mm/thp: remap_page() is only needed on anonymous THP

THP splitting's unmap_page() only sets TTU_SPLIT_FREEZE when PageAnon, and migration entries are only inserted when TTU_MIGRATION (unused here) or TTU_SPLIT_FREEZE is set: so it's just a waste of time for remap_page() to search for migration entries to remove when !PageAnon.

Fixes baa355fd3314 ("thp: file pages support for split_huge_page()")
Cc Alistair Popple <[email protected]>
Cc Jan Kara <[email protected]>
Cc Jue Wang <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Miaohe Lin <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Naoya Horiguchi <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Peter Xu <[email protected]>
Cc Ralph Campbell <[email protected]>
Cc Shakeel Butt <[email protected]>
Cc Wang Yugui <[email protected]>
Cc Zi Yan <[email protected]>

---

 mm/huge_memory.c |    5 +++++
 1 file changed, 5 insertions(+)
mm/huge_memory.c renamed from mm/huge_memory.c~mm-thp-remap_page-is-only-needed-on-anonymous-thp +5 -0
@@ -2307,6 +2307,7 @@ static void unmap_page(struct page *page
 
 	VM_BUG_ON_PAGE(!PageHead(page), page);
 
+	/* If TTU_SPLIT_FREEZE is ever extended to file, update remap_page() */
 	if (PageAnon(page))
 		ttu_flags |= TTU_SPLIT_FREEZE;
 
@@ -2318,6 +2319,10 @@ static void unmap_page(struct page *page
 static void remap_page(struct page *page, unsigned int nr)
 {
 	int i;
+
+	/* If TTU_SPLIT_FREEZE is ever extended to file, remove this check */
+	if (!PageAnon(page))
+		return;
 	if (PageTransHuge(page)) {
 		remove_migration_ptes(page, page, true);
 	} else {

_

author maintainer
#99 lore raw

PATCH 93/192 mm: hwpoison_user_mappings() try_to_unmap() with TTU_SYNC

In reply to Andrew Morton

From: Hugh Dickins <[email protected]>
Subject: mm: hwpoison_user_mappings() try_to_unmap() with TTU_SYNC

TTU_SYNC prevents an unlikely race, when try_to_unmap() returns shortly before the page is accounted as unmapped. It is unlikely to coincide with hwpoisoning, but now that we have the flag, hwpoison_user_mappings() would do well to use it.

---

 mm/memory-failure.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/memory-failure.c renamed from mm/memory-failure.c~mm-hwpoison_user_mappings-try_to_unmap-with-ttu_sync +1 -1
@@ -1266,7 +1266,7 @@ static int get_hwpoison_page(struct page
 static bool hwpoison_user_mappings(struct page *p, unsigned long pfn,
 				  int flags, struct page **hpagep)
 {
-	enum ttu_flags ttu = TTU_IGNORE_MLOCK;
+	enum ttu_flags ttu = TTU_IGNORE_MLOCK | TTU_SYNC;
 	struct address_space *mapping;
 	LIST_HEAD(tokill);
 	bool unmap_success;

_

author maintainer
#100 lore raw

PATCH 94/192 mm/thp: fix strncpy warning

In reply to Andrew Morton

From: "Matthew Wilcox (Oracle)" <[email protected]>
Subject: mm/thp: fix strncpy warning

Using MAX_INPUT_BUF_SZ as the maximum length of the string makes fortify complain as it thinks the string might be longer than the buffer, and if it is, we will end up with a "string" that is missing a NUL terminator. It's trivial to show that 'tok' points to a NUL-terminated string which is less than MAX_INPUT_BUF_SZ in length, so we may as well just use strcpy() and avoid the warning.

---

 mm/huge_memory.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/huge_memory.c renamed from mm/huge_memory.c~mm-thp-fix-strncpy-warning +1 -1
@@ -3101,7 +3101,7 @@ static ssize_t split_huge_pages_write(st
 
 		tok = strsep(&buf, ",");
 		if (tok) {
-			strncpy(file_path, tok, MAX_INPUT_BUF_SZ);
+			strcpy(file_path, tok);
 		} else {
 			ret = -EINVAL;
 			goto out;

_

author maintainer
#101 lore raw

PATCH 95/192 nommu: remove __GFP_HIGHMEM in vmalloc/vzalloc

In reply to Andrew Morton

From: Chen Li <[email protected]>
Subject: nommu: remove __GFP_HIGHMEM in vmalloc/vzalloc

mm/nommu.c:
void *__vmalloc(unsigned long size, gfp_t gfp_mask)

{
	/*
	 *  You can't specify __GFP_HIGHMEM with kmalloc() since kmalloc()
	 * returns only a logical address.
	 */
	return kmalloc(size, (gfp_mask | __GFP_COMP) & ~__GFP_HIGHMEM);
}

nommu's __vmalloc just uses kmalloc internally and elimitates __GFP_HIGHMEM, so it makes no sense to add __GFP_HIGHMEM for nommu's vmalloc/vzalloc.

---

 mm/nommu.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/nommu.c renamed from mm/nommu.c~nommu-remove-__gfp_highmem-in-vmalloc-vzalloc +2 -2
@@ -223,7 +223,7 @@ long vread(char *buf, char *addr, unsign
  */
 void *vmalloc(unsigned long size)
 {
-       return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM);
+	return __vmalloc(size, GFP_KERNEL);
 }
 EXPORT_SYMBOL(vmalloc);
 
@@ -241,7 +241,7 @@ EXPORT_SYMBOL(vmalloc);
  */
 void *vzalloc(unsigned long size)
 {
-	return __vmalloc(size, GFP_KERNEL | __GFP_HIGHMEM | __GFP_ZERO);
+	return __vmalloc(size, GFP_KERNEL | __GFP_ZERO);
 }
 EXPORT_SYMBOL(vzalloc);
 

_

author maintainer
#102 lore raw

PATCH 96/192 mm/nommu: unexport do_munmap()

In reply to Andrew Morton

From: Liam Howlett <[email protected]>
Subject: mm/nommu: unexport do_munmap()

do_munmap() does not take the mmap_write_lock(). vm_munmap() should be used instead.

---

 mm/nommu.c |    1 -
 1 file changed, 1 deletion(-)
mm/nommu.c renamed from mm/nommu.c~mm-nommu-unexport-do_munmap +0 -1
@@ -1501,7 +1501,6 @@ erase_whole_vma:
 	delete_vma(mm, vma);
 	return 0;
 }
-EXPORT_SYMBOL(do_munmap);
 
 int vm_munmap(unsigned long addr, size_t len)
 {

_

author maintainer
#103 lore raw

PATCH 97/192 mm: generalize ZONE_[DMA|DMA32]

In reply to Andrew Morton

From: Kefeng Wang <[email protected]>
Subject: mm: generalize ZONE_[DMA|DMA32]

ZONE_[DMA|DMA32] configs have duplicate definitions on platforms that subscribe to them. Instead, just make them generic options which can be selected on applicable platforms.

Also only x86/arm64 architectures could enable both ZONE_DMA and ZONE_DMA32 if EXPERT, add ARCH_HAS_ZONE_DMA_SET to make dma zone configurable and visible on the two architectures.

---

 arch/alpha/Kconfig                     |    5 +----
 arch/arm/Kconfig                       |    3 ---
 arch/arm64/Kconfig                     |    9 +--------
 arch/ia64/Kconfig                      |    4 +---
 arch/m68k/Kconfig                      |    5 +----
 arch/microblaze/Kconfig                |    4 +---
 arch/mips/Kconfig                      |    7 -------
 arch/powerpc/Kconfig                   |    4 ----
 arch/powerpc/platforms/Kconfig.cputype |    1 +
 arch/riscv/Kconfig                     |    5 +----
 arch/s390/Kconfig                      |    4 +---
 arch/sparc/Kconfig                     |    5 +----
 arch/x86/Kconfig                       |   15 ++-------------
 mm/Kconfig                             |   12 ++++++++++++
 14 files changed, 23 insertions(+), 60 deletions(-)
arch/alpha/Kconfig renamed from arch/alpha/Kconfig~mm-generalize-zone_ +1 -4
@@ -40,6 +40,7 @@ config ALPHA
 	select MMU_GATHER_NO_RANGE
 	select SET_FS
 	select SPARSEMEM_EXTREME if SPARSEMEM
+	select ZONE_DMA
 	help
 	  The Alpha is a 64-bit general-purpose processor designed and
 	  marketed by the Digital Equipment Corporation of blessed memory,
@@ -65,10 +66,6 @@ config GENERIC_CALIBRATE_DELAY
 	bool
 	default y
 
-config ZONE_DMA
-	bool
-	default y
-
 config GENERIC_ISA_DMA
 	bool
 	default y
arch/arm64/Kconfig renamed from arch/arm64/Kconfig~mm-generalize-zone_ +1 -8
@@ -42,6 +42,7 @@ config ARM64
 	select ARCH_HAS_SYSCALL_WRAPPER
 	select ARCH_HAS_TEARDOWN_DMA_OPS if IOMMU_SUPPORT
 	select ARCH_HAS_TICK_BROADCAST if GENERIC_CLOCKEVENTS_BROADCAST
+	select ARCH_HAS_ZONE_DMA_SET if EXPERT
 	select ARCH_HAVE_ELF_PROT
 	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 	select ARCH_INLINE_READ_LOCK if !PREEMPTION
@@ -306,14 +307,6 @@ config GENERIC_CSUM
 config GENERIC_CALIBRATE_DELAY
 	def_bool y
 
-config ZONE_DMA
-	bool "Support DMA zone" if EXPERT
-	default y
-
-config ZONE_DMA32
-	bool "Support DMA32 zone" if EXPERT
-	default y
-
 config ARCH_MHP_MEMMAP_ON_MEMORY_ENABLE
 	def_bool y
 
arch/arm/Kconfig renamed from arch/arm/Kconfig~mm-generalize-zone_ +0 -3
@@ -218,9 +218,6 @@ config GENERIC_CALIBRATE_DELAY
 config ARCH_MAY_HAVE_PC_FDC
 	bool
 
-config ZONE_DMA
-	bool
-
 config ARCH_SUPPORTS_UPROBES
 	def_bool y
 
arch/ia64/Kconfig renamed from arch/ia64/Kconfig~mm-generalize-zone_ +1 -3
@@ -60,6 +60,7 @@ config IA64
 	select NUMA if !FLATMEM
 	select PCI_MSI_ARCH_FALLBACKS if PCI_MSI
 	select SET_FS
+	select ZONE_DMA32
 	default y
 	help
 	  The Itanium Processor Family is Intel's 64-bit successor to
@@ -72,9 +73,6 @@ config 64BIT
 	select ATA_NONSTANDARD if ATA
 	default y
 
-config ZONE_DMA32
-	def_bool y
-
 config MMU
 	bool
 	default y
arch/m68k/Kconfig renamed from arch/m68k/Kconfig~mm-generalize-zone_ +1 -4
@@ -34,6 +34,7 @@ config M68K
 	select SET_FS
 	select UACCESS_MEMCPY if !MMU
 	select VIRT_TO_BUS
+	select ZONE_DMA
 
 config CPU_BIG_ENDIAN
 	def_bool y
@@ -62,10 +63,6 @@ config TIME_LOW_RES
 config NO_IOPORT_MAP
 	def_bool y
 
-config ZONE_DMA
-	bool
-	default y
-
 config HZ
 	int
 	default 1000 if CLEOPATRA
arch/microblaze/Kconfig renamed from arch/microblaze/Kconfig~mm-generalize-zone_ +1 -3
@@ -43,6 +43,7 @@ config MICROBLAZE
 	select MMU_GATHER_NO_RANGE
 	select SPARSE_IRQ
 	select SET_FS
+	select ZONE_DMA
 
 # Endianness selection
 choice
@@ -60,9 +61,6 @@ config CPU_LITTLE_ENDIAN
 
 endchoice
 
-config ZONE_DMA
-	def_bool y
-
 config ARCH_HAS_ILOG2_U32
 	def_bool n
 
arch/mips/Kconfig renamed from arch/mips/Kconfig~mm-generalize-zone_ +0 -7
@@ -3274,13 +3274,6 @@ config I8253
 	select CLKSRC_I8253
 	select CLKEVT_I8253
 	select MIPS_EXTERNAL_TIMER
-
-config ZONE_DMA
-	bool
-
-config ZONE_DMA32
-	bool
-
 endmenu
 
 config TRAD_SIGNALS
arch/powerpc/Kconfig renamed from arch/powerpc/Kconfig~mm-generalize-zone_ +0 -4
@@ -403,10 +403,6 @@ config PPC_ADV_DEBUG_DAC_RANGE
 config PPC_DAWR
 	bool
 
-config ZONE_DMA
-	bool
-	default y if PPC_BOOK3E_64
-
 config PGTABLE_LEVELS
 	int
 	default 2 if !PPC64
arch/powerpc/platforms/Kconfig.cputype renamed from arch/powerpc/platforms/Kconfig.cputype~mm-generalize-zone_ +1 -0
@@ -111,6 +111,7 @@ config PPC_BOOK3E_64
 	select PPC_FPU # Make it a choice ?
 	select PPC_SMP_MUXED_IPI
 	select PPC_DOORBELL
+	select ZONE_DMA
 
 endchoice
 
arch/riscv/Kconfig renamed from arch/riscv/Kconfig~mm-generalize-zone_ +1 -4
@@ -104,6 +104,7 @@ config RISCV
 	select SYSCTL_EXCEPTION_TRACE
 	select THREAD_INFO_IN_TASK
 	select UACCESS_MEMCPY if !MMU
+	select ZONE_DMA32 if 64BIT
 
 config ARCH_MMAP_RND_BITS_MIN
 	default 18 if 64BIT
@@ -133,10 +134,6 @@ config MMU
 	  Select if you want MMU-based virtualised addressing space
 	  support by paged memory management. If unsure, say 'Y'.
 
-config ZONE_DMA32
-	bool
-	default y if 64BIT
-
 config VA_BITS
 	int
 	default 32 if 32BIT
arch/s390/Kconfig renamed from arch/s390/Kconfig~mm-generalize-zone_ +1 -3
@@ -2,9 +2,6 @@
 config MMU
 	def_bool y
 
-config ZONE_DMA
-	def_bool y
-
 config CPU_BIG_ENDIAN
 	def_bool y
 
@@ -210,6 +207,7 @@ config S390
 	select THREAD_INFO_IN_TASK
 	select TTY
 	select VIRT_CPU_ACCOUNTING
+	select ZONE_DMA
 	# Note: keep the above list sorted alphabetically
 
 config SCHED_OMIT_FRAME_POINTER
arch/sparc/Kconfig renamed from arch/sparc/Kconfig~mm-generalize-zone_ +1 -4
@@ -59,6 +59,7 @@ config SPARC32
 	select CLZ_TAB
 	select HAVE_UID16
 	select OLD_SIGACTION
+	select ZONE_DMA
 
 config SPARC64
 	def_bool 64BIT
@@ -141,10 +142,6 @@ config HIGHMEM
 	default y if SPARC32
 	select KMAP_LOCAL
 
-config ZONE_DMA
-	bool
-	default y if SPARC32
-
 config GENERIC_ISA_DMA
 	bool
 	default y if SPARC32
arch/x86/Kconfig renamed from arch/x86/Kconfig~mm-generalize-zone_ +2 -13
@@ -33,6 +33,7 @@ config X86_64
 	select NEED_DMA_MAP_STATE
 	select SWIOTLB
 	select ARCH_HAS_ELFCORE_COMPAT
+	select ZONE_DMA32
 
 config FORCE_DYNAMIC_FTRACE
 	def_bool y
@@ -93,6 +94,7 @@ config X86
 	select ARCH_HAS_SYSCALL_WRAPPER
 	select ARCH_HAS_UBSAN_SANITIZE_ALL
 	select ARCH_HAS_DEBUG_WX
+	select ARCH_HAS_ZONE_DMA_SET if EXPERT
 	select ARCH_HAVE_NMI_SAFE_CMPXCHG
 	select ARCH_MIGHT_HAVE_ACPI_PDC		if ACPI
 	select ARCH_MIGHT_HAVE_PC_PARPORT
@@ -343,9 +345,6 @@ config ARCH_SUSPEND_POSSIBLE
 config ARCH_WANT_GENERAL_HUGETLB
 	def_bool y
 
-config ZONE_DMA32
-	def_bool y if X86_64
-
 config AUDIT_ARCH
 	def_bool y if X86_64
 
@@ -393,16 +392,6 @@ config CC_HAS_SANE_STACKPROTECTOR
 
 menu "Processor type and features"
 
-config ZONE_DMA
-	bool "DMA memory allocation support" if EXPERT
-	default y
-	help
-	  DMA memory allocation support allows devices with less than 32-bit
-	  addressing to allocate within the first 16MB of address space.
-	  Disable if no such devices will be used.
-
-	  If unsure, say Y.
-
 config SMP
 	bool "Symmetric multi-processing support"
 	help
mm/Kconfig renamed from mm/Kconfig~mm-generalize-zone_ +12 -0
@@ -761,6 +761,18 @@ config ARCH_HAS_CACHE_LINE_SIZE
 config ARCH_HAS_PTE_DEVMAP
 	bool
 
+config ARCH_HAS_ZONE_DMA_SET
+	bool
+
+config ZONE_DMA
+	bool "Support DMA zone" if ARCH_HAS_ZONE_DMA_SET
+	default y if ARM64 || X86
+
+config ZONE_DMA32
+	bool "Support DMA32 zone" if ARCH_HAS_ZONE_DMA_SET
+	depends on !X86_32
+	default y if ARM64
+
 config ZONE_DEVICE
 	bool "Device memory (pmem, HMM, etc...) hotplug support"
 	depends on MEMORY_HOTPLUG

_

#104 lore raw

Re: [patch 097/192] mm: generalize ZONE_[DMA|DMA32]

Quoted 7 lines · Andrew Morton

From: Kefeng Wang <[email protected]>
Subject: mm: generalize ZONE_[DMA|DMA32]

ZONE_[DMA|DMA32] configs have duplicate definitions on platforms that subscribe to them. Instead, just make them generic options which can be selected on applicable platforms.

Hmm. 'b4' doesn't pick up this patch, for some reason.

Once again, it seems to be a "missing from the lists" case, even though I see the "cc: mm-commits".

I don't see _why_, though.

I've picked it up from my own mailbox, but it's a bit annoying how b4 _almost_ makes this all painfree - but not quite.

Linus

#105 lore raw

Re: [patch 097/192] mm: generalize ZONE_[DMA|DMA32]

Quoted 6 lines · Linus Torvalds
Quoted 3 lines

ZONE_[DMA|DMA32] configs have duplicate definitions on platforms that subscribe to them. Instead, just make them generic options which can be selected on applicable platforms.

Hmm. 'b4' doesn't pick up this patch, for some reason.

Quoted 7 lines

Once again, it seems to be a "missing from the lists" case, even though I see the "cc: mm-commits".

I don't see _why_, though.

I've picked it up from my own mailbox, but it's a bit annoying how b4 _almost_ makes this all painfree - but not quite.

It seems that 097/192 didn't make it to any of the archival services either for linux-mm or mm-commits, which is really bizarre, since they are hosted at two different listserv hosts. E.g. marc.info doesn't have 097 either:

https://marc.info/?l=linux-mm&r=4&b=202107&w=2
https://marc.info/?l=linux-mm-commits&r=4&b=202107&w=2

Since both kvack.org and vger.kernel.org use majordomo, I would guess that something about that message caused them to drop it. Unfortunately, I don't have anything insightful to add here other than "b4 is only as good as what lore.kernel.org actually receives."

-K

author maintainer
#106 lore raw

PATCH 98/192 mm: make variable names for populate_vma_page_range() consistent

In reply to Andrew Morton

From: David Hildenbrand <[email protected]>
Subject: mm: make variable names for populate_vma_page_range() consistent

Patch series "mm/madvise: introduce MADV_POPULATE_(READ|WRITE) to prefault page tables", v2.

Excessive details on MADV_POPULATE_(READ|WRITE) can be found in patch #2.

This patch (of 5):

Let's make the variable names in the function declaration match the variable names used in the definition.

Cc Michal Hocko <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Peter Xu <[email protected]>
Cc Andrea Arcangeli <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Chris Zankel <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Helge Deller <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Ivan Kokshaysky <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Matt Turner <[email protected]>
Cc Max Filippov <[email protected]>
Cc Michael S. Tsirkin <[email protected]>
Cc Mike Kravetz <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Ram Pai <[email protected]>
Cc Richard Henderson <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Rolf Eike Beer <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc Vlastimil Babka <[email protected]>

---

 mm/internal.h |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/internal.h renamed from mm/internal.h~mm-make-variable-names-for-populate_vma_page_range-consistent +1 -1
@@ -344,7 +344,7 @@ void __vma_unlink_list(struct mm_struct
 
 #ifdef CONFIG_MMU
 extern long populate_vma_page_range(struct vm_area_struct *vma,
-		unsigned long start, unsigned long end, int *nonblocking);
+		unsigned long start, unsigned long end, int *locked);
 extern void munlock_vma_pages_range(struct vm_area_struct *vma,
 			unsigned long start, unsigned long end);
 static inline void munlock_vma_pages_all(struct vm_area_struct *vma)

_

author maintainer
#107 lore raw

PATCH 99/192 mm/madvise: introduce MADV_POPULATE_(READ|WRITE) to prefault page tables

In reply to Andrew Morton

From: David Hildenbrand <[email protected]>
Subject: mm/madvise: introduce MADV_POPULATE_(READ|WRITE) to prefault page tables

I. Background: Sparse Memory Mappings

When we manage sparse memory mappings dynamically in user space - also sometimes involving MAP_NORESERVE - we want to dynamically populate/ discard memory inside such a sparse memory region. Example users are hypervisors (especially implementing memory ballooning or similar technologies like virtio-mem) and memory allocators. In addition, we want to fail in a nice way (instead of generating SIGBUS) if populating does not succeed because we are out of backend memory (which can happen easily with file-based mappings, especially tmpfs and hugetlbfs).

While MADV_DONTNEED, MADV_REMOVE and FALLOC_FL_PUNCH_HOLE allow for reliably discarding memory for most mapping types, there is no generic approach to populate page tables and preallocate memory.

Although mmap() supports MAP_POPULATE, it is not applicable to the concept of sparse memory mappings, where we want to populate/discard dynamically and avoid expensive/problematic remappings. In addition, we never actually report errors during the final populate phase - it is best-effort only.

fallocate() can be used to preallocate file-based memory and fail in a safe way. However, it cannot really be used for any private mappings on anonymous files via memfd due to COW semantics. In addition, fallocate() does not actually populate page tables, so we still always get pagefaults on first access - which is sometimes undesired (i.e., real-time workloads) and requires real prefaulting of page tables, not just a preallocation of backend storage. There might be interesting use cases for sparse memory regions along with mlockall(MCL_ONFAULT) which fallocate() cannot satisfy as it does not prefault page tables.

II. On preallcoation/prefaulting from user space

Because we don't have a proper interface, what applications (like QEMU and databases) end up doing is touching (i.e., reading+writing one byte to not overwrite existing data) all individual pages.

However, that approach
1) Can result in wear on storage backing, because we end up reading/writing each page; this is especially a problem for dax/pmem.
2) Can result in mmap_sem contention when prefaulting via multiple threads.
3) Requires expensive signal handling, especially to catch SIGBUS in case of hugetlbfs/shmem/file-backed memory. For example, this is problematic in hypervisors like QEMU where SIGBUS handlers might already be used by other subsystems concurrently to e.g, handle hardware errors. "Simply" doing preallocation concurrently from other thread is not that easy.

III. On MADV_WILLNEED

Extending MADV_WILLNEED is not an option because
1. It would change the semantics: "Expect access in the near future." and "might be a good idea to read some pages" vs. "Definitely populate/ preallocate all memory and definitely fail on errors.".
2. Existing users (like virtio-balloon in QEMU when deflating the balloon) don't want populate/prealloc semantics. They treat this rather as a hint to give a little performance boost without too much overhead - and don't expect that a lot of memory might get consumed or a lot of time might be spent.

IV. MADV_POPULATE_READ and MADV_POPULATE_WRITE

Let's introduce MADV_POPULATE_READ and MADV_POPULATE_WRITE, inspired by MAP_POPULATE, with the following semantics:
1. MADV_POPULATE_READ can be used to prefault page tables just like manually reading each individual page. This will not break any COW mappings. The shared zero page might get mapped and no backend storage might get preallocated -- allocation might be deferred to write-fault time. Especially shared file mappings require an explicit fallocate() upfront to actually preallocate backend memory (blocks in the file system) in case the file might have holes.
2. If MADV_POPULATE_READ succeeds, all page tables have been populated (prefaulted) readable once.
3. MADV_POPULATE_WRITE can be used to preallocate backend memory and prefault page tables just like manually writing (or reading+writing) each individual page. This will break any COW mappings -- e.g., the shared zeropage is never populated.
4. If MADV_POPULATE_WRITE succeeds, all page tables have been populated (prefaulted) writable once.
5. MADV_POPULATE_READ and MADV_POPULATE_WRITE cannot be applied to special mappings marked with VM_PFNMAP and VM_IO. Also, proper access permissions (e.g., PROT_READ, PROT_WRITE) are required. If any such mapping is encountered, madvise() fails with -EINVAL.
6. If MADV_POPULATE_READ or MADV_POPULATE_WRITE fails, some page tables might have been populated.
7. MADV_POPULATE_READ and MADV_POPULATE_WRITE will return -EHWPOISON when encountering a HW poisoned page in the range.
8. Similar to MAP_POPULATE, MADV_POPULATE_READ and MADV_POPULATE_WRITE cannot protect from the OOM (Out Of Memory) handler killing the process.

While the use case for MADV_POPULATE_WRITE is fairly obvious (i.e., preallocate memory and prefault page tables for VMs), one issue is that whenever we prefault pages writable, the pages have to be marked dirty, because the CPU could dirty them any time. while not a real problem for hugetlbfs or dax/pmem, it can be a problem for shared file mappings: each page will be marked dirty and has to be written back later when evicting.

MADV_POPULATE_READ allows for optimizing this scenario: Pre-read a whole mapping from backend storage without marking it dirty, such that eviction won't have to write it back. As discussed above, shared file mappings might require an explciit fallocate() upfront to achieve preallcoation+prepopulation.

Although sparse memory mappings are the primary use case, this will also be useful for other preallocate/prefault use cases where MAP_POPULATE is not desired or the semantics of MAP_POPULATE are not sufficient: as one example, QEMU users can trigger preallocation/prefaulting of guest RAM after the mapping was created -- and don't want errors to be silently suppressed.

Looking at the history, MADV_POPULATE was already proposed in 2013 [1], however, the main motivation back than was performance improvements -- which should also still be the case.

V. Single-threaded performance comparison

I did a short experiment, prefaulting page tables on completely *empty mappings/files* and repeated the experiment 10 times. The results correspond to the shortest execution time. In general, the performance benefit for huge pages is negligible with small mappings.

V.1: Private mappings

POPULATE_READ and POPULATE_WRITE is fastest. Note that Reading/POPULATE_READ will populate the shared zeropage where applicable -- which result in short population times.

The fastest way to allocate backend storage (here: swap or huge pages) and prefault page tables is POPULATE_WRITE.

V.2: Shared mappings

fallocate() is fastest, however, doesn't prefault page tables. POPULATE_WRITE is faster than simple writes and read/writes. POPULATE_READ is faster than simple reads.

Without a fd, the fastest way to allocate backend storage and prefault page tables is POPULATE_WRITE. With an fd, the fastest way is usually FALLOCATE+POPULATE_READ or FALLOCATE+POPULATE_WRITE respectively; one exception are actual files: FALLOCATE+Read is slightly faster than FALLOCATE+POPULATE_READ.

The fastest way to allocate backend storage prefault page tables is FALLOCATE+POPULATE_WRITE -- except when dealing with actual files; then, FALLOCATE+POPULATE_READ is fastest and won't directly mark all pages as dirty.

v.3: Detailed results

==================================================
2 MiB MAP_PRIVATE:
**************************************************
Anon 4 KiB : Read : 0.119 ms
Anon 4 KiB : Write : 0.222 ms
Anon 4 KiB : Read/Write : 0.380 ms
Anon 4 KiB : POPULATE_READ : 0.060 ms
Anon 4 KiB : POPULATE_WRITE : 0.158 ms
Memfd 4 KiB : Read : 0.034 ms
Memfd 4 KiB : Write : 0.310 ms
Memfd 4 KiB : Read/Write : 0.362 ms
Memfd 4 KiB : POPULATE_READ : 0.039 ms
Memfd 4 KiB : POPULATE_WRITE : 0.229 ms
Memfd 2 MiB : Read : 0.030 ms
Memfd 2 MiB : Write : 0.030 ms
Memfd 2 MiB : Read/Write : 0.030 ms
Memfd 2 MiB : POPULATE_READ : 0.030 ms
Memfd 2 MiB : POPULATE_WRITE : 0.030 ms
tmpfs : Read : 0.033 ms
tmpfs : Write : 0.313 ms
tmpfs : Read/Write : 0.406 ms
tmpfs : POPULATE_READ : 0.039 ms
tmpfs : POPULATE_WRITE : 0.285 ms
file : Read : 0.033 ms
file : Write : 0.351 ms
file : Read/Write : 0.408 ms
file : POPULATE_READ : 0.039 ms
file : POPULATE_WRITE : 0.290 ms
hugetlbfs : Read : 0.030 ms
hugetlbfs : Write : 0.030 ms
hugetlbfs : Read/Write : 0.030 ms
hugetlbfs : POPULATE_READ : 0.030 ms
hugetlbfs : POPULATE_WRITE : 0.030 ms
**************************************************
4096 MiB MAP_PRIVATE:
**************************************************
Anon 4 KiB : Read : 237.940 ms
Anon 4 KiB : Write : 708.409 ms
Anon 4 KiB : Read/Write : 1054.041 ms
Anon 4 KiB : POPULATE_READ : 124.310 ms
Anon 4 KiB : POPULATE_WRITE : 572.582 ms
Memfd 4 KiB : Read : 136.928 ms
Memfd 4 KiB : Write : 963.898 ms
Memfd 4 KiB : Read/Write : 1106.561 ms
Memfd 4 KiB : POPULATE_READ : 78.450 ms
Memfd 4 KiB : POPULATE_WRITE : 805.881 ms
Memfd 2 MiB : Read : 357.116 ms
Memfd 2 MiB : Write : 357.210 ms
Memfd 2 MiB : Read/Write : 357.606 ms
Memfd 2 MiB : POPULATE_READ : 356.094 ms
Memfd 2 MiB : POPULATE_WRITE : 356.937 ms
tmpfs : Read : 137.536 ms
tmpfs : Write : 954.362 ms
tmpfs : Read/Write : 1105.954 ms
tmpfs : POPULATE_READ : 80.289 ms
tmpfs : POPULATE_WRITE : 822.826 ms
file : Read : 137.874 ms
file : Write : 987.025 ms
file : Read/Write : 1107.439 ms
file : POPULATE_READ : 80.413 ms
file : POPULATE_WRITE : 857.622 ms
hugetlbfs : Read : 355.607 ms
hugetlbfs : Write : 355.729 ms
hugetlbfs : Read/Write : 356.127 ms
hugetlbfs : POPULATE_READ : 354.585 ms
hugetlbfs : POPULATE_WRITE : 355.138 ms
**************************************************
2 MiB MAP_SHARED:
**************************************************
Anon 4 KiB : Read : 0.394 ms
Anon 4 KiB : Write : 0.348 ms
Anon 4 KiB : Read/Write : 0.400 ms
Anon 4 KiB : POPULATE_READ : 0.326 ms
Anon 4 KiB : POPULATE_WRITE : 0.273 ms
Anon 2 MiB : Read : 0.030 ms
Anon 2 MiB : Write : 0.030 ms
Anon 2 MiB : Read/Write : 0.030 ms
Anon 2 MiB : POPULATE_READ : 0.030 ms
Anon 2 MiB : POPULATE_WRITE : 0.030 ms
Memfd 4 KiB : Read : 0.412 ms
Memfd 4 KiB : Write : 0.372 ms
Memfd 4 KiB : Read/Write : 0.419 ms
Memfd 4 KiB : POPULATE_READ : 0.343 ms
Memfd 4 KiB : POPULATE_WRITE : 0.288 ms
Memfd 4 KiB : FALLOCATE : 0.137 ms
Memfd 4 KiB : FALLOCATE+Read : 0.446 ms
Memfd 4 KiB : FALLOCATE+Write : 0.330 ms
Memfd 4 KiB : FALLOCATE+Read/Write : 0.454 ms
Memfd 4 KiB : FALLOCATE+POPULATE_READ : 0.379 ms
Memfd 4 KiB : FALLOCATE+POPULATE_WRITE : 0.268 ms
Memfd 2 MiB : Read : 0.030 ms
Memfd 2 MiB : Write : 0.030 ms
Memfd 2 MiB : Read/Write : 0.030 ms
Memfd 2 MiB : POPULATE_READ : 0.030 ms
Memfd 2 MiB : POPULATE_WRITE : 0.030 ms
Memfd 2 MiB : FALLOCATE : 0.030 ms
Memfd 2 MiB : FALLOCATE+Read : 0.031 ms
Memfd 2 MiB : FALLOCATE+Write : 0.031 ms
Memfd 2 MiB : FALLOCATE+Read/Write : 0.031 ms
Memfd 2 MiB : FALLOCATE+POPULATE_READ : 0.030 ms
Memfd 2 MiB : FALLOCATE+POPULATE_WRITE : 0.030 ms
tmpfs : Read : 0.416 ms
tmpfs : Write : 0.369 ms
tmpfs : Read/Write : 0.425 ms
tmpfs : POPULATE_READ : 0.346 ms
tmpfs : POPULATE_WRITE : 0.295 ms
tmpfs : FALLOCATE : 0.139 ms
tmpfs : FALLOCATE+Read : 0.447 ms
tmpfs : FALLOCATE+Write : 0.333 ms
tmpfs : FALLOCATE+Read/Write : 0.454 ms
tmpfs : FALLOCATE+POPULATE_READ : 0.380 ms
tmpfs : FALLOCATE+POPULATE_WRITE : 0.272 ms
file : Read : 0.191 ms
file : Write : 0.511 ms
file : Read/Write : 0.524 ms
file : POPULATE_READ : 0.196 ms
file : POPULATE_WRITE : 0.434 ms
file : FALLOCATE : 0.004 ms
file : FALLOCATE+Read : 0.197 ms
file : FALLOCATE+Write : 0.554 ms
file : FALLOCATE+Read/Write : 0.480 ms
file : FALLOCATE+POPULATE_READ : 0.201 ms
file : FALLOCATE+POPULATE_WRITE : 0.381 ms
hugetlbfs : Read : 0.030 ms
hugetlbfs : Write : 0.030 ms
hugetlbfs : Read/Write : 0.030 ms
hugetlbfs : POPULATE_READ : 0.030 ms
hugetlbfs : POPULATE_WRITE : 0.030 ms
hugetlbfs : FALLOCATE : 0.030 ms
hugetlbfs : FALLOCATE+Read : 0.031 ms
hugetlbfs : FALLOCATE+Write : 0.031 ms
hugetlbfs : FALLOCATE+Read/Write : 0.030 ms
hugetlbfs : FALLOCATE+POPULATE_READ : 0.030 ms
hugetlbfs : FALLOCATE+POPULATE_WRITE : 0.030 ms
**************************************************
4096 MiB MAP_SHARED:
**************************************************
Anon 4 KiB : Read : 1053.090 ms
Anon 4 KiB : Write : 913.642 ms
Anon 4 KiB : Read/Write : 1060.350 ms
Anon 4 KiB : POPULATE_READ : 893.691 ms
Anon 4 KiB : POPULATE_WRITE : 782.885 ms
Anon 2 MiB : Read : 358.553 ms
Anon 2 MiB : Write : 358.419 ms
Anon 2 MiB : Read/Write : 357.992 ms
Anon 2 MiB : POPULATE_READ : 357.533 ms
Anon 2 MiB : POPULATE_WRITE : 357.808 ms
Memfd 4 KiB : Read : 1078.144 ms
Memfd 4 KiB : Write : 942.036 ms
Memfd 4 KiB : Read/Write : 1100.391 ms
Memfd 4 KiB : POPULATE_READ : 925.829 ms
Memfd 4 KiB : POPULATE_WRITE : 804.394 ms
Memfd 4 KiB : FALLOCATE : 304.632 ms
Memfd 4 KiB : FALLOCATE+Read : 1163.359 ms
Memfd 4 KiB : FALLOCATE+Write : 933.186 ms
Memfd 4 KiB : FALLOCATE+Read/Write : 1187.304 ms
Memfd 4 KiB : FALLOCATE+POPULATE_READ : 1013.660 ms
Memfd 4 KiB : FALLOCATE+POPULATE_WRITE : 794.560 ms
Memfd 2 MiB : Read : 358.131 ms
Memfd 2 MiB : Write : 358.099 ms
Memfd 2 MiB : Read/Write : 358.250 ms
Memfd 2 MiB : POPULATE_READ : 357.563 ms
Memfd 2 MiB : POPULATE_WRITE : 357.334 ms
Memfd 2 MiB : FALLOCATE : 356.735 ms
Memfd 2 MiB : FALLOCATE+Read : 358.152 ms
Memfd 2 MiB : FALLOCATE+Write : 358.331 ms
Memfd 2 MiB : FALLOCATE+Read/Write : 358.018 ms
Memfd 2 MiB : FALLOCATE+POPULATE_READ : 357.286 ms
Memfd 2 MiB : FALLOCATE+POPULATE_WRITE : 357.523 ms
tmpfs : Read : 1087.265 ms
tmpfs : Write : 950.840 ms
tmpfs : Read/Write : 1107.567 ms
tmpfs : POPULATE_READ : 922.605 ms
tmpfs : POPULATE_WRITE : 810.094 ms
tmpfs : FALLOCATE : 306.320 ms
tmpfs : FALLOCATE+Read : 1169.796 ms
tmpfs : FALLOCATE+Write : 933.730 ms
tmpfs : FALLOCATE+Read/Write : 1191.610 ms
tmpfs : FALLOCATE+POPULATE_READ : 1020.474 ms
tmpfs : FALLOCATE+POPULATE_WRITE : 798.945 ms
file : Read : 654.101 ms
file : Write : 1259.142 ms
file : Read/Write : 1289.509 ms
file : POPULATE_READ : 661.642 ms
file : POPULATE_WRITE : 1106.816 ms
file : FALLOCATE : 1.864 ms
file : FALLOCATE+Read : 656.328 ms
file : FALLOCATE+Write : 1153.300 ms
file : FALLOCATE+Read/Write : 1180.613 ms
file : FALLOCATE+POPULATE_READ : 668.347 ms
file : FALLOCATE+POPULATE_WRITE : 996.143 ms
hugetlbfs : Read : 357.245 ms
hugetlbfs : Write : 357.413 ms
hugetlbfs : Read/Write : 357.120 ms
hugetlbfs : POPULATE_READ : 356.321 ms
hugetlbfs : POPULATE_WRITE : 356.693 ms
hugetlbfs : FALLOCATE : 355.927 ms
hugetlbfs : FALLOCATE+Read : 357.074 ms
hugetlbfs : FALLOCATE+Write : 357.120 ms
hugetlbfs : FALLOCATE+Read/Write : 356.983 ms
hugetlbfs : FALLOCATE+POPULATE_READ : 356.413 ms
hugetlbfs : FALLOCATE+POPULATE_WRITE : 356.266 ms
**************************************************

[1] https://lkml.org/lkml/2013/6/27/698

[[email protected]: coding style fixes]
Cc Arnd Bergmann <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Andrea Arcangeli <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Michael S. Tsirkin <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Richard Henderson <[email protected]>
Cc Ivan Kokshaysky <[email protected]>
Cc Matt Turner <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Helge Deller <[email protected]>
Cc Chris Zankel <[email protected]>
Cc Max Filippov <[email protected]>
Cc Mike Kravetz <[email protected]>
Cc Peter Xu <[email protected]>
Cc Rolf Eike Beer <[email protected]>
Cc Ram Pai <[email protected]>
Cc Shuah Khan <[email protected]>

---

 arch/alpha/include/uapi/asm/mman.h     |    3 +
 arch/mips/include/uapi/asm/mman.h      |    3 +
 arch/parisc/include/uapi/asm/mman.h    |    3 +
 arch/xtensa/include/uapi/asm/mman.h    |    3 +
 include/uapi/asm-generic/mman-common.h |    3 +
 mm/gup.c                               |   58 ++++++++++++++++++++
 mm/internal.h                          |    3 +
 mm/madvise.c                           |   66 +++++++++++++++++++++++
 8 files changed, 142 insertions(+)
arch/alpha/include/uapi/asm/mman.h renamed from arch/alpha/include/uapi/asm/mman.h~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +3 -0
@@ -71,6 +71,9 @@
 #define MADV_COLD	20		/* deactivate these pages */
 #define MADV_PAGEOUT	21		/* reclaim these pages */
 
+#define MADV_POPULATE_READ	22	/* populate (prefault) page tables readable */
+#define MADV_POPULATE_WRITE	23	/* populate (prefault) page tables writable */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
arch/mips/include/uapi/asm/mman.h renamed from arch/mips/include/uapi/asm/mman.h~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +3 -0
@@ -98,6 +98,9 @@
 #define MADV_COLD	20		/* deactivate these pages */
 #define MADV_PAGEOUT	21		/* reclaim these pages */
 
+#define MADV_POPULATE_READ	22	/* populate (prefault) page tables readable */
+#define MADV_POPULATE_WRITE	23	/* populate (prefault) page tables writable */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
arch/parisc/include/uapi/asm/mman.h renamed from arch/parisc/include/uapi/asm/mman.h~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +3 -0
@@ -52,6 +52,9 @@
 #define MADV_COLD	20		/* deactivate these pages */
 #define MADV_PAGEOUT	21		/* reclaim these pages */
 
+#define MADV_POPULATE_READ	22	/* populate (prefault) page tables readable */
+#define MADV_POPULATE_WRITE	23	/* populate (prefault) page tables writable */
+
 #define MADV_MERGEABLE   65		/* KSM may merge identical pages */
 #define MADV_UNMERGEABLE 66		/* KSM may not merge identical pages */
 
arch/xtensa/include/uapi/asm/mman.h renamed from arch/xtensa/include/uapi/asm/mman.h~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +3 -0
@@ -106,6 +106,9 @@
 #define MADV_COLD	20		/* deactivate these pages */
 #define MADV_PAGEOUT	21		/* reclaim these pages */
 
+#define MADV_POPULATE_READ	22	/* populate (prefault) page tables readable */
+#define MADV_POPULATE_WRITE	23	/* populate (prefault) page tables writable */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
include/uapi/asm-generic/mman-common.h renamed from include/uapi/asm-generic/mman-common.h~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +3 -0
@@ -72,6 +72,9 @@
 #define MADV_COLD	20		/* deactivate these pages */
 #define MADV_PAGEOUT	21		/* reclaim these pages */
 
+#define MADV_POPULATE_READ	22	/* populate (prefault) page tables readable */
+#define MADV_POPULATE_WRITE	23	/* populate (prefault) page tables writable */
+
 /* compatibility flags */
 #define MAP_FILE	0
 
mm/gup.c renamed from mm/gup.c~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +58 -0

64 lines not on this page · raw message

mm/internal.h renamed from mm/internal.h~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +3 -0
@@ -345,6 +345,9 @@ void __vma_unlink_list(struct mm_struct
 #ifdef CONFIG_MMU
 extern long populate_vma_page_range(struct vm_area_struct *vma,
 		unsigned long start, unsigned long end, int *locked);
+extern long faultin_vma_page_range(struct vm_area_struct *vma,
+				   unsigned long start, unsigned long end,
+				   bool write, int *locked);
 extern void munlock_vma_pages_range(struct vm_area_struct *vma,
 			unsigned long start, unsigned long end);
 static inline void munlock_vma_pages_all(struct vm_area_struct *vma)
mm/madvise.c renamed from mm/madvise.c~mm-madvise-introduce-madv_populate_readwrite-to-prefault-page-tables +66 -0

96 lines not on this page · raw message

_

author maintainer
#108 lore raw

PATCH 100/192 MAINTAINERS: add tools/testing/selftests/vm/ to MEMORY MANAGEMENT

In reply to Andrew Morton

From: David Hildenbrand <[email protected]>
Subject: MAINTAINERS: add tools/testing/selftests/vm/ to MEMORY MANAGEMENT

MEMORY MANAGEMENT seems to be a good fit.

Cc Michal Hocko <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Peter Xu <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Andrea Arcangeli <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Chris Zankel <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Helge Deller <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Ivan Kokshaysky <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Matt Turner <[email protected]>
Cc Max Filippov <[email protected]>
Cc Michael S. Tsirkin <[email protected]>
Cc Mike Kravetz <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Ram Pai <[email protected]>
Cc Richard Henderson <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Rolf Eike Beer <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc Vlastimil Babka <[email protected]>

---

 MAINTAINERS |    1 +
 1 file changed, 1 insertion(+)
MAINTAINERS renamed from MAINTAINERS~maintainers-add-tools-testing-selftests-vm-to-memory-management +1 -0
@@ -11828,6 +11828,7 @@ F:	include/linux/mmzone.h
 F:	include/linux/pagewalk.h
 F:	include/linux/vmalloc.h
 F:	mm/
+F:	tools/testing/selftests/vm/
 
 MEMORY TECHNOLOGY DEVICES (MTD)
 M:	Miquel Raynal <[email protected]>

_

author maintainer
#109 lore raw

PATCH 101/192 selftests/vm: add protection_keys_32 / protection_keys_64 to gitignore

In reply to Andrew Morton

From: David Hildenbrand <[email protected]>
Subject: selftests/vm: add protection_keys_32 / protection_keys_64 to gitignore

We missed adding two binaries to gitignore.

Cc Michal Hocko <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Peter Xu <[email protected]>
Cc Ram Pai <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Andrea Arcangeli <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Chris Zankel <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Helge Deller <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Ivan Kokshaysky <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Jann Horn <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Matt Turner <[email protected]>
Cc Max Filippov <[email protected]>
Cc Michael S. Tsirkin <[email protected]>
Cc Mike Kravetz <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Richard Henderson <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Rolf Eike Beer <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc Vlastimil Babka <[email protected]>

---

 tools/testing/selftests/vm/.gitignore |    2 ++
 1 file changed, 2 insertions(+)
tools/testing/selftests/vm/.gitignore renamed from tools/testing/selftests/vm/.gitignore~selftests-vm-add-protection_keys_32-protection_keys_64-to-gitignore +2 -0
@@ -12,6 +12,8 @@ mremap_test
 on-fault-limit
 transhuge-stress
 protection_keys
+protection_keys_32
+protection_keys_64
 userfaultfd
 mlock-intersect-test
 mlock-random-test

_

author maintainer
#110 lore raw

PATCH 102/192 selftests/vm: add test for MADV_POPULATE_(READ|WRITE)

In reply to Andrew Morton

From: David Hildenbrand <[email protected]>
Subject: selftests/vm: add test for MADV_POPULATE_(READ|WRITE)

Let's add a simple test for MADV_POPULATE_READ and MADV_POPULATE_WRITE, verifying some error handling, that population works, and that softdirty tracking works as expected. For now, limit the test to private anonymous memory.

Cc Arnd Bergmann <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Oscar Salvador <[email protected]>
Cc Matthew Wilcox (Oracle) <[email protected]>
Cc Andrea Arcangeli <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Jann Horn <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc Dave Hansen <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Rik van Riel <[email protected]>
Cc Michael S. Tsirkin <[email protected]>
Cc Kirill A. Shutemov <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Richard Henderson <[email protected]>
Cc Ivan Kokshaysky <[email protected]>
Cc Matt Turner <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Helge Deller <[email protected]>
Cc Chris Zankel <[email protected]>
Cc Max Filippov <[email protected]>
Cc Mike Kravetz <[email protected]>
Cc Peter Xu <[email protected]>
Cc Rolf Eike Beer <[email protected]>
Cc Shuah Khan <[email protected]>
Cc Ram Pai <[email protected]>

---

 tools/testing/selftests/vm/.gitignore      |    1 
 tools/testing/selftests/vm/Makefile        |    1 
 tools/testing/selftests/vm/madv_populate.c |  342 +++++++++++++++++++
 tools/testing/selftests/vm/run_vmtests.sh  |   16 
 4 files changed, 360 insertions(+)
tools/testing/selftests/vm/.gitignore renamed from tools/testing/selftests/vm/.gitignore~selftests-vm-add-test-for-madv_populate_readwrite +1 -0
@@ -14,6 +14,7 @@ transhuge-stress
 protection_keys
 protection_keys_32
 protection_keys_64
+madv_populate
 userfaultfd
 mlock-intersect-test
 mlock-random-test
tools/testing/selftests/vm/madv_populate.c new file +342 -0

342 lines not on this page · raw message

tools/testing/selftests/vm/Makefile renamed from tools/testing/selftests/vm/Makefile~selftests-vm-add-test-for-madv_populate_readwrite +1 -0
@@ -31,6 +31,7 @@ TEST_GEN_FILES += hmm-tests
 TEST_GEN_FILES += hugepage-mmap
 TEST_GEN_FILES += hugepage-shm
 TEST_GEN_FILES += khugepaged
+TEST_GEN_FILES += madv_populate
 TEST_GEN_FILES += map_fixed_noreplace
 TEST_GEN_FILES += map_hugetlb
 TEST_GEN_FILES += map_populate
tools/testing/selftests/vm/run_vmtests.sh renamed from tools/testing/selftests/vm/run_vmtests.sh~selftests-vm-add-test-for-madv_populate_readwrite +16 -0
@@ -346,4 +346,20 @@ else
 	exitcode=1
 fi
 
+echo "--------------------------------------------------------"
+echo "running MADV_POPULATE_READ and MADV_POPULATE_WRITE tests"
+echo "--------------------------------------------------------"
+./madv_populate
+ret_val=$?
+
+if [ $ret_val -eq 0 ]; then
+	echo "[PASS]"
+elif [ $ret_val -eq $ksft_skip ]; then
+	echo "[SKIP]"
+	exitcode=$ksft_skip
+else
+	echo "[FAIL]"
+	exitcode=1
+fi
+
 exit $exitcode

_

author maintainer
#111 lore raw

PATCH 103/192 mm/memory_hotplug: rate limit page migration warnings

In reply to Andrew Morton

From: Liam Mark <[email protected]>
Subject: mm/memory_hotplug: rate limit page migration warnings

When offlining memory the system can attempt to migrate a lot of pages, if there are problems with migration this can flood the logs. Printing all the data hogs the CPU and cause some RT threads to run for a long time, which may have some bad consequences.

Rate limit the page migration warnings in order to avoid this.

---

 mm/memory_hotplug.c |   16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-rate-limit-page-migration-warnings +11 -5
@@ -1406,6 +1406,8 @@ do_migrate_range(unsigned long start_pfn
 	struct page *page, *head;
 	int ret = 0;
 	LIST_HEAD(source);
+	static DEFINE_RATELIMIT_STATE(migrate_rs, DEFAULT_RATELIMIT_INTERVAL,
+				      DEFAULT_RATELIMIT_BURST);
 
 	for (pfn = start_pfn; pfn < end_pfn; pfn++) {
 		if (!pfn_valid(pfn))
@@ -1452,8 +1454,10 @@ do_migrate_range(unsigned long start_pfn
 						    page_is_file_lru(page));
 
 		} else {
-			pr_warn("failed to isolate pfn %lx\n", pfn);
-			dump_page(page, "isolation failed");
+			if (__ratelimit(&migrate_rs)) {
+				pr_warn("failed to isolate pfn %lx\n", pfn);
+				dump_page(page, "isolation failed");
+			}
 		}
 		put_page(page);
 	}
@@ -1482,9 +1486,11 @@ do_migrate_range(unsigned long start_pfn
 			(unsigned long)&mtc, MIGRATE_SYNC, MR_MEMORY_HOTPLUG);
 		if (ret) {
 			list_for_each_entry(page, &source, lru) {
-				pr_warn("migrating pfn %lx failed ret:%d ",
-				       page_to_pfn(page), ret);
-				dump_page(page, "migration failure");
+				if (__ratelimit(&migrate_rs)) {
+					pr_warn("migrating pfn %lx failed ret:%d\n",
+						page_to_pfn(page), ret);
+					dump_page(page, "migration failure");
+				}
 			}
 			putback_movable_pages(&source);
 		}

_

author maintainer
#112 lore raw

PATCH 104/192 mm,memory_hotplug: drop unneeded locking

In reply to Andrew Morton

From: Oscar Salvador <[email protected]>
Subject: mm,memory_hotplug: drop unneeded locking

Currently, memory-hotplug code takes zone's span_writelock and pgdat's resize_lock when resizing the node/zone's spanned pages via {move_pfn_range_to_zone(),remove_pfn_range_from_zone()} and when resizing node and zone's present pages via adjust_present_page_count().

These locks are also taken during the initialization of the system at boot time, where it protects parallel struct page initialization, but they should not really be needed in memory-hotplug where all operations are a) synchronized on device level and b) serialized by the mem_hotplug_lock lock.

---

 mm/memory_hotplug.c |   16 +---------------
 1 file changed, 1 insertion(+), 15 deletions(-)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mmmemory_hotplug-drop-unneeded-locking +1 -15
@@ -329,7 +329,6 @@ static void shrink_zone_span(struct zone
 	unsigned long pfn;
 	int nid = zone_to_nid(zone);
 
-	zone_span_writelock(zone);
 	if (zone->zone_start_pfn == start_pfn) {
 		/*
 		 * If the section is smallest section in the zone, it need
@@ -362,7 +361,6 @@ static void shrink_zone_span(struct zone
 			zone->spanned_pages = 0;
 		}
 	}
-	zone_span_writeunlock(zone);
 }
 
 static void update_pgdat_span(struct pglist_data *pgdat)
@@ -399,7 +397,7 @@ void __ref remove_pfn_range_from_zone(st
 {
 	const unsigned long end_pfn = start_pfn + nr_pages;
 	struct pglist_data *pgdat = zone->zone_pgdat;
-	unsigned long pfn, cur_nr_pages, flags;
+	unsigned long pfn, cur_nr_pages;
 
 	/* Poison struct pages because they are now uninitialized again. */
 	for (pfn = start_pfn; pfn < end_pfn; pfn += cur_nr_pages) {
@@ -424,10 +422,8 @@ void __ref remove_pfn_range_from_zone(st
 
 	clear_zone_contiguous(zone);
 
-	pgdat_resize_lock(zone->zone_pgdat, &flags);
 	shrink_zone_span(zone, start_pfn, start_pfn + nr_pages);
 	update_pgdat_span(pgdat);
-	pgdat_resize_unlock(zone->zone_pgdat, &flags);
 
 	set_zone_contiguous(zone);
 }
@@ -634,19 +630,13 @@ void __ref move_pfn_range_to_zone(struct
 {
 	struct pglist_data *pgdat = zone->zone_pgdat;
 	int nid = pgdat->node_id;
-	unsigned long flags;
 
 	clear_zone_contiguous(zone);
 
-	/* TODO Huh pgdat is irqsave while zone is not. It used to be like that before */
-	pgdat_resize_lock(pgdat, &flags);
-	zone_span_writelock(zone);
 	if (zone_is_empty(zone))
 		init_currently_empty_zone(zone, start_pfn, nr_pages);
 	resize_zone_range(zone, start_pfn, nr_pages);
-	zone_span_writeunlock(zone);
 	resize_pgdat_range(pgdat, start_pfn, nr_pages);
-	pgdat_resize_unlock(pgdat, &flags);
 
 	/*
 	 * Subsection population requires care in pfn_to_online_page().
@@ -736,12 +726,8 @@ struct zone *zone_for_pfn_range(int onli
  */
 void adjust_present_page_count(struct zone *zone, long nr_pages)
 {
-	unsigned long flags;
-
 	zone->present_pages += nr_pages;
-	pgdat_resize_lock(zone->zone_pgdat, &flags);
 	zone->zone_pgdat->node_present_pages += nr_pages;
-	pgdat_resize_unlock(zone->zone_pgdat, &flags);
 }
 
 int mhp_init_memmap_on_memory(unsigned long pfn, unsigned long nr_pages,

_

author maintainer
#113 lore raw

PATCH 105/192 mm/zswap.c: remove unused function zswap_debugfs_exit()

In reply to Andrew Morton

From: Miaohe Lin <[email protected]>
Subject: mm/zswap.c: remove unused function zswap_debugfs_exit()

Patch series "Cleanup and fixup for zswap".

This series contains cleanups to remove unused function and avoid unnecessary copy-in at map time. Also this fixes two bugs in the function zswap_writeback_entry(). More details can be found in the respective changelogs.

This patch (of 3):

zswap_debugfs_exit() is unused, remove it.

---

 mm/zswap.c |    7 -------
 1 file changed, 7 deletions(-)
mm/zswap.c renamed from mm/zswap.c~mm-zswapc-remove-unused-function-zswap_debugfs_exit +0 -7
@@ -1427,18 +1427,11 @@ static int __init zswap_debugfs_init(voi
 
 	return 0;
 }
-
-static void __exit zswap_debugfs_exit(void)
-{
-	debugfs_remove_recursive(zswap_debugfs_root);
-}
 #else
 static int __init zswap_debugfs_init(void)
 {
 	return 0;
 }
-
-static void __exit zswap_debugfs_exit(void) { }
 #endif
 
 /*********************************

_

author maintainer
#114 lore raw

PATCH 106/192 mm/zswap.c: avoid unnecessary copy-in at map time

In reply to Andrew Morton

From: Miaohe Lin <[email protected]>
Subject: mm/zswap.c: avoid unnecessary copy-in at map time

The buf mapped via zpool_map_handle() is only used to store compressed page buffer and there is no information to extract from it. So we could use ZPOOL_MM_WO instead to avoid unnecessary copy-in at map time.

Cc Colin Ian King <[email protected]>
Cc Dan Streetman <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Sebastian Andrzej Siewior <[email protected]>
Cc Seth Jennings <[email protected]>
Cc Tian Tao <[email protected]>
Cc Vitaly Wool <[email protected]>

---

 mm/zswap.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zswap.c renamed from mm/zswap.c~mm-zswapc-avoid-unnecessary-copy-in-at-map-time +1 -1
@@ -1203,7 +1203,7 @@ static int zswap_frontswap_store(unsigne
 		zswap_reject_alloc_fail++;
 		goto put_dstmem;
 	}
-	buf = zpool_map_handle(entry->pool->zpool, handle, ZPOOL_MM_RW);
+	buf = zpool_map_handle(entry->pool->zpool, handle, ZPOOL_MM_WO);
 	memcpy(buf, &zhdr, hlen);
 	memcpy(buf + hlen, dst, dlen);
 	zpool_unmap_handle(entry->pool->zpool, handle);

_

author maintainer
#115 lore raw

PATCH 107/192 mm/zswap.c: fix two bugs in zswap_writeback_entry()

In reply to Andrew Morton

From: Miaohe Lin <[email protected]>
Subject: mm/zswap.c: fix two bugs in zswap_writeback_entry()

In the ZSWAP_SWAPCACHE_FAIL and ZSWAP_SWAPCACHE_EXIST case, we forgot to call zpool_unmap_handle() when zpool can't sleep. And we might sleep in zswap_get_swap_cache_page() while zpool can't sleep. To fix all of these, zpool_unmap_handle() should be done before zswap_get_swap_cache_page() when zpool can't sleep.

Fixes fc6697a89f56 ("mm/zswap: add the flag can_sleep_mapped")
Cc Colin Ian King <[email protected]>
Cc Dan Streetman <[email protected]>
Cc Nathan Chancellor <[email protected]>
Cc Sebastian Andrzej Siewior <[email protected]>
Cc Seth Jennings <[email protected]>
Cc Tian Tao <[email protected]>
Cc Vitaly Wool <[email protected]>

---

 mm/zswap.c |   17 +++++++----------
 1 file changed, 7 insertions(+), 10 deletions(-)
mm/zswap.c renamed from mm/zswap.c~mm-zswapc-fix-two-bugs-in-zswap_writeback_entry +7 -10
@@ -967,6 +967,13 @@ static int zswap_writeback_entry(struct
 	spin_unlock(&tree->lock);
 	BUG_ON(offset != entry->offset);
 
+	src = (u8 *)zhdr + sizeof(struct zswap_header);
+	if (!zpool_can_sleep_mapped(pool)) {
+		memcpy(tmp, src, entry->length);
+		src = tmp;
+		zpool_unmap_handle(pool, handle);
+	}
+
 	/* try to allocate swap cache page */
 	switch (zswap_get_swap_cache_page(swpentry, &page)) {
 	case ZSWAP_SWAPCACHE_FAIL: /* no memory or invalidate happened */
@@ -982,17 +989,7 @@ static int zswap_writeback_entry(struct
 	case ZSWAP_SWAPCACHE_NEW: /* page is locked */
 		/* decompress */
 		acomp_ctx = raw_cpu_ptr(entry->pool->acomp_ctx);
-
 		dlen = PAGE_SIZE;
-		src = (u8 *)zhdr + sizeof(struct zswap_header);
-
-		if (!zpool_can_sleep_mapped(pool)) {
-
-			memcpy(tmp, src, entry->length);
-			src = tmp;
-
-			zpool_unmap_handle(pool, handle);
-		}
 
 		mutex_lock(acomp_ctx->mutex);
 		sg_init_one(&input, src, entry->length);

_

author maintainer
#116 lore raw

PATCH 108/192 mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

In reply to Andrew Morton

From: Zhaoyang Huang <[email protected]>
Subject: mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Zspage_cachep is found be merged with other kmem cache during test, which is not good for debug things (zs_pool->zspage_cachep present to be another kmem cache in memory dumpfile). It is also neccessary to do so as shrinker has been registered for zspage.

Amending this flag can help kernel to calculate SLAB_RECLAIMBLE correctly.

---

 mm/zsmalloc.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zsmalloc.c renamed from mm/zsmalloc.c~mm-zram-amend-slab_reclaim_account-on-zspage_cachep +1 -1
@@ -328,7 +328,7 @@ static int create_cache(struct zs_pool *
 		return 1;
 
 	pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
-					0, 0, NULL);
+					0, SLAB_RECLAIM_ACCOUNT, NULL);
 	if (!pool->zspage_cachep) {
 		kmem_cache_destroy(pool->handle_cachep);
 		pool->handle_cachep = NULL;

_

maintainer
#117 lore raw

Re: [patch 108/192] mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Quoted 8 lines · Andrew Morton

From: Zhaoyang Huang <[email protected]>
Subject: mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Zspage_cachep is found be merged with other kmem cache during test, which is not good for debug things (zs_pool->zspage_cachep present to be another kmem cache in memory dumpfile). It is also neccessary to do so as shrinker has been registered for zspage.

Quoted 7 lines

Amending this flag can help kernel to calculate SLAB_RECLAIMBLE correctly.

Sorry for the late. I don't think this is correct.

It's true "struct zspage" can be freed by zsmalloc's compaction registerred by slab shrinker so tempted to make it SLAB_RECLAIM_ACCOUNT. However, it's quite limited to work only when objects in the zspage are heavily fragmented. Once the compaction is done, zspage are never discardable until objects are fragmented again. It means it could hurt other reclaimable slab page reclaiming since the zspage slab object pins the page.

Quoted 17 lines

---

 mm/zsmalloc.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zsmalloc.c renamed from mm/zsmalloc.c~mm-zram-amend-slab_reclaim_account-on-zspage_cachep +1 -1
@@ -328,7 +328,7 @@ static int create_cache(struct zs_pool *
 		return 1;
 
 	pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
-					0, 0, NULL);
+					0, SLAB_RECLAIM_ACCOUNT, NULL);
 	if (!pool->zspage_cachep) {
 		kmem_cache_destroy(pool->handle_cachep);
 		pool->handle_cachep = NULL;

_

#118 lore raw

Re: [patch 108/192] mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Quoted 2 lines · Minchan Kim

Sorry for the late. I don't think this is correct.

Not _too_ late - I had applied the series to my tree already, but I try to delay merging my akpm branch overnight exactly to see if there are any replies to Andrew's sending of the series.

So I've dropped this patch from that branch.

Linus

#119 lore raw

Re: [patch 108/192] mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

In reply to Minchan Kim
Quoted 18 lines · Minchan Kim
Quoted 8 lines · Andrew Morton

From: Zhaoyang Huang <[email protected]>
Subject: mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Zspage_cachep is found be merged with other kmem cache during test, which is not good for debug things (zs_pool->zspage_cachep present to be another kmem cache in memory dumpfile). It is also neccessary to do so as shrinker has been registered for zspage.

Quoted 7 lines

Amending this flag can help kernel to calculate SLAB_RECLAIMBLE correctly.

Quoted 8 lines

Sorry for the late. I don't think this is correct.

It's true "struct zspage" can be freed by zsmalloc's compaction registerred by slab shrinker so tempted to make it SLAB_RECLAIM_ACCOUNT. However, it's quite limited to work only when objects in the zspage are heavily fragmented. Once the compaction is done, zspage are never discardable until objects are fragmented again. It means it could hurt other reclaimable slab page reclaiming since the zspage slab object pins the page.

IMHO, kmem cache's reclaiming is NOT affected by SLAB_RECLAIM_ACCOUNT . This flag just affects kmem cache merge[1], the slab page's migrate type[2] and the page's statistics. Actually, zspage's cache DO merged with others even without SLAB_RECLAIM_ACCOUNT currently, which maybe cause zspage's object will NEVER be discarded.(SLAB_MERGE_SAME introduce confusions as people believe the cache will merge with others when it set and vice versa)

[1]
struct kmem_cache *find_mergeable(size_t size, size_t align, unsigned
long flags, const char *name, void (*ctor)(void *))
...

    if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
     continue;

[2]
if (s->flags & SLAB_RECLAIM_ACCOUNT)

    s->allocflags |= __GFP_RECLAIMABLE;
Quoted 18 lines
Quoted 18 lines

---

 mm/zsmalloc.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zsmalloc.c renamed from mm/zsmalloc.c~mm-zram-amend-slab_reclaim_account-on-zspage_cachep +1 -1
@@ -328,7 +328,7 @@ static int create_cache(struct zs_pool *
              return 1;
 
      pool->zspage_cachep = kmem_cache_create("zspage", sizeof(struct zspage),
-                                     0, 0, NULL);
+                                     0, SLAB_RECLAIM_ACCOUNT, NULL);
      if (!pool->zspage_cachep) {
              kmem_cache_destroy(pool->handle_cachep);
              pool->handle_cachep = NULL;

_

maintainer
#120 lore raw

Re: [patch 108/192] mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Quoted 39 lines · Zhaoyang Huang
Quoted 18 lines · Minchan Kim
Quoted 8 lines · Andrew Morton

From: Zhaoyang Huang <[email protected]>
Subject: mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Zspage_cachep is found be merged with other kmem cache during test, which is not good for debug things (zs_pool->zspage_cachep present to be another kmem cache in memory dumpfile). It is also neccessary to do so as shrinker has been registered for zspage.

Quoted 7 lines

Amending this flag can help kernel to calculate SLAB_RECLAIMBLE correctly.

Quoted 8 lines

Sorry for the late. I don't think this is correct.

It's true "struct zspage" can be freed by zsmalloc's compaction registerred by slab shrinker so tempted to make it SLAB_RECLAIM_ACCOUNT. However, it's quite limited to work only when objects in the zspage are heavily fragmented. Once the compaction is done, zspage are never discardable until objects are fragmented again. It means it could hurt other reclaimable slab page reclaiming since the zspage slab object pins the page.

IMHO, kmem cache's reclaiming is NOT affected by SLAB_RECLAIM_ACCOUNT . This flag just affects kmem cache merge[1], the slab page's migrate type[2] and the page's statistics. Actually, zspage's cache DO merged with others even without SLAB_RECLAIM_ACCOUNT currently, which maybe cause zspage's object will NEVER be discarded.(SLAB_MERGE_SAME introduce confusions as people believe the cache will merge with others when it set and vice versa)

[1]
struct kmem_cache *find_mergeable(size_t size, size_t align, unsigned
long flags, const char *name, void (*ctor)(void *))
...

Quoted 6 lines
    if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
     continue;

[2]
if (s->flags & SLAB_RECLAIM_ACCOUNT)

    s->allocflags |= __GFP_RECLAIMABLE;

That's the point here. With SLAB_RECLAIM_ACCOUNT, page allocator try to allocate pages from MIGRATE_RECLAIMABLE with belief those objects are easily reclaimable. Say a page has object A, B, C, D and E. A-D are easily reclaimable but E is hard. What happens is VM couldn't reclaim the page in the end due to E even though it already reclaimed A-D. And the such fragmenation could be spread out entire MIGRATE_RECLAIMABLE pageblocks over time. That's why I'd like to put zspage into MIGRATE_UNMOVALBE from the beginning since I don't think it's easily reclaimble once compaction is done.

#121 lore raw

Re: [patch 108/192] mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Quoted 48 lines · Minchan Kim
Quoted 39 lines · Zhaoyang Huang
Quoted 18 lines · Minchan Kim
Quoted 8 lines · Andrew Morton

From: Zhaoyang Huang <[email protected]>
Subject: mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Zspage_cachep is found be merged with other kmem cache during test, which is not good for debug things (zs_pool->zspage_cachep present to be another kmem cache in memory dumpfile). It is also neccessary to do so as shrinker has been registered for zspage.

Quoted 7 lines

Amending this flag can help kernel to calculate SLAB_RECLAIMBLE correctly.

Quoted 8 lines

Sorry for the late. I don't think this is correct.

It's true "struct zspage" can be freed by zsmalloc's compaction registerred by slab shrinker so tempted to make it SLAB_RECLAIM_ACCOUNT. However, it's quite limited to work only when objects in the zspage are heavily fragmented. Once the compaction is done, zspage are never discardable until objects are fragmented again. It means it could hurt other reclaimable slab page reclaiming since the zspage slab object pins the page.

IMHO, kmem cache's reclaiming is NOT affected by SLAB_RECLAIM_ACCOUNT . This flag just affects kmem cache merge[1], the slab page's migrate type[2] and the page's statistics. Actually, zspage's cache DO merged with others even without SLAB_RECLAIM_ACCOUNT currently, which maybe cause zspage's object will NEVER be discarded.(SLAB_MERGE_SAME introduce confusions as people believe the cache will merge with others when it set and vice versa)

[1]
struct kmem_cache *find_mergeable(size_t size, size_t align, unsigned
long flags, const char *name, void (*ctor)(void *))
...

Quoted 6 lines
    if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
     continue;

[2]
if (s->flags & SLAB_RECLAIM_ACCOUNT)

    s->allocflags |= __GFP_RECLAIMABLE;
Quoted 10 lines

That's the point here. With SLAB_RECLAIM_ACCOUNT, page allocator try to allocate pages from MIGRATE_RECLAIMABLE with belief those objects are easily reclaimable. Say a page has object A, B, C, D and E. A-D are easily reclaimable but E is hard. What happens is VM couldn't reclaim the page in the end due to E even though it already reclaimed A-D. And the such fragmenation could be spread out entire MIGRATE_RECLAIMABLE pageblocks over time. That's why I'd like to put zspage into MIGRATE_UNMOVALBE from the beginning since I don't think it's easily reclaimble once compaction is done.

The slab page could fallback to any migrate type even allocating with __GFP_RECLAIMABLE, and there is only one page per slab within zspage's cache, which will not be affected by compaction, so I think that doesn't make sense.

maintainer
#122 lore raw

Re: [patch 108/192] mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Quoted 59 lines · Zhaoyang Huang
Quoted 48 lines · Minchan Kim
Quoted 39 lines · Zhaoyang Huang
Quoted 18 lines · Minchan Kim
Quoted 8 lines · Andrew Morton

From: Zhaoyang Huang <[email protected]>
Subject: mm: zram: amend SLAB_RECLAIM_ACCOUNT on zspage_cachep

Zspage_cachep is found be merged with other kmem cache during test, which is not good for debug things (zs_pool->zspage_cachep present to be another kmem cache in memory dumpfile). It is also neccessary to do so as shrinker has been registered for zspage.

Quoted 7 lines

Amending this flag can help kernel to calculate SLAB_RECLAIMBLE correctly.

Quoted 8 lines

Sorry for the late. I don't think this is correct.

It's true "struct zspage" can be freed by zsmalloc's compaction registerred by slab shrinker so tempted to make it SLAB_RECLAIM_ACCOUNT. However, it's quite limited to work only when objects in the zspage are heavily fragmented. Once the compaction is done, zspage are never discardable until objects are fragmented again. It means it could hurt other reclaimable slab page reclaiming since the zspage slab object pins the page.

IMHO, kmem cache's reclaiming is NOT affected by SLAB_RECLAIM_ACCOUNT . This flag just affects kmem cache merge[1], the slab page's migrate type[2] and the page's statistics. Actually, zspage's cache DO merged with others even without SLAB_RECLAIM_ACCOUNT currently, which maybe cause zspage's object will NEVER be discarded.(SLAB_MERGE_SAME introduce confusions as people believe the cache will merge with others when it set and vice versa)

[1]
struct kmem_cache *find_mergeable(size_t size, size_t align, unsigned
long flags, const char *name, void (*ctor)(void *))
...

Quoted 6 lines
    if ((flags & SLAB_MERGE_SAME) != (s->flags & SLAB_MERGE_SAME))
     continue;

[2]
if (s->flags & SLAB_RECLAIM_ACCOUNT)

    s->allocflags |= __GFP_RECLAIMABLE;
Quoted 10 lines

That's the point here. With SLAB_RECLAIM_ACCOUNT, page allocator try to allocate pages from MIGRATE_RECLAIMABLE with belief those objects are easily reclaimable. Say a page has object A, B, C, D and E. A-D are easily reclaimable but E is hard. What happens is VM couldn't reclaim the page in the end due to E even though it already reclaimed A-D. And the such fragmenation could be spread out entire MIGRATE_RECLAIMABLE pageblocks over time. That's why I'd like to put zspage into MIGRATE_UNMOVALBE from the beginning since I don't think it's easily reclaimble once compaction is done.

Quoted 1 line

The slab page could fallback to any migrate type even allocating with

It's true but it couldn't be justication to allocate objects from any migration type. We should try to select right type. Please see below.

Quoted 3 lines

__GFP_RECLAIMABLE, and there is only one page per slab within zspage's cache, which will not be affected by compaction, so I think that doesn't make sense.

You shouldn't rely on how many pages the slab has since it's internal implemenation and zspage size also could be changed in the future. And please think about external fragmentaion as well as internal one.

What we want to try with allocation type is to group similar lifetime objects together in a pageblock group to help external fragmentation for high-order allocation. Think what happens if the unreclaimable object is located in a reclaimable pageblock. The block couldn't be merged into high-order page in the end so it causes more compaction and smaller available high-order pages in the system.

author maintainer
#123 lore raw

PATCH 109/192 mm/zsmalloc.c: remove confusing code in obj_free()

In reply to Andrew Morton

From: Miaohe Lin <[email protected]>
Subject: mm/zsmalloc.c: remove confusing code in obj_free()

Patch series "Cleanup for zsmalloc".

This series contains cleanups to remove confusing code in obj_free(), combine two atomic ops and improve readability for async_free_zspage(). More details can be found in the respective changelogs.

This patch (of 2):

OBJ_ALLOCATED_TAG is only set for handle to indicate allocated object. It's irrelevant with obj. So remove this misleading code to improve readability.

---

 mm/zsmalloc.c |    1 -
 1 file changed, 1 deletion(-)
mm/zsmalloc.c renamed from mm/zsmalloc.c~mm-zsmallocc-remove-confusing-code-in-obj_free +0 -1
@@ -1471,7 +1471,6 @@ static void obj_free(struct size_class *
 	unsigned int f_objidx;
 	void *vaddr;
 
-	obj &= ~OBJ_ALLOCATED_TAG;
 	obj_to_location(obj, &f_page, &f_objidx);
 	f_offset = (class->size * f_objidx) & ~PAGE_MASK;
 	zspage = get_zspage(f_page);

_

author maintainer
#124 lore raw

PATCH 110/192 mm/zsmalloc.c: improve readability for async_free_zspage()

In reply to Andrew Morton

From: Miaohe Lin <[email protected]>
Subject: mm/zsmalloc.c: improve readability for async_free_zspage()

The class is extracted from pool->size_class[class_idx] again before calling __free_zspage(). It looks like class will change after we fetch the class lock. But this is misleading as class will stay unchanged.

---

 mm/zsmalloc.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/zsmalloc.c renamed from mm/zsmalloc.c~mm-zsmallocc-improve-readability-for-async_free_zspage +1 -1
@@ -2162,7 +2162,7 @@ static void async_free_zspage(struct wor
 		VM_BUG_ON(fullness != ZS_EMPTY);
 		class = pool->size_class[class_idx];
 		spin_lock(&class->lock);
-		__free_zspage(pool, pool->size_class[class_idx], zspage);
+		__free_zspage(pool, class, zspage);
 		spin_unlock(&class->lock);
 	}
 };

_

author maintainer
#125 lore raw

PATCH 111/192 zram: move backing_dev under macro CONFIG_ZRAM_WRITEBACK

In reply to Andrew Morton

From: Yue Hu <[email protected]>
Subject: zram: move backing_dev under macro CONFIG_ZRAM_WRITEBACK

backing_dev is never used when not enable CONFIG_ZRAM_WRITEBACK and it's introduced from writeback feature. So it's needless also affect readability in that case.

---

 drivers/block/zram/zram_drv.h |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/block/zram/zram_drv.h renamed from drivers/block/zram/zram_drv.h~zram-move-backing_dev-under-macro-config_zram_writeback +1 -1
@@ -113,8 +113,8 @@ struct zram {
 	 * zram is claimed so open request will be failed
 	 */
 	bool claim; /* Protected by bdev->bd_mutex */
-	struct file *backing_dev;
 #ifdef CONFIG_ZRAM_WRITEBACK
+	struct file *backing_dev;
 	spinlock_t wb_limit_lock;
 	bool wb_limit_enable;
 	u64 bd_wb_limit;

_

author maintainer
#126 lore raw

PATCH 112/192 mm: fix typos and grammar error in comments

In reply to Andrew Morton

From: Hyeonggon Yoo <[email protected]>
Subject: mm: fix typos and grammar error in comments

We moves tha -> We move that in mm/swap.c statments -> statements in include/linux/mm.h

---

 include/linux/mm.h |    2 +-
 mm/swap.c          |    2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
include/linux/mm.h renamed from include/linux/mm.h~mm-fix-typos-and-grammar-error-in-comments +1 -1
@@ -155,7 +155,7 @@ extern int mmap_rnd_compat_bits __read_m
 /* This function must be updated when the size of struct page grows above 80
  * or reduces below 56. The idea that compiler optimizes out switch()
  * statement, and only leaves move/store instructions. Also the compiler can
- * combine write statments if they are both assignments and can be reordered,
+ * combine write statements if they are both assignments and can be reordered,
  * this can result in several of the writes here being dropped.
  */
 #define	mm_zero_struct_page(pp) __mm_zero_struct_page(pp)
mm/swap.c renamed from mm/swap.c~mm-fix-typos-and-grammar-error-in-comments +1 -1
@@ -554,7 +554,7 @@ static void lru_deactivate_file_fn(struc
 	} else {
 		/*
 		 * The page's writeback ends up during pagevec
-		 * We moves tha page into tail of inactive.
+		 * We move that page into tail of inactive.
 		 */
 		add_page_to_lru_list_tail(page, lruvec);
 		__count_vm_events(PGROTATED, nr_pages);

_

author maintainer
#127 lore raw

PATCH 113/192 mm: define default value for FIRST_USER_ADDRESS

In reply to Andrew Morton

From: Anshuman Khandual <[email protected]>
Subject: mm: define default value for FIRST_USER_ADDRESS

Currently most platforms define FIRST_USER_ADDRESS as 0UL duplication the same code all over. Instead just define a generic default value (i.e 0UL) for FIRST_USER_ADDRESS and let the platforms override when required. This makes it much cleaner with reduced code.

The default FIRST_USER_ADDRESS here would be skipped in <linux/pgtable.h> when the given platform overrides its value via <asm/pgtable.h>.

Cc Richard Henderson <[email protected]>
Cc Vineet Gupta <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Will Deacon <[email protected]>
Cc Guo Ren <[email protected]>
Cc Brian Cain <[email protected]>
Cc Geert Uytterhoeven <[email protected]>
Cc Michal Simek <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc Ley Foon Tan <[email protected]>
Cc Jonas Bonn <[email protected]>
Cc Stefan Kristiansson <[email protected]>
Cc Stafford Horne <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Christophe Leroy <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Yoshinori Sato <[email protected]>
Cc "David S. Miller" <[email protected]>
Cc Jeff Dike <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Chris Zankel <[email protected]>

---

 arch/alpha/include/asm/pgtable.h             |    1 -
 arch/arc/include/asm/pgtable.h               |    6 ------
 arch/arm64/include/asm/pgtable.h             |    2 --
 arch/csky/include/asm/pgtable.h              |    1 -
 arch/hexagon/include/asm/pgtable.h           |    3 ---
 arch/ia64/include/asm/pgtable.h              |    1 -
 arch/m68k/include/asm/pgtable_mm.h           |    1 -
 arch/microblaze/include/asm/pgtable.h        |    2 --
 arch/mips/include/asm/pgtable-32.h           |    1 -
 arch/mips/include/asm/pgtable-64.h           |    1 -
 arch/nios2/include/asm/pgtable.h             |    2 --
 arch/openrisc/include/asm/pgtable.h          |    1 -
 arch/parisc/include/asm/pgtable.h            |    2 --
 arch/powerpc/include/asm/book3s/pgtable.h    |    1 -
 arch/powerpc/include/asm/nohash/32/pgtable.h |    1 -
 arch/powerpc/include/asm/nohash/64/pgtable.h |    2 --
 arch/riscv/include/asm/pgtable.h             |    2 --
 arch/s390/include/asm/pgtable.h              |    2 --
 arch/sh/include/asm/pgtable.h                |    2 --
 arch/sparc/include/asm/pgtable_32.h          |    1 -
 arch/sparc/include/asm/pgtable_64.h          |    3 ---
 arch/um/include/asm/pgtable-2level.h         |    1 -
 arch/um/include/asm/pgtable-3level.h         |    1 -
 arch/x86/include/asm/pgtable_types.h         |    2 --
 arch/xtensa/include/asm/pgtable.h            |    1 -
 include/linux/pgtable.h                      |    9 +++++++++
 26 files changed, 9 insertions(+), 43 deletions(-)
arch/alpha/include/asm/pgtable.h renamed from arch/alpha/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -1
@@ -46,7 +46,6 @@ struct vm_area_struct;
 #define PTRS_PER_PMD	(1UL << (PAGE_SHIFT-3))
 #define PTRS_PER_PGD	(1UL << (PAGE_SHIFT-3))
 #define USER_PTRS_PER_PGD	(TASK_SIZE / PGDIR_SIZE)
-#define FIRST_USER_ADDRESS	0UL
 
 /* Number of pointers that fit on a page:  this will go away. */
 #define PTRS_PER_PAGE	(1UL << (PAGE_SHIFT-3))
arch/arc/include/asm/pgtable.h renamed from arch/arc/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -6
@@ -222,12 +222,6 @@
  */
 #define	USER_PTRS_PER_PGD	(TASK_SIZE / PGDIR_SIZE)
 
-/*
- * No special requirements for lowest virtual address we permit any user space
- * mapping to be mapped at.
- */
-#define FIRST_USER_ADDRESS      0UL
-
 
 /****************************************************************
  * Bucket load of VM Helpers
arch/arm64/include/asm/pgtable.h renamed from arch/arm64/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -26,8 +26,6 @@
 
 #define vmemmap			((struct page *)VMEMMAP_START - (memstart_addr >> PAGE_SHIFT))
 
-#define FIRST_USER_ADDRESS	0UL
-
 #ifndef __ASSEMBLY__
 
 #include <asm/cmpxchg.h>
arch/csky/include/asm/pgtable.h renamed from arch/csky/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -1
@@ -14,7 +14,6 @@
 #define PGDIR_MASK		(~(PGDIR_SIZE-1))
 
 #define USER_PTRS_PER_PGD	(PAGE_OFFSET/PGDIR_SIZE)
-#define FIRST_USER_ADDRESS	0UL
 
 /*
  * C-SKY is two-level paging structure:
arch/hexagon/include/asm/pgtable.h renamed from arch/hexagon/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -3
@@ -155,9 +155,6 @@ extern unsigned long _dflt_cache_att;
 
 extern pgd_t swapper_pg_dir[PTRS_PER_PGD];  /* located in head.S */
 
-/* Seems to be zero even in architectures where the zero page is firewalled? */
-#define FIRST_USER_ADDRESS 0UL
-
 /*  HUGETLB not working currently  */
 #ifdef CONFIG_HUGETLB_PAGE
 #define pte_mkhuge(pte) __pte((pte_val(pte) & ~0x3) | HVM_HUGEPAGE_SIZE)
arch/ia64/include/asm/pgtable.h renamed from arch/ia64/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -1
@@ -128,7 +128,6 @@
 #define PTRS_PER_PGD_SHIFT	PTRS_PER_PTD_SHIFT
 #define PTRS_PER_PGD		(1UL << PTRS_PER_PGD_SHIFT)
 #define USER_PTRS_PER_PGD	(5*PTRS_PER_PGD/8)	/* regions 0-4 are user regions */
-#define FIRST_USER_ADDRESS	0UL
 
 /*
  * All the normal masks have the "page accessed" bits on, as any time
arch/m68k/include/asm/pgtable_mm.h renamed from arch/m68k/include/asm/pgtable_mm.h~mm-define-default-value-for-first_user_address +0 -1
@@ -72,7 +72,6 @@
 #define PTRS_PER_PGD	128
 #endif
 #define USER_PTRS_PER_PGD	(TASK_SIZE/PGDIR_SIZE)
-#define FIRST_USER_ADDRESS	0UL
 
 /* Virtual address region for use by kernel_map() */
 #ifdef CONFIG_SUN3
arch/microblaze/include/asm/pgtable.h renamed from arch/microblaze/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -25,8 +25,6 @@ extern int mem_init_done;
 #include <asm/mmu.h>
 #include <asm/page.h>
 
-#define FIRST_USER_ADDRESS	0UL
-
 extern unsigned long va_to_phys(unsigned long address);
 extern pte_t *va_to_pte(unsigned long address);
 
arch/mips/include/asm/pgtable-32.h renamed from arch/mips/include/asm/pgtable-32.h~mm-define-default-value-for-first_user_address +0 -1
@@ -93,7 +93,6 @@ extern int add_temporary_entry(unsigned
 #endif
 
 #define USER_PTRS_PER_PGD	(0x80000000UL/PGDIR_SIZE)
-#define FIRST_USER_ADDRESS	0UL
 
 #define VMALLOC_START	  MAP_BASE
 
arch/mips/include/asm/pgtable-64.h renamed from arch/mips/include/asm/pgtable-64.h~mm-define-default-value-for-first_user_address +0 -1
@@ -137,7 +137,6 @@
 #define PTRS_PER_PTE	((PAGE_SIZE << PTE_ORDER) / sizeof(pte_t))
 
 #define USER_PTRS_PER_PGD       ((TASK_SIZE64 / PGDIR_SIZE)?(TASK_SIZE64 / PGDIR_SIZE):1)
-#define FIRST_USER_ADDRESS	0UL
 
 /*
  * TLB refill handlers also map the vmalloc area into xuseg.  Avoid
arch/nios2/include/asm/pgtable.h renamed from arch/nios2/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -24,8 +24,6 @@
 #include <asm/pgtable-bits.h>
 #include <asm-generic/pgtable-nopmd.h>
 
-#define FIRST_USER_ADDRESS	0UL
-
 #define VMALLOC_START		CONFIG_NIOS2_KERNEL_MMU_REGION_BASE
 #define VMALLOC_END		(CONFIG_NIOS2_KERNEL_REGION_BASE - 1)
 
arch/openrisc/include/asm/pgtable.h renamed from arch/openrisc/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -1
@@ -73,7 +73,6 @@ extern void paging_init(void);
  */
 
 #define USER_PTRS_PER_PGD       (TASK_SIZE/PGDIR_SIZE)
-#define FIRST_USER_ADDRESS      0UL
 
 /*
  * Kernels own virtual memory area.
arch/parisc/include/asm/pgtable.h renamed from arch/parisc/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -171,8 +171,6 @@ static inline void purge_tlb_entries(str
  * pgd entries used up by user/kernel:
  */
 
-#define FIRST_USER_ADDRESS	0UL
-
 /* NB: The tlb miss handlers make certain assumptions about the order */
 /*     of the following bits, so be careful (One example, bits 25-31  */
 /*     are moved together in one instruction).                        */
arch/powerpc/include/asm/book3s/pgtable.h renamed from arch/powerpc/include/asm/book3s/pgtable.h~mm-define-default-value-for-first_user_address +0 -1
@@ -8,7 +8,6 @@
 #include <asm/book3s/32/pgtable.h>
 #endif
 
-#define FIRST_USER_ADDRESS	0UL
 #ifndef __ASSEMBLY__
 /* Insert a PTE, top-level function is out of line. It uses an inline
  * low level function in the respective pgtable-* files
arch/powerpc/include/asm/nohash/32/pgtable.h renamed from arch/powerpc/include/asm/nohash/32/pgtable.h~mm-define-default-value-for-first_user_address +0 -1
@@ -54,7 +54,6 @@ extern int icache_44x_need_flush;
 #define PGD_MASKED_BITS		0
 
 #define USER_PTRS_PER_PGD	(TASK_SIZE / PGDIR_SIZE)
-#define FIRST_USER_ADDRESS	0UL
 
 #define pte_ERROR(e) \
 	pr_err("%s:%d: bad pte %llx.\n", __FILE__, __LINE__, \
arch/powerpc/include/asm/nohash/64/pgtable.h renamed from arch/powerpc/include/asm/nohash/64/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -12,8 +12,6 @@
 #include <asm/barrier.h>
 #include <asm/asm-const.h>
 
-#define FIRST_USER_ADDRESS	0UL
-
 /*
  * Size of EA range mapped by our pagetables.
  */
arch/riscv/include/asm/pgtable.h renamed from arch/riscv/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -536,8 +536,6 @@ void setup_bootmem(void);
 void paging_init(void);
 void misc_mem_init(void);
 
-#define FIRST_USER_ADDRESS  0
-
 /*
  * ZERO_PAGE is a global shared page that is always zero,
  * used for zero-mapped memory areas, etc.
arch/s390/include/asm/pgtable.h renamed from arch/s390/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -65,8 +65,6 @@ extern unsigned long zero_page_mask;
 
 /* TODO: s390 cannot support io_remap_pfn_range... */
 
-#define FIRST_USER_ADDRESS  0UL
-
 #define pte_ERROR(e) \
 	printk("%s:%d: bad pte %p.\n", __FILE__, __LINE__, (void *) pte_val(e))
 #define pmd_ERROR(e) \
arch/sh/include/asm/pgtable.h renamed from arch/sh/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -2
@@ -59,8 +59,6 @@ static inline unsigned long long neff_si
 /* Entries per level */
 #define PTRS_PER_PTE	(PAGE_SIZE / (1 << PTE_MAGNITUDE))
 
-#define FIRST_USER_ADDRESS	0UL
-
 #define PHYS_ADDR_MASK29		0x1fffffff
 #define PHYS_ADDR_MASK32		0xffffffff
 
arch/sparc/include/asm/pgtable_32.h renamed from arch/sparc/include/asm/pgtable_32.h~mm-define-default-value-for-first_user_address +0 -1
@@ -48,7 +48,6 @@ unsigned long __init bootmem_init(unsign
 #define PTRS_PER_PMD    	64
 #define PTRS_PER_PGD    	256
 #define USER_PTRS_PER_PGD	PAGE_OFFSET / PGDIR_SIZE
-#define FIRST_USER_ADDRESS	0UL
 #define PTE_SIZE		(PTRS_PER_PTE*4)
 
 #define PAGE_NONE	SRMMU_PAGE_NONE
arch/sparc/include/asm/pgtable_64.h renamed from arch/sparc/include/asm/pgtable_64.h~mm-define-default-value-for-first_user_address +0 -3
@@ -95,9 +95,6 @@ bool kern_addr_valid(unsigned long addr)
 #define PTRS_PER_PUD	(1UL << PUD_BITS)
 #define PTRS_PER_PGD	(1UL << PGDIR_BITS)
 
-/* Kernel has a separate 44bit address space. */
-#define FIRST_USER_ADDRESS	0UL
-
 #define pmd_ERROR(e)							\
 	pr_err("%s:%d: bad pmd %p(%016lx) seen at (%pS)\n",		\
 	       __FILE__, __LINE__, &(e), pmd_val(e), __builtin_return_address(0))
arch/um/include/asm/pgtable-2level.h renamed from arch/um/include/asm/pgtable-2level.h~mm-define-default-value-for-first_user_address +0 -1
@@ -23,7 +23,6 @@
 #define PTRS_PER_PTE	1024
 #define USER_PTRS_PER_PGD ((TASK_SIZE + (PGDIR_SIZE - 1)) / PGDIR_SIZE)
 #define PTRS_PER_PGD	1024
-#define FIRST_USER_ADDRESS	0UL
 
 #define pte_ERROR(e) \
         printk("%s:%d: bad pte %p(%08lx).\n", __FILE__, __LINE__, &(e), \
arch/um/include/asm/pgtable-3level.h renamed from arch/um/include/asm/pgtable-3level.h~mm-define-default-value-for-first_user_address +0 -1
@@ -41,7 +41,6 @@
 #endif
 
 #define USER_PTRS_PER_PGD ((TASK_SIZE + (PGDIR_SIZE - 1)) / PGDIR_SIZE)
-#define FIRST_USER_ADDRESS	0UL
 
 #define pte_ERROR(e) \
         printk("%s:%d: bad pte %p(%016lx).\n", __FILE__, __LINE__, &(e), \
arch/x86/include/asm/pgtable_types.h renamed from arch/x86/include/asm/pgtable_types.h~mm-define-default-value-for-first_user_address +0 -2
@@ -7,8 +7,6 @@
 
 #include <asm/page_types.h>
 
-#define FIRST_USER_ADDRESS	0UL
-
 #define _PAGE_BIT_PRESENT	0	/* is present */
 #define _PAGE_BIT_RW		1	/* writeable */
 #define _PAGE_BIT_USER		2	/* userspace addressable */
arch/xtensa/include/asm/pgtable.h renamed from arch/xtensa/include/asm/pgtable.h~mm-define-default-value-for-first_user_address +0 -1
@@ -59,7 +59,6 @@
 #define PTRS_PER_PGD		1024
 #define PGD_ORDER		0
 #define USER_PTRS_PER_PGD	(TASK_SIZE/PGDIR_SIZE)
-#define FIRST_USER_ADDRESS	0UL
 #define FIRST_USER_PGD_NR	(FIRST_USER_ADDRESS >> PGDIR_SHIFT)
 
 #ifdef CONFIG_MMU
include/linux/pgtable.h renamed from include/linux/pgtable.h~mm-define-default-value-for-first_user_address +9 -0
@@ -29,6 +29,15 @@
 #endif
 
 /*
+ * This defines the first usable user address. Platforms
+ * can override its value with custom FIRST_USER_ADDRESS
+ * defined in their respective <asm/pgtable.h>.
+ */
+#ifndef FIRST_USER_ADDRESS
+#define FIRST_USER_ADDRESS	0UL
+#endif
+
+/*
  * A page table page can be thought of an array like this: pXd_t[PTRS_PER_PxD]
  *
  * The pXx_index() functions return the index of the entry in the page

_

author maintainer
#128 lore raw

PATCH 114/192 mm: fix spelling mistakes

In reply to Andrew Morton

From: Zhen Lei <[email protected]>
Subject: mm: fix spelling mistakes

Fix some spelling mistakes in comments:
each having differents usage ==> each has a different usage statments ==> statements
adresses ==> addresses
aggresive ==> aggressive
datas ==> data
posion ==> poison
higer ==> higher
precisly ==> precisely
wont ==> won't
We moves tha ==> We move the
endianess ==> endianness

---

 include/linux/memremap.h |    2 +-
 include/linux/mm_types.h |    2 +-
 include/linux/mmzone.h   |    2 +-
 mm/memory-failure.c      |    2 +-
 mm/memory_hotplug.c      |    4 ++--
 mm/page_alloc.c          |    2 +-
 mm/swapfile.c            |    2 +-
 7 files changed, 8 insertions(+), 8 deletions(-)
include/linux/memremap.h renamed from include/linux/memremap.h~mm-clear-spelling-mistakes +1 -1
@@ -26,7 +26,7 @@ struct vmem_altmap {
 };
 
 /*
- * Specialize ZONE_DEVICE memory into multiple types each having differents
+ * Specialize ZONE_DEVICE memory into multiple types each has a different
  * usage.
  *
  * MEMORY_DEVICE_PRIVATE:
include/linux/mm_types.h renamed from include/linux/mm_types.h~mm-clear-spelling-mistakes +1 -1
@@ -397,7 +397,7 @@ struct mm_struct {
 		unsigned long mmap_base;	/* base of mmap area */
 		unsigned long mmap_legacy_base;	/* base of mmap area in bottom-up allocations */
 #ifdef CONFIG_HAVE_ARCH_COMPAT_MMAP_BASES
-		/* Base adresses for compatible mmap() */
+		/* Base addresses for compatible mmap() */
 		unsigned long mmap_compat_base;
 		unsigned long mmap_compat_legacy_base;
 #endif
include/linux/mmzone.h renamed from include/linux/mmzone.h~mm-clear-spelling-mistakes +1 -1
@@ -114,7 +114,7 @@ static inline bool free_area_empty(struc
 struct pglist_data;
 
 /*
- * Add a wild amount of padding here to ensure datas fall into separate
+ * Add a wild amount of padding here to ensure data fall into separate
  * cachelines.  There are very few zone structures in the machine, so space
  * consumption is not a concern here.
  */
mm/memory-failure.c renamed from mm/memory-failure.c~mm-clear-spelling-mistakes +1 -1
@@ -1340,7 +1340,7 @@ static bool hwpoison_user_mappings(struc
 			 * could potentially call huge_pmd_unshare.  Because of
 			 * this, take semaphore in write mode here and set
 			 * TTU_RMAP_LOCKED to indicate we have taken the lock
-			 * at this higer level.
+			 * at this higher level.
 			 */
 			mapping = hugetlb_page_mapping_lock_write(hpage);
 			if (mapping) {
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-clear-spelling-mistakes +2 -2
@@ -783,7 +783,7 @@ int __ref online_pages(unsigned long pfn
 
 	/*
 	 * {on,off}lining is constrained to full memory sections (or more
-	 * precisly to memory blocks from the user space POV).
+	 * precisely to memory blocks from the user space POV).
 	 * memmap_on_memory is an exception because it reserves initial part
 	 * of the physical memory space for vmemmaps. That space is pageblock
 	 * aligned.
@@ -1580,7 +1580,7 @@ int __ref offline_pages(unsigned long st
 
 	/*
 	 * {on,off}lining is constrained to full memory sections (or more
-	 * precisly to memory blocks from the user space POV).
+	 * precisely to memory blocks from the user space POV).
 	 * memmap_on_memory is an exception because it reserves initial part
 	 * of the physical memory space for vmemmaps. That space is pageblock
 	 * aligned.
mm/page_alloc.c renamed from mm/page_alloc.c~mm-clear-spelling-mistakes +1 -1
@@ -3180,7 +3180,7 @@ static void __drain_all_pages(struct zon
 	int cpu;
 
 	/*
-	 * Allocate in the BSS so we wont require allocation in
+	 * Allocate in the BSS so we won't require allocation in
 	 * direct reclaim path for CONFIG_CPUMASK_OFFSTACK=y
 	 */
 	static cpumask_t cpus_with_pcps;
mm/swapfile.c renamed from mm/swapfile.c~mm-clear-spelling-mistakes +1 -1
@@ -2967,7 +2967,7 @@ static unsigned long read_swap_header(st
 		return 0;
 	}
 
-	/* swap partition endianess hack... */
+	/* swap partition endianness hack... */
 	if (swab32(swap_header->info.version) == 1) {
 		swab32s(&swap_header->info.version);
 		swab32s(&swap_header->info.last_page);

_

author maintainer
#129 lore raw

PATCH 115/192 mm/vmscan: remove kerneldoc-like comment from isolate_lru_pages

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/vmscan: remove kerneldoc-like comment from isolate_lru_pages

Patch series "Clean W=1 build warnings for mm/".

This is a janitorial only. During development of a tool to catch build warnings early to avoid tripping the Intel lkp-robot, I noticed that mm/ is not clean for W=1. This is generally harmless but there is no harm in cleaning it up. It disrupts git blame a little but on relatively obvious lines that are unlikely to be git blame targets.

This patch (of 13):

make W=1 generates the following warning for vmscan.c

mm/vmscan.c:1814: warning: This comment starts with '/**', but isn't a kernel-doc comment. Refer Documentation/doc-guide/kernel-doc.rst

It is not a kerneldoc comment and isolate_lru_pages() is a static function. While the detailed comment is nice, it does not need to be exposed via kernel-doc.

---

 mm/vmscan.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/vmscan.c renamed from mm/vmscan.c~mm-vmscan-remove-kerneldoc-like-comment-from-isolate_lru_pages +1 -1
@@ -1821,7 +1821,7 @@ static __always_inline void update_lru_s
 
 }
 
-/**
+/*
  * Isolating page from the lruvec to fill in @dst list by nr_to_scan times.
  *
  * lruvec->lru_lock is heavily contended.  Some of the functions that

_

author maintainer
#130 lore raw

PATCH 116/192 mm/vmalloc: include header for prototype of set_iounmap_nonlazy

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/vmalloc: include header for prototype of set_iounmap_nonlazy

make W=1 generates the following warning for mm/vmalloc.c

mm/vmalloc.c:1599:6: warning: no previous prototype for `set_iounmap_nonlazy' [-Wmissing-prototypes]
void set_iounmap_nonlazy(void)

        ^~~~~~~~~~~~~~~~~~~

This is an arch-generic function only used by x86. On other arches, it's dead code. Include the header with the definition and make it x86-64 specific.

---

 mm/vmalloc.c |    3 +++
 1 file changed, 3 insertions(+)
mm/vmalloc.c renamed from mm/vmalloc.c~mm-vmalloc-include-header-for-prototype-of-set_iounmap_nonlazy +3 -0
@@ -25,6 +25,7 @@
 #include <linux/notifier.h>
 #include <linux/rbtree.h>
 #include <linux/xarray.h>
+#include <linux/io.h>
 #include <linux/rcupdate.h>
 #include <linux/pfn.h>
 #include <linux/kmemleak.h>
@@ -1607,6 +1608,7 @@ static DEFINE_MUTEX(vmap_purge_lock);
 /* for per-CPU blocks */
 static void purge_fragmented_blocks_allcpus(void);
 
+#ifdef CONFIG_X86_64
 /*
  * called before a call to iounmap() if the caller wants vm_area_struct's
  * immediately freed.
@@ -1615,6 +1617,7 @@ void set_iounmap_nonlazy(void)
 {
 	atomic_long_set(&vmap_lazy_nr, lazy_max_pages()+1);
 }
+#endif /* CONFIG_X86_64 */
 
 /*
  * Purges all lazily-freed vmap areas.

_

author maintainer
#131 lore raw

PATCH 117/192 mm/page_alloc: make should_fail_alloc_page() static

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/page_alloc: make should_fail_alloc_page() static

make W=1 generates the following warning for mm/page_alloc.c

mm/page_alloc.c:3651:15: warning: no previous prototype for `should_fail_alloc_page' [-Wmissing-prototypes]
noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)

                 ^~~~~~~~~~~~~~~~~~~~~~

This function is deliberately split out for BPF to allow errors to be injected. The function is not used anywhere else so it is local to the file. Make it static which should still allow error injection to be used similar to how block/blk-core.c:should_fail_bio() works.

---

 mm/page_alloc.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/page_alloc.c renamed from mm/page_alloc.c~mm-page_alloc-make-should_fail_alloc_page-a-static-function-should_fail_alloc_page-static +1 -1
@@ -3819,7 +3819,7 @@ static inline bool __should_fail_alloc_p
 
 #endif /* CONFIG_FAIL_PAGE_ALLOC */
 
-noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
+static noinline bool should_fail_alloc_page(gfp_t gfp_mask, unsigned int order)
 {
 	return __should_fail_alloc_page(gfp_mask, order);
 }

_

author maintainer
#132 lore raw

PATCH 118/192 mm/mapping_dirty_helpers: remove double Note in kerneldoc

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/mapping_dirty_helpers: remove double Note in kerneldoc

make W=1 generates the following warning for mm/mapping_dirty_helpers.c

mm/mapping_dirty_helpers.c:325: warning: duplicate section name 'Note'

The helper function is very specific to one driver -- vmwgfx. While the two notes are separate, all of it needs to be taken into account when using the helper so make it one note.

---

 mm/mapping_dirty_helpers.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/mapping_dirty_helpers.c renamed from mm/mapping_dirty_helpers.c~mm-mapping_dirty_helpers-remove-double-note-in-kerneldoc +1 -1
@@ -317,7 +317,7 @@ EXPORT_SYMBOL_GPL(wp_shared_mapping_rang
  * pfn_mkwrite(). And then after a TLB flush following the write-protection
  * pick up all dirty bits.
  *
- * Note: This function currently skips transhuge page-table entries, since
+ * This function currently skips transhuge page-table entries, since
  * it's intended for dirty-tracking on the PTE level. It will warn on
  * encountering transhuge dirty entries, though, and can easily be extended
  * to handle them as well.

_

author maintainer
#133 lore raw

PATCH 119/192 mm/memcontrol.c: fix kerneldoc comment for mem_cgroup_calculate_protection

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/memcontrol.c: fix kerneldoc comment for mem_cgroup_calculate_protection

make W=1 generates the following warning for mem_cgroup_calculate_protection

mm/memcontrol.c:6468: warning: expecting prototype for mem_cgroup_protected(). Prototype was for mem_cgroup_calculate_protection() instead

Commit 45c7f7e1ef17 ("mm, memcg: decouple e{low,min} state mutations from protection checks") changed the function definition but not the associated kerneldoc comment.

Fixes 45c7f7e1ef17 ("mm, memcg: decouple e{low,min} state mutations from protection checks")
Cc Dan Streetman <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Michal Hocko <[email protected]>

---

 mm/memcontrol.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/memcontrol.c renamed from mm/memcontrol.c~mm-memcontrolc-fix-kerneldoc-comment-for-mem_cgroup_calculate_protection +1 -1
@@ -6639,7 +6639,7 @@ static unsigned long effective_protectio
 }
 
 /**
- * mem_cgroup_protected - check if memory consumption is in the normal range
+ * mem_cgroup_calculate_protection - check if memory consumption is in the normal range
  * @root: the top ancestor of the sub-tree being checked
  * @memcg: the memory cgroup to check
  *

_

author maintainer
#134 lore raw

PATCH 120/192 mm/memory_hotplug: fix kerneldoc comment for __try_online_node

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/memory_hotplug: fix kerneldoc comment for __try_online_node

make W=1 generates the following warning for try_online_node

mm/memory_hotplug.c:1087: warning: expecting prototype for try_online_node(). Prototype was for __try_online_node() instead

Commit b9ff036082cd ("mm/memory_hotplug.c: make add_memory_resource use __try_online_node") renamed the function but did not update the associated kerneldoc. The function is static and somewhat specialised in nature so it's not clear it warrants being a kerneldoc by moving the comment to try_online_node. Hence, leave the comment of the internal helper in place but leave it out of kerneldoc and correct the function name in the comment.

Fixes Commit b9ff036082cd ("mm/memory_hotplug.c: make add_memory_resource use __try_online_node")
Cc Dan Streetman <[email protected]>
Cc Michal Hocko <[email protected]>

---

 mm/memory_hotplug.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-fix-kerneldoc-comment-for-__try_online_node +2 -2
@@ -942,8 +942,8 @@ static void rollback_node_hotadd(int nid
 }
 
 
-/**
- * try_online_node - online a node if offlined
+/*
+ * __try_online_node - online a node if offlined
  * @nid: the node ID
  * @set_node_online: Whether we want to online the node
  * called by cpu_up() to online a node without onlined memory.

_

author maintainer
#135 lore raw

PATCH 121/192 mm/memory_hotplug: fix kerneldoc comment for __remove_memory

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/memory_hotplug: fix kerneldoc comment for __remove_memory

make W=1 generates the following warning for __remove_memory

mm/memory_hotplug.c:2044: warning: expecting prototype for remove_memory(). Prototype was for __remove_memory() instead

Commit eca499ab3749 ("mm/hotplug: make remove_memory() interface usable") introduced the kerneldoc comment and function but the kerneldoc name and function name did not match.

Fixes eca499ab3749 ("mm/hotplug: make remove_memory() interface usable")
Cc Dan Streetman <[email protected]>
Cc Michal Hocko <[email protected]>

---

 mm/memory_hotplug.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/memory_hotplug.c renamed from mm/memory_hotplug.c~mm-memory_hotplug-fix-kerneldoc-comment-for-__remove_memory +1 -1
@@ -1908,7 +1908,7 @@ static int __ref try_remove_memory(int n
 }
 
 /**
- * remove_memory
+ * __remove_memory - Remove memory if every memory block is offline
  * @nid: the node ID
  * @start: physical address of the region to remove
  * @size: size of the region to remove

_

author maintainer
#136 lore raw

PATCH 122/192 mm/zbud: add kerneldoc fields for zbud_pool

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/zbud: add kerneldoc fields for zbud_pool

make W=1 generates the following warning for zbud_pool

mm/zbud.c:105: warning: Function parameter or member 'zpool' not described in 'zbud_pool' mm/zbud.c:105: warning: Function parameter or member 'zpool_ops' not described in 'zbud_pool'

Commit 479305fd7172 ("zpool: remove zpool_evict()") removed the zpool_evict helper and added the associated zpool and operations structure in struct zbud_pool but did not add documentation for the fields. Add rudimentary documentation.

Fixes 479305fd7172 ("zpool: remove zpool_evict()")
Cc Dan Streetman <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Michal Hocko <[email protected]>

---

 mm/zbud.c |    2 ++
 1 file changed, 2 insertions(+)
mm/zbud.c renamed from mm/zbud.c~mm-zbud-add-kerneldoc-fields-for-zbud_pool +2 -0
@@ -92,6 +92,8 @@ struct zbud_ops {
  * @pages_nr:	number of zbud pages in the pool.
  * @ops:	pointer to a structure of user defined operations specified at
  *		pool creation time.
+ * @zpool:	zpool driver
+ * @zpool_ops:	zpool operations structure with an evict callback
  *
  * This structure is allocated at pool creation time and maintains metadata
  * pertaining to a particular zbud pool.

_

author maintainer
#137 lore raw

PATCH 123/192 mm/z3fold: add kerneldoc fields for z3fold_pool

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/z3fold: add kerneldoc fields for z3fold_pool

make W=1 generates the following warning for z3fold_pool

mm/z3fold.c:171: warning: Function parameter or member 'zpool' not described in 'z3fold_pool' mm/z3fold.c:171: warning: Function parameter or member 'zpool_ops' not described in 'z3fold_pool'

Commit 9a001fc19ccc ("z3fold: the 3-fold allocator for compressed pages") simply did not document the fields at the time. Add rudimentary documentation.

---

 mm/z3fold.c |    2 ++
 1 file changed, 2 insertions(+)
mm/z3fold.c renamed from mm/z3fold.c~mm-z3fold-add-kerneldoc-fields-for-z3fold_pool +2 -0
@@ -144,6 +144,8 @@ struct z3fold_header {
  * @c_handle:	cache for z3fold_buddy_slots allocation
  * @ops:	pointer to a structure of user defined operations specified at
  *		pool creation time.
+ * @zpool:	zpool driver
+ * @zpool_ops:	zpool operations structure with an evict callback
  * @compact_wq:	workqueue for page layout background optimization
  * @release_wq:	workqueue for safe page release
  * @work:	work_struct for safe page release

_

author maintainer
#138 lore raw

PATCH 124/192 mm/swap: make swap_address_space an inline function

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/swap: make swap_address_space an inline function

make W=1 generates the following warning in page_mapping() for allnoconfig

mm/util.c:700:15: warning: variable `entry' set but not used [-Wunused-but-set-variable]

     swp_entry_t entry;
                 ^~~~~

swap_address is a #define on !CONFIG_SWAP configurations. Make the helper an inline function to suppress the warning, add type checking and to apply any side-effects in the parameter list.

---

 include/linux/swap.h |    6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
include/linux/swap.h renamed from include/linux/swap.h~mm-swap-make-swap_address_space-an-inline-function +5 -1
@@ -537,7 +537,11 @@ static inline void put_swap_device(struc
 {
 }
 
-#define swap_address_space(entry)		(NULL)
+static inline struct address_space *swap_address_space(swp_entry_t entry)
+{
+	return NULL;
+}
+
 #define get_nr_swap_pages()			0L
 #define total_swap_pages			0L
 #define total_swapcache_pages()			0UL

_

author maintainer
#139 lore raw

PATCH 125/192 mm/mmap_lock: remove dead code for !CONFIG_TRACING configurations

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/mmap_lock: remove dead code for !CONFIG_TRACING configurations

make W=1 generates the following warning in mmap_lock.c for allnoconfig

mm/mmap_lock.c:213:6: warning: no previous prototype for `__mmap_lock_do_trace_start_locking' [-Wmissing-prototypes]
void __mmap_lock_do_trace_start_locking(struct mm_struct *mm, bool write)

        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  mm/mmap_lock.c:219:6: warning: no previous prototype for `__mmap_lock_do_trace_acquire_returned' [-Wmissing-prototypes]
   void __mmap_lock_do_trace_acquire_returned(struct mm_struct *mm, bool write,
        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

mm/mmap_lock.c:226:6: warning: no previous prototype for `__mmap_lock_do_trace_released' [-Wmissing-prototypes]
void __mmap_lock_do_trace_released(struct mm_struct *mm, bool write)

On !CONFIG_TRACING configurations, the code is dead so put it behind an #ifdef.

---

 mm/mmap_lock.c |   59 +++++++++++++++++++++++++----------------------
 1 file changed, 32 insertions(+), 27 deletions(-)
mm/mmap_lock.c renamed from mm/mmap_lock.c~mm-mmap_lock-remove-dead-code-for-config_tracing-configurations +32 -27
@@ -153,6 +153,37 @@ static inline void put_memcg_path_buf(vo
 	rcu_read_unlock();
 }
 
+#define TRACE_MMAP_LOCK_EVENT(type, mm, ...)                                   \
+	do {                                                                   \
+		const char *memcg_path;                                        \
+		preempt_disable();                                             \
+		memcg_path = get_mm_memcg_path(mm);                            \
+		trace_mmap_lock_##type(mm,                                     \
+				       memcg_path != NULL ? memcg_path : "",   \
+				       ##__VA_ARGS__);                         \
+		if (likely(memcg_path != NULL))                                \
+			put_memcg_path_buf();                                  \
+		preempt_enable();                                              \
+	} while (0)
+
+#else /* !CONFIG_MEMCG */
+
+int trace_mmap_lock_reg(void)
+{
+	return 0;
+}
+
+void trace_mmap_lock_unreg(void)
+{
+}
+
+#define TRACE_MMAP_LOCK_EVENT(type, mm, ...)                                   \
+	trace_mmap_lock_##type(mm, "", ##__VA_ARGS__)
+
+#endif /* CONFIG_MEMCG */
+
+#ifdef CONFIG_TRACING
+#ifdef CONFIG_MEMCG
 /*
  * Write the given mm_struct's memcg path to a percpu buffer, and return a
  * pointer to it. If the path cannot be determined, or no buffer was available
@@ -187,33 +218,6 @@ out:
 	return buf;
 }
 
-#define TRACE_MMAP_LOCK_EVENT(type, mm, ...)                                   \
-	do {                                                                   \
-		const char *memcg_path;                                        \
-		local_lock(&memcg_paths.lock);				       \
-		memcg_path = get_mm_memcg_path(mm);                            \
-		trace_mmap_lock_##type(mm,                                     \
-				       memcg_path != NULL ? memcg_path : "",   \
-				       ##__VA_ARGS__);                         \
-		if (likely(memcg_path != NULL))                                \
-			put_memcg_path_buf();                                  \
-		local_unlock(&memcg_paths.lock);			       \
-	} while (0)
-
-#else /* !CONFIG_MEMCG */
-
-int trace_mmap_lock_reg(void)
-{
-	return 0;
-}
-
-void trace_mmap_lock_unreg(void)
-{
-}
-
-#define TRACE_MMAP_LOCK_EVENT(type, mm, ...)                                   \
-	trace_mmap_lock_##type(mm, "", ##__VA_ARGS__)
-
 #endif /* CONFIG_MEMCG */
 
 /*
@@ -239,3 +243,4 @@ void __mmap_lock_do_trace_released(struc
 	TRACE_MMAP_LOCK_EVENT(released, mm, write);
 }
 EXPORT_SYMBOL(__mmap_lock_do_trace_released);
+#endif /* CONFIG_TRACING */

_

author maintainer
#140 lore raw

PATCH 126/192 mm/page_alloc: move prototype for find_suitable_fallback

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/page_alloc: move prototype for find_suitable_fallback

make W=1 generates the following warning in mmap_lock.c for allnoconfig

mm/page_alloc.c:2670:5: warning: no previous prototype for `find_suitable_fallback' [-Wmissing-prototypes]
int find_suitable_fallback(struct free_area *area, unsigned int order,

       ^~~~~~~~~~~~~~~~~~~~~~

find_suitable_fallback is only shared outside of page_alloc.c for CONFIG_COMPACTION but to suppress the warning, move the protype outside of CONFIG_COMPACTION. It is not worth the effort at this time to find a clever way of allowing compaction.c to share the code or avoid the use entirely as the function is called on relatively slow paths.

---

 mm/internal.h |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
mm/internal.h renamed from mm/internal.h~mm-page_alloc-move-prototype-for-find_suitable_fallback +1 -2
@@ -274,11 +274,10 @@ isolate_freepages_range(struct compact_c
 int
 isolate_migratepages_range(struct compact_control *cc,
 			   unsigned long low_pfn, unsigned long end_pfn);
+#endif
 int find_suitable_fallback(struct free_area *area, unsigned int order,
 			int migratetype, bool only_stealable, bool *can_steal);
 
-#endif
-
 /*
  * This function returns the order of a free page in the buddy system. In
  * general, page_zone(page)->lock must be held by the caller to prevent the

_

author maintainer
#141 lore raw

PATCH 127/192 mm/swap: make NODE_DATA an inline function on CONFIG_FLATMEM

In reply to Andrew Morton

From: Mel Gorman <[email protected]>
Subject: mm/swap: make NODE_DATA an inline function on CONFIG_FLATMEM

make W=1 generates the following warning in mm/workingset.c for allnoconfig

mm/workingset.c: In function `unpack_shadow':
mm/workingset.c:201:15: warning: variable `nid' set but not used [-Wunused-but-set-variable]

    int memcgid, nid;
                 ^~~

On FLATMEM, NODE_DATA returns a global pglist_data without dereferencing nid. Make the helper an inline function to suppress the warning, add type checking and to apply any side-effects in the parameter list.

---

 include/linux/mmzone.h |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
include/linux/mmzone.h renamed from include/linux/mmzone.h~mm-swap-make-node_data-an-inline-function-on-config_flatmem +4 -1
@@ -1064,7 +1064,10 @@ extern char numa_zonelist_order[];
 #ifndef CONFIG_NUMA
 
 extern struct pglist_data contig_page_data;
-#define NODE_DATA(nid)		(&contig_page_data)
+static inline struct pglist_data *NODE_DATA(int nid)
+{
+	return &contig_page_data;
+}
 #define NODE_MEM_MAP(nid)	mem_map
 
 #else /* CONFIG_NUMA */

_

author maintainer
#142 lore raw

PATCH 128/192 mm/thp: define default pmd_pgtable()

In reply to Andrew Morton

From: Anshuman Khandual <[email protected]>
Subject: mm/thp: define default pmd_pgtable()

Currently most platforms define pmd_pgtable() as pmd_page() duplicating the same code all over. Instead just define a default value i.e pmd_page() for pmd_pgtable() and let platforms override when required via <asm/pgtable.h>. All the existing platform that override pmd_pgtable() have been moved into their respective <asm/pgtable.h> header in order to precede before the new generic definition. This makes it much cleaner with reduced code.

Cc Nick Hu <[email protected]>
Cc Richard Henderson <[email protected]>
Cc Vineet Gupta <[email protected]>
Cc Catalin Marinas <[email protected]>
Cc Will Deacon <[email protected]>
Cc Guo Ren <[email protected]>
Cc Brian Cain <[email protected]>
Cc Geert Uytterhoeven <[email protected]>
Cc Michal Simek <[email protected]>
Cc Thomas Bogendoerfer <[email protected]>
Cc Ley Foon Tan <[email protected]>
Cc Jonas Bonn <[email protected]>
Cc Stefan Kristiansson <[email protected]>
Cc Stafford Horne <[email protected]>
Cc "James E.J. Bottomley" <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Christophe Leroy <[email protected]>
Cc Paul Walmsley <[email protected]>
Cc Palmer Dabbelt <[email protected]>
Cc Heiko Carstens <[email protected]>
Cc Yoshinori Sato <[email protected]>
Cc "David S. Miller" <[email protected]>
Cc Jeff Dike <[email protected]>
Cc Thomas Gleixner <[email protected]>
Cc Chris Zankel <[email protected]>

---

 arch/alpha/include/asm/pgalloc.h         |    1 -
 arch/arc/include/asm/pgalloc.h           |    2 --
 arch/arc/include/asm/pgtable.h           |    2 ++
 arch/arm/include/asm/pgalloc.h           |    1 -
 arch/arm64/include/asm/pgalloc.h         |    1 -
 arch/csky/include/asm/pgalloc.h          |    2 --
 arch/hexagon/include/asm/pgtable.h       |    1 -
 arch/ia64/include/asm/pgalloc.h          |    1 -
 arch/m68k/include/asm/mcf_pgalloc.h      |    2 --
 arch/m68k/include/asm/mcf_pgtable.h      |    2 ++
 arch/m68k/include/asm/motorola_pgalloc.h |    1 -
 arch/m68k/include/asm/motorola_pgtable.h |    2 ++
 arch/m68k/include/asm/sun3_pgalloc.h     |    1 -
 arch/microblaze/include/asm/pgalloc.h    |    2 --
 arch/mips/include/asm/pgalloc.h          |    1 -
 arch/nds32/include/asm/pgalloc.h         |    5 -----
 arch/nios2/include/asm/pgalloc.h         |    1 -
 arch/openrisc/include/asm/pgalloc.h      |    2 --
 arch/parisc/include/asm/pgalloc.h        |    1 -
 arch/powerpc/include/asm/pgalloc.h       |    5 -----
 arch/powerpc/include/asm/pgtable.h       |    6 ++++++
 arch/riscv/include/asm/pgalloc.h         |    2 --
 arch/s390/include/asm/pgalloc.h          |    3 ---
 arch/s390/include/asm/pgtable.h          |    3 +++
 arch/sh/include/asm/pgalloc.h            |    1 -
 arch/sparc/include/asm/pgalloc_32.h      |    1 -
 arch/sparc/include/asm/pgalloc_64.h      |    1 -
 arch/sparc/include/asm/pgtable_32.h      |    2 ++
 arch/sparc/include/asm/pgtable_64.h      |    2 ++
 arch/um/include/asm/pgalloc.h            |    1 -
 arch/x86/include/asm/pgalloc.h           |    2 --
 arch/xtensa/include/asm/pgalloc.h        |    2 --
 include/linux/pgtable.h                  |    9 +++++++++
 33 files changed, 28 insertions(+), 43 deletions(-)
arch/alpha/include/asm/pgalloc.h renamed from arch/alpha/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -18,7 +18,6 @@ pmd_populate(struct mm_struct *mm, pmd_t
 {
 	pmd_set(pmd, (pte_t *)(page_to_pa(pte) + PAGE_OFFSET));
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 static inline void
 pmd_populate_kernel(struct mm_struct *mm, pmd_t *pmd, pte_t *pte)
arch/arc/include/asm/pgalloc.h renamed from arch/arc/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -129,6 +129,4 @@ static inline void pte_free(struct mm_st
 
 #define __pte_free_tlb(tlb, pte, addr)  pte_free((tlb)->mm, pte)
 
-#define pmd_pgtable(pmd)	((pgtable_t) pmd_page_vaddr(pmd))
-
 #endif /* _ASM_ARC_PGALLOC_H */
arch/arc/include/asm/pgtable.h renamed from arch/arc/include/asm/pgtable.h~mm-thp-define-default-pmd_pgtable +2 -0
@@ -350,6 +350,8 @@ void update_mmu_cache(struct vm_area_str
 
 #define kern_addr_valid(addr)	(1)
 
+#define pmd_pgtable(pmd)       ((pgtable_t) pmd_page_vaddr(pmd))
+
 /*
  * remap a physical page `pfn' of size `size' with page protection `prot'
  * into virtual address `from'
arch/arm64/include/asm/pgalloc.h renamed from arch/arm64/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -86,6 +86,5 @@ pmd_populate(struct mm_struct *mm, pmd_t
 	VM_BUG_ON(mm == &init_mm);
 	__pmd_populate(pmdp, page_to_phys(ptep), PMD_TYPE_TABLE | PMD_TABLE_PXN);
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 #endif
arch/arm/include/asm/pgalloc.h renamed from arch/arm/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -143,7 +143,6 @@ pmd_populate(struct mm_struct *mm, pmd_t
 
 	__pmd_populate(pmdp, page_to_phys(ptep), prot);
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 #endif /* CONFIG_MMU */
 
arch/csky/include/asm/pgalloc.h renamed from arch/csky/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -22,8 +22,6 @@ static inline void pmd_populate(struct m
 	set_pmd(pmd, __pmd(__pa(page_address(pte))));
 }
 
-#define pmd_pgtable(pmd) pmd_page(pmd)
-
 extern void pgd_init(unsigned long *p);
 
 static inline pte_t *pte_alloc_one_kernel(struct mm_struct *mm)
arch/hexagon/include/asm/pgtable.h renamed from arch/hexagon/include/asm/pgtable.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -239,7 +239,6 @@ static inline int pmd_bad(pmd_t pmd)
  * pmd_page - converts a PMD entry to a page pointer
  */
 #define pmd_page(pmd)  (pfn_to_page(pmd_val(pmd) >> PAGE_SHIFT))
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 /**
  * pte_none - check if pte is mapped
arch/ia64/include/asm/pgalloc.h renamed from arch/ia64/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -52,7 +52,6 @@ pmd_populate(struct mm_struct *mm, pmd_t
 {
 	pmd_val(*pmd_entry) = page_to_phys(pte);
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 static inline void
 pmd_populate_kernel(struct mm_struct *mm, pmd_t * pmd_entry, pte_t * pte)
arch/m68k/include/asm/mcf_pgalloc.h renamed from arch/m68k/include/asm/mcf_pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -32,8 +32,6 @@ extern inline pmd_t *pmd_alloc_kernel(pg
 
 #define pmd_populate_kernel pmd_populate
 
-#define pmd_pgtable(pmd) pfn_to_virt(pmd_val(pmd) >> PAGE_SHIFT)
-
 static inline void __pte_free_tlb(struct mmu_gather *tlb, pgtable_t pgtable,
 				  unsigned long address)
 {
arch/m68k/include/asm/mcf_pgtable.h renamed from arch/m68k/include/asm/mcf_pgtable.h~mm-thp-define-default-pmd_pgtable +2 -0
@@ -150,6 +150,8 @@
 
 #ifndef __ASSEMBLY__
 
+#define pmd_pgtable(pmd) pfn_to_virt(pmd_val(pmd) >> PAGE_SHIFT)
+
 /*
  * Conversion functions: convert a page and protection to a page entry,
  * and a page entry and page directory to the page they refer to.
arch/m68k/include/asm/motorola_pgalloc.h renamed from arch/m68k/include/asm/motorola_pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -88,7 +88,6 @@ static inline void pmd_populate(struct m
 {
 	pmd_set(pmd, page);
 }
-#define pmd_pgtable(pmd) ((pgtable_t)pmd_page_vaddr(pmd))
 
 static inline void pud_populate(struct mm_struct *mm, pud_t *pud, pmd_t *pmd)
 {
arch/m68k/include/asm/motorola_pgtable.h renamed from arch/m68k/include/asm/motorola_pgtable.h~mm-thp-define-default-pmd_pgtable +2 -0
@@ -105,6 +105,8 @@ extern unsigned long mm_cachebits;
 #define __S110	PAGE_SHARED_C
 #define __S111	PAGE_SHARED_C
 
+#define pmd_pgtable(pmd) ((pgtable_t)pmd_page_vaddr(pmd))
+
 /*
  * Conversion functions: convert a page and protection to a page entry,
  * and a page entry and page directory to the page they refer to.
arch/m68k/include/asm/sun3_pgalloc.h renamed from arch/m68k/include/asm/sun3_pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -32,7 +32,6 @@ static inline void pmd_populate(struct m
 {
 	pmd_val(*pmd) = __pa((unsigned long)page_address(page));
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 /*
  * allocating and freeing a pmd is trivial: the 1-entry pmd is
arch/microblaze/include/asm/pgalloc.h renamed from arch/microblaze/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -28,8 +28,6 @@ static inline pgd_t *get_pgd(void)
 
 #define pgd_alloc(mm)		get_pgd()
 
-#define pmd_pgtable(pmd)	pmd_page(pmd)
-
 extern pte_t *pte_alloc_one_kernel(struct mm_struct *mm);
 
 #define __pte_free_tlb(tlb, pte, addr)	pte_free((tlb)->mm, (pte))
arch/mips/include/asm/pgalloc.h renamed from arch/mips/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -28,7 +28,6 @@ static inline void pmd_populate(struct m
 {
 	set_pmd(pmd, __pmd((unsigned long)page_address(pte)));
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 /*
  * Initialize a new pmd table with invalid pointers.
arch/nds32/include/asm/pgalloc.h renamed from arch/nds32/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -5
@@ -12,11 +12,6 @@
 #define __HAVE_ARCH_PTE_ALLOC_ONE
 #include <asm-generic/pgalloc.h>	/* for pte_{alloc,free}_one */
 
-/*
- * Since we have only two-level page tables, these are trivial
- */
-#define pmd_pgtable(pmd) pmd_page(pmd)
-
 extern pgd_t *pgd_alloc(struct mm_struct *mm);
 extern void pgd_free(struct mm_struct *mm, pgd_t * pgd);
 
arch/nios2/include/asm/pgalloc.h renamed from arch/nios2/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -25,7 +25,6 @@ static inline void pmd_populate(struct m
 {
 	set_pmd(pmd, __pmd((unsigned long)page_address(pte)));
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 /*
  * Initialize a new pmd table with invalid pointers.
arch/openrisc/include/asm/pgalloc.h renamed from arch/openrisc/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -72,6 +72,4 @@ do {					\
 	tlb_remove_page((tlb), (pte));	\
 } while (0)
 
-#define pmd_pgtable(pmd) pmd_page(pmd)
-
 #endif
arch/parisc/include/asm/pgalloc.h renamed from arch/parisc/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -69,6 +69,5 @@ pmd_populate_kernel(struct mm_struct *mm
 
 #define pmd_populate(mm, pmd, pte_page) \
 	pmd_populate_kernel(mm, pmd, page_address(pte_page))
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 #endif
arch/powerpc/include/asm/pgalloc.h renamed from arch/powerpc/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -5
@@ -70,9 +70,4 @@ extern struct kmem_cache *pgtable_cache[
 #include <asm/nohash/pgalloc.h>
 #endif
 
-static inline pgtable_t pmd_pgtable(pmd_t pmd)
-{
-	return (pgtable_t)pmd_page_vaddr(pmd);
-}
-
 #endif /* _ASM_POWERPC_PGALLOC_H */
arch/powerpc/include/asm/pgtable.h renamed from arch/powerpc/include/asm/pgtable.h~mm-thp-define-default-pmd_pgtable +6 -0
@@ -152,6 +152,12 @@ static inline bool p4d_is_leaf(p4d_t p4d
 }
 #endif
 
+#define pmd_pgtable pmd_pgtable
+static inline pgtable_t pmd_pgtable(pmd_t pmd)
+{
+	return (pgtable_t)pmd_page_vaddr(pmd);
+}
+
 #ifdef CONFIG_PPC64
 #define is_ioremap_addr is_ioremap_addr
 static inline bool is_ioremap_addr(const void *x)
arch/riscv/include/asm/pgalloc.h renamed from arch/riscv/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -38,8 +38,6 @@ static inline void pud_populate(struct m
 }
 #endif /* __PAGETABLE_PMD_FOLDED */
 
-#define pmd_pgtable(pmd)	pmd_page(pmd)
-
 static inline pgd_t *pgd_alloc(struct mm_struct *mm)
 {
 	pgd_t *pgd;
arch/s390/include/asm/pgalloc.h renamed from arch/s390/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -3
@@ -134,9 +134,6 @@ static inline void pmd_populate(struct m
 
 #define pmd_populate_kernel(mm, pmd, pte) pmd_populate(mm, pmd, pte)
 
-#define pmd_pgtable(pmd) \
-	((pgtable_t)__va(pmd_val(pmd) & -sizeof(pte_t)*PTRS_PER_PTE))
-
 /*
  * page table entry allocation/free routines.
  */
arch/s390/include/asm/pgtable.h renamed from arch/s390/include/asm/pgtable.h~mm-thp-define-default-pmd_pgtable +3 -0
@@ -1709,4 +1709,7 @@ extern void s390_reset_cmma(struct mm_st
 #define HAVE_ARCH_UNMAPPED_AREA
 #define HAVE_ARCH_UNMAPPED_AREA_TOPDOWN
 
+#define pmd_pgtable(pmd) \
+	((pgtable_t)__va(pmd_val(pmd) & -sizeof(pte_t)*PTRS_PER_PTE))
+
 #endif /* _S390_PAGE_H */
arch/sh/include/asm/pgalloc.h renamed from arch/sh/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -30,7 +30,6 @@ static inline void pmd_populate(struct m
 {
 	set_pmd(pmd, __pmd((unsigned long)page_address(pte)));
 }
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 #define __pte_free_tlb(tlb,pte,addr)			\
 do {							\
arch/sparc/include/asm/pgalloc_32.h renamed from arch/sparc/include/asm/pgalloc_32.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -51,7 +51,6 @@ static inline void free_pmd_fast(pmd_t *
 #define __pmd_free_tlb(tlb, pmd, addr)	pmd_free((tlb)->mm, pmd)
 
 #define pmd_populate(mm, pmd, pte)	pmd_set(pmd, pte)
-#define pmd_pgtable(pmd)		(pgtable_t)__pmd_page(pmd)
 
 void pmd_set(pmd_t *pmdp, pte_t *ptep);
 #define pmd_populate_kernel		pmd_populate
arch/sparc/include/asm/pgalloc_64.h renamed from arch/sparc/include/asm/pgalloc_64.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -67,7 +67,6 @@ void pte_free(struct mm_struct *mm, pgta
 
 #define pmd_populate_kernel(MM, PMD, PTE)	pmd_set(MM, PMD, PTE)
 #define pmd_populate(MM, PMD, PTE)		pmd_set(MM, PMD, PTE)
-#define pmd_pgtable(PMD)			((pte_t *)pmd_page_vaddr(PMD))
 
 void pgtable_free(void *table, bool is_page);
 
arch/sparc/include/asm/pgtable_32.h renamed from arch/sparc/include/asm/pgtable_32.h~mm-thp-define-default-pmd_pgtable +2 -0
@@ -432,4 +432,6 @@ static inline int io_remap_pfn_range(str
 /* We provide our own get_unmapped_area to cope with VA holes for userland */
 #define HAVE_ARCH_UNMAPPED_AREA
 
+#define pmd_pgtable(pmd)	((pgtable_t)__pmd_page(pmd))
+
 #endif /* !(_SPARC_PGTABLE_H) */
arch/sparc/include/asm/pgtable_64.h renamed from arch/sparc/include/asm/pgtable_64.h~mm-thp-define-default-pmd_pgtable +2 -0
@@ -1117,6 +1117,8 @@ extern unsigned long cmdline_memory_size
 
 asmlinkage void do_sparc64_fault(struct pt_regs *regs);
 
+#define pmd_pgtable(PMD)	((pte_t *)pmd_page_vaddr(PMD))
+
 #ifdef CONFIG_HUGETLB_PAGE
 
 #define pud_leaf_size pud_leaf_size
arch/um/include/asm/pgalloc.h renamed from arch/um/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -1
@@ -19,7 +19,6 @@
 	set_pmd(pmd, __pmd(_PAGE_TABLE +			\
 		((unsigned long long)page_to_pfn(pte) <<	\
 			(unsigned long long) PAGE_SHIFT)))
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 /*
  * Allocate and free page tables.
arch/x86/include/asm/pgalloc.h renamed from arch/x86/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -84,8 +84,6 @@ static inline void pmd_populate(struct m
 	set_pmd(pmd, __pmd(((pteval_t)pfn << PAGE_SHIFT) | _PAGE_TABLE));
 }
 
-#define pmd_pgtable(pmd) pmd_page(pmd)
-
 #if CONFIG_PGTABLE_LEVELS > 2
 extern void ___pmd_free_tlb(struct mmu_gather *tlb, pmd_t *pmd);
 
arch/xtensa/include/asm/pgalloc.h renamed from arch/xtensa/include/asm/pgalloc.h~mm-thp-define-default-pmd_pgtable +0 -2
@@ -25,7 +25,6 @@
 	(pmd_val(*(pmdp)) = ((unsigned long)ptep))
 #define pmd_populate(mm, pmdp, page)					     \
 	(pmd_val(*(pmdp)) = ((unsigned long)page_to_virt(page)))
-#define pmd_pgtable(pmd) pmd_page(pmd)
 
 static inline pgd_t*
 pgd_alloc(struct mm_struct *mm)
@@ -63,7 +62,6 @@ static inline pgtable_t pte_alloc_one(st
 	return page;
 }
 
-#define pmd_pgtable(pmd) pmd_page(pmd)
 #endif /* CONFIG_MMU */
 
 #endif /* _XTENSA_PGALLOC_H */
include/linux/pgtable.h renamed from include/linux/pgtable.h~mm-thp-define-default-pmd_pgtable +9 -0
@@ -38,6 +38,15 @@
 #endif
 
 /*
+ * This defines the generic helper for accessing PMD page
+ * table page. Although platforms can still override this
+ * via their respective <asm/pgtable.h>.
+ */
+#ifndef pmd_pgtable
+#define pmd_pgtable(pmd) pmd_page(pmd)
+#endif
+
+/*
  * A page table page can be thought of an array like this: pXd_t[PTRS_PER_PxD]
  *
  * The pXx_index() functions return the index of the entry in the page

_

author maintainer
#143 lore raw

PATCH 129/192 kfence: unconditionally use unbound work queue

In reply to Andrew Morton

From: Marco Elver <[email protected]>
Subject: kfence: unconditionally use unbound work queue

Unconditionally use unbound work queue, and not just if wq_power_efficient is true. Because if the system is idle, KFENCE may wait, and by being run on the unbound work queue, we permit the scheduler to make better scheduling decisions and not require pinning KFENCE to the same CPU upon waking up.

Fixes 36f0b35d0894 ("kfence: use power-efficient work queue to run delayed work")
Cc Dmitry Vyukov <[email protected]>

---

 mm/kfence/core.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/kfence/core.c renamed from mm/kfence/core.c~kfence-unconditionally-use-unbound-work-queue +2 -2
@@ -636,7 +636,7 @@ static void toggle_allocation_gate(struc
 	/* Disable static key and reset timer. */
 	static_branch_disable(&kfence_allocation_key);
 #endif
-	queue_delayed_work(system_power_efficient_wq, &kfence_timer,
+	queue_delayed_work(system_unbound_wq, &kfence_timer,
 			   msecs_to_jiffies(kfence_sample_interval));
 }
 static DECLARE_DELAYED_WORK(kfence_timer, toggle_allocation_gate);
@@ -666,7 +666,7 @@ void __init kfence_init(void)
 	}
 
 	WRITE_ONCE(kfence_enabled, true);
-	queue_delayed_work(system_power_efficient_wq, &kfence_timer, 0);
+	queue_delayed_work(system_unbound_wq, &kfence_timer, 0);
 	pr_info("initialized - using %lu bytes for %d objects at 0x%p-0x%p\n", KFENCE_POOL_SIZE,
 		CONFIG_KFENCE_NUM_OBJECTS, (void *)__kfence_pool,
 		(void *)(__kfence_pool + KFENCE_POOL_SIZE));

_

author maintainer
#144 lore raw

PATCH 130/192 mm: remove special swap entry functions

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm: remove special swap entry functions

Patch series "Add support for SVM atomics in Nouveau", v11.

Introduction
============

Some devices have features such as atomic PTE bits that can be used to implement atomic access to system memory. To support atomic operations to a shared virtual memory page such a device needs access to that page which is exclusive of the CPU. This series introduces a mechanism to temporarily unmap pages granting exclusive access to a device.

These changes are required to support OpenCL atomic operations in Nouveau to shared virtual memory (SVM) regions allocated with the CL_MEM_SVM_ATOMICS clSVMAlloc flag. A more complete description of the OpenCL SVM feature is available at
https://www.khronos.org/registry/OpenCL/specs/3.0-unified/html/
OpenCL_API.html#_shared_virtual_memory .

Implementation
==============

Exclusive device access is implemented by adding a new swap entry type (SWAP_DEVICE_EXCLUSIVE) which is similar to a migration entry. The main difference is that on fault the original entry is immediately restored by the fault handler instead of waiting.

Restoring the entry triggers calls to MMU notifers which allows a device driver to revoke the atomic access permission from the GPU prior to the CPU finalising the entry.

Patches
=======

Patches 1 & 2 refactor existing migration and device private entry functions.

Patches 3 & 4 rework try_to_unmap_one() by splitting out unrelated functionality into separate functions - try_to_migrate_one() and try_to_munlock_one().

Patch 5 renames some existing code but does not introduce functionality.

Patch 6 is a small clean-up to swap entry handling in copy_pte_range().

Patch 7 contains the bulk of the implementation for device exclusive memory.

Patch 8 contains some additions to the HMM selftests to ensure everything works as expected.

Patch 9 is a cleanup for the Nouveau SVM implementation.

Patch 10 contains the implementation of atomic access for the Nouveau driver.

Testing
=======

This has been tested with upstream Mesa 21.1.0 and a simple OpenCL program which checks that GPU atomic accesses to system memory are atomic. Without this series the test fails as there is no way of write-protecting the page mapping which results in the device clobbering CPU writes. For reference the test is available at
https://ozlabs.org/~apopple/opencl_svm_atomics/

Further testing has been performed by adding support for testing exclusive access to the hmm-tests kselftests.

This patch (of 10):

Remove multiple similar inline functions for dealing with different types of special swap entries.

Both migration and device private swap entries use the swap offset to store a pfn. Instead of multiple inline functions to obtain a struct page for each swap entry type use a common function pfn_swap_entry_to_page(). Also open-code the various entry_to_pfn() functions as this results is shorter code that is easier to understand.

---

 arch/s390/mm/pgtable.c  |    2 -
 fs/proc/task_mmu.c      |   23 ++++--------
 include/linux/swap.h    |    4 +-
 include/linux/swapops.h |   69 ++++++++++++--------------------------
 mm/hmm.c                |    5 +-
 mm/huge_memory.c        |    6 +--
 mm/memcontrol.c         |    2 -
 mm/memory.c             |   10 ++---
 mm/migrate.c            |    6 +--
 mm/page_vma_mapped.c    |    6 +--
 10 files changed, 51 insertions(+), 82 deletions(-)
arch/s390/mm/pgtable.c renamed from arch/s390/mm/pgtable.c~mm-remove-special-swap-entry-functions +1 -1
@@ -691,7 +691,7 @@ static void ptep_zap_swap_entry(struct m
 	if (!non_swap_entry(entry))
 		dec_mm_counter(mm, MM_SWAPENTS);
 	else if (is_migration_entry(entry)) {
-		struct page *page = migration_entry_to_page(entry);
+		struct page *page = pfn_swap_entry_to_page(entry);
 
 		dec_mm_counter(mm, mm_counter(page));
 	}
fs/proc/task_mmu.c renamed from fs/proc/task_mmu.c~mm-remove-special-swap-entry-functions +8 -15
@@ -514,10 +514,8 @@ static void smaps_pte_entry(pte_t *pte,
 			} else {
 				mss->swap_pss += (u64)PAGE_SIZE << PSS_SHIFT;
 			}
-		} else if (is_migration_entry(swpent))
-			page = migration_entry_to_page(swpent);
-		else if (is_device_private_entry(swpent))
-			page = device_private_entry_to_page(swpent);
+		} else if (is_pfn_swap_entry(swpent))
+			page = pfn_swap_entry_to_page(swpent);
 	} else if (unlikely(IS_ENABLED(CONFIG_SHMEM) && mss->check_shmem_swap
 							&& pte_none(*pte))) {
 		page = xa_load(&vma->vm_file->f_mapping->i_pages,
@@ -549,7 +547,7 @@ static void smaps_pmd_entry(pmd_t *pmd,
 		swp_entry_t entry = pmd_to_swp_entry(*pmd);
 
 		if (is_migration_entry(entry))
-			page = migration_entry_to_page(entry);
+			page = pfn_swap_entry_to_page(entry);
 	}
 	if (IS_ERR_OR_NULL(page))
 		return;
@@ -694,10 +692,8 @@ static int smaps_hugetlb_range(pte_t *pt
 	} else if (is_swap_pte(*pte)) {
 		swp_entry_t swpent = pte_to_swp_entry(*pte);
 
-		if (is_migration_entry(swpent))
-			page = migration_entry_to_page(swpent);
-		else if (is_device_private_entry(swpent))
-			page = device_private_entry_to_page(swpent);
+		if (is_pfn_swap_entry(swpent))
+			page = pfn_swap_entry_to_page(swpent);
 	}
 	if (page) {
 		int mapcount = page_mapcount(page);
@@ -1389,11 +1385,8 @@ static pagemap_entry_t pte_to_pagemap_en
 			frame = swp_type(entry) |
 				(swp_offset(entry) << MAX_SWAPFILES_SHIFT);
 		flags |= PM_SWAP;
-		if (is_migration_entry(entry))
-			page = migration_entry_to_page(entry);
-
-		if (is_device_private_entry(entry))
-			page = device_private_entry_to_page(entry);
+		if (is_pfn_swap_entry(entry))
+			page = pfn_swap_entry_to_page(entry);
 	}
 
 	if (page && !PageAnon(page))
@@ -1454,7 +1447,7 @@ static int pagemap_pmd_range(pmd_t *pmdp
 			if (pmd_swp_uffd_wp(pmd))
 				flags |= PM_UFFD_WP;
 			VM_BUG_ON(!is_pmd_migration_entry(pmd));
-			page = migration_entry_to_page(entry);
+			page = pfn_swap_entry_to_page(entry);
 		}
 #endif
 
include/linux/swap.h renamed from include/linux/swap.h~mm-remove-special-swap-entry-functions +2 -2
@@ -564,8 +564,8 @@ static inline void show_swap_cache_info(
 {
 }
 
-#define free_swap_and_cache(e) ({(is_migration_entry(e) || is_device_private_entry(e));})
-#define swapcache_prepare(e) ({(is_migration_entry(e) || is_device_private_entry(e));})
+/* used to sanity check ptes in zap_pte_range when CONFIG_SWAP=0 */
+#define free_swap_and_cache(e) is_pfn_swap_entry(e)
 
 static inline int add_swap_count_continuation(swp_entry_t swp, gfp_t gfp_mask)
 {
include/linux/swapops.h renamed from include/linux/swapops.h~mm-remove-special-swap-entry-functions +23 -46

99 lines not on this page · raw message

mm/hmm.c renamed from mm/hmm.c~mm-remove-special-swap-entry-functions +2 -3
@@ -214,7 +214,7 @@ static inline bool hmm_is_device_private
 		swp_entry_t entry)
 {
 	return is_device_private_entry(entry) &&
-		device_private_entry_to_page(entry)->pgmap->owner ==
+		pfn_swap_entry_to_page(entry)->pgmap->owner ==
 		range->dev_private_owner;
 }
 
@@ -257,8 +257,7 @@ static int hmm_vma_handle_pte(struct mm_
 			cpu_flags = HMM_PFN_VALID;
 			if (is_write_device_private_entry(entry))
 				cpu_flags |= HMM_PFN_WRITE;
-			*hmm_pfn = device_private_entry_to_pfn(entry) |
-					cpu_flags;
+			*hmm_pfn = swp_offset(entry) | cpu_flags;
 			return 0;
 		}
 
mm/huge_memory.c renamed from mm/huge_memory.c~mm-remove-special-swap-entry-functions +3 -3
@@ -1643,7 +1643,7 @@ int zap_huge_pmd(struct mmu_gather *tlb,
 
 			VM_BUG_ON(!is_pmd_migration_entry(orig_pmd));
 			entry = pmd_to_swp_entry(orig_pmd);
-			page = migration_entry_to_page(entry);
+			page = pfn_swap_entry_to_page(entry);
 			flush_needed = 0;
 		} else
 			WARN_ONCE(1, "Non present huge pmd without pmd migration enabled!");
@@ -2012,7 +2012,7 @@ static void __split_huge_pmd_locked(stru
 			swp_entry_t entry;
 
 			entry = pmd_to_swp_entry(old_pmd);
-			page = migration_entry_to_page(entry);
+			page = pfn_swap_entry_to_page(entry);
 		} else {
 			page = pmd_page(old_pmd);
 			if (!PageDirty(page) && pmd_dirty(old_pmd))
@@ -2066,7 +2066,7 @@ static void __split_huge_pmd_locked(stru
 		swp_entry_t entry;
 
 		entry = pmd_to_swp_entry(old_pmd);
-		page = migration_entry_to_page(entry);
+		page = pfn_swap_entry_to_page(entry);
 		write = is_write_migration_entry(entry);
 		young = false;
 		soft_dirty = pmd_swp_soft_dirty(old_pmd);
mm/memcontrol.c renamed from mm/memcontrol.c~mm-remove-special-swap-entry-functions +1 -1
@@ -5532,7 +5532,7 @@ static struct page *mc_handle_swap_pte(s
 	 * as special swap entry in the CPU page table.
 	 */
 	if (is_device_private_entry(ent)) {
-		page = device_private_entry_to_page(ent);
+		page = pfn_swap_entry_to_page(ent);
 		/*
 		 * MEMORY_DEVICE_PRIVATE means ZONE_DEVICE page and which have
 		 * a refcount of 1 when free (unlike normal page)
mm/memory.c renamed from mm/memory.c~mm-remove-special-swap-entry-functions +5 -5
@@ -729,7 +729,7 @@ copy_nonpresent_pte(struct mm_struct *ds
 		}
 		rss[MM_SWAPENTS]++;
 	} else if (is_migration_entry(entry)) {
-		page = migration_entry_to_page(entry);
+		page = pfn_swap_entry_to_page(entry);
 
 		rss[mm_counter(page)]++;
 
@@ -748,7 +748,7 @@ copy_nonpresent_pte(struct mm_struct *ds
 			set_pte_at(src_mm, addr, src_pte, pte);
 		}
 	} else if (is_device_private_entry(entry)) {
-		page = device_private_entry_to_page(entry);
+		page = pfn_swap_entry_to_page(entry);
 
 		/*
 		 * Update rss count even for unaddressable pages, as
@@ -1280,7 +1280,7 @@ again:
 
 		entry = pte_to_swp_entry(ptent);
 		if (is_device_private_entry(entry)) {
-			struct page *page = device_private_entry_to_page(entry);
+			struct page *page = pfn_swap_entry_to_page(entry);
 
 			if (unlikely(details && details->check_mapping)) {
 				/*
@@ -1309,7 +1309,7 @@ again:
 		else if (is_migration_entry(entry)) {
 			struct page *page;
 
-			page = migration_entry_to_page(entry);
+			page = pfn_swap_entry_to_page(entry);
 			rss[mm_counter(page)]--;
 		}
 		if (unlikely(!free_swap_and_cache(entry)))
@@ -3372,7 +3372,7 @@ vm_fault_t do_swap_page(struct vm_fault
 			migration_entry_wait(vma->vm_mm, vmf->pmd,
 					     vmf->address);
 		} else if (is_device_private_entry(entry)) {
-			vmf->page = device_private_entry_to_page(entry);
+			vmf->page = pfn_swap_entry_to_page(entry);
 			ret = vmf->page->pgmap->ops->migrate_to_ram(vmf);
 		} else if (is_hwpoison_entry(entry)) {
 			ret = VM_FAULT_HWPOISON;
mm/migrate.c renamed from mm/migrate.c~mm-remove-special-swap-entry-functions +3 -3
@@ -296,7 +296,7 @@ void __migration_entry_wait(struct mm_st
 	if (!is_migration_entry(entry))
 		goto out;
 
-	page = migration_entry_to_page(entry);
+	page = pfn_swap_entry_to_page(entry);
 	page = compound_head(page);
 
 	/*
@@ -337,7 +337,7 @@ void pmd_migration_entry_wait(struct mm_
 	ptl = pmd_lock(mm, pmd);
 	if (!is_pmd_migration_entry(*pmd))
 		goto unlock;
-	page = migration_entry_to_page(pmd_to_swp_entry(*pmd));
+	page = pfn_swap_entry_to_page(pmd_to_swp_entry(*pmd));
 	if (!get_page_unless_zero(page))
 		goto unlock;
 	spin_unlock(ptl);
@@ -2289,7 +2289,7 @@ again:
 			if (!is_device_private_entry(entry))
 				goto next;
 
-			page = device_private_entry_to_page(entry);
+			page = pfn_swap_entry_to_page(entry);
 			if (!(migrate->flags &
 				MIGRATE_VMA_SELECT_DEVICE_PRIVATE) ||
 			    page->pgmap->owner != migrate->pgmap_owner)
mm/page_vma_mapped.c renamed from mm/page_vma_mapped.c~mm-remove-special-swap-entry-functions +3 -3
@@ -96,7 +96,7 @@ static bool check_pte(struct page_vma_ma
 		if (!is_migration_entry(entry))
 			return false;
 
-		pfn = migration_entry_to_pfn(entry);
+		pfn = swp_offset(entry);
 	} else if (is_swap_pte(*pvmw->pte)) {
 		swp_entry_t entry;
 
@@ -105,7 +105,7 @@ static bool check_pte(struct page_vma_ma
 		if (!is_device_private_entry(entry))
 			return false;
 
-		pfn = device_private_entry_to_pfn(entry);
+		pfn = swp_offset(entry);
 	} else {
 		if (!pte_present(*pvmw->pte))
 			return false;
@@ -233,7 +233,7 @@ restart:
 					return not_found(pvmw);
 				entry = pmd_to_swp_entry(pmde);
 				if (!is_migration_entry(entry) ||
-				    migration_entry_to_page(entry) != page)
+				    pfn_swap_entry_to_page(entry) != page)
 					return not_found(pvmw);
 				return true;
 			}

_

author maintainer
#145 lore raw

PATCH 131/192 mm/swapops: rework swap entry manipulation code

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm/swapops: rework swap entry manipulation code

Both migration and device private pages use special swap entries that are manipluated by a range of inline functions. The arguments to these are somewhat inconsitent so rework them to remove flag type arguments and to make the arguments similar for both read and write entry creation.

---

 include/linux/swapops.h |   56 ++++++++++++++++++++------------------
 mm/debug_vm_pgtable.c   |   12 ++++----
 mm/hmm.c                |    2 -
 mm/huge_memory.c        |   26 ++++++++++++-----
 mm/hugetlb.c            |   10 ++++--
 mm/memory.c             |   10 ++++--
 mm/migrate.c            |   26 +++++++++++++----
 mm/mprotect.c           |   10 ++++--
 mm/rmap.c               |   10 ++++--
 9 files changed, 100 insertions(+), 62 deletions(-)
include/linux/swapops.h renamed from include/linux/swapops.h~mm-swapops-rework-swap-entry-manipulation-code +30 -26
@@ -107,35 +107,35 @@ static inline void *swp_to_radix_entry(s
 }
 
 #if IS_ENABLED(CONFIG_DEVICE_PRIVATE)
-static inline swp_entry_t make_device_private_entry(struct page *page, bool write)
+static inline swp_entry_t make_readable_device_private_entry(pgoff_t offset)
 {
-	return swp_entry(write ? SWP_DEVICE_WRITE : SWP_DEVICE_READ,
-			 page_to_pfn(page));
+	return swp_entry(SWP_DEVICE_READ, offset);
 }
 
-static inline bool is_device_private_entry(swp_entry_t entry)
+static inline swp_entry_t make_writable_device_private_entry(pgoff_t offset)
 {
-	int type = swp_type(entry);
-	return type == SWP_DEVICE_READ || type == SWP_DEVICE_WRITE;
+	return swp_entry(SWP_DEVICE_WRITE, offset);
 }
 
-static inline void make_device_private_entry_read(swp_entry_t *entry)
+static inline bool is_device_private_entry(swp_entry_t entry)
 {
-	*entry = swp_entry(SWP_DEVICE_READ, swp_offset(*entry));
+	int type = swp_type(entry);
+	return type == SWP_DEVICE_READ || type == SWP_DEVICE_WRITE;
 }
 
-static inline bool is_write_device_private_entry(swp_entry_t entry)
+static inline bool is_writable_device_private_entry(swp_entry_t entry)
 {
 	return unlikely(swp_type(entry) == SWP_DEVICE_WRITE);
 }
 #else /* CONFIG_DEVICE_PRIVATE */
-static inline swp_entry_t make_device_private_entry(struct page *page, bool write)
+static inline swp_entry_t make_readable_device_private_entry(pgoff_t offset)
 {
 	return swp_entry(0, 0);
 }
 
-static inline void make_device_private_entry_read(swp_entry_t *entry)
+static inline swp_entry_t make_writable_device_private_entry(pgoff_t offset)
 {
+	return swp_entry(0, 0);
 }
 
 static inline bool is_device_private_entry(swp_entry_t entry)
@@ -143,35 +143,32 @@ static inline bool is_device_private_ent
 	return false;
 }
 
-static inline bool is_write_device_private_entry(swp_entry_t entry)
+static inline bool is_writable_device_private_entry(swp_entry_t entry)
 {
 	return false;
 }
 #endif /* CONFIG_DEVICE_PRIVATE */
 
 #ifdef CONFIG_MIGRATION
-static inline swp_entry_t make_migration_entry(struct page *page, int write)
-{
-	BUG_ON(!PageLocked(compound_head(page)));
-
-	return swp_entry(write ? SWP_MIGRATION_WRITE : SWP_MIGRATION_READ,
-			page_to_pfn(page));
-}
-
 static inline int is_migration_entry(swp_entry_t entry)
 {
 	return unlikely(swp_type(entry) == SWP_MIGRATION_READ ||
 			swp_type(entry) == SWP_MIGRATION_WRITE);
 }
 
-static inline int is_write_migration_entry(swp_entry_t entry)
+static inline int is_writable_migration_entry(swp_entry_t entry)
 {
 	return unlikely(swp_type(entry) == SWP_MIGRATION_WRITE);
 }
 
-static inline void make_migration_entry_read(swp_entry_t *entry)
+static inline swp_entry_t make_readable_migration_entry(pgoff_t offset)
 {
-	*entry = swp_entry(SWP_MIGRATION_READ, swp_offset(*entry));
+	return swp_entry(SWP_MIGRATION_READ, offset);
+}
+
+static inline swp_entry_t make_writable_migration_entry(pgoff_t offset)
+{
+	return swp_entry(SWP_MIGRATION_WRITE, offset);
 }
 
 extern void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
@@ -181,21 +178,28 @@ extern void migration_entry_wait(struct
 extern void migration_entry_wait_huge(struct vm_area_struct *vma,
 		struct mm_struct *mm, pte_t *pte);
 #else
+static inline swp_entry_t make_readable_migration_entry(pgoff_t offset)
+{
+	return swp_entry(0, 0);
+}
+
+static inline swp_entry_t make_writable_migration_entry(pgoff_t offset)
+{
+	return swp_entry(0, 0);
+}
 
-#define make_migration_entry(page, write) swp_entry(0, 0)
 static inline int is_migration_entry(swp_entry_t swp)
 {
 	return 0;
 }
 
-static inline void make_migration_entry_read(swp_entry_t *entryp) { }
 static inline void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep,
 					spinlock_t *ptl) { }
 static inline void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd,
 					 unsigned long address) { }
 static inline void migration_entry_wait_huge(struct vm_area_struct *vma,
 		struct mm_struct *mm, pte_t *pte) { }
-static inline int is_write_migration_entry(swp_entry_t entry)
+static inline int is_writable_migration_entry(swp_entry_t entry)
 {
 	return 0;
 }
mm/debug_vm_pgtable.c renamed from mm/debug_vm_pgtable.c~mm-swapops-rework-swap-entry-manipulation-code +6 -6
@@ -843,17 +843,17 @@ static void __init swap_migration_tests(
 	 * locked, otherwise it stumbles upon a BUG_ON().
 	 */
 	__SetPageLocked(page);
-	swp = make_migration_entry(page, 1);
+	swp = make_writable_migration_entry(page_to_pfn(page));
 	WARN_ON(!is_migration_entry(swp));
-	WARN_ON(!is_write_migration_entry(swp));
+	WARN_ON(!is_writable_migration_entry(swp));
 
-	make_migration_entry_read(&swp);
+	swp = make_readable_migration_entry(swp_offset(swp));
 	WARN_ON(!is_migration_entry(swp));
-	WARN_ON(is_write_migration_entry(swp));
+	WARN_ON(is_writable_migration_entry(swp));
 
-	swp = make_migration_entry(page, 0);
+	swp = make_readable_migration_entry(page_to_pfn(page));
 	WARN_ON(!is_migration_entry(swp));
-	WARN_ON(is_write_migration_entry(swp));
+	WARN_ON(is_writable_migration_entry(swp));
 	__ClearPageLocked(page);
 	__free_page(page);
 }
mm/hmm.c renamed from mm/hmm.c~mm-swapops-rework-swap-entry-manipulation-code +1 -1
@@ -255,7 +255,7 @@ static int hmm_vma_handle_pte(struct mm_
 		 */
 		if (hmm_is_device_private_entry(range, entry)) {
 			cpu_flags = HMM_PFN_VALID;
-			if (is_write_device_private_entry(entry))
+			if (is_writable_device_private_entry(entry))
 				cpu_flags |= HMM_PFN_WRITE;
 			*hmm_pfn = swp_offset(entry) | cpu_flags;
 			return 0;
mm/huge_memory.c renamed from mm/huge_memory.c~mm-swapops-rework-swap-entry-manipulation-code +18 -8
@@ -1054,8 +1054,9 @@ int copy_huge_pmd(struct mm_struct *dst_
 		swp_entry_t entry = pmd_to_swp_entry(pmd);
 
 		VM_BUG_ON(!is_pmd_migration_entry(pmd));
-		if (is_write_migration_entry(entry)) {
-			make_migration_entry_read(&entry);
+		if (is_writable_migration_entry(entry)) {
+			entry = make_readable_migration_entry(
+							swp_offset(entry));
 			pmd = swp_entry_to_pmd(entry);
 			if (pmd_swp_soft_dirty(*src_pmd))
 				pmd = pmd_swp_mksoft_dirty(pmd);
@@ -1772,13 +1773,14 @@ int change_huge_pmd(struct vm_area_struc
 		swp_entry_t entry = pmd_to_swp_entry(*pmd);
 
 		VM_BUG_ON(!is_pmd_migration_entry(*pmd));
-		if (is_write_migration_entry(entry)) {
+		if (is_writable_migration_entry(entry)) {
 			pmd_t newpmd;
 			/*
 			 * A protection check is difficult so
 			 * just be safe and disable write
 			 */
-			make_migration_entry_read(&entry);
+			entry = make_readable_migration_entry(
+							swp_offset(entry));
 			newpmd = swp_entry_to_pmd(entry);
 			if (pmd_swp_soft_dirty(*pmd))
 				newpmd = pmd_swp_mksoft_dirty(newpmd);
@@ -2067,7 +2069,7 @@ static void __split_huge_pmd_locked(stru
 
 		entry = pmd_to_swp_entry(old_pmd);
 		page = pfn_swap_entry_to_page(entry);
-		write = is_write_migration_entry(entry);
+		write = is_writable_migration_entry(entry);
 		young = false;
 		soft_dirty = pmd_swp_soft_dirty(old_pmd);
 		uffd_wp = pmd_swp_uffd_wp(old_pmd);
@@ -2099,7 +2101,12 @@ static void __split_huge_pmd_locked(stru
 		 */
 		if (freeze || pmd_migration) {
 			swp_entry_t swp_entry;
-			swp_entry = make_migration_entry(page + i, write);
+			if (write)
+				swp_entry = make_writable_migration_entry(
+							page_to_pfn(page + i));
+			else
+				swp_entry = make_readable_migration_entry(
+							page_to_pfn(page + i));
 			entry = swp_entry_to_pte(swp_entry);
 			if (soft_dirty)
 				entry = pte_swp_mksoft_dirty(entry);
@@ -3171,7 +3178,10 @@ void set_pmd_migration_entry(struct page
 	pmdval = pmdp_invalidate(vma, address, pvmw->pmd);
 	if (pmd_dirty(pmdval))
 		set_page_dirty(page);
-	entry = make_migration_entry(page, pmd_write(pmdval));
+	if (pmd_write(pmdval))
+		entry = make_writable_migration_entry(page_to_pfn(page));
+	else
+		entry = make_readable_migration_entry(page_to_pfn(page));
 	pmdswp = swp_entry_to_pmd(entry);
 	if (pmd_soft_dirty(pmdval))
 		pmdswp = pmd_swp_mksoft_dirty(pmdswp);
@@ -3197,7 +3207,7 @@ void remove_migration_pmd(struct page_vm
 	pmde = pmd_mkold(mk_huge_pmd(new, vma->vm_page_prot));
 	if (pmd_swp_soft_dirty(*pvmw->pmd))
 		pmde = pmd_mksoft_dirty(pmde);
-	if (is_write_migration_entry(entry))
+	if (is_writable_migration_entry(entry))
 		pmde = maybe_pmd_mkwrite(pmde, vma);
 	if (pmd_swp_uffd_wp(*pvmw->pmd))
 		pmde = pmd_wrprotect(pmd_mkuffd_wp(pmde));
mm/hugetlb.c renamed from mm/hugetlb.c~mm-swapops-rework-swap-entry-manipulation-code +6 -4
@@ -4242,12 +4242,13 @@ again:
 				    is_hugetlb_entry_hwpoisoned(entry))) {
 			swp_entry_t swp_entry = pte_to_swp_entry(entry);
 
-			if (is_write_migration_entry(swp_entry) && cow) {
+			if (is_writable_migration_entry(swp_entry) && cow) {
 				/*
 				 * COW mappings require pages in both
 				 * parent and child to be set to read.
 				 */
-				make_migration_entry_read(&swp_entry);
+				swp_entry = make_readable_migration_entry(
+							swp_offset(swp_entry));
 				entry = swp_entry_to_pte(swp_entry);
 				set_huge_swap_pte_at(src, addr, src_pte,
 						     entry, sz);
@@ -5532,10 +5533,11 @@ unsigned long hugetlb_change_protection(
 		if (unlikely(is_hugetlb_entry_migration(pte))) {
 			swp_entry_t entry = pte_to_swp_entry(pte);
 
-			if (is_write_migration_entry(entry)) {
+			if (is_writable_migration_entry(entry)) {
 				pte_t newpte;
 
-				make_migration_entry_read(&entry);
+				entry = make_readable_migration_entry(
+							swp_offset(entry));
 				newpte = swp_entry_to_pte(entry);
 				set_huge_swap_pte_at(mm, address, ptep,
 						     newpte, huge_page_size(h));
mm/memory.c renamed from mm/memory.c~mm-swapops-rework-swap-entry-manipulation-code +6 -4
@@ -733,13 +733,14 @@ copy_nonpresent_pte(struct mm_struct *ds
 
 		rss[mm_counter(page)]++;
 
-		if (is_write_migration_entry(entry) &&
+		if (is_writable_migration_entry(entry) &&
 				is_cow_mapping(vm_flags)) {
 			/*
 			 * COW mappings require pages in both
 			 * parent and child to be set to read.
 			 */
-			make_migration_entry_read(&entry);
+			entry = make_readable_migration_entry(
+							swp_offset(entry));
 			pte = swp_entry_to_pte(entry);
 			if (pte_swp_soft_dirty(*src_pte))
 				pte = pte_swp_mksoft_dirty(pte);
@@ -770,9 +771,10 @@ copy_nonpresent_pte(struct mm_struct *ds
 		 * when a device driver is involved (you cannot easily
 		 * save and restore device driver state).
 		 */
-		if (is_write_device_private_entry(entry) &&
+		if (is_writable_device_private_entry(entry) &&
 		    is_cow_mapping(vm_flags)) {
-			make_device_private_entry_read(&entry);
+			entry = make_readable_device_private_entry(
+							swp_offset(entry));
 			pte = swp_entry_to_pte(entry);
 			if (pte_swp_uffd_wp(*src_pte))
 				pte = pte_swp_mkuffd_wp(pte);
mm/migrate.c renamed from mm/migrate.c~mm-swapops-rework-swap-entry-manipulation-code +20 -6
@@ -210,13 +210,18 @@ static bool remove_migration_pte(struct
 		 * Recheck VMA as permissions can change since migration started
 		 */
 		entry = pte_to_swp_entry(*pvmw.pte);
-		if (is_write_migration_entry(entry))
+		if (is_writable_migration_entry(entry))
 			pte = maybe_mkwrite(pte, vma);
 		else if (pte_swp_uffd_wp(*pvmw.pte))
 			pte = pte_mkuffd_wp(pte);
 
 		if (unlikely(is_device_private_page(new))) {
-			entry = make_device_private_entry(new, pte_write(pte));
+			if (pte_write(pte))
+				entry = make_writable_device_private_entry(
+							page_to_pfn(new));
+			else
+				entry = make_readable_device_private_entry(
+							page_to_pfn(new));
 			pte = swp_entry_to_pte(entry);
 			if (pte_swp_soft_dirty(*pvmw.pte))
 				pte = pte_swp_mksoft_dirty(pte);
@@ -2297,7 +2302,7 @@ again:
 
 			mpfn = migrate_pfn(page_to_pfn(page)) |
 					MIGRATE_PFN_MIGRATE;
-			if (is_write_device_private_entry(entry))
+			if (is_writable_device_private_entry(entry))
 				mpfn |= MIGRATE_PFN_WRITE;
 		} else {
 			if (!(migrate->flags & MIGRATE_VMA_SELECT_SYSTEM))
@@ -2343,8 +2348,12 @@ again:
 			ptep_get_and_clear(mm, addr, ptep);
 
 			/* Setup special migration page table entry */
-			entry = make_migration_entry(page, mpfn &
-						     MIGRATE_PFN_WRITE);
+			if (mpfn & MIGRATE_PFN_WRITE)
+				entry = make_writable_migration_entry(
+							page_to_pfn(page));
+			else
+				entry = make_readable_migration_entry(
+							page_to_pfn(page));
 			swp_pte = swp_entry_to_pte(entry);
 			if (pte_present(pte)) {
 				if (pte_soft_dirty(pte))
@@ -2817,7 +2826,12 @@ static void migrate_vma_insert_page(stru
 		if (is_device_private_page(page)) {
 			swp_entry_t swp_entry;
 
-			swp_entry = make_device_private_entry(page, vma->vm_flags & VM_WRITE);
+			if (vma->vm_flags & VM_WRITE)
+				swp_entry = make_writable_device_private_entry(
+							page_to_pfn(page));
+			else
+				swp_entry = make_readable_device_private_entry(
+							page_to_pfn(page));
 			entry = swp_entry_to_pte(swp_entry);
 		} else {
 			/*
mm/mprotect.c renamed from mm/mprotect.c~mm-swapops-rework-swap-entry-manipulation-code +6 -4
@@ -143,23 +143,25 @@ static unsigned long change_pte_range(st
 			swp_entry_t entry = pte_to_swp_entry(oldpte);
 			pte_t newpte;
 
-			if (is_write_migration_entry(entry)) {
+			if (is_writable_migration_entry(entry)) {
 				/*
 				 * A protection check is difficult so
 				 * just be safe and disable write
 				 */
-				make_migration_entry_read(&entry);
+				entry = make_readable_migration_entry(
+							swp_offset(entry));
 				newpte = swp_entry_to_pte(entry);
 				if (pte_swp_soft_dirty(oldpte))
 					newpte = pte_swp_mksoft_dirty(newpte);
 				if (pte_swp_uffd_wp(oldpte))
 					newpte = pte_swp_mkuffd_wp(newpte);
-			} else if (is_write_device_private_entry(entry)) {
+			} else if (is_writable_device_private_entry(entry)) {
 				/*
 				 * We do not preserve soft-dirtiness. See
 				 * copy_one_pte() for explanation.
 				 */
-				make_device_private_entry_read(&entry);
+				entry = make_readable_device_private_entry(
+							swp_offset(entry));
 				newpte = swp_entry_to_pte(entry);
 				if (pte_swp_uffd_wp(oldpte))
 					newpte = pte_swp_mkuffd_wp(newpte);
mm/rmap.c renamed from mm/rmap.c~mm-swapops-rework-swap-entry-manipulation-code +7 -3
@@ -1533,7 +1533,7 @@ static bool try_to_unmap_one(struct page
 			 * pte. do_swap_page() will wait until the migration
 			 * pte is removed and then restart fault handling.
 			 */
-			entry = make_migration_entry(page, 0);
+			entry = make_readable_migration_entry(page_to_pfn(page));
 			swp_pte = swp_entry_to_pte(entry);
 
 			/*
@@ -1629,8 +1629,12 @@ static bool try_to_unmap_one(struct page
 			 * pte. do_swap_page() will wait until the migration
 			 * pte is removed and then restart fault handling.
 			 */
-			entry = make_migration_entry(subpage,
-					pte_write(pteval));
+			if (pte_write(pteval))
+				entry = make_writable_migration_entry(
+							page_to_pfn(subpage));
+			else
+				entry = make_readable_migration_entry(
+							page_to_pfn(subpage));
 			swp_pte = swp_entry_to_pte(entry);
 			if (pte_soft_dirty(pteval))
 				swp_pte = pte_swp_mksoft_dirty(swp_pte);

_

author maintainer
#146 lore raw

PATCH 132/192 mm/rmap: split try_to_munlock from try_to_unmap

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm/rmap: split try_to_munlock from try_to_unmap

The behaviour of try_to_unmap_one() is difficult to follow because it performs different operations based on a fairly large set of flags used in different combinations.

TTU_MUNLOCK is one such flag. However it is exclusively used by try_to_munlock() which specifies no other flags. Therefore rather than overload try_to_unmap_one() with unrelated behaviour split this out into it's own function and remove the flag.

---

 Documentation/vm/unevictable-lru.rst |   33 ++++--------
 include/linux/rmap.h                 |    3 -
 mm/mlock.c                           |   12 ++--
 mm/rmap.c                            |   66 ++++++++++++++++++-------
 4 files changed, 69 insertions(+), 45 deletions(-)
Documentation/vm/unevictable-lru.rst renamed from Documentation/vm/unevictable-lru.rst~mm-rmap-split-try_to_munlock-from-try_to_unmap +13 -20
@@ -389,14 +389,14 @@ mlocked, munlock_vma_page() updates that
 mlocked pages.  Note, however, that at this point we haven't checked whether
 the page is mapped by other VM_LOCKED VMAs.
 
-We can't call try_to_munlock(), the function that walks the reverse map to
+We can't call page_mlock(), the function that walks the reverse map to
 check for other VM_LOCKED VMAs, without first isolating the page from the LRU.
-try_to_munlock() is a variant of try_to_unmap() and thus requires that the page
+page_mlock() is a variant of try_to_unmap() and thus requires that the page
 not be on an LRU list [more on these below].  However, the call to
-isolate_lru_page() could fail, in which case we couldn't try_to_munlock().  So,
+isolate_lru_page() could fail, in which case we can't call page_mlock().  So,
 we go ahead and clear PG_mlocked up front, as this might be the only chance we
-have.  If we can successfully isolate the page, we go ahead and
-try_to_munlock(), which will restore the PG_mlocked flag and update the zone
+have.  If we can successfully isolate the page, we go ahead and call
+page_mlock(), which will restore the PG_mlocked flag and update the zone
 page statistics if it finds another VMA holding the page mlocked.  If we fail
 to isolate the page, we'll have left a potentially mlocked page on the LRU.
 This is fine, because we'll catch it later if and if vmscan tries to reclaim
@@ -545,31 +545,24 @@ munlock or munmap system calls, mm teard
 holepunching, and truncation of file pages and their anonymous COWed pages.
 
 
-try_to_munlock() Reverse Map Scan
+page_mlock() Reverse Map Scan
 ---------------------------------
 
-.. warning::
-   [!] TODO/FIXME: a better name might be page_mlocked() - analogous to the
-   page_referenced() reverse map walker.
-
 When munlock_vma_page() [see section :ref:`munlock()/munlockall() System Call
 Handling <munlock_munlockall_handling>` above] tries to munlock a
 page, it needs to determine whether or not the page is mapped by any
 VM_LOCKED VMA without actually attempting to unmap all PTEs from the
 page.  For this purpose, the unevictable/mlock infrastructure
-introduced a variant of try_to_unmap() called try_to_munlock().
+introduced a variant of try_to_unmap() called page_mlock().
 
-try_to_munlock() calls the same functions as try_to_unmap() for anonymous and
-mapped file and KSM pages with a flag argument specifying unlock versus unmap
-processing.  Again, these functions walk the respective reverse maps looking
-for VM_LOCKED VMAs.  When such a VMA is found, as in the try_to_unmap() case,
-the functions mlock the page via mlock_vma_page() and return SWAP_MLOCK.  This
-undoes the pre-clearing of the page's PG_mlocked done by munlock_vma_page.
+page_mlock() walks the respective reverse maps looking for VM_LOCKED VMAs. When
+such a VMA is found the page is mlocked via mlock_vma_page(). This undoes the
+pre-clearing of the page's PG_mlocked done by munlock_vma_page.
 
-Note that try_to_munlock()'s reverse map walk must visit every VMA in a page's
+Note that page_mlock()'s reverse map walk must visit every VMA in a page's
 reverse map to determine that a page is NOT mapped into any VM_LOCKED VMA.
 However, the scan can terminate when it encounters a VM_LOCKED VMA.
-Although try_to_munlock() might be called a great many times when munlocking a
+Although page_mlock() might be called a great many times when munlocking a
 large region or tearing down a large address space that has been mlocked via
 mlockall(), overall this is a fairly rare event.
 
@@ -602,7 +595,7 @@ inactive lists to the appropriate node's
 shrink_inactive_list() should only see SHM_LOCK'd pages that became SHM_LOCK'd
 after shrink_active_list() had moved them to the inactive list, or pages mapped
 into VM_LOCKED VMAs that munlock_vma_page() couldn't isolate from the LRU to
-recheck via try_to_munlock().  shrink_inactive_list() won't notice the latter,
+recheck via page_mlock().  shrink_inactive_list() won't notice the latter,
 but will pass on to shrink_page_list().
 
 shrink_page_list() again culls obviously unevictable pages that it could
include/linux/rmap.h renamed from include/linux/rmap.h~mm-rmap-split-try_to_munlock-from-try_to_unmap +1 -2
@@ -87,7 +87,6 @@ struct anon_vma_chain {
 
 enum ttu_flags {
 	TTU_MIGRATION		= 0x1,	/* migration mode */
-	TTU_MUNLOCK		= 0x2,	/* munlock mode */
 
 	TTU_SPLIT_HUGE_PMD	= 0x4,	/* split huge PMD if any */
 	TTU_IGNORE_MLOCK	= 0x8,	/* ignore mlock */
@@ -240,7 +239,7 @@ int page_mkclean(struct page *);
  * called in munlock()/munmap() path to check for other vmas holding
  * the page mlocked.
  */
-void try_to_munlock(struct page *);
+void page_mlock(struct page *page);
 
 void remove_migration_ptes(struct page *old, struct page *new, bool locked);
 
mm/mlock.c renamed from mm/mlock.c~mm-rmap-split-try_to_munlock-from-try_to_unmap +6 -6
@@ -108,7 +108,7 @@ void mlock_vma_page(struct page *page)
 /*
  * Finish munlock after successful page isolation
  *
- * Page must be locked. This is a wrapper for try_to_munlock()
+ * Page must be locked. This is a wrapper for page_mlock()
  * and putback_lru_page() with munlock accounting.
  */
 static void __munlock_isolated_page(struct page *page)
@@ -118,7 +118,7 @@ static void __munlock_isolated_page(stru
 	 * and we don't need to check all the other vmas.
 	 */
 	if (page_mapcount(page) > 1)
-		try_to_munlock(page);
+		page_mlock(page);
 
 	/* Did try_to_unlock() succeed or punt? */
 	if (!PageMlocked(page))
@@ -158,7 +158,7 @@ static void __munlock_isolation_failed(s
  * munlock()ed or munmap()ed, we want to check whether other vmas hold the
  * page locked so that we can leave it on the unevictable lru list and not
  * bother vmscan with it.  However, to walk the page's rmap list in
- * try_to_munlock() we must isolate the page from the LRU.  If some other
+ * page_mlock() we must isolate the page from the LRU.  If some other
  * task has removed the page from the LRU, we won't be able to do that.
  * So we clear the PageMlocked as we might not get another chance.  If we
  * can't isolate the page, we leave it for putback_lru_page() and vmscan
@@ -168,7 +168,7 @@ unsigned int munlock_vma_page(struct pag
 {
 	int nr_pages;
 
-	/* For try_to_munlock() and to serialize with page migration */
+	/* For page_mlock() and to serialize with page migration */
 	BUG_ON(!PageLocked(page));
 	VM_BUG_ON_PAGE(PageTail(page), page);
 
@@ -205,7 +205,7 @@ static int __mlock_posix_error_return(lo
  *
  * The fast path is available only for evictable pages with single mapping.
  * Then we can bypass the per-cpu pvec and get better performance.
- * when mapcount > 1 we need try_to_munlock() which can fail.
+ * when mapcount > 1 we need page_mlock() which can fail.
  * when !page_evictable(), we need the full redo logic of putback_lru_page to
  * avoid leaving evictable page in unevictable list.
  *
@@ -414,7 +414,7 @@ static unsigned long __munlock_pagevec_f
  *
  * We don't save and restore VM_LOCKED here because pages are
  * still on lru.  In unmap path, pages might be scanned by reclaim
- * and re-mlocked by try_to_{munlock|unmap} before we unmap and
+ * and re-mlocked by page_mlock/try_to_unmap before we unmap and
  * free them.  This will result in freeing mlocked pages.
  */
 void munlock_vma_pages_range(struct vm_area_struct *vma,
mm/rmap.c renamed from mm/rmap.c~mm-rmap-split-try_to_munlock-from-try_to_unmap +49 -17

101 lines not on this page · raw message

_

author maintainer
#147 lore raw

PATCH 133/192 mm/rmap: split migration into its own function

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm/rmap: split migration into its own function

Migration is currently implemented as a mode of operation for try_to_unmap_one() generally specified by passing the TTU_MIGRATION flag or in the case of splitting a huge anonymous page TTU_SPLIT_FREEZE.

However it does not have much in common with the rest of the unmap functionality of try_to_unmap_one() and thus splitting it into a separate function reduces the complexity of try_to_unmap_one() making it more readable.

Several simplifications can also be made in try_to_migrate_one() based on the following observations:

- All users of TTU_MIGRATION also set TTU_IGNORE_MLOCK.
- No users of TTU_MIGRATION ever set TTU_IGNORE_HWPOISON.
- No users of TTU_MIGRATION ever set TTU_BATCH_FLUSH.

TTU_SPLIT_FREEZE is a special case of migration used when splitting an anonymous page. This is most easily dealt with by calling the correct function from unmap_page() in mm/huge_memory.c - either try_to_migrate() for PageAnon or try_to_unmap().

---

 include/linux/rmap.h |    4 
 mm/huge_memory.c     |   16 +
 mm/migrate.c         |    9 -
 mm/rmap.c            |  367 ++++++++++++++++++++++++++++++-----------
 4 files changed, 289 insertions(+), 107 deletions(-)
include/linux/rmap.h renamed from include/linux/rmap.h~mm-rmap-split-migration-into-its-own-function +1 -3
@@ -86,8 +86,6 @@ struct anon_vma_chain {
 };
 
 enum ttu_flags {
-	TTU_MIGRATION		= 0x1,	/* migration mode */
-
 	TTU_SPLIT_HUGE_PMD	= 0x4,	/* split huge PMD if any */
 	TTU_IGNORE_MLOCK	= 0x8,	/* ignore mlock */
 	TTU_SYNC		= 0x10,	/* avoid racy checks with PVMW_SYNC */
@@ -97,7 +95,6 @@ enum ttu_flags {
 					 * do a final flush if necessary */
 	TTU_RMAP_LOCKED		= 0x80,	/* do not grab rmap lock:
 					 * caller holds it */
-	TTU_SPLIT_FREEZE	= 0x100,		/* freeze pte under splitting thp */
 };
 
 #ifdef CONFIG_MMU
@@ -194,6 +191,7 @@ static inline void page_dup_rmap(struct
 int page_referenced(struct page *, int is_locked,
 			struct mem_cgroup *memcg, unsigned long *vm_flags);
 
+void try_to_migrate(struct page *page, enum ttu_flags flags);
 void try_to_unmap(struct page *, enum ttu_flags flags);
 
 /* Avoid racy checks */
mm/huge_memory.c renamed from mm/huge_memory.c~mm-rmap-split-migration-into-its-own-function +10 -6
@@ -2309,16 +2309,20 @@ void vma_adjust_trans_huge(struct vm_are
 
 static void unmap_page(struct page *page)
 {
-	enum ttu_flags ttu_flags = TTU_IGNORE_MLOCK | TTU_SYNC |
-		TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD;
+	enum ttu_flags ttu_flags = TTU_RMAP_LOCKED | TTU_SPLIT_HUGE_PMD |
+		TTU_SYNC;
 
 	VM_BUG_ON_PAGE(!PageHead(page), page);
 
-	/* If TTU_SPLIT_FREEZE is ever extended to file, update remap_page() */
+	/*
+	 * Anon pages need migration entries to preserve them, but file
+	 * pages can simply be left unmapped, then faulted back on demand.
+	 * If that is ever changed (perhaps for mlock), update remap_page().
+	 */
 	if (PageAnon(page))
-		ttu_flags |= TTU_SPLIT_FREEZE;
-
-	try_to_unmap(page, ttu_flags);
+		try_to_migrate(page, ttu_flags);
+	else
+		try_to_unmap(page, ttu_flags | TTU_IGNORE_MLOCK);
 
 	VM_WARN_ON_ONCE_PAGE(page_mapped(page), page);
 }
mm/migrate.c renamed from mm/migrate.c~mm-rmap-split-migration-into-its-own-function +4 -5
@@ -1109,7 +1109,7 @@ static int __unmap_and_move(struct page
 		/* Establish migration ptes */
 		VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma,
 				page);
-		try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK);
+		try_to_migrate(page, 0);
 		page_was_mapped = 1;
 	}
 
@@ -1311,7 +1311,7 @@ static int unmap_and_move_huge_page(new_
 
 	if (page_mapped(hpage)) {
 		bool mapping_locked = false;
-		enum ttu_flags ttu = TTU_MIGRATION|TTU_IGNORE_MLOCK;
+		enum ttu_flags ttu = 0;
 
 		if (!PageAnon(hpage)) {
 			/*
@@ -1328,7 +1328,7 @@ static int unmap_and_move_huge_page(new_
 			ttu |= TTU_RMAP_LOCKED;
 		}
 
-		try_to_unmap(hpage, ttu);
+		try_to_migrate(hpage, ttu);
 		page_was_mapped = 1;
 
 		if (mapping_locked)
@@ -2602,7 +2602,6 @@ static void migrate_vma_prepare(struct m
  */
 static void migrate_vma_unmap(struct migrate_vma *migrate)
 {
-	int flags = TTU_MIGRATION | TTU_IGNORE_MLOCK;
 	const unsigned long npages = migrate->npages;
 	const unsigned long start = migrate->start;
 	unsigned long addr, i, restore = 0;
@@ -2614,7 +2613,7 @@ static void migrate_vma_unmap(struct mig
 			continue;
 
 		if (page_mapped(page)) {
-			try_to_unmap(page, flags);
+			try_to_migrate(page, 0);
 			if (page_mapped(page))
 				goto restore;
 		}
mm/rmap.c renamed from mm/rmap.c~mm-rmap-split-migration-into-its-own-function +274 -93

403 lines not on this page · raw message

_

author maintainer
#148 lore raw

PATCH 134/192 mm: rename migrate_pgmap_owner

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm: rename migrate_pgmap_owner

MMU notifier ranges have a migrate_pgmap_owner field which is used by drivers to store a pointer. This is subsequently used by the driver callback to filter MMU_NOTIFY_MIGRATE events. Other notifier event types can also benefit from this filtering, so rename the 'migrate_pgmap_owner' field to 'owner' and create a new notifier initialisation function to initialise this field.

Cc Ben Skeggs <[email protected]>
Cc Christoph Hellwig <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc John Hubbard <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Ralph Campbell <[email protected]>
Cc Shakeel Butt <[email protected]>

---

 Documentation/vm/hmm.rst              |    2 +-
 drivers/gpu/drm/nouveau/nouveau_svm.c |    2 +-
 include/linux/mmu_notifier.h          |   20 ++++++++++----------
 lib/test_hmm.c                        |    2 +-
 mm/migrate.c                          |   10 +++++-----
 5 files changed, 18 insertions(+), 18 deletions(-)
Documentation/vm/hmm.rst renamed from Documentation/vm/hmm.rst~mm-rename-migrate_pgmap_owner +1 -1
@@ -332,7 +332,7 @@ between device driver specific code and
    walks to fill in the ``args->src`` array with PFNs to be migrated.
    The ``invalidate_range_start()`` callback is passed a
    ``struct mmu_notifier_range`` with the ``event`` field set to
-   ``MMU_NOTIFY_MIGRATE`` and the ``migrate_pgmap_owner`` field set to
+   ``MMU_NOTIFY_MIGRATE`` and the ``owner`` field set to
    the ``args->pgmap_owner`` field passed to migrate_vma_setup(). This is
    allows the device driver to skip the invalidation callback and only
    invalidate device private MMU mappings that are actually migrating.
drivers/gpu/drm/nouveau/nouveau_svm.c renamed from drivers/gpu/drm/nouveau/nouveau_svm.c~mm-rename-migrate_pgmap_owner +1 -1
@@ -265,7 +265,7 @@ nouveau_svmm_invalidate_range_start(stru
 	 * the invalidation is handled as part of the migration process.
 	 */
 	if (update->event == MMU_NOTIFY_MIGRATE &&
-	    update->migrate_pgmap_owner == svmm->vmm->cli->drm->dev)
+	    update->owner == svmm->vmm->cli->drm->dev)
 		goto out;
 
 	if (limit > svmm->unmanaged.start && start < svmm->unmanaged.limit) {
include/linux/mmu_notifier.h renamed from include/linux/mmu_notifier.h~mm-rename-migrate_pgmap_owner +10 -10
@@ -41,7 +41,7 @@ struct mmu_interval_notifier;
  *
  * @MMU_NOTIFY_MIGRATE: used during migrate_vma_collect() invalidate to signal
  * a device driver to possibly ignore the invalidation if the
- * migrate_pgmap_owner field matches the driver's device private pgmap owner.
+ * owner field matches the driver's device private pgmap owner.
  */
 enum mmu_notifier_event {
 	MMU_NOTIFY_UNMAP = 0,
@@ -269,7 +269,7 @@ struct mmu_notifier_range {
 	unsigned long end;
 	unsigned flags;
 	enum mmu_notifier_event event;
-	void *migrate_pgmap_owner;
+	void *owner;
 };
 
 static inline int mm_has_notifiers(struct mm_struct *mm)
@@ -521,14 +521,14 @@ static inline void mmu_notifier_range_in
 	range->flags = flags;
 }
 
-static inline void mmu_notifier_range_init_migrate(
-			struct mmu_notifier_range *range, unsigned int flags,
+static inline void mmu_notifier_range_init_owner(
+			struct mmu_notifier_range *range,
+			enum mmu_notifier_event event, unsigned int flags,
 			struct vm_area_struct *vma, struct mm_struct *mm,
-			unsigned long start, unsigned long end, void *pgmap)
+			unsigned long start, unsigned long end, void *owner)
 {
-	mmu_notifier_range_init(range, MMU_NOTIFY_MIGRATE, flags, vma, mm,
-				start, end);
-	range->migrate_pgmap_owner = pgmap;
+	mmu_notifier_range_init(range, event, flags, vma, mm, start, end);
+	range->owner = owner;
 }
 
 #define ptep_clear_flush_young_notify(__vma, __address, __ptep)		\
@@ -655,8 +655,8 @@ static inline void _mmu_notifier_range_i
 
 #define mmu_notifier_range_init(range,event,flags,vma,mm,start,end)  \
 	_mmu_notifier_range_init(range, start, end)
-#define mmu_notifier_range_init_migrate(range, flags, vma, mm, start, end, \
-					pgmap) \
+#define mmu_notifier_range_init_owner(range, event, flags, vma, mm, start, \
+					end, owner) \
 	_mmu_notifier_range_init(range, start, end)
 
 static inline bool
lib/test_hmm.c renamed from lib/test_hmm.c~mm-rename-migrate_pgmap_owner +1 -1
@@ -218,7 +218,7 @@ static bool dmirror_interval_invalidate(
 	 * the invalidation is handled as part of the migration process.
 	 */
 	if (range->event == MMU_NOTIFY_MIGRATE &&
-	    range->migrate_pgmap_owner == dmirror->mdevice)
+	    range->owner == dmirror->mdevice)
 		return true;
 
 	if (mmu_notifier_range_blockable(range))
mm/migrate.c renamed from mm/migrate.c~mm-rename-migrate_pgmap_owner +5 -5
@@ -2416,8 +2416,8 @@ static void migrate_vma_collect(struct m
 	 * that the registered device driver can skip invalidating device
 	 * private page mappings that won't be migrated.
 	 */
-	mmu_notifier_range_init_migrate(&range, 0, migrate->vma,
-		migrate->vma->vm_mm, migrate->start, migrate->end,
+	mmu_notifier_range_init_owner(&range, MMU_NOTIFY_MIGRATE, 0,
+		migrate->vma, migrate->vma->vm_mm, migrate->start, migrate->end,
 		migrate->pgmap_owner);
 	mmu_notifier_invalidate_range_start(&range);
 
@@ -2927,9 +2927,9 @@ void migrate_vma_pages(struct migrate_vm
 			if (!notified) {
 				notified = true;
 
-				mmu_notifier_range_init_migrate(&range, 0,
-					migrate->vma, migrate->vma->vm_mm,
-					addr, migrate->end,
+				mmu_notifier_range_init_owner(&range,
+					MMU_NOTIFY_MIGRATE, 0, migrate->vma,
+					migrate->vma->vm_mm, addr, migrate->end,
 					migrate->pgmap_owner);
 				mmu_notifier_invalidate_range_start(&range);
 			}

_

author maintainer
#149 lore raw

PATCH 135/192 mm/memory.c: allow different return codes for copy_nonpresent_pte()

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm/memory.c: allow different return codes for copy_nonpresent_pte()

Currently if copy_nonpresent_pte() returns a non-zero value it is assumed to be a swap entry which requires further processing outside the loop in copy_pte_range() after dropping locks. This prevents other values being returned to signal conditions such as failure which a subsequent change requires.

Instead make copy_nonpresent_pte() return an error code if further processing is required and read the value for the swap entry in the main loop under the ptl.

Cc Ben Skeggs <[email protected]>
Cc Christoph Hellwig <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc John Hubbard <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Ralph Campbell <[email protected]>
Cc Shakeel Butt <[email protected]>

---

 mm/memory.c |   28 +++++++++++++++++-----------
 1 file changed, 17 insertions(+), 11 deletions(-)
mm/memory.c renamed from mm/memory.c~mm-memoryc-allow-different-return-codes-for-copy_nonpresent_pte +17 -11
@@ -717,7 +717,7 @@ copy_nonpresent_pte(struct mm_struct *ds
 
 	if (likely(!non_swap_entry(entry))) {
 		if (swap_duplicate(entry) < 0)
-			return entry.val;
+			return -EIO;
 
 		/* make sure dst_mm is on swapoff's mmlist. */
 		if (unlikely(list_empty(&dst_mm->mmlist))) {
@@ -973,12 +973,14 @@ again:
 			continue;
 		}
 		if (unlikely(!pte_present(*src_pte))) {
-			entry.val = copy_nonpresent_pte(dst_mm, src_mm,
-							dst_pte, src_pte,
-							dst_vma, src_vma,
-							addr, rss);
-			if (entry.val)
+			ret = copy_nonpresent_pte(dst_mm, src_mm,
+						  dst_pte, src_pte,
+						  dst_vma, src_vma,
+						  addr, rss);
+			if (ret == -EIO) {
+				entry = pte_to_swp_entry(*src_pte);
 				break;
+			}
 			progress += 8;
 			continue;
 		}
@@ -1011,20 +1013,24 @@ again:
 	pte_unmap_unlock(orig_dst_pte, dst_ptl);
 	cond_resched();
 
-	if (entry.val) {
+	if (ret == -EIO) {
+		VM_WARN_ON_ONCE(!entry.val);
 		if (add_swap_count_continuation(entry, GFP_KERNEL) < 0) {
 			ret = -ENOMEM;
 			goto out;
 		}
 		entry.val = 0;
-	} else if (ret) {
-		WARN_ON_ONCE(ret != -EAGAIN);
+	} else if (ret ==  -EAGAIN) {
 		prealloc = page_copy_prealloc(src_mm, src_vma, addr);
 		if (!prealloc)
 			return -ENOMEM;
-		/* We've captured and resolved the error. Reset, try again. */
-		ret = 0;
+	} else if (ret) {
+		VM_WARN_ON_ONCE(1);
 	}
+
+	/* We've captured and resolved the error. Reset, try again. */
+	ret = 0;
+
 	if (addr != end)
 		goto again;
 out:

_

author maintainer
#150 lore raw

PATCH 136/192 mm: device exclusive memory access

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm: device exclusive memory access

Some devices require exclusive write access to shared virtual memory (SVM) ranges to perform atomic operations on that memory. This requires CPU page tables to be updated to deny access whilst atomic operations are occurring.

In order to do this introduce a new swap entry type (SWP_DEVICE_EXCLUSIVE). When a SVM range needs to be marked for exclusive access by a device all page table mappings for the particular range are replaced with device exclusive swap entries. This causes any CPU access to the page to result in a fault.

Faults are resovled by replacing the faulting entry with the original mapping. This results in MMU notifiers being called which a driver uses to update access permissions such as revoking atomic access. After notifiers have been called the device will no longer have exclusive access to the region.

Walking of the page tables to find the target pages is handled by get_user_pages() rather than a direct page table walk. A direct page table walk similar to what migrate_vma_collect()/unmap() does could also have been utilised. However this resulted in more code similar in functionality to what get_user_pages() provides as page faulting is required to make the PTEs present and to break COW.

[[email protected]: fix signedness bug in make_device_exclusive_range()]
Cc Ben Skeggs <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc John Hubbard <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Peter Xu <[email protected]>
Cc Ralph Campbell <[email protected]>
Cc Shakeel Butt <[email protected]>

---

 Documentation/vm/hmm.rst     |   17 +++
 include/linux/mmu_notifier.h |    6 +
 include/linux/rmap.h         |    4 
 include/linux/swap.h         |    9 +
 include/linux/swapops.h      |   44 +++++++
 mm/hmm.c                     |    5 
 mm/memory.c                  |  127 +++++++++++++++++++++-
 mm/mprotect.c                |    8 +
 mm/page_vma_mapped.c         |    9 +
 mm/rmap.c                    |  186 +++++++++++++++++++++++++++++++++
 10 files changed, 405 insertions(+), 10 deletions(-)
Documentation/vm/hmm.rst renamed from Documentation/vm/hmm.rst~mm-device-exclusive-memory-access +17 -0
@@ -405,6 +405,23 @@ between device driver specific code and
 
    The lock can now be released.
 
+Exclusive access memory
+=======================
+
+Some devices have features such as atomic PTE bits that can be used to implement
+atomic access to system memory. To support atomic operations to a shared virtual
+memory page such a device needs access to that page which is exclusive of any
+userspace access from the CPU. The ``make_device_exclusive_range()`` function
+can be used to make a memory range inaccessible from userspace.
+
+This replaces all mappings for pages in the given range with special swap
+entries. Any attempt to access the swap entry results in a fault which is
+resovled by replacing the entry with the original mapping. A driver gets
+notified that the mapping has been changed by MMU notifiers, after which point
+it will no longer have exclusive access to the page. Exclusive access is
+guranteed to last until the driver drops the page lock and page reference, at
+which point any CPU faults on the page may proceed as described.
+
 Memory cgroup (memcg) and rss accounting
 ========================================
 
include/linux/mmu_notifier.h renamed from include/linux/mmu_notifier.h~mm-device-exclusive-memory-access +6 -0
@@ -42,6 +42,11 @@ struct mmu_interval_notifier;
  * @MMU_NOTIFY_MIGRATE: used during migrate_vma_collect() invalidate to signal
  * a device driver to possibly ignore the invalidation if the
  * owner field matches the driver's device private pgmap owner.
+ *
+ * @MMU_NOTIFY_EXCLUSIVE: to signal a device driver that the device will no
+ * longer have exclusive access to the page. When sent during creation of an
+ * exclusive range the owner will be initialised to the value provided by the
+ * caller of make_device_exclusive_range(), otherwise the owner will be NULL.
  */
 enum mmu_notifier_event {
 	MMU_NOTIFY_UNMAP = 0,
@@ -51,6 +56,7 @@ enum mmu_notifier_event {
 	MMU_NOTIFY_SOFT_DIRTY,
 	MMU_NOTIFY_RELEASE,
 	MMU_NOTIFY_MIGRATE,
+	MMU_NOTIFY_EXCLUSIVE,
 };
 
 #define MMU_NOTIFIER_RANGE_BLOCKABLE (1 << 0)
include/linux/rmap.h renamed from include/linux/rmap.h~mm-device-exclusive-memory-access +4 -0
@@ -194,6 +194,10 @@ int page_referenced(struct page *, int i
 void try_to_migrate(struct page *page, enum ttu_flags flags);
 void try_to_unmap(struct page *, enum ttu_flags flags);
 
+int make_device_exclusive_range(struct mm_struct *mm, unsigned long start,
+				unsigned long end, struct page **pages,
+				void *arg);
+
 /* Avoid racy checks */
 #define PVMW_SYNC		(1 << 0)
 /* Look for migarion entries rather than present PTEs */
include/linux/swap.h renamed from include/linux/swap.h~mm-device-exclusive-memory-access +7 -2
@@ -62,12 +62,17 @@ static inline int current_is_kswapd(void
  * migrate part of a process memory to device memory.
  *
  * When a page is migrated from CPU to device, we set the CPU page table entry
- * to a special SWP_DEVICE_* entry.
+ * to a special SWP_DEVICE_{READ|WRITE} entry.
+ *
+ * When a page is mapped by the device for exclusive access we set the CPU page
+ * table entries to special SWP_DEVICE_EXCLUSIVE_* entries.
  */
 #ifdef CONFIG_DEVICE_PRIVATE
-#define SWP_DEVICE_NUM 2
+#define SWP_DEVICE_NUM 4
 #define SWP_DEVICE_WRITE (MAX_SWAPFILES+SWP_HWPOISON_NUM+SWP_MIGRATION_NUM)
 #define SWP_DEVICE_READ (MAX_SWAPFILES+SWP_HWPOISON_NUM+SWP_MIGRATION_NUM+1)
+#define SWP_DEVICE_EXCLUSIVE_WRITE (MAX_SWAPFILES+SWP_HWPOISON_NUM+SWP_MIGRATION_NUM+2)
+#define SWP_DEVICE_EXCLUSIVE_READ (MAX_SWAPFILES+SWP_HWPOISON_NUM+SWP_MIGRATION_NUM+3)
 #else
 #define SWP_DEVICE_NUM 0
 #endif
include/linux/swapops.h renamed from include/linux/swapops.h~mm-device-exclusive-memory-access +43 -1

62 lines not on this page · raw message

mm/hmm.c renamed from mm/hmm.c~mm-device-exclusive-memory-access +5 -0
@@ -26,6 +26,8 @@
 #include <linux/mmu_notifier.h>
 #include <linux/memory_hotplug.h>
 
+#include "internal.h"
+
 struct hmm_vma_walk {
 	struct hmm_range	*range;
 	unsigned long		last;
@@ -271,6 +273,9 @@ static int hmm_vma_handle_pte(struct mm_
 		if (!non_swap_entry(entry))
 			goto fault;
 
+		if (is_device_exclusive_entry(entry))
+			goto fault;
+
 		if (is_migration_entry(entry)) {
 			pte_unmap(ptep);
 			hmm_vma_walk->last = addr;
mm/memory.c renamed from mm/memory.c~mm-device-exclusive-memory-access +123 -4

176 lines not on this page · raw message

mm/mprotect.c renamed from mm/mprotect.c~mm-device-exclusive-memory-access +8 -0
@@ -165,6 +165,14 @@ static unsigned long change_pte_range(st
 				newpte = swp_entry_to_pte(entry);
 				if (pte_swp_uffd_wp(oldpte))
 					newpte = pte_swp_mkuffd_wp(newpte);
+			} else if (is_writable_device_exclusive_entry(entry)) {
+				entry = make_readable_device_exclusive_entry(
+							swp_offset(entry));
+				newpte = swp_entry_to_pte(entry);
+				if (pte_swp_soft_dirty(oldpte))
+					newpte = pte_swp_mksoft_dirty(newpte);
+				if (pte_swp_uffd_wp(oldpte))
+					newpte = pte_swp_mkuffd_wp(newpte);
 			} else {
 				newpte = oldpte;
 			}
mm/page_vma_mapped.c renamed from mm/page_vma_mapped.c~mm-device-exclusive-memory-access +6 -3
@@ -41,7 +41,8 @@ static bool map_pte(struct page_vma_mapp
 
 				/* Handle un-addressable ZONE_DEVICE memory */
 				entry = pte_to_swp_entry(*pvmw->pte);
-				if (!is_device_private_entry(entry))
+				if (!is_device_private_entry(entry) &&
+				    !is_device_exclusive_entry(entry))
 					return false;
 			} else if (!pte_present(*pvmw->pte))
 				return false;
@@ -93,7 +94,8 @@ static bool check_pte(struct page_vma_ma
 			return false;
 		entry = pte_to_swp_entry(*pvmw->pte);
 
-		if (!is_migration_entry(entry))
+		if (!is_migration_entry(entry) &&
+		    !is_device_exclusive_entry(entry))
 			return false;
 
 		pfn = swp_offset(entry);
@@ -102,7 +104,8 @@ static bool check_pte(struct page_vma_ma
 
 		/* Handle un-addressable ZONE_DEVICE memory */
 		entry = pte_to_swp_entry(*pvmw->pte);
-		if (!is_device_private_entry(entry))
+		if (!is_device_private_entry(entry) &&
+		    !is_device_exclusive_entry(entry))
 			return false;
 
 		pfn = swp_offset(entry);
mm/rmap.c renamed from mm/rmap.c~mm-device-exclusive-memory-access +186 -0

192 lines not on this page · raw message

_

author maintainer
#151 lore raw

PATCH 137/192 mm: selftests for exclusive device memory

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: mm: selftests for exclusive device memory

Adds some selftests for exclusive device memory.

---

 lib/test_hmm.c                         |  125 ++++++++++++++++++
 lib/test_hmm_uapi.h                    |    2 
 tools/testing/selftests/vm/hmm-tests.c |  158 +++++++++++++++++++++++
 3 files changed, 285 insertions(+)
lib/test_hmm.c renamed from lib/test_hmm.c~mm-selftests-for-exclusive-device-memory +125 -0
@@ -25,6 +25,7 @@
 #include <linux/swapops.h>
 #include <linux/sched/mm.h>
 #include <linux/platform_device.h>
+#include <linux/rmap.h>
 
 #include "test_hmm_uapi.h"
 
@@ -46,6 +47,7 @@ struct dmirror_bounce {
 	unsigned long		cpages;
 };
 
+#define DPT_XA_TAG_ATOMIC 1UL
 #define DPT_XA_TAG_WRITE 3UL
 
 /*
@@ -619,6 +621,54 @@ static void dmirror_migrate_alloc_and_co
 	}
 }
 
+static int dmirror_check_atomic(struct dmirror *dmirror, unsigned long start,
+			     unsigned long end)
+{
+	unsigned long pfn;
+
+	for (pfn = start >> PAGE_SHIFT; pfn < (end >> PAGE_SHIFT); pfn++) {
+		void *entry;
+		struct page *page;
+
+		entry = xa_load(&dmirror->pt, pfn);
+		page = xa_untag_pointer(entry);
+		if (xa_pointer_tag(entry) == DPT_XA_TAG_ATOMIC)
+			return -EPERM;
+	}
+
+	return 0;
+}
+
+static int dmirror_atomic_map(unsigned long start, unsigned long end,
+			      struct page **pages, struct dmirror *dmirror)
+{
+	unsigned long pfn, mapped = 0;
+	int i;
+
+	/* Map the migrated pages into the device's page tables. */
+	mutex_lock(&dmirror->mutex);
+
+	for (i = 0, pfn = start >> PAGE_SHIFT; pfn < (end >> PAGE_SHIFT); pfn++, i++) {
+		void *entry;
+
+		if (!pages[i])
+			continue;
+
+		entry = pages[i];
+		entry = xa_tag_pointer(entry, DPT_XA_TAG_ATOMIC);
+		entry = xa_store(&dmirror->pt, pfn, entry, GFP_ATOMIC);
+		if (xa_is_err(entry)) {
+			mutex_unlock(&dmirror->mutex);
+			return xa_err(entry);
+		}
+
+		mapped++;
+	}
+
+	mutex_unlock(&dmirror->mutex);
+	return mapped;
+}
+
 static int dmirror_migrate_finalize_and_map(struct migrate_vma *args,
 					    struct dmirror *dmirror)
 {
@@ -661,6 +711,72 @@ static int dmirror_migrate_finalize_and_
 	return 0;
 }
 
+static int dmirror_exclusive(struct dmirror *dmirror,
+			     struct hmm_dmirror_cmd *cmd)
+{
+	unsigned long start, end, addr;
+	unsigned long size = cmd->npages << PAGE_SHIFT;
+	struct mm_struct *mm = dmirror->notifier.mm;
+	struct page *pages[64];
+	struct dmirror_bounce bounce;
+	unsigned long next;
+	int ret;
+
+	start = cmd->addr;
+	end = start + size;
+	if (end < start)
+		return -EINVAL;
+
+	/* Since the mm is for the mirrored process, get a reference first. */
+	if (!mmget_not_zero(mm))
+		return -EINVAL;
+
+	mmap_read_lock(mm);
+	for (addr = start; addr < end; addr = next) {
+		unsigned long mapped;
+		int i;
+
+		if (end < addr + (ARRAY_SIZE(pages) << PAGE_SHIFT))
+			next = end;
+		else
+			next = addr + (ARRAY_SIZE(pages) << PAGE_SHIFT);
+
+		ret = make_device_exclusive_range(mm, addr, next, pages, NULL);
+		mapped = dmirror_atomic_map(addr, next, pages, dmirror);
+		for (i = 0; i < ret; i++) {
+			if (pages[i]) {
+				unlock_page(pages[i]);
+				put_page(pages[i]);
+			}
+		}
+
+		if (addr + (mapped << PAGE_SHIFT) < next) {
+			mmap_read_unlock(mm);
+			mmput(mm);
+			return -EBUSY;
+		}
+	}
+	mmap_read_unlock(mm);
+	mmput(mm);
+
+	/* Return the migrated data for verification. */
+	ret = dmirror_bounce_init(&bounce, start, size);
+	if (ret)
+		return ret;
+	mutex_lock(&dmirror->mutex);
+	ret = dmirror_do_read(dmirror, start, end, &bounce);
+	mutex_unlock(&dmirror->mutex);
+	if (ret == 0) {
+		if (copy_to_user(u64_to_user_ptr(cmd->ptr), bounce.ptr,
+				 bounce.size))
+			ret = -EFAULT;
+	}
+
+	cmd->cpages = bounce.cpages;
+	dmirror_bounce_fini(&bounce);
+	return ret;
+}
+
 static int dmirror_migrate(struct dmirror *dmirror,
 			   struct hmm_dmirror_cmd *cmd)
 {
@@ -948,6 +1064,15 @@ static long dmirror_fops_unlocked_ioctl(
 		ret = dmirror_migrate(dmirror, &cmd);
 		break;
 
+	case HMM_DMIRROR_EXCLUSIVE:
+		ret = dmirror_exclusive(dmirror, &cmd);
+		break;
+
+	case HMM_DMIRROR_CHECK_EXCLUSIVE:
+		ret = dmirror_check_atomic(dmirror, cmd.addr,
+					cmd.addr + (cmd.npages << PAGE_SHIFT));
+		break;
+
 	case HMM_DMIRROR_SNAPSHOT:
 		ret = dmirror_snapshot(dmirror, &cmd);
 		break;
lib/test_hmm_uapi.h renamed from lib/test_hmm_uapi.h~mm-selftests-for-exclusive-device-memory +2 -0
@@ -33,6 +33,8 @@ struct hmm_dmirror_cmd {
 #define HMM_DMIRROR_WRITE		_IOWR('H', 0x01, struct hmm_dmirror_cmd)
 #define HMM_DMIRROR_MIGRATE		_IOWR('H', 0x02, struct hmm_dmirror_cmd)
 #define HMM_DMIRROR_SNAPSHOT		_IOWR('H', 0x03, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_EXCLUSIVE		_IOWR('H', 0x04, struct hmm_dmirror_cmd)
+#define HMM_DMIRROR_CHECK_EXCLUSIVE	_IOWR('H', 0x05, struct hmm_dmirror_cmd)
 
 /*
  * Values returned in hmm_dmirror_cmd.ptr for HMM_DMIRROR_SNAPSHOT.
tools/testing/selftests/vm/hmm-tests.c renamed from tools/testing/selftests/vm/hmm-tests.c~mm-selftests-for-exclusive-device-memory +158 -0

162 lines not on this page · raw message

_

author maintainer
#152 lore raw

PATCH 138/192 nouveau/svm: refactor nouveau_range_fault

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: nouveau/svm: refactor nouveau_range_fault

Call mmu_interval_notifier_insert() as part of nouveau_range_fault(). This doesn't introduce any functional change but makes it easier for a subsequent patch to alter the behaviour of nouveau_range_fault() to support GPU atomic operations.

Cc Christoph Hellwig <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc John Hubbard <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Peter Xu <[email protected]>
Cc Ralph Campbell <[email protected]>
Cc Shakeel Butt <[email protected]>

---

 drivers/gpu/drm/nouveau/nouveau_svm.c |   34 ++++++++++++++----------
 1 file changed, 20 insertions(+), 14 deletions(-)
drivers/gpu/drm/nouveau/nouveau_svm.c renamed from drivers/gpu/drm/nouveau/nouveau_svm.c~nouveau-svm-refactor-nouveau_range_fault +20 -14
@@ -567,18 +567,27 @@ static int nouveau_range_fault(struct no
 	unsigned long hmm_pfns[1];
 	struct hmm_range range = {
 		.notifier = &notifier->notifier,
-		.start = notifier->notifier.interval_tree.start,
-		.end = notifier->notifier.interval_tree.last + 1,
 		.default_flags = hmm_flags,
 		.hmm_pfns = hmm_pfns,
 		.dev_private_owner = drm->dev,
 	};
-	struct mm_struct *mm = notifier->notifier.mm;
+	struct mm_struct *mm = svmm->notifier.mm;
 	int ret;
 
+	ret = mmu_interval_notifier_insert(&notifier->notifier, mm,
+					args->p.addr, args->p.size,
+					&nouveau_svm_mni_ops);
+	if (ret)
+		return ret;
+
+	range.start = notifier->notifier.interval_tree.start;
+	range.end = notifier->notifier.interval_tree.last + 1;
+
 	while (true) {
-		if (time_after(jiffies, timeout))
-			return -EBUSY;
+		if (time_after(jiffies, timeout)) {
+			ret = -EBUSY;
+			goto out;
+		}
 
 		range.notifier_seq = mmu_interval_read_begin(range.notifier);
 		mmap_read_lock(mm);
@@ -587,7 +596,7 @@ static int nouveau_range_fault(struct no
 		if (ret) {
 			if (ret == -EBUSY)
 				continue;
-			return ret;
+			goto out;
 		}
 
 		mutex_lock(&svmm->mutex);
@@ -606,6 +615,9 @@ static int nouveau_range_fault(struct no
 	svmm->vmm->vmm.object.client->super = false;
 	mutex_unlock(&svmm->mutex);
 
+out:
+	mmu_interval_notifier_remove(&notifier->notifier);
+
 	return ret;
 }
 
@@ -727,14 +739,8 @@ nouveau_svm_fault(struct nvif_notify *no
 		}
 
 		notifier.svmm = svmm;
-		ret = mmu_interval_notifier_insert(&notifier.notifier, mm,
-						   args.i.p.addr, args.i.p.size,
-						   &nouveau_svm_mni_ops);
-		if (!ret) {
-			ret = nouveau_range_fault(svmm, svm->drm, &args.i,
-				sizeof(args), hmm_flags, &notifier);
-			mmu_interval_notifier_remove(&notifier.notifier);
-		}
+		ret = nouveau_range_fault(svmm, svm->drm, &args.i,
+					sizeof(args), hmm_flags, &notifier);
 		mmput(mm);
 
 		limit = args.i.p.addr + args.i.p.size;

_

author maintainer
#153 lore raw

PATCH 139/192 nouveau/svm: implement atomic SVM access

In reply to Andrew Morton

From: Alistair Popple <[email protected]>
Subject: nouveau/svm: implement atomic SVM access

Some NVIDIA GPUs do not support direct atomic access to system memory via PCIe. Instead this must be emulated by granting the GPU exclusive access to the memory. This is achieved by replacing CPU page table entries with special swap entries that fault on userspace access.

The driver then grants the GPU permission to update the page undergoing atomic access via the GPU page tables. When CPU access to the page is required a CPU fault is raised which calls into the device driver via MMU notifiers to revoke the atomic access. The original page table entries are then restored allowing CPU access to proceed.

Cc Christoph Hellwig <[email protected]>
Cc Hugh Dickins <[email protected]>
Cc Jason Gunthorpe <[email protected]>
Cc John Hubbard <[email protected]>
Cc "Matthew Wilcox (Oracle)" <[email protected]>
Cc Peter Xu <[email protected]>
Cc Ralph Campbell <[email protected]>
Cc Shakeel Butt <[email protected]>

---

 drivers/gpu/drm/nouveau/include/nvif/if000c.h      |    1 
 drivers/gpu/drm/nouveau/nouveau_svm.c              |  126 ++++++++++-
 drivers/gpu/drm/nouveau/nvkm/subdev/mmu/vmm.h      |    1 
 drivers/gpu/drm/nouveau/nvkm/subdev/mmu/vmmgp100.c |    6 
 4 files changed, 123 insertions(+), 11 deletions(-)
drivers/gpu/drm/nouveau/include/nvif/if000c.h renamed from drivers/gpu/drm/nouveau/include/nvif/if000c.h~nouveau-svm-implement-atomic-svm-access +1 -0
@@ -77,6 +77,7 @@ struct nvif_vmm_pfnmap_v0 {
 #define NVIF_VMM_PFNMAP_V0_APER                           0x00000000000000f0ULL
 #define NVIF_VMM_PFNMAP_V0_HOST                           0x0000000000000000ULL
 #define NVIF_VMM_PFNMAP_V0_VRAM                           0x0000000000000010ULL
+#define NVIF_VMM_PFNMAP_V0_A				  0x0000000000000004ULL
 #define NVIF_VMM_PFNMAP_V0_W                              0x0000000000000002ULL
 #define NVIF_VMM_PFNMAP_V0_V                              0x0000000000000001ULL
 #define NVIF_VMM_PFNMAP_V0_NONE                           0x0000000000000000ULL
drivers/gpu/drm/nouveau/nouveau_svm.c renamed from drivers/gpu/drm/nouveau/nouveau_svm.c~nouveau-svm-implement-atomic-svm-access +115 -11

192 lines not on this page · raw message

drivers/gpu/drm/nouveau/nvkm/subdev/mmu/vmmgp100.c renamed from drivers/gpu/drm/nouveau/nvkm/subdev/mmu/vmmgp100.c~nouveau-svm-implement-atomic-svm-access +6 -0
@@ -88,6 +88,9 @@ gp100_vmm_pgt_pfn(struct nvkm_vmm *vmm,
 		if (!(*map->pfn & NVKM_VMM_PFN_W))
 			data |= BIT_ULL(6); /* RO. */
 
+		if (!(*map->pfn & NVKM_VMM_PFN_A))
+			data |= BIT_ULL(7); /* Atomic disable. */
+
 		if (!(*map->pfn & NVKM_VMM_PFN_VRAM)) {
 			addr = *map->pfn >> NVKM_VMM_PFN_ADDR_SHIFT;
 			addr = dma_map_page(dev, pfn_to_page(addr), 0,
@@ -322,6 +325,9 @@ gp100_vmm_pd0_pfn(struct nvkm_vmm *vmm,
 		if (!(*map->pfn & NVKM_VMM_PFN_W))
 			data |= BIT_ULL(6); /* RO. */
 
+		if (!(*map->pfn & NVKM_VMM_PFN_A))
+			data |= BIT_ULL(7); /* Atomic disable. */
+
 		if (!(*map->pfn & NVKM_VMM_PFN_VRAM)) {
 			addr = *map->pfn >> NVKM_VMM_PFN_ADDR_SHIFT;
 			addr = dma_map_page(dev, pfn_to_page(addr), 0,
drivers/gpu/drm/nouveau/nvkm/subdev/mmu/vmm.h renamed from drivers/gpu/drm/nouveau/nvkm/subdev/mmu/vmm.h~nouveau-svm-implement-atomic-svm-access +1 -0
@@ -178,6 +178,7 @@ void nvkm_vmm_unmap_region(struct nvkm_v
 #define NVKM_VMM_PFN_APER                                 0x00000000000000f0ULL
 #define NVKM_VMM_PFN_HOST                                 0x0000000000000000ULL
 #define NVKM_VMM_PFN_VRAM                                 0x0000000000000010ULL
+#define NVKM_VMM_PFN_A					  0x0000000000000004ULL
 #define NVKM_VMM_PFN_W                                    0x0000000000000002ULL
 #define NVKM_VMM_PFN_V                                    0x0000000000000001ULL
 #define NVKM_VMM_PFN_NONE                                 0x0000000000000000ULL

_

author maintainer
#154 lore raw

PATCH 140/192 proc: Avoid mixing integer types in mem_rw()

In reply to Andrew Morton

From: Marcelo Henrique Cerri <[email protected]>
Subject: proc: Avoid mixing integer types in mem_rw()

Use size_t when capping the count argument received by mem_rw(). Since count is size_t, using min_t(int, ...) can lead to a negative value that will later be passed to access_remote_vm(), which can cause unexpected behavior.

Since we are capping the value to at maximum PAGE_SIZE, the conversion from size_t to int when passing it to access_remote_vm() as "len" shouldn't be a problem.

---

 fs/proc/base.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/proc/base.c renamed from fs/proc/base.c~proc-avoid-mixing-integer-types-in-mem_rw +1 -1
@@ -854,7 +854,7 @@ static ssize_t mem_rw(struct file *file,
 	flags = FOLL_FORCE | (write ? FOLL_WRITE : 0);
 
 	while (count > 0) {
-		int this_len = min_t(int, count, PAGE_SIZE);
+		size_t this_len = min_t(size_t, count, PAGE_SIZE);
 
 		if (write && copy_from_user(page, buf, this_len)) {
 			copied = -EFAULT;

_

author maintainer
#155 lore raw

PATCH 141/192 fs/proc/kcore.c: add mmap interface

In reply to Andrew Morton

From: ZHOUFENG <[email protected]>
Subject: fs/proc/kcore.c: add mmap interface

When we do the kernel monitor, use the DRGN
(https://github.com/osandov/drgn) access to kernel data structures, found that the system calls a lot. DRGN is implemented by reading /proc/kcore. After looking at the kcore code, it is found that kcore does not implement mmap, resulting in frequent context switching triggered by read. Therefore, we want to add mmap interface to optimize performance. Since vmalloc and module areas will change with allocation and release, consistency cannot be guaranteed, so mmap interface only maps KCORE_TEXT and KCORE_RAM.

The test results:
1. the default version of kcore
real 11.00
user 8.53
sys 3.59

% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------
99.64 128.578319 12 11168701 pread64
...
------ ----------- ----------- --------- --------- ----------------
100.00 129.042853 11193748 966 total

2. added kcore for the mmap interface
real 6.44
user 7.32
sys 0.24

% time seconds usecs/call calls errors syscall
------ ----------- ----------- --------- --------- ----------------

32.94    0.130120          24      5317       315 futex
11.66    0.046077          21      2231         1 lstat
 9.23    0.036449         177       206           mmap

...
------ ----------- ----------- --------- --------- ----------------
100.00 0.395077 25435 971 total

The test results show that the number of system calls and time consumption are significantly reduced.

Thanks to Andrew Morton for your advice.

---

 fs/proc/kcore.c |   67 ++++++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 67 insertions(+)
fs/proc/kcore.c renamed from fs/proc/kcore.c~fs-proc-kcorec-add-mmap-interface +67 -0
@@ -614,11 +614,78 @@ static int release_kcore(struct inode *i
 	return 0;
 }
 
+static vm_fault_t mmap_kcore_fault(struct vm_fault *vmf)
+{
+	return VM_FAULT_SIGBUS;
+}
+
+static const struct vm_operations_struct kcore_mmap_ops = {
+	.fault = mmap_kcore_fault,
+};
+
+static int mmap_kcore(struct file *file, struct vm_area_struct *vma)
+{
+	size_t size = vma->vm_end - vma->vm_start;
+	u64 start, pfn;
+	int nphdr;
+	size_t data_offset;
+	size_t phdrs_len, notes_len;
+	struct kcore_list *m = NULL;
+	int ret = 0;
+
+	down_read(&kclist_lock);
+
+	get_kcore_size(&nphdr, &phdrs_len, &notes_len, &data_offset);
+
+	start = kc_offset_to_vaddr(((u64)vma->vm_pgoff << PAGE_SHIFT) -
+		((data_offset >> PAGE_SHIFT) << PAGE_SHIFT));
+
+	list_for_each_entry(m, &kclist_head, list) {
+		if (start >= m->addr && size <= m->size)
+			break;
+	}
+
+	if (&m->list == &kclist_head) {
+		ret = -EINVAL;
+		goto out;
+	}
+
+	if (vma->vm_flags & (VM_WRITE | VM_EXEC)) {
+		ret = -EPERM;
+		goto out;
+	}
+
+	vma->vm_flags &= ~(VM_MAYWRITE | VM_MAYEXEC);
+	vma->vm_flags |= VM_MIXEDMAP;
+	vma->vm_ops = &kcore_mmap_ops;
+
+	if (kern_addr_valid(start)) {
+		if (m->type == KCORE_RAM)
+			pfn = __pa(start) >> PAGE_SHIFT;
+		else if (m->type == KCORE_TEXT)
+			pfn = __pa_symbol(start) >> PAGE_SHIFT;
+		else {
+			ret = -EFAULT;
+			goto out;
+		}
+
+		ret = remap_pfn_range(vma, vma->vm_start, pfn, size,
+				vma->vm_page_prot);
+	} else {
+		ret = -EFAULT;
+	}
+
+out:
+	up_read(&kclist_lock);
+	return ret;
+}
+
 static const struct proc_ops kcore_proc_ops = {
 	.proc_read	= read_kcore,
 	.proc_open	= open_kcore,
 	.proc_release	= release_kcore,
 	.proc_lseek	= default_llseek,
+	.proc_mmap	= mmap_kcore,
 };
 
 /* just remember that we have to update kcore */

_

#156 lore raw

Re: [patch 141/192] fs/proc/kcore.c: add mmap interface

Quoted 6 lines · Andrew Morton

When we do the kernel monitor, use the DRGN
(https://github.com/osandov/drgn) access to kernel data structures, found that the system calls a lot. DRGN is implemented by reading /proc/kcore. After looking at the kcore code, it is found that kcore does not implement mmap, resulting in frequent context switching triggered by read. Therefore, we want to add mmap interface to optimize performance.

Ok, this is funky, but I'm going to drop this patch because I think it's buggy as is.

Since

fs/proc/kcore.c static int release_kcore(struct inode *i · line 628

Quoted 3 lines
fs/proc/kcore.c renamed from fs/proc/kcore.c~fs-proc-kcorec-add-mmap-interface +3 -0
+static int mmap_kcore(struct file *file, struct vm_area_struct *vma)
+{
+       size_t size = vma->vm_end - vma->vm_start;

Ok.

But then:

fs/proc/kcore.c static int release_kcore(struct inode *i · line 641

Quoted 2 lines
fs/proc/kcore.c renamed from fs/proc/kcore.c~fs-proc-kcorec-add-mmap-interface +2 -0
+       start = kc_offset_to_vaddr(((u64)vma->vm_pgoff << PAGE_SHIFT) -
+               ((data_offset >> PAGE_SHIFT) << PAGE_SHIFT));

Not only is that

        ((data_offset >> PAGE_SHIFT) << PAGE_SHIFT)

a very strange calculation (did you mean "data_offset & PAGE_MASK"?), but I don't see anything that protects against underflow in that calculation. pg_off can easily be arbitrarily small (eg zero), so that subtraction can underflow afaik.

So that needs a test, and return -EINVAL or whatever.

But even if that is fixed, this test is entirely broken:

fs/proc/kcore.c static int release_kcore(struct inode *i · line 646

Quoted 4 lines
fs/proc/kcore.c renamed from fs/proc/kcore.c~fs-proc-kcorec-add-mmap-interface +4 -0
+       list_for_each_entry(m, &kclist_head, list) {
+               if (start >= m->addr && size <= m->size)
+                       break;
+       }

No, that's wrong.

You allow 'size' to be as big as 'm->size', but you do that even if 'start' isn't 'm->start'.

The proper check would be something like

       u64 end = start + size;

        if (start >= m->addr && end <= m->addr+m->size) ..

or similar (and that should check that "start+size" hasn't overflowed).

So I see what appears to be multiple problems, and while I hand-waved some fixes for them, those are very much "maybe something like this", and I'm going to drop this patch. Not for 5.14.

Linus

#157 lore raw

Re: [External] Re: [patch 141/192] fs/proc/kcore.c: add mmap interface

Quoted 24 lines · Linus Torvalds
Quoted 6 lines · Andrew Morton

When we do the kernel monitor, use the DRGN
(https://github.com/osandov/drgn) access to kernel data structures, found that the system calls a lot. DRGN is implemented by reading /proc/kcore. After looking at the kcore code, it is found that kcore does not implement mmap, resulting in frequent context switching triggered by read. Therefore, we want to add mmap interface to optimize performance.

Ok, this is funky, but I'm going to drop this patch because I think it's buggy as is.

Since

fs/proc/kcore.c static int release_kcore(struct inode *i · line 628

Quoted 3 lines
fs/proc/kcore.c renamed from fs/proc/kcore.c~fs-proc-kcorec-add-mmap-interface +3 -0
+static int mmap_kcore(struct file *file, struct vm_area_struct *vma)
+{
+       size_t size = vma->vm_end - vma->vm_start;

Ok.

But then:

fs/proc/kcore.c static int release_kcore(struct inode *i · line 641

Quoted 2 lines
fs/proc/kcore.c renamed from fs/proc/kcore.c~fs-proc-kcorec-add-mmap-interface +2 -0
+       start = kc_offset_to_vaddr(((u64)vma->vm_pgoff << PAGE_SHIFT) -
+               ((data_offset >> PAGE_SHIFT) << PAGE_SHIFT));
Quoted 8 lines

Not only is that

         ((data_offset >> PAGE_SHIFT) << PAGE_SHIFT)

a very strange calculation (did you mean "data_offset & PAGE_MASK"?), but I don't see anything that protects against underflow in that calculation. pg_off can easily be arbitrarily small (eg zero), so that subtraction can underflow afaik.

Sorry, the calculations here are really confusing. The reason is that when DRGN read /proc/kcore for ELF file header:
phdr->p_offset = kc_vaddr_to_offset(m->addr) + data_offset;
and DRGN call mmap, use phdr->p_offset passed in, I need to subtract "data_offset".

Quoted 3 lines

So that needs a test, and return -EINVAL or whatever.

There's a problem with not judging "start". I will fix it in a v3.

Quoted 9 lines

But even if that is fixed, this test is entirely broken:

fs/proc/kcore.c static int release_kcore(struct inode *i · line 646

Quoted 4 lines
fs/proc/kcore.c renamed from fs/proc/kcore.c~fs-proc-kcorec-add-mmap-interface +4 -0
+       list_for_each_entry(m, &kclist_head, list) {
+               if (start >= m->addr && size <= m->size)
+                       break;
+       }

No, that's wrong.

Yes, this is indeed wrong, I will fix it in a v3.

Quoted 17 lines

You allow 'size' to be as big as 'm->size', but you do that even if 'start' isn't 'm->start'.

The proper check would be something like

        u64 end = start + size;

         if (start >= m->addr && end <= m->addr+m->size) ..

or similar (and that should check that "start+size" hasn't overflowed).

So I see what appears to be multiple problems, and while I hand-waved some fixes for them, those are very much "maybe something like this", and I'm going to drop this patch. Not for 5.14.

Linus

author maintainer
#158 lore raw

PATCH 142/192 procfs: allow reading fdinfo with PTRACE_MODE_READ

In reply to Andrew Morton

From: Kalesh Singh <[email protected]>
Subject: procfs: allow reading fdinfo with PTRACE_MODE_READ

Android captures per-process system memory state when certain low memory events (e.g a foreground app kill) occur, to identify potential memory hoggers. In order to measure how much memory a process actually consumes, it is necessary to include the DMA buffer sizes for that process in the memory accounting. Since the handle to DMA buffers are raw FDs, it is important to be able to identify which processes have FD references to a DMA buffer.

Currently, DMA buffer FDs can be accounted using /proc/<pid>/fd/* and /proc/<pid>/fdinfo -- both are only readable by the process owner, as follows:

1. Do a readlink on each FD.
2. If the target path begins with "/dmabuf", then the FD is a dmabuf FD.
3. stat the file to get the dmabuf inode number.
4. Read/ proc/<pid>/fdinfo/<fd>, to get the DMA buffer size.

Accessing other processes' fdinfo requires root privileges. This limits the use of the interface to debugging environments and is not suitable for production builds. Granting root privileges even to a system process increases the attack surface and is highly undesirable.

Since fdinfo doesn't permit reading process memory and manipulating process state, allow accessing fdinfo under PTRACE_MODE_READ_FSCRED.

Cc Alexander Viro <[email protected]>
Cc Alexey Dobriyan <[email protected]>
Cc Alexey Gladkov <[email protected]>
Cc Andrei Vagin <[email protected]>
Cc Bernd Edlinger <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Eric W. Biederman <[email protected]>
Cc Helge Deller <[email protected]>
Cc Hridya Valsaraju <[email protected]>
Cc James Morris <[email protected]>
Cc Jeff Vander Stoep <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Kees Cook <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Mauro Carvalho Chehab <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michel Lespinasse <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Szabolcs Nagy <[email protected]>

---

 fs/proc/base.c |    4 ++--
 fs/proc/fd.c   |   15 ++++++++++++++-
 2 files changed, 16 insertions(+), 3 deletions(-)
fs/proc/base.c renamed from fs/proc/base.c~procfs-allow-reading-fdinfo-with-ptrace_mode_read +2 -2
@@ -3172,7 +3172,7 @@ static const struct pid_entry tgid_base_
 	DIR("task",       S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
 	DIR("fd",         S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
 	DIR("map_files",  S_IRUSR|S_IXUSR, proc_map_files_inode_operations, proc_map_files_operations),
-	DIR("fdinfo",     S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
+	DIR("fdinfo",     S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
 	DIR("ns",	  S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
 #ifdef CONFIG_NET
 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
@@ -3517,7 +3517,7 @@ static const struct inode_operations pro
  */
 static const struct pid_entry tid_base_stuff[] = {
 	DIR("fd",        S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
-	DIR("fdinfo",    S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
+	DIR("fdinfo",    S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
 	DIR("ns",	 S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
 #ifdef CONFIG_NET
 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
fs/proc/fd.c renamed from fs/proc/fd.c~procfs-allow-reading-fdinfo-with-ptrace_mode_read +14 -1
@@ -6,6 +6,7 @@
 #include <linux/fdtable.h>
 #include <linux/namei.h>
 #include <linux/pid.h>
+#include <linux/ptrace.h>
 #include <linux/security.h>
 #include <linux/file.h>
 #include <linux/seq_file.h>
@@ -72,6 +73,18 @@ out:
 
 static int seq_fdinfo_open(struct inode *inode, struct file *file)
 {
+	bool allowed = false;
+	struct task_struct *task = get_proc_task(inode);
+
+	if (!task)
+		return -ESRCH;
+
+	allowed = ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS);
+	put_task_struct(task);
+
+	if (!allowed)
+		return -EACCES;
+
 	return single_open(file, seq_show, inode);
 }
 
@@ -308,7 +321,7 @@ static struct dentry *proc_fdinfo_instan
 	struct proc_inode *ei;
 	struct inode *inode;
 
-	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFREG | S_IRUSR);
+	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFREG | S_IRUGO);
 	if (!inode)
 		return ERR_PTR(-ENOENT);
 

_

Acked-by on v1 142/192
#159 lore raw

Re: [patch 142/192] procfs: allow reading fdinfo with PTRACE_MODE_READ

Quoted 54 lines · Andrew Morton

From: Kalesh Singh <[email protected]>
Subject: procfs: allow reading fdinfo with PTRACE_MODE_READ

Android captures per-process system memory state when certain low memory events (e.g a foreground app kill) occur, to identify potential memory hoggers. In order to measure how much memory a process actually consumes, it is necessary to include the DMA buffer sizes for that process in the memory accounting. Since the handle to DMA buffers are raw FDs, it is important to be able to identify which processes have FD references to a DMA buffer.

Currently, DMA buffer FDs can be accounted using /proc/<pid>/fd/* and /proc/<pid>/fdinfo -- both are only readable by the process owner, as follows:

1. Do a readlink on each FD.
2. If the target path begins with "/dmabuf", then the FD is a dmabuf FD.
3. stat the file to get the dmabuf inode number.
4. Read/ proc/<pid>/fdinfo/<fd>, to get the DMA buffer size.

Accessing other processes' fdinfo requires root privileges. This limits the use of the interface to debugging environments and is not suitable for production builds. Granting root privileges even to a system process increases the attack surface and is highly undesirable.

Since fdinfo doesn't permit reading process memory and manipulating process state, allow accessing fdinfo under PTRACE_MODE_READ_FSCRED.

Cc Alexander Viro <[email protected]>
Cc Alexey Dobriyan <[email protected]>
Cc Alexey Gladkov <[email protected]>
Cc Andrei Vagin <[email protected]>
Cc Bernd Edlinger <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Eric W. Biederman <[email protected]>
Cc Helge Deller <[email protected]>
Cc Hridya Valsaraju <[email protected]>
Cc James Morris <[email protected]>
Cc Jeff Vander Stoep <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Kees Cook <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Mauro Carvalho Chehab <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michel Lespinasse <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Szabolcs Nagy <[email protected]>
Quoted 1 line

---

Rather useful (also for CRIU and others).

#160 lore raw

Re: [patch 142/192] procfs: allow reading fdinfo with PTRACE_MODE_READ

In reply to Andrew Morton
Quoted 95 lines · Andrew Morton

From: Kalesh Singh <[email protected]>
Subject: procfs: allow reading fdinfo with PTRACE_MODE_READ

Android captures per-process system memory state when certain low memory events (e.g a foreground app kill) occur, to identify potential memory hoggers. In order to measure how much memory a process actually consumes, it is necessary to include the DMA buffer sizes for that process in the memory accounting. Since the handle to DMA buffers are raw FDs, it is important to be able to identify which processes have FD references to a DMA buffer.

Currently, DMA buffer FDs can be accounted using /proc/<pid>/fd/* and /proc/<pid>/fdinfo -- both are only readable by the process owner, as follows:

1. Do a readlink on each FD.
2. If the target path begins with "/dmabuf", then the FD is a dmabuf FD.
3. stat the file to get the dmabuf inode number.
4. Read/ proc/<pid>/fdinfo/<fd>, to get the DMA buffer size.

Accessing other processes' fdinfo requires root privileges. This limits the use of the interface to debugging environments and is not suitable for production builds. Granting root privileges even to a system process increases the attack surface and is highly undesirable.

Since fdinfo doesn't permit reading process memory and manipulating process state, allow accessing fdinfo under PTRACE_MODE_READ_FSCRED.

Cc Alexander Viro <[email protected]>
Cc Alexey Dobriyan <[email protected]>
Cc Alexey Gladkov <[email protected]>
Cc Andrei Vagin <[email protected]>
Cc Bernd Edlinger <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Eric W. Biederman <[email protected]>
Cc Helge Deller <[email protected]>
Cc Hridya Valsaraju <[email protected]>
Cc James Morris <[email protected]>
Cc Jeff Vander Stoep <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Kees Cook <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Mauro Carvalho Chehab <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michel Lespinasse <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Randy Dunlap <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Szabolcs Nagy <[email protected]>

---

 fs/proc/base.c |    4 ++--
 fs/proc/fd.c   |   15 ++++++++++++++-
 2 files changed, 16 insertions(+), 3 deletions(-)
fs/proc/base.c renamed from fs/proc/base.c~procfs-allow-reading-fdinfo-with-ptrace_mode_read +2 -2
@@ -3172,7 +3172,7 @@ static const struct pid_entry tgid_base_
 	DIR("task",       S_IRUGO|S_IXUGO, proc_task_inode_operations, proc_task_operations),
 	DIR("fd",         S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
 	DIR("map_files",  S_IRUSR|S_IXUSR, proc_map_files_inode_operations, proc_map_files_operations),
-	DIR("fdinfo",     S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
+	DIR("fdinfo",     S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
 	DIR("ns",	  S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
 #ifdef CONFIG_NET
 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
@@ -3517,7 +3517,7 @@ static const struct inode_operations pro
  */
 static const struct pid_entry tid_base_stuff[] = {
 	DIR("fd",        S_IRUSR|S_IXUSR, proc_fd_inode_operations, proc_fd_operations),
-	DIR("fdinfo",    S_IRUSR|S_IXUSR, proc_fdinfo_inode_operations, proc_fdinfo_operations),
+	DIR("fdinfo",    S_IRUGO|S_IXUGO, proc_fdinfo_inode_operations, proc_fdinfo_operations),
 	DIR("ns",	 S_IRUSR|S_IXUGO, proc_ns_dir_inode_operations, proc_ns_dir_operations),
 #ifdef CONFIG_NET
 	DIR("net",        S_IRUGO|S_IXUGO, proc_net_inode_operations, proc_net_operations),
fs/proc/fd.c renamed from fs/proc/fd.c~procfs-allow-reading-fdinfo-with-ptrace_mode_read +2 -0
@@ -6,6 +6,7 @@
 #include <linux/fdtable.h>
 #include <linux/namei.h>
 #include <linux/pid.h>
+#include <linux/ptrace.h>
 #include <linux/security.h>
 #include <linux/file.h>
 #include <linux/seq_file.h>
@@ -72,6 +73,18 @@ out:
 
 static int seq_fdinfo_open(struct inode *inode, struct file *file)
 {
+	bool allowed = false;

fs/proc/fd.c out: · line 86

Quoted 10 lines
fs/proc/fd.c renamed from fs/proc/fd.c~procfs-allow-reading-fdinfo-with-ptrace_mode_read +10 -0
+	struct task_struct *task = get_proc_task(inode);
+
+	if (!task)
+		return -ESRCH;
+
+	allowed = ptrace_may_access(task, PTRACE_MODE_READ_FSCREDS);
+	put_task_struct(task);
+
+	if (!allowed)
+		return -EACCES;

Uhm, this is only checked in open(), and never again? Is this safe in the face of exec or pid re-use?

-Kees

Quoted 14 lines
fs/proc/fd.c renamed from fs/proc/fd.c~procfs-allow-reading-fdinfo-with-ptrace_mode_read +2 -1
+
 	return single_open(file, seq_show, inode);
 }
 
@@ -308,7 +321,7 @@ static struct dentry *proc_fdinfo_instan
 	struct proc_inode *ei;
 	struct inode *inode;
 
-	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFREG | S_IRUSR);
+	inode = proc_pid_make_inode(dentry->d_sb, task, S_IFREG | S_IRUGO);
 	if (!inode)
 		return ERR_PTR(-ENOENT);
 

_

Signature · 1 line
Kees Cook
#161 lore raw

Re: [patch 142/192] procfs: allow reading fdinfo with PTRACE_MODE_READ

Quoted 3 lines · Kees Cook

Uhm, this is only checked in open(), and never again? Is this safe in the face of exec or pid re-use?

Interesting question, but not really all that valid for this particular patch.

Why? Because we already only check for owner permissions on open, and never again. So if we have fdinfo issues across a suid exec or pid re-use, they are pre-existing..

But yes, it would probably be a good idea to think about readdir() on that directory. If somebody reminds me after the merge window is over, I'll come back to this, but if somebody else wants to think about it before then, that would be great.

Linus

#162 lore raw

Re: [patch 142/192] procfs: allow reading fdinfo with PTRACE_MODE_READ

Quoted 4 lines · Linus Torvalds
Quoted 3 lines · Kees Cook

Uhm, this is only checked in open(), and never again? Is this safe in the face of exec or pid re-use?

Exec does not change the file descriptor table.

The open holds a reference to the proc inode. The proc inode holds the struct pid of the task and the file descriptor number. References using struct pid do not suffer from userspace pid rollover issues.

So the only issue I see is file descriptor reuse after an exec, that changes the processes struct cred.

Assuming we care it would probably be worth a bug fix patch to check something.

Eric

#163 lore raw

Re: [patch 142/192] procfs: allow reading fdinfo with PTRACE_MODE_READ

Quoted 8 lines · Eric W. Biederman
Quoted 4 lines · Linus Torvalds
Quoted 3 lines · Kees Cook

Uhm, this is only checked in open(), and never again? Is this safe in the face of exec or pid re-use?

Exec does not change the file descriptor table.

Ah yeah, good point. I've been thinking too much about vmas.

Quoted 3 lines

The open holds a reference to the proc inode. The proc inode holds the struct pid of the task and the file descriptor number. References using struct pid do not suffer from userspace pid rollover issues.

Okay, cool.

Quoted 2 lines

So the only issue I see is file descriptor reuse after an exec, that changes the processes struct cred.

Right -- the info leak would be snooping on what a privileged process was doing with a given fd? Similar stuff has been used to do typing pattern analysis with login passwords, but that's a stretch here, I think. Hmm.

Quoted 2 lines

Assuming we care it would probably be worth a bug fix patch to check something.

Sounds good.

Signature · 1 line
Kees Cook
#164 lore raw

Re: [patch 142/192] procfs: allow reading fdinfo with PTRACE_MODE_READ

Quoted 5 lines · Kees Cook

Right -- the info leak would be snooping on what a privileged process was doing with a given fd? Similar stuff has been used to do typing pattern analysis with login passwords, but that's a stretch here, I think. Hmm.

So I think you'd see the directory list, but generally that's just the file descriptor numbers.

Which is information you shouldn't have access to, but it's probably not very *interesting* information.

I think it would be worth fixing but possibly not a very high priority.

Linus

#165 lore raw

Re: [patch 142/192] procfs: allow reading fdinfo with PTRACE_MODE_READ

Quoted 7 lines · Linus Torvalds
Quoted 5 lines · Kees Cook

Right -- the info leak would be snooping on what a privileged process was doing with a given fd? Similar stuff has been used to do typing pattern analysis with login passwords, but that's a stretch here, I think. Hmm.

Quoted 8 lines

So I think you'd see the directory list, but generally that's just the file descriptor numbers.

Which is information you shouldn't have access to, but it's probably not very *interesting* information.

I think it would be worth fixing but possibly not a very high priority.

It is not just the directory whose permission changed but the individual files in that directory.

You can also see the position, flags, mnt_id, and soon inode number of fdinfo files you open before a suid exec.

Knowing what file someone is reading on a particular file descriptor number and how far they are in reading that file sounds like a side channel someone can do something with.

Eric

author maintainer
#166 lore raw

PATCH 143/192 procfs/dmabuf: add inode number to /proc/*/fdinfo

In reply to Andrew Morton

From: Kalesh Singh <[email protected]>
Subject: procfs/dmabuf: add inode number to /proc/*/fdinfo

And 'ino' field to /proc/<pid>/fdinfo/<FD> and
/proc/<pid>/task/<tid>/fdinfo/<FD>.

The inode numbers can be used to uniquely identify DMA buffers in user space and avoids a dependency on /proc/<pid>/fd/* when accounting per-process DMA buffer sizes.

Cc Jann Horn <[email protected]>
Cc Jeff Vander Stoep <[email protected]>
Cc Kees Cook <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Minchan Kim <[email protected]>
Cc Hridya Valsaraju <[email protected]>
Cc Matthew Wilcox <[email protected]>
Cc Alexander Viro <[email protected]>
Cc Kalesh Singh <[email protected]>
Cc Alexey Dobriyan <[email protected]>
Cc Jonathan Corbet <[email protected]>
Cc Mauro Carvalho Chehab <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Alexey Gladkov <[email protected]>
Cc Szabolcs Nagy <[email protected]>
Cc Eric W. Biederman <[email protected]>
Cc Christian Brauner <[email protected]>
Cc Michel Lespinasse <[email protected]>
Cc Bernd Edlinger <[email protected]>
Cc Andrei Vagin <[email protected]>
Cc Helge Deller <[email protected]>
Cc James Morris <[email protected]>

---

 Documentation/filesystems/proc.rst |   37 ++++++++++++++++++++++-----
 fs/proc/fd.c                       |    5 ++-
 2 files changed, 34 insertions(+), 8 deletions(-)
Documentation/filesystems/proc.rst renamed from Documentation/filesystems/proc.rst~procfs-dmabuf-add-inode-number-to-proc-fdinfo +31 -6
@@ -1920,18 +1920,20 @@ if precise results are needed.
 3.8	/proc/<pid>/fdinfo/<fd> - Information about opened file
 ---------------------------------------------------------------
 This file provides information associated with an opened file. The regular
-files have at least three fields -- 'pos', 'flags' and 'mnt_id'. The 'pos'
-represents the current offset of the opened file in decimal form [see lseek(2)
-for details], 'flags' denotes the octal O_xxx mask the file has been
-created with [see open(2) for details] and 'mnt_id' represents mount ID of
-the file system containing the opened file [see 3.5 /proc/<pid>/mountinfo
-for details].
+files have at least four fields -- 'pos', 'flags', 'mnt_id' and 'ino'.
+The 'pos' represents the current offset of the opened file in decimal
+form [see lseek(2) for details], 'flags' denotes the octal O_xxx mask the
+file has been created with [see open(2) for details] and 'mnt_id' represents
+mount ID of the file system containing the opened file [see 3.5
+/proc/<pid>/mountinfo for details]. 'ino' represents the inode number of
+the file.
 
 A typical output is::
 
 	pos:	0
 	flags:	0100002
 	mnt_id:	19
+	ino:	63107
 
 All locks associated with a file descriptor are shown in its fdinfo too::
 
@@ -1948,6 +1950,7 @@ Eventfd files
 	pos:	0
 	flags:	04002
 	mnt_id:	9
+	ino:	63107
 	eventfd-count:	5a
 
 where 'eventfd-count' is hex value of a counter.
@@ -1960,6 +1963,7 @@ Signalfd files
 	pos:	0
 	flags:	04002
 	mnt_id:	9
+	ino:	63107
 	sigmask:	0000000000000200
 
 where 'sigmask' is hex value of the signal mask associated
@@ -1973,6 +1977,7 @@ Epoll files
 	pos:	0
 	flags:	02
 	mnt_id:	9
+	ino:	63107
 	tfd:        5 events:       1d data: ffffffffffffffff pos:0 ino:61af sdev:7
 
 where 'tfd' is a target file descriptor number in decimal form,
@@ -1989,6 +1994,8 @@ For inotify files the format is the foll
 
 	pos:	0
 	flags:	02000000
+	mnt_id:	9
+	ino:	63107
 	inotify wd:3 ino:9e7e sdev:800013 mask:800afce ignored_mask:0 fhandle-bytes:8 fhandle-type:1 f_handle:7e9e0000640d1b6d
 
 where 'wd' is a watch descriptor in decimal form, i.e. a target file
@@ -2011,6 +2018,7 @@ For fanotify files the format is::
 	pos:	0
 	flags:	02
 	mnt_id:	9
+	ino:	63107
 	fanotify flags:10 event-flags:0
 	fanotify mnt_id:12 mflags:40 mask:38 ignored_mask:40000003
 	fanotify ino:4f969 sdev:800013 mflags:0 mask:3b ignored_mask:40000000 fhandle-bytes:8 fhandle-type:1 f_handle:69f90400c275b5b4
@@ -2035,6 +2043,7 @@ Timerfd files
 	pos:	0
 	flags:	02
 	mnt_id:	9
+	ino:	63107
 	clockid: 0
 	ticks: 0
 	settime flags: 01
@@ -2049,6 +2058,22 @@ details]. 'it_value' is remaining time u
 with TIMER_ABSTIME option which will be shown in 'settime flags', but 'it_value'
 still exhibits timer's remaining time.
 
+DMA Buffer files
+~~~~~~~~~~~~~~~~
+
+::
+
+	pos:	0
+	flags:	04002
+	mnt_id:	9
+	ino:	63107
+	size:   32768
+	count:  2
+	exp_name:  system-heap
+
+where 'size' is the size of the DMA buffer in bytes. 'count' is the file count of
+the DMA buffer file. 'exp_name' is the name of the DMA buffer exporter.
+
 3.9	/proc/<pid>/map_files - Information about memory mapped files
 ---------------------------------------------------------------------
 This directory contains symbolic links which represent memory mapped files
fs/proc/fd.c renamed from fs/proc/fd.c~procfs-dmabuf-add-inode-number-to-proc-fdinfo +3 -2
@@ -54,9 +54,10 @@ static int seq_show(struct seq_file *m,
 	if (ret)
 		return ret;
 
-	seq_printf(m, "pos:\t%lli\nflags:\t0%o\nmnt_id:\t%i\n",
+	seq_printf(m, "pos:\t%lli\nflags:\t0%o\nmnt_id:\t%i\nino:\t%lu\n",
 		   (long long)file->f_pos, f_flags,
-		   real_mount(file->f_path.mnt)->mnt_id);
+		   real_mount(file->f_path.mnt)->mnt_id,
+		   file_inode(file)->i_ino);
 
 	/* show_fd_locks() never deferences files so a stale value is safe */
 	show_fd_locks(m, file, files);

_

author maintainer
#167 lore raw

PATCH 144/192 sysctl: remove redundant assignment to first

In reply to Andrew Morton

From: Jiapeng Chong <[email protected]>
Subject: sysctl: remove redundant assignment to first

Variable first is set to '0', but this value is never read as it is not used later on, hence it is a redundant assignment and can be removed.

Clean up the following clang-analyzer warning:

kernel/sysctl.c:1562:4: warning: Value stored to 'first' is never read [clang-analyzer-deadcode.DeadStores].

---

 kernel/sysctl.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
kernel/sysctl.c renamed from kernel/sysctl.c~sysctl-remove-redundant-assignment-to-first +1 -2
@@ -1494,7 +1494,6 @@ int proc_do_large_bitmap(struct ctl_tabl
 			 void *buffer, size_t *lenp, loff_t *ppos)
 {
 	int err = 0;
-	bool first = 1;
 	size_t left = *lenp;
 	unsigned long bitmap_len = table->maxlen;
 	unsigned long *bitmap = *(unsigned long **) table->data;
@@ -1579,12 +1578,12 @@ int proc_do_large_bitmap(struct ctl_tabl
 			}
 
 			bitmap_set(tmp_bitmap, val_a, val_b - val_a + 1);
-			first = 0;
 			proc_skip_char(&p, &left, '\n');
 		}
 		left += skipped;
 	} else {
 		unsigned long bit_a, bit_b = 0;
+		bool first = 1;
 
 		while (left) {
 			bit_a = find_next_bit(bitmap, bitmap_len, bit_b);

_

author maintainer
#168 lore raw

PATCH 145/192 drm: include only needed headers in ascii85.h

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: drm: include only needed headers in ascii85.h

The ascii85.h is user of exactly two headers, i.e. math.h and types.h. There is no need to carry on entire kernel.h.

---

 include/linux/ascii85.h |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/ascii85.h renamed from include/linux/ascii85.h~drm-include-only-needed-headers-in-ascii85h +2 -1
@@ -8,7 +8,8 @@
 #ifndef _ASCII85_H_
 #define _ASCII85_H_
 
-#include <linux/kernel.h>
+#include <linux/math.h>
+#include <linux/types.h>
 
 #define ASCII85_BUFSZ 6
 

_

author maintainer
#169 lore raw

PATCH 146/192 kernel.h: split out panic and oops helpers

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: kernel.h: split out panic and oops helpers

kernel.h is being used as a dump for all kinds of stuff for a long time. Here is the attempt to start cleaning it up by splitting out panic and oops helpers.

There are several purposes of doing this:
- dropping dependency in bug.h
- dropping a loop by moving out panic_notifier.h
- unload kernel.h from something which has its own domain

At the same time convert users tree-wide to use new headers, although for the time being include new header back to kernel.h to avoid twisted indirected includes for existing users.

---

 arch/alpha/kernel/setup.c                         |    2 
 arch/arm64/kernel/setup.c                         |    1 
 arch/ia64/include/asm/pal.h                       |    1 
 arch/mips/kernel/relocate.c                       |    1 
 arch/mips/sgi-ip22/ip22-reset.c                   |    1 
 arch/mips/sgi-ip32/ip32-reset.c                   |    1 
 arch/parisc/kernel/pdc_chassis.c                  |    1 
 arch/powerpc/kernel/setup-common.c                |    1 
 arch/s390/kernel/ipl.c                            |    1 
 arch/sparc/kernel/sstate.c                        |    1 
 arch/um/drivers/mconsole_kern.c                   |    1 
 arch/um/kernel/um_arch.c                          |    1 
 arch/x86/include/asm/desc.h                       |    1 
 arch/x86/kernel/cpu/mshyperv.c                    |    1 
 arch/x86/kernel/setup.c                           |    1 
 arch/x86/purgatory/purgatory.c                    |    2 
 arch/x86/xen/enlighten.c                          |    1 
 arch/xtensa/platforms/iss/setup.c                 |    1 
 drivers/bus/brcmstb_gisb.c                        |    1 
 drivers/char/ipmi/ipmi_msghandler.c               |    1 
 drivers/clk/analogbits/wrpll-cln28hpc.c           |    4 
 drivers/edac/altera_edac.c                        |    1 
 drivers/firmware/google/gsmi.c                    |    1 
 drivers/hv/vmbus_drv.c                            |    1 
 drivers/hwtracing/coresight/coresight-cpu-debug.c |    1 
 drivers/leds/trigger/ledtrig-activity.c           |    1 
 drivers/leds/trigger/ledtrig-heartbeat.c          |    1 
 drivers/leds/trigger/ledtrig-panic.c              |    1 
 drivers/misc/bcm-vk/bcm_vk_dev.c                  |    1 
 drivers/misc/ibmasm/heartbeat.c                   |    1 
 drivers/misc/pvpanic/pvpanic.c                    |    1 
 drivers/net/ipa/ipa_smp2p.c                       |    1 
 drivers/parisc/power.c                            |    1 
 drivers/power/reset/ltc2952-poweroff.c            |    1 
 drivers/remoteproc/remoteproc_core.c              |    1 
 drivers/s390/char/con3215.c                       |    1 
 drivers/s390/char/con3270.c                       |    1 
 drivers/s390/char/sclp.c                          |    1 
 drivers/s390/char/sclp_con.c                      |    1 
 drivers/s390/char/sclp_vt220.c                    |    1 
 drivers/s390/char/zcore.c                         |    1 
 drivers/soc/bcm/brcmstb/pm/pm-arm.c               |    1 
 drivers/staging/olpc_dcon/olpc_dcon.c             |    1 
 drivers/video/fbdev/hyperv_fb.c                   |    1 
 include/asm-generic/bug.h                         |    3 
 include/linux/kernel.h                            |   84 ----------
 include/linux/panic.h                             |   98 ++++++++++++
 include/linux/panic_notifier.h                    |   12 +
 include/linux/thread_info.h                       |    1 
 kernel/hung_task.c                                |    1 
 kernel/kexec_core.c                               |    1 
 kernel/panic.c                                    |    1 
 kernel/rcu/tree.c                                 |    2 
 kernel/sysctl.c                                   |    1 
 kernel/trace/trace.c                              |    1 
 55 files changed, 169 insertions(+), 85 deletions(-)
arch/alpha/kernel/setup.c renamed from arch/alpha/kernel/setup.c~kernelh-split-out-panic-and-oops-helpers +1 -1
@@ -28,6 +28,7 @@
 #include <linux/init.h>
 #include <linux/string.h>
 #include <linux/ioport.h>
+#include <linux/panic_notifier.h>
 #include <linux/platform_device.h>
 #include <linux/memblock.h>
 #include <linux/pci.h>
@@ -46,7 +47,6 @@
 #include <linux/log2.h>
 #include <linux/export.h>
 
-extern struct atomic_notifier_head panic_notifier_list;
 static int alpha_panic_event(struct notifier_block *, unsigned long, void *);
 static struct notifier_block alpha_panic_block = {
 	alpha_panic_event,
arch/arm64/kernel/setup.c renamed from arch/arm64/kernel/setup.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -23,6 +23,7 @@
 #include <linux/interrupt.h>
 #include <linux/smp.h>
 #include <linux/fs.h>
+#include <linux/panic_notifier.h>
 #include <linux/proc_fs.h>
 #include <linux/memblock.h>
 #include <linux/of_fdt.h>
arch/ia64/include/asm/pal.h renamed from arch/ia64/include/asm/pal.h~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -99,6 +99,7 @@
 
 #include <linux/types.h>
 #include <asm/fpu.h>
+#include <asm/intrinsics.h>
 
 /*
  * Data types needed to pass information into PAL procedures and
arch/mips/kernel/relocate.c renamed from arch/mips/kernel/relocate.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -18,6 +18,7 @@
 #include <linux/kernel.h>
 #include <linux/libfdt.h>
 #include <linux/of_fdt.h>
+#include <linux/panic_notifier.h>
 #include <linux/sched/task.h>
 #include <linux/start_kernel.h>
 #include <linux/string.h>
arch/mips/sgi-ip22/ip22-reset.c renamed from arch/mips/sgi-ip22/ip22-reset.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -12,6 +12,7 @@
 #include <linux/kernel.h>
 #include <linux/sched/signal.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/pm.h>
 #include <linux/timer.h>
 
arch/mips/sgi-ip32/ip32-reset.c renamed from arch/mips/sgi-ip32/ip32-reset.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -12,6 +12,7 @@
 #include <linux/init.h>
 #include <linux/kernel.h>
 #include <linux/module.h>
+#include <linux/panic_notifier.h>
 #include <linux/sched.h>
 #include <linux/sched/signal.h>
 #include <linux/notifier.h>
arch/parisc/kernel/pdc_chassis.c renamed from arch/parisc/kernel/pdc_chassis.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -20,6 +20,7 @@
 #include <linux/init.h>
 #include <linux/module.h>
 #include <linux/kernel.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/notifier.h>
 #include <linux/cache.h>
arch/powerpc/kernel/setup-common.c renamed from arch/powerpc/kernel/setup-common.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -9,6 +9,7 @@
 #undef DEBUG
 
 #include <linux/export.h>
+#include <linux/panic_notifier.h>
 #include <linux/string.h>
 #include <linux/sched.h>
 #include <linux/init.h>
arch/s390/kernel/ipl.c renamed from arch/s390/kernel/ipl.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -13,6 +13,7 @@
 #include <linux/init.h>
 #include <linux/device.h>
 #include <linux/delay.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/ctype.h>
 #include <linux/fs.h>
arch/sparc/kernel/sstate.c renamed from arch/sparc/kernel/sstate.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -6,6 +6,7 @@
 
 #include <linux/kernel.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/init.h>
 
arch/um/drivers/mconsole_kern.c renamed from arch/um/drivers/mconsole_kern.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -12,6 +12,7 @@
 #include <linux/mm.h>
 #include <linux/module.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/sched/debug.h>
 #include <linux/proc_fs.h>
arch/um/kernel/um_arch.c renamed from arch/um/kernel/um_arch.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -7,6 +7,7 @@
 #include <linux/init.h>
 #include <linux/mm.h>
 #include <linux/module.h>
+#include <linux/panic_notifier.h>
 #include <linux/seq_file.h>
 #include <linux/string.h>
 #include <linux/utsname.h>
arch/x86/include/asm/desc.h renamed from arch/x86/include/asm/desc.h~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -9,6 +9,7 @@
 #include <asm/irq_vectors.h>
 #include <asm/cpu_entry_area.h>
 
+#include <linux/debug_locks.h>
 #include <linux/smp.h>
 #include <linux/percpu.h>
 
arch/x86/kernel/cpu/mshyperv.c renamed from arch/x86/kernel/cpu/mshyperv.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -17,6 +17,7 @@
 #include <linux/irq.h>
 #include <linux/kexec.h>
 #include <linux/i8253.h>
+#include <linux/panic_notifier.h>
 #include <linux/random.h>
 #include <asm/processor.h>
 #include <asm/hypervisor.h>
arch/x86/kernel/setup.c renamed from arch/x86/kernel/setup.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -14,6 +14,7 @@
 #include <linux/initrd.h>
 #include <linux/iscsi_ibft.h>
 #include <linux/memblock.h>
+#include <linux/panic_notifier.h>
 #include <linux/pci.h>
 #include <linux/root_dev.h>
 #include <linux/hugetlb.h>
arch/x86/purgatory/purgatory.c renamed from arch/x86/purgatory/purgatory.c~kernelh-split-out-panic-and-oops-helpers +2 -0
@@ -9,6 +9,8 @@
  */
 
 #include <linux/bug.h>
+#include <linux/kernel.h>
+#include <linux/types.h>
 #include <crypto/sha2.h>
 #include <asm/purgatory.h>
 
arch/x86/xen/enlighten.c renamed from arch/x86/xen/enlighten.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -6,6 +6,7 @@
 #include <linux/cpu.h>
 #include <linux/kexec.h>
 #include <linux/slab.h>
+#include <linux/panic_notifier.h>
 
 #include <xen/xen.h>
 #include <xen/features.h>
arch/xtensa/platforms/iss/setup.c renamed from arch/xtensa/platforms/iss/setup.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -14,6 +14,7 @@
 #include <linux/init.h>
 #include <linux/kernel.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/printk.h>
 #include <linux/string.h>
 
drivers/bus/brcmstb_gisb.c renamed from drivers/bus/brcmstb_gisb.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -6,6 +6,7 @@
 #include <linux/init.h>
 #include <linux/types.h>
 #include <linux/module.h>
+#include <linux/panic_notifier.h>
 #include <linux/platform_device.h>
 #include <linux/interrupt.h>
 #include <linux/sysfs.h>
drivers/char/ipmi/ipmi_msghandler.c renamed from drivers/char/ipmi/ipmi_msghandler.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -16,6 +16,7 @@
 
 #include <linux/module.h>
 #include <linux/errno.h>
+#include <linux/panic_notifier.h>
 #include <linux/poll.h>
 #include <linux/sched.h>
 #include <linux/seq_file.h>
drivers/clk/analogbits/wrpll-cln28hpc.c renamed from drivers/clk/analogbits/wrpll-cln28hpc.c~kernelh-split-out-panic-and-oops-helpers +4 -0
@@ -23,8 +23,12 @@
 
 #include <linux/bug.h>
 #include <linux/err.h>
+#include <linux/limits.h>
 #include <linux/log2.h>
 #include <linux/math64.h>
+#include <linux/math.h>
+#include <linux/minmax.h>
+
 #include <linux/clk/analogbits-wrpll-cln28hpc.h>
 
 /* MIN_INPUT_FREQ: minimum input clock frequency, in Hz (Fref_min) */
drivers/edac/altera_edac.c renamed from drivers/edac/altera_edac.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -20,6 +20,7 @@
 #include <linux/of_address.h>
 #include <linux/of_irq.h>
 #include <linux/of_platform.h>
+#include <linux/panic_notifier.h>
 #include <linux/platform_device.h>
 #include <linux/regmap.h>
 #include <linux/types.h>
drivers/firmware/google/gsmi.c renamed from drivers/firmware/google/gsmi.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -19,6 +19,7 @@
 #include <linux/dma-mapping.h>
 #include <linux/fs.h>
 #include <linux/slab.h>
+#include <linux/panic_notifier.h>
 #include <linux/ioctl.h>
 #include <linux/acpi.h>
 #include <linux/io.h>
drivers/hv/vmbus_drv.c renamed from drivers/hv/vmbus_drv.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -25,6 +25,7 @@
 
 #include <linux/delay.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/ptrace.h>
 #include <linux/screen_info.h>
 #include <linux/kdebug.h>
drivers/hwtracing/coresight/coresight-cpu-debug.c renamed from drivers/hwtracing/coresight/coresight-cpu-debug.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -17,6 +17,7 @@
 #include <linux/kernel.h>
 #include <linux/module.h>
 #include <linux/moduleparam.h>
+#include <linux/panic_notifier.h>
 #include <linux/pm_qos.h>
 #include <linux/slab.h>
 #include <linux/smp.h>
drivers/leds/trigger/ledtrig-activity.c renamed from drivers/leds/trigger/ledtrig-activity.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -11,6 +11,7 @@
 #include <linux/kernel_stat.h>
 #include <linux/leds.h>
 #include <linux/module.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/sched.h>
 #include <linux/slab.h>
drivers/leds/trigger/ledtrig-heartbeat.c renamed from drivers/leds/trigger/ledtrig-heartbeat.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -11,6 +11,7 @@
 #include <linux/module.h>
 #include <linux/kernel.h>
 #include <linux/init.h>
+#include <linux/panic_notifier.h>
 #include <linux/slab.h>
 #include <linux/timer.h>
 #include <linux/sched.h>
drivers/leds/trigger/ledtrig-panic.c renamed from drivers/leds/trigger/ledtrig-panic.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -8,6 +8,7 @@
 #include <linux/kernel.h>
 #include <linux/init.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/leds.h>
 #include "../leds.h"
 
drivers/misc/bcm-vk/bcm_vk_dev.c renamed from drivers/misc/bcm-vk/bcm_vk_dev.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -9,6 +9,7 @@
 #include <linux/fs.h>
 #include <linux/idr.h>
 #include <linux/interrupt.h>
+#include <linux/panic_notifier.h>
 #include <linux/kref.h>
 #include <linux/module.h>
 #include <linux/mutex.h>
drivers/misc/ibmasm/heartbeat.c renamed from drivers/misc/ibmasm/heartbeat.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -9,6 +9,7 @@
  */
 
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include "ibmasm.h"
 #include "dot_command.h"
 #include "lowlevel.h"
drivers/misc/pvpanic/pvpanic.c renamed from drivers/misc/pvpanic/pvpanic.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -13,6 +13,7 @@
 #include <linux/mod_devicetable.h>
 #include <linux/module.h>
 #include <linux/platform_device.h>
+#include <linux/panic_notifier.h>
 #include <linux/types.h>
 #include <linux/cdev.h>
 #include <linux/list.h>
drivers/net/ipa/ipa_smp2p.c renamed from drivers/net/ipa/ipa_smp2p.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -8,6 +8,7 @@
 #include <linux/device.h>
 #include <linux/interrupt.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/soc/qcom/smem.h>
 #include <linux/soc/qcom/smem_state.h>
 
drivers/parisc/power.c renamed from drivers/parisc/power.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -38,6 +38,7 @@
 #include <linux/init.h>
 #include <linux/kernel.h>
 #include <linux/notifier.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/sched/signal.h>
 #include <linux/kthread.h>
drivers/power/reset/ltc2952-poweroff.c renamed from drivers/power/reset/ltc2952-poweroff.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -52,6 +52,7 @@
 #include <linux/slab.h>
 #include <linux/kmod.h>
 #include <linux/module.h>
+#include <linux/panic_notifier.h>
 #include <linux/mod_devicetable.h>
 #include <linux/gpio/consumer.h>
 #include <linux/reboot.h>
drivers/remoteproc/remoteproc_core.c renamed from drivers/remoteproc/remoteproc_core.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -20,6 +20,7 @@
 #include <linux/kernel.h>
 #include <linux/module.h>
 #include <linux/device.h>
+#include <linux/panic_notifier.h>
 #include <linux/slab.h>
 #include <linux/mutex.h>
 #include <linux/dma-map-ops.h>
drivers/s390/char/con3215.c renamed from drivers/s390/char/con3215.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -19,6 +19,7 @@
 #include <linux/console.h>
 #include <linux/interrupt.h>
 #include <linux/err.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/serial.h> /* ASYNC_* flags */
 #include <linux/slab.h>
drivers/s390/char/con3270.c renamed from drivers/s390/char/con3270.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -13,6 +13,7 @@
 #include <linux/init.h>
 #include <linux/interrupt.h>
 #include <linux/list.h>
+#include <linux/panic_notifier.h>
 #include <linux/types.h>
 #include <linux/slab.h>
 #include <linux/err.h>
drivers/s390/char/sclp.c renamed from drivers/s390/char/sclp.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -11,6 +11,7 @@
 #include <linux/kernel_stat.h>
 #include <linux/module.h>
 #include <linux/err.h>
+#include <linux/panic_notifier.h>
 #include <linux/spinlock.h>
 #include <linux/interrupt.h>
 #include <linux/timer.h>
drivers/s390/char/sclp_con.c renamed from drivers/s390/char/sclp_con.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -10,6 +10,7 @@
 #include <linux/kmod.h>
 #include <linux/console.h>
 #include <linux/init.h>
+#include <linux/panic_notifier.h>
 #include <linux/timer.h>
 #include <linux/jiffies.h>
 #include <linux/termios.h>
drivers/s390/char/sclp_vt220.c renamed from drivers/s390/char/sclp_vt220.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -9,6 +9,7 @@
 
 #include <linux/module.h>
 #include <linux/spinlock.h>
+#include <linux/panic_notifier.h>
 #include <linux/list.h>
 #include <linux/wait.h>
 #include <linux/timer.h>
drivers/s390/char/zcore.c renamed from drivers/s390/char/zcore.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -15,6 +15,7 @@
 #include <linux/init.h>
 #include <linux/slab.h>
 #include <linux/debugfs.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 
 #include <asm/asm-offsets.h>
drivers/soc/bcm/brcmstb/pm/pm-arm.c renamed from drivers/soc/bcm/brcmstb/pm/pm-arm.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -28,6 +28,7 @@
 #include <linux/notifier.h>
 #include <linux/of.h>
 #include <linux/of_address.h>
+#include <linux/panic_notifier.h>
 #include <linux/platform_device.h>
 #include <linux/pm.h>
 #include <linux/printk.h>
drivers/staging/olpc_dcon/olpc_dcon.c renamed from drivers/staging/olpc_dcon/olpc_dcon.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -22,6 +22,7 @@
 #include <linux/device.h>
 #include <linux/uaccess.h>
 #include <linux/ctype.h>
+#include <linux/panic_notifier.h>
 #include <linux/reboot.h>
 #include <linux/olpc-ec.h>
 #include <asm/tsc.h>
drivers/video/fbdev/hyperv_fb.c renamed from drivers/video/fbdev/hyperv_fb.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -52,6 +52,7 @@
 #include <linux/completion.h>
 #include <linux/fb.h>
 #include <linux/pci.h>
+#include <linux/panic_notifier.h>
 #include <linux/efi.h>
 #include <linux/console.h>
 
include/asm-generic/bug.h renamed from include/asm-generic/bug.h~kernelh-split-out-panic-and-oops-helpers +2 -1
@@ -17,7 +17,8 @@
 #endif
 
 #ifndef __ASSEMBLY__
-#include <linux/kernel.h>
+#include <linux/panic.h>
+#include <linux/printk.h>
 
 #ifdef CONFIG_BUG
 
include/linux/kernel.h renamed from include/linux/kernel.h~kernelh-split-out-panic-and-oops-helpers +1 -83

116 lines not on this page · raw message

include/linux/panic.h new file +98 -0

98 lines not on this page · raw message

include/linux/panic_notifier.h new file +12 -0
@@ -0,0 +1,12 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_PANIC_NOTIFIERS_H
+#define _LINUX_PANIC_NOTIFIERS_H
+
+#include <linux/notifier.h>
+#include <linux/types.h>
+
+extern struct atomic_notifier_head panic_notifier_list;
+
+extern bool crash_kexec_post_notifiers;
+
+#endif	/* _LINUX_PANIC_NOTIFIERS_H */
include/linux/thread_info.h renamed from include/linux/thread_info.h~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -9,6 +9,7 @@
 #define _LINUX_THREAD_INFO_H
 
 #include <linux/types.h>
+#include <linux/limits.h>
 #include <linux/bug.h>
 #include <linux/restart_block.h>
 #include <linux/errno.h>
kernel/hung_task.c renamed from kernel/hung_task.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -15,6 +15,7 @@
 #include <linux/kthread.h>
 #include <linux/lockdep.h>
 #include <linux/export.h>
+#include <linux/panic_notifier.h>
 #include <linux/sysctl.h>
 #include <linux/suspend.h>
 #include <linux/utsname.h>
kernel/kexec_core.c renamed from kernel/kexec_core.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -26,6 +26,7 @@
 #include <linux/suspend.h>
 #include <linux/device.h>
 #include <linux/freezer.h>
+#include <linux/panic_notifier.h>
 #include <linux/pm.h>
 #include <linux/cpu.h>
 #include <linux/uaccess.h>
kernel/panic.c renamed from kernel/panic.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -23,6 +23,7 @@
 #include <linux/reboot.h>
 #include <linux/delay.h>
 #include <linux/kexec.h>
+#include <linux/panic_notifier.h>
 #include <linux/sched.h>
 #include <linux/sysrq.h>
 #include <linux/init.h>
kernel/rcu/tree.c renamed from kernel/rcu/tree.c~kernelh-split-out-panic-and-oops-helpers +2 -0
@@ -32,6 +32,8 @@
 #include <linux/export.h>
 #include <linux/completion.h>
 #include <linux/moduleparam.h>
+#include <linux/panic.h>
+#include <linux/panic_notifier.h>
 #include <linux/percpu.h>
 #include <linux/notifier.h>
 #include <linux/cpu.h>
kernel/sysctl.c renamed from kernel/sysctl.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -27,6 +27,7 @@
 #include <linux/sysctl.h>
 #include <linux/bitmap.h>
 #include <linux/signal.h>
+#include <linux/panic.h>
 #include <linux/printk.h>
 #include <linux/proc_fs.h>
 #include <linux/security.h>
kernel/trace/trace.c renamed from kernel/trace/trace.c~kernelh-split-out-panic-and-oops-helpers +1 -0
@@ -39,6 +39,7 @@
 #include <linux/slab.h>
 #include <linux/ctype.h>
 #include <linux/init.h>
+#include <linux/panic_notifier.h>
 #include <linux/poll.h>
 #include <linux/nmi.h>
 #include <linux/fs.h>

_

author maintainer
#170 lore raw

PATCH 147/192 lib: decompress_bunzip2: remove an unneeded semicolon

In reply to Andrew Morton

From: Zhen Lei <[email protected]>
Subject: lib: decompress_bunzip2: remove an unneeded semicolon

The semicolon immediately following '}' is unneeded.

---

 lib/decompress_bunzip2.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/decompress_bunzip2.c renamed from lib/decompress_bunzip2.c~lib-decompress_bunzip2-remove-an-unneeded-semicolon +1 -1
@@ -385,7 +385,7 @@ static int INIT get_next_block(struct bu
 			bd->inbufBits =
 				(bd->inbufBits << 8)|bd->inbuf[bd->inbufPos++];
 			bd->inbufBitCount += 8;
-		};
+		}
 		bd->inbufBitCount -= hufGroup->maxLen;
 		j = (bd->inbufBits >> bd->inbufBitCount)&
 			((1 << hufGroup->maxLen)-1);

_

author maintainer
#171 lore raw

PATCH 148/192 lib/string_helpers: switch to use BIT() macro

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/string_helpers: switch to use BIT() macro

Patch series "lib/string_helpers: get rid of ugly *_escape_mem_ascii()", v3.

Get rid of ugly *_escape_mem_ascii() API since it's not flexible and has the only single user. Provide better approach based on usage of the string_escape_mem() with appropriate flags.

Test cases has been expanded accordingly to cover new functionality.

This patch (of 15):

Switch to use BIT() macro for flag definitions. No changes implied.

---

 include/linux/string_helpers.h |   21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
include/linux/string_helpers.h renamed from include/linux/string_helpers.h~lib-string_helpers-switch-to-use-bit-macro +11 -10
@@ -2,6 +2,7 @@
 #ifndef _LINUX_STRING_HELPERS_H_
 #define _LINUX_STRING_HELPERS_H_
 
+#include <linux/bits.h>
 #include <linux/ctype.h>
 #include <linux/types.h>
 
@@ -18,10 +19,10 @@ enum string_size_units {
 void string_get_size(u64 size, u64 blk_size, enum string_size_units units,
 		     char *buf, int len);
 
-#define UNESCAPE_SPACE		0x01
-#define UNESCAPE_OCTAL		0x02
-#define UNESCAPE_HEX		0x04
-#define UNESCAPE_SPECIAL	0x08
+#define UNESCAPE_SPACE		BIT(0)
+#define UNESCAPE_OCTAL		BIT(1)
+#define UNESCAPE_HEX		BIT(2)
+#define UNESCAPE_SPECIAL	BIT(3)
 #define UNESCAPE_ANY		\
 	(UNESCAPE_SPACE | UNESCAPE_OCTAL | UNESCAPE_HEX | UNESCAPE_SPECIAL)
 
@@ -42,15 +43,15 @@ static inline int string_unescape_any_in
 	return string_unescape_any(buf, buf, 0);
 }
 
-#define ESCAPE_SPACE		0x01
-#define ESCAPE_SPECIAL		0x02
-#define ESCAPE_NULL		0x04
-#define ESCAPE_OCTAL		0x08
+#define ESCAPE_SPACE		BIT(0)
+#define ESCAPE_SPECIAL		BIT(1)
+#define ESCAPE_NULL		BIT(2)
+#define ESCAPE_OCTAL		BIT(3)
 #define ESCAPE_ANY		\
 	(ESCAPE_SPACE | ESCAPE_OCTAL | ESCAPE_SPECIAL | ESCAPE_NULL)
-#define ESCAPE_NP		0x10
+#define ESCAPE_NP		BIT(4)
 #define ESCAPE_ANY_NP		(ESCAPE_ANY | ESCAPE_NP)
-#define ESCAPE_HEX		0x20
+#define ESCAPE_HEX		BIT(5)
 
 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
 		unsigned int flags, const char *only);

_

author maintainer
#172 lore raw

PATCH 149/192 lib/string_helpers: move ESCAPE_NP check inside 'else' branch in a loop

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/string_helpers: move ESCAPE_NP check inside 'else' branch in a loop

Refactor code to have better readability by moving ESCAPE_NP handling inside 'else' branch in the loop.

No functional change intended.

---

 lib/string_helpers.c |   17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)
lib/string_helpers.c renamed from lib/string_helpers.c~lib-string_helpers-move-escape_np-check-inside-else-branch-in-a-loop +10 -7
@@ -452,10 +452,10 @@ static bool escape_hex(unsigned char c,
  * The process of escaping byte buffer includes several parts. They are applied
  * in the following sequence.
  *
- *	1. The character is matched to the printable class, if asked, and in
- *	   case of match it passes through to the output.
- *	2. The character is not matched to the one from @only string and thus
+ *	1. The character is not matched to the one from @only string and thus
  *	   must go as-is to the output.
+ *	2. The character is matched to the printable class, if asked, and in
+ *	   case of match it passes through to the output.
  *	3. The character is checked if it falls into the class given by @flags.
  *	   %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
  *	   character. Note that they actually can't go together, otherwise
@@ -506,19 +506,22 @@ int string_escape_mem(const char *src, s
 
 		/*
 		 * Apply rules in the following sequence:
-		 *	- the character is printable, when @flags has
-		 *	  %ESCAPE_NP bit set
 		 *	- the @only string is supplied and does not contain a
 		 *	  character under question
+		 *	- the character is printable, when @flags has
+		 *	  %ESCAPE_NP bit set
 		 *	- the character doesn't fall into a class of symbols
 		 *	  defined by given @flags
 		 * In these cases we just pass through a character to the
 		 * output buffer.
 		 */
-		if ((flags & ESCAPE_NP && isprint(c)) ||
-		    (is_dict && !strchr(only, c))) {
+		if (is_dict && !strchr(only, c)) {
 			/* do nothing */
 		} else {
+			if (isprint(c) &&
+			    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
+				continue;
+
 			if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
 				continue;
 

_

author maintainer
#173 lore raw

PATCH 150/192 lib/string_helpers: drop indentation level in string_escape_mem()

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/string_helpers: drop indentation level in string_escape_mem()

The only one conditional is left on the upper level, move the rest to the same level and drop indentation level. No functional changes.

---

 lib/string_helpers.c |   46 ++++++++++++++++++++---------------------
 1 file changed, 23 insertions(+), 23 deletions(-)
lib/string_helpers.c renamed from lib/string_helpers.c~lib-string_helpers-drop-indentation-level-in-string_escape_mem +23 -23
@@ -515,29 +515,29 @@ int string_escape_mem(const char *src, s
 		 * In these cases we just pass through a character to the
 		 * output buffer.
 		 */
-		if (is_dict && !strchr(only, c)) {
-			/* do nothing */
-		} else {
-			if (isprint(c) &&
-			    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
-				continue;
-
-			if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
-				continue;
-
-			if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
-				continue;
-
-			if (flags & ESCAPE_NULL && escape_null(c, &p, end))
-				continue;
-
-			/* ESCAPE_OCTAL and ESCAPE_HEX always go last */
-			if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
-				continue;
-
-			if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
-				continue;
-		}
+		if (is_dict && !strchr(only, c) &&
+					  escape_passthrough(c, &p, end))
+			continue;
+
+		if (isprint(c) &&
+		    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
+			continue;
+
+		if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
+			continue;
+
+		if (flags & ESCAPE_SPECIAL && escape_special(c, &p, end))
+			continue;
+
+		if (flags & ESCAPE_NULL && escape_null(c, &p, end))
+			continue;
+
+		/* ESCAPE_OCTAL and ESCAPE_HEX always go last */
+		if (flags & ESCAPE_OCTAL && escape_octal(c, &p, end))
+			continue;
+
+		if (flags & ESCAPE_HEX && escape_hex(c, &p, end))
+			continue;
 
 		escape_passthrough(c, &p, end);
 	}

_

author maintainer
#174 lore raw

PATCH 151/192 lib/string_helpers: introduce ESCAPE_NA for escaping non-ASCII

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/string_helpers: introduce ESCAPE_NA for escaping non-ASCII

Some users may want to have an ASCII based filter, provided by isascii() function. Here is the addition of a such.

---

 include/linux/string_helpers.h |    1 +
 lib/string_helpers.c           |   21 +++++++++++++++++----
 2 files changed, 18 insertions(+), 4 deletions(-)
include/linux/string_helpers.h renamed from include/linux/string_helpers.h~lib-string_helpers-introduce-escape_na-for-escaping-non-ascii +1 -0
@@ -52,6 +52,7 @@ static inline int string_unescape_any_in
 #define ESCAPE_NP		BIT(4)
 #define ESCAPE_ANY_NP		(ESCAPE_ANY | ESCAPE_NP)
 #define ESCAPE_HEX		BIT(5)
+#define ESCAPE_NA		BIT(6)
 
 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
 		unsigned int flags, const char *only);
lib/string_helpers.c renamed from lib/string_helpers.c~lib-string_helpers-introduce-escape_na-for-escaping-non-ascii +17 -4
@@ -454,8 +454,8 @@ static bool escape_hex(unsigned char c,
  *
  *	1. The character is not matched to the one from @only string and thus
  *	   must go as-is to the output.
- *	2. The character is matched to the printable class, if asked, and in
- *	   case of match it passes through to the output.
+ *	2. The character is matched to the printable or ASCII class, if asked,
+ *	   and in case of match it passes through to the output.
  *	3. The character is checked if it falls into the class given by @flags.
  *	   %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
  *	   character. Note that they actually can't go together, otherwise
@@ -463,7 +463,7 @@ static bool escape_hex(unsigned char c,
  *
  * Caller must provide valid source and destination pointers. Be aware that
  * destination buffer will not be NULL-terminated, thus caller have to append
- * it if needs.   The supported flags are::
+ * it if needs. The supported flags are::
  *
  *	%ESCAPE_SPACE: (special white space, not space itself)
  *		'\f' - form feed
@@ -482,11 +482,18 @@ static bool escape_hex(unsigned char c,
  *	%ESCAPE_ANY:
  *		all previous together
  *	%ESCAPE_NP:
- *		escape only non-printable characters (checked by isprint)
+ *		escape only non-printable characters, checked by isprint()
  *	%ESCAPE_ANY_NP:
  *		all previous together
  *	%ESCAPE_HEX:
  *		'\xHH' - byte with hexadecimal value HH (2 digits)
+ *	%ESCAPE_NA:
+ *		escape only non-ascii characters, checked by isascii()
+ *
+ * One notable caveat, the %ESCAPE_NP and %ESCAPE_NA have higher priority
+ * than the rest of the flags (%ESCAPE_NP is higher than %ESCAPE_NA).
+ * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
+ * or %ESCAPE_HEX, because they cover most of the other character classes.
  *
  * Return:
  * The total size of the escaped output that would be generated for
@@ -510,6 +517,8 @@ int string_escape_mem(const char *src, s
 		 *	  character under question
 		 *	- the character is printable, when @flags has
 		 *	  %ESCAPE_NP bit set
+		 *	- the character is ASCII, when @flags has
+		 *	  %ESCAPE_NA bit set
 		 *	- the character doesn't fall into a class of symbols
 		 *	  defined by given @flags
 		 * In these cases we just pass through a character to the
@@ -523,6 +532,10 @@ int string_escape_mem(const char *src, s
 		    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
 			continue;
 
+		if (isascii(c) &&
+		    flags & ESCAPE_NA && escape_passthrough(c, &p, end))
+			continue;
+
 		if (flags & ESCAPE_SPACE && escape_space(c, &p, end))
 			continue;
 

_

author maintainer
#175 lore raw

PATCH 152/192 lib/string_helpers: introduce ESCAPE_NAP to escape non-ASCII and non-printable

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/string_helpers: introduce ESCAPE_NAP to escape non-ASCII and non-printable

Some users may want to have an ASCII based filter for printable only characters, provided by conjunction of isascii() and isprint() functions.

Here is the addition of a such.

---

 include/linux/string_helpers.h |    1 +
 lib/string_helpers.c           |   20 ++++++++++++++++----
 2 files changed, 17 insertions(+), 4 deletions(-)
include/linux/string_helpers.h renamed from include/linux/string_helpers.h~lib-string_helpers-introduce-escape_nap-to-escape-non-ascii-and-non-printable +1 -0
@@ -53,6 +53,7 @@ static inline int string_unescape_any_in
 #define ESCAPE_ANY_NP		(ESCAPE_ANY | ESCAPE_NP)
 #define ESCAPE_HEX		BIT(5)
 #define ESCAPE_NA		BIT(6)
+#define ESCAPE_NAP		BIT(7)
 
 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
 		unsigned int flags, const char *only);
lib/string_helpers.c renamed from lib/string_helpers.c~lib-string_helpers-introduce-escape_nap-to-escape-non-ascii-and-non-printable +16 -4
@@ -454,9 +454,11 @@ static bool escape_hex(unsigned char c,
  *
  *	1. The character is not matched to the one from @only string and thus
  *	   must go as-is to the output.
- *	2. The character is matched to the printable or ASCII class, if asked,
+ *	2. The character is matched to the printable and ASCII classes, if asked,
  *	   and in case of match it passes through to the output.
- *	3. The character is checked if it falls into the class given by @flags.
+ *	3. The character is matched to the printable or ASCII class, if asked,
+ *	   and in case of match it passes through to the output.
+ *	4. The character is checked if it falls into the class given by @flags.
  *	   %ESCAPE_OCTAL and %ESCAPE_HEX are going last since they cover any
  *	   character. Note that they actually can't go together, otherwise
  *	   %ESCAPE_HEX will be ignored.
@@ -489,11 +491,15 @@ static bool escape_hex(unsigned char c,
  *		'\xHH' - byte with hexadecimal value HH (2 digits)
  *	%ESCAPE_NA:
  *		escape only non-ascii characters, checked by isascii()
+ *	%ESCAPE_NAP:
+ *		escape only non-printable or non-ascii characters
  *
- * One notable caveat, the %ESCAPE_NP and %ESCAPE_NA have higher priority
- * than the rest of the flags (%ESCAPE_NP is higher than %ESCAPE_NA).
+ * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
+ * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
  * It doesn't make much sense to use either of them without %ESCAPE_OCTAL
  * or %ESCAPE_HEX, because they cover most of the other character classes.
+ * %ESCAPE_NAP can utilize %ESCAPE_SPACE or %ESCAPE_SPECIAL in addition to
+ * the above.
  *
  * Return:
  * The total size of the escaped output that would be generated for
@@ -515,6 +521,8 @@ int string_escape_mem(const char *src, s
 		 * Apply rules in the following sequence:
 		 *	- the @only string is supplied and does not contain a
 		 *	  character under question
+		 *	- the character is printable and ASCII, when @flags has
+		 *	  %ESCAPE_NAP bit set
 		 *	- the character is printable, when @flags has
 		 *	  %ESCAPE_NP bit set
 		 *	- the character is ASCII, when @flags has
@@ -528,6 +536,10 @@ int string_escape_mem(const char *src, s
 					  escape_passthrough(c, &p, end))
 			continue;
 
+		if (isascii(c) && isprint(c) &&
+		    flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
+			continue;
+
 		if (isprint(c) &&
 		    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
 			continue;

_

author maintainer
#176 lore raw

PATCH 153/192 lib/string_helpers: allow to append additional characters to be escaped

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/string_helpers: allow to append additional characters to be escaped

Introduce a new flag to append additional characters, passed in 'only' parameter, to be escaped if they fall in the corresponding class.

---

 include/linux/string_helpers.h |    1 +
 lib/string_helpers.c           |   19 +++++++++++++++----
 2 files changed, 16 insertions(+), 4 deletions(-)
include/linux/string_helpers.h renamed from include/linux/string_helpers.h~lib-string_helpers-allow-to-append-additional-characters-to-be-escaped +1 -0
@@ -54,6 +54,7 @@ static inline int string_unescape_any_in
 #define ESCAPE_HEX		BIT(5)
 #define ESCAPE_NA		BIT(6)
 #define ESCAPE_NAP		BIT(7)
+#define ESCAPE_APPEND		BIT(8)
 
 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
 		unsigned int flags, const char *only);
lib/string_helpers.c renamed from lib/string_helpers.c~lib-string_helpers-allow-to-append-additional-characters-to-be-escaped +15 -4
@@ -493,6 +493,11 @@ static bool escape_hex(unsigned char c,
  *		escape only non-ascii characters, checked by isascii()
  *	%ESCAPE_NAP:
  *		escape only non-printable or non-ascii characters
+ *	%ESCAPE_APPEND:
+ *		append characters from @only to be escaped by the given classes
+ *
+ * %ESCAPE_APPEND would help to pass additional characters to the escaped, when
+ * one of %ESCAPE_NP, %ESCAPE_NA, or %ESCAPE_NAP is provided.
  *
  * One notable caveat, the %ESCAPE_NAP, %ESCAPE_NP and %ESCAPE_NA have the
  * higher priority than the rest of the flags (%ESCAPE_NAP is the highest).
@@ -513,9 +518,11 @@ int string_escape_mem(const char *src, s
 	char *p = dst;
 	char *end = p + osz;
 	bool is_dict = only && *only;
+	bool is_append = flags & ESCAPE_APPEND;
 
 	while (isz--) {
 		unsigned char c = *src++;
+		bool in_dict = is_dict && strchr(only, c);
 
 		/*
 		 * Apply rules in the following sequence:
@@ -531,20 +538,24 @@ int string_escape_mem(const char *src, s
 		 *	  defined by given @flags
 		 * In these cases we just pass through a character to the
 		 * output buffer.
+		 *
+		 * When %ESCAPE_APPEND is passed, the characters from @only
+		 * have been excluded from the %ESCAPE_NAP, %ESCAPE_NP, and
+		 * %ESCAPE_NA cases.
 		 */
-		if (is_dict && !strchr(only, c) &&
+		if (!(is_append || in_dict) && is_dict &&
 					  escape_passthrough(c, &p, end))
 			continue;
 
-		if (isascii(c) && isprint(c) &&
+		if (!(is_append && in_dict) && isascii(c) && isprint(c) &&
 		    flags & ESCAPE_NAP && escape_passthrough(c, &p, end))
 			continue;
 
-		if (isprint(c) &&
+		if (!(is_append && in_dict) && isprint(c) &&
 		    flags & ESCAPE_NP && escape_passthrough(c, &p, end))
 			continue;
 
-		if (isascii(c) &&
+		if (!(is_append && in_dict) && isascii(c) &&
 		    flags & ESCAPE_NA && escape_passthrough(c, &p, end))
 			continue;
 

_

author maintainer
#177 lore raw

PATCH 154/192 lib/test-string_helpers: print flags in hexadecimal format

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/test-string_helpers: print flags in hexadecimal format

Since flags are bitmapped, it's better to print them in hexadecimal format.

---

 lib/test-string_helpers.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
lib/test-string_helpers.c renamed from lib/test-string_helpers.c~lib-test-string_helpers-print-flags-in-hexadecimal-format +2 -2
@@ -19,7 +19,7 @@ static __init bool test_string_check_buf
 	if (q_real == q_test && !memcmp(out_test, out_real, q_test))
 		return true;
 
-	pr_warn("Test '%s' failed: flags = %u\n", name, flags);
+	pr_warn("Test '%s' failed: flags = %#x\n", name, flags);
 
 	print_hex_dump(KERN_WARNING, "Input: ", DUMP_PREFIX_NONE, 16, 1,
 		       in, p, true);
@@ -290,7 +290,7 @@ test_string_escape_overflow(const char *
 
 	q_real = string_escape_mem(in, p, NULL, 0, flags, esc);
 	if (q_real != q_test)
-		pr_warn("Test '%s' failed: flags = %u, osz = 0, expected %d, got %d\n",
+		pr_warn("Test '%s' failed: flags = %#x, osz = 0, expected %d, got %d\n",
 			name, flags, q_test, q_real);
 }
 

_

author maintainer
#178 lore raw

PATCH 155/192 lib/test-string_helpers: get rid of trailing comma in terminators

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/test-string_helpers: get rid of trailing comma in terminators

Terminators by definition shouldn't accept anything behind. Make them robust by removing trailing commas.

---

 lib/test-string_helpers.c |   12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
lib/test-string_helpers.c renamed from lib/test-string_helpers.c~lib-test-string_helpers-get-rid-of-trailing-comma-in-terminators +6 -6
@@ -136,7 +136,7 @@ static const struct test_string_2 escape
 		.flags = ESCAPE_SPACE | ESCAPE_HEX,
 	},{
 		/* terminator */
-	}},
+	}}
 },{
 	.in = "\\h\\\"\a\e\\",
 	.s1 = {{
@@ -150,7 +150,7 @@ static const struct test_string_2 escape
 		.flags = ESCAPE_SPECIAL | ESCAPE_HEX,
 	},{
 		/* terminator */
-	}},
+	}}
 },{
 	.in = "\eb \\C\007\"\x90\r]",
 	.s1 = {{
@@ -201,7 +201,7 @@ static const struct test_string_2 escape
 		.flags = ESCAPE_NP | ESCAPE_HEX,
 	},{
 		/* terminator */
-	}},
+	}}
 },{
 	/* terminator */
 }};
@@ -217,7 +217,7 @@ static const struct test_string_2 escape
 		.flags = ESCAPE_HEX,
 	},{
 		/* terminator */
-	}},
+	}}
 },{
 	.in = "\\h\\\"\a\e\\",
 	.s1 = {{
@@ -225,7 +225,7 @@ static const struct test_string_2 escape
 		.flags = ESCAPE_OCTAL,
 	},{
 		/* terminator */
-	}},
+	}}
 },{
 	.in = "\eb \\C\007\"\x90\r]",
 	.s1 = {{
@@ -233,7 +233,7 @@ static const struct test_string_2 escape
 		.flags = ESCAPE_OCTAL,
 	},{
 		/* terminator */
-	}},
+	}}
 },{
 	/* terminator */
 }};

_

author maintainer
#179 lore raw

PATCH 156/192 lib/test-string_helpers: add test cases for new features

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: lib/test-string_helpers: add test cases for new features

We have got new flags and hence new features of string_escape_mem(). Add test cases for that.

---

 include/linux/string_helpers.h |    4 
 lib/test-string_helpers.c      |  141 +++++++++++++++++++++++++++++--
 2 files changed, 137 insertions(+), 8 deletions(-)
include/linux/string_helpers.h renamed from include/linux/string_helpers.h~lib-test-string_helpers-add-test-cases-for-new-features +4 -0
@@ -26,6 +26,8 @@ void string_get_size(u64 size, u64 blk_s
 #define UNESCAPE_ANY		\
 	(UNESCAPE_SPACE | UNESCAPE_OCTAL | UNESCAPE_HEX | UNESCAPE_SPECIAL)
 
+#define UNESCAPE_ALL_MASK	GENMASK(3, 0)
+
 int string_unescape(char *src, char *dst, size_t size, unsigned int flags);
 
 static inline int string_unescape_inplace(char *buf, unsigned int flags)
@@ -56,6 +58,8 @@ static inline int string_unescape_any_in
 #define ESCAPE_NAP		BIT(7)
 #define ESCAPE_APPEND		BIT(8)
 
+#define ESCAPE_ALL_MASK		GENMASK(8, 0)
+
 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
 		unsigned int flags, const char *only);
 
lib/test-string_helpers.c renamed from lib/test-string_helpers.c~lib-test-string_helpers-add-test-cases-for-new-features +133 -8

188 lines not on this page · raw message

_

author maintainer
#180 lore raw

PATCH 157/192 MAINTAINERS: add myself as designated reviewer for generic string library

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: MAINTAINERS: add myself as designated reviewer for generic string library

Add myself as designated reviewer for generic string library.

---

 MAINTAINERS |    8 ++++++++
 1 file changed, 8 insertions(+)
MAINTAINERS renamed from MAINTAINERS~maintainers-add-myself-as-designated-reviewer-for-generic-string-library +8 -0
@@ -7648,6 +7648,14 @@ L:	[email protected]
 S:	Maintained
 F:	drivers/input/touchscreen/resistive-adc-touch.c
 
+GENERIC STRING LIBRARY
+R:	Andy Shevchenko <[email protected]>
+S:	Maintained
+F:	lib/string.c
+F:	lib/string_helpers.c
+F:	lib/test_string.c
+F:	lib/test-string_helpers.c
+
 GENERIC UIO DRIVER FOR PCI DEVICES
 M:	"Michael S. Tsirkin" <[email protected]>
 L:	[email protected]

_

author maintainer
#181 lore raw

PATCH 158/192 seq_file: introduce seq_escape_mem()

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: seq_file: introduce seq_escape_mem()

Introduce seq_escape_mem() to allow users to pass additional parameters to string_escape_mem().

---

 fs/seq_file.c            |   25 +++++++++++++++++++++++++
 include/linux/seq_file.h |    2 ++
 2 files changed, 27 insertions(+)
fs/seq_file.c renamed from fs/seq_file.c~seq_file-introduce-seq_escape_mem +25 -0
@@ -356,6 +356,31 @@ int seq_release(struct inode *inode, str
 EXPORT_SYMBOL(seq_release);
 
 /**
+ * seq_escape_mem - print data into buffer, escaping some characters
+ * @m: target buffer
+ * @src: source buffer
+ * @len: size of source buffer
+ * @flags: flags to pass to string_escape_mem()
+ * @esc: set of characters that need escaping
+ *
+ * Puts data into buffer, replacing each occurrence of character from
+ * given class (defined by @flags and @esc) with printable escaped sequence.
+ *
+ * Use seq_has_overflowed() to check for errors.
+ */
+void seq_escape_mem(struct seq_file *m, const char *src, size_t len,
+		    unsigned int flags, const char *esc)
+{
+	char *buf;
+	size_t size = seq_get_buf(m, &buf);
+	int ret;
+
+	ret = string_escape_mem(src, len, buf, size, flags, esc);
+	seq_commit(m, ret < size ? ret : -1);
+}
+EXPORT_SYMBOL(seq_escape_mem);
+
+/**
  *	seq_escape -	print string into buffer, escaping some characters
  *	@m:	target buffer
  *	@s:	string
include/linux/seq_file.h renamed from include/linux/seq_file.h~seq_file-introduce-seq_escape_mem +2 -0
@@ -126,6 +126,8 @@ void seq_put_decimal_ll(struct seq_file
 void seq_put_hex_ll(struct seq_file *m, const char *delimiter,
 		    unsigned long long v, unsigned int width);
 
+void seq_escape_mem(struct seq_file *m, const char *src, size_t len,
+		    unsigned int flags, const char *esc);
 void seq_escape(struct seq_file *m, const char *s, const char *esc);
 void seq_escape_mem_ascii(struct seq_file *m, const char *src, size_t isz);
 

_

author maintainer
#182 lore raw

PATCH 159/192 seq_file: add seq_escape_str() as replica of string_escape_str()

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: seq_file: add seq_escape_str() as replica of string_escape_str()

In some cases we want to escape characters from NULL-terminated strings. Add seq_escape_str() as replica of string_escape_str() for that.

---

 include/linux/seq_file.h |    7 +++++++
 1 file changed, 7 insertions(+)
include/linux/seq_file.h renamed from include/linux/seq_file.h~seq_file-add-seq_escape_str-as-replica-of-string_escape_str +7 -0
@@ -128,6 +128,13 @@ void seq_put_hex_ll(struct seq_file *m,
 
 void seq_escape_mem(struct seq_file *m, const char *src, size_t len,
 		    unsigned int flags, const char *esc);
+
+static inline void seq_escape_str(struct seq_file *m, const char *src,
+				  unsigned int flags, const char *esc)
+{
+	seq_escape_mem(m, src, strlen(src), flags, esc);
+}
+
 void seq_escape(struct seq_file *m, const char *s, const char *esc);
 void seq_escape_mem_ascii(struct seq_file *m, const char *src, size_t isz);
 

_

author maintainer
#183 lore raw

PATCH 160/192 seq_file: convert seq_escape() to use seq_escape_str()

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: seq_file: convert seq_escape() to use seq_escape_str()

Convert seq_escape() to use seq_escape_str() rather than open coding it.

Note, for now we leave it as an exported symbol due to some old code that can't tolerate ctype.h being (indirectly) included.

---

 fs/seq_file.c |    7 +------
 1 file changed, 1 insertion(+), 6 deletions(-)
fs/seq_file.c renamed from fs/seq_file.c~seq_file-convert-seq_escape-to-use-seq_escape_str +1 -6
@@ -392,12 +392,7 @@ EXPORT_SYMBOL(seq_escape_mem);
  */
 void seq_escape(struct seq_file *m, const char *s, const char *esc)
 {
-	char *buf;
-	size_t size = seq_get_buf(m, &buf);
-	int ret;
-
-	ret = string_escape_str(s, buf, size, ESCAPE_OCTAL, esc);
-	seq_commit(m, ret < size ? ret : -1);
+	seq_escape_str(m, s, ESCAPE_OCTAL, esc);
 }
 EXPORT_SYMBOL(seq_escape);
 

_

author maintainer
#184 lore raw

PATCH 161/192 nfsd: avoid non-flexible API in seq_quote_mem()

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: nfsd: avoid non-flexible API in seq_quote_mem()

The seq_escape_mem_ascii() is completely non-flexible and shouldn't be used. Replace it with properly called seq_escape_mem().

---

 fs/nfsd/nfs4state.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/nfsd/nfs4state.c renamed from fs/nfsd/nfs4state.c~nfsd-avoid-non-flexible-api-in-seq_quote_mem +1 -1
@@ -2351,7 +2351,7 @@ static struct nfs4_client *get_nfsdfs_cl
 static void seq_quote_mem(struct seq_file *m, char *data, int len)
 {
 	seq_printf(m, "\"");
-	seq_escape_mem_ascii(m, data, len);
+	seq_escape_mem(m, data, len, ESCAPE_HEX | ESCAPE_NAP | ESCAPE_APPEND, "\"\\");
 	seq_printf(m, "\"");
 }
 

_

author maintainer
#185 lore raw

PATCH 162/192 seq_file: drop unused *_escape_mem_ascii()

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: seq_file: drop unused *_escape_mem_ascii()

There are no more users of the seq_escape_mem_ascii() followed by string_escape_mem_ascii().

Remove them for good.

---

 fs/seq_file.c                  |   11 -----------
 include/linux/seq_file.h       |    1 -
 include/linux/string_helpers.h |    3 ---
 lib/string_helpers.c           |   19 -------------------
 4 files changed, 34 deletions(-)
fs/seq_file.c renamed from fs/seq_file.c~seq_file-drop-unused-_escape_mem_ascii +0 -11
@@ -396,17 +396,6 @@ void seq_escape(struct seq_file *m, cons
 }
 EXPORT_SYMBOL(seq_escape);
 
-void seq_escape_mem_ascii(struct seq_file *m, const char *src, size_t isz)
-{
-	char *buf;
-	size_t size = seq_get_buf(m, &buf);
-	int ret;
-
-	ret = string_escape_mem_ascii(src, isz, buf, size);
-	seq_commit(m, ret < size ? ret : -1);
-}
-EXPORT_SYMBOL(seq_escape_mem_ascii);
-
 void seq_vprintf(struct seq_file *m, const char *f, va_list args)
 {
 	int len;
include/linux/seq_file.h renamed from include/linux/seq_file.h~seq_file-drop-unused-_escape_mem_ascii +0 -1
@@ -136,7 +136,6 @@ static inline void seq_escape_str(struct
 }
 
 void seq_escape(struct seq_file *m, const char *s, const char *esc);
-void seq_escape_mem_ascii(struct seq_file *m, const char *src, size_t isz);
 
 void seq_hex_dump(struct seq_file *m, const char *prefix_str, int prefix_type,
 		  int rowsize, int groupsize, const void *buf, size_t len,
include/linux/string_helpers.h renamed from include/linux/string_helpers.h~seq_file-drop-unused-_escape_mem_ascii +0 -3
@@ -63,9 +63,6 @@ static inline int string_unescape_any_in
 int string_escape_mem(const char *src, size_t isz, char *dst, size_t osz,
 		unsigned int flags, const char *only);
 
-int string_escape_mem_ascii(const char *src, size_t isz, char *dst,
-					size_t osz);
-
 static inline int string_escape_mem_any_np(const char *src, size_t isz,
 		char *dst, size_t osz, const char *only)
 {
lib/string_helpers.c renamed from lib/string_helpers.c~seq_file-drop-unused-_escape_mem_ascii +0 -19
@@ -582,25 +582,6 @@ int string_escape_mem(const char *src, s
 }
 EXPORT_SYMBOL(string_escape_mem);
 
-int string_escape_mem_ascii(const char *src, size_t isz, char *dst,
-					size_t osz)
-{
-	char *p = dst;
-	char *end = p + osz;
-
-	while (isz--) {
-		unsigned char c = *src++;
-
-		if (!isprint(c) || !isascii(c) || c == '"' || c == '\\')
-			escape_hex(c, &p, end);
-		else
-			escape_passthrough(c, &p, end);
-	}
-
-	return p - dst;
-}
-EXPORT_SYMBOL(string_escape_mem_ascii);
-
 /*
  * Return an allocated string that has been escaped of special characters
  * and double quotes, making it safe to log in quotes.

_

author maintainer
#186 lore raw

PATCH 163/192 lib/math/rational.c: fix divide by zero

In reply to Andrew Morton

From: Trent Piepho <[email protected]>
Subject: lib/math/rational.c: fix divide by zero

If the input is out of the range of the allowed values, either larger than the largest value or closer to zero than the smallest non-zero allowed value, then a division by zero would occur.

In the case of input too large, the division by zero will occur on the first iteration. The best result (largest allowed value) will be found by always choosing the semi-convergent and excluding the denominator based limit when finding it.

In the case of the input too small, the division by zero will occur on the second iteration. The numerator based semi-convergent should not be calculated to avoid the division by zero. But the semi-convergent vs previous convergent test is still needed, which effectively chooses between 0 (the previous convergent) vs the smallest allowed fraction (best semi-convergent) as the result.

Fixes 323dd2c3ed0 ("lib/math/rational.c: fix possible incorrect result from rational fractions helper")
Cc Oskar Schirmer <[email protected]>
Cc Daniel Latypov <[email protected]>

---

 lib/math/rational.c |   16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)
lib/math/rational.c renamed from lib/math/rational.c~lib-math-rationalc-fix-divide-by-zero +11 -5
@@ -12,6 +12,7 @@
 #include <linux/compiler.h>
 #include <linux/export.h>
 #include <linux/minmax.h>
+#include <linux/limits.h>
 
 /*
  * calculate best rational approximation for a given fraction
@@ -78,13 +79,18 @@ void rational_best_approximation(
 		 * found below as 't'.
 		 */
 		if ((n2 > max_numerator) || (d2 > max_denominator)) {
-			unsigned long t = min((max_numerator - n0) / n1,
-					      (max_denominator - d0) / d1);
+			unsigned long t = ULONG_MAX;
 
-			/* This tests if the semi-convergent is closer
-			 * than the previous convergent.
+			if (d1)
+				t = (max_denominator - d0) / d1;
+			if (n1)
+				t = min(t, (max_numerator - n0) / n1);
+
+			/* This tests if the semi-convergent is closer than the previous
+			 * convergent.  If d1 is zero there is no previous convergent as this
+			 * is the 1st iteration, so always choose the semi-convergent.
 			 */
-			if (2u * t > a || (2u * t == a && d0 * dp > d1 * d)) {
+			if (!d1 || 2u * t > a || (2u * t == a && d0 * dp > d1 * d)) {
 				n1 = n0 + t * n1;
 				d1 = d0 + t * d1;
 			}

_

author maintainer
#187 lore raw

PATCH 164/192 lib/math/rational: add Kunit test cases

In reply to Andrew Morton

From: Trent Piepho <[email protected]>
Subject: lib/math/rational: add Kunit test cases

Adds a number of test cases that cover a range of possible code paths.

[[email protected]: remove non-ascii characters, fix whitespace]
[[email protected]: fix spelling mistake "demominator" -> "denominator"]
Cc Daniel Latypov <[email protected]>
Cc Oskar Schirmer <[email protected]>
Cc Yiyuan Guo <[email protected]>

---

 lib/Kconfig.debug        |   12 +++++++
 lib/math/Makefile        |    1 
 lib/math/rational-test.c |   56 +++++++++++++++++++++++++++++++++++++
 3 files changed, 69 insertions(+)
lib/Kconfig.debug renamed from lib/Kconfig.debug~lib-math-rational-add-kunit-test-cases +12 -0
@@ -2444,6 +2444,18 @@ config SLUB_KUNIT_TEST
 
 	  If unsure, say N.
 
+config RATIONAL_KUNIT_TEST
+	tristate "KUnit test for rational.c" if !KUNIT_ALL_TESTS
+	depends on KUNIT
+	select RATIONAL
+	default KUNIT_ALL_TESTS
+	help
+	  This builds the rational math unit test.
+	  For more information on KUnit and unit tests in general please refer
+	  to the KUnit documentation in Documentation/dev-tools/kunit/.
+
+	  If unsure, say N.
+
 config TEST_UDELAY
 	tristate "udelay test driver"
 	help
lib/math/Makefile renamed from lib/math/Makefile~lib-math-rational-add-kunit-test-cases +1 -0
@@ -6,3 +6,4 @@ obj-$(CONFIG_PRIME_NUMBERS)	+= prime_num
 obj-$(CONFIG_RATIONAL)		+= rational.o
 
 obj-$(CONFIG_TEST_DIV64)	+= test_div64.o
+obj-$(CONFIG_RATIONAL_KUNIT_TEST) += rational-test.o
lib/math/rational-test.c new file +56 -0

56 lines not on this page · raw message

_

author maintainer
#188 lore raw

PATCH 165/192 lib/decompressors: fix spelling mistakes

In reply to Andrew Morton

From: Zhen Lei <[email protected]>
Subject: lib/decompressors: fix spelling mistakes

Fix some spelling mistakes in comments:
sentinal ==> sentinel
compresed ==> compressed
dependeny ==> dependency
immediatelly ==> immediately
dervied ==> derived
splitted ==> split
nore ==> not
independed ==> independent
asumed ==> assumed

---

 lib/decompress_bunzip2.c   |    4 ++--
 lib/decompress_unxz.c      |    2 +-
 lib/decompress_unzstd.c    |    4 ++--
 lib/xz/xz_dec_bcj.c        |    2 +-
 lib/xz/xz_dec_lzma2.c      |    8 ++++----
 lib/zlib_inflate/inffast.c |    2 +-
 lib/zstd/huf.h             |    2 +-
 7 files changed, 12 insertions(+), 12 deletions(-)
lib/decompress_bunzip2.c renamed from lib/decompress_bunzip2.c~lib-decompressors-fix-spelling-mistakes +2 -2
@@ -80,7 +80,7 @@
 
 /* This is what we know about each Huffman coding group */
 struct group_data {
-	/* We have an extra slot at the end of limit[] for a sentinal value. */
+	/* We have an extra slot at the end of limit[] for a sentinel value. */
 	int limit[MAX_HUFCODE_BITS+1];
 	int base[MAX_HUFCODE_BITS];
 	int permute[MAX_SYMBOLS];
@@ -337,7 +337,7 @@ static int INIT get_next_block(struct bu
 			pp <<= 1;
 			base[i+1] = pp-(t += temp[i]);
 		}
-		limit[maxLen+1] = INT_MAX; /* Sentinal value for
+		limit[maxLen+1] = INT_MAX; /* Sentinel value for
 					    * reading next sym. */
 		limit[maxLen] = pp+temp[maxLen]-1;
 		base[minLen] = 0;
lib/decompress_unxz.c renamed from lib/decompress_unxz.c~lib-decompressors-fix-spelling-mistakes +1 -1
@@ -23,7 +23,7 @@
  * uncompressible. Thus, we must look for worst-case expansion when the
  * compressor is encoding uncompressible data.
  *
- * The structure of the .xz file in case of a compresed kernel is as follows.
+ * The structure of the .xz file in case of a compressed kernel is as follows.
  * Sizes (as bytes) of the fields are in parenthesis.
  *
  *    Stream Header (12)
lib/decompress_unzstd.c renamed from lib/decompress_unzstd.c~lib-decompressors-fix-spelling-mistakes +2 -2
@@ -16,7 +16,7 @@
  * uncompressible. Thus, we must look for worst-case expansion when the
  * compressor is encoding uncompressible data.
  *
- * The structure of the .zst file in case of a compresed kernel is as follows.
+ * The structure of the .zst file in case of a compressed kernel is as follows.
  * Maximum sizes (as bytes) of the fields are in parenthesis.
  *
  *    Frame Header: (18)
@@ -56,7 +56,7 @@
 /*
  * Preboot environments #include "path/to/decompress_unzstd.c".
  * All of the source files we depend on must be #included.
- * zstd's only source dependeny is xxhash, which has no source
+ * zstd's only source dependency is xxhash, which has no source
  * dependencies.
  *
  * When UNZSTD_PREBOOT is defined we declare __decompress(), which is
lib/xz/xz_dec_bcj.c renamed from lib/xz/xz_dec_bcj.c~lib-decompressors-fix-spelling-mistakes +1 -1
@@ -422,7 +422,7 @@ XZ_EXTERN enum xz_ret xz_dec_bcj_run(str
 
 	/*
 	 * Flush pending already filtered data to the output buffer. Return
-	 * immediatelly if we couldn't flush everything, or if the next
+	 * immediately if we couldn't flush everything, or if the next
 	 * filter in the chain had already returned XZ_STREAM_END.
 	 */
 	if (s->temp.filtered > 0) {
lib/xz/xz_dec_lzma2.c renamed from lib/xz/xz_dec_lzma2.c~lib-decompressors-fix-spelling-mistakes +4 -4
@@ -147,8 +147,8 @@ struct lzma_dec {
 
 	/*
 	 * LZMA properties or related bit masks (number of literal
-	 * context bits, a mask dervied from the number of literal
-	 * position bits, and a mask dervied from the number
+	 * context bits, a mask derived from the number of literal
+	 * position bits, and a mask derived from the number
 	 * position bits)
 	 */
 	uint32_t lc;
@@ -484,7 +484,7 @@ static __always_inline void rc_normalize
 }
 
 /*
- * Decode one bit. In some versions, this function has been splitted in three
+ * Decode one bit. In some versions, this function has been split in three
  * functions so that the compiler is supposed to be able to more easily avoid
  * an extra branch. In this particular version of the LZMA decoder, this
  * doesn't seem to be a good idea (tested with GCC 3.3.6, 3.4.6, and 4.3.3
@@ -761,7 +761,7 @@ static bool lzma_main(struct xz_dec_lzma
 }
 
 /*
- * Reset the LZMA decoder and range decoder state. Dictionary is nore reset
+ * Reset the LZMA decoder and range decoder state. Dictionary is not reset
  * here, because LZMA state may be reset without resetting the dictionary.
  */
 static void lzma_reset(struct xz_dec_lzma2 *s)
lib/zlib_inflate/inffast.c renamed from lib/zlib_inflate/inffast.c~lib-decompressors-fix-spelling-mistakes +1 -1
@@ -15,7 +15,7 @@ union uu {
 	unsigned char b[2];
 };
 
-/* Endian independed version */
+/* Endian independent version */
 static inline unsigned short
 get_unaligned16(const unsigned short *p)
 {
lib/zstd/huf.h renamed from lib/zstd/huf.h~lib-decompressors-fix-spelling-mistakes +1 -1
@@ -134,7 +134,7 @@ typedef enum {
 	HUF_repeat_none,  /**< Cannot use the previous table */
 	HUF_repeat_check, /**< Can use the previous table but it must be checked. Note : The previous table must have been constructed by HUF_compress{1,
 			     4}X_repeat */
-	HUF_repeat_valid  /**< Can use the previous table and it is asumed to be valid */
+	HUF_repeat_valid  /**< Can use the previous table and it is assumed to be valid */
 } HUF_repeat;
 /** HUF_compress4X_repeat() :
 *   Same as HUF_compress4X_wksp(), but considers using hufTable if *repeat != HUF_repeat_none.

_

author maintainer
#189 lore raw

PATCH 166/192 lib/mpi: fix spelling mistakes

In reply to Andrew Morton

From: Zhen Lei <[email protected]>
Subject: lib/mpi: fix spelling mistakes

Fix some spelling mistakes in comments:
flaged ==> flagged
bufer ==> buffer
multipler ==> multiplier
MULTIPLER ==> MULTIPLIER
leaset ==> least
chnage ==> change

---

 include/linux/mpi.h |    4 ++--
 lib/mpi/longlong.h  |    4 ++--
 lib/mpi/mpicoder.c  |    6 +++---
 lib/mpi/mpiutil.c   |    2 +-
 4 files changed, 8 insertions(+), 8 deletions(-)
include/linux/mpi.h renamed from include/linux/mpi.h~lib-mpi-fix-spelling-mistakes +2 -2
@@ -200,7 +200,7 @@ struct mpi_ec_ctx {
 	unsigned int nbits;            /* Number of bits.  */
 
 	/* Domain parameters.  Note that they may not all be set and if set
-	 * the MPIs may be flaged as constant.
+	 * the MPIs may be flagged as constant.
 	 */
 	MPI p;         /* Prime specifying the field GF(p).  */
 	MPI a;         /* First coefficient of the Weierstrass equation.  */
@@ -267,7 +267,7 @@ int mpi_ec_curve_point(MPI_POINT point,
 /**
  * mpi_get_size() - returns max size required to store the number
  *
- * @a:	A multi precision integer for which we want to allocate a bufer
+ * @a:	A multi precision integer for which we want to allocate a buffer
  *
  * Return: size required to store the number
  */
lib/mpi/longlong.h renamed from lib/mpi/longlong.h~lib-mpi-fix-spelling-mistakes +2 -2
@@ -48,8 +48,8 @@
 
 /* Define auxiliary asm macros.
  *
- * 1) umul_ppmm(high_prod, low_prod, multipler, multiplicand) multiplies two
- * UWtype integers MULTIPLER and MULTIPLICAND, and generates a two UWtype
+ * 1) umul_ppmm(high_prod, low_prod, multiplier, multiplicand) multiplies two
+ * UWtype integers MULTIPLIER and MULTIPLICAND, and generates a two UWtype
  * word product in HIGH_PROD and LOW_PROD.
  *
  * 2) __umulsidi3(a,b) multiplies two UWtype integers A and B, and returns a
lib/mpi/mpicoder.c renamed from lib/mpi/mpicoder.c~lib-mpi-fix-spelling-mistakes +3 -3
@@ -234,11 +234,11 @@ static int count_lzeros(MPI a)
 }
 
 /**
- * mpi_read_buffer() - read MPI to a bufer provided by user (msb first)
+ * mpi_read_buffer() - read MPI to a buffer provided by user (msb first)
  *
  * @a:		a multi precision integer
- * @buf:	bufer to which the output will be written to. Needs to be at
- *		leaset mpi_get_size(a) long.
+ * @buf:	buffer to which the output will be written to. Needs to be at
+ *		least mpi_get_size(a) long.
  * @buf_len:	size of the buf.
  * @nbytes:	receives the actual length of the data written on success and
  *		the data to-be-written on -EOVERFLOW in case buf_len was too
lib/mpi/mpiutil.c renamed from lib/mpi/mpiutil.c~lib-mpi-fix-spelling-mistakes +1 -1
@@ -80,7 +80,7 @@ EXPORT_SYMBOL_GPL(mpi_const);
 /****************
  * Note:  It was a bad idea to use the number of limbs to allocate
  *	  because on a alpha the limbs are large but we normally need
- *	  integers of n bits - So we should chnage this to bits (or bytes).
+ *	  integers of n bits - So we should change this to bits (or bytes).
  *
  *	  But mpi_alloc is used in a lot of places :-)
  */

_

author maintainer
#190 lore raw

PATCH 167/192 lib: memscan() fixlet

In reply to Andrew Morton

From: Alexey Dobriyan <[email protected]>
Subject: lib: memscan() fixlet

Generic version doesn't trucate second argument to char.

Older brother memchr() does as do s390, sparc and i386 assembly versions.

Fortunately, no code passes c >= 256.

---

 lib/string.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/string.c renamed from lib/string.c~lib-memscan-fixlet +1 -1
@@ -977,7 +977,7 @@ void *memscan(void *addr, int c, size_t
 	unsigned char *p = addr;
 
 	while (size) {
-		if (*p == c)
+		if (*p == (unsigned char)c)
 			return (void *)p;
 		p++;
 		size--;

_

author maintainer
#191 lore raw

PATCH 168/192 lib: uninline simple_strtoull()

In reply to Andrew Morton

From: Alexey Dobriyan <[email protected]>
Subject: lib: uninline simple_strtoull()

Gcc inlines simple_strtoull() too agressively.

Given that all 4 signatures match, everything very efficiently calls or tailcalls into simple_strtoull():

	ffffffff81da0240 <simple_strtoll>:
	ffffffff81da0240:       80 3f 2d                cmp    BYTE PTR [rdi],0x2d
	ffffffff81da0243:       74 05                   je     ffffffff81da024a <simple_strtoll+0xa>
	ffffffff81da0245:       e9 76 ff ff ff          jmp    simple_strtoull
	ffffffff81da024a:       48 83 c7 01             add    rdi,0x1
	ffffffff81da024e:       e8 6d ff ff ff          call   simple_strtoull
	ffffffff81da0253:       48 f7 d8                neg    rax
	ffffffff81da0256:       c3                      ret

Space savings (on F34-ish .config)

add/remove: 0/0 grow/shrink: 1/3 up/down: 52/-313 (-261)
Function old new delta
vsscanf 2167 2219 +52
simple_strtoul 72 2 -70
simple_strtoll 143 23 -120
simple_strtol 143 20 -123

---

 lib/vsprintf.c |    1 +
 1 file changed, 1 insertion(+)
lib/vsprintf.c renamed from lib/vsprintf.c~lib-uninline-simple_strtoull +1 -0
@@ -61,6 +61,7 @@
  *
  * This function has caveats. Please use kstrtoull instead.
  */
+noinline
 unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base)
 {
 	unsigned long long result;

_

author maintainer
#192 lore raw

PATCH 169/192 lib/test_string.c: allow module removal

In reply to Andrew Morton

From: Matteo Croce <[email protected]>
Subject: lib/test_string.c: allow module removal

The test_string module can't be removed because it lacks an exit hook. Since there is no reason for it to be permanent, add an empty one to allow module removal.

---

 lib/test_string.c |    5 +++++
 1 file changed, 5 insertions(+)
lib/test_string.c renamed from lib/test_string.c~lib-test_stringc-allow-mode-removal +5 -0
@@ -179,6 +179,10 @@ static __init int strnchr_selftest(void)
 	return 0;
 }
 
+static __exit void string_selftest_remove(void)
+{
+}
+
 static __init int string_selftest_init(void)
 {
 	int test, subtest;
@@ -216,4 +220,5 @@ fail:
 }
 
 module_init(string_selftest_init);
+module_exit(string_selftest_remove);
 MODULE_LICENSE("GPL v2");

_

author maintainer
#193 lore raw

PATCH 170/192 kernel.h: split out kstrtox() and simple_strtox() to a separate header

In reply to Andrew Morton

From: Andy Shevchenko <[email protected]>
Subject: kernel.h: split out kstrtox() and simple_strtox() to a separate header

kernel.h is being used as a dump for all kinds of stuff for a long time. Here is the attempt to start cleaning it up by splitting out kstrtox() and simple_strtox() helpers.

At the same time convert users in header and lib folders to use new header. Though for time being include new header back to kernel.h to avoid twisted indirected includes for existing users.

---

 Documentation/core-api/kernel-api.rst |    7 -
 include/linux/kernel.h                |  143 ----------------------
 include/linux/kstrtox.h               |  155 ++++++++++++++++++++++++
 include/linux/string.h                |    7 -
 include/linux/sunrpc/cache.h          |    1 
 lib/kstrtox.c                         |    5 
 lib/parser.c                          |    1 
 7 files changed, 163 insertions(+), 156 deletions(-)
Documentation/core-api/kernel-api.rst renamed from Documentation/core-api/kernel-api.rst~kernelh-split-out-kstrtox-and-simple_strtox-to-a-separate-header +2 -5
@@ -24,11 +24,8 @@ String Conversions
 .. kernel-doc:: lib/vsprintf.c
    :export:
 
-.. kernel-doc:: include/linux/kernel.h
-   :functions: kstrtol
-
-.. kernel-doc:: include/linux/kernel.h
-   :functions: kstrtoul
+.. kernel-doc:: include/linux/kstrtox.h
+   :functions: kstrtol kstrtoul
 
 .. kernel-doc:: lib/kstrtox.c
    :export:
include/linux/kernel.h renamed from include/linux/kernel.h~kernelh-split-out-kstrtox-and-simple_strtox-to-a-separate-header +1 -142

155 lines not on this page · raw message

include/linux/kstrtox.h new file +155 -0

155 lines not on this page · raw message

include/linux/string.h renamed from include/linux/string.h~kernelh-split-out-kstrtox-and-simple_strtox-to-a-separate-header +0 -7
@@ -2,7 +2,6 @@
 #ifndef _LINUX_STRING_H_
 #define _LINUX_STRING_H_
 
-
 #include <linux/compiler.h>	/* for inline */
 #include <linux/types.h>	/* for size_t */
 #include <linux/stddef.h>	/* for NULL */
@@ -184,12 +183,6 @@ extern char **argv_split(gfp_t gfp, cons
 extern void argv_free(char **argv);
 
 extern bool sysfs_streq(const char *s1, const char *s2);
-extern int kstrtobool(const char *s, bool *res);
-static inline int strtobool(const char *s, bool *res)
-{
-	return kstrtobool(s, res);
-}
-
 int match_string(const char * const *array, size_t n, const char *string);
 int __sysfs_match_string(const char * const *array, size_t n, const char *s);
 
include/linux/sunrpc/cache.h renamed from include/linux/sunrpc/cache.h~kernelh-split-out-kstrtox-and-simple_strtox-to-a-separate-header +1 -0
@@ -14,6 +14,7 @@
 #include <linux/kref.h>
 #include <linux/slab.h>
 #include <linux/atomic.h>
+#include <linux/kstrtox.h>
 #include <linux/proc_fs.h>
 
 /*
lib/kstrtox.c renamed from lib/kstrtox.c~kernelh-split-out-kstrtox-and-simple_strtox-to-a-separate-header +3 -2
@@ -14,11 +14,12 @@
  */
 #include <linux/ctype.h>
 #include <linux/errno.h>
-#include <linux/kernel.h>
-#include <linux/math64.h>
 #include <linux/export.h>
+#include <linux/kstrtox.h>
+#include <linux/math64.h>
 #include <linux/types.h>
 #include <linux/uaccess.h>
+
 #include "kstrtox.h"
 
 const char *_parse_integer_fixup_radix(const char *s, unsigned int *base)
lib/parser.c renamed from lib/parser.c~kernelh-split-out-kstrtox-and-simple_strtox-to-a-separate-header +1 -0
@@ -6,6 +6,7 @@
 #include <linux/ctype.h>
 #include <linux/types.h>
 #include <linux/export.h>
+#include <linux/kstrtox.h>
 #include <linux/parser.h>
 #include <linux/slab.h>
 #include <linux/string.h>

_

author maintainer
#194 lore raw

PATCH 171/192 lz4_decompress: declare LZ4_decompress_safe_withPrefix64k static

In reply to Andrew Morton

From: Rajat Asthana <[email protected]>
Subject: lz4_decompress: declare LZ4_decompress_safe_withPrefix64k static

Declare LZ4_decompress_safe_withPrefix64k as static to fix sparse warning:

Quoted 2 lines

warning: symbol 'LZ4_decompress_safe_withPrefix64k' was not declared. Should it be static?

---

 lib/lz4/lz4_decompress.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/lz4/lz4_decompress.c renamed from lib/lz4/lz4_decompress.c~lz4_decompress-declare-lz4_decompress_safe_withprefix64k-static +1 -1
@@ -481,7 +481,7 @@ int LZ4_decompress_fast(const char *sour
 
 /* ===== Instantiate a few more decoding cases, used more than once. ===== */
 
-int LZ4_decompress_safe_withPrefix64k(const char *source, char *dest,
+static int LZ4_decompress_safe_withPrefix64k(const char *source, char *dest,
 				      int compressedSize, int maxOutputSize)
 {
 	return LZ4_decompress_generic(source, dest,

_

author maintainer
#195 lore raw

PATCH 172/192 lib/decompress_unlz4.c: correctly handle zero-padding around initrds.

In reply to Andrew Morton

From: Dimitri John Ledkov <[email protected]>
Subject: lib/decompress_unlz4.c: correctly handle zero-padding around initrds.

lz4 compatible decompressor is simple. The format is underspecified and relies on EOF notification to determine when to stop. Initramfs buffer format[1] explicitly states that it can have arbitrary number of zero padding. Thus when operating without a fill function, be extra careful to ensure that sizes less than 4, or apperantly empty chunksizes are treated as EOF.

To test this I have created two cpio initrds, first a normal one, main.cpio. And second one with just a single /test-file with content "second" second.cpio. Then i compressed both of them with gzip, and with lz4 -l. Then I created a padding of 4 bytes (dd if=/dev/zero of=pad4 bs=1 count=4). To create four testcase initrds:

1) main.cpio.gzip + extra.cpio.gzip = pad0.gzip
2) main.cpio.lz4 + extra.cpio.lz4 = pad0.lz4
3) main.cpio.gzip + pad4 + extra.cpio.gzip = pad4.gzip
4) main.cpio.lz4 + pad4 + extra.cpio.lz4 = pad4.lz4

The pad4 test-cases replicate the initrd load by grub, as it pads and aligns every initrd it loads.

All of the above boot, however /test-file was not accessible in the initrd for the testcase #4, as decoding in lz4 decompressor failed. Also an error message printed which usually is harmless.

Whith a patched kernel, all of the above testcases now pass, and /test-file is accessible.

This fixes lz4 initrd decompress warning on every boot with grub. And more importantly this fixes inability to load multiple lz4 compressed initrds with grub. This patch has been shipping in Ubuntu kernels since January 2021.

[1] ./Documentation/driver-api/early-userspace/buffer-format.rst

---

 lib/decompress_unlz4.c |    8 ++++++++
 1 file changed, 8 insertions(+)
lib/decompress_unlz4.c renamed from lib/decompress_unlz4.c~lib-decompress_unlz4c-correctly-handle-zero-padding-around-initrds +8 -0
@@ -112,6 +112,9 @@ STATIC inline int INIT unlz4(u8 *input,
 				error("data corrupted");
 				goto exit_2;
 			}
+		} else if (size < 4) {
+			/* empty or end-of-file */
+			goto exit_3;
 		}
 
 		chunksize = get_unaligned_le32(inp);
@@ -125,6 +128,10 @@ STATIC inline int INIT unlz4(u8 *input,
 			continue;
 		}
 
+		if (!fill && chunksize == 0) {
+			/* empty or end-of-file */
+			goto exit_3;
+		}
 
 		if (posp)
 			*posp += 4;
@@ -184,6 +191,7 @@ STATIC inline int INIT unlz4(u8 *input,
 		}
 	}
 
+exit_3:
 	ret = 0;
 exit_2:
 	if (!input)

_

author maintainer
#196 lore raw

PATCH 173/192 checkpatch: scripts/spdxcheck.py now requires python3

In reply to Andrew Morton

From: Guenter Roeck <[email protected]>
Subject: checkpatch: scripts/spdxcheck.py now requires python3

Since commit d0259c42abff ("spdxcheck.py: Use Python 3"), spdxcheck.py explicitly expects to run as python3 script. If "python" still points to python v2.7 and the script is executed with "python scripts/spdxcheck.py", the following error may be seen even if git-python is installed for python3.

Traceback (most recent call last):
File "scripts/spdxcheck.py", line 10, in <module>
import git
ImportError: No module named git

To fix the problem, check for the existence of python3, check if the script is executable and not just for its existence, and execute it directly.

---

 scripts/checkpatch.pl |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
scripts/checkpatch.pl renamed from scripts/checkpatch.pl~checkpatch-scripts-spdxcheckpy-now-requires-python3 +2 -2
@@ -1084,10 +1084,10 @@ sub is_maintained_obsolete {
 sub is_SPDX_License_valid {
 	my ($license) = @_;
 
-	return 1 if (!$tree || which("python") eq "" || !(-e "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
+	return 1 if (!$tree || which("python3") eq "" || !(-x "$root/scripts/spdxcheck.py") || !(-e "$gitroot"));
 
 	my $root_path = abs_path($root);
-	my $status = `cd "$root_path"; echo "$license" | python scripts/spdxcheck.py -`;
+	my $status = `cd "$root_path"; echo "$license" | scripts/spdxcheck.py -`;
 	return 0 if ($status ne "");
 	return 1;
 }

_

author maintainer
#197 lore raw

PATCH 174/192 checkpatch: improve the indented label test

In reply to Andrew Morton

From: Joe Perches <[email protected]>
Subject: checkpatch: improve the indented label test

checkpatch identifies a label only when a terminating colon immediately follows an identifier.

Bitfield definitions can appear to be labels so ignore any spaces between the identifier terminating colon and any digit that may be used to define a bitfield length.

Miscellanea:

o Improve the initial checkpatch comment
o Use the more typical '&&' instead of 'and'
o Require the initial label character to be a non-digit (Can't use $Ident here because $Ident allows ## concatenation)
o Use $sline instead of $line to ignore comments
o Use '$sline !~ /.../' instead of '!($line =~ /.../)'

---

 scripts/checkpatch.pl |   10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
scripts/checkpatch.pl renamed from scripts/checkpatch.pl~checkpatch-improve-the-indented-label-test +7 -3
@@ -5361,9 +5361,13 @@ sub process {
 			}
 		}
 
-#goto labels aren't indented, allow a single space however
-		if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and
-		   !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) {
+# check that goto labels aren't indented (allow a single space indentation)
+# and ignore bitfield definitions like foo:1
+# Strictly, labels can have whitespace after the identifier and before the :
+# but this is not allowed here as many ?: uses would appear to be labels
+		if ($sline =~ /^.\s+[A-Za-z_][A-Za-z\d_]*:(?!\s*\d+)/ &&
+		    $sline !~ /^. [A-Za-z\d_][A-Za-z\d_]*:/ &&
+		    $sline !~ /^.\s+default:/) {
 			if (WARN("INDENTED_LABEL",
 				 "labels should not be indented\n" . $herecurr) &&
 			    $fix) {

_

author maintainer
#198 lore raw

PATCH 175/192 checkpatch: do not complain about positive return values starting with EPOLL

In reply to Andrew Morton

From: Guenter Roeck <[email protected]>
Subject: checkpatch: do not complain about positive return values starting with EPOLL

checkpatch complains about positive return values of poll functions. Example:

WARNING: return of an errno should typically be negative (ie: return -EPOLLIN)
+ return EPOLLIN;

Poll functions return positive values. The defines for the return values of poll functions all start with EPOLL, resulting in a number of false positives. An often used workaround is to assign poll function return values to variables and returning that variable, but that is a less than perfect solution.

There is no error definition which starts with EPOLL, so it is safe to omit the warning for return values starting with EPOLL.

---

 scripts/checkpatch.pl |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
scripts/checkpatch.pl renamed from scripts/checkpatch.pl~checkpatch-do-not-complain-about-positive-return-values-starting-with-epoll +1 -1
@@ -5462,7 +5462,7 @@ sub process {
 # Return of what appears to be an errno should normally be negative
 		if ($sline =~ /\breturn(?:\s*\(+\s*|\s+)(E[A-Z]+)(?:\s*\)+\s*|\s*)[;:,]/) {
 			my $name = $1;
-			if ($name ne 'EOF' && $name ne 'ERROR') {
+			if ($name ne 'EOF' && $name ne 'ERROR' && $name !~ /^EPOLL/) {
 				WARN("USE_NEGATIVE_ERRNO",
 				     "return of an errno should typically be negative (ie: return -$1)\n" . $herecurr);
 			}

_

author maintainer
#199 lore raw

PATCH 176/192 init: print out unknown kernel parameters

In reply to Andrew Morton

From: Andrew Halaney <[email protected]>
Subject: init: print out unknown kernel parameters

It is easy to foobar setting a kernel parameter on the command line without realizing it, there's not much output that you can use to assess what the kernel did with that parameter by default.

Make it a little more explicit which parameters on the command line _looked_ like a valid parameter for the kernel, but did not match anything and ultimately got tossed to init. This is very similar to the unknown parameter message received when loading a module.

This assumes the parameters are processed in a normal fashion, some parameters (dyndbg= for example) don't register their parameter with the rest of the kernel's parameters, and therefore always show up in this list (and are also given to init - like the rest of this list).

Another example is BOOT_IMAGE= is highlighted as an offender, which it technically is, but is passed by LILO and GRUB so most systems will see that complaint.

An example output where "foobared" and "unrecognized" are intentionally invalid parameters:

Kernel command line: BOOT_IMAGE=/boot/vmlinuz-5.12-dirty debug log_buf_len=4M foobared unrecognized=foo Unknown command line parameters: foobared BOOT_IMAGE=/boot/vmlinuz-5.12-dirty unrecognized=foo

---

 init/main.c |   42 ++++++++++++++++++++++++++++++++++++++++++
 1 file changed, 42 insertions(+)
init/main.c renamed from init/main.c~init-print-out-unknown-kernel-parameters +42 -0
@@ -872,6 +872,47 @@ void __init __weak arch_call_rest_init(v
 	rest_init();
 }
 
+static void __init print_unknown_bootoptions(void)
+{
+	char *unknown_options;
+	char *end;
+	const char *const *p;
+	size_t len;
+
+	if (panic_later || (!argv_init[1] && !envp_init[2]))
+		return;
+
+	/*
+	 * Determine how many options we have to print out, plus a space
+	 * before each
+	 */
+	len = 1; /* null terminator */
+	for (p = &argv_init[1]; *p; p++) {
+		len++;
+		len += strlen(*p);
+	}
+	for (p = &envp_init[2]; *p; p++) {
+		len++;
+		len += strlen(*p);
+	}
+
+	unknown_options = memblock_alloc(len, SMP_CACHE_BYTES);
+	if (!unknown_options) {
+		pr_err("%s: Failed to allocate %zu bytes\n",
+			__func__, len);
+		return;
+	}
+	end = unknown_options;
+
+	for (p = &argv_init[1]; *p; p++)
+		end += sprintf(end, " %s", *p);
+	for (p = &envp_init[2]; *p; p++)
+		end += sprintf(end, " %s", *p);
+
+	pr_notice("Unknown command line parameters:%s\n", unknown_options);
+	memblock_free(__pa(unknown_options), len);
+}
+
 asmlinkage __visible void __init __no_sanitize_address start_kernel(void)
 {
 	char *command_line;
@@ -913,6 +954,7 @@ asmlinkage __visible void __init __no_sa
 				  static_command_line, __start___param,
 				  __stop___param - __start___param,
 				  -1, -1, NULL, &unknown_bootoption);
+	print_unknown_bootoptions();
 	if (!IS_ERR_OR_NULL(after_dashes))
 		parse_args("Setting init args", after_dashes, NULL, 0, -1, -1,
 			   NULL, set_init_arg);

_

author maintainer
#200 lore raw

PATCH 177/192 kprobes: remove duplicated strong free_insn_page in x86 and s390

In reply to Andrew Morton

From: Barry Song <[email protected]>
Subject: kprobes: remove duplicated strong free_insn_page in x86 and s390

free_insn_page() in x86 and s390 is same with the common weak function in kernel/kprobes.c. Plus, the comment "Recover page to RW mode before releasing it" in x86 seems insensible to be there since resetting mapping is done by common code in vfree() of module_memfree(). So drop these two duplicated strong functions and related comment, then mark the common one in kernel/kprobes.c strong.

---

 arch/s390/kernel/kprobes.c     |    5 -----
 arch/x86/kernel/kprobes/core.c |    6 ------
 include/linux/kprobes.h        |    1 -
 kernel/kprobes.c               |    2 +-
 4 files changed, 1 insertion(+), 13 deletions(-)
arch/s390/kernel/kprobes.c renamed from arch/s390/kernel/kprobes.c~kprobes-remove-duplicated-strong-free_insn_page-in-x86-and-s390 +0 -5
@@ -44,11 +44,6 @@ void *alloc_insn_page(void)
 	return page;
 }
 
-void free_insn_page(void *page)
-{
-	module_memfree(page);
-}
-
 static void *alloc_s390_insn_page(void)
 {
 	if (xchg(&insn_page_in_use, 1) == 1)
arch/x86/kernel/kprobes/core.c renamed from arch/x86/kernel/kprobes/core.c~kprobes-remove-duplicated-strong-free_insn_page-in-x86-and-s390 +0 -6
@@ -422,12 +422,6 @@ void *alloc_insn_page(void)
 	return page;
 }
 
-/* Recover page to RW mode before releasing it */
-void free_insn_page(void *page)
-{
-	module_memfree(page);
-}
-
 /* Kprobe x86 instruction emulation - only regs->ip or IF flag modifiers */
 
 static void kprobe_emulate_ifmodifiers(struct kprobe *p, struct pt_regs *regs)
include/linux/kprobes.h renamed from include/linux/kprobes.h~kprobes-remove-duplicated-strong-free_insn_page-in-x86-and-s390 +0 -1
@@ -407,7 +407,6 @@ int enable_kprobe(struct kprobe *kp);
 void dump_kprobe(struct kprobe *kp);
 
 void *alloc_insn_page(void);
-void free_insn_page(void *page);
 
 int kprobe_get_kallsym(unsigned int symnum, unsigned long *value, char *type,
 		       char *sym);
kernel/kprobes.c renamed from kernel/kprobes.c~kprobes-remove-duplicated-strong-free_insn_page-in-x86-and-s390 +1 -1
@@ -106,7 +106,7 @@ void __weak *alloc_insn_page(void)
 	return module_alloc(PAGE_SIZE);
 }
 
-void __weak free_insn_page(void *page)
+static void free_insn_page(void *page)
 {
 	module_memfree(page);
 }

_

author maintainer
#201 lore raw

PATCH 178/192 nilfs2: remove redundant continue statement in a while-loop

In reply to Andrew Morton

From: Colin Ian King <[email protected]>
Subject: nilfs2: remove redundant continue statement in a while-loop

The continue statement at the end of the while-loop is redundant, remove it.

Addresses-Coverity: ("Continue has no effect")

---

 fs/nilfs2/btree.c |    1 -
 1 file changed, 1 deletion(-)
fs/nilfs2/btree.c renamed from fs/nilfs2/btree.c~nilfs2-remove-redundant-continue-statement-in-a-while-loop +0 -1
@@ -738,7 +738,6 @@ static int nilfs_btree_lookup_contig(con
 			if (ptr2 != ptr + cnt || ++cnt == maxblocks)
 				goto end;
 			index++;
-			continue;
 		}
 		if (level == maxlevel)
 			break;

_

author maintainer
#202 lore raw

PATCH 179/192 hfsplus: remove unnecessary oom message

In reply to Andrew Morton

From: Zhen Lei <[email protected]>
Subject: hfsplus: remove unnecessary oom message

Fixes scripts/checkpatch.pl warning:
WARNING: Possible unnecessary 'out of memory' message

Remove it can help us save a bit of memory.

---

 fs/hfsplus/xattr.c |    1 -
 1 file changed, 1 deletion(-)
fs/hfsplus/xattr.c renamed from fs/hfsplus/xattr.c~hfsplus-remove-unnecessary-oom-message +0 -1
@@ -204,7 +204,6 @@ check_attr_tree_state_again:
 
 	buf = kzalloc(node_size, GFP_NOFS);
 	if (!buf) {
-		pr_err("failed to allocate memory for header node\n");
 		err = -ENOMEM;
 		goto end_attr_file_creation;
 	}

_

author maintainer
#203 lore raw

PATCH 180/192 hfsplus: report create_date to kstat.btime

In reply to Andrew Morton

From: Chung-Chiang Cheng <[email protected]>
Subject: hfsplus: report create_date to kstat.btime

The create_date field of inode in hfsplus is corresponding to kstat.btime and could be reported in statx.

---

 fs/hfsplus/inode.c |    5 +++++
 1 file changed, 5 insertions(+)
fs/hfsplus/inode.c renamed from fs/hfsplus/inode.c~hfsplus-report-create_date-to-kstatbtime +5 -0
@@ -281,6 +281,11 @@ int hfsplus_getattr(struct user_namespac
 	struct inode *inode = d_inode(path->dentry);
 	struct hfsplus_inode_info *hip = HFSPLUS_I(inode);
 
+	if (request_mask & STATX_BTIME) {
+		stat->result_mask |= STATX_BTIME;
+		stat->btime = hfsp_mt2ut(hip->create_date);
+	}
+
 	if (inode->i_flags & S_APPEND)
 		stat->attributes |= STATX_ATTR_APPEND;
 	if (inode->i_flags & S_IMMUTABLE)

_

author maintainer
#204 lore raw

PATCH 181/192 x86: signal: don't do sas_ss_reset() until we are certain that sigframe won't be abandoned

In reply to Andrew Morton

From: Al Viro <[email protected]>
Subject: x86: signal: don't do sas_ss_reset() until we are certain that sigframe won't be abandoned

Currently we handle SS_AUTODISARM as soon as we have stored the altstack settings into sigframe - that's the point when we have set the things up for eventual sigreturn to restore the old settings. And if we manage to set the sigframe up (we are not done with that yet), everything's fine. However, in case of failure we end up with sigframe-to-be abandoned and SIGSEGV force-delivered. And in that case we end up with inconsistent rules - late failures have altstack reset, early ones do not.

It's trivial to get consistent behaviour - just handle SS_AUTODISARM once we have set the sigframe up and are committed to entering the handler, i.e. in signal_delivered().

---

 include/linux/compat.h |    2 --
 include/linux/signal.h |    2 --
 kernel/signal.c        |   14 ++++----------
 3 files changed, 4 insertions(+), 14 deletions(-)
include/linux/compat.h renamed from include/linux/compat.h~x86-signal-dont-do-sas_ss_reset-until-we-are-certain-that-sigframe-wont-be-abandoned +0 -2
@@ -532,8 +532,6 @@ int __compat_save_altstack(compat_stack_
 			&__uss->ss_sp, label); \
 	unsafe_put_user(t->sas_ss_flags, &__uss->ss_flags, label); \
 	unsafe_put_user(t->sas_ss_size, &__uss->ss_size, label); \
-	if (t->sas_ss_flags & SS_AUTODISARM) \
-		sas_ss_reset(t); \
 } while (0);
 
 /*
include/linux/signal.h renamed from include/linux/signal.h~x86-signal-dont-do-sas_ss_reset-until-we-are-certain-that-sigframe-wont-be-abandoned +0 -2
@@ -462,8 +462,6 @@ int __save_altstack(stack_t __user *, un
 	unsafe_put_user((void __user *)t->sas_ss_sp, &__uss->ss_sp, label); \
 	unsafe_put_user(t->sas_ss_flags, &__uss->ss_flags, label); \
 	unsafe_put_user(t->sas_ss_size, &__uss->ss_size, label); \
-	if (t->sas_ss_flags & SS_AUTODISARM) \
-		sas_ss_reset(t); \
 } while (0);
 
 #ifdef CONFIG_PROC_FS
kernel/signal.c renamed from kernel/signal.c~x86-signal-dont-do-sas_ss_reset-until-we-are-certain-that-sigframe-wont-be-abandoned +4 -10
@@ -2829,6 +2829,8 @@ static void signal_delivered(struct ksig
 	if (!(ksig->ka.sa.sa_flags & SA_NODEFER))
 		sigaddset(&blocked, ksig->sig);
 	set_current_blocked(&blocked);
+	if (current->sas_ss_flags & SS_AUTODISARM)
+		sas_ss_reset(current);
 	tracehook_signal_handler(stepping);
 }
 
@@ -4147,11 +4149,7 @@ int __save_altstack(stack_t __user *uss,
 	int err = __put_user((void __user *)t->sas_ss_sp, &uss->ss_sp) |
 		__put_user(t->sas_ss_flags, &uss->ss_flags) |
 		__put_user(t->sas_ss_size, &uss->ss_size);
-	if (err)
-		return err;
-	if (t->sas_ss_flags & SS_AUTODISARM)
-		sas_ss_reset(t);
-	return 0;
+	return err;
 }
 
 #ifdef CONFIG_COMPAT
@@ -4206,11 +4204,7 @@ int __compat_save_altstack(compat_stack_
 			 &uss->ss_sp) |
 		__put_user(t->sas_ss_flags, &uss->ss_flags) |
 		__put_user(t->sas_ss_size, &uss->ss_size);
-	if (err)
-		return err;
-	if (t->sas_ss_flags & SS_AUTODISARM)
-		sas_ss_reset(t);
-	return 0;
+	return err;
 }
 #endif
 

_

author maintainer
#205 lore raw

PATCH 182/192 exec: remove checks in __register_bimfmt()

In reply to Andrew Morton

From: Alexey Dobriyan <[email protected]>
Subject: exec: remove checks in __register_bimfmt()

Delete NULL check, all callers pass valid pointer.

Delete ->load_binary check -- failure to provide hook in a custom module will be very noticeable at the very first execve call.

---

 fs/exec.c |    3 ---
 1 file changed, 3 deletions(-)
fs/exec.c renamed from fs/exec.c~exec-remove-checks-in-__register_bimfmt +0 -3
@@ -84,9 +84,6 @@ static DEFINE_RWLOCK(binfmt_lock);
 
 void __register_binfmt(struct linux_binfmt * fmt, int insert)
 {
-	BUG_ON(!fmt);
-	if (WARN_ON(!fmt->load_binary))
-		return;
 	write_lock(&binfmt_lock);
 	insert ? list_add(&fmt->lh, &formats) :
 		 list_add_tail(&fmt->lh, &formats);

_

author maintainer
#206 lore raw

PATCH 183/192 kcov: add __no_sanitize_coverage to fix noinstr for all architectures

In reply to Andrew Morton

From: Marco Elver <[email protected]>
Subject: kcov: add __no_sanitize_coverage to fix noinstr for all architectures

Until now no compiler supported an attribute to disable coverage instrumentation as used by KCOV.

To work around this limitation on x86, noinstr functions have their coverage instrumentation turned into nops by objtool. However, this solution doesn't scale automatically to other architectures, such as arm64, which are migrating to use the generic entry code.

Clang [1] and GCC [2] have added support for the attribute recently.
[1] https://github.com/llvm/llvm-project/commit/280333021e9550d80f5c1152a34e33e81df1e178
[2] https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=cec4d4a6782c9bd8d071839c50a239c49caca689
The changes will appear in Clang 13 and GCC 12.

Add __no_sanitize_coverage for both compilers, and add it to noinstr.

Note: In the Clang case, __has_feature(coverage_sanitizer) is only true if the feature is enabled, and therefore we do not require an additional defined(CONFIG_KCOV) (like in the GCC case where __has_attribute(..) is always true) to avoid adding redundant attributes to functions if KCOV is off. That being said, compilers that support the attribute will not generate errors/warnings if the attribute is redundantly used; however, where possible let's avoid it as it reduces preprocessed code size and associated compile-time overheads.

[[email protected]: Implement __has_feature(coverage_sanitizer) in Clang]
[[email protected]: add comment explaining __has_feature() in Clang]
Cc Nick Desaulniers <[email protected]>
Cc Kees Cook <[email protected]>
Cc Will Deacon <[email protected]>
Cc Ard Biesheuvel <[email protected]>
Cc Luc Van Oostenryck <[email protected]>
Cc Arvind Sankar <[email protected]>
Cc Masahiro Yamada <[email protected]>
Cc Sami Tolvanen <[email protected]>
Cc Arnd Bergmann <[email protected]>
Cc Dmitry Vyukov <[email protected]>
Cc Mark Rutland <[email protected]>

---

 include/linux/compiler-clang.h |   17 +++++++++++++++++
 include/linux/compiler-gcc.h   |    6 ++++++
 include/linux/compiler_types.h |    2 +-
 3 files changed, 24 insertions(+), 1 deletion(-)
include/linux/compiler-clang.h renamed from include/linux/compiler-clang.h~kcov-add-__no_sanitize_coverage-to-fix-noinstr-for-all-architectures +17 -0
@@ -13,6 +13,12 @@
 /* all clang versions usable with the kernel support KASAN ABI version 5 */
 #define KASAN_ABI_VERSION 5
 
+/*
+ * Note: Checking __has_feature(*_sanitizer) is only true if the feature is
+ * enabled. Therefore it is not required to additionally check defined(CONFIG_*)
+ * to avoid adding redundant attributes in other configurations.
+ */
+
 #if __has_feature(address_sanitizer) || __has_feature(hwaddress_sanitizer)
 /* Emulate GCC's __SANITIZE_ADDRESS__ flag */
 #define __SANITIZE_ADDRESS__
@@ -46,6 +52,17 @@
 #endif
 
 /*
+ * Support for __has_feature(coverage_sanitizer) was added in Clang 13 together
+ * with no_sanitize("coverage"). Prior versions of Clang support coverage
+ * instrumentation, but cannot be queried for support by the preprocessor.
+ */
+#if __has_feature(coverage_sanitizer)
+#define __no_sanitize_coverage __attribute__((no_sanitize("coverage")))
+#else
+#define __no_sanitize_coverage
+#endif
+
+/*
  * Not all versions of clang implement the type-generic versions
  * of the builtin overflow checkers. Fortunately, clang implements
  * __has_builtin allowing us to avoid awkward version
include/linux/compiler-gcc.h renamed from include/linux/compiler-gcc.h~kcov-add-__no_sanitize_coverage-to-fix-noinstr-for-all-architectures +6 -0
@@ -122,6 +122,12 @@
 #define __no_sanitize_undefined
 #endif
 
+#if defined(CONFIG_KCOV) && __has_attribute(__no_sanitize_coverage__)
+#define __no_sanitize_coverage __attribute__((no_sanitize_coverage))
+#else
+#define __no_sanitize_coverage
+#endif
+
 #if GCC_VERSION >= 50100
 #define COMPILER_HAS_GENERIC_BUILTIN_OVERFLOW 1
 #endif
include/linux/compiler_types.h renamed from include/linux/compiler_types.h~kcov-add-__no_sanitize_coverage-to-fix-noinstr-for-all-architectures +1 -1
@@ -210,7 +210,7 @@ struct ftrace_likely_data {
 /* Section for code which can't be instrumented at all */
 #define noinstr								\
 	noinline notrace __attribute((__section__(".noinstr.text")))	\
-	__no_kcsan __no_sanitize_address
+	__no_kcsan __no_sanitize_address __no_sanitize_coverage
 
 #endif /* __KERNEL__ */
 

_

author maintainer
#207 lore raw

PATCH 184/192 selftests/vm/pkeys: fix alloc_random_pkey() to make it really, really random

In reply to Andrew Morton

From: Dave Hansen <[email protected]>
Subject: selftests/vm/pkeys: fix alloc_random_pkey() to make it really, really random

Patch series "selftests/vm/pkeys: Bug fixes and a new test".

There has been a lot of activity on the x86 front around the XSAVE architecture which is used to context-switch processor state (among other things). In addition, AMD has recently joined the protection keys club by adding processor support for PKU.

The AMD implementation helped uncover a kernel bug around the PKRU "init state", which actually applied to Intel's implementation but was just harder to hit. This series adds a test which is expected to help find this class of bug both on AMD and Intel. All the work around pkeys on x86 also uncovered a few bugs in the selftest.

This patch (of 4):

The "random" pkey allocation code currently does the good old:

	srand((unsigned int)time(NULL));

*But*, it unfortunately does this on every random pkey allocation.

There may be thousands of these a second. time() has a one second resolution. So, each time alloc_random_pkey() is called, the PRNG is *RESET* to time(). This is nasty. Normally, if you do:

	srand(<ANYTHING>);
	foo = rand();
	bar = rand();

You'll be quite guaranteed that 'foo' and 'bar' are different. But, if you do:

	srand(1);
	foo = rand();
	srand(1);
	bar = rand();

You are quite guaranteed that 'foo' and 'bar' are the *SAME*. The recent "fix" effectively forced the test case to use the same "random" pkey for the whole test, unless the test run crossed a second boundary.

Only run srand() once at program startup.

This explains some very odd and persistent test failures I've been seeing.

Fixes 6e373263ce07 ("selftests/vm/pkeys: fix alloc_random_pkey() to make it really random")
Cc Ram Pai <[email protected]>
Cc Sandipan Das <[email protected]>
Cc Florian Weimer <[email protected]>
Cc "Desnes A. Nunes do Rosario" <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Thiago Jung Bauermann <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michal Suchanek <[email protected]>
Cc Shuah Khan <[email protected]>

---

 tools/testing/selftests/vm/protection_keys.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
tools/testing/selftests/vm/protection_keys.c renamed from tools/testing/selftests/vm/protection_keys.c~selftests-vm-pkeys-fix-alloc_random_pkey-to-make-it-really-really-random +2 -1
@@ -561,7 +561,6 @@ int alloc_random_pkey(void)
 	int nr_alloced = 0;
 	int random_index;
 	memset(alloced_pkeys, 0, sizeof(alloced_pkeys));
-	srand((unsigned int)time(NULL));
 
 	/* allocate every possible key and make a note of which ones we got */
 	max_nr_pkey_allocs = NR_PKEYS;
@@ -1552,6 +1551,8 @@ int main(void)
 	int nr_iterations = 22;
 	int pkeys_supported = is_pkeys_supported();
 
+	srand((unsigned int)time(NULL));
+
 	setup_handlers();
 
 	printf("has pkeys: %d\n", pkeys_supported);

_

author maintainer
#208 lore raw

PATCH 185/192 selftests/vm/pkeys: handle negative sys_pkey_alloc() return code

In reply to Andrew Morton

From: Dave Hansen <[email protected]>
Subject: selftests/vm/pkeys: handle negative sys_pkey_alloc() return code

The alloc_pkey() sefltest function wraps the sys_pkey_alloc() system call. On success, it updates its "shadow" register value because sys_pkey_alloc() updates the real register.

But, the success check is wrong. pkey_alloc() considers any non-zero return code to indicate success where the pkey register will be modified. This fails to take negative return codes into account.

Consider only a positive return value as a successful call.

Fixes 5f23f6d082a9 ("x86/pkeys: Add self-tests")
Cc Ram Pai <[email protected]>
Cc Sandipan Das <[email protected]>
Cc Florian Weimer <[email protected]>
Cc "Desnes A. Nunes do Rosario" <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Thiago Jung Bauermann <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michal Suchanek <[email protected]>
Cc Shuah Khan <[email protected]>

---

 tools/testing/selftests/vm/protection_keys.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/vm/protection_keys.c renamed from tools/testing/selftests/vm/protection_keys.c~selftests-vm-pkeys-handle-negative-sys_pkey_alloc-return-code +1 -1
@@ -510,7 +510,7 @@ int alloc_pkey(void)
 			" shadow: 0x%016llx\n",
 			__func__, __LINE__, ret, __read_pkey_reg(),
 			shadow_pkey_reg);
-	if (ret) {
+	if (ret > 0) {
 		/* clear both the bits: */
 		shadow_pkey_reg = set_pkey_bits(shadow_pkey_reg, ret,
 						~PKEY_MASK);

_

author maintainer
#209 lore raw

PATCH 186/192 selftests/vm/pkeys: refill shadow register after implicit kernel write

In reply to Andrew Morton

From: Dave Hansen <[email protected]>
Subject: selftests/vm/pkeys: refill shadow register after implicit kernel write

The pkey test code keeps a "shadow" of the pkey register around. This ensures that any bugs which might write to the register can be caught more quickly.

Generally, userspace has a good idea when the kernel is going to write to the register. For instance, alloc_pkey() is passed a permission mask. The caller of alloc_pkey() can update the shadow based on the return value and the mask.

But, the kernel can also modify the pkey register in a more sneaky way. For mprotect(PROT_EXEC) mappings, the kernel will allocate a pkey and write the pkey register to create an execute-only mapping. The kernel never tells userspace what key it uses for this.

This can cause the test to fail with messages like:

	protection_keys_64.2: pkey-helpers.h:132: _read_pkey_reg: Assertion `pkey_reg == shadow_pkey_reg' failed.

because the shadow was not updated with the new kernel-set value.

Forcibly update the shadow value immediately after an mprotect().

Fixes 6af17cf89e99 ("x86/pkeys/selftests: Add PROT_EXEC test")
Cc Ram Pai <[email protected]>
Cc Sandipan Das <[email protected]>
Cc Florian Weimer <[email protected]>
Cc "Desnes A. Nunes do Rosario" <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Thiago Jung Bauermann <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michal Suchanek <[email protected]>
Cc Shuah Khan <[email protected]>

---

 tools/testing/selftests/vm/protection_keys.c |    7 +++++++
 1 file changed, 7 insertions(+)
tools/testing/selftests/vm/protection_keys.c renamed from tools/testing/selftests/vm/protection_keys.c~selftests-vm-pkeys-refill-shadow-register-after-implicit-kernel-write +7 -0
@@ -1448,6 +1448,13 @@ void test_implicit_mprotect_exec_only_me
 	ret = mprotect(p1, PAGE_SIZE, PROT_EXEC);
 	pkey_assert(!ret);
 
+	/*
+	 * Reset the shadow, assuming that the above mprotect()
+	 * correctly changed PKRU, but to an unknown value since
+	 * the actual alllocated pkey is unknown.
+	 */
+	shadow_pkey_reg = __read_pkey_reg();
+
 	dprintf2("pkey_reg: %016llx\n", read_pkey_reg());
 
 	/* Make sure this is an *instruction* fault */

_

author maintainer
#210 lore raw

PATCH 187/192 selftests/vm/pkeys: exercise x86 XSAVE init state

In reply to Andrew Morton

From: Dave Hansen <[email protected]>
Subject: selftests/vm/pkeys: exercise x86 XSAVE init state

On x86, there is a set of instructions used to save and restore register state collectively known as the XSAVE architecture. There are about a dozen different features managed with XSAVE. The protection keys register, PKRU, is one of those features.

The hardware optimizes XSAVE by tracking when the state has not changed from its initial (init) state. In this case, it can avoid the cost of writing state to memory (it would usually just be a bunch of 0's).

When the pkey register is 0x0 the hardware optionally choose to track the register as being in the init state (optimize away the writes). AMD CPUs do this more aggressively compared to Intel.

On x86, PKRU is rarely in its (very permissive) init state. Instead, the value defaults to something very restrictive. It is not surprising that bugs have popped up in the rare cases when PKRU reaches its init state.

Add a protection key selftest which gets the protection keys register into its init state in a way that should work on Intel and AMD. Then, do a bunch of pkey register reads to watch for inadvertent changes.

This adds "-mxsave" to CFLAGS for all the x86 vm selftests in order to allow use of the XSAVE instruction __builtin functions. This will make the builtins available on all of the vm selftests, but is expected to be harmless.

Cc Ram Pai <[email protected]>
Cc Sandipan Das <[email protected]>
Cc Florian Weimer <[email protected]>
Cc "Desnes A. Nunes do Rosario" <[email protected]>
Cc Ingo Molnar <[email protected]>
Cc Thiago Jung Bauermann <[email protected]>
Cc Michael Ellerman <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Michal Suchanek <[email protected]>
Cc Shuah Khan <[email protected]>

---

 tools/testing/selftests/vm/Makefile          |    4 
 tools/testing/selftests/vm/pkey-x86.h        |    1 
 tools/testing/selftests/vm/protection_keys.c |   73 +++++++++++++++++
 3 files changed, 76 insertions(+), 2 deletions(-)
tools/testing/selftests/vm/Makefile renamed from tools/testing/selftests/vm/Makefile~selftests-vm-pkeys-exercise-x86-xsave-init-state +2 -2
@@ -101,7 +101,7 @@ $(1) $(1)_64: $(OUTPUT)/$(1)_64
 endef
 
 ifeq ($(CAN_BUILD_I386),1)
-$(BINARIES_32): CFLAGS += -m32
+$(BINARIES_32): CFLAGS += -m32 -mxsave
 $(BINARIES_32): LDLIBS += -lrt -ldl -lm
 $(BINARIES_32): $(OUTPUT)/%_32: %.c
 	$(CC) $(CFLAGS) $(EXTRA_CFLAGS) $(notdir $^) $(LDLIBS) -o $@
@@ -109,7 +109,7 @@ $(foreach t,$(TARGETS),$(eval $(call gen
 endif
 
 ifeq ($(CAN_BUILD_X86_64),1)
-$(BINARIES_64): CFLAGS += -m64
+$(BINARIES_64): CFLAGS += -m64 -mxsave
 $(BINARIES_64): LDLIBS += -lrt -ldl
 $(BINARIES_64): $(OUTPUT)/%_64: %.c
 	$(CC) $(CFLAGS) $(EXTRA_CFLAGS) $(notdir $^) $(LDLIBS) -o $@
tools/testing/selftests/vm/pkey-x86.h renamed from tools/testing/selftests/vm/pkey-x86.h~selftests-vm-pkeys-exercise-x86-xsave-init-state +1 -0
@@ -126,6 +126,7 @@ static inline u32 pkey_bit_position(int
 
 #define XSTATE_PKEY_BIT	(9)
 #define XSTATE_PKEY	0x200
+#define XSTATE_BV_OFFSET	512
 
 int pkey_reg_xstate_offset(void)
 {
tools/testing/selftests/vm/protection_keys.c renamed from tools/testing/selftests/vm/protection_keys.c~selftests-vm-pkeys-exercise-x86-xsave-init-state +73 -0

85 lines not on this page · raw message

_

author maintainer
#211 lore raw

PATCH 188/192 lib/decompressors: remove set but not used variabled 'level'

In reply to Andrew Morton

From: Yu Kuai <[email protected]>
Subject: lib/decompressors: remove set but not used variabled 'level'

Fixes gcc '-Wunused-but-set-variable' warning:

lib/decompress_unlzo.c:46:5: warning: variable `level' set but not used [-Wunused-but-set-variable]

It is never used and so can be removed.

[[email protected]: warning: value computed is not used]
Fixes 7dd65feb6c60 ("lib: add support for LZO-compressed kernels")

---

 lib/decompress_unlzo.c |    3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
lib/decompress_unlzo.c renamed from lib/decompress_unlzo.c~lib-decompressors-remove-set-but-not-used-variabled-level +1 -2
@@ -43,7 +43,6 @@ STATIC inline long INIT parse_header(u8
 	int l;
 	u8 *parse = input;
 	u8 *end = input + in_len;
-	u8 level = 0;
 	u16 version;
 
 	/*
@@ -65,7 +64,7 @@ STATIC inline long INIT parse_header(u8
 	version = get_unaligned_be16(parse);
 	parse += 7;
 	if (version >= 0x0940)
-		level = *parse++;
+		parse++;
 	if (get_unaligned_be32(parse) & HEADER_HAS_FILTER)
 		parse += 8; /* flags + filter info */
 	else

_

author maintainer
#212 lore raw

PATCH 189/192 ipc sem: use kvmalloc for sem_undo allocation

In reply to Andrew Morton

From: Vasily Averin <[email protected]>
Subject: ipc sem: use kvmalloc for sem_undo allocation

Patch series "ipc: allocations cleanup", v2.

Some ipc objects use the wrong allocation functions: small objects can use kmalloc(), and vice versa, potentially large objects can use kmalloc().

This patch (of 2):

Size of sem_undo can exceed one page and with the maximum possible nsems = 32000 it can grow up to 64Kb. Let's switch its allocation to kvmalloc to avoid user-triggered disruptive actions like OOM killer in case of high-order memory shortage.

User triggerable high order allocations are quite a problem on heavily fragmented systems. They can be a DoS vector.

---

 ipc/sem.c |   11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
ipc/sem.c renamed from ipc/sem.c~ipc-sem-use-kvmalloc-for-sem_undo-allocation +6 -5
@@ -1154,7 +1154,7 @@ static void freeary(struct ipc_namespace
 		un->semid = -1;
 		list_del_rcu(&un->list_proc);
 		spin_unlock(&un->ulp->lock);
-		kfree_rcu(un, rcu);
+		kvfree_rcu(un, rcu);
 	}
 
 	/* Wake up all pending processes and let them fail with EIDRM. */
@@ -1937,7 +1937,8 @@ static struct sem_undo *find_alloc_undo(
 	rcu_read_unlock();
 
 	/* step 2: allocate new undo structure */
-	new = kzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems, GFP_KERNEL);
+	new = kvzalloc(sizeof(struct sem_undo) + sizeof(short)*nsems,
+		       GFP_KERNEL);
 	if (!new) {
 		ipc_rcu_putref(&sma->sem_perm, sem_rcu_free);
 		return ERR_PTR(-ENOMEM);
@@ -1949,7 +1950,7 @@ static struct sem_undo *find_alloc_undo(
 	if (!ipc_valid_object(&sma->sem_perm)) {
 		sem_unlock(sma, -1);
 		rcu_read_unlock();
-		kfree(new);
+		kvfree(new);
 		un = ERR_PTR(-EIDRM);
 		goto out;
 	}
@@ -1960,7 +1961,7 @@ static struct sem_undo *find_alloc_undo(
 	 */
 	un = lookup_undo(ulp, semid);
 	if (un) {
-		kfree(new);
+		kvfree(new);
 		goto success;
 	}
 	/* step 5: initialize & link new undo structure */
@@ -2420,7 +2421,7 @@ void exit_sem(struct task_struct *tsk)
 		rcu_read_unlock();
 		wake_up_q(&wake_q);
 
-		kfree_rcu(un, rcu);
+		kvfree_rcu(un, rcu);
 	}
 	kfree(ulp);
 }

_

author maintainer
#213 lore raw

PATCH 190/192 ipc: use kmalloc for msg_queue and shmid_kernel

In reply to Andrew Morton

From: Vasily Averin <[email protected]>
Subject: ipc: use kmalloc for msg_queue and shmid_kernel

msg_queue and shmid_kernel are quite small objects, no need to use kvmalloc for them. mhocko@: "Both of them are 256B on most 64b systems."

Previously these objects was allocated via ipc_alloc/ipc_rcu_alloc(), common function for several ipc objects. It had kvmalloc call inside(). Later, this function went away and was finally replaced by direct kvmalloc call, and now we can use more suitable kmalloc/kfree for them.

---

 ipc/msg.c |    6 +++---
 ipc/shm.c |    6 +++---
 2 files changed, 6 insertions(+), 6 deletions(-)
ipc/msg.c renamed from ipc/msg.c~ipc-use-kmalloc-for-msg_queue-and-shmid_kernel +3 -3
@@ -130,7 +130,7 @@ static void msg_rcu_free(struct rcu_head
 	struct msg_queue *msq = container_of(p, struct msg_queue, q_perm);
 
 	security_msg_queue_free(&msq->q_perm);
-	kvfree(msq);
+	kfree(msq);
 }
 
 /**
@@ -147,7 +147,7 @@ static int newque(struct ipc_namespace *
 	key_t key = params->key;
 	int msgflg = params->flg;
 
-	msq = kvmalloc(sizeof(*msq), GFP_KERNEL);
+	msq = kmalloc(sizeof(*msq), GFP_KERNEL);
 	if (unlikely(!msq))
 		return -ENOMEM;
 
@@ -157,7 +157,7 @@ static int newque(struct ipc_namespace *
 	msq->q_perm.security = NULL;
 	retval = security_msg_queue_alloc(&msq->q_perm);
 	if (retval) {
-		kvfree(msq);
+		kfree(msq);
 		return retval;
 	}
 
ipc/shm.c renamed from ipc/shm.c~ipc-use-kmalloc-for-msg_queue-and-shmid_kernel +3 -3
@@ -222,7 +222,7 @@ static void shm_rcu_free(struct rcu_head
 	struct shmid_kernel *shp = container_of(ptr, struct shmid_kernel,
 							shm_perm);
 	security_shm_free(&shp->shm_perm);
-	kvfree(shp);
+	kfree(shp);
 }
 
 static inline void shm_rmid(struct ipc_namespace *ns, struct shmid_kernel *s)
@@ -619,7 +619,7 @@ static int newseg(struct ipc_namespace *
 			ns->shm_tot + numpages > ns->shm_ctlall)
 		return -ENOSPC;
 
-	shp = kvmalloc(sizeof(*shp), GFP_KERNEL);
+	shp = kmalloc(sizeof(*shp), GFP_KERNEL);
 	if (unlikely(!shp))
 		return -ENOMEM;
 
@@ -630,7 +630,7 @@ static int newseg(struct ipc_namespace *
 	shp->shm_perm.security = NULL;
 	error = security_shm_alloc(&shp->shm_perm);
 	if (error) {
-		kvfree(shp);
+		kfree(shp);
 		return error;
 	}
 

_

author maintainer
#214 lore raw

PATCH 191/192 ipc/sem.c: use READ_ONCE()/WRITE_ONCE() for use_global_lock

In reply to Andrew Morton

From: Manfred Spraul <[email protected]>
Subject: ipc/sem.c: use READ_ONCE()/WRITE_ONCE() for use_global_lock

The patch solves three weaknesses in ipc/sem.c:

1) The initial read of use_global_lock in sem_lock() is an intentional race. KCSAN detects these accesses and prints a warning.

2) The code assumes that plain C read/writes are not mangled by the CPU or the compiler.

3) The comment it sysvipc_sem_proc_show() was hard to understand: The rest of the comments in ipc/sem.c speaks about sem_perm.lock, and suddenly this function speaks about ipc_lock_object().

To solve 1) and 2), use READ_ONCE()/WRITE_ONCE(). Plain C reads are used in code that owns sma->sem_perm.lock.

The comment is updated to solve 3)

---

 ipc/sem.c |   14 +++++++++-----
 1 file changed, 9 insertions(+), 5 deletions(-)
ipc/sem.c renamed from ipc/sem.c~ipc-semc-use-read_once-write_once-for-use_global_lock +9 -5
@@ -217,6 +217,8 @@ static int sysvipc_sem_proc_show(struct
  * this smp_load_acquire(), this is guaranteed because the smp_load_acquire()
  * is inside a spin_lock() and after a write from 0 to non-zero a
  * spin_lock()+spin_unlock() is done.
+ * To prevent the compiler/cpu temporarily writing 0 to use_global_lock,
+ * READ_ONCE()/WRITE_ONCE() is used.
  *
  * 2) queue.status: (SEM_BARRIER_2)
  * Initialization is done while holding sem_lock(), so no further barrier is
@@ -342,10 +344,10 @@ static void complexmode_enter(struct sem
 		 * Nothing to do, just reset the
 		 * counter until we return to simple mode.
 		 */
-		sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
+		WRITE_ONCE(sma->use_global_lock, USE_GLOBAL_LOCK_HYSTERESIS);
 		return;
 	}
-	sma->use_global_lock = USE_GLOBAL_LOCK_HYSTERESIS;
+	WRITE_ONCE(sma->use_global_lock, USE_GLOBAL_LOCK_HYSTERESIS);
 
 	for (i = 0; i < sma->sem_nsems; i++) {
 		sem = &sma->sems[i];
@@ -371,7 +373,8 @@ static void complexmode_tryleave(struct
 		/* See SEM_BARRIER_1 for purpose/pairing */
 		smp_store_release(&sma->use_global_lock, 0);
 	} else {
-		sma->use_global_lock--;
+		WRITE_ONCE(sma->use_global_lock,
+				sma->use_global_lock-1);
 	}
 }
 
@@ -412,7 +415,7 @@ static inline int sem_lock(struct sem_ar
 	 * Initial check for use_global_lock. Just an optimization,
 	 * no locking, no memory barrier.
 	 */
-	if (!sma->use_global_lock) {
+	if (!READ_ONCE(sma->use_global_lock)) {
 		/*
 		 * It appears that no complex operation is around.
 		 * Acquire the per-semaphore lock.
@@ -2436,7 +2439,8 @@ static int sysvipc_sem_proc_show(struct
 
 	/*
 	 * The proc interface isn't aware of sem_lock(), it calls
-	 * ipc_lock_object() directly (in sysvipc_find_ipc).
+	 * ipc_lock_object(), i.e. spin_lock(&sma->sem_perm.lock).
+	 * (in sysvipc_find_ipc)
 	 * In order to stay compatible with sem_lock(), we must
 	 * enter / leave complex_mode.
 	 */

_

author maintainer
#215 lore raw

PATCH 192/192 ipc/util.c: use binary search for max_idx

In reply to Andrew Morton

From: Manfred Spraul <[email protected]>
Subject: ipc/util.c: use binary search for max_idx

If semctl(), msgctl() and shmctl() are called with IPC_INFO, SEM_INFO, MSG_INFO or SHM_INFO, then the return value is the index of the highest used index in the kernel's internal array recording information about all SysV objects of the requested type for the current namespace. (This information can be used with repeated ..._STAT or ..._STAT_ANY operations to obtain information about all SysV objects on the system.)

There is a cache for this value. But when the cache needs up be updated, then the highest used index is determined by looping over all possible values. With the introduction of IPCMNI_EXTEND_SHIFT, this could be a loop over 16 million entries. And due to /proc/sys/kernel/*next_id, the index values do not need to be consecutive.

With <write 16000000 to msg_next_id>, msgget(), msgctl(,IPC_RMID) in a loop, I have observed a performance increase of around factor 13000.

As there is no get_last() function for idr structures: Implement a "get_last()" using a binary search.

As far as I see, ipc is the only user that needs get_last(), thus implement it in ipc/util.c and not in a central location.

---

 ipc/util.c |   44 +++++++++++++++++++++++++++++++++++++++-----
 ipc/util.h |    3 +++
 2 files changed, 42 insertions(+), 5 deletions(-)
ipc/util.c renamed from ipc/util.c~ipc-utilc-use-binary-search-for-max_idx +39 -5
@@ -64,6 +64,7 @@
 #include <linux/memory.h>
 #include <linux/ipc_namespace.h>
 #include <linux/rhashtable.h>
+#include <linux/log2.h>
 
 #include <asm/unistd.h>
 
@@ -451,6 +452,41 @@ static void ipc_kht_remove(struct ipc_id
 }
 
 /**
+ * ipc_search_maxidx - search for the highest assigned index
+ * @ids: ipc identifier set
+ * @limit: known upper limit for highest assigned index
+ *
+ * The function determines the highest assigned index in @ids. It is intended
+ * to be called when ids->max_idx needs to be updated.
+ * Updating ids->max_idx is necessary when the current highest index ipc
+ * object is deleted.
+ * If no ipc object is allocated, then -1 is returned.
+ *
+ * ipc_ids.rwsem needs to be held by the caller.
+ */
+static int ipc_search_maxidx(struct ipc_ids *ids, int limit)
+{
+	int tmpidx;
+	int i;
+	int retval;
+
+	i = ilog2(limit+1);
+
+	retval = 0;
+	for (; i >= 0; i--) {
+		tmpidx = retval | (1<<i);
+		/*
+		 * "0" is a possible index value, thus search using
+		 * e.g. 15,7,3,1,0 instead of 16,8,4,2,1.
+		 */
+		tmpidx = tmpidx-1;
+		if (idr_get_next(&ids->ipcs_idr, &tmpidx))
+			retval |= (1<<i);
+	}
+	return retval - 1;
+}
+
+/**
  * ipc_rmid - remove an ipc identifier
  * @ids: ipc identifier set
  * @ipcp: ipc perm structure containing the identifier to remove
@@ -468,11 +504,9 @@ void ipc_rmid(struct ipc_ids *ids, struc
 	ipcp->deleted = true;
 
 	if (unlikely(idx == ids->max_idx)) {
-		do {
-			idx--;
-			if (idx == -1)
-				break;
-		} while (!idr_find(&ids->ipcs_idr, idx));
+		idx = ids->max_idx-1;
+		if (idx >= 0)
+			idx = ipc_search_maxidx(ids, idx);
 		ids->max_idx = idx;
 	}
 }
ipc/util.h renamed from ipc/util.h~ipc-utilc-use-binary-search-for-max_idx +3 -0
@@ -145,6 +145,9 @@ int ipcperms(struct ipc_namespace *ns, s
  * ipc_get_maxidx - get the highest assigned index
  * @ids: ipc identifier set
  *
+ * The function returns the highest assigned index for @ids. The function
+ * doesn't scan the idr tree, it uses a cached value.
+ *
  * Called with ipc_ids.rwsem held for reading.
  */
 static inline int ipc_get_maxidx(struct ipc_ids *ids)

_

#216 lore raw
In reply to Andrew Morton
Quoted 4 lines · Andrew Morton

This is the rest of the -mm tree, less 66 patches which are dependent on things which are (or were recently) in linux-next. I'll trickle that material over next week.

I haven't bisected this yet, but with the current -git I'm getting

   watchdog: BUG: soft lockup - CPU#41 stuck for 49s!

and the common call chain seems to be in flush_tlb_mm_range -> on_each_cpu_cond_mask.

Commit e058a84bfddc42ba356a2316f2cf1141974625c9 is good, and looking at the pulls and merges I've done since, this -mm series looks like the obvious culprit.

I'll go start bisection, but I thought I'd give a heads-up in case somebody else has seen TLB-flush-related lockups and already figured out the guilty party..

Linus

#217 lore raw
Quoted 4 lines · Linus Torvalds

Commit e058a84bfddc42ba356a2316f2cf1141974625c9 is good, and looking at the pulls and merges I've done since, this -mm series looks like the obvious culprit.

No, unless my bisection is wrong, the -mm branch is innocent, and was discarded from the suspects on the very first bisection trial.

So never mind.

Linus