ns_cgroup.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 descendant 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. if (current != task) {
  42. if (!capable(CAP_SYS_ADMIN))
  43. return -EPERM;
  44. if (!cgroup_is_descendant(new_cgroup, current))
  45. return -EPERM;
  46. }
  47. if (!cgroup_is_descendant(new_cgroup, task))
  48. return -EPERM;
  49. return 0;
  50. }
  51. /*
  52. * Rules: you can only create a cgroup if
  53. * 1. you are capable(CAP_SYS_ADMIN)
  54. * 2. the target cgroup is a descendant of your own cgroup
  55. */
  56. static struct cgroup_subsys_state *ns_create(struct cgroup_subsys *ss,
  57. struct cgroup *cgroup)
  58. {
  59. struct ns_cgroup *ns_cgroup;
  60. if (!capable(CAP_SYS_ADMIN))
  61. return ERR_PTR(-EPERM);
  62. if (!cgroup_is_descendant(cgroup, current))
  63. return ERR_PTR(-EPERM);
  64. ns_cgroup = kzalloc(sizeof(*ns_cgroup), GFP_KERNEL);
  65. if (!ns_cgroup)
  66. return ERR_PTR(-ENOMEM);
  67. return &ns_cgroup->css;
  68. }
  69. static void ns_destroy(struct cgroup_subsys *ss,
  70. struct cgroup *cgroup)
  71. {
  72. struct ns_cgroup *ns_cgroup;
  73. ns_cgroup = cgroup_to_ns(cgroup);
  74. kfree(ns_cgroup);
  75. }
  76. struct cgroup_subsys ns_subsys = {
  77. .name = "ns",
  78. .can_attach = ns_can_attach,
  79. .create = ns_create,
  80. .destroy = ns_destroy,
  81. .subsys_id = ns_subsys_id,
  82. };