xref: /dragonfly/sys/dev/raid/vinum/vinumio.c (revision 0bb9290e)
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.15 2006/07/28 02:17:38 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, proc0.p_ucred);
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 	proc0.p_ucred);
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);
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, BUF_CMD_READ)
308  * #define write_drive(a, b, c, d) driveio (a, b, c, d, BUF_CMD_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, buf_cmd_t cmd)
317 {
318     int error;
319     struct buf *bp;
320     caddr_t saveaddr;
321 
322     error = 0;						    /* to keep the compiler happy */
323     while (length) {					    /* divide into small enough blocks */
324 	int len = min(length, MAXBSIZE);		    /* maximum block device transfer is MAXBSIZE */
325 
326 	bp = geteblk(len);				    /* get a buffer header */
327 	bp->b_cmd = cmd;
328 	bp->b_bio1.bio_offset = offset;			    /* disk offset */
329 	saveaddr = bp->b_data;
330 	bp->b_data = buf;
331 	bp->b_bcount = len;
332 	dev_dstrategy(drive->dev, &bp->b_bio1);
333 	error = biowait(bp);
334 	bp->b_data = saveaddr;
335 	bp->b_flags |= B_INVAL | B_AGE;
336 	bp->b_flags &= ~B_ERROR;
337 	brelse(bp);
338 	if (error)
339 	    break;
340 	length -= len;					    /* update pointers */
341 	buf += len;
342 	offset += len;
343     }
344     return error;
345 }
346 
347 /*
348  * Check a drive for a vinum header.  If found,
349  * update the drive information.  We come here
350  * with a partially populated drive structure
351  * which includes the device name.
352  *
353  * Return information on what we found.
354  *
355  * This function is called from two places: check_drive,
356  * which wants to find out whether the drive is a
357  * Vinum drive, and config_drive, which asserts that
358  * it is a vinum drive.  In the first case, we don't
359  * print error messages (verbose==0), in the second
360  * we do (verbose==1).
361  */
362 enum drive_label_info
363 read_drive_label(struct drive *drive, int verbose)
364 {
365     int error;
366     int result;						    /* result of our search */
367     struct vinum_hdr *vhdr;				    /* and as header */
368 
369     error = init_drive(drive, 0);			    /* find the drive */
370     if (error)						    /* find the drive */
371 	return DL_CANT_OPEN;				    /* not ours */
372 
373     vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN);	    /* allocate buffers */
374     CHECKALLOC(vhdr, "Can't allocate memory");
375 
376     drive->state = drive_up;				    /* be optimistic */
377     error = read_drive(drive, (void *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
378     if (vhdr->magic == VINUM_MAGIC) {			    /* ours! */
379 	if (drive->label.name[0]			    /* we have a name for this drive */
380 	&&(strcmp(drive->label.name, vhdr->label.name))) {  /* but it doesn't match the real name */
381 	    drive->lasterror = EINVAL;
382 	    result = DL_WRONG_DRIVE;			    /* it's the wrong drive */
383 	    drive->state = drive_unallocated;		    /* put it back, it's not ours */
384 	} else
385 	    result = DL_OURS;
386 	/*
387 	 * We copy the drive anyway so that we have
388 	 * the correct name in the drive info.  This
389 	 * may not be the name specified
390 	 */
391 	drive->label = vhdr->label;			    /* put in the label information */
392     } else if (vhdr->magic == VINUM_NOMAGIC)		    /* was ours, but we gave it away */
393 	result = DL_DELETED_LABEL;			    /* and return the info */
394     else
395 	result = DL_NOT_OURS;				    /* we could have it, but we don't yet */
396     Free(vhdr);						    /* that's all. */
397     return result;
398 }
399 
400 /*
401  * Check a drive for a vinum header.  If found,
402  * read configuration information from the drive and
403  * incorporate the data into the configuration.
404  *
405  * Return drive number.
406  */
407 struct drive *
408 check_drive(char *devicename)
409 {
410     int driveno;
411     int i;
412     struct drive *drive;
413 
414     driveno = find_drive_by_dev(devicename, 1);		    /* if entry doesn't exist, create it */
415     drive = &vinum_conf.drive[driveno];			    /* and get a pointer */
416 
417     if (read_drive_label(drive, 0) == DL_OURS) {	    /* one of ours */
418 	for (i = 0; i < vinum_conf.drives_allocated; i++) { /* see if the name already exists */
419 	    if ((i != driveno)				    /* not this drive */
420 	    &&(DRIVE[i].state != drive_unallocated)	    /* and it's allocated */
421 	    &&(strcmp(DRIVE[i].label.name,
422 			DRIVE[driveno].label.name) == 0)) { /* and it has the same name */
423 		struct drive *mydrive = &DRIVE[i];
424 
425 		if (mydrive->devicename[0] == '/') {	    /* we know a device name for it */
426 		    /*
427 		     * set an error, but don't take the
428 		     * drive down: that would cause unneeded
429 		     * error messages.
430 		     */
431 		    drive->lasterror = EEXIST;
432 		    break;
433 		} else {				    /* it's just a place holder, */
434 		    int sdno;
435 
436 		    for (sdno = 0; sdno < vinum_conf.subdisks_allocated; sdno++) { /* look at each subdisk */
437 			if ((SD[sdno].driveno == i)	    /* it's pointing to this one, */
438 			&&(SD[sdno].state != sd_unallocated)) {	/* and it's a real subdisk */
439 			    SD[sdno].driveno = drive->driveno; /* point to the one we found */
440 			    update_sd_state(sdno);	    /* and update its state */
441 			}
442 		    }
443 		    bzero(mydrive, sizeof(struct drive));   /* don't deallocate it, just remove it */
444 		}
445 	    }
446 	}
447     } else {
448 	if (drive->lasterror == 0)
449 	    drive->lasterror = ENODEV;
450 	close_drive(drive);
451 	drive->state = drive_down;
452     }
453     return drive;
454 }
455 
456 static char *
457 sappend(char *txt, char *s)
458 {
459     while ((*s++ = *txt++) != 0);
460     return s - 1;
461 }
462 
463 void
464 format_config(char *config, int len)
465 {
466     int i;
467     int j;
468     char *s = config;
469     char *configend = &config[len];
470 
471     bzero(config, len);
472 
473     /* First write the volume configuration */
474     for (i = 0; i < vinum_conf.volumes_allocated; i++) {
475 	struct volume *vol;
476 
477 	vol = &vinum_conf.volume[i];
478 	if ((vol->state > volume_uninit)
479 	    && (vol->name[0] != '\0')) {		    /* paranoia */
480 	    snprintf(s,
481 		configend - s,
482 		"volume %s state %s",
483 		vol->name,
484 		volume_state(vol->state));
485 	    while (*s)
486 		s++;					    /* find the end */
487 	    if (vol->preferred_plex >= 0)		    /* preferences, */
488 		snprintf(s,
489 		    configend - s,
490 		    " readpol prefer %s",
491 		    vinum_conf.plex[vol->preferred_plex].name);
492 	    while (*s)
493 		s++;					    /* find the end */
494 	    s = sappend("\n", s);
495 	}
496     }
497 
498     /* Then the plex configuration */
499     for (i = 0; i < vinum_conf.plexes_allocated; i++) {
500 	struct plex *plex;
501 
502 	plex = &vinum_conf.plex[i];
503 	if ((plex->state > plex_referenced)
504 	    && (plex->name[0] != '\0')) {		    /* paranoia */
505 	    snprintf(s,
506 		configend - s,
507 		"plex name %s state %s org %s ",
508 		plex->name,
509 		plex_state(plex->state),
510 		plex_org(plex->organization));
511 	    while (*s)
512 		s++;					    /* find the end */
513 	    if (isstriped(plex)) {
514 		snprintf(s,
515 		    configend - s,
516 		    "%ds ",
517 		    (int) plex->stripesize);
518 		while (*s)
519 		    s++;				    /* find the end */
520 	    }
521 	    if (plex->volno >= 0)			    /* we have a volume */
522 		snprintf(s,
523 		    configend - s,
524 		    "vol %s ",
525 		    vinum_conf.volume[plex->volno].name);
526 	    while (*s)
527 		s++;					    /* find the end */
528 	    for (j = 0; j < plex->subdisks; j++) {
529 		snprintf(s,
530 		    configend - s,
531 		    " sd %s",
532 		    vinum_conf.sd[plex->sdnos[j]].name);
533 	    }
534 	    s = sappend("\n", s);
535 	}
536     }
537 
538     /* And finally the subdisk configuration */
539     for (i = 0; i < vinum_conf.subdisks_allocated; i++) {
540 	struct sd *sd;
541 	char *drivename;
542 
543 	sd = &SD[i];
544 	if ((sd->state != sd_referenced)
545 	    && (sd->state != sd_unallocated)
546 	    && (sd->name[0] != '\0')) {			    /* paranoia */
547 	    drivename = vinum_conf.drive[sd->driveno].label.name;
548 	    /*
549 	     * XXX We've seen cases of dead subdisks
550 	     * which don't have a drive.  If we let them
551 	     * through here, the drive name is null, so
552 	     * they get the drive named 'plex'.
553 	     *
554 	     * This is a breakage limiter, not a fix.
555 	     */
556 	    if (drivename[0] == '\0')
557 		drivename = "*invalid*";
558 	    snprintf(s,
559 		configend - s,
560 		"sd name %s drive %s plex %s len %llus driveoffset %llus state %s",
561 		sd->name,
562 		drivename,
563 		vinum_conf.plex[sd->plexno].name,
564 		(unsigned long long) sd->sectors,
565 		(unsigned long long) sd->driveoffset,
566 		sd_state(sd->state));
567 	    while (*s)
568 		s++;					    /* find the end */
569 	    if (sd->plexno >= 0)
570 		snprintf(s,
571 		    configend - s,
572 		    " plexoffset %llds",
573 		    (long long) sd->plexoffset);
574 	    else
575 		snprintf(s, configend - s, " detached");
576 	    while (*s)
577 		s++;					    /* find the end */
578 	    if (sd->flags & VF_RETRYERRORS) {
579 		snprintf(s, configend - s, " retryerrors");
580 		while (*s)
581 		    s++;				    /* find the end */
582 	    }
583 	    snprintf(s, configend - s, " \n");
584 	    while (*s)
585 		s++;					    /* find the end */
586 	}
587     }
588     if (s > &config[len - 2])
589 	panic("vinum: configuration data overflow");
590 }
591 
592 /*
593  * issue a save config request to the d�mon.  The actual work
594  * is done in process context by daemon_save_config
595  */
596 void
597 save_config(void)
598 {
599     queue_daemon_request(daemonrq_saveconfig, (union daemoninfo) NULL);
600 }
601 
602 /*
603  * Write the configuration to all vinum slices.  This
604  * is performed by the d�mon only
605  */
606 void
607 daemon_save_config(void)
608 {
609     int error;
610     int written_config;					    /* set when we first write the config to disk */
611     int driveno;
612     struct drive *drive;				    /* point to current drive info */
613     struct vinum_hdr *vhdr;				    /* and as header */
614     char *config;					    /* point to config data */
615     int wlabel_on;					    /* to set writing label on/off */
616 
617     /* don't save the configuration while we're still working on it */
618     if (vinum_conf.flags & VF_CONFIGURING)
619 	return;
620     written_config = 0;					    /* no config written yet */
621     /* Build a volume header */
622     vhdr = (struct vinum_hdr *) Malloc(VINUMHEADERLEN);	    /* get space for the config data */
623     CHECKALLOC(vhdr, "Can't allocate config data");
624     vhdr->magic = VINUM_MAGIC;				    /* magic number */
625     vhdr->config_length = MAXCONFIG;			    /* length of following config info */
626 
627     config = Malloc(MAXCONFIG);				    /* get space for the config data */
628     CHECKALLOC(config, "Can't allocate config data");
629 
630     format_config(config, MAXCONFIG);
631     error = 0;						    /* no errors yet */
632     for (driveno = 0; driveno < vinum_conf.drives_allocated; driveno++) {
633 	drive = &vinum_conf.drive[driveno];		    /* point to drive */
634 	if (drive->state > drive_referenced) {
635 	    LOCKDRIVE(drive);				    /* don't let it change */
636 
637 	    /*
638 	     * First, do some drive consistency checks.  Some
639 	     * of these are kludges, others require a process
640 	     * context and couldn't be done before
641 	     */
642 	    if ((drive->devicename[0] == '\0')
643 		|| (drive->label.name[0] == '\0')) {
644 		unlockdrive(drive);
645 		free_drive(drive);			    /* get rid of it */
646 		break;
647 	    }
648 	    if (((drive->flags & VF_OPEN) == 0)		    /* drive not open */
649 	    &&(drive->state > drive_down)) {		    /* and it thinks it's not down */
650 		unlockdrive(drive);
651 		set_drive_state(driveno, drive_down, setstate_force); /* tell it what's what */
652 		continue;
653 	    }
654 	    if ((drive->state == drive_down)		    /* it's down */
655 	    &&(drive->flags & VF_OPEN)) {		    /* but open, */
656 		unlockdrive(drive);
657 		close_drive(drive);			    /* close it */
658 	    } else if (drive->state > drive_down) {
659 		getmicrotime(&drive->label.last_update);    /* time of last update is now */
660 		bcopy((char *) &drive->label,		    /* and the label info from the drive structure */
661 		    (char *) &vhdr->label,
662 		    sizeof(vhdr->label));
663 		if ((drive->state != drive_unallocated)
664 		    && (drive->state != drive_referenced)) { /* and it's a real drive */
665 		    wlabel_on = 1;			    /* enable writing the label */
666 		    error = dev_dioctl(drive->dev, /* make the label writeable */
667 			DIOCWLABEL,
668 			(caddr_t) & wlabel_on,
669 			FWRITE,
670 			proc0.p_ucred);
671 		    if (error == 0)
672 			error = write_drive(drive, (char *) vhdr, VINUMHEADERLEN, VINUM_LABEL_OFFSET);
673 		    if (error == 0)
674 			error = write_drive(drive, config, MAXCONFIG, VINUM_CONFIG_OFFSET); /* first config copy */
675 		    if (error == 0)
676 			error = write_drive(drive, config, MAXCONFIG, VINUM_CONFIG_OFFSET + MAXCONFIG);	/* second copy */
677 		    wlabel_on = 0;			    /* enable writing the label */
678 		    if (error == 0)
679 			error = dev_dioctl(drive->dev, /* make the label non-writeable again */
680 			    DIOCWLABEL,
681 			    (caddr_t) & wlabel_on,
682 			    FWRITE,
683 			    proc0.p_ucred);
684 		    unlockdrive(drive);
685 		    if (error) {
686 			log(LOG_ERR,
687 			    "vinum: Can't write config to %s, error %d\n",
688 			    drive->devicename,
689 			    error);
690 			set_drive_state(drive->driveno, drive_down, setstate_force);
691 		    } else
692 			written_config = 1;		    /* we've written it on at least one drive */
693 		}
694 	    } else					    /* not worth looking at, */
695 		unlockdrive(drive);			    /* just unlock it again */
696 	}
697     }
698     Free(vhdr);
699     Free(config);
700 }
701 
702 /*
703  * Disk labels are a mess.  The correct way to
704  * access them is with the DIOC[GSW]DINFO ioctls,
705  * but some programs, such as newfs, access the
706  * disk directly, so we have to write things
707  * there.  We do this only on request.  If a user
708  * request tries to read it directly, we fake up
709  * one on the fly.
710  */
711 
712 /*
713  * get_volume_label returns a label structure to lp, which
714  * is allocated by the caller
715  */
716 void
717 get_volume_label(char *name, int plexes, u_int64_t size, struct disklabel *lp)
718 {
719     bzero(lp, sizeof(struct disklabel));
720 
721     strncpy(lp->d_typename, "vinum", sizeof(lp->d_typename));
722     lp->d_type = DTYPE_VINUM;
723     strncpy(lp->d_packname, name, min(sizeof(lp->d_packname), sizeof(name)));
724     lp->d_rpm = 14400 * plexes;				    /* to keep them guessing */
725     lp->d_interleave = 1;
726     lp->d_flags = 0;
727 
728     /*
729      * A Vinum volume has a single track with all
730      * its sectors.
731      */
732     lp->d_secsize = DEV_BSIZE;				    /* bytes per sector */
733     lp->d_nsectors = size;				    /* data sectors per track */
734     lp->d_ntracks = 1;					    /* tracks per cylinder */
735     lp->d_ncylinders = 1;				    /* data cylinders per unit */
736     lp->d_secpercyl = size;				    /* data sectors per cylinder */
737     lp->d_secperunit = size;				    /* data sectors per unit */
738 
739     lp->d_bbsize = BBSIZE;
740     lp->d_sbsize = SBSIZE;
741 
742     lp->d_magic = DISKMAGIC;
743     lp->d_magic2 = DISKMAGIC;
744 
745     /*
746      * Set up partitions a, b and c to be identical
747      * and the size of the volume.  a is UFS, b is
748      * swap, c is nothing.
749      */
750     lp->d_partitions[0].p_size = size;
751     lp->d_partitions[0].p_fsize = 1024;
752     lp->d_partitions[0].p_fstype = FS_BSDFFS;		    /* FreeBSD File System :-) */
753     lp->d_partitions[0].p_fsize = 1024;			    /* FS fragment size */
754     lp->d_partitions[0].p_frag = 8;			    /* and fragments per block */
755     lp->d_partitions[SWAP_PART].p_size = size;
756     lp->d_partitions[SWAP_PART].p_fstype = FS_SWAP;	    /* swap partition */
757     lp->d_partitions[LABEL_PART].p_size = size;
758     lp->d_npartitions = LABEL_PART + 1;
759     strncpy(lp->d_packname, name, min(sizeof(lp->d_packname), sizeof(name)));
760     lp->d_checksum = dkcksum(lp);
761 }
762 
763 /* Write a volume label.  This implements the VINUM_LABEL ioctl. */
764 int
765 write_volume_label(int volno)
766 {
767     struct disklabel *lp;
768     struct buf *bp;
769     struct disklabel *dlp;
770     struct volume *vol;
771     int error;
772     dev_t dev;
773 
774     lp = (struct disklabel *) Malloc((sizeof(struct disklabel) + (DEV_BSIZE - 1)) & (DEV_BSIZE - 1));
775     if (lp == 0)
776 	return ENOMEM;
777 
778     if ((unsigned) (volno) >= (unsigned) vinum_conf.volumes_allocated) /* invalid volume */
779 	return ENOENT;
780 
781     vol = &VOL[volno];					    /* volume in question */
782     if (vol->state <= volume_uninit)			    /* nothing there */
783 	return ENXIO;
784     else if (vol->state < volume_up)			    /* not accessible */
785 	return EIO;					    /* I/O error */
786 
787     get_volume_label(vol->name, vol->plexes, vol->size, lp); /* get the label */
788 
789     /*
790      * Now write to disk.  This code is derived from the
791      * system writedisklabel (), which does silly things
792      * like reading the label and refusing to write
793      * unless it's already there.
794      */
795     bp = geteblk((int) lp->d_secsize);			    /* get a buffer */
796     dev = make_adhoc_dev(&vinum_ops, vol->volno);
797     bp->b_bio1.bio_offset = (off_t)LABELSECTOR * lp->d_secsize;
798     bp->b_bcount = lp->d_secsize;
799     bzero(bp->b_data, lp->d_secsize);
800     dlp = (struct disklabel *) bp->b_data;
801     *dlp = *lp;
802     bp->b_flags &= ~B_INVAL;
803     bp->b_cmd = BUF_CMD_WRITE;
804 
805     /*
806      * This should read:
807      *
808      *       vinumstrategy (bp);
809      *
810      * Negotiate with phk to get it fixed.
811      */
812     dev_dstrategy(dev, &bp->b_bio1);
813     error = biowait(bp);
814     bp->b_flags |= B_INVAL | B_AGE;
815     bp->b_flags &= ~B_ERROR;
816     brelse(bp);
817     return error;
818 }
819 
820 /* Look at all disks on the system for vinum slices */
821 int
822 vinum_scandisk(char *devicename[], int drives)
823 {
824     struct drive *volatile drive;
825     volatile int driveno;
826     int firstdrive;					    /* first drive in this list */
827     volatile int gooddrives;				    /* number of usable drives found */
828     int firsttime;					    /* set if we have never configured before */
829     int error;
830     char *config_text;					    /* read the config info from disk into here */
831     char *volatile cptr;				    /* pointer into config information */
832     char *eptr;						    /* end pointer into config information */
833     char *config_line;					    /* copy the config line to */
834     volatile int status;
835     int *volatile drivelist;				    /* list of drive indices */
836 #define DRIVENAMELEN 64
837 #define DRIVEPARTS   35					    /* max partitions per drive, excluding c */
838     char partname[DRIVENAMELEN];			    /* for creating partition names */
839 
840     status = 0;						    /* success indication */
841     vinum_conf.flags |= VF_READING_CONFIG;		    /* reading config from disk */
842 
843     gooddrives = 0;					    /* number of usable drives found */
844     firstdrive = vinum_conf.drives_used;		    /* the first drive */
845     firsttime = vinum_conf.drives_used == 0;		    /* are we a virgin? */
846 
847     /* allocate a drive pointer list */
848     drivelist = (int *) Malloc(drives * DRIVEPARTS * sizeof(int));
849     CHECKALLOC(drivelist, "Can't allocate memory");
850 
851     /* Open all drives and find which was modified most recently */
852     for (driveno = 0; driveno < drives; driveno++) {
853 	char part;					    /* UNIX partition */
854 	int slice;
855 	int founddrive;					    /* flag when we find a vinum drive */
856 	int has_slice = 0;
857 	int has_part = 0;
858 	char *tmp;
859 
860 	founddrive = 0;					    /* no vinum drive found yet on this spindle */
861 
862 	/*
863 	 * If the device path contains a slice we do not try to tack on
864 	 * another slice.  If the device path has a partition we only check
865 	 * that partition.
866 	 */
867 	if ((tmp = rindex(devicename[driveno], '/')) == NULL)
868 	    tmp = devicename[driveno];
869 	while (*tmp && (*tmp < '0' || *tmp > '9'))
870 	    ++tmp;
871 	while (*tmp && *tmp >= '0' && *tmp <= '9')
872 	    ++tmp;
873 	if (*tmp == 's')
874 	    has_slice = strtol(tmp + 1, &tmp, 0);
875 	if (*tmp >= 'a' && *tmp <= 'p')
876 	    has_part = *tmp;
877 
878 	/*
879 	 * Scan slices if no slice was specified, only if no partition was
880 	 * specified.
881 	 */
882 	if (has_slice == 0 && has_part == 0)
883 	for (slice = 1; slice < 5; slice++) {
884 	    if (has_slice && slice != has_slice)
885 		continue;
886 
887 	    for (part = 'a'; part <= 'p'; part++) {
888 		if (has_part && part != has_part)
889 		    continue;
890 		if (part == 'c')
891 		    continue;
892 		snprintf(partname, DRIVENAMELEN,
893 			"%ss%d%c", devicename[driveno], slice, part);
894 		drive = check_drive(partname);	    /* try to open it */
895 		if ((drive->lasterror != 0)		    /* didn't work, */
896 		    ||(drive->state != drive_up))
897 		    free_drive(drive);		    /* get rid of it */
898 		else if (drive->flags & VF_CONFIGURED)  /* already read this config, */
899 		    log(LOG_WARNING,
900 			"vinum: already read config from %s\n", /* say so */
901 			drive->label.name);
902 		else {
903 		    drivelist[gooddrives] = drive->driveno;	/* keep the drive index */
904 		    drive->flags &= ~VF_NEWBORN;	    /* which is no longer newly born */
905 		    gooddrives++;
906 		    founddrive++;
907 		}
908 	    }
909 	}
910 	if (founddrive == 0 && has_slice == 0) {	    /* didn't find anything, */
911 	    for (part = 'a'; part <= 'p'; part++) {	    /* try the compatibility partition */
912 		if (has_part && has_part != part)
913 		    continue;
914 		if (part == 'c')
915 		    continue;
916 		if (has_part) {
917 		    snprintf(partname, DRIVENAMELEN,
918 			    "%s", devicename[driveno]);
919 		} else {
920 		    snprintf(partname, DRIVENAMELEN,
921 			    "%s%c", devicename[driveno], part);
922 		}
923 		drive = check_drive(partname);	    /* try to open it */
924 		if ((drive->lasterror != 0)		    /* didn't work, */
925 		||(drive->state != drive_up))
926 		    free_drive(drive);		    /* get rid of it */
927 		else if (drive->flags & VF_CONFIGURED)  /* already read this config, */
928 		    log(LOG_WARNING,
929 			"vinum: already read config from %s\n", /* say so */
930 			drive->label.name);
931 		else {
932 		    drivelist[gooddrives] = drive->driveno;	/* keep the drive index */
933 		    drive->flags &= ~VF_NEWBORN;	    /* which is no longer newly born */
934 		    gooddrives++;
935 		}
936 	    }
937 	}
938     }
939 
940     if (gooddrives == 0) {
941 	if (firsttime)
942 	    log(LOG_WARNING, "vinum: no drives found\n");
943 	else
944 	    log(LOG_INFO, "vinum: no additional drives found\n");
945 	return ENOENT;
946     }
947     /*
948      * We now have at least one drive
949      * open.  Sort them in order of config time
950      * and merge the config info with what we
951      * have already.
952      */
953     qsort(drivelist, gooddrives, sizeof(int), drivecmp);
954     config_text = (char *) Malloc(MAXCONFIG * 2);	    /* allocate buffers */
955     CHECKALLOC(config_text, "Can't allocate memory");
956     config_line = (char *) Malloc(MAXCONFIGLINE * 2);	    /* allocate buffers */
957     CHECKALLOC(config_line, "Can't allocate memory");
958     for (driveno = 0; driveno < gooddrives; driveno++) {    /* now include the config */
959 	drive = &DRIVE[drivelist[driveno]];		    /* point to the drive */
960 
961 	if (firsttime && (driveno == 0))		    /* we've never configured before, */
962 	    log(LOG_INFO, "vinum: reading configuration from %s\n", drive->devicename);
963 	else
964 	    log(LOG_INFO, "vinum: updating configuration from %s\n", drive->devicename);
965 
966 	if (drive->state == drive_up)
967 	    /* Read in both copies of the configuration information */
968 	    error = read_drive(drive, config_text, MAXCONFIG * 2, VINUM_CONFIG_OFFSET);
969 	else {
970 	    error = EIO;
971 	    printf("vinum_scandisk: %s is %s\n", drive->devicename, drive_state(drive->state));
972 	}
973 
974 	if (error != 0) {
975 	    log(LOG_ERR, "vinum: Can't read device %s, error %d\n", drive->devicename, error);
976 	    free_drive(drive);				    /* give it back */
977 	    status = error;
978 	}
979 	/*
980 	 * At this point, check that the two copies
981 	 * are the same, and do something useful if
982 	 * not.  In particular, consider which is
983 	 * newer, and what this means for the
984 	 * integrity of the data on the drive.
985 	 */
986 	else {
987 	    vinum_conf.drives_used++;			    /* another drive in use */
988 	    /* Parse the configuration, and add it to the global configuration */
989 	    for (cptr = config_text; *cptr != '\0';) {	    /* love this style(9) */
990 		volatile int parse_status;		    /* return value from parse_config */
991 
992 		for (eptr = config_line; (*cptr != '\n') && (*cptr != '\0');) /* until the end of the line */
993 		    *eptr++ = *cptr++;
994 		*eptr = '\0';				    /* and delimit */
995 		if (setjmp(command_fail) == 0) {	    /* come back here on error and continue */
996 		    parse_status = parse_config(config_line, &keyword_set, 1); /* parse the config line */
997 		    if (parse_status < 0) {		    /* error in config */
998 			/*
999 			   * This config should have been parsed in user
1000 			   * space.  If we run into problems here, something
1001 			   * serious is afoot.  Complain and let the user
1002 			   * snarf the config to see what's wrong.
1003 			 */
1004 			log(LOG_ERR,
1005 			    "vinum: Config error on %s, aborting integration\n",
1006 			    drive->devicename);
1007 			free_drive(drive);		    /* give it back */
1008 			status = EINVAL;
1009 		    }
1010 		}
1011 		while (*cptr == '\n')
1012 		    cptr++;				    /* skip to next line */
1013 	    }
1014 	}
1015 	drive->flags |= VF_CONFIGURED;			    /* read this drive's configuration */
1016     }
1017 
1018     Free(config_line);
1019     Free(config_text);
1020     Free(drivelist);
1021     vinum_conf.flags &= ~VF_READING_CONFIG;		    /* no longer reading from disk */
1022     if (status != 0)
1023 	printf("vinum: couldn't read configuration");
1024     else
1025 	updateconfig(VF_READING_CONFIG);		    /* update from disk config */
1026     return status;
1027 }
1028 
1029 /*
1030  * Compare the modification dates of the drives, for qsort.
1031  * Return 1 if a < b, 0 if a == b, 01 if a > b: in other
1032  * words, sort backwards.
1033  */
1034 int
1035 drivecmp(const void *va, const void *vb)
1036 {
1037     const struct drive *a = &DRIVE[*(const int *) va];
1038     const struct drive *b = &DRIVE[*(const int *) vb];
1039 
1040     if ((a->label.last_update.tv_sec == b->label.last_update.tv_sec)
1041 	&& (a->label.last_update.tv_usec == b->label.last_update.tv_usec))
1042 	return 0;
1043     else if ((a->label.last_update.tv_sec > b->label.last_update.tv_sec)
1044 	    || ((a->label.last_update.tv_sec == b->label.last_update.tv_sec)
1045 	    && (a->label.last_update.tv_usec > b->label.last_update.tv_usec)))
1046 	return -1;
1047     else
1048 	return 1;
1049 }
1050 /* Local Variables: */
1051 /* fill-column: 50 */
1052 /* End: */
1053