[bouffalo lab] fix wifi scan issues and update some platform changes (#37455)

* [bouffalo lab] fix wifi scan issues and update some platform changes

* Restyled by clang-format

* Restyled by gn

* Restyled by clang-format

* fix wifi scan on bl706 + bl602 platform

* Restyled by whitespace

* Restyled by clang-format

* use strncpy to copy ssid

* Restyled by whitespace

* Restyled by clang-format

---------

Co-authored-by: Restyled.io <commits@restyled.io>
diff --git a/examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp b/examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp
index e3ed09a..d6b2141 100644
--- a/examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp
+++ b/examples/contact-sensor-app/bouffalolab/bl702l/app_pds.cpp
@@ -59,17 +59,9 @@
     extern BaseType_t TrapNetCounter, *pTrapNetCounter;
     if (app_pds_wakeup_source == PDS_WAKEUP_BY_RTC)
     {
-        extern void * pxCurrentTCB;
-
-        ChipLogProgress(NotSpecified, "wakeup source: rtc. %lu vs %lu ms @ %lu\r\n", xExpectedIdleTime,
-                        (uint32_t) (bl_rtc_get_timestamp_ms() - sleep_before), (uint32_t) bl_rtc_get_timestamp_ms());
-
-        ChipLogProgress(NotSpecified, "application_sleep; %lu, %lu, %lu\r\n", (uint32_t) sleep_calling_time, (uint32_t) sleep_time,
-                        (uint32_t) wakeup_time);
     }
     else if (app_pds_wakeup_source == PDS_WAKEUP_BY_GPIO)
     {
-
         if (((1 << CHIP_RESET_PIN) & app_pds_wakeup_pin) && app_pds_irq_handler)
         {
             app_pds_irq_handler(&gpio_key);
@@ -79,10 +71,6 @@
         {
             app_pds_irq_handler(&gpio_contact);
         }
-
-        ChipLogProgress(NotSpecified, "wakeup source: gpio -> 0x%08lX. %lu vs %lu ms @ %lu\r\n", app_pds_wakeup_pin,
-                        xExpectedIdleTime, (uint32_t) (bl_rtc_get_timestamp_ms() - sleep_before),
-                        (uint32_t) bl_rtc_get_timestamp_ms());
     }
 
     app_pds_wakeup_source = -1;
diff --git a/examples/lighting-app/bouffalolab/bl602/BUILD.gn b/examples/lighting-app/bouffalolab/bl602/BUILD.gn
index a487c81..fa35de6 100644
--- a/examples/lighting-app/bouffalolab/bl602/BUILD.gn
+++ b/examples/lighting-app/bouffalolab/bl602/BUILD.gn
@@ -96,7 +96,7 @@
   output_name = "chip-bl602-lighting-example.out"
 
   defines = [
-    "APP_TASK_STACK_SIZE=2044",
+    "APP_TASK_STACK_SIZE=4096",
     "CHIP_UART_BAUDRATE=${baudrate}",
     "START_ENTRY=bfl_main",
     "SYS_AOS_LOOP_ENABLE",
@@ -109,6 +109,10 @@
   defines +=
       [ "CONFIG_BOUFFALOLAB_FACTORY_DATA_ENABLE=${chip_enable_factory_data}" ]
 
+  if (enable_lwip_pbuf_ram) {
+    defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ]
+  }
+
   bl_plat_name = "bl602"
   sources = [
     "${examples_plat_dir}/common/route_hook/bl_route_hook.c",
@@ -227,6 +231,10 @@
   inputs = [ ldscript ]
 
   if (chip_print_memory_usage) {
+    if (enable_lwip_pbuf_ram) {
+      ldflags += [ "-Wl,--defsym=__RAM_PBUF_POOL=0" ]
+    }
+
     ldflags += [
       "-Wl,--print-memory-usage",
       "-fstack-usage",
diff --git a/examples/lighting-app/bouffalolab/bl616/BUILD.gn b/examples/lighting-app/bouffalolab/bl616/BUILD.gn
index 6671db3..6890ad5 100644
--- a/examples/lighting-app/bouffalolab/bl616/BUILD.gn
+++ b/examples/lighting-app/bouffalolab/bl616/BUILD.gn
@@ -121,6 +121,10 @@
     defines += [ "BOOT_PIN_RESET=2" ]
   }
 
+  if (enable_lwip_pbuf_ram) {
+    defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ]
+  }
+
   defines += [ "BL616DK" ]
 
   sources = [
diff --git a/examples/lighting-app/bouffalolab/bl616/args.gni b/examples/lighting-app/bouffalolab/bl616/args.gni
index d031a4b..aa60a42 100644
--- a/examples/lighting-app/bouffalolab/bl616/args.gni
+++ b/examples/lighting-app/bouffalolab/bl616/args.gni
@@ -19,16 +19,7 @@
 
 bouffalo_sdk_target = get_label_info(":sdk", "label_no_toolchain")
 
-pw_log_BACKEND = "${chip_root}/src/pw_backends/log"
-pw_assert_BACKEND = "${chip_root}/src/pw_backends/assert"
-pw_rpc_CONFIG = "$dir_pw_rpc:disable_global_mutex"
-
-chip_detail_logging = true
+chip_detail_logging = false
 
 # use -Os instead of -Og
 is_debug = false
-
-pw_build_LINK_DEPS = [
-  "$dir_pw_assert:impl",
-  "$dir_pw_log:impl",
-]
diff --git a/examples/lighting-app/bouffalolab/bl702/BUILD.gn b/examples/lighting-app/bouffalolab/bl702/BUILD.gn
index c86d331..35b7041 100644
--- a/examples/lighting-app/bouffalolab/bl702/BUILD.gn
+++ b/examples/lighting-app/bouffalolab/bl702/BUILD.gn
@@ -126,7 +126,7 @@
   bl_plat_name = "bl702"
 
   defines = [
-    "APP_TASK_STACK_SIZE=2048",
+    "APP_TASK_STACK_SIZE=4096",
     "CHIP_UART_BAUDRATE=${baudrate}",
     "START_ENTRY=bl702_main",
   ]
diff --git a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn
index c004af4..de9210b 100644
--- a/examples/lighting-app/bouffalolab/bl702l/BUILD.gn
+++ b/examples/lighting-app/bouffalolab/bl702l/BUILD.gn
@@ -106,7 +106,7 @@
   bl_plat_name = "bl702l"
 
   defines = [
-    "APP_TASK_STACK_SIZE=2048",
+    "APP_TASK_STACK_SIZE=4096",
     "CHIP_UART_BAUDRATE=${baudrate}",
     "START_ENTRY=bl702_main",
   ]
diff --git a/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld b/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld
index 206f89b..6393c9d 100644
--- a/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld
+++ b/examples/platform/bouffalolab/bl602/ldscripts/flash_rom.ld
@@ -11,7 +11,9 @@
 __RAM_START = 0x4200C000;
 __RAM_END = 0x4200C000 + 256K - __EM_SIZE; /* leave 8K left for BLE */
 
-__RAM_TCM_LEN = (16K + 16K + 48K + 64K + 64K - 16K - 16K);
+__RAM_PBUF_POOL = DEFINED(__RAM_PBUF_POOL) ? __RAM_PBUF_POOL : 30K;
+
+__RAM_TCM_LEN = (16K + 16K + 48K + 64K + 64K - 16K - 16K + 30K - 12K - __RAM_PBUF_POOL);
 __RAM_WIFI_LEN = (__RAM_END - __RAM_START - __RAM_TCM_LEN);
 
 MEMORY
@@ -173,6 +175,9 @@
     *libwifi_drv.a:bl_utils.o(.bss*)
     *(.wifi_ram*)
     . = ALIGN(16);
+
+    KEEP(*libCHIP.a:*(.bss.*PlatformManagerImp*))
+    . = ALIGN(16);
   } > ram_wifi
 
   PROVIDE( _heap_wifi_start = . );
diff --git a/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h b/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h
index 93c14da..ebcb05a 100644
--- a/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h
+++ b/examples/platform/bouffalolab/bl602/lwipopts/lwipopts.h
@@ -78,10 +78,6 @@
 
 #define MEMP_NUM_NETCONN (MEMP_NUM_TCP_PCB + MEMP_NUM_UDP_PCB + MEMP_NUM_TCP_PCB_LISTEN)
 
-/* ---------- Pbuf options ---------- */
-/* PBUF_POOL_SIZE: the number of buffers in the pbuf pool. */
-#define PBUF_POOL_SIZE 20
-
 /* ---------- TCP options ---------- */
 #define LWIP_TCP 1
 #define IP_DEFAULT_TTL 64
@@ -269,17 +265,37 @@
 
 #define LWIP_NETIF_EXT_STATUS_CALLBACK 1
 
-/* PBUF_POOL_BUFSIZE: the size of each pbuf in the pbuf pool. */
 #define PBUF_POOL_BUFSIZE LWIP_MEM_ALIGN_SIZE(TCP_MSS + 40 + PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN)
 
-#define LWIP_PBUF_FROM_CUSTOM_POOLS (0)
-
 /*
    ---------------------------------
    ---------- MISC. options ----------
    ---------------------------------
 */
 
+#if defined(CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM) && CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM
+#define PBUF_POOL_SIZE 0
+#define MEM_LIBC_MALLOC 0
+#define MEM_USE_POOLS 0
+#define MEMP_USE_CUSTOM_POOLS 0
+
+#include <lwip/arch.h>
+#include <lwip/mem.h>
+#define LWIP_PBUF_CUSTOM_DATA mem_size_t pool;
+
+#if defined(__cplusplus)
+extern "C" const mem_size_t * memp_sizes;
+extern "C" struct pbuf * pbuf_rightsize(struct pbuf * p, s16_t offset);
+#else
+extern const mem_size_t * memp_sizes;
+extern struct pbuf * pbuf_rightsize(struct pbuf * p, s16_t offset);
+#endif
+#else
+
+#define PBUF_POOL_SIZE 20
+#define LWIP_PBUF_FROM_CUSTOM_POOLS (0)
+#endif
+
 #if defined(__cplusplus)
 extern "C" int bl_rand(void);
 extern "C" int * __errno(void);
diff --git a/examples/platform/bouffalolab/bl616/lwipopts.h b/examples/platform/bouffalolab/bl616/lwipopts.h
index 91d779f..04671c9 100644
--- a/examples/platform/bouffalolab/bl616/lwipopts.h
+++ b/examples/platform/bouffalolab/bl616/lwipopts.h
@@ -120,10 +120,9 @@
 #define MEMP_NUM_UDP_PCB 16
 #define MEMP_NUM_REASSDATA LWIP_MIN((IP_REASS_MAX_PBUFS), 5)
 
-#define PBUF_POOL_SIZE 0
 #define MEM_ALIGNMENT 4
 #define MEM_SIZE 30720
-#define PBUF_POOL_BUFSIZE (PBUF_LINK_ENCAPSULATION_HLEN + PBUF_LINK_HLEN + 1280)
+#define PBUF_POOL_BUFSIZE (1280 + 462 + 26)
 #define MEMP_MEM_MALLOC 1
 
 // #define LWIP_HOOK_FILENAME        "lwiphooks.h"
@@ -177,4 +176,22 @@
 #define LWIP_DECLARE_MEMORY_ALIGNED(variable_name, size)                                                                           \
     u8_t variable_name[size] __attribute__((aligned(4))) __attribute__((section("SHAREDRAM")))
 
+#if defined(CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM) && CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM
+#define PBUF_POOL_SIZE 0
+
+#include <lwip/arch.h>
+#include <lwip/mem.h>
+#define LWIP_PBUF_CUSTOM_DATA mem_size_t pool;
+
+#if defined(__cplusplus)
+extern "C" const mem_size_t * memp_sizes;
+extern "C" struct pbuf * pbuf_rightsize(struct pbuf * p, s16_t offset);
+#else
+extern const mem_size_t * memp_sizes;
+extern struct pbuf * pbuf_rightsize(struct pbuf * p, s16_t offset);
+#endif
+#else
+#define PBUF_POOL_SIZE 20
+#endif
+
 #endif /* LWIP_HDR_LWIPOPTS_H__ */
diff --git a/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld b/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld
index a9ed717..593af0d 100644
--- a/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld
+++ b/examples/platform/bouffalolab/bl702/ldscripts/psram_flash.ld
@@ -208,6 +208,9 @@
     _bt_l2cap_fixed_chan_list_start = .;
     KEEP(*(SORT_BY_NAME("._bt_l2cap_fixed_chan.static.*")))
     _bt_l2cap_fixed_chan_list_end = .;
+
+    . = ALIGN(8);
+    KEEP(*libCHIP.a:*(.bss.*PlatformManagerImp*))
   } >tcm_ocram AT >flash
 
   .boot2 (NOLOAD) :
diff --git a/examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld b/examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld
index 597d98a..076f3d6 100644
--- a/examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld
+++ b/examples/platform/bouffalolab/bl702l/ldscripts/psram_flash.ld
@@ -170,6 +170,9 @@
     _bt_l2cap_fixed_chan_list_start = .;
     KEEP(*(SORT_BY_NAME("._bt_l2cap_fixed_chan.static.*")))
     _bt_l2cap_fixed_chan_list_end = .;
+
+    . = ALIGN(8);
+    KEEP(*libCHIP.a:*(.bss.*PlatformManagerImp*))
   } >tcm_ocram AT >flash
 
   .boot2 (NOLOAD) :
diff --git a/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp
index f92b527..e1be14c 100644
--- a/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp
+++ b/examples/platform/bouffalolab/common/bouffalo_sdk/platform_port.cpp
@@ -56,6 +56,8 @@
         printf("vAssertCalled, ra = %p in task %s\r\n", (void *) ra, pcTaskGetName(NULL));
     }
 
