Skip to contentSkip to conversation

exfat: memory optimisations and stringent integrity checks for up-case table

PATCH In review David Timber 2 participants 11 messages May 5 – May 14

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v2 cover exfat: memory optimisations and stringent integrity checks for up-case table

Reroll v1:

- Mark the volume read-only if the up-case table seems damaged
- Inline exfat_lookup_upcase_ptable()
- Fix uninitialised variable(ret) in exfat_load_upcase_table()

Reroll v2:

- Optimise and refactor filename up-case conversion (Suggested-by: Yuezhang Mo)
- Fix memory leak on module init failure,
- Remove exfat_init_default_upcase_ptable()
- Use null-terminated array consistent with the convention in Linux kernel
- Add missing function and variable attributes(__init, __initconst)
- Return identity instead of zero from exfat_lookup_upcase_ptable() (Suggested-by: Yuezhang Mo)
- Remove unnecessary global variables
- Refactor exfat_load_upcase_table()
- Add test exfat-test-illegal-chr.sh for exfat_illegal_chr()

v1 coverletter:

This round of patches introduces efficient upcase table implementation to exFAT as well as more stringent check against the upcase table when mounting the volume.

**Theoretical trade offs**

The use of "paged upcase table" saw runtime memory footprint reduced from 131KB to 8KB(+some slab overhead). Other trade offs include:

- Reduced .rodata usage from 5KB to 2KB at the cost of added delay in module initialisation for populating the default upcase table
- Slight performance increase from reduced cache misses when traversing directories with entries with a wide range of unicode code points

**Tests**

Upcase table test cases are available in my repo(https://github.com/dxdxdt/gists/tree/master/writeups/exfat):

- exfat-default-upcase:
- -c option: uncompresses and prints the default compressed upcase table
- -p option: tests if exfat_populate_upcase_ptable() produces the same default upcase table included in the kernel prior to the patches
- -pc option: generates .rodata included in fs/exfat/tables.c
- exfat-test-upcase: brute forces combinations(2^32) of unicode upcase conversion to ensure that no regression is introduced. The test finishes within 24 hours ;)
- exfat-profile-upcase.sh and exfat-print-all-allowed: profile kernel memory use per mount and the worse-case directory traversal, entries filled with a range of unicode code points. Run with make profile
- exfat-test-illegal-chr.sh: exfat_illegal_chr() regression test

**Profiling**

When tested with 16 volumes(make profile), ~1MB saving in memory usage per volume is observed(available mem 122528 -> 140884).

**NOTES**

Errors found in the "recommended" upcase table are outlined in fs/exfat/tables.c.

The value of EXFAT_UPTBL_PAGESIZE(512 __u16 entries or 1024 bytes) is determined to be the best based on the data:

```
  $ ./exfat-default-upcase > test-control
  ...
  entries: 874 (1748 bytes)
  non-empty pages: 8 (nb_page * pagesize * 2 = 512 * 8 * 2 = 8192 bytes)
```

The program reports that the total of 8 "pages" of 1KiB are used by the table.

Regression test:

```

  (with the mainline exfat module)
  $ ./exfat-test-upcase /PATH/TO/EXFAT/MOUNTPOINT > a
  ...

  (with the patched exfat module)
  $ ./exfat-test-upcase /PATH/TO/EXFAT/MOUNTPOINT > b
  ...

  $ diff a b
```

Let me know if the test programs need to be added in the source tree (perhaps in /tools/testing/selftests/filesystems/exfat/ ??)

David Timber (4):
exfat: use upcase_ptable and upcase_range_info to reduce memory
footprint
exfat: optimise and refactor filename up-case conversion
exfat: add default_upcase option (read-only)
exfat: more pedantic upcase table validity check

 fs/exfat/Makefile   |   2 +-
 fs/exfat/exfat_fs.h |  49 ++-
 fs/exfat/nls.c      | 614 +++++++-----------------------
 fs/exfat/super.c    |  13 +
 fs/exfat/upcase.c   | 900 ++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 1090 insertions(+), 488 deletions(-)
 create mode 100644 fs/exfat/upcase.c
Signature · 1 line
2.53.0.1.ga224b40d3f.dirty
#1 lore raw

PATCH v2 1/4 exfat: use upcase_ptable and upcase_range_info to reduce memory footprint

Introduce upcase_ptable("paged up-case table"). Instead of allocating the entire 131KB of memory(2^16 possible entries times 2 bytes), break up the upcase table into 1024-byte pages and do not allocate memory for pages containing no data. The size of default upcase table populated during module initialisation is 8KB.

Reduce the size of .rodata section further by employing exfat_upcase_range_info, each representing a run in the unicode BMP. Each entry in exfat_def_utbl_ri represent the exact copy of the "recommended upcase table" from the exFAT spec but compressed in a format of our own(less than 1KB of .rodata compared to 5836 bytes of the compressed format in the spec).

When the contents of the upcase table loaded from the volume is identical to that of the default upcase table during mounting process, free the memory dynamically allocated to load the table and set up the super block to use the default table already populated during module initialisation.

As a custom upcase table is almost never used, keeping a copy of upcase table for every super block is wasteful. If one is used, it means that name hashing behaviour may not work as expected so warn the user by printing a kernel message.

