@@ -768,6 +768,8 @@ static int semu_init(emu_state_t *emu, int argc, char **argv)
768768
769769 /* Set up peripherals */
770770 emu -> uart .in_fd = 0 , emu -> uart .out_fd = 1 ;
771+ emu -> uart .waiting_hart_id = UINT32_MAX ;
772+ emu -> uart .has_waiting_hart = false;
771773 capture_keyboard_input (); /* set up uart */
772774#if SEMU_HAS (VIRTIONET )
773775 /* Always set ram pointer, even if netdev is not configured.
@@ -853,17 +855,20 @@ static int semu_init(emu_state_t *emu, int argc, char **argv)
853855 */
854856static void wfi_handler (hart_t * hart )
855857{
856- vm_t * vm = hart -> vm ;
857- /* Only yield in SMP mode (n_hart > 1) */
858- if (vm -> n_hart > 1 ) {
859- /* Per RISC-V spec: WFI returns immediately if interrupt is pending.
860- * Only yield to scheduler if no interrupt is currently pending.
858+ /* Per RISC-V spec: WFI returns immediately if interrupt is pending.
859+ * We check if any interrupt is actually pending (sip & sie != 0).
860+ */
861+ bool interrupt_pending = (hart -> sip & hart -> sie ) != 0 ;
862+
863+ if (!interrupt_pending ) {
864+ hart -> in_wfi = true; /* Mark as waiting for interrupt */
865+ coro_yield (); /* Suspend until scheduler resumes us */
866+ /* NOTE: Do NOT clear in_wfi here to avoid race condition.
867+ * The scheduler needs to see this flag to detect idle state.
868+ * The flag will be cleared when an interrupt is actually injected.
861869 */
862- if (!(hart -> sip & hart -> sie )) {
863- hart -> in_wfi = true; /* Mark as waiting for interrupt */
864- coro_yield (); /* Suspend until scheduler resumes us */
865- hart -> in_wfi = false; /* Resumed - no longer waiting */
866- }
870+ } else {
871+ hart -> in_wfi = false; /* Clear if interrupt already pending */
867872 }
868873}
869874
@@ -1150,87 +1155,144 @@ static int semu_run(emu_state_t *emu)
11501155 poll_capacity = needed ;
11511156 }
11521157
1158+ /* Determine poll timeout based on hart states BEFORE setting up
1159+ * poll fds. This check must happen before coro_resume_hart()
1160+ * modifies flags.
1161+ *
1162+ * - If no harts are STARTED, block indefinitely (wait for IPI)
1163+ * - If all STARTED harts are idle (WFI or UART waiting), block
1164+ * - Otherwise, use non-blocking poll (timeout=0)
1165+ */
1166+ int poll_timeout = 0 ;
1167+ uint32_t started_harts = 0 ;
1168+ uint32_t idle_harts = 0 ;
1169+ for (uint32_t i = 0 ; i < vm -> n_hart ; i ++ ) {
1170+ if (vm -> hart [i ]-> hsm_status == SBI_HSM_STATE_STARTED ) {
1171+ started_harts ++ ;
1172+ /* Count hart as idle if it's in WFI or waiting for UART */
1173+ if (vm -> hart [i ]-> in_wfi ||
1174+ (emu -> uart .has_waiting_hart &&
1175+ emu -> uart .waiting_hart_id == i )) {
1176+ idle_harts ++ ;
1177+ }
1178+ }
1179+ }
1180+
11531181 /* Collect file descriptors for poll() */
11541182 size_t pfd_count = 0 ;
11551183 int timer_index = -1 ;
11561184
1157- /* Add periodic timer fd (1ms interval for guest timer emulation) */
1185+ /* Add periodic timer fd (1ms interval for guest timer emulation).
1186+ * Only add timer when ALL harts are active (none idle) to allow
1187+ * poll() to sleep when any harts are in WFI. When harts are idle,
1188+ * timer updates can be deferred until they wake up.
1189+ *
1190+ * IMPORTANT: During SMP boot (started_harts < vm->n_hart), always
1191+ * include the timer to ensure secondary harts can complete
1192+ * initialization. Only apply conditional exclusion after all harts
1193+ * have started.
1194+ */
1195+ bool all_harts_started = (started_harts >= vm -> n_hart );
1196+ bool harts_active = !all_harts_started || (idle_harts == 0 );
11581197#ifdef __APPLE__
11591198 /* macOS: use kqueue with EVFILT_TIMER */
1160- if (kq >= 0 && pfd_count < poll_capacity ) {
1199+ if (kq >= 0 && pfd_count < poll_capacity && harts_active ) {
11611200 pfds [pfd_count ] = (struct pollfd ){kq , POLLIN , 0 };
11621201 timer_index = (int ) pfd_count ;
11631202 pfd_count ++ ;
11641203 }
11651204#else
11661205 /* Linux: use timerfd */
1167- if (wfi_timer_fd >= 0 && pfd_count < poll_capacity ) {
1206+ if (wfi_timer_fd >= 0 && pfd_count < poll_capacity &&
1207+ harts_active ) {
11681208 pfds [pfd_count ] = (struct pollfd ){wfi_timer_fd , POLLIN , 0 };
11691209 timer_index = (int ) pfd_count ;
11701210 pfd_count ++ ;
11711211 }
11721212#endif
11731213
1174- /* Add UART input fd (stdin for keyboard input) */
1175- if (emu -> uart .in_fd >= 0 && pfd_count < poll_capacity ) {
1214+ /* Add UART input fd (stdin for keyboard input).
1215+ * Only add UART when:
1216+ * 1. During SMP boot (not all harts started), OR
1217+ * 2. All harts are active (idle_harts == 0), OR
1218+ * 3. A hart is actively waiting for UART input
1219+ *
1220+ * This prevents UART (which is always "readable" on TTY) from
1221+ * preventing poll() sleep when harts are idle. Trade-off: user
1222+ * input (Ctrl+A x) may be delayed by up to poll_timeout (10ms)
1223+ * when harts are idle, which is acceptable for an emulator.
1224+ */
1225+ bool need_uart = !all_harts_started || (idle_harts == 0 ) ||
1226+ emu -> uart .has_waiting_hart ;
1227+ if (emu -> uart .in_fd >= 0 && pfd_count < poll_capacity &&
1228+ need_uart ) {
11761229 pfds [pfd_count ] = (struct pollfd ){emu -> uart .in_fd , POLLIN , 0 };
11771230 pfd_count ++ ;
11781231 }
11791232
1180- /* Determine poll timeout based on hart WFI states:
1181- * - If no harts are STARTED, block indefinitely (wait for IPI)
1182- * - If all STARTED harts are in WFI, block indefinitely
1183- * - Otherwise, use non-blocking poll (timeout=0)
1233+ /* Set poll timeout based on current idle state (adaptive timeout).
1234+ * This implements three-tier polling strategy:
1235+ * 1. Blocking (-1): All harts idle → deep sleep, wait for events
1236+ * 2. Short timeout (10ms): Some harts idle → reduce CPU usage
1237+ * 3. Non-blocking (0): No harts idle → maximum responsiveness
1238+ *
1239+ * The 10ms timeout for partial idle is critical for SMP systems
1240+ * where Linux keeps some harts active even when "idle".
1241+ *
1242+ * Note: When pfd_count==0 (no fds), poll() acts as a sleep.
11841243 */
1185- int poll_timeout = 0 ;
1186- uint32_t started_harts = 0 ;
1187- uint32_t wfi_harts = 0 ;
1188- for (uint32_t i = 0 ; i < vm -> n_hart ; i ++ ) {
1189- if (vm -> hart [i ]-> hsm_status == SBI_HSM_STATE_STARTED ) {
1190- started_harts ++ ;
1191- if (vm -> hart [i ]-> in_wfi )
1192- wfi_harts ++ ;
1193- }
1194- }
1195- /* Block if no harts running or all running harts are waiting */
1196- if (pfd_count > 0 &&
1197- (started_harts == 0 || wfi_harts == started_harts ))
1244+ if (started_harts == 0 || idle_harts == started_harts ) {
1245+ /* Deep sleep: all harts idle or no harts started */
11981246 poll_timeout = -1 ;
1247+ } else if (idle_harts > 0 ) {
1248+ /* Partial idle: some harts idle, use 10ms timeout */
1249+ poll_timeout = 10 ;
1250+ } else {
1251+ /* Active: no harts idle, use non-blocking poll */
1252+ poll_timeout = 0 ;
1253+ }
11991254
12001255 /* Execute poll() to wait for I/O events.
1201- * - timeout=0: non-blocking poll when harts are running
1202- * - timeout=-1: blocking poll when all harts in WFI (idle state)
1256+ * - timeout=0: non-blocking poll when harts are active
1257+ * - timeout=10: short sleep when some harts idle
1258+ * - timeout=-1: blocking poll when all harts idle (WFI or UART
1259+ * wait)
1260+ *
1261+ * When pfd_count==0, poll() acts as a pure sleep mechanism.
12031262 */
1204- if (pfd_count > 0 ) {
1205- int nevents = poll (pfds , pfd_count , poll_timeout );
1206- if (nevents > 0 ) {
1207- /* Consume timer expiration events to prevent fd staying
1208- * readable
1209- */
1210- if (timer_index >= 0 &&
1211- (pfds [timer_index ].revents & POLLIN )) {
1263+ int nevents = poll (pfds , pfd_count , poll_timeout );
1264+
1265+ if (pfd_count > 0 && nevents > 0 ) {
1266+ /* Consume timer expiration events to prevent fd staying
1267+ * readable
1268+ */
1269+ if (timer_index >= 0 && (pfds [timer_index ].revents & POLLIN )) {
12121270#ifdef __APPLE__
1213- /* drain kqueue events with non-blocking kevent */
1214- struct kevent events [32 ];
1215- struct timespec timeout_zero = {0 , 0 };
1216- kevent (kq , NULL , 0 , events , 32 , & timeout_zero );
1271+ /* drain kqueue events with non-blocking kevent */
1272+ struct kevent events [32 ];
1273+ struct timespec timeout_zero = {0 , 0 };
1274+ kevent (kq , NULL , 0 , events , 32 , & timeout_zero );
12171275#else
1218- /* Linux: read timerfd to consume expiration count */
1219- uint64_t expirations ;
1220- ssize_t ret_read = read ( wfi_timer_fd , & expirations ,
1221- sizeof (expirations ));
1222- (void ) ret_read ;
1276+ /* Linux: read timerfd to consume expiration count */
1277+ uint64_t expirations ;
1278+ ssize_t ret_read =
1279+ read ( wfi_timer_fd , & expirations , sizeof (expirations ));
1280+ (void ) ret_read ;
12231281#endif
1224- }
1225- } else if (nevents < 0 && errno != EINTR ) {
1226- perror ("poll" );
12271282 }
1283+ } else if (nevents < 0 && errno != EINTR ) {
1284+ perror ("poll" );
12281285 }
12291286
12301287 /* Resume all hart coroutines (round-robin scheduling).
12311288 * Each hart executes a batch of instructions, then yields back.
12321289 * Harts in WFI will clear their in_wfi flag when resuming from
12331290 * coro_yield() in wfi_handler().
1291+ *
1292+ * Note: We must always resume harts after poll() returns, even if
1293+ * all harts appear idle. The in_wfi flag is only cleared during
1294+ * resume, so skipping resume would cause a deadlock where harts
1295+ * remain stuck waiting even after events arrive.
12341296 */
12351297 for (uint32_t i = 0 ; i < vm -> n_hart ; i ++ ) {
12361298 coro_resume_hart (i );
0 commit comments