+    abort();
+
     while (true)
         ;
 }
diff --git a/examples/platform/bouffalolab/common/plat/platform.cpp b/examples/platform/bouffalolab/common/plat/platform.cpp
index 9559641..3566535 100644
--- a/examples/platform/bouffalolab/common/plat/platform.cpp
+++ b/examples/platform/bouffalolab/common/plat/platform.cpp
@@ -264,7 +264,8 @@
     }
     else
     {
-        ChipLogError(NotSpecified, "sFactoryDataProvider.Init() failed");
+        ChipLogError(NotSpecified, "factory data provider is failed to initialize, use example DAC provider.");
+        SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
     }
 #else
     SetDeviceAttestationCredentialsProvider(Examples::GetExampleDACProvider());
diff --git a/scripts/build/builders/bouffalolab.py b/scripts/build/builders/bouffalolab.py
index d575259..5cee2d8 100644
--- a/scripts/build/builders/bouffalolab.py
+++ b/scripts/build/builders/bouffalolab.py
@@ -285,16 +285,14 @@
 
     def PostBuildCommand(self):
 
-        bouffalo_sdk_chips = ["bl616"]
-        abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin")
-
-        if self.chip_name not in bouffalo_sdk_chips:
-            abs_path_fw_raw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".raw")
+        if self.chip_name in ["bl616"]:
+            abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".raw")
+        else:
+            abs_path_fw = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin")
 
         if os.path.isfile(abs_path_fw):
             target_dir = self.output_dir.replace(self.chip_dir, "").strip("/")
 
