Skip to contentSkip to conversation

Present useful limits to user

RFC In review Topi Miettinen 15 participants 61 messages Jun 13, 2016 – Jul 19, 2016

Subsystems (27)
lore
Share & tools
lore
#6 lore raw

RFC 2/18 cgroup_pids: track maximum pids

In reply to Topi Miettinen

Track maximum pids in the cgroup, present it in cgroup pids.current_max.

---
 kernel/cgroup_pids.c | 32 ++++++++++++++++++++++++++++++++
 1 file changed, 32 insertions(+)
kernel/cgroup_pids.c +32 -0
index 303097b..53fb21d 100644
@@ -48,6 +48,7 @@ struct pids_cgroup {
 	 * %PIDS_MAX = (%PID_MAX_LIMIT + 1).
 	 */
 	atomic64_t			counter;
+	atomic64_t			cur_max;
 	int64_t				limit;
 };
 
@@ -72,6 +73,7 @@ pids_css_alloc(struct cgroup_subsys_state *parent)
 
 	pids->limit = PIDS_MAX;
 	atomic64_set(&pids->counter, 0);
+	atomic64_set(&pids->cur_max, 0);
 	return &pids->css;
 }
 
@@ -182,6 +184,10 @@ static int pids_can_attach(struct cgroup_taskset *tset)
 
 		pids_charge(pids, 1);
 		pids_uncharge(old_pids, 1);
+		if (atomic64_read(&pids->cur_max) <
+		    atomic64_read(&pids->counter))
+			atomic64_set(&pids->cur_max,
+				     atomic64_read(&pids->counter));
 	}
 
 	return 0;
@@ -202,6 +208,10 @@ static void pids_cancel_attach(struct cgroup_taskset *tset)
 
 		pids_charge(old_pids, 1);
 		pids_uncharge(pids, 1);
+		if (atomic64_read(&old_pids->cur_max) <
+		    atomic64_read(&old_pids->counter))
+			atomic64_set(&old_pids->cur_max,
+				     atomic64_read(&old_pids->counter));
 	}
 }
 
@@ -236,6 +246,14 @@ static void pids_free(struct task_struct *task)
 	pids_uncharge(pids, 1);
 }
 
+static void pids_fork(struct task_struct *task)
+{
+	struct pids_cgroup *pids = css_pids(task_css(task, pids_cgrp_id));
+
+	if (atomic64_read(&pids->cur_max) < atomic64_read(&pids->counter))
+		atomic64_set(&pids->cur_max, atomic64_read(&pids->counter));
+}
+
 static ssize_t pids_max_write(struct kernfs_open_file *of, char *buf,
 			      size_t nbytes, loff_t off)
 {
@@ -288,6 +306,14 @@ static s64 pids_current_read(struct cgroup_subsys_state *css,
 	return atomic64_read(&pids->counter);
 }
 
+static s64 pids_current_max_read(struct cgroup_subsys_state *css,
+				 struct cftype *cft)
+{
+	struct pids_cgroup *pids = css_pids(css);
+
+	return atomic64_read(&pids->cur_max);
+}
+
 static struct cftype pids_files[] = {
 	{
 		.name = "max",
@@ -300,6 +326,11 @@ static struct cftype pids_files[] = {
 		.read_s64 = pids_current_read,
 		.flags = CFTYPE_NOT_ON_ROOT,
 	},
+	{
+		.name = "current_max",
+		.read_s64 = pids_current_max_read,
+		.flags = CFTYPE_NOT_ON_ROOT,
+	},
 	{ }	/* terminate */
 };
 
@@ -313,4 +344,5 @@ struct cgroup_subsys pids_cgrp_subsys = {
 	.free		= pids_free,
 	.legacy_cftypes	= pids_files,
 	.dfl_cftypes	= pids_files,
+	.fork		= pids_fork,
 };
Signature · 1 line
2.8.1
#16 lore raw

RFC 3/18 memcontrol: present maximum used memory also for cgroup-v2

In reply to Topi Miettinen

Present maximum used memory in cgroup memory.current_max.

---
 include/linux/page_counter.h |  7 ++++++-
 mm/memcontrol.c              | 13 +++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)
include/linux/page_counter.h +6 -1
index 7e62920..be4de17 100644
@@ -9,9 +9,9 @@ struct page_counter {
 	atomic_long_t count;
 	unsigned long limit;
 	struct page_counter *parent;
+	unsigned long watermark;
 
 	/* legacy */
-	unsigned long watermark;
 	unsigned long failcnt;
 };
 
@@ -34,6 +34,11 @@ static inline unsigned long page_counter_read(struct page_counter *counter)
 	return atomic_long_read(&counter->count);
 }
 
+static inline unsigned long page_counter_read_watermark(struct page_counter *counter)
+{
+	return counter->watermark;
+}
+
 void page_counter_cancel(struct page_counter *counter, unsigned long nr_pages);
 void page_counter_charge(struct page_counter *counter, unsigned long nr_pages);
 bool page_counter_try_charge(struct page_counter *counter,
mm/memcontrol.c +13 -0
index 75e7440..5513771 100644
@@ -4966,6 +4966,14 @@ static u64 memory_current_read(struct cgroup_subsys_state *css,
 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
 }
 
+static u64 memory_current_max_read(struct cgroup_subsys_state *css,
+				   struct cftype *cft)
+{
+	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
+
+	return (u64)page_counter_read_watermark(&memcg->memory) * PAGE_SIZE;
+}
+
 static int memory_low_show(struct seq_file *m, void *v)
 {
 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
@@ -5179,6 +5187,11 @@ static struct cftype memory_files[] = {
 		.read_u64 = memory_current_read,
 	},
 	{
+		.name = "current_max",
+		.flags = CFTYPE_NOT_ON_ROOT,
+		.read_u64 = memory_current_max_read,
+	},
+	{
 		.name = "low",
 		.flags = CFTYPE_NOT_ON_ROOT,
 		.seq_show = memory_low_show,
Signature · 7 lines
2.8.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#24 lore raw

RFC 5/18 limits: track and present RLIMIT_NOFILE actual max

In reply to Topi Miettinen

Track maximum number of files for the process, present current maximum in /proc/self/limits.

---
 fs/file.c             |  4 ++++
 fs/proc/base.c        | 10 ++++++----
 include/linux/sched.h |  7 +++++++
 3 files changed, 17 insertions(+), 4 deletions(-)
fs/file.c +4 -0
index 6b1acdf..2d0d206 100644
@@ -547,6 +547,8 @@ repeat:
 	}
 #endif
 
+	bump_rlimit(RLIMIT_NOFILE, fd);
+
 out:
 	spin_unlock(&files->file_lock);
 	return error;
@@ -857,6 +859,8 @@ __releases(&files->file_lock)
 	if (tofree)
 		filp_close(tofree, files);
 
+	bump_rlimit(RLIMIT_NOFILE, fd);
+
 	return fd;
 
 Ebusy:
fs/proc/base.c +6 -4
index a11eb71..227997b 100644
@@ -630,8 +630,8 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 	/*
 	 * print the file header
 	 */
-       seq_printf(m, "%-25s %-20s %-20s %-10s\n",
-		  "Limit", "Soft Limit", "Hard Limit", "Units");
+	seq_printf(m, "%-25s %-20s %-20s %-10s %-20s\n",
+		   "Limit", "Soft Limit", "Hard Limit", "Units", "Max");
 
 	for (i = 0; i < RLIM_NLIMITS; i++) {
 		if (rlim[i].rlim_cur == RLIM_INFINITY)
@@ -647,9 +647,11 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 			seq_printf(m, "%-20lu ", rlim[i].rlim_max);
 
 		if (lnames[i].unit)
-			seq_printf(m, "%-10s\n", lnames[i].unit);
+			seq_printf(m, "%-10s", lnames[i].unit);
 		else
-			seq_putc(m, '\n');
+			seq_printf(m, "%-10s", "");
+		seq_printf(m, "%-20lu\n",
+			   task->signal->rlim_curmax[i]);
 	}
 
 	return 0;
include/linux/sched.h +7 -0
index 9c48a08..0150380 100644
@@ -782,6 +782,7 @@ struct signal_struct {
 	 * have no need to disable irqs.
 	 */
 	struct rlimit rlim[RLIM_NLIMITS];
+	unsigned long rlim_curmax[RLIM_NLIMITS];
 
 #ifdef CONFIG_BSD_PROCESS_ACCT
 	struct pacct_struct pacct;	/* per-process accounting information */
@@ -3376,6 +3377,12 @@ static inline unsigned long rlimit_max(unsigned int limit)
 	return task_rlimit_max(current, limit);
 }
 
+static inline void bump_rlimit(unsigned int limit, unsigned long r)
+{
+	if (READ_ONCE(current->signal->rlim_curmax[limit]) < r)
+		current->signal->rlim_curmax[limit] = r;
+}
+
 #ifdef CONFIG_CPU_FREQ
 struct update_util_data {
 	void (*func)(struct update_util_data *data,
Signature · 1 line
2.8.1
#31 lore raw

RFC 7/18 limits: track RLIMIT_FSIZE actual max

In reply to Topi Miettinen

Track maximum file size, presented in /proc/self/limits.

---
 fs/attr.c    | 2 ++
 mm/filemap.c | 1 +
 2 files changed, 3 insertions(+)
fs/attr.c +2 -0
index 25b24d0..1b620f7 100644
@@ -116,6 +116,8 @@ int inode_newsize_ok(const struct inode *inode, loff_t offset)
 			return -ETXTBSY;
 	}
 
+	bump_rlimit(RLIMIT_FSIZE, offset);
+
 	return 0;
 out_sig:
 	send_sig(SIGXFSZ, current, 0);
mm/filemap.c +1 -0
index 00ae878..1fa9864 100644
@@ -2447,6 +2447,7 @@ inline ssize_t generic_write_checks(struct kiocb *iocb, struct iov_iter *from)
 			send_sig(SIGXFSZ, current, 0);
 			return -EFBIG;
 		}
+		bump_rlimit(RLIMIT_FSIZE, iocb->ki_pos);
 		iov_iter_truncate(from, limit - (unsigned long)pos);
 	}
 
Signature · 7 lines
2.8.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#32 lore raw

RFC 8/18 limits: track RLIMIT_DATA actual max

In reply to Topi Miettinen

Track maximum size of data VM, presented in /proc/self/limits.

---
 arch/x86/ia32/ia32_aout.c | 1 +
 fs/binfmt_aout.c          | 1 +
 fs/binfmt_flat.c          | 1 +
 kernel/sys.c              | 2 ++
 mm/mmap.c                 | 6 +++++-
 5 files changed, 10 insertions(+), 1 deletion(-)
arch/x86/ia32/ia32_aout.c +1 -0
index cb26f18..8a7d502 100644
@@ -398,6 +398,7 @@ beyond_if:
 	regs->r8 = regs->r9 = regs->r10 = regs->r11 =
 	regs->r12 = regs->r13 = regs->r14 = regs->r15 = 0;
 	set_fs(USER_DS);
+	bump_limit(RLIMIT_DATA, ex.a_data + ex.a_bss);
 	return 0;
 }
 
fs/binfmt_aout.c +1 -0
index ae1b540..86c6548 100644
@@ -330,6 +330,7 @@ beyond_if:
 	regs->gp = ex.a_gpvalue;
 #endif
 	start_thread(regs, ex.a_entry, current->mm->start_stack);
+	bump_limit(RLIMIT_DATA, ex.a_data + ex.a_bss);
 	return 0;
 }
 
fs/binfmt_flat.c +1 -0
index caf9e39..e309dad 100644
@@ -792,6 +792,7 @@ static int load_flat_file(struct linux_binprm * bprm,
 			libinfo->lib_list[id].start_brk) +	/* start brk */
 			stack_len);
 
+	bump_limit(RLIMIT_DATA, data_len + bss_len);
 	return 0;
 err:
 	return ret;
kernel/sys.c +2 -0
index 89d5be4..6629f6f 100644
@@ -1896,6 +1896,8 @@ static int prctl_set_mm_map(int opt, const void __user *addr, unsigned long data
 	if (prctl_map.auxv_size)
 		memcpy(mm->saved_auxv, user_auxv, sizeof(user_auxv));
 
+	bump_limit(RLIMIT_DATA, mm->end_data - mm->start_data);
+
 	up_write(&mm->mmap_sem);
 	return 0;
 }
mm/mmap.c +5 -1
index de2c176..61867de 100644
@@ -228,6 +228,8 @@ SYSCALL_DEFINE1(brk, unsigned long, brk)
 		goto out;
 
 set_brk:
+	bump_rlimit(RLIMIT_DATA, (brk - mm->start_brk) +
+		    (mm->end_data - mm->start_data));
 	mm->brk = brk;
 	populate = newbrk > oldbrk && (mm->def_flags & VM_LOCKED) != 0;
 	up_write(&mm->mmap_sem);
@@ -2924,8 +2926,10 @@ void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
 		mm->exec_vm += npages;
 	else if (is_stack_mapping(flags))
 		mm->stack_vm += npages;
-	else if (is_data_mapping(flags))
+	else if (is_data_mapping(flags)) {
 		mm->data_vm += npages;
+		bump_rlimit(RLIMIT_DATA, mm->data_vm << PAGE_SHIFT);
+	}
 }
 
 static int special_mapping_fault(struct vm_area_struct *vma,
Signature · 7 lines
2.8.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#39 lore raw

RFC 12/18 limits: track RLIMIT_MEMLOCK actual max

In reply to Topi Miettinen

Track maximum size of locked memory, presented in /proc/self/limits.

---
 arch/ia64/kernel/perfmon.c                 |  1 +
 arch/powerpc/kvm/book3s_64_vio.c           |  1 +
 arch/powerpc/mm/mmu_context_iommu.c        |  1 +
 drivers/infiniband/core/umem.c             |  1 +
 drivers/infiniband/hw/hfi1/user_pages.c    |  1 +
 drivers/infiniband/hw/qib/qib_user_pages.c |  1 +
 drivers/infiniband/hw/usnic/usnic_uiom.c   |  2 ++
 drivers/misc/mic/scif/scif_rma.c           |  1 +
 drivers/vfio/vfio_iommu_spapr_tce.c        |  2 ++
 drivers/vfio/vfio_iommu_type1.c            |  2 ++
 include/linux/sched.h                      | 10 ++++++++--
 kernel/bpf/syscall.c                       |  6 ++++++
 kernel/events/core.c                       |  1 +
 mm/mlock.c                                 |  7 +++++++
 mm/mmap.c                                  |  3 +++
 mm/mremap.c                                |  3 +++
 16 files changed, 41 insertions(+), 2 deletions(-)
arch/ia64/kernel/perfmon.c +1 -0
index 2436ad5..d05ff3b 100644
@@ -2341,6 +2341,7 @@ pfm_smpl_buffer_alloc(struct task_struct *task, struct file *filp, pfm_context_t
 	ctx->ctx_smpl_vaddr = (void *)vma->vm_start;
 	*(unsigned long *)user_vaddr = vma->vm_start;
 
+	task_bump_rlimit(task, RLIMIT_MEMLOCK, size);
 	return 0;
 
 error:
arch/powerpc/kvm/book3s_64_vio.c +1 -0
index 18cf6d1..2714bbf 100644
@@ -71,6 +71,7 @@ static long kvmppc_account_memlimit(unsigned long stt_pages, bool inc)
 			ret = -ENOMEM;
 		else
 			current->mm->locked_vm += stt_pages;
+		bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
 	} else {
 		if (WARN_ON_ONCE(stt_pages > current->mm->locked_vm))
 			stt_pages = current->mm->locked_vm;
arch/powerpc/mm/mmu_context_iommu.c +1 -0
index da6a216..ace8b9d 100644
@@ -46,6 +46,7 @@ static long mm_iommu_adjust_locked_vm(struct mm_struct *mm,
 			ret = -ENOMEM;
 		else
 			mm->locked_vm += npages;
+		bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
 	} else {
 		if (WARN_ON_ONCE(npages > mm->locked_vm))
 			npages = mm->locked_vm;
drivers/infiniband/core/umem.c +1 -0
index fe4d2e1..9bd9638 100644
@@ -224,6 +224,7 @@ struct ib_umem *ib_umem_get(struct ib_ucontext *context, unsigned long addr,
 
 	ret = 0;
 
+	bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
 out:
 	if (ret < 0) {
 		if (need_release)
drivers/infiniband/hw/hfi1/user_pages.c +1 -0
index 88e10b5f..096910d7 100644
@@ -111,6 +111,7 @@ int hfi1_acquire_user_pages(unsigned long vaddr, size_t npages, bool writable,
 
 	down_write(&current->mm->mmap_sem);
 	current->mm->pinned_vm += ret;
+	bump_rlimit(RLIMIT_MEMLOCK, current->mm->pinned_vm << PAGE_SHIFT);
 	up_write(&current->mm->mmap_sem);
 
 	return ret;
drivers/infiniband/hw/qib/qib_user_pages.c +1 -0
index 2d2b94f..06f93de 100644
@@ -74,6 +74,7 @@ static int __qib_get_user_pages(unsigned long start_page, size_t num_pages,
 	}
 
 	current->mm->pinned_vm += num_pages;
+	bump_rlimit(RLIMIT_MEMLOCK, current->mm->pinned_vm << PAGE_SHIFT);
 
 	ret = 0;
 	goto bail;
drivers/infiniband/hw/usnic/usnic_uiom.c +2 -0
index a0b6ebe..83409dc 100644
@@ -178,6 +178,8 @@ static int usnic_uiom_get_pages(unsigned long addr, size_t size, int writable,
 		ret = 0;
 	}
 
+	bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
+
 out:
 	if (ret < 0)
 		usnic_uiom_put_pages(chunk_list, 0);
drivers/misc/mic/scif/scif_rma.c +1 -0
index e0203b1..1d6315a 100644
@@ -306,6 +306,7 @@ static inline int __scif_check_inc_pinned_vm(struct mm_struct *mm,
 		return -ENOMEM;
 	}
 	mm->pinned_vm = locked;
+	bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
 	return 0;
 }
 
drivers/vfio/vfio_iommu_spapr_tce.c +2 -0
index 80378dd..769a5b8 100644
@@ -55,6 +55,8 @@ static long try_increment_locked_vm(long npages)
 			rlimit(RLIMIT_MEMLOCK),
 			ret ? " - exceeded" : "");
 
+	bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
+
 	up_write(&current->mm->mmap_sem);
 
 	return ret;
drivers/vfio/vfio_iommu_type1.c +2 -0
index 2ba1942..4c6e7a3 100644
@@ -312,6 +312,8 @@ static long vfio_pin_pages(unsigned long vaddr, long npage,
 		}
 	}
 
+	bump_rlimit(RLIMIT_MEMLOCK, (current->mm->locked_vm + i) << PAGE_SHIFT);
+
 	if (!rsvd)
 		vfio_lock_acct(i);
 
include/linux/sched.h +8 -2
index feb9bb7..d3f3c9f 100644
@@ -3378,10 +3378,16 @@ static inline unsigned long rlimit_max(unsigned int limit)
 	return task_rlimit_max(current, limit);
 }
 
+static inline void task_bump_rlimit(struct task_struct *tsk,
+				    unsigned int limit, unsigned long r)
+{
+	if (READ_ONCE(tsk->signal->rlim_curmax[limit]) < r)
+		tsk->signal->rlim_curmax[limit] = r;
+}
+
 static inline void bump_rlimit(unsigned int limit, unsigned long r)
 {
-	if (READ_ONCE(current->signal->rlim_curmax[limit]) < r)
-		current->signal->rlim_curmax[limit] = r;
+	return task_bump_rlimit(current, limit, r);
 }
 
 #ifdef CONFIG_CPU_FREQ
kernel/bpf/syscall.c +6 -0
index 46ecce4..192001e 100644
@@ -76,6 +76,9 @@ static int bpf_map_charge_memlock(struct bpf_map *map)
 		return -EPERM;
 	}
 	map->user = user;
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, atomic_long_read(&user->locked_vm) <<
+		    PAGE_SHIFT);
 	return 0;
 }
 
