1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <inttypes.h>
18#include <stdint.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <sys/types.h>
22#include <unistd.h>
23#include <fcntl.h>
24
25// This is an extremely simplified version of libpagemap.
26
27#define _BITS(x, offset, bits) (((x) >> (offset)) & ((1LL << (bits)) - 1))
28
29#define PAGEMAP_PRESENT(x)     (_BITS(x, 63, 1))
30#define PAGEMAP_SWAPPED(x)     (_BITS(x, 62, 1))
31#define PAGEMAP_SHIFT(x)       (_BITS(x, 55, 6))
32#define PAGEMAP_PFN(x)         (_BITS(x, 0, 55))
33#define PAGEMAP_SWAP_OFFSET(x) (_BITS(x, 5, 50))
34#define PAGEMAP_SWAP_TYPE(x)   (_BITS(x, 0,  5))
35
36static bool ReadData(int fd, off_t place, uint64_t *data) {
37  if (lseek(fd, place * sizeof(uint64_t), SEEK_SET) < 0) {
38    return false;
39  }
40  if (read(fd, (void*)data, sizeof(uint64_t)) != (ssize_t)sizeof(uint64_t)) {
41    return false;
42  }
43  return true;
44}
45
46size_t GetPssBytes() {
47  FILE* maps = fopen("/proc/self/maps", "r");
48  if (maps == nullptr) {
49    return 0;
50  }
51
52  int pagecount_fd = open("/proc/kpagecount", O_RDONLY);
53  if (pagecount_fd == -1) {
54    fclose(maps);
55    return 0;
56  }
57
58  int pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
59  if (pagemap_fd == -1) {
60    fclose(maps);
61    close(pagecount_fd);
62    return 0;
63  }
64
65  char line[4096];
66  size_t total_pss = 0;
67  int pagesize = getpagesize();
68  while (fgets(line, sizeof(line), maps)) {
69    uintptr_t start, end;
70    if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " ", &start, &end) != 2) {
71      total_pss = 0;
72      break;
73    }
74    for (off_t page = static_cast<off_t>(start/pagesize);
75         page < static_cast<off_t>(end/pagesize); page++) {
76      uint64_t data;
77      if (ReadData(pagemap_fd, page, &data)) {
78        if (PAGEMAP_PRESENT(data) && !PAGEMAP_SWAPPED(data)) {
79          uint64_t count;
80          if (ReadData(pagecount_fd, static_cast<off_t>(PAGEMAP_PFN(data)), &count)) {
81            total_pss += (count >= 1) ? pagesize / count : 0;
82          }
83        }
84      }
85    }
86  }
87
88  fclose(maps);
89
90  close(pagecount_fd);
91  close(pagemap_fd);
92
93  return total_pss;
94}
95