]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/vinum/vinumio.c
This commit was generated by cvs2svn to compensate for changes in r101613,
[FreeBSD/FreeBSD.git] / sys / dev / 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.32 2001/05/23 23:03:45 grog Exp grog $
37  * $FreeBSD$
38  */
39
40 #include <dev/vinum/vinumhdr.h>
41 #include <dev/vinum/request.h>
42
43 static char *sappend(char *txt, char *s);
44 static int drivecmp(const void *va, const void *vb);
45
46 /*
47  * Open the device associated with the drive, and set drive's vp.
48  * Return an error number
49  */
50 int
51 open_drive(struct drive *drive, struct thread *td, int verbose)
52 {
53     int devmajor;                                           /* major devs for disk device */
54     int devminor;                                           /* minor devs for disk device */
55     int unit;
56     char *dname;
57     struct cdevsw *dsw;                                     /* pointer to cdevsw entry */
58
59     if (bcmp(drive->devicename, "/dev/", 5))                /* device name doesn't start with /dev */
60         return ENOENT;                                      /* give up */
61     if (drive->flags & VF_OPEN)                             /* open already, */
62         return EBUSY;                                       /* don't do it again */
63
64     /*
65      * Yes, Bruce, I know this is horrible, but we
66      * don't have a root filesystem when we first
67      * try to do this.  If you can come up with a
68      * better solution, I'd really like it.  I'm
69      * just putting it in now to add ammuntion to
70      * moving the system to devfs.
71      */
72     dname = &drive->devicename[5];
73     drive->dev = NULL;                                      /* no device yet */
74
75     /* Find the device */
76     if (bcmp(dname, "ad", 2) == 0)                          /* IDE disk */
77         devmajor = 116;
78     else if (bcmp(dname, "wd", 2) == 0)                     /* IDE disk */
79         devmajor = 3;
80     else if (bcmp(dname, "da", 2) == 0)
81         devmajor = 13;
82     else if (bcmp(dname, "vn", 2) == 0)
83         devmajor = 43;
84     else if (bcmp(dname, "md", 2) == 0)
85         devmajor = 95;
86     else if (bcmp(dname, "ar", 2) == 0)
87         devmajor = 157;
88     else if (bcmp(dname, "amrd", 4) == 0) {
89         devmajor = 133;
90         dname += 2;
91     } else if (bcmp(dname, "mlxd", 4) == 0) {
92         devmajor = 131;
93         dname += 2;
94     } else if (bcmp(dname, "idad", 4) == 0) {
95         devmajor = 109;
96         dname += 2;
97     } else if (bcmp(dname, "twed", 4) == 0) {               /* 3ware raid */
98       devmajor = 147;
99       dname += 2;
100     } else
101       return ENODEV;
102     dname += 2;                                             /* point past */
103
104     /*
105      * Found the device.  We can expect one of
106      * two formats for the rest: a unit number,
107      * then either a partition letter for the
108      * compatiblity partition (e.g. h) or a
109      * slice ID and partition (e.g. s2e).
110      * Create a minor number for each of them.
111      */
112     unit = 0;
113     while ((*dname >= '0')                                  /* unit number */
114     &&(*dname <= '9')) {
115         unit = unit * 10 + *dname - '0';
116         dname++;
117     }
118
119     if (*dname == 's') {                                    /* slice */
120         if (((dname[1] < '1') || (dname[1] > '4'))          /* invalid slice */
121         ||((dname[2] < 'a') || (dname[2] > 'h')))           /* or invalid partition */
122             return ENODEV;
123         devminor = ((unit & 31) << 3)                       /* unit */
124         +(dname[2] - 'a')                                   /* partition */
125         +((dname[1] - '0' + 1) << 16)                       /* slice */
126         +((unit & ~31) << 16);                              /* high-order unit bits */
127     } else {                                                /* compatibility partition */
128         if ((*dname < 'a') || (*dname > 'h'))               /* or invalid partition */
129             return ENODEV;
130         devminor = (*dname - 'a')                           /* partition */
131         +((unit & 31) << 3)                                 /* unit */
132         +((unit & ~31) << 16);                              /* high-order unit bits */
133     }
134
135     if ((devminor & 7) == 2)                                /* partition c */
136         return ENOTTY;                                      /* not buying that */
137
138     drive->dev = makedev(devmajor, devminor);               /* find the device */
139     if (drive->dev == NULL)                                 /* didn't find anything */
140         return ENODEV;
141
142     drive->dev->si_iosize_max = DFLTPHYS;
143     dsw = devsw(drive->dev);
144     if (dsw == NULL)
145         drive->lasterror = ENOENT;
146     else
147         drive->lasterror = (dsw->d_open) (drive->dev, FWRITE, 0, NULL);
148
149     if (drive->lasterror != 0) {                            /* failed */
150         drive->state = drive_down;                          /* just force it down */
151         if (verbose)
152             log(LOG_WARNING,
153                 "vinum open_drive %s: failed with error %d\n",
154                 drive->devicename, drive->lasterror);
155     } else
156         drive->flags |= VF_OPEN;                            /* we're open now */
157
158     return drive->lasterror;
159 }
160
161 /*
162  * Set some variables in the drive struct
163  * in more convenient form.  Return error indication
164  */
165 int
166 set_drive_parms(struct drive *drive)
167 {
168     drive->blocksize = BLKDEV_IOSIZE;                       /* do we need this? */
169     drive->secsperblock = drive->blocksize                  /* number of sectors per block */
170         / drive->sectorsize;
171
172     /* Now update the label part */
173     bcopy(hostname, drive->label.sysname, VINUMHOSTNAMELEN); /* put in host name */
174     getmicrotime(&drive->label.date_of_birth);              /* and current time */
175     drive->label.drive_size = drive->mediasize;
176 #ifdef VINUMDEBUG
177     if (debug & DEBUG_BIGDRIVE)                             /* pretend we're 100 times as big */
178         drive->label.drive_size *= 100;
179 #endif
180
181     /* number of sectors available for subdisks */
182     drive->sectors_available = drive->label.drive_size / DEV_BSIZE - DATASTART;
183
184     /*
185      * Bug in 3.0 as of January 1998: you can open
186      * non-existent slices.  They have a length of 0.
187      */
188     if (drive->label.drive_size < MINVINUMSLICE) {          /* too small to worry about */
189         set_drive_state(drive->driveno, drive_down, setstate_force);
190         drive->lasterror = ENOSPC;
191         return ENOSPC;
192     }
193     drive->freelist_size = INITIAL_DRIVE_FREELIST;          /* initial number of entries */
194     drive->freelist = (struct drive_freelist *)
195         Malloc(INITIAL_DRIVE_FREELIST * sizeof(struct drive_freelist));
196     if (drive->freelist == NULL)                            /* can't malloc, dammit */
197         return ENOSPC;
198     drive->freelist_entries = 1;                            /* just (almost) the complete drive */
199     drive->freelist[0].offset = DATASTART;                  /* starts here */
200     drive->freelist[0].sectors = (drive->label.drive_size >> DEV_BSHIFT) - DATASTART; /* and it's this long */
201     if (drive->label.name[0] != '\0')                       /* got a name */
202         set_drive_state(drive->driveno, drive_up, setstate_force); /* our drive is accessible */
203     else                                                    /* we know about it, but that's all */
204         drive->state = drive_referenced;
205     return 0;
206 }
207
208 /*
209  * Initialize a drive: open the device and add device
210  * information
211  */
212 int
213 init_drive(struct drive *drive, int verbose)
214 {
215     if (drive->devicename[0] != '/') {
216         drive->lasterror = EINVAL;
217         log(LOG_ERR, "vinum: Can't open drive without drive name\n");
218         return EINVAL;
219     }
220     drive->lasterror = open_drive(drive, curthread, verbose); /* open the drive */
221     if (drive->lasterror)
222         return drive->lasterror;
223
224     drive->lasterror = (*devsw(drive->dev)->d_ioctl) (drive->dev,
225         DIOCGSECTORSIZE,
226         (caddr_t) & drive->sectorsize,
227         FREAD,
228         curthread);
229     if (drive->lasterror == 0)
230             drive->lasterror = (*devsw(drive->dev)->d_ioctl) (drive->dev,
231                 DIOCGMEDIASIZE,
232                 (caddr_t) & drive->mediasize,
233                 FREAD,
234                 curthread);
235     if (drive->lasterror) {
236         if (verbose)
237             log(LOG_WARNING,
238                 "vinum open_drive %s: Can't get partition information, drive->lasterror %d\n",
239                 drive->devicename,
240                 drive->lasterror);
241         close_drive(drive);
242         return drive->lasterror;
243     }
244 #if 0
245     /*
246      * XXX: this check is bogus and needs to be rewitten, we cannot guarantee
247      * XXX: that there will be a label with a typefield on all platforms.
248      */
249     if (drive->partinfo.part->p_fstype != FS_VINUM) {       /* not Vinum */
250         drive->lasterror = EFTYPE;
251         if (verbose)
252             log(LOG_WARNING,
253                 "vinum open_drive %s: Wrong partition type for vinum\n",
254                 drive->devicename);
255         close_drive(drive);
256         return EFTYPE;
257     }
258 #endif
259     return set_drive_parms(drive);                          /* set various odds and ends */
260 }
261
262 /* Close a drive if it's open. */
263 void
264 close_drive(struct drive *drive)
265 {
266     LOCKDRIVE(drive);                                       /* keep the daemon out */
267     if (drive->flags & VF_OPEN)
268         close_locked_drive(drive);                          /* and close it */
269     if (drive->state > drive_down)                          /* if it's up */
270         drive->state = drive_down;                          /* make sure it's down */
271     unlockdrive(drive);
272 }
273
274 /*
275  * Real drive close code, called with drive already locked.
276  * We have also checked that the drive is open.  No errors.
277  */
278 void
279 close_locked_drive(struct drive *drive)
280 {
281     /*
282      * If we can't access the drive, we can't flush
283      * the queues, which spec_close() will try to
284      * do.  Get rid of them here first.
285      */
286     drive->lasterror = (*devsw(drive->dev)->d_close) (drive->dev, 0, 0, NULL);
287     drive->flags &= ~VF_OPEN;                               /* no longer open */
288 }
289
290 /*
291  * Remove drive from the configuration.
292  * Caller must ensure that it isn't active.
293  */
294 void
295 remove_drive(int driveno)
296 {
297     struct drive *drive = &vinum_conf.drive[driveno];
298     struct vinum_hdr *vhdr;                                 /* buffer for header */
299     int error;
300
301     if (drive->state > drive_referenced) {                  /* real drive */
302         if (drive->state == drive_up) {
303             vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN); /* allocate buffer */
304             CHECKALLOC(vhdr, "Can't allocate memory");
305             error = read_drive(drive, (void *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
306             if (error)
307                 drive->lasterror = error;
308             else {
309                 vhdr->magic = VINUM_NOMAGIC;                /* obliterate the magic, but leave the rest */
310                 write_drive(drive, (void *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
311             }
312             Free(vhdr);
313         }
314         free_drive(drive);                                  /* close it and free resources */
315         save_config();                                      /* and save the updated configuration */
316     }
317 }
318
319 /*
320  * Transfer drive data.  Usually called from one of these defines;
321  * #define read_drive(a, b, c, d) driveio (a, b, c, d, B_READ)
322  * #define write_drive(a, b, c, d) driveio (a, b, c, d, B_WRITE)
323  *
324  * length and offset are in bytes, but must be multiples of sector
325  * size.  The function *does not check* for this condition, and
326  * truncates ruthlessly.
327  * Return error number
328  */
329 int
330 driveio(struct drive *drive, char *buf, size_t length, off_t offset, int flag)
331 {
332     int error;
333     struct buf *bp;
334
335     error = 0;                                              /* to keep the compiler happy */
336     while (length) {                                        /* divide into small enough blocks */
337         int len = min(length, MAXBSIZE);                    /* maximum block device transfer is MAXBSIZE */
338
339         bp = geteblk(len);                                  /* get a buffer header */
340         bp->b_flags = 0;
341         bp->b_iocmd = flag;
342         bp->b_dev = drive->dev;                             /* device */
343         bp->b_blkno = offset / drive->sectorsize;           /* block number */
344         bp->b_saveaddr = bp->b_data;
345         bp->b_data = buf;
346         bp->b_bcount = len;
347         DEV_STRATEGY(bp, 0);                                /* initiate the transfer */
348         error = bufwait(bp);
349         bp->b_data = bp->b_saveaddr;
350         bp->b_flags |= B_INVAL | B_AGE;
351         bp->b_ioflags &= ~BIO_ERROR;
352         brelse(bp);
353         if (error)
354             break;
355         length -= len;                                      /* update pointers */
356         buf += len;
357         offset += len;
358     }
359     return error;
360 }
361
362 /*
363  * Check a drive for a vinum header.  If found,
364  * update the drive information.  We come here
365  * with a partially populated drive structure
366  * which includes the device name.
367  *
368  * Return information on what we found.
369  *
370  * This function is called from two places: check_drive,
371  * which wants to find out whether the drive is a
372  * Vinum drive, and config_drive, which asserts that
373  * it is a vinum drive.  In the first case, we don't
374  * print error messages (verbose==0), in the second
375  * we do (verbose==1).
376  */
377 enum drive_label_info
378 read_drive_label(struct drive *drive, int verbose)
379 {
380     int error;
381     int result;                                             /* result of our search */
382     struct vinum_hdr *vhdr;                                 /* and as header */
383
384     error = init_drive(drive, 0);                           /* find the drive */
385     if (error)                                              /* find the drive */
386         return DL_CANT_OPEN;                                /* not ours */
387
388     vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN);     /* allocate buffers */
389     CHECKALLOC(vhdr, "Can't allocate memory");
390
391     drive->state = drive_up;                                /* be optimistic */
392     error = read_drive(drive, (void *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
393     if (vhdr->magic == VINUM_MAGIC) {                       /* ours! */
394         if (drive->label.name[0]                            /* we have a name for this drive */
395         &&(strcmp(drive->label.name, vhdr->label.name))) {  /* but it doesn't match the real name */
396             drive->lasterror = EINVAL;
397             result = DL_WRONG_DRIVE;                        /* it's the wrong drive */
398             drive->state = drive_unallocated;               /* put it back, it's not ours */
399         } else
400             result = DL_OURS;
401         /*
402          * We copy the drive anyway so that we have
403          * the correct name in the drive info.  This
404          * may not be the name specified
405          */
406         drive->label = vhdr->label;                         /* put in the label information */
407     } else if (vhdr->magic == VINUM_NOMAGIC)                /* was ours, but we gave it away */
408         result = DL_DELETED_LABEL;                          /* and return the info */
409     else
410         result = DL_NOT_OURS;                               /* we could have it, but we don't yet */
411     Free(vhdr);                                             /* that's all. */
412     return result;
413 }
414
415 /*
416  * Check a drive for a vinum header.  If found,
417  * read configuration information from the drive and
418  * incorporate the data into the configuration.
419  *
420  * Return drive number.
421  */
422 struct drive *
423 check_drive(char *devicename)
424 {
425     int driveno;
426     int i;
427     struct drive *drive;
428
429     driveno = find_drive_by_dev(devicename, 1);             /* if entry doesn't exist, create it */
430     drive = &vinum_conf.drive[driveno];                     /* and get a pointer */
431
432     if (read_drive_label(drive, 0) == DL_OURS) {            /* one of ours */
433         for (i = 0; i < vinum_conf.drives_allocated; i++) { /* see if the name already exists */
434             if ((i != driveno)                              /* not this drive */
435             &&(DRIVE[i].state != drive_unallocated)         /* and it's allocated */
436             &&(strcmp(DRIVE[i].label.name,
437                         DRIVE[driveno].label.name) == 0)) { /* and it has the same name */
438                 struct drive *mydrive = &DRIVE[i];
439
440                 if (mydrive->devicename[0] == '/') {        /* we know a device name for it */
441                     /*
442                      * set an error, but don't take the
443                      * drive down: that would cause unneeded
444                      * error messages.
445                      */
446                     drive->lasterror = EEXIST;
447                     break;
448                 } else {                                    /* it's just a place holder, */
449                     int sdno;
450
451                     for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) { /* look at each subdisk */
452                         if ((SD[sdno].driveno == i)         /* it's pointing to this one, */
453                         &&(SD[sdno].state != sd_unallocated)) { /* and it's a real subdisk */
454                             SD[sdno].driveno = drive->driveno; /* point to the one we found */
455                             update_sd_state(sdno);          /* and update its state */
456                         }
457                     }
458                     bzero(mydrive, sizeof(struct drive));   /* don't deallocate it, just remove it */
459                 }
460             }
461         }
462     } else {
463         if (drive->lasterror == 0)
464             drive->lasterror = ENODEV;
465         close_drive(drive);
466         drive->state = drive_down;
467     }
468     return drive;
469 }
470
471 static char *
472 sappend(char *txt, char *s)
473 {
474     while ((*s++ = *txt++) != 0);
475     return s - 1;
476 }
477
478 void
479 format_config(char *config, int len)
480 {
481     int i;
482     int j;
483     char *s = config;
484     char *configend = &config[len];
485
486     bzero(config, len);
487
488     /* First write the volume configuration */
489     for (i = 0; i < vinum_conf.volumes_allocated; i++) {
490         struct volume *vol;
491
492         vol = &vinum_conf.volume[i];
493         if ((vol->state > volume_uninit)
494             && (vol->name[0] != '\0')) {                    /* paranoia */
495             snprintf(s,
496                 configend - s,
497                 "volume %s state %s",
498                 vol->name,
499                 volume_state(vol->state));
500             while (*s)
501                 s++;                                        /* find the end */
502             if (vol->preferred_plex >= 0)                   /* preferences, */
503                 snprintf(s,
504                     configend - s,
505                     " readpol prefer %s",
506                     vinum_conf.plex[vol->preferred_plex].name);
507             while (*s)
508                 s++;                                        /* find the end */
509             s = sappend("\n", s);
510         }
511     }
512
513     /* Then the plex configuration */
514     for (i = 0; i < vinum_conf.plexes_allocated; i++) {
515         struct plex *plex;
516
517         plex = &vinum_conf.plex[i];
518         if ((plex->state > plex_referenced)
519             && (plex->name[0] != '\0')) {                   /* paranoia */
520             snprintf(s,
521                 configend - s,
522                 "plex name %s state %s org %s ",
523                 plex->name,
524                 plex_state(plex->state),
525                 plex_org(plex->organization));
526             while (*s)
527                 s++;                                        /* find the end */
528             if (isstriped(plex)) {
529                 snprintf(s,
530                     configend - s,
531                     "%ds ",
532                     (int) plex->stripesize);
533                 while (*s)
534                     s++;                                    /* find the end */
535             }
536             if (plex->volno >= 0)                           /* we have a volume */
537                 snprintf(s,
538                     configend - s,
539                     "vol %s ",
540                     vinum_conf.volume[plex->volno].name);
541             while (*s)
542                 s++;                                        /* find the end */
543             for (j = 0; j < plex->subdisks; j++) {
544                 snprintf(s,
545                     configend - s,
546                     " sd %s",
547                     vinum_conf.sd[plex->sdnos[j]].name);
548             }
549             s = sappend("\n", s);
550         }
551     }
552
553     /* And finally the subdisk configuration */
554     for (i = 0; i < vinum_conf.subdisks_allocated; i++) {
555         struct sd *sd;
556         char *drivename;
557
558         sd = &SD[i];
559         if ((sd->state != sd_referenced)
560             && (sd->state != sd_unallocated)
561             && (sd->name[0] != '\0')) {                     /* paranoia */
562             drivename = vinum_conf.drive[sd->driveno].label.name;
563             /*
564              * XXX We've seen cases of dead subdisks
565              * which don't have a drive.  If we let them
566              * through here, the drive name is null, so
567              * they get the drive named 'plex'.
568              *
569              * This is a breakage limiter, not a fix.
570              */
571             if (drivename[0] == '\0')
572                 drivename = "*invalid*";
573             snprintf(s,
574                 configend - s,
575                 "sd name %s drive %s plex %s len %llus driveoffset %llus state %s",
576                 sd->name,
577                 drivename,
578                 vinum_conf.plex[sd->plexno].name,
579                 (unsigned long long) sd->sectors,
580                 (unsigned long long) sd->driveoffset,
581                 sd_state(sd->state));
582             while (*s)
583                 s++;                                        /* find the end */
584             if (sd->plexno >= 0)
585                 snprintf(s,
586                     configend - s,
587                     " plexoffset %llds",
588                     (long long) sd->plexoffset);
589             else
590                 snprintf(s, configend - s, " detached");
591             while (*s)
592                 s++;                                        /* find the end */
593             if (sd->flags & VF_RETRYERRORS) {
594                 snprintf(s, configend - s, " retryerrors");
595                 while (*s)
596                     s++;                                    /* find the end */
597             }
598             snprintf(s, configend - s, " \n");
599             while (*s)
600                 s++;                                        /* find the end */
601         }
602     }
603     if (s > &config[len - 2])
604         panic("vinum: configuration data overflow");
605 }
606
607 /*
608  * issue a save config request to the dæmon.  The actual work
609  * is done in process context by daemon_save_config
610  */
611 void
612 save_config(void)
613 {
614     queue_daemon_request(daemonrq_saveconfig, (union daemoninfo) NULL);
615 }
616
617 /*
618  * Write the configuration to all vinum slices.  This
619  * is performed by the dæmon only
620  */
621 void
622 daemon_save_config(void)
623 {
624     int error;
625     int written_config;                                     /* set when we first write the config to disk */
626     int driveno;
627     struct drive *drive;                                    /* point to current drive info */
628     struct vinum_hdr *vhdr;                                 /* and as header */
629     char *config;                                           /* point to config data */
630     int wlabel_on;                                          /* to set writing label on/off */
631
632     /* don't save the configuration while we're still working on it */
633     if (vinum_conf.flags & VF_CONFIGURING)
634         return;
635     written_config = 0;                                     /* no config written yet */
636     /* Build a volume header */
637     vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN);     /* get space for the config data */
638     CHECKALLOC(vhdr, "Can't allocate config data");
639     vhdr->magic = VINUM_MAGIC;                              /* magic number */
640     vhdr->config_length = MAXCONFIG;                        /* length of following config info */
641
642     config = Malloc(MAXCONFIG);                             /* get space for the config data */
643     CHECKALLOC(config, "Can't allocate config data");
644
645     format_config(config, MAXCONFIG);
646     error = 0;                                              /* no errors yet */
647     for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
648         drive = &vinum_conf.drive[driveno];                 /* point to drive */
649         if (drive->state > drive_referenced) {
650             LOCKDRIVE(drive);                               /* don't let it change */
651
652             /*
653              * First, do some drive consistency checks.  Some
654              * of these are kludges, others require a process
655              * context and couldn't be done before
656              */
657             if ((drive->devicename[0] == '\0')
658                 || (drive->label.name[0] == '\0')) {
659                 unlockdrive(drive);
660                 free_drive(drive);                          /* get rid of it */
661                 break;
662             }
663             if (((drive->flags & VF_OPEN) == 0)             /* drive not open */
664             &&(drive->state > drive_down)) {                /* and it thinks it's not down */
665                 unlockdrive(drive);
666                 set_drive_state(driveno, drive_down, setstate_force); /* tell it what's what */
667                 continue;
668             }
669             if ((drive->state == drive_down)                /* it's down */
670             &&(drive->flags & VF_OPEN)) {                   /* but open, */
671                 unlockdrive(drive);
672                 close_drive(drive);                         /* close it */
673             } else if (drive->state > drive_down) {
674                 getmicrotime(&drive->label.last_update);    /* time of last update is now */
675                 bcopy((char *) &drive->label,               /* and the label info from the drive structure */
676                     (char *) &vhdr->label,
677                     sizeof(vhdr->label));
678                 if ((drive->state != drive_unallocated)
679                     && (drive->state != drive_referenced)) { /* and it's a real drive */
680                     wlabel_on = 1;                          /* enable writing the label */
681                     error = (*devsw(drive->dev)->d_ioctl) (drive->dev, /* make the label writeable */
682                         DIOCWLABEL,
683                         (caddr_t) & wlabel_on,
684                         FWRITE,
685                         curthread);
686                     if (error == 0)
687                         error = write_drive(drive, (char *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
688                     if (error == 0)
689                         error = write_drive(drive, config, MAXCONFIG, VINUM_CONFIG_OFFSET); /* first config copy */
690                     if (error == 0)
691                         error = write_drive(drive, config, MAXCONFIG, VINUM_CONFIG_OFFSET + MAXCONFIG); /* second copy */
692                     wlabel_on = 0;                          /* enable writing the label */
693                     if (error == 0)
694                         error = (*devsw(drive->dev)->d_ioctl) (drive->dev, /* make the label non-writeable again */
695                             DIOCWLABEL,
696                             (caddr_t) & wlabel_on,
697                             FWRITE,
698                             curthread);
699                     unlockdrive(drive);
700                     if (error) {
701                         log(LOG_ERR,
702                             "vinum: Can't write config to %s, error %d\n",
703                             drive->devicename,
704                             error);
705                         set_drive_state(drive->driveno, drive_down, setstate_force);
706                     } else
707                         written_config = 1;                 /* we've written it on at least one drive */
708                 }
709             } else                                          /* not worth looking at, */
710                 unlockdrive(drive);                         /* just unlock it again */
711         }
712     }
713     Free(vhdr);
714     Free(config);
715 }
716
717 /*
718  * Disk labels are a mess.  The correct way to
719  * access them is with the DIOC[GSW]DINFO ioctls,
720  * but some programs, such as newfs, access the
721  * disk directly, so we have to write things
722  * there.  We do this only on request.  If a user
723  * request tries to read it directly, we fake up
724  * one on the fly.
725  */
726
727 /*
728  * get_volume_label returns a label structure to lp, which
729  * is allocated by the caller
730  */
731 void
732 get_volume_label(char *name, int plexes, u_int64_t size, struct disklabel *lp)
733 {
734     bzero(lp, sizeof(struct disklabel));
735
736     strncpy(lp->d_typename, "vinum", sizeof(lp->d_typename));
737     lp->d_type = DTYPE_VINUM;
738     strncpy(lp->d_packname, name, min(sizeof(lp->d_packname), sizeof(name)));
739     lp->d_rpm = 14400 * plexes;                             /* to keep them guessing */
740     lp->d_interleave = 1;
741     lp->d_flags = 0;
742
743     /*
744      * A Vinum volume has a single track with all
745      * its sectors.
746      */
747     lp->d_secsize = DEV_BSIZE;                              /* bytes per sector */
748     lp->d_nsectors = size;                                  /* data sectors per track */
749     lp->d_ntracks = 1;                                      /* tracks per cylinder */
750     lp->d_ncylinders = 1;                                   /* data cylinders per unit */
751     lp->d_secpercyl = size;                                 /* data sectors per cylinder */
752     lp->d_secperunit = size;                                /* data sectors per unit */
753
754     lp->d_bbsize = BBSIZE;
755     lp->d_sbsize = 0;
756
757     lp->d_magic = DISKMAGIC;
758     lp->d_magic2 = DISKMAGIC;
759
760     /*
761      * Set up partitions a, b and c to be identical
762      * and the size of the volume.  a is UFS, b is
763      * swap, c is nothing.
764      */
765     lp->d_partitions[0].p_size = size;
766     lp->d_partitions[0].p_fsize = 1024;
767     lp->d_partitions[0].p_fstype = FS_BSDFFS;               /* FreeBSD File System :-) */
768     lp->d_partitions[0].p_fsize = 1024;                     /* FS fragment size */
769     lp->d_partitions[0].p_frag = 8;                         /* and fragments per block */
770     lp->d_partitions[SWAP_PART].p_size = size;
771     lp->d_partitions[SWAP_PART].p_fstype = FS_SWAP;         /* swap partition */
772     lp->d_partitions[LABEL_PART].p_size = size;
773     lp->d_npartitions = LABEL_PART + 1;
774     strncpy(lp->d_packname, name, min(sizeof(lp->d_packname), sizeof(name)));
775     lp->d_checksum = dkcksum(lp);
776 }
777
778 /* Write a volume label.  This implements the VINUM_LABEL ioctl. */
779 int
780 write_volume_label(int volno)
781 {
782     struct disklabel *lp;
783     struct buf *bp;
784     struct disklabel *dlp;
785     struct volume *vol;
786     int error;
787
788     lp = (struct disklabel *) Malloc((sizeof(struct disklabel) + (DEV_BSIZE - 1)) & (DEV_BSIZE - 1));
789     if (lp == 0)
790         return ENOMEM;
791
792     if ((unsigned) (volno) >= (unsigned) vinum_conf.volumes_allocated) /* invalid volume */
793         return ENOENT;
794
795     vol = &VOL[volno];                                      /* volume in question */
796     if (vol->state <= volume_uninit)                        /* nothing there */
797         return ENXIO;
798     else if (vol->state < volume_up)                        /* not accessible */
799         return EIO;                                         /* I/O error */
800
801     get_volume_label(vol->name, vol->plexes, vol->size, lp); /* get the label */
802
803     /*
804      * Now write to disk.  This code is derived from the
805      * system writedisklabel (), which does silly things
806      * like reading the label and refusing to write
807      * unless it's already there.
808      */
809     bp = geteblk((int) lp->d_secsize);                      /* get a buffer */
810     bp->b_dev = makedev(VINUM_CDEV_MAJOR, vol->volno);      /* our own raw volume */
811     bp->b_blkno = LABELSECTOR * ((int) lp->d_secsize / DEV_BSIZE);
812     bp->b_bcount = lp->d_secsize;
813     bzero(bp->b_data, lp->d_secsize);
814     dlp = (struct disklabel *) bp->b_data;
815     *dlp = *lp;
816     bp->b_flags &= ~B_INVAL;
817     bp->b_iocmd = BIO_WRITE;
818
819     /*
820      * This should read:
821      *
822      *       vinumstrategy (bp);
823      *
824      * Negotiate with phk to get it fixed.
825      */
826     DEV_STRATEGY(bp, 0);
827     error = bufwait(bp);
828     bp->b_flags |= B_INVAL | B_AGE;
829     bp->b_ioflags &= ~BIO_ERROR;
830
831     brelse(bp);
832     return error;
833 }
834
835 /* Look at all disks on the system for vinum slices */
836 int
837 vinum_scandisk(char *devicename[], int drives)
838 {
839     struct drive *volatile drive;
840     volatile int driveno;
841     int firstdrive;                                         /* first drive in this list */
842     volatile int gooddrives;                                /* number of usable drives found */
843     int firsttime;                                          /* set if we have never configured before */
844     int error;
845     char *config_text;                                      /* read the config info from disk into here */
846     char *volatile cptr;                                    /* pointer into config information */
847     char *eptr;                                             /* end pointer into config information */
848     char *config_line;                                      /* copy the config line to */
849     volatile int status;
850     int *volatile drivelist;                                /* list of drive indices */
851 #define DRIVENAMELEN 64
852 #define DRIVEPARTS   35                                     /* max partitions per drive, excluding c */
853     char partname[DRIVENAMELEN];                            /* for creating partition names */
854
855     status = 0;                                             /* success indication */
856     vinum_conf.flags |= VF_READING_CONFIG;                  /* reading config from disk */
857
858     gooddrives = 0;                                         /* number of usable drives found */
859     firstdrive = vinum_conf.drives_used;                    /* the first drive */
860     firsttime = vinum_conf.drives_used == 0;                /* are we a virgin? */
861
862     /* allocate a drive pointer list */
863     drivelist = (int *) Malloc(drives * DRIVEPARTS * sizeof(int));
864     CHECKALLOC(drivelist, "Can't allocate memory");
865
866     /* Open all drives and find which was modified most recently */
867     for (driveno = 0; driveno < drives; driveno++) {
868         char part;                                          /* UNIX partition */
869         int slice;
870         int founddrive;                                     /* flag when we find a vinum drive */
871
872         founddrive = 0;                                     /* no vinum drive found yet on this spindle */
873         /* first try the partition table */
874         for (slice = 1; slice < 5; slice++)
875             for (part = 'a'; part < 'i'; part++) {
876                 if (part != 'c') {                          /* don't do the c partition */
877                     snprintf(partname,
878                         DRIVENAMELEN,
879                         "%ss%d%c",
880                         devicename[driveno],
881                         slice,
882                         part);
883                     drive = check_drive(partname);          /* try to open it */
884                     if ((drive->lasterror != 0)             /* didn't work, */
885                     ||(drive->state != drive_up))
886                         free_drive(drive);                  /* get rid of it */
887                     else if (drive->flags & VF_CONFIGURED)  /* already read this config, */
888                         log(LOG_WARNING,
889                             "vinum: already read config from %s\n", /* say so */
890                             drive->label.name);
891                     else {
892                         drivelist[gooddrives] = drive->driveno; /* keep the drive index */
893                         drive->flags &= ~VF_NEWBORN;        /* which is no longer newly born */
894                         gooddrives++;
895                         founddrive++;
896                     }
897                 }
898             }
899         if (founddrive == 0) {                              /* didn't find anything, */
900             for (part = 'a'; part < 'i'; part++)            /* try the compatibility partition */
901                 if (part != 'c') {                          /* don't do the c partition */
902                     snprintf(partname,                      /* /dev/sd0a */
903                         DRIVENAMELEN,
904                         "%s%c",
905                         devicename[driveno],
906                         part);
907                     drive = check_drive(partname);          /* try to open it */
908                     if ((drive->lasterror != 0)             /* didn't work, */
909                     ||(drive->state != drive_up))
910                         free_drive(drive);                  /* get rid of it */
911                     else if (drive->flags & VF_CONFIGURED)  /* already read this config, */
912                         log(LOG_WARNING,
913                             "vinum: already read config from %s\n", /* say so */
914                             drive->label.name);
915                     else {
916                         drivelist[gooddrives] = drive->driveno; /* keep the drive index */
917                         drive->flags &= ~VF_NEWBORN;        /* which is no longer newly born */
918                         gooddrives++;
919                     }
920                 }
921         }
922     }
923
924     if (gooddrives == 0) {
925         if (firsttime)
926             log(LOG_WARNING, "vinum: no drives found\n");
927         else
928             log(LOG_INFO, "vinum: no additional drives found\n");
929         return ENOENT;
930     }
931     /*
932      * We now have at least one drive
933      * open.  Sort them in order of config time
934      * and merge the config info with what we
935      * have already.
936      */
937     qsort(drivelist, gooddrives, sizeof(int), drivecmp);
938     config_text = (char *) Malloc(MAXCONFIG * 2);           /* allocate buffers */
939     CHECKALLOC(config_text, "Can't allocate memory");
940     config_line = (char *) Malloc(MAXCONFIGLINE * 2);       /* allocate buffers */
941     CHECKALLOC(config_line, "Can't allocate memory");
942     for (driveno = 0; driveno < gooddrives; driveno++) {    /* now include the config */
943         drive = &DRIVE[drivelist[driveno]];                 /* point to the drive */
944
945         if (firsttime && (driveno == 0))                    /* we've never configured before, */
946             log(LOG_INFO, "vinum: reading configuration from %s\n", drive->devicename);
947         else
948             log(LOG_INFO, "vinum: updating configuration from %s\n", drive->devicename);
949
950         if (drive->state == drive_up)
951             /* Read in both copies of the configuration information */
952             error = read_drive(drive, config_text, MAXCONFIG * 2, VINUM_CONFIG_OFFSET);
953         else {
954             error = EIO;
955             printf("vinum_scandisk: %s is %s\n", drive->devicename, drive_state(drive->state));
956         }
957
958         if (error != 0) {
959             log(LOG_ERR, "vinum: Can't read device %s, error %d\n", drive->devicename, error);
960             free_drive(drive);                              /* give it back */
961             status = error;
962         }
963         /*
964          * At this point, check that the two copies
965          * are the same, and do something useful if
966          * not.  In particular, consider which is
967          * newer, and what this means for the
968          * integrity of the data on the drive.
969          */
970         else {
971             vinum_conf.drives_used++;                       /* another drive in use */
972             /* Parse the configuration, and add it to the global configuration */
973             for (cptr = config_text; *cptr != '\0';) {      /* love this style(9) */
974                 volatile int parse_status;                  /* return value from parse_config */
975
976                 for (eptr = config_line; (*cptr != '\n') && (*cptr != '\0');) /* until the end of the line */
977                     *eptr++ = *cptr++;
978                 *eptr = '\0';                               /* and delimit */
979                 if (setjmp(command_fail) == 0) {            /* come back here on error and continue */
980                     parse_status = parse_config(config_line, &keyword_set, 1); /* parse the config line */
981                     if (parse_status < 0) {                 /* error in config */
982                         /*
983                            * This config should have been parsed in user
984                            * space.  If we run into problems here, something
985                            * serious is afoot.  Complain and let the user
986                            * snarf the config to see what's wrong.
987                          */
988                         log(LOG_ERR,
989                             "vinum: Config error on %s, aborting integration\n",
990                             drive->devicename);
991                         free_drive(drive);                  /* give it back */
992                         status = EINVAL;
993                     }
994                 }
995                 while (*cptr == '\n')
996                     cptr++;                                 /* skip to next line */
997             }
998         }
999         drive->flags |= VF_CONFIGURED;                      /* read this drive's configuration */
1000     }
1001
1002     Free(config_text);
1003     Free(drivelist);
1004     vinum_conf.flags &= ~VF_READING_CONFIG;                 /* no longer reading from disk */
1005     if (status != 0)
1006         printf("vinum: couldn't read configuration");
1007     else
1008         updateconfig(VF_READING_CONFIG);                    /* update from disk config */
1009     return status;
1010 }
1011
1012 /*
1013  * Compare the modification dates of the drives, for qsort.
1014  * Return 1 if a < b, 0 if a == b, 01 if a > b: in other
1015  * words, sort backwards.
1016  */
1017 int
1018 drivecmp(const void *va, const void *vb)
1019 {
1020     const struct drive *a = &DRIVE[*(const int *) va];
1021     const struct drive *b = &DRIVE[*(const int *) vb];
1022
1023     if ((a->label.last_update.tv_sec == b->label.last_update.tv_sec)
1024         && (a->label.last_update.tv_usec == b->label.last_update.tv_usec))
1025         return 0;
1026     else if ((a->label.last_update.tv_sec > b->label.last_update.tv_sec)
1027             || ((a->label.last_update.tv_sec == b->label.last_update.tv_sec)
1028             && (a->label.last_update.tv_usec > b->label.last_update.tv_usec)))
1029         return -1;
1030     else
1031         return 1;
1032 }
1033 /* Local Variables: */
1034 /* fill-column: 50 */
1035 /* End: */