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 <assert.h>
18#include <inttypes.h>
19#include <stdio.h>
20#include <stdlib.h>
21#include <stdint.h>
22#include <sys/types.h>
23#include <unistd.h>
24#include <fcntl.h>
25
26// This is an extremely simplified version of libpagemap.
27
28#define _BITS(x, offset, bits) (((x) >> offset) & ((1LL << (bits)) - 1))
29
30#define PAGEMAP_PRESENT(x)     (_BITS(x, 63, 1))
31#define PAGEMAP_SWAPPED(x)     (_BITS(x, 62, 1))
32#define PAGEMAP_SHIFT(x)       (_BITS(x, 55, 6))
33#define PAGEMAP_PFN(x)         (_BITS(x, 0, 55))
34#define PAGEMAP_SWAP_OFFSET(x) (_BITS(x, 5, 50))
35#define PAGEMAP_SWAP_TYPE(x)   (_BITS(x, 0,  5))
36
37static bool ReadData(int fd, unsigned long place, uint64_t *data) {
38  if (lseek(fd, place * sizeof(uint64_t), SEEK_SET) < 0) {
39    return false;
40  }
41  if (read(fd, (void*)data, sizeof(uint64_t)) != (ssize_t)sizeof(uint64_t)) {
42    return false;
43  }
44  return true;
45}
46
47size_t GetPssBytes() {
48  FILE* maps = fopen("/proc/self/maps", "r");
49  assert(maps != NULL);
50
51  int pagecount_fd = open("/proc/kpagecount", O_RDONLY);
52  assert(pagecount_fd >= 0);
53
54  int pagemap_fd = open("/proc/self/pagemap", O_RDONLY);
55  assert(pagemap_fd >= 0);
56
57  char line[4096];
58  size_t total_pss = 0;
59  int pagesize = getpagesize();
60  while (fgets(line, sizeof(line), maps)) {
61    uintptr_t start, end;
62    if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " ", &start, &end) != 2) {
63      total_pss = 0;
64      break;
65    }
66    for (size_t page = start/pagesize; page < end/pagesize; page++) {
67      uint64_t data;
68      if (ReadData(pagemap_fd, page, &data)) {
69        if (PAGEMAP_PRESENT(data) && !PAGEMAP_SWAPPED(data)) {
70          uint64_t count;
71          if (ReadData(pagecount_fd, PAGEMAP_PFN(data), &count)) {
72            total_pss += (count >= 1) ? pagesize / count : 0;
73          }
74        }
75      }
76    }
77  }
78
79  fclose(maps);
80
81  close(pagecount_fd);
82  close(pagemap_fd);
83
84  return total_pss;
85}
86