Home | History | Annotate | Download | only in lmkd
      1 /*
      2  *  Copyright 2018 Google, Inc
      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 <errno.h>
     18 #include <fcntl.h>
     19 #include <sys/cdefs.h>
     20 #include <sys/stat.h>
     21 #include <sys/types.h>
     22 #include <stdio.h>
     23 #include <unistd.h>
     24 
     25 #include <liblmkd_utils.h>
     26 #include <cutils/sockets.h>
     27 
     28 int lmkd_connect() {
     29     return socket_local_client("lmkd",
     30                                ANDROID_SOCKET_NAMESPACE_RESERVED,
     31                                SOCK_SEQPACKET);
     32 }
     33 
     34 int lmkd_register_proc(int sock, struct lmk_procprio *params) {
     35     LMKD_CTRL_PACKET packet;
     36     size_t size;
     37     int ret;
     38 
     39     size = lmkd_pack_set_procprio(packet, params);
     40     ret = TEMP_FAILURE_RETRY(write(sock, packet, size));
     41 
     42     return (ret < 0) ? -1 : 0;
     43 }
     44 
     45 int create_memcg(uid_t uid, pid_t pid) {
     46     char buf[256];
     47     int tasks_file;
     48     int written;
     49 
     50     snprintf(buf, sizeof(buf), "/dev/memcg/apps/uid_%u", uid);
     51     if (mkdir(buf, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0 &&
     52         errno != EEXIST) {
     53         return -1;
     54     }
     55 
     56     snprintf(buf, sizeof(buf), "/dev/memcg/apps/uid_%u/pid_%u", uid, pid);
     57     if (mkdir(buf, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) < 0 &&
     58         errno != EEXIST) {
     59         return -1;
     60     }
     61 
     62     snprintf(buf, sizeof(buf), "/dev/memcg/apps/uid_%u/pid_%u/tasks", uid, pid);
     63     tasks_file = open(buf, O_WRONLY);
     64     if (tasks_file < 0) {
     65         return -2;
     66     }
     67     written = snprintf(buf, sizeof(buf), "%u", pid);
     68     if (__predict_false(written >= (int)sizeof(buf))) {
     69         written = sizeof(buf) - 1;
     70     }
     71     written = TEMP_FAILURE_RETRY(write(tasks_file, buf, written));
     72     close(tasks_file);
     73 
     74     return (written < 0) ? -3 : 0;
     75 }
     76 
     77