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