int pm_map_workingset(pm_map_t *map, pm_memusage_t *ws_out) {
    uint64_t *pagemap;
    size_t len, i;
    uint64_t count, flags;
    pm_memusage_t ws;
    int error;

    if (!map || !ws_out)
        return -1;

    error = pm_map_pagemap(map, &pagemap, &len);
    if (error) return error;

    pm_memusage_zero(&ws);
    
    for (i = 0; i < len; i++) {
        error = pm_kernel_flags(map->proc->ker, PM_PAGEMAP_PFN(pagemap[i]),
                                &flags);
        if (error) goto out;

        if (!(flags & PM_PAGE_REFERENCED)) 
            continue;

        error = pm_kernel_count(map->proc->ker, PM_PAGEMAP_PFN(pagemap[i]),
                                &count);
        if (error) goto out;

        ws.vss += map->proc->ker->pagesize;
        if( PM_PAGEMAP_SWAPPED(pagemap[i]) ) continue;
        ws.rss += (count >= 1) ? (map->proc->ker->pagesize) : (0);
        ws.pss += (count >= 1) ? (map->proc->ker->pagesize / count) : (0);
        ws.uss += (count == 1) ? (map->proc->ker->pagesize) : (0);
    }

    memcpy(ws_out, &ws, sizeof(ws));

    error = 0;

out:
    free(pagemap);

    return 0;
}
int pm_map_usage(pm_map_t *map, pm_memusage_t *usage_out) {
    uint64_t *pagemap;
    size_t len, i;
    uint64_t count;
    pm_memusage_t usage;
    int error;

    if (!map || !usage_out)
        return -1;

    error = pm_map_pagemap(map, &pagemap, &len);
    if (error) return error;

    pm_memusage_zero(&usage);

    for (i = 0; i < len; i++) {
        if (!PM_PAGEMAP_PRESENT(pagemap[i]) ||
            PM_PAGEMAP_SWAPPED(pagemap[i]))
            continue;

        error = pm_kernel_count(map->proc->ker, PM_PAGEMAP_PFN(pagemap[i]),
                                &count);
        if (error) goto out;

        usage.vss += map->proc->ker->pagesize;
        usage.rss += (count >= 1) ? (map->proc->ker->pagesize) : (0);
        usage.pss += (count >= 1) ? (map->proc->ker->pagesize / count) : (0);
        usage.uss += (count == 1) ? (map->proc->ker->pagesize) : (0);
    }

    memcpy(usage_out, &usage, sizeof(usage));

    error = 0;

out:    
    free(pagemap);

    return error;
}
static int read_pages(struct ksm_pages *kp, pm_map_t **maps, size_t num_maps, uint8_t pr_flags) {
    size_t i, j, k;
    size_t len;
    uint64_t *pagemap;
    size_t map_len;
    uint64_t flags;
    pm_kernel_t *ker;
    int error;
    unsigned long vaddr;
    int fd;
    off_t off;
    char filename[MAX_FILENAME];
    uint32_t *data;
    uint32_t hash;
    int rc = 0;
    struct ksm_page *cur_page;
    pid_t pid;

    if (num_maps == 0)
        return 0;

    pid = pm_process_pid(maps[0]->proc);
    ker = maps[0]->proc->ker;
    error = snprintf(filename, MAX_FILENAME, "/proc/%d/mem", pid);
    if (error < 0 || error >= MAX_FILENAME) {
        return -1;
    }

    data = malloc(pm_kernel_pagesize(ker));
    if (data == NULL) {
        fprintf(stderr, "warning: not enough memory to malloc data buffer\n");
        return -1;
    }

    fd = open(filename, O_RDONLY);
    if (fd < 0) {
        fprintf(stderr, "warning: could not open %s\n", filename);
        rc = -1;
        goto err_open;
    }

    for (i = 0; i < num_maps; i++) {
        error = pm_map_pagemap(maps[i], &pagemap, &map_len);
        if (error) {
            fprintf(stderr, "warning: could not read the pagemap of %d\n",
                    pm_process_pid(maps[i]->proc));
            continue;
        }
        for (j = 0; j < map_len; j++) {
            error = pm_kernel_flags(ker, PM_PAGEMAP_PFN(pagemap[j]), &flags);
            if (error) {
                fprintf(stderr, "warning: could not read flags for pfn at address 0x%016" PRIx64 "\n",
                        pagemap[i]);
                continue;
            }
            if (!(flags & PM_PAGE_KSM)) {
                continue;
            }
            vaddr = pm_map_start(maps[i]) + j * pm_kernel_pagesize(ker);
            off = lseek(fd, vaddr, SEEK_SET);
            if (off == (off_t)-1) {
                fprintf(stderr, "warning: could not lseek to 0x%08lx\n", vaddr);
                continue;
            }
            len = read(fd, data, pm_kernel_pagesize(ker));
            if (len != pm_kernel_pagesize(ker)) {
                fprintf(stderr, "warning: could not read page at 0x%08lx\n", vaddr);
                continue;
            }

            hash = hashword(data, pm_kernel_pagesize(ker) / sizeof(*data), 17);

            for (k = 0; k < kp->len; k++) {
                if (kp->pages[k].hash == hash) break;
            }

            if (k == kp->len) {
                if (kp->len == kp->size) {
                    struct ksm_page *tmp = realloc(kp->pages,
                            (kp->size + GROWTH_FACTOR) * sizeof(*kp->pages));
                    if (tmp == NULL) {
                        fprintf(stderr, "warning: not enough memory to realloc pages struct\n");
                        free(pagemap);
                        rc = -1;
                        goto err_realloc;
                    }
                    memset(&tmp[k], 0, sizeof(tmp[k]) * GROWTH_FACTOR);
                    kp->pages = tmp;
                    kp->size += GROWTH_FACTOR;
                }
                rc = pm_kernel_count(ker, PM_PAGEMAP_PFN(pagemap[j]), &kp->pages[kp->len].count);
                if (rc) {
                    fprintf(stderr, "error reading page count\n");
                    free(pagemap);
                    goto err_count;
                }
                kp->pages[kp->len].hash = hash;
                kp->pages[kp->len].pattern =
                        is_pattern((uint8_t *)data, pm_kernel_pagesize(ker)) ?
                        (data[0] & 0xFF) : NO_PATTERN;
                kp->len++;
            }

            cur_page = &kp->pages[k];

            if (pr_flags & PR_VERBOSE) {
                if (cur_page->vaddr_len > 0 &&
                        cur_page->vaddr[cur_page->vaddr_len - 1].pid == pid &&
                        cur_page->vaddr[cur_page->vaddr_len - 1].addr ==
                        vaddr - (cur_page->vaddr[cur_page->vaddr_len - 1].num_pages *
                        pm_kernel_pagesize(ker))) {
                    cur_page->vaddr[cur_page->vaddr_len - 1].num_pages++;
                } else {
                    if (cur_page->vaddr_len == cur_page->vaddr_size) {
                        struct vaddr *tmp = realloc(cur_page->vaddr,
                                (cur_page->vaddr_size + GROWTH_FACTOR) * sizeof(*(cur_page->vaddr)));
                        if (tmp == NULL) {
                            fprintf(stderr, "warning: not enough memory to realloc vaddr array\n");
                            free(pagemap);
                            rc = -1;
                            goto err_realloc;
                        }
                        memset(&tmp[cur_page->vaddr_len], 0, sizeof(tmp[cur_page->vaddr_len]) * GROWTH_FACTOR);
                        cur_page->vaddr = tmp;
                        cur_page->vaddr_size += GROWTH_FACTOR;
                    }
                    cur_page->vaddr[cur_page->vaddr_len].addr = vaddr;
                    cur_page->vaddr[cur_page->vaddr_len].num_pages = 1;
                    cur_page->vaddr[cur_page->vaddr_len].pid = pid;
                    cur_page->vaddr_len++;
                }
            }
            cur_page->vaddr_count++;
        }
        free(pagemap);
    }
    goto no_err;

err_realloc:
err_count:
    if (pr_flags & PR_VERBOSE) {
        for (i = 0; i < kp->len; i++) {
            free(kp->pages[i].vaddr);
        }
    }
    free(kp->pages);

no_err:
    close(fd);
err_open:
    free(data);
    return rc;
}
int main(int argc, char *argv[]) {
    pid_t pid;

    /* libpagemap context */
    pm_kernel_t *ker;
    int pagesize; /* cached for speed */
    pm_process_t *proc;

    /* maps and such */
    pm_map_t **maps; int num_maps;

    struct map_info **mis;
    struct map_info *mi;

    /* pagemap information */
    uint64_t *pagemap; int num_pages;
    unsigned long address; uint64_t mapentry;
    uint64_t count, flags;

    /* totals */
    unsigned long total_shared_clean, total_shared_dirty, total_private_clean, total_private_dirty;
    pm_memusage_t total_usage;

    /* command-line options */
    int ws;
#define WS_OFF (0)
#define WS_ONLY (1)
#define WS_RESET (2)
    int (*compfn)(const void *a, const void *b);
    int hide_zeros;

    /* temporary variables */
    int i, j;
    char *endptr;
    int error;

    if (argc < 2) {
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    ws = WS_OFF;
    compfn = NULL;
    hide_zeros = 0;
    for (i = 1; i < argc - 1; i++) {
        if (!strcmp(argv[i], "-w")) { ws = WS_ONLY; continue; }
        if (!strcmp(argv[i], "-W")) { ws = WS_RESET; continue; }
        if (!strcmp(argv[i], "-m")) { compfn = NULL; continue; }
        if (!strcmp(argv[i], "-p")) { compfn = &comp_pss; continue; }
        if (!strcmp(argv[i], "-h")) { hide_zeros = 1; continue; }
        fprintf(stderr, "Invalid argument \"%s\".\n", argv[i]);
        usage(argv[0]);
        exit(EXIT_FAILURE);
    }

    pid = (pid_t)strtol(argv[argc - 1], &endptr, 10);
    if (*endptr != '\0') {
        fprintf(stderr, "Invalid PID \"%s\".\n", argv[argc - 1]);
        exit(EXIT_FAILURE);
    }

    error = pm_kernel_create(&ker);
    if (error) {
        fprintf(stderr, "error creating kernel interface -- "
                        "does this kernel have pagemap?\n");
        exit(EXIT_FAILURE);
    }

    pagesize = pm_kernel_pagesize(ker);

    error = pm_process_create(ker, pid, &proc);
    if (error) {
        fprintf(stderr, "error creating process interface -- "
                        "does process %d really exist?\n", pid);
        exit(EXIT_FAILURE);
    }

    if (ws == WS_RESET) {
        error = pm_process_workingset(proc, NULL, 1);
        if (error) {
            fprintf(stderr, "error resetting working set for process.\n");
            exit(EXIT_FAILURE);
        }
        exit(EXIT_SUCCESS);
    }

    /* get maps, and allocate our map_info array */
    error = pm_process_maps(proc, &maps, &num_maps);
    if (error) {
        fprintf(stderr, "error listing maps.\n");
        exit(EXIT_FAILURE);
    }

    mis = (struct map_info **)calloc(num_maps, sizeof(struct map_info *));
    if (!mis) {
        fprintf(stderr, "error allocating map_info array: %s\n", strerror(errno));
        exit(EXIT_FAILURE);
    }

    /* print header */
    if (ws == WS_ONLY) {
        printf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
               "WRss", "WPss", "WUss", "WShCl", "WShDi", "WPrCl", "WPrDi", "Name");
        printf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
               "-------", "-------", "-------", "-------", "-------", "-------", "-------", "");
    } else {
        printf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
               "Vss", "Rss", "Pss", "Uss", "ShCl", "ShDi", "PrCl", "PrDi", "Name");
        printf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
               "-------", "-------", "-------", "-------", "-------", "-------", "-------", "-------", "");
    }

    /* zero things */
    pm_memusage_zero(&total_usage);
    total_shared_clean = total_shared_dirty = total_private_clean = total_private_dirty = 0;

    for (i = 0; i < num_maps; i++) {
        mi = (struct map_info *)calloc(1, sizeof(struct map_info));
        if (!mi) {
            fprintf(stderr, "error allocating map_info: %s\n", strerror(errno));
            exit(EXIT_FAILURE);
        }

        mi->map = maps[i];

        /* get, and sum, memory usage */

        if (ws == WS_ONLY)
            error = pm_map_workingset(mi->map, &mi->usage);
        else
            error = pm_map_usage(mi->map, &mi->usage);
        if (error) {
            fflush(stdout);
            fprintf(stderr, "error getting usage for map.\n");
            continue;
        }

        pm_memusage_add(&total_usage, &mi->usage);

        /* get, and sum, individual page counts */

        error = pm_map_pagemap(mi->map, &pagemap, &num_pages);
        if (error) {
            fflush(stdout);
            fprintf(stderr, "error getting pagemap for map.\n");
            continue;
        }

        mi->shared_clean = mi->shared_dirty = mi->private_clean = mi->private_dirty = 0;

        for (j = 0; j < num_pages; j++) {
            address = pm_map_start(mi->map) + j * ker->pagesize;
            mapentry = pagemap[j];

            if (PM_PAGEMAP_PRESENT(mapentry) && !PM_PAGEMAP_SWAPPED(mapentry)) {

                error = pm_kernel_count(ker, PM_PAGEMAP_PFN(mapentry), &count);
                if (error) {
                    fflush(stdout);
                    fprintf(stderr, "error getting count for frame.\n");
                }

                error = pm_kernel_flags(ker, PM_PAGEMAP_PFN(mapentry), &flags);
                if (error) {
                    fflush(stdout);
                    fprintf(stderr, "error getting flags for frame.\n");
                }

                if ((ws != WS_ONLY) || (flags & PM_PAGE_REFERENCED)) {
                    if (count > 1) {
                        if (flags & PM_PAGE_DIRTY)
                            mi->shared_dirty++;
                        else
                            mi->shared_clean++;
                    } else {
                        if (flags & PM_PAGE_DIRTY)
                            mi->private_dirty++;
                        else
                            mi->private_clean++;
                    }
                }
            }
        }

        total_shared_clean += mi->shared_clean;
        total_shared_dirty += mi->shared_dirty;
        total_private_clean += mi->private_clean;
        total_private_dirty += mi->private_dirty;

        /* add to array */
        mis[i] = mi;
    }

    /* sort the array, if requested (compfn == NULL for original order) */
    if (compfn)
        qsort(mis, num_maps, sizeof(mis[0]), compfn);

    for (i = 0; i < num_maps; i++) {
        mi = mis[i];

        if ((!mi) || (hide_zeros && !mi->usage.rss))
            continue;

        if (ws == WS_ONLY) {
            printf("%6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %s\n",
                (long)mi->usage.rss / 1024,
                (long)mi->usage.pss / 1024,
                (long)mi->usage.uss / 1024,
                mi->shared_clean * pagesize / 1024,
                mi->shared_dirty * pagesize / 1024,
                mi->private_clean * pagesize / 1024,
                mi->private_dirty * pagesize / 1024,
                pm_map_name(mi->map)
            );
        } else {
            printf("%6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %s\n",
                (long)mi->usage.vss / 1024,
                (long)mi->usage.rss / 1024,
                (long)mi->usage.pss / 1024,
                (long)mi->usage.uss / 1024,
                mi->shared_clean * pagesize / 1024,
                mi->shared_dirty * pagesize / 1024,
                mi->private_clean * pagesize / 1024,
                mi->private_dirty * pagesize / 1024,
                pm_map_name(mi->map)
            );
        }
    }

    /* print totals */
    if (ws == WS_ONLY) {
        printf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
               "-------", "-------", "-------", "-------", "-------", "-------", "-------", "");
        printf("%6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %s\n",
            (long)total_usage.rss / 1024,
            (long)total_usage.pss / 1024,
            (long)total_usage.uss / 1024,
            total_shared_clean * pagesize / 1024,
            total_shared_dirty * pagesize / 1024,
            total_private_clean * pagesize / 1024,
            total_private_dirty * pagesize / 1024,
            "TOTAL"
        );
    } else {
        printf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
               "-------", "-------", "-------", "-------", "-------", "-------", "-------", "-------", "");
        printf("%6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %6ldK  %s\n",
            (long)total_usage.vss / 1024,
            (long)total_usage.rss / 1024,
            (long)total_usage.pss / 1024,
            (long)total_usage.uss / 1024,
            total_shared_clean * pagesize / 1024,
            total_shared_dirty * pagesize / 1024,
            total_private_clean * pagesize / 1024,
            total_private_dirty * pagesize / 1024,
            "TOTAL"
        );
    }

    return 0;
}