DeviceControllerFactory: Add InitAndRetainSystemState (#32998)

* DeviceControllerFactory: Add InitAndRetainSystemState

This does a RetainSystemState, but re-initializes if necessary.

Also rename no-arg InitSystemState() to ReinitSystemStateIfNecessary() and
check for the case where no work is necessary before creating the
FactoryInitParams and calling InitSystemState(params).

This means InitSystemState(params) doesn't have to handle that case anymore
since it's only called from Init() or after ReinitSystemStateIfNecessary() has
already done the check.

* Rename to EnsureAndRetainSystemState
diff --git a/src/controller/CHIPDeviceControllerFactory.cpp b/src/controller/CHIPDeviceControllerFactory.cpp
index e4e4199..248e96c 100644
--- a/src/controller/CHIPDeviceControllerFactory.cpp
+++ b/src/controller/CHIPDeviceControllerFactory.cpp
@@ -73,41 +73,36 @@
     return err;
 }
 
-CHIP_ERROR DeviceControllerFactory::InitSystemState()
+CHIP_ERROR DeviceControllerFactory::ReinitSystemStateIfNecessary()
 {
+    VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE);
+    VerifyOrReturnError(mSystemState->IsShutdown(), CHIP_NO_ERROR);
+
     FactoryInitParams params;
-    if (mSystemState != nullptr)
-    {
-        params.systemLayer        = mSystemState->SystemLayer();
-        params.udpEndPointManager = mSystemState->UDPEndPointManager();
+    params.systemLayer        = mSystemState->SystemLayer();
+    params.udpEndPointManager = mSystemState->UDPEndPointManager();
 #if INET_CONFIG_ENABLE_TCP_ENDPOINT
-        params.tcpEndPointManager = mSystemState->TCPEndPointManager();
+    params.tcpEndPointManager = mSystemState->TCPEndPointManager();
 #endif
 #if CONFIG_NETWORK_LAYER_BLE
-        params.bleLayer = mSystemState->BleLayer();
+    params.bleLayer = mSystemState->BleLayer();
 #endif
-        params.listenPort                = mListenPort;
-        params.fabricIndependentStorage  = mFabricIndependentStorage;
-        params.enableServerInteractions  = mEnableServerInteractions;
-        params.groupDataProvider         = mSystemState->GetGroupDataProvider();
-        params.sessionKeystore           = mSystemState->GetSessionKeystore();
-        params.fabricTable               = mSystemState->Fabrics();
-        params.operationalKeystore       = mOperationalKeystore;
-        params.opCertStore               = mOpCertStore;
-        params.certificateValidityPolicy = mCertificateValidityPolicy;
-        params.sessionResumptionStorage  = mSessionResumptionStorage;
-    }
+    params.listenPort                = mListenPort;
+    params.fabricIndependentStorage  = mFabricIndependentStorage;
+    params.enableServerInteractions  = mEnableServerInteractions;
+    params.groupDataProvider         = mSystemState->GetGroupDataProvider();
+    params.sessionKeystore           = mSystemState->GetSessionKeystore();
+    params.fabricTable               = mSystemState->Fabrics();
+    params.operationalKeystore       = mOperationalKeystore;
+    params.opCertStore               = mOpCertStore;
+    params.certificateValidityPolicy = mCertificateValidityPolicy;
+    params.sessionResumptionStorage  = mSessionResumptionStorage;
 
     return InitSystemState(params);
 }
 
 CHIP_ERROR DeviceControllerFactory::InitSystemState(FactoryInitParams params)
 {
-    if (mSystemState != nullptr && mSystemState->IsInitialized())
-    {
-        return CHIP_NO_ERROR;
-    }
-
     if (mSystemState != nullptr)
     {
         Platform::Delete(mSystemState);
@@ -331,10 +326,8 @@
 
 CHIP_ERROR DeviceControllerFactory::SetupController(SetupParams params, DeviceController & controller)
 {
-    VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE);
     VerifyOrReturnError(params.controllerVendorId != VendorId::Unspecified, CHIP_ERROR_INVALID_ARGUMENT);
-
-    ReturnErrorOnFailure(InitSystemState());
+    ReturnErrorOnFailure(ReinitSystemStateIfNecessary());
 
     ControllerInitParams controllerParams;
     PopulateInitParams(controllerParams, params);
@@ -351,10 +344,8 @@
 
 CHIP_ERROR DeviceControllerFactory::SetupCommissioner(SetupParams params, DeviceCommissioner & commissioner)
 {
-    VerifyOrReturnError(mSystemState != nullptr, CHIP_ERROR_INCORRECT_STATE);
     VerifyOrReturnError(params.controllerVendorId != VendorId::Unspecified, CHIP_ERROR_INVALID_ARGUMENT);
-
-    ReturnErrorOnFailure(InitSystemState());
+    ReturnErrorOnFailure(ReinitSystemStateIfNecessary());
 
     CommissionerInitParams commissionerParams;
 
@@ -397,6 +388,13 @@
     return mSystemState->Release();
 }
 
+CHIP_ERROR DeviceControllerFactory::EnsureAndRetainSystemState()
+{
+    ReturnErrorOnFailure(ReinitSystemStateIfNecessary());
+    RetainSystemState();
+    return CHIP_NO_ERROR;
+}
+
 DeviceControllerFactory::~DeviceControllerFactory()
 {
     Shutdown();
diff --git a/src/controller/CHIPDeviceControllerFactory.h b/src/controller/CHIPDeviceControllerFactory.h
index 19b19e5..d4e50e9 100644
--- a/src/controller/CHIPDeviceControllerFactory.h
+++ b/src/controller/CHIPDeviceControllerFactory.h
@@ -209,6 +209,9 @@
     //
     bool ReleaseSystemState();
 
+    // Like RetainSystemState(), but will re-initialize the system state first if necessary.
+    CHIP_ERROR EnsureAndRetainSystemState();
+
     //
     // Retrieve a read-only pointer to the system state object that contains pointers to key stack
     // singletons. If the pointer is null, it indicates that the DeviceControllerFactory has yet to
@@ -272,7 +275,7 @@
     DeviceControllerFactory() {}
     void PopulateInitParams(ControllerInitParams & controllerParams, const SetupParams & params);
     CHIP_ERROR InitSystemState(FactoryInitParams params);
-    CHIP_ERROR InitSystemState();
+    CHIP_ERROR ReinitSystemStateIfNecessary();
     void ControllerInitialized(const DeviceController & controller);
 
     uint16_t mListenPort;