-            abs_path_fw_bin = os.path.join(self.output_dir, self.app.AppNamePrefix(self.chip_name) + ".bin")
             path_fw = os.path.join(target_dir, self.app.AppNamePrefix(self.chip_name) + ".bin")
             path_flash_script = os.path.join(target_dir, self.app.AppNamePrefix(self.chip_name) + ".flash.py")
 
diff --git a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp
index 8713626..3da54f0 100644
--- a/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp
+++ b/src/platform/bouffalolab/BL602/NetworkCommissioningDriver.cpp
@@ -268,7 +268,7 @@
     }
 
     wifi_mgmr_ap_item_t * ScanResult = (wifi_mgmr_ap_item_t *) pvPortMalloc(ap_num * sizeof(wifi_mgmr_ap_item_t));
-    wifi_mgmr_get_scan_result(ScanResult, &ap_num, 0, mScanSSID);
+    wifi_mgmr_get_scan_result(ScanResult, &ap_num, mScanType, mScanSSID);
 
     if (ScanResult)
     {
diff --git a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp b/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp
index 24df9f3..4b2b8b7 100644
--- a/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp
+++ b/src/platform/bouffalolab/BL702/ConnectivityManagerImpl.cpp
@@ -106,8 +106,15 @@
 
 extern "C" void wifiInterface_eventScanDone(struct netif * interface, netbus_fs_scan_ind_cmd_msg_t * pmsg)
 {
+    ChipDeviceEvent event;
+
     ChipLogProgress(DeviceLayer, "wifiInterface_eventScanDone");
+
+    memset(&event, 0, sizeof(ChipDeviceEvent));
     NetworkCommissioning::BLWiFiDriver::GetInstance().OnScanWiFiNetworkDone(pmsg);
+
+    event.Type = kWiFiOnScanDone;
+    PlatformMgr().PostEventOrDie(&event);
 }
 #endif // CHIP_DEVICE_CONFIG_ENABLE_WIFI
 
diff --git a/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.cpp b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.cpp
index 22df7c3..43f813a 100644
--- a/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.cpp
+++ b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.cpp
@@ -211,15 +211,15 @@
 {
     if (callback != nullptr)
     {
-        ChipLogError(NetworkProvisioning, "ssid.data(): %s", ssid.data());
-
         if (ssid.data())
         {
             memset(mScanSSID, 0, sizeof(mScanSSID));
             memcpy(mScanSSID, ssid.data(), ssid.size());
             mScanSpecific = true;
         }
-        mpScanCallback = callback;
+
+        mScanResponseNum = 0;
+        mpScanCallback   = callback;
         wifiInterface_startScan();
     }
 }
@@ -229,20 +229,90 @@
     netbus_wifi_mgmr_msg_cmd_t * pkg_data = (netbus_wifi_mgmr_msg_cmd_t *) ((struct pkg_protocol *) opaque)->payload;
     netbus_fs_scan_ind_cmd_msg_t * pmsg   = (netbus_fs_scan_ind_cmd_msg_t *) ((netbus_fs_scan_ind_cmd_msg_t *) pkg_data);
 
-    size_t i = 0, ap_num = 0;
+    size_t i = 0, ap_num = 0, ap_cnt = 0;
     WiFiScanResponse *pScanResponse, *p;
 
-    for (i = 0; i < pmsg->num; i++)
+    ChipLogProgress(DeviceLayer, "expected ssid %s. get %d in total, %d", mScanSSID, pmsg->num, mScanSpecific);
+
+    if (mScanSpecific)
     {
-        ChipLogProgress(DeviceLayer, "OnScanWiFiNetworkDone %s", pmsg->records[i].ssid);
-        if (mScanSpecific && !strcmp(mScanSSID, (char *) (pmsg->records[i].ssid)))
+        for (i = 0; i < pmsg->num; i++)
         {
-            ap_num = 1;
-            break;
+            if (mScanSpecific && !strcmp(mScanSSID, (char *) (pmsg->records[i].ssid)))
+            {
+                ap_num = 1;
+                break;
+            }
+        }
+    }
+    else
+    {
+        ap_num = pmsg->num;
+    }
+
+    if (ap_num)
+    {
+        p = mScanResponse = (WiFiScanResponse *) malloc(sizeof(WiFiScanResponse) * ap_num);
+        if (mScanResponse == nullptr)
+        {
+            return;
+        }
+
+        for (i = 0; i < pmsg->num; i++)
+        {
+            if (mScanSpecific && strcmp(mScanSSID, (char *) (pmsg->records[i].ssid)))
+            {
+                continue;
+            }
+
+            p->security.SetRaw(pmsg->records[i].auth_mode);
+            strncpy((char *) p->ssid, (const char *) pmsg->records[i].ssid, kMaxWiFiSSIDLength);
+            p->ssidLen  = strlen((char *) pmsg->records[i].ssid);
+            p->channel  = pmsg->records[i].channel;
+            p->wiFiBand = chip::DeviceLayer::NetworkCommissioning::WiFiBand::k2g4;
+            p->rssi     = pmsg->records[i].rssi;
+            memcpy(p->bssid, pmsg->records[i].bssid, 6);
+
+            p++;
+            ap_cnt++;
+
+            if (ap_cnt >= ap_num)
+            {
+                break;
+            }
         }
     }
 
-    if (0 == pmsg->num || (mScanSpecific && 0 == ap_num))
+    mScanResponseNum = ap_cnt;
+}
+
+void BLWiFiDriver::OnScanWiFiNetworkDone(void)
+{
+    size_t ap_cnt                    = mScanResponseNum;
+    WiFiScanResponse * pScanResponse = mScanResponse;
+
+    if (mScanResponse)
+    {
+        if (CHIP_NO_ERROR == DeviceLayer::SystemLayer().ScheduleLambda([ap_cnt, pScanResponse]() {
+                BLScanResponseIterator iter(ap_cnt, pScanResponse);
+                if (GetInstance().mpScanCallback)
+                {
+                    GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter);
+                    GetInstance().mpScanCallback = nullptr;
+                }
+                else
+                {
+                    ChipLogError(DeviceLayer, "can't find the ScanCallback function");
+                }
+            }))
+        {
+            ChipLogProgress(DeviceLayer, "ScheduleLambda OK");
+        }
+
+        free(mScanResponse);
+        mScanResponse = nullptr;
+    }
+    else
     {
         ChipLogProgress(DeviceLayer, "No AP found");
         if (mpScanCallback != nullptr)
@@ -250,60 +320,9 @@
             mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), nullptr);
             mpScanCallback = nullptr;
         }
