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