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