@@ -601,6 +604,9 @@ static int bpf_prog_charge_memlock(struct bpf_prog *prog)
 		return -EPERM;
 	}
 	prog->aux->user = user;
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, atomic_long_read(&user->locked_vm) <<
+		    PAGE_SHIFT);
 	return 0;
 }
 
kernel/events/core.c +1 -0
index 9c51ec3..92467e8 100644
@@ -5075,6 +5075,7 @@ accounting:
 		if (!ret)
 			rb->aux_mmap_locked = extra;
 	}
+	bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
 
 unlock:
 	if (!ret) {
mm/mlock.c +7 -0
index ef8dc9f..554bee9 100644
@@ -648,6 +648,8 @@ static __must_check int do_mlock(unsigned long start, size_t len, vm_flags_t fla
 	if (error)
 		return error;
 
+	bump_rlimit(RLIMIT_MEMLOCK, locked << PAGE_SHIFT);
+
 	error = __mm_populate(start, len, 0);
 	if (error)
 		return __mlock_posix_error_return(error);
@@ -761,6 +763,8 @@ SYSCALL_DEFINE1(mlockall, int, flags)
 	if (!ret && (flags & MCL_CURRENT))
 		mm_populate(0, TASK_SIZE);
 
+	bump_rlimit(RLIMIT_MEMLOCK, current->mm->total_vm << PAGE_SHIFT);
+
 	return ret;
 }
 
@@ -798,6 +802,9 @@ int user_shm_lock(size_t size, struct user_struct *user)
 	get_uid(user);
 	user->locked_shm += locked;
 	allowed = 1;
+
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, user->locked_shm << PAGE_SHIFT);
 out:
 	spin_unlock(&shmlock_user_lock);
 	return allowed;
mm/mmap.c +3 -0
index 0963e7f..4e683dd 100644
@@ -2020,6 +2020,9 @@ static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, uns
 		return -ENOMEM;
 
 	bump_rlimit(RLIMIT_STACK, actual_size);
+	if (vma->vm_flags & VM_LOCKED)
+		bump_rlimit(RLIMIT_MEMLOCK,
+			    (mm->locked_vm + grow) << PAGE_SHIFT);
 
 	return 0;
 }
mm/mremap.c +3 -0
index 1f157ad..ade3e13 100644
@@ -394,6 +394,9 @@ static struct vm_area_struct *vma_to_resize(unsigned long addr,
 		*p = charged;
 	}
 
+	if (vma->vm_flags & VM_LOCKED)
+		bump_rlimit(RLIMIT_MEMLOCK, (mm->locked_vm << PAGE_SHIFT) +
+			    new_len - old_len);
 	return vma;
 }
 
Signature · 7 lines
2.8.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#0 lore raw

cover Present useful limits to user

Hello,

There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even the source code is only implicit, in-depth knowledge of each capability must be used when analyzing a program to judge which capabilities the program will exercise.

Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the current tasks and memory status can be easily seen with ps(1). However, any transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no universal method. Program sources typically give no useful indication about memory use or how many tasks there could be.