-        return;
     }
 
-    if (ap_num)
-    {
-        p = pScanResponse = (WiFiScanResponse *) malloc(sizeof(WiFiScanResponse) * ap_num);
-    }
-    else
-    {
-        p = pScanResponse = (WiFiScanResponse *) malloc(sizeof(WiFiScanResponse) * pmsg->num);
-        ap_num            = pmsg->num;
-    }
-    for (i = 0; i < pmsg->num; i++)
-    {
-        if (mScanSpecific && strcmp(mScanSSID, (char *) (pmsg->records[i].ssid)))
-        {
-            continue;
-        }
-
-        p->security.SetRaw(pmsg->records[i].auth_mode);
-        p->ssidLen  = strlen((char *) pmsg->records[i].ssid) < chip::DeviceLayer::Internal::kMaxWiFiSSIDLength
-             ? strlen((char *) pmsg->records[i].ssid)
-             : chip::DeviceLayer::Internal::kMaxWiFiSSIDLength;
-        p->channel  = pmsg->records[i].channel;
-        p->wiFiBand = chip::DeviceLayer::NetworkCommissioning::WiFiBand::k2g4;
-        p->rssi     = pmsg->records[i].rssi;
-        memcpy(p->ssid, pmsg->records[i].ssid, p->ssidLen);
-        memcpy(p->bssid, pmsg->records[i].bssid, 6);
-
-        if (mScanSpecific)
-        {
-            break;
-        }
-
-        p++;
-    }
-
-    if (CHIP_NO_ERROR == DeviceLayer::SystemLayer().ScheduleLambda([ap_num, pScanResponse]() {
-            BLScanResponseIterator iter(ap_num, pScanResponse);
-            if (GetInstance().mpScanCallback)
-            {
-                GetInstance().mpScanCallback->OnFinished(Status::kSuccess, CharSpan(), &iter);
-                GetInstance().mpScanCallback = nullptr;
-            }
-            else
-            {
-                ChipLogError(DeviceLayer, "can't find the ScanCallback function");
-            }
-        }))
-    {
-        ChipLogProgress(DeviceLayer, "ScheduleLambda OK");
-    }
-
-    free(pScanResponse);
+    mScanResponseNum = 0;
 }
 
 CHIP_ERROR GetConfiguredNetwork(Network & network)
