KeyChain writes done near time of device lock/unlock will hang for several seconds

Number:rdar://29741117 Date Originated:19-Dec-2016 10:56 PM
Status:Open Resolved:
Product:iOS Product Version:10.2
Classification:Crash/Hang/Data Loss Reproducible:Always
Since iOS 10.2, doing writes to the KeyChain (either SecItemAdd or SecItemDelete) just when the device gets locked or just got unlocked, the SecItemAdd or SecItemDelete calls will not return for 3 to 30 seconds and often hang the LockScreen as well, making it completely unresponsive.

Steps to Reproduce:
1. Create an app that, in applicationDidEnterBackground:, calls SecItemAdd() with kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
2. Lock the device using the Sleep/wake button
3. Unlock the device using either Touch ID or passcode

Expected Results:
- App launches quickly

Actual Results:
- App hangs while waiting on SecItemAdd() to finish

This did not happen on iOS 10.1 or any version before that.

- Any writes to the KeyChain done in other background queues are also hanging, until something in the security daemon stops hanging.
- Attached is a Console log capture from around the time the device got unlocked and started hanging
- Attached is a screenshot of a captured stack trace of our app hanging for about 15 seconds on this specific call


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!