Resource limits
[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current [RFC 07/18] limits: track RLIMIT_FSIZE actual max
[RFC 08/18] limits: track RLIMIT_DATA actual max
[RFC 09/18] limits: track RLIMIT_CORE actual max
[RFC 10/18] limits: track RLIMIT_STACK actual max
[RFC 11/18] limits: track and present RLIMIT_NPROC actual max [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max [RFC 13/18] limits: track RLIMIT_AS actual max
[RFC 14/18] limits: track RLIMIT_SIGPENDING actual max [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max [RFC 16/18] limits: track RLIMIT_NICE actual max
[RFC 17/18] limits: track RLIMIT_RTPRIO actual max
[RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

Current number of files and current VM usage (data pages, address space size) could be calculated from available /proc files. Again, any temporarily higher values could be easily missed. For many limits, there is no way to see what is the current situation and source code is mostly useless.

As a side note, the resouce limits seem to be in bad shape. For example, RLIMIT_MEMLOCK is used incoherently and I think VM statistics can miss some changes. Adding RLIMIT_CODE could be useful.

The current maximum values for the resource limits are now shown in /proc/task/limits. If this is deemed too confusing for the existing programs which rely on the exact format, I can change that to a new file.

Finally, the patches work in my testing but I have probably missed finer lock/RCU details.

-Topi

#1 lore raw

RFC 1/18 capabilities: track actually used capabilities

Track what capabilities are actually used and present the current situation in /proc/self/status.

---
 fs/exec.c             | 1 +
 fs/proc/array.c       | 1 +
 include/linux/sched.h | 1 +
 kernel/capability.c   | 1 +
 4 files changed, 4 insertions(+)
fs/exec.c +1 -0
index 887c1c9..ff6f644 100644
@@ -1269,6 +1269,7 @@ void setup_new_exec(struct linux_binprm * bprm)
 		if (bprm->interp_flags & BINPRM_FLAGS_ENFORCE_NONDUMP)
 			set_dumpable(current->mm, suid_dumpable);
 	}
+	cap_clear(current->cap_used);
 
 	/* An exec changes our domain. We are no longer part of the thread
 	   group */
fs/proc/array.c +1 -0
index 88c7de1..cccc9ee 100644
@@ -343,6 +343,7 @@ static inline void task_cap(struct seq_file *m, struct task_struct *p)
 	render_cap_t(m, "CapEff:\t", &cap_effective);
 	render_cap_t(m, "CapBnd:\t", &cap_bset);
 	render_cap_t(m, "CapAmb:\t", &cap_ambient);
+	render_cap_t(m, "CapUsd:\t", &p->cap_used);
 }
 
 static inline void task_seccomp(struct seq_file *m, struct task_struct *p)
include/linux/sched.h +1 -0
index 6e42ada..9c48a08 100644
@@ -1918,6 +1918,7 @@ struct task_struct {
 #ifdef CONFIG_MMU
 	struct task_struct *oom_reaper_list;
 #endif
+	kernel_cap_t	cap_used;	/* Capabilities actually used */
 /* CPU-specific state of this task */
 	struct thread_struct thread;
 /*
kernel/capability.c +1 -0
index 45432b5..aad8854 100644
@@ -380,6 +380,7 @@ bool ns_capable(struct user_namespace *ns, int cap)
 	}
 
 	if (security_capable(current_cred(), ns, cap) == 0) {
+		cap_raise(current->cap_used, cap);
 		current->flags |= PF_SUPERPRIV;
 		return true;
 	}
Signature · 1 line
2.8.1
#22 lore raw

RFC 4/18 device_cgroup: track and present accessed devices

In reply to Topi Miettinen

Track what devices are accessed and present them cgroup devices.accessed.

---
 security/device_cgroup.c | 70 +++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 60 insertions(+), 10 deletions(-)
security/device_cgroup.c +60 -10
index 03c1652..45aa730 100644
@@ -48,6 +48,7 @@ struct dev_exception_item {
 struct dev_cgroup {
 	struct cgroup_subsys_state css;
 	struct list_head exceptions;
+	struct list_head accessed;
 	enum devcg_behavior behavior;
 };
 
@@ -90,7 +91,7 @@ free_and_exit:
 /*
  * called under devcgroup_mutex
  */
-static int dev_exception_add(struct dev_cgroup *dev_cgroup,
+static int dev_exception_add(struct list_head *exceptions,
 			     struct dev_exception_item *ex)
 {
 	struct dev_exception_item *excopy, *walk;
@@ -101,7 +102,7 @@ static int dev_exception_add(struct dev_cgroup *dev_cgroup,
 	if (!excopy)
 		return -ENOMEM;
 
-	list_for_each_entry(walk, &dev_cgroup->exceptions, list) {
+	list_for_each_entry(walk, exceptions, list) {
 		if (walk->type != ex->type)
 			continue;
 		if (walk->major != ex->major)
@@ -115,7 +116,7 @@ static int dev_exception_add(struct dev_cgroup *dev_cgroup,
 	}
 
 	if (excopy != NULL)
-		list_add_tail_rcu(&excopy->list, &dev_cgroup->exceptions);
+		list_add_tail_rcu(&excopy->list, exceptions);
 	return 0;
 }
 
@@ -155,6 +156,16 @@ static void __dev_exception_clean(struct dev_cgroup *dev_cgroup)
 	}
 }
 
+static void dev_accessed_clean(struct dev_cgroup *dev_cgroup)
+{
+	struct dev_exception_item *ex, *tmp;
+
+	list_for_each_entry_safe(ex, tmp, &dev_cgroup->accessed, list) {
+		list_del_rcu(&ex->list);
+		kfree_rcu(ex, rcu);
+	}
+}
+
 /**
  * dev_exception_clean - frees all entries of the exception list
  * @dev_cgroup: dev_cgroup with the exception list to be cleaned
@@ -221,6 +232,7 @@ devcgroup_css_alloc(struct cgroup_subsys_state *parent_css)
 	if (!dev_cgroup)
 		return ERR_PTR(-ENOMEM);
 	INIT_LIST_HEAD(&dev_cgroup->exceptions);
+	INIT_LIST_HEAD(&dev_cgroup->accessed);
 	dev_cgroup->behavior = DEVCG_DEFAULT_NONE;
 
 	return &dev_cgroup->css;
@@ -231,6 +243,7 @@ static void devcgroup_css_free(struct cgroup_subsys_state *css)
 	struct dev_cgroup *dev_cgroup = css_to_devcgroup(css);
 
 	__dev_exception_clean(dev_cgroup);
+	dev_accessed_clean(dev_cgroup);
 	kfree(dev_cgroup);
 }
 
@@ -272,9 +285,9 @@ static void set_majmin(char *str, unsigned m)
 		sprintf(str, "%u", m);
 }
 
-static int devcgroup_seq_show(struct seq_file *m, void *v)
+static int devcgroup_seq_show_list(struct seq_file *m, struct dev_cgroup *devcgroup,
+				   struct list_head *exceptions, bool allow)
 {
-	struct dev_cgroup *devcgroup = css_to_devcgroup(seq_css(m));
 	struct dev_exception_item *ex;
 	char maj[MAJMINLEN], min[MAJMINLEN], acc[ACCLEN];
 
@@ -285,14 +298,14 @@ static int devcgroup_seq_show(struct seq_file *m, void *v)
 	 * - List the exceptions in case the default policy is to deny
 	 * This way, the file remains as a "whitelist of devices"
 	 */
-	if (devcgroup->behavior == DEVCG_DEFAULT_ALLOW) {
+	if (allow) {
 		set_access(acc, ACC_MASK);
 		set_majmin(maj, ~0);
 		set_majmin(min, ~0);
 		seq_printf(m, "%c %s:%s %s\n", type_to_char(DEV_ALL),
 			   maj, min, acc);
 	} else {
-		list_for_each_entry_rcu(ex, &devcgroup->exceptions, list) {
+		list_for_each_entry_rcu(ex, exceptions, list) {
 			set_access(acc, ex->access);
 			set_majmin(maj, ex->major);
 			set_majmin(min, ex->minor);
@@ -305,6 +318,36 @@ static int devcgroup_seq_show(struct seq_file *m, void *v)
 	return 0;
 }
 
+static int devcgroup_seq_show(struct seq_file *m, void *v)
+{
+	struct dev_cgroup *devcgroup = css_to_devcgroup(seq_css(m));
+
+	return devcgroup_seq_show_list(m, devcgroup, &devcgroup->exceptions,
+				       devcgroup->behavior == DEVCG_DEFAULT_ALLOW);
+}
+
+static int devcgroup_seq_show_accessed(struct seq_file *m, void *v)
+{
+	struct dev_cgroup *devcgroup = css_to_devcgroup(seq_css(m));
+
+	return devcgroup_seq_show_list(m, devcgroup, &devcgroup->accessed, false);
+}
+
+static void devcgroup_add_accessed(struct dev_cgroup *dev_cgroup, short type,
+				   u32 major, u32 minor, short access)
+{
+	struct dev_exception_item ex;
+
+	ex.type = type;
+	ex.major = major;
+	ex.minor = minor;
+	ex.access = access;
+
+	mutex_lock(&devcgroup_mutex);
+	dev_exception_add(&dev_cgroup->accessed, &ex);
+	mutex_unlock(&devcgroup_mutex);
+}
+
 /**
  * match_exception	- iterates the exception list trying to find a complete match
  * @exceptions: list of exceptions
@@ -566,7 +609,7 @@ static int propagate_exception(struct dev_cgroup *devcg_root,
 		 */
 		if (devcg_root->behavior == DEVCG_DEFAULT_ALLOW &&
 		    devcg->behavior == DEVCG_DEFAULT_ALLOW) {
-			rc = dev_exception_add(devcg, ex);
+			rc = dev_exception_add(&devcg->exceptions, ex);
 			if (rc)
 				break;
 		} else {
@@ -736,7 +779,7 @@ static int devcgroup_update_access(struct dev_cgroup *devcgroup,
 
 		if (!parent_has_perm(devcgroup, &ex))
 			return -EPERM;
-		rc = dev_exception_add(devcgroup, &ex);
+		rc = dev_exception_add(&devcgroup->exceptions, &ex);
 		break;
 	case DEVCG_DENY:
 		/*
@@ -747,7 +790,7 @@ static int devcgroup_update_access(struct dev_cgroup *devcgroup,
 		if (devcgroup->behavior == DEVCG_DEFAULT_DENY)
 			dev_exception_rm(devcgroup, &ex);
 		else
-			rc = dev_exception_add(devcgroup, &ex);
+			rc = dev_exception_add(&devcgroup->exceptions, &ex);
 
 		if (rc)
 			break;
@@ -788,6 +831,11 @@ static struct cftype dev_cgroup_files[] = {
 		.seq_show = devcgroup_seq_show,
 		.private = DEVCG_LIST,
 	},
+	{
+		.name = "accessed",
+		.seq_show = devcgroup_seq_show_accessed,
+		.private = DEVCG_LIST,
+	},
 	{ }	/* terminate */
 };
 
@@ -830,6 +878,8 @@ static int __devcgroup_check_permission(short type, u32 major, u32 minor,
 	if (!rc)
 		return -EPERM;
 
+	devcgroup_add_accessed(dev_cgroup, type, major, minor, access);
+
 	return 0;
 }
 
Signature · 1 line
2.8.1
#29 lore raw

RFC 6/18 limits: present RLIMIT_CPU and RLIMIT_RTTIMER current status

In reply to Topi Miettinen

Present current cputimer status in /proc/self/limits.

---
 fs/proc/base.c | 26 ++++++++++++++++++++++++--
 1 file changed, 24 insertions(+), 2 deletions(-)
fs/proc/base.c +24 -2
index 227997b..1df4fc8 100644
@@ -650,8 +650,30 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 			seq_printf(m, "%-10s", lnames[i].unit);
 		else
 			seq_printf(m, "%-10s", "");
-		seq_printf(m, "%-20lu\n",
-			   task->signal->rlim_curmax[i]);
+
+		switch (i) {
+		case RLIMIT_RTTIME:
+		case RLIMIT_CPU:
+			if (rlim[i].rlim_max == RLIM_INFINITY)
+				seq_printf(m, "%-20s\n", "-");
+			else {
+				unsigned long long utime, ptime;
+				unsigned long psecs;
+				struct task_cputime cputime;
+
+				thread_group_cputimer(task, &cputime);
+				utime = cputime_to_expires(cputime.utime);
+				ptime = utime + cputime_to_expires(cputime.stime);
+				psecs = cputime_to_secs(ptime);
+				if (i == RLIMIT_RTTIME)
+					psecs *= USEC_PER_SEC;
+				seq_printf(m, "%-20lu\n", psecs);
+			}
+			break;
+		default:
+			seq_printf(m, "%-20lu\n",
+				   task->signal->rlim_curmax[i]);
+		}
 	}
 
 	return 0;
Signature · 1 line
2.8.1
#33 lore raw

RFC 9/18 limits: track RLIMIT_CORE actual max

In reply to Topi Miettinen

Track maximum size of core dump written, presented in /proc/self/limits.

---
 fs/coredump.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
fs/coredump.c +8 -3
index 281b768..abedc99 100644
@@ -784,20 +784,25 @@ int dump_emit(struct coredump_params *cprm, const void *addr, int nr)
 	struct file *file = cprm->file;
 	loff_t pos = file->f_pos;
 	ssize_t n;
+	int r = 0;
+
 	if (cprm->written + nr > cprm->limit)
 		return 0;
 	while (nr) {
 		if (dump_interrupted())
-			return 0;
+			goto err;
 		n = __kernel_write(file, addr, nr, &pos);
 		if (n <= 0)
-			return 0;
+			goto err;
 		file->f_pos = pos;
 		cprm->written += n;
 		cprm->pos += n;
 		nr -= n;
 	}
-	return 1;
+	r = 1;
+ err:
+	bump_rlimit(RLIMIT_CORE, cprm->written);
+	return r;
 }
 EXPORT_SYMBOL(dump_emit);
 
Signature · 1 line
2.8.1
#34 lore raw

RFC 10/18 limits: track RLIMIT_STACK actual max

In reply to Topi Miettinen

Track maximum stack size, presented in /proc/self/limits.

---
 mm/mmap.c | 2 ++
 1 file changed, 2 insertions(+)
mm/mmap.c +2 -0
index 61867de..0963e7f 100644
@@ -2019,6 +2019,8 @@ static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, uns
 	if (security_vm_enough_memory_mm(mm, grow))
 		return -ENOMEM;
 
+	bump_rlimit(RLIMIT_STACK, actual_size);
+
 	return 0;
 }
 
Signature · 7 lines
2.8.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#35 lore raw

RFC 11/18 limits: track and present RLIMIT_NPROC actual max

In reply to Topi Miettinen

Track maximum number of processes per user and present it in /proc/self/limits.

---
 fs/proc/base.c        | 4 ++++
 include/linux/sched.h | 1 +
 kernel/fork.c         | 5 +++++
 kernel/sys.c          | 5 +++++
 4 files changed, 15 insertions(+)
fs/proc/base.c +4 -0
index 1df4fc8..02576c6 100644
@@ -670,6 +670,10 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 				seq_printf(m, "%-20lu\n", psecs);
 			}
 			break;
+		case RLIMIT_NPROC:
+			seq_printf(m, "%-20d\n",
+				   atomic_read(&task->real_cred->user->max_processes));
+			break;
 		default:
 			seq_printf(m, "%-20lu\n",
 				   task->signal->rlim_curmax[i]);
include/linux/sched.h +1 -0
index 0150380..feb9bb7 100644
@@ -838,6 +838,7 @@ static inline int signal_group_exit(const struct signal_struct *sig)
 struct user_struct {
 	atomic_t __count;	/* reference count */
 	atomic_t processes;	/* How many processes does this user have? */
+	atomic_t max_processes;	/* How many processes has this user had at the same time? */
 	atomic_t sigpending;	/* How many pending signals does this user have? */
 #ifdef CONFIG_INOTIFY_USER
 	atomic_t inotify_watches; /* How many inotify watches does this user have? */
kernel/fork.c +5 -0
index 5c2c355..667290f 100644
@@ -1653,6 +1653,11 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	trace_task_newtask(p, clone_flags);
 	uprobe_copy_process(p, clone_flags);
 
+	if (atomic_read(&p->real_cred->user->max_processes) <
+	    atomic_read(&p->real_cred->user->processes))
+		atomic_set(&p->real_cred->user->max_processes,
+			   atomic_read(&p->real_cred->user->processes));
+
 	return p;
 
 bad_fork_cancel_cgroup:
kernel/sys.c +5 -0
index 6629f6f..955cf21 100644
@@ -439,6 +439,11 @@ static int set_user(struct cred *new)
 	else
 		current->flags &= ~PF_NPROC_EXCEEDED;
 
+	if (atomic_read(&new_user->max_processes) <
+	    atomic_read(&new_user->processes))
+		atomic_set(&new_user->max_processes,
+			   atomic_read(&new_user->processes));
+
 	free_uid(new->user);
 	new->user = new_user;
 	return 0;
Signature · 1 line
2.8.1
#44 lore raw

RFC 13/18 limits: track RLIMIT_AS actual max

In reply to Topi Miettinen

Track maximum size of address space, presented in /proc/self/limits.

---
 mm/mmap.c   | 4 ++++
 mm/mremap.c | 3 +++
 2 files changed, 7 insertions(+)
mm/mmap.c +4 -0
index 4e683dd..4876c21 100644
@@ -2706,6 +2706,9 @@ static int do_brk(unsigned long addr, unsigned long len)
 out:
 	perf_event_mmap(vma);
 	mm->total_vm += len >> PAGE_SHIFT;
+
+	bump_rlimit(RLIMIT_AS, mm->total_vm << PAGE_SHIFT);
+
 	mm->data_vm += len >> PAGE_SHIFT;
 	if (flags & VM_LOCKED)
 		mm->locked_vm += (len >> PAGE_SHIFT);
@@ -2926,6 +2929,7 @@ bool may_expand_vm(struct mm_struct *mm, vm_flags_t flags, unsigned long npages)
 void vm_stat_account(struct mm_struct *mm, vm_flags_t flags, long npages)
 {
 	mm->total_vm += npages;
+	bump_rlimit(RLIMIT_AS, mm->total_vm << PAGE_SHIFT);
 
 	if (is_exec_mapping(flags))
 		mm->exec_vm += npages;
mm/mremap.c +3 -0
index ade3e13..6be3c01 100644
@@ -397,6 +397,9 @@ static struct vm_area_struct *vma_to_resize(unsigned long addr,
 	if (vma->vm_flags & VM_LOCKED)
 		bump_rlimit(RLIMIT_MEMLOCK, (mm->locked_vm << PAGE_SHIFT) +
 			    new_len - old_len);
+	bump_rlimit(RLIMIT_AS, (mm->total_vm << PAGE_SHIFT) +
+		    new_len - old_len);
+
 	return vma;
 }
 
Signature · 7 lines
2.8.1

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in
the body to [email protected].  For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>
#45 lore raw

RFC 14/18 limits: track RLIMIT_SIGPENDING actual max

In reply to Topi Miettinen

Track maximum number of pending signals, presented in /proc/self/limits.

---
 kernel/signal.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/signal.c +2 -0
index 96e9bc4..c8fbccd 100644
@@ -387,6 +387,8 @@ __sigqueue_alloc(int sig, struct task_struct *t, gfp_t flags, int override_rlimi
 		INIT_LIST_HEAD(&q->list);
 		q->flags = 0;
 		q->user = user;
+		/* XXX resource limits apply per task, not per user */
+		bump_rlimit(RLIMIT_SIGPENDING, atomic_read(&user->sigpending));
 	}
 
 	return q;
Signature · 1 line
2.8.1
#48 lore raw

RFC 15/18 limits: track RLIMIT_MSGQUEUE actual max

In reply to Topi Miettinen

Track maximum size of message queues, presented in /proc/self/limits.

---
 ipc/mqueue.c | 2 ++
 1 file changed, 2 insertions(+)
ipc/mqueue.c +2 -0
index ade739f..edccf55 100644
@@ -287,6 +287,8 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
 
 		/* all is ok */
 		info->user = get_uid(u);
+		/* XXX resource limits apply per task, not per user */
+		bump_rlimit(RLIMIT_MSGQUEUE, u->mq_bytes);
 	} else if (S_ISDIR(mode)) {
 		inc_nlink(inode);
 		/* Some things misbehave if size == 0 on a directory */
Signature · 1 line
2.8.1
#50 lore raw

RFC 16/18 limits: track RLIMIT_NICE actual max

In reply to Topi Miettinen

Track maximum nice priority, presented in /proc/self/limits.

---
 kernel/sched/core.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/sched/core.c +2 -0
index 017d539..817d720 100644
@@ -3692,6 +3692,8 @@ void set_user_nice(struct task_struct *p, long nice)
 		if (delta < 0 || (delta > 0 && task_running(rq, p)))
 			resched_curr(rq);
 	}
+	task_bump_rlimit(p, RLIMIT_NICE, nice_to_rlimit(nice));
+
 out_unlock:
 	task_rq_unlock(rq, p, &rf);
 }
Signature · 1 line
2.8.1
#51 lore raw

RFC 17/18 limits: track RLIMIT_RTPRIO actual max

In reply to Topi Miettinen

Track maximum RT priority, presented in /proc/self/limits.

---
 kernel/sched/core.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/sched/core.c +2 -0
index 817d720..d31a06a 100644
@@ -4219,6 +4219,8 @@ change:
 	balance_callback(rq);
 	preempt_enable();
 
+	task_bump_rlimit(p, RLIMIT_RTPRIO, attr->sched_priority);
+
 	return 0;
 }
 
Signature · 1 line
2.8.1
#52 lore raw

RFC 18/18 proc: present VM_LOCKED memory in /proc/self/maps

In reply to Topi Miettinen

Add a flag to /proc/self/maps to show that the memory area is locked.

---
 fs/proc/task_mmu.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/proc/task_mmu.c +2 -1
index 4648c7f..8229509 100644
@@ -313,13 +313,14 @@ show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid)
 		end -= PAGE_SIZE;
 
 	seq_setwidth(m, 25 + sizeof(void *) * 6 - 1);
-	seq_printf(m, "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu ",
+	seq_printf(m, "%08lx-%08lx %c%c%c%c%c %08llx %02x:%02x %lu ",
 			start,
 			end,
 			flags & VM_READ ? 'r' : '-',
 			flags & VM_WRITE ? 'w' : '-',
 			flags & VM_EXEC ? 'x' : '-',
 			flags & VM_MAYSHARE ? 's' : 'p',
+			flags & VM_LOCKED ? 'l' : '-',
 			pgoff,
 			MAJOR(dev), MINOR(dev), ino);
 
Signature · 1 line
2.8.1
#2 lore raw

Re: [RFC 01/18] capabilities: track actually used capabilities

In reply to Topi Miettinen
Quoted 2 lines · Topi Miettinen

Track what capabilities are actually used and present the current situation in /proc/self/status.

What for?

What is the intended behavior on fork()? Whatever the intended behavior is, there should IMO be a selftest for it.

--Andy

#25 lore raw

Re: [RFC 05/18] limits: track and present RLIMIT_NOFILE actual max

In reply to Topi Miettinen
Quoted 2 lines · Topi Miettinen

Track maximum number of files for the process, present current maximum in /proc/self/limits.

The core part should be its own patch.

Also, you have this weirdly named (and racy!) function bump_rlimit. Wouldn't this be nicer if you taught the rlimit code to track the *current* usage generically and to derive the max usage from that?

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns, · line 634

Quoted 12 lines
fs/proc/base.c +2 -2
index a11eb71..227997b 100644
@@ -630,8 +630,8 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 	/*
 	 * print the file header
 	 */
-       seq_printf(m, "%-25s %-20s %-20s %-10s\n",
-		  "Limit", "Soft Limit", "Hard Limit", "Units");
+	seq_printf(m, "%-25s %-20s %-20s %-10s %-20s\n",
+		   "Limit", "Soft Limit", "Hard Limit", "Units", "Max");

What existing programs, if any, does this break?

Quoted 43 lines
fs/proc/base.c +4 -2
 	for (i = 0; i < RLIM_NLIMITS; i++) {
 		if (rlim[i].rlim_cur == RLIM_INFINITY)
@@ -647,9 +647,11 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 			seq_printf(m, "%-20lu ", rlim[i].rlim_max);
 
 		if (lnames[i].unit)
-			seq_printf(m, "%-10s\n", lnames[i].unit);
+			seq_printf(m, "%-10s", lnames[i].unit);
 		else
-			seq_putc(m, '\n');
+			seq_printf(m, "%-10s", "");
+		seq_printf(m, "%-20lu\n",
+			   task->signal->rlim_curmax[i]);
 	}
 
 	return 0;
include/linux/sched.h +7 -0
index 9c48a08..0150380 100644
@@ -782,6 +782,7 @@ struct signal_struct {
 	 * have no need to disable irqs.
 	 */
 	struct rlimit rlim[RLIM_NLIMITS];
+	unsigned long rlim_curmax[RLIM_NLIMITS];
 
 #ifdef CONFIG_BSD_PROCESS_ACCT
 	struct pacct_struct pacct;	/* per-process accounting information */
@@ -3376,6 +3377,12 @@ static inline unsigned long rlimit_max(unsigned int limit)
 	return task_rlimit_max(current, limit);
 }
 
+static inline void bump_rlimit(unsigned int limit, unsigned long r)
+{
+	if (READ_ONCE(current->signal->rlim_curmax[limit]) < r)
+		current->signal->rlim_curmax[limit] = r;
+}
+
 #ifdef CONFIG_CPU_FREQ
 struct update_util_data {
 	void (*func)(struct update_util_data *data,
#40 lore raw

Re: [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max

In reply to Topi Miettinen
Quoted 21 lines · On Mon, 13 Jun 2016 22:44:19 +0300 Topi Miettinen <[email protected]> wrote:

Track maximum size of locked memory, presented in /proc/self/limits.

---
 arch/ia64/kernel/perfmon.c                 |  1 +
 arch/powerpc/kvm/book3s_64_vio.c           |  1 +
 arch/powerpc/mm/mmu_context_iommu.c        |  1 +
 drivers/infiniband/core/umem.c             |  1 +
 drivers/infiniband/hw/hfi1/user_pages.c    |  1 +
 drivers/infiniband/hw/qib/qib_user_pages.c |  1 +
 drivers/infiniband/hw/usnic/usnic_uiom.c   |  2 ++
 drivers/misc/mic/scif/scif_rma.c           |  1 +
 drivers/vfio/vfio_iommu_spapr_tce.c        |  2 ++
 drivers/vfio/vfio_iommu_type1.c            |  2 ++
 include/linux/sched.h                      | 10 ++++++++--
 kernel/bpf/syscall.c                       |  6 ++++++
 kernel/events/core.c                       |  1 +
 mm/mlock.c                                 |  7 +++++++
 mm/mmap.c                                  |  3 +++
 mm/mremap.c                                |  3 +++
 16 files changed, 41 insertions(+), 2 deletions(-)

...

Quoted 6 lines
drivers/vfio/vfio_iommu_type1.c +0 -0
index 2ba1942..4c6e7a3 100644

drivers/vfio/vfio_iommu_type1.c static long vfio_pin_pages(unsigned long vaddr, long npage, · line 319

Quoted 8 lines
drivers/vfio/vfio_iommu_type1.c +2 -0
@@ -312,6 +312,8 @@ static long vfio_pin_pages(unsigned long vaddr, long npage,
 		}
 	}
 
+	bump_rlimit(RLIMIT_MEMLOCK, (current->mm->locked_vm + i) << PAGE_SHIFT);
+
 	if (!rsvd)
 		vfio_lock_acct(i);
 

Not all cases passing through here bump rlimit (see: rsvd), there's an entire case above the other end of this closing bracket that does bump rlimit but returns before here, and I wonder why we wouldn't just do this in our vfio_lock_acct() accounting function anyway. Thanks,

Alex

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#3 lore raw

Re: [RFC 01/18] capabilities: track actually used capabilities

In reply to Andy Lutomirski
Quoted 5 lines · Andy Lutomirski
Quoted 2 lines · Topi Miettinen

Track what capabilities are actually used and present the current situation in /proc/self/status.

What for?

Excerpt from the cover letter:

"There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even
the source code is only implicit, in-depth knowledge of each capability must be used when analyzing a program to judge which capabilities the program will
exercise."

Should I perhaps cite some of this in the commit?

Quoted 6 lines

What is the intended behavior on fork()? Whatever the intended behavior is, there should IMO be a selftest for it.

--Andy

The capabilities could be tracked from three points of daemon initialization sequence onwards:
fork()
setpcap()
exec()

fork() case would be logical as the /proc entry is per task. But if you consider the tools to set the capabilities (for example systemd unit files), there can be between fork() and exec() further preparations which need more capabilities than the program itself needs.

setpcap() is probably the real point after which we are interested if the capabilities are enough.

The amount of setup between setpcap() and exec() is probably very low.

-Topi

#54 lore raw

Re: [RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

In reply to Kees Cook
Quoted 28 lines · Kees Cook

fs/proc/task_mmu.c

Quoted 11 lines · Topi Miettinen

Add a flag to /proc/self/maps to show that the memory area is locked.

---
 fs/proc/task_mmu.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/proc/task_mmu.c +0 -0
index 4648c7f..8229509 100644

If you change the maps format, you'll need to update task_nommu.c too.

fs/proc/task_mmu.c show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid) · line 315

Quoted 4 lines
fs/proc/task_mmu.c +0 -0
@@ -313,13 +313,14 @@ show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid)
 		end -= PAGE_SIZE;
 
 	seq_setwidth(m, 25 + sizeof(void *) * 6 - 1);

I think the width needs to be adjusted for the new character.

fs/proc/task_mmu.c show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid) · line 316

Quoted 2 lines
fs/proc/task_mmu.c +1 -1
-	seq_printf(m, "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu ",
+	seq_printf(m, "%08lx-%08lx %c%c%c%c%c %08llx %02x:%02x %lu ",

Have you checked that no userspace tools that parse "maps" will break with this flag addition?

Quoted 11 lines

fs/proc/task_mmu.c show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid) · line 323

Quoted 7 lines
fs/proc/task_mmu.c +1 -0
 			start,
 			end,
 			flags & VM_READ ? 'r' : '-',
 			flags & VM_WRITE ? 'w' : '-',
 			flags & VM_EXEC ? 'x' : '-',
 			flags & VM_MAYSHARE ? 's' : 'p',
+			flags & VM_LOCKED ? 'l' : '-',

IIUC, the smaps file already includes the locked information in VmFlags as "lo" (see show_smap_vma_flags), so I think you probably don't want this patch at all.

Yes. the amount of locked memory is also shown:
Locked: 8 kB
VmFlags: rd wr mr mw me lo ac sd

Sorry, I didn't notice that. I'll drop the patch.

-Topi

Quoted 9 lines

-Kees

Quoted 5 lines
fs/proc/task_mmu.c +0 -0
 			pgoff,
 			MAJOR(dev), MINOR(dev), ino);
 
Signature · 1 line
2.8.1
#53 lore raw

Re: [RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

In reply to Topi Miettinen

fs/proc/task_mmu.c

Quoted 11 lines · Topi Miettinen

Add a flag to /proc/self/maps to show that the memory area is locked.

---
 fs/proc/task_mmu.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/proc/task_mmu.c +0 -0
index 4648c7f..8229509 100644

If you change the maps format, you'll need to update task_nommu.c too.

fs/proc/task_mmu.c show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid) · line 315

Quoted 4 lines
fs/proc/task_mmu.c +0 -0
@@ -313,13 +313,14 @@ show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid)
 		end -= PAGE_SIZE;
 
 	seq_setwidth(m, 25 + sizeof(void *) * 6 - 1);

I think the width needs to be adjusted for the new character.

fs/proc/task_mmu.c show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid) · line 316

Quoted 2 lines
fs/proc/task_mmu.c +1 -1
-	seq_printf(m, "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu ",
+	seq_printf(m, "%08lx-%08lx %c%c%c%c%c %08llx %02x:%02x %lu ",

Have you checked that no userspace tools that parse "maps" will break with this flag addition?

fs/proc/task_mmu.c show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid) · line 323

Quoted 7 lines
fs/proc/task_mmu.c +1 -0
 			start,
 			end,
 			flags & VM_READ ? 'r' : '-',
 			flags & VM_WRITE ? 'w' : '-',
 			flags & VM_EXEC ? 'x' : '-',
 			flags & VM_MAYSHARE ? 's' : 'p',
+			flags & VM_LOCKED ? 'l' : '-',

IIUC, the smaps file already includes the locked information in VmFlags as "lo" (see show_smap_vma_flags), so I think you probably don't want this patch at all.

-Kees

Quoted 5 lines
fs/proc/task_mmu.c +0 -0
 			pgoff,
 			MAJOR(dev), MINOR(dev), ino);
 
Signature · 1 line
2.8.1
Signature · 1 line
Kees Cook                                            @outflux.net
maintainer
#7 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

In reply to Topi Miettinen

Hello,

Quoted 1 line · Topi Miettinen

Track maximum pids in the cgroup, present it in cgroup pids.current_max.

"max" is often used for maximum limits in cgroup. I think "watermark" or "high_watermark" would be a lot clearer.

kernel/cgroup_pids.c static void pids_free(struct task_struct *task) · line 255

Quoted 11 lines
kernel/cgroup_pids.c +7 -0
@@ -236,6 +246,14 @@ static void pids_free(struct task_struct *task)
 	pids_uncharge(pids, 1);
 }
 
+static void pids_fork(struct task_struct *task)
+{
+	struct pids_cgroup *pids = css_pids(task_css(task, pids_cgrp_id));
+
+	if (atomic64_read(&pids->cur_max) < atomic64_read(&pids->counter))
+		atomic64_set(&pids->cur_max, atomic64_read(&pids->counter));
+}

Wouldn't it make more sense to track high watermark from the charge functions instead? I don't get why this requires a separate fork callback. Also, racing atomic64_set's are racy. The counter can end up with a lower number than it should be.

kernel/cgroup_pids.c static struct cftype pids_files[] = { · line 330

Quoted 6 lines
kernel/cgroup_pids.c +2 -0
@@ -300,6 +326,11 @@ static struct cftype pids_files[] = {
 		.read_s64 = pids_current_read,
 		.flags = CFTYPE_NOT_ON_ROOT,
 	},
+	{
+		.name = "current_max",

Please make this "high_watermark" field in pids.stats file.

Thanks.

Signature · 1 line
tejun
#4 lore raw

Re: [RFC 01/18] capabilities: track actually used capabilities

In reply to Topi Miettinen
Quoted 12 lines · Topi Miettinen
Quoted 5 lines · Andy Lutomirski
Quoted 2 lines · Topi Miettinen

Track what capabilities are actually used and present the current situation in /proc/self/status.

What for?

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Quoted 8 lines

Currently, there is no way to know which capabilities are actually used. Even
the source code is only implicit, in-depth knowledge of each capability must be used when analyzing a program to judge which capabilities the program will
exercise."

Should I perhaps cite some of this in the commit?

Yes, but you should also clarify what users are supposed to do with this. Given ambient capabilities, I suspect that you'll find that your patch doesn't actually work very well. For example, if you run a shell script with ambient caps, then you won't notice caps used by short-lived helper processes.

Quoted 19 lines
Quoted 7 lines

What is the intended behavior on fork()? Whatever the intended behavior is, there should IMO be a selftest for it.

--Andy

The capabilities could be tracked from three points of daemon initialization sequence onwards:
fork()
setpcap()
exec()

fork() case would be logical as the /proc entry is per task. But if you consider the tools to set the capabilities (for example systemd unit files), there can be between fork() and exec() further preparations which need more capabilities than the program itself needs.

Quoted 4 lines

setpcap() is probably the real point after which we are interested if the capabilities are enough.

The amount of setup between setpcap() and exec() is probably very low.

When I asked "what is the intended behavior on fork()?", I mean "what should CapUsed be after fork()?". The answer should be about four words long and should have a test case. There should maybe also be an explanation of why the intended behavior is useful.

But, as I said above, I think that you may need to rethink this entirely to make it useful. You might need to do it per process tree or per cgroup or something.

--Andy

#26 lore raw

Re: [RFC 05/18] limits: track and present RLIMIT_NOFILE actual max

In reply to Andy Lutomirski
Quoted 7 lines · Andy Lutomirski
Quoted 2 lines · Topi Miettinen

Track maximum number of files for the process, present current maximum in /proc/self/limits.

The core part should be its own patch.

Also, you have this weirdly named (and racy!) function bump_rlimit.

I can change the name if you have better suggestions. rlimit_track_max?

The max value is written often but read seldom, if ever. What kind of locking should I use then?

Quoted 2 lines

Wouldn't this be nicer if you taught the rlimit code to track the *current* usage generically and to derive the max usage from that?

Current rlimit code performs checks against current limits. These are typically done early in the calling function and further checks could also fail. Thus max should not be updated until much later. Maybe these could be combined, but not easily if at all.

Quoted 16 lines
Quoted 6 lines
fs/proc/base.c +0 -0
index a11eb71..227997b 100644

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, · line 635

Quoted 8 lines
fs/proc/base.c +2 -2
@@ -630,8 +630,8 @@ static int proc_pid_limits(struct seq_file *m,
 struct pid_namespace *ns,
     /*
      * print the file header
      */
-       seq_printf(m, "%-25s %-20s %-20s %-10s\n",
-          "Limit", "Soft Limit", "Hard Limit", "Units");
+    seq_printf(m, "%-25s %-20s %-20s %-10s %-20s\n",
+           "Limit", "Soft Limit", "Hard Limit", "Units", "Max");

What existing programs, if any, does this break?

Using Debian codesearch for /limits" string, I'd check pam_limits and rtkit. The max values could be put into a new file if you prefer.

Quoted 48 lines
Quoted 47 lines
fs/proc/base.c +4 -2
     for (i = 0; i < RLIM_NLIMITS; i++) {
         if (rlim[i].rlim_cur == RLIM_INFINITY)
@@ -647,9 +647,11 @@ static int proc_pid_limits(struct seq_file *m,
 struct pid_namespace *ns,
             seq_printf(m, "%-20lu ", rlim[i].rlim_max);
 
         if (lnames[i].unit)
-            seq_printf(m, "%-10s\n", lnames[i].unit);
+            seq_printf(m, "%-10s", lnames[i].unit);
         else
-            seq_putc(m, '\n');
+            seq_printf(m, "%-10s", "");
+        seq_printf(m, "%-20lu\n",
+               task->signal->rlim_curmax[i]);
     }
 
     return 0;
include/linux/sched.h +1 -0
index 9c48a08..0150380 100644
@@ -782,6 +782,7 @@ struct signal_struct {
      * have no need to disable irqs.
      */
     struct rlimit rlim[RLIM_NLIMITS];
+    unsigned long rlim_curmax[RLIM_NLIMITS];
 
 #ifdef CONFIG_BSD_PROCESS_ACCT
     struct pacct_struct pacct;    /* per-process accounting

information */

include/linux/sched.h +6 -0
@@ -3376,6 +3377,12 @@ static inline unsigned long rlimit_max(unsigned
 int limit)
     return task_rlimit_max(current, limit);
 }
 
+static inline void bump_rlimit(unsigned int limit, unsigned long r)
+{
+    if (READ_ONCE(current->signal->rlim_curmax[limit]) < r)
+        current->signal->rlim_curmax[limit] = r;
+}
+
 #ifdef CONFIG_CPU_FREQ
 struct update_util_data {

void (*func)(struct update_util_data *data,

#27 lore raw

Re: [RFC 05/18] limits: track and present RLIMIT_NOFILE actual max

Quoted 5 lines · Topi Miettinen
Quoted 4 lines · Andy Lutomirski
Quoted 2 lines · Topi Miettinen

Track maximum number of files for the process, present current maximum in /proc/self/limits.

Quoted 8 lines
Quoted 3 lines

The core part should be its own patch.

Also, you have this weirdly named (and racy!) function bump_rlimit.

I can change the name if you have better suggestions. rlimit_track_max?

The max value is written often but read seldom, if ever. What kind of locking should I use then?

Possibly none, but WRITE_ONCE would be good as would a comment indicating that your code in intentionally racy. Or you could use atomic_cmpxchg if that won't kill performance.

rlimit_track_max sounds like a better name to me.

Quoted 8 lines
Quoted 3 lines

Wouldn't this be nicer if you taught the rlimit code to track the *current* usage generically and to derive the max usage from that?

Current rlimit code performs checks against current limits. These are typically done early in the calling function and further checks could also fail. Thus max should not be updated until much later. Maybe these could be combined, but not easily if at all.

I mean: why not actually show the current value in /proc/pid/limits and track the max via whatever teaches proc about the current value?

Quoted 18 lines
Quoted 17 lines
Quoted 7 lines
fs/proc/base.c +0 -0
index a11eb71..227997b 100644

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, · line 635

Quoted 8 lines
fs/proc/base.c +2 -2
@@ -630,8 +630,8 @@ static int proc_pid_limits(struct seq_file *m,
 struct pid_namespace *ns,
     /*
      * print the file header
      */
-       seq_printf(m, "%-25s %-20s %-20s %-10s\n",
-          "Limit", "Soft Limit", "Hard Limit", "Units");
+    seq_printf(m, "%-25s %-20s %-20s %-10s %-20s\n",
+           "Limit", "Soft Limit", "Hard Limit", "Units", "Max");

What existing programs, if any, does this break?

Quoted 2 lines

Using Debian codesearch for /limits" string, I'd check pam_limits and rtkit. The max values could be put into a new file if you prefer.

If it actually breaks them, then you need to change the patch so you don't break them.

#41 lore raw

Re: [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max

In reply to Alex Williamson
Quoted 34 lines · Alex Williamson
Quoted 21 lines · On Mon, 13 Jun 2016 22:44:19 +0300 Topi Miettinen <[email protected]> wrote:

Track maximum size of locked memory, presented in /proc/self/limits.

---
 arch/ia64/kernel/perfmon.c                 |  1 +
 arch/powerpc/kvm/book3s_64_vio.c           |  1 +
 arch/powerpc/mm/mmu_context_iommu.c        |  1 +
 drivers/infiniband/core/umem.c             |  1 +
 drivers/infiniband/hw/hfi1/user_pages.c    |  1 +
 drivers/infiniband/hw/qib/qib_user_pages.c |  1 +
 drivers/infiniband/hw/usnic/usnic_uiom.c   |  2 ++
 drivers/misc/mic/scif/scif_rma.c           |  1 +
 drivers/vfio/vfio_iommu_spapr_tce.c        |  2 ++
 drivers/vfio/vfio_iommu_type1.c            |  2 ++
 include/linux/sched.h                      | 10 ++++++++--
 kernel/bpf/syscall.c                       |  6 ++++++
 kernel/events/core.c                       |  1 +
 mm/mlock.c                                 |  7 +++++++
 mm/mmap.c                                  |  3 +++
 mm/mremap.c                                |  3 +++
 16 files changed, 41 insertions(+), 2 deletions(-)

...

Quoted 9 lines
drivers/vfio/vfio_iommu_type1.c +0 -0
index 2ba1942..4c6e7a3 100644
@@ -312,6 +312,8 @@ static long vfio_pin_pages(unsigned long vaddr, long npage,
 		}
 	}
 
Quoted 11 lines

drivers/vfio/vfio_iommu_type1.c static long vfio_pin_pages(unsigned long vaddr, long npage, · line 319

Quoted 5 lines
drivers/vfio/vfio_iommu_type1.c +2 -0
+	bump_rlimit(RLIMIT_MEMLOCK, (current->mm->locked_vm + i) << PAGE_SHIFT);
+
 	if (!rsvd)
 		vfio_lock_acct(i);
 

Not all cases passing through here bump rlimit (see: rsvd), there's an entire case above the other end of this closing bracket that does bump rlimit but returns before here, and I wonder why we wouldn't just do this in our vfio_lock_acct() accounting function anyway. Thanks,

Yes, just make disable_hugepages case go to end of function.

-Topi

Quoted 3 lines

Alex

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#8 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

In reply to Tejun Heo
Quoted 7 lines · Tejun Heo

Hello,

Quoted 1 line · Topi Miettinen

Track maximum pids in the cgroup, present it in cgroup pids.current_max.

"max" is often used for maximum limits in cgroup. I think "watermark" or "high_watermark" would be a lot clearer.

OK, I have no preference.

Quoted 5 lines
Quoted 5 lines
kernel/cgroup_pids.c +0 -0
@@ -236,6 +246,14 @@ static void pids_free(struct task_struct *task)
 	pids_uncharge(pids, 1);
 }
 
Quoted 13 lines

kernel/cgroup_pids.c static void pids_free(struct task_struct *task) · line 255

Quoted 7 lines
kernel/cgroup_pids.c +7 -0
+static void pids_fork(struct task_struct *task)
+{
+	struct pids_cgroup *pids = css_pids(task_css(task, pids_cgrp_id));
+
+	if (atomic64_read(&pids->cur_max) < atomic64_read(&pids->counter))
+		atomic64_set(&pids->cur_max, atomic64_read(&pids->counter));
+}

Wouldn't it make more sense to track high watermark from the charge functions instead? I don't get why this requires a separate fork callback. Also, racing atomic64_set's are racy. The counter can end up with a lower number than it should be.

I used fork callback as I don't want to lower the watermark in all cases where the charge can be lowered, so I'd update the watermark only when the fork really happens.

Is there a better way to compare and set? I don't think atomic_cmpxchg() does what's needed,

Quoted 11 lines

kernel/cgroup_pids.c static struct cftype pids_files[] = { · line 330

Quoted 6 lines
kernel/cgroup_pids.c +2 -0
@@ -300,6 +326,11 @@ static struct cftype pids_files[] = {
 		.read_s64 = pids_current_read,
 		.flags = CFTYPE_NOT_ON_ROOT,
 	},
+	{
+		.name = "current_max",

Please make this "high_watermark" field in pids.stats file.

Thanks.

OK.

-Topi

maintainer
#9 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

Hello,

Quoted 3 lines · Topi Miettinen

I used fork callback as I don't want to lower the watermark in all cases where the charge can be lowered, so I'd update the watermark only when the fork really happens.

I don't think that would make a noticeable difference. That's where we decide whether to grant fork or not after all and thus where the actual usage is.

Quoted 2 lines

Is there a better way to compare and set? I don't think atomic_cmpxchg() does what's needed,

cmpxchg loop should do what's necessary although I'm not sure how much being strictly correct matters here.

Thanks.

Signature · 1 line
tejun
#5 lore raw

Re: [RFC 01/18] capabilities: track actually used capabilities

In reply to Andy Lutomirski
Quoted 20 lines · Andy Lutomirski
Quoted 19 lines · Topi Miettinen
Quoted 5 lines · Andy Lutomirski
Quoted 2 lines · Topi Miettinen

Track what capabilities are actually used and present the current situation in /proc/self/status.

What for?

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even
the source code is only implicit, in-depth knowledge of each capability must be used when analyzing a program to judge which capabilities the program will
exercise."

Quoted 8 lines
Quoted 1 line

Should I perhaps cite some of this in the commit?

Yes, but you should also clarify what users are supposed to do with this. Given ambient capabilities, I suspect that you'll find that your patch doesn't actually work very well. For example, if you run a shell script with ambient caps, then you won't notice caps used by short-lived helper processes.

Right, I suppose this model works well only within a single process, or where the helper processes are always unprivileged (like Xorg runs xkbcomp) or less privileged.

Quoted 22 lines
Quoted 22 lines
Quoted 7 lines

What is the intended behavior on fork()? Whatever the intended behavior is, there should IMO be a selftest for it.

--Andy

The capabilities could be tracked from three points of daemon initialization sequence onwards:
fork()
setpcap()
exec()

fork() case would be logical as the /proc entry is per task. But if you consider the tools to set the capabilities (for example systemd unit files), there can be between fork() and exec() further preparations which need more capabilities than the program itself needs.

setpcap() is probably the real point after which we are interested if the capabilities are enough.

Quoted 6 lines
Quoted 1 line

The amount of setup between setpcap() and exec() is probably very low.

When I asked "what is the intended behavior on fork()?", I mean "what should CapUsed be after fork()?". The answer should be about four words long and should have a test case. There should maybe also be an explanation of why the intended behavior is useful.

In this model:
fork: no change
setpcap: no change
exec: reset

But I hadn't thought that much where the reset happens.

Quoted 7 lines

But, as I said above, I think that you may need to rethink this entirely to make it useful. You might need to do it per process tree or per cgroup or something.

--Andy

I'd actually prefer the cgroup approach. Though that's much more work than this simple patch which already gives somewhat useful information in limited cases (once the logic is correct).

-Topi

#10 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

In reply to Tejun Heo
Quoted 11 lines · Tejun Heo

Hello,

Quoted 3 lines · Topi Miettinen

I used fork callback as I don't want to lower the watermark in all cases where the charge can be lowered, so I'd update the watermark only when the fork really happens.

I don't think that would make a noticeable difference. That's where we decide whether to grant fork or not after all and thus where the actual usage is.

You mean, increment count on cgroup_can_fork()? But what if the fork() fails after that (signal_pending case)?

Quoted 8 lines
Quoted 2 lines

Is there a better way to compare and set? I don't think atomic_cmpxchg() does what's needed,

cmpxchg loop should do what's necessary although I'm not sure how much being strictly correct matters here.

Thanks.

These are not used for any decisions taken by kernel, but by the user. I have to say I don't know where's the line between strict correctness and less strict.

-Topi

maintainer
#11 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

Quoted 8 lines · Topi Miettinen
Quoted 7 lines · Tejun Heo

Hello,

Quoted 3 lines · Topi Miettinen

I used fork callback as I don't want to lower the watermark in all cases where the charge can be lowered, so I'd update the watermark only when the fork really happens.

Quoted 7 lines
Quoted 4 lines

I don't think that would make a noticeable difference. That's where we decide whether to grant fork or not after all and thus where the actual usage is.

You mean, increment count on cgroup_can_fork()? But what if the fork() fails after that (signal_pending case)?

That number isn't gonna deviate by any significant amount and the counter is to estimate what the limit should be set to to begin with. It's logical to collect how close the usage got to can_attach failure due to limit breach.

Quoted 9 lines
Quoted 5 lines
Quoted 2 lines

Is there a better way to compare and set? I don't think atomic_cmpxchg() does what's needed,

cmpxchg loop should do what's necessary although I'm not sure how much being strictly correct matters here.

These are not used for any decisions taken by kernel, but by the user. I have to say I don't know where's the line between strict correctness and less strict.

Provided that cmpxchg is done only when the counter needs to be actually updated, it's not gonna be noticeably expensive. Might as well make it correct.

Thanks.

Signature · 1 line
tejun
#36 lore raw

Re: [RFC 11/18] limits: track and present RLIMIT_NPROC actual max

In reply to Topi Miettinen
Quoted 16 lines · Topi Miettinen

Track maximum number of processes per user and present it in /proc/self/limits.

---
 fs/proc/base.c        | 4 ++++
 include/linux/sched.h | 1 +
 kernel/fork.c         | 5 +++++
 kernel/sys.c          | 5 +++++
 4 files changed, 15 insertions(+)
fs/proc/base.c +0 -0
index 1df4fc8..02576c6 100644

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns, · line 675

Quoted 6 lines
fs/proc/base.c +3 -0
@@ -670,6 +670,10 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 				seq_printf(m, "%-20lu\n", psecs);
 			}
 			break;
+		case RLIMIT_NPROC:
+			seq_printf(m, "%-20d\n",
+				   atomic_read(&task->real_cred->user->max_processes));

Don't you have to take an RCU read lock before dereferencing task->real_cred? And shouldn't this be done with __task_cred(task) instead of task->real_cred?

Quoted 37 lines
fs/proc/base.c +1 -0
+			break;
 		default:
 			seq_printf(m, "%-20lu\n",
 				   task->signal->rlim_curmax[i]);
include/linux/sched.h +1 -0
index 0150380..feb9bb7 100644
@@ -838,6 +838,7 @@ static inline int signal_group_exit(const struct signal_struct *sig)
 struct user_struct {
 	atomic_t __count;	/* reference count */
 	atomic_t processes;	/* How many processes does this user have? */
+	atomic_t max_processes;	/* How many processes has this user had at the same time? */
 	atomic_t sigpending;	/* How many pending signals does this user have? */
 #ifdef CONFIG_INOTIFY_USER
 	atomic_t inotify_watches; /* How many inotify watches does this user have? */
kernel/fork.c +5 -0
index 5c2c355..667290f 100644
@@ -1653,6 +1653,11 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	trace_task_newtask(p, clone_flags);
 	uprobe_copy_process(p, clone_flags);
 
+	if (atomic_read(&p->real_cred->user->max_processes) <
+	    atomic_read(&p->real_cred->user->processes))
+		atomic_set(&p->real_cred->user->max_processes,
+			   atomic_read(&p->real_cred->user->processes));
+
 	return p;
 
 bad_fork_cancel_cgroup:
kernel/sys.c +0 -0
index 6629f6f..955cf21 100644

kernel/sys.c static int set_user(struct cred *new) · line 446

Quoted 8 lines
kernel/sys.c +5 -0
@@ -439,6 +439,11 @@ static int set_user(struct cred *new)
 	else
 		current->flags &= ~PF_NPROC_EXCEEDED;
 
+	if (atomic_read(&new_user->max_processes) <
+	    atomic_read(&new_user->processes))
+		atomic_set(&new_user->max_processes,
+			   atomic_read(&new_user->processes));
+

Is this intentionally slightly racy? If so, it might be nice to have a comment here that documents that.

maintainer
#17 lore raw

Re: [RFC 03/18] memcontrol: present maximum used memory also for cgroup-v2

In reply to Topi Miettinen
Quoted 1 line · Topi Miettinen

Present maximum used memory in cgroup memory.current_max.

It would be really much more preferable to present the usecase in the patch description. It is true that this information is presented in the v1 API but the current policy is to export new knobs only when there is a reasonable usecase for it.

Quoted 66 lines
---
 include/linux/page_counter.h |  7 ++++++-
 mm/memcontrol.c              | 13 +++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)
include/linux/page_counter.h +6 -1
index 7e62920..be4de17 100644
@@ -9,9 +9,9 @@ struct page_counter {
 	atomic_long_t count;
 	unsigned long limit;
 	struct page_counter *parent;
+	unsigned long watermark;
 
 	/* legacy */
-	unsigned long watermark;
 	unsigned long failcnt;
 };
 
@@ -34,6 +34,11 @@ static inline unsigned long page_counter_read(struct page_counter *counter)
 	return atomic_long_read(&counter->count);
 }
 
+static inline unsigned long page_counter_read_watermark(struct page_counter *counter)
+{
+	return counter->watermark;
+}
+
 void page_counter_cancel(struct page_counter *counter, unsigned long nr_pages);
 void page_counter_charge(struct page_counter *counter, unsigned long nr_pages);
 bool page_counter_try_charge(struct page_counter *counter,
mm/memcontrol.c +13 -0
index 75e7440..5513771 100644
@@ -4966,6 +4966,14 @@ static u64 memory_current_read(struct cgroup_subsys_state *css,
 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
 }
 
+static u64 memory_current_max_read(struct cgroup_subsys_state *css,
+				   struct cftype *cft)
+{
+	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
+
+	return (u64)page_counter_read_watermark(&memcg->memory) * PAGE_SIZE;
+}
+
 static int memory_low_show(struct seq_file *m, void *v)
 {
 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
@@ -5179,6 +5187,11 @@ static struct cftype memory_files[] = {
 		.read_u64 = memory_current_read,
 	},
 	{
+		.name = "current_max",
+		.flags = CFTYPE_NOT_ON_ROOT,
+		.read_u64 = memory_current_max_read,
+	},
+	{
 		.name = "low",
 		.flags = CFTYPE_NOT_ON_ROOT,
 		.seq_show = memory_low_show,
Signature · 1 line
2.8.1
Signature · 2 lines
Michal Hocko
SUSE Labs
#30 lore raw

Re: [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current status

In reply to Topi Miettinen
Quoted 14 lines · Topi Miettinen

Present current cputimer status in /proc/self/limits.

fs/proc/base.c +9 -0
@@ -650,8 +650,30 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
+               switch (i) {
+               case RLIMIT_RTTIME:
+               case RLIMIT_CPU:
+                       if (rlim[i].rlim_max == RLIM_INFINITY)
+                               seq_printf(m, "%-20s\n", "-");
+                       else {
+                               unsigned long long utime, ptime;
+                               unsigned long psecs;
+                               struct task_cputime cputime;

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns, · line 668

Quoted 10 lines
fs/proc/base.c +10 -0
+
+                               thread_group_cputimer(task, &cputime);
+                               utime = cputime_to_expires(cputime.utime);
+                               ptime = utime + cputime_to_expires(cputime.stime);
+                               psecs = cputime_to_secs(ptime);
+                               if (i == RLIMIT_RTTIME)
+                                       psecs *= USEC_PER_SEC;
+                               seq_printf(m, "%-20lu\n", psecs);
+                       }
+                       break;

Let's keep rlimits file for rlimits.

#46 lore raw

Re: [RFC 14/18] limits: track RLIMIT_SIGPENDING actual max

In reply to Topi Miettinen
Quoted 13 lines · Topi Miettinen

Track maximum number of pending signals, presented in /proc/self/limits.

---
 kernel/signal.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/signal.c +0 -0
index 96e9bc4..c8fbccd 100644

kernel/signal.c __sigqueue_alloc(int sig, struct task_struct *t, gfp_t flags, int override_rlimi · line 391

Quoted 5 lines
kernel/signal.c +2 -0
@@ -387,6 +387,8 @@ __sigqueue_alloc(int sig, struct task_struct *t, gfp_t flags, int override_rlimi
 		INIT_LIST_HEAD(&q->list);
 		q->flags = 0;
 		q->user = user;
+		/* XXX resource limits apply per task, not per user */
+		bump_rlimit(RLIMIT_SIGPENDING, atomic_read(&user->sigpending));

Well, I have to admit that I too dislike the very idea of these changes...

But this particular patch looks wrong in any case. I wasn't cc'ed on the previous patches which add bump_rlimit(), but I have found

	"[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max"
	http://marc.info/?l=linux-fsdevel&m=146584742331072&w=2

and bump_rlimit() changes current->signal->rlim_curmax, while in this case you need to bump t->signal->rlim_curmax.

Oleg.

#28 lore raw

Re: [RFC 05/18] limits: track and present RLIMIT_NOFILE actual max

In reply to Andy Lutomirski
Quoted 25 lines · Andy Lutomirski
Quoted 5 lines · Topi Miettinen
Quoted 4 lines · Andy Lutomirski
Quoted 2 lines · Topi Miettinen

Track maximum number of files for the process, present current maximum in /proc/self/limits.

Quoted 8 lines
Quoted 3 lines

The core part should be its own patch.

Also, you have this weirdly named (and racy!) function bump_rlimit.

I can change the name if you have better suggestions. rlimit_track_max?

The max value is written often but read seldom, if ever. What kind of locking should I use then?

Possibly none, but WRITE_ONCE would be good as would a comment indicating that your code in intentionally racy. Or you could use atomic_cmpxchg if that won't kill performance.

rlimit_track_max sounds like a better name to me.

Quoted 4 lines
Quoted 3 lines

Wouldn't this be nicer if you taught the rlimit code to track the *current* usage generically and to derive the max usage from that?

Quoted 8 lines
Quoted 4 lines

Current rlimit code performs checks against current limits. These are typically done early in the calling function and further checks could also fail. Thus max should not be updated until much later. Maybe these could be combined, but not easily if at all.

I mean: why not actually show the current value in /proc/pid/limits and track the max via whatever teaches proc about the current value?

That could be interesting data too. In other comments, a new file was proposed and then your model would be good choice.

Quoted 24 lines
Quoted 18 lines
Quoted 17 lines
Quoted 7 lines
fs/proc/base.c +0 -0
index a11eb71..227997b 100644

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, · line 635

Quoted 8 lines
fs/proc/base.c +2 -2
@@ -630,8 +630,8 @@ static int proc_pid_limits(struct seq_file *m,
 struct pid_namespace *ns,
     /*
      * print the file header
      */
-       seq_printf(m, "%-25s %-20s %-20s %-10s\n",
-          "Limit", "Soft Limit", "Hard Limit", "Units");
+    seq_printf(m, "%-25s %-20s %-20s %-10s %-20s\n",
+           "Limit", "Soft Limit", "Hard Limit", "Units", "Max");

What existing programs, if any, does this break?

Quoted 2 lines

Using Debian codesearch for /limits" string, I'd check pam_limits and rtkit. The max values could be put into a new file if you prefer.

If it actually breaks them, then you need to change the patch so you don't break them.

#37 lore raw

Re: [RFC 11/18] limits: track and present RLIMIT_NPROC actual max

In reply to Jann Horn
Quoted 12 lines · Jann Horn
Quoted 11 lines · Topi Miettinen

Track maximum number of processes per user and present it in /proc/self/limits.

---
 fs/proc/base.c        | 4 ++++
 include/linux/sched.h | 1 +
 kernel/fork.c         | 5 +++++
 kernel/sys.c          | 5 +++++
 4 files changed, 15 insertions(+)
Quoted 13 lines

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns, · line 675

Quoted 11 lines
fs/proc/base.c +3 -0
index 1df4fc8..02576c6 100644
@@ -670,6 +670,10 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 				seq_printf(m, "%-20lu\n", psecs);
 			}
 			break;
+		case RLIMIT_NPROC:
+			seq_printf(m, "%-20d\n",
+				   atomic_read(&task->real_cred->user->max_processes));

Don't you have to take an RCU read lock before dereferencing task->real_cred?

In other comments in the series, cmpxchg loop was suggested, would that work here?

Quoted 1 line

And shouldn't this be done with __task_cred(task) instead of task->real_cred?

How about atomic_read(task_cred_xxx(task, user)->max_processes)?

Quoted 42 lines
Quoted 42 lines
fs/proc/base.c +1 -0
+			break;
 		default:
 			seq_printf(m, "%-20lu\n",
 				   task->signal->rlim_curmax[i]);
include/linux/sched.h +1 -0
index 0150380..feb9bb7 100644
@@ -838,6 +838,7 @@ static inline int signal_group_exit(const struct signal_struct *sig)
 struct user_struct {
 	atomic_t __count;	/* reference count */
 	atomic_t processes;	/* How many processes does this user have? */
+	atomic_t max_processes;	/* How many processes has this user had at the same time? */
 	atomic_t sigpending;	/* How many pending signals does this user have? */
 #ifdef CONFIG_INOTIFY_USER
 	atomic_t inotify_watches; /* How many inotify watches does this user have? */
kernel/fork.c +5 -0
index 5c2c355..667290f 100644
@@ -1653,6 +1653,11 @@ static struct task_struct *copy_process(unsigned long clone_flags,
 	trace_task_newtask(p, clone_flags);
 	uprobe_copy_process(p, clone_flags);
 
+	if (atomic_read(&p->real_cred->user->max_processes) <
+	    atomic_read(&p->real_cred->user->processes))
+		atomic_set(&p->real_cred->user->max_processes,
+			   atomic_read(&p->real_cred->user->processes));
+
 	return p;
 
 bad_fork_cancel_cgroup:
kernel/sys.c +0 -0
index 6629f6f..955cf21 100644
@@ -439,6 +439,11 @@ static int set_user(struct cred *new)
 	else
 		current->flags &= ~PF_NPROC_EXCEEDED;
 
Quoted 9 lines

kernel/sys.c static int set_user(struct cred *new) · line 446

Quoted 5 lines
kernel/sys.c +5 -0
+	if (atomic_read(&new_user->max_processes) <
+	    atomic_read(&new_user->processes))
+		atomic_set(&new_user->max_processes,
+			   atomic_read(&new_user->processes));
+

Is this intentionally slightly racy? If so, it might be nice to have a comment here that documents that.

I'd suppose cmpxchg loop could be used to avoid races.

-Topi

#18 lore raw

Re: [RFC 03/18] memcontrol: present maximum used memory also for cgroup-v2

In reply to Michal Hocko
Quoted 8 lines · Michal Hocko
Quoted 1 line · Topi Miettinen

Present maximum used memory in cgroup memory.current_max.

It would be really much more preferable to present the usecase in the patch description. It is true that this information is presented in the v1 API but the current policy is to export new knobs only when there is a reasonable usecase for it.

This was stated in the cover letter:
https://lkml.org/lkml/2016/6/13/857

"There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby."

"Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the current tasks and memory status can be easily seen with ps(1). However, any transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no universal method. Program sources typically give no useful indication about memory use or how many tasks there could be."

I can add some of this to the commit message, is that sufficient for you?

Quoted 67 lines
Quoted 66 lines
---
 include/linux/page_counter.h |  7 ++++++-
 mm/memcontrol.c              | 13 +++++++++++++
 2 files changed, 19 insertions(+), 1 deletion(-)
include/linux/page_counter.h +6 -1
index 7e62920..be4de17 100644
@@ -9,9 +9,9 @@ struct page_counter {
 	atomic_long_t count;
 	unsigned long limit;
 	struct page_counter *parent;
+	unsigned long watermark;
 
 	/* legacy */
-	unsigned long watermark;
 	unsigned long failcnt;
 };
 
@@ -34,6 +34,11 @@ static inline unsigned long page_counter_read(struct page_counter *counter)
 	return atomic_long_read(&counter->count);
 }
 
+static inline unsigned long page_counter_read_watermark(struct page_counter *counter)
+{
+	return counter->watermark;
+}
+
 void page_counter_cancel(struct page_counter *counter, unsigned long nr_pages);
 void page_counter_charge(struct page_counter *counter, unsigned long nr_pages);
 bool page_counter_try_charge(struct page_counter *counter,
mm/memcontrol.c +13 -0
index 75e7440..5513771 100644
@@ -4966,6 +4966,14 @@ static u64 memory_current_read(struct cgroup_subsys_state *css,
 	return (u64)page_counter_read(&memcg->memory) * PAGE_SIZE;
 }
 
+static u64 memory_current_max_read(struct cgroup_subsys_state *css,
+				   struct cftype *cft)
+{
+	struct mem_cgroup *memcg = mem_cgroup_from_css(css);
+
+	return (u64)page_counter_read_watermark(&memcg->memory) * PAGE_SIZE;
+}
+
 static int memory_low_show(struct seq_file *m, void *v)
 {
 	struct mem_cgroup *memcg = mem_cgroup_from_css(seq_css(m));
@@ -5179,6 +5187,11 @@ static struct cftype memory_files[] = {
 		.read_u64 = memory_current_read,
 	},
 	{
+		.name = "current_max",
+		.flags = CFTYPE_NOT_ON_ROOT,
+		.read_u64 = memory_current_max_read,
+	},
+	{
 		.name = "low",
 		.flags = CFTYPE_NOT_ON_ROOT,
 		.seq_show = memory_low_show,
Signature · 1 line
2.8.1
#47 lore raw

Re: [RFC 14/18] limits: track RLIMIT_SIGPENDING actual max

In reply to Oleg Nesterov
Quoted 22 lines · Oleg Nesterov
Quoted 13 lines · Topi Miettinen

Track maximum number of pending signals, presented in /proc/self/limits.

---
 kernel/signal.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/signal.c +0 -0
index 96e9bc4..c8fbccd 100644

kernel/signal.c __sigqueue_alloc(int sig, struct task_struct *t, gfp_t flags, int override_rlimi · line 391

Quoted 5 lines
kernel/signal.c +2 -0
@@ -387,6 +387,8 @@ __sigqueue_alloc(int sig, struct task_struct *t, gfp_t flags, int override_rlimi
 		INIT_LIST_HEAD(&q->list);
 		q->flags = 0;
 		q->user = user;
+		/* XXX resource limits apply per task, not per user */
+		bump_rlimit(RLIMIT_SIGPENDING, atomic_read(&user->sigpending));

Well, I have to admit that I too dislike the very idea of these changes...

Quoted 6 lines

But this particular patch looks wrong in any case. I wasn't cc'ed on the previous patches which add bump_rlimit(), but I have found

	"[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max"
	http://marc.info/?l=linux-fsdevel&m=146584742331072&w=2

I used git send-email --cc-cmd=scripts/get_maintainer.pl to generate the CC lists. Is there a better way?

Quoted 5 lines

and bump_rlimit() changes current->signal->rlim_curmax, while in this case you need to bump t->signal->rlim_curmax.

Oleg.

Yes, I also added task_bump_rlimit() which would be better choice here.

-Topi

maintainer
#19 lore raw

Re: [RFC 03/18] memcontrol: present maximum used memory also for cgroup-v2

In reply to Topi Miettinen
Quoted 26 lines · Topi Miettinen
Quoted 8 lines · Michal Hocko
Quoted 1 line · Topi Miettinen

Present maximum used memory in cgroup memory.current_max.

It would be really much more preferable to present the usecase in the patch description. It is true that this information is presented in the v1 API but the current policy is to export new knobs only when there is a reasonable usecase for it.

This was stated in the cover letter:
https://lkml.org/lkml/2016/6/13/857

"There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby."

"Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

Quoted 8 lines

For tasks and memory cgroup limits the situation is somewhat better as the current tasks and memory status can be easily seen with ps(1). However, any transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no universal method. Program sources typically give no useful indication about memory use or how many tasks there could be."

I can add some of this to the commit message, is that sufficient for you?

It's useful to have a short summary of the justification in each patch as well. Other than that it's fine to be broader and more detailed about your motivation in the coverletter.

I didn't catch the coverletter, though. It makes sense to CC recipients of any of those patches on the full series, including the cover, since even though we are specialized in certain areas of the code, many of us are interested in the whole picture of addressing a problem, and not just the few bits in our area without more context.

As far as the memcg part of this series goes, one concern is that page cache is trimmed back only when there is pressure, so in all but very few cases the high watermark you are introducing will be pegged to the configured limit. It doesn't give a whole lot of insight.

But there are consumers that are less/not compressible than cache, such as anonymous memory, unreclaimable slab, maybe socket buffers etc. Having spikes in those slip through two sampling points is an issue, indeed. Adding consumer-specific watermarks might be useful.

Thanks

#20 lore raw

Re: [RFC 03/18] memcontrol: present maximum used memory also for cgroup-v2

Quoted 40 lines · Johannes Weiner
Quoted 26 lines · Topi Miettinen
Quoted 8 lines · Michal Hocko
Quoted 1 line · Topi Miettinen

Present maximum used memory in cgroup memory.current_max.

It would be really much more preferable to present the usecase in the patch description. It is true that this information is presented in the v1 API but the current policy is to export new knobs only when there is a reasonable usecase for it.

This was stated in the cover letter:
https://lkml.org/lkml/2016/6/13/857

"There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby."

"Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

Quoted 8 lines

For tasks and memory cgroup limits the situation is somewhat better as the current tasks and memory status can be easily seen with ps(1). However, any transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no universal method. Program sources typically give no useful indication about memory use or how many tasks there could be."

I can add some of this to the commit message, is that sufficient for you?

It's useful to have a short summary of the justification in each patch as well. Other than that it's fine to be broader and more detailed about your motivation in the coverletter.

Quoted 6 lines

I didn't catch the coverletter, though. It makes sense to CC recipients of any of those patches on the full series, including the cover, since even though we are specialized in certain areas of the code, many of us are interested in the whole picture of addressing a problem, and not just the few bits in our area without more context.

Thank you for this nice explanation. I suppose "git send-email --cc-cmd=scripts/get_maintainer.pl" doesn't do this.

Quoted 5 lines

As far as the memcg part of this series goes, one concern is that page cache is trimmed back only when there is pressure, so in all but very few cases the high watermark you are introducing will be pegged to the configured limit. It doesn't give a whole lot of insight.

So using the high watermark would not give a very useful starting point for the user who wished to configure the memory limit? What else could be used instead?

Quoted 7 lines

But there are consumers that are less/not compressible than cache, such as anonymous memory, unreclaimable slab, maybe socket buffers etc. Having spikes in those slip through two sampling points is an issue, indeed. Adding consumer-specific watermarks might be useful.

Thanks

OK, but there's no limiting or tuning mechanism in place for now for those, or is there? How could the results be used?

-Topi

#55 lore raw
In reply to Topi Miettinen

I don't like the idea of this patchset.

All limitations are context dependent and that context changes rapidly. You'll never dump enough information for predicting future errors or investigating reson of errors in past. You could try to reproduce all kernel logic but model always will be aproximate.

If you want to track origin of failures in user space applications when it hits some limit you should track errors. For example rlimits and other limitation subsystems could provide resonable amount of tracepoints which could tell what exactly happened before error. If you need highwater of some values you could track it in userspace, or maybe tracing subsystem could provide postpocessing for tracepoint parameters. Anyway, systemtap and other monsters can do this right now.

Quoted 66 lines · Topi Miettinen

Hello,

There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even the source code is only implicit, in-depth knowledge of each capability must be used when analyzing a program to judge which capabilities the program will exercise.

Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the current tasks and memory status can be easily seen with ps(1). However, any transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no universal method. Program sources typically give no useful indication about memory use or how many tasks there could be.

Resource limits
[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current [RFC 07/18] limits: track RLIMIT_FSIZE actual max
[RFC 08/18] limits: track RLIMIT_DATA actual max
[RFC 09/18] limits: track RLIMIT_CORE actual max
[RFC 10/18] limits: track RLIMIT_STACK actual max
[RFC 11/18] limits: track and present RLIMIT_NPROC actual max [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max [RFC 13/18] limits: track RLIMIT_AS actual max
[RFC 14/18] limits: track RLIMIT_SIGPENDING actual max [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max [RFC 16/18] limits: track RLIMIT_NICE actual max
[RFC 17/18] limits: track RLIMIT_RTPRIO actual max
[RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

Current number of files and current VM usage (data pages, address space size) could be calculated from available /proc files. Again, any temporarily higher values could be easily missed. For many limits, there is no way to see what is the current situation and source code is mostly useless.

As a side note, the resouce limits seem to be in bad shape. For example, RLIMIT_MEMLOCK is used incoherently and I think VM statistics can miss some changes. Adding RLIMIT_CODE could be useful.

The current maximum values for the resource limits are now shown in /proc/task/limits. If this is deemed too confusing for the existing programs which rely on the exact format, I can change that to a new file.

Finally, the patches work in my testing but I have probably missed finer lock/RCU details.

-Topi

#56 lore raw
Quoted 7 lines · Konstantin Khlebnikov

I don't like the idea of this patchset.

All limitations are context dependent and that context changes rapidly. You'll never dump enough information for predicting future errors or investigating reson of errors in past. You could try to reproduce all kernel logic but model always will be aproximate.

But that is true regardless of how the starting point for the limits was determined. There will be always a possibility of setting too tight limits which may work for a couple of test runs but which could also eventually fail. The opposite is also possible, to use too loose limits which are not effective. That's the way with limits in any case.

Quoted 8 lines

If you want to track origin of failures in user space applications when it hits some limit you should track errors. For example rlimits and other limitation subsystems could provide resonable amount of tracepoints which could tell what exactly happened before error. If you need highwater of some values you could track it in userspace, or maybe tracing subsystem could provide postpocessing for tracepoint parameters. Anyway, systemtap and other monsters can do this right now.

Those tools could help improving the starting point. But how could they give exact value for that?

With this patch set, the user can just look at files in /proc and simply copy the values to a config file as a starting point. What would be the work flow with the tracepoint approach?

Quoted 67 lines · Topi Miettinen
Quoted 66 lines

Hello,

There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even the source code is only implicit, in-depth knowledge of each capability must be used when analyzing a program to judge which capabilities the program will exercise.

Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the current tasks and memory status can be easily seen with ps(1). However, any transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no universal method. Program sources typically give no useful indication about memory use or how many tasks there could be.

Resource limits
[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current [RFC 07/18] limits: track RLIMIT_FSIZE actual max
[RFC 08/18] limits: track RLIMIT_DATA actual max
[RFC 09/18] limits: track RLIMIT_CORE actual max
[RFC 10/18] limits: track RLIMIT_STACK actual max
[RFC 11/18] limits: track and present RLIMIT_NPROC actual max [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max [RFC 13/18] limits: track RLIMIT_AS actual max
[RFC 14/18] limits: track RLIMIT_SIGPENDING actual max [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max [RFC 16/18] limits: track RLIMIT_NICE actual max
[RFC 17/18] limits: track RLIMIT_RTPRIO actual max
[RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

Current number of files and current VM usage (data pages, address space size) could be calculated from available /proc files. Again, any temporarily higher values could be easily missed. For many limits, there is no way to see what is the current situation and source code is mostly useless.

As a side note, the resouce limits seem to be in bad shape. For example, RLIMIT_MEMLOCK is used incoherently and I think VM statistics can miss some changes. Adding RLIMIT_CODE could be useful.

The current maximum values for the resource limits are now shown in /proc/task/limits. If this is deemed too confusing for the existing programs which rely on the exact format, I can change that to a new file.

Finally, the patches work in my testing but I have probably missed finer lock/RCU details.

-Topi

#38 lore raw

Re: [RFC 11/18] limits: track and present RLIMIT_NPROC actual max

In reply to Topi Miettinen
Quoted 27 lines · Topi Miettinen
Quoted 12 lines · Jann Horn
Quoted 11 lines · Topi Miettinen

Track maximum number of processes per user and present it in /proc/self/limits.

---
 fs/proc/base.c        | 4 ++++
 include/linux/sched.h | 1 +
 kernel/fork.c         | 5 +++++
 kernel/sys.c          | 5 +++++
 4 files changed, 15 insertions(+)
Quoted 13 lines

fs/proc/base.c static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns, · line 675

Quoted 11 lines
fs/proc/base.c +3 -0
index 1df4fc8..02576c6 100644
@@ -670,6 +670,10 @@ static int proc_pid_limits(struct seq_file *m, struct pid_namespace *ns,
 				seq_printf(m, "%-20lu\n", psecs);
 			}
 			break;
+		case RLIMIT_NPROC:
+			seq_printf(m, "%-20d\n",
+				   atomic_read(&task->real_cred->user->max_processes));

Don't you have to take an RCU read lock before dereferencing task->real_cred?

Quoted 2 lines

In other comments in the series, cmpxchg loop was suggested, would that work here?

What would a cmpxchg loop have to do with missing RCU locking?

Quoted 3 lines
Quoted 1 line

And shouldn't this be done with __task_cred(task) instead of task->real_cred?

How about atomic_read(task_cred_xxx(task, user)->max_processes)?

No. You'd still end up dereferencing max_processes in the user_struct without any guarantee that it hasn't been freed. I think the code should look this way:

    case RLIMIT_NPROC:
        rcu_read_lock();
        seq_printf(m, "%-20d\n",
            atomic_read(&__task_cred(task)->user->max_processes));
        rcu_read_unlock();
        break;
#57 lore raw
In reply to Konstantin Khlebnikov
Quoted 6 lines · Konstantin Khlebnikov

I don't like the idea of this patchset.

All limitations are context dependent and that context changes rapidly. You'll never dump enough information for predicting future errors or investigating reson of errors in past. You could try to reproduce all kernel logic but model always will be aproximate.

It's still better than what we have now, and there is one particular use for the cgroup stuff that I find intriguing, you can create a cgroup, populate it, set no limits, and then run a simulated workload against it and see how it reacts. This in general will probably provide a better starting point for what to actually set the limits to than just making an arbitrary guess. Certain applications in particular come to mind which will just hang when they can't start a new thread or process (Dropbox is particularly guilty of this). In such cases, setting the limit too low doesn't result in a crash, it results in the program just not appearing to work yet still running otherwise normally.

In general, I could see the rlimit stuff being in the same situation, it's not for figuring out why something failed (good software will tell you somewhere), but figuring out limits so it doesn't fail but still is reasonably contained. A lot of things that seem at face value like they shouldn't need specific exceptions to limits do. Most normal users probably wouldn't guess that acpid needs a RLIMIT_NPROC count of at least 4 or more to work with the default rules. Similarly, there's probably not many normal users who know that the Dropbox daemon spawns an insanely large thread pool and preallocates significant amounts of memory and will just hang if either of these fail. By having a way to get running max counts of resource usage, it makes it easier for people to know what the minimum limit they need to put on something is.

Quoted 7 lines

If you want to track origin of failures in user space applications when it hits some limit you should track errors. For example rlimits and other limitation subsystems could provide resonable amount of tracepoints which could tell what exactly happened before error. If you need highwater of some values you could track it in userspace, or maybe tracing subsystem could provide postpocessing for tracepoint parameters. Anyway, systemtap and other monsters can do this right now.

Userspace tracking of some things just isn't practical. Take RLIMIT_NPROC for example. There's not really any reliable way to track this from userspace without modifying the process which is being tracked, which is not a user friendly way of doing things, and in some cases is functionally impossible for an end user to do.

Quoted 68 lines · Topi Miettinen
Quoted 66 lines

Hello,

There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even the source code is only implicit, in-depth knowledge of each capability must be used when analyzing a program to judge which capabilities the program will exercise.

Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the current tasks and memory status can be easily seen with ps(1). However, any transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no universal method. Program sources typically give no useful indication about memory use or how many tasks there could be.

Resource limits
[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current [RFC 07/18] limits: track RLIMIT_FSIZE actual max
[RFC 08/18] limits: track RLIMIT_DATA actual max
[RFC 09/18] limits: track RLIMIT_CORE actual max
[RFC 10/18] limits: track RLIMIT_STACK actual max
[RFC 11/18] limits: track and present RLIMIT_NPROC actual max [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max [RFC 13/18] limits: track RLIMIT_AS actual max
[RFC 14/18] limits: track RLIMIT_SIGPENDING actual max [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max [RFC 16/18] limits: track RLIMIT_NICE actual max
[RFC 17/18] limits: track RLIMIT_RTPRIO actual max
[RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

Current number of files and current VM usage (data pages, address space size) could be calculated from available /proc files. Again, any temporarily higher values could be easily missed. For many limits, there is no way to see what is the current situation and source code is mostly useless.

As a side note, the resouce limits seem to be in bad shape. For example, RLIMIT_MEMLOCK is used incoherently and I think VM statistics can miss some changes. Adding RLIMIT_CODE could be useful.

The current maximum values for the resource limits are now shown in /proc/task/limits. If this is deemed too confusing for the existing programs which rely on the exact format, I can change that to a new file.

Finally, the patches work in my testing but I have probably missed finer lock/RCU details.

-Topi

maintainer
#21 lore raw

Re: [RFC 03/18] memcontrol: present maximum used memory also for cgroup-v2

In reply to Topi Miettinen
Quoted 1 line · Topi Miettinen

On 06/14/16 16:04, Johannes Weiner wrote:

[...]

Quoted 9 lines
Quoted 6 lines

I didn't catch the coverletter, though. It makes sense to CC recipients of any of those patches on the full series, including the cover, since even though we are specialized in certain areas of the code, many of us are interested in the whole picture of addressing a problem, and not just the few bits in our area without more context.

Thank you for this nice explanation. I suppose "git send-email --cc-cmd=scripts/get_maintainer.pl" doesn't do this.

No it doesn't. What I do for this kind of series is the following. Put an explicit CC (acked, reviews etc...) to each patch. git format-patch $RANGE and then

$ git send-email --cc-cmd=./cc-cmd-only-cover.sh $DEFAULT_TO_CC --compose *.patch
$ cat cc-cmd-only-cover.sh
#!/bin/bash

if [[ $1 == *gitsendemail.msg* || $1 == *cover-letter* ]]; then

        grep '<.*@.*>' -h *.patch | sed 's/^.*: //' | sort | uniq

fi

A bit error prone because you have to cleanup any previous patch files from the directory but works more or less well for me.

s

Quoted 9 lines
Quoted 5 lines

As far as the memcg part of this series goes, one concern is that page cache is trimmed back only when there is pressure, so in all but very few cases the high watermark you are introducing will be pegged to the configured limit. It doesn't give a whole lot of insight.

So using the high watermark would not give a very useful starting point for the user who wished to configure the memory limit? What else could be used instead?

we have an event notification mechanism. In v1 it is vmpressure and v2 you will get a notification when the high/max limit is hit or when we hit the oom.

Signature · 2 lines
Michal Hocko
SUSE Labs
maintainer
#23 lore raw

Re: [RFC 04/18] device_cgroup: track and present accessed devices

In reply to Topi Miettinen
Quoted 20 lines · Topi Miettinen

Track what devices are accessed and present them cgroup devices.accessed.

---
 security/device_cgroup.c | 70 +++++++++++++++++++++++++++++++++++++++++-------
 1 file changed, 60 insertions(+), 10 deletions(-)
security/device_cgroup.c +1 -0
index 03c1652..45aa730 100644
@@ -48,6 +48,7 @@ struct dev_exception_item {
 struct dev_cgroup {
 	struct cgroup_subsys_state css;
 	struct list_head exceptions;
+	struct list_head accessed;
 	enum devcg_behavior behavior;
 };
 

security/device_cgroup.c free_and_exit: · line 95

Quoted 6 lines
security/device_cgroup.c +1 -1
@@ -90,7 +91,7 @@ free_and_exit:
 /*
  * called under devcgroup_mutex
  */
-static int dev_exception_add(struct dev_cgroup *dev_cgroup,
+static int dev_exception_add(struct list_head *exceptions,
 			     struct dev_exception_item *ex)

If you're going to re-use this function for the accessed list, then it should be renamed, bc as it is it's misleading.

It also should be restructured. The add-exceptions case was rare, so doing kmemdup before checking for duplicates was ok. But for the accessed list I think we want to check for duplicates before we kmemdup.

Quoted 169 lines
security/device_cgroup.c +58 -9
 {
 	struct dev_exception_item *excopy, *walk;
@@ -101,7 +102,7 @@ static int dev_exception_add(struct dev_cgroup *dev_cgroup,
 	if (!excopy)
 		return -ENOMEM;
 
-	list_for_each_entry(walk, &dev_cgroup->exceptions, list) {
+	list_for_each_entry(walk, exceptions, list) {
 		if (walk->type != ex->type)
 			continue;
 		if (walk->major != ex->major)
@@ -115,7 +116,7 @@ static int dev_exception_add(struct dev_cgroup *dev_cgroup,
 	}
 
 	if (excopy != NULL)
-		list_add_tail_rcu(&excopy->list, &dev_cgroup->exceptions);
+		list_add_tail_rcu(&excopy->list, exceptions);
 	return 0;
 }
 
@@ -155,6 +156,16 @@ static void __dev_exception_clean(struct dev_cgroup *dev_cgroup)
 	}
 }
 
+static void dev_accessed_clean(struct dev_cgroup *dev_cgroup)
+{
+	struct dev_exception_item *ex, *tmp;
+
+	list_for_each_entry_safe(ex, tmp, &dev_cgroup->accessed, list) {
+		list_del_rcu(&ex->list);
+		kfree_rcu(ex, rcu);
+	}
+}
+
 /**
  * dev_exception_clean - frees all entries of the exception list
  * @dev_cgroup: dev_cgroup with the exception list to be cleaned
@@ -221,6 +232,7 @@ devcgroup_css_alloc(struct cgroup_subsys_state *parent_css)
 	if (!dev_cgroup)
 		return ERR_PTR(-ENOMEM);
 	INIT_LIST_HEAD(&dev_cgroup->exceptions);
+	INIT_LIST_HEAD(&dev_cgroup->accessed);
 	dev_cgroup->behavior = DEVCG_DEFAULT_NONE;
 
 	return &dev_cgroup->css;
@@ -231,6 +243,7 @@ static void devcgroup_css_free(struct cgroup_subsys_state *css)
 	struct dev_cgroup *dev_cgroup = css_to_devcgroup(css);
 
 	__dev_exception_clean(dev_cgroup);
+	dev_accessed_clean(dev_cgroup);
 	kfree(dev_cgroup);
 }
 
@@ -272,9 +285,9 @@ static void set_majmin(char *str, unsigned m)
 		sprintf(str, "%u", m);
 }
 
-static int devcgroup_seq_show(struct seq_file *m, void *v)
+static int devcgroup_seq_show_list(struct seq_file *m, struct dev_cgroup *devcgroup,
+				   struct list_head *exceptions, bool allow)
 {
-	struct dev_cgroup *devcgroup = css_to_devcgroup(seq_css(m));
 	struct dev_exception_item *ex;
 	char maj[MAJMINLEN], min[MAJMINLEN], acc[ACCLEN];
 
@@ -285,14 +298,14 @@ static int devcgroup_seq_show(struct seq_file *m, void *v)
 	 * - List the exceptions in case the default policy is to deny
 	 * This way, the file remains as a "whitelist of devices"
 	 */
-	if (devcgroup->behavior == DEVCG_DEFAULT_ALLOW) {
+	if (allow) {
 		set_access(acc, ACC_MASK);
 		set_majmin(maj, ~0);
 		set_majmin(min, ~0);
 		seq_printf(m, "%c %s:%s %s\n", type_to_char(DEV_ALL),
 			   maj, min, acc);
 	} else {
-		list_for_each_entry_rcu(ex, &devcgroup->exceptions, list) {
+		list_for_each_entry_rcu(ex, exceptions, list) {
 			set_access(acc, ex->access);
 			set_majmin(maj, ex->major);
 			set_majmin(min, ex->minor);
@@ -305,6 +318,36 @@ static int devcgroup_seq_show(struct seq_file *m, void *v)
 	return 0;
 }
 
+static int devcgroup_seq_show(struct seq_file *m, void *v)
+{
+	struct dev_cgroup *devcgroup = css_to_devcgroup(seq_css(m));
+
+	return devcgroup_seq_show_list(m, devcgroup, &devcgroup->exceptions,
+				       devcgroup->behavior == DEVCG_DEFAULT_ALLOW);
+}
+
+static int devcgroup_seq_show_accessed(struct seq_file *m, void *v)
+{
+	struct dev_cgroup *devcgroup = css_to_devcgroup(seq_css(m));
+
+	return devcgroup_seq_show_list(m, devcgroup, &devcgroup->accessed, false);
+}
+
+static void devcgroup_add_accessed(struct dev_cgroup *dev_cgroup, short type,
+				   u32 major, u32 minor, short access)
+{
+	struct dev_exception_item ex;
+
+	ex.type = type;
+	ex.major = major;
+	ex.minor = minor;
+	ex.access = access;
+
+	mutex_lock(&devcgroup_mutex);
+	dev_exception_add(&dev_cgroup->accessed, &ex);
+	mutex_unlock(&devcgroup_mutex);
+}
+
 /**
  * match_exception	- iterates the exception list trying to find a complete match
  * @exceptions: list of exceptions
@@ -566,7 +609,7 @@ static int propagate_exception(struct dev_cgroup *devcg_root,
 		 */
 		if (devcg_root->behavior == DEVCG_DEFAULT_ALLOW &&
 		    devcg->behavior == DEVCG_DEFAULT_ALLOW) {
-			rc = dev_exception_add(devcg, ex);
+			rc = dev_exception_add(&devcg->exceptions, ex);
 			if (rc)
 				break;
 		} else {
@@ -736,7 +779,7 @@ static int devcgroup_update_access(struct dev_cgroup *devcgroup,
 
 		if (!parent_has_perm(devcgroup, &ex))
 			return -EPERM;
-		rc = dev_exception_add(devcgroup, &ex);
+		rc = dev_exception_add(&devcgroup->exceptions, &ex);
 		break;
 	case DEVCG_DENY:
 		/*
@@ -747,7 +790,7 @@ static int devcgroup_update_access(struct dev_cgroup *devcgroup,
 		if (devcgroup->behavior == DEVCG_DEFAULT_DENY)
 			dev_exception_rm(devcgroup, &ex);
 		else
-			rc = dev_exception_add(devcgroup, &ex);
+			rc = dev_exception_add(&devcgroup->exceptions, &ex);
 
 		if (rc)
 			break;
@@ -788,6 +831,11 @@ static struct cftype dev_cgroup_files[] = {
 		.seq_show = devcgroup_seq_show,
 		.private = DEVCG_LIST,
 	},
+	{
+		.name = "accessed",
+		.seq_show = devcgroup_seq_show_accessed,
+		.private = DEVCG_LIST,
+	},
 	{ }	/* terminate */
 };
 
@@ -830,6 +878,8 @@ static int __devcgroup_check_permission(short type, u32 major, u32 minor,
 	if (!rc)
 		return -EPERM;
 
+	devcgroup_add_accessed(dev_cgroup, type, major, minor, access);
+
 	return 0;
 }
 
Signature · 1 line
2.8.1
#49 lore raw

Re: [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max

In reply to Topi Miettinen
Quoted 13 lines · Topi Miettinen

Track maximum size of message queues, presented in /proc/self/limits.

---
 ipc/mqueue.c | 2 ++
 1 file changed, 2 insertions(+)
ipc/mqueue.c +0 -0
index ade739f..edccf55 100644

ipc/mqueue.c static struct inode *mqueue_get_inode(struct super_block *sb, · line 294

Quoted 8 lines
ipc/mqueue.c +2 -0
@@ -287,6 +287,8 @@ static struct inode *mqueue_get_inode(struct super_block *sb,
 
 		/* all is ok */
 		info->user = get_uid(u);
+		/* XXX resource limits apply per task, not per user */
+		bump_rlimit(RLIMIT_MSGQUEUE, u->mq_bytes);
 	} else if (S_ISDIR(mode)) {
 		inc_nlink(inode);
 		/* Some things misbehave if size == 0 on a directory */

This patch looks all sorts of wrong to me.

In a current linus tree I can't find a single instance of bump_rlimit. Where is this magical function coming from?

Second, u->mq_bytes is the current size of all message queues for a given user. It is not per-task. So your message about limits being per-task is wrong (at least partially, the actual byte count is per-user not per-task, but the limit we check when we create a new queue is per-task and not per-user). So your comment is wrong, the one functional line you added appears to be a non-existent function, and even if those two things are resolved, why in the world would the fact that we created a new message queue mean we should bump our rlimit? That makes no sense, because would *never* have a working rlimit any more, we would simply increase our rlimit by the size of our existing queues every time we made a queue.

This is just a totally broken patch. Major NAK.

Signature · 2 lines
Doug Ledford <[email protected]>
    GPG Key ID: 0E572FDD
#42 lore raw

Re: [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max

In reply to Topi Miettinen
Quoted 1 line · Topi Miettinen

Track maximum size of locked memory, presented in /proc/self/limits.

You should have probably Cc:ed everyone on the cover letter and probably patch 1 of this series. This patch is hard to decipher without the additional context of those items. However, that said, I think I see what you are doing. But your wording of your comments below is bad:

Quoted 28 lines
include/linux/sched.h +8 -2
index feb9bb7..d3f3c9f 100644
@@ -3378,10 +3378,16 @@ static inline unsigned long rlimit_max(unsigned int limit)
 	return task_rlimit_max(current, limit);
 }
 
+static inline void task_bump_rlimit(struct task_struct *tsk,
+				    unsigned int limit, unsigned long r)
+{
+	if (READ_ONCE(tsk->signal->rlim_curmax[limit]) < r)
+		tsk->signal->rlim_curmax[limit] = r;
+}
+
 static inline void bump_rlimit(unsigned int limit, unsigned long r)
 {
-	if (READ_ONCE(current->signal->rlim_curmax[limit]) < r)
-		current->signal->rlim_curmax[limit] = r;
+	return task_bump_rlimit(current, limit, r);
 }
 
 #ifdef CONFIG_CPU_FREQ
kernel/bpf/syscall.c +0 -0
index 46ecce4..192001e 100644

kernel/bpf/syscall.c static int bpf_map_charge_memlock(struct bpf_map *map) · line 81

Quoted 6 lines
kernel/bpf/syscall.c +3 -0
@@ -76,6 +76,9 @@ static int bpf_map_charge_memlock(struct bpf_map *map)
 		return -EPERM;
 	}
 	map->user = user;
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, atomic_long_read(&user->locked_vm) <<
+		    PAGE_SHIFT);

No, these resource limits do not apply per task. They are per user. However, you are doing maximum usage accounting on a per-task basis by adding a new counter to the signal struct of the task. Fine, but your comments need to reflect that instead of the confusing comment above. In addition, your function name is horrible for what you are doing. A person reading this function will think that you are bumping the actual rlimit on the task, which is not what you are doing. You are performing per-task accounting of MEMLOCK memory. The actual permission checks are per-user, and the primary accounting is per-user. So, really, this is just a nice little feature that provides a more granular per-task usage (but not control) so a user can see where their overall memlock memory is being used. Fine. I would reword the comment something like this:

/* XXX resource is tracked and limit enforced on a per user basis,
but we track it on a per-task basis as well so users can identify hogs of this resource, stats can be found in /proc/<pid>/limits */

And I would rename bump_rlimit and task_bump_rlimit to something like account_rlimit and task_account_rlimit. Calling it bump just gives the wrong idea entirely on first read.

Quoted 52 lines
kernel/bpf/syscall.c +6 -0
 	return 0;
 }
 
@@ -601,6 +604,9 @@ static int bpf_prog_charge_memlock(struct bpf_prog *prog)
 		return -EPERM;
 	}
 	prog->aux->user = user;
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, atomic_long_read(&user->locked_vm) <<
+		    PAGE_SHIFT);
 	return 0;
 }
 
@@ -798,6 +802,9 @@ int user_shm_lock(size_t size, struct user_struct *user)
 	get_uid(user);
 	user->locked_shm += locked;
 	allowed = 1;
+
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, user->locked_shm << PAGE_SHIFT);
 out:
 	spin_unlock(&shmlock_user_lock);
 	return allowed;
mm/mmap.c +3 -0
index 0963e7f..4e683dd 100644
@@ -2020,6 +2020,9 @@ static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, uns
 		return -ENOMEM;
 
 	bump_rlimit(RLIMIT_STACK, actual_size);
+	if (vma->vm_flags & VM_LOCKED)
+		bump_rlimit(RLIMIT_MEMLOCK,
+			    (mm->locked_vm + grow) << PAGE_SHIFT);
 
 	return 0;
 }
mm/mremap.c +3 -0
index 1f157ad..ade3e13 100644
@@ -394,6 +394,9 @@ static struct vm_area_struct *vma_to_resize(unsigned long addr,
 		*p = charged;
 	}
 
+	if (vma->vm_flags & VM_LOCKED)
+		bump_rlimit(RLIMIT_MEMLOCK, (mm->locked_vm << PAGE_SHIFT) +
+			    new_len - old_len);
 	return vma;
 }
 
Signature · 2 lines
Doug Ledford <[email protected]>
    GPG Key ID: 0E572FDD
#43 lore raw

Re: [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max

Quoted 6 lines · Doug Ledford
Quoted 1 line · Topi Miettinen

Track maximum size of locked memory, presented in /proc/self/limits.

You should have probably Cc:ed everyone on the cover letter and probably patch 1 of this series. This patch is hard to decipher without the additional context of those items. However, that said, I think I see

Yes, I didn't know to CC everybody involved, sorry about that.

Quoted 24 lines

what you are doing. But your wording of your comments below is bad:

Quoted 22 lines
include/linux/sched.h +8 -2
index feb9bb7..d3f3c9f 100644
@@ -3378,10 +3378,16 @@ static inline unsigned long rlimit_max(unsigned int limit)
 	return task_rlimit_max(current, limit);
 }
 
+static inline void task_bump_rlimit(struct task_struct *tsk,
+				    unsigned int limit, unsigned long r)
+{
+	if (READ_ONCE(tsk->signal->rlim_curmax[limit]) < r)
+		tsk->signal->rlim_curmax[limit] = r;
+}
+
 static inline void bump_rlimit(unsigned int limit, unsigned long r)
 {
-	if (READ_ONCE(current->signal->rlim_curmax[limit]) < r)
-		current->signal->rlim_curmax[limit] = r;
+	return task_bump_rlimit(current, limit, r);
 }
 
Quoted 14 lines

kernel/bpf/syscall.c static int bpf_map_charge_memlock(struct bpf_map *map) · line 81

Quoted 12 lines
include/linux/sched.h +0 -0
 #ifdef CONFIG_CPU_FREQ
kernel/bpf/syscall.c +3 -0
index 46ecce4..192001e 100644
@@ -76,6 +76,9 @@ static int bpf_map_charge_memlock(struct bpf_map *map)
 		return -EPERM;
 	}
 	map->user = user;
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, atomic_long_read(&user->locked_vm) <<
+		    PAGE_SHIFT);

No, these resource limits do not apply per task. They are per user.

The problem could be that the manual pages do not say that but more to the opposite direction. For example, setrlimit(2) says that some limits (RLIMIT_MEMLOCK only for SHML_LOCK and others like RLIMIT_MSGQUEUE) apply indeed per user but others are per process. This note in mlock(2) could be also easily read as specifying a per process limit:

"Since Linux 2.6.9, no limits are placed on the amount of memory that
a privileged process can lock and the RLIMIT_MEMLOCK soft resource limit instead defines a limit on how much memory an unprivileged process may lock."

It's also confusing (to me, at least) that the limit values are stored in per task structures, so the actual limits can be different for each process for the same user.

The limits are also sometimes compared to per task current->mm->pinned_vm, in other places to current->mm->locked_vm and in still other places to per user user->locked_vm. How can the same limit apply to all of them at the same time? I'd think the user can actually lock many times the limit because of this.

Anyway, assuming that the actual implementation is always correct and unchangeable due to ABI stability reasons, it's useless to add XXX comments like I did.

Quoted 12 lines

However, you are doing maximum usage accounting on a per-task basis by adding a new counter to the signal struct of the task. Fine, but your comments need to reflect that instead of the confusing comment above. In addition, your function name is horrible for what you are doing. A person reading this function will think that you are bumping the actual rlimit on the task, which is not what you are doing. You are performing per-task accounting of MEMLOCK memory. The actual permission checks are per-user, and the primary accounting is per-user. So, really, this is just a nice little feature that provides a more granular per-task usage (but not control) so a user can see where their overall memlock memory is being used. Fine. I would reword the comment something like this:

Quoted 7 lines

/* XXX resource is tracked and limit enforced on a per user basis,
but we track it on a per-task basis as well so users can identify hogs of this resource, stats can be found in /proc/<pid>/limits */

And I would rename bump_rlimit and task_bump_rlimit to something like account_rlimit and task_account_rlimit. Calling it bump just gives the wrong idea entirely on first read.

Right, others have also proposed better names.

-Topi

Quoted 46 lines
Quoted 46 lines
kernel/bpf/syscall.c +6 -0
 	return 0;
 }
 
@@ -601,6 +604,9 @@ static int bpf_prog_charge_memlock(struct bpf_prog *prog)
 		return -EPERM;
 	}
 	prog->aux->user = user;
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, atomic_long_read(&user->locked_vm) <<
+		    PAGE_SHIFT);
 	return 0;
 }
 
@@ -798,6 +802,9 @@ int user_shm_lock(size_t size, struct user_struct *user)
 	get_uid(user);
 	user->locked_shm += locked;
 	allowed = 1;
+
+	/* XXX resource limits apply per task, not per user */
+	bump_rlimit(RLIMIT_MEMLOCK, user->locked_shm << PAGE_SHIFT);
 out:
 	spin_unlock(&shmlock_user_lock);
 	return allowed;
mm/mmap.c +3 -0
index 0963e7f..4e683dd 100644
@@ -2020,6 +2020,9 @@ static int acct_stack_growth(struct vm_area_struct *vma, unsigned long size, uns
 		return -ENOMEM;
 
 	bump_rlimit(RLIMIT_STACK, actual_size);
+	if (vma->vm_flags & VM_LOCKED)
+		bump_rlimit(RLIMIT_MEMLOCK,
+			    (mm->locked_vm + grow) << PAGE_SHIFT);
 
 	return 0;
 }
mm/mremap.c +0 -0
index 1f157ad..ade3e13 100644
@@ -394,6 +394,9 @@ static struct vm_area_struct *vma_to_resize(unsigned long addr,
 		*p = charged;
 	}
 
Quoted 9 lines

mm/mremap.c static struct vm_area_struct *vma_to_resize(unsigned long addr, · line 402

Quoted 7 lines
mm/mremap.c +3 -0
+	if (vma->vm_flags & VM_LOCKED)
+		bump_rlimit(RLIMIT_MEMLOCK, (mm->locked_vm << PAGE_SHIFT) +
+			    new_len - old_len);
 	return vma;
 }
 

--
To unsubscribe, send a message with 'unsubscribe linux-mm' in the body to [email protected]. For more info on Linux MM,
see: http://www.linux-mm.org/ .
Don't email: <a href=mailto:"[email protected]"> [email protected] </a>

#58 lore raw
In reply to Austin S. Hemmelgarn
Quoted 20 lines · Austin S. Hemmelgarn
Quoted 7 lines · Konstantin Khlebnikov

I don't like the idea of this patchset.

All limitations are context dependent and that context changes rapidly. You'll never dump enough information for predicting future errors or investigating reson of errors in past. You could try to reproduce all kernel logic but model always will be aproximate.

It's still better than what we have now, and there is one particular use for the cgroup stuff that I find intriguing, you can create a cgroup, populate it, set no limits, and then run a simulated workload against it and see how it reacts. This in general will probably provide a better starting point for what to actually set the limits to than just making an arbitrary guess. Certain applications in particular come to mind which will just hang when they can't start a new thread or process (Dropbox is particularly guilty of this). In such cases, setting the limit too low doesn't result in a crash, it results in the program just not appearing to work yet still running otherwise normally.

Quoted 12 lines

In general, I could see the rlimit stuff being in the same situation, it's not for figuring out why something failed (good software will tell you somewhere), but figuring out limits so it doesn't fail but still is reasonably contained. A lot of things that seem at face value like they shouldn't need specific exceptions to limits do. Most normal users probably wouldn't guess that acpid needs a RLIMIT_NPROC count of at least 4 or more to work with the default rules. Similarly, there's probably not many normal users who know that the Dropbox daemon spawns an insanely large thread pool and preallocates significant amounts of memory and will just hang if either of these fail. By having a way to get running max counts of resource usage, it makes it easier for people to know what the minimum limit they need to put on something is.

Rlimits work only if resource usage could be estimated apriori. They allows app limit itself to prevent failures is something goes wrong.

Rlimits are useless for controlling resource destribition: just use cgroups for that.

Quoted 11 lines
Quoted 10 lines

If you want to track origin of failures in user space applications when it hits
some limit you should track errors. For example rlimits and other limitation
subsystems could provide resonable amount of tracepoints which could tell what exactly happened before error. If you need highwater of some values you could track it in userspace, or maybe tracing subsystem could provide postpocessing for tracepoint parameters. Anyway, systemtap and other monsters can do this right now.

Quoted 5 lines

Userspace tracking of some things just isn't practical. Take RLIMIT_NPROC for example. There's not really any reliable way to track this from userspace without modifying the process which is being tracked, which is not a user friendly way of doing things, and in some cases is functionally impossible for an end user to do.

You cannot get reliable upper bound for nr-proc from black box observations. Highwater mark is very racy - tiny timing shifts can change it drammaticaly.

Quoted 84 lines
Quoted 83 lines
Quoted 79 lines · Topi Miettinen

Hello,

There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out
useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked
and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even
the source code is only implicit, in-depth knowledge of each capability must
be used when analyzing a program to judge which capabilities the program will
exercise.

Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the
current tasks and memory status can be easily seen with ps(1). However, any
transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no
universal method. Program sources typically give no useful indication about
memory use or how many tasks there could be.

Resource limits
[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current [RFC 07/18] limits: track RLIMIT_FSIZE actual max
[RFC 08/18] limits: track RLIMIT_DATA actual max
[RFC 09/18] limits: track RLIMIT_CORE actual max
[RFC 10/18] limits: track RLIMIT_STACK actual max
[RFC 11/18] limits: track and present RLIMIT_NPROC actual max [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max [RFC 13/18] limits: track RLIMIT_AS actual max
[RFC 14/18] limits: track RLIMIT_SIGPENDING actual max [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max [RFC 16/18] limits: track RLIMIT_NICE actual max
[RFC 17/18] limits: track RLIMIT_RTPRIO actual max
[RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

Current number of files and current VM usage (data pages, address space size)
could be calculated from available /proc files. Again, any temporarily higher
values could be easily missed. For many limits, there is no way to see what
is the current situation and source code is mostly useless.

As a side note, the resouce limits seem to be in bad shape. For example, RLIMIT_MEMLOCK is used incoherently and I think VM statistics can miss some changes. Adding RLIMIT_CODE could be useful.

The current maximum values for the resource limits are now shown in /proc/task/limits. If this is deemed too confusing for the existing programs which rely on the exact format, I can change that to a new file.

Finally, the patches work in my testing but I have probably missed finer lock/RCU details.

-Topi

#59 lore raw
Quoted 35 lines · Konstantin Khlebnikov
Quoted 20 lines · Austin S. Hemmelgarn
Quoted 7 lines · Konstantin Khlebnikov

I don't like the idea of this patchset.

All limitations are context dependent and that context changes rapidly. You'll never dump enough information for predicting future errors or investigating reson of errors in past. You could try to reproduce all kernel logic but model always will be aproximate.

It's still better than what we have now, and there is one particular use for the cgroup stuff that I find intriguing, you can create a cgroup, populate it, set no limits, and then run a simulated workload against it and see how it reacts. This in general will probably provide a better starting point for what to actually set the limits to than just making an arbitrary guess. Certain applications in particular come to mind which will just hang when they can't start a new thread or process (Dropbox is particularly guilty of this). In such cases, setting the limit too low doesn't result in a crash, it results in the program just not appearing to work yet still running otherwise normally.

Quoted 12 lines

In general, I could see the rlimit stuff being in the same situation, it's not for figuring out why something failed (good software will tell you somewhere), but figuring out limits so it doesn't fail but still is reasonably contained. A lot of things that seem at face value like they shouldn't need specific exceptions to limits do. Most normal users probably wouldn't guess that acpid needs a RLIMIT_NPROC count of at least 4 or more to work with the default rules. Similarly, there's probably not many normal users who know that the Dropbox daemon spawns an insanely large thread pool and preallocates significant amounts of memory and will just hang if either of these fail. By having a way to get running max counts of resource usage, it makes it easier for people to know what the minimum limit they need to put on something is.

Quoted 1 line

Rlimits work only if resource usage could be estimated apriori.

Now there's no way to estimate resource usage except analyzing source code and even that does give any estimate for memory limits. With the patches there's an easy way. Another way could be trial and error with binary search. Any way, even those estimates can be too small.

Perhaps the problem is that the limiting mechanisms are too discrete, either everything is OK or system calls fail (or the process is killed), there's no throttling in between. Also, the applications could in some cases tolerate the failures better.

Quoted 2 lines

They allows app limit itself to prevent failures is something goes wrong.

The application is not in any better position to estimate the limits. Typically the limits are set elsewhere.

Quoted 3 lines

Rlimits are useless for controlling resource destribition: just use cgroups for that.

There are no direct cgroup equivalents for most rlimits. I think the memory rlimits also make more sense per task. But otherwise cgroup approach would be more flexible and adding further cgroups doesn't look very difficult.

Quoted 11 lines
Quoted 11 lines
Quoted 10 lines

If you want to track origin of failures in user space applications when it hits
some limit you should track errors. For example rlimits and other limitation
subsystems could provide resonable amount of tracepoints which could tell what exactly happened before error. If you need highwater of some values you could track it in userspace, or maybe tracing subsystem could provide postpocessing for tracepoint parameters. Anyway, systemtap and other monsters can do this right now.

Quoted 9 lines
Quoted 5 lines

Userspace tracking of some things just isn't practical. Take RLIMIT_NPROC for example. There's not really any reliable way to track this from userspace without modifying the process which is being tracked, which is not a user friendly way of doing things, and in some cases is functionally impossible for an end user to do.

You cannot get reliable upper bound for nr-proc from black box observations. Highwater mark is very racy - tiny timing shifts can change it drammaticaly.

The estimates are imperfect, but does this make the highwater mark tracking any less valuable? How would you make the less imperfect estimate with tracepoints?

Quoted 84 lines
Quoted 84 lines
Quoted 83 lines
Quoted 79 lines · Topi Miettinen

Hello,

There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out
useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked
and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even
the source code is only implicit, in-depth knowledge of each capability must
be used when analyzing a program to judge which capabilities the program will
exercise.

Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the
current tasks and memory status can be easily seen with ps(1). However, any
transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no
universal method. Program sources typically give no useful indication about
memory use or how many tasks there could be.

Resource limits
[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current [RFC 07/18] limits: track RLIMIT_FSIZE actual max
[RFC 08/18] limits: track RLIMIT_DATA actual max
[RFC 09/18] limits: track RLIMIT_CORE actual max
[RFC 10/18] limits: track RLIMIT_STACK actual max
[RFC 11/18] limits: track and present RLIMIT_NPROC actual max [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max [RFC 13/18] limits: track RLIMIT_AS actual max
[RFC 14/18] limits: track RLIMIT_SIGPENDING actual max [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max [RFC 16/18] limits: track RLIMIT_NICE actual max
[RFC 17/18] limits: track RLIMIT_RTPRIO actual max
[RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

Current number of files and current VM usage (data pages, address space size)
could be calculated from available /proc files. Again, any temporarily higher
values could be easily missed. For many limits, there is no way to see what
is the current situation and source code is mostly useless.

As a side note, the resouce limits seem to be in bad shape. For example, RLIMIT_MEMLOCK is used incoherently and I think VM statistics can miss some changes. Adding RLIMIT_CODE could be useful.

The current maximum values for the resource limits are now shown in /proc/task/limits. If this is deemed too confusing for the existing programs which rely on the exact format, I can change that to a new file.

Finally, the patches work in my testing but I have probably missed finer lock/RCU details.

-Topi

#60 lore raw
In reply to Konstantin Khlebnikov
Quoted 35 lines · Konstantin Khlebnikov
Quoted 20 lines · Austin S. Hemmelgarn
Quoted 7 lines · Konstantin Khlebnikov

I don't like the idea of this patchset.

All limitations are context dependent and that context changes rapidly. You'll never dump enough information for predicting future errors or investigating reson of errors in past. You could try to reproduce all kernel logic but model always will be aproximate.

It's still better than what we have now, and there is one particular use for the cgroup stuff that I find intriguing, you can create a cgroup, populate it, set no limits, and then run a simulated workload against it and see how it reacts. This in general will probably provide a better starting point for what to actually set the limits to than just making an arbitrary guess. Certain applications in particular come to mind which will just hang when they can't start a new thread or process (Dropbox is particularly guilty of this). In such cases, setting the limit too low doesn't result in a crash, it results in the program just not appearing to work yet still running otherwise normally.

Quoted 12 lines

In general, I could see the rlimit stuff being in the same situation, it's not for figuring out why something failed (good software will tell you somewhere), but figuring out limits so it doesn't fail but still is reasonably contained. A lot of things that seem at face value like they shouldn't need specific exceptions to limits do. Most normal users probably wouldn't guess that acpid needs a RLIMIT_NPROC count of at least 4 or more to work with the default rules. Similarly, there's probably not many normal users who know that the Dropbox daemon spawns an insanely large thread pool and preallocates significant amounts of memory and will just hang if either of these fail. By having a way to get running max counts of resource usage, it makes it easier for people to know what the minimum limit they need to put on something is.

Quoted 2 lines

Rlimits work only if resource usage could be estimated apriori. They allows app limit itself to prevent failures is something goes wrong.

And yet many apps allow the _user_ to specify rlimits. Avahi has the option for the user to set every single rlimit, ntpd (the reference implementation) lets the user configure MEMLOCK, and quite a few other daemons I've seen that are very widely used allow similar manual configuration of limits. Most of these are network service daemons, which _can't_ reasonably limit themselves, because they can't know what type of workload they'll run against.

Quoted 3 lines

Rlimits are useless for controlling resource destribition: just use cgroups for that.

The only rlimit that has a cgroup specifically for managing it is NPROC.
There's a bunch of memory ones that can't be individually controlled
in the memcg. MEMLOCK is actually pretty widely used from what I've seen, but there is no way to control it at all with cgroups right now. NOFILE, LOCKS, FSIZE, and CORE all deal with the filesystem and have no cgroup that controls such resources (the only two that might be useful this way are NOFILE and LOCKS, but I doubt that those will get in, because they technically tie in with the kernel memory accounting in memcg). NICE and RTPRIO are nonsensical in a cgroup context, although I don't think I've ever talked to anyone who actually uses them. CPU and RTTIME have no equivalent in cgroups, but could in theory be tacked onto the cpu controller, but they haven't been and until that happens, people still have to use them instead of cgroups.

Quoted 12 lines
Quoted 12 lines
Quoted 11 lines

If you want to track origin of failures in user space applications when it hits
some limit you should track errors. For example rlimits and other limitation
subsystems could provide resonable amount of tracepoints which could tell what exactly happened before error. If you need highwater of some values you could track it in userspace, or maybe tracing subsystem could provide postpocessing for tracepoint parameters. Anyway, systemtap and other monsters can do this right now.

Quoted 8 lines
Quoted 5 lines

Userspace tracking of some things just isn't practical. Take RLIMIT_NPROC for example. There's not really any reliable way to track this from userspace without modifying the process which is being tracked, which is not a user friendly way of doing things, and in some cases is functionally impossible for an end user to do.

You cannot get reliable upper bound for nr-proc from black box observations. Highwater mark is very racy - tiny timing shifts can change it drammaticaly.

You can't get a perfectly reliable upper bound for any type of resource usage with just black box observations, period. You also can't do so with tracing without some significant secondary work either for _exactly the same reason_. The thing to remember though is that in a majority of cases, what most people need is simply a reasonable estimate which is guaranteed to not be below the actual usage. They don't care exactly how many processes application Y uses at most, they just care that it uses fewer than some reasonable limit under normal usage. To go back to the NPROC example, most people want to be able to set a limit that will catch things if they start to get out of hand, but absolutely have to estimate high because almost nothing handles a fork failure gracefully without completely shutting down. In such a situation, it doesn't matter if it's a bit racy, as long as they have some reasonable lower bound to base the estimate off of and the specifics of it not being 100% reliable are properly documented.

Quoted 85 lines
Quoted 85 lines
Quoted 84 lines
Quoted 79 lines · Topi Miettinen

Hello,

There are many basic ways to control processes, including capabilities, cgroups and resource limits. However, there are far fewer ways to find out
useful values for the limits, except blind trial and error.

This patch series attempts to fix that by giving at least a nice starting point from the actual maximum values. I looked where each limit is checked
and added a call to limit bump nearby.

Capabilities
[RFC 01/18] capabilities: track actually used capabilities

Currently, there is no way to know which capabilities are actually used. Even
the source code is only implicit, in-depth knowledge of each capability must
be used when analyzing a program to judge which capabilities the program will
exercise.

Cgroups
[RFC 02/18] cgroup_pids: track maximum pids
[RFC 03/18] memcontrol: present maximum used memory also for [RFC 04/18] device_cgroup: track and present accessed devices

For tasks and memory cgroup limits the situation is somewhat better as the
current tasks and memory status can be easily seen with ps(1). However, any
transient tasks or temporary higher memory use might slip from the view. Device use may be seen with advanced MAC tools, like TOMOYO, but there is no
universal method. Program sources typically give no useful indication about
memory use or how many tasks there could be.

Resource limits
[RFC 05/18] limits: track and present RLIMIT_NOFILE actual max [RFC 06/18] limits: present RLIMIT_CPU and RLIMIT_RTTIMER current [RFC 07/18] limits: track RLIMIT_FSIZE actual max
[RFC 08/18] limits: track RLIMIT_DATA actual max
[RFC 09/18] limits: track RLIMIT_CORE actual max
[RFC 10/18] limits: track RLIMIT_STACK actual max
[RFC 11/18] limits: track and present RLIMIT_NPROC actual max [RFC 12/18] limits: track RLIMIT_MEMLOCK actual max [RFC 13/18] limits: track RLIMIT_AS actual max
[RFC 14/18] limits: track RLIMIT_SIGPENDING actual max [RFC 15/18] limits: track RLIMIT_MSGQUEUE actual max [RFC 16/18] limits: track RLIMIT_NICE actual max
[RFC 17/18] limits: track RLIMIT_RTPRIO actual max
[RFC 18/18] proc: present VM_LOCKED memory in /proc/self/maps

Current number of files and current VM usage (data pages, address space size)
could be calculated from available /proc files. Again, any temporarily higher
values could be easily missed. For many limits, there is no way to see what
is the current situation and source code is mostly useless.

As a side note, the resouce limits seem to be in bad shape. For example, RLIMIT_MEMLOCK is used incoherently and I think VM statistics can miss some changes. Adding RLIMIT_CODE could be useful.

The current maximum values for the resource limits are now shown in /proc/task/limits. If this is deemed too confusing for the existing programs which rely on the exact format, I can change that to a new file.

Finally, the patches work in my testing but I have probably missed finer lock/RCU details.

-Topi

#12 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

In reply to Tejun Heo
Quoted 10 lines · Tejun Heo

Hello,

Quoted 3 lines · Topi Miettinen

I used fork callback as I don't want to lower the watermark in all cases where the charge can be lowered, so I'd update the watermark only when the fork really happens.

I don't think that would make a noticeable difference. That's where we decide whether to grant fork or not after all and thus where the actual usage is.

I tried using only charge functions, but then the result was too low. With fork callback, the result was as expected.

-Topi

Quoted 9 lines
Quoted 3 lines

Is there a better way to compare and set? I don't think atomic_cmpxchg() does what's needed,

cmpxchg loop should do what's necessary although I'm not sure how much being strictly correct matters here.

Thanks.

maintainer
#13 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

Quoted 8 lines · Topi Miettinen
Quoted 7 lines · Tejun Heo

Hello,

Quoted 3 lines · Topi Miettinen

I used fork callback as I don't want to lower the watermark in all cases where the charge can be lowered, so I'd update the watermark only when the fork really happens.

Quoted 6 lines
Quoted 3 lines

I don't think that would make a noticeable difference. That's where we decide whether to grant fork or not after all and thus where the actual usage is.

I tried using only charge functions, but then the result was too low. With fork callback, the result was as expected.

Can you please elaborate in more details?

Thanks.

Signature · 1 line
tejun
#14 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

Quoted 9 lines · Tejun Heo
Quoted 8 lines · Topi Miettinen
Quoted 7 lines · Tejun Heo

Hello,

Quoted 3 lines · Topi Miettinen

I used fork callback as I don't want to lower the watermark in all cases where the charge can be lowered, so I'd update the watermark only when the fork really happens.

Quoted 8 lines
Quoted 6 lines
Quoted 3 lines

I don't think that would make a noticeable difference. That's where we decide whether to grant fork or not after all and thus where the actual usage is.

I tried using only charge functions, but then the result was too low. With fork callback, the result was as expected.

Can you please elaborate in more details?

With the example systemd-timesyncd case, I was only getting 1 as the highwatermark, but there were already two tasks.

-Topi

maintainer
#15 lore raw

Re: [RFC 02/18] cgroup_pids: track maximum pids

Quoted 2 lines · Topi Miettinen

With the example systemd-timesyncd case, I was only getting 1 as the highwatermark, but there were already two tasks.

Can you please find out why that is so? Given that that's where we charge pid usage, it doesn't make sense to me that you're getting lower numbers than actual usage there.

Thanks.

Signature · 1 line
tejun