/*
 * Copyright (C) 2018 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef __ANDROID_PSI_H__
#define __ANDROID_PSI_H__

#include <sys/cdefs.h>
#include <sys/types.h>

__BEGIN_DECLS

enum psi_resource { PSI_MEMORY, PSI_IO, PSI_CPU, PSI_RESOURCE_COUNT };

enum psi_stall_type {
    PSI_SOME,
    PSI_FULL,
    PSI_TYPE_COUNT
};

struct psi_stats {
    float avg10;
    float avg60;
    float avg300;
    unsigned long total;
};

struct psi_data {
    struct psi_stats mem_stats[PSI_TYPE_COUNT];
    struct psi_stats io_stats[PSI_TYPE_COUNT];
    struct psi_stats cpu_stats[PSI_TYPE_COUNT];
};

static const char* psi_resource_file[PSI_RESOURCE_COUNT] = {
        "/proc/pressure/memory",
        "/proc/pressure/io",
        "/proc/pressure/cpu",
};

/*
 * Initializes psi monitor for the given psi resource type.
 * stall_type, threshold_us and window_us are monitor parameters
 * When successful, the function returns file descriptor that can
 * be used with poll/epoll syscalls to wait for EPOLLPRI events.
 * When unsuccessful, the function returns -1 and errno is set
 * appropriately.
 */
int init_psi_monitor(enum psi_stall_type stall_type, int threshold_us, int window_us,
                     enum psi_resource resource = PSI_MEMORY);

/*
 * Registers psi monitor file descriptor fd on the epoll instance
 * referred to by the file descriptor epollfd.
 * data parameter will be associated with event's epoll_data.ptr
 * member.
 */
int register_psi_monitor(int epollfd, int fd, void* data);

/*
 * Unregisters psi monitor file descriptor fd from the epoll instance
 * referred to by the file descriptor epollfd.
 */
int unregister_psi_monitor(int epollfd, int fd);

/*
 * Destroys psi monitor.
 * fd is the file descriptor returned by psi monitor initialization
 * routine.
 * Note that if user process exits without calling this routine
 * kernel will destroy the monitor as its lifetime is linked to
 * the file descriptor.
 */
void destroy_psi_monitor(int fd);

/*
 * Parse psi file line content. Expected file format is:
 *    some avg10=0.00 avg60=0.00 avg300=0.00 total=0
 *    full avg10=0.00 avg60=0.00 avg300=0.00 total=0
 */
int parse_psi_line(char *line, enum psi_stall_type stall_type, struct psi_stats stats[]);

__END_DECLS

#endif  // __ANDROID_PSI_H__
