#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <string.h>
#include <errno.h>

int test_chunk_size(int chunk_size) {
    size_t page_size = sysconf(_SC_PAGESIZE);
    
    void *mem = malloc(page_size * chunk_size);
    if (!mem) return -1;
    
    memset(mem, 0xFF, page_size * chunk_size);
    
    void **ptrs = malloc(sizeof(void*) * chunk_size);
    int *status = malloc(sizeof(int) * chunk_size);
    
    for (int j = 0; j < chunk_size; j++) {
        ptrs[j] = (char*)mem + (j * page_size);
        status[j] = -999;
    }
    
    long result = syscall(SYS_move_pages, 0, chunk_size, ptrs, NULL, status, 0);
    
    int errors = 0;
    if (result == 0) {
        for (int j = 0; j < chunk_size; j++) {
            if (status[j] < 0) errors++;
        }
    }
    
    free(mem);
    free(ptrs);
    free(status);
    
    return (result == 0) ? errors : -1;
}

int main() {
    int threshold = -1;
    
    // Test sizes from 1 to 40 pages
    for (int size = 1; size <= 40; size++) {
        int errors = test_chunk_size(size);
        
        if (errors == -1) {
            if (threshold == -1) threshold = size;
            break;
        } else if (errors == 0) {
            printf("%2d pages: SUCCESS (0 errors)\n", size);
        } else {
            printf("%2d pages: %d errors\n", 
                   size, errors);
            threshold = size;
            break;
        }
    }
    
    if (threshold > 0)
        printf("Threshold: %d pages\n", threshold);
     else 
        printf("No threshold found in range 1-40 pages\n");
    
    return 0;
}
