From: Kalle Valo > Sent: 10 January 2023 12:03 ... > > Most hardware definitions align everything. > > > > What you may want to do is add compile-time asserts for the > > sizes of the structures. > > > > Remember that if you have 16/32 bit fields in packed structures > > on some architectures the compile has to generate code that does > > byte loads and shifts. > > > > The 'misaligned' property is lost when you take the address - so > > you can easily generate a fault. > > > > Adding __packed to a struct is a sledgehammer you really shouldn't need. > > Avoiding use of __packed is news to me, but is this really a safe rule? > Most of the wireless engineers are no compiler experts (myself included) > so I'm worried. For example, in ath10k and ath11k I try to use __packed > for all structs which are accessing hardware or firmware just to make > sure that the compiler is not changing anything. What may wish to do is get the compiler to generate an error if it would add any padding - but that isn't what __packed is for or what it does. The compiler will only ever add padding to ensure that fields are correctly aligned (usually a multiple of their size). There can also be padding at the end of a structure so that arrays are aligned. There are some unusual ABI that align all structures on 4 byte boundaries - but i don't think Linux has any of them. In any case this rarely matters. All structures that hardware/firmware access are very likely to have everything on its natural alignment unless you have a very old structure hat might have a 16bit aligned 32bit value that was assumed to be two words. Now if you have: struct { char a[4]; int b; } __packed foo; whenever you access foo.b the compiler might have to generate 4 separate byte memory accesses and a load of shift/and/or instructions in order to avoid a misaligned address trap. So you don't want to use __packed unless the field is actually expected to be misaligned. For most hardware/firmware structures this isn't true. David - Registered Address Lakeside, Bramley Road, Mount Farm, Milton Keynes, MK1 1PT, UK Registration No: 1397386 (Wales)