1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802
|
/*
** ATOP - System & Process Monitor
**
** The program 'atop' offers the possibility to view the activity of
** the system on system-level as well as process-/thread-level.
**
** This source-file contains functions to read and handle cgroup metrics.
** ==========================================================================
** Author: Gerlof Langeveld
** E-mail: gerlof.langeveld@atoptool.nl
** Initial date: January 2024
** --------------------------------------------------------------------------
** Copyright (C) 2024 Gerlof Langeveld
**
** This program is free software; you can redistribute it and/or modify it
** under the terms of the GNU General Public License as published by the
** Free Software Foundation; either version 2, or (at your option) any
** later version.
**
** This program is distributed in the hope that it will be useful, but
** WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
** See the GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
** --------------------------------------------------------------------------
*/
#define _POSIX_C_SOURCE
#define _XOPEN_SOURCE
#define _GNU_SOURCE
#define _DEFAULT_SOURCE
#include <sys/types.h>
#include <sys/param.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <ctype.h>
#include <time.h>
#include <stdlib.h>
#include <regex.h>
#include "atop.h"
#include "cgroups.h"
#include "photosyst.h"
#include "photoproc.h"
#include "showgeneric.h"
static void cgcalcdeviate(void);
static void cgrewind(struct cgchainer **);
static struct cgchainer *cgnext(struct cgchainer **, struct cgchainer **);
static void cgwipe(struct cgchainer **, struct cgchainer **,
struct cgchainer **, struct cgchainer **);
static unsigned long walkcgroup(char *, struct cgchainer *, int, long, int, int);
static void getconfig(struct cstat *, struct cstat *);
static int readconfigval(char *, count_t []);
static void getmetrics(struct cstat *);
static void getpressure(char *, count_t *, count_t *);
static long hashcalc(char *, long, int);
static void hashadd(struct cgchainer *[], struct cgchainer *);
static struct cgchainer *hashfind(struct cgchainer *[], long);
static int cgroupfilter(struct cstat *, int, char);
#define CGROUPROOT "/sys/fs/cgroup"
#define CGROUPNHASH 128 // power of 2
#define CGROUPMASK (CGROUPNHASH-1)
// cgroup administration
// =====================
// three types of cgroup collections are maintained:
//
// - current linked list
// -------------------
// this administration consists of a chain of cgchainer structs
// that each refer to a cstat struct containing the cgroup metrics
//
// this chain is built while gathering the current information by the
// walkcgroup() function
// this function mallocs one cgchainer struct and one cstat struct
//
// - previous linked list
// --------------------
// this administration consists of a chain of cgchainer structs
// that each refer to a cstat struct containing the previous cgroup metrics
//
// before building a new current chain, the current chain will be
// saved as the previous chain
//
// - deviation array
// ---------------
// this administration consists of an array(!) of cgchainer structs in which
// the cgchainer struct are still chained to the next element in the array
//
// current cgroup admi
//
static struct cgchainer *cgcurfirst, // first in linked list
*cgcurlast, // last in linked list
*cgcurcursor;
static unsigned int cgcursize; // total size of all cstat structs
static unsigned int cgcurnum; // number of cstat structs
static unsigned int cgcurprocs; // number of processes in current list
static int cgcursequence; // maintain sequence number to be
// assigned to every cgchainer struct
//
// later on this value can be used
// as index in the deviation array
// previous cgroup admi
//
static struct cgchainer *cgprefirst, // first in linked list
*cgprelast, // last in linked list
*cgprecursor,
*cgprehash[CGROUPNHASH];
// deviation cgroup admi
//
static struct cgchainer *cgdevfirst, // pointer to array (!)
*cgdevcursor;
// Check if cgroup v2 is supported on this machine
//
// Return value: 1 - yes
// 0 - no
//
int
cgroupv2support(void)
{
FILE *fp;
char line[128];
// check if this kernel offers cgroups version 2
//
if ( (fp = fopen("/proc/1/cgroup", "r")) )
{
while (fgets(line, sizeof line, fp))
{
if (memcmp(line, "0::", 3) == 0) // equal?
{
supportflags |= CGROUPV2;
break;
}
}
fclose(fp);
}
return (supportflags&CGROUPV2) > 0;
}
// Gather all metrics from the entire cgroup tree,
// creating a chain of cgchainer structs
//
void
photocgroup(void)
{
char origdir[4096];
// wipe previous cgroup chain (not needed any more)
//
cgwipe(&cgprefirst, &cgprelast, &cgprecursor, cgprehash);
// move current cgroup chain to previous cgroup chain
//
cgprefirst = cgcurfirst;
cgprelast = cgcurlast;
cgcurfirst = cgcurlast = cgcurcursor = NULL;
// wipe deviation cgroup memory
// - wipe all contiguous cstat structs (start address in first cgchainer)
// - wipe pidlist (start address in first cgchainer)
// - wipe all contiguous cgchainer structs
//
if (cgdevfirst)
{
free(cgdevfirst->cstat);
free(cgdevfirst->proclist);
free(cgdevfirst);
}
// save current directory and move to top directory
// of cgroup fs
//
if ( getcwd(origdir, sizeof origdir) == NULL)
mcleanstop(53, "failed to save current dir\n");
if ( chdir(CGROUPROOT) == -1)
mcleanstop(54, "failed to change to " CGROUPROOT "\n");
// read all subdirectory names below the cgroup top directory
//
cgcursequence = 0;
cgcursize = 0;
cgcurnum = 0;
cgcurprocs = 0;
walkcgroup(".", NULL, -1, 0, 0, 0);
// return to original directory
//
if ( chdir(origdir) == -1)
mcleanstop(55, "cannot change to %s\n", origdir);
}
// Gather statistics from one cgroup directory level
// and walk the directory tree further downwards by nested calls.
// Every call to this function will add one struct to the current
// cgroup chain.
//
// Return value: number of processes in this dir and the dirs underneath
// -1 = fail
//
static unsigned long
walkcgroup(char *dirname, struct cgchainer *cparent, int parentseq,
long upperhash, int upperlen, int depth)
{
FILE *fp;
DIR *dirp;
struct dirent *entp;
int namelen = strlen(dirname);
int cstatlen, i;
unsigned long procsbelow=0, proccnt=0, hash;
struct cgchainer *ccp;
// change to new directory
//
if ( chdir(dirname) == -1)
return -1;
// --------------------------------------------
// gather statistics for this cgroup directory
// --------------------------------------------
// - create new cgchainer struct
//
ccp = calloc(1, sizeof(struct cgchainer));
ptrverify(ccp, "Malloc failed for current cgchainer\n");
// - add cgchainer to current chain
//
if (cgcurfirst)
{
cgcurlast->next = ccp;
cgcurlast = ccp;
}
else
{
cgcurfirst = ccp;
cgcurlast = ccp;
}
// - create corresponding cstat struct
// with a rounded length to avoid unaligned structs later on
//
cstatlen = sizeof(struct cstat) + namelen + 1;
if (cstatlen & 0x7) // length is not 64-bit multiple?
cstatlen = ((cstatlen >> 3) + 1) << 3; // round up to 64-bit
ccp->cstat = calloc(1, cstatlen);
ptrverify(ccp->cstat, "Malloc failed for cstat of %d bytes\n", cstatlen);
cgcursize += cstatlen;
cgcurnum++;
// - determine number of processes in this cgroup directory
//
if ( (fp = fopen("cgroup.procs", "r")) )
{
char line[64];
while (fgets(line, sizeof line, fp))
proccnt++;
fclose(fp);
}
// - create corresponding pid list to cgchainer
// and fill it with the PIDs
//
if (proccnt)
{
ccp->proclist = malloc(sizeof(pid_t) * proccnt);
ptrverify(ccp->proclist,
"Malloc failed for proclist (%d pids)\n", proccnt);
}
else
{
ccp->proclist = NULL;
}
i = 0;
if ( (fp = fopen("cgroup.procs", "r")) )
{
char line[64];
while (fgets(line, sizeof line, fp))
{
*(ccp->proclist+i) = strtol(line, NULL, 10);
if (++i >= proccnt)
break;
}
fclose(fp);
}
proccnt = i; // number of processes might have shrunk
cgcurprocs += proccnt;
// - fill basic info in current cgchainer
//
strcpy(ccp->cstat->cgname, dirname); // copy directory name
if (*dirname == '.') // top directory?
{
ccp->cstat->cgname[0] = '\0'; // wipe name
namelen = 0;
}
hash = hashcalc(ccp->cstat->cgname, upperhash, upperlen);
ccp->cstat->gen.structlen = cstatlen;
ccp->cstat->gen.sequence = cgcursequence++; // assign unique sequence number
ccp->cstat->gen.parentseq = parentseq;
ccp->cstat->gen.depth = depth;
ccp->cstat->gen.nprocs = proccnt;
ccp->cstat->gen.namelen = namelen;
ccp->cstat->gen.fullnamelen = upperlen + namelen; // excluding slashes
ccp->cstat->gen.namehash = hash;
// - gather and store current cgroup configuration
//
getconfig(ccp->cstat, cparent ? cparent->cstat : NULL);
// - gather and store current cgroup metrics
//
getmetrics(ccp->cstat);
// --------------------------------------------
// walk subdirectories by nested calls
// --------------------------------------------
//
dirp = opendir(".");
while ( (entp = readdir(dirp)) )
{
// skip dot files/directories
//
if (entp->d_name[0] == '.')
continue;
// check if this entry represents a subdirectory
// to be walked as well
//
if (entp->d_type == DT_DIR)
procsbelow += walkcgroup(entp->d_name,
ccp, ccp->cstat->gen.sequence,
hash, upperlen+namelen, depth+1);
}
closedir(dirp);
chdir("..");
ccp->cstat->gen.procsbelow = procsbelow;
return procsbelow + proccnt;
}
// Gather configuration values for one specific cgroup
// value -2: undefined
// value -1: maximum
//
static void
getconfig(struct cstat *csp, struct cstat *csparent)
{
count_t retvals[2];
// get cpu.weight
//
csp->conf.cpuweight = -2; // initial value (undefined)
switch (readconfigval("cpu.weight", retvals))
{
case 1:
csp->conf.cpuweight = retvals[0];
break;
}
// get cpu.max limitation
//
csp->conf.cpumax = -2; // initial value (undefined)
switch (readconfigval("cpu.max", retvals))
{
case 2:
if (retvals[0] == -1)
csp->conf.cpumax = -1; // max
else
csp->conf.cpumax = retvals[0] * 100 / retvals[1];
break;
}
// get io.bpf.weight
//
csp->conf.dskweight = -2; // initial value (undefined)
switch (readconfigval("io.bfq.weight", retvals))
{
case 2:
csp->conf.dskweight = retvals[1];
break;
}
// get memory.max limitation
//
csp->conf.memmax = -2; // initial value (undefined)
switch (readconfigval("memory.max", retvals))
{
case 1:
if (retvals[0] == -1)
csp->conf.memmax = -1; // max
else
csp->conf.memmax = retvals[0] / pagesize;
break;
}
// get memory.swap.max limitation
//
csp->conf.swpmax = -2; // initial value (undefined)
switch (readconfigval("memory.swap.max", retvals))
{
case 1:
if (retvals[0] == -1)
csp->conf.swpmax = -1; // max
else
csp->conf.swpmax = retvals[0] / pagesize;
break;
}
}
// read line with one or two values and
// fill one or (maximum) two values
// in retvals (value 'max' converted into -1)
//
// return value: number of entries in retvals filled
//
static int
readconfigval(char *fname, count_t retvals[])
{
char line[64];
int n;
FILE *fp;
if ( (fp = fopen(fname, "r")) )
{
char firststr[16];
if (!fgets(line, sizeof line, fp))
{
fclose(fp);
return 0;
}
fclose(fp);
switch (n = sscanf(line, "%15s %llu", firststr, &retvals[1]))
{
case 0:
return 0;
case 1:
case 2:
if ( strcmp(firststr, "max") == 0)
retvals[0] = -1;
else
retvals[0] = atol(firststr);
return n;
default:
return 0;
}
}
return 0;
}
// Gather metrics for one specific cgroup
//
static void
getmetrics(struct cstat *csp)
{
FILE *fp;
char line[256];
int cnt;
// gather CPU metrics
//
csp->cpu.utime = -1; // undefined
csp->cpu.stime = -1; // undefined
cnt = 0;
if ( (fp = fopen("cpu.stat", "r")) )
{
while (fgets(line, sizeof line, fp) && cnt < 2)
{
if (memcmp(line, "user_usec ", 10) == 0)
{
sscanf(line, "user_usec %lld", &(csp->cpu.utime));
cnt++;
continue;
}
if (memcmp(line, "system_usec ", 12) == 0)
{
sscanf(line, "system_usec %lld", &(csp->cpu.stime));
cnt++;
continue;
}
}
fclose(fp);
}
getpressure("cpu.pressure", &(csp->cpu.somepres), &(csp->cpu.fullpres));
// gather memory metrics
//
csp->mem.current = -1; // undefined
csp->mem.anon = -1; // undefined
csp->mem.file = -1; // undefined
csp->mem.kernel = -1; // undefined
csp->mem.shmem = -1; // undefined
cnt = 0;
if ( (fp = fopen("memory.current", "r")) )
{
if (fgets(line, sizeof line, fp) != NULL)
csp->mem.current = strtoll(line, NULL, 10) / pagesize;
fclose(fp);
}
if ( (fp = fopen("memory.stat", "r")) )
{
while (fgets(line, sizeof line, fp) && cnt < 4)
{
if (memcmp(line, "anon ", 5) == 0)
{
sscanf(line, "anon %lld", &(csp->mem.anon));
csp->mem.anon /= pagesize;
cnt++;
continue;
}
if (memcmp(line, "file ", 5) == 0)
{
sscanf(line, "file %lld", &(csp->mem.file));
csp->mem.file /= pagesize;
cnt++;
continue;
}
if (memcmp(line, "kernel ", 7) == 0)
{
sscanf(line, "kernel %lld", &(csp->mem.kernel));
csp->mem.kernel /= pagesize;
cnt++;
continue;
}
if (memcmp(line, "shmem ", 6) == 0)
{
sscanf(line, "shmem %lld", &(csp->mem.shmem));
csp->mem.shmem /= pagesize;
cnt++;
continue;
}
}
fclose(fp);
}
getpressure("memory.pressure", &(csp->mem.somepres), &(csp->mem.fullpres));
// gather disk I/O metrics
//
// 253:2 rbytes=2544128 wbytes=2192896 rios=313 wios=22 dbytes=0 dios=0
// 253:1 rbytes=143278080 wbytes=3843604480 rios=34222 wios=853554 ...
// 253:0 rbytes=19492288000 wbytes=105266814976 rios=386493 wios=1691322
// 11:0
// 8:0 rbytes=328956266496 wbytes=109243312640 rios=764129 wios=1415575
//
csp->dsk.rbytes = 0;
csp->dsk.wbytes = 0;
csp->dsk.rios = 0;
csp->dsk.wios = 0;
if ( (fp = fopen("io.stat", "r")) )
{
int major, minor;
count_t rbytes, wbytes, rios, wios;
while (fgets(line, sizeof line, fp))
{
if (sscanf(line,
"%d:%d rbytes=%lld wbytes=%lld rios=%lld wios=%lld",
&major, &minor,
&rbytes, &wbytes, &rios, &wios) == 6)
{
if (isdisk_major(major) == DSKTYPE)
{
csp->dsk.rbytes += rbytes;
csp->dsk.wbytes += wbytes;
csp->dsk.rios += rios;
csp->dsk.wios += wios;
}
}
}
fclose(fp);
}
else
{
csp->dsk.rbytes = -1; // undefined
csp->dsk.wbytes = -1; // undefined
csp->dsk.rios = -1; // undefined
csp->dsk.wios = -1; // undefined
}
getpressure("io.pressure", &(csp->dsk.somepres), &(csp->dsk.fullpres));
}
// Get total pressure values from file with a format similar to:
//
// some avg10=0.00 avg60=0.00 avg300=0.00 total=9660682563
// full avg10=0.00 avg60=0.00 avg300=0.00 total=9376892229
//
static void
getpressure(char *fname, count_t *some, count_t *full)
{
char psiformat[] = "%c%*s avg10=%f avg60=%f avg300=%f total=%llu",
linebuf[256], psitype;
float a10, a60, a300;
FILE *fp;
*some = -1; // initially undefined
*full = -1; // initially undefined
if ( (fp = fopen(fname, "r")) != NULL)
{
// handle first line: 'some' pressure
//
if ( fgets(linebuf, sizeof(linebuf), fp) != NULL)
{
sscanf(linebuf, psiformat,
&psitype, &a10, &a60, &a300, some);
}
// handle second line: 'full' pressure
//
if ( fgets(linebuf, sizeof(linebuf), fp) != NULL)
{
sscanf(linebuf, psiformat,
&psitype, &a10, &a60, &a300, full);
}
fclose(fp);
}
}
// Calculate deviations between current cgroup chain and
// previous cgroup chain.
// Notice that the deviation chain structure is identical to
// the current chain structure, so they can be walked alongside.
// Also the deviation cstat struct is already a copy of the current
// cstat structure.
//
static void
cgcalcdeviate(void)
{
struct cgchainer *dp, *pp;
int insync = 1, prevfound;
// walk thru the deviation chain and calculate the differences
// with the previous chain
//
// when no cgroups have been added or removed since the
// previous sample, we might assume that the previous chain
// has the same order of elements as the deviation chain (insync)
//
// when cgroups have been added or removed since the
// previous sample (!insync), we build a hash list for the
// previous chain to find the correct entry based on the hashed name
//
cgrewind(&cgdevcursor);
cgrewind(&cgprecursor);
while ( (dp = cgnext(&cgdevfirst, &cgdevcursor)) )
{
// find previous cgroup struct
//
prevfound = 0;
if (insync)
{
// assume unchanged cgroup chain: take next from previous chain
//
pp = cgnext(&cgprefirst, &cgprecursor);
if (pp && dp->cstat->gen.namehash == pp->cstat->gen.namehash)
{
prevfound = 1;
}
else
{
insync = 0;
// build hash list for previous chain to find names
// based on hashed name for the rest of this loop
//
cgrewind(&cgprecursor);
while ( (pp = cgnext(&cgprefirst, &cgprecursor)) )
hashadd(cgprehash, pp);
}
}
if (!insync)
{
// modified cgroup chain: search previous by name hash
//
if ( (pp = hashfind(cgprehash, dp->cstat->gen.namehash)) )
prevfound = 1;
}
// calculate deviations related to previous sample
//
if (prevfound)
{
if (dp->cstat->cpu.utime != -1) // defined?
dp->cstat->cpu.utime -= pp->cstat->cpu.utime;
if (dp->cstat->cpu.stime != -1) // defined?
dp->cstat->cpu.stime -= pp->cstat->cpu.stime;
if (dp->cstat->cpu.somepres != -1) // defined?
dp->cstat->cpu.somepres -= pp->cstat->cpu.somepres;
if (dp->cstat->cpu.fullpres != -1) // defined?
dp->cstat->cpu.fullpres -= pp->cstat->cpu.fullpres;
if (dp->cstat->mem.somepres != -1) // defined?
dp->cstat->mem.somepres -= pp->cstat->mem.somepres;
if (dp->cstat->mem.fullpres != -1) // defined?
dp->cstat->mem.fullpres -= pp->cstat->mem.fullpres;
if (dp->cstat->dsk.rbytes != -1) // defined?
{
dp->cstat->dsk.rbytes -= pp->cstat->dsk.rbytes;
dp->cstat->dsk.wbytes -= pp->cstat->dsk.wbytes;
dp->cstat->dsk.rios -= pp->cstat->dsk.rios;
dp->cstat->dsk.wios -= pp->cstat->dsk.wios;
}
if (dp->cstat->dsk.somepres != -1) // defined?
dp->cstat->dsk.somepres -= pp->cstat->dsk.somepres;
if (dp->cstat->dsk.fullpres != -1) // defined?
dp->cstat->dsk.fullpres -= pp->cstat->dsk.fullpres;
}
}
}
// Rewind cglist
//
static void
cgrewind(struct cgchainer **cursor)
{
*cursor = NULL;
}
// Get next cgchainer from current cglist
//
static struct cgchainer *
cgnext(struct cgchainer **first, struct cgchainer **cursor)
{
if (! *cursor)
*cursor = *first;
else
*cursor = (*cursor)->next;
if (*cursor)
return *cursor;
else
return NULL;
}
// Wipe current cgroup chain
//
void
cgwipecur(void)
{
cgwipe(&cgcurfirst, &cgcurlast, &cgcurcursor, NULL);
}
// Wipe all struct's from cgroup admi
//
static void
cgwipe(struct cgchainer **first, struct cgchainer **last,
struct cgchainer **cursor, struct cgchainer **hashlist)
{
struct cgchainer *cp, *cpn;
if (! *first) // empty already?
return;
// free all chain members
//
for (cp=*first; cp; cp=cpn)
{
cpn = cp->next;
free(cp->proclist);
free(cp->cstat);
free(cp);
}
*first = *last = *cursor = NULL;
if (hashlist)
memset(hashlist, 0, sizeof(struct cgchainer *) * CGROUPNHASH);
}
// Create enough memory to copy all cstat structures from
// the current list to one contiguous area.
// Also create enough memory to copy all pid lists from
// the current list to one contiguous area.
// Next, create and fill an array of cgchainer structs.
//
// Returns: number of cgchainer structs
//
int
deviatcgroup(struct cgchainer **cdpp, int *npids)
{
struct cgchainer *ccp = cgcurfirst;
char *allc, *allp, *cp, *pp;
// allocate contiguous memory areas for all cstat structs
// and all pid lists
//
allc = calloc(1, cgcursize);
allp = malloc(sizeof(pid_t) * cgcurprocs);
ptrverify(allc, "Malloc failed for contiguous cstats (%d bytes)\n", cgcursize);
ptrverify(allp, "Malloc failed for contiguous pids (%d pids)\n", cgcurprocs);
// concatenate all current cstat structs and all pid lists
// into the new memory areas
//
ccp = cgcurfirst;
cp = allc;
pp = allp;
while (ccp)
{
int cstatlen = ccp->cstat->gen.structlen;
int plistlen = ccp->cstat->gen.nprocs * sizeof(pid_t);
memcpy(cp, ccp->cstat, cstatlen);
cp += cstatlen;
if (ccp->proclist)
{
memcpy(pp, ccp->proclist, plistlen);
pp += plistlen;
}
ccp = ccp->next;
}
// build array of cgchainer structs and a hash list for the
// concatenated cstat structs for the deviation values
//
cgbuildarray(&cgdevfirst, allc, allp, cgcurnum);
// calculate deviation values
//
cgcalcdeviate();
*cdpp = cgdevfirst;
*npids = cgcurprocs;
return cgcurnum;
}
// Create concatenated array of cgchainer structs referring to
// proper location in the concatenated cstat structs and
// the concatenated pid lists.
//
void
cgbuildarray(struct cgchainer **firstp, char *cstats, char *pids, int ncstats)
{
struct cgchainer *cdp;
int i;
*firstp = malloc(sizeof(struct cgchainer) * ncstats);
ptrverify(firstp, "Malloc failed for contiguous cgchainers (%d)\n", ncstats);
for (cdp=*firstp, i=0; i < ncstats; cdp++, i++)
{
cdp->next = cdp+1;
cdp->hashnext = NULL;
cdp->proclist = (pid_t *)pids;
pids += sizeof(pid_t) * ((struct cstat *)cstats)->gen.nprocs;
cdp->cstat = (struct cstat *)cstats;
cstats += ((struct cstat *)cstats)->gen.structlen;
}
cdp = *firstp + ncstats - 1;
cdp->next = NULL; // terminate chain
}
// Assemble full pathname of cgroup directory (from cgroup top directory)
// from the deviation array.
// For JSON output, double escape characters (backslashes) can be requested
// vi boolean 'escdouble'.
//
// Returns: malloc'ed string with full path name to be freed later on
//
#define MAXESCAPES 16
char *
cggetpath(struct cgchainer *cdp, struct cgchainer *cdbase, int escdouble)
{
// calculate path length including slashes (depth) and terminating 0-byte
//
// in case of double escapes, add a (hopefully) worst-case number of
// bytes to the malloc'ed buffer to double the backslashes
//
// in case of the top directory (without a parent), reserve one extra
// byte for the '/' character
//
int pathlen = cdp->cstat->gen.fullnamelen +
cdp->cstat->gen.depth + 1 +
(cdp->cstat->gen.sequence ? 0 : 1);
char *path = calloc(1, pathlen);
char *ps;
ptrverify(path, "Malloc failed for concatenated cgpath (%d)\n", pathlen);
// not the top directory?
//
if (cdp->cstat->gen.sequence)
{
// any other path: place all path components
// including preceding slashes
//
while (cdp->cstat->gen.parentseq != -1)
{
// determine location of preceding slash
// of this specific path component
//
ps = path + cdp->cstat->gen.fullnamelen -
cdp->cstat->gen.namelen +
cdp->cstat->gen.depth - 1;
// store slash and path component
//
*ps = '/';
memcpy(ps+1, cdp->cstat->cgname, cdp->cstat->gen.namelen);
// climb upwards
//
cdp = cdbase + cdp->cstat->gen.parentseq;
}
*(path+pathlen-1) = '\0'; // terminate string
}
else // exceptional case only for top directory
{
*path = '/';
*(path+1) = '\0'; // terminate string
}
// when double escapes are required and at least one backslash
// is present, reallocate and convert the assembled path
//
// room for a worst-case number of backslashes is allocated
// to avoid counting backslashes before transferring all bytes
//
if (escdouble && strchr(path, '\\'))
{
char *escpath, *pi, *po;
pathlen += MAXESCAPES;
escpath = malloc(pathlen);
ptrverify(escpath, "Malloc failed for escape cgpath (%d)\n", pathlen);
pi = path;
po = escpath;
while (*pi)
{
*po++ = *pi;
if (*pi++ == '\\') // insert additional backslash
*po++ = '\\';
if (po - escpath >= pathlen-1)
break; // truncate to avoid overflow
}
*po = 0;
free(path); // free original string
path = escpath;
}
return path;
}
// ===========================================================
// name hashing to find cgroup with specific path name
// ===========================================================
// Calculate hash for directory name.
// The 'basehash' contains the hashed value of the
// previous path components and the 'offset' is
// the offset of this (sub)string in a larger path.
// Notice that '/' characters will be ignored during
// calculation of the hash value (and ignored in the offset).
//
static long
hashcalc(char *p, long basehash, int offset)
{
offset += 1; // avoid multiplication by 0
while (*p)
{
if (*p == '/')
{
p++;
continue;
}
basehash += *p++ * offset++;
}
return basehash;
}
// Add new hash cgroup directory name to hash
//
static void
hashadd(struct cgchainer *hashlist[], struct cgchainer *cp)
{
long hash = cp->cstat->gen.namehash;
cp->hashnext = hashlist[hash&CGROUPMASK];
hashlist[hash&CGROUPMASK] = cp;
}
// Find directory name in hash based on hashed name value
//
static struct cgchainer *
hashfind(struct cgchainer *hashlist[], long hash)
{
struct cgchainer *cp;
// search hash list
//
for (cp = hashlist[hash&CGROUPMASK]; cp; cp = cp->hashnext)
{
if (hash == cp->cstat->gen.namehash)
return cp;
}
return NULL;
}
// ===========================================================
// PID hashing to find the processes that are related to
// a particular cgroup
// ===========================================================
struct pid2tstat {
struct pid2tstat *hashnext;
struct tstat *tstat;
};
#define PIDNHASH 512 // power of 2
#define PIDMASK (PIDNHASH-1)
static int compselcpu(const void *, const void *);
static int compselmem(const void *, const void *);
static int compseldsk(const void *, const void *);
// Create a mixed list with cgroups and
// processes belonging to those cgroups
//
// Return: number of entries (= screen lines) in the list
//
int
mergecgrouplist(struct cglinesel **cgroupselp, int newdepth,
struct cgchainer **cgchainerp, int ncgroups,
struct tstat **tpp, int nprocs, char showorder)
{
int ic, ip, im, is;
struct cglinesel *cgroupsel;
struct pid2tstat *pidhash[PIDNHASH], *pidlist, *pidcur;
// create a hashlist to find the PIDs in a fast way
//
if (newdepth == 8 || newdepth == 9) // depth requires processes?
{
// initialize hash list
//
memset(pidhash, 0, sizeof pidhash);
// create one pid2tstat struct per tstat struct
//
pidlist = calloc(nprocs, sizeof(struct pid2tstat));
ptrverify(pidlist,
"Malloc for pid2tstat structs failed (%d)\n", nprocs);
pidcur = pidlist;
// build hash list
//
for (ip=0; ip < nprocs; ip++, tpp++, pidcur++)
{
int hash = (*tpp)->gen.pid&PIDMASK;
pidcur->hashnext = pidhash[hash];
pidcur->tstat = (*tpp);
pidhash[hash] = pidcur;
}
}
else
{
nprocs = 0; // ignore processes
}
// allocate space for merged list
//
cgroupsel = malloc(sizeof(struct cglinesel) * (ncgroups+nprocs));
if (cgroupsel == NULL)
ptrverify(cgroupsel, "Malloc for cglinesel structs failed (%d)\n",
ncgroups + nprocs);
*cgroupselp = cgroupsel;
// fill merged list
//
for (ic=im=0; ic < ncgroups; ic++)
{
int cgroupnprocs;
// take next cgroup and add it to the merged list
//
if ( cgroupfilter((*(cgchainerp+ic))->cstat,
newdepth, showorder) )
{
(cgroupsel+im)->cgp = *(cgchainerp+ic);
(cgroupsel+im)->tsp = NULL;
im++;
}
else
{
// suppress this cgroup
// when it is a stub cgroup for this level,
// pass the stub to the previous valid entry
// of this level
//
if ( (*(cgchainerp+ic))->stub)
{
int j;
for (j=im-1; j > 0; j--)
{
int depth = (*(cgchainerp+ic))->cstat->gen.depth;
if (depth > (cgroupsel+j)->cgp->cstat->gen.depth)
{
break;
}
if (depth == (cgroupsel+j)->cgp->cstat->gen.depth)
{
(cgroupsel+j)->cgp->stub = 7;
break;
}
else
{
if (depth < CGRMAXDEPTH)
(cgroupsel+j)->cgp->vlinemask &= ~(1ULL << (depth-1));
}
}
}
continue;
}
// if relevant, search for processes that belong to this cgroup
// and add them to the merged list
//
if (!nprocs) // ignore processes anyhow?
continue;
cgroupnprocs = (*(cgchainerp+ic))->cstat->gen.nprocs;
if (!cgroupnprocs) // no processes in this cgroup?
continue;
for (ip=0, is=im; ip < cgroupnprocs; ip++)
{
int pid = (*(cgchainerp+ic))->proclist[ip];
int hash = pid&PIDMASK;
// search for tstat struct relate to this PID via hashlist
//
for (pidcur=pidhash[hash]; pidcur; pidcur=pidcur->hashnext)
{
// process tstat found??
//
if (pidcur->tstat->gen.pid == pid)
{
// skip kernel processes in case of level 8
//
if (newdepth == 9 ||
pidcur->tstat->mem.vmem > 0 )
{
(cgroupsel+im)->cgp = *(cgchainerp+ic);
(cgroupsel+im)->tsp = pidcur->tstat;
im++;
}
break;
}
}
}
// sort the list of processes added for this cgroup
//
if (im-is > 1)
{
switch (showorder)
{
case MSORTCPU:
qsort(cgroupsel+is, im-is,
sizeof(struct cglinesel), compselcpu);
break;
case MSORTMEM:
qsort(cgroupsel+is, im-is,
sizeof(struct cglinesel), compselmem);
break;
case MSORTDSK:
qsort(cgroupsel+is, im-is,
sizeof(struct cglinesel), compseldsk);
break;
}
}
}
if (nprocs)
free(pidlist);
return im;
}
// Judge if a cgroup should be selected, based on the
// current requested directory level (depth) and
// based on the fact if unused branches are requested
//
// returns 0 (false) or 1 (true)
//
static int
cgroupfilter(struct cstat *csp, int newdepth, char showorder)
{
// skip lower level of cgroups when required
// by entering key 2 till 8 (9=max)
//
if (newdepth < 9 &&
newdepth <= csp->gen.depth)
return 0;
// skip this level and lower levels if
// no processes are assigned at all
//
if (deviatonly &&
showorder != MSORTMEM &&
csp->gen.nprocs == 0 &&
csp->gen.procsbelow == 0 )
return 0;
return 1;
}
// Funtion to be called by qsort() to compare the
// CPU time consumption of two processes in a cgroup.
//
static int
compselcpu(const void *a, const void *b)
{
count_t acpu = ((struct cglinesel *)a)->tsp->cpu.utime +
((struct cglinesel *)a)->tsp->cpu.stime;
count_t bcpu = ((struct cglinesel *)b)->tsp->cpu.utime +
((struct cglinesel *)b)->tsp->cpu.stime;
if (acpu < bcpu)
return 1;
if (acpu > bcpu)
return -1;
return 0;
}
// Funtion to be called by qsort() to compare the
// memory consumption of two processes in a cgroup.
//
static int
compselmem(const void *a, const void *b)
{
count_t amem = ((struct cglinesel *)a)->tsp->mem.rmem;
count_t bmem = ((struct cglinesel *)b)->tsp->mem.rmem;
if (amem < bmem)
return 1;
if (amem > bmem)
return -1;
return 0;
}
// Funtion to be called by qsort() to compare the
// disk activity of two processes in a cgroup.
//
static int
compseldsk(const void *a, const void *b)
{
count_t adisk = ((struct cglinesel *)a)->tsp->dsk.rsz +
((struct cglinesel *)a)->tsp->dsk.wsz;
count_t bdisk = ((struct cglinesel *)b)->tsp->dsk.rsz +
((struct cglinesel *)b)->tsp->dsk.wsz;
if (adisk < bdisk)
return 1;
if (adisk > bdisk)
return -1;
return 0;
}
// Generate a list of pointers to cgchainer struct, sorted on
// specific resource consumption in the cgroup
//
struct cgsorter {
struct cgchainer *cgthis;
struct cgsorter *cgsame;
struct cgsorter *cgchild;
struct cgsorter **sortlist;
count_t sortval;
int nrchild;
};
static struct cgsorter cgroot; // struct for root with depth zero
static struct cgchainer *sortlevel(int, struct cgsorter *, struct cgchainer *, int, char);
static struct cgchainer **mergelevels(struct cgsorter *, int);
static int mergelevel(struct cgsorter *, struct cgchainer **, unsigned long);
static void createsortlist(struct cgsorter *);
static int compsortval(const void *, const void *);
// Main function to create a list of pointers to cgchainer structs,
// in the order of resource consumption while maintaining
// the proper cgroup directory structure.
//
// Return value: list with sorted pointers to cgchainer structs
//
struct cgchainer **
cgsort(struct cgchainer *cgphys, int cgsize, char showorder)
{
struct cgchainer **cgsorted;
// reinitialize the root cgsorter struct and fill
// the pointer to the root cgchainer
//
memset(&cgroot, 0, sizeof cgroot);
cgroot.cgthis = cgphys;
// build a tree structure reflecting the directories of the cgroups
// (skip the first entry representing the root cgroup)
//
sortlevel(1, &cgroot, &cgphys[1], cgsize-1, showorder);
// merge all sorted cgchainer struct pointers into one
// contiguous list
//
cgsorted = mergelevels(&cgroot, cgsize);
return cgsorted;
}
// Create a tree structure of cgsorter structs (by nested calls).
// A cgsorter struct will be created per cgchainer struct,
// with the following members:
//
// cgthis pointer to corresponding cgchainer struct
// cgsame pointer to next cgsorter struct on same directory level
// cgchild pointer to first cgsorter struct on lower directory level
// sortlist pointer to list of pointers to child cgsorter structs
// (same pointers as chained via cgchild) to be sorted
// sortval sort value (e.g. consumed CPU time or used memory)
// nrchild number of direct child members
//
static struct cgchainer *
sortlevel(int curlevel, struct cgsorter *cgparent,
struct cgchainer *cgp, int cgsize, char showorder)
{
int newlevel, cgleft = cgsize;
struct cgchainer *cgc = cgp;
struct cgsorter *cgs = NULL;
// as long as cgchainer structs are left...
//
while (cgleft > 0)
{
newlevel = cgc->cstat->gen.depth;
// higher level in directory tree?
// - create and sort the cgchainer pointers in order of resource utilization
// - return to caller to continue with higher level
//
if (newlevel < curlevel)
{
createsortlist(cgparent);
return cgc; // leave this level
}
// same directory level: chain to same-level list
// which is the child list of the higher level that called us
//
if (newlevel == curlevel)
{
// malloc and fill new cgsorter struct
//
cgs = malloc(sizeof(struct cgsorter));
ptrverify(cgs, "Malloc failed for cgsorter struct\n");
cgs->cgthis = cgc;
cgs->cgsame = cgparent->cgchild;
cgs->cgchild = 0;
cgs->nrchild = 0;
switch (showorder)
{
case MSORTCPU:
cgs->sortval = cgc->cstat->cpu.utime +
cgc->cstat->cpu.stime;
break;
case MSORTMEM:
if (cgc->cstat->mem.current > 0)
{
cgs->sortval = cgc->cstat->mem.current;
}
else
{
cgs->sortval = cgc->cstat->mem.anon +
cgc->cstat->mem.file +
cgc->cstat->mem.kernel +
cgc->cstat->mem.shmem;
}
break;
case MSORTDSK:
cgs->sortval = cgc->cstat->dsk.rbytes +
cgc->cstat->dsk.wbytes;
break;
default:
cgs->sortval = 0; // no sorting
}
// chain cgsorter struct to this level
//
cgparent->cgchild = cgs;
cgparent->nrchild++;
cgc++;
cgleft--;
continue;
}
// newlevel > curlevel?
// recursively call sortlevel() for each new
// directory level underneath
//
cgc = sortlevel(newlevel, cgs, cgc, cgleft, showorder);
cgleft = cgsize - (cgc - cgp);
}
createsortlist(cgparent);
return cgc;
}
// Create a list of pointers to the cgchainer structs
// on the current level and sort it on resource consumption
//
static void
createsortlist(struct cgsorter *cgparent)
{
int i;
struct cgsorter *cgs;
if (cgparent->nrchild == 1) // no sorting needed with one child
{
cgparent->sortlist = NULL;
}
else // sorting needed by creating sortlist
{
cgparent->sortlist = calloc(cgparent->nrchild,
sizeof(struct cgsorter *));
ptrverify(cgparent->sortlist, "Malloc failed for cgsorter list\n");
// fill elements of sortlist with pointers to child cgsorters
//
for (i=0, cgs=cgparent->cgchild; i < cgparent->nrchild;
i++, cgs = cgs->cgsame)
{
*((cgparent->sortlist)+i) = cgs;
}
// sort list on sort value
//
qsort(cgparent->sortlist, cgparent->nrchild,
sizeof(struct cgsorter *), compsortval);
}
}
// Function to be called by qsort() to compare
// the sortvalue in two cgsorter structs
//
static int
compsortval(const void *a, const void *b)
{
struct cgsorter *cga = *(struct cgsorter **)a;
struct cgsorter *cgb = *(struct cgsorter **)b;
if (cga->sortval < cgb->sortval)
return 1;
if (cga->sortval > cgb->sortval)
return -1;
return 0;
}
// Gather all sorted cgsorter structs from the entire tree
// and create one array of cgchainer pointers in sorted order.
//
static struct cgchainer **
mergelevels(struct cgsorter *cgrootp, int cgsize)
{
struct cgchainer **cgpp;
unsigned long vlinemask = 0;
// allocate the list of pointers to be returned
//
cgpp = malloc(sizeof(struct cgchainer *) * cgsize);
ptrverify(cgpp, "Malloc failed for cgchainer ptr list (%d)\n", cgsize);
// fill the first entry with the root cgchainer struct pointer
//
*cgpp = cgrootp->cgthis;
(*cgpp)->stub = 1; // no more entries on this level
(*cgpp)->vlinemask = vlinemask;
mergelevel(cgrootp, cgpp+1, vlinemask);
return cgpp;
}
// Gather all cgsorter structs from one directory level.
// To be called in a nested way for each level underneath.
//
static int
mergelevel(struct cgsorter *cgparent, struct cgchainer **cgpp,
unsigned long vlinemask)
{
struct cgsorter *cgs, *cgsave;
int i, j, depth = cgparent->cgthis->cstat->gen.depth;
switch (cgparent->nrchild)
{
case 0: // should never occur....
j = 0;
break;
case 1: // in case of one child no sortlist has been created
*cgpp = cgparent->cgchild->cgthis;
(*cgpp)->stub = 1; // no more entries on this level
if (depth < CGRMAXDEPTH)
vlinemask &= ~(1ULL << depth);
(*cgpp)->vlinemask = vlinemask;
j = 1;
if (cgparent->cgchild->nrchild) // merge descendants on lower level?
j += mergelevel(cgparent->cgchild, cgpp+1, vlinemask);
free(cgparent->cgchild);
break;
default:
for (i=0, j=0; i < cgparent->nrchild; i++, j++)
{
cgs = *((cgparent->sortlist)+i);
*(cgpp+j) = cgs->cgthis;
if (i == cgparent->nrchild -1) // last on this level?
{
(*(cgpp+j))->stub = 1; // no more entries on this level
if (depth < CGRMAXDEPTH)
vlinemask &= ~(1ULL << depth);
(*(cgpp+j))->vlinemask = vlinemask;
}
else
{
(*(cgpp+j))->stub = 0; // more entries on this level
if (depth < CGRMAXDEPTH)
vlinemask |= 1ULL << depth;
(*(cgpp+j))->vlinemask = vlinemask;
}
if (cgs->nrchild) // merge descendants on lower level?
j += mergelevel(cgs, cgpp+j+1, vlinemask);
}
// for all cgroups of this level merged: free malloced areas
//
free(cgparent->sortlist);
for (cgs=cgparent->cgchild; cgs; cgs=cgsave)
{
cgsave = cgs->cgsame;
free(cgs);
}
}
return j;
}
// ===========================================================
// PID hashing to find the cgroup that is related to
// a particular process
// ===========================================================
struct pid2cgchainer {
struct pid2cgchainer *hashnext;
pid_t pid;
int cgindex; // cgchainer index
};
// For every tstat struct, fill the reference (index) to
// the related cgroup, represented by the cgchainer struct
//
void
cgfillref(struct devtstat *devtstat, struct cgchainer *devchain,
int ncgroups, int npids)
{
int ic, ip, it, hash;
pid_t pid;
struct pid2cgchainer *pidhash[PIDNHASH], *pidlist, *pidcur;
struct cgchainer *cp;
struct tstat *tp = devtstat->taskall;
// create a hashlist to find the PIDs in a fast way
// initialize hash list
//
memset(pidhash, 0, sizeof pidhash);
// create one pid2cgchainer struct per cgroup pid
//
pidlist = calloc(npids, sizeof(struct pid2cgchainer));
ptrverify(pidlist, "Malloc for pid2cgchainer structs failed (%d)\n", npids);
// build hash list to find right cgchainer (cgroup) for a PID
//
for (ic=0, cp=devchain, pidcur=pidlist; ic < ncgroups; ic++, cp++)
{
for (ip=0; ip < cp->cstat->gen.nprocs; ip++, pidcur++)
{
pid = cp->proclist[ip];
hash = pid & PIDMASK;
pidcur->hashnext = pidhash[hash];
pidcur->pid = pid;
pidcur->cgindex = ic;
pidhash[hash] = pidcur;
}
}
// connect every tstat struct to the concerning cgchainer
// by filling the index
//
for (it=0; it < devtstat->ntaskall; it++, tp++)
{
tp->gen.cgroupix = -1;
if (! tp->gen.isproc) // skip threads
continue;
pid = tp->gen.pid;
hash = pid & PIDMASK;
// search for cgchainer index related to this PID via hashlist
//
for (pidcur=pidhash[hash]; pidcur; pidcur=pidcur->hashnext)
{
if (pidcur->pid == pid)
{
tp->gen.cgroupix = pidcur->cgindex;
break;
}
}
}
free(pidlist);
}
|