git: d9aa256201b8 - stable/14 - sysctl: add KERN_PROC_RLIMIT_USAGE

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Sat, 05 Oct 2024 07:11:27 UTC
The branch stable/14 has been updated by kib:

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

commit d9aa256201b8d149907d490029d5a3ea123a3d89
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2024-09-22 17:01:56 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2024-10-05 07:08:56 +0000

    sysctl: add KERN_PROC_RLIMIT_USAGE
    
    (cherry picked from commit c85d3064c454bde9f1c0cfbb6f42c0ac9fa229e9)
---
 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 b4548b38f633..9729bf987aa6 100644
--- a/sys/kern/kern_resource.c
+++ b/sys/kern/kern_resource.c
@@ -1744,3 +1744,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 0cfa2a7bd245..a446d6701cfa 100644
--- a/sys/sys/sysctl.h
+++ b/sys/sys/sysctl.h
@@ -1042,6 +1042,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