ns_cgroup.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /*
  2. * ns_cgroup.c - namespace cgroup subsystem
  3. *
  4. * Copyright 2006, 2007 IBM Corp
  5. */
  6. #include <linux/module.h>
  7. #include <linux/cgroup.h>
  8. #include <linux/fs.h>
  9. #include <linux/proc_fs.h>
  10. #include <linux/slab.h>
  11. #include <linux/nsproxy.h>
  12. struct ns_cgroup {
  13. struct cgroup_subsys_state css;
  14. };
  15. struct cgroup_subsys ns_subsys;
  16. static inline struct ns_cgroup *cgroup_to_ns(
  17. struct cgroup *cgroup)
  18. {
  19. return container_of(cgroup_subsys_state(cgroup, ns_subsys_id),
  20. struct ns_cgroup, css);
  21. }
  22. int ns_cgroup_clone(struct task_struct *task, struct pid *pid)
  23. {
  24. char name[PROC_NUMBUF];
  25. snprintf(name, PROC_NUMBUF, "%d", pid_vnr(pid));
  26. return cgroup_clone(task, &ns_subsys, name);
  27. }
  28. /*
  29. * Rules:
  30. * 1. you can only enter a cgroup which is a child of your current
  31. * cgroup
  32. * 2. you can only place another process into a cgroup if
  33. * a. you have CAP_SYS_ADMIN
  34. * b. your cgroup is an ancestor of task's destination cgroup
  35. * (hence either you are in the same cgroup as task, or in an
  36. * ancestor cgroup thereof)
  37. */
  38. static int ns_can_attach(struct cgroup_subsys *ss,
  39. struct cgroup *new_cgroup, struct task_struct *task)
  40. {
  41. struct cgroup *orig;
  42. if (current != task) {
  43. if (!capable(CAP_SYS_ADMIN))
  44. return -EPERM;
  45. if (!cgroup_is_descendant(new_cgroup))
  46. return -EPERM;
  47. }
  48. if (atomic_read(&new_cgroup->count) != 0)
  49. return -EPERM;
  50. orig = task_cgroup(task, ns_subsys_id);
  51. if (orig && orig != new_cgroup->parent)
  52. return -EPERM;
  53. return 0;
  54. }
  55. /*
  56. * Rules: you can only create a cgroup if
  57. * 1. you are capable(CAP_SYS_ADMIN)
  58. * 2. the target cgroup is a descendant of your own cgroup
  59. */
  60. static struct cgroup_subsys_state *ns_create(struct cgroup_subsys *ss,
  61. struct cgroup *cgroup)
  62. {
  63. struct ns_cgroup *ns_cgroup;
  64. if (!capable(CAP_SYS_ADMIN))
  65. return ERR_PTR(-EPERM);
  66. if (!cgroup_is_descendant(cgroup))
  67. return ERR_PTR(-EPERM);
  68. ns_cgroup = kzalloc(sizeof(*ns_cgroup), GFP_KERNEL);
  69. if (!ns_cgroup)
  70. return ERR_PTR(-ENOMEM);
  71. return &ns_cgroup->css;
  72. }
  73. static void ns_destroy(struct cgroup_subsys *ss,
  74. struct cgroup *cgroup)
  75. {
  76. struct ns_cgroup *ns_cgroup;
  77. ns_cgroup = cgroup_to_ns(cgroup);
  78. kfree(ns_cgroup);
  79. }
  80. struct cgroup_subsys ns_subsys = {
  81. .name = "ns",
  82. .can_attach = ns_can_attach,
  83. .create = ns_create,
  84. .destroy = ns_destroy,
  85. .subsys_id = ns_subsys_id,
  86. };