Commit 849694f
committed
Fix SMP deadlock by avoiding nested monitors/processes_table locks
https://ampcode.com/threads/T-019ba1c2-2a7f-77c7-bd33-ce9f303152a2
Fix lock ordering inversion causing deadlocks on ESP32 SMP under heavy socket load.
The functions enif_demonitor_process and destroy_resource_monitors previously
acquired locks in the order: monitors -> processes_table. However,
enif_monitor_process and context_get_process_info (via resource_monitor_to_resource)
use the opposite order: processes_table -> monitors. This created an ABBA
deadlock under SMP when these code paths ran concurrently.
The fix uses a two-phase approach in both functions:
- Phase 1: Acquire monitors lock, find/remove entries, release monitors lock
- Phase 2: Acquire process lock, send signals, release process lock
This ensures the two locks are never held simultaneously, eliminating the
deadlock while preserving correct semantics. If the target process dies
between phases, the demonitor signal is simply skipped (harmless no-op).
Also fixes a pre-existing bug where enif_demonitor_process failed to unlock
the monitors list on the resource_type mismatch error path.
Signed-off-by: Peter M <petermm@gmail.com>1 parent 6fd67cb commit 849694f
1 file changed
+40
-17
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
476 | 476 | | |
477 | 477 | | |
478 | 478 | | |
| 479 | + | |
| 480 | + | |
| 481 | + | |
| 482 | + | |
479 | 483 | | |
480 | 484 | | |
481 | 485 | | |
482 | 486 | | |
483 | 487 | | |
484 | 488 | | |
485 | 489 | | |
| 490 | + | |
486 | 491 | | |
487 | 492 | | |
488 | 493 | | |
489 | | - | |
490 | | - | |
491 | | - | |
492 | | - | |
493 | | - | |
494 | | - | |
| 494 | + | |
| 495 | + | |
495 | 496 | | |
496 | 497 | | |
497 | | - | |
498 | | - | |
| 498 | + | |
499 | 499 | | |
500 | 500 | | |
501 | | - | |
502 | 501 | | |
503 | 502 | | |
504 | | - | |
| 503 | + | |
| 504 | + | |
| 505 | + | |
| 506 | + | |
| 507 | + | |
| 508 | + | |
| 509 | + | |
| 510 | + | |
| 511 | + | |
| 512 | + | |
| 513 | + | |
| 514 | + | |
| 515 | + | |
505 | 516 | | |
506 | 517 | | |
507 | 518 | | |
508 | 519 | | |
509 | 520 | | |
| 521 | + | |
| 522 | + | |
| 523 | + | |
| 524 | + | |
| 525 | + | |
510 | 526 | | |
511 | 527 | | |
512 | 528 | | |
513 | 529 | | |
514 | 530 | | |
515 | 531 | | |
516 | | - | |
517 | | - | |
518 | | - | |
519 | | - | |
520 | | - | |
521 | 532 | | |
522 | | - | |
| 533 | + | |
523 | 534 | | |
524 | 535 | | |
525 | | - | |
526 | 536 | | |
| 537 | + | |
| 538 | + | |
| 539 | + | |
| 540 | + | |
| 541 | + | |
| 542 | + | |
| 543 | + | |
| 544 | + | |
| 545 | + | |
| 546 | + | |
| 547 | + | |
| 548 | + | |
| 549 | + | |
527 | 550 | | |
528 | 551 | | |
529 | 552 | | |
| |||
0 commit comments