Merge branch 'vendor/GCC44'
[dragonfly.git] / sys / dev / raid / vinum / vinumio.c
1 /*-
2  * Copyright (c) 1997, 1998
3  *      Nan Yang Computer Services Limited.  All rights reserved.
4  *
5  *  This software is distributed under the so-called ``Berkeley
6  *  License'':
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. All advertising materials mentioning features or use of this software
17  *    must display the following acknowledgement:
18  *      This product includes software developed by Nan Yang Computer
19  *      Services Limited.
20  * 4. Neither the name of the Company nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * This software is provided ``as is'', and any express or implied
25  * warranties, including, but not limited to, the implied warranties of
26  * merchantability and fitness for a particular purpose are disclaimed.
27  * In no event shall the company or contributors be liable for any
28  * direct, indirect, incidental, special, exemplary, or consequential
29  * damages (including, but not limited to, procurement of substitute
30  * goods or services; loss of use, data, or profits; or business
31  * interruption) however caused and on any theory of liability, whether
32  * in contract, strict liability, or tort (including negligence or
33  * otherwise) arising in any way out of the use of this software, even if
34  * advised of the possibility of such damage.
35  *
36  * $Id: vinumio.c,v 1.30 2000/05/10 23:23:30 grog Exp grog $
37  * $FreeBSD: src/sys/dev/vinum/vinumio.c,v 1.52.2.6 2002/05/02 08:43:44 grog Exp $
38  * $DragonFly: src/sys/dev/raid/vinum/vinumio.c,v 1.31 2008/06/05 18:06:31 swildner Exp $
39  */
40
41 #include "vinumhdr.h"
42 #include "request.h"
43 #include <vm/vm_zone.h>
44 #include <sys/nlookup.h>
45
46 static char *sappend(char *txt, char *s);
47 static int drivecmp(const void *va, const void *vb);
48
49 /*
50  * Open the device associated with the drive, and set drive's vp.
51  * Return an error number
52  */
53 int
54 open_drive(struct drive *drive, struct proc *p, int verbose)
55 {
56     struct nlookupdata nd;
57     int error;
58     const char *dname;
59
60     /*
61      * Fail if already open
62      */
63     if (drive->flags & VF_OPEN)
64         return EBUSY;
65     dname = drive->devicename;
66
67     /*
68      * Severe hack to disallow opening partition 'c'
69      */
70     if (strncmp(dname, "/dev", 4) == 0 && dname[strlen(dname)-1] == 'c')
71         return ENOTTY;
72
73     if (rootdev) {
74         /*
75          * Open via filesystem (future)
76          */
77         error = nlookup_init(&nd, drive->devicename, UIO_SYSSPACE, NLC_FOLLOW);
78         if (error)
79             return error;
80         error = vn_open(&nd, NULL, FREAD|FWRITE, 0);
81         drive->vp = nd.nl_open_vp;
82         nd.nl_open_vp = NULL;
83         nlookup_done(&nd);
84     } else {
85         /*
86          * Open via synthesized vnode backed by disk device
87          */
88         error = vn_opendisk(drive->devicename, FREAD|FWRITE, &drive->vp);
89         if (error)
90             return error;
91     }
92
93     if (error == 0 && drive->vp == NULL)
94         error = ENODEV;
95
96     /*
97      * A huge amount of pollution all over vinum requires that our low
98      * level drive be a device.
99      */
100     if (error == 0 && drive->vp->v_type != VCHR) {
101         vn_close(drive->vp, FREAD|FWRITE);
102         drive->vp = NULL;
103         error = ENODEV;
104     }
105     if (error) {
106         drive->state = drive_down;
107         if (verbose) {
108             log(LOG_WARNING,
109                 "vinum open_drive %s: failed with error %d\n",
110                 drive->devicename, error);
111         }
112     } else {
113         drive->dev = drive->vp->v_rdev;
114         drive->flags |= VF_OPEN;
115     }
116     drive->lasterror = error;
117     return error;
118 }
119
120 /*
121  * Set some variables in the drive struct
122  * in more convenient form.  Return error indication
123  */
124 int
125 set_drive_parms(struct drive *drive)
126 {
127     drive->blocksize = BLKDEV_IOSIZE;                       /* do we need this? */
128     drive->secsperblock = drive->blocksize                  /* number of sectors per block */
129         / drive->partinfo.media_blksize;
130
131     /* Now update the label part */
132     bcopy(hostname, drive->label.sysname, VINUMHOSTNAMELEN); /* put in host name */
133     getmicrotime(&drive->label.date_of_birth);              /* and current time */
134     drive->label.drive_size = drive->partinfo.media_size;
135 #if VINUMDEBUG
136     if (debug & DEBUG_BIGDRIVE)                             /* pretend we're 100 times as big */
137         drive->label.drive_size *= 100;
138 #endif
139
140     /* number of sectors available for subdisks */
141     drive->sectors_available = drive->label.drive_size / DEV_BSIZE - DATASTART;
142
143     /*
144      * Bug in 3.0 as of January 1998: you can open
145      * non-existent slices.  They have a length of 0.
146      */
147     if (drive->label.drive_size < MINVINUMSLICE) {          /* too small to worry about */
148         set_drive_state(drive->driveno, drive_down, setstate_force);
149         drive->lasterror = ENOSPC;
150         return ENOSPC;
151     }
152     drive->freelist_size = INITIAL_DRIVE_FREELIST;          /* initial number of entries */
153     drive->freelist = (struct drive_freelist *)
154         Malloc(INITIAL_DRIVE_FREELIST * sizeof(struct drive_freelist));
155     if (drive->freelist == NULL)                            /* can't malloc, dammit */
156         return ENOSPC;
157     drive->freelist_entries = 1;                            /* just (almost) the complete drive */
158     drive->freelist[0].offset = DATASTART;                  /* starts here */
159     drive->freelist[0].sectors = (drive->label.drive_size >> DEV_BSHIFT) - DATASTART; /* and it's this long */
160     if (drive->label.name[0] != '\0')                       /* got a name */
161         set_drive_state(drive->driveno, drive_up, setstate_force); /* our drive is accessible */
162     else                                                    /* we know about it, but that's all */
163         drive->state = drive_referenced;
164     return 0;
165 }
166
167 /*
168  * Initialize a drive: open the device and add device
169  * information
170  */
171 int
172 init_drive(struct drive *drive, int verbose)
173 {
174     if (drive->devicename[0] != '/') {
175         drive->lasterror = EINVAL;
176         log(LOG_ERR, "vinum: Can't open drive without drive name\n");
177         return EINVAL;
178     }
179     drive->lasterror = open_drive(drive, curproc, verbose); /* open the drive */
180     if (drive->lasterror)
181         return drive->lasterror;
182
183     drive->lasterror = VOP_IOCTL(drive->vp, DIOCGPART,
184                                  (caddr_t)&drive->partinfo,
185                                  FREAD|FWRITE, proc0.p_ucred);
186     if (drive->lasterror) {
187         if (verbose)
188             log(LOG_WARNING,
189                 "vinum open_drive %s: Can't get partition information, drive->lasterror %d\n",
190                 drive->devicename,
191                 drive->lasterror);
192         close_drive(drive);
193         return drive->lasterror;
194     }
195     if (drive->partinfo.fstype != FS_VINUM &&
196         !kuuid_is_vinum(&drive->partinfo.fstype_uuid)
197     ) {  
198         drive->lasterror = EFTYPE;
199         if (verbose)
200             log(LOG_WARNING,
201                 "vinum open_drive %s: Wrong partition type for vinum\n",
202                 drive->devicename);
203         close_drive(drive);
204         return EFTYPE;
205     }
206     return set_drive_parms(drive);                          /* set various odds and ends */
207 }
208
209 /* Close a drive if it's open. */
210 void
211 close_drive(struct drive *drive)
212 {
213     LOCKDRIVE(drive);                                       /* keep the daemon out */
214     if (drive->flags & VF_OPEN)
215         close_locked_drive(drive);                          /* and close it */
216     if (drive->state > drive_down)                          /* if it's up */
217         drive->state = drive_down;                          /* make sure it's down */
218     unlockdrive(drive);
219 }
220
221 /*
222  * Real drive close code, called with drive already locked.
223  * We have also checked that the drive is open.  No errors.
224  */
225 void
226 close_locked_drive(struct drive *drive)
227 {
228     /*
229      * If we can't access the drive, we can't flush
230      * the queues, which spec_close() will try to
231      * do.  Get rid of them here first.
232      */
233     if (drive->vp) {
234         drive->lasterror = vn_close(drive->vp, FREAD|FWRITE);
235         drive->vp = NULL;
236     }
237     drive->flags &= ~VF_OPEN;
238 }
239
240 /*
241  * Remove drive from the configuration.
242  * Caller must ensure that it isn't active.
243  */
244 void
245 remove_drive(int driveno)
246 {
247     struct drive *drive = &vinum_conf.drive[driveno];
248     struct vinum_hdr *vhdr;                                 /* buffer for header */
249     int error;
250
251     if (drive->state > drive_referenced) {                  /* real drive */
252         if (drive->state == drive_up) {
253             vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN); /* allocate buffer */
254             CHECKALLOC(vhdr, "Can't allocate memory");
255             error = read_drive(drive, (void *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
256             if (error)
257                 drive->lasterror = error;
258             else {
259                 vhdr->magic = VINUM_NOMAGIC;                /* obliterate the magic, but leave the rest */
260                 write_drive(drive, (void *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
261             }
262             Free(vhdr);
263         }
264         free_drive(drive);                                  /* close it and free resources */
265         save_config();                                      /* and save the updated configuration */
266     }
267 }
268
269 /*
270  * Transfer drive data.  Usually called from one of these defines;
271  * #define read_drive(a, b, c, d) driveio (a, b, c, d, BUF_CMD_READ)
272  * #define write_drive(a, b, c, d) driveio (a, b, c, d, BUF_CMD_WRITE)
273  *
274  * length and offset are in bytes, but must be multiples of sector
275  * size.  The function *does not check* for this condition, and
276  * truncates ruthlessly.
277  * Return error number
278  */
279 int
280 driveio(struct drive *drive, char *buf, size_t length, off_t offset, buf_cmd_t cmd)
281 {
282     int error;
283     struct buf *bp;
284     caddr_t saveaddr;
285
286     error = 0;                                              /* to keep the compiler happy */
287     while (length) {                                        /* divide into small enough blocks */
288         int len = min(length, MAXBSIZE);                    /* maximum block device transfer is MAXBSIZE */
289
290         bp = geteblk(len);                                  /* get a buffer header */
291         bp->b_cmd = cmd;
292         bp->b_bio1.bio_offset = offset;                     /* disk offset */
293         bp->b_bio1.bio_done = biodone_sync;
294         bp->b_bio1.bio_flags |= BIO_SYNC;
295         saveaddr = bp->b_data;
296         bp->b_data = buf;
297         bp->b_bcount = len;
298         vn_strategy(drive->vp, &bp->b_bio1);
299         error = biowait(&bp->b_bio1, (cmd == BUF_CMD_READ ? "drvrd" : "drvwr"));
300         bp->b_data = saveaddr;
301         bp->b_flags |= B_INVAL | B_AGE;
302         bp->b_flags &= ~B_ERROR;
303         brelse(bp);
304         if (error)
305             break;
306         length -= len;                                      /* update pointers */
307         buf += len;
308         offset += len;
309     }
310     return error;
311 }
312
313 /*
314  * Check a drive for a vinum header.  If found,
315  * update the drive information.  We come here
316  * with a partially populated drive structure
317  * which includes the device name.
318  *
319  * Return information on what we found.
320  *
321  * This function is called from two places: check_drive,
322  * which wants to find out whether the drive is a
323  * Vinum drive, and config_drive, which asserts that
324  * it is a vinum drive.  In the first case, we don't
325  * print error messages (verbose==0), in the second
326  * we do (verbose==1).
327  */
328 enum drive_label_info
329 read_drive_label(struct drive *drive, int verbose)
330 {
331     int error;
332     int result;                                             /* result of our search */
333     struct vinum_hdr *vhdr;                                 /* and as header */
334
335     error = init_drive(drive, 0);                           /* find the drive */
336     if (error)                                              /* find the drive */
337         return DL_CANT_OPEN;                                /* not ours */
338
339     vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN);     /* allocate buffers */
340     CHECKALLOC(vhdr, "Can't allocate memory");
341
342     drive->state = drive_up;                                /* be optimistic */
343     error = read_drive(drive, (void *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
344     if (vhdr->magic == VINUM_MAGIC) {                       /* ours! */
345         if (drive->label.name[0]                            /* we have a name for this drive */
346         &&(strcmp(drive->label.name, vhdr->label.name))) {  /* but it doesn't match the real name */
347             drive->lasterror = EINVAL;
348             result = DL_WRONG_DRIVE;                        /* it's the wrong drive */
349             drive->state = drive_unallocated;               /* put it back, it's not ours */
350         } else
351             result = DL_OURS;
352         /*
353          * We copy the drive anyway so that we have
354          * the correct name in the drive info.  This
355          * may not be the name specified
356          */
357         drive->label = vhdr->label;                         /* put in the label information */
358     } else if (vhdr->magic == VINUM_NOMAGIC)                /* was ours, but we gave it away */
359         result = DL_DELETED_LABEL;                          /* and return the info */
360     else
361         result = DL_NOT_OURS;                               /* we could have it, but we don't yet */
362     Free(vhdr);                                             /* that's all. */
363     return result;
364 }
365
366 /*
367  * Check a drive for a vinum header.  If found,
368  * read configuration information from the drive and
369  * incorporate the data into the configuration.
370  *
371  * Return drive number.
372  */
373 struct drive *
374 check_drive(char *devicename)
375 {
376     int driveno;
377     int i;
378     struct drive *drive;
379
380     driveno = find_drive_by_dev(devicename, 1);             /* if entry doesn't exist, create it */
381     drive = &vinum_conf.drive[driveno];                     /* and get a pointer */
382
383     if (read_drive_label(drive, 0) == DL_OURS) {            /* one of ours */
384         for (i = 0; i < vinum_conf.drives_allocated; i++) { /* see if the name already exists */
385             if ((i != driveno)                              /* not this drive */
386             &&(DRIVE[i].state != drive_unallocated)         /* and it's allocated */
387             &&(strcmp(DRIVE[i].label.name,
388                         DRIVE[driveno].label.name) == 0)) { /* and it has the same name */
389                 struct drive *mydrive = &DRIVE[i];
390
391                 if (mydrive->devicename[0] == '/') {        /* we know a device name for it */
392                     /*
393                      * set an error, but don't take the
394                      * drive down: that would cause unneeded
395                      * error messages.
396                      */
397                     drive->lasterror = EEXIST;
398                     break;
399                 } else {                                    /* it's just a place holder, */
400                     int sdno;
401
402                     for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) { /* look at each subdisk */
403                         if ((SD[sdno].driveno == i)         /* it's pointing to this one, */
404                         &&(SD[sdno].state != sd_unallocated)) { /* and it's a real subdisk */
405                             SD[sdno].driveno = drive->driveno; /* point to the one we found */
406                             update_sd_state(sdno);          /* and update its state */
407                         }
408                     }
409                     bzero(mydrive, sizeof(struct drive));   /* don't deallocate it, just remove it */
410                 }
411             }
412         }
413     } else {
414         if (drive->lasterror == 0)
415             drive->lasterror = ENODEV;
416         close_drive(drive);
417         drive->state = drive_down;
418     }
419     return drive;
420 }
421
422 static char *
423 sappend(char *txt, char *s)
424 {
425     while ((*s++ = *txt++) != 0);
426     return s - 1;
427 }
428
429 void
430 format_config(char *config, int len)
431 {
432     int i;
433     int j;
434     char *s = config;
435     char *configend = &config[len];
436
437     bzero(config, len);
438
439     /* First write the volume configuration */
440     for (i = 0; i < vinum_conf.volumes_allocated; i++) {
441         struct volume *vol;
442
443         vol = &vinum_conf.volume[i];
444         if ((vol->state > volume_uninit)
445             && (vol->name[0] != '\0')) {                    /* paranoia */
446             ksnprintf(s,
447                 configend - s,
448                 "volume %s state %s",
449                 vol->name,
450                 volume_state(vol->state));
451             while (*s)
452                 s++;                                        /* find the end */
453             if (vol->preferred_plex >= 0)                   /* preferences, */
454                 ksnprintf(s,
455                     configend - s,
456                     " readpol prefer %s",
457                     vinum_conf.plex[vol->preferred_plex].name);
458             while (*s)
459                 s++;                                        /* find the end */
460             s = sappend("\n", s);
461         }
462     }
463
464     /* Then the plex configuration */
465     for (i = 0; i < vinum_conf.plexes_allocated; i++) {
466         struct plex *plex;
467
468         plex = &vinum_conf.plex[i];
469         if ((plex->state > plex_referenced)
470             && (plex->name[0] != '\0')) {                   /* paranoia */
471             ksnprintf(s,
472                 configend - s,
473                 "plex name %s state %s org %s ",
474                 plex->name,
475                 plex_state(plex->state),
476                 plex_org(plex->organization));
477             while (*s)
478                 s++;                                        /* find the end */
479             if (isstriped(plex)) {
480                 ksnprintf(s,
481                     configend - s,
482                     "%ds ",
483                     (int) plex->stripesize);
484                 while (*s)
485                     s++;                                    /* find the end */
486             }
487             if (plex->volno >= 0)                           /* we have a volume */
488                 ksnprintf(s,
489                     configend - s,
490                     "vol %s ",
491                     vinum_conf.volume[plex->volno].name);
492             while (*s)
493                 s++;                                        /* find the end */
494             for (j = 0; j < plex->subdisks; j++) {
495                 ksnprintf(s,
496                     configend - s,
497                     " sd %s",
498                     vinum_conf.sd[plex->sdnos[j]].name);
499             }
500             s = sappend("\n", s);
501         }
502     }
503
504     /* And finally the subdisk configuration */
505     for (i = 0; i < vinum_conf.subdisks_allocated; i++) {
506         struct sd *sd;
507         char *drivename;
508
509         sd = &SD[i];
510         if ((sd->state != sd_referenced)
511             && (sd->state != sd_unallocated)
512             && (sd->name[0] != '\0')) {                     /* paranoia */
513             drivename = vinum_conf.drive[sd->driveno].label.name;
514             /*
515              * XXX We've seen cases of dead subdisks
516              * which don't have a drive.  If we let them
517              * through here, the drive name is null, so
518              * they get the drive named 'plex'.
519              *
520              * This is a breakage limiter, not a fix.
521              */
522             if (drivename[0] == '\0')
523                 drivename = "*invalid*";
524             ksnprintf(s,
525                 configend - s,
526                 "sd name %s drive %s plex %s len %llus driveoffset %llus state %s",
527                 sd->name,
528                 drivename,
529                 vinum_conf.plex[sd->plexno].name,
530                 (unsigned long long) sd->sectors,
531                 (unsigned long long) sd->driveoffset,
532                 sd_state(sd->state));
533             while (*s)
534                 s++;                                        /* find the end */
535             if (sd->plexno >= 0)
536                 ksnprintf(s,
537                     configend - s,
538                     " plexoffset %llds",
539                     (long long) sd->plexoffset);
540             else
541                 ksnprintf(s, configend - s, " detached");
542             while (*s)
543                 s++;                                        /* find the end */
544             if (sd->flags & VF_RETRYERRORS) {
545                 ksnprintf(s, configend - s, " retryerrors");
546                 while (*s)
547                     s++;                                    /* find the end */
548             }
549             ksnprintf(s, configend - s, " \n");
550             while (*s)
551                 s++;                                        /* find the end */
552         }
553     }
554     if (s > &config[len - 2])
555         panic("vinum: configuration data overflow");
556 }
557
558 /*
559  * issue a save config request to the dæmon.  The actual work
560  * is done in process context by daemon_save_config
561  */
562 void
563 save_config(void)
564 {
565     queue_daemon_request(daemonrq_saveconfig, (union daemoninfo) 0);
566 }
567
568 /*
569  * Write the configuration to all vinum slices.  This
570  * is performed by the dæmon only
571  */
572 void
573 daemon_save_config(void)
574 {
575     int error;
576     int written_config;                                     /* set when we first write the config to disk */
577     int driveno;
578     struct drive *drive;                                    /* point to current drive info */
579     struct vinum_hdr *vhdr;                                 /* and as header */
580     char *config;                                           /* point to config data */
581     int wlabel_on;                                          /* to set writing label on/off */
582
583     /* don't save the configuration while we're still working on it */
584     if (vinum_conf.flags & VF_CONFIGURING)
585         return;
586     written_config = 0;                                     /* no config written yet */
587     /* Build a volume header */
588     vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN);     /* get space for the config data */
589     CHECKALLOC(vhdr, "Can't allocate config data");
590     vhdr->magic = VINUM_MAGIC;                              /* magic number */
591     vhdr->config_length = MAXCONFIG;                        /* length of following config info */
592
593     config = Malloc(MAXCONFIG);                             /* get space for the config data */
594     CHECKALLOC(config, "Can't allocate config data");
595
596     format_config(config, MAXCONFIG);
597     error = 0;                                              /* no errors yet */
598     for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
599         drive = &vinum_conf.drive[driveno];                 /* point to drive */
600         if (drive->state > drive_referenced) {
601             LOCKDRIVE(drive);                               /* don't let it change */
602
603             /*
604              * First, do some drive consistency checks.  Some
605              * of these are kludges, others require a process
606              * context and couldn't be done before
607              */
608             if ((drive->devicename[0] == '\0')
609                 || (drive->label.name[0] == '\0')) {
610                 unlockdrive(drive);
611                 free_drive(drive);                          /* get rid of it */
612                 break;
613             }
614             if (((drive->flags & VF_OPEN) == 0)             /* drive not open */
615             &&(drive->state > drive_down)) {                /* and it thinks it's not down */
616                 unlockdrive(drive);
617                 set_drive_state(driveno, drive_down, setstate_force); /* tell it what's what */
618                 continue;
619             }
620             if ((drive->state == drive_down)                /* it's down */
621             &&(drive->flags & VF_OPEN)) {                   /* but open, */
622                 unlockdrive(drive);
623                 close_drive(drive);                         /* close it */
624             } else if (drive->state > drive_down) {
625                 getmicrotime(&drive->label.last_update);    /* time of last update is now */
626                 bcopy((char *) &drive->label,               /* and the label info from the drive structure */
627                     (char *) &vhdr->label,
628                     sizeof(vhdr->label));
629                 if ((drive->state != drive_unallocated)
630                     && (drive->state != drive_referenced)) { /* and it's a real drive */
631                     wlabel_on = 1;                          /* enable writing the label */
632                     error = 0;
633 #if 1
634                     error = VOP_IOCTL(drive->vp, DIOCWLABEL,
635                                       (caddr_t)&wlabel_on,
636                                       FREAD|FWRITE, proc0.p_ucred);
637 #endif
638                     if (error == 0)
639                         error = write_drive(drive, (char *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
640                     if (error == 0)
641                         error = write_drive(drive, config, MAXCONFIG, VINUM_CONFIG_OFFSET); /* first config copy */
642                     if (error == 0)
643                         error = write_drive(drive, config, MAXCONFIG, VINUM_CONFIG_OFFSET + MAXCONFIG); /* second copy */
644                     wlabel_on = 0;                          /* enable writing the label */
645 #if 1
646                     if (error == 0) {
647                         error = VOP_IOCTL(drive->vp, DIOCWLABEL,
648                                           (caddr_t)&wlabel_on,
649                                           FREAD|FWRITE, proc0.p_ucred);
650                     }
651 #endif
652                     unlockdrive(drive);
653                     if (error) {
654                         log(LOG_ERR,
655                             "vinum: Can't write config to %s, error %d\n",
656                             drive->devicename,
657                             error);
658                         set_drive_state(drive->driveno, drive_down, setstate_force);
659                     } else
660                         written_config = 1;                 /* we've written it on at least one drive */
661                 }
662             } else                                          /* not worth looking at, */
663                 unlockdrive(drive);                         /* just unlock it again */
664         }
665     }
666     Free(vhdr);
667     Free(config);
668 }
669
670 /* Look at all disks on the system for vinum slices */
671 int
672 vinum_scandisk(char *devicename[], int drives)
673 {
674     struct drive *volatile drive;
675     volatile int driveno;
676     int firstdrive;                                         /* first drive in this list */
677     volatile int gooddrives;                                /* number of usable drives found */
678     int firsttime;                                          /* set if we have never configured before */
679     int error;
680     char *config_text;                                      /* read the config info from disk into here */
681     char *volatile cptr;                                    /* pointer into config information */
682     char *eptr;                                             /* end pointer into config information */
683     char *config_line;                                      /* copy the config line to */
684     volatile int status;
685     int *volatile drivelist;                                /* list of drive indices */
686 #define DRIVENAMELEN 64
687 #define DRIVEPARTS   35                                     /* max partitions per drive, excluding c */
688     char partname[DRIVENAMELEN];                            /* for creating partition names */
689
690     status = 0;                                             /* success indication */
691     vinum_conf.flags |= VF_READING_CONFIG;                  /* reading config from disk */
692
693     gooddrives = 0;                                         /* number of usable drives found */
694     firstdrive = vinum_conf.drives_used;                    /* the first drive */
695     firsttime = vinum_conf.drives_used == 0;                /* are we a virgin? */
696
697     /* allocate a drive pointer list */
698     drivelist = (int *) Malloc(drives * DRIVEPARTS * sizeof(int));
699     CHECKALLOC(drivelist, "Can't allocate memory");
700     error = lock_config();                                  /* make sure we're alone here */
701     if (error)
702         return error;
703     error = setjmp(command_fail);                           /* come back here on error */
704     if (error) {                                            /* longjmped out */
705         unlock_config();
706         return error;
707     }
708
709     /* Open all drives and find which was modified most recently */
710     for (driveno = 0; driveno < drives; driveno++) {
711         char part;                                          /* UNIX partition */
712         int slice;
713         int founddrive;                                     /* flag when we find a vinum drive */
714         int has_slice = 0;
715         int has_part = 0;
716         char *tmp;
717
718         founddrive = 0;                                     /* no vinum drive found yet on this spindle */
719
720         /*
721          * If the device path contains a slice we do not try to tack on
722          * another slice.  If the device path has a partition we only check
723          * that partition.
724          */
725         if ((tmp = rindex(devicename[driveno], '/')) == NULL)
726             tmp = devicename[driveno];
727         while (*tmp && (*tmp < '0' || *tmp > '9'))
728             ++tmp;
729         while (*tmp && *tmp >= '0' && *tmp <= '9')
730             ++tmp;
731         if (*tmp == 's')
732             has_slice = strtol(tmp + 1, &tmp, 0);
733         if (*tmp >= 'a' && *tmp <= 'p')
734             has_part = *tmp;
735
736         /*
737          * Scan slices if no slice was specified, only if no partition was
738          * specified.
739          */
740         if (has_slice == 0 && has_part == 0)
741         for (slice = 0; slice < MAX_SLICES; slice++) {
742             if (has_slice && slice != has_slice)
743                 continue;
744
745             for (part = 'a'; part < 'a' + MAXPARTITIONS; part++) {
746                 if (has_part && part != has_part)
747                     continue;
748                 if (part == 'c')
749                     continue;
750                 ksnprintf(partname, DRIVENAMELEN,
751                         "%ss%d%c", devicename[driveno], slice, part);
752                 drive = check_drive(partname);      /* try to open it */
753                 if ((drive->lasterror != 0)                 /* didn't work, */
754                     ||(drive->state != drive_up))
755                     free_drive(drive);              /* get rid of it */
756                 else if (drive->flags & VF_CONFIGURED)  /* already read this config, */
757                     log(LOG_WARNING,
758                         "vinum: already read config from %s\n", /* say so */
759                         drive->label.name);
760                 else {
761                     drivelist[gooddrives] = drive->driveno;     /* keep the drive index */
762                     drive->flags &= ~VF_NEWBORN;            /* which is no longer newly born */
763                     gooddrives++;
764                     founddrive++;
765                 }
766             }
767         }
768         if (founddrive == 0 && has_slice == 0) {            /* didn't find anything, */
769             for (part = 'a'; part < 'a' + MAXPARTITIONS; part++) {          /* try the compatibility partition */
770                 if (has_part && has_part != part)
771                     continue;
772                 if (part == 'c')
773                     continue;
774                 if (has_part) {
775                     ksnprintf(partname, DRIVENAMELEN,
776                             "%s", devicename[driveno]);
777                 } else {
778                     ksnprintf(partname, DRIVENAMELEN,
779                             "%s%c", devicename[driveno], part);
780                 }
781                 drive = check_drive(partname);      /* try to open it */
782                 if ((drive->lasterror != 0)                 /* didn't work, */
783                 ||(drive->state != drive_up))
784                     free_drive(drive);              /* get rid of it */
785                 else if (drive->flags & VF_CONFIGURED)  /* already read this config, */
786                     log(LOG_WARNING,
787                         "vinum: already read config from %s\n", /* say so */
788                         drive->label.name);
789                 else {
790                     drivelist[gooddrives] = drive->driveno;     /* keep the drive index */
791                     drive->flags &= ~VF_NEWBORN;            /* which is no longer newly born */
792                     gooddrives++;
793                 }
794             }
795         }
796     }
797
798     if (gooddrives == 0) {
799         if (firsttime)
800             log(LOG_WARNING, "vinum: no drives found\n");
801         else
802             log(LOG_INFO, "vinum: no additional drives found\n");
803         unlock_config();
804         return ENOENT;
805     }
806     /*
807      * We now have at least one drive
808      * open.  Sort them in order of config time
809      * and merge the config info with what we
810      * have already.
811      */
812     kqsort(drivelist, gooddrives, sizeof(int), drivecmp);
813     config_text = (char *) Malloc(MAXCONFIG * 2);           /* allocate buffers */
814     CHECKALLOC(config_text, "Can't allocate memory");
815     config_line = (char *) Malloc(MAXCONFIGLINE * 2);       /* allocate buffers */
816     CHECKALLOC(config_line, "Can't allocate memory");
817     for (driveno = 0; driveno < gooddrives; driveno++) {    /* now include the config */
818         drive = &DRIVE[drivelist[driveno]];                 /* point to the drive */
819
820         if (firsttime && (driveno == 0))                    /* we've never configured before, */
821             log(LOG_INFO, "vinum: reading configuration from %s\n", drive->devicename);
822         else
823             log(LOG_INFO, "vinum: updating configuration from %s\n", drive->devicename);
824
825         if (drive->state == drive_up)
826             /* Read in both copies of the configuration information */
827             error = read_drive(drive, config_text, MAXCONFIG * 2, VINUM_CONFIG_OFFSET);
828         else {
829             error = EIO;
830             kprintf("vinum_scandisk: %s is %s\n", drive->devicename, drive_state(drive->state));
831         }
832
833         if (error != 0) {
834             log(LOG_ERR, "vinum: Can't read device %s, error %d\n", drive->devicename, error);
835             free_drive(drive);                              /* give it back */
836             status = error;
837         }
838         /*
839          * At this point, check that the two copies
840          * are the same, and do something useful if
841          * not.  In particular, consider which is
842          * newer, and what this means for the
843          * integrity of the data on the drive.
844          */
845         else {
846             vinum_conf.drives_used++;                       /* another drive in use */
847             /* Parse the configuration, and add it to the global configuration */
848             for (cptr = config_text; *cptr != '\0';) {      /* love this style(9) */
849                 volatile int parse_status;                  /* return value from parse_config */
850
851                 for (eptr = config_line; (*cptr != '\n') && (*cptr != '\0');) /* until the end of the line */
852                     *eptr++ = *cptr++;
853                 *eptr = '\0';                               /* and delimit */
854                 if (setjmp(command_fail) == 0) {            /* come back here on error and continue */
855                     parse_status = parse_config(config_line, &keyword_set, 1); /* parse the config line */
856                     if (parse_status < 0) {                 /* error in config */
857                         /*
858                            * This config should have been parsed in user
859                            * space.  If we run into problems here, something
860                            * serious is afoot.  Complain and let the user
861                            * snarf the config to see what's wrong.
862                          */
863                         log(LOG_ERR,
864                             "vinum: Config error on %s, aborting integration\n",
865                             drive->devicename);
866                         free_drive(drive);                  /* give it back */
867                         status = EINVAL;
868                     }
869                 }
870                 while (*cptr == '\n')
871                     cptr++;                                 /* skip to next line */
872             }
873         }
874         drive->flags |= VF_CONFIGURED;                      /* read this drive's configuration */
875     }
876
877     Free(config_line);
878     Free(config_text);
879     Free(drivelist);
880     vinum_conf.flags &= ~VF_READING_CONFIG;                 /* no longer reading from disk */
881     if (status != 0)
882         kprintf("vinum: couldn't read configuration");
883     else
884         updateconfig(VF_READING_CONFIG);                    /* update from disk config */
885     unlock_config();
886     return status;
887 }
888
889 /*
890  * Compare the modification dates of the drives, for qsort.
891  * Return 1 if a < b, 0 if a == b, 01 if a > b: in other
892  * words, sort backwards.
893  */
894 int
895 drivecmp(const void *va, const void *vb)
896 {
897     const struct drive *a = &DRIVE[*(const int *) va];
898     const struct drive *b = &DRIVE[*(const int *) vb];
899
900     if ((a->label.last_update.tv_sec == b->label.last_update.tv_sec)
901         && (a->label.last_update.tv_usec == b->label.last_update.tv_usec))
902         return 0;
903     else if ((a->label.last_update.tv_sec > b->label.last_update.tv_sec)
904             || ((a->label.last_update.tv_sec == b->label.last_update.tv_sec)
905             && (a->label.last_update.tv_usec > b->label.last_update.tv_usec)))
906         return -1;
907     else
908         return 1;
909 }
910 /* Local Variables: */
911 /* fill-column: 50 */
912 /* End: */