---
 fs/exfat/Makefile   |   2 +-
 fs/exfat/exfat_fs.h |  49 ++-
 fs/exfat/nls.c      | 495 +++---------------------
 fs/exfat/super.c    |  10 +
 fs/exfat/upcase.c   | 900 ++++++++++++++++++++++++++++++++++++++++++++
 5 files changed, 1016 insertions(+), 440 deletions(-)
 create mode 100644 fs/exfat/upcase.c
fs/exfat/Makefile +1 -1
index ed51926a4971..30fe75a725b8 100644
@@ -5,4 +5,4 @@
 obj-$(CONFIG_EXFAT_FS) += exfat.o
 
 exfat-y	:= inode.o namei.o dir.o super.o fatent.o cache.o nls.o misc.o \
-	   file.o balloc.o
+	   file.o balloc.o upcase.o
fs/exfat/exfat_fs.h +48 -1

73 lines not on this page · raw message

fs/exfat/nls.c +57 -438

579 lines not on this page · raw message

fs/exfat/super.c +10 -0
index 95d87e2d7717..3197263aa1be 100644
@@ -657,6 +657,7 @@ static int __exfat_fill_super(struct super_block *sb,
 	exfat_free_bitmap(sbi);
 free_bh:
 	brelse(sbi->boot_bh);
+	exfat_free_upcase_table(sbi);
 	return ret;
 }
 
@@ -752,6 +753,7 @@ static int exfat_get_tree(struct fs_context *fc)
 
 static void exfat_free_sbi(struct exfat_sb_info *sbi)
 {
+	exfat_free_upcase_table(sbi);
 	exfat_free_iocharset(sbi);
 	kfree(sbi);
 }
@@ -896,6 +898,12 @@ static int __init init_exfat_fs(void)
 {
 	int err;
 
+	err = exfat_populate_upcase_ptable(&exfat_def_upcase_ptable);
+	if (err) {
+		WARN_ON(err == -EINVAL);
+		return err;
+	}
+
 	err = exfat_cache_init();
 	if (err)
 		return err;
@@ -919,6 +927,7 @@ static int __init init_exfat_fs(void)
 	kmem_cache_destroy(exfat_inode_cachep);
 shutdown_cache:
 	exfat_cache_shutdown();
+	exfat_free_upcase_ptable(&exfat_def_upcase_ptable);
 	return err;
 }
 
@@ -932,6 +941,7 @@ static void __exit exit_exfat_fs(void)
 	kmem_cache_destroy(exfat_inode_cachep);
 	unregister_filesystem(&exfat_fs_type);
 	exfat_cache_shutdown();
+	exfat_free_upcase_ptable(&exfat_def_upcase_ptable);
 }
 
 module_init(init_exfat_fs);
fs/exfat/upcase.c new file +900 -0

900 lines not on this page · raw message

Signature · 1 line
2.53.0.1.ga224b40d3f.dirty
#2 lore raw

Re: [PATCH v2 1/4] exfat: use upcase_ptable and upcase_range_info to reduce memory footprint

fs/exfat/upcase.c line 35

Quoted 11 lines

+ * To maintain interoperability, these errors are not corrected.
+ */

