CS 134

Understanding the OS/161 Swap System

Overview

The swap system in OS/161 manages the swap file, which provides virtual memory backing store. For your VM implementation, you'll primarily interact with the swap reservation system, which ensures there's always enough swap space available when needed.

Key Concepts

Swap Space States

A swap page can be in one of three states:

  1. Free: Available for allocation
  2. Reserved: Promised to a zero-filled page but not yet allocated
  3. Allocated: Actually in use for a specific page

Reservation System

  • Reserves space for future allocations
  • Prevents out-of-memory conditions
  • Crucial for zero-filled pages

Key Functions You'll Use

/*
 * Reserve swap pages for future use
 * Returns: 0 on success, ENOMEM if insufficient space
 */
int swap_reserve(unsigned long npages);

/*
 * Release previously reserved swap pages
 */
void swap_unreserve(unsigned long npages);

Usage Patterns

When Growing VM Objects

/* Example pattern for reserving swap */
unsigned long new_pages = growth_amount;
result = swap_reserve(new_pages);
if (result) {
    /* Handle out of swap space case */
    return result;
}
/* Now safe to create zero-filled pages */

When Shrinking VM Objects

/* Example pattern for unreserving swap */
unsigned long removed_pages = shrink_amount;
swap_unreserve(removed_pages);

Important Considerations

  1. Always Reserve First
    • Must reserve space before creating zero-filled pages
    • Ensures system can't run out of swap unexpectedly
  2. Proper Cleanup
    • Unreserve space when removing pages
    • Handle both explicit pages and zero-filled pages
  3. Error Handling
    • Check return value from swap_reserve
    • Clean up properly if reservation fails

Common Pitfalls

  1. Resource Management
    • Forgetting to unreserve on cleanup
    • Not maintaining correct reservation counts
    • Double-unreserving pages
  2. Error Cases
    • Not handling ENOMEM from swap_reserve
    • Leaving system in inconsistent state after errors

Best Practices

  1. Reserve swap space before making any changes
  2. Track number of pages carefully
  3. Clean up reservations on error paths
  4. Maintain proper accounting between reserved and allocated pages

Note on Zero-Filled Pages

  • Zero-filled pages don't immediately consume swap space
  • But they need reserved space for future paging
  • Proper swap reservation is crucial

(When logged in, completion status appears here.)