1 /*
2 * Copyright (C) 2018 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 #define LOG_TAG "libpsi"
18
19 #include <errno.h>
20 #include <fcntl.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <sys/epoll.h>
24 #include <unistd.h>
25
26 #include <log/log.h>
27 #include <cutils/fs.h>
28 #include <stdio.h>
29 #include "psi/psi.h"
30
31 #define PSI_MON_FILE_MEMORY "/proc/pressure/memory"
32
33 static const char* stall_type_name[] = {
34 "some",
35 "full",
36 };
37
init_psi_monitor(enum psi_stall_type stall_type,int threshold_us,int window_us)38 int init_psi_monitor(enum psi_stall_type stall_type,
39 int threshold_us, int window_us) {
40 int fd;
41 int res;
42 char buf[256];
43
44 fd = TEMP_FAILURE_RETRY(open(PSI_MON_FILE_MEMORY, O_WRONLY | O_CLOEXEC));
45 if (fd < 0) {
46 ALOGE("No kernel psi monitor support (errno=%d)", errno);
47 return -1;
48 }
49
50 switch (stall_type) {
51 case (PSI_SOME):
52 case (PSI_FULL):
53 res = snprintf(buf, sizeof(buf), "%s %d %d",
54 stall_type_name[stall_type], threshold_us, window_us);
55 break;
56 default:
57 ALOGE("Invalid psi stall type: %d", stall_type);
58 errno = EINVAL;
59 goto err;
60 }
61
62 if (res >= (ssize_t)sizeof(buf)) {
63 ALOGE("%s line overflow for psi stall type '%s'",
64 PSI_MON_FILE_MEMORY, stall_type_name[stall_type]);
65 errno = EINVAL;
66 goto err;
67 }
68
69 res = TEMP_FAILURE_RETRY(write(fd, buf, strlen(buf) + 1));
70 if (res < 0) {
71 ALOGE("%s write failed for psi stall type '%s'; errno=%d",
72 PSI_MON_FILE_MEMORY, stall_type_name[stall_type], errno);
73 goto err;
74 }
75
76 return fd;
77
78 err:
79 close(fd);
80 return -1;
81 }
82
register_psi_monitor(int epollfd,int fd,void * data)83 int register_psi_monitor(int epollfd, int fd, void* data) {
84 int res;
85 struct epoll_event epev;
86
87 epev.events = EPOLLPRI;
88 epev.data.ptr = data;
89 res = epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &epev);
90 if (res < 0) {
91 ALOGE("epoll_ctl for psi monitor failed; errno=%d", errno);
92 }
93 return res;
94 }
95
unregister_psi_monitor(int epollfd,int fd)96 int unregister_psi_monitor(int epollfd, int fd) {
97 return epoll_ctl(epollfd, EPOLL_CTL_DEL, fd, NULL);
98 }
99
destroy_psi_monitor(int fd)100 void destroy_psi_monitor(int fd) {
101 if (fd >= 0) {
102 close(fd);
103 }
104 }
105