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