1 /*	$OpenBSD: rf_configure.c,v 1.12 2004/07/17 02:14:33 deraadt Exp $	*/
2 /*	$NetBSD: rf_configure.c,v 1.14 2001/02/04 21:05:42 christos Exp $	*/
3 
4 /*
5  * Copyright © 2013
6  *	Thorsten “mirabilos” Glaser <tg@mirbsd.org>
7  * Copyright (c) 1995 Carnegie-Mellon University.
8  * All rights reserved.
9  *
10  * Author: Mark Holland
11  *
12  * Permission to use, copy, modify and distribute this software and
13  * its documentation is hereby granted, provided that both the copyright
14  * notice and this permission notice appear in all copies of the
15  * software, derivative works or modified versions, and any portions
16  * thereof, and that both notices appear in supporting documentation.
17  *
18  * CARNEGIE MELLON ALLOWS FREE USE OF THIS SOFTWARE IN ITS "AS IS"
19  * CONDITION.  CARNEGIE MELLON DISCLAIMS ANY LIABILITY OF ANY KIND
20  * FOR ANY DAMAGES WHATSOEVER RESULTING FROM THE USE OF THIS SOFTWARE.
21  *
22  * Carnegie Mellon requests users of this software to return to
23  *
24  *  Software Distribution Coordinator  or  Software.Distribution@CS.CMU.EDU
25  *  School of Computer Science
26  *  Carnegie Mellon University
27  *  Pittsburgh PA 15213-3890
28  *
29  * any improvements or extensions that they make and grant Carnegie the
30  * rights to redistribute these changes.
31  */
32 
33 /***************************************************************
34  *
35  * rf_configure.c -- code related to configuring the RAIDframe system
36  *
37  * configuration is complicated by the fact that we want the same
38  * driver to work both in the kernel and at user level.  In the
39  * kernel, we can't read the configuration file, so we configure
40  * by running a user-level program that reads the config file,
41  * creates a data structure describing the configuration and
42  * passes it into the kernel via an ioctl.  Since we want the config
43  * code to be common between the two versions of the driver, we
44  * configure using the same two-step process when running at
45  * user level.  Of course, at user level, the config structure is
46  * passed directly to the config routine, rather than via ioctl.
47  *
48  * This file is not compiled into the kernel, so we have no
49  * need for KERNEL ifdefs.
50  *
51  **************************************************************/
52 
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <errno.h>
56 #include <strings.h>
57 #include <sys/types.h>
58 #include <sys/stat.h>
59 #include "rf_raid.h"
60 #include "rf_raidframe.h"
61 #include "rf_general.h"
62 #include "rf_decluster.h"
63 #include "rf_configure.h"
64 
65 __RCSID("$MirOS: src/sbin/raidctl/rf_configure.c,v 1.4 2013/10/31 20:06:45 tg Exp $");
66 
67 /* so much for #include <ansidecl.h> */
68 #ifdef __GNUCC__
69 #define	ATTRIBUTE_UNUSED	__attribute__((__unused__))
70 #else
71 #define	ATTRIBUTE_UNUSED
72 #endif
73 
74 /*
75  * XXX we include this here so we don't need to drag rf_debugMem.c into
76  * the picture...  This is userland, afterall...
77  */
78 
79 /*
80  * XXX sucky hack to override the defn. of RF_Malloc as given in
81  * rf_debugMem.c...  but I *really* don't want (nor need) to link with
82  * that file here in userland..  GO
83 */
84 
85 #undef RF_Malloc
86 #define RF_Malloc(_p_, _size_, _cast_) \
87   { \
88      _p_ = _cast_ malloc((u_long)_size_); \
89      bzero((char *)_p_, _size_); \
90   }
91 
92 int     distSpareYes = 1;
93 int     distSpareNo = 0;
94 
95 /* The mapsw[] table below contains all the various RAID types that might
96    be supported by the kernel.  The actual supported types are found
97    in sys/dev/raidframe/rf_layout.c. */
98 
99 static RF_LayoutSW_t mapsw[] = {
100 	/* parity declustering */
101 	{'T', "Parity declustering",
102 	 rf_MakeLayoutSpecificDeclustered, &distSpareNo},
103 	/* parity declustering with distributed sparing */
104 	{'D', "Distributed sparing parity declustering",
105 	 rf_MakeLayoutSpecificDeclustered, &distSpareYes},
106 	/* declustered P+Q */
107 	{'Q', "Declustered P+Q",
108 	 rf_MakeLayoutSpecificDeclustered, &distSpareNo},
109 	/* RAID 5 with rotated sparing */
110 	{'R', "RAID Level 5 rotated sparing", rf_MakeLayoutSpecificNULL, NULL},
111 	/* Chained Declustering */
112 	{'C', "Chained Declustering", rf_MakeLayoutSpecificNULL, NULL},
113 	/* Interleaved Declustering */
114 	{'I', "Interleaved Declustering", rf_MakeLayoutSpecificNULL, NULL},
115 	/* RAID level 0 */
116 	{'0', "RAID Level 0", rf_MakeLayoutSpecificNULL, NULL},
117 	/* RAID level 1 */
118 	{'1', "RAID Level 1", rf_MakeLayoutSpecificNULL, NULL},
119 	/* RAID level 4 */
120 	{'4', "RAID Level 4", rf_MakeLayoutSpecificNULL, NULL},
121 	/* RAID level 5 */
122 	{'5', "RAID Level 5", rf_MakeLayoutSpecificNULL, NULL},
123 	/* Evenodd */
124 	{'E', "EvenOdd", rf_MakeLayoutSpecificNULL, NULL},
125 	/* Declustered Evenodd */
126 	{'e', "Declustered EvenOdd",
127 	 rf_MakeLayoutSpecificDeclustered, &distSpareNo},
128 	/* parity logging */
129 	{'L', "Parity logging", rf_MakeLayoutSpecificNULL, NULL},
130 	/* end-of-list marker */
131 	{'\0', NULL, NULL, NULL}
132 };
133 RF_LayoutSW_t *
rf_GetLayout(RF_ParityConfig_t parityConfig)134 rf_GetLayout(RF_ParityConfig_t parityConfig)
135 {
136 	RF_LayoutSW_t *p;
137 
138 	/* look up the specific layout */
139 	for (p = &mapsw[0]; p->parityConfig; p++)
140 		if (p->parityConfig == parityConfig)
141 			break;
142 	if (!p->parityConfig)
143 		return (NULL);
144 	RF_ASSERT(p->parityConfig == parityConfig);
145 	return (p);
146 }
147 
148 int rf_search_file_for_start_of(const char *string, char *buf,
149     int len, FILE * fp);
150 int rf_get_next_nonblank_line(char *buf, int len, FILE *fp,
151     const char *errmsg);
152 
153 /*
154  * called from user level to read the configuration file and create
155  * a configuration control structure.  This is used in the user-level
156  * version of the driver, and in the user-level program that configures
157  * the system via ioctl.
158  */
159 int
rf_MakeConfig(char * configname,RF_Config_t * cfgPtr)160 rf_MakeConfig(char *configname, RF_Config_t *cfgPtr)
161 {
162   int numscanned, val, r, c, retcode, aa, bb, cc;
163   char buf[256], buf1[256], *cp;
164   RF_LayoutSW_t *lp;
165   FILE *fp;
166 
167   bzero((char *)cfgPtr, sizeof(RF_Config_t));
168 
169   fp = fopen(configname, "r");
170   if (!fp) {
171     RF_ERRORMSG1("Can't open config file %s\n",configname);
172     return(-1);
173   }
174   rewind(fp);
175   if (rf_search_file_for_start_of("array", buf, 256, fp)) {
176     RF_ERRORMSG1("Unable to find start of \"array\" params in config file %s\n",configname);
177 		retcode = -1;
178 		goto out;
179   }
180   rf_get_next_nonblank_line(buf, 256, fp, "Config file error (\"array\" section):  unable to get numRow and numCol\n");
181 
182   /*
183          * wackiness with aa, bb, cc to get around size problems on
184          * different platforms
185    */
186   numscanned = sscanf(buf,"%d %d %d", &aa, &bb, &cc);
187   if (numscanned != 3) {
188     RF_ERRORMSG("Config file error (\"array\" section):  unable to get numRow, numCol, numSpare\n");
189 		retcode = -1;
190 		goto out;
191   }
192   cfgPtr->numRow = (RF_RowCol_t)aa;
193   cfgPtr->numCol = (RF_RowCol_t)bb;
194   cfgPtr->numSpare = (RF_RowCol_t)cc;
195 
196   /* debug section is optional */
197   for (c=0; c<RF_MAXDBGV; c++)
198     cfgPtr->debugVars[c][0] = '\0';
199   rewind(fp);
200   if (!rf_search_file_for_start_of("debug", buf, 256, fp)) {
201     for (c=0; c < RF_MAXDBGV; c++) {
202 			if (rf_get_next_nonblank_line(buf, 256, fp, NULL))
203 				break;
204       cp = rf_find_non_white(buf);
205 			if (!strncmp(cp, "START", strlen("START")))
206 				break;
207       strlcpy(&cfgPtr->debugVars[c][0], cp, RF_MAXDBGVLEN);
208     }
209   }
210   rewind(fp);
211   strlcpy(cfgPtr->diskQueueType,"fifo", sizeof(RF_DiskQueueType_t));
212   cfgPtr->maxOutstandingDiskReqs = 1;
213   /* scan the file for the block related to disk queues */
214   if (rf_search_file_for_start_of("queue",buf,256,fp)) {
215     RF_ERRORMSG2("[No disk queue discipline specified in config file %s.  Using %s.]\n",configname, cfgPtr->diskQueueType);
216   } else {
217     if (rf_get_next_nonblank_line(buf, 256, fp, NULL)) {
218       RF_ERRORMSG2("[No disk queue discipline specified in config file %s.  Using %s.]\n",configname, cfgPtr->diskQueueType);
219     }
220   }
221 
222 	/* the queue specifier line contains two entries: 1st char of first
223 	 * word specifies queue to be used 2nd word specifies max num reqs
224 	 * that can be outstanding on the disk itself (typically 1) */
225   if (sscanf(buf,"%s %d",buf1,&val)!=2) {
226     RF_ERRORMSG1("Can't determine queue type and/or max outstanding reqs from line: %s",buf);
227     RF_ERRORMSG2("Using %s-%d\n", cfgPtr->diskQueueType, cfgPtr->maxOutstandingDiskReqs);
228   } else {
229 		char *ch;
230 		memmove(cfgPtr->diskQueueType, buf1,
231 		    RF_MIN(sizeof(cfgPtr->diskQueueType), strlen(buf1) + 1));
232 		for (ch = buf1; *ch; ch++) {
233 			if (*ch == ' ') {
234 				*ch = '\0';
235         break;
236       }
237     }
238     cfgPtr->maxOutstandingDiskReqs = val;
239   }
240 
241   rewind(fp);
242 
243   if (rf_search_file_for_start_of("disks",buf,256,fp)) {
244     RF_ERRORMSG1("Can't find \"disks\" section in config file %s\n",configname);
245 		retcode = -1;
246 		goto out;
247   }
248   for (r=0; r<cfgPtr->numRow; r++) {
249     for (c=0; c<cfgPtr->numCol; c++) {
250 			if (rf_get_next_nonblank_line(
251 			    &cfgPtr->devnames[r][c][0], 50, fp, NULL)) {
252 	RF_ERRORMSG2("Config file error: unable to get device file for disk at row %d col %d\n",r,c);
253 				retcode = -1;
254 				goto out;
255       }
256     }
257   }
258 
259   /* "spare" section is optional */
260   rewind(fp);
261 	if (rf_search_file_for_start_of("spare", buf, 256, fp))
262 		cfgPtr->numSpare = 0;
263   for (c = 0; c < cfgPtr->numSpare; c++) {
264 		if (rf_get_next_nonblank_line(&cfgPtr->spare_names[c][0],
265 		    256, fp, NULL)) {
266       RF_ERRORMSG1("Config file error: unable to get device file for spare disk %d\n",c);
267 			retcode = -1;
268 			goto out;
269     }
270   }
271 
272   /* scan the file for the block related to layout */
273   rewind(fp);
274   if (rf_search_file_for_start_of("layout",buf,256,fp)) {
275     RF_ERRORMSG1("Can't find \"layout\" section in configuration file %s\n",configname);
276 		retcode = -1;
277 		goto out;
278   }
279   if (rf_get_next_nonblank_line(buf, 256, fp, NULL)) {
280     RF_ERRORMSG("Config file error (\"layout\" section): unable to find common layout param line\n");
281 		retcode = -1;
282 		goto out;
283   }
284   c = sscanf(buf,"%d %d %d %c", &aa, &bb, &cc, &cfgPtr->parityConfig);
285   cfgPtr->sectPerSU = (RF_SectorNum_t)aa;
286   cfgPtr->SUsPerPU = (RF_StripeNum_t)bb;
287   cfgPtr->SUsPerRU = (RF_StripeNum_t)cc;
288   if (c != 4) {
289     RF_ERRORMSG("Unable to scan common layout line\n");
290 		retcode = -1;
291 		goto out;
292   }
293   lp = rf_GetLayout(cfgPtr->parityConfig);
294   if (lp == NULL) {
295 		RF_ERRORMSG1("Unknown parity config '%c'\n",
296 		    cfgPtr->parityConfig);
297     retcode = -1;
298     goto out;
299   }
300 
301   retcode = lp->MakeLayoutSpecific(fp, cfgPtr, lp->makeLayoutSpecificArg);
302 out:
303   fclose(fp);
304   if (retcode < 0)
305     retcode = errno = EINVAL;
306   else
307     errno = retcode;
308   return(retcode);
309 }
310 
311 
312 /* used in architectures such as RAID0 where there is no layout-specific
313  * information to be passed into the configuration code.
314  */
315 int
rf_MakeLayoutSpecificNULL(FILE * fp ATTRIBUTE_UNUSED,RF_Config_t * cfgPtr,void * ignored ATTRIBUTE_UNUSED)316 rf_MakeLayoutSpecificNULL(FILE *fp ATTRIBUTE_UNUSED, RF_Config_t *cfgPtr,
317 			  void *ignored ATTRIBUTE_UNUSED)
318 {
319   cfgPtr->layoutSpecificSize = 0;
320   cfgPtr->layoutSpecific     = NULL;
321   return(0);
322 }
323 
324 int
rf_MakeLayoutSpecificDeclustered(FILE * configfp,RF_Config_t * cfgPtr,void * arg)325 rf_MakeLayoutSpecificDeclustered(FILE *configfp, RF_Config_t *cfgPtr, void *arg)
326 {
327   int b, v, k, r, lambda, norotate, i, val, distSpare;
328   char *cfgBuf, *bdfile, *p, *smname;
329   char buf[256], smbuf[256];
330   FILE *fp;
331 
332   distSpare = *((int *)arg);
333 
334   /* get the block design file name */
335 	if (rf_get_next_nonblank_line(buf, 256, configfp,
336 	    "Can't find block design file name in config file\n"))
337     return(EINVAL);
338   bdfile = rf_find_non_white(buf);
339   if (bdfile[strlen(bdfile)-1] == '\n') {
340     /* strip newline char */
341     bdfile[strlen(bdfile)-1] = '\0';
342   }
343   /* open bd file, check validity of configuration */
344   if ((fp = fopen(bdfile,"r"))==NULL) {
345     RF_ERRORMSG1("RAID: config error: Can't open layout table file %s\n",bdfile);
346     return(EINVAL);
347   }
348 	if (fgets(buf, 256, fp) == NULL) {
349 		RF_ERRORMSG1("RAID: config error: Can't read layout from layout table file %s\n", bdfile);
350 		return (EINVAL);
351 	}
352   i = sscanf(buf,"%u %u %u %u %u %u",&b,&v,&k,&r,&lambda,&norotate);
353   if (i == 5)
354     norotate = 0; /* no-rotate flag is optional */
355   else if (i != 6) {
356     RF_ERRORMSG("Unable to parse header line in block design file\n");
357     return(EINVAL);
358   }
359 	/* set the sparemap directory.  In the in-kernel version, there's a
360 	 * daemon that's responsible for finding the sparemaps */
361   if (distSpare) {
362 		if (rf_get_next_nonblank_line(smbuf, 256, configfp,
363 		    "Can't find sparemap file name in config file\n"))
364       return(EINVAL);
365     smname = rf_find_non_white(smbuf);
366     if (smname[strlen(smname)-1] == '\n') {
367       /* strip newline char */
368       smname[strlen(smname)-1] = '\0';
369     }
370 	} else {
371     smbuf[0] = '\0';
372     smname = smbuf;
373   }
374 
375   /* allocate a buffer to hold the configuration info */
376 	cfgPtr->layoutSpecificSize = RF_SPAREMAP_NAME_LEN +
377 	    6 * sizeof(int) + b * k;
378   /* can't use RF_Malloc here b/c debugMem module not yet init'd */
379   cfgBuf = (char *) malloc(cfgPtr->layoutSpecificSize);
380   cfgPtr->layoutSpecific = (void *) cfgBuf;
381   p = cfgBuf;
382 
383   /* install name of sparemap file */
384   for (i=0; smname[i]; i++)
385     *p++ = smname[i];
386   /* pad with zeros */
387   while (i<RF_SPAREMAP_NAME_LEN) {
388     *p++ = '\0';
389     i++;
390   }
391 
392   /*
393    * fill in the buffer with the block design parameters
394    * and then the block design itself
395    */
396 	*((int *) p) = b;
397 	p += sizeof(int);
398 	*((int *) p) = v;
399 	p += sizeof(int);
400 	*((int *) p) = k;
401 	p += sizeof(int);
402 	*((int *) p) = r;
403 	p += sizeof(int);
404 	*((int *) p) = lambda;
405 	p += sizeof(int);
406 	*((int *) p) = norotate;
407 	p += sizeof(int);
408 
409   while (fscanf(fp,"%d",&val) == 1)
410     *p++ = (char) val;
411   fclose(fp);
412   if ((unsigned int)(p - cfgBuf) != cfgPtr->layoutSpecificSize) {
413       RF_ERRORMSG2("Size mismatch creating layout specific data: is %d sb %d bytes\n",(int)(p-cfgBuf),(int)(6*sizeof(int)+b*k));
414       return(EINVAL);
415   }
416   return(0);
417 }
418 
419 /****************************************************************************
420  *
421  * utilities
422  *
423  ***************************************************************************/
424 
425 /* finds a non-white character in the line */
426 char   *
rf_find_non_white(char * p)427 rf_find_non_white(char *p)
428 {
429 	for (; *p != '\0' && (*p == ' ' || *p == '\t'); p++);
430 	return (p);
431 }
432 
433 /* finds a white character in the line */
434 char   *
rf_find_white(char * p)435 rf_find_white(char *p)
436 {
437 	for (; *p != '\0' && (*p != ' ' && *p != '\t'); p++);
438 	return (p);
439 }
440 
441 /*
442  * searches a file for a line that says "START string", where string is
443  * specified as a parameter
444  */
445 int
rf_search_file_for_start_of(const char * string,char * buf,int len,FILE * fp)446 rf_search_file_for_start_of(const char *string, char *buf, int len, FILE *fp)
447 {
448   char *p;
449 
450   while (1) {
451 		if (fgets(buf, len, fp) == NULL)
452 			return (-1);
453     p = rf_find_non_white(buf);
454     if (!strncmp(p, "START", strlen("START"))) {
455       p = rf_find_white(p);
456       p = rf_find_non_white(p);
457 			if (!strncmp(p, string, strlen(string)))
458 				return (0);
459     }
460   }
461 }
462 
463 /* reads from file fp into buf until it finds an interesting line */
464 int
rf_get_next_nonblank_line(char * buf,int len ATTRIBUTE_UNUSED,FILE * fp,const char * errmsg)465 rf_get_next_nonblank_line(char *buf, int len ATTRIBUTE_UNUSED, FILE *fp,
466 			  const char *errmsg)
467 {
468   char *p;
469 
470   while (fgets(buf,256,fp) != NULL) {
471     p = rf_find_non_white(buf);
472 		if (*p == '\n' || *p == '\0' || *p == '#')
473 			continue;
474     return(0);
475   }
476 	if (errmsg)
477 		RF_ERRORMSG1("%s", errmsg);
478   return(1);
479 }
480 
481 /*
482  * Allocates an array for the spare table, and initializes it from a file.
483  * In the user-level version, this is called when recon is initiated.
484  * When/if I move recon into the kernel, there'll be a daemon that does
485  * an ioctl into RAIDframe which will block until a spare table is needed.
486  * When it returns, it will read a spare table from the file system,
487  * pass it into the kernel via a different ioctl, and then block again
488  * on the original ioctl.
489  *
490  * This is specific to the declustered layout, but doesn't belong in
491  * rf_decluster.c because it uses stuff that can't be compiled into
492  * the kernel, and it needs to be compiled into the user-level sparemap daemon.
493  *
494  */
495 void *
rf_ReadSpareTable(RF_SparetWait_t * req,char * fname)496 rf_ReadSpareTable(RF_SparetWait_t *req, char *fname)
497 {
498 	int i, j, numFound, linecount, tableNum, tupleNum,
499 	    spareDisk, spareBlkOffset;
500   char buf[1024], targString[100], errString[100];
501   RF_SpareTableEntry_t **table;
502   FILE *fp;
503 
504   /* allocate and initialize the table */
505 	RF_Malloc(table,
506 	    req->TablesPerSpareRegion * sizeof(RF_SpareTableEntry_t *),
507 	    (RF_SpareTableEntry_t **));
508   for (i=0; i<req->TablesPerSpareRegion; i++) {
509 		RF_Malloc(table[i],
510 		    req->BlocksPerTable * sizeof(RF_SpareTableEntry_t),
511 		    (RF_SpareTableEntry_t *));
512 		for (j = 0; j < req->BlocksPerTable; j++)
513 			table[i][j].spareDisk =
514 			    table[i][j].spareBlockOffsetInSUs = -1;
515   }
516 
517   /* 2.  open sparemap file, sanity check */
518   if ((fp = fopen(fname,"r"))==NULL) {
519 		fprintf(stderr,
520 		    "rf_ReadSpareTable:  Can't open sparemap file %s\n", fname);
521 		return (NULL);
522   }
523 	if (rf_get_next_nonblank_line(buf, 1024, fp,
524 	    "Invalid sparemap file:  can't find header line\n"))
525     return(NULL);
526   if (buf[strlen(buf)-1] == '\n')
527     buf[strlen(buf)-1] = '\0';
528 
529 	snprintf(targString, sizeof targString, "fdisk %d\n", req->fcol);
530 	snprintf(errString, sizeof errString,
531 	    "Invalid sparemap file:  can't find \"fdisk %d\" line\n",
532 	    req->fcol);
533   while (1) {
534     rf_get_next_nonblank_line(buf,1024,fp,errString);
535 		if (!strncmp(buf, targString, strlen(targString)))
536 			break;
537   }
538 
539   /* no more blank lines or comments allowed now */
540   linecount = req->TablesPerSpareRegion * req->TableDepthInPUs;
541   for (i=0; i<linecount; i++) {
542 		numFound = fscanf(fp, " %d %d %d %d", &tableNum, &tupleNum,
543 		    &spareDisk, &spareBlkOffset);
544     if (numFound != 4) {
545 			fprintf(stderr, "Sparemap file prematurely exhausted after %d of %d lines\n", i, linecount);
546 			return (NULL);
547     }
548 		RF_ASSERT(tableNum >= 0 &&
549 		    tableNum < req->TablesPerSpareRegion);
550     RF_ASSERT(tupleNum >= 0 && tupleNum < req->BlocksPerTable);
551     RF_ASSERT(spareDisk >= 0 && spareDisk < req->C);
552 		RF_ASSERT(spareBlkOffset >= 0 && spareBlkOffset <
553 		    req->SpareSpaceDepthPerRegionInSUs / req->SUsPerPU);
554 
555     table[tableNum][tupleNum].spareDisk = spareDisk;
556 		table[tableNum][tupleNum].spareBlockOffsetInSUs =
557 		    spareBlkOffset * req->SUsPerPU;
558   }
559 
560   fclose(fp);
561   return((void *) table);
562 }
563