git: c85d3064c454 - main - sysctl: add KERN_PROC_RLIMIT_USAGE

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Fri, 27 Sep 2024 15:03:30 UTC
The branch main has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=c85d3064c454bde9f1c0cfbb6f42c0ac9fa229e9

commit c85d3064c454bde9f1c0cfbb6f42c0ac9fa229e9
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2024-09-22 17:01:56 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2024-09-27 15:02:23 +0000

    sysctl: add KERN_PROC_RLIMIT_USAGE
    
    Reviewed by:    markj, olce
    Sponsored by:   The FreeBSD Foundation
    MFC after:      1 week
    Differential revision:  https://reviews.freebsd.org/D46747
---
 sys/kern/kern_resource.c | 50 ++++++++++++++++++++++++++++++++++++++++++++++++
 sys/sys/sysctl.h         |  1 +
 2 files changed, 51 insertions(+)

diff --git a/sys/kern/kern_resource.c b/sys/kern/kern_resource.c
index db5cce833012..c8b01afeab4f 100644
--- a/sys/kern/kern_resource.c
+++ b/sys/kern/kern_resource.c
@@ -1741,3 +1741,53 @@ chgpipecnt(struct uidinfo *uip, int diff, rlim_t max)
 
 	return (chglimit(uip, &uip->ui_pipecnt, diff, max, "pipecnt"));
 }
+
+static int
+sysctl_kern_proc_rlimit_usage(SYSCTL_HANDLER_ARGS)
+{
+	rlim_t resval[RLIM_NLIMITS];
+	struct proc *p;
+	size_t len;
+	int error, *name, i;
+
+	name = (int *)arg1;
+	if ((u_int)arg2 != 1 && (u_int)arg2 != 2)
+		return (EINVAL);
+	if (req->newptr != NULL)
+		return (EINVAL);
+
+	error = pget((pid_t)name[0], PGET_WANTREAD, &p);
+	if (error != 0)
+		return (error);
+
+	if ((u_int)arg2 == 1) {
+		len = sizeof(resval);
+		memset(resval, 0, sizeof(resval));
+		for (i = 0; i < RLIM_NLIMITS; i++) {
+			error = getrlimitusage_one(p, (unsigned)i, 0,
+			    &resval[i]);
+			if (error == ENXIO) {
+				resval[i] = -1;
+				error = 0;
+			} else if (error != 0) {
+				break;
+			}
+		}
+	} else {
+		len = sizeof(resval[0]);
+		error = getrlimitusage_one(p, (unsigned)name[1], 0,
+		    &resval[0]);
+		if (error == ENXIO) {
+			resval[0] = -1;
+			error = 0;
+		}
+	}
+	if (error == 0)
+		error = SYSCTL_OUT(req, resval, len);
+	PRELE(p);
+	return (error);
+}
+static SYSCTL_NODE(_kern_proc, KERN_PROC_RLIMIT_USAGE, rlimit_usage,
+    CTLFLAG_RD | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE,
+    sysctl_kern_proc_rlimit_usage,
+    "Process limited resources usage info");
diff --git a/sys/sys/sysctl.h b/sys/sys/sysctl.h
index 66c6ff1640b7..f7abc27083aa 100644
--- a/sys/sys/sysctl.h
+++ b/sys/sys/sysctl.h
@@ -1040,6 +1040,7 @@ TAILQ_HEAD(sysctl_ctx_list, sysctl_ctx_entry);
 #define	KERN_PROC_NFDS		43	/* number of open file descriptors */
 #define	KERN_PROC_SIGFASTBLK	44	/* address of fastsigblk magic word */
 #define	KERN_PROC_VM_LAYOUT	45	/* virtual address space layout info */
+#define	KERN_PROC_RLIMIT_USAGE	46	/* array of rlim_t */
 
 /*
  * KERN_IPC identifiers