Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unaligned issue about ether_addr_equal function?

I'm reading some articles about unaligned memory access problem and referred this article UNALIGNED MEMORY ACCESSES

bool ether_addr_equal(const u8 *addr1, const u8 *addr2) {
    #ifdef CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS
    u32 fold = ((*(const u32 *)addr1) ^ (*(const u32 *)addr2)) |
       ((*(const u16 *)(addr1 + 4)) ^ (*(const u16 *)(addr2 + 4)));
    return fold == 0;
    #else
    const u16 *a = (const u16 *)addr1;
    const u16 *b = (const u16 *)addr2;
    return ((a[0] ^ b[0]) | (a[1] ^ b[1]) | (a[2] ^ b[2])) != 0;
    #endif
}

and it said:

But when the hardware isn't able to access memory on arbitrary boundaries, the reference to a[0] causes 2 bytes (16 bits) to be read from memory starting at address addr1.

Well, I DO NOT know that what it means. In my mind, a[0] must be read 2 bytes from addr1, if not, what will it read? (maybe crash, but it is a 2 bytes or nothing situation I think). So what problem will occur here? And why don't they use u8* and compare one byte by one byte to solve the unaligned problem?

like image 385
rpbear Avatar asked Nov 18 '25 15:11

rpbear


1 Answers

In my mind,a[0] must be read 2 bytes from addr1,if not,what will it read? So what problem will occur here?

The intended meaning is certainly that a[0] reads one byte from addr1 and one byte from addr1 + 1 using a 2-byte access. A system may have a restriction that requires a 2-byte access to begin on even address boundaries. If addr1 is odd, that is violated.

And why don't they use u8* and compare one byte by one byte to solve the unaligned problem?

Likely it was assumed target systems would not encounter the above problem. Using one byte at a time would handle that case.


Note:It appears the two halves of the function are not functionality equivalent. Consider data bits all zero, the first returns true, the 2nd returns false.

like image 75
chux - Reinstate Monica Avatar answered Nov 20 '25 03:11

chux - Reinstate Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!