xref: /netbsd-src/sys/arch/amiga/dev/fd.c (revision 4b896b232495b7a9b8b94a1cf1e21873296d53b8)
1 /*	$NetBSD: fd.c,v 1.62 2003/07/14 15:57:39 aymeric Exp $ */
2 
3 /*
4  * Copyright (c) 1994 Christian E. Hopps
5  * Copyright (c) 1996 Ezra Story
6  * All rights reserved.
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 Christian E. Hopps.
19  *      This product includes software developed by Ezra Story.
20  * 4. The name of the author may not be used to endorse or promote products
21  *    derived from this software without specific prior written permission
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
24  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
25  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
26  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
27  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
28  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
29  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
30  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
31  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
32  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
33  */
34 
35 #include <sys/cdefs.h>
36 __KERNEL_RCSID(0, "$NetBSD: fd.c,v 1.62 2003/07/14 15:57:39 aymeric Exp $");
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/callout.h>
41 #include <sys/kernel.h>
42 #include <sys/malloc.h>
43 #include <sys/buf.h>
44 #include <sys/device.h>
45 #include <sys/ioctl.h>
46 #include <sys/fcntl.h>
47 #include <sys/disklabel.h>
48 #include <sys/disk.h>
49 #include <sys/dkbad.h>
50 #include <sys/proc.h>
51 #include <sys/conf.h>
52 
53 #include <uvm/uvm_extern.h>
54 
55 #include <machine/cpu.h>
56 #include <amiga/amiga/device.h>
57 #include <amiga/amiga/custom.h>
58 #include <amiga/amiga/cia.h>
59 #include <amiga/amiga/cc.h>
60 
61 #include "locators.h"
62 
63 enum fdc_bits { FDB_CHANGED = 2, FDB_PROTECT, FDB_CYLZERO, FDB_READY };
64 /*
65  * partitions in fd represent different format floppies
66  * partition a is 0 etc..
67  */
68 enum fd_parttypes {
69 	FDAMIGAPART = 0,
70 	FDMSDOSPART,
71 	FDMAXPARTS
72 };
73 
74 #define FDBBSIZE	(8192)
75 #define FDSBSIZE	(8192)
76 
77 #define FDUNIT(dev)	DISKUNIT(dev)
78 #define FDPART(dev)	DISKPART(dev)
79 #define FDMAKEDEV(m, u, p)	MAKEDISKDEV((m), (u), (p))
80 
81 /* that's nice, but we don't want to always use this as an amiga drive
82 bunghole :-) */
83 #define FDNHEADS	(2)	/* amiga drives always have 2 heads */
84 #define FDSECSIZE	(512)	/* amiga drives always have 512 byte sectors */
85 #define FDSECLWORDS	(128)
86 
87 #define FDSETTLEDELAY	(18000)	/* usec delay after seeking after switch dir */
88 #define FDSTEPDELAY	(3500)	/* usec delay after steping */
89 #define FDPRESIDEDELAY	(1000)	/* usec delay before writing can occur */
90 #define FDWRITEDELAY	(1300)	/* usec delay after write */
91 
92 #define FDSTEPOUT	(1)	/* decrease track step */
93 #define FDSTEPIN	(0)	/* increase track step */
94 
95 #define FDCUNITMASK	(0x78)	/* mask for all units (bits 6-3) */
96 
97 #define FDRETRIES	(2)	/* default number of retries */
98 #define FDMAXUNITS	(4)	/* maximum number of supported units */
99 
100 #define DISKLEN_READ	(0)	/* fake mask for reading */
101 #define DISKLEN_WRITE	(1 << 14)	/* bit for writing */
102 #define DISKLEN_DMAEN	(1 << 15)	/* DMA go */
103 #define DMABUFSZ ((DISKLEN_WRITE - 1) * 2)	/* largest DMA possible */
104 
105 #define FDMFMSYNC	(0x4489)
106 #define FDMFMID		(0x5554)
107 #define FDMFMDATA	(0x5545)
108 #define FDMFMGAP1	(0x9254)
109 #define FDMFMGAP2	(0xAAAA)
110 #define FDMFMGAP3	(0x9254)
111 #define CRC16POLY	(0x1021) /* (x^16) + x^12 + x^5 + x^0 */
112 
113 /*
114  * Msdos-type MFM encode/decode
115  */
116 static u_char msdecode[128];
117 static u_char msencode[16] =
118 {
119     0x2a, 0x29, 0x24, 0x25, 0x12, 0x11, 0x14, 0x15,
120     0x4a, 0x49, 0x44, 0x45, 0x52, 0x51, 0x54, 0x55
121 };
122 static u_short mscrctab[256];
123 
124 /*
125   5554    aaaa    aaaa    aaa5    2aa4    4452    aa51
126           00      00      03      02      ac      0d
127 */
128 
129 /*
130  * floppy device type
131  */
132 struct fdtype {
133 	u_int driveid;		/* drive identification (from drive) */
134 	u_int ncylinders;	/* number of cylinders on drive */
135 	u_int amiga_nsectors;	/* number of sectors per amiga track */
136 	u_int msdos_nsectors;	/* number of sectors per msdos track */
137 	u_int nreadw;		/* number of words (short) read per track */
138 	u_int nwritew;		/* number of words (short) written per track */
139 	u_int gap;		/* track gap size in long words */
140 	u_int precomp[2];	/* 1st and 2nd precomp values */
141 	char *desc;		/* description of drive type (useq) */
142 };
143 
144 /*
145  * floppy disk device data
146  */
147 struct fd_softc {
148 	struct device sc_dv;	/* generic device info; must come first */
149 	struct disk dkdev;	/* generic disk info */
150 	struct bufq_state bufq;	/* queue pending I/O operations */
151 	struct buf curbuf;	/* state of current I/O operation */
152 	struct callout calibrate_ch;
153 	struct callout motor_ch;
154 	struct fdtype *type;
155 	void *cachep;		/* cached track data (write through) */
156 	int cachetrk;		/* cahced track -1 for none */
157 	int hwunit;		/* unit for amiga controlling hw */
158 	int unitmask;		/* mask for cia select deslect */
159 	int pstepdir;		/* previous step direction */
160 	int curcyl;		/* current curcyl head positioned on */
161 	int flags;		/* misc flags */
162 	int wlabel;
163 	int stepdelay;		/* useq to delay after seek user setable */
164 	int nsectors;		/* number of sectors per track */
165 	int openpart;		/* which partition [ab] == [12] is open */
166 	short retries;		/* number of times to retry failed io */
167 	short retried;		/* number of times current io retried */
168 	int bytespersec;	/* number of bytes per sector */
169 };
170 
171 /* fd_softc->flags */
172 #define FDF_MOTORON	(0x01)	/* motor is running */
173 #define FDF_MOTOROFF	(0x02)	/* motor is waiting to be turned off */
174 #define FDF_WMOTOROFF	(0x04)	/* unit wants a wakeup after off */
175 #define FDF_DIRTY	(0x08)	/* track cache needs write */
176 #define FDF_WRITEWAIT	(0x10)	/* need to head select delay on next setpos */
177 #define FDF_HAVELABEL	(0x20)	/* label is valid */
178 #define FDF_JUSTFLUSH	(0x40)	/* don't bother caching track. */
179 #define FDF_NOTRACK0	(0x80)	/* was not able to recalibrate drive */
180 
181 int fdc_wantwakeup;
182 int fdc_side;
183 void  *fdc_dmap;
184 struct fd_softc *fdc_indma;
185 int fdc_dmalen;
186 int fdc_dmawrite;
187 
188 struct fdcargs {
189 	struct fdtype *type;
190 	int unit;
191 };
192 
193 int	fdcmatch(struct device *, struct cfdata *, void *);
194 void	fdcattach(struct device *, struct device *, void *);
195 int	fdcprint(void *, const char *);
196 int	fdmatch(struct device *, struct cfdata *, void *);
197 void	fdattach(struct device *, struct device *, void *);
198 
199 void	fdintr(int);
200 void	fdidxintr(void);
201 int	fdloaddisk(struct fd_softc *);
202 void	fdgetdefaultlabel(struct fd_softc *, struct disklabel *, int);
203 int	fdgetdisklabel(struct fd_softc *, dev_t);
204 int	fdsetdisklabel(struct fd_softc *, struct disklabel *);
205 int	fdputdisklabel(struct fd_softc *, dev_t);
206 struct	fdtype * fdcgetfdtype(int);
207 void	fdmotoroff(void *);
208 void	fdsetpos(struct fd_softc *, int, int);
209 void	fdselunit(struct fd_softc *);
210 void	fdstart(struct fd_softc *);
211 void	fdcont(struct fd_softc *);
212 void	fddmastart(struct fd_softc *, int);
213 void	fdcalibrate(void *);
214 void	fddmadone(struct fd_softc *, int);
215 void	fddone(struct fd_softc *);
216 void	fdfindwork(int);
217 void	fdminphys(struct buf *);
218 void	fdcachetoraw(struct fd_softc *);
219 void	amcachetoraw(struct fd_softc *);
220 int	amrawtocache(struct fd_softc *);
221 u_long	*fdfindsync(u_long *, u_long *);
222 int	fdrawtocache(struct fd_softc *);
223 void	mscachetoraw(struct fd_softc *);
224 int	msrawtocache(struct fd_softc *);
225 u_long	*mfmblkencode(u_long *, u_long *, u_long *, int);
226 u_long	*mfmblkdecode(u_long *, u_long *, u_long *, int);
227 u_short	*msblkdecode(u_short *, u_char *, int);
228 u_short	*msblkencode(u_short *, u_char *, int, u_short *);
229 
230 /*
231  * read size is (nsectors + 1) * mfm secsize + gap bytes + 2 shorts
232  * write size is nsectors * mfm secsize + gap bytes + 3 shorts
233  * the extra shorts are to deal with a DMA hw bug in the controller
234  * they are probably too much (I belive the bug is 1 short on write and
235  * 3 bits on read) but there is no need to be cheap here.
236  */
237 #define MAXTRKSZ (22 * FDSECSIZE)
238 struct fdtype fdtype[] = {
239 	{ 0x00000000, 80, 11, 9, 7358, 6815, 414, { 80, 161 }, "3.5dd" },
240 	{ 0x55555555, 40, 11, 9, 7358, 6815, 414, { 80, 161 }, "5.25dd" },
241 	{ 0xAAAAAAAA, 80, 22, 18, 14716, 13630, 828, { 80, 161 }, "3.5hd" }
242 };
243 int nfdtype = sizeof(fdtype) / sizeof(*fdtype);
244 
245 CFATTACH_DECL(fd, sizeof(struct fd_softc),
246     fdmatch, fdattach, NULL, NULL);
247 
248 extern struct cfdriver fd_cd;
249 
250 dev_type_open(fdopen);
251 dev_type_close(fdclose);
252 dev_type_read(fdread);
253 dev_type_write(fdwrite);
254 dev_type_ioctl(fdioctl);
255 dev_type_strategy(fdstrategy);
256 
257 const struct bdevsw fd_bdevsw = {
258 	fdopen, fdclose, fdstrategy, fdioctl, nodump, nosize, D_DISK
259 };
260 
261 const struct cdevsw fd_cdevsw = {
262 	fdopen, fdclose, fdread, fdwrite, fdioctl,
263 	nostop, notty, nopoll, nommap, nokqfilter, D_DISK
264 };
265 
266 struct dkdriver fddkdriver = { fdstrategy };
267 
268 CFATTACH_DECL(fdc, sizeof(struct device),
269     fdcmatch, fdcattach, NULL, NULL);
270 
271 /*
272  * all hw access through macros, this helps to hide the active low
273  * properties
274  */
275 
276 #define FDUNITMASK(unit)	(1 << (3 + (unit)))
277 
278 /*
279  * select units using mask
280  */
281 #define FDSELECT(um)	do { ciab.prb &= ~(um); } while (0)
282 
283 /*
284  * deselect units using mask
285  */
286 #define FDDESELECT(um)	do { ciab.prb |= (um); delay(1); } while (0)
287 
288 /*
289  * test hw condition bits
290  */
291 #define FDTESTC(bit)	((ciaa.pra & (1 << (bit))) == 0)
292 
293 /*
294  * set motor for select units, true motor on else off
295  */
296 #define FDSETMOTOR(on)	do { \
297 	if (on) ciab.prb &= ~CIAB_PRB_MTR; else ciab.prb |= CIAB_PRB_MTR; \
298 	} while (0)
299 
300 /*
301  * set head for select units
302  */
303 #define FDSETHEAD(head)	do { \
304 	if (head) ciab.prb &= ~CIAB_PRB_SIDE; else ciab.prb |= CIAB_PRB_SIDE; \
305 	delay(1); } while (0)
306 
307 /*
308  * select direction, true towards spindle else outwards
309  */
310 #define FDSETDIR(in)	do { \
311 	if (in) ciab.prb &= ~CIAB_PRB_DIR; else ciab.prb |= CIAB_PRB_DIR; \
312 	delay(1); } while (0)
313 
314 /*
315  * step the selected units
316  */
317 #define FDSTEP	do { \
318     ciab.prb &= ~CIAB_PRB_STEP; ciab.prb |= CIAB_PRB_STEP; \
319     } while (0)
320 
321 #define FDDMASTART(len, towrite)	do { \
322     int dmasz = (len) | ((towrite) ? DISKLEN_WRITE : 0) | DISKLEN_DMAEN; \
323     custom.dsklen = dmasz; custom.dsklen = dmasz; } while (0)
324 
325 #define FDDMASTOP	do { custom.dsklen = 0; } while (0)
326 
327 
328 int
329 fdcmatch(struct device *pdp, struct cfdata *cfp, void *auxp)
330 {
331 	static int fdc_matched = 0;
332 
333 	/* Allow only once instance. */
334 	if (matchname("fdc", auxp) == 0 || fdc_matched)
335 		return(0);
336 	if ((fdc_dmap = alloc_chipmem(DMABUFSZ)) == NULL) {
337 		printf("fdc: unable to allocate DMA buffer\n");
338 		return(0);
339 	}
340 
341 	fdc_matched = 1;
342 	return(1);
343 }
344 
345 void
346 fdcattach(struct device *pdp, struct device *dp, void *auxp)
347 {
348 	struct fdcargs args;
349 
350 	printf(": dmabuf pa 0x%x", kvtop(fdc_dmap));
351 	printf(": dmabuf ka %p\n", fdc_dmap);
352 	args.unit = 0;
353 	args.type = fdcgetfdtype(args.unit);
354 
355 	fdc_side = -1;
356 	config_found(dp, &args, fdcprint);
357 	for (args.unit++; args.unit < FDMAXUNITS; args.unit++) {
358 		if ((args.type = fdcgetfdtype(args.unit)) == NULL)
359 			continue;
360 		config_found(dp, &args, fdcprint);
361 	}
362 }
363 
364 int
365 fdcprint(void *auxp, const char *pnp)
366 {
367 	struct fdcargs *fcp;
368 
369 	fcp = auxp;
370 	if (pnp)
371 		aprint_normal("fd%d at %s unit %d:", fcp->unit, pnp,
372 			fcp->type->driveid);
373 	return(UNCONF);
374 }
375 
376 /*ARGSUSED*/
377 int
378 fdmatch(struct device *pdp, struct cfdata *cfp, void *auxp)
379 {
380 	struct fdcargs *fdap;
381 
382 	fdap = auxp;
383 	if (cfp->cf_loc[FDCCF_UNIT] == fdap->unit ||
384 	    cfp->cf_loc[FDCCF_UNIT] == FDCCF_UNIT_DEFAULT)
385 		return(1);
386 
387 	return(0);
388 }
389 
390 void
391 fdattach(struct device *pdp, struct device *dp, void *auxp)
392 {
393 	struct fdcargs *ap;
394 	struct fd_softc *sc;
395 	int i;
396 
397 	ap = auxp;
398 	sc = (struct fd_softc *)dp;
399 
400 	bufq_alloc(&sc->bufq, BUFQ_DISKSORT|BUFQ_SORT_CYLINDER);
401 	callout_init(&sc->calibrate_ch);
402 	callout_init(&sc->motor_ch);
403 
404 	sc->curcyl = sc->cachetrk = -1;
405 	sc->openpart = -1;
406 	sc->type = ap->type;
407 	sc->hwunit = ap->unit;
408 	sc->unitmask = 1 << (3 + ap->unit);
409 	sc->retries = FDRETRIES;
410 	sc->stepdelay = FDSTEPDELAY;
411 	sc->bytespersec = 512;
412 	printf(" unit %d: %s %d cyl, %d head, %d sec [%d sec], 512 bytes/sec\n",
413 	    sc->hwunit, sc->type->desc, sc->type->ncylinders, FDNHEADS,
414 	    sc->type->amiga_nsectors, sc->type->msdos_nsectors);
415 
416 	/*
417 	 * Initialize and attach the disk structure.
418 	 */
419 	sc->dkdev.dk_name = sc->sc_dv.dv_xname;
420 	sc->dkdev.dk_driver = &fddkdriver;
421 	disk_attach(&sc->dkdev);
422 
423 	/*
424 	 * calibrate the drive
425 	 */
426 	fdsetpos(sc, 0, 0);
427 	fdsetpos(sc, sc->type->ncylinders, 0);
428 	fdsetpos(sc, 0, 0);
429 	fdmotoroff(sc);
430 
431 	/*
432 	 * precalc msdos MFM and CRC
433 	 */
434 	for (i = 0; i < 128; i++)
435 		msdecode[i] = 0xff;
436 	for (i = 0; i < 16; i++)
437 		msdecode[msencode[i]] = i;
438 	for (i = 0; i < 256; i++) {
439 		mscrctab[i] = (0x1021 * (i & 0xf0)) ^ (0x1021 * (i & 0x0f)) ^
440 		    (0x1021 * (i >> 4));
441 	}
442 
443 	/*
444 	 * enable disk related interrupts
445 	 */
446 	custom.dmacon = DMAF_SETCLR | DMAF_MASTER | DMAF_DISK;
447 	custom.intena = INTF_SETCLR | INTF_DSKBLK;
448 	ciab.icr = CIA_ICR_FLG;
449 }
450 
451 /*ARGSUSED*/
452 int
453 fdopen(dev_t dev, int flags, int devtype, struct proc *p)
454 {
455 	struct fd_softc *sc;
456 	int wasopen, fwork, error, s;
457 
458 	error = 0;
459 
460 	if (FDPART(dev) >= FDMAXPARTS)
461 		return(ENXIO);
462 
463 	if ((sc = getsoftc(fd_cd, FDUNIT(dev))) == NULL)
464 		return(ENXIO);
465 	if (sc->flags & FDF_NOTRACK0)
466 		return(ENXIO);
467 	if (sc->cachep == NULL)
468 		sc->cachep = malloc(MAXTRKSZ, M_DEVBUF, M_WAITOK);
469 
470 	s = splbio();
471 	/*
472 	 * if we are sleeping in fdclose(); waiting for a chance to
473 	 * shut the motor off, do a sleep here also.
474 	 */
475 	while (sc->flags & FDF_WMOTOROFF)
476 		tsleep(fdmotoroff, PRIBIO, "fdopen", 0);
477 
478 	fwork = 0;
479 	/*
480 	 * if not open let user open request type, otherwise
481 	 * ensure they are trying to open same type.
482 	 */
483 	if (sc->openpart == FDPART(dev))
484 		wasopen = 1;
485 	else if (sc->openpart == -1) {
486 		sc->openpart = FDPART(dev);
487 		wasopen = 0;
488 	} else {
489 		wasopen = 1;
490 		error = EPERM;
491 		goto done;
492 	}
493 
494 	/*
495 	 * wait for current io to complete if any
496 	 */
497 	if (fdc_indma) {
498 		fwork = 1;
499 		fdc_wantwakeup++;
500 		tsleep(fdopen, PRIBIO, "fdopen", 0);
501 	}
502 	if ((error = fdloaddisk(sc)) != 0)
503 		goto done;
504 	if ((error = fdgetdisklabel(sc, dev)) != 0)
505 		goto done;
506 #ifdef FDDEBUG
507 	printf("  open successful\n");
508 #endif
509 done:
510 	/*
511 	 * if we requested that fddone()->fdfindwork() wake us, allow it to
512 	 * complete its job now
513 	 */
514 	if (fwork)
515 		fdfindwork(FDUNIT(dev));
516 	splx(s);
517 
518 	/*
519 	 * if we were not open and we marked us so reverse that.
520 	 */
521 	if (error && wasopen == 0)
522 		sc->openpart = -1;
523 	return(error);
524 }
525 
526 /*ARGSUSED*/
527 int
528 fdclose(dev_t dev, int flags, int devtype, struct proc *p)
529 {
530 	struct fd_softc *sc;
531 	int s;
532 
533 #ifdef FDDEBUG
534 	printf("fdclose()\n");
535 #endif
536 	sc = getsoftc(fd_cd, FDUNIT(dev));
537 	s = splbio();
538 	if (sc->flags & FDF_MOTORON) {
539 		sc->flags |= FDF_WMOTOROFF;
540 		tsleep(fdmotoroff, PRIBIO, "fdclose", 0);
541 		sc->flags &= ~FDF_WMOTOROFF;
542 		wakeup(fdmotoroff);
543 	}
544 	sc->openpart = -1;
545 	splx(s);
546 	return(0);
547 }
548 
549 int
550 fdioctl(dev_t dev, u_long cmd, caddr_t addr, int flag, struct proc *p)
551 {
552 	struct fd_softc *sc;
553 	int error, wlab;
554 
555 	sc = getsoftc(fd_cd, FDUNIT(dev));
556 
557 	if ((sc->flags & FDF_HAVELABEL) == 0)
558 		return(EBADF);
559 
560 	switch (cmd) {
561 	case DIOCSBAD:
562 		return(EINVAL);
563 	case DIOCSRETRIES:
564 		if (*(int *)addr < 0)
565 			return(EINVAL);
566 		sc->retries = *(int *)addr;
567 		return(0);
568 	case DIOCSSTEP:
569 		if (*(int *)addr < FDSTEPDELAY)
570 			return(EINVAL);
571 		sc->dkdev.dk_label->d_trkseek = sc->stepdelay = *(int *)addr;
572 		return(0);
573 	case DIOCGDINFO:
574 		*(struct disklabel *)addr = *(sc->dkdev.dk_label);
575 		return(0);
576 	case DIOCGPART:
577 		((struct partinfo *)addr)->disklab = sc->dkdev.dk_label;
578 		((struct partinfo *)addr)->part =
579 		    &sc->dkdev.dk_label->d_partitions[FDPART(dev)];
580 		return(0);
581 	case DIOCSDINFO:
582 		if ((flag & FWRITE) == 0)
583 			return(EBADF);
584 		return(fdsetdisklabel(sc, (struct disklabel *)addr));
585 	case DIOCWDINFO:
586 		if ((flag & FWRITE) == 0)
587 			return(EBADF);
588 		if ((error = fdsetdisklabel(sc, (struct disklabel *)addr)) != 0)
589 			return(error);
590 		wlab = sc->wlabel;
591 		sc->wlabel = 1;
592 		error = fdputdisklabel(sc, dev);
593 		sc->wlabel = wlab;
594 		return(error);
595 	case DIOCWLABEL:
596 		if ((flag & FWRITE) == 0)
597 			return(EBADF);
598 		sc->wlabel = *(int *)addr;
599 		return(0);
600 	case DIOCGDEFLABEL:
601 		fdgetdefaultlabel(sc, (struct disklabel *)addr, FDPART(dev));
602 		return(0);
603 	default:
604 		return(ENOTTY);
605 	}
606 }
607 
608 int
609 fdread(dev_t dev, struct uio *uio, int flags)
610 {
611 	return (physio(fdstrategy, NULL, dev, B_READ, fdminphys, uio));
612 }
613 
614 int
615 fdwrite(dev_t dev, struct uio *uio, int flags)
616 {
617 	return (physio(fdstrategy, NULL, dev, B_WRITE, fdminphys, uio));
618 }
619 
620 
621 void
622 fdintr(int flag)
623 {
624 	int s;
625 
626 	s = splbio();
627 	if (fdc_indma)
628 		fddmadone(fdc_indma, 0);
629 	splx(s);
630 }
631 
632 void
633 fdidxintr(void)
634 {
635 	if (fdc_indma && fdc_dmalen) {
636 		/*
637 		 * turn off intr and start actual dma
638 		 */
639 		ciab.icr = CIA_ICR_FLG;
640 		FDDMASTART(fdc_dmalen, fdc_dmawrite);
641 		fdc_dmalen = 0;
642 	}
643 }
644 
645 void
646 fdstrategy(struct buf *bp)
647 {
648 	struct disklabel *lp;
649 	struct fd_softc *sc;
650 	int unit, part, s;
651 
652 	unit = FDUNIT(bp->b_dev);
653 	part = FDPART(bp->b_dev);
654 	sc = getsoftc(fd_cd, unit);
655 
656 #ifdef FDDEBUG
657 	printf("fdstrategy: %p\n", bp);
658 #endif
659 	/*
660 	 * check for valid partition and bounds
661 	 */
662 	lp = sc->dkdev.dk_label;
663 	if ((sc->flags & FDF_HAVELABEL) == 0) {
664 		bp->b_error = EIO;
665 		goto bad;
666 	}
667 	if (bounds_check_with_label(&sc->dkdev, bp, sc->wlabel) <= 0)
668 		goto done;
669 
670 	/*
671 	 * trans count of zero or bounds check indicates io is done
672 	 * we are done.
673 	 */
674 	if (bp->b_bcount == 0)
675 		goto done;
676 
677 	bp->b_rawblkno = bp->b_blkno;
678 
679 	/*
680 	 * queue the buf and kick the low level code
681 	 */
682 	s = splbio();
683 	BUFQ_PUT(&sc->bufq, bp);
684 	fdstart(sc);
685 	splx(s);
686 	return;
687 bad:
688 	bp->b_flags |= B_ERROR;
689 done:
690 	bp->b_resid = bp->b_bcount;
691 	biodone(bp);
692 }
693 
694 /*
695  * make sure disk is loaded and label is up-to-date.
696  */
697 int
698 fdloaddisk(struct fd_softc *sc)
699 {
700 	/*
701 	 * if diskchange is low step drive to 0 then up one then to zero.
702 	 */
703 	fdselunit(sc);			/* make sure the unit is selected */
704 	if (FDTESTC(FDB_CHANGED)) {
705 		fdsetpos(sc, 0, 0);
706 		sc->cachetrk = -1;		/* invalidate the cache */
707 		sc->flags &= ~FDF_HAVELABEL;
708 		fdsetpos(sc, FDNHEADS, 0);
709 		fdsetpos(sc, 0, 0);
710 		if (FDTESTC(FDB_CHANGED)) {
711 			fdmotoroff(sc);
712 			FDDESELECT(sc->unitmask);
713 			return(ENXIO);
714 		}
715 	}
716 	FDDESELECT(sc->unitmask);
717 	fdmotoroff(sc);
718 	sc->type = fdcgetfdtype(sc->hwunit);
719 	if (sc->type == NULL)
720 		return(ENXIO);
721 	if (sc->openpart == FDMSDOSPART)
722 		sc->nsectors = sc->type->msdos_nsectors;
723 	else
724 		sc->nsectors = sc->type->amiga_nsectors;
725 	return(0);
726 }
727 
728 void
729 fdgetdefaultlabel(struct fd_softc *sc, struct disklabel *lp, int part)
730 /* (variable part) XXX ick */
731 {
732 
733 	bzero(lp, sizeof(struct disklabel));
734 	lp->d_secsize = FDSECSIZE;
735 	lp->d_ntracks = FDNHEADS;
736 	lp->d_ncylinders = sc->type->ncylinders;
737 	lp->d_nsectors = sc->nsectors;
738 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
739 	lp->d_type = DTYPE_FLOPPY;
740 	lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
741 	lp->d_rpm = 300; 		/* good guess I suppose. */
742 	lp->d_interleave = 1;		/* should change when adding msdos */
743 	sc->stepdelay = lp->d_trkseek = FDSTEPDELAY;
744 	lp->d_bbsize = 0;
745 	lp->d_sbsize = 0;
746 	lp->d_partitions[part].p_size = lp->d_secperunit;
747 	lp->d_partitions[part].p_fstype = FS_UNUSED;
748 	lp->d_partitions[part].p_fsize = 1024;
749 	lp->d_partitions[part].p_frag = 8;
750 	lp->d_partitions[part].p_cpg = 2;	/* adosfs: reserved blocks */
751 	lp->d_npartitions = part + 1;
752 	lp->d_magic = lp->d_magic2 = DISKMAGIC;
753 	lp->d_checksum = dkcksum(lp);
754 }
755 
756 /*
757  * read disk label, if present otherwise create one
758  * return a new label if raw part and none found, otherwise err.
759  */
760 int
761 fdgetdisklabel(struct fd_softc *sc, dev_t dev)
762 {
763 	struct disklabel *lp, *dlp;
764 	struct cpu_disklabel *clp;
765 	struct buf *bp;
766 	int error, part;
767 
768 	if (sc->flags & FDF_HAVELABEL &&
769 	    sc->dkdev.dk_label->d_npartitions == (FDPART(dev) + 1))
770 		return(0);
771 #ifdef FDDEBUG
772 	printf("fdgetdisklabel()\n");
773 #endif
774 	part = FDPART(dev);
775 	lp = sc->dkdev.dk_label;
776 	clp =  sc->dkdev.dk_cpulabel;
777 	bzero(lp, sizeof(struct disklabel));
778 	bzero(clp, sizeof(struct cpu_disklabel));
779 
780 	lp->d_secsize = FDSECSIZE;
781 	lp->d_ntracks = FDNHEADS;
782 	lp->d_ncylinders = sc->type->ncylinders;
783 	lp->d_nsectors = sc->nsectors;
784 	lp->d_secpercyl = lp->d_ntracks * lp->d_nsectors;
785 	lp->d_secperunit = lp->d_secpercyl * lp->d_ncylinders;
786 	lp->d_npartitions = part + 1;
787 	lp->d_partitions[part].p_size = lp->d_secperunit;
788 	lp->d_partitions[part].p_fstype = FS_UNUSED;
789 	lp->d_partitions[part].p_fsize = 1024;
790 	lp->d_partitions[part].p_frag = 8;
791 	lp->d_partitions[part].p_cpg = 2;	/* for adosfs: reserved blks */
792 
793 	sc->flags |= FDF_HAVELABEL;
794 
795 	bp = (void *)geteblk((int)lp->d_secsize);
796 	bp->b_dev = dev;
797 	bp->b_blkno = 0;
798 	bp->b_cylinder = 0;
799 	bp->b_bcount = FDSECSIZE;
800 	bp->b_flags |= B_READ;
801 	fdstrategy(bp);
802 	if ((error = biowait(bp)) != 0)
803 		goto nolabel;
804 	dlp = (struct disklabel *)(bp->b_data + LABELOFFSET);
805 	if (dlp->d_magic != DISKMAGIC || dlp->d_magic2 != DISKMAGIC ||
806 	    dkcksum(dlp)) {
807 		error = EINVAL;
808 		goto nolabel;
809 	}
810 	bcopy(dlp, lp, sizeof(struct disklabel));
811 	if (lp->d_trkseek > FDSTEPDELAY)
812 		sc->stepdelay = lp->d_trkseek;
813 	brelse(bp);
814 	return(0);
815 nolabel:
816 	fdgetdefaultlabel(sc, lp, part);
817 	brelse(bp);
818 	return(0);
819 }
820 
821 /*
822  * set the incore copy of this units disklabel
823  */
824 int
825 fdsetdisklabel(struct fd_softc *sc, struct disklabel *lp)
826 {
827 	struct disklabel *clp;
828 	struct partition *pp;
829 
830 	/*
831 	 * must have at least opened raw unit to fetch the
832 	 * raw_part stuff.
833 	 */
834 	if ((sc->flags & FDF_HAVELABEL) == 0)
835 		return(EINVAL);
836 	clp = sc->dkdev.dk_label;
837 	/*
838 	 * make sure things check out and we only have one valid
839 	 * partition
840 	 */
841 #ifdef FDDEBUG
842 	printf("fdsetdisklabel\n");
843 #endif
844 	if (lp->d_secsize != FDSECSIZE ||
845 	    lp->d_nsectors != clp->d_nsectors ||
846 	    lp->d_ntracks != FDNHEADS ||
847 	    lp->d_ncylinders != clp->d_ncylinders ||
848 	    lp->d_secpercyl != clp->d_secpercyl ||
849 	    lp->d_secperunit != clp->d_secperunit ||
850 	    lp->d_magic != DISKMAGIC ||
851 	    lp->d_magic2 != DISKMAGIC ||
852 	    lp->d_npartitions == 0 ||
853 	    lp->d_npartitions > FDMAXPARTS ||
854 	    (lp->d_partitions[0].p_offset && lp->d_partitions[1].p_offset) ||
855 	    dkcksum(lp))
856 		return(EINVAL);
857 	/*
858 	 * if any partitions are present make sure they
859 	 * represent the currently open type
860 	 */
861 	if ((pp = &lp->d_partitions[0])->p_size) {
862 		if ((pp = &lp->d_partitions[1])->p_size == 0)
863 			goto done;
864 		else if (sc->openpart != 1)
865 			return(EINVAL);
866 	} else if (sc->openpart != 0)
867 		return(EINVAL);
868 	/*
869 	 * make sure selected partition is within bounds
870 	 * XXX on the second check, its to handle a bug in
871 	 * XXX the cluster routines as they require mutliples
872 	 * XXX of PAGE_SIZE currently
873 	 */
874 	if ((pp->p_offset + pp->p_size >= lp->d_secperunit) ||
875 	    (pp->p_frag * pp->p_fsize % PAGE_SIZE))
876 		return(EINVAL);
877 done:
878 	bcopy(lp, clp, sizeof(struct disklabel));
879 	return(0);
880 }
881 
882 /*
883  * write out the incore copy of this units disklabel
884  */
885 int
886 fdputdisklabel(struct fd_softc *sc, dev_t dev)
887 {
888 	struct disklabel *lp, *dlp;
889 	struct buf *bp;
890 	int error;
891 
892 	if ((sc->flags & FDF_HAVELABEL) == 0)
893 		return(EBADF);
894 #ifdef FDDEBUG
895 	printf("fdputdisklabel\n");
896 #endif
897 	/*
898 	 * get buf and read in sector 0
899 	 */
900 	lp = sc->dkdev.dk_label;
901 	bp = geteblk((int)lp->d_secsize);
902 	bp->b_dev = FDMAKEDEV(major(dev), FDUNIT(dev), RAW_PART);
903 	bp->b_blkno = 0;
904 	bp->b_cylinder = 0;
905 	bp->b_bcount = FDSECSIZE;
906 	bp->b_flags |= B_READ;
907 	fdstrategy(bp);
908 	if ((error = biowait(bp)) != 0)
909 		goto done;
910 	/*
911 	 * copy disklabel to buf and write it out synchronous
912 	 */
913 	dlp = (struct disklabel *)(bp->b_data + LABELOFFSET);
914 	bcopy(lp, dlp, sizeof(struct disklabel));
915 	bp->b_blkno = 0;
916 	bp->b_cylinder = 0;
917 	bp->b_flags &= ~(B_READ|B_DONE);
918 	bp->b_flags |= B_WRITE;
919 	fdstrategy(bp);
920 	error = biowait(bp);
921 done:
922 	brelse(bp);
923 	return(error);
924 }
925 
926 /*
927  * figure out drive type or NULL if none.
928  */
929 struct fdtype *
930 fdcgetfdtype(int unit)
931 {
932 	struct fdtype *ftp;
933 	u_long id, idb;
934 	int cnt, umask;
935 
936 	id = 0;
937 	umask = 1 << (3 + unit);
938 
939 	FDDESELECT(FDCUNITMASK);
940 
941 	FDSETMOTOR(1);
942 	delay(1);
943 	FDSELECT(umask);
944 	delay(1);
945 	FDDESELECT(umask);
946 
947 	FDSETMOTOR(0);
948 	delay(1);
949 	FDSELECT(umask);
950 	delay(1);
951 	FDDESELECT(umask);
952 
953 	for (idb = 0x80000000; idb; idb >>= 1) {
954 		FDSELECT(umask);
955 		delay(1);
956 		if (FDTESTC(FDB_READY) == 0)
957 			id |= idb;
958 		FDDESELECT(umask);
959 		delay(1);
960 	}
961 #ifdef FDDEBUG
962 	printf("fdcgettype unit %d id 0x%lx\n", unit, id);
963 #endif
964 
965 	for (cnt = 0, ftp = fdtype; cnt < nfdtype; ftp++, cnt++)
966 		if (ftp->driveid == id)
967 			return(ftp);
968 	/*
969 	 * 3.5dd's at unit 0 do not always return id.
970 	 */
971 	if (unit == 0)
972 		return(fdtype);
973 	return(NULL);
974 }
975 
976 /*
977  * turn motor off if possible otherwise mark as needed and will be done
978  * later.
979  */
980 void
981 fdmotoroff(void *arg)
982 {
983 	struct fd_softc *sc;
984 	int s;
985 
986 	sc = arg;
987 	s = splbio();
988 
989 #ifdef FDDEBUG
990 	printf("fdmotoroff: unit %d\n", sc->hwunit);
991 #endif
992 	if ((sc->flags & FDF_MOTORON) == 0)
993 		goto done;
994 	/*
995 	 * if we have a timeout on a DMA operation let fddmadone()
996 	 * deal with it.
997 	 */
998 	if (fdc_indma == sc) {
999 		fddmadone(sc, 1);
1000 		goto done;
1001 	}
1002 #ifdef FDDEBUG
1003 	printf(" motor was on, turning off\n");
1004 #endif
1005 
1006 	/*
1007 	 * flush cache if needed
1008 	 */
1009 	if (sc->flags & FDF_DIRTY) {
1010 		sc->flags |= FDF_JUSTFLUSH | FDF_MOTOROFF;
1011 #ifdef FDDEBUG
1012 		printf("  flushing dirty buffer first\n");
1013 #endif
1014 		/*
1015 		 * if DMA'ing done for now, fddone() will call us again
1016 		 */
1017 		if (fdc_indma)
1018 			goto done;
1019 		fddmastart(sc, sc->cachetrk);
1020 		goto done;
1021 	}
1022 
1023 	/*
1024 	 * if controller is busy just schedule us to be called back
1025 	 */
1026 	if (fdc_indma) {
1027 		/*
1028 		 * someone else has the controller now
1029 		 * just set flag and let fddone() call us again.
1030 		 */
1031 		sc->flags |= FDF_MOTOROFF;
1032 		goto done;
1033 	}
1034 
1035 #ifdef FDDEBUG
1036 	printf("  hw turning unit off\n");
1037 #endif
1038 
1039 	sc->flags &= ~(FDF_MOTORON | FDF_MOTOROFF);
1040 	FDDESELECT(FDCUNITMASK);
1041 	FDSETMOTOR(0);
1042 	delay(1);
1043 	FDSELECT(sc->unitmask);
1044 	delay(4);
1045 	FDDESELECT(sc->unitmask);
1046 	delay(1);
1047 	if (sc->flags & FDF_WMOTOROFF)
1048 		wakeup(fdmotoroff);
1049 done:
1050 	splx(s);
1051 }
1052 
1053 /*
1054  * select drive seek to track exit with motor on.
1055  * fdsetpos(x, 0, 0) does calibrates the drive.
1056  */
1057 void
1058 fdsetpos(struct fd_softc *sc, int trk, int towrite)
1059 {
1060 	int nstep, sdir, ondly, ncyl, nside;
1061 
1062 	FDDESELECT(FDCUNITMASK);
1063 	FDSETMOTOR(1);
1064 	delay(1);
1065 	FDSELECT(sc->unitmask);
1066 	delay(1);
1067 	if ((sc->flags & FDF_MOTORON) == 0) {
1068 		ondly = 0;
1069 		while (FDTESTC(FDB_READY) == 0) {
1070 			delay(1000);
1071 			if (++ondly >= 1000)
1072 				break;
1073 		}
1074 	}
1075 	sc->flags |= FDF_MOTORON;
1076 
1077 	ncyl = trk / FDNHEADS;
1078 	nside = trk % FDNHEADS;
1079 
1080 	if (sc->curcyl == ncyl && fdc_side == nside)
1081 		return;
1082 
1083 	if (towrite)
1084 		sc->flags |= FDF_WRITEWAIT;
1085 
1086 #ifdef FDDEBUG
1087 	printf("fdsetpos: cyl %d head %d towrite %d\n", trk / FDNHEADS,
1088 	    trk % FDNHEADS, towrite);
1089 #endif
1090 	nstep = ncyl - sc->curcyl;
1091 	if (nstep) {
1092 		/*
1093 		 * figure direction
1094 		 */
1095 		if (nstep > 0 && ncyl != 0) {
1096 			sdir = FDSTEPIN;
1097 			FDSETDIR(1);
1098 		} else {
1099 			nstep = -nstep;
1100 			sdir = FDSTEPOUT;
1101 			FDSETDIR(0);
1102 		}
1103 		if (ncyl == 0) {
1104 			/*
1105 			 * either just want cylinder 0 or doing
1106 			 * a calibrate.
1107 			 */
1108 			nstep = 256;
1109 			while (FDTESTC(FDB_CYLZERO) == 0 && nstep--) {
1110 				FDSTEP;
1111 				delay(sc->stepdelay);
1112 			}
1113 			if (nstep < 0)
1114 				sc->flags |= FDF_NOTRACK0;
1115 		} else {
1116 			/*
1117 			 * step the needed amount amount.
1118 			 */
1119 			while (nstep--) {
1120 				FDSTEP;
1121 				delay(sc->stepdelay);
1122 			}
1123 		}
1124 		/*
1125 		 * if switched directions
1126 		 * allow drive to settle.
1127 		 */
1128 		if (sc->pstepdir != sdir)
1129 			delay(FDSETTLEDELAY);
1130 		sc->pstepdir = sdir;
1131 		sc->curcyl = ncyl;
1132 	}
1133 	if (nside == fdc_side)
1134 		return;
1135 	/*
1136 	 * select side
1137 	 */
1138 	fdc_side = nside;
1139 	FDSETHEAD(nside);
1140 	delay(FDPRESIDEDELAY);
1141 }
1142 
1143 void
1144 fdselunit(struct fd_softc *sc)
1145 {
1146 	FDDESELECT(FDCUNITMASK);		/* deselect all */
1147 	FDSETMOTOR(sc->flags & FDF_MOTORON);	/* set motor to unit's state */
1148 	delay(1);
1149 	FDSELECT(sc->unitmask);			/* select unit */
1150 	delay(1);
1151 }
1152 
1153 /*
1154  * process next buf on device queue.
1155  * normall sequence of events:
1156  * fdstart() -> fddmastart();
1157  * fdidxintr();
1158  * fdintr() -> fddmadone() -> fddone();
1159  * if the track is in the cache then fdstart() will short-circuit
1160  * to fddone() else if the track cache is dirty it will flush.  If
1161  * the buf is not an entire track it will cache the requested track.
1162  */
1163 void
1164 fdstart(struct fd_softc *sc)
1165 {
1166 	int trk, error, write;
1167 	struct buf *bp, *dp;
1168 	int changed;
1169 
1170 #ifdef FDDEBUG
1171 	printf("fdstart: unit %d\n", sc->hwunit);
1172 #endif
1173 
1174 	/*
1175 	 * if DMA'ing just return. we must have been called from fdstartegy.
1176 	 */
1177 	if (fdc_indma)
1178 		return;
1179 
1180 	/*
1181 	 * get next buf if there.
1182 	 */
1183 	dp = &sc->curbuf;
1184 	if ((bp = BUFQ_PEEK(&sc->bufq)) == NULL) {
1185 #ifdef FDDEBUG
1186 		printf("  nothing to do\n");
1187 #endif
1188 		return;
1189 	}
1190 
1191 	/*
1192 	 * Mark us as busy now, in case fddone() gets called in one
1193 	 * of the cases below.
1194 	 */
1195 	disk_busy(&sc->dkdev);
1196 
1197 	/*
1198 	 * make sure same disk is loaded
1199 	 */
1200 	fdselunit(sc);
1201 	changed = FDTESTC(FDB_CHANGED);
1202 	FDDESELECT(sc->unitmask);
1203 	if (changed) {
1204 		/*
1205 		 * disk missing, invalidate all future io on
1206 		 * this unit until re-open()'ed also invalidate
1207 		 * all current io
1208 		 */
1209 printf("fdstart: disk changed\n");
1210 #ifdef FDDEBUG
1211 		printf("  disk was removed invalidating all io\n");
1212 #endif
1213 		sc->flags &= ~FDF_HAVELABEL;
1214 		for (;;) {
1215 			bp = BUFQ_GET(&sc->bufq);
1216 			bp->b_flags |= B_ERROR;
1217 			bp->b_error = EIO;
1218 			if (BUFQ_PEEK(&sc->bufq) == NULL)
1219 				break;
1220 			biodone(bp);
1221 		}
1222 		/*
1223 		 * do fddone() on last buf to allow other units to start.
1224 		 */
1225 		BUFQ_PUT(&sc->bufq, bp);
1226 		fddone(sc);
1227 		return;
1228 	}
1229 
1230 	/*
1231 	 * we have a valid buf, setup our local version
1232 	 * we use this count to allow reading over multiple tracks.
1233 	 * into a single buffer
1234 	 */
1235 	dp->b_bcount = bp->b_bcount;
1236 	dp->b_blkno = bp->b_blkno;
1237 	dp->b_data = bp->b_data;
1238 	dp->b_flags = bp->b_flags;
1239 	dp->b_resid = 0;
1240 
1241 	if (bp->b_flags & B_READ)
1242 		write = 0;
1243 	else if (FDTESTC(FDB_PROTECT) == 0)
1244 		write = 1;
1245 	else {
1246 		error = EPERM;
1247 		goto bad;
1248 	}
1249 
1250 	/*
1251 	 * figure trk given blkno
1252 	 */
1253 	trk = bp->b_blkno / sc->nsectors;
1254 
1255 	/*
1256 	 * check to see if same as currently cached track
1257 	 * if so we need to do no DMA read.
1258 	 */
1259 	if (trk == sc->cachetrk) {
1260 		fddone(sc);
1261 		return;
1262 	}
1263 
1264 	/*
1265 	 * if we will be overwriting the entire cache, don't bother to
1266 	 * fetch it.
1267 	 */
1268 	if (bp->b_bcount == (sc->nsectors * FDSECSIZE) && write &&
1269 	    bp->b_blkno % sc->nsectors == 0) {
1270 		if (sc->flags & FDF_DIRTY)
1271 			sc->flags |= FDF_JUSTFLUSH;
1272 		else {
1273 			sc->cachetrk = trk;
1274 			fddone(sc);
1275 			return;
1276 		}
1277 	}
1278 
1279 	/*
1280 	 * start DMA read of `trk'
1281 	 */
1282 	fddmastart(sc, trk);
1283 	return;
1284 bad:
1285 	bp->b_flags |= B_ERROR;
1286 	bp->b_error = error;
1287 	fddone(sc);
1288 }
1289 
1290 /*
1291  * continue a started operation on next track. always begin at
1292  * sector 0 on the next track.
1293  */
1294 void
1295 fdcont(struct fd_softc *sc)
1296 {
1297 	struct buf *dp, *bp;
1298 	int trk, write;
1299 
1300 	dp = &sc->curbuf;
1301 	bp = BUFQ_PEEK(&sc->bufq);
1302 	dp->b_data += (dp->b_bcount - bp->b_resid);
1303 	dp->b_blkno += (dp->b_bcount - bp->b_resid) / FDSECSIZE;
1304 	dp->b_bcount = bp->b_resid;
1305 
1306 	/*
1307 	 * figure trk given blkno
1308 	 */
1309 	trk = dp->b_blkno / sc->nsectors;
1310 #ifdef DEBUG
1311 	if (trk != sc->cachetrk + 1 || dp->b_blkno % sc->nsectors != 0)
1312 		panic("fdcont: confused");
1313 #endif
1314 	if (dp->b_flags & B_READ)
1315 		write = 0;
1316 	else
1317 		write = 1;
1318 	/*
1319 	 * if we will be overwriting the entire cache, don't bother to
1320 	 * fetch it.
1321 	 */
1322 	if (dp->b_bcount == (sc->nsectors * FDSECSIZE) && write) {
1323 		if (sc->flags & FDF_DIRTY)
1324 			sc->flags |= FDF_JUSTFLUSH;
1325 		else {
1326 			sc->cachetrk = trk;
1327 			fddone(sc);
1328 			return;
1329 		}
1330 	}
1331 	/*
1332 	 * start DMA read of `trk'
1333 	 */
1334 	fddmastart(sc, trk);
1335 	return;
1336 }
1337 
1338 void
1339 fddmastart(struct fd_softc *sc, int trk)
1340 {
1341 	int adkmask, ndmaw, write, dmatrk;
1342 
1343 #ifdef FDDEBUG
1344 	printf("fddmastart: unit %d cyl %d head %d", sc->hwunit,
1345 	    trk / FDNHEADS, trk % FDNHEADS);
1346 #endif
1347 	/*
1348 	 * flush the cached track if dirty else read requested track.
1349 	 */
1350 	if (sc->flags & FDF_DIRTY) {
1351 		fdcachetoraw(sc);
1352 		ndmaw = sc->type->nwritew;
1353 		dmatrk = sc->cachetrk;
1354 		write = 1;
1355 	} else {
1356 		ndmaw = sc->type->nreadw;
1357 		dmatrk = trk;
1358 		write = 0;
1359 	}
1360 
1361 #ifdef FDDEBUG
1362 	printf(" %s", write ? " flushing cache\n" : " loading cache\n");
1363 #endif
1364 	sc->cachetrk = trk;
1365 	fdc_indma = sc;
1366 	fdsetpos(sc, dmatrk, write);
1367 
1368 	/*
1369 	 * setup dma stuff
1370 	 */
1371 	if (write == 0) {
1372 		custom.adkcon = ADKF_MSBSYNC;
1373 		custom.adkcon = ADKF_SETCLR | ADKF_WORDSYNC | ADKF_FAST;
1374 		custom.dsksync = FDMFMSYNC;
1375 	} else {
1376 		custom.adkcon = ADKF_PRECOMP1 | ADKF_PRECOMP0 | ADKF_WORDSYNC |
1377 		    ADKF_MSBSYNC;
1378 		adkmask = ADKF_SETCLR | ADKF_FAST | ADKF_MFMPREC;
1379 		if (dmatrk >= sc->type->precomp[0])
1380 			adkmask |= ADKF_PRECOMP0;
1381 		if (dmatrk >= sc->type->precomp[1])
1382 			adkmask |= ADKF_PRECOMP1;
1383 		custom.adkcon = adkmask;
1384 	}
1385 	custom.dskpt = (u_char *)kvtop(fdc_dmap);
1386 
1387 	/*
1388 	 * If writing an MSDOS track, activate disk index pulse
1389 	 * interrupt, DMA will be started in the intr routine fdidxintr()
1390 	 * Otherwise, start the DMA here.
1391 	 */
1392 	if (write && sc->openpart == FDMSDOSPART) {
1393 		fdc_dmalen = ndmaw;
1394 		fdc_dmawrite = write;
1395 		ciab.icr = CIA_ICR_IR_SC | CIA_ICR_FLG;
1396 	} else {
1397 		FDDMASTART(ndmaw, write);
1398 		fdc_dmalen = 0;
1399 	}
1400 
1401 #ifdef FDDEBUG
1402 	printf("  DMA started\n");
1403 #endif
1404 }
1405 
1406 /*
1407  * recalibrate the drive
1408  */
1409 void
1410 fdcalibrate(void *arg)
1411 {
1412 	struct fd_softc *sc;
1413 	static int loopcnt;
1414 
1415 	sc = arg;
1416 
1417 	if (loopcnt == 0) {
1418 		/*
1419 		 * seek cyl 0
1420 		 */
1421 		fdc_indma = sc;
1422 		sc->stepdelay += 900;
1423 		if (sc->cachetrk > 1)
1424 			fdsetpos(sc, sc->cachetrk % FDNHEADS, 0);
1425 		sc->stepdelay -= 900;
1426 	}
1427 	if (loopcnt++ & 1)
1428 		fdsetpos(sc, sc->cachetrk, 0);
1429 	else
1430 		fdsetpos(sc, sc->cachetrk + FDNHEADS, 0);
1431 	/*
1432 	 * trk++, trk, trk++, trk, trk++, trk, trk++, trk and DMA
1433 	 */
1434 	if (loopcnt < 8)
1435 		callout_reset(&sc->calibrate_ch, hz / 8, fdcalibrate, sc);
1436 	else {
1437 		loopcnt = 0;
1438 		fdc_indma = NULL;
1439 		callout_reset(&sc->motor_ch, 3 * hz / 2, fdmotoroff, sc);
1440 		fddmastart(sc, sc->cachetrk);
1441 	}
1442 }
1443 
1444 void
1445 fddmadone(struct fd_softc *sc, int timeo)
1446 {
1447 #ifdef FDDEBUG
1448 	printf("fddmadone: unit %d, timeo %d\n", sc->hwunit, timeo);
1449 #endif
1450 	fdc_indma = NULL;
1451 	callout_stop(&sc->motor_ch);
1452 	FDDMASTOP;
1453 
1454 	/*
1455 	 * guarantee the drive has been at current head and cyl
1456 	 * for at least FDWRITEDELAY after a write.
1457 	 */
1458 	if (sc->flags & FDF_WRITEWAIT) {
1459 		delay(FDWRITEDELAY);
1460 		sc->flags &= ~FDF_WRITEWAIT;
1461 	}
1462 
1463 	if ((sc->flags & FDF_MOTOROFF) == 0) {
1464 		/*
1465 		 * motor runs for 1.5 seconds after last DMA
1466 		 */
1467 		callout_reset(&sc->motor_ch, 3 * hz / 2, fdmotoroff, sc);
1468 	}
1469 	if (sc->flags & FDF_DIRTY) {
1470 		/*
1471 		 * if buffer dirty, the last DMA cleaned it
1472 		 */
1473 		sc->flags &= ~FDF_DIRTY;
1474 		if (timeo)
1475 			printf("%s: write of track cache timed out.\n",
1476 			    sc->sc_dv.dv_xname);
1477 		if (sc->flags & FDF_JUSTFLUSH) {
1478 			sc->flags &= ~FDF_JUSTFLUSH;
1479 			/*
1480 			 * we are done DMA'ing
1481 			 */
1482 			fddone(sc);
1483 			return;
1484 		}
1485 		/*
1486 		 * load the cache
1487 		 */
1488 		fddmastart(sc, sc->cachetrk);
1489 		return;
1490 	}
1491 #ifdef FDDEBUG
1492 	else if (sc->flags & FDF_MOTOROFF)
1493 		panic("fddmadone: FDF_MOTOROFF with no FDF_DIRTY");
1494 #endif
1495 
1496 	/*
1497 	 * cache loaded decode it into cache buffer
1498 	 */
1499 	if (timeo == 0 && fdrawtocache(sc) == 0)
1500 		sc->retried = 0;
1501 	else {
1502 #ifdef FDDEBUG
1503 		if (timeo)
1504 			printf("%s: fddmadone: cache load timed out.\n",
1505 			    sc->sc_dv.dv_xname);
1506 #endif
1507 		if (sc->retried >= sc->retries) {
1508 			sc->retried = 0;
1509 			sc->cachetrk = -1;
1510 		} else {
1511 			sc->retried++;
1512 			/*
1513 			 * this will be restarted at end of calibrate loop.
1514 			 */
1515 			callout_stop(&sc->motor_ch);
1516 			fdcalibrate(sc);
1517 			return;
1518 		}
1519 	}
1520 	fddone(sc);
1521 }
1522 
1523 void
1524 fddone(struct fd_softc *sc)
1525 {
1526 	struct buf *dp, *bp;
1527 	char *data;
1528 	int sz;
1529 
1530 #ifdef FDDEBUG
1531 	printf("fddone: unit %d\n", sc->hwunit);
1532 #endif
1533 	/*
1534 	 * check to see if unit is just flushing the cache,
1535 	 * that is we have no io queued.
1536 	 */
1537 	if (sc->flags & FDF_MOTOROFF)
1538 		goto nobuf;
1539 
1540 	dp = &sc->curbuf;
1541 	if ((bp = BUFQ_PEEK(&sc->bufq)) == NULL)
1542 		panic ("fddone");
1543 	/*
1544 	 * check for an error that may have occurred
1545 	 * while getting the track.
1546 	 */
1547 	if (sc->cachetrk == -1) {
1548 		sc->retried = 0;
1549 		bp->b_flags |= B_ERROR;
1550 		bp->b_error = EIO;
1551 	} else if ((bp->b_flags & B_ERROR) == 0) {
1552 		data = sc->cachep;
1553 		/*
1554 		 * get offset of data in track cache and limit
1555 		 * the copy size to not exceed the cache's end.
1556 		 */
1557 		data += (dp->b_blkno % sc->nsectors) * FDSECSIZE;
1558 		sz = sc->nsectors - dp->b_blkno % sc->nsectors;
1559 		sz *= FDSECSIZE;
1560 		sz = min(dp->b_bcount, sz);
1561 		if (bp->b_flags & B_READ)
1562 			bcopy(data, dp->b_data, sz);
1563 		else {
1564 			bcopy(dp->b_data, data, sz);
1565 			sc->flags |= FDF_DIRTY;
1566 		}
1567 		bp->b_resid = dp->b_bcount - sz;
1568 		if (bp->b_resid == 0) {
1569 			bp->b_error = 0;
1570 		} else {
1571 			/*
1572 			 * not done yet need to read next track
1573 			 */
1574 			fdcont(sc);
1575 			return;
1576 		}
1577 	}
1578 	/*
1579 	 * remove from queue.
1580 	 */
1581 	(void)BUFQ_GET(&sc->bufq);
1582 
1583 	disk_unbusy(&sc->dkdev, (bp->b_bcount - bp->b_resid),
1584 	    (bp->b_flags & B_READ));
1585 
1586 	biodone(bp);
1587 nobuf:
1588 	fdfindwork(sc->sc_dv.dv_unit);
1589 }
1590 
1591 void
1592 fdfindwork(int unit)
1593 {
1594 	struct fd_softc *ssc, *sc;
1595 	int i, last;
1596 
1597 	/*
1598 	 * first see if we have any fdopen()'s waiting
1599 	 */
1600 	if (fdc_wantwakeup) {
1601 		wakeup(fdopen);
1602 		fdc_wantwakeup--;
1603 		return;
1604 	}
1605 
1606 	/*
1607 	 * start next available unit, linear search from the next unit
1608 	 * wrapping and finally this unit.
1609 	 */
1610 	last = 0;
1611 	ssc = NULL;
1612 	for (i = unit + 1; last == 0; i++) {
1613 		if (i == unit)
1614 			last = 1;
1615 		if (i >= fd_cd.cd_ndevs) {
1616 			i = -1;
1617 			continue;
1618 		}
1619 		if ((sc = fd_cd.cd_devs[i]) == NULL)
1620 			continue;
1621 
1622 		/*
1623 		 * if unit has requested to be turned off
1624 		 * and it has no buf's queued do it now
1625 		 */
1626 		if (sc->flags & FDF_MOTOROFF) {
1627 			if (BUFQ_PEEK(&sc->bufq) == NULL)
1628 				fdmotoroff(sc);
1629 			else {
1630 				/*
1631 				 * we gained a buf request while
1632 				 * we waited, forget the motoroff
1633 				 */
1634 				sc->flags &= ~FDF_MOTOROFF;
1635 			}
1636 			/*
1637 			 * if we now have DMA unit must have needed
1638 			 * flushing, quit
1639 			 */
1640 			if (fdc_indma)
1641 				return;
1642 		}
1643 		/*
1644 		 * if we have no start unit and the current unit has
1645 		 * io waiting choose this unit to start.
1646 		 */
1647 		if (ssc == NULL && BUFQ_PEEK(&sc->bufq) != NULL)
1648 			ssc = sc;
1649 	}
1650 	if (ssc)
1651 		fdstart(ssc);
1652 }
1653 
1654 /*
1655  * min byte count to whats left of the track in question
1656  */
1657 void
1658 fdminphys(struct buf *bp)
1659 {
1660 	struct fd_softc *sc;
1661 	int trk, sec, toff, tsz;
1662 
1663 	if ((sc = getsoftc(fd_cd, FDUNIT(bp->b_dev))) == NULL)
1664 		panic("fdminphys: couldn't get softc");
1665 
1666 	trk = bp->b_blkno / sc->nsectors;
1667 	sec = bp->b_blkno % sc->nsectors;
1668 
1669 	toff = sec * FDSECSIZE;
1670 	tsz = sc->nsectors * FDSECSIZE;
1671 #ifdef FDDEBUG
1672 	printf("fdminphys: before %ld", bp->b_bcount);
1673 #endif
1674 	bp->b_bcount = min(bp->b_bcount, tsz - toff);
1675 #ifdef FDDEBUG
1676 	printf(" after %ld\n", bp->b_bcount);
1677 #endif
1678 	minphys(bp);
1679 }
1680 
1681 /*
1682  * encode the track cache into raw MFM ready for DMA
1683  * when we go to multiple disk formats, this will call type dependent
1684  * functions
1685  */
1686 void fdcachetoraw(struct fd_softc *sc)
1687 {
1688 	if (sc->openpart == FDMSDOSPART)
1689 		mscachetoraw(sc);
1690 	else
1691 		amcachetoraw(sc);
1692 }
1693 
1694 /*
1695  * decode raw MFM from DMA into units track cache.
1696  * when we go to multiple disk formats, this will call type dependent
1697  * functions
1698  */
1699 int
1700 fdrawtocache(struct fd_softc *sc)
1701 {
1702 
1703 	if (sc->openpart == FDMSDOSPART)
1704 		return(msrawtocache(sc));
1705 	else
1706 		return(amrawtocache(sc));
1707 }
1708 
1709 void
1710 amcachetoraw(struct fd_softc *sc)
1711 {
1712 	static u_long mfmnull[4];
1713 	u_long *rp, *crp, *dp, hcksum, dcksum, info, zero;
1714 	int sec, i;
1715 
1716 	rp = fdc_dmap;
1717 
1718 	/*
1719 	 * not yet one sector (- 1 long) gap.
1720 	 * for now use previous drivers values
1721 	 */
1722 	for (i = 0; i < sc->type->gap; i++)
1723 		*rp++ = 0xaaaaaaaa;
1724 	/*
1725 	 * process sectors
1726 	 */
1727 	dp = sc->cachep;
1728 	zero = 0;
1729 	info = 0xff000000 | (sc->cachetrk << 16) | sc->nsectors;
1730 	for (sec = 0; sec < sc->nsectors; sec++, info += (1 << 8) - 1) {
1731 		hcksum = dcksum = 0;
1732 		/*
1733 		 * sector format
1734 		 *	offset		description
1735 		 *-----------------------------------
1736 		 *  0			null
1737 		 *  1			sync
1738 		 * oddbits	evenbits
1739 		 *----------------------
1740 		 *  2		3	[0xff]b [trk]b [sec]b [togap]b
1741 		 *  4-7		8-11	null
1742 		 * 12		13	header cksum [2-11]
1743 		 * 14		15	data cksum [16-271]
1744 		 * 16-143	144-271	data
1745 		 */
1746 		*rp = 0xaaaaaaaa;
1747 		if (*(rp - 1) & 0x1)
1748 			*rp &= 0x7fffffff;	/* clock bit correction */
1749 		rp++;
1750 		*rp++ = (FDMFMSYNC << 16) | FDMFMSYNC;
1751 		rp = mfmblkencode(&info, rp, &hcksum, 1);
1752 		rp = mfmblkencode(mfmnull, rp, &hcksum, 4);
1753 		rp = mfmblkencode(&hcksum, rp, NULL, 1);
1754 
1755 		crp = rp;
1756 		rp = mfmblkencode(dp, rp + 2, &dcksum, FDSECLWORDS);
1757 		dp += FDSECLWORDS;
1758 		crp = mfmblkencode(&dcksum, crp, NULL, 1);
1759 		if (*(crp - 1) & 0x1)
1760 			*crp &= 0x7fffffff;	/* clock bit correction */
1761 		else if ((*crp & 0x40000000) == 0)
1762 			*crp |= 0x80000000;
1763 	}
1764 	*rp = 0xaaa80000;
1765 	if (*(rp - 1) & 0x1)
1766 		*rp &= 0x7fffffff;
1767 }
1768 
1769 u_long *
1770 fdfindsync(u_long *rp, u_long *ep)
1771 {
1772 	u_short *sp;
1773 
1774 	sp = (u_short *)rp;
1775 	while ((u_long *)sp < ep && *sp != FDMFMSYNC)
1776 		sp++;
1777 	while ((u_long *)sp < ep && *sp == FDMFMSYNC)
1778 		sp++;
1779 	if ((u_long *)sp < ep)
1780 		return((u_long *)sp);
1781 	return(NULL);
1782 }
1783 
1784 int
1785 amrawtocache(struct fd_softc *sc)
1786 {
1787 	u_long mfmnull[4];
1788 	u_long *dp, *rp, *erp, *crp, *srp, hcksum, dcksum, info, cktmp;
1789 	int cnt, doagain;
1790 
1791 	doagain = 1;
1792 	srp = rp = fdc_dmap;
1793 	erp = (u_long *)((u_short *)rp + sc->type->nreadw);
1794 	cnt = 0;
1795 again:
1796 	if (doagain == 0 || (rp = srp = fdfindsync(srp, erp)) == NULL) {
1797 #ifdef DIAGNOSTIC
1798 		printf("%s: corrupted track (%d) data.\n",
1799 		    sc->sc_dv.dv_xname, sc->cachetrk);
1800 #endif
1801 		return(-1);
1802 	}
1803 
1804 	/*
1805 	 * process sectors
1806 	 */
1807 	for (; cnt < sc->nsectors; cnt++) {
1808 		hcksum = dcksum = 0;
1809 		rp = mfmblkdecode(rp, &info, &hcksum, 1);
1810 		rp = mfmblkdecode(rp, mfmnull, &hcksum, 4);
1811 		rp = mfmblkdecode(rp, &cktmp, NULL, 1);
1812 		if (cktmp != hcksum) {
1813 #ifdef FDDEBUG
1814 			printf("  info 0x%lx hchksum 0x%lx trkhcksum 0x%lx\n",
1815 			    info, hcksum, cktmp);
1816 #endif
1817 			goto again;
1818 		}
1819 		if (((info >> 16) & 0xff) != sc->cachetrk) {
1820 #ifdef DEBUG
1821 			printf("%s: incorrect track found: 0x%lx %d\n",
1822 			    sc->sc_dv.dv_xname, info, sc->cachetrk);
1823 #endif
1824 			goto again;
1825 		}
1826 #ifdef FDDEBUG
1827 		printf("  info 0x%lx\n", info);
1828 #endif
1829 
1830 		rp = mfmblkdecode(rp, &cktmp, NULL, 1);
1831 		dp = sc->cachep;
1832 		dp += FDSECLWORDS * ((info >> 8) & 0xff);
1833 		crp = mfmblkdecode(rp, dp, &dcksum, FDSECLWORDS);
1834 		if (cktmp != dcksum) {
1835 #ifdef FDDEBUG
1836 			printf("  info 0x%lx dchksum 0x%lx trkdcksum 0x%lx\n",
1837 			    info, dcksum, cktmp);
1838 #endif
1839 			goto again;
1840 		}
1841 
1842 		/*
1843 		 * if we are at gap then we can no longer be sure
1844 		 * of correct sync marks
1845 		 */
1846 		if ((info && 0xff) == 1)
1847 			doagain = 1;
1848 		else
1849 			doagain = 0;
1850 		srp = rp = fdfindsync(crp, erp);
1851 	}
1852 	return(0);
1853 }
1854 
1855 void
1856 mscachetoraw(struct fd_softc *sc)
1857 {
1858 	u_short *rp, *erp, crc;
1859 	u_char *cp, tb[5];
1860 	int sec, i;
1861 
1862 	rp = (u_short *)fdc_dmap;
1863 	erp = rp + sc->type->nwritew;
1864 	cp = sc->cachep;
1865 
1866 	/*
1867 	 * initial track filler  (828 * GAP1)
1868 	 */
1869 	for (i = 0; i < sc->type->gap; i++) {
1870 		*rp++ = FDMFMGAP1;
1871 		*rp++ = FDMFMGAP1;
1872 	}
1873 
1874 	for (sec = 0; sec < sc->nsectors; sec++) {
1875 
1876 		/*
1877 		 * leading sector gap
1878 		 * (12 * GAP2) + (3 * SYNC)
1879 		 */
1880 		for (i = 0; i < 12; i++)
1881 			*rp++ = FDMFMGAP2;
1882 		*rp++ = FDMFMSYNC;
1883 		*rp++ = FDMFMSYNC;
1884 		*rp++ = FDMFMSYNC;
1885 
1886 		/*
1887 		 * sector information
1888 		 * (ID) + track + side + sector + sector size + CRC16
1889 		 */
1890 		*rp++ = FDMFMID;
1891 		tb[0] = sc->cachetrk / FDNHEADS;
1892 		tb[1] = sc->cachetrk % FDNHEADS;
1893 		tb[2] = sec + 1;
1894 		i = sc->bytespersec;
1895 		tb[3] = i < 256 ? 0 : (i < 512 ? 1 : (i < 1024 ? 2 : 3));
1896 		rp = msblkencode(rp, tb, 4, &crc);
1897 		tb[0] = crc >> 8;
1898 		tb[1] = crc & 0xff;
1899 		tb[2] = 0x4e; /* GAP1 decoded */
1900 		rp = msblkencode(rp, tb, 3, 0);
1901 
1902 		/*
1903 		 * sector info/data gap
1904 		 * (22 * GAP1) + (12 * GAP2) + (3 * SYNC)
1905 		 */
1906 		for (i = 0; i < 21; i++)
1907 			*rp++ = FDMFMGAP1;
1908 		for (i = 0; i < 12; i++)
1909 			*rp++ = FDMFMGAP2;
1910 		*rp++ = FDMFMSYNC;
1911 		*rp++ = FDMFMSYNC;
1912 		*rp++ = FDMFMSYNC;
1913 
1914 		/*
1915 		 * sector data
1916 		 * (DATA) + ...data... + CRC16
1917 		 */
1918 		*rp++ = FDMFMDATA;
1919 		rp = msblkencode(rp, cp, sc->bytespersec, &crc);
1920 		cp += sc->bytespersec;
1921 		tb[0] = crc >> 8;
1922 		tb[1] = crc & 0xff;
1923 		tb[2] = 0x4e; /* GAP3 decoded */
1924 		rp = msblkencode(rp, tb, 3, 0);
1925 
1926 		/*
1927 		 * trailing sector gap
1928 		 * (80 * GAP3)
1929 		 */
1930 		for (i = 0; i < 79; i++)
1931 			*rp++ = FDMFMGAP3;
1932 	}
1933 
1934 	/*
1935 	 * fill rest of track with GAP3
1936 	 */
1937 	while (rp != erp)
1938 		*rp++ = FDMFMGAP3;
1939 
1940 }
1941 
1942 int
1943 msrawtocache(struct fd_softc *sc)
1944 {
1945 	u_short *rp, *srp, *erp;
1946 	u_char tb[5], *cp;
1947 	int ct, sec, retry;
1948 
1949 	srp = rp = (u_short *)fdc_dmap;
1950 	erp = rp + sc->type->nreadw;
1951 	cp = sc->cachep;
1952 
1953 	for (ct = 0; ct < sc->nsectors; ct++) {
1954 		retry = 1;
1955 		do {
1956 			/*
1957 			 * skip leading gap to sync
1958 			 */
1959 			if ((rp = (u_short *)fdfindsync((u_long *)rp, (u_long *)erp)) == NULL) {
1960 #ifdef DIAGNOSTIC
1961 				printf("%s: corrupted track (%d) data.\n",
1962 				sc->sc_dv.dv_xname, sc->cachetrk);
1963 #endif
1964 				return(-1);
1965 			}
1966 
1967 			/*
1968 			 * Grab sector info
1969 			 */
1970 			if (*rp++ != FDMFMID)
1971 				continue;
1972 			rp = msblkdecode(rp, tb, 4);
1973 #ifdef FDDEBUG
1974 			printf("sector id: sector %d, track %d, side %d,"
1975 			    "bps %d\n", tb[2], tb[0], tb[1], 128 << tb[3]);
1976 #endif
1977 			if ((tb[0] * FDNHEADS + tb[1]) != sc->cachetrk ||
1978 			    tb[2] > sc->nsectors)
1979 				continue;
1980 
1981 			sec = tb[2];
1982 			sc->bytespersec = 128 << tb[3];
1983 			rp += 2; /* skip CRC-16 */
1984 
1985 			/*
1986 			 * skip gap and read in data
1987 			 */
1988 			if ((rp = (u_short *)fdfindsync((u_long *)rp, (u_long *)erp)) == NULL)
1989 				return(-1);
1990 			if (*rp++ != FDMFMDATA)
1991 				continue;
1992 			rp = msblkdecode(rp, cp + ((sec-1) * sc->bytespersec),
1993 			    sc->bytespersec);
1994 			rp += 2; /* skip CRC-16 */
1995 
1996 			retry = 0;
1997 		} while (retry);
1998 	}
1999 	return(0);
2000 }
2001 
2002 /*
2003  * encode len longwords of `dp' data in amiga mfm block format (`rp')
2004  * this format specified that the odd bits are at current pos and even
2005  * bits at len + current pos
2006  */
2007 u_long *
2008 mfmblkencode(u_long *dp, u_long *rp, u_long *cp, int len)
2009 {
2010 	u_long *sdp, *edp, d, dtmp, correct;
2011 
2012 	sdp = dp;
2013 	edp = dp + len;
2014 
2015 	if (*(rp - 1) & 0x1)
2016 		correct = 1;
2017 	else
2018 		correct = 0;
2019 	/*
2020 	 * do odd bits
2021 	 */
2022 	while (dp < edp) {
2023 		d = (*dp >> 1) & 0x55555555;	/* remove clock bits */
2024 		dtmp = d ^ 0x55555555;
2025 		d |= ((dtmp >> 1) | 0x80000000) & (dtmp << 1);
2026 		/*
2027 		 * correct upper clock bit if needed
2028 		 */
2029 		if (correct)
2030 			d &= 0x7fffffff;
2031 		if (d & 0x1)
2032 			correct = 1;
2033 		else
2034 			correct = 0;
2035 		/*
2036 		 * do checksums and store in raw buffer
2037 		 */
2038 		if (cp)
2039 			*cp ^= d;
2040 		*rp++ = d;
2041 		dp++;
2042 	}
2043 	/*
2044 	 * do even bits
2045 	 */
2046 	dp = sdp;
2047 	while (dp < edp) {
2048 		d = *dp & 0x55555555;	/* remove clock bits */
2049 		dtmp = d ^ 0x55555555;
2050 		d |= ((dtmp >> 1) | 0x80000000) & (dtmp << 1);
2051 		/*
2052 		 * correct upper clock bit if needed
2053 		 */
2054 		if (correct)
2055 			d &= 0x7fffffff;
2056 		if (d & 0x1)
2057 			correct = 1;
2058 		else
2059 			correct = 0;
2060 		/*
2061 		 * do checksums and store in raw buffer
2062 		 */
2063 		if (cp)
2064 			*cp ^= d;
2065 		*rp++ = d;
2066 		dp++;
2067 	}
2068 	if (cp)
2069 		*cp &= 0x55555555;
2070 	return(rp);
2071 }
2072 
2073 /*
2074  * decode len longwords of `dp' data in amiga mfm block format (`rp')
2075  * this format specified that the odd bits are at current pos and even
2076  * bits at len + current pos
2077  */
2078 u_long *
2079 mfmblkdecode(u_long *rp, u_long *dp, u_long *cp, int len)
2080 {
2081 	u_long o, e;
2082 	int cnt;
2083 
2084 	cnt = len;
2085 	while (cnt--) {
2086 		o = *rp;
2087 		e = *(rp + len);
2088 		if (cp) {
2089 			*cp ^= o;
2090 			*cp ^= e;
2091 		}
2092 		o &= 0x55555555;
2093 		e &= 0x55555555;
2094 		*dp++ = (o << 1) | e;
2095 		rp++;
2096 	}
2097 	if (cp)
2098 		*cp &= 0x55555555;
2099 	return(rp + len);
2100 }
2101 
2102 /*
2103  * decode len words in standard MFM format to len bytes
2104  * of data.
2105  */
2106 u_short *
2107 msblkdecode(u_short *rp, u_char *cp, int len)
2108 {
2109 	while (len--) {
2110 		*cp++ = msdecode[*rp & 0x7f] |
2111 		    (msdecode[(*rp >> 8) & 0x7f] << 4);
2112 		rp++;
2113 	}
2114 
2115 	return(rp);
2116 }
2117 
2118 /*
2119  * encode len bytes of data into len words in standard MFM format.
2120  * If a pointer is supplied for crc, calculate the CRC-16 of the data
2121  * as well.
2122  */
2123 u_short *
2124 msblkencode(u_short *rp, u_char *cp, int len, u_short *crc)
2125 {
2126 	u_short td;
2127 	u_short mycrc;
2128 
2129 	/* preload crc for header (4 bytes)
2130 	 * or data (anything else)
2131 	 */
2132 	mycrc = (len == 4) ? 0xb230 : 0xe295;
2133 
2134 	while (len--) {
2135 		td = (msencode[*cp >> 4] << 8) | msencode[*cp & 0x0f];
2136 
2137 		/* Check for zeros in top bit of encode and bottom
2138 		 * bit of previous encode.  if so, slap a one in betweem
2139 		 * them.
2140 		 */
2141 		if ((td & 0x140) == 0)
2142 			td |= 0x80;
2143 		if ((td & 0x4000) == 0 && (rp[-1] & 1) == 0)
2144 			td |= 0x8000;
2145 
2146 		*rp++ = td;
2147 
2148 		/*
2149 		 * calc crc if requested
2150 		 */
2151 		if (crc)
2152 			mycrc = (mycrc << 8) ^ mscrctab[*cp ^ (mycrc >> 8)];
2153 
2154 		cp++;
2155 	}
2156 
2157 	if (crc)
2158 		*crc = mycrc;
2159 
2160 	return(rp);
2161 }
2162