diff --git a/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.h b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.h
index 8e5557b..b98ea60 100644
--- a/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.h
+++ b/src/platform/bouffalolab/BL702/NetworkCommissioningDriver.h
@@ -113,7 +113,8 @@
 
     CHIP_ERROR ConnectWiFiNetwork(const char * ssid, uint8_t ssidLen, const char * key, uint8_t keyLen);
     void OnConnectWiFiNetwork(bool isConnected);
-    void OnScanWiFiNetworkDone(void * opaque = NULL);
+    void OnScanWiFiNetworkDone(void);
+    void OnScanWiFiNetworkDone(void * opaque);
     void OnNetworkStatusChange(void);
 
     CHIP_ERROR SetLastDisconnectReason(const ChipDeviceEvent * event);
@@ -128,6 +129,9 @@
 private:
     bool NetworkMatch(const WiFiNetwork & network, ByteSpan networkId);
 
+    WiFiScanResponse * mScanResponse = nullptr;
+    size_t mScanResponseNum          = 0;
+
     WiFiNetwork mSavedNetwork;
     WiFiNetwork mStagingNetwork;
     ScanCallback * mpScanCallback;
diff --git a/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h
index bc34d91..7f1bbf3 100644
--- a/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h
+++ b/src/platform/bouffalolab/common/CHIPDevicePlatformConfig.h
@@ -58,4 +58,6 @@
 #define CHIP_CONFIG_FREERTOS_USE_STATIC_QUEUE 1
 #elif CHIP_DEVICE_LAYER_TARGET_BL702
 #define CHIP_CONFIG_FREERTOS_USE_STATIC_TASK 1
