The conditional lock ...
LOCK2(cs_main, pwallet ? &pwallet->cs_wallet : nullptr)
... confuses Clang's thread safety analysis (it complains about not holding the mutex pwallet->cs_wallet even in the case when pwallet is non-NULL).
So does the access to pwallet->mapKeyMetadata via meta (it complains about not holding the mutex cs_wallet despite pwallet->cs_wallet being held).
This commit introduces locking that Clang's thread safety analysis is able to comprehend.