+ #include <stdlib.h>
+ #include <sys/param.h> /* dbtob */
+ #include <sys/swap.h>
+ #include <sys/types.h>
+ #include <unistd.h>
+
+ static int
+ getstats(int *total, int *used)
+ {
+ struct swapent *sep, *fsep;
+ int rnswap, nswap, i;
+
+ if ((nswap = swapctl(SWAP_NSWAP, 0, 0)) < 1) {
+ warn("swaptctl 'SWAP_NSWAP':");
+ return 1;
+ }
+ if (!(fsep = sep = calloc(nswap, sizeof(*sep)))) {
+ warn("calloc 'nswap':");
+ return 1;
+ }
+ if ((rnswap = swapctl(SWAP_STATS, (void *)sep, nswap)) < 0) {
+ warn("swapctl 'SWAP_STATA':");
+ return 1;
+ }
+ if (nswap != rnswap) {
+ warn("getstats: SWAP_STATS != SWAP_NSWAP");
+ return 1;
+ }
+
+ *total = 0;
+ *used = 0;
+
+ for (i = 0; i < rnswap; i++) {
+ *total += sep->se_nblks >> 1;
+ *used += sep->se_inuse >> 1;
+ }
+
+ free(fsep);
+
+ return 0;
+ }
+
+ const char *
+ swap_free(void)
+ {
+ int total, used;
+
+ if (getstats(&total, &used)) {
+ return NULL;
+ }
+
+ return fmt_human((total - used) * 1024, 1024);
+ }
+
+ const char *
+ swap_perc(void)
+ {
+ int total, used;
+
+ if (getstats(&total, &used)) {
+ return NULL;
+ }
+
+ if (total == 0) {
+ return NULL;
+ }
+
+ return bprintf("%d", 100 * used / total);
+ }
+
+ const char *
+ swap_total(void)
+ {
+ int total, used;
+
+ if (getstats(&total, &used)) {
+ return NULL;
+ }
+
+ return fmt_human(total * 1024, 1024);
+ }
+
+ const char *
+ swap_used(void)
+ {
+ int total, used;
+
+ if (getstats(&total, &used)) {
+ return NULL;
+ }
+
+ return fmt_human(used * 1024, 1024);
+ }