+#elif CHIP_DEVICE_LAYER_TARGET_BL702L
+#define CHIP_CONFIG_FREERTOS_USE_STATIC_TASK 1
 #endif
diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp
index a5d7024..12a58f9 100644
--- a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp
+++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.cpp
@@ -78,7 +78,10 @@
 CHIP_ERROR DiagnosticDataProviderImpl::GetCurrentHeapHighWatermark(uint64_t & currentHeapHighWatermark)
 {
 #if CHIP_DEVICE_LAYER_TARGET_BL616
-    return CHIP_ERROR_NOT_IMPLEMENTED;
+    struct meminfo info;
+    bflb_mem_usage(KMEM_HEAP, &info);
+    currentHeapHighWatermark = info.total_size - info.max_free_size;
+
 #else
 #ifdef CFG_USE_PSRAM
     currentHeapHighWatermark =
@@ -86,8 +89,9 @@
 #else
     currentHeapHighWatermark = get_heap_size() - xPortGetMinimumEverFreeHeapSize();
 #endif
-    return CHIP_NO_ERROR;
 #endif
+
+    return CHIP_NO_ERROR;
 }
 
 CHIP_ERROR DiagnosticDataProviderImpl::GetThreadMetrics(ThreadMetrics ** threadMetricsOut)
