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