xref: /dragonfly/usr.sbin/fdformat/fdformat.c (revision 4e7eb5cc)
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.3 2003/11/16 14:10:45 eirikn 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 	register 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]) j++;
67 	    il[(j%secs)+1] = i;
68 	    j += interleave;
69 	}
70 
71 	f.format_version = FD_FORMAT_VERSION;
72 	f.head = head;
73 	f.cyl = cyl;
74 	f.transfer_rate = rate;
75 
76 	f.fd_formb_secshift = secsize;
77 	f.fd_formb_nsecs = secs;
78 	f.fd_formb_gaplen = gaplen;
79 	f.fd_formb_fillbyte = fill;
80 	for(i = 0; i < secs; i++) {
81 		f.fd_formb_cylno(i) = cyl;
82 		f.fd_formb_headno(i) = head;
83 		f.fd_formb_secno(i) = il[i+1];
84 		f.fd_formb_secsize(i) = secsize;
85 	}
86 	if(ioctl(fd, FD_FORM, (caddr_t)&f) < 0)
87 		err(1, "ioctl(FD_FORM)");
88 }
89 
90 static int
91 verify_track(int fd, int track, int tracksize)
92 {
93 	static char *buf = 0;
94 	static int bufsz = 0;
95 	int fdopts = -1, ofdopts, rv = 0;
96 
97 	if (ioctl(fd, FD_GOPTS, &fdopts) < 0)
98 		warn("warning: ioctl(FD_GOPTS)");
99 	else {
100 		ofdopts = fdopts;
101 		fdopts |= FDOPT_NORETRY;
102 		(void)ioctl(fd, FD_SOPTS, &fdopts);
103 	}
104 
105 	if (bufsz < tracksize) {
106 		if (buf)
107 			free (buf);
108 		bufsz = tracksize;
109 		buf = 0;
110 	}
111 	if (! buf)
112 		buf = malloc (bufsz);
113 	if (! buf)
114 		errx(2, "out of memory");
115 	if (lseek (fd, (long) track*tracksize, 0) < 0)
116 		rv = -1;
117 	/* try twice reading it, without using the normal retrier */
118 	else if (read (fd, buf, tracksize) != tracksize
119 		 && read (fd, buf, tracksize) != tracksize)
120 		rv = -1;
121 	if(fdopts != -1)
122 		(void)ioctl(fd, FD_SOPTS, &ofdopts);
123 	return (rv);
124 }
125 
126 static const char *
127 makename(const char *arg, const char *suffix)
128 {
129 	static char namebuff[20];	/* big enough for "/dev/fd0a"... */
130 
131 	memset(namebuff, 0, 20);
132 	if(*arg == '\0') /* ??? */
133 		return arg;
134 	if(*arg == '/')  /* do not convert absolute pathnames */
135 		return arg;
136 	strcpy(namebuff, _PATH_DEV);
137 	strncat(namebuff, arg, 3);
138 	strcat(namebuff, suffix);
139 	return namebuff;
140 }
141 
142 static void
143 usage (void)
144 {
145 	fprintf(stderr, "%s\n%s\n",
146 	"usage: fdformat [-y] [-q] [-n | -v] [-f #] [-c #] [-s #] [-h #]",
147 	"                [-r #] [-g #] [-i #] [-S #] [-F #] [-t #] devname");
148 	exit(2);
149 }
150 
151 static int
152 yes (void)
153 {
154 	char reply [256], *p;
155 
156 	reply[sizeof(reply)-1] = 0;
157 	for (;;) {
158 		fflush(stdout);
159 		if (! fgets (reply, sizeof(reply)-1, stdin))
160 			return (0);
161 		for (p=reply; *p==' ' || *p=='\t'; ++p)
162 			continue;
163 		if (*p=='y' || *p=='Y')
164 			return (1);
165 		if (*p=='n' || *p=='N' || *p=='\n' || *p=='\r')
166 			return (0);
167 		printf("Answer `yes' or `no': ");
168 	}
169 }
170 
171 /*
172  * Some definitions imported from /sys/isa/ic/nec765.h for convenience.
173  */
174 
175 /* Status register ST0 */
176 #define NE7_ST0_IC	0xc0	/* interrupt completion code */
177 #define NE7_ST0_IC_AT	0x40	/* abnormal termination, check error stat */
178 #define NE7_ST0_IC_RC	0xc0	/* terminated due to ready changed, n/a */
179 
180 /* Status register ST1 */
181 #define NE7_ST1_EN	0x80	/* end of cylinder, access past last record */
182 #define NE7_ST1_DE	0x20	/* data error, CRC fail in ID or data */
183 #define NE7_ST1_ND	0x04	/* no data, sector not found or CRC in ID f. */
184 #define NE7_ST1_MA	0x01	/* missing address mark (in ID or data field)*/
185 
186 /* Status register ST2 */
187 #define NE7_ST2_DD	0x20	/* data error in data field, CRC fail */
188 #define NE7_ST2_WC	0x10	/* wrong cylinder, ID field mismatches cmd */
189 #define NE7_ST2_MD	0x01	/* missing address mark in data field */
190 
191 /*
192  * Decode the FDC status pointed to by `fdcsp', and print a textual
193  * translation to stderr.
194  */
195 static void
196 printstatus(struct fdc_status *fdcsp)
197 {
198 	char msgbuf[100];
199 
200 	if ((fdcsp->status[0] & NE7_ST0_IC_RC) != NE7_ST0_IC_AT) {
201 		sprintf(msgbuf, "unexcpted interrupt code %#x",
202 			fdcsp->status[0] & NE7_ST0_IC_RC);
203 	} else {
204 		strcpy(msgbuf, "unexpected error code in ST1/ST2");
205 
206 		if (fdcsp->status[1] & NE7_ST1_EN)
207 			strcpy(msgbuf, "end of cylinder (wrong format)");
208 		else if (fdcsp->status[1] & NE7_ST1_DE) {
209 			if (fdcsp->status[2] & NE7_ST2_DD)
210 				strcpy(msgbuf, "CRC error in data field");
211 			else
212 				strcpy(msgbuf, "CRC error in ID field");
213 		} else if (fdcsp->status[1] & NE7_ST1_MA) {
214 			if (fdcsp->status[2] & NE7_ST2_MD)
215 				strcpy(msgbuf, "no address mark in data field");
216 			else
217 				strcpy(msgbuf, "no address mark in ID field");
218 		} else if (fdcsp->status[2] & NE7_ST2_WC)
219 			strcpy(msgbuf, "wrong cylinder (format mismatch)");
220 		else if (fdcsp->status[1] & NE7_ST1_ND)
221 			strcpy(msgbuf, "no data (sector not found)");
222 	}
223 	fputs(msgbuf, stderr);
224 }
225 
226 int
227 main(int argc, char **argv)
228 {
229 	int format = -1, cyls = -1, secs = -1, heads = -1, intleave = -1;
230 	int rate = -1, gaplen = -1, secsize = -1, steps = -1;
231 	int fill = 0xf6, quiet = 0, verify = 1, verify_only = 0, confirm = 0;
232 	int fd, c, i, track, error, tracks_per_dot, bytes_per_track, errs;
233 	int fdopts;
234 	const char *devname, *suffix;
235 	struct fd_type fdt;
236 #define MAXPRINTERRS 10
237 	struct fdc_status fdcs[MAXPRINTERRS];
238 
239 	while((c = getopt(argc, argv, "f:c:s:h:r:g:S:F:t:i:qyvn")) != -1)
240 		switch(c) {
241 		case 'f':	/* format in kilobytes */
242 			format = atoi(optarg);
243 			break;
244 
245 		case 'c':	/* # of cyls */
246 			cyls = atoi(optarg);
247 			break;
248 
249 		case 's':	/* # of secs per track */
250 			secs = atoi(optarg);
251 			break;
252 
253 		case 'h':	/* # of heads */
254 			heads = atoi(optarg);
255 			break;
256 
257 		case 'r':	/* transfer rate, kilobyte/sec */
258 			rate = atoi(optarg);
259 			break;
260 
261 		case 'g':	/* length of GAP3 to format with */
262 			gaplen = atoi(optarg);
263 			break;
264 
265 		case 'S':	/* sector size shift factor (1 << S)*128 */
266 			secsize = atoi(optarg);
267 			break;
268 
269 		case 'F':	/* fill byte, C-like notation allowed */
270 			fill = (int)strtol(optarg, (char **)0, 0);
271 			break;
272 
273 		case 't':	/* steps per track */
274 			steps = atoi(optarg);
275 			break;
276 
277 		case 'i':       /* interleave factor */
278 			intleave = atoi(optarg);
279 			break;
280 
281 		case 'q':
282 			quiet = 1;
283 			break;
284 
285 		case 'y':
286 			confirm = 1;
287 			break;
288 
289 		case 'n':
290 			verify = 0;
291 			break;
292 
293 		case 'v':
294 			verify = 1;
295 			verify_only = 1;
296 			break;
297 
298 		case '?': default:
299 			usage();
300 		}
301 
302 	if(optind != argc - 1)
303 		usage();
304 
305 	switch(format) {
306 	default:
307 		errx(2, "bad floppy size: %dK", format);
308 	case -1:   suffix = "";      break;
309 	case 360:  suffix = ".360";  break;
310 	case 640:  suffix = ".640";  break;
311 	case 720:  suffix = ".720";  break;
312 	case 800:  suffix = ".800";  break;
313 	case 820:  suffix = ".820";  break;
314 	case 1200: suffix = ".1200"; break;
315 	case 1232: suffix = ".1232"; break;
316 	case 1440: suffix = ".1440"; break;
317 	case 1480: suffix = ".1480"; break;
318 	case 1720: suffix = ".1720"; break;
319 	}
320 
321 	devname = makename(argv[optind], suffix);
322 
323 	if((fd = open(devname, O_RDWR)) < 0)
324 		err(1, "%s", devname);
325 
326 	if(ioctl(fd, FD_GTYPE, &fdt) < 0)
327 		errx(1, "not a floppy disk: %s", devname);
328 	fdopts = FDOPT_NOERRLOG;
329 	if (ioctl(fd, FD_SOPTS, &fdopts) == -1)
330 		err(1, "ioctl(FD_SOPTS, FDOPT_NOERRLOG)");
331 
332 	switch(rate) {
333 	case -1:  break;
334 	case 250: fdt.trans = FDC_250KBPS; break;
335 	case 300: fdt.trans = FDC_300KBPS; break;
336 	case 500: fdt.trans = FDC_500KBPS; break;
337 	default:
338 		errx(2, "invalid transfer rate: %d", rate);
339 	}
340 
341 	if (cyls >= 0)    fdt.tracks = cyls;
342 	if (secs >= 0)    fdt.sectrac = secs;
343 	if (fdt.sectrac > FD_MAX_NSEC)
344 		errx(2, "too many sectors per track, max value is %d", FD_MAX_NSEC);
345 	if (heads >= 0)   fdt.heads = heads;
346 	if (gaplen >= 0)  fdt.f_gap = gaplen;
347 	if (secsize >= 0) fdt.secsize = secsize;
348 	if (steps >= 0)   fdt.steptrac = steps;
349 	if (intleave >= 0) fdt.f_inter = intleave;
350 
351 	bytes_per_track = fdt.sectrac * (1<<fdt.secsize) * 128;
352 
353 	/* XXX  20/40 = 0.5 */
354 	tracks_per_dot = (fdt.tracks * fdt.heads + 20) / 40;
355 
356 	if (verify_only) {
357 		if(!quiet)
358 			printf("Verify %dK floppy `%s'.\n",
359 				fdt.tracks * fdt.heads * bytes_per_track / 1024,
360 				devname);
361 	}
362 	else if(!quiet && !confirm) {
363 		printf("Format %dK floppy `%s'? (y/n): ",
364 			fdt.tracks * fdt.heads * bytes_per_track / 1024,
365 			devname);
366 		if(! yes ()) {
367 			printf("Not confirmed.\n");
368 			return 3;
369 		}
370 	}
371 
372 	/*
373 	 * Formatting.
374 	 */
375 	if(!quiet) {
376 		int i;
377 
378 		printf("Processing ");
379 		for (i = 0; i < (fdt.tracks * fdt.heads) / tracks_per_dot; i++)
380 			putchar('-');
381 		printf("\rProcessing ");
382 		fflush(stdout);
383 	}
384 
385 	error = errs = 0;
386 
387 	for (track = 0; track < fdt.tracks * fdt.heads; track++) {
388 		if (!verify_only) {
389 			format_track(fd, track / fdt.heads, fdt.sectrac,
390 				track % fdt.heads, fdt.trans, fdt.f_gap,
391 				fdt.secsize, fill, fdt.f_inter);
392 			if(!quiet && !((track + 1) % tracks_per_dot)) {
393 				putchar('F');
394 				fflush(stdout);
395 			}
396 		}
397 		if (verify) {
398 			if (verify_track(fd, track, bytes_per_track) < 0) {
399 				error = 1;
400 				if (errs < MAXPRINTERRS && errno == EIO) {
401 					if (ioctl(fd, FD_GSTAT, fdcs + errs) ==
402 					    -1)
403 						errx(1,
404 					"floppy IO error, but no FDC status");
405 					errs++;
406 				}
407 			}
408 			if(!quiet && !((track + 1) % tracks_per_dot)) {
409 				if (!verify_only)
410 					putchar('\b');
411 				if (error) {
412 					putchar('E');
413 					error = 0;
414 				}
415 				else
416 					putchar('V');
417 				fflush(stdout);
418 			}
419 		}
420 	}
421 	if(!quiet)
422 		printf(" done.\n");
423 
424 	if (!quiet && errs) {
425 		fflush(stdout);
426 		fprintf(stderr, "Errors encountered:\nCyl Head Sect   Error\n");
427 		for (i = 0; i < errs && i < MAXPRINTERRS; i++) {
428 			fprintf(stderr, " %2d   %2d   %2d   ",
429 				fdcs[i].status[3], fdcs[i].status[4],
430 				fdcs[i].status[5]);
431 			printstatus(fdcs + i);
432 			putc('\n', stderr);
433 		}
434 		if (errs >= MAXPRINTERRS)
435 			fprintf(stderr, "(Further errors not printed.)\n");
436 	}
437 
438 	return errs != 0;
439 }
440 /*
441  * Local Variables:
442  *  c-indent-level:               8
443  *  c-continued-statement-offset: 8
444  *  c-continued-brace-offset:     0
445  *  c-brace-offset:              -8
446  *  c-brace-imaginary-offset:     0
447  *  c-argdecl-indent:             8
448  *  c-label-offset:              -8
449  *  c++-hanging-braces:           1
450  *  c++-access-specifier-offset: -8
451  *  c++-empty-arglist-indent:     8
452  *  c++-friend-offset:            0
453  * End:
454  */
455