diff --git a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h
index 8001afb..6ff0d07 100644
--- a/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h
+++ b/src/platform/bouffalolab/common/DiagnosticDataProviderImpl.h
@@ -32,6 +32,7 @@
     static DiagnosticDataProviderImpl & GetDefaultInstance();
 
     // ===== Methods that implement the PlatformManager abstract interface.
+    bool SupportsWatermarks() override { return true; }
 
     CHIP_ERROR GetCurrentHeapFree(uint64_t & currentHeapFree) override;
     CHIP_ERROR GetCurrentHeapUsed(uint64_t & currentHeapUsed) override;
diff --git a/third_party/bouffalolab/bl602/bl_iot_sdk.gni b/third_party/bouffalolab/bl602/bl_iot_sdk.gni
index ba564db..0cf4768 100644
--- a/third_party/bouffalolab/bl602/bl_iot_sdk.gni
+++ b/third_party/bouffalolab/bl602/bl_iot_sdk.gni
@@ -20,6 +20,7 @@
 declare_args() {
   bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo"
 
+  enable_lwip_pbuf_ram = false
   enable_debug_coredump = false
   coredump_binary_id = 0
 }
@@ -63,6 +64,10 @@
       "-include",
       rebase_path("${invoker.freertos_config}", root_build_dir),
     ]
+
+    if (defined(invoker.enable_lwip_pbuf_ram) && invoker.enable_lwip_pbuf_ram) {
+      defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ]
+    }
   }
 
   source_set("${sdk_target_name}_soc") {
@@ -906,6 +911,10 @@
       "${bl_iot_sdk_root}/components/network/lwip_dhcpd",
     ]
 
+    if (defined(invoker.enable_lwip_pbuf_ram) && invoker.enable_lwip_pbuf_ram) {
+      include_dirs += [ "${bouffalolab_iot_sdk_build_root}/patches/lwip" ]
+    }
+
     defines = [ "LWIP_IPV6=1" ]
   }
 
@@ -927,7 +936,6 @@
       "${bl_iot_sdk_root}/components/network/lwip/src/core/inet_chksum.c",
       "${bl_iot_sdk_root}/components/network/lwip/src/core/init.c",
       "${bl_iot_sdk_root}/components/network/lwip/src/core/ip.c",
-      "${bl_iot_sdk_root}/components/network/lwip/src/core/mem.c",
       "${bl_iot_sdk_root}/components/network/lwip/src/core/memp.c",
       "${bl_iot_sdk_root}/components/network/lwip/src/core/netif.c",
       "${bl_iot_sdk_root}/components/network/lwip/src/core/pbuf.c",
@@ -941,6 +949,12 @@
       "${bl_iot_sdk_root}/components/network/lwip/src/core/udp.c",
     ]
 
