]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/vinum/vinumconfig.c
This commit was generated by cvs2svn to compensate for changes in r98038,
[FreeBSD/FreeBSD.git] / sys / dev / vinum / vinumconfig.c
1 /*
2  * To do:
3  *
4  * Don't store drive configuration on the config DB: read each drive's header
5  * to decide where it is.
6  *
7  * Accept any old crap in the config_<foo> functions, and complain when
8  * we try to bring it up.
9  *
10  * When trying to bring volumes up, check that the complete address range
11  * is covered.
12  */
13 /*-
14  * Copyright (c) 1997, 1998
15  *      Nan Yang Computer Services Limited.  All rights reserved.
16  *
17  *  This software is distributed under the so-called ``Berkeley
18  *  License'':
19  *
20  * Redistribution and use in source and binary forms, with or without
21  * modification, are permitted provided that the following conditions
22  * are met:
23  * 1. Redistributions of source code must retain the above copyright
24  *    notice, this list of conditions and the following disclaimer.
25  * 2. Redistributions in binary form must reproduce the above copyright
26  *    notice, this list of conditions and the following disclaimer in the
27  *    documentation and/or other materials provided with the distribution.
28  * 3. All advertising materials mentioning features or use of this software
29  *    must display the following acknowledgement:
30  *      This product includes software developed by Nan Yang Computer
31  *      Services Limited.
32  * 4. Neither the name of the Company nor the names of its contributors
33  *    may be used to endorse or promote products derived from this software
34  *    without specific prior written permission.
35  *
36  * This software is provided ``as is'', and any express or implied
37  * warranties, including, but not limited to, the implied warranties of
38  * merchantability and fitness for a particular purpose are disclaimed.
39  * In no event shall the company or contributors be liable for any
40  * direct, indirect, incidental, special, exemplary, or consequential
41  * damages (including, but not limited to, procurement of substitute
42  * goods or services; loss of use, data, or profits; or business
43  * interruption) however caused and on any theory of liability, whether
44  * in contract, strict liability, or tort (including negligence or
45  * otherwise) arising in any way out of the use of this software, even if
46  * advised of the possibility of such damage.
47  *
48  * $Id: vinumconfig.c,v 1.30 2000/05/01 09:45:50 grog Exp grog $
49  * $FreeBSD$
50  */
51
52 #define STATIC static
53
54 #include <dev/vinum/vinumhdr.h>
55 #include <dev/vinum/request.h>
56
57 #define MAXTOKEN 64                                         /* maximum number of tokens in a line */
58
59 /*
60  * We can afford the luxury of global variables here,
61  * since start_config ensures that these functions
62  * are single-threaded.
63  */
64
65 /* These are indices in vinum_conf of the last-mentioned of each kind of object */
66 static int current_drive;                                   /* note the last drive we mention, for
67                                                             * some defaults */
68 static int current_plex;                                    /* and the same for the last plex */
69 static int current_volume;                                  /* and the last volme */
70 static struct _ioctl_reply *ioctl_reply;                    /* struct to return via ioctl */
71
72
73 /* These values are used by most of these routines, so set them as globals */
74 static char *token[MAXTOKEN];                               /* pointers to individual tokens */
75 static int tokens;                                          /* number of tokens */
76
77 #define TOCONS  0x01
78 #define TOTTY   0x02
79 #define TOLOG   0x04
80
81 struct putchar_arg {
82     int flags;
83     struct tty *tty;
84 };
85
86 #define MSG_MAX 1024                                        /* maximum length of a formatted message */
87 /*
88  * Format an error message and return to the user in the reply.
89  * CARE: This routine is designed to be called only from the
90  * configuration routines, so it assumes it's the owner of
91  * the configuration lock, and unlocks it on exit
92  */
93 void
94 throw_rude_remark(int error, char *msg,...)
95 {
96     int retval;
97     va_list ap;
98     char *text;
99     static int finishing;                                   /* don't recurse */
100     int was_finishing;
101
102     if ((vinum_conf.flags & VF_LOCKED) == 0)                /* bug catcher */
103         panic ("throw_rude_remark: called without config lock");
104     va_start(ap, msg);
105     if ((ioctl_reply != NULL)                               /* we're called from the user */
106     &&(!(vinum_conf.flags & VF_READING_CONFIG))) {          /* and not reading from disk: return msg */
107         /*
108          * We can't just format to ioctl_reply, since it
109          * may contain our input parameters
110          */
111         text = Malloc(MSG_MAX);
112         if (text == NULL) {
113             log(LOG_ERR, "vinum: can't allocate error message buffer\n");
114             printf("vinum: ");
115             vprintf(msg, ap);                               /* print to the console */
116             printf("\n");
117         } else {
118             retval = kvprintf(msg, NULL, (void *) text, 10, ap);
119             text[retval] = '\0';                            /* delimit */
120             strcpy(ioctl_reply->msg, text);
121             ioctl_reply->error = error;                     /* first byte is the error number */
122             Free(text);
123         }
124     } else {
125         printf("vinum: ");
126         vprintf(msg, ap);                                   /* print to the console */
127         printf("\n");
128     }
129     va_end(ap);
130
131     if (vinum_conf.flags & VF_READING_CONFIG) {             /* go through to the bitter end, */
132         if ((vinum_conf.flags & VF_READING_CONFIG)          /* we're reading from disk, */
133         &&((daemon_options & daemon_noupdate) == 0)) {
134             log(LOG_NOTICE, "Disabling configuration updates\n");
135             daemon_options |= daemon_noupdate;
136         }
137         return;
138     }
139     /*
140      * We have a problem here: we want to unlock the
141      * configuration, which implies tidying up, but
142      * if we find an error while tidying up, we could
143      * recurse for ever.  Use this kludge to only try
144      * once
145      */
146     was_finishing = finishing;
147     finishing = 1;
148     finish_config(was_finishing);                           /* unlock anything we may be holding */
149     finishing = was_finishing;
150     longjmp(command_fail, error);
151 }
152
153 /*
154  * Check a volume to see if the plex is already assigned to it.
155  * Return index in volume->plex, or -1 if not assigned
156  */
157 int
158 my_plex(int volno, int plexno)
159 {
160     int i;
161     struct volume *vol;
162
163     vol = &VOL[volno];                                      /* point to volno */
164     for (i = 0; i < vol->plexes; i++)
165         if (vol->plex[i] == plexno)
166             return i;
167     return -1;                                              /* not found */
168 }
169
170 /*
171  * Check a plex to see if the subdisk is already assigned to it.
172  * Return index in plex->sd, or -1 if not assigned
173  */
174 int
175 my_sd(int plexno, int sdno)
176 {
177     int i;
178     struct plex *plex;
179
180     plex = &PLEX[plexno];
181     for (i = 0; i < plex->subdisks; i++)
182         if (plex->sdnos[i] == sdno)
183             return i;
184     return -1;                                              /* not found */
185 }
186
187 /* Add plex to the volume if possible */
188 int
189 give_plex_to_volume(int volno, int plexno)
190 {
191     struct volume *vol;
192     int i;
193
194     /*
195      * It's not an error for the plex to already
196      * belong to the volume, but we need to check a
197      * number of things to make sure it's done right.
198      * Some day.
199      */
200     if (my_plex(volno, plexno) >= 0)
201         return plexno;                                      /* that's it */
202
203     vol = &VOL[volno];                                      /* point to volume */
204     if (vol->plexes == MAXPLEX)                             /* all plexes allocated */
205         throw_rude_remark(ENOSPC,
206             "Too many plexes for volume %s",
207             vol->name);
208     else if ((vol->plexes > 0)                              /* we have other plexes */
209     &&((vol->flags & VF_CONFIG_SETUPSTATE) == 0))           /* and we're not setting up state */
210         invalidate_subdisks(&PLEX[plexno], sd_stale);       /* make the subdisks invalid */
211     vol->plex[vol->plexes] = plexno;                        /* this one */
212     vol->plexes++;                                          /* add another plex */
213     PLEX[plexno].volno = volno;                             /* note the number of our volume */
214
215     /* Find out how big our volume is */
216     for (i = 0; i < vol->plexes; i++)
217         vol->size = max(vol->size, PLEX[vol->plex[i]].length);
218     return vol->plexes - 1;                                 /* and return its index */
219 }
220
221 /*
222  * Add subdisk to a plex if possible
223  */
224 int
225 give_sd_to_plex(int plexno, int sdno)
226 {
227     int i;
228     struct plex *plex;
229     struct sd *sd;
230
231     /*
232      * It's not an error for the sd to already
233      * belong to the plex, but we need to check a
234      * number of things to make sure it's done right.
235      * Some day.
236      */
237     i = my_sd(plexno, sdno);
238     if (i >= 0)                                             /* does it already belong to us? */
239         return i;                                           /* that's it */
240
241     plex = &PLEX[plexno];                                   /* point to the plex */
242     sd = &SD[sdno];                                         /* and the subdisk */
243
244     /* Do we have an offset?  Otherwise put it after the last one */
245     if (sd->plexoffset < 0) {                               /* no offset specified */
246         if (plex->subdisks > 0) {
247             struct sd *lastsd = &SD[plex->sdnos[plex->subdisks - 1]]; /* last subdisk */
248
249             if (plex->organization == plex_concat)          /* concat, */
250                 sd->plexoffset = lastsd->sectors + lastsd->plexoffset; /* starts here */
251             else                                            /* striped, RAID-4 or RAID-5 */
252                 sd->plexoffset = plex->stripesize * plex->subdisks; /* starts here */
253         } else                                              /* first subdisk */
254             sd->plexoffset = 0;                             /* start at the beginning */
255     }
256     if (plex->subdisks == MAXSD)                            /* we already have our maximum */
257         throw_rude_remark(ENOSPC,                           /* crap out */
258             "Can't add %s to %s: plex full",
259             sd->name,
260             plex->name);
261
262     plex->subdisks++;                                       /* another entry */
263     if (plex->subdisks >= plex->subdisks_allocated)         /* need more space */
264         EXPAND(plex->sdnos, int, plex->subdisks_allocated, INITIAL_SUBDISKS_IN_PLEX);
265
266     /* Adjust size of plex and volume. */
267     if (isparity(plex))                                     /* RAID-4 or RAID-5 */
268         plex->length = (plex->subdisks - 1) * sd->sectors;  /* size is one disk short */
269     else
270         plex->length += sd->sectors;                        /* plex gets this much bigger */
271     if (plex->volno >= 0)                                   /* we have a volume */
272         VOL[plex->volno].size = max(VOL[plex->volno].size, plex->length); /* adjust its size */
273
274     /*
275      * We need to check that the subdisks don't overlap,
276      * but we can't do that until a point where we *must*
277      * know the size of all the subdisks.  That's not
278      * here.  But we need to sort them by offset
279      */
280     for (i = 0; i < plex->subdisks - 1; i++) {
281         if (sd->plexoffset < SD[plex->sdnos[i]].plexoffset) { /* it fits before this one */
282             /* First move any remaining subdisks by one */
283             int j;
284
285             for (j = plex->subdisks - 1; j > i; j--)        /* move up one at a time */
286                 plex->sdnos[j] = plex->sdnos[j - 1];
287             plex->sdnos[i] = sdno;
288             sd->plexsdno = i;                               /* note where we are in the subdisk */
289             return i;
290         }
291     }
292
293     /*
294      * The plex doesn't have any subdisk with a
295      * larger offset.  Insert it here.
296      */
297     plex->sdnos[i] = sdno;
298     sd->plexsdno = i;                                       /* note where we are in the subdisk */
299     sd->plexno = plex->plexno;                              /* and who we belong to */
300     return i;
301 }
302
303 /*
304  * Add a subdisk to drive if possible.  The
305  * pointer to the drive must already be stored in
306  * the sd structure, but the drive doesn't know
307  * about the subdisk yet.
308  */
309 void
310 give_sd_to_drive(int sdno)
311 {
312     struct sd *sd;                                          /* pointer to subdisk */
313     struct drive *drive;                                    /* and drive */
314     int fe;                                                 /* index in free list */
315     int sfe;                                                /* and index of subdisk when assigning max */
316
317     sd = &SD[sdno];                                         /* point to sd */
318     drive = &DRIVE[sd->driveno];                            /* and drive */
319
320     if (drive->state != drive_up) {
321         update_sd_state(sdno);                              /* that crashes the subdisk */
322         return;
323     }
324     if (drive->flags & VF_HOTSPARE)                         /* the drive is a hot spare, */
325         throw_rude_remark(ENOSPC,
326             "Can't place %s on hot spare drive %s",
327             sd->name,
328             drive->label.name);
329     if ((drive->sectors_available == 0)                     /* no space left */
330     ||(sd->sectors > drive->sectors_available)) {           /* or too big, */
331         sd->driveoffset = -1;                               /* don't be confusing */
332         free_sd(sd->sdno);
333         throw_rude_remark(ENOSPC, "No space for %s on %s", sd->name, drive->label.name);
334         return;                                             /* in case we come back here */
335     }
336     drive->subdisks_used++;                                 /* one more subdisk */
337
338     if (sd->sectors == 0) {                                 /* take the largest chunk */
339         sfe = 0;                                            /* to keep the compiler happy */
340         for (fe = 0; fe < drive->freelist_entries; fe++) {
341             if (drive->freelist[fe].sectors >= sd->sectors) { /* more space here */
342                 sd->sectors = drive->freelist[fe].sectors;  /* take it */
343                 sd->driveoffset = drive->freelist[fe].offset;
344                 sfe = fe;                                   /* and note the index for later */
345             }
346         }
347         if (sd->sectors == 0) {                             /* no luck, */
348             sd->driveoffset = -1;                           /* don't be confusing */
349             free_sd(sd->sdno);
350             throw_rude_remark(ENOSPC,                       /* give up */
351                 "No space for %s on %s",
352                 sd->name,
353                 drive->label.name);
354         }
355         if (sfe < (drive->freelist_entries - 1))            /* not the last one, */
356             bcopy(&drive->freelist[sfe + 1],
357                 &drive->freelist[sfe],
358                 (drive->freelist_entries - sfe) * sizeof(struct drive_freelist));
359         drive->freelist_entries--;                          /* one less entry */
360         drive->sectors_available -= sd->sectors;            /* and note how much less space we have */
361     } else if (sd->driveoffset < 0) {                       /* no offset specified, find one */
362         for (fe = 0; fe < drive->freelist_entries; fe++) {
363             if (drive->freelist[fe].sectors >= sd->sectors) { /* it'll fit here */
364                 sd->driveoffset = drive->freelist[fe].offset;
365                 if (sd->sectors == drive->freelist[fe].sectors) { /* used up the entire entry */
366                     if (fe < (drive->freelist_entries - 1)) /* not the last one, */
367                         bcopy(&drive->freelist[fe + 1],
368                             &drive->freelist[fe],
369                             (drive->freelist_entries - fe) * sizeof(struct drive_freelist));
370                     drive->freelist_entries--;              /* one less entry */
371                 } else {
372                     drive->freelist[fe].sectors -= sd->sectors; /* this much less space */
373                     drive->freelist[fe].offset += sd->sectors; /* this much further on */
374                 }
375                 drive->sectors_available -= sd->sectors;    /* and note how much less space we have */
376                 break;
377             }
378         }
379         if (sd->driveoffset < 0)
380             /*
381              * Didn't find anything.  Although the drive has
382              * enough space, it's too fragmented
383              */
384         {
385             free_sd(sd->sdno);
386             throw_rude_remark(ENOSPC, "No space for %s on %s", sd->name, drive->label.name);
387         }
388     } else {                                                /* specific offset */
389         /*
390          * For a specific offset to work, the space must be
391          * entirely in a single freelist entry.  Look for it.
392          */
393         u_int64_t sdend = sd->driveoffset + sd->sectors;    /* end of our subdisk */
394         for (fe = 0; fe < drive->freelist_entries; fe++) {
395             u_int64_t dend = drive->freelist[fe].offset + drive->freelist[fe].sectors; /* end of entry */
396             if (dend >= sdend) {                            /* fits before here */
397                 if (drive->freelist[fe].offset > sd->driveoffset) { /* starts after the beginning of sd area */
398                     sd->driveoffset = -1;                   /* don't be confusing */
399                     set_sd_state(sd->sdno, sd_down, setstate_force);
400                     throw_rude_remark(ENOSPC,
401                         "No space for %s on drive %s at offset %lld",
402                         sd->name,
403                         drive->label.name,
404                         sd->driveoffset);
405                     return;
406                 }
407                 /*
408                  * We've found the space, and we can allocate it.
409                  * We don't need to say that to the subdisk, which
410                  * already knows about it.  We need to tell it to
411                  * the free list, though.  We have four possibilities:
412                  *
413                  * 1.  The subdisk exactly eats up the entry.  That's the
414                  *     same as above.
415                  * 2.  The subdisk starts at the beginning and leaves space
416                  *     at the end.
417                  * 3.  The subdisk starts after the beginning and leaves
418                  *     space at the end as well: we end up with another
419                  *     fragment.
420                  * 4.  The subdisk leaves space at the beginning and finishes
421                  *     at the end.
422                  */
423                 drive->sectors_available -= sd->sectors;    /* note how much less space we have */
424                 if (sd->driveoffset == drive->freelist[fe].offset) { /* 1 or 2 */
425                     if (sd->sectors == drive->freelist[fe].sectors) { /* 1: used up the entire entry */
426                         if (fe < (drive->freelist_entries - 1)) /* not the last one, */
427                             bcopy(&drive->freelist[fe + 1],
428                                 &drive->freelist[fe],
429                                 (drive->freelist_entries - fe) * sizeof(struct drive_freelist));
430                         drive->freelist_entries--;          /* one less entry */
431                     } else {                                /* 2: space at the end */
432                         drive->freelist[fe].sectors -= sd->sectors; /* this much less space */
433                         drive->freelist[fe].offset += sd->sectors; /* this much further on */
434                     }
435                 } else {                                    /* 3 or 4 */
436                     drive->freelist[fe].sectors = sd->driveoffset - drive->freelist[fe].offset;
437                     if (dend > sdend) {                     /* 3: space at the end as well */
438                         if (fe < (drive->freelist_entries - 1)) /* not the last one */
439                             bcopy(&drive->freelist[fe],     /* move the rest down */
440                                 &drive->freelist[fe + 1],
441                                 (drive->freelist_entries - fe) * sizeof(struct drive_freelist));
442                         drive->freelist_entries++;          /* one less entry */
443                         drive->freelist[fe + 1].offset = sdend; /* second entry starts after sd */
444                         drive->freelist[fe + 1].sectors = dend - sdend; /* and is this long */
445                     }
446                 }
447                 break;
448             }
449         }
450     }
451     drive->opencount++;                                     /* one more subdisk attached */
452 }
453
454 /* Get an empty drive entry from the drive table */
455 int
456 get_empty_drive(void)
457 {
458     int driveno;
459     struct drive *drive;
460
461     /* first see if we have one which has been deallocated */
462     for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
463         if (DRIVE[driveno].state == drive_unallocated)      /* bingo */
464             break;
465     }
466
467     if (driveno >= vinum_conf.drives_allocated)             /* we've used all our allocation */
468         EXPAND(DRIVE, struct drive, vinum_conf.drives_allocated, INITIAL_DRIVES);
469
470     /* got a drive entry.  Make it pretty */
471     drive = &DRIVE[driveno];
472     bzero(drive, sizeof(struct drive));
473     drive->driveno = driveno;                               /* put number in structure */
474     drive->flags |= VF_NEWBORN;                             /* newly born drive */
475     strcpy("unknown", drive->devicename);                   /* and make the name ``unknown'' */
476     return driveno;                                         /* return the index */
477 }
478
479 /*
480  * Find the named drive in vinum_conf.drive, return a pointer
481  * return the index in vinum_conf.drive.
482  * Don't mark the drive as allocated (XXX SMP)
483  * If create != 0, create an entry if it doesn't exist
484  */
485 /* XXX check if we have it open from attach */
486 int
487 find_drive(const char *name, int create)
488 {
489     int driveno;
490     struct drive *drive;
491
492     if (name != NULL) {
493         for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
494             drive = &DRIVE[driveno];                        /* point to drive */
495             if ((drive->label.name[0] != '\0')              /* it has a name */
496             &&(strcmp(drive->label.name, name) == 0)        /* and it's this one */
497             &&(drive->state > drive_unallocated))           /* and it's a real one: found */
498                 return driveno;
499         }
500     }
501     /* the drive isn't in the list.  Add it if he wants */
502     if (create == 0)                                        /* don't want to create */
503         return -1;                                          /* give up */
504
505     driveno = get_empty_drive();
506     drive = &DRIVE[driveno];
507     if (name != NULL)
508         bcopy(name,                                         /* put in its name */
509             drive->label.name,
510             min(sizeof(drive->label.name),
511                 strlen(name)));
512     drive->state = drive_referenced;                        /* in use, nothing worthwhile there */
513     return driveno;                                         /* return the index */
514 }
515
516 /*
517  * Find a drive given its device name.
518  * devname must be valid.
519  * Otherwise the same as find_drive above
520  */
521 int
522 find_drive_by_dev(const char *devname, int create)
523 {
524     int driveno;
525     struct drive *drive;
526
527     for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
528         drive = &DRIVE[driveno];                            /* point to drive */
529         if ((strcmp(drive->devicename, devname) == 0)       /* it's this device */
530         &&(drive->state > drive_unallocated))               /* and it's a real one: found */
531             return driveno;
532     }
533
534     /* the drive isn't in the list.  Add it if he wants */
535     if (create == 0)                                        /* don't want to create */
536         return -1;                                          /* give up */
537
538     driveno = get_empty_drive();
539     drive = &DRIVE[driveno];
540     bcopy(devname,                                          /* put in its name */
541         drive->devicename,
542         min(sizeof(drive->devicename),
543             strlen(devname)));
544     drive->state = drive_referenced;                        /* in use, nothing worthwhile there */
545     return driveno;                                         /* return the index */
546 }
547
548 /* Find an empty subdisk in the subdisk table */
549 int
550 get_empty_sd(void)
551 {
552     int sdno;
553     struct sd *sd;
554
555     /* first see if we have one which has been deallocated */
556     for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
557         if (SD[sdno].state == sd_unallocated)               /* bingo */
558             break;
559     }
560     if (sdno >= vinum_conf.subdisks_allocated)
561         /*
562          * We've run out of space.  sdno is pointing
563          * where we want it, but at the moment we
564          * don't have the space.  Get it.
565          */
566         EXPAND(SD, struct sd, vinum_conf.subdisks_allocated, INITIAL_SUBDISKS);
567
568     /* initialize some things */
569     sd = &SD[sdno];                                         /* point to it */
570     bzero(sd, sizeof(struct sd));                           /* initialize */
571     sd->flags |= VF_NEWBORN;                                /* newly born subdisk */
572     sd->plexno = -1;                                        /* no plex */
573     sd->sectors = -1;                                       /* no space */
574     sd->driveno = -1;                                       /* no drive */
575     sd->plexoffset = -1;                                    /* and no offsets */
576     sd->driveoffset = -1;
577     return sdno;                                            /* return the index */
578 }
579
580 /* return a drive to the free pool */
581 void
582 free_drive(struct drive *drive)
583 {
584     if ((drive->state > drive_referenced)                   /* real drive */
585     ||(drive->flags & VF_OPEN)) {                           /* how can it be open without a state? */
586         LOCKDRIVE(drive);
587         if (drive->flags & VF_OPEN) {                       /* it's open, */
588             close_locked_drive(drive);                      /* close it */
589             drive->state = drive_down;                      /* and note the fact */
590         }
591         if (drive->freelist)
592             Free(drive->freelist);
593         bzero(drive, sizeof(struct drive));                 /* this also sets drive_unallocated */
594         unlockdrive(drive);
595     }
596 }
597
598 /*
599  * Find the named subdisk in vinum_conf.sd.
600  *
601  * If create != 0, create an entry if it doesn't exist
602  *
603  * Return index in vinum_conf.sd
604  */
605 int
606 find_subdisk(const char *name, int create)
607 {
608     int sdno;
609     struct sd *sd;
610
611     for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
612         if (strcmp(SD[sdno].name, name) == 0)               /* found it */
613             return sdno;
614     }
615
616     /* the subdisk isn't in the list.  Add it if he wants */
617     if (create == 0)                                        /* don't want to create */
618         return -1;                                          /* give up */
619
620     /* Allocate one and insert the name */
621     sdno = get_empty_sd();
622     sd = &SD[sdno];
623     bcopy(name, sd->name, min(sizeof(sd->name), strlen(name))); /* put in its name */
624     return sdno;                                            /* return the pointer */
625 }
626
627 /* Return space to a drive */
628 void
629 return_drive_space(int driveno, int64_t offset, int length)
630 {
631     struct drive *drive;
632     int fe;                                                 /* free list entry */
633     u_int64_t sdend;                                        /* end of our subdisk */
634     u_int64_t dend;                                         /* end of our freelist entry */
635
636     drive = &DRIVE[driveno];
637     if (drive->state == drive_up) {
638         sdend = offset + length;                            /* end of our subdisk */
639
640         /* Look for where to return the sd address space */
641         for (fe = 0;
642             (fe < drive->freelist_entries) && (drive->freelist[fe].offset < offset);
643             fe++);
644         /*
645          * Now we are pointing to the last entry, the first
646          * with a higher offset than the subdisk, or both.
647          */
648         if ((fe > 1)                                        /* not the first entry */
649         &&((fe == drive->freelist_entries)                  /* gone past the end */
650         ||(drive->freelist[fe].offset > offset)))           /* or past the block were looking for */
651             fe--;                                           /* point to the block before */
652         dend = drive->freelist[fe].offset + drive->freelist[fe].sectors; /* end of the entry */
653
654         /*
655          * At this point, we are pointing to the correct
656          * place in the free list.  A number of possibilities
657          * exist:
658          *
659          * 1.  The block to be freed starts at the end of the
660          *     block to which we are pointing.  This has two
661          *     subcases:
662          *
663          * a.  The block to be freed ends at the beginning
664          *     of the following block.  Merge the three
665          *     areas into a single block.
666          *
667          * b.  The block is shorter than the space between
668          *     the current block and the next one.  Enlarge
669          *     the current block.
670          *
671          * 2.  The block to be freed starts after the end
672          *     of the block.  Again, we have two cases:
673          *
674          * a.  It ends before the start of the following block.
675          *     Create a new free block.
676          *
677          * b.  It ends at the start of the following block.
678          *     Enlarge the following block downwards.
679          *
680          * When there is only one free space block, and the
681          * space to be returned is before it, the pointer is
682          * to a non-existent zeroth block. XXX check this
683          */
684         if (offset == dend) {                               /* Case 1: it starts at the end of this block */
685             if ((fe < drive->freelist_entries - 1)          /* we're not the last block in the free list */
686             /* and the subdisk ends at the start of the next block */
687             &&(sdend == drive->freelist[fe + 1].offset)) {
688                 drive->freelist[fe].sectors                 /* 1a: merge all three blocks */
689                     = drive->freelist[fe + 1].sectors;
690                 if (fe < drive->freelist_entries - 2)       /* still more blocks after next */
691                     bcopy(&drive->freelist[fe + 2],         /* move down one */
692                         &drive->freelist[fe + 1],
693                         (drive->freelist_entries - 2 - fe)
694                         * sizeof(struct drive_freelist));
695                 drive->freelist_entries--;                  /* one less entry in the free list */
696             } else                                          /* 1b: just enlarge this block */
697                 drive->freelist[fe].sectors += length;
698         } else {                                            /* Case 2 */
699             if (offset > dend)                              /* it starts after this block */
700                 fe++;                                       /* so look at the next block */
701             if ((fe < drive->freelist_entries)              /* we're not the last block in the free list */
702             /* and the subdisk ends at the start of this block: case 4 */
703             &&(sdend == drive->freelist[fe].offset)) {
704                 drive->freelist[fe].offset = offset;        /* it starts where the sd was */
705                 drive->freelist[fe].sectors += length;      /* and it's this much bigger */
706             } else {                                        /* case 3: non-contiguous */
707                 if (fe < drive->freelist_entries)           /* not after the last block, */
708                     bcopy(&drive->freelist[fe],             /* move the rest up one entry */
709                         &drive->freelist[fe + 1],
710                         (drive->freelist_entries - fe)
711                         * sizeof(struct drive_freelist));
712                 drive->freelist_entries++;                  /* one less entry */
713                 drive->freelist[fe].offset = offset;        /* this entry represents the sd */
714                 drive->freelist[fe].sectors = length;
715             }
716         }
717         drive->sectors_available += length;                 /* the sectors are now available */
718     }
719 }
720
721 /*
722  * Free an allocated sd entry.
723  * This performs memory management only.  remove()
724  * is responsible for checking relationships.
725  */
726 void
727 free_sd(int sdno)
728 {
729     struct sd *sd;
730
731     sd = &SD[sdno];
732     if ((sd->driveno >= 0)                                  /* we have a drive, */
733     &&(sd->sectors > 0))                                    /* and some space on it */
734         return_drive_space(sd->driveno,                     /* return the space */
735             sd->driveoffset,
736             sd->sectors);
737     if (sd->plexno >= 0)
738         PLEX[sd->plexno].subdisks--;                        /* one less subdisk */
739     destroy_dev(sd->dev);
740     bzero(sd, sizeof(struct sd));                           /* and clear it out */
741     sd->state = sd_unallocated;
742     vinum_conf.subdisks_used--;                             /* one less sd */
743 }
744
745 /* Find an empty plex in the plex table */
746 int
747 get_empty_plex(void)
748 {
749     int plexno;
750     struct plex *plex;                                      /* if we allocate one */
751
752     /* first see if we have one which has been deallocated */
753     for (plexno = 0; plexno < vinum_conf.plexes_allocated; plexno++) {
754         if (PLEX[plexno].state == plex_unallocated)         /* bingo */
755             break;                                          /* and get out of here */
756     }
757
758     if (plexno >= vinum_conf.plexes_allocated)
759         EXPAND(PLEX, struct plex, vinum_conf.plexes_allocated, INITIAL_PLEXES);
760
761     /* Found a plex.  Give it an sd structure */
762     plex = &PLEX[plexno];                                   /* this one is ours */
763     bzero(plex, sizeof(struct plex));                       /* polish it up */
764     plex->sdnos = (int *) Malloc(sizeof(int) * INITIAL_SUBDISKS_IN_PLEX); /* allocate sd table */
765     CHECKALLOC(plex->sdnos, "vinum: Can't allocate plex subdisk table");
766     bzero(plex->sdnos, (sizeof(int) * INITIAL_SUBDISKS_IN_PLEX)); /* do we need this? */
767     plex->flags |= VF_NEWBORN;                              /* newly born plex */
768     plex->subdisks = 0;                                     /* no subdisks in use */
769     plex->subdisks_allocated = INITIAL_SUBDISKS_IN_PLEX;    /* and we have space for this many */
770     plex->organization = plex_disorg;                       /* and it's not organized */
771     plex->volno = -1;                                       /* no volume yet */
772     return plexno;                                          /* return the index */
773 }
774
775 /*
776  * Find the named plex in vinum_conf.plex
777  *
778  * If create != 0, create an entry if it doesn't exist
779  * return index in vinum_conf.plex
780  */
781 int
782 find_plex(const char *name, int create)
783 {
784     int plexno;
785     struct plex *plex;
786
787     for (plexno = 0; plexno < vinum_conf.plexes_allocated; plexno++) {
788         if (strcmp(PLEX[plexno].name, name) == 0)           /* found it */
789             return plexno;
790     }
791
792     /* the plex isn't in the list.  Add it if he wants */
793     if (create == 0)                                        /* don't want to create */
794         return -1;                                          /* give up */
795
796     /* Allocate one and insert the name */
797     plexno = get_empty_plex();
798     plex = &PLEX[plexno];                                   /* point to it */
799     bcopy(name, plex->name, min(sizeof(plex->name), strlen(name))); /* put in its name */
800     return plexno;                                          /* return the pointer */
801 }
802
803 /*
804  * Free an allocated plex entry
805  * and its associated memory areas
806  */
807 void
808 free_plex(int plexno)
809 {
810     struct plex *plex;
811
812     plex = &PLEX[plexno];
813     if (plex->sdnos)
814         Free(plex->sdnos);
815     if (plex->lock)
816         Free(plex->lock);
817     destroy_dev(plex->dev);
818     bzero(plex, sizeof(struct plex));                       /* and clear it out */
819     plex->state = plex_unallocated;
820 }
821
822 /* Find an empty volume in the volume table */
823 int
824 get_empty_volume(void)
825 {
826     int volno;
827     struct volume *vol;
828     int i;
829
830     /* first see if we have one which has been deallocated */
831     for (volno = 0; volno < vinum_conf.volumes_allocated; volno++) {
832         if (VOL[volno].state == volume_unallocated)         /* bingo */
833             break;
834     }
835
836     if (volno >= vinum_conf.volumes_allocated)
837         EXPAND(VOL, struct volume, vinum_conf.volumes_allocated, INITIAL_VOLUMES);
838
839     /* Now initialize fields */
840     vol = &VOL[volno];
841     bzero(vol, sizeof(struct volume));
842     vol->flags |= VF_NEWBORN | VF_CREATED;                  /* newly born volume */
843     vol->preferred_plex = ROUND_ROBIN_READPOL;              /* round robin */
844     for (i = 0; i < MAXPLEX; i++)                           /* mark the plexes missing */
845         vol->plex[i] = -1;
846     return volno;                                           /* return the index */
847 }
848
849 /*
850  * Find the named volume in vinum_conf.volume.
851  *
852  * If create != 0, create an entry if it doesn't exist
853  * return the index in vinum_conf
854  */
855 int
856 find_volume(const char *name, int create)
857 {
858     int volno;
859     struct volume *vol;
860
861     for (volno = 0; volno < vinum_conf.volumes_allocated; volno++) {
862         if (strcmp(VOL[volno].name, name) == 0)             /* found it */
863             return volno;
864     }
865
866     /* the volume isn't in the list.  Add it if he wants */
867     if (create == 0)                                        /* don't want to create */
868         return -1;                                          /* give up */
869
870     /* Allocate one and insert the name */
871     volno = get_empty_volume();
872     vol = &VOL[volno];
873     bcopy(name, vol->name, min(sizeof(vol->name), strlen(name))); /* put in its name */
874     vol->blocksize = DEV_BSIZE;                             /* block size of this volume */
875     return volno;                                           /* return the pointer */
876 }
877
878 /*
879  * Free an allocated volume entry
880  * and its associated memory areas
881  */
882 void
883 free_volume(int volno)
884 {
885     struct volume *vol;
886
887     vol = &VOL[volno];
888     destroy_dev(vol->dev);
889     bzero(vol, sizeof(struct volume));                      /* and clear it out */
890     vol->state = volume_unallocated;
891 }
892
893 /*
894  * Handle a drive definition.  We store the information in the global variable
895  * drive, so we don't need to allocate.
896  *
897  * If we find an error, print a message and return
898  */
899 void
900 config_drive(int update)
901 {
902     enum drive_label_info partition_status;                 /* info about the partition */
903     int parameter;
904     int driveno;                                            /* index of drive in vinum_conf */
905     struct drive *drive;                                    /* and pointer to it */
906     int otherdriveno;                                       /* index of possible second drive */
907     int sdno;
908
909     if (tokens < 2)                                         /* not enough tokens */
910         throw_rude_remark(EINVAL, "Drive has no name\n");
911     driveno = find_drive(token[1], 1);                      /* allocate a drive to initialize */
912     drive = &DRIVE[driveno];                                /* and get a pointer */
913     if (update && ((drive->flags & VF_NEWBORN) == 0))       /* this drive exists already */
914         return;                                             /* don't do anything */
915     drive->flags &= ~VF_NEWBORN;                            /* no longer newly born */
916
917     if (drive->state != drive_referenced) {                 /* we already know this drive */
918         /*
919          * XXX Check which definition is more up-to-date.  Give
920          * preference for the definition on its own drive.
921          */
922         return;                                             /* XXX */
923     }
924     for (parameter = 2; parameter < tokens; parameter++) {  /* look at the other tokens */
925         switch (get_keyword(token[parameter], &keyword_set)) {
926         case kw_device:
927             parameter++;
928             otherdriveno = find_drive_by_dev(token[parameter], 0); /* see if it exists already */
929             if (otherdriveno >= 0) {                        /* yup, */
930                 drive->state = drive_unallocated;           /* deallocate the drive */
931                 throw_rude_remark(EEXIST,                   /* and complain */
932                     "Drive %s would have same device as drive %s",
933                     token[1],
934                     DRIVE[otherdriveno].label.name);
935             }
936             if (drive->devicename[0] == '/') {              /* we know this drive... */
937                 if (strcmp(drive->devicename, token[parameter])) /* different name */
938                     close_drive(drive);                     /* close it if it's open */
939                 else                                        /* no change */
940                     break;
941             }
942             /* open the device and get the configuration */
943             bcopy(token[parameter],                         /* insert device information */
944                 drive->devicename,
945                 min(sizeof(drive->devicename),
946                     strlen(token[parameter])));
947             partition_status = read_drive_label(drive, 1);
948             switch (partition_status) {
949             case DL_CANT_OPEN:                              /* not our kind */
950                 close_drive(drive);
951                 if (drive->lasterror == EFTYPE)             /* wrong kind of partition */
952                     throw_rude_remark(drive->lasterror,
953                         "Drive %s has invalid partition type",
954                         drive->label.name);
955                 else                                        /* I/O error of some kind */
956                     throw_rude_remark(drive->lasterror,
957                         "Can't initialize drive %s",
958                         drive->label.name);
959                 break;
960
961             case DL_WRONG_DRIVE:                            /* valid drive, not the name we expected */
962                 if (vinum_conf.flags & VF_FORCECONFIG) {    /* but we'll accept that */
963                     bcopy(token[1], drive->label.name, sizeof(drive->label.name));
964                     break;
965                 }
966                 close_drive(drive);
967                 /*
968                  * There's a potential race condition here:
969                  * the rude remark refers to a field in an
970                  * unallocated drive, which potentially could
971                  * be reused.  This works because we're the only
972                  * thread accessing the config at the moment.
973                  */
974                 drive->state = drive_unallocated;           /* throw it away completely */
975                 throw_rude_remark(drive->lasterror,
976                     "Incorrect drive name %s specified for drive %s",
977                     token[1],
978                     drive->label.name);
979                 break;
980
981             case DL_DELETED_LABEL:                          /* it was a drive, but we deleted it */
982             case DL_NOT_OURS:                               /* nothing to do with the rest */
983             case DL_OURS:
984                 break;
985             }
986             /*
987              * read_drive_label overwrites the device name.
988              * If we get here, we can have the drive,
989              * so put it back again
990              */
991             bcopy(token[parameter],
992                 drive->devicename,
993                 min(sizeof(drive->devicename),
994                     strlen(token[parameter])));
995             break;
996
997         case kw_state:
998             parameter++;                                    /* skip the keyword */
999             if (vinum_conf.flags & VF_READING_CONFIG)
1000                 drive->state = DriveState(token[parameter]); /* set the state */
1001             break;
1002
1003         case kw_hotspare:                                   /* this drive is a hot spare */
1004             drive->flags |= VF_HOTSPARE;
1005             break;
1006
1007         default:
1008             close_drive(drive);
1009             throw_rude_remark(EINVAL,
1010                 "Drive %s, invalid keyword: %s",
1011                 token[1],
1012                 token[parameter]);
1013         }
1014     }
1015
1016     if (drive->devicename[0] != '/') {
1017         drive->state = drive_unallocated;                   /* deallocate the drive */
1018         throw_rude_remark(EINVAL, "No device name for %s", drive->label.name);
1019     }
1020     vinum_conf.drives_used++;                               /* passed all hurdles: one more in use */
1021     /*
1022      * If we're replacing a drive, it could be that
1023      * we already have subdisks referencing this
1024      * drive.  Note where they should be and change
1025      * their state to obsolete.
1026      */
1027     for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
1028         if ((SD[sdno].state > sd_referenced)
1029             && (SD[sdno].driveno == driveno)) {
1030             give_sd_to_drive(sdno);
1031             if (SD[sdno].state > sd_stale)
1032                 SD[sdno].state = sd_stale;
1033         }
1034     }
1035 }
1036
1037 /*
1038  * Handle a subdisk definition.  We store the information in the global variable
1039  * sd, so we don't need to allocate.
1040  *
1041  * If we find an error, print a message and return
1042  */
1043 void
1044 config_subdisk(int update)
1045 {
1046     int parameter;
1047     int sdno;                                               /* index of sd in vinum_conf */
1048     struct sd *sd;                                          /* and pointer to it */
1049     u_int64_t size;
1050     int detached = 0;                                       /* set to 1 if this is a detached subdisk */
1051     int sdindex = -1;                                       /* index in plexes subdisk table */
1052     enum sdstate state = sd_unallocated;                    /* state to set, if specified */
1053     int autosize = 0;                                       /* set if we autosize in give_sd_to_drive */
1054     int namedsdno;                                          /* index of another with this name */
1055     char partition = 0;                                     /* partition of external subdisk */
1056
1057     sdno = get_empty_sd();                                  /* allocate an SD to initialize */
1058     sd = &SD[sdno];                                         /* and get a pointer */
1059
1060     for (parameter = 1; parameter < tokens; parameter++) {  /* look at the other tokens */
1061         switch (get_keyword(token[parameter], &keyword_set)) {
1062             /*
1063              * If we have a 'name' parameter, it must
1064              * come first, because we're too lazy to tidy
1065              * up dangling refs if it comes later.
1066              */
1067         case kw_name:
1068             namedsdno = find_subdisk(token[++parameter], 0); /* find an existing sd with this name */
1069             if (namedsdno >= 0) {                           /* got one */
1070                 if (SD[namedsdno].state == sd_referenced) { /* we've been told about this one */
1071                     if (parameter > 2)
1072                         throw_rude_remark(EINVAL,
1073                             "sd %s: name parameter must come first\n", /* no go */
1074                             token[parameter]);
1075                     else {
1076                         int i;
1077                         struct plex *plex;                  /* for tidying up dangling references */
1078
1079                         *sd = SD[namedsdno];                /* copy from the referenced one */
1080                         SD[namedsdno].state = sd_unallocated; /* and deallocate the referenced one */
1081                         plex = &PLEX[sd->plexno];           /* now take a look at our plex */
1082                         for (i = 0; i < plex->subdisks; i++) { /* look for the pointer */
1083                             if (plex->sdnos[i] == namedsdno) /* pointing to the old subdisk */
1084                                 plex->sdnos[i] = sdno;      /* bend it to point here */
1085                         }
1086                     }
1087                 }
1088                 if (update)                                 /* are we updating? */
1089                     return;                                 /* that's OK, nothing more to do */
1090                 else
1091                     throw_rude_remark(EINVAL, "Duplicate subdisk %s", token[parameter]);
1092             } else
1093                 bcopy(token[parameter],
1094                     sd->name,
1095                     min(sizeof(sd->name), strlen(token[parameter])));
1096             break;
1097
1098         case kw_detached:
1099             detached = 1;
1100             break;
1101
1102         case kw_plexoffset:
1103             size = sizespec(token[++parameter]);
1104             if ((size == -1)                                /* unallocated */
1105             &&(vinum_conf.flags & VF_READING_CONFIG))       /* reading from disk */
1106                 break;                                      /* invalid sd; just ignore it */
1107             if ((size % DEV_BSIZE) != 0)
1108                 throw_rude_remark(EINVAL,
1109                     "sd %s, bad plex offset alignment: %lld",
1110                     sd->name,
1111                     (long long) size);
1112             else
1113                 sd->plexoffset = size / DEV_BSIZE;
1114             break;
1115
1116         case kw_driveoffset:
1117             size = sizespec(token[++parameter]);
1118             if ((size == -1)                                /* unallocated */
1119             &&(vinum_conf.flags & VF_READING_CONFIG))       /* reading from disk */
1120                 break;                                      /* invalid sd; just ignore it */
1121             if ((size % DEV_BSIZE) != 0)
1122                 throw_rude_remark(EINVAL,
1123                     "sd %s, bad drive offset alignment: %lld",
1124                     sd->name,
1125                     (long long) size);
1126             else
1127                 sd->driveoffset = size / DEV_BSIZE;
1128             break;
1129
1130         case kw_len:
1131             if (get_keyword(token[++parameter], &keyword_set) == kw_max) /* select maximum size from drive */
1132                 size = 0;                                   /* this is how we say it :-) */
1133             else
1134                 size = sizespec(token[parameter]);
1135             if ((size % DEV_BSIZE) != 0)
1136                 throw_rude_remark(EINVAL, "sd %s, length %d not multiple of sector size", sd->name, size);
1137             else
1138                 sd->sectors = size / DEV_BSIZE;
1139             /*
1140              * We have a problem with autosizing: we need to
1141              * give the drive to the plex before we give it
1142              * to the drive, in order to be clean if we give
1143              * up in the middle, but at this time the size hasn't
1144              * been set.  Note that we have to fix up after
1145              * giving the subdisk to the drive.
1146              */
1147             if (size == 0)
1148                 autosize = 1;                               /* note that we're autosizing */
1149             break;
1150
1151         case kw_drive:
1152             sd->driveno = find_drive(token[++parameter], 1); /* insert drive information */
1153             break;
1154
1155         case kw_plex:
1156             sd->plexno = find_plex(token[++parameter], 1);  /* insert plex information */
1157             break;
1158
1159             /*
1160              * Set the state.  We can't do this directly,
1161              * because give_sd_to_plex may change it
1162              */
1163         case kw_state:
1164             parameter++;                                    /* skip the keyword */
1165             if (vinum_conf.flags & VF_READING_CONFIG)
1166                 state = SdState(token[parameter]);          /* set the state */
1167             break;
1168
1169         case kw_partition:
1170             parameter++;                                    /* skip the keyword */
1171             if ((strlen(token[parameter]) != 1)
1172                 || (token[parameter][0] < 'a')
1173                 || (token[parameter][0] > 'h'))
1174                 throw_rude_remark(EINVAL,
1175                     "%s: invalid partition %c",
1176                     sd->name,
1177                     token[parameter][0]);
1178             else
1179                 partition = token[parameter][0];
1180             break;
1181
1182         case kw_retryerrors:
1183             sd->flags |= VF_RETRYERRORS;
1184             break;
1185
1186         default:
1187             throw_rude_remark(EINVAL, "%s: invalid keyword: %s", sd->name, token[parameter]);
1188         }
1189     }
1190
1191     /* Check we have a drive name */
1192     if (sd->driveno < 0) {                                  /* didn't specify a drive */
1193         sd->driveno = current_drive;                        /* set to the current drive */
1194         if (sd->driveno < 0)                                /* no current drive? */
1195             throw_rude_remark(EINVAL, "Subdisk %s is not associated with a drive", sd->name);
1196     }
1197     /*
1198      * This is tacky.  If something goes wrong
1199      * with the checks, we may end up losing drive
1200      * space.  FIXME.
1201      */
1202     if (autosize != 0)                                      /* need to find a size, */
1203         give_sd_to_drive(sdno);                             /* do it before the plex */
1204
1205     /*  Check for a plex name */
1206     if ((sd->plexno < 0)                                    /* didn't specify a plex */
1207     &&(!detached))                                          /* and didn't say not to, */
1208         sd->plexno = current_plex;                          /* set to the current plex */
1209
1210     if (sd->plexno >= 0)
1211         sdindex = give_sd_to_plex(sd->plexno, sdno);        /* now tell the plex that it has this sd */
1212
1213     sd->sdno = sdno;                                        /* point to our entry in the table */
1214
1215     /* Does the subdisk have a name?  If not, give it one */
1216     if (sd->name[0] == '\0') {                              /* no name */
1217         char sdsuffix[8];                                   /* form sd name suffix here */
1218
1219         /* Do we have a plex name? */
1220         if (sdindex >= 0)                                   /* we have a plex */
1221             strcpy(sd->name, PLEX[sd->plexno].name);        /* take it from there */
1222         else                                                /* no way */
1223             throw_rude_remark(EINVAL, "Unnamed sd is not associated with a plex");
1224         sprintf(sdsuffix, ".s%d", sdindex);                 /* form the suffix */
1225         strcat(sd->name, sdsuffix);                         /* and add it to the name */
1226     }
1227     /* do we have complete info for this subdisk? */
1228     if (sd->sectors < 0)
1229         throw_rude_remark(EINVAL, "sd %s has no length spec", sd->name);
1230
1231     sd->dev = make_dev(&vinum_cdevsw, VINUMRMINOR(sdno, VINUM_SD_TYPE),
1232         UID_ROOT,
1233         GID_WHEEL,
1234         S_IRUSR | S_IWUSR,
1235         "vinum/sd/%s",
1236         sd->name);
1237     if (state != sd_unallocated)                            /* we had a specific state to set */
1238         sd->state = state;                                  /* do it now */
1239     else if (sd->state == sd_unallocated)                   /* no, nothing set yet, */
1240         sd->state = sd_empty;                               /* must be empty */
1241     if (autosize == 0)                                      /* no autoconfig, do the drive now */
1242         give_sd_to_drive(sdno);
1243     vinum_conf.subdisks_used++;                             /* one more in use */
1244 }
1245
1246 /*
1247  * Handle a plex definition.
1248  */
1249 void
1250 config_plex(int update)
1251 {
1252     int parameter;
1253     int plexno;                                             /* index of plex in vinum_conf */
1254     struct plex *plex;                                      /* and pointer to it */
1255     int pindex = MAXPLEX;                                   /* index in volume's plex list */
1256     int detached = 0;                                       /* don't give it to a volume */
1257     int namedplexno;
1258     enum plexstate state = plex_init;                       /* state to set at end */
1259
1260     current_plex = -1;                                      /* forget the previous plex */
1261     plexno = get_empty_plex();                              /* allocate a plex */
1262     plex = &PLEX[plexno];                                   /* and point to it */
1263     plex->plexno = plexno;                                  /* and back to the config */
1264
1265     for (parameter = 1; parameter < tokens; parameter++) {  /* look at the other tokens */
1266         switch (get_keyword(token[parameter], &keyword_set)) {
1267             /*
1268              * If we have a 'name' parameter, it must
1269              * come first, because we're too lazy to tidy
1270              * up dangling refs if it comes later.
1271              */
1272         case kw_name:
1273             namedplexno = find_plex(token[++parameter], 0); /* find an existing plex with this name */
1274             if (namedplexno >= 0) {                         /* plex exists already, */
1275                 if (PLEX[namedplexno].state == plex_referenced) { /* we've been told about this one */
1276                     if (parameter > 2)                      /* we've done other things first, */
1277                         throw_rude_remark(EINVAL,
1278                             "plex %s: name parameter must come first\n", /* no go */
1279                             token[parameter]);
1280                     else {
1281                         int i;
1282                         struct volume *vol;                 /* for tidying up dangling references */
1283
1284                         *plex = PLEX[namedplexno];          /* get the info */
1285                         PLEX[namedplexno].state = plex_unallocated; /* and deallocate the other one */
1286                         vol = &VOL[plex->volno];            /* point to the volume */
1287                         for (i = 0; i < MAXPLEX; i++) {     /* for each plex */
1288                             if (vol->plex[i] == namedplexno)
1289                                 vol->plex[i] = plexno;      /* bend the pointer */
1290                         }
1291                     }
1292                     break;                                  /* use this one */
1293                 }
1294                 if (update)                                 /* are we updating? */
1295                     return;                                 /* yes: that's OK, just return */
1296                 else
1297                     throw_rude_remark(EINVAL, "Duplicate plex %s", token[parameter]);
1298             } else
1299                 bcopy(token[parameter],                     /* put in the name */
1300                     plex->name,
1301                     min(MAXPLEXNAME, strlen(token[parameter])));
1302             break;
1303
1304         case kw_detached:
1305             detached = 1;
1306             break;
1307
1308         case kw_org:                                        /* plex organization */
1309             switch (get_keyword(token[++parameter], &keyword_set)) {
1310             case kw_concat:
1311                 plex->organization = plex_concat;
1312                 break;
1313
1314             case kw_striped:
1315                 {
1316                     int stripesize = sizespec(token[++parameter]);
1317
1318                     plex->organization = plex_striped;
1319                     if (stripesize % DEV_BSIZE != 0)        /* not a multiple of block size, */
1320                         throw_rude_remark(EINVAL, "plex %s: stripe size %d not a multiple of sector size",
1321                             plex->name,
1322                             stripesize);
1323                     else
1324                         plex->stripesize = stripesize / DEV_BSIZE;
1325                     break;
1326                 }
1327
1328             case kw_raid4:
1329                 {
1330                     int stripesize = sizespec(token[++parameter]);
1331
1332                     plex->organization = plex_raid4;
1333                     if (stripesize % DEV_BSIZE != 0)        /* not a multiple of block size, */
1334                         throw_rude_remark(EINVAL, "plex %s: stripe size %d not a multiple of sector size",
1335                             plex->name,
1336                             stripesize);
1337                     else
1338                         plex->stripesize = stripesize / DEV_BSIZE;
1339                     break;
1340                 }
1341
1342             case kw_raid5:
1343                 {
1344                     int stripesize = sizespec(token[++parameter]);
1345
1346                     plex->organization = plex_raid5;
1347                     if (stripesize % DEV_BSIZE != 0)        /* not a multiple of block size, */
1348                         throw_rude_remark(EINVAL, "plex %s: stripe size %d not a multiple of sector size",
1349                             plex->name,
1350                             stripesize);
1351                     else
1352                         plex->stripesize = stripesize / DEV_BSIZE;
1353                     break;
1354                 }
1355
1356             default:
1357                 throw_rude_remark(EINVAL, "Invalid plex organization");
1358             }
1359             if (isstriped(plex)
1360                 && (plex->stripesize == 0))                 /* didn't specify a valid stripe size */
1361                 throw_rude_remark(EINVAL, "Need a stripe size parameter");
1362             break;
1363
1364         case kw_volume:
1365             plex->volno = find_volume(token[++parameter], 1); /* insert a pointer to the volume */
1366             break;
1367
1368         case kw_sd:                                         /* add a subdisk */
1369             {
1370                 int sdno;
1371
1372                 sdno = find_subdisk(token[++parameter], 1); /* find a subdisk */
1373                 SD[sdno].plexoffset = sizespec(token[++parameter]); /* get the offset */
1374                 give_sd_to_plex(plexno, sdno);              /* and insert it there */
1375                 break;
1376             }
1377
1378         case kw_state:
1379             parameter++;                                    /* skip the keyword */
1380             if (vinum_conf.flags & VF_READING_CONFIG)
1381                 state = PlexState(token[parameter]);        /* set the state */
1382             break;
1383
1384         default:
1385             throw_rude_remark(EINVAL, "plex %s, invalid keyword: %s",
1386                 plex->name,
1387                 token[parameter]);
1388         }
1389     }
1390
1391     if (plex->organization == plex_disorg)
1392         throw_rude_remark(EINVAL, "No plex organization specified");
1393
1394     if ((plex->volno < 0)                                   /* we don't have a volume */
1395     &&(!detached))                                          /* and we wouldn't object */
1396         plex->volno = current_volume;
1397
1398     if (plex->volno >= 0)
1399         pindex = give_plex_to_volume(plex->volno, plexno);  /* Now tell the volume that it has this plex */
1400
1401     /* Does the plex have a name?  If not, give it one */
1402     if (plex->name[0] == '\0') {                            /* no name */
1403         char plexsuffix[8];                                 /* form plex name suffix here */
1404         /* Do we have a volume name? */
1405         if (plex->volno >= 0)                               /* we have a volume */
1406             strcpy(plex->name,                              /* take it from there */
1407                 VOL[plex->volno].name);
1408         else                                                /* no way */
1409             throw_rude_remark(EINVAL, "Unnamed plex is not associated with a volume");
1410         sprintf(plexsuffix, ".p%d", pindex);                /* form the suffix */
1411         strcat(plex->name, plexsuffix);                     /* and add it to the name */
1412     }
1413     if (isstriped(plex)) {
1414         plex->lock = (struct rangelock *)
1415             Malloc(PLEX_LOCKS * sizeof(struct rangelock));
1416         CHECKALLOC(plex->lock, "vinum: Can't allocate lock table\n");
1417         bzero((char *) plex->lock, PLEX_LOCKS * sizeof(struct rangelock));
1418         mtx_init(&plex->lockmtx, plex->name, "plex", MTX_DEF);
1419     }
1420     /* Note the last plex we configured */
1421     current_plex = plexno;
1422     plex->state = state;                                    /* set whatever state we chose */
1423     vinum_conf.plexes_used++;                               /* one more in use */
1424     plex->dev = make_dev(&vinum_cdevsw,
1425         VINUMRMINOR(plexno, VINUM_PLEX_TYPE),
1426         UID_ROOT,
1427         GID_WHEEL,
1428         S_IRUSR | S_IWUSR,
1429         "vinum/plex/%s",
1430         plex->name);
1431 }
1432
1433 /*
1434  * Handle a volume definition.
1435  * If we find an error, print a message, deallocate the nascent volume, and return
1436  */
1437 void
1438 config_volume(int update)
1439 {
1440     int parameter;
1441     int volno;
1442     struct volume *vol;                                     /* collect volume info here */
1443     int i;
1444
1445     if (tokens < 2)                                         /* not enough tokens */
1446         throw_rude_remark(EINVAL, "Volume has no name");
1447     current_volume = -1;                                    /* forget the previous volume */
1448     volno = find_volume(token[1], 1);                       /* allocate a volume to initialize */
1449     vol = &VOL[volno];                                      /* and get a pointer */
1450     if (update && ((vol->flags & VF_CREATED) == 0))         /* this volume exists already */
1451         return;                                             /* don't do anything */
1452     vol->flags &= ~VF_CREATED;                              /* it exists now */
1453
1454     for (parameter = 2; parameter < tokens; parameter++) {  /* look at all tokens */
1455         switch (get_keyword(token[parameter], &keyword_set)) {
1456         case kw_plex:
1457             {
1458                 int plexno;                                 /* index of this plex */
1459                 int myplexno;                               /* and index if it's already ours */
1460
1461                 plexno = find_plex(token[++parameter], 1);  /* find a plex */
1462                 if (plexno < 0)                             /* couldn't */
1463                     break;                                  /* we've already had an error message */
1464                 myplexno = my_plex(volno, plexno);          /* does it already belong to us? */
1465                 if (myplexno > 0)                           /* yes, shouldn't get it again */
1466                     throw_rude_remark(EINVAL,
1467                         "Plex %s already belongs to volume %s",
1468                         token[parameter],
1469                         vol->name);
1470                 else if (++vol->plexes > 8)                 /* another entry */
1471                     throw_rude_remark(EINVAL,
1472                         "Too many plexes for volume %s",
1473                         vol->name);
1474                 vol->plex[vol->plexes - 1] = plexno;
1475                 PLEX[plexno].state = plex_referenced;       /* we know something about it */
1476                 PLEX[plexno].volno = volno;                 /* and this volume references it */
1477             }
1478             break;
1479
1480         case kw_readpol:
1481             switch (get_keyword(token[++parameter], &keyword_set)) { /* decide what to do */
1482             case kw_round:
1483                 vol->preferred_plex = ROUND_ROBIN_READPOL;  /* default */
1484                 break;
1485
1486             case kw_prefer:
1487                 {
1488                     int myplexno;                           /* index of this plex */
1489
1490                     myplexno = find_plex(token[++parameter], 1); /* find a plex */
1491                     if (myplexno < 0)                       /* couldn't */
1492                         break;                              /* we've already had an error message */
1493                     myplexno = my_plex(volno, myplexno);    /* does it already belong to us? */
1494                     if (myplexno > 0)                       /* yes */
1495                         vol->preferred_plex = myplexno;     /* just note the index */
1496                     else if (++vol->plexes > 8)             /* another entry */
1497                         throw_rude_remark(EINVAL, "Too many plexes");
1498                     else {                                  /* space for the new plex */
1499                         vol->plex[vol->plexes - 1] = myplexno; /* add it to our list */
1500                         vol->preferred_plex = vol->plexes - 1; /* and note the index */
1501                     }
1502                 }
1503                 break;
1504
1505             default:
1506                 throw_rude_remark(EINVAL, "Invalid read policy");
1507             }
1508
1509         case kw_setupstate:
1510             vol->flags |= VF_CONFIG_SETUPSTATE;             /* set the volume up later on */
1511             break;
1512
1513         case kw_state:
1514             parameter++;                                    /* skip the keyword */
1515             if (vinum_conf.flags & VF_READING_CONFIG)
1516                 vol->state = VolState(token[parameter]);    /* set the state */
1517             break;
1518
1519             /*
1520              * XXX experimental ideas.  These are not
1521              * documented, and will not be until I
1522              * decide they're worth keeping
1523              */
1524         case kw_writethrough:                               /* set writethrough mode */
1525             vol->flags |= VF_WRITETHROUGH;
1526             break;
1527
1528         case kw_writeback:                                  /* set writeback mode */
1529             vol->flags &= ~VF_WRITETHROUGH;
1530             break;
1531
1532         case kw_raw:
1533             vol->flags |= VF_RAW;                           /* raw volume (no label) */
1534             break;
1535
1536         default:
1537             throw_rude_remark(EINVAL, "volume %s, invalid keyword: %s",
1538                 vol->name,
1539                 token[parameter]);
1540         }
1541     }
1542     current_volume = volno;                                 /* note last referred volume */
1543     vol->volno = volno;                                     /* also note in volume */
1544
1545     /*
1546      * Before we can actually use the volume, we need
1547      * a volume label.  We could start to fake one here,
1548      * but it will be a lot easier when we have some
1549      * to copy from the drives, so defer it until we
1550      * set up the configuration. XXX
1551      */
1552     if (vol->state == volume_unallocated)
1553         vol->state = volume_down;                           /* now ready to bring up at the end */
1554
1555     /* Find out how big our volume is */
1556     for (i = 0; i < vol->plexes; i++)
1557         vol->size = max(vol->size, PLEX[vol->plex[i]].length);
1558     vinum_conf.volumes_used++;                              /* one more in use */
1559     vol->dev = make_dev(&vinum_cdevsw,
1560         VINUMRMINOR(volno, VINUM_VOLUME_TYPE),
1561         UID_ROOT,
1562         GID_WHEEL,
1563         S_IRUSR | S_IWUSR,
1564         "vinum/%s",
1565         vol->name);
1566 }
1567
1568 /*
1569  * Parse a config entry.  CARE!  This destroys the original contents of the
1570  * config entry, which we don't really need after this.  More specifically, it
1571  * places \0 characters at the end of each token.
1572  *
1573  * Return 0 if all is well, otherwise EINVAL for invalid keyword,
1574  * or ENOENT if 'read' command doesn't find any drives.
1575  */
1576 int
1577 parse_config(char *cptr, struct keywordset *keyset, int update)
1578 {
1579     int status;
1580
1581     status = 0;                                             /* until proven otherwise */
1582     tokens = tokenize(cptr, token, MAXTOKEN);               /* chop up into tokens */
1583
1584     if (tokens <= 0)                                        /* screwed up or empty line */
1585         return tokens;                                      /* give up */
1586     else if (tokens == MAXTOKEN)                            /* too many */
1587         throw_rude_remark(E2BIG,
1588             "Configuration error for %s: too many parameters",
1589             token[1]);
1590
1591     if (token[0][0] == '#')                                 /* comment line */
1592         return 0;
1593
1594     switch (get_keyword(token[0], keyset)) {                /* decide what to do */
1595     case kw_read:                                           /* read config from a specified drive */
1596         status = vinum_scandisk(&token[1], tokens - 1);     /* read the config from disk */
1597         break;
1598
1599     case kw_drive:
1600         config_drive(update);
1601         break;
1602
1603     case kw_subdisk:
1604         config_subdisk(update);
1605         break;
1606
1607     case kw_plex:
1608         config_plex(update);
1609         break;
1610
1611     case kw_volume:
1612         config_volume(update);
1613         break;
1614
1615         /* Anything else is invalid in this context */
1616     default:
1617         throw_rude_remark(EINVAL,                           /* should we die? */
1618             "Invalid configuration information: %s",
1619             token[0]);
1620     }
1621     return status;
1622 }
1623
1624 /*
1625  * parse a line handed in from userland via ioctl.
1626  * This differs only by the error reporting mechanism:
1627  * we return the error indication in the reply to the
1628  * ioctl, so we need to set a global static pointer in
1629  * this file.  This technique works because we have
1630  * ensured that configuration is performed in a single-
1631  * threaded manner
1632  */
1633 int
1634 parse_user_config(char *cptr, struct keywordset *keyset)
1635 {
1636     int status;
1637
1638     ioctl_reply = (struct _ioctl_reply *) cptr;
1639     status = parse_config(cptr, keyset, 0);
1640     if (status == ENOENT)                                   /* from scandisk, but it can't tell us */
1641         strcpy(ioctl_reply->msg, "no drives found");
1642     ioctl_reply = NULL;                                     /* don't do this again */
1643     return status;
1644 }
1645
1646 /* Remove an object */
1647 void
1648 remove(struct vinum_ioctl_msg *msg)
1649 {
1650     struct vinum_ioctl_msg message = *msg;                  /* make a copy to hand on */
1651
1652     ioctl_reply = (struct _ioctl_reply *) msg;              /* reinstate the address to reply to */
1653     ioctl_reply->error = 0;                                 /* no error, */
1654     ioctl_reply->msg[0] = '\0';                             /* no message */
1655
1656     switch (message.type) {
1657     case drive_object:
1658         remove_drive_entry(message.index, message.force);
1659         updateconfig(0);
1660         return;
1661
1662     case sd_object:
1663         remove_sd_entry(message.index, message.force, message.recurse);
1664         updateconfig(0);
1665         return;
1666
1667     case plex_object:
1668         remove_plex_entry(message.index, message.force, message.recurse);
1669         updateconfig(0);
1670         return;
1671
1672     case volume_object:
1673         remove_volume_entry(message.index, message.force, message.recurse);
1674         updateconfig(0);
1675         return;
1676
1677     default:
1678         ioctl_reply->error = EINVAL;
1679         strcpy(ioctl_reply->msg, "Invalid object type");
1680     }
1681 }
1682
1683 /* Remove a drive.  */
1684 void
1685 remove_drive_entry(int driveno, int force)
1686 {
1687     struct drive *drive = &DRIVE[driveno];
1688     int sdno;
1689
1690     if ((driveno > vinum_conf.drives_allocated)             /* not a valid drive */
1691     ||(drive->state == drive_unallocated)) {                /* or nothing there */
1692         ioctl_reply->error = EINVAL;
1693         strcpy(ioctl_reply->msg, "No such drive");
1694     } else if (drive->opencount > 0) {                      /* we have subdisks */
1695         if (force) {                                        /* do it at any cost */
1696             for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) {
1697                 if ((SD[sdno].state != sd_unallocated)      /* subdisk is allocated */
1698                 &&(SD[sdno].driveno == driveno))            /* and it belongs to this drive */
1699                     remove_sd_entry(sdno, force, 0);
1700             }
1701             remove_drive(driveno);                          /* now remove it */
1702             vinum_conf.drives_used--;                       /* one less drive */
1703         } else
1704             ioctl_reply->error = EBUSY;                     /* can't do that */
1705     } else {
1706         remove_drive(driveno);                              /* just remove it */
1707         vinum_conf.drives_used--;                           /* one less drive */
1708     }
1709 }
1710
1711 /* remove a subdisk */
1712 void
1713 remove_sd_entry(int sdno, int force, int recurse)
1714 {
1715     struct sd *sd = &SD[sdno];
1716
1717     if ((sdno > vinum_conf.subdisks_allocated)              /* not a valid sd */
1718     ||(sd->state == sd_unallocated)) {                      /* or nothing there */
1719         ioctl_reply->error = EINVAL;
1720         strcpy(ioctl_reply->msg, "No such subdisk");
1721     } else if (sd->flags & VF_OPEN)                         /* we're open */
1722         ioctl_reply->error = EBUSY;                         /* no getting around that */
1723     else if (sd->plexno >= 0) {                             /* we have a plex */
1724         if (force) {                                        /* do it at any cost */
1725             struct plex *plex = &PLEX[sd->plexno];          /* point to our plex */
1726             int mysdno;
1727
1728             for (mysdno = 0;                                /* look for ourselves */
1729                 mysdno < plex->subdisks && &SD[plex->sdnos[mysdno]] != sd;
1730                 mysdno++);
1731             if (mysdno == plex->subdisks)                   /* didn't find it */
1732                 log(LOG_ERR,
1733                     "Error removing subdisk %s: not found in plex %s\n",
1734                     SD[mysdno].name,
1735                     plex->name);
1736             else {                                          /* remove the subdisk from plex */
1737                 if (mysdno < (plex->subdisks - 1))          /* not the last subdisk */
1738                     bcopy(&plex->sdnos[mysdno + 1],
1739                         &plex->sdnos[mysdno],
1740                         (plex->subdisks - 1 - mysdno) * sizeof(int));
1741                 plex->subdisks--;
1742                 sd->plexno = -1;                            /* disown the subdisk */
1743             }
1744
1745             /*
1746              * Removing a subdisk from a striped or
1747              * RAID-4 or RAID-5 plex really tears the
1748              * hell out of the structure, and it needs
1749              * to be reinitialized.
1750              */
1751             if (plex->organization != plex_concat)          /* not concatenated, */
1752                 set_plex_state(plex->plexno, plex_faulty, setstate_force); /* need to reinitialize */
1753             log(LOG_INFO, "vinum: removing %s\n", sd->name);
1754             free_sd(sdno);
1755         } else
1756             ioctl_reply->error = EBUSY;                     /* can't do that */
1757     } else {
1758         log(LOG_INFO, "vinum: removing %s\n", sd->name);
1759         free_sd(sdno);
1760     }
1761 }
1762
1763 /* remove a plex */
1764 void
1765 remove_plex_entry(int plexno, int force, int recurse)
1766 {
1767     struct plex *plex = &PLEX[plexno];
1768     int sdno;
1769
1770     if ((plexno > vinum_conf.plexes_allocated)              /* not a valid plex */
1771     ||(plex->state == plex_unallocated)) {                  /* or nothing there */
1772         ioctl_reply->error = EINVAL;
1773         strcpy(ioctl_reply->msg, "No such plex");
1774     } else if (plex->flags & VF_OPEN) {                     /* we're open */
1775         ioctl_reply->error = EBUSY;                         /* no getting around that */
1776         return;
1777     }
1778     if (plex->subdisks) {
1779         if (force) {                                        /* do it anyway */
1780             if (recurse) {                                  /* remove all below */
1781                 int sds = plex->subdisks;
1782                 for (sdno = 0; sdno < sds; sdno++)
1783                     free_sd(plex->sdnos[sdno]);             /* free all subdisks */
1784             } else {                                        /* just tear them out */
1785                 int sds = plex->subdisks;
1786                 for (sdno = 0; sdno < sds; sdno++)
1787                     SD[plex->sdnos[sdno]].plexno = -1;      /* no plex any more */
1788             }
1789         } else {                                            /* can't do it without force */
1790             ioctl_reply->error = EBUSY;                     /* can't do that */
1791             return;
1792         }
1793     }
1794     if (plex->volno >= 0) {                                 /* we are part of a volume */
1795         if (force) {                                        /* do it at any cost */
1796             struct volume *vol = &VOL[plex->volno];
1797             int myplexno;
1798
1799             for (myplexno = 0; myplexno < vol->plexes; myplexno++)
1800                 if (vol->plex[myplexno] == plexno)          /* found it */
1801                     break;
1802             if (myplexno == vol->plexes)                    /* didn't find it.  Huh? */
1803                 log(LOG_ERR,
1804                     "Error removing plex %s: not found in volume %s\n",
1805                     plex->name,
1806                     vol->name);
1807             if (myplexno < (vol->plexes - 1))               /* not the last plex in the list */
1808                 bcopy(&vol->plex[myplexno + 1],
1809                     &vol->plex[myplexno],
1810                     vol->plexes - 1 - myplexno);
1811             vol->plexes--;
1812         } else {
1813             ioctl_reply->error = EBUSY;                     /* can't do that */
1814             return;
1815         }
1816     }
1817     log(LOG_INFO, "vinum: removing %s\n", plex->name);
1818     if (isstriped(plex))
1819         mtx_destroy(&plex->lockmtx);
1820     free_plex(plexno);
1821     vinum_conf.plexes_used--;                               /* one less plex */
1822 }
1823
1824 /* remove a volume */
1825 void
1826 remove_volume_entry(int volno, int force, int recurse)
1827 {
1828     struct volume *vol = &VOL[volno];
1829     int plexno;
1830
1831     if ((volno > vinum_conf.volumes_allocated)              /* not a valid volume */
1832     ||(vol->state == volume_unallocated)) {                 /* or nothing there */
1833         ioctl_reply->error = EINVAL;
1834         strcpy(ioctl_reply->msg, "No such volume");
1835     } else if (vol->flags & VF_OPEN)                        /* we're open */
1836         ioctl_reply->error = EBUSY;                         /* no getting around that */
1837     else if (vol->plexes) {
1838         if (recurse && force) {                             /* remove all below */
1839             int plexes = vol->plexes;
1840
1841 /*       for (plexno = plexes - 1; plexno >= 0; plexno--) */
1842             for (plexno = 0; plexno < plexes; plexno++)
1843                 remove_plex_entry(vol->plex[plexno], force, recurse);
1844             log(LOG_INFO, "vinum: removing %s\n", vol->name);
1845             free_volume(volno);
1846             vinum_conf.volumes_used--;                      /* one less volume */
1847         } else
1848             ioctl_reply->error = EBUSY;                     /* can't do that */
1849     } else {
1850         log(LOG_INFO, "vinum: removing %s\n", vol->name);
1851         free_volume(volno);
1852         vinum_conf.volumes_used--;                          /* one less volume */
1853     }
1854 }
1855
1856 /* Currently called only from ioctl */
1857 void
1858 update_sd_config(int sdno, int diskconfig)
1859 {
1860     if (!diskconfig)
1861         set_sd_state(sdno, sd_up, setstate_configuring);
1862     SD[sdno].flags &= ~VF_NEWBORN;
1863 }
1864
1865 void
1866 update_plex_config(int plexno, int diskconfig)
1867 {
1868     u_int64_t size;
1869     int sdno;
1870     struct plex *plex = &PLEX[plexno];
1871     enum plexstate state = plex_up;                         /* state we want the plex in */
1872     int remainder;                                          /* size of fractional stripe at end */
1873     int added_plex;                                         /* set if we add a plex to a volume */
1874     int required_sds;                                       /* number of subdisks we need */
1875     struct sd *sd;
1876     struct volume *vol;
1877     int data_sds = 0;                                       /* number of sds carrying data */
1878
1879     if (plex->state < plex_init)                            /* not a real plex, */
1880         return;
1881     added_plex = 0;
1882     if (plex->volno >= 0) {                                 /* we have a volume */
1883         vol = &VOL[plex->volno];
1884
1885         /*
1886          * If we're newly born,
1887          * and the volume isn't,
1888          * and it has other plexes,
1889          * and we didn't read this mess from disk,
1890          * we were added later.
1891          */
1892         if ((plex->flags & VF_NEWBORN)
1893             && ((vol->flags & VF_NEWBORN) == 0)
1894             && (vol->plexes > 0)
1895             && (diskconfig == 0)) {
1896             added_plex = 1;
1897             state = plex_down;                              /* so take ourselves down */
1898         }
1899     }
1900     /*
1901      * Check that our subdisks make sense.  For
1902      * striped plexes, we need at least two
1903      * subdisks, and for RAID-4 and RAID-5 plexes we
1904      * need at least three subdisks.  In each case
1905      * they must all be the same size.
1906      */
1907     if (plex->organization == plex_striped) {
1908         data_sds = plex->subdisks;
1909         required_sds = 2;
1910     } else if (isparity(plex)) {                            /* RAID 4 or 5 */
1911         data_sds = plex->subdisks - 1;
1912         required_sds = 3;
1913     } else
1914         required_sds = 0;
1915     if (required_sds > 0) {                                 /* striped, RAID-4 or RAID-5 */
1916         if (plex->subdisks < required_sds) {
1917             log(LOG_ERR,
1918                 "vinum: plex %s does not have at least %d subdisks\n",
1919                 plex->name,
1920                 required_sds);
1921             state = plex_faulty;
1922         }
1923         /*
1924          * Now see if the plex size is a multiple of
1925          * the stripe size.  If not, trim off the end
1926          * of each subdisk and return it to the drive.
1927          */
1928         if (plex->length > 0) {
1929             if (data_sds > 0) {
1930                 if (plex->stripesize > 0) {
1931                     remainder = (int) (plex->length         /* are we exact? */
1932                         % ((u_int64_t) plex->stripesize * data_sds));
1933                     if (remainder) {                        /* no */
1934                         log(LOG_INFO, "vinum: removing %d blocks of partial stripe at the end of %s\n",
1935                             remainder,
1936                             plex->name);
1937                         plex->length -= remainder;          /* shorten the plex */
1938                         remainder /= data_sds;              /* spread the remainder amongst the sds */
1939                         for (sdno = 0; sdno < plex->subdisks; sdno++) {
1940                             sd = &SD[plex->sdnos[sdno]];    /* point to the subdisk */
1941                             return_drive_space(sd->driveno, /* return the space */
1942                                 sd->driveoffset + sd->sectors - remainder,
1943                                 remainder);
1944                             sd->sectors -= remainder;       /* and shorten it */
1945                         }
1946                     }
1947                 } else                                      /* no data sds, */
1948                     plex->length = 0;                       /* reset length */
1949             }
1950         }
1951     }
1952     size = 0;
1953     for (sdno = 0; sdno < plex->subdisks; sdno++) {
1954         sd = &SD[plex->sdnos[sdno]];
1955         if (isstriped(plex)
1956             && (sdno > 0)
1957             && (sd->sectors != SD[plex->sdnos[sdno - 1]].sectors)) {
1958             log(LOG_ERR, "vinum: %s must have equal sized subdisks\n", plex->name);
1959             state = plex_down;
1960         }
1961         size += sd->sectors;
1962         if (added_plex)                                     /* we were added later */
1963             sd->state = sd_stale;                           /* stale until proven otherwise */
1964     }
1965
1966     if (plex->subdisks) {                                   /* plex has subdisks, calculate size */
1967         /*
1968          * XXX We shouldn't need to calculate the size any
1969          * more.  Check this some time
1970          */
1971         if (isparity(plex))
1972             size = size / plex->subdisks * (plex->subdisks - 1); /* less space for RAID-4 and RAID-5 */
1973         if (plex->length != size)
1974             log(LOG_INFO,
1975                 "Correcting length of %s: was %lld, is %lld\n",
1976                 plex->name,
1977                 (long long) plex->length,
1978                 (long long) size);
1979         plex->length = size;
1980     } else {                                                /* no subdisks, */
1981         plex->length = 0;                                   /* no size */
1982         state = plex_down;                                  /* take it down */
1983     }
1984     update_plex_state(plexno);                              /* set the state */
1985     plex->flags &= ~VF_NEWBORN;
1986 }
1987
1988 void
1989 update_volume_config(int volno, int diskconfig)
1990 {
1991     struct volume *vol = &VOL[volno];
1992     struct plex *plex;
1993     int plexno;
1994
1995     if (vol->state != volume_unallocated)
1996         /*
1997          * Recalculate the size of the volume,
1998          * which might change if the original
1999          * plexes were not a multiple of the
2000          * stripe size.
2001          */
2002     {
2003         vol->size = 0;
2004         for (plexno = 0; plexno < vol->plexes; plexno++) {
2005             plex = &PLEX[vol->plex[plexno]];
2006             vol->size = max(plex->length, vol->size);       /* maximum size */
2007             plex->volplexno = plexno;                       /* note it in the plex */
2008         }
2009     }
2010     vol->flags &= ~VF_NEWBORN;                              /* no longer newly born */
2011 }
2012
2013 /*
2014  * Update the global configuration.
2015  * diskconfig is != 0 if we're reading in a config
2016  * from disk.  In this case, we don't try to
2017  * bring the devices up, though we will bring
2018  * them down if there's some error which got
2019  * missed when writing to disk.
2020  */
2021 void
2022 updateconfig(int diskconfig)
2023 {
2024     int plexno;
2025     int volno;
2026
2027     for (plexno = 0; plexno < vinum_conf.plexes_allocated; plexno++)
2028         update_plex_config(plexno, diskconfig);
2029
2030     for (volno = 0; volno < vinum_conf.volumes_allocated; volno++) {
2031         if (VOL[volno].state > volume_uninit) {
2032             VOL[volno].flags &= ~VF_CONFIG_SETUPSTATE;      /* no more setupstate */
2033             update_volume_state(volno);
2034             update_volume_config(volno, diskconfig);
2035         }
2036     }
2037     save_config();
2038 }
2039
2040 /*
2041  * Start manual changes to the configuration and lock out
2042  * others who may wish to do so.
2043  * XXX why do we need this and lock_config too?
2044  */
2045 int
2046 start_config(int force)
2047 {
2048     int error;
2049
2050     current_drive = -1;                                     /* note the last drive we mention, for
2051                                                             * some defaults */
2052     current_plex = -1;                                      /* and the same for the last plex */
2053     current_volume = -1;                                    /* and the last volume */
2054     while ((vinum_conf.flags & VF_CONFIGURING) != 0) {
2055         vinum_conf.flags |= VF_WILL_CONFIGURE;
2056         if ((error = tsleep(&vinum_conf, PRIBIO | PCATCH, "vincfg", 0)) != 0)
2057             return error;
2058     }
2059     /*
2060      * We need two flags here: VF_CONFIGURING
2061      * tells other processes to hold off (this
2062      * function), and VF_CONFIG_INCOMPLETE
2063      * tells the state change routines not to
2064      * propagate incrememntal state changes
2065      */
2066     vinum_conf.flags |= VF_CONFIGURING | VF_CONFIG_INCOMPLETE;
2067     if (force)
2068         vinum_conf.flags |= VF_FORCECONFIG;                 /* overwrite differently named drives */
2069     current_drive = -1;                                     /* reset the defaults */
2070     current_plex = -1;                                      /* and the same for the last plex */
2071     current_volume = -1;                                    /* and the last volme */
2072     return 0;
2073 }
2074
2075 /*
2076  * Update the config if update is 1, and unlock
2077  * it.  We won't update the configuration if we
2078  * are called in a recursive loop via throw_rude_remark.
2079  */
2080 void
2081 finish_config(int update)
2082 {
2083     /* we've finished our config */
2084     vinum_conf.flags &= ~(VF_CONFIG_INCOMPLETE | VF_READING_CONFIG | VF_FORCECONFIG);
2085     if (update)
2086         updateconfig(0);                                    /* so update things */
2087     else
2088         updateconfig(1);                                    /* do some updates only */
2089     vinum_conf.flags &= ~VF_CONFIGURING;                    /* and now other people can take a turn */
2090     if ((vinum_conf.flags & VF_WILL_CONFIGURE) != 0) {
2091         vinum_conf.flags &= ~VF_WILL_CONFIGURE;
2092         wakeup_one(&vinum_conf);
2093     }
2094 }
2095 /* Local Variables: */
2096 /* fill-column: 50 */
2097 /* End: */