fs/exfat/upcase.c new file +9 -0
+static const struct exfat_upcase_range_info def_utbl_ri[] __initconst = {
+       /* ASCII */
+       {
+               /* (index = 0, len = 26) */
+               .start = 0x0061,
+               .end   = 0x007B,
+               .value = 0x0041,
+               .inc   = 0x0001,
+       },

How about changing to this style? the table looks too long.

/* start end value inc */
/* ASCII */
[0] = {0x0061, 0x007B, 0x0041, 0x0001}, /* 26 characters */

And 'len' in the comments is not very meaningful, the comments indicate how many characters need to be converted more appropriately.

Quoted 4 lines
fs/exfat/super.c +0 -0
@@ -896,6 +898,12 @@ static int __init init_exfat_fs(void)
 {
        int err;

fs/exfat/super.c static int __init init_exfat_fs(void) · line 909

Quoted 10 lines
fs/exfat/super.c +6 -0
 
+       err = exfat_populate_upcase_ptable(&exfat_def_upcase_ptable);
+       if (err) {
+               WARN_ON(err == -EINVAL);
+               return err;
+       }
+
        err = exfat_cache_init();
        if (err)
                return err;

As I said before, we should call exfat_free_upcase_ptable() if exfat_cache_init() return an error.

Quoted 5 lines
fs/exfat/nls.c +0 -1
@@ -691,53 +330,36 @@ static int exfat_load_upcase_table(struct super_block *sb,
                brelse(bh);
        }
 
-       if (index >= 0xFFFF && utbl_checksum == chksum)

fs/exfat/nls.c static int exfat_load_upcase_table(struct super_block *sb, · line 342

Quoted 10 lines
fs/exfat/nls.c +9 -0
+       if (index >= 0xFFFF && utbl_checksum == chksum) {
+               /*
+                * is_default being set does not necessarily mean the contents are exact same as the
+                * upcase table loaded from the volume may be missing some entries. The checksum
+                * matching should be enough to cover that case.
+                */
+               if (is_default && utbl_checksum == EXFAT_DEF_UTBL_CHKSUM) {
+                       exfat_free_upcase_ptable(upcase_table);
+                       kvfree(upcase_table);
 

If the default upcase table is used, 874 entries will be set.

We can determine whether the default upcase table is being used, rather than checksum, by checking is_default and the number of entries.

#3 lore raw

Re: [PATCH v2 1/4] exfat: use upcase_ptable and upcase_range_info to reduce memory footprint

Quoted 11 lines · On 5/7/26 21:03, [email protected] wrote:

fs/exfat/upcase.c line 35

Quoted 11 lines

+ * To maintain interoperability, these errors are not corrected.
+ */

fs/exfat/upcase.c new file +9 -0
+static const struct exfat_upcase_range_info def_utbl_ri[] __initconst = {
+       /* ASCII */
+       {
+               /* (index = 0, len = 26) */
+               .start = 0x0061,
+               .end   = 0x007B,
+               .value = 0x0041,
+               .inc   = 0x0001,
+       },
Quoted 8 lines

How about changing to this style? the table looks too long.

/* start end value inc */
/* ASCII */
[0] = {0x0061, 0x007B, 0x0041, 0x0001}, /* 26 characters */

And 'len' in the comments is not very meaningful, the comments indicate how many characters need to be converted more appropriately.

Agreed. Will change the procuder program.

Quoted 4 lines
Quoted 4 lines
fs/exfat/super.c +0 -0
@@ -896,6 +898,12 @@ static int __init init_exfat_fs(void)
 {
        int err;
 
Quoted 12 lines

fs/exfat/super.c static int __init init_exfat_fs(void) · line 909

Quoted 10 lines
fs/exfat/super.c +6 -0
+       err = exfat_populate_upcase_ptable(&exfat_def_upcase_ptable);
+       if (err) {
+               WARN_ON(err == -EINVAL);
+               return err;
+       }
+
        err = exfat_cache_init();
        if (err)
                return err;

As I said before, we should call exfat_free_upcase_ptable() if exfat_cache_init() return an error.

This is frustrating. Yes, this is skill issues on my end, but it makes me wonder why we can't just have only two return points(success and bail).

Whilst trying to hunt down the kernel memory corruption error in f2fs, I've witness the horrors in the fill_super() as well. Why complicate things by having too many goto labels?

https://www.kernel.org/doc/html/latest/process/coding-style.html#centralized-exiting-of-functions

I think this generally comes from the coding guidelines that mixes up goto and return statements for clean ups. Sure, it makes sense if this is the function that gets called millions of times in like skb a handling callback, where avoiding a couple of no-op calls actually matters. In this case, I fail to see if doing something like this can hurt anything as long as we're careful with the order of resources being freed:

    static int __init init_exfat_fs(void)
    {
    	int err;

    	err = exfat_populate_upcase_ptable(&exfat_def_upcase_ptable);
    	if (err) {
    		WARN_ON(err == -EINVAL);
    		goto bail;
    	}

    	err = exfat_cache_init();
    	if (err)
    		goto bail;

    	exfat_inode_cachep = kmem_cache_create("exfat_inode_cache",
    			sizeof(struct exfat_inode_info),
    			0, SLAB_RECLAIM_ACCOUNT,
    			exfat_inode_init_once);
    	if (!exfat_inode_cachep) {
    		err = -ENOMEM;
    		goto bail;
    	}

    	err = register_filesystem(&exfat_fs_type);
    	if (err)
    		goto bail;

    	return 0;

    bail:
    	kmem_cache_destroy(exfat_inode_cachep);
    	exfat_cache_shutdown();
    	exfat_free_upcase_ptable(&exfat_def_upcase_ptable);

    	return err;
    }
Quoted 17 lines
Quoted 5 lines
fs/exfat/nls.c +0 -1
@@ -691,53 +330,36 @@ static int exfat_load_upcase_table(struct super_block *sb,
                brelse(bh);
        }
 
-       if (index >= 0xFFFF && utbl_checksum == chksum)

fs/exfat/nls.c static int exfat_load_upcase_table(struct super_block *sb, · line 342

Quoted 10 lines
fs/exfat/nls.c +9 -0
+       if (index >= 0xFFFF && utbl_checksum == chksum) {
+               /*
+                * is_default being set does not necessarily mean the contents are exact same as the
+                * upcase table loaded from the volume may be missing some entries. The checksum
+                * matching should be enough to cover that case.
+                */
+               if (is_default && utbl_checksum == EXFAT_DEF_UTBL_CHKSUM) {
+                       exfat_free_upcase_ptable(upcase_table);
+                       kvfree(upcase_table);
 

If the default upcase table is used, 874 entries will be set.

Quoted 3 lines

We can determine whether the default upcase table is being used, rather than checksum, by checking is_default and the number of entries.

Hmmm.. I can read between the lines. I get what you're saying.

I have to admit, I realise now that the idea of is_default was rather stupid. Even with the algorithm you suggested, I've found that there are some corner cases that would have been missed.

The look up op will definitely add a few milliseconds to the mounting process. Let's not do that.

The thing is, we're probably giving too much love to the codepath that will (probably) never be executed in production. No sane formatter will ever use non-default table. We can even assume that volumes with non-default upcase tables are probably with malicious intent. I have no real-world data, though. If anyone can prove that there is indeed an exfat formatting util that uses non-default upcase table, I'd like to be enlightened, please.

Anyway, we're stuck with the specs and so we have to do our best to find the common ground. How about removing is_default and just checking utbl_checksum == EXFAT_DEF_UTBL_CHKSUM for non-default fallback? That should be more than enough. I don't think other implementations actually bother to use the upcase table in the first place.

Anyway, my patches will have to wait whilst Jeon is trying hard to get iomap settled down in the mainline. In the mean time, I will continue to contribute from userland as much as possible.

Regards,
Davo

#4 lore raw

Re: [PATCH v2 1/4] exfat: use upcase_ptable and upcase_range_info to reduce memory footprint

Quoted 38 lines · On 5/7/26 21:03, [email protected] wrote:
Quoted 11 lines

fs/exfat/upcase.c line 35

Quoted 11 lines

+ * To maintain interoperability, these errors are not corrected.
+ */

fs/exfat/upcase.c new file +9 -0
+static const struct exfat_upcase_range_info def_utbl_ri[] __initconst = {
+       /* ASCII */
+       {
+               /* (index = 0, len = 26) */
+               .start = 0x0061,
+               .end   = 0x007B,
+               .value = 0x0041,
+               .inc   = 0x0001,
+       },
Quoted 8 lines

How about changing to this style? the table looks too long.

/* start end value inc */
/* ASCII */
[0] = {0x0061, 0x007B, 0x0041, 0x0001}, /* 26 characters */

And 'len' in the comments is not very meaningful, the comments indicate how many characters need to be converted more appropriately.

Agreed. Will change the procuder program.

Quoted 4 lines
Quoted 4 lines
fs/exfat/super.c +0 -0
@@ -896,6 +898,12 @@ static int __init init_exfat_fs(void)
 {
        int err;
 
Quoted 12 lines

fs/exfat/super.c static int __init init_exfat_fs(void) · line 909

Quoted 10 lines
fs/exfat/super.c +6 -0
+       err = exfat_populate_upcase_ptable(&exfat_def_upcase_ptable);
+       if (err) {
+               WARN_ON(err == -EINVAL);
+               return err;
+       }
+
        err = exfat_cache_init();
        if (err)
                return err;

As I said before, we should call exfat_free_upcase_ptable() if exfat_cache_init() return an error.

Quoted 7 lines

This is frustrating. Yes, this is skill issues on my end, but it makes me wonder why we can't just have only two return points(success and bail).

Whilst trying to hunt down the kernel memory corruption error in f2fs, I've witness the horrors in the fill_super() as well. Why complicate things by having too many goto labels?

A single bail label might seem simpler, but it obscures the pairing of resource allocation and release. Using multiple goto labels (e.g., err_free_upcase, err_shutdown_cache), each cleanup operation perfectly matches an allocation step, and the reverse order is explicit.

A unified bail approach enforces that each cleanup function can be safely called even if the resource was never allocated; while this is currently true, future additions of new cleanup functions might overlook this.

Quoted 84 lines

I think this generally comes from the coding guidelines that mixes up goto and return statements for clean ups. Sure, it makes sense if this is the function that gets called millions of times in like skb a handling callback, where avoiding a couple of no-op calls actually matters. In this case, I fail to see if doing something like this can hurt anything as long as we're careful with the order of resources being freed:

    static int __init init_exfat_fs(void)
    {
        int err;

        err = exfat_populate_upcase_ptable(&exfat_def_upcase_ptable);
        if (err) {
                WARN_ON(err == -EINVAL);
                goto bail;
        }

        err = exfat_cache_init();
        if (err)
                goto bail;

        exfat_inode_cachep = kmem_cache_create("exfat_inode_cache",
                        sizeof(struct exfat_inode_info),
                        0, SLAB_RECLAIM_ACCOUNT,
                        exfat_inode_init_once);
        if (!exfat_inode_cachep) {
                err = -ENOMEM;
                goto bail;
        }

        err = register_filesystem(&exfat_fs_type);
        if (err)
                goto bail;

        return 0;

    bail:
        kmem_cache_destroy(exfat_inode_cachep);
        exfat_cache_shutdown();
        exfat_free_upcase_ptable(&exfat_def_upcase_ptable);

        return err;
    }
Quoted 17 lines
Quoted 5 lines
fs/exfat/nls.c +0 -1
@@ -691,53 +330,36 @@ static int exfat_load_upcase_table(struct super_block *sb,
                brelse(bh);
        }
 
-       if (index >= 0xFFFF && utbl_checksum == chksum)

fs/exfat/nls.c static int exfat_load_upcase_table(struct super_block *sb, · line 342

Quoted 10 lines
fs/exfat/nls.c +9 -0
+       if (index >= 0xFFFF && utbl_checksum == chksum) {
+               /*
+                * is_default being set does not necessarily mean the contents are exact same as the
+                * upcase table loaded from the volume may be missing some entries. The checksum
+                * matching should be enough to cover that case.
+                */
+               if (is_default && utbl_checksum == EXFAT_DEF_UTBL_CHKSUM) {
+                       exfat_free_upcase_ptable(upcase_table);
+                       kvfree(upcase_table);
 

If the default upcase table is used, 874 entries will be set.

Quoted 3 lines

We can determine whether the default upcase table is being used, rather than checksum, by checking is_default and the number of entries.

Hmmm.. I can read between the lines. I get what you're saying.

I have to admit, I realise now that the idea of is_default was rather stupid. Even with the algorithm you suggested, I've found that there are some corner cases that would have been missed.

The look up op will definitely add a few milliseconds to the mounting process. Let's not do that.

The thing is, we're probably giving too much love to the codepath that will (probably) never be executed in production. No sane formatter will ever use non-default table. We can even assume that volumes with non-default upcase tables are probably with malicious intent. I have no real-world data, though. If anyone can prove that there is indeed an exfat formatting util that uses non-default upcase table, I'd like to be enlightened, please.

Quoted 5 lines

Anyway, we're stuck with the specs and so we have to do our best to find the common ground. How about removing is_default and just checking utbl_checksum == EXFAT_DEF_UTBL_CHKSUM for non-default fallback? That should be more than enough. I don't think other implementations actually bother to use the upcase table in the first place.

I understand your point that currently known formatters all use default tables, and I agree that in practice, the probability of a non-default table unexpectedly matching the default checksum is extremely low, and such conflicts are extremely rare. However, theoretically, simply checking utbl_checksum == EXFAT_DEF_UTBL_CHKSUM, even with checking tbl_size == EXFAT_NUM_UPCASE * 2, is not rigorous.

#5 lore raw

Re: [PATCH v2 1/4] exfat: use upcase_ptable and upcase_range_info to reduce memory footprint

Quoted 8 lines · On 5/14/26 19:04, [email protected] wrote:

A single bail label might seem simpler, but it obscures the pairing of resource allocation and release. Using multiple goto labels (e.g., err_free_upcase, err_shutdown_cache), each cleanup operation perfectly matches an allocation step, and the reverse order is explicit.

A unified bail approach enforces that each cleanup function can be safely called even if the resource was never allocated; while this is currently true, future additions of new cleanup functions might overlook this.

I dug further into this rabbit hole.

Turns out, this debate goes way back to early 2000s. A quick LLM prompt revealed that numberous kernel devs already pointed it out and different parts of the kernel have their own agenda(especially ARM and Netfilter devs). I was just rediscovering it. A simple fs like exFAT will probably never grow that much complexity (hopefully) so it wouldn't make much difference on this matter.

I'm in no position to demand such changes to exFAT, but I'd be voicing a different opinions on the projects I maintain. I will report back with additional error labels in the fill_super() and module init function.

Quoted 6 lines

I understand your point that currently known formatters all use default tables, and I agree that in practice, the probability of a non-default table unexpectedly matching the default checksum is extremely low, and such conflicts are extremely rare. However, theoretically, simply checking utbl_checksum == EXFAT_DEF_UTBL_CHKSUM, even with checking tbl_size == EXFAT_NUM_UPCASE * 2, is not rigorous.

Well, if we really want a rigorous one... I really don't know what we're trying to prove here, but that I can probably whip out some sort of algorithm to make sure all the 874 default entries are covered only once using hasing, bit test or bitmap tricks. It could come out fairly obsecure, but, well, as long as it's documented somewhere.

Stay tuned.

Davo

#6 lore raw

PATCH v2 2/4 exfat: optimise and refactor filename up-case conversion

In reply to David Timber

For better readability and to eliminate potential cache misses during file name up-case conversion process, replace exfat_bad_uni_chars and exfat_wstrchr() with exfat_illegal_chr().

Theoretically, by inlining the contents of exfat_bad_uni_chars are converted to a couple of bit tests and compare instructions, which will likely be prefetched to icache thereby eliminating cache misses.

However, it is reported that in some cases, Clang produces poor quality code for the switch ... case statement at the time of writing.

---
 fs/exfat/nls.c | 61 +++++++++++++++++++++++++++++++-------------------
 1 file changed, 38 insertions(+), 23 deletions(-)
fs/exfat/nls.c +38 -23
index 7d86fe7f3a8d..68b09a99f8be 100644
@@ -11,20 +11,6 @@
 #include "exfat_raw.h"
 #include "exfat_fs.h"
 
-/*
- * Allow full-width illegal characters :
- * "MS windows 7" supports full-width-invalid-name-characters.
- * So we should check half-width-invalid-name-characters(ASCII) only
- * for compatibility.
- *
- * " * / : < > ? \ |
- */
-static unsigned short bad_uni_chars[] = {
-	0x0022,         0x002A, 0x002F, 0x003A,
-	0x003C, 0x003E, 0x003F, 0x005C, 0x007C,
-	0
-};
-
 struct exfat_upcase_ptable exfat_def_upcase_ptable;
 
 static int exfat_convert_char_to_ucs2(struct nls_table *nls,
@@ -80,13 +66,44 @@ unsigned short exfat_toupper(struct super_block *sb, unsigned short a)
 	return exfat_lookup_upcase_ptable(sbi->vol_utbl, a);
 }
 
-static unsigned short *exfat_wstrchr(unsigned short *str, unsigned short wchar)
+/*
+ * Allow full-width illegal characters :
+ * "MS windows 7" supports full-width-invalid-name-characters.
+ * So we should check half-width-invalid-name-characters(ASCII) only
+ * for compatibility.
+ *
+ * " * / : < > ? \ |
+ */
+static inline bool exfat_illegal_chr(const unsigned short wchar)
 {
-	while (*str) {
-		if (*(str++) == wchar)
-			return str;
+	switch (wchar) {
+	/*
+	 * Control characters
+	 *
+	 * This saves some cmp instructions if the compiler does its job correctly
+	 */
+	case 0x0000: case 0x0001: case 0x0002: case 0x0003:
+	case 0x0004: case 0x0005: case 0x0006: case 0x0007:
+	case 0x0008: case 0x0009: case 0x000A: case 0x000B:
+	case 0x000C: case 0x000D: case 0x000E: case 0x000F:
+	case 0x0010: case 0x0011: case 0x0012: case 0x0013:
+	case 0x0014: case 0x0015: case 0x0016: case 0x0017:
+	case 0x0018: case 0x0019: case 0x001A: case 0x001B:
+	case 0x001C: case 0x001D: case 0x001E: case 0x001F:
+
+	case 0x0022: /* QUOTATION MARK:    (") */
+	case 0x002A: /* ASTERISK:          (*) */
+	case 0x002F: /* FORWARD SLASH:     (/) */
+	case 0x003A: /* COLON:             (:) */
+	case 0x003C: /* LESS-THAN SIGN:    (<) */
+	case 0x003E: /* GREATER-THAN SIGN: (>) */
+	case 0x003F: /* QUESTION MARK:     (?) */
+	case 0x005C: /* BACKSLASH:         (\) */
+	case 0x007C: /* PIPE:              (|) */
+		return true;
 	}
-	return NULL;
+
+	return false;
 }
 
 int exfat_uniname_ncmp(struct super_block *sb, unsigned short *a,
@@ -139,8 +156,7 @@ static int exfat_utf8_to_utf16(struct super_block *sb,
 	}
 
 	for (i = 0; i < unilen; i++) {
-		if (*uniname < 0x0020 ||
-		    exfat_wstrchr(bad_uni_chars, *uniname))
+		if (exfat_illegal_chr(*uniname))
 			lossy |= NLS_NAME_LOSSY;
 
 		upname[i] = cpu_to_le16(exfat_toupper(sb, *uniname));
@@ -231,8 +247,7 @@ static int exfat_nls_to_ucs2(struct super_block *sb,
 		i += exfat_convert_char_to_ucs2(nls, p_cstring + i, len - i,
 				uniname, &lossy);
 
-		if (*uniname < 0x0020 ||
-		    exfat_wstrchr(bad_uni_chars, *uniname))
+		if (exfat_illegal_chr(*uniname))
 			lossy |= NLS_NAME_LOSSY;
 
 		upname[unilen] = cpu_to_le16(exfat_toupper(sb, *uniname));
Signature · 1 line
2.53.0.1.ga224b40d3f.dirty
#7 lore raw

Re: [PATCH v2 2/4] exfat: optimise and refactor filename up-case conversion

Quoted 20 lines
fs/exfat/nls.c +16 -3
+static inline bool exfat_illegal_chr(const unsigned short wchar)
 {
-	while (*str) {
-		if (*(str++) == wchar)
-			return str;
+	switch (wchar) {
+	/*
+	 * Control characters
+	 *
+	 * This saves some cmp instructions if the compiler does its job correctly
+	 */
+	case 0x0000: case 0x0001: case 0x0002: case 0x0003:
+	case 0x0004: case 0x0005: case 0x0006: case 0x0007:
+	case 0x0008: case 0x0009: case 0x000A: case 0x000B:
+	case 0x000C: case 0x000D: case 0x000E: case 0x000F:
+	case 0x0010: case 0x0011: case 0x0012: case 0x0013:
+	case 0x0014: case 0x0015: case 0x0016: case 0x0017:
+	case 0x0018: case 0x0019: case 0x001A: case 0x001B:
+	case 0x001C: case 0x001D: case 0x001E: case 0x001F:
+

fs/exfat/nls.c unsigned short exfat_toupper(struct super_block *sb, unsigned short a) · line 103

Quoted 10 lines
fs/exfat/nls.c +10 -0
+	case 0x0022: /* QUOTATION MARK:    (") */
+	case 0x002A: /* ASTERISK:          (*) */
+	case 0x002F: /* FORWARD SLASH:     (/) */
+	case 0x003A: /* COLON:             (:) */
+	case 0x003C: /* LESS-THAN SIGN:    (<) */
+	case 0x003E: /* GREATER-THAN SIGN: (>) */
+	case 0x003F: /* QUESTION MARK:     (?) */
+	case 0x005C: /* BACKSLASH:         (\) */
+	case 0x007C: /* PIPE:              (|) */
+		return true;

For the continuous range 0x0000 to 0x001F, I think it's better to handle it like below, which avoids the large jump table, and may be just as fast(or even faster).

	default:
		return wchar < 0x0020;
#8 lore raw

Re: [PATCH v2 2/4] exfat: optimise and refactor filename up-case conversion

Quoted 34 lines · On 5/7/26 21:03, [email protected] wrote:
Quoted 20 lines
fs/exfat/nls.c +16 -3
+static inline bool exfat_illegal_chr(const unsigned short wchar)
 {
-	while (*str) {
-		if (*(str++) == wchar)
-			return str;
+	switch (wchar) {
+	/*
+	 * Control characters
+	 *
+	 * This saves some cmp instructions if the compiler does its job correctly
+	 */
+	case 0x0000: case 0x0001: case 0x0002: case 0x0003:
+	case 0x0004: case 0x0005: case 0x0006: case 0x0007:
+	case 0x0008: case 0x0009: case 0x000A: case 0x000B:
+	case 0x000C: case 0x000D: case 0x000E: case 0x000F:
+	case 0x0010: case 0x0011: case 0x0012: case 0x0013:
+	case 0x0014: case 0x0015: case 0x0016: case 0x0017:
+	case 0x0018: case 0x0019: case 0x001A: case 0x001B:
+	case 0x001C: case 0x001D: case 0x001E: case 0x001F:
+

fs/exfat/nls.c unsigned short exfat_toupper(struct super_block *sb, unsigned short a) · line 103

Quoted 10 lines
fs/exfat/nls.c +10 -0
+	case 0x0022: /* QUOTATION MARK:    (") */
+	case 0x002A: /* ASTERISK:          (*) */
+	case 0x002F: /* FORWARD SLASH:     (/) */
+	case 0x003A: /* COLON:             (:) */
+	case 0x003C: /* LESS-THAN SIGN:    (<) */
+	case 0x003E: /* GREATER-THAN SIGN: (>) */
+	case 0x003F: /* QUESTION MARK:     (?) */
+	case 0x005C: /* BACKSLASH:         (\) */
+	case 0x007C: /* PIPE:              (|) */
+		return true;

For the continuous range 0x0000 to 0x001F, I think it's better to handle it like below, which avoids the large jump table, and may be just as fast(or even faster).

Quoted 2 lines
	default:
		return wchar < 0x0020;

I guess you're right.

That costs one extra cmp instructions but still fits under a cache granularity on modern hardware(64 bytes) so it wouldn't really show up in profiling. Better to avoid risking compiler mindlessly producing a huge jump table.

Either way, still a win since the processor no longer has to iterate over the array.

#9 lore raw

PATCH v2 3/4 exfat: add default_upcase option (read-only)

In reply to David Timber

Show "default_upcase" in the mount options if the default upcase table is being used for the volume for diagnostic purposes.

---
 fs/exfat/super.c | 3 +++
 1 file changed, 3 insertions(+)
fs/exfat/super.c +3 -0
index 3197263aa1be..c2668524c06a 100644
@@ -149,6 +149,9 @@ static int exfat_show_options(struct seq_file *m, struct dentry *root)
 		seq_printf(m, ",time_offset=%d", opts->time_offset);
 	if (opts->zero_size_dir)
 		seq_puts(m, ",zero_size_dir");
+	if (sbi->vol_utbl_own == NULL)
+		seq_puts(m, ",default_upcase");
+
 	return 0;
 }
 
Signature · 1 line
2.53.0.1.ga224b40d3f.dirty
#10 lore raw

PATCH v2 4/4 exfat: more pedantic upcase table validity check

In reply to David Timber

It is observed that most exFAT implementations reject a volume with an upcase table whose index of the last entry is not 0xFFFF and treat the volume as damaged.

Upon encoutering an incomplete or malformed upcase table:

- whose index of last entry is not 0xFFFF
- that has extra data after the end of the table

Raise exfat_fs_error() to mark the volume read-only.

---
 fs/exfat/nls.c | 90 +++++++++++++++++++++++++++-----------------------
 1 file changed, 49 insertions(+), 41 deletions(-)
fs/exfat/nls.c +49 -41
index 68b09a99f8be..61b191a79fb6 100644
@@ -283,42 +283,45 @@ int exfat_nls_to_utf16(struct super_block *sb, const unsigned char *p_cstring,
 	return exfat_nls_to_ucs2(sb, p_cstring, len, uniname, p_lossy);
 }
 
-static int exfat_load_upcase_table(struct super_block *sb,
-		sector_t sector, unsigned long long num_sectors,
-		unsigned int utbl_checksum)
+static int exfat_load_upcase_table(struct super_block *sb, sector_t sector,
+		unsigned long long tbl_size, unsigned int utbl_checksum)
 {
 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
-	unsigned int sect_size = sb->s_blocksize;
+	struct buffer_head *bh = NULL;
 	unsigned int i, index = 0;
 	u32 chksum = 0;
-	unsigned char skip = false;
-	struct exfat_upcase_ptable *upcase_table;
+	bool skip = false, is_default = true;
+	struct exfat_upcase_ptable *upcase_table = NULL;
 	unsigned short def_upcase;
-	bool is_default;
 	unsigned int entries = 0;
 	int ret = -EINVAL;
 
+	if (tbl_size == 0 || tbl_size % 2 != 0 || tbl_size > EXFAT_UPTBL_SIZE * 2) {
+		exfat_fs_error(sb, "bogus upcase table size(%llu bytes). Please run fsck", tbl_size);
+		return -EINVAL;
+	}
+
 	upcase_table = kvcalloc(1, sizeof(struct exfat_upcase_ptable), GFP_KERNEL);
 	if (!upcase_table)
 		return -ENOMEM;
 
-	num_sectors += sector;
-	is_default = sector < num_sectors;
-
-	while (sector < num_sectors) {
-		struct buffer_head *bh;
-
+	for (; tbl_size > 1; sector++) {
+		brelse(bh);
 		bh = sb_bread(sb, sector);
 		if (!bh) {
-			exfat_err(sb, "failed to read sector(0x%llx)",
+			exfat_err(sb, "failed to read upcase table sector(0x%llx)",
 				  (unsigned long long)sector);
 			ret = -EIO;
 			goto err;
 		}
-		sector++;
-		for (i = 0; i < sect_size && index <= 0xFFFF; i += 2) {
+		chksum = exfat_calc_chksum32(bh->b_data, MIN(tbl_size, sb->s_blocksize),
+					     chksum, CS_DEFAULT);
+
+		for (i = 0; i < sb->s_blocksize && tbl_size > 1; i += 2) {
 			unsigned short uni = get_unaligned_le16(bh->b_data + i);
 
+			tbl_size -= 2;
+
 			if (skip) {
 				index += uni;
 				skip = false;
@@ -328,10 +331,8 @@ static int exfat_load_upcase_table(struct super_block *sb,
 				skip = true;
 			} else { /* uni != index , uni != 0xFFFF */
 				ret = exfat_set_upcase_ptable(upcase_table, index, uni);
-				if (ret) {
-					brelse(bh);
+				if (ret)
 					goto err;
-				}
 
 				def_upcase = exfat_lookup_upcase_ptable(&exfat_def_upcase_ptable,
 									index);
@@ -340,12 +341,14 @@ static int exfat_load_upcase_table(struct super_block *sb,
 				entries++;
 				index++;
 			}
+
+			if (index > 0xFFFF)
+				goto indexed;
 		}
-		chksum = exfat_calc_chksum32(bh->b_data, i, chksum, CS_DEFAULT);
-		brelse(bh);
 	}
 
-	if (index >= 0xFFFF && utbl_checksum == chksum) {
+indexed:
+	if (index == 0x10000 && utbl_checksum == chksum && tbl_size == 0) {
 		/*
 		 * is_default being set does not necessarily mean the contents are exact same as the
 		 * upcase table loaded from the volume may be missing some entries. The checksum
@@ -356,17 +359,22 @@ static int exfat_load_upcase_table(struct super_block *sb,
 			kvfree(upcase_table);
 		} else {
 			sbi->vol_utbl = sbi->vol_utbl_own = upcase_table;
-			exfat_info(sb, "using non-default upcase table (chksum: 0x%08x, entries: %u, memsize: %zu+)",
-				   chksum, entries, upcase_table->cnt * EXFAT_UPTBL_PAGESIZE);
+			exfat_info(sb, "using non-default upcase table "
+				   "(chksum: 0x%08x, entries: %u, memsize: %zu+ bytes)",
+				   chksum, entries, upcase_table->cnt * EXFAT_UPTBL_PAGESIZE * 2);
 		}
 
-		return 0;
-	}
-
-	exfat_err(sb, "failed to load upcase table (idx : 0x%08x, chksum : 0x%08x, utbl_chksum : 0x%08x)",
-		  index, chksum, utbl_checksum);
+		upcase_table = NULL;
+		ret = 0;
+	} else
+		ret = -EINVAL;
 
 err:
+	if (ret == -EINVAL)
+		exfat_fs_error(sb, "damaged upcase table. Please run fsck "
+				"(idx : 0x%08x, chksum : 0x%08x, utbl_chksum : 0x%08x, rem : %llu bytes)",
+				index, chksum, utbl_checksum, tbl_size);
+	brelse(bh);
 	exfat_free_upcase_ptable(upcase_table);
 	kvfree(upcase_table);
 
@@ -377,8 +385,8 @@ int exfat_create_upcase_table(struct super_block *sb)
 {
 	unsigned int tbl_clu, type;
 	sector_t sector;
-	unsigned long long tbl_size, num_sectors;
-	unsigned char blksize_bits = sb->s_blocksize_bits;
+	unsigned long long tbl_size;
+	unsigned int chksum;
 	struct exfat_chain clu;
 	struct exfat_dentry *ep;
 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
@@ -411,18 +419,18 @@ int exfat_create_upcase_table(struct super_block *sb)
 
 			tbl_clu  = le32_to_cpu(ep->dentry.upcase.start_clu);
 			tbl_size = le64_to_cpu(ep->dentry.upcase.size);
-			if (tbl_size) {
-				sector = exfat_cluster_to_sector(sbi, tbl_clu);
-				num_sectors = ((tbl_size - 1) >> blksize_bits) + 1;
-				ret = exfat_load_upcase_table(sb, sector, num_sectors,
-					le32_to_cpu(ep->dentry.upcase.checksum));
-			} else
-				exfat_fs_error(sb,
-					       "bad upcase table size (0 bytes). Please run fsck");
+			sector = exfat_cluster_to_sector(sbi, tbl_clu);
+			chksum = le32_to_cpu(ep->dentry.upcase.checksum);
+
+			ret = exfat_load_upcase_table(sb, sector, tbl_size, chksum);
 
 			brelse(bh);
-			if (ret && ret != -EIO)
-				ret = 0;
+			/*
+			 * Continue w/ damaged table(EINVAL) in read-only mode, unless overridden.
+			 * Treat ENOMEM and EIO as fatal.
+			 */
+			if (ret == -EINVAL)
+				return 0;
 			return ret;
 		}
 
Signature · 1 line
2.53.0.1.ga224b40d3f.dirty