xref: /freebsd/usr.sbin/fdformat/fdformat.c (revision 39beb93c)
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$
27  */
28 
29 #include <sys/types.h>
30 #include <sys/fdcio.h>
31 #include <sys/stat.h>
32 
33 #include <ctype.h>
34 #include <err.h>
35 #include <errno.h>
36 #include <fcntl.h>
37 #include <paths.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <strings.h>
42 #include <sysexits.h>
43 #include <unistd.h>
44 
45 #include "fdutil.h"
46 
47 static void
48 format_track(int fd, int cyl, int secs, int head, int rate,
49 	     int gaplen, int secsize, int fill, int interleave,
50 	     int offset)
51 {
52 	struct fd_formb f;
53 	int i, j, il[FD_MAX_NSEC + 1];
54 
55 	memset(il, 0, sizeof il);
56 	for(j = 0, i = 1 + offset; i <= secs + offset; i++) {
57 	    while(il[(j % secs) + 1])
58 		    j++;
59 	    il[(j % secs) + 1] = i;
60 	    j += interleave;
61 	}
62 
63 	f.format_version = FD_FORMAT_VERSION;
64 	f.head = head;
65 	f.cyl = cyl;
66 	f.transfer_rate = rate;
67 
68 	f.fd_formb_secshift = secsize;
69 	f.fd_formb_nsecs = secs;
70 	f.fd_formb_gaplen = gaplen;
71 	f.fd_formb_fillbyte = fill;
72 	for(i = 0; i < secs; i++) {
73 		f.fd_formb_cylno(i) = cyl;
74 		f.fd_formb_headno(i) = head;
75 		f.fd_formb_secno(i) = il[i+1];
76 		f.fd_formb_secsize(i) = secsize;
77 	}
78 	if(ioctl(fd, FD_FORM, (caddr_t)&f) < 0)
79 		err(EX_OSERR, "ioctl(FD_FORM)");
80 }
81 
82 static int
83 verify_track(int fd, int track, int tracksize)
84 {
85 	static char *buf;
86 	static int bufsz;
87 	int fdopts = -1, ofdopts, rv = 0;
88 
89 	if (ioctl(fd, FD_GOPTS, &fdopts) < 0)
90 		warn("warning: ioctl(FD_GOPTS)");
91 	else {
92 		ofdopts = fdopts;
93 		fdopts |= FDOPT_NORETRY;
94 		(void)ioctl(fd, FD_SOPTS, &fdopts);
95 	}
96 
97 	if (bufsz < tracksize)
98 		buf = realloc(buf, bufsz = tracksize);
99 	if (buf == 0)
100 		errx(EX_UNAVAILABLE, "out of memory");
101 	if (lseek (fd, (long) track * tracksize, 0) < 0)
102 		rv = -1;
103 	/* try twice reading it, without using the normal retrier */
104 	else if (read (fd, buf, tracksize) != tracksize
105 		 && read (fd, buf, tracksize) != tracksize)
106 		rv = -1;
107 	if (fdopts != -1)
108 		(void)ioctl(fd, FD_SOPTS, &ofdopts);
109 	return (rv);
110 }
111 
112 static void
113 usage (void)
114 {
115 	errx(EX_USAGE,
116 	     "usage: fdformat [-F fill] [-f fmt] [-s fmtstr] [-nqvy] device");
117 }
118 
119 static int
120 yes (void)
121 {
122 	char reply[256], *p;
123 
124 	reply[sizeof(reply) - 1] = 0;
125 	for (;;) {
126 		fflush(stdout);
127 		if (!fgets (reply, sizeof(reply) - 1, stdin))
128 			return (0);
129 		for (p=reply; *p==' ' || *p=='\t'; ++p)
130 			continue;
131 		if (*p=='y' || *p=='Y')
132 			return (1);
133 		if (*p=='n' || *p=='N' || *p=='\n' || *p=='\r')
134 			return (0);
135 		printf("Answer `yes' or `no': ");
136 	}
137 }
138 
139 int
140 main(int argc, char **argv)
141 {
142 	enum fd_drivetype type;
143 	struct fd_type fdt, newft, *fdtp;
144 	struct stat sb;
145 #define MAXPRINTERRS 10
146 	struct fdc_status fdcs[MAXPRINTERRS];
147 	int format, fill, quiet, verify, verify_only, confirm;
148 	int fd, c, i, track, error, tracks_per_dot, bytes_per_track, errs;
149 	int fdopts, flags;
150 	char *fmtstring, *device;
151 	const char *name, *descr;
152 
153 	format = quiet = verify_only = confirm = 0;
154 	verify = 1;
155 	fill = 0xf6;
156 	fmtstring = 0;
157 
158 	while((c = getopt(argc, argv, "F:f:nqs:vy")) != -1)
159 		switch(c) {
160 		case 'F':	/* fill byte */
161 			if (getnum(optarg, &fill)) {
162 				fprintf(stderr,
163 			"Bad argument %s to -F option; must be numeric\n",
164 					optarg);
165 				usage();
166 			}
167 			break;
168 
169 		case 'f':	/* format in kilobytes */
170 			if (getnum(optarg, &format)) {
171 				fprintf(stderr,
172 			"Bad argument %s to -f option; must be numeric\n",
173 					optarg);
174 				usage();
175 			}
176 			break;
177 
178 		case 'n':	/* don't verify */
179 			verify = 0;
180 			break;
181 
182 		case 'q':	/* quiet */
183 			quiet = 1;
184 			break;
185 
186 		case 's':	/* format string with detailed options */
187 			fmtstring = optarg;
188 			break;
189 
190 		case 'v':	/* verify only */
191 			verify = 1;
192 			verify_only = 1;
193 			break;
194 
195 		case 'y':	/* confirm */
196 			confirm = 1;
197 			break;
198 
199 		default:
200 			usage();
201 		}
202 
203 	if(optind != argc - 1)
204 		usage();
205 
206 	if (stat(argv[optind], &sb) == -1 && errno == ENOENT) {
207 		/* try prepending _PATH_DEV */
208 		device = malloc(strlen(argv[optind]) + sizeof(_PATH_DEV) + 1);
209 		if (device == 0)
210 			errx(EX_UNAVAILABLE, "out of memory");
211 		strcpy(device, _PATH_DEV);
212 		strcat(device, argv[optind]);
213 		if (stat(device, &sb) == -1) {
214 			free(device);
215 			device = argv[optind]; /* let it fail below */
216 		}
217 	} else {
218 		device = argv[optind];
219 	}
220 
221 	if ((fd = open(device, O_RDWR | O_NONBLOCK)) < 0)
222 		err(EX_OSERR, "open(%s)", device);
223 
224 	/*
225 	 * Device initialization.
226 	 *
227 	 * First, get the device type descriptor.  This tells us about
228 	 * the media geometry data we need to format a medium.  It also
229 	 * lets us know quickly whether the device name actually points
230 	 * to a floppy disk drive.
231 	 *
232 	 * Then, obtain any drive options.  We're mainly interested to
233 	 * see whether we're currently working on a device with media
234 	 * density autoselection (FDOPT_AUTOSEL).  Then, we add the
235 	 * device option to tell the kernel not to log media errors,
236 	 * since we can handle them ourselves.  If the device does
237 	 * media density autoselection, we then need to set the device
238 	 * type appropriately, since by opening with O_NONBLOCK we
239 	 * told the driver to bypass media autoselection (otherwise we
240 	 * wouldn't stand a chance to format an unformatted or damaged
241 	 * medium).  We do not attempt to set the media type on any
242 	 * other devices since this is a privileged operation.  For the
243 	 * same reason, specifying -f and -s options is only possible
244 	 * for autoselecting devices.
245 	 *
246 	 * Finally, we are ready to turn off O_NONBLOCK, and start to
247 	 * actually format something.
248 	 */
249 	if(ioctl(fd, FD_GTYPE, &fdt) < 0)
250 		errx(EX_OSERR, "not a floppy disk: %s", device);
251 	if (ioctl(fd, FD_GDTYPE, &type) == -1)
252 		err(EX_OSERR, "ioctl(FD_GDTYPE)");
253 	if (ioctl(fd, FD_GOPTS, &fdopts) == -1)
254 		err(EX_OSERR, "ioctl(FD_GOPTS)");
255 	fdopts |= FDOPT_NOERRLOG;
256 	if (ioctl(fd, FD_SOPTS, &fdopts) == -1)
257 		err(EX_OSERR, "ioctl(FD_SOPTS, FDOPT_NOERRLOG)");
258 	if (format) {
259 		getname(type, &name, &descr);
260 		fdtp = get_fmt(format, type);
261 		if (fdtp == 0)
262 			errx(EX_USAGE,
263 			    "unknown format %d KB for drive type %s",
264 			     format, name);
265 		fdt = *fdtp;
266 	}
267 	if (fmtstring) {
268 		parse_fmt(fmtstring, type, fdt, &newft);
269 		fdt = newft;
270 	}
271 	if (ioctl(fd, FD_STYPE, &fdt) < 0)
272 		err(EX_OSERR, "ioctl(FD_STYPE)");
273 	if ((flags = fcntl(fd, F_GETFL, 0)) == -1)
274 		err(EX_OSERR, "fcntl(F_GETFL)");
275 	flags &= ~O_NONBLOCK;
276 	if (fcntl(fd, F_SETFL, flags) == -1)
277 		err(EX_OSERR, "fcntl(F_SETFL)");
278 
279 	bytes_per_track = fdt.sectrac * (128 << fdt.secsize);
280 
281 	/* XXX  20/40 = 0.5 */
282 	tracks_per_dot = (fdt.tracks * fdt.heads + 20) / 40;
283 
284 	if (verify_only) {
285 		if(!quiet)
286 			printf("Verify %dK floppy `%s'.\n",
287 				fdt.tracks * fdt.heads * bytes_per_track / 1024,
288 				device);
289 	}
290 	else if(!quiet && !confirm) {
291 		printf("Format %dK floppy `%s'? (y/n): ",
292 			fdt.tracks * fdt.heads * bytes_per_track / 1024,
293 			device);
294 		if(!yes()) {
295 			printf("Not confirmed.\n");
296 			return (EX_UNAVAILABLE);
297 		}
298 	}
299 
300 	/*
301 	 * Formatting.
302 	 */
303 	if(!quiet) {
304 		printf("Processing ");
305 		for (i = 0; i < (fdt.tracks * fdt.heads) / tracks_per_dot; i++)
306 			putchar('-');
307 		printf("\rProcessing ");
308 		fflush(stdout);
309 	}
310 
311 	error = errs = 0;
312 
313 	for (track = 0; track < fdt.tracks * fdt.heads; track++) {
314 		if (!verify_only) {
315 			format_track(fd, track / fdt.heads, fdt.sectrac,
316 				track % fdt.heads, fdt.trans, fdt.f_gap,
317 				fdt.secsize, fill, fdt.f_inter,
318 				track % fdt.heads? fdt.offset_side2: 0);
319 			if(!quiet && !((track + 1) % tracks_per_dot)) {
320 				putchar('F');
321 				fflush(stdout);
322 			}
323 		}
324 		if (verify) {
325 			if (verify_track(fd, track, bytes_per_track) < 0) {
326 				error = 1;
327 				if (errs < MAXPRINTERRS && errno == EIO) {
328 					if (ioctl(fd, FD_GSTAT, fdcs + errs) ==
329 					    -1)
330 						errx(EX_IOERR,
331 					"floppy IO error, but no FDC status");
332 					errs++;
333 				}
334 			}
335 			if(!quiet && !((track + 1) % tracks_per_dot)) {
336 				if (!verify_only)
337 					putchar('\b');
338 				if (error) {
339 					putchar('E');
340 					error = 0;
341 				}
342 				else
343 					putchar('V');
344 				fflush(stdout);
345 			}
346 		}
347 	}
348 	if(!quiet)
349 		printf(" done.\n");
350 
351 	if (!quiet && errs) {
352 		fflush(stdout);
353 		fprintf(stderr, "Errors encountered:\nCyl Head Sect   Error\n");
354 		for (i = 0; i < errs && i < MAXPRINTERRS; i++) {
355 			fprintf(stderr, " %2d   %2d   %2d   ",
356 				fdcs[i].status[3], fdcs[i].status[4],
357 				fdcs[i].status[5]);
358 			printstatus(fdcs + i, 1);
359 			putc('\n', stderr);
360 		}
361 		if (errs >= MAXPRINTERRS)
362 			fprintf(stderr, "(Further errors not printed.)\n");
363 	}
364 
365 	return errs != 0;
366 }
367