+    if (defined(invoker.enable_lwip_pbuf_ram) && invoker.enable_lwip_pbuf_ram) {
+      sources += [ "${bouffalolab_iot_sdk_build_root}/patches/lwip/mem.c" ]
+    } else {
+      sources += [ "${bl_iot_sdk_root}/components/network/lwip/src/core/mem.c" ]
+    }
+
     sources += [
       "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/autoip.c",
       "${bl_iot_sdk_root}/components/network/lwip/src/core/ipv4/dhcp.c",
diff --git a/third_party/bouffalolab/bl616/bouffalo_sdk.gni b/third_party/bouffalolab/bl616/bouffalo_sdk.gni
index 174b04b..9b49896 100644
--- a/third_party/bouffalolab/bl616/bouffalo_sdk.gni
+++ b/third_party/bouffalolab/bl616/bouffalo_sdk.gni
@@ -21,6 +21,7 @@
   # Location of the bl616 SDK.
   bouffalo_sdk_root = "${chip_root}/third_party/bouffalolab/bouffalo_sdk"
 
+  enable_lwip_pbuf_ram = false
   enable_debug_coredump = false
   coredump_binary_id = 0
   bouffalo_sdk_coredump_version = 1
@@ -72,6 +73,10 @@
     if (defined(invoker.defines)) {
       defines += invoker.defines
     }
+
+    if (defined(invoker.enable_lwip_pbuf_ram) && invoker.enable_lwip_pbuf_ram) {
+      defines += [ "CHIP_SYSTEM_CONFIG_PACKETBUFFER_LWIP_PBUF_RAM=1" ]
+    }
   }
 
   config("${sdk_target_name}_config_startup") {
@@ -412,6 +417,7 @@
     include_dirs = [ "${bouffalo_sdk_root}/components/libc" ]
 
     sources = [
+      "${bouffalo_sdk_root}/components/libc/assert.c",
       "${bouffalo_sdk_root}/components/libc/newlib/port_init_fini.c",
       "${bouffalo_sdk_root}/components/libc/newlib/port_memory.c",
       "${bouffalo_sdk_root}/components/libc/newlib/syscalls_nosys.c",
@@ -895,6 +901,10 @@
     include_dirs +=
         [ "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd" ]
 
+    if (defined(invoker.enable_lwip_pbuf_ram) && invoker.enable_lwip_pbuf_ram) {
+      include_dirs += [ "${bouffalolab_iot_sdk_build_root}/patches/lwip" ]
+    }
+
     defines = [
       "CONFIG_LWIP",
       "CONFIG_MAC_TXQ_DEPTH=8",
@@ -937,7 +947,6 @@
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/ip6_frag.c",
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/mld6.c",
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/ipv6/nd6.c",
-      "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/mem.c",
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/memp.c",
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/netif.c",
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/pbuf.c",
@@ -952,6 +961,13 @@
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/netif/ethernet.c",
     ]
 
+    if (defined(invoker.enable_lwip_pbuf_ram) && invoker.enable_lwip_pbuf_ram) {
+      sources += [ "${bouffalolab_iot_sdk_build_root}/patches/lwip/mem.c" ]
+    } else {
+      sources +=
+          [ "${bouffalo_sdk_root}/components/net/lwip/lwip/src/core/mem.c" ]
+    }
+
     sources += [
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/dhcpd/dhcp_server_raw.c",
       "${bouffalo_sdk_root}/components/net/lwip/lwip/src/apps/lwiperf/lwiperf.c",
diff --git a/third_party/bouffalolab/bl702/bl_iot_sdk.gni b/third_party/bouffalolab/bl702/bl_iot_sdk.gni
index 76d35da..45122f4 100644
--- a/third_party/bouffalolab/bl702/bl_iot_sdk.gni
+++ b/third_party/bouffalolab/bl702/bl_iot_sdk.gni
@@ -21,6 +21,7 @@
 declare_args() {
   bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo"
 
+  enable_lwip_pbuf_ram = false
   enable_debug_coredump = false
   coredump_binary_id = 0
 }
diff --git a/third_party/bouffalolab/bl702l/bl_iot_sdk.gni b/third_party/bouffalolab/bl702l/bl_iot_sdk.gni
index ac608a7..514d25d 100644
--- a/third_party/bouffalolab/bl702l/bl_iot_sdk.gni
+++ b/third_party/bouffalolab/bl702l/bl_iot_sdk.gni
@@ -21,6 +21,7 @@
 declare_args() {
   bl_iot_sdk_root = "${chip_root}/third_party/bouffalolab/repo"
 
+  enable_lwip_pbuf_ram = false
   enable_pds = false
   enable_debug_coredump = false
   coredump_binary_id = 0
diff --git a/third_party/bouffalolab/repo b/third_party/bouffalolab/repo
index 75df6e8..11448ae 160000
--- a/third_party/bouffalolab/repo
+++ b/third_party/bouffalolab/repo
@@ -1 +1 @@
-Subproject commit 75df6e87ffa10b905c9dbb0efc5fd35f96955c55
+Subproject commit 11448aeb1a5d9c000859db47863a3bfcbc4d6032