+{
+ char *container_name = NULL;
+ int devnum;
+ char *devname;
+ int status = 0;
+ int arg;
+ int all = 0;
+ int takeover = 0;
+
+ for (arg = 1; arg < argc; arg++) {
+ if (strncmp(argv[arg], "--all",5) == 0 ||
+ strcmp(argv[arg], "/proc/mdstat") == 0) {
+ container_name = argv[arg];
+ all = 1;
+ } else if (strcmp(argv[arg], "--takeover") == 0)
+ takeover = 1;
+ else if (container_name == NULL)
+ container_name = argv[arg];
+ else
+ usage();
+ }
+ if (container_name == NULL)
+ usage();
+
+ if (all) {
+ struct mdstat_ent *mdstat, *e;
+ int container_len = strlen(container_name);
+
+ /* launch an mdmon instance for each container found */
+ mdstat = mdstat_read(0, 0);
+ for (e = mdstat; e; e = e->next) {
+ if (strncmp(e->metadata_version, "external:", 9) == 0 &&
+ !is_subarray(&e->metadata_version[9])) {
+ devname = devnum2devname(e->devnum);
+ /* update cmdline so this mdmon instance can be
+ * distinguished from others in a call to ps(1)
+ */
+ if (strlen(devname) <= (unsigned)container_len) {
+ memset(container_name, 0, container_len);
+ sprintf(container_name, "%s", devname);
+ }
+ status |= mdmon(devname, e->devnum, 1,
+ takeover);
+ }
+ }
+ free_mdstat(mdstat);
+
+ return status;
+ } else if (strncmp(container_name, "md", 2) == 0) {
+ devnum = devname2devnum(container_name);
+ devname = devnum2devname(devnum);
+ if (strcmp(container_name, devname) != 0)
+ devname = NULL;
+ } else {
+ struct stat st;
+
+ devnum = NoMdDev;
+ if (stat(container_name, &st) == 0)
+ devnum = stat2devnum(&st);
+ if (devnum == NoMdDev)
+ devname = NULL;
+ else
+ devname = devnum2devname(devnum);
+ }
+
+ if (!devname) {
+ fprintf(stderr, "mdmon: %s is not a valid md device name\n",
+ container_name);
+ exit(1);
+ }
+ return mdmon(devname, devnum, do_fork(), takeover);
+}
+
+static int mdmon(char *devname, int devnum, int must_fork, int takeover)