xref: /dragonfly/usr.sbin/fdformat/fdformat.c (revision c9f721c2)
1 /*
2  * Copyright (C) 1992-1994,2001 by Joerg Wunsch, Dresden
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
17  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT,
18  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
19  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
20  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
22  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
23  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  *
26  * $FreeBSD: src/usr.sbin/fdformat/fdformat.c,v 1.11.2.4 2001/07/19 13:20:42 joerg Exp $
27  * $DragonFly: src/usr.sbin/fdformat/fdformat.c,v 1.4 2004/03/24 18:23:46 cpressey Exp $
28  */
29 
30 /*
31  * FreeBSD:
32  * format a floppy disk
33  *
34  * Added FD_GTYPE ioctl, verifying, proportional indicators.
35  * Serge Vakulenko, vak@zebub.msk.su
36  * Sat Dec 18 17:45:47 MSK 1993
37  *
38  * Final adaptation, change format/verify logic, add separate
39  * format gap/interleave values
40  * Andrew A. Chernov, ache@astral.msk.su
41  * Thu Jan 27 00:47:24 MSK 1994
42  */
43 
44 #include <ctype.h>
45 #include <err.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <paths.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <strings.h>
52 #include <unistd.h>
53 
54 #include <machine/ioctl_fd.h>
55 
56 static void
57 format_track(int fd, int cyl, int secs, int head, int rate,
58              int gaplen, int secsize, int fill,int interleave)
59 {
60 	struct fd_formb f;
61 	int i, j;
62 	int il[FD_MAX_NSEC + 1];
63 
64 	memset(il, 0, sizeof(il));
65 	for (j = 0, i = 1; i <= secs; i++) {
66 		while (il[(j % secs) + 1])
67 			j++;
68 		il[(j % secs) + 1] = i;
69 		j += interleave;
70 	}
71 
72 	f.format_version = FD_FORMAT_VERSION;
73 	f.head = head;
74 	f.cyl = cyl;
75 	f.transfer_rate = rate;
76 
77 	f.fd_formb_secshift = secsize;
78 	f.fd_formb_nsecs = secs;
79 	f.fd_formb_gaplen = gaplen;
80 	f.fd_formb_fillbyte = fill;
81 	for (i = 0; i < secs; i++) {
82 		f.fd_formb_cylno(i) = cyl;
83 		f.fd_formb_headno(i) = head;
84 		f.fd_formb_secno(i) = il[i+1];
85 		f.fd_formb_secsize(i) = secsize;
86 	}
87 	if (ioctl(fd, FD_FORM, (caddr_t)&f) < 0)
88 		err(1, "ioctl(FD_FORM)");
89 }
90 
91 static int
92 verify_track(int fd, int track, int tracksize)
93 {
94 	static char *buf = NULL;
95 	static int bufsz = 0;
96 	int fdopts = -1, ofdopts, rv = 0;
97 
98 	if (ioctl(fd, FD_GOPTS, &fdopts) < 0)
99 		warn("warning: ioctl(FD_GOPTS)");
100 	else {
101 		ofdopts = fdopts;
102 		fdopts |= FDOPT_NORETRY;
103 		ioctl(fd, FD_SOPTS, &fdopts);
104 	}
105 
106 	if (bufsz < tracksize) {
107 		if (buf != NULL)	/* XXX why would this ever be? */
108 			free(buf);
109 		bufsz = tracksize;
110 		buf = NULL;
111 	}
112 	if (buf == NULL)
113 		buf = malloc(bufsz);
114 	if (buf == NULL)
115 		errx(2, "out of memory");
116 	if (lseek(fd, (long)track * tracksize, 0) < 0)
117 		rv = -1;
118 	/* try twice reading it, without using the normal retrier */
119 	else if (read(fd, buf, tracksize) != tracksize
120 		 && read(fd, buf, tracksize) != tracksize)
121 		rv = -1;
122 	if(fdopts != -1)
123 		ioctl(fd, FD_SOPTS, &ofdopts);
124 	return(rv);
125 }
126 
127 static const char *
128 makename(const char *arg, const char *suffix)
129 {
130 	static char namebuff[20];	/* big enough for "/dev/fd0a"... */
131 
132 	memset(namebuff, 0, 20);
133 	if(*arg == '\0') /* ??? */
134 		return(arg);
135 	if(*arg == '/')  /* do not convert absolute pathnames */
136 		return(arg);
137 	strcpy(namebuff, _PATH_DEV);
138 	strncat(namebuff, arg, 3);
139 	strcat(namebuff, suffix);
140 	return(namebuff);
141 }
142 
143 static void
144 usage(void)
145 {
146 	fprintf(stderr, "%s\n%s\n",
147 	"usage: fdformat [-y] [-q] [-n | -v] [-f #] [-c #] [-s #] [-h #]",
148 	"                [-r #] [-g #] [-i #] [-S #] [-F #] [-t #] devname");
149 	exit(2);
150 }
151 
152 static int
153 yes(void)
154 {
155 	char reply[256], *p;
156 
157 	reply[sizeof(reply) - 1] = 0;
158 	for (;;) {
159 		fflush(stdout);
160 		if (fgets(reply, sizeof(reply) - 1, stdin) == NULL)
161 			return(0);
162 		for (p = reply; *p == ' ' || *p == '\t'; ++p)
163 			continue;
164 		if (*p == 'y' || *p == 'Y')
165 			return(1);
166 		if (*p == 'n' || *p == 'N' || *p == '\n' || *p == '\r')
167 			return(0);
168 		printf("Answer `yes' or `no': ");
169 	}
170 }
171 
172 /*
173  * Some definitions imported from /sys/isa/ic/nec765.h for convenience.
174  */
175 
176 /* Status register ST0 */
177 #define NE7_ST0_IC	0xc0	/* interrupt completion code */
178 #define NE7_ST0_IC_AT	0x40	/* abnormal termination, check error stat */
179 #define NE7_ST0_IC_RC	0xc0	/* terminated due to ready changed, n/a */
180 
181 /* Status register ST1 */
182 #define NE7_ST1_EN	0x80	/* end of cylinder, access past last record */
183 #define NE7_ST1_DE	0x20	/* data error, CRC fail in ID or data */
184 #define NE7_ST1_ND	0x04	/* no data, sector not found or CRC in ID f. */
185 #define NE7_ST1_MA	0x01	/* missing address mark (in ID or data field)*/
186 
187 /* Status register ST2 */
188 #define NE7_ST2_DD	0x20	/* data error in data field, CRC fail */
189 #define NE7_ST2_WC	0x10	/* wrong cylinder, ID field mismatches cmd */
190 #define NE7_ST2_MD	0x01	/* missing address mark in data field */
191 
192 /*
193  * Decode the FDC status pointed to by `fdcsp', and print a textual
194  * translation to stderr.
195  */
196 static void
197 printstatus(struct fdc_status *fdcsp)
198 {
199 	char msgbuf[100];
200 
201 	if ((fdcsp->status[0] & NE7_ST0_IC_RC) != NE7_ST0_IC_AT) {
202 		sprintf(msgbuf, "unexcpted interrupt code %#x",
203 			fdcsp->status[0] & NE7_ST0_IC_RC);
204 	} else {
205 		strcpy(msgbuf, "unexpected error code in ST1/ST2");
206 
207 		if (fdcsp->status[1] & NE7_ST1_EN)
208 			strcpy(msgbuf, "end of cylinder (wrong format)");
209 		else if (fdcsp->status[1] & NE7_ST1_DE) {
210 			if (fdcsp->status[2] & NE7_ST2_DD)
211 				strcpy(msgbuf, "CRC error in data field");
212 			else
213 				strcpy(msgbuf, "CRC error in ID field");
214 		} else if (fdcsp->status[1] & NE7_ST1_MA) {
215 			if (fdcsp->status[2] & NE7_ST2_MD)
216 				strcpy(msgbuf, "no address mark in data field");
217 			else
218 				strcpy(msgbuf, "no address mark in ID field");
219 		} else if (fdcsp->status[2] & NE7_ST2_WC)
220 			strcpy(msgbuf, "wrong cylinder (format mismatch)");
221 		else if (fdcsp->status[1] & NE7_ST1_ND)
222 			strcpy(msgbuf, "no data (sector not found)");
223 	}
224 	fputs(msgbuf, stderr);
225 }
226 
227 int
228 main(int argc, char **argv)
229 {
230 	int format = -1, cyls = -1, secs = -1, heads = -1, intleave = -1;
231 	int rate = -1, gaplen = -1, secsize = -1, steps = -1;
232 	int fill = 0xf6, quiet = 0, verify = 1, verify_only = 0, confirm = 0;
233 	int fd, c, i, track, error, tracks_per_dot, bytes_per_track, errs;
234 	int fdopts;
235 	const char *devname, *suffix;
236 	struct fd_type fdt;
237 #define MAXPRINTERRS 10
238 	struct fdc_status fdcs[MAXPRINTERRS];
239 
240 	while ((c = getopt(argc, argv, "f:c:s:h:r:g:S:F:t:i:qyvn")) != -1)
241 		switch (c) {
242 		case 'f':	/* format in kilobytes */
243 			format = atoi(optarg);
244 			break;
245 
246 		case 'c':	/* # of cyls */
247 			cyls = atoi(optarg);
248 			break;
249 
250 		case 's':	/* # of secs per track */
251 			secs = atoi(optarg);
252 			break;
253 
254 		case 'h':	/* # of heads */
255 			heads = atoi(optarg);
256 			break;
257 
258 		case 'r':	/* transfer rate, kilobyte/sec */
259 			rate = atoi(optarg);
260 			break;
261 
262 		case 'g':	/* length of GAP3 to format with */
263 			gaplen = atoi(optarg);
264 			break;
265 
266 		case 'S':	/* sector size shift factor (1 << S)*128 */
267 			secsize = atoi(optarg);
268 			break;
269 
270 		case 'F':	/* fill byte, C-like notation allowed */
271 			fill = (int)strtol(optarg, (char **)0, 0);
272 			break;
273 
274 		case 't':	/* steps per track */
275 			steps = atoi(optarg);
276 			break;
277 
278 		case 'i':       /* interleave factor */
279 			intleave = atoi(optarg);
280 			break;
281 
282 		case 'q':
283 			quiet = 1;
284 			break;
285 
286 		case 'y':
287 			confirm = 1;
288 			break;
289 
290 		case 'n':
291 			verify = 0;
292 			break;
293 
294 		case 'v':
295 			verify = 1;
296 			verify_only = 1;
297 			break;
298 
299 		case '?': default:
300 			usage();
301 		}
302 
303 	if (optind != argc - 1)
304 		usage();
305 
306 	switch (format) {
307 	default:
308 		errx(2, "bad floppy size: %dK", format);
309 	case -1:   suffix = "";      break;
310 	case 360:  suffix = ".360";  break;
311 	case 640:  suffix = ".640";  break;
312 	case 720:  suffix = ".720";  break;
313 	case 800:  suffix = ".800";  break;
314 	case 820:  suffix = ".820";  break;
315 	case 1200: suffix = ".1200"; break;
316 	case 1232: suffix = ".1232"; break;
317 	case 1440: suffix = ".1440"; break;
318 	case 1480: suffix = ".1480"; break;
319 	case 1720: suffix = ".1720"; break;
320 	}
321 
322 	devname = makename(argv[optind], suffix);
323 
324 	if ((fd = open(devname, O_RDWR)) < 0)
325 		err(1, "%s", devname);
326 
327 	if (ioctl(fd, FD_GTYPE, &fdt) < 0)
328 		errx(1, "not a floppy disk: %s", devname);
329 	fdopts = FDOPT_NOERRLOG;
330 	if (ioctl(fd, FD_SOPTS, &fdopts) == -1)
331 		err(1, "ioctl(FD_SOPTS, FDOPT_NOERRLOG)");
332 
333 	switch(rate) {
334 	case -1:  break;
335 	case 250: fdt.trans = FDC_250KBPS; break;
336 	case 300: fdt.trans = FDC_300KBPS; break;
337 	case 500: fdt.trans = FDC_500KBPS; break;
338 	default:
339 		errx(2, "invalid transfer rate: %d", rate);
340 	}
341 
342 	if (cyls >= 0)    fdt.tracks = cyls;
343 	if (secs >= 0)    fdt.sectrac = secs;
344 	if (fdt.sectrac > FD_MAX_NSEC)
345 		errx(2, "too many sectors per track, max value is %d", FD_MAX_NSEC);
346 	if (heads >= 0)   fdt.heads = heads;
347 	if (gaplen >= 0)  fdt.f_gap = gaplen;
348 	if (secsize >= 0) fdt.secsize = secsize;
349 	if (steps >= 0)   fdt.steptrac = steps;
350 	if (intleave >= 0) fdt.f_inter = intleave;
351 
352 	bytes_per_track = fdt.sectrac * (1 << fdt.secsize) * 128;
353 
354 	/* XXX  20/40 = 0.5 */
355 	tracks_per_dot = (fdt.tracks * fdt.heads + 20) / 40;
356 
357 	if (verify_only) {
358 		if (!quiet)
359 			printf("Verify %dK floppy `%s'.\n",
360 				fdt.tracks * fdt.heads * bytes_per_track / 1024,
361 				devname);
362 	}
363 	else if (!quiet && !confirm) {
364 		printf("Format %dK floppy `%s'? (y/n): ",
365 			fdt.tracks * fdt.heads * bytes_per_track / 1024,
366 			devname);
367 		if (!yes()) {
368 			printf("Not confirmed.\n");
369 			return(3);
370 		}
371 	}
372 
373 	/*
374 	 * Formatting.
375 	 */
376 	if (!quiet) {
377 		int i;
378 
379 		printf("Processing ");
380 		for (i = 0; i < (fdt.tracks * fdt.heads) / tracks_per_dot; i++)
381 			putchar('-');
382 		printf("\rProcessing ");
383 		fflush(stdout);
384 	}
385 
386 	error = errs = 0;
387 
388 	for (track = 0; track < fdt.tracks * fdt.heads; track++) {
389 		if (!verify_only) {
390 			format_track(fd, track / fdt.heads, fdt.sectrac,
391 				track % fdt.heads, fdt.trans, fdt.f_gap,
392 				fdt.secsize, fill, fdt.f_inter);
393 			if(!quiet && !((track + 1) % tracks_per_dot)) {
394 				putchar('F');
395 				fflush(stdout);
396 			}
397 		}
398 		if (verify) {
399 			if (verify_track(fd, track, bytes_per_track) < 0) {
400 				error = 1;
401 				if (errs < MAXPRINTERRS && errno == EIO) {
402 					if (ioctl(fd, FD_GSTAT, fdcs + errs) ==
403 					    -1)
404 						errx(1,
405 					"floppy IO error, but no FDC status");
406 					errs++;
407 				}
408 			}
409 			if(!quiet && !((track + 1) % tracks_per_dot)) {
410 				if (!verify_only)
411 					putchar('\b');
412 				if (error) {
413 					putchar('E');
414 					error = 0;
415 				}
416 				else
417 					putchar('V');
418 				fflush(stdout);
419 			}
420 		}
421 	}
422 	if (!quiet)
423 		printf(" done.\n");
424 
425 	if (!quiet && errs) {
426 		fflush(stdout);
427 		fprintf(stderr, "Errors encountered:\nCyl Head Sect   Error\n");
428 		for (i = 0; i < errs && i < MAXPRINTERRS; i++) {
429 			fprintf(stderr, " %2d   %2d   %2d   ",
430 				fdcs[i].status[3], fdcs[i].status[4],
431 				fdcs[i].status[5]);
432 			printstatus(fdcs + i);
433 			putc('\n', stderr);
434 		}
435 		if (errs >= MAXPRINTERRS)
436 			fprintf(stderr, "(Further errors not printed.)\n");
437 	}
438 
439 	return(errs != 0);
440 }
441 /*
442  * Local Variables:
443  *  c-indent-level:               8
444  *  c-continued-statement-offset: 8
445  *  c-continued-brace-offset:     0
446  *  c-brace-offset:              -8
447  *  c-brace-imaginary-offset:     0
448  *  c-argdecl-indent:             8
449  *  c-label-offset:              -8
450  *  c++-hanging-braces:           1
451  *  c++-access-specifier-offset: -8
452  *  c++-empty-arglist-indent:     8
453  *  c++-friend-offset:            0
454